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
use crate::consts::*;
use crate::{Input, Output, Transaction, Witness};

use fuel_types::{Color, Word};

mod error;

pub use error::ValidationError;

impl Input {
    pub fn validate(
        &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 })
            }

            // ∀ 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 {
    pub fn validate(&self, block_height: Word) -> Result<(), ValidationError> {
        if self.gas_price() > 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)?
        }

        let input_colors: Vec<&Color> = self.input_colors().collect();
        for input_color in input_colors.as_slice() {
            if self
                .outputs()
                .iter()
                .filter_map(|output| match output {
                    Output::Change { color, .. }
                        if color != &Color::default() && input_color == &color =>
                    {
                        Some(())
                    }
                    _ => None,
                })
                .count()
                > 1
            {
                Err(ValidationError::TransactionOutputChangeColorDuplicated)?
            }
        }

        for (index, input) in self.inputs().iter().enumerate() {
            input.validate(index, self.outputs(), self.witnesses())?;
        }

        for (index, output) in self.outputs().iter().enumerate() {
            output.validate(index, self.inputs())?;
            if let Output::Change { color, .. } = output {
                if !input_colors.iter().any(|input_color| input_color == &color) {
                    Err(ValidationError::TransactionOutputChangeColorNotFound)?
                }
            }
        }

        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,
                ..
            } => {
                match witnesses.get(*bytecode_witness_index as usize) {
                    Some(witness) if witness.as_ref().len() as u64 * 4 > 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)?;
                }

                // 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

                for (index, input) in inputs.iter().enumerate() {
                    if let Input::Contract { .. } = input {
                        Err(ValidationError::TransactionCreateInputContract { index })?
                    }
                }

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

                        Output::Change { color, .. }
                            if color == &Color::default() && change_color_zero =>
                        {
                            Err(ValidationError::TransactionCreateOutputChangeColorZero { index })?
                        }
                        Output::Change { color, .. } if color == &Color::default() => {
                            change_color_zero = true
                        }
                        Output::Change { .. } => {
                            Err(ValidationError::TransactionCreateOutputChangeColorNonZero {
                                index,
                            })?
                        }

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

                        _ => (),
                    }
                }

                Ok(())
            }
        }
    }
}