From 467dc396da355e1fb15757f8be87cebf5e9e9782 Mon Sep 17 00:00:00 2001 From: Voxelot Date: Wed, 15 Feb 2023 21:39:28 -0800 Subject: [PATCH 1/3] enable backward jumps in predicates --- fuel-vm/src/interpreter/flow.rs | 2 -- fuel-vm/src/util.rs | 3 +-- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/fuel-vm/src/interpreter/flow.rs b/fuel-vm/src/interpreter/flow.rs index 98e44984e9..9783a24071 100644 --- a/fuel-vm/src/interpreter/flow.rs +++ b/fuel-vm/src/interpreter/flow.rs @@ -24,8 +24,6 @@ where if j > VM_MAX_RAM - 1 { Err(PanicReason::MemoryOverflow.into()) - } else if self.is_predicate() && j <= self.registers[RegId::PC] { - Err(PanicReason::IllegalJump.into()) } else { self.registers[RegId::PC] = j; diff --git a/fuel-vm/src/util.rs b/fuel-vm/src/util.rs index f6ff54ff75..fe37ea1b08 100644 --- a/fuel-vm/src/util.rs +++ b/fuel-vm/src/util.rs @@ -8,9 +8,8 @@ /// # Example /// /// ``` -/// use fuel_asm::op; +/// use fuel_asm::{op, RegId}; /// use fuel_types::{Immediate18, Word}; -/// use fuel_vm::consts::{RegId::ONE, RegId::ZERO}; /// use fuel_vm::prelude::{Call, ConsensusParameters, ContractId, Opcode, SerializableVec}; /// use fuel_vm::script_with_data_offset; /// use itertools::Itertools; From 83f5958ba956e488278ac6cc0039f040a2bf243e Mon Sep 17 00:00:00 2001 From: Voxelot Date: Wed, 15 Feb 2023 21:41:43 -0800 Subject: [PATCH 2/3] bump version to 0.26.1 --- Cargo.toml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 003ffb7ccd..f0e566dbbe 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,12 +18,12 @@ edition = "2021" homepage = "https://fuel.network/" license = "BUSL-1.1" repository = "https://github.com/FuelLabs/fuel-vm" -version = "0.26.0" +version = "0.26.1" [workspace.dependencies] -fuel-asm = { version = "0.26.0", path = "./fuel-asm", default-features = false } -fuel-crypto = { version = "0.26.0", path = "./fuel-crypto", default-features = false } -fuel-merkle = { version = "0.26.0", path = "./fuel-merkle", default-features = false } -fuel-storage = { version = "0.26.0", path = "./fuel-storage", default-features = false } -fuel-tx = { version = "0.26.0", path = "./fuel-tx", default-features = false } -fuel-types = { version = "0.26.0", path = "./fuel-types", default-features = false } +fuel-asm = { version = "0.26.1", path = "./fuel-asm", default-features = false } +fuel-crypto = { version = "0.26.1", path = "./fuel-crypto", default-features = false } +fuel-merkle = { version = "0.26.1", path = "./fuel-merkle", default-features = false } +fuel-storage = { version = "0.26.1", path = "./fuel-storage", default-features = false } +fuel-tx = { version = "0.26.1", path = "./fuel-tx", default-features = false } +fuel-types = { version = "0.26.1", path = "./fuel-types", default-features = false } From 4a5780656a6b5aaf756ce8f7a58e4b40f2351f9e Mon Sep 17 00:00:00 2001 From: green Date: Mon, 27 Mar 2023 19:46:19 +0100 Subject: [PATCH 3/3] Added `BlockHeight` type and unified the code to use it everywhere --- fuel-tx/src/builder.rs | 10 +- fuel-tx/src/tests/bytes.rs | 32 +-- fuel-tx/src/tests/valid_cases/input.rs | 8 +- fuel-tx/src/tests/valid_cases/output.rs | 6 +- fuel-tx/src/tests/valid_cases/transaction.rs | 40 +-- fuel-tx/src/transaction.rs | 56 ++-- fuel-tx/src/transaction/id.rs | 24 +- fuel-tx/src/transaction/types/create.rs | 20 +- fuel-tx/src/transaction/types/input.rs | 8 +- fuel-tx/src/transaction/types/input/coin.rs | 8 +- fuel-tx/src/transaction/types/input/sizes.rs | 2 +- .../transaction/types/input/snapshot_tests.rs | 10 +- fuel-tx/src/transaction/types/mint.rs | 10 +- fuel-tx/src/transaction/types/script.rs | 20 +- fuel-tx/src/transaction/validity.rs | 18 +- fuel-tx/src/tx_pointer.rs | 30 +-- fuel-tx/test-helpers/src/lib.rs | 2 +- fuel-types/src/{types.rs => array_types.rs} | 11 +- fuel-types/src/lib.rs | 15 +- fuel-types/src/numeric_types.rs | 244 ++++++++++++++++++ fuel-vm/fuzz/fuzz_targets/grammar_aware.rs | 4 +- fuel-vm/src/checked_transaction.rs | 81 ++++-- fuel-vm/src/checked_transaction/builder.rs | 19 +- fuel-vm/src/checked_transaction/types.rs | 16 +- fuel-vm/src/context.rs | 7 +- fuel-vm/src/interpreter/blockchain.rs | 11 +- .../src/interpreter/blockchain/code_tests.rs | 8 +- .../src/interpreter/blockchain/other_tests.rs | 58 +++-- .../src/interpreter/blockchain/smo_tests.rs | 2 +- fuel-vm/src/interpreter/blockchain/test.rs | 28 +- .../src/interpreter/blockchain/test/scwq.rs | 2 +- .../src/interpreter/blockchain/test/srwq.rs | 22 +- .../src/interpreter/blockchain/test/swwq.rs | 2 +- fuel-vm/src/interpreter/contract/tests.rs | 26 +- fuel-vm/src/interpreter/crypto/tests.rs | 12 +- fuel-vm/src/interpreter/debug.rs | 8 +- fuel-vm/src/interpreter/diff/storage.rs | 6 +- .../instruction/tests/reserved_registers.rs | 13 +- fuel-vm/src/interpreter/flow/ret_tests.rs | 4 +- fuel-vm/src/interpreter/flow/tests.rs | 30 ++- fuel-vm/src/interpreter/internal.rs | 4 +- fuel-vm/src/interpreter/internal/tests.rs | 10 +- fuel-vm/src/interpreter/log/tests.rs | 4 +- .../interpreter/memory/allocation_tests.rs | 16 +- fuel-vm/src/interpreter/memory/tests.rs | 60 ++--- fuel-vm/src/interpreter/metadata.rs | 6 +- fuel-vm/src/predicate.rs | 2 +- fuel-vm/src/storage/interpreter.rs | 10 +- fuel-vm/src/storage/memory.rs | 16 +- fuel-vm/src/storage/predicate.rs | 6 +- fuel-vm/src/tests/alu.rs | 20 +- fuel-vm/src/tests/backtrace.rs | 4 +- fuel-vm/src/tests/blockchain.rs | 31 ++- fuel-vm/src/tests/code_coverage.rs | 13 +- fuel-vm/src/tests/contract.rs | 21 +- fuel-vm/src/tests/crypto.rs | 12 +- fuel-vm/src/tests/encoding.rs | 38 +-- fuel-vm/src/tests/flow.rs | 32 +-- fuel-vm/src/tests/jump_absolute.rs | 20 +- fuel-vm/src/tests/memory.rs | 12 +- fuel-vm/src/tests/metadata.rs | 14 +- fuel-vm/src/tests/outputs.rs | 15 +- fuel-vm/src/tests/predicate.rs | 82 ++++-- fuel-vm/src/tests/profile_gas.rs | 13 +- fuel-vm/src/tests/test_helpers.rs | 4 +- fuel-vm/src/tests/validation.rs | 16 +- fuel-vm/src/util.rs | 30 ++- 67 files changed, 972 insertions(+), 472 deletions(-) rename fuel-types/src/{types.rs => array_types.rs} (97%) create mode 100644 fuel-types/src/numeric_types.rs diff --git a/fuel-tx/src/builder.rs b/fuel-tx/src/builder.rs index 0ab08f4b8d..bd9655e99b 100644 --- a/fuel-tx/src/builder.rs +++ b/fuel-tx/src/builder.rs @@ -6,7 +6,7 @@ use crate::{Cacheable, Input, Mint, Output, StorageSlot, Transaction, TxPointer, use crate::Signable; use fuel_crypto::SecretKey; -use fuel_types::{Nonce, Salt, Word}; +use fuel_types::{BlockHeight, Nonce, Salt, Word}; use alloc::vec::Vec; @@ -57,7 +57,7 @@ where } /// Set the maturity - fn set_maturity(&mut self, maturity: Word) { + fn set_maturity(&mut self, maturity: BlockHeight) { *self.maturity_mut() = maturity; } } @@ -143,7 +143,7 @@ impl TransactionBuilder { } impl TransactionBuilder { - pub fn mint(block_height: u32, tx_index: u16) -> Self { + pub fn mint(block_height: BlockHeight, tx_index: u16) -> Self { let tx = Mint { tx_pointer: TxPointer::new(block_height, tx_index), outputs: Default::default(), @@ -196,7 +196,7 @@ impl TransactionBuilder { self } - pub fn maturity(&mut self, maturity: Word) -> &mut Self { + pub fn maturity(&mut self, maturity: BlockHeight) -> &mut Self { self.tx.set_maturity(maturity); self @@ -210,7 +210,7 @@ impl TransactionBuilder { amount: Word, asset_id: fuel_types::AssetId, tx_pointer: TxPointer, - maturity: Word, + maturity: BlockHeight, ) -> &mut Self { let pk = secret.public_key(); diff --git a/fuel-tx/src/tests/bytes.rs b/fuel-tx/src/tests/bytes.rs index cdaac38e54..67ac285be8 100644 --- a/fuel-tx/src/tests/bytes.rs +++ b/fuel-tx/src/tests/bytes.rs @@ -97,7 +97,7 @@ fn input() { rng.gen(), rng.gen(), rng.gen(), - rng.next_u64(), + rng.gen(), ), Input::coin_predicate( rng.gen(), @@ -494,7 +494,7 @@ fn transaction() { Transaction::script( rng.next_u64(), rng.next_u64(), - rng.next_u64(), + rng.gen(), rng.gen::().into_inner(), rng.gen::().into_inner(), vec![i.clone()], @@ -504,7 +504,7 @@ fn transaction() { Transaction::script( rng.next_u64(), rng.next_u64(), - rng.next_u64(), + rng.gen(), vec![], generate_bytes(rng), vec![i.clone()], @@ -514,7 +514,7 @@ fn transaction() { Transaction::script( rng.next_u64(), rng.next_u64(), - rng.next_u64(), + rng.gen(), rng.gen::().into_inner(), vec![], vec![i.clone()], @@ -524,7 +524,7 @@ fn transaction() { Transaction::script( rng.next_u64(), rng.next_u64(), - rng.next_u64(), + rng.gen(), vec![], vec![], vec![i.clone()], @@ -534,7 +534,7 @@ fn transaction() { Transaction::script( rng.next_u64(), rng.next_u64(), - rng.next_u64(), + rng.gen(), vec![], vec![], vec![], @@ -544,7 +544,7 @@ fn transaction() { Transaction::script( rng.next_u64(), rng.next_u64(), - rng.next_u64(), + rng.gen(), vec![], vec![], vec![], @@ -554,7 +554,7 @@ fn transaction() { Transaction::script( rng.next_u64(), rng.next_u64(), - rng.next_u64(), + rng.gen(), vec![], vec![], vec![], @@ -566,7 +566,7 @@ fn transaction() { Transaction::create( rng.next_u64(), ConsensusParameters::DEFAULT.max_gas_per_tx, - rng.next_u64(), + rng.gen(), rng.gen(), rng.gen(), vec![s.clone()], @@ -577,7 +577,7 @@ fn transaction() { Transaction::create( rng.next_u64(), ConsensusParameters::DEFAULT.max_gas_per_tx, - rng.next_u64(), + rng.gen(), rng.gen(), rng.gen(), vec![s], @@ -588,7 +588,7 @@ fn transaction() { Transaction::create( rng.next_u64(), ConsensusParameters::DEFAULT.max_gas_per_tx, - rng.next_u64(), + rng.gen(), rng.gen(), rng.gen(), vec![], @@ -599,7 +599,7 @@ fn transaction() { Transaction::create( rng.next_u64(), ConsensusParameters::DEFAULT.max_gas_per_tx, - rng.next_u64(), + rng.gen(), rng.gen(), rng.gen(), vec![], @@ -610,7 +610,7 @@ fn transaction() { Transaction::create( rng.next_u64(), ConsensusParameters::DEFAULT.max_gas_per_tx, - rng.next_u64(), + rng.gen(), rng.gen(), rng.gen(), vec![], @@ -621,7 +621,7 @@ fn transaction() { Transaction::create( rng.next_u64(), ConsensusParameters::DEFAULT.max_gas_per_tx, - rng.next_u64(), + rng.gen(), rng.gen(), rng.gen(), vec![], @@ -646,7 +646,7 @@ fn create_input_data_offset() { let gas_price = 100; let gas_limit = 1000; - let maturity = 10; + let maturity = 10.into(); let bytecode_witness_index = 0x00; let salt = rng.gen(); @@ -758,7 +758,7 @@ fn script_input_coin_data_offset() { let gas_price = 100; let gas_limit = 1000; - let maturity = 10; + let maturity = 10.into(); let script: Vec> = vec![vec![], generate_bytes(rng)]; let script_data: Vec> = vec![vec![], generate_bytes(rng)]; diff --git a/fuel-tx/src/tests/valid_cases/input.rs b/fuel-tx/src/tests/valid_cases/input.rs index 8c42ed7549..8bee5eac22 100644 --- a/fuel-tx/src/tests/valid_cases/input.rs +++ b/fuel-tx/src/tests/valid_cases/input.rs @@ -413,7 +413,7 @@ fn transaction_with_duplicate_coin_inputs_is_invalid() { .add_input(b) .add_witness(rng.gen()) .finalize() - .check_without_signatures(0, &Default::default()) + .check_without_signatures(Default::default(), &Default::default()) .expect_err("Expected checkable failure"); assert_eq!(err, CheckError::DuplicateInputUtxoId { utxo_id }); @@ -431,7 +431,7 @@ fn transaction_with_duplicate_message_inputs_is_invalid() { .add_input(message_input) .add_witness(rng.gen()) .finalize() - .check_without_signatures(0, &Default::default()) + .check_without_signatures(Default::default(), &Default::default()) .expect_err("Expected checkable failure"); assert_eq!(err, CheckError::DuplicateMessageInputId { message_id }); @@ -454,7 +454,7 @@ fn transaction_with_duplicate_contract_inputs_is_invalid() { .add_output(o) .add_output(p) .finalize() - .check_without_signatures(0, &Default::default()) + .check_without_signatures(Default::default(), &Default::default()) .expect_err("Expected checkable failure"); assert_eq!(err, CheckError::DuplicateInputContractId { contract_id }); @@ -477,6 +477,6 @@ fn transaction_with_duplicate_contract_utxo_id_is_valid() { .add_output(o) .add_output(p) .finalize() - .check_without_signatures(0, &Default::default()) + .check_without_signatures(Default::default(), &Default::default()) .expect("Duplicated UTXO id is valid for contract input"); } diff --git a/fuel-tx/src/tests/valid_cases/output.rs b/fuel-tx/src/tests/valid_cases/output.rs index fbfc4010a4..4eaca7aee6 100644 --- a/fuel-tx/src/tests/valid_cases/output.rs +++ b/fuel-tx/src/tests/valid_cases/output.rs @@ -28,7 +28,7 @@ fn contract() { rng.gen(), rng.gen(), rng.next_u32().to_be_bytes()[0], - rng.next_u64(), + rng.gen(), ), Input::contract(rng.gen(), rng.gen(), rng.gen(), rng.gen(), rng.gen()), ], @@ -46,7 +46,7 @@ fn contract() { rng.gen(), rng.gen(), rng.next_u32().to_be_bytes()[0], - rng.next_u64(), + rng.gen(), ), Input::contract(rng.gen(), rng.gen(), rng.gen(), rng.gen(), rng.gen()), ], @@ -67,7 +67,7 @@ fn contract() { rng.gen(), rng.gen(), rng.next_u32().to_be_bytes()[0], - rng.next_u64(), + rng.gen(), ), Input::contract(rng.gen(), rng.gen(), rng.gen(), rng.gen(), rng.gen()), ], diff --git a/fuel-tx/src/tests/valid_cases/transaction.rs b/fuel-tx/src/tests/valid_cases/transaction.rs index 859b017834..a1cc5cc0c2 100644 --- a/fuel-tx/src/tests/valid_cases/transaction.rs +++ b/fuel-tx/src/tests/valid_cases/transaction.rs @@ -12,8 +12,8 @@ use std::io::Write; fn gas_limit() { let rng = &mut StdRng::seed_from_u64(8586); - let maturity = 100; - let block_height = 1000; + let maturity = 100.into(); + let block_height = 1000.into(); Transaction::script( rng.gen(), @@ -78,7 +78,7 @@ fn gas_limit() { fn maturity() { let rng = &mut StdRng::seed_from_u64(8586); - let block_height = 1000; + let block_height = 1000.into(); Transaction::script( rng.gen(), @@ -96,7 +96,7 @@ fn maturity() { Transaction::create( rng.gen(), PARAMS.max_gas_per_tx, - 1000, + 1000.into(), 0, rng.gen(), vec![], @@ -110,7 +110,7 @@ fn maturity() { let err = Transaction::script( rng.gen(), PARAMS.max_gas_per_tx, - 1001, + 1001.into(), vec![], vec![], vec![], @@ -125,7 +125,7 @@ fn maturity() { let err = Transaction::create( rng.gen(), PARAMS.max_gas_per_tx, - 1001, + 1001.into(), 0, rng.gen(), vec![], @@ -143,8 +143,8 @@ fn maturity() { fn max_iow() { let rng = &mut StdRng::seed_from_u64(8586); - let maturity = 100; - let block_height = 1000; + let maturity = 100.into(); + let block_height = 1000.into(); let secret = SecretKey::random(rng); @@ -300,8 +300,8 @@ fn max_iow() { fn output_change_asset_id() { let rng = &mut StdRng::seed_from_u64(8586); - let maturity = 100; - let block_height = 1000; + let maturity = 100.into(); + let block_height = 1000.into(); let a: AssetId = rng.gen(); let b: AssetId = rng.gen(); @@ -374,8 +374,8 @@ fn output_change_asset_id() { fn script() { let rng = &mut StdRng::seed_from_u64(8586); - let maturity = 100; - let block_height = 1000; + let maturity = 100.into(); + let block_height = 1000.into(); let secret = SecretKey::random(rng); let asset_id: AssetId = rng.gen(); @@ -443,8 +443,8 @@ fn script() { fn create() { let rng = &mut StdRng::seed_from_u64(8586); - let maturity = 100; - let block_height = 1000; + let maturity = 100.into(); + let block_height = 1000.into(); let secret = SecretKey::random(rng); let secret_b = SecretKey::random(rng); @@ -659,19 +659,19 @@ fn create() { fn mint() { let rng = &mut StdRng::seed_from_u64(8586); - let block_height = 1000; + let block_height = 1000.into(); TransactionBuilder::mint(block_height, rng.gen()) .add_output(Output::coin(rng.gen(), rng.next_u64(), rng.gen())) .add_output(Output::coin(rng.gen(), rng.next_u64(), rng.gen())) .finalize() - .check(block_height as Word, &PARAMS) + .check(block_height, &PARAMS) .expect("Failed to validate tx"); let err = TransactionBuilder::mint(block_height, rng.gen()) .add_output(Output::contract(0, rng.gen(), rng.gen())) .finalize() - .check(block_height as Word, &PARAMS) + .check(block_height, &PARAMS) .expect_err("Expected erroneous transaction"); assert_eq!(err, CheckError::TransactionMintOutputIsNotCoin); @@ -680,7 +680,7 @@ fn mint() { .add_output(Output::coin(rng.gen(), rng.next_u64(), AssetId::BASE)) .add_output(Output::coin(rng.gen(), rng.next_u64(), AssetId::BASE)) .finalize() - .check(block_height as Word, &PARAMS) + .check(block_height, &PARAMS) .expect_err("Expected erroneous transaction"); assert_eq!(err, CheckError::TransactionOutputCoinAssetIdDuplicated(AssetId::BASE)); @@ -689,7 +689,7 @@ fn mint() { .add_output(Output::coin(rng.gen(), rng.next_u64(), AssetId::BASE)) .add_output(Output::coin(rng.gen(), rng.next_u64(), AssetId::BASE)) .finalize() - .check(block_height as Word + 1, &PARAMS) + .check(block_height + 1.into(), &PARAMS) .expect_err("Expected erroneous transaction"); assert_eq!(err, CheckError::TransactionMintIncorrectBlockHeight); @@ -699,7 +699,7 @@ fn mint() { fn tx_id_bytecode_len() { let rng = &mut StdRng::seed_from_u64(8586); - let maturity = 100; + let maturity = 100.into(); let gas_price = rng.gen(); let salt = rng.gen(); diff --git a/fuel-tx/src/transaction.rs b/fuel-tx/src/transaction.rs index 4a5947e7f4..4bb5abf15a 100644 --- a/fuel-tx/src/transaction.rs +++ b/fuel-tx/src/transaction.rs @@ -1,6 +1,6 @@ use fuel_crypto::PublicKey; use fuel_types::bytes::SizedBytes; -use fuel_types::{Address, AssetId, Bytes32, Nonce, Salt, Word}; +use fuel_types::{Address, AssetId, BlockHeight, Bytes32, Nonce, Salt, Word}; use alloc::vec::{IntoIter, Vec}; use itertools::Itertools; @@ -58,7 +58,7 @@ impl Transaction { pub const fn script( gas_price: Word, gas_limit: Word, - maturity: Word, + maturity: BlockHeight, script: Vec, script_data: Vec, inputs: Vec, @@ -84,7 +84,7 @@ impl Transaction { pub fn create( gas_price: Word, gas_limit: Word, - maturity: Word, + maturity: BlockHeight, bytecode_witness_index: u8, salt: Salt, storage_slots: Vec, @@ -284,7 +284,7 @@ pub trait Executable: field::Inputs + field::Outputs + field::Witnesses { amount: Word, asset_id: AssetId, tx_pointer: TxPointer, - maturity: Word, + maturity: BlockHeight, ) { let owner = Input::owner(owner); @@ -377,7 +377,7 @@ impl From for Transaction { /// used to write generic code based on the different combinations of the fields. pub mod field { use crate::{Input, Output, StorageSlot, Witness}; - use fuel_types::{Bytes32, Word}; + use fuel_types::{BlockHeight, Bytes32, Word}; use alloc::vec::Vec; @@ -402,8 +402,8 @@ pub mod field { } pub trait Maturity { - fn maturity(&self) -> &Word; - fn maturity_mut(&mut self) -> &mut Word; + fn maturity(&self) -> &BlockHeight; + fn maturity_mut(&mut self) -> &mut BlockHeight; fn maturity_offset(&self) -> usize { Self::maturity_offset_static() } @@ -528,21 +528,47 @@ mod tests { #[test] fn metered_data_excludes_witnesses() { // test script - let script_with_no_witnesses = Transaction::script(0, 0, 0, vec![], vec![], vec![], vec![], vec![]); - let script_with_witnesses = - Transaction::script(0, 0, 0, vec![], vec![], vec![], vec![], vec![[0u8; 64].to_vec().into()]); + let script_with_no_witnesses = Transaction::script( + Default::default(), + Default::default(), + Default::default(), + vec![], + vec![], + vec![], + vec![], + vec![], + ); + let script_with_witnesses = Transaction::script( + Default::default(), + Default::default(), + Default::default(), + vec![], + vec![], + vec![], + vec![], + vec![[0u8; 64].to_vec().into()], + ); assert_eq!( script_with_witnesses.metered_bytes_size(), script_with_no_witnesses.metered_bytes_size() ); // test create - let create_with_no_witnesses = - Transaction::create(0, 0, 0, 0, Default::default(), vec![], vec![], vec![], vec![]); - let create_with_witnesses = Transaction::create( - 0, - 0, + let create_with_no_witnesses = Transaction::create( + Default::default(), + Default::default(), + Default::default(), 0, + Default::default(), + vec![], + vec![], + vec![], + vec![], + ); + let create_with_witnesses = Transaction::create( + Default::default(), + Default::default(), + Default::default(), 0, Default::default(), vec![], diff --git a/fuel-tx/src/transaction/id.rs b/fuel-tx/src/transaction/id.rs index f75964091d..6bcbb688f7 100644 --- a/fuel-tx/src/transaction/id.rs +++ b/fuel-tx/src/transaction/id.rs @@ -134,6 +134,15 @@ mod tests { mem::swap(t, &mut t_p); } + fn not_u32(t: &mut T) + where + T: Copy + Into + From, + { + let u_32: u32 = (*t).into(); + let mut t_p = u_32.not().into(); + mem::swap(t, &mut t_p); + } + fn assert_id_eq(tx: &Tx, mut f: F) where F: FnMut(&mut Tx), @@ -203,9 +212,10 @@ mod tests { } fn assert_id_common_attrs(tx: &Tx) { + use core::ops::Deref; assert_id_ne(tx, |t| t.set_gas_price(t.gas_price().not())); assert_id_ne(tx, |t| t.set_gas_limit(t.gas_limit().not())); - assert_id_ne(tx, |t| t.set_maturity(t.maturity().not())); + assert_id_ne(tx, |t| t.set_maturity((t.maturity().deref().not()).into())); if !tx.inputs().is_empty() { assert_io_ne!(tx, inputs_mut, Input::CoinSigned[CoinSigned], utxo_id, invert_utxo_id); @@ -213,7 +223,7 @@ mod tests { assert_io_ne!(tx, inputs_mut, Input::CoinSigned[CoinSigned], amount, not); assert_io_ne!(tx, inputs_mut, Input::CoinSigned[CoinSigned], asset_id, invert); assert_io_ne!(tx, inputs_mut, Input::CoinSigned[CoinSigned], witness_index, not); - assert_io_ne!(tx, inputs_mut, Input::CoinSigned[CoinSigned], maturity, not); + assert_io_ne!(tx, inputs_mut, Input::CoinSigned[CoinSigned], maturity, not_u32); assert_io_ne!( tx, @@ -225,7 +235,7 @@ mod tests { assert_io_ne!(tx, inputs_mut, Input::CoinPredicate[CoinPredicate], owner, invert); assert_io_ne!(tx, inputs_mut, Input::CoinPredicate[CoinPredicate], amount, not); assert_io_ne!(tx, inputs_mut, Input::CoinPredicate[CoinPredicate], asset_id, invert); - assert_io_ne!(tx, inputs_mut, Input::CoinPredicate[CoinPredicate], maturity, not); + assert_io_ne!(tx, inputs_mut, Input::CoinPredicate[CoinPredicate], maturity, not_u32); assert_io_ne!(tx, inputs_mut, Input::CoinPredicate[CoinPredicate], predicate, inv_v); assert_io_ne!( tx, @@ -441,7 +451,7 @@ mod tests { rng.gen(), rng.gen(), rng.next_u32().to_be_bytes()[0], - rng.next_u64(), + rng.gen(), ), Input::coin_predicate( rng.gen(), @@ -449,7 +459,7 @@ mod tests { rng.next_u64(), rng.gen(), rng.gen(), - rng.next_u64(), + rng.gen(), generate_nonempty_padded_bytes(rng), generate_bytes(rng), ), @@ -514,7 +524,7 @@ mod tests { let tx = Transaction::script( rng.next_u64(), rng.next_u64(), - rng.next_u64(), + rng.gen(), script.clone(), script_data.clone(), inputs.clone(), @@ -532,7 +542,7 @@ mod tests { let tx = Transaction::create( rng.next_u64(), ConsensusParameters::DEFAULT.max_gas_per_tx, - rng.next_u64(), + rng.gen(), rng.next_u32().to_be_bytes()[0], rng.gen(), storage_slots.clone(), diff --git a/fuel-tx/src/transaction/types/create.rs b/fuel-tx/src/transaction/types/create.rs index 5593d51ff8..bb1c0dacbc 100644 --- a/fuel-tx/src/transaction/types/create.rs +++ b/fuel-tx/src/transaction/types/create.rs @@ -8,7 +8,7 @@ use crate::transaction::{ }; use crate::{Chargeable, CheckError, ConsensusParameters, Contract, Input, Output, StorageSlot, Witness}; use derivative::Derivative; -use fuel_types::{bytes, AssetId, Salt, Word}; +use fuel_types::{bytes, AssetId, BlockHeight, Salt, Word}; use fuel_types::{ bytes::{SizedBytes, WORD_SIZE}, mem_layout, MemLayout, MemLocType, @@ -32,7 +32,7 @@ mod ser_de_tests; pub struct Create { pub(crate) gas_price: Word, pub(crate) gas_limit: Word, - pub(crate) maturity: Word, + pub(crate) maturity: BlockHeight, pub(crate) bytecode_length: Word, pub(crate) bytecode_witness_index: u8, pub(crate) storage_slots: Vec, @@ -50,7 +50,7 @@ mem_layout!( repr: u8 = WORD_SIZE, gas_price: Word = WORD_SIZE, gas_limit: Word = WORD_SIZE, - maturity: Word = WORD_SIZE, + maturity: u32 = WORD_SIZE, bytecode_length: Word = WORD_SIZE, bytecode_witness_index: u8 = WORD_SIZE, storage_slots_len: Word = WORD_SIZE, @@ -111,7 +111,11 @@ impl FormatValidityChecks for Create { Ok(()) } - fn check_without_signatures(&self, block_height: Word, parameters: &ConsensusParameters) -> Result<(), CheckError> { + fn check_without_signatures( + &self, + block_height: BlockHeight, + parameters: &ConsensusParameters, + ) -> Result<(), CheckError> { check_common_part(self, block_height, parameters)?; let bytecode_witness_len = self @@ -237,12 +241,12 @@ mod field { impl Maturity for Create { #[inline(always)] - fn maturity(&self) -> &Word { + fn maturity(&self) -> &BlockHeight { &self.maturity } #[inline(always)] - fn maturity_mut(&mut self) -> &mut Word { + fn maturity_mut(&mut self) -> &mut BlockHeight { &mut self.maturity } @@ -518,7 +522,7 @@ impl io::Read for Create { bytes::store_number_at(buf, Self::layout(Self::LAYOUT.gas_price), *gas_price); bytes::store_number_at(buf, Self::layout(Self::LAYOUT.gas_limit), *gas_limit); - bytes::store_number_at(buf, Self::layout(Self::LAYOUT.maturity), *maturity); + bytes::store_number_at(buf, Self::layout(Self::LAYOUT.maturity), **maturity); bytes::store_number_at(buf, Self::layout(Self::LAYOUT.bytecode_length), *bytecode_length); bytes::store_number_at( buf, @@ -588,7 +592,7 @@ impl io::Write for Create { let gas_price = bytes::restore_number_at(buf, Self::layout(Self::LAYOUT.gas_price)); let gas_limit = bytes::restore_number_at(buf, Self::layout(Self::LAYOUT.gas_limit)); - let maturity = bytes::restore_number_at(buf, Self::layout(Self::LAYOUT.maturity)); + let maturity = bytes::restore_u32_at(buf, Self::layout(Self::LAYOUT.maturity)).into(); let bytecode_length = bytes::restore_number_at(buf, Self::layout(Self::LAYOUT.bytecode_length)); let bytecode_witness_index = bytes::restore_u8_at(buf, Self::layout(Self::LAYOUT.bytecode_witness_index)); let storage_slots_len = bytes::restore_usize_at(buf, Self::layout(Self::LAYOUT.storage_slots_len)); diff --git a/fuel-tx/src/transaction/types/input.rs b/fuel-tx/src/transaction/types/input.rs index d9ae8afd53..19805a0f0b 100644 --- a/fuel-tx/src/transaction/types/input.rs +++ b/fuel-tx/src/transaction/types/input.rs @@ -5,7 +5,7 @@ use consts::*; use contract::*; use fuel_crypto::PublicKey; use fuel_types::bytes::{SizedBytes, WORD_SIZE}; -use fuel_types::{bytes, Nonce}; +use fuel_types::{bytes, BlockHeight, Nonce}; use fuel_types::{Address, AssetId, Bytes32, ContractId, MessageId, Word}; use message::*; @@ -118,7 +118,7 @@ impl Input { amount: Word, asset_id: AssetId, tx_pointer: TxPointer, - maturity: Word, + maturity: BlockHeight, predicate: Vec, predicate_data: Vec, ) -> Self { @@ -142,7 +142,7 @@ impl Input { asset_id: AssetId, tx_pointer: TxPointer, witness_index: u8, - maturity: Word, + maturity: BlockHeight, ) -> Self { Self::CoinSigned(CoinSigned { utxo_id, @@ -322,7 +322,7 @@ impl Input { } } - pub const fn maturity(&self) -> Option { + pub const fn maturity(&self) -> Option { match self { Input::CoinSigned(CoinSigned { maturity, .. }) | Input::CoinPredicate(CoinPredicate { maturity, .. }) => { Some(*maturity) diff --git a/fuel-tx/src/transaction/types/input/coin.rs b/fuel-tx/src/transaction/types/input/coin.rs index 0a26bdc0c7..71e1a278f1 100644 --- a/fuel-tx/src/transaction/types/input/coin.rs +++ b/fuel-tx/src/transaction/types/input/coin.rs @@ -2,7 +2,7 @@ use crate::input::sizes::CoinSizes; use crate::transaction::types::input::AsField; use crate::{TxPointer, UtxoId}; use fuel_types::bytes::{Deserializable, SizedBytes}; -use fuel_types::{bytes, Address, AssetId, MemLayout, MemLocType, Word}; +use fuel_types::{bytes, Address, AssetId, BlockHeight, MemLayout, MemLocType, Word}; pub type CoinFull = Coin; pub type CoinSigned = Coin; @@ -88,7 +88,7 @@ where pub asset_id: AssetId, pub tx_pointer: TxPointer, pub witness_index: Specification::Witness, - pub maturity: Word, + pub maturity: BlockHeight, pub predicate: Specification::Predicate, pub predicate_data: Specification::PredicateData, } @@ -176,7 +176,7 @@ where 0 }; bytes::store_number_at(buf, S::layout(S::LAYOUT.witness_index), witness_index); - bytes::store_number_at(buf, S::layout(S::LAYOUT.maturity), *maturity); + bytes::store_number_at(buf, S::layout(S::LAYOUT.maturity), **maturity); let predicate_len = if let Some(predicate) = predicate.as_field() { predicate.len() @@ -245,7 +245,7 @@ where if let Some(witness_index_field) = self.witness_index.as_mut_field() { *witness_index_field = witness_index; } - let maturity = bytes::restore_number_at(buf, S::layout(S::LAYOUT.maturity)); + let maturity = bytes::restore_u32_at(buf, S::layout(S::LAYOUT.maturity)).into(); self.maturity = maturity; let predicate_len = bytes::restore_usize_at(buf, S::layout(S::LAYOUT.predicate_len)); diff --git a/fuel-tx/src/transaction/types/input/sizes.rs b/fuel-tx/src/transaction/types/input/sizes.rs index 60a0c1705a..0024cee212 100644 --- a/fuel-tx/src/transaction/types/input/sizes.rs +++ b/fuel-tx/src/transaction/types/input/sizes.rs @@ -18,7 +18,7 @@ mem_layout!( asset_id: AssetId = {AssetId::LEN}, tx_pointer: TxPointer = {TxPointer::LEN}, witness_index: u8 = WORD_SIZE, - maturity: Word = WORD_SIZE, + maturity: u32 = WORD_SIZE, predicate_len: Word = WORD_SIZE, predicate_data_len: Word = WORD_SIZE ); diff --git a/fuel-tx/src/transaction/types/input/snapshot_tests.rs b/fuel-tx/src/transaction/types/input/snapshot_tests.rs index 6a4fc6450d..6465da4325 100644 --- a/fuel-tx/src/transaction/types/input/snapshot_tests.rs +++ b/fuel-tx/src/transaction/types/input/snapshot_tests.rs @@ -12,9 +12,9 @@ fn tx_with_signed_coin_snapshot() { owner: [2u8; 32].into(), amount: 11, asset_id: [5u8; 32].into(), - tx_pointer: TxPointer::new(46, 5), + tx_pointer: TxPointer::new(46.into(), 5), witness_index: 4, - maturity: 2, + maturity: 2.into(), predicate: (), predicate_data: (), })) @@ -33,9 +33,9 @@ fn tx_with_predicate_coin_snapshot() { owner: [2u8; 32].into(), amount: 11, asset_id: [5u8; 32].into(), - tx_pointer: TxPointer::new(46, 5), + tx_pointer: TxPointer::new(46.into(), 5), witness_index: (), - maturity: 2, + maturity: 2.into(), predicate: vec![3u8; 10], predicate_data: vec![4u8; 12], })) @@ -53,7 +53,7 @@ fn tx_with_contract_snapshot() { utxo_id: UtxoId::new([1u8; 32].into(), 2), balance_root: [2u8; 32].into(), state_root: [3u8; 32].into(), - tx_pointer: TxPointer::new(46, 5), + tx_pointer: TxPointer::new(46.into(), 5), contract_id: [5u8; 32].into(), })) .finalize_as_transaction(); diff --git a/fuel-tx/src/transaction/types/mint.rs b/fuel-tx/src/transaction/types/mint.rs index 3852977e79..c118257578 100644 --- a/fuel-tx/src/transaction/types/mint.rs +++ b/fuel-tx/src/transaction/types/mint.rs @@ -6,7 +6,7 @@ use crate::{CheckError, ConsensusParameters, Output, TxPointer}; use derivative::Derivative; use fuel_types::{ bytes::{SizedBytes, WORD_SIZE}, - mem_layout, MemLayout, MemLocType, + mem_layout, BlockHeight, MemLayout, MemLocType, }; use fuel_types::{Bytes32, Word}; @@ -104,11 +104,15 @@ impl FormatValidityChecks for Mint { Ok(()) } - fn check_without_signatures(&self, block_height: Word, parameters: &ConsensusParameters) -> Result<(), CheckError> { + fn check_without_signatures( + &self, + block_height: BlockHeight, + parameters: &ConsensusParameters, + ) -> Result<(), CheckError> { if self.outputs().len() > parameters.max_outputs as usize { return Err(CheckError::TransactionOutputsMax); } - if self.tx_pointer().block_height() as u64 != block_height { + if self.tx_pointer().block_height() != block_height { return Err(CheckError::TransactionMintIncorrectBlockHeight); } diff --git a/fuel-tx/src/transaction/types/script.rs b/fuel-tx/src/transaction/types/script.rs index a867c4fc7b..2ce06e6899 100644 --- a/fuel-tx/src/transaction/types/script.rs +++ b/fuel-tx/src/transaction/types/script.rs @@ -8,7 +8,7 @@ use crate::transaction::{ }; use crate::{CheckError, ConsensusParameters, Input, Output, Witness}; use derivative::Derivative; -use fuel_types::{bytes, Bytes32, Word}; +use fuel_types::{bytes, BlockHeight, Bytes32, Word}; use fuel_types::{ bytes::{SizedBytes, WORD_SIZE}, mem_layout, MemLayout, MemLocType, @@ -35,7 +35,7 @@ pub(crate) struct ScriptMetadata { pub struct Script { pub(crate) gas_price: Word, pub(crate) gas_limit: Word, - pub(crate) maturity: Word, + pub(crate) maturity: BlockHeight, pub(crate) script: Vec, pub(crate) script_data: Vec, pub(crate) inputs: Vec, @@ -52,7 +52,7 @@ mem_layout!( repr: u8 = WORD_SIZE, gas_price: Word = WORD_SIZE, gas_limit: Word = WORD_SIZE, - maturity: Word = WORD_SIZE, + maturity: u32 = WORD_SIZE, script_len: Word = WORD_SIZE, script_data_len: Word = WORD_SIZE, inputs_len: Word = WORD_SIZE, @@ -139,7 +139,11 @@ impl FormatValidityChecks for Script { Ok(()) } - fn check_without_signatures(&self, block_height: Word, parameters: &ConsensusParameters) -> Result<(), CheckError> { + fn check_without_signatures( + &self, + block_height: BlockHeight, + parameters: &ConsensusParameters, + ) -> Result<(), CheckError> { check_common_part(self, block_height, parameters)?; if self.script.len() > parameters.max_script_length as usize { @@ -222,12 +226,12 @@ mod field { impl Maturity for Script { #[inline(always)] - fn maturity(&self) -> &Word { + fn maturity(&self) -> &BlockHeight { &self.maturity } #[inline(always)] - fn maturity_mut(&mut self) -> &mut Word { + fn maturity_mut(&mut self) -> &mut BlockHeight { &mut self.maturity } @@ -504,7 +508,7 @@ impl io::Read for Script { bytes::store_number_at(buf, Self::layout(Self::LAYOUT.gas_price), *gas_price); bytes::store_number_at(buf, Self::layout(Self::LAYOUT.gas_limit), *gas_limit); - bytes::store_number_at(buf, Self::layout(Self::LAYOUT.maturity), *maturity); + bytes::store_number_at(buf, Self::layout(Self::LAYOUT.maturity), **maturity); bytes::store_number_at(buf, Self::layout(Self::LAYOUT.script_len), script.len() as Word); bytes::store_number_at( buf, @@ -562,7 +566,7 @@ impl io::Write for Script { let gas_price = bytes::restore_number_at(buf, Self::layout(Self::LAYOUT.gas_price)); let gas_limit = bytes::restore_number_at(buf, Self::layout(Self::LAYOUT.gas_limit)); - let maturity = bytes::restore_number_at(buf, Self::layout(Self::LAYOUT.maturity)); + let maturity = bytes::restore_u32_at(buf, Self::layout(Self::LAYOUT.maturity)).into(); let script_len = bytes::restore_usize_at(buf, Self::layout(Self::LAYOUT.script_len)); let script_data_len = bytes::restore_usize_at(buf, Self::layout(Self::LAYOUT.script_data_len)); let inputs_len = bytes::restore_usize_at(buf, Self::layout(Self::LAYOUT.inputs_len)); diff --git a/fuel-tx/src/transaction/validity.rs b/fuel-tx/src/transaction/validity.rs index 544a58ac01..f343291f58 100644 --- a/fuel-tx/src/transaction/validity.rs +++ b/fuel-tx/src/transaction/validity.rs @@ -1,7 +1,7 @@ use crate::{Input, Output, Transaction, Witness}; use core::hash::Hash; -use fuel_types::{AssetId, Word}; +use fuel_types::{AssetId, BlockHeight}; #[cfg(feature = "std")] use fuel_types::Bytes32; @@ -181,7 +181,7 @@ pub trait FormatValidityChecks { #[cfg(feature = "std")] /// Performs all stateless transaction validity checks. This includes the validity /// of fields according to rules in the specification and validity of signatures. - fn check(&self, block_height: Word, parameters: &ConsensusParameters) -> Result<(), CheckError> { + fn check(&self, block_height: BlockHeight, parameters: &ConsensusParameters) -> Result<(), CheckError> { self.check_without_signatures(block_height, parameters)?; self.check_signatures()?; @@ -194,7 +194,11 @@ pub trait FormatValidityChecks { /// Validates the transactions according to rules from the specification: /// https://github.com/FuelLabs/fuel-specs/blob/master/src/protocol/tx_format/transaction.md#transaction - fn check_without_signatures(&self, block_height: Word, parameters: &ConsensusParameters) -> Result<(), CheckError>; + fn check_without_signatures( + &self, + block_height: BlockHeight, + parameters: &ConsensusParameters, + ) -> Result<(), CheckError>; } impl FormatValidityChecks for Transaction { @@ -207,7 +211,11 @@ impl FormatValidityChecks for Transaction { } } - fn check_without_signatures(&self, block_height: Word, parameters: &ConsensusParameters) -> Result<(), CheckError> { + fn check_without_signatures( + &self, + block_height: BlockHeight, + parameters: &ConsensusParameters, + ) -> Result<(), CheckError> { match self { Transaction::Script(script) => script.check_without_signatures(block_height, parameters), Transaction::Create(create) => create.check_without_signatures(block_height, parameters), @@ -218,7 +226,7 @@ impl FormatValidityChecks for Transaction { pub(crate) fn check_common_part( tx: &T, - block_height: Word, + block_height: BlockHeight, parameters: &ConsensusParameters, ) -> Result<(), CheckError> where diff --git a/fuel-tx/src/tx_pointer.rs b/fuel-tx/src/tx_pointer.rs index 22b6fdcbc4..7172e9bce3 100644 --- a/fuel-tx/src/tx_pointer.rs +++ b/fuel-tx/src/tx_pointer.rs @@ -1,7 +1,6 @@ -use fuel_asm::Word; use fuel_types::{ bytes::{SizedBytes, WORD_SIZE}, - mem_layout, MemLayout, MemLocType, + mem_layout, BlockHeight, MemLayout, MemLocType, }; use core::{fmt, str}; @@ -23,25 +22,25 @@ use rand::{ #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct TxPointer { /// Block height - block_height: u32, + block_height: BlockHeight, /// Transaction index tx_index: u16, } mem_layout!( TxPointerLayout for TxPointer - block_height: Word = WORD_SIZE, - tx_index: Word = WORD_SIZE + block_height: u32 = WORD_SIZE, + tx_index: u16 = WORD_SIZE ); impl TxPointer { pub const LEN: usize = 2 * WORD_SIZE; - pub const fn new(block_height: u32, tx_index: u16) -> Self { + pub const fn new(block_height: BlockHeight, tx_index: u16) -> Self { Self { block_height, tx_index } } - pub const fn block_height(&self) -> u32 { + pub const fn block_height(&self) -> BlockHeight { self.block_height } @@ -88,7 +87,7 @@ impl str::FromStr for TxPointer { let block_height = u32::from_str_radix(&s[..8], 16).map_err(|_| ERR)?; let tx_index = u16::from_str_radix(&s[8..12], 16).map_err(|_| ERR)?; - Ok(Self::new(block_height, tx_index)) + Ok(Self::new(block_height.into(), tx_index)) } } @@ -106,12 +105,11 @@ impl io::Write for TxPointer { .and_then(|slice| slice.try_into().ok()) .ok_or(bytes::eof())?; - let block_height = bytes::restore_word_at(buf, Self::layout(Self::LAYOUT.block_height)); - let tx_index = bytes::restore_word_at(buf, Self::layout(Self::LAYOUT.tx_index)); + let block_height = bytes::restore_u32_at(buf, Self::layout(Self::LAYOUT.block_height)).into(); + let tx_index = bytes::restore_u16_at(buf, Self::layout(Self::LAYOUT.tx_index)); - self.block_height = u32::try_from(block_height).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; - - self.tx_index = u16::try_from(tx_index).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; + self.block_height = block_height; + self.tx_index = tx_index; Ok(Self::LEN) } @@ -129,8 +127,8 @@ impl io::Read for TxPointer { .and_then(|slice| slice.try_into().ok()) .ok_or(bytes::eof())?; - bytes::store_number_at(buf, Self::layout(Self::LAYOUT.block_height), self.block_height as Word); - bytes::store_number_at(buf, Self::layout(Self::LAYOUT.tx_index), self.tx_index as Word); + bytes::store_number_at(buf, Self::layout(Self::LAYOUT.block_height), *self.block_height); + bytes::store_number_at(buf, Self::layout(Self::LAYOUT.tx_index), self.tx_index); Ok(Self::LEN) } @@ -143,7 +141,7 @@ fn fmt_encode_decode() { let cases = vec![(83473, 3829)]; for (block_height, tx_index) in cases { - let tx_pointer = TxPointer::new(block_height, tx_index); + let tx_pointer = TxPointer::new(block_height.into(), tx_index); let lower = format!("{tx_pointer:x}"); let upper = format!("{tx_pointer:X}"); diff --git a/fuel-tx/test-helpers/src/lib.rs b/fuel-tx/test-helpers/src/lib.rs index 14812fc236..3074754702 100644 --- a/fuel-tx/test-helpers/src/lib.rs +++ b/fuel-tx/test-helpers/src/lib.rs @@ -27,7 +27,7 @@ pub fn generate_bytes(rng: &mut R) -> Vec where R: Rng, { - let len = rng.gen_range(0..512); + let len = rng.gen_range(1..512); let mut data = alloc::vec![0u8; len]; rng.fill_bytes(data.as_mut_slice()); diff --git a/fuel-types/src/types.rs b/fuel-types/src/array_types.rs similarity index 97% rename from fuel-types/src/types.rs rename to fuel-types/src/array_types.rs index d16528cff9..d2edb1f66f 100644 --- a/fuel-types/src/types.rs +++ b/fuel-types/src/array_types.rs @@ -13,19 +13,12 @@ use rand::{ Rng, }; -const fn hex_val(c: u8) -> Option { - match c { - b'A'..=b'F' => Some(c - b'A' + 10), - b'a'..=b'f' => Some(c - b'a' + 10), - b'0'..=b'9' => Some(c - b'0'), - _ => None, - } -} +use crate::hex_val; macro_rules! key { ($i:ident, $s:expr) => { #[derive(Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] - /// FuelVM atomic type. + /// FuelVM atomic array type. #[repr(transparent)] pub struct $i([u8; $s]); diff --git a/fuel-types/src/lib.rs b/fuel-types/src/lib.rs index 71be657eb9..0530940eb3 100644 --- a/fuel-types/src/lib.rs +++ b/fuel-types/src/lib.rs @@ -9,11 +9,13 @@ extern crate alloc; extern crate core; +mod array_types; mod layout; -mod types; +mod numeric_types; +pub use array_types::*; pub use layout::*; -pub use types::*; +pub use numeric_types::*; /// Word-aligned bytes serialization functions. pub mod bytes; @@ -38,3 +40,12 @@ pub type Immediate18 = u32; /// 24-bits immediate value type pub type Immediate24 = u32; + +pub(crate) const fn hex_val(c: u8) -> Option { + match c { + b'A'..=b'F' => Some(c - b'A' + 10), + b'a'..=b'f' => Some(c - b'a' + 10), + b'0'..=b'9' => Some(c - b'0'), + _ => None, + } +} diff --git a/fuel-types/src/numeric_types.rs b/fuel-types/src/numeric_types.rs new file mode 100644 index 0000000000..178cabd57f --- /dev/null +++ b/fuel-types/src/numeric_types.rs @@ -0,0 +1,244 @@ +use core::array::TryFromSliceError; +use core::borrow::Borrow; +use core::borrow::BorrowMut; +use core::convert::TryFrom; +use core::ops::{Add, Deref, DerefMut, Sub}; +use core::{fmt, str}; + +#[cfg(feature = "random")] +use rand::{ + distributions::{Distribution, Standard}, + Rng, +}; + +use crate::hex_val; + +macro_rules! key { + ($i:ident, $t:ty) => { + #[derive(Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] + /// FuelVM atomic numeric type. + #[repr(transparent)] + pub struct $i($t); + + key_methods!($i, $t); + + #[cfg(feature = "random")] + impl Distribution<$i> for Standard { + fn sample(&self, rng: &mut R) -> $i { + $i(rng.gen()) + } + } + }; +} + +macro_rules! key_methods { + ($i:ident, $t:ty) => { + impl $i { + /// Number constructor. + pub const fn new(number: $t) -> Self { + Self(number) + } + + /// Convert to array of big endian bytes. + pub fn to_bytes(self) -> [u8; 4] { + self.0.to_be_bytes() + } + + /// Convert to usize. + pub const fn to_usize(self) -> usize { + self.0 as usize + } + + /// Convert to usize. + pub const fn as_usize(&self) -> usize { + self.0 as usize + } + } + + const SIZE: usize = core::mem::size_of::<$t>(); + + #[cfg(feature = "random")] + impl rand::Fill for $i { + fn try_fill(&mut self, rng: &mut R) -> Result<(), rand::Error> { + let number = rng.gen(); + *self = $i(number); + + Ok(()) + } + } + + impl Deref for $i { + type Target = $t; + + fn deref(&self) -> &$t { + &self.0 + } + } + + impl Borrow<$t> for $i { + fn borrow(&self) -> &$t { + &self.0 + } + } + + impl BorrowMut<$t> for $i { + fn borrow_mut(&mut self) -> &mut $t { + &mut self.0 + } + } + + impl DerefMut for $i { + fn deref_mut(&mut self) -> &mut $t { + &mut self.0 + } + } + + impl From<[u8; SIZE]> for $i { + fn from(bytes: [u8; SIZE]) -> Self { + Self(<$t>::from_be_bytes(bytes)) + } + } + + impl From<$t> for $i { + fn from(value: $t) -> Self { + Self(value) + } + } + + impl From<$i> for [u8; SIZE] { + fn from(salt: $i) -> [u8; SIZE] { + salt.0.to_be_bytes() + } + } + + impl From<$i> for $t { + fn from(salt: $i) -> $t { + salt.0 + } + } + + impl TryFrom<&[u8]> for $i { + type Error = TryFromSliceError; + + fn try_from(bytes: &[u8]) -> Result<$i, TryFromSliceError> { + <[u8; SIZE]>::try_from(bytes).map(|b| b.into()) + } + } + + impl fmt::LowerHex for $i { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if f.alternate() { + write!(f, "0x")? + } + + let bytes = self.0.to_be_bytes(); + match f.width() { + Some(w) if w > 0 => bytes + .chunks(2 * bytes.len() / w) + .try_for_each(|c| write!(f, "{:02x}", c.iter().fold(0u8, |acc, x| acc ^ x))), + + _ => bytes.iter().try_for_each(|b| write!(f, "{:02x}", &b)), + } + } + } + + impl fmt::UpperHex for $i { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if f.alternate() { + write!(f, "0x")? + } + + let bytes = self.0.to_be_bytes(); + match f.width() { + Some(w) if w > 0 => bytes + .chunks(2 * bytes.len() / w) + .try_for_each(|c| write!(f, "{:02X}", c.iter().fold(0u8, |acc, x| acc ^ x))), + + _ => bytes.iter().try_for_each(|b| write!(f, "{:02X}", &b)), + } + } + } + + impl fmt::Debug for $i { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + ::fmt(&self, f) + } + } + + impl fmt::Display for $i { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + ::fmt(&self, f) + } + } + + impl str::FromStr for $i { + type Err = &'static str; + + fn from_str(s: &str) -> Result { + const ERR: &str = "Invalid encoded byte"; + + let alternate = s.starts_with("0x"); + + let mut b = s.bytes(); + let mut ret = <[u8; SIZE]>::default(); + + if alternate { + b.next(); + b.next(); + } + + for r in ret.as_mut() { + let h = b.next().and_then(hex_val).ok_or(ERR)?; + let l = b.next().and_then(hex_val).ok_or(ERR)?; + + *r = h << 4 | l; + } + + Ok(ret.into()) + } + } + + impl Add for $i { + type Output = $i; + + #[inline(always)] + fn add(self, rhs: $i) -> $i { + $i(self.0.wrapping_add(rhs.0)) + } + } + + impl Sub for $i { + type Output = $i; + + #[inline(always)] + fn sub(self, rhs: $i) -> $i { + $i(self.0.wrapping_sub(rhs.0)) + } + } + + #[cfg(feature = "serde")] + impl serde::Serialize for $i { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + use alloc::format; + serializer.serialize_str(&format!("{:x}", &self)) + } + } + + #[cfg(feature = "serde")] + impl<'de> serde::Deserialize<'de> for $i { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + use serde::de::Error; + let s: &str = serde::Deserialize::deserialize(deserializer)?; + s.parse().map_err(D::Error::custom) + } + } + }; +} + +key!(BlockHeight, u32); diff --git a/fuel-vm/fuzz/fuzz_targets/grammar_aware.rs b/fuel-vm/fuzz/fuzz_targets/grammar_aware.rs index aed723a705..3d2aa1779e 100644 --- a/fuel-vm/fuzz/fuzz_targets/grammar_aware.rs +++ b/fuel-vm/fuzz/fuzz_targets/grammar_aware.rs @@ -18,8 +18,8 @@ fuzz_target!(|data: FuzzData| { let gas_price = 0; let gas_limit = 1_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::DEFAULT; let tx = Transaction::script( diff --git a/fuel-vm/src/checked_transaction.rs b/fuel-vm/src/checked_transaction.rs index 51311a8798..91707e8a69 100644 --- a/fuel-vm/src/checked_transaction.rs +++ b/fuel-vm/src/checked_transaction.rs @@ -6,7 +6,7 @@ #![allow(non_upper_case_globals)] use fuel_tx::{CheckError, ConsensusParameters, Create, Mint, Script, Transaction}; -use fuel_types::Word; +use fuel_types::BlockHeight; use core::borrow::Borrow; @@ -149,7 +149,7 @@ pub trait IntoChecked: FormatValidityChecks + Sized { /// Returns transaction that passed all `Checks`. fn into_checked( self, - block_height: Word, + block_height: BlockHeight, params: &ConsensusParameters, gas_costs: &GasCosts, ) -> Result, CheckError> @@ -162,7 +162,11 @@ pub trait IntoChecked: FormatValidityChecks + Sized { } /// Returns transaction that passed only `Checks::Basic`. - fn into_checked_basic(self, block_height: Word, params: &ConsensusParameters) -> Result, CheckError>; + fn into_checked_basic( + self, + block_height: BlockHeight, + params: &ConsensusParameters, + ) -> Result, CheckError>; } /// Performs predicate verification for a transaction @@ -318,7 +322,11 @@ impl From<::Metadata> for CheckedMetadata { impl IntoChecked for Transaction { type Metadata = CheckedMetadata; - fn into_checked_basic(self, block_height: Word, params: &ConsensusParameters) -> Result, CheckError> { + fn into_checked_basic( + self, + block_height: BlockHeight, + params: &ConsensusParameters, + ) -> Result, CheckError> { let (transaction, metadata) = match self { Transaction::Script(script) => { let (transaction, metadata) = script.into_checked_basic(block_height, params)?.into(); @@ -351,7 +359,7 @@ mod tests { #[test] fn checked_tx_has_default() { - let height = 1; + let height = 1.into(); Checked::::default() .transaction() @@ -371,7 +379,7 @@ mod tests { let checked = tx .clone() - .into_checked(0, &ConsensusParameters::DEFAULT, &Default::default()) + .into_checked(Default::default(), &ConsensusParameters::DEFAULT, &Default::default()) .expect("Expected valid transaction"); // verify transaction getter works @@ -393,7 +401,7 @@ mod tests { let tx = signed_message_coin_tx(rng, gas_price, gas_limit, input_amount); let checked = tx - .into_checked(0, &ConsensusParameters::DEFAULT, &Default::default()) + .into_checked(Default::default(), &ConsensusParameters::DEFAULT, &Default::default()) .expect("Expected valid transaction"); // verify available balance was decreased by max fee @@ -413,7 +421,7 @@ mod tests { let tx = signed_message_coin_tx(rng, gas_price, gas_limit, input_amount); let checked = tx - .into_checked(0, &ConsensusParameters::DEFAULT, &Default::default()) + .into_checked(Default::default(), &ConsensusParameters::DEFAULT, &Default::default()) .expect("Expected valid transaction"); // verify available balance was decreased by max fee @@ -437,7 +445,7 @@ mod tests { .finalize(); let err = tx - .into_checked(0, &ConsensusParameters::DEFAULT, &Default::default()) + .into_checked(Default::default(), &ConsensusParameters::DEFAULT, &Default::default()) .expect_err("Expected valid transaction"); // verify available balance was decreased by max fee @@ -472,7 +480,7 @@ mod tests { .finalize(); let err = tx - .into_checked(0, &ConsensusParameters::DEFAULT, &Default::default()) + .into_checked(Default::default(), &ConsensusParameters::DEFAULT, &Default::default()) .expect_err("Expected valid transaction"); // verify available balance was decreased by max fee @@ -610,8 +618,8 @@ mod tests { input_amount, asset, rng.gen(), - 0, - 0, + Default::default(), + Default::default(), )) .add_input(Input::contract(rng.gen(), rng.gen(), rng.gen(), rng.gen(), rng.gen())) .add_output(Output::contract(1, rng.gen(), rng.gen())) @@ -621,7 +629,7 @@ mod tests { .finalize(); let checked = tx - .into_checked(0, &ConsensusParameters::DEFAULT, &Default::default()) + .into_checked(Default::default(), &ConsensusParameters::DEFAULT, &Default::default()) .expect_err("Expected invalid transaction"); // assert that tx without base input assets fails @@ -647,7 +655,7 @@ mod tests { let transaction = base_asset_tx(rng, input_amount, gas_price, gas_limit); let err = transaction - .into_checked(0, ¶ms, &Default::default()) + .into_checked(Default::default(), ¶ms, &Default::default()) .expect_err("insufficient fee amount expected"); let provided = match err { @@ -672,7 +680,7 @@ mod tests { let transaction = base_asset_tx(rng, input_amount, gas_price, gas_limit); let err = transaction - .into_checked(0, ¶ms, &Default::default()) + .into_checked(Default::default(), ¶ms, &Default::default()) .expect_err("insufficient fee amount expected"); let provided = match err { @@ -694,7 +702,7 @@ mod tests { let transaction = base_asset_tx(rng, input_amount, gas_price, gas_limit); let err = transaction - .into_checked(0, ¶ms, &Default::default()) + .into_checked(Default::default(), ¶ms, &Default::default()) .expect_err("overflow expected"); assert_eq!(err, CheckError::ArithmeticOverflow); @@ -711,7 +719,7 @@ mod tests { let transaction = base_asset_tx(rng, input_amount, gas_price, gas_limit); let err = transaction - .into_checked(0, ¶ms, &Default::default()) + .into_checked(Default::default(), ¶ms, &Default::default()) .expect_err("overflow expected"); assert_eq!(err, CheckError::ArithmeticOverflow); @@ -727,16 +735,30 @@ mod tests { .gas_price(1) .gas_limit(100) // base asset - .add_unsigned_coin_input(secret, rng.gen(), input_amount, AssetId::default(), rng.gen(), 0) + .add_unsigned_coin_input( + secret, + rng.gen(), + input_amount, + AssetId::default(), + rng.gen(), + Default::default(), + ) .add_output(Output::change(rng.gen(), 0, AssetId::default())) // arbitrary spending asset - .add_unsigned_coin_input(secret, rng.gen(), input_amount, any_asset, rng.gen(), 0) + .add_unsigned_coin_input( + secret, + rng.gen(), + input_amount, + any_asset, + rng.gen(), + Default::default(), + ) .add_output(Output::coin(rng.gen(), input_amount + 1, any_asset)) .add_output(Output::change(rng.gen(), 0, any_asset)) .finalize(); let checked = tx - .into_checked(0, &ConsensusParameters::DEFAULT, &Default::default()) + .into_checked(Default::default(), &ConsensusParameters::DEFAULT, &Default::default()) .expect_err("Expected valid transaction"); assert_eq!( @@ -751,7 +773,7 @@ mod tests { #[test] fn basic_check_marks_basic_flag() { - let block_height = 1; + let block_height = 1.into(); let params = ConsensusParameters::default(); let tx = Transaction::default(); @@ -763,7 +785,7 @@ mod tests { #[test] fn signatures_check_marks_signatures_flag() { let mut rng = StdRng::seed_from_u64(1); - let block_height = 1; + let block_height = 1.into(); let params = ConsensusParameters::default(); let tx = valid_coin_tx(&mut rng, 1, 100000, 1000000, 10); @@ -781,7 +803,7 @@ mod tests { #[test] fn predicates_check_marks_predicate_flag() { let mut rng = StdRng::seed_from_u64(1); - let block_height = 1; + let block_height = 1.into(); let params = ConsensusParameters::default(); let gas_costs = GasCosts::default(); @@ -839,7 +861,7 @@ mod tests { TransactionBuilder::script(vec![], vec![]) .gas_price(gas_price) .gas_limit(gas_limit) - .add_unsigned_coin_input(rng.gen(), rng.gen(), input_amount, asset, rng.gen(), 0) + .add_unsigned_coin_input(rng.gen(), rng.gen(), input_amount, asset, rng.gen(), Default::default()) .add_input(Input::contract(rng.gen(), rng.gen(), rng.gen(), rng.gen(), rng.gen())) .add_output(Output::contract(1, rng.gen(), rng.gen())) .add_output(Output::coin(rng.gen(), output_amount, asset)) @@ -861,7 +883,7 @@ mod tests { fee_input_amount, asset, rng.gen(), - 0, + Default::default(), predicate, vec![], )) @@ -897,7 +919,14 @@ mod tests { TransactionBuilder::script(vec![], vec![]) .gas_price(gas_price) .gas_limit(gas_limit) - .add_unsigned_coin_input(rng.gen(), rng.gen(), input_amount, AssetId::default(), rng.gen(), 0) + .add_unsigned_coin_input( + rng.gen(), + rng.gen(), + input_amount, + AssetId::default(), + rng.gen(), + Default::default(), + ) .add_output(Output::change(rng.gen(), 0, AssetId::default())) .finalize() } diff --git a/fuel-vm/src/checked_transaction/builder.rs b/fuel-vm/src/checked_transaction/builder.rs index 7025bdd8fa..0a305323d5 100644 --- a/fuel-vm/src/checked_transaction/builder.rs +++ b/fuel-vm/src/checked_transaction/builder.rs @@ -4,6 +4,7 @@ use super::{Checked, IntoChecked}; use crate::checked_transaction::CheckPredicates; use crate::prelude::*; use fuel_tx::ConsensusParameters; +use fuel_types::BlockHeight; /// Extension trait for [`fuel_tx::TransactionBuilder`] adding finalization methods pub trait TransactionBuilderExt @@ -11,10 +12,15 @@ where Tx: IntoChecked, { /// Finalize the builder into a [`Checked`] of the correct type - fn finalize_checked(&mut self, height: Word, params: &ConsensusParameters, gas_costs: &GasCosts) -> Checked; + fn finalize_checked( + &mut self, + height: BlockHeight, + params: &ConsensusParameters, + gas_costs: &GasCosts, + ) -> Checked; /// Finalize the builder into a [`Checked`] of the correct type, with basic checks only - fn finalize_checked_basic(&mut self, height: Word, params: &ConsensusParameters) -> Checked; + fn finalize_checked_basic(&mut self, height: BlockHeight, params: &ConsensusParameters) -> Checked; } impl TransactionBuilderExt for TransactionBuilder @@ -22,13 +28,18 @@ where Self: Finalizable, Checked: CheckPredicates, { - fn finalize_checked(&mut self, height: Word, params: &ConsensusParameters, gas_costs: &GasCosts) -> Checked { + fn finalize_checked( + &mut self, + height: BlockHeight, + params: &ConsensusParameters, + gas_costs: &GasCosts, + ) -> Checked { self.finalize() .into_checked(height, params, gas_costs) .expect("failed to check tx") } - fn finalize_checked_basic(&mut self, height: Word, params: &ConsensusParameters) -> Checked { + fn finalize_checked_basic(&mut self, height: BlockHeight, params: &ConsensusParameters) -> Checked { self.finalize() .into_checked_basic(height, params) .expect("failed to check tx") diff --git a/fuel-vm/src/checked_transaction/types.rs b/fuel-vm/src/checked_transaction/types.rs index 49378cc161..2a1a6f3c78 100644 --- a/fuel-vm/src/checked_transaction/types.rs +++ b/fuel-vm/src/checked_transaction/types.rs @@ -53,7 +53,7 @@ pub mod create { }; use crate::checked_transaction::NonRetryableFreeBalances; use fuel_tx::{Cacheable, CheckError, ConsensusParameters, Create, FormatValidityChecks, TransactionFee}; - use fuel_types::Word; + use fuel_types::{BlockHeight, Word}; /// Metdata produced by checking [`fuel_tx::Create`]. #[derive(Debug, Clone, Eq, PartialEq, Hash)] @@ -61,7 +61,7 @@ pub mod create { /// See [`NonRetryableFreeBalances`]. pub free_balances: NonRetryableFreeBalances, /// The block height this tx was verified with - pub block_height: Word, + pub block_height: BlockHeight, /// The fees and gas usage pub fee: TransactionFee, /// If predicates have been checked, this is how much gas checking them used. @@ -74,7 +74,7 @@ pub mod create { fn into_checked_basic( mut self, - block_height: Word, + block_height: BlockHeight, params: &ConsensusParameters, ) -> Result, CheckError> { self.precompute(); @@ -107,14 +107,14 @@ pub mod create { pub mod mint { use super::super::{Checked, IntoChecked}; use fuel_tx::{Cacheable, CheckError, ConsensusParameters, FormatValidityChecks, Mint}; - use fuel_types::Word; + use fuel_types::BlockHeight; impl IntoChecked for Mint { type Metadata = (); fn into_checked_basic( mut self, - block_height: Word, + block_height: BlockHeight, params: &ConsensusParameters, ) -> Result, CheckError> { self.precompute(); @@ -133,7 +133,7 @@ pub mod script { }; use crate::checked_transaction::{NonRetryableFreeBalances, RetryableAmount}; use fuel_tx::{Cacheable, CheckError, ConsensusParameters, FormatValidityChecks, Script, TransactionFee}; - use fuel_types::Word; + use fuel_types::{BlockHeight, Word}; /// Metdata produced by checking [`fuel_tx::Script`]. #[derive(Debug, Clone, Eq, PartialEq, Hash)] @@ -143,7 +143,7 @@ pub mod script { /// See [`RetryableAmount`]. pub retryable_balance: RetryableAmount, /// The block height this tx was verified with - pub block_height: Word, + pub block_height: BlockHeight, /// The fees and gas usage pub fee: TransactionFee, /// If predicates have been checked, this is how much gas checking them used. @@ -156,7 +156,7 @@ pub mod script { fn into_checked_basic( mut self, - block_height: Word, + block_height: BlockHeight, params: &ConsensusParameters, ) -> Result, CheckError> { self.precompute(); diff --git a/fuel-vm/src/context.rs b/fuel-vm/src/context.rs index 7978753c22..a1ac86dfcc 100644 --- a/fuel-vm/src/context.rs +++ b/fuel-vm/src/context.rs @@ -3,6 +3,7 @@ use crate::predicate::RuntimePredicate; use fuel_asm::Word; +use fuel_types::BlockHeight; #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -16,12 +17,12 @@ pub enum Context { /// Current context is a script execution. Script { /// Block height of the context - block_height: u32, + block_height: BlockHeight, }, /// Current context is under a `CALL` scope Call { /// Block height of the context - block_height: u32, + block_height: BlockHeight, }, /// No transaction initialized/invalid context. NotInitialized, @@ -58,7 +59,7 @@ impl Context { } /// Return the block height from the context, if either script or call - pub const fn block_height(&self) -> Option { + pub const fn block_height(&self) -> Option { match self { Context::Script { block_height } | Context::Call { block_height } => Some(*block_height), _ => None, diff --git a/fuel-vm/src/interpreter/blockchain.rs b/fuel-vm/src/interpreter/blockchain.rs index f3caf79278..b9849b1630 100644 --- a/fuel-vm/src/interpreter/blockchain.rs +++ b/fuel-vm/src/interpreter/blockchain.rs @@ -21,7 +21,7 @@ use crate::{arith, consts::*}; use fuel_asm::PanicReason; use fuel_storage::{StorageInspect, StorageSize}; use fuel_tx::Receipt; -use fuel_types::bytes; +use fuel_types::{bytes, BlockHeight}; use fuel_types::{Address, AssetId, Bytes32, ContractId, RegisterId, Word}; use std::borrow::Borrow; @@ -491,7 +491,7 @@ pub(crate) fn block_hash( pub(crate) fn block_height(context: &Context, pc: RegMut, result: &mut Word) -> Result<(), RuntimeError> { context .block_height() - .map(|h| h as Word) + .map(|h| *h as Word) .map(|h| *result = h) .ok_or(PanicReason::TransactionValidity)?; @@ -654,17 +654,16 @@ pub(crate) fn state_write_word( pub(crate) fn timestamp( storage: &impl InterpreterStorage, - block_height: u32, + block_height: BlockHeight, pc: RegMut, result: &mut Word, b: Word, ) -> Result<(), RuntimeError> { - (b <= block_height as Word) + let b = u32::try_from(b).map_err(|_| PanicReason::ArithmeticOverflow)?.into(); + (b <= block_height) .then_some(()) .ok_or(PanicReason::TransactionValidity)?; - let b = u32::try_from(b).map_err(|_| PanicReason::ArithmeticOverflow)?; - *result = storage.timestamp(b).map_err(|e| e.into())?; inc_pc(pc) diff --git a/fuel-vm/src/interpreter/blockchain/code_tests.rs b/fuel-vm/src/interpreter/blockchain/code_tests.rs index b2cdece778..db8fe8d25d 100644 --- a/fuel-vm/src/interpreter/blockchain/code_tests.rs +++ b/fuel-vm/src/interpreter/blockchain/code_tests.rs @@ -6,7 +6,7 @@ use fuel_tx::Contract; #[test] fn test_load_contract() -> Result<(), RuntimeError> { - let mut storage = MemoryStorage::new(0, Default::default()); + let mut storage = MemoryStorage::new(Default::default(), Default::default()); let mut memory: Memory = vec![1u8; MEM_SIZE].try_into().unwrap(); let mut pc = 4; let hp = 2000; @@ -47,7 +47,7 @@ fn test_load_contract() -> Result<(), RuntimeError> { #[test] fn test_code_copy() -> Result<(), RuntimeError> { - let mut storage = MemoryStorage::new(0, Default::default()); + let mut storage = MemoryStorage::new(Default::default(), Default::default()); let mut memory: Memory = vec![1u8; MEM_SIZE].try_into().unwrap(); let mut pc = 4; @@ -76,7 +76,9 @@ fn test_code_copy() -> Result<(), RuntimeError> { ssp: 1000, hp: 2000, prev_hp: VM_MAX_RAM - 1, - context: Context::Call { block_height: 0 }, + context: Context::Call { + block_height: Default::default(), + }, }, }; input.code_copy(dest_mem_address, contract_id_mem_address, offset, num_bytes)?; diff --git a/fuel-vm/src/interpreter/blockchain/other_tests.rs b/fuel-vm/src/interpreter/blockchain/other_tests.rs index ccc8e0fffd..7b7d0b5b14 100644 --- a/fuel-vm/src/interpreter/blockchain/other_tests.rs +++ b/fuel-vm/src/interpreter/blockchain/other_tests.rs @@ -15,7 +15,7 @@ use test_case::test_case; #[test_case(false, 0, 100, 101 => Err(RuntimeError::Recoverable(PanicReason::NotEnoughBalance)); "Can't burn too much")] #[test_case(false, 0, None, 1 => Err(RuntimeError::Recoverable(PanicReason::NotEnoughBalance)); "Can't burn when no balance")] fn test_burn(external: bool, fp: Word, initialize: impl Into>, amount: Word) -> Result<(), RuntimeError> { - let mut storage = MemoryStorage::new(0, Default::default()); + let mut storage = MemoryStorage::new(Default::default(), Default::default()); let mut memory: Memory = vec![1u8; MEM_SIZE].try_into().unwrap(); memory[0..ContractId::LEN].copy_from_slice(&[3u8; ContractId::LEN][..]); let contract_id = ContractId::from([3u8; 32]); @@ -27,9 +27,13 @@ fn test_burn(external: bool, fp: Word, initialize: impl Into>, amou .unwrap(); } let context = if external { - Context::Script { block_height: 0 } + Context::Script { + block_height: Default::default(), + } } else { - Context::Call { block_height: 0 } + Context::Call { + block_height: Default::default(), + } }; let mut pc = 4; burn( @@ -61,7 +65,7 @@ fn test_burn(external: bool, fp: Word, initialize: impl Into>, amou #[test_case(true, 0, 100, 10 => Err(RuntimeError::Recoverable(PanicReason::ExpectedInternalContext)); "Can't mint from external context")] #[test_case(false, 0, 1, Word::MAX => Err(RuntimeError::Recoverable(PanicReason::ArithmeticOverflow)); "Can't mint too much")] fn test_mint(external: bool, fp: Word, initialize: impl Into>, amount: Word) -> Result<(), RuntimeError> { - let mut storage = MemoryStorage::new(0, Default::default()); + let mut storage = MemoryStorage::new(Default::default(), Default::default()); let mut memory: Memory = vec![1u8; MEM_SIZE].try_into().unwrap(); memory[0..ContractId::LEN].copy_from_slice(&[3u8; ContractId::LEN][..]); let contract_id = ContractId::from([3u8; 32]); @@ -73,9 +77,13 @@ fn test_mint(external: bool, fp: Word, initialize: impl Into>, amou .unwrap(); } let context = if external { - Context::Script { block_height: 0 } + Context::Script { + block_height: Default::default(), + } } else { - Context::Call { block_height: 0 } + Context::Call { + block_height: Default::default(), + } }; let mut pc = 4; mint( @@ -97,14 +105,16 @@ fn test_mint(external: bool, fp: Word, initialize: impl Into>, amou #[test] fn test_block_hash() { - let storage = MemoryStorage::new(0, Default::default()); + let storage = MemoryStorage::new(Default::default(), Default::default()); let mut memory: Memory = vec![1u8; MEM_SIZE].try_into().unwrap(); let owner = OwnershipRegisters { sp: 1000, ssp: 1, hp: 2000, prev_hp: 3000, - context: Context::Script { block_height: 0 }, + context: Context::Script { + block_height: Default::default(), + }, }; let mut pc = 4; block_hash(&storage, &mut memory, owner, RegMut::new(&mut pc), 20, 40).unwrap(); @@ -114,7 +124,9 @@ fn test_block_hash() { #[test] fn test_block_height() { - let context = Context::Script { block_height: 20 }; + let context = Context::Script { + block_height: 20.into(), + }; let mut pc = 4; let mut result = 0; block_height(&context, RegMut::new(&mut pc), &mut result).unwrap(); @@ -124,14 +136,16 @@ fn test_block_height() { #[test] fn test_coinbase() { - let storage = MemoryStorage::new(0, Default::default()); + let storage = MemoryStorage::new(Default::default(), Default::default()); let mut memory: Memory = vec![1u8; MEM_SIZE].try_into().unwrap(); let owner = OwnershipRegisters { sp: 1000, ssp: 1, hp: 2000, prev_hp: 3000, - context: Context::Script { block_height: 0 }, + context: Context::Script { + block_height: Default::default(), + }, }; let mut pc = 4; coinbase(&storage, &mut memory, owner, RegMut::new(&mut pc), 20).unwrap(); @@ -141,7 +155,7 @@ fn test_coinbase() { #[test] fn test_code_root() { - let mut storage = MemoryStorage::new(0, Default::default()); + let mut storage = MemoryStorage::new(Default::default(), Default::default()); let mut memory: Memory = vec![1u8; MEM_SIZE].try_into().unwrap(); memory[0..ContractId::LEN].copy_from_slice(&[3u8; ContractId::LEN][..]); let owner = OwnershipRegisters { @@ -149,7 +163,9 @@ fn test_code_root() { ssp: 1, hp: 2000, prev_hp: 3000, - context: Context::Script { block_height: 0 }, + context: Context::Script { + block_height: Default::default(), + }, }; let mut pc = 4; code_root(&storage, &mut memory, owner, RegMut::new(&mut pc), 20, 0).expect_err("Contract is not found"); @@ -167,7 +183,9 @@ fn test_code_root() { ssp: 1, hp: 2000, prev_hp: 3000, - context: Context::Script { block_height: 0 }, + context: Context::Script { + block_height: Default::default(), + }, }; code_root(&storage, &mut memory, owner, RegMut::new(&mut pc), 20, 0).unwrap(); assert_eq!(pc, 8); @@ -176,7 +194,7 @@ fn test_code_root() { #[test] fn test_code_size() { - let mut storage = MemoryStorage::new(0, Default::default()); + let mut storage = MemoryStorage::new(Default::default(), Default::default()); let mut memory: Memory = vec![1u8; MEM_SIZE].try_into().unwrap(); memory[0..ContractId::LEN].copy_from_slice(&[3u8; ContractId::LEN][..]); StorageAsMut::storage::(&mut storage) @@ -226,14 +244,14 @@ fn test_code_size() { #[test] fn test_timestamp() { - let storage = MemoryStorage::new(0, Default::default()); + let storage = MemoryStorage::new(Default::default(), Default::default()); let mut pc = 4; let mut result = 0; - timestamp(&storage, 0, RegMut::new(&mut pc), &mut result, 1) + timestamp(&storage, Default::default(), RegMut::new(&mut pc), &mut result, 1) .expect_err("Height is greater then current block height"); timestamp( &storage, - u32::MAX, + u32::MAX.into(), RegMut::new(&mut pc), &mut result, u32::MAX as Word + 1, @@ -241,9 +259,9 @@ fn test_timestamp() { .expect_err("Height doesn't fit into a u32"); assert_eq!(pc, 4); - timestamp(&storage, 0, RegMut::new(&mut pc), &mut result, 0).unwrap(); + timestamp(&storage, Default::default(), RegMut::new(&mut pc), &mut result, 0).unwrap(); assert_eq!(pc, 8); - timestamp(&storage, 20, RegMut::new(&mut pc), &mut result, 19).unwrap(); + timestamp(&storage, 20.into(), RegMut::new(&mut pc), &mut result, 19).unwrap(); assert_eq!(pc, 12); } diff --git a/fuel-vm/src/interpreter/blockchain/smo_tests.rs b/fuel-vm/src/interpreter/blockchain/smo_tests.rs index fa7f71d685..fdfc87cd54 100644 --- a/fuel-vm/src/interpreter/blockchain/smo_tests.rs +++ b/fuel-vm/src/interpreter/blockchain/smo_tests.rs @@ -199,7 +199,7 @@ fn test_smo( } let mut receipts = Default::default(); let mut tx = Create::default(); - let mut storage = MemoryStorage::new(0, Address::default()); + let mut storage = MemoryStorage::new(Default::default(), Address::default()); storage .merkle_contract_asset_id_balance_insert(&ContractId::default(), &asset, initial_balance) .unwrap(); diff --git a/fuel-vm/src/interpreter/blockchain/test.rs b/fuel-vm/src/interpreter/blockchain/test.rs index b9fb3d3d96..f52a1a36ec 100644 --- a/fuel-vm/src/interpreter/blockchain/test.rs +++ b/fuel-vm/src/interpreter/blockchain/test.rs @@ -46,7 +46,7 @@ fn test_state_read_word( insert: impl Into>, key: Word, ) -> Result<(Word, Word), RuntimeError> { - let mut storage = MemoryStorage::new(0, Default::default()); + let mut storage = MemoryStorage::new(Default::default(), Default::default()); let mut memory: Memory = vec![1u8; MEM_SIZE].try_into().unwrap(); memory[0..ContractId::LEN].copy_from_slice(&[3u8; ContractId::LEN][..]); memory[32..64].copy_from_slice(&[4u8; 32][..]); @@ -54,14 +54,20 @@ fn test_state_read_word( let mut result = 0; let mut got_result = 0; let context = if external { - Context::Script { block_height: 0 } + Context::Script { + block_height: Default::default(), + } } else { - Context::Call { block_height: 0 } + Context::Call { + block_height: Default::default(), + } }; if let Some(insert) = insert.into() { let fp = 0; - let context = Context::Call { block_height: 0 }; + let context = Context::Call { + block_height: Default::default(), + }; let input = StateWordCtx { storage: &mut storage, memory: &mut memory, @@ -96,21 +102,27 @@ fn test_state_read_word( #[test_case(true, 0, false, Word::MAX => Err(RuntimeError::Recoverable(PanicReason::MemoryOverflow)); "Overflowing key")] #[test_case(true, 0, false, VM_MAX_RAM => Err(RuntimeError::Recoverable(PanicReason::MemoryOverflow)); "Overflowing key ram")] fn test_state_write_word(external: bool, fp: Word, insert: bool, key: Word) -> Result { - let mut storage = MemoryStorage::new(0, Default::default()); + let mut storage = MemoryStorage::new(Default::default(), Default::default()); let mut memory: Memory = vec![1u8; MEM_SIZE].try_into().unwrap(); memory[0..ContractId::LEN].copy_from_slice(&[3u8; ContractId::LEN][..]); memory[32..64].copy_from_slice(&[4u8; 32][..]); let mut pc = 4; let mut result = 0; let context = if external { - Context::Script { block_height: 0 } + Context::Script { + block_height: Default::default(), + } } else { - Context::Call { block_height: 0 } + Context::Call { + block_height: Default::default(), + } }; if insert { let fp = 0; - let context = Context::Call { block_height: 0 }; + let context = Context::Call { + block_height: Default::default(), + }; let input = StateWordCtx { storage: &mut storage, memory: &mut memory, diff --git a/fuel-vm/src/interpreter/blockchain/test/scwq.rs b/fuel-vm/src/interpreter/blockchain/test/scwq.rs index f0a40bba64..d28af8e990 100644 --- a/fuel-vm/src/interpreter/blockchain/test/scwq.rs +++ b/fuel-vm/src/interpreter/blockchain/test/scwq.rs @@ -67,7 +67,7 @@ fn test_state_clear_qword(input: SCWQInput) -> (Vec<([u8; 32], [u8; 32])>, bool) storage_slots, memory, } = input; - let mut storage = MemoryStorage::new(0, Default::default()); + let mut storage = MemoryStorage::new(Default::default(), Default::default()); for (k, v) in storage_slots { storage diff --git a/fuel-vm/src/interpreter/blockchain/test/srwq.rs b/fuel-vm/src/interpreter/blockchain/test/srwq.rs index 7155cedf0e..046e700ee1 100644 --- a/fuel-vm/src/interpreter/blockchain/test/srwq.rs +++ b/fuel-vm/src/interpreter/blockchain/test/srwq.rs @@ -23,7 +23,9 @@ impl StateReadQWord { ssp: 0, hp: u64::MAX / 2 + 1, prev_hp: u64::MAX, - context: crate::context::Context::Call { block_height: 0 }, + context: crate::context::Context::Call { + block_height: Default::default(), + }, }; Self::new(destination_memory_address, origin_key_memory_address, num_slots, r) } @@ -91,7 +93,7 @@ fn test_state_read_qword(input: SRWQInput) -> (Memory, bool) { storage_slots, mut memory, } = input; - let mut storage = MemoryStorage::new(0, Default::default()); + let mut storage = MemoryStorage::new(Default::default(), Default::default()); for (k, v) in storage_slots { storage .storage::() @@ -113,42 +115,42 @@ fn test_state_read_qword(input: SRWQInput) -> (Memory, bool) { } #[test_case( - 0, 0, 1, OwnershipRegisters::test(0..100, 100..200, Context::Call{ block_height: 0}) + 0, 0, 1, OwnershipRegisters::test(0..100, 100..200, Context::Call{ block_height: Default::default()}) => matches Ok(()) ; "Ownership check passes when destination is within allocated stack" )] #[test_case( - 2, 0, 1, OwnershipRegisters::test(0..1, 3..4, Context::Call{ block_height: 0}) + 2, 0, 1, OwnershipRegisters::test(0..1, 3..4, Context::Call{ block_height: Default::default()}) => matches Err(_) ; "Ownership check fails when destination is in-between stack and heap" )] #[test_case( - 2, 0, 1, OwnershipRegisters::test(0..4, 5..6, Context::Call {block_height: 0}) + 2, 0, 1, OwnershipRegisters::test(0..4, 5..6, Context::Call {block_height: Default::default()}) => matches Err(_) ; "Ownership check fails when stack is too small" )] #[test_case( - 3, 0, 1, OwnershipRegisters::test(0..1, 2..35, Context::Call{ block_height: 0}) + 3, 0, 1, OwnershipRegisters::test(0..1, 2..35, Context::Call{ block_height: Default::default()}) => matches Ok(_) ; "Ownership check passes when heap is large enough" )] #[test_case( - VM_MAX_RAM, 0, 1, OwnershipRegisters::test(0..1, 3..u64::MAX, Context::Call{ block_height: 0}) + VM_MAX_RAM, 0, 1, OwnershipRegisters::test(0..1, 3..u64::MAX, Context::Call{ block_height: Default::default()}) => matches Err(_) ; "Ownership check fails when destination range exceeds VM MAX" )] #[test_case( - 4, VM_MAX_RAM, 1, OwnershipRegisters::test(0..1, 3..u64::MAX, Context::Call{ block_height: 0}) + 4, VM_MAX_RAM, 1, OwnershipRegisters::test(0..1, 3..u64::MAX, Context::Call{ block_height: Default::default()}) => matches Err(_) ; "Fail when start key memory range exceeds VM_MAX_RAM" )] #[test_case( - 4, u64::MAX, 1, OwnershipRegisters::test(0..1, 3..u64::MAX, Context::Call{ block_height: 0}) + 4, u64::MAX, 1, OwnershipRegisters::test(0..1, 3..u64::MAX, Context::Call{ block_height: Default::default()}) => matches Err(_) ; "Fail when start key memory range exceeds u64::MAX" )] #[test_case( - 4, 0, 1, OwnershipRegisters::test(0..1, 3..u64::MAX, Context::Script { block_height: 0}) + 4, 0, 1, OwnershipRegisters::test(0..1, 3..u64::MAX, Context::Script { block_height: Default::default()}) => matches Err(_) ; "Fail when context is not inside of a call" )] diff --git a/fuel-vm/src/interpreter/blockchain/test/swwq.rs b/fuel-vm/src/interpreter/blockchain/test/swwq.rs index fec640d644..1545a68917 100644 --- a/fuel-vm/src/interpreter/blockchain/test/swwq.rs +++ b/fuel-vm/src/interpreter/blockchain/test/swwq.rs @@ -91,7 +91,7 @@ fn test_state_write_qword(input: SWWQInput) -> (Vec<([u8; 32], [u8; 32])>, bool) storage_slots, memory, } = input; - let mut storage = MemoryStorage::new(0, Default::default()); + let mut storage = MemoryStorage::new(Default::default(), Default::default()); for (k, v) in storage_slots { storage diff --git a/fuel-vm/src/interpreter/contract/tests.rs b/fuel-vm/src/interpreter/contract/tests.rs index c30f845fda..d7842b2842 100644 --- a/fuel-vm/src/interpreter/contract/tests.rs +++ b/fuel-vm/src/interpreter/contract/tests.rs @@ -14,7 +14,7 @@ fn test_contract_balance(b: Word, c: Word) -> Result<(), RuntimeError> { memory[b as usize..(b as usize + AssetId::LEN)].copy_from_slice(&[2u8; AssetId::LEN][..]); memory[c as usize..(c as usize + ContractId::LEN)].copy_from_slice(&[3u8; ContractId::LEN][..]); let contract_id = ContractId::from([3u8; 32]); - let mut storage = MemoryStorage::new(0, Default::default()); + let mut storage = MemoryStorage::new(Default::default(), Default::default()); storage .merkle_contract_asset_id_balance_insert(&contract_id, &AssetId::from([2u8; 32]), 33) .unwrap(); @@ -44,16 +44,20 @@ fn test_transfer(external: bool, a: Word, b: Word, c: Word) -> Result<(), Runtim memory[c as usize..(c as usize + AssetId::LEN)].copy_from_slice(&[2u8; AssetId::LEN][..]); let contract_id = ContractId::from([3u8; 32]); let asset_id = AssetId::from([2u8; 32]); - let mut storage = MemoryStorage::new(0, Default::default()); + let mut storage = MemoryStorage::new(Default::default(), Default::default()); storage .merkle_contract_asset_id_balance_insert(&contract_id, &asset_id, 60) .unwrap(); let mut pc = 4; let context = if external { - Context::Script { block_height: 0 } + Context::Script { + block_height: Default::default(), + } } else { - Context::Call { block_height: 0 } + Context::Call { + block_height: Default::default(), + } }; let mut balances = RuntimeBalances::try_from_iter([(AssetId::from([2u8; 32]), 50)]).unwrap(); @@ -104,16 +108,20 @@ fn test_transfer_output(external: bool, a: Word, b: Word, c: Word, d: Word) -> R memory[d as usize..(d as usize + AssetId::LEN)].copy_from_slice(&[2u8; AssetId::LEN][..]); let contract_id = ContractId::from([3u8; 32]); let asset_id = AssetId::from([2u8; 32]); - let mut storage = MemoryStorage::new(0, Default::default()); + let mut storage = MemoryStorage::new(Default::default(), Default::default()); storage .merkle_contract_asset_id_balance_insert(&contract_id, &asset_id, 60) .unwrap(); let mut pc = 4; let context = if external { - Context::Script { block_height: 0 } + Context::Script { + block_height: Default::default(), + } } else { - Context::Call { block_height: 0 } + Context::Call { + block_height: Default::default(), + } }; let mut balances = RuntimeBalances::try_from_iter([(AssetId::from([2u8; 32]), 50)]).unwrap(); @@ -171,7 +179,7 @@ fn test_transfer_output(external: bool, a: Word, b: Word, c: Word, d: Word) -> R fn test_balance_increase(initial: impl Into>, amount: Word) -> Result<(), RuntimeError> { let contract_id = ContractId::from([3u8; 32]); let asset_id = AssetId::from([2u8; 32]); - let mut storage = MemoryStorage::new(0, Default::default()); + let mut storage = MemoryStorage::new(Default::default(), Default::default()); let initial = initial.into(); if let Some(initial) = initial { storage @@ -203,7 +211,7 @@ fn test_balance_increase(initial: impl Into>, amount: Word) -> Resu fn test_balance_decrease(initial: impl Into>, amount: Word) -> Result<(), RuntimeError> { let contract_id = ContractId::from([3u8; 32]); let asset_id = AssetId::from([2u8; 32]); - let mut storage = MemoryStorage::new(0, Default::default()); + let mut storage = MemoryStorage::new(Default::default(), Default::default()); let initial = initial.into(); if let Some(initial) = initial { storage diff --git a/fuel-vm/src/interpreter/crypto/tests.rs b/fuel-vm/src/interpreter/crypto/tests.rs index 06368c5659..820160fe2b 100644 --- a/fuel-vm/src/interpreter/crypto/tests.rs +++ b/fuel-vm/src/interpreter/crypto/tests.rs @@ -13,7 +13,9 @@ fn test_ecrecover() -> Result<(), RuntimeError> { ssp: 1000, hp: 2000, prev_hp: VM_MAX_RAM - 1, - context: Context::Call { block_height: 0 }, + context: Context::Call { + block_height: Default::default(), + }, }; let mut err = 0; let mut pc = 4; @@ -56,7 +58,9 @@ fn test_keccak256() -> Result<(), RuntimeError> { ssp: 1000, hp: 2000, prev_hp: VM_MAX_RAM - 1, - context: Context::Call { block_height: 0 }, + context: Context::Call { + block_height: Default::default(), + }, }; let mut pc = 4; let hash = 2100; @@ -76,7 +80,9 @@ fn test_sha256() -> Result<(), RuntimeError> { ssp: 1000, hp: 2000, prev_hp: VM_MAX_RAM - 1, - context: Context::Call { block_height: 0 }, + context: Context::Call { + block_height: Default::default(), + }, }; let mut pc = 4; let hash = 2100; diff --git a/fuel-vm/src/interpreter/debug.rs b/fuel-vm/src/interpreter/debug.rs index 1bdf31d518..b781cd8f6a 100644 --- a/fuel-vm/src/interpreter/debug.rs +++ b/fuel-vm/src/interpreter/debug.rs @@ -52,8 +52,8 @@ fn breakpoint_script() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); let script = [ @@ -117,8 +117,8 @@ fn single_stepping() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); // Repeats the middle two instructions five times diff --git a/fuel-vm/src/interpreter/diff/storage.rs b/fuel-vm/src/interpreter/diff/storage.rs index 1242f4847c..31979b53ea 100644 --- a/fuel-vm/src/interpreter/diff/storage.rs +++ b/fuel-vm/src/interpreter/diff/storage.rs @@ -3,8 +3,8 @@ use std::fmt::Debug; use fuel_storage::StorageRead; use fuel_storage::StorageSize; -use fuel_types::Bytes32; use fuel_types::ContractId; +use fuel_types::{BlockHeight, Bytes32}; use crate::storage::ContractsAssetsStorage; use crate::storage::{ContractsAssetKey, ContractsStateKey, InterpreterStorage}; @@ -326,11 +326,11 @@ where { type DataError = ::DataError; - fn block_height(&self) -> Result { + fn block_height(&self) -> Result { self.0.block_height() } - fn timestamp(&self, height: u32) -> Result { + fn timestamp(&self, height: BlockHeight) -> Result { self.0.timestamp(height) } diff --git a/fuel-vm/src/interpreter/executors/instruction/tests/reserved_registers.rs b/fuel-vm/src/interpreter/executors/instruction/tests/reserved_registers.rs index f424ca582e..b8420461b7 100644 --- a/fuel-vm/src/interpreter/executors/instruction/tests/reserved_registers.rs +++ b/fuel-vm/src/interpreter/executors/instruction/tests/reserved_registers.rs @@ -26,8 +26,17 @@ fn cant_write_to_reserved_registers(raw_random_instruction: u32) -> TestResult { let params = ConsensusParameters::default(); let script = op::ret(0x10).to_bytes().to_vec(); - let block_height = 0; - let tx = Transaction::script(0, params.max_gas_per_tx, 0, script, vec![], vec![], vec![], vec![]); + let block_height = Default::default(); + let tx = Transaction::script( + 0, + params.max_gas_per_tx, + Default::default(), + script, + vec![], + vec![], + vec![], + vec![], + ); let tx = tx .into_checked(block_height, ¶ms, vm.gas_costs()) .expect("failed to check tx"); diff --git a/fuel-vm/src/interpreter/flow/ret_tests.rs b/fuel-vm/src/interpreter/flow/ret_tests.rs index b70c9a68bd..aa9aeabd98 100644 --- a/fuel-vm/src/interpreter/flow/ret_tests.rs +++ b/fuel-vm/src/interpreter/flow/ret_tests.rs @@ -24,7 +24,9 @@ fn test_return() { expected[RegId::RET] = 101; expected[RegId::RETL] = 102; expected[RegId::PC] += 4; - let mut context = Context::Call { block_height: 0 }; + let mut context = Context::Call { + block_height: Default::default(), + }; let mut receipts = Default::default(); let mut memory: Memory = vec![0u8; MEM_SIZE].try_into().unwrap(); diff --git a/fuel-vm/src/interpreter/flow/tests.rs b/fuel-vm/src/interpreter/flow/tests.rs index 87eed2964c..0a31330d14 100644 --- a/fuel-vm/src/interpreter/flow/tests.rs +++ b/fuel-vm/src/interpreter/flow/tests.rs @@ -30,7 +30,9 @@ impl Default for Input { ggas: 40, ..Default::default() }, - context: Context::Script { block_height: 0 }, + context: Context::Script { + block_height: Default::default(), + }, balance: Default::default(), input_contracts: vec![Default::default()], storage_balance: Default::default(), @@ -119,7 +121,9 @@ impl Default for Output { 700, )] .into(), - context: Context::Call { block_height: 0 }, + context: Context::Call { + block_height: Default::default(), + }, script: None, } } @@ -142,7 +146,7 @@ fn mem(set: &[(usize, Vec)]) -> Memory { amount_of_gas_to_forward: 0, }, reg: RegInput{hp: 1000, sp: 100, ssp: 100, fp: 0, pc: 0, is: 0, bal: 0, cgas: 21, ggas: 21 }, - context: Context::Script{ block_height: 0u32 }, + context: Context::Script{ block_height: Default::default() }, ..Default::default() } => using check_output(Ok(Output{ reg: RegInput{hp: 1000, sp: 712, ssp: 712, fp: 100, pc: 700, is: 700, bal: 0, cgas: 0, ggas: 10 }, @@ -158,7 +162,7 @@ fn mem(set: &[(usize, Vec)]) -> Memory { amount_of_gas_to_forward: 30, }, reg: RegInput{hp: 1000, sp: 200, ssp: 200, fp: 0, pc: 0, is: 0, bal: 0, cgas: 201, ggas: 201 }, - context: Context::Script{ block_height: 0u32 }, + context: Context::Script{ block_height: Default::default() }, input_contracts: vec![ContractId::from([1u8; 32])], memory: mem(&[(2000, vec![2; 32]), (2032, Call::new(ContractId::from([1u8; 32]), 4, 5).into())]), storage_contract: vec![(ContractId::from([1u8; 32]), vec![0u8; 100])], @@ -189,7 +193,7 @@ fn mem(set: &[(usize, Vec)]) -> Memory { amount_of_gas_to_forward: 0, }, reg: RegInput{hp: 1000, sp: 100, ssp: 100, fp: 0, pc: 0, is: 0, bal: 0, cgas: 11, ggas: 11 }, - context: Context::Script{ block_height: 0u32 }, + context: Context::Script{ block_height: Default::default() }, balance: [(AssetId::default(), 30)].into_iter().collect(), ..Default::default() } => using check_output(Ok(Output{ @@ -208,7 +212,7 @@ fn mem(set: &[(usize, Vec)]) -> Memory { amount_of_gas_to_forward: 10, }, reg: RegInput{hp: 1000, sp: 100, ssp: 100, fp: 0, pc: 0, is: 0, bal: 0, cgas: 40, ggas: 80 }, - context: Context::Script{ block_height: 0u32 }, + context: Context::Script{ block_height: Default::default() }, balance: [(AssetId::default(), 30)].into_iter().collect(), ..Default::default() } => using check_output(Ok(Output{ @@ -227,7 +231,7 @@ fn mem(set: &[(usize, Vec)]) -> Memory { amount_of_gas_to_forward: 0, }, reg: RegInput{hp: 1000, sp: 100, ssp: 100, fp: 0, pc: 0, is: 0, bal: 0, cgas: 11, ggas: 11 }, - context: Context::Call{ block_height: 0u32 }, + context: Context::Call{ block_height: Default::default() }, storage_balance: [(AssetId::default(), 30)].into_iter().collect(), ..Default::default() } => using check_output(Ok(Output{ @@ -246,7 +250,7 @@ fn mem(set: &[(usize, Vec)]) -> Memory { amount_of_gas_to_forward: 0, }, reg: RegInput{hp: 1000, sp: 0, ssp: 0, fp: 0, pc: 0, is: 0, bal: 0, cgas: 11, ggas: 11 }, - context: Context::Script{ block_height: 0u32 }, + context: Context::Script{ block_height: Default::default() }, ..Default::default() } => using check_output(Err(RuntimeError::Recoverable(PanicReason::NotEnoughBalance))); "Tries to forward more coins than the contract has" )] @@ -259,7 +263,7 @@ fn mem(set: &[(usize, Vec)]) -> Memory { amount_of_gas_to_forward: 0, }, reg: RegInput{hp: 1000, sp: 0, ssp: 0, fp: 0, pc: 0, is: 0, bal: 0, cgas: 11, ggas: 11 }, - context: Context::Script{ block_height: 0u32 }, + context: Context::Script{ block_height: Default::default() }, ..Default::default() } => using check_output(Err(RuntimeError::Recoverable(PanicReason::MemoryOverflow))); "call_params_mem_address overflow" )] @@ -272,7 +276,7 @@ fn mem(set: &[(usize, Vec)]) -> Memory { amount_of_gas_to_forward: 0, }, reg: RegInput{hp: 1000, sp: 0, ssp: 0, fp: 0, pc: 0, is: 0, bal: 0, cgas: 11, ggas: 11 }, - context: Context::Script{ block_height: 0u32 }, + context: Context::Script{ block_height: Default::default() }, ..Default::default() } => using check_output(Err(RuntimeError::Recoverable(PanicReason::MemoryOverflow))); "asset_id_mem_address overflow" )] @@ -285,7 +289,7 @@ fn mem(set: &[(usize, Vec)]) -> Memory { amount_of_gas_to_forward: 0, }, reg: RegInput{hp: 1000, sp: 0, ssp: 0, fp: 0, pc: 0, is: 0, bal: 0, cgas: 11, ggas: 11 }, - context: Context::Call{ block_height: 0u32 }, + context: Context::Call{ block_height: Default::default() }, balance: [(AssetId::default(), 30)].into_iter().collect(), ..Default::default() } => using check_output(Err(RuntimeError::Recoverable(PanicReason::NotEnoughBalance))); "Transfer too many coins internally" @@ -316,7 +320,7 @@ fn test_prepare_call(input: Input) -> Result { registers.system_registers.ggas = RegMut::new(&mut reg.ggas); let memory = PrepareCallMemory::try_from((mem.as_mut(), ¶ms))?; let mut runtime_balances = RuntimeBalances::try_from_iter(balance).expect("Balance should be valid"); - let mut storage = MemoryStorage::new(0, Default::default()); + let mut storage = MemoryStorage::new(Default::default(), Default::default()); for (id, code) in storage_contract { StorageAsMut::storage::(&mut storage) .write(&id, code) @@ -395,7 +399,7 @@ fn check_output(expected: Result) -> impl FnOnce(Result Result { let frame_bytes = call_frame.to_bytes(); - let mut storage = MemoryStorage::new(0, Default::default()); + let mut storage = MemoryStorage::new(Default::default(), Default::default()); let code = vec![6u8; call_frame.code_size() as usize]; StorageAsMut::storage::(&mut storage) .insert(call_frame.to(), &code) diff --git a/fuel-vm/src/interpreter/internal.rs b/fuel-vm/src/interpreter/internal.rs index 504fb19a82..72df285c3a 100644 --- a/fuel-vm/src/interpreter/internal.rs +++ b/fuel-vm/src/interpreter/internal.rs @@ -11,7 +11,7 @@ use fuel_tx::field::{Outputs, ReceiptsRoot}; use fuel_tx::Script; use fuel_tx::{Output, Receipt}; use fuel_types::bytes::SizedBytes; -use fuel_types::{AssetId, Bytes32, ContractId, Word}; +use fuel_types::{AssetId, BlockHeight, Bytes32, ContractId, Word}; use core::mem; @@ -169,7 +169,7 @@ impl Interpreter { self.params().tx_offset() } - pub(crate) fn get_block_height(&self) -> Result { + pub(crate) fn get_block_height(&self) -> Result { self.context().block_height().ok_or(PanicReason::TransactionValidity) } } diff --git a/fuel-vm/src/interpreter/internal/tests.rs b/fuel-vm/src/interpreter/internal/tests.rs index 9f36e9d826..f0733fbac0 100644 --- a/fuel-vm/src/interpreter/internal/tests.rs +++ b/fuel-vm/src/interpreter/internal/tests.rs @@ -18,8 +18,8 @@ fn external_balance() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let script = op::ret(0x01).to_bytes().to_vec(); let balances = vec![(rng.gen(), 100), (rng.gen(), 500)]; @@ -35,7 +35,7 @@ fn external_balance() { .gas_limit(gas_limit) .gas_limit(100) .maturity(maturity) - .finalize_checked(height as Word, &Default::default(), &Default::default()); + .finalize_checked(height, &Default::default(), &Default::default()); vm.init_script(tx).expect("Failed to init VM!"); @@ -56,8 +56,8 @@ fn variable_output_updates_in_memory() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let asset_id_to_update: AssetId = rng.gen(); let amount_to_set: Word = 100; let owner: Address = rng.gen(); diff --git a/fuel-vm/src/interpreter/log/tests.rs b/fuel-vm/src/interpreter/log/tests.rs index a3647f701d..70c16124af 100644 --- a/fuel-vm/src/interpreter/log/tests.rs +++ b/fuel-vm/src/interpreter/log/tests.rs @@ -5,7 +5,9 @@ use super::*; #[test] fn test_log() -> Result<(), RuntimeError> { let mut memory: Memory = vec![1u8; MEM_SIZE].try_into().unwrap(); - let context = Context::Script { block_height: 0 }; + let context = Context::Script { + block_height: Default::default(), + }; let mut receipts = Default::default(); let mut script = Some(Script::default()); diff --git a/fuel-vm/src/interpreter/memory/allocation_tests.rs b/fuel-vm/src/interpreter/memory/allocation_tests.rs index 5a9b502dd8..64c7afb017 100644 --- a/fuel-vm/src/interpreter/memory/allocation_tests.rs +++ b/fuel-vm/src/interpreter/memory/allocation_tests.rs @@ -22,7 +22,9 @@ fn test_memclear(has_ownership: bool, a: Word, b: Word) -> Result<(), RuntimeErr ssp: 0, hp: 0, prev_hp: 0, - context: Context::Script { block_height: 0 }, + context: Context::Script { + block_height: Default::default(), + }, }; if has_ownership { owner.ssp = a - 1; @@ -53,7 +55,9 @@ fn test_memcopy(has_ownership: bool, a: Word, b: Word, c: Word) -> Result<(), Ru ssp: 0, hp: 0, prev_hp: 0, - context: Context::Script { block_height: 0 }, + context: Context::Script { + block_height: Default::default(), + }, }; if has_ownership { owner.ssp = b - 1; @@ -152,7 +156,9 @@ fn test_store_byte(has_ownership: bool, a: Word, b: Word, c: Word) -> Result<(), ssp: 0, hp: 0, prev_hp: 0, - context: Context::Script { block_height: 0 }, + context: Context::Script { + block_height: Default::default(), + }, }; if has_ownership { owner.ssp = b - 1; @@ -176,7 +182,9 @@ fn test_store_word(has_ownership: bool, a: Word, b: Word, c: Word) -> Result<(), ssp: 0, hp: 0, prev_hp: 0, - context: Context::Script { block_height: 0 }, + context: Context::Script { + block_height: Default::default(), + }, }; if has_ownership { owner.ssp = b - 1; diff --git a/fuel-vm/src/interpreter/memory/tests.rs b/fuel-vm/src/interpreter/memory/tests.rs index d88337fc17..048197835a 100644 --- a/fuel-vm/src/interpreter/memory/tests.rs +++ b/fuel-vm/src/interpreter/memory/tests.rs @@ -14,7 +14,7 @@ fn memcopy() { let tx = Transaction::script( 0, params.max_gas_per_tx, - 0, + Default::default(), op::ret(0x10).to_bytes().to_vec(), vec![], vec![], @@ -115,47 +115,47 @@ fn stack_alloc_ownership() { } #[test_case( - OwnershipRegisters::test(0..0, 0..0, Context::Call{ block_height: 0}), 0..0 + OwnershipRegisters::test(0..0, 0..0, Context::Call{ block_height: Default::default()}), 0..0 => false ; "empty mem range" )] #[test_case( - OwnershipRegisters::test(0..0, 0..0, Context::Script{ block_height: 0}), 0..0 + OwnershipRegisters::test(0..0, 0..0, Context::Script{ block_height: Default::default()}), 0..0 => false ; "empty mem range (external)" )] #[test_case( - OwnershipRegisters::test(0..0, 0..0, Context::Call{ block_height: 0}), 0..1 + OwnershipRegisters::test(0..0, 0..0, Context::Call{ block_height: Default::default()}), 0..1 => false ; "empty stack and heap" )] #[test_case( - OwnershipRegisters::test(0..0, VM_MAX_RAM..VM_MAX_RAM, Context::Script{ block_height: 0 }), 0..1 + OwnershipRegisters::test(0..0, VM_MAX_RAM..VM_MAX_RAM, Context::Script{ block_height: Default::default() }), 0..1 => false ; "empty stack and heap (external)" )] #[test_case( - OwnershipRegisters::test(0..1, 0..0, Context::Call{ block_height: 0}), 0..1 + OwnershipRegisters::test(0..1, 0..0, Context::Call{ block_height: Default::default()}), 0..1 => true ; "in range for stack" )] #[test_case( - OwnershipRegisters::test(0..1, 0..0, Context::Call{ block_height: 0}), 0..2 + OwnershipRegisters::test(0..1, 0..0, Context::Call{ block_height: Default::default()}), 0..2 => false; "above stack range" )] #[test_case( - OwnershipRegisters::test(0..0, 0..2, Context::Call{ block_height: 0}), 1..2 + OwnershipRegisters::test(0..0, 0..2, Context::Call{ block_height: Default::default()}), 1..2 => true ; "in range for heap" )] #[test_case( - OwnershipRegisters::test(0..2, 1..2, Context::Call{ block_height: 0}), 0..2 + OwnershipRegisters::test(0..2, 1..2, Context::Call{ block_height: Default::default()}), 0..2 => true ; "crosses stack and heap" )] #[test_case( - OwnershipRegisters::test(0..0, 0..0, Context::Script{ block_height: 0}), 1..2 + OwnershipRegisters::test(0..0, 0..0, Context::Script{ block_height: Default::default()}), 1..2 => true ; "in heap range (external)" )] #[test_case( - OwnershipRegisters::test(0..19, 31..100, Context::Script{ block_height: 0}), 20..30 + OwnershipRegisters::test(0..19, 31..100, Context::Script{ block_height: Default::default()}), 20..30 => false; "between ranges (external)" )] #[test_case( - OwnershipRegisters::test(0..19, 31..100, Context::Script{ block_height: 0 }), 0..1 + OwnershipRegisters::test(0..19, 31..100, Context::Script{ block_height: Default::default() }), 0..1 => true; "in stack range (external)" )] fn test_ownership(reg: OwnershipRegisters, range: Range) -> bool { @@ -170,47 +170,47 @@ fn set_index(index: usize, val: u8, mut array: [u8; 100]) -> [u8; 100] { #[test_case( 1, &[], - OwnershipRegisters::test(0..1, 100..100, Context::Script{ block_height: 0}) + OwnershipRegisters::test(0..1, 100..100, Context::Script{ block_height: Default::default()}) => (false, [0u8; 100]); "External errors when write is empty" )] #[test_case( 1, &[], - OwnershipRegisters::test(0..1, 100..100, Context::Call{ block_height: 0}) + OwnershipRegisters::test(0..1, 100..100, Context::Call{ block_height: Default::default()}) => (false, [0u8; 100]); "Internal errors when write is empty" )] #[test_case( 1, &[2], - OwnershipRegisters::test(0..2, 100..100, Context::Script{ block_height: 0}) + OwnershipRegisters::test(0..2, 100..100, Context::Script{ block_height: Default::default()}) => (true, set_index(1, 2, [0u8; 100])); "External writes to stack" )] #[test_case( 98, &[2], - OwnershipRegisters::test(0..2, 97..100, Context::Script{ block_height: 0}) + OwnershipRegisters::test(0..2, 97..100, Context::Script{ block_height: Default::default()}) => (true, set_index(98, 2, [0u8; 100])); "External writes to heap" )] #[test_case( 1, &[2], - OwnershipRegisters::test(0..2, 100..100, Context::Call { block_height: 0}) + OwnershipRegisters::test(0..2, 100..100, Context::Call { block_height: Default::default()}) => (true, set_index(1, 2, [0u8; 100])); "Internal writes to stack" )] #[test_case( 98, &[2], - OwnershipRegisters::test(0..2, 97..100, Context::Call { block_height: 0}) + OwnershipRegisters::test(0..2, 97..100, Context::Call { block_height: Default::default()}) => (true, set_index(98, 2, [0u8; 100])); "Internal writes to heap" )] #[test_case( 1, &[2; 50], - OwnershipRegisters::test(0..40, 100..100, Context::Script{ block_height: 0}) + OwnershipRegisters::test(0..40, 100..100, Context::Script{ block_height: Default::default()}) => (false, [0u8; 100]); "External too large for stack" )] #[test_case( 1, &[2; 50], - OwnershipRegisters::test(0..40, 100..100, Context::Call{ block_height: 0}) + OwnershipRegisters::test(0..40, 100..100, Context::Call{ block_height: Default::default()}) => (false, [0u8; 100]); "Internal too large for stack" )] #[test_case( 61, &[2; 50], - OwnershipRegisters::test(0..0, 60..100, Context::Call{ block_height: 0}) + OwnershipRegisters::test(0..0, 60..100, Context::Call{ block_height: Default::default()}) => (false, [0u8; 100]); "Internal too large for heap" )] fn test_mem_write(addr: usize, data: &[u8], registers: OwnershipRegisters) -> (bool, [u8; 100]) { @@ -222,47 +222,47 @@ fn test_mem_write(addr: usize, data: &[u8], registers: OwnershipRegisters) -> (b #[test_case( 1, 0, - OwnershipRegisters::test(0..1, 100..100, Context::Script{ block_height: 0}) + OwnershipRegisters::test(0..1, 100..100, Context::Script{ block_height: Default::default()}) => (false, [1u8; 100]); "External errors when write is empty" )] #[test_case( 1, 0, - OwnershipRegisters::test(0..1, 100..100, Context::Call{ block_height: 0}) + OwnershipRegisters::test(0..1, 100..100, Context::Call{ block_height: Default::default()}) => (false, [1u8; 100]); "Internal errors when write is empty" )] #[test_case( 1, 1, - OwnershipRegisters::test(0..2, 100..100, Context::Script{ block_height: 0}) + OwnershipRegisters::test(0..2, 100..100, Context::Script{ block_height: Default::default()}) => (true, set_index(1, 0, [1u8; 100])); "External writes to stack" )] #[test_case( 98, 1, - OwnershipRegisters::test(0..2, 97..100, Context::Script{ block_height: 0}) + OwnershipRegisters::test(0..2, 97..100, Context::Script{ block_height: Default::default()}) => (true, set_index(98, 0, [1u8; 100])); "External writes to heap" )] #[test_case( 1, 1, - OwnershipRegisters::test(0..2, 100..100, Context::Call { block_height: 0}) + OwnershipRegisters::test(0..2, 100..100, Context::Call { block_height: Default::default()}) => (true, set_index(1, 0, [1u8; 100])); "Internal writes to stack" )] #[test_case( 98, 1, - OwnershipRegisters::test(0..2, 97..100, Context::Call { block_height: 0}) + OwnershipRegisters::test(0..2, 97..100, Context::Call { block_height: Default::default()}) => (true, set_index(98, 0, [1u8; 100])); "Internal writes to heap" )] #[test_case( 1, 50, - OwnershipRegisters::test(0..40, 100..100, Context::Script{ block_height: 0}) + OwnershipRegisters::test(0..40, 100..100, Context::Script{ block_height: Default::default()}) => (false, [1u8; 100]); "External too large for stack" )] #[test_case( 1, 50, - OwnershipRegisters::test(0..40, 100..100, Context::Call{ block_height: 0}) + OwnershipRegisters::test(0..40, 100..100, Context::Call{ block_height: Default::default()}) => (false, [1u8; 100]); "Internal too large for stack" )] #[test_case( 61, 50, - OwnershipRegisters::test(0..0, 60..100, Context::Call{ block_height: 0}) + OwnershipRegisters::test(0..0, 60..100, Context::Call{ block_height: Default::default()}) => (false, [1u8; 100]); "Internal too large for heap" )] fn test_try_zeroize(addr: usize, len: usize, registers: OwnershipRegisters) -> (bool, [u8; 100]) { diff --git a/fuel-vm/src/interpreter/metadata.rs b/fuel-vm/src/interpreter/metadata.rs index 5ce529048f..03c240025a 100644 --- a/fuel-vm/src/interpreter/metadata.rs +++ b/fuel-vm/src/interpreter/metadata.rs @@ -108,7 +108,7 @@ impl GTFInput<'_, Tx> { // General GTFArgs::ScriptGasPrice | GTFArgs::CreateGasPrice => tx.price(), GTFArgs::ScriptGasLimit | GTFArgs::CreateGasLimit => tx.limit(), - GTFArgs::ScriptMaturity | GTFArgs::CreateMaturity => *tx.maturity(), + GTFArgs::ScriptMaturity | GTFArgs::CreateMaturity => **tx.maturity() as Word, GTFArgs::ScriptInputsCount | GTFArgs::CreateInputsCount => tx.inputs().len() as Word, GTFArgs::ScriptOutputsCount | GTFArgs::CreateOutputsCount => tx.outputs().len() as Word, GTFArgs::ScriptWitnessesCound | GTFArgs::CreateWitnessesCount => tx.witnesses().len() as Word, @@ -187,12 +187,12 @@ impl GTFInput<'_, Tx> { .filter(|i| i.is_coin()) .and_then(Input::witness_index) .ok_or(PanicReason::InputNotFound)? as Word, - GTFArgs::InputCoinMaturity => tx + GTFArgs::InputCoinMaturity => *tx .inputs() .get(b) .filter(|i| i.is_coin()) .and_then(Input::maturity) - .ok_or(PanicReason::InputNotFound)?, + .ok_or(PanicReason::InputNotFound)? as Word, GTFArgs::InputCoinPredicateLength => tx .inputs() .get(b) diff --git a/fuel-vm/src/predicate.rs b/fuel-vm/src/predicate.rs index ad18714a81..fe8317098e 100644 --- a/fuel-vm/src/predicate.rs +++ b/fuel-vm/src/predicate.rs @@ -52,7 +52,7 @@ fn from_tx_works() { let rng = &mut StdRng::seed_from_u64(2322u64); let params = ConsensusParameters::default(); - let height = 1; + let height = 1.into(); #[rustfmt::skip] let predicate: Vec = vec![ diff --git a/fuel-vm/src/storage/interpreter.rs b/fuel-vm/src/storage/interpreter.rs index 1f4854778c..a6da473816 100644 --- a/fuel-vm/src/storage/interpreter.rs +++ b/fuel-vm/src/storage/interpreter.rs @@ -2,7 +2,7 @@ use fuel_storage::{MerkleRootStorage, StorageAsRef, StorageInspect, StorageMutate, StorageRead, StorageSize}; use fuel_tx::{Contract, StorageSlot}; -use fuel_types::{Address, AssetId, Bytes32, ContractId, Salt, Word}; +use fuel_types::{Address, AssetId, BlockHeight, Bytes32, ContractId, Salt, Word}; use crate::storage::{ContractsAssets, ContractsInfo, ContractsRawCode, ContractsState}; use std::borrow::Cow; @@ -25,7 +25,7 @@ pub trait InterpreterStorage: /// Provide the current block height in which the transactions should be /// executed. - fn block_height(&self) -> Result; + fn block_height(&self) -> Result; /// Return the timestamp of a given block /// @@ -33,7 +33,7 @@ pub trait InterpreterStorage: /// passed - under the assumption that the block height is consistent, the storage should /// necessarily have the timestamp for the block, unless some I/O error prevents it from /// fetching it. - fn timestamp(&self, height: u32) -> Result; + fn timestamp(&self, height: BlockHeight) -> Result; /// Provide the block hash from a given height. fn block_hash(&self, block_height: u32) -> Result; @@ -199,11 +199,11 @@ where { type DataError = S::DataError; - fn block_height(&self) -> Result { + fn block_height(&self) -> Result { ::block_height(self.deref()) } - fn timestamp(&self, height: u32) -> Result { + fn timestamp(&self, height: BlockHeight) -> Result { ::timestamp(self.deref(), height) } diff --git a/fuel-vm/src/storage/memory.rs b/fuel-vm/src/storage/memory.rs index 77a4a58c21..ca31d29c1e 100644 --- a/fuel-vm/src/storage/memory.rs +++ b/fuel-vm/src/storage/memory.rs @@ -11,7 +11,7 @@ use fuel_storage::{ StorageWrite, }; use fuel_tx::Contract; -use fuel_types::{Address, Bytes32, ContractId, Salt, Word}; +use fuel_types::{Address, BlockHeight, Bytes32, ContractId, Salt, Word}; use itertools::Itertools; use tai64::Tai64; @@ -38,7 +38,7 @@ struct MemoryStorageInner { /// - transacted: will receive the committed `memory` state. /// - persisted: will receive the persisted `transacted` state. pub struct MemoryStorage { - block_height: u32, + block_height: BlockHeight, coinbase: Address, memory: MemoryStorageInner, transacted: MemoryStorageInner, @@ -47,7 +47,7 @@ pub struct MemoryStorage { impl MemoryStorage { /// Create a new memory storage. - pub fn new(block_height: u32, coinbase: Address) -> Self { + pub fn new(block_height: BlockHeight, coinbase: Address) -> Self { Self { block_height, coinbase, @@ -96,14 +96,14 @@ impl MemoryStorage { #[cfg(feature = "test-helpers")] /// Set the block height of the chain - pub fn set_block_height(&mut self, block_height: u32) { + pub fn set_block_height(&mut self, block_height: BlockHeight) { self.block_height = block_height; } } impl Default for MemoryStorage { fn default() -> Self { - let block_height = 1; + let block_height = 1.into(); let coinbase = Address::from(*Hasher::hash(b"coinbase")); Self::new(block_height, coinbase) @@ -277,15 +277,15 @@ impl ContractsAssetsStorage for MemoryStorage {} impl InterpreterStorage for MemoryStorage { type DataError = Infallible; - fn block_height(&self) -> Result { + fn block_height(&self) -> Result { Ok(self.block_height) } - fn timestamp(&self, height: u32) -> Result { + fn timestamp(&self, height: BlockHeight) -> Result { const GENESIS: Tai64 = Tai64::UNIX_EPOCH; const INTERVAL: Word = 10; - Ok((GENESIS + (height as Word * INTERVAL)).0) + Ok((GENESIS + (*height as Word * INTERVAL)).0) } fn block_hash(&self, block_height: u32) -> Result { diff --git a/fuel-vm/src/storage/predicate.rs b/fuel-vm/src/storage/predicate.rs index 046def026a..beb7fb9260 100644 --- a/fuel-vm/src/storage/predicate.rs +++ b/fuel-vm/src/storage/predicate.rs @@ -5,7 +5,7 @@ use crate::storage::InterpreterStorage; use fuel_asm::Word; use fuel_storage::{Mappable, MerkleRoot, MerkleRootStorage, StorageInspect, StorageMutate, StorageRead, StorageSize}; -use fuel_types::{Address, Bytes32, ContractId}; +use fuel_types::{Address, BlockHeight, Bytes32, ContractId}; use super::{interpreter::ContractsAssetsStorage, ContractsRawCode}; @@ -66,11 +66,11 @@ impl ContractsAssetsStorage for PredicateStorage {} impl InterpreterStorage for PredicateStorage { type DataError = InterpreterError; - fn block_height(&self) -> Result { + fn block_height(&self) -> Result { Err(InterpreterError::PredicateFailure) } - fn timestamp(&self, _height: u32) -> Result { + fn timestamp(&self, _height: BlockHeight) -> Result { Err(InterpreterError::PredicateFailure) } diff --git a/fuel-vm/src/tests/alu.rs b/fuel-vm/src/tests/alu.rs index a77f47562a..c0b6e20771 100644 --- a/fuel-vm/src/tests/alu.rs +++ b/fuel-vm/src/tests/alu.rs @@ -9,8 +9,8 @@ fn alu(registers_init: &[(RegisterId, Word)], ins: Instruction, reg: RegisterId, let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); let reg = u8::try_from(reg).unwrap(); let gas_costs = GasCosts::default(); @@ -42,8 +42,8 @@ fn alu_overflow(program: &[Instruction], reg: RegisterId, expected: u128, boolea let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); let gas_costs = GasCosts::default(); @@ -122,8 +122,8 @@ fn alu_wrapping( let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); let gas_costs = GasCosts::default(); @@ -175,8 +175,8 @@ fn alu_err(registers_init: &[(RegisterId, Immediate18)], ins: Instruction, reg: let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); let reg = u8::try_from(reg).unwrap(); let gas_costs = GasCosts::default(); @@ -240,8 +240,8 @@ fn alu_reserved(registers_init: &[(RegisterId, Word)], ins: Instruction) { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); let gas_costs = GasCosts::default(); diff --git a/fuel-vm/src/tests/backtrace.rs b/fuel-vm/src/tests/backtrace.rs index 4115fdb4d0..6bbcde935c 100644 --- a/fuel-vm/src/tests/backtrace.rs +++ b/fuel-vm/src/tests/backtrace.rs @@ -13,8 +13,8 @@ fn backtrace() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); let gas_costs = GasCosts::default(); diff --git a/fuel-vm/src/tests/blockchain.rs b/fuel-vm/src/tests/blockchain.rs index 0111d17f2a..ff84727d50 100644 --- a/fuel-vm/src/tests/blockchain.rs +++ b/fuel-vm/src/tests/blockchain.rs @@ -27,8 +27,8 @@ fn state_read_write() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); let salt: Salt = rng.gen(); @@ -293,8 +293,8 @@ fn load_external_contract_code() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); // Start by creating and deploying a new example contract @@ -423,8 +423,8 @@ fn ldc_reason_helper(cmd: Vec, expected_reason: PanicReason, should let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); // Start by creating and deploying a new example contract @@ -937,8 +937,8 @@ fn check_receipts_for_program_call(program: Vec, expected_values: V let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); let salt: Salt = rng.gen(); @@ -1311,8 +1311,8 @@ fn smo_instruction_works() { let mut client = MemoryClient::default(); let gas_limit = 1_000_000; - let maturity = 0; - let block_height = 0; + let maturity = Default::default(); + let block_height = Default::default(); let params = client.params(); @@ -1434,8 +1434,8 @@ fn timestamp_works() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let block_height = 0; + let maturity = Default::default(); + let block_height = Default::default(); let params = *client.params(); @@ -1454,9 +1454,12 @@ fn timestamp_works() { ]; for (height, input) in cases { - client.as_mut().set_block_height(height); + client.as_mut().set_block_height(height.into()); - let expected = client.as_ref().timestamp(input).expect("failed to calculate timestamp"); + let expected = client + .as_ref() + .timestamp(input.into()) + .expect("failed to calculate timestamp"); #[rustfmt::skip] let script = vec![ diff --git a/fuel-vm/src/tests/code_coverage.rs b/fuel-vm/src/tests/code_coverage.rs index 85c41e51c6..9b49dd3016 100644 --- a/fuel-vm/src/tests/code_coverage.rs +++ b/fuel-vm/src/tests/code_coverage.rs @@ -16,8 +16,8 @@ fn code_coverage() { let gas_price = 1; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); // Deploy contract with loops @@ -32,7 +32,14 @@ fn code_coverage() { ]; let tx_script = TransactionBuilder::script(script_code.into_iter().collect(), vec![]) - .add_unsigned_coin_input(rng.gen(), rng.gen(), 1, Default::default(), rng.gen(), 0) + .add_unsigned_coin_input( + rng.gen(), + rng.gen(), + 1, + Default::default(), + rng.gen(), + Default::default(), + ) .gas_price(gas_price) .gas_limit(gas_limit) .maturity(maturity) diff --git a/fuel-vm/src/tests/contract.rs b/fuel-vm/src/tests/contract.rs index b052a73746..7757276180 100644 --- a/fuel-vm/src/tests/contract.rs +++ b/fuel-vm/src/tests/contract.rs @@ -34,9 +34,9 @@ fn prevent_contract_id_redeployment() { let mut create = Transaction::create( gas_price, - 0, - 0, - 0, + Default::default(), + Default::default(), + Default::default(), salt, vec![], vec![], @@ -47,9 +47,16 @@ fn prevent_contract_id_redeployment() { ], vec![program], ); - create.add_unsigned_coin_input(rng.gen(), &Default::default(), input_amount, asset_id, rng.gen(), 0); + create.add_unsigned_coin_input( + rng.gen(), + &Default::default(), + input_amount, + asset_id, + rng.gen(), + Default::default(), + ); let create = create - .into_checked_basic(1, &ConsensusParameters::default()) + .into_checked_basic(1.into(), &ConsensusParameters::default()) .expect("failed to generate checked tx"); // deploy contract @@ -70,8 +77,8 @@ fn mint_burn() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::DEFAULT; let salt: Salt = rng.gen(); diff --git a/fuel-vm/src/tests/crypto.rs b/fuel-vm/src/tests/crypto.rs index 2365100c2b..9b7545fa5e 100644 --- a/fuel-vm/src/tests/crypto.rs +++ b/fuel-vm/src/tests/crypto.rs @@ -17,8 +17,8 @@ fn ecrecover() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); let gas_costs = GasCosts::default(); @@ -145,8 +145,8 @@ fn sha256() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); let gas_costs = GasCosts::default(); @@ -235,8 +235,8 @@ fn keccak256() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); let message = b"...and, moreover, I consider it my duty to warn you that the cat is an ancient, inviolable animal."; diff --git a/fuel-vm/src/tests/encoding.rs b/fuel-vm/src/tests/encoding.rs index 3ca2f488c3..eb6fa005a5 100644 --- a/fuel-vm/src/tests/encoding.rs +++ b/fuel-vm/src/tests/encoding.rs @@ -98,17 +98,17 @@ fn input() { [0xbb; 32].into(), Word::MAX, [0xcc; 32].into(), - TxPointer::new(0x3802, 0x28), + TxPointer::new(0x3802.into(), 0x28), 0xff, - Word::MAX >> 1, + (u32::MAX >> 1).into(), ), Input::coin_predicate( UtxoId::new([0xaa; 32].into(), 0), [0xbb; 32].into(), Word::MAX, [0xcc; 32].into(), - TxPointer::new(0x3802, 0x28), - Word::MAX >> 1, + TxPointer::new(0x3802.into(), 0x28), + (u32::MAX >> 1).into(), vec![0xdd; 50], vec![0xee; 23], ), @@ -117,8 +117,8 @@ fn input() { [0xbb; 32].into(), Word::MAX, [0xcc; 32].into(), - TxPointer::new(0x3802, 0x28), - Word::MAX >> 1, + TxPointer::new(0x3802.into(), 0x28), + (u32::MAX >> 1).into(), vec![0xdd; 50], vec![], ), @@ -169,7 +169,7 @@ fn input() { UtxoId::new([0xaa; 32].into(), 0), [0xbb; 32].into(), [0xcc; 32].into(), - TxPointer::new(0x3802, 0x28), + TxPointer::new(0x3802.into(), 0x28), [0xdd; 32].into(), ), ]); @@ -192,7 +192,7 @@ fn transaction() { UtxoId::new([0xaa; 32].into(), 0), [0xbb; 32].into(), [0xcc; 32].into(), - TxPointer::new(0xbeef, 0xeaae), + TxPointer::new(0xbeef.into(), 0xeaae), [0xdd; 32].into(), ); let o = Output::coin([0xaa; 32].into(), Word::MAX >> 1, [0xbb; 32].into()); @@ -202,7 +202,7 @@ fn transaction() { Transaction::script( Word::MAX >> 1, Word::MAX >> 2, - Word::MAX >> 3, + (u32::MAX >> 3).into(), vec![0xfa], vec![0xfb, 0xfc], vec![i.clone()], @@ -212,7 +212,7 @@ fn transaction() { Transaction::script( Word::MAX >> 1, Word::MAX >> 2, - Word::MAX >> 3, + (u32::MAX >> 3).into(), vec![], vec![0xfb, 0xfc], vec![i.clone()], @@ -222,7 +222,7 @@ fn transaction() { Transaction::script( Word::MAX >> 1, Word::MAX >> 2, - Word::MAX >> 3, + (u32::MAX >> 3).into(), vec![0xfa], vec![], vec![i.clone()], @@ -232,7 +232,7 @@ fn transaction() { Transaction::script( Word::MAX >> 1, Word::MAX >> 2, - Word::MAX >> 3, + (u32::MAX >> 3).into(), vec![], vec![], vec![i.clone()], @@ -242,7 +242,7 @@ fn transaction() { Transaction::script( Word::MAX >> 1, Word::MAX >> 2, - Word::MAX >> 3, + (u32::MAX >> 3).into(), vec![], vec![], vec![], @@ -252,7 +252,7 @@ fn transaction() { Transaction::script( Word::MAX >> 1, Word::MAX >> 2, - Word::MAX >> 3, + (u32::MAX >> 3).into(), vec![], vec![], vec![], @@ -262,7 +262,7 @@ fn transaction() { Transaction::script( Word::MAX >> 1, Word::MAX >> 2, - Word::MAX >> 3, + (u32::MAX >> 3).into(), vec![], vec![], vec![], @@ -274,7 +274,7 @@ fn transaction() { Transaction::create( Word::MAX >> 1, Word::MAX >> 2, - Word::MAX >> 3, + (u32::MAX >> 3).into(), 0xba, [0xdd; 32].into(), vec![], @@ -285,7 +285,7 @@ fn transaction() { Transaction::create( Word::MAX >> 1, Word::MAX >> 2, - Word::MAX >> 3, + (u32::MAX >> 3).into(), 0xba, [0xdd; 32].into(), vec![], @@ -296,7 +296,7 @@ fn transaction() { Transaction::create( Word::MAX >> 1, Word::MAX >> 2, - Word::MAX >> 3, + (u32::MAX >> 3).into(), 0xba, [0xdd; 32].into(), vec![], @@ -307,7 +307,7 @@ fn transaction() { Transaction::create( Word::MAX >> 1, Word::MAX >> 2, - Word::MAX >> 3, + (u32::MAX >> 3).into(), 0xba, [0xdd; 32].into(), vec![], diff --git a/fuel-vm/src/tests/flow.rs b/fuel-vm/src/tests/flow.rs index 0db9257141..51b662a723 100644 --- a/fuel-vm/src/tests/flow.rs +++ b/fuel-vm/src/tests/flow.rs @@ -17,8 +17,8 @@ fn can_execute_empty_script_transaction() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::DEFAULT; let empty_script = vec![]; @@ -58,8 +58,8 @@ fn code_copy() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::DEFAULT; let salt: Salt = rng.gen(); @@ -155,9 +155,9 @@ fn call() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; + let maturity = Default::default(); let salt: Salt = rng.gen(); - let height = 0; + let height = Default::default(); let params = ConsensusParameters::DEFAULT; let gas_costs = GasCosts::default(); @@ -256,8 +256,8 @@ fn call_frame_code_offset() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::DEFAULT; let gas_costs = GasCosts::default(); @@ -426,8 +426,8 @@ fn repeated_nested_calls() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::DEFAULT; let salt: Salt = rng.gen(); @@ -513,8 +513,8 @@ fn revert() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::DEFAULT; let salt: Salt = rng.gen(); @@ -702,8 +702,8 @@ fn retd_from_top_of_heap() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::DEFAULT; const REG_SIZE: u8 = RegId::WRITABLE.to_u8(); @@ -737,8 +737,8 @@ fn logd_from_top_of_heap() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::DEFAULT; const REG_SIZE: RegId = RegId::WRITABLE; diff --git a/fuel-vm/src/tests/jump_absolute.rs b/fuel-vm/src/tests/jump_absolute.rs index f8496f11a6..007cf3965a 100644 --- a/fuel-vm/src/tests/jump_absolute.rs +++ b/fuel-vm/src/tests/jump_absolute.rs @@ -7,8 +7,8 @@ fn jump_if_not_zero_immediate_jump() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::DEFAULT; #[rustfmt::skip] @@ -47,8 +47,8 @@ fn jump_if_not_zero_immediate_no_jump() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::DEFAULT; #[rustfmt::skip] @@ -87,8 +87,8 @@ fn jump_dynamic() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::DEFAULT; #[rustfmt::skip] @@ -119,8 +119,8 @@ fn jump_dynamic_condition_true() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::DEFAULT; #[rustfmt::skip] @@ -151,8 +151,8 @@ fn jump_dynamic_condition_false() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::DEFAULT; #[rustfmt::skip] diff --git a/fuel-vm/src/tests/memory.rs b/fuel-vm/src/tests/memory.rs index 302b6ac630..e49e9317a6 100644 --- a/fuel-vm/src/tests/memory.rs +++ b/fuel-vm/src/tests/memory.rs @@ -13,8 +13,8 @@ fn setup(program: Vec) -> Transactor { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); let gas_costs = GasCosts::default(); @@ -87,8 +87,8 @@ fn test_stack_and_heap_cannot_overlap(offset: u64, cause_error: bool) { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); let gas_costs = GasCosts::default(); @@ -142,8 +142,8 @@ fn dynamic_call_frame_ops() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); let gas_costs = GasCosts::default(); diff --git a/fuel-vm/src/tests/metadata.rs b/fuel-vm/src/tests/metadata.rs index 8379cee3f9..9f7f19912c 100644 --- a/fuel-vm/src/tests/metadata.rs +++ b/fuel-vm/src/tests/metadata.rs @@ -18,8 +18,8 @@ fn metadata() { let gas_price = 0; let gas_limit = 1_000_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); let gas_costs = GasCosts::default(); @@ -183,8 +183,8 @@ fn get_transaction_fields() { let gas_price = 1; let gas_limit = 1_000_000; - let maturity = 50; - let height = 122; + let maturity = 50.into(); + let height = 122.into(); let input = 10_000_000; let params = ConsensusParameters::default(); @@ -214,7 +214,7 @@ fn get_transaction_fields() { 1_500, rng.gen(), rng.gen(), - 100, + 100.into(), predicate.clone(), predicate_data.clone(), ); @@ -355,7 +355,7 @@ fn get_transaction_fields() { op::and(0x20, 0x20, 0x10), op::movi(0x19, 0x00), - op::movi(0x11, maturity as Immediate18), + op::movi(0x11, *maturity as Immediate18), op::gtf_args(0x10, 0x19, GTFArgs::ScriptMaturity), op::eq(0x10, 0x10, 0x11), op::and(0x20, 0x20, 0x10), @@ -478,7 +478,7 @@ fn get_transaction_fields() { op::eq(0x10, 0x10, 0x11), op::and(0x20, 0x20, 0x10), - op::movi(0x11, inputs[0].maturity().unwrap() as Immediate18), + op::movi(0x11, *inputs[0].maturity().unwrap() as Immediate18), op::movi(0x19, 0x00), op::gtf_args(0x10, 0x19, GTFArgs::InputCoinMaturity), op::eq(0x10, 0x10, 0x11), diff --git a/fuel-vm/src/tests/outputs.rs b/fuel-vm/src/tests/outputs.rs index 76e8365560..60a8a5436b 100644 --- a/fuel-vm/src/tests/outputs.rs +++ b/fuel-vm/src/tests/outputs.rs @@ -104,8 +104,8 @@ fn correct_change_is_provided_for_coin_outputs_create() { let bytecode_witness = 0; let mut create = Transaction::create( gas_price, - 0, - 0, + Default::default(), + Default::default(), bytecode_witness, salt, vec![], @@ -117,9 +117,16 @@ fn correct_change_is_provided_for_coin_outputs_create() { ], vec![program], ); - create.add_unsigned_coin_input(rng.gen(), &Default::default(), input_amount, asset_id, rng.gen(), 0); + create.add_unsigned_coin_input( + rng.gen(), + &Default::default(), + input_amount, + asset_id, + rng.gen(), + Default::default(), + ); let create = create - .into_checked_basic(context.get_block_height() as Word, context.get_params()) + .into_checked_basic(context.get_block_height(), context.get_params()) .expect("failed to generate checked tx"); let state = context.execute_tx(create).expect("Create should be executed"); diff --git a/fuel-vm/src/tests/predicate.rs b/fuel-vm/src/tests/predicate.rs index 108da18202..235088c342 100644 --- a/fuel-vm/src/tests/predicate.rs +++ b/fuel-vm/src/tests/predicate.rs @@ -23,8 +23,8 @@ where let amount = 0; let asset_id = rng.gen(); let tx_pointer = rng.gen(); - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); let owner = Input::predicate_owner(&predicate); @@ -119,12 +119,22 @@ fn execute_gas_metered_predicates(predicates: Vec>) -> Result>) -> Result>) -> Result::check_predicates(tx, Default::default(), Default::default()) .map(|r| r.gas_used()) .map_err(|_| ()) @@ -193,14 +203,24 @@ fn gas_used_by_predicates_is_deducted_from_script_gas() { let params = ConsensusParameters::default(); let mut builder = TransactionBuilder::script(script, script_data); - builder.gas_price(gas_price).gas_limit(gas_limit).maturity(0); + builder + .gas_price(gas_price) + .gas_limit(gas_limit) + .maturity(Default::default()); let coin_amount = 10_000_000; - builder.add_unsigned_coin_input(rng.gen(), rng.gen(), coin_amount, AssetId::default(), rng.gen(), 0); + builder.add_unsigned_coin_input( + rng.gen(), + rng.gen(), + coin_amount, + AssetId::default(), + rng.gen(), + Default::default(), + ); let tx_without_predicate = builder - .finalize_checked_basic(0, ¶ms) + .finalize_checked_basic(Default::default(), ¶ms) .check_predicates(¶ms, &GasCosts::default()) .expect("Predicate check failed even if we don't have any predicates"); @@ -222,7 +242,7 @@ fn gas_used_by_predicates_is_deducted_from_script_gas() { coin_amount, AssetId::default(), rng.gen(), - 0, + Default::default(), predicate, vec![], ); @@ -230,7 +250,7 @@ fn gas_used_by_predicates_is_deducted_from_script_gas() { builder.add_input(input); let tx_with_predicate = builder - .finalize_checked_basic(0, &ConsensusParameters::default()) + .finalize_checked_basic(Default::default(), &ConsensusParameters::default()) .check_predicates(¶ms, &GasCosts::default()) .expect("Predicate check failed"); @@ -256,14 +276,24 @@ fn gas_used_by_predicates_causes_out_of_gas_during_script() { let script_data = vec![]; let mut builder = TransactionBuilder::script(script, script_data); - builder.gas_price(gas_price).gas_limit(gas_limit).maturity(0); + builder + .gas_price(gas_price) + .gas_limit(gas_limit) + .maturity(Default::default()); let coin_amount = 10_000_000; - builder.add_unsigned_coin_input(rng.gen(), rng.gen(), coin_amount, AssetId::default(), rng.gen(), 0); + builder.add_unsigned_coin_input( + rng.gen(), + rng.gen(), + coin_amount, + AssetId::default(), + rng.gen(), + Default::default(), + ); let tx_without_predicate = builder - .finalize_checked_basic(0, &ConsensusParameters::default()) + .finalize_checked_basic(Default::default(), &ConsensusParameters::default()) .check_predicates(¶ms, &GasCosts::default()) .expect("Predicate check failed even if we don't have any predicates"); @@ -288,7 +318,7 @@ fn gas_used_by_predicates_causes_out_of_gas_during_script() { coin_amount, AssetId::default(), rng.gen(), - 0, + Default::default(), predicate, vec![], ); @@ -296,7 +326,7 @@ fn gas_used_by_predicates_causes_out_of_gas_during_script() { builder.add_input(input); let tx_with_predicate = builder - .finalize_checked_basic(0, &ConsensusParameters::default()) + .finalize_checked_basic(Default::default(), &ConsensusParameters::default()) .check_predicates(¶ms, &GasCosts::default()) .expect("Predicate check failed"); @@ -322,14 +352,24 @@ fn gas_used_by_predicates_more_than_limit() { let script_data = vec![]; let mut builder = TransactionBuilder::script(script, script_data); - builder.gas_price(gas_price).gas_limit(gas_limit).maturity(0); + builder + .gas_price(gas_price) + .gas_limit(gas_limit) + .maturity(Default::default()); let coin_amount = 10_000_000; - builder.add_unsigned_coin_input(rng.gen(), rng.gen(), coin_amount, AssetId::default(), rng.gen(), 0); + builder.add_unsigned_coin_input( + rng.gen(), + rng.gen(), + coin_amount, + AssetId::default(), + rng.gen(), + Default::default(), + ); let tx_without_predicate = builder - .finalize_checked_basic(0, &ConsensusParameters::default()) + .finalize_checked_basic(Default::default(), &ConsensusParameters::default()) .check_predicates(¶ms, &GasCosts::default()) .expect("Predicate check failed even if we don't have any predicates"); @@ -360,7 +400,7 @@ fn gas_used_by_predicates_more_than_limit() { coin_amount, AssetId::default(), rng.gen(), - 0, + Default::default(), predicate, vec![], ); @@ -368,7 +408,7 @@ fn gas_used_by_predicates_more_than_limit() { builder.add_input(input); let tx_with_predicate = builder - .finalize_checked_basic(0, &ConsensusParameters::default()) + .finalize_checked_basic(Default::default(), &ConsensusParameters::default()) .check_predicates(¶ms, &GasCosts::default()); assert_eq!(tx_with_predicate.unwrap_err(), CheckError::PredicateExhaustedGas); diff --git a/fuel-vm/src/tests/profile_gas.rs b/fuel-vm/src/tests/profile_gas.rs index b19bf76e74..b4e616474d 100644 --- a/fuel-vm/src/tests/profile_gas.rs +++ b/fuel-vm/src/tests/profile_gas.rs @@ -11,8 +11,8 @@ fn profile_gas() { let gas_price = 1; let gas_limit = 1_000; - let maturity = 0; - let height = 0; + let maturity = Default::default(); + let height = Default::default(); let params = ConsensusParameters::default(); // Deploy contract with loops @@ -29,7 +29,14 @@ fn profile_gas() { ]; let tx_deploy = TransactionBuilder::script(script_code.into_iter().collect(), vec![]) - .add_unsigned_coin_input(rng.gen(), rng.gen(), 1, Default::default(), rng.gen(), 0) + .add_unsigned_coin_input( + rng.gen(), + rng.gen(), + 1, + Default::default(), + rng.gen(), + Default::default(), + ) .gas_limit(gas_limit) .gas_price(gas_price) .maturity(maturity) diff --git a/fuel-vm/src/tests/test_helpers.rs b/fuel-vm/src/tests/test_helpers.rs index 20edde3e4e..1f2db7af59 100644 --- a/fuel-vm/src/tests/test_helpers.rs +++ b/fuel-vm/src/tests/test_helpers.rs @@ -17,8 +17,8 @@ pub fn set_full_word(r: RegisterId, v: Word) -> Vec { pub fn run_script(script: Vec) -> Vec { let script = script.into_iter().collect(); let mut client = MemoryClient::default(); - let tx = Transaction::script(0, 1_000_000, 0, script, vec![], vec![], vec![], vec![]) - .into_checked(0, &ConsensusParameters::DEFAULT, client.gas_costs()) + let tx = Transaction::script(0, 1_000_000, Default::default(), script, vec![], vec![], vec![], vec![]) + .into_checked(Default::default(), &ConsensusParameters::DEFAULT, client.gas_costs()) .expect("failed to generate a checked tx"); client.transact(tx); client.receipts().expect("Expected receipts").to_vec() diff --git a/fuel-vm/src/tests/validation.rs b/fuel-vm/src/tests/validation.rs index b61cbcc750..950c87087d 100644 --- a/fuel-vm/src/tests/validation.rs +++ b/fuel-vm/src/tests/validation.rs @@ -1,23 +1,31 @@ use fuel_asm::op; use fuel_tx::TransactionBuilder; +use fuel_types::BlockHeight; use fuel_vm::prelude::*; use rand::rngs::StdRng; use rand::{Rng, SeedableRng}; #[test] fn transaction_can_be_executed_after_maturity() { - const MATURITY: u64 = 1; - const BLOCK_HEIGHT: u32 = 2; + const MATURITY: BlockHeight = BlockHeight::new(1); + const BLOCK_HEIGHT: BlockHeight = BlockHeight::new(2); let params = ConsensusParameters::default(); let gas_costs = GasCosts::default(); let rng = &mut StdRng::seed_from_u64(2322u64); let tx = TransactionBuilder::script(Some(op::ret(1)).into_iter().collect(), Default::default()) - .add_unsigned_coin_input(rng.gen(), rng.gen(), 1, Default::default(), rng.gen(), 0) + .add_unsigned_coin_input( + rng.gen(), + rng.gen(), + 1, + Default::default(), + rng.gen(), + Default::default(), + ) .gas_limit(100) .maturity(MATURITY) - .finalize_checked(BLOCK_HEIGHT as Word, ¶ms, &gas_costs); + .finalize_checked(BLOCK_HEIGHT, ¶ms, &gas_costs); let result = TestBuilder::new(2322u64).block_height(BLOCK_HEIGHT).execute_tx(tx); assert!(result.is_ok()); diff --git a/fuel-vm/src/util.rs b/fuel-vm/src/util.rs index e3782f8266..d12d481719 100644 --- a/fuel-vm/src/util.rs +++ b/fuel-vm/src/util.rs @@ -88,7 +88,7 @@ pub mod test_helpers { TransactionBuilder, Witness, }; use fuel_types::bytes::{Deserializable, SerializableVec, SizedBytes}; - use fuel_types::{Address, AssetId, ContractId, Immediate12, Salt, Word}; + use fuel_types::{Address, AssetId, BlockHeight, ContractId, Immediate12, Salt, Word}; use itertools::Itertools; use rand::prelude::StdRng; use rand::{Rng, SeedableRng}; @@ -107,7 +107,7 @@ pub mod test_helpers { storage: MemoryStorage, params: ConsensusParameters, gas_costs: GasCosts, - block_height: u32, + block_height: BlockHeight, } impl TestBuilder { @@ -121,11 +121,11 @@ pub mod test_helpers { storage: MemoryStorage::default(), params: ConsensusParameters::default(), gas_costs: Default::default(), - block_height: 0, + block_height: Default::default(), } } - pub fn get_block_height(&self) -> u32 { + pub fn get_block_height(&self) -> BlockHeight { self.block_height } @@ -184,8 +184,14 @@ pub mod test_helpers { } pub fn coin_input(&mut self, asset_id: AssetId, amount: Word) -> &mut TestBuilder { - self.builder - .add_unsigned_coin_input(self.rng.gen(), self.rng.gen(), amount, asset_id, self.rng.gen(), 0); + self.builder.add_unsigned_coin_input( + self.rng.gen(), + self.rng.gen(), + amount, + asset_id, + self.rng.gen(), + Default::default(), + ); self } @@ -215,7 +221,7 @@ pub mod test_helpers { self } - pub fn block_height(&mut self, block_height: u32) -> &mut TestBuilder { + pub fn block_height(&mut self, block_height: BlockHeight) -> &mut TestBuilder { self.block_height = block_height; self } @@ -226,7 +232,7 @@ pub mod test_helpers { pub fn build(&mut self) -> Checked