1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
use super::{Input, Output, Transaction, Witness};
use crate::consts::*;

use fuel_types::{AssetId, Word};

#[cfg(feature = "std")]
use fuel_types::Bytes32;

#[cfg(feature = "std")]
use fuel_crypto::{Message, Signature};

mod error;

pub use error::ValidationError;

impl Input {
    #[cfg(feature = "std")]
    pub fn validate(
        &self,
        index: usize,
        txhash: &Bytes32,
        outputs: &[Output],
        witnesses: &[Witness],
    ) -> Result<(), ValidationError> {
        self.validate_without_signature(index, outputs, witnesses)?;
        self.validate_signature(index, txhash, witnesses)?;

        Ok(())
    }

    #[cfg(feature = "std")]
    pub fn validate_signature(
        &self,
        index: usize,
        txhash: &Bytes32,
        witnesses: &[Witness],
    ) -> Result<(), ValidationError> {
        if let Input::Coin {
            witness_index,
            owner,
            ..
        } = self
        {
            let witness = witnesses
                .get(*witness_index as usize)
                .ok_or(ValidationError::InputCoinWitnessIndexBounds { index })?
                .as_ref();

            if witness.len() != Signature::LEN {
                return Err(ValidationError::InputCoinInvalidSignature { index });
            }

            // Safety: checked length
            let signature = unsafe { Signature::as_ref_unchecked(witness) };

            // Safety: checked length
            let message = unsafe { Message::as_ref_unchecked(txhash.as_ref()) };

            let pk = signature
                .recover(message)
                .map_err(|_| ValidationError::InputCoinInvalidSignature { index })
                .map(|pk| Input::coin_owner(&pk))?;

            if owner != &pk {
                return Err(ValidationError::InputCoinInvalidSignature { index });
            }
        }

        Ok(())
    }

    pub fn validate_without_signature(
        &self,
        index: usize,
        outputs: &[Output],
        witnesses: &[Witness],
    ) -> Result<(), ValidationError> {
        match self {
            Self::Coin { predicate, .. } if predicate.len() > MAX_PREDICATE_LENGTH as usize => {
                Err(ValidationError::InputCoinPredicateLength { index })
            }

            Self::Coin { predicate_data, .. }
                if predicate_data.len() > MAX_PREDICATE_DATA_LENGTH as usize =>
            {
                Err(ValidationError::InputCoinPredicateDataLength { index })
            }

            Self::Coin { witness_index, .. } if *witness_index as usize >= witnesses.len() => {
                Err(ValidationError::InputCoinWitnessIndexBounds { index })
            }

            Self::Coin { .. } => Ok(()),

            // ∀ inputContract ∃! outputContract : outputContract.inputIndex = inputContract.index
            Self::Contract { .. }
                if 1 != outputs
                    .iter()
                    .filter_map(|output| match output {
                        Output::Contract { input_index, .. } if *input_index as usize == index => {
                            Some(())
                        }
                        _ => None,
                    })
                    .count() =>
            {
                Err(ValidationError::InputContractAssociatedOutputContract { index })
            }

            // TODO If h is the block height the UTXO being spent was created, transaction is
            // invalid if `blockheight() < h + maturity`.
            _ => Ok(()),
        }
    }
}

impl Output {
    pub fn validate(&self, index: usize, inputs: &[Input]) -> Result<(), ValidationError> {
        match self {
            Self::Contract { input_index, .. } => match inputs.get(*input_index as usize) {
                Some(Input::Contract { .. }) => Ok(()),
                _ => Err(ValidationError::OutputContractInputIndex { index }),
            },

            _ => Ok(()),
        }
    }
}

impl Transaction {
    #[cfg(feature = "std")]
    pub fn validate(&self, block_height: Word) -> Result<(), ValidationError> {
        self.validate_without_signature(block_height)?;
        self.validate_input_signature()?;

        Ok(())
    }

    #[cfg(feature = "std")]
    pub fn validate_input_signature(&self) -> Result<(), ValidationError> {
        let id = self.id();

        self.inputs()
            .iter()
            .enumerate()
            .try_for_each(|(index, input)| {
                input.validate_signature(index, &id, self.witnesses())
            })?;

        Ok(())
    }

    pub fn validate_without_signature(&self, block_height: Word) -> Result<(), ValidationError> {
        if self.gas_limit() > MAX_GAS_PER_TX {
            Err(ValidationError::TransactionGasLimit)?
        }

        if block_height < self.maturity() as Word {
            Err(ValidationError::TransactionMaturity)?;
        }

        if self.inputs().len() > MAX_INPUTS as usize {
            Err(ValidationError::TransactionInputsMax)?
        }

        if self.outputs().len() > MAX_OUTPUTS as usize {
            Err(ValidationError::TransactionOutputsMax)?
        }

        if self.witnesses().len() > MAX_WITNESSES as usize {
            Err(ValidationError::TransactionWitnessesMax)?
        }

        self.input_asset_ids_unique()
            .try_for_each(|input_asset_id| {
                // check for duplicate change outputs
                if self
                    .outputs()
                    .iter()
                    .filter_map(|output| match output {
                        Output::Change { asset_id, .. } if input_asset_id == asset_id => Some(()),
                        Output::Change { asset_id, .. }
                            if asset_id != &AssetId::default() && input_asset_id == asset_id =>
                        {
                            Some(())
                        }
                        _ => None,
                    })
                    .count()
                    > 1
                {
                    return Err(ValidationError::TransactionOutputChangeAssetIdDuplicated);
                }

                Ok(())
            })?;

        self.inputs()
            .iter()
            .enumerate()
            .try_for_each(|(index, input)| {
                input.validate_without_signature(index, self.outputs(), self.witnesses())
            })?;

        self.outputs()
            .iter()
            .enumerate()
            .try_for_each(|(index, output)| {
                output.validate(index, self.inputs())?;

                if let Output::Change { asset_id, .. } = output {
                    if !self
                        .input_asset_ids()
                        .any(|input_asset_id| input_asset_id == asset_id)
                    {
                        return Err(ValidationError::TransactionOutputChangeAssetIdNotFound);
                    }
                }

                Ok(())
            })?;

        match self {
            Self::Script {
                outputs,
                script,
                script_data,
                ..
            } => {
                if script.len() > MAX_SCRIPT_LENGTH as usize {
                    Err(ValidationError::TransactionScriptLength)?;
                }

                if script_data.len() > MAX_SCRIPT_DATA_LENGTH as usize {
                    Err(ValidationError::TransactionScriptDataLength)?;
                }

                outputs
                    .iter()
                    .enumerate()
                    .try_for_each(|(index, output)| match output {
                        Output::ContractCreated { .. } => {
                            Err(ValidationError::TransactionScriptOutputContractCreated { index })
                        }
                        _ => Ok(()),
                    })?;

                Ok(())
            }

            Self::Create {
                inputs,
                outputs,
                witnesses,
                bytecode_witness_index,
                static_contracts,
                storage_slots,
                ..
            } => {
                match witnesses.get(*bytecode_witness_index as usize) {
                    Some(witness) if witness.as_ref().len() as u64 > CONTRACT_MAX_SIZE => {
                        Err(ValidationError::TransactionCreateBytecodeLen)?
                    }
                    None => Err(ValidationError::TransactionCreateBytecodeWitnessIndex)?,
                    _ => (),
                }

                if static_contracts.len() > MAX_STATIC_CONTRACTS as usize {
                    Err(ValidationError::TransactionCreateStaticContractsMax)?;
                }

                if !static_contracts.as_slice().windows(2).all(|w| w[0] <= w[1]) {
                    Err(ValidationError::TransactionCreateStaticContractsOrder)?;
                }

                // Restrict to subset of u16::MAX, allowing this to be increased in the future
                // in a non-breaking way.
                if storage_slots.len() > MAX_STORAGE_SLOTS as usize {
                    return Err(ValidationError::TransactionCreateStorageSlotMax);
                }

                if !storage_slots.as_slice().windows(2).all(|s| s[0] <= s[1]) {
                    return Err(ValidationError::TransactionCreateStorageSlotOrder);
                }

                // TODO Any contract with ADDRESS in staticContracts is not in the state
                // TODO The computed contract ADDRESS (see below) is not equal to the
                // contractADDRESS of the one OutputType.ContractCreated output

                inputs.iter().enumerate().try_for_each(|(index, input)| {
                    if let Input::Contract { .. } = input {
                        return Err(ValidationError::TransactionCreateInputContract { index });
                    }

                    Ok(())
                })?;

                let mut contract_created = false;
                outputs
                    .iter()
                    .enumerate()
                    .try_for_each(|(index, output)| match output {
                        Output::Contract { .. } => {
                            Err(ValidationError::TransactionCreateOutputContract { index })
                        }
                        Output::Variable { .. } => {
                            Err(ValidationError::TransactionCreateOutputVariable { index })
                        }

                        Output::Change { asset_id, .. } if asset_id != &AssetId::default() => {
                            Err(ValidationError::TransactionCreateOutputChangeNotBaseAsset {
                                index,
                            })
                        }

                        Output::ContractCreated { .. } if contract_created => Err(
                            ValidationError::TransactionCreateOutputContractCreatedMultiple {
                                index,
                            },
                        ),

                        Output::ContractCreated { .. } => {
                            contract_created = true;

                            Ok(())
                        }

                        _ => Ok(()),
                    })?;

                Ok(())
            }
        }
    }
}