From f583e8b7cc496e49691d1511efd15fb5038d06a1 Mon Sep 17 00:00:00 2001 From: varun-doshi Date: Mon, 2 Dec 2024 19:41:52 +0530 Subject: [PATCH 1/8] replaced storage_index from u64 to proper type --- crates/merkle-tree/src/merkle_node.rs | 25 +++++++++++++++++++++---- crates/merkle-tree/src/tree.rs | 22 +++++++++++----------- 2 files changed, 32 insertions(+), 15 deletions(-) diff --git a/crates/merkle-tree/src/merkle_node.rs b/crates/merkle-tree/src/merkle_node.rs index b162208bff..c2827709f2 100644 --- a/crates/merkle-tree/src/merkle_node.rs +++ b/crates/merkle-tree/src/merkle_node.rs @@ -12,6 +12,7 @@ use bitvec::prelude::BitVec; use bitvec::slice::BitSlice; use pathfinder_common::hash::FeltHash; use pathfinder_crypto::Felt; +use pathfinder_storage::Storage; /// A node in a Binary Merkle-Patricia Tree graph. #[derive(Clone, Debug, PartialEq)] @@ -28,11 +29,27 @@ pub enum InternalNode { Leaf, } +/// A newtype for the storage index of a trie node. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct StorageIndex(u64); + +impl StorageIndex { + /// Create a new StorageIndex. + pub fn new(index: u64) -> Self { + Self(index) + } + + /// Get the inner u64 value. + pub fn value(&self) -> u64 { + self.0 + } +} + /// Describes the [InternalNode::Binary] variant. #[derive(Clone, Debug, PartialEq)] pub struct BinaryNode { /// The storage index of this node (if it was loaded from storage). - pub storage_index: Option, + pub storage_index: Option, /// The height of this node in the tree. pub height: usize, /// [Left](Direction::Left) child. @@ -44,7 +61,7 @@ pub struct BinaryNode { #[derive(Clone, Debug, PartialEq)] pub struct EdgeNode { /// The storage index of this node (if it was loaded from storage). - pub storage_index: Option, + pub storage_index: Option, /// The starting height of this node in the tree. pub height: usize, /// The path this edge takes. @@ -144,9 +161,9 @@ impl InternalNode { matches!(self, InternalNode::Leaf) } - pub fn storage_index(&self) -> Option { + pub fn storage_index(&self) -> Option { match self { - InternalNode::Unresolved(storage_index) => Some(*storage_index), + InternalNode::Unresolved(storage_index) => Some(StorageIndex::new(*storage_index)), InternalNode::Binary(binary) => binary.storage_index, InternalNode::Edge(edge) => edge.storage_index, InternalNode::Leaf => None, diff --git a/crates/merkle-tree/src/tree.rs b/crates/merkle-tree/src/tree.rs index 8118d23f9a..bceb270612 100644 --- a/crates/merkle-tree/src/tree.rs +++ b/crates/merkle-tree/src/tree.rs @@ -63,7 +63,7 @@ use pathfinder_common::trie::TrieNode; use pathfinder_crypto::Felt; use pathfinder_storage::{Node, NodeRef, StoredNode, TrieUpdate}; -use crate::merkle_node::{BinaryNode, Direction, EdgeNode, InternalNode}; +use crate::merkle_node::{BinaryNode, Direction, EdgeNode, InternalNode, StorageIndex}; use crate::storage::Storage; /// A Starknet binary Merkle-Patricia tree. @@ -214,7 +214,7 @@ impl MerkleTree { }; if let Some(storage_index) = binary.storage_index { - removed.push(storage_index); + removed.push(storage_index.value()); }; let node_index = added.len(); @@ -247,7 +247,7 @@ impl MerkleTree { let node_index = added.len(); added.push((hash, persisted_node)); if let Some(storage_index) = edge.storage_index { - removed.push(storage_index); + removed.push(storage_index.value()); }; (hash, Some(NodeRef::Index(node_index))) @@ -371,7 +371,7 @@ impl MerkleTree { let old_node = node.replace(updated); if let Some(index) = old_node.storage_index() { - self.nodes_removed.push(index); + self.nodes_removed.push(index.value()); }; } None => { @@ -438,7 +438,7 @@ impl MerkleTree { InternalNode::Binary(_) => false, _ => { if let Some(index) = node.storage_index() { - indexes_removed.push(index); + indexes_removed.push(index.value()); }; true } @@ -471,7 +471,7 @@ impl MerkleTree { // Replace the old binary node with the new edge node. let old_node = node.replace(InternalNode::Edge(new_edge)); if let Some(index) = old_node.storage_index() { - self.nodes_removed.push(index); + self.nodes_removed.push(index.value()); }; } None => { @@ -747,25 +747,25 @@ impl MerkleTree { let node = match node { StoredNode::Binary { left, right } => InternalNode::Binary(BinaryNode { - storage_index: Some(index), + storage_index: Some(StorageIndex::new(index)), height, left: Rc::new(RefCell::new(InternalNode::Unresolved(left))), right: Rc::new(RefCell::new(InternalNode::Unresolved(right))), }), StoredNode::Edge { child, path } => InternalNode::Edge(EdgeNode { - storage_index: Some(index), + storage_index: Some(StorageIndex::new(index)), height, path, child: Rc::new(RefCell::new(InternalNode::Unresolved(child))), }), StoredNode::LeafBinary => InternalNode::Binary(BinaryNode { - storage_index: Some(index), + storage_index: Some(StorageIndex::new(index)), height, left: Rc::new(RefCell::new(InternalNode::Leaf)), right: Rc::new(RefCell::new(InternalNode::Leaf)), }), StoredNode::LeafEdge { path } => InternalNode::Edge(EdgeNode { - storage_index: Some(index), + storage_index: Some(StorageIndex::new(index)), height, path, child: Rc::new(RefCell::new(InternalNode::Leaf)), @@ -794,7 +794,7 @@ impl MerkleTree { if let Some(child_edge) = resolved_child.as_edge().cloned() { parent.path.extend_from_bitslice(&child_edge.path); if let Some(storage_index) = child_edge.storage_index { - self.nodes_removed.push(storage_index); + self.nodes_removed.push(storage_index.value()); } parent.child = child_edge.child; } From c2fc124e43b48073dabbe28dfb26001310caaf99 Mon Sep 17 00:00:00 2001 From: varun-doshi Date: Mon, 2 Dec 2024 19:46:24 +0530 Subject: [PATCH 2/8] fmt --- crates/merkle-tree/src/tree.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/merkle-tree/src/tree.rs b/crates/merkle-tree/src/tree.rs index bceb270612..72d8b36d91 100644 --- a/crates/merkle-tree/src/tree.rs +++ b/crates/merkle-tree/src/tree.rs @@ -1583,11 +1583,7 @@ mod tests { mod real_world { use pathfinder_common::{ - class_commitment, - class_commitment_leaf_hash, - felt, - sierra_hash, - BlockNumber, + class_commitment, class_commitment_leaf_hash, felt, sierra_hash, BlockNumber, ClassCommitmentLeafHash, }; use pathfinder_storage::RootIndexUpdate; From d1274556270310da50c7881f6693f8a7a3b87dd5 Mon Sep 17 00:00:00 2001 From: varun-doshi Date: Wed, 4 Dec 2024 15:45:44 +0530 Subject: [PATCH 3/8] fixed comments and lint --- crates/common/src/lib.rs | 1 + crates/common/src/prelude.rs | 51 ++--------- crates/common/src/state_update.rs | 19 +--- crates/common/src/storage_index.rs | 15 ++++ crates/common/src/test_utils.rs | 11 +-- crates/common/src/transaction.rs | 6 +- crates/compiler/src/lib.rs | 16 ++-- crates/crypto/src/lib.rs | 8 +- crates/crypto/src/signature/mod.rs | 7 +- crates/ethereum/src/lib.rs | 12 +-- crates/executor/src/error.rs | 3 +- crates/executor/src/error_stack.rs | 3 +- crates/executor/src/execution_state.rs | 7 +- crates/executor/src/lib.rs | 5 +- crates/executor/src/pending.rs | 7 +- crates/executor/src/simulate.rs | 28 ++---- crates/executor/src/types.rs | 8 +- crates/gateway-client/src/lib.rs | 8 +- crates/gateway-test-fixtures/src/lib.rs | 7 +- crates/gateway-types/src/class_hash.rs | 8 +- crates/gateway-types/src/reply.rs | 67 +++----------- crates/gateway-types/src/request.rs | 22 +---- crates/merkle-tree/src/class.rs | 6 +- crates/merkle-tree/src/contract.rs | 14 ++- crates/merkle-tree/src/contract_state.rs | 7 +- crates/merkle-tree/src/merkle_node.rs | 38 +++----- crates/merkle-tree/src/tree.rs | 90 +++++++++++-------- crates/p2p/src/behaviour.rs | 13 +-- crates/p2p/src/client/conv.rs | 86 ++++-------------- crates/p2p/src/client/peer_agnostic.rs | 35 ++------ .../p2p/src/client/peer_agnostic/fixtures.rs | 19 +--- crates/p2p/src/client/peer_agnostic/traits.rs | 9 +- crates/p2p/src/client/types.rs | 25 +----- crates/p2p_proto/src/header.rs | 8 +- crates/p2p_proto/src/receipt.rs | 12 +-- crates/p2p_proto/src/state.rs | 8 +- crates/p2p_proto/src/transaction.rs | 32 ++----- crates/p2p_stream/src/handler.rs | 10 +-- crates/p2p_stream/src/lib.rs | 11 +-- crates/p2p_stream/tests/error_reporting.rs | 12 +-- crates/p2p_stream/tests/sanity.rs | 8 +- .../examples/compute_pre0132_hashes.rs | 13 +-- crates/pathfinder/examples/feeder_gateway.rs | 15 +--- crates/pathfinder/examples/re_execute.rs | 4 +- .../examples/verify_block_hashes.rs | 5 +- crates/pathfinder/src/bin/pathfinder/main.rs | 4 +- .../src/p2p_network/sync_handlers.rs | 14 +-- .../src/p2p_network/sync_handlers/tests.rs | 34 ++----- crates/pathfinder/src/state.rs | 9 +- crates/pathfinder/src/state/block_hash.rs | 32 ++----- crates/pathfinder/src/state/sync.rs | 23 +---- crates/pathfinder/src/state/sync/l2.rs | 49 ++-------- crates/pathfinder/src/state/sync/pending.rs | 13 +-- crates/pathfinder/src/state/sync/revert.rs | 6 +- crates/pathfinder/src/sync.rs | 37 ++------ crates/pathfinder/src/sync/checkpoint.rs | 50 ++--------- .../pathfinder/src/sync/class_definitions.rs | 3 +- crates/pathfinder/src/sync/events.rs | 6 +- crates/pathfinder/src/sync/headers.rs | 12 +-- crates/pathfinder/src/sync/state_updates.rs | 33 ++----- crates/pathfinder/src/sync/track.rs | 28 ++---- crates/pathfinder/src/sync/transactions.rs | 18 +--- crates/rpc/src/dto/state_update.rs | 8 +- crates/rpc/src/executor.rs | 4 +- crates/rpc/src/felt.rs | 30 ++----- crates/rpc/src/jsonrpc.rs | 7 +- crates/rpc/src/jsonrpc/router/method.rs | 7 +- crates/rpc/src/jsonrpc/router/subscription.rs | 6 +- crates/rpc/src/jsonrpc/websocket/data.rs | 7 +- crates/rpc/src/jsonrpc/websocket/logic.rs | 23 +---- crates/rpc/src/lib.rs | 6 +- .../rpc/src/method/add_declare_transaction.rs | 49 +++------- .../method/add_deploy_account_transaction.rs | 24 ++--- .../rpc/src/method/add_invoke_transaction.rs | 12 +-- crates/rpc/src/method/call.rs | 16 +--- crates/rpc/src/method/estimate_fee.rs | 10 +-- crates/rpc/src/method/get_compiled_casm.rs | 7 +- crates/rpc/src/method/get_events.rs | 8 +- crates/rpc/src/method/get_state_update.rs | 11 +-- crates/rpc/src/method/get_storage_proof.rs | 39 ++++---- .../rpc/src/method/get_transaction_status.rs | 3 +- .../rpc/src/method/simulate_transactions.rs | 25 ++---- crates/rpc/src/method/subscribe_events.rs | 12 +-- .../method/subscribe_pending_transactions.rs | 7 +- .../method/subscribe_transaction_status.rs | 7 +- .../src/method/trace_block_transactions.rs | 14 +-- crates/rpc/src/method/trace_transaction.rs | 6 +- .../rpc/src/pathfinder/methods/get_proof.rs | 21 ++--- crates/rpc/src/test_setup.rs | 12 +-- crates/rpc/src/types.rs | 27 ++---- crates/rpc/src/types/class.rs | 3 +- .../src/v06/method/add_declare_transaction.rs | 49 +++------- .../method/add_deploy_account_transaction.rs | 24 ++--- .../src/v06/method/add_invoke_transaction.rs | 12 +-- crates/rpc/src/v06/method/call.rs | 16 +--- crates/rpc/src/v06/method/estimate_fee.rs | 21 ++--- .../src/v06/method/estimate_message_fee.rs | 19 +--- .../get_transaction_by_block_id_and_index.rs | 3 +- .../src/v06/method/get_transaction_receipt.rs | 11 +-- .../src/v06/method/get_transaction_status.rs | 3 +- .../src/v06/method/simulate_transactions.rs | 29 ++---- .../v06/method/trace_block_transactions.rs | 30 ++----- .../rpc/src/v06/method/trace_transaction.rs | 13 +-- crates/rpc/src/v06/types.rs | 10 +-- crates/rpc/src/v06/types/transaction.rs | 24 ++--- crates/serde/src/lib.rs | 13 +-- crates/storage/src/connection.rs | 5 +- crates/storage/src/connection/block.rs | 12 +-- crates/storage/src/connection/event.rs | 7 +- crates/storage/src/connection/state_update.rs | 19 +--- crates/storage/src/connection/trie.rs | 60 +++++++------ crates/storage/src/fake.rs | 28 ++---- crates/storage/src/params.rs | 58 +++--------- crates/storage/src/schema/revision_0052.rs | 11 +-- crates/storage/src/test_utils.rs | 6 +- 115 files changed, 489 insertions(+), 1575 deletions(-) create mode 100644 crates/common/src/storage_index.rs diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index ed226143c1..c3112f38f9 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -27,6 +27,7 @@ pub mod prelude; pub mod receipt; pub mod signature; pub mod state_update; +pub mod storage_index; pub mod test_utils; pub mod transaction; pub mod trie; diff --git a/crates/common/src/prelude.rs b/crates/common/src/prelude.rs index 0fda3c2135..ff2b393854 100644 --- a/crates/common/src/prelude.rs +++ b/crates/common/src/prelude.rs @@ -1,46 +1,11 @@ pub use crate::{ - BlockHash, - BlockHeader, - BlockNumber, - BlockTimestamp, - ByteCodeOffset, - CallParam, - CallResultValue, - CasmHash, - ChainId, - ClassCommitment, - ClassCommitmentLeafHash, - ClassHash, - ConstructorParam, - ContractAddress, - ContractAddressSalt, - ContractClass, - ContractNonce, - ContractRoot, - ContractStateHash, - EntryPoint, - EthereumAddress, - EventCommitment, - EventData, - EventKey, - Fee, - FromSliceError, - GasPrice, - L1ToL2MessageNonce, - L1ToL2MessagePayloadElem, - L2ToL1MessagePayloadElem, - SequencerAddress, - SierraHash, - StarknetVersion, - StateCommitment, - StateUpdate, - StorageAddress, - StorageCommitment, - StorageValue, - TransactionCommitment, - TransactionHash, - TransactionIndex, - TransactionNonce, - TransactionSignatureElem, + BlockHash, BlockHeader, BlockNumber, BlockTimestamp, ByteCodeOffset, CallParam, + CallResultValue, CasmHash, ChainId, ClassCommitment, ClassCommitmentLeafHash, ClassHash, + ConstructorParam, ContractAddress, ContractAddressSalt, ContractClass, ContractNonce, + ContractRoot, ContractStateHash, EntryPoint, EthereumAddress, EventCommitment, EventData, + EventKey, Fee, FromSliceError, GasPrice, L1ToL2MessageNonce, L1ToL2MessagePayloadElem, + L2ToL1MessagePayloadElem, SequencerAddress, SierraHash, StarknetVersion, StateCommitment, + StateUpdate, StorageAddress, StorageCommitment, StorageValue, TransactionCommitment, + TransactionHash, TransactionIndex, TransactionNonce, TransactionSignatureElem, TransactionVersion, }; diff --git a/crates/common/src/state_update.rs b/crates/common/src/state_update.rs index e44b64adf7..7a23fd1a5f 100644 --- a/crates/common/src/state_update.rs +++ b/crates/common/src/state_update.rs @@ -4,16 +4,8 @@ use std::slice; use fake::Dummy; use crate::{ - BlockHash, - CasmHash, - ClassHash, - ContractAddress, - ContractNonce, - SierraHash, - StateCommitment, - StateDiffCommitment, - StorageAddress, - StorageValue, + BlockHash, CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, StateCommitment, + StateDiffCommitment, StorageAddress, StorageValue, }; #[derive(Default, Debug, Clone, PartialEq)] @@ -518,12 +510,7 @@ mod state_diff_commitment { use super::{ContractUpdate, SystemContractUpdate}; use crate::{ - felt_bytes, - CasmHash, - ClassHash, - ContractAddress, - SierraHash, - StateDiffCommitment, + felt_bytes, CasmHash, ClassHash, ContractAddress, SierraHash, StateDiffCommitment, }; /// Compute the state diff commitment used in block commitment signatures. diff --git a/crates/common/src/storage_index.rs b/crates/common/src/storage_index.rs new file mode 100644 index 0000000000..b18843e6c1 --- /dev/null +++ b/crates/common/src/storage_index.rs @@ -0,0 +1,15 @@ +/// A newtype for the storage index of a trie node. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct StorageIndex(u64); + +impl StorageIndex { + /// Create a new StorageIndex. + pub fn new(index: u64) -> Self { + Self(index) + } + + /// Get the inner u64 value. + pub fn get(&self) -> u64 { + self.0 + } +} diff --git a/crates/common/src/test_utils.rs b/crates/common/src/test_utils.rs index 9805638ad9..588985806e 100644 --- a/crates/common/src/test_utils.rs +++ b/crates/common/src/test_utils.rs @@ -24,16 +24,7 @@ pub mod metrics { use std::sync::{Arc, RwLock}; use metrics::{ - Counter, - CounterFn, - Gauge, - Histogram, - Key, - KeyName, - Label, - Recorder, - SharedString, - Unit, + Counter, CounterFn, Gauge, Histogram, Key, KeyName, Label, Recorder, SharedString, Unit, }; /// # Purpose diff --git a/crates/common/src/transaction.rs b/crates/common/src/transaction.rs index 4490650d23..38c18ed538 100644 --- a/crates/common/src/transaction.rs +++ b/crates/common/src/transaction.rs @@ -5,11 +5,7 @@ use primitive_types::H256; use crate::prelude::*; use crate::{ - felt_bytes, - AccountDeploymentDataElem, - PaymasterDataElem, - ResourceAmount, - ResourcePricePerUnit, + felt_bytes, AccountDeploymentDataElem, PaymasterDataElem, ResourceAmount, ResourcePricePerUnit, Tip, }; diff --git a/crates/compiler/src/lib.rs b/crates/compiler/src/lib.rs index 97d5c6015e..55ca5edb68 100644 --- a/crates/compiler/src/lib.rs +++ b/crates/compiler/src/lib.rs @@ -78,8 +78,7 @@ pub fn casm_class_hash(casm_definition: &[u8]) -> anyhow::Result { mod v1_0_0_alpha6 { use anyhow::Context; use casm_compiler_v1_0_0_alpha6::allowed_libfuncs::{ - validate_compatible_sierra_version, - ListSelector, + validate_compatible_sierra_version, ListSelector, }; use casm_compiler_v1_0_0_alpha6::casm_contract_class::CasmContractClass; use casm_compiler_v1_0_0_alpha6::contract_class::ContractClass; @@ -125,8 +124,7 @@ mod v1_0_0_alpha6 { mod v1_0_0_rc0 { use anyhow::Context; use casm_compiler_v1_0_0_rc0::allowed_libfuncs::{ - validate_compatible_sierra_version, - ListSelector, + validate_compatible_sierra_version, ListSelector, }; use casm_compiler_v1_0_0_rc0::casm_contract_class::CasmContractClass; use casm_compiler_v1_0_0_rc0::contract_class::ContractClass; @@ -172,8 +170,7 @@ mod v1_0_0_rc0 { mod v1_1_1 { use anyhow::Context; use casm_compiler_v1_1_1::allowed_libfuncs::{ - validate_compatible_sierra_version, - ListSelector, + validate_compatible_sierra_version, ListSelector, }; use casm_compiler_v1_1_1::casm_contract_class::CasmContractClass; use casm_compiler_v1_1_1::contract_class::ContractClass; @@ -296,9 +293,7 @@ mod tests { mod parse_version { use rstest::rstest; use starknet_gateway_test_fixtures::class_definitions::{ - CAIRO_1_0_0_ALPHA5_SIERRA, - CAIRO_1_0_0_RC0_SIERRA, - CAIRO_1_1_0_RC0_SIERRA, + CAIRO_1_0_0_ALPHA5_SIERRA, CAIRO_1_0_0_RC0_SIERRA, CAIRO_1_1_0_RC0_SIERRA, CAIRO_2_0_0_STACK_OVERFLOW, }; @@ -361,8 +356,7 @@ mod tests { mod starknet_v0_11_2_onwards { use starknet_gateway_test_fixtures::class_definitions::{ - CAIRO_1_1_0_RC0_SIERRA, - CAIRO_2_0_0_STACK_OVERFLOW, + CAIRO_1_1_0_RC0_SIERRA, CAIRO_2_0_0_STACK_OVERFLOW, }; use super::*; diff --git a/crates/crypto/src/lib.rs b/crates/crypto/src/lib.rs index 543a4cee54..5a6e71f974 100644 --- a/crates/crypto/src/lib.rs +++ b/crates/crypto/src/lib.rs @@ -11,11 +11,5 @@ pub mod hash; pub mod signature; pub use algebra::{ - AffinePoint, - CurveOrderMontFelt, - Felt, - HexParseError, - MontFelt, - OverflowError, - ProjectivePoint, + AffinePoint, CurveOrderMontFelt, Felt, HexParseError, MontFelt, OverflowError, ProjectivePoint, }; diff --git a/crates/crypto/src/signature/mod.rs b/crates/crypto/src/signature/mod.rs index 0621d619b3..b9963a7968 100644 --- a/crates/crypto/src/signature/mod.rs +++ b/crates/crypto/src/signature/mod.rs @@ -1,10 +1,5 @@ mod ecdsa; pub use ecdsa::{ - ecdsa_sign, - ecdsa_sign_k, - ecdsa_verify, - ecdsa_verify_partial, - get_pk, - SignatureError, + ecdsa_sign, ecdsa_sign_k, ecdsa_verify, ecdsa_verify_partial, get_pk, SignatureError, }; diff --git a/crates/ethereum/src/lib.rs b/crates/ethereum/src/lib.rs index f12e435c88..cea9fbdf6d 100644 --- a/crates/ethereum/src/lib.rs +++ b/crates/ethereum/src/lib.rs @@ -10,16 +10,8 @@ use anyhow::Context; use futures::StreamExt; use pathfinder_common::transaction::L1HandlerTransaction; use pathfinder_common::{ - BlockHash, - BlockNumber, - CallParam, - ContractAddress, - EntryPoint, - EthereumChain, - L1BlockNumber, - L1TransactionHash, - StateCommitment, - TransactionNonce, + BlockHash, BlockNumber, CallParam, ContractAddress, EntryPoint, EthereumChain, L1BlockNumber, + L1TransactionHash, StateCommitment, TransactionNonce, }; use pathfinder_crypto::Felt; use primitive_types::{H160, U256}; diff --git a/crates/executor/src/error.rs b/crates/executor/src/error.rs index b32a85f4a4..2934b202a1 100644 --- a/crates/executor/src/error.rs +++ b/crates/executor/src/error.rs @@ -1,7 +1,6 @@ use blockifier::execution::errors::{ ConstructorEntryPointExecutionError, - EntryPointExecutionError as BlockifierEntryPointExecutionError, - PreExecutionError, + EntryPointExecutionError as BlockifierEntryPointExecutionError, PreExecutionError, }; use blockifier::execution::stack_trace::gen_transaction_execution_error_trace; use blockifier::state::errors::StateError; diff --git a/crates/executor/src/error_stack.rs b/crates/executor/src/error_stack.rs index 0128cfa8a7..630ffe1035 100644 --- a/crates/executor/src/error_stack.rs +++ b/crates/executor/src/error_stack.rs @@ -1,6 +1,5 @@ use blockifier::execution::stack_trace::{ - gen_transaction_execution_error_trace, - ErrorStack as BlockifierErrorStack, + gen_transaction_execution_error_trace, ErrorStack as BlockifierErrorStack, }; use blockifier::transaction::errors::TransactionExecutionError; use pathfinder_common::{ClassHash, ContractAddress, EntryPoint}; diff --git a/crates/executor/src/execution_state.rs b/crates/executor/src/execution_state.rs index 739fb46dbc..8d359c4327 100644 --- a/crates/executor/src/execution_state.rs +++ b/crates/executor/src/execution_state.rs @@ -7,12 +7,7 @@ use blockifier::context::{BlockContext, ChainInfo}; use blockifier::state::cached_state::CachedState; use blockifier::versioned_constants::VersionedConstants; use pathfinder_common::{ - contract_address, - BlockHeader, - ChainId, - ContractAddress, - L1DataAvailabilityMode, - StateUpdate, + contract_address, BlockHeader, ChainId, ContractAddress, L1DataAvailabilityMode, StateUpdate, }; use starknet_api::core::PatriciaKey; diff --git a/crates/executor/src/lib.rs b/crates/executor/src/lib.rs index a73edd1e2f..ec7c679fed 100644 --- a/crates/executor/src/lib.rs +++ b/crates/executor/src/lib.rs @@ -23,10 +23,7 @@ pub use error::{CallError, TransactionExecutionError}; pub use error_stack::{CallFrame, ErrorStack, Frame}; pub use estimate::estimate; pub use execution_state::{ - ExecutionState, - L1BlobDataAvailability, - ETH_FEE_TOKEN_ADDRESS, - STRK_FEE_TOKEN_ADDRESS, + ExecutionState, L1BlobDataAvailability, ETH_FEE_TOKEN_ADDRESS, STRK_FEE_TOKEN_ADDRESS, }; pub use felt::{IntoFelt, IntoStarkFelt}; pub use simulate::{simulate, trace, TraceCache}; diff --git a/crates/executor/src/pending.rs b/crates/executor/src/pending.rs index 1d9a632da3..6c962ca596 100644 --- a/crates/executor/src/pending.rs +++ b/crates/executor/src/pending.rs @@ -105,12 +105,7 @@ impl StateReader for PendingStateReader { mod tests { use blockifier::state::state_api::StateReader; use pathfinder_common::{ - class_hash, - contract_address, - contract_nonce, - storage_address, - storage_value, - StateUpdate, + class_hash, contract_address, contract_nonce, storage_address, storage_value, StateUpdate, }; use starknet_types_core::felt::Felt as CoreFelt; diff --git a/crates/executor/src/simulate.rs b/crates/executor/src/simulate.rs index 3656002bd8..94943c4784 100644 --- a/crates/executor/src/simulate.rs +++ b/crates/executor/src/simulate.rs @@ -8,15 +8,8 @@ use blockifier::transaction::transaction_execution::Transaction; use blockifier::transaction::transactions::ExecutableTransaction; use cached::{Cached, SizedCache}; use pathfinder_common::{ - BlockHash, - CasmHash, - ClassHash, - ContractAddress, - ContractNonce, - SierraHash, - StorageAddress, - StorageValue, - TransactionHash, + BlockHash, CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, StorageAddress, + StorageValue, TransactionHash, }; use super::error::TransactionExecutionError; @@ -25,19 +18,10 @@ use super::types::{FeeEstimate, TransactionSimulation, TransactionTrace}; use crate::error_stack::ErrorStack; use crate::transaction::transaction_hash; use crate::types::{ - DataAvailabilityResources, - DeclareTransactionTrace, - DeclaredSierraClass, - DeployAccountTransactionTrace, - DeployedContract, - ExecuteInvocation, - ExecutionResources, - FunctionInvocation, - InvokeTransactionTrace, - L1HandlerTransactionTrace, - ReplacedClass, - StateDiff, - StorageDiff, + DataAvailabilityResources, DeclareTransactionTrace, DeclaredSierraClass, + DeployAccountTransactionTrace, DeployedContract, ExecuteInvocation, ExecutionResources, + FunctionInvocation, InvokeTransactionTrace, L1HandlerTransactionTrace, ReplacedClass, + StateDiff, StorageDiff, }; use crate::IntoFelt; diff --git a/crates/executor/src/types.rs b/crates/executor/src/types.rs index fb5edb846d..39698a2995 100644 --- a/crates/executor/src/types.rs +++ b/crates/executor/src/types.rs @@ -4,13 +4,7 @@ use blockifier::blockifier::block::BlockInfo; use blockifier::execution::call_info::OrderedL2ToL1Message; use blockifier::transaction::objects::{FeeType, GasVector, TransactionExecutionInfo}; use pathfinder_common::{ - CasmHash, - ClassHash, - ContractAddress, - ContractNonce, - SierraHash, - StorageAddress, - StorageValue, + CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, StorageAddress, StorageValue, }; use pathfinder_crypto::Felt; diff --git a/crates/gateway-client/src/lib.rs b/crates/gateway-client/src/lib.rs index abf73d8f1b..e0369767ab 100644 --- a/crates/gateway-client/src/lib.rs +++ b/crates/gateway-client/src/lib.rs @@ -4,13 +4,7 @@ use std::result::Result; use std::time::Duration; use pathfinder_common::{ - BlockHash, - BlockId, - BlockNumber, - ClassHash, - PublicKey, - StateUpdate, - TransactionHash, + BlockHash, BlockId, BlockNumber, ClassHash, PublicKey, StateUpdate, TransactionHash, }; use reqwest::Url; use starknet_gateway_types::error::SequencerError; diff --git a/crates/gateway-test-fixtures/src/lib.rs b/crates/gateway-test-fixtures/src/lib.rs index 5776b1f109..406594c467 100644 --- a/crates/gateway-test-fixtures/src/lib.rs +++ b/crates/gateway-test-fixtures/src/lib.rs @@ -168,12 +168,7 @@ pub mod class_definitions { pub mod testnet { use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - CallParam, - ClassHash, - ContractAddress, - EntryPoint, - StorageAddress, - TransactionHash, + CallParam, ClassHash, ContractAddress, EntryPoint, StorageAddress, TransactionHash, }; use pathfinder_crypto::Felt; diff --git a/crates/gateway-types/src/class_hash.rs b/crates/gateway-types/src/class_hash.rs index d19b3b8ffd..bc5e32d920 100644 --- a/crates/gateway-types/src/class_hash.rs +++ b/crates/gateway-types/src/class_hash.rs @@ -60,9 +60,7 @@ pub mod from_parts { use anyhow::Result; use pathfinder_common::class_definition::{ - EntryPointType, - SelectorAndOffset, - SierraEntryPoints, + EntryPointType, SelectorAndOffset, SierraEntryPoints, }; use pathfinder_common::ClassHash; use pathfinder_crypto::Felt; @@ -501,9 +499,7 @@ mod json { use std::collections::{BTreeMap, HashMap}; use pathfinder_common::class_definition::{ - EntryPointType, - SelectorAndFunctionIndex, - SelectorAndOffset, + EntryPointType, SelectorAndFunctionIndex, SelectorAndOffset, }; pub enum ContractDefinition<'a> { diff --git a/crates/gateway-types/src/reply.rs b/crates/gateway-types/src/reply.rs index 024aad5833..9671f1abb2 100644 --- a/crates/gateway-types/src/reply.rs +++ b/crates/gateway-types/src/reply.rs @@ -1,20 +1,9 @@ //! Structures used for deserializing replies from Starkware's sequencer REST //! API. use pathfinder_common::{ - BlockCommitmentSignatureElem, - BlockHash, - BlockNumber, - BlockTimestamp, - ContractAddress, - EthereumAddress, - EventCommitment, - GasPrice, - ReceiptCommitment, - SequencerAddress, - StarknetVersion, - StateCommitment, - StateDiffCommitment, - TransactionCommitment, + BlockCommitmentSignatureElem, BlockHash, BlockNumber, BlockTimestamp, ContractAddress, + EthereumAddress, EventCommitment, GasPrice, ReceiptCommitment, SequencerAddress, + StarknetVersion, StateCommitment, StateDiffCommitment, TransactionCommitment, }; use pathfinder_serde::{EthereumAddressAsHexStr, GasPriceAsHexStr}; use serde::{Deserialize, Serialize}; @@ -239,39 +228,17 @@ pub mod transaction_status { pub mod transaction { use fake::{Dummy, Fake, Faker}; use pathfinder_common::{ - AccountDeploymentDataElem, - CallParam, - CasmHash, - ClassHash, - ConstructorParam, - ContractAddress, - ContractAddressSalt, - EntryPoint, - EthereumAddress, - Fee, - L1ToL2MessageNonce, - L1ToL2MessagePayloadElem, - L2ToL1MessagePayloadElem, - PaymasterDataElem, - ResourceAmount, - ResourcePricePerUnit, - Tip, - TransactionHash, - TransactionIndex, - TransactionNonce, - TransactionSignatureElem, - TransactionVersion, + AccountDeploymentDataElem, CallParam, CasmHash, ClassHash, ConstructorParam, + ContractAddress, ContractAddressSalt, EntryPoint, EthereumAddress, Fee, L1ToL2MessageNonce, + L1ToL2MessagePayloadElem, L2ToL1MessagePayloadElem, PaymasterDataElem, ResourceAmount, + ResourcePricePerUnit, Tip, TransactionHash, TransactionIndex, TransactionNonce, + TransactionSignatureElem, TransactionVersion, }; use pathfinder_crypto::Felt; use pathfinder_serde::{ - CallParamAsDecimalStr, - ConstructorParamAsDecimalStr, - EthereumAddressAsHexStr, - L1ToL2MessagePayloadElemAsDecimalStr, - L2ToL1MessagePayloadElemAsDecimalStr, - ResourceAmountAsHexStr, - ResourcePricePerUnitAsHexStr, - TipAsHexStr, + CallParamAsDecimalStr, ConstructorParamAsDecimalStr, EthereumAddressAsHexStr, + L1ToL2MessagePayloadElemAsDecimalStr, L2ToL1MessagePayloadElemAsDecimalStr, + ResourceAmountAsHexStr, ResourcePricePerUnitAsHexStr, TipAsHexStr, TransactionSignatureElemAsDecimalStr, }; use primitive_types::H256; @@ -2087,12 +2054,7 @@ pub mod state_update { use std::collections::{HashMap, HashSet}; use pathfinder_common::{ - CasmHash, - ClassHash, - ContractAddress, - ContractNonce, - SierraHash, - StorageAddress, + CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, StorageAddress, StorageValue, }; use serde::{Deserialize, Serialize}; @@ -2248,10 +2210,7 @@ mod tests { use primitive_types::H256; use crate::reply::state_update::{ - DeclaredSierraClass, - DeployedContract, - ReplacedClass, - StorageDiff, + DeclaredSierraClass, DeployedContract, ReplacedClass, StorageDiff, }; use crate::reply::transaction::L1HandlerTransaction; diff --git a/crates/gateway-types/src/request.rs b/crates/gateway-types/src/request.rs index 4cf781794c..c724fc8445 100644 --- a/crates/gateway-types/src/request.rs +++ b/crates/gateway-types/src/request.rs @@ -1,11 +1,6 @@ //! Structures used for serializing requests to Starkware's sequencer REST API. use pathfinder_common::{ - BlockHash, - BlockNumber, - CallParam, - ContractAddress, - Fee, - TransactionSignatureElem, + BlockHash, BlockNumber, CallParam, ContractAddress, Fee, TransactionSignatureElem, }; use serde::{Deserialize, Serialize}; @@ -123,20 +118,11 @@ pub mod add_transaction { use std::collections::HashMap; use pathfinder_common::class_definition::{ - EntryPointType, - SelectorAndFunctionIndex, - SelectorAndOffset, + EntryPointType, SelectorAndFunctionIndex, SelectorAndOffset, }; use pathfinder_common::{ - AccountDeploymentDataElem, - CasmHash, - ClassHash, - ContractAddressSalt, - EntryPoint, - PaymasterDataElem, - Tip, - TransactionNonce, - TransactionVersion, + AccountDeploymentDataElem, CasmHash, ClassHash, ContractAddressSalt, EntryPoint, + PaymasterDataElem, Tip, TransactionNonce, TransactionVersion, }; use pathfinder_serde::{CallParamAsDecimalStr, TransactionSignatureElemAsDecimalStr}; use serde_with::serde_as; diff --git a/crates/merkle-tree/src/class.rs b/crates/merkle-tree/src/class.rs index 83ca0360ff..9cd5610bd7 100644 --- a/crates/merkle-tree/src/class.rs +++ b/crates/merkle-tree/src/class.rs @@ -1,11 +1,7 @@ use anyhow::Context; use pathfinder_common::hash::PoseidonHash; use pathfinder_common::{ - BlockNumber, - ClassCommitment, - ClassCommitmentLeafHash, - ClassHash, - SierraHash, + BlockNumber, ClassCommitment, ClassCommitmentLeafHash, ClassHash, SierraHash, }; use pathfinder_crypto::Felt; use pathfinder_storage::{Transaction, TrieUpdate}; diff --git a/crates/merkle-tree/src/contract.rs b/crates/merkle-tree/src/contract.rs index 418827c2cb..90c64ed605 100644 --- a/crates/merkle-tree/src/contract.rs +++ b/crates/merkle-tree/src/contract.rs @@ -10,14 +10,10 @@ use anyhow::Context; use bitvec::prelude::Msb0; use bitvec::slice::BitSlice; use pathfinder_common::hash::PedersenHash; +use pathfinder_common::storage_index::StorageIndex; use pathfinder_common::{ - BlockNumber, - ContractAddress, - ContractRoot, - ContractStateHash, - StorageAddress, - StorageCommitment, - StorageValue, + BlockNumber, ContractAddress, ContractRoot, ContractStateHash, StorageAddress, + StorageCommitment, StorageValue, }; use pathfinder_crypto::Felt; use pathfinder_storage::{Transaction, TrieUpdate}; @@ -66,7 +62,7 @@ impl<'tx> ContractsStorageTree<'tx> { block: Some(block), contract, }; - let tree = MerkleTree::new(root); + let tree = MerkleTree::new(StorageIndex::new(root)); Ok(Self { tree, storage }) } @@ -173,7 +169,7 @@ impl<'tx> StorageCommitmentTree<'tx> { block: Some(block), }; - let tree = MerkleTree::new(root); + let tree = MerkleTree::new(StorageIndex::new(root.get())); Ok(Self { tree, storage }) } diff --git a/crates/merkle-tree/src/contract_state.rs b/crates/merkle-tree/src/contract_state.rs index 710bd82926..8ba5fd00a1 100644 --- a/crates/merkle-tree/src/contract_state.rs +++ b/crates/merkle-tree/src/contract_state.rs @@ -1,12 +1,7 @@ use anyhow::Context; use pathfinder_common::state_update::{ReverseContractUpdate, StorageRef}; use pathfinder_common::{ - BlockNumber, - ClassHash, - ContractAddress, - ContractNonce, - ContractRoot, - ContractStateHash, + BlockNumber, ClassHash, ContractAddress, ContractNonce, ContractRoot, ContractStateHash, }; use pathfinder_crypto::hash::pedersen_hash; use pathfinder_crypto::Felt; diff --git a/crates/merkle-tree/src/merkle_node.rs b/crates/merkle-tree/src/merkle_node.rs index c2827709f2..1b801c2b24 100644 --- a/crates/merkle-tree/src/merkle_node.rs +++ b/crates/merkle-tree/src/merkle_node.rs @@ -11,8 +11,8 @@ use bitvec::order::Msb0; use bitvec::prelude::BitVec; use bitvec::slice::BitSlice; use pathfinder_common::hash::FeltHash; +use pathfinder_common::storage_index::StorageIndex; use pathfinder_crypto::Felt; -use pathfinder_storage::Storage; /// A node in a Binary Merkle-Patricia Tree graph. #[derive(Clone, Debug, PartialEq)] @@ -20,7 +20,7 @@ pub enum InternalNode { /// A node that has not been fetched from storage yet. /// /// As such, all we know is its index. - Unresolved(u64), + Unresolved(StorageIndex), /// A branch node with exactly two children. Binary(BinaryNode), /// Describes a path connecting two other nodes. @@ -29,22 +29,6 @@ pub enum InternalNode { Leaf, } -/// A newtype for the storage index of a trie node. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct StorageIndex(u64); - -impl StorageIndex { - /// Create a new StorageIndex. - pub fn new(index: u64) -> Self { - Self(index) - } - - /// Get the inner u64 value. - pub fn value(&self) -> u64 { - self.0 - } -} - /// Describes the [InternalNode::Binary] variant. #[derive(Clone, Debug, PartialEq)] pub struct BinaryNode { @@ -163,7 +147,7 @@ impl InternalNode { pub fn storage_index(&self) -> Option { match self { - InternalNode::Unresolved(storage_index) => Some(StorageIndex::new(*storage_index)), + InternalNode::Unresolved(storage_index) => Some(StorageIndex::new(storage_index.get())), InternalNode::Binary(binary) => binary.storage_index, InternalNode::Edge(edge) => edge.storage_index, InternalNode::Leaf => None, @@ -248,8 +232,8 @@ mod tests { let uut = BinaryNode { storage_index: None, height: 1, - left: Rc::new(RefCell::new(InternalNode::Unresolved(1))), - right: Rc::new(RefCell::new(InternalNode::Unresolved(2))), + left: Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new(1)))), + right: Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new(2)))), }; let mut zero_key = bitvec![u8, Msb0; 1; 251]; @@ -267,8 +251,8 @@ mod tests { #[test] fn get_child() { - let left = Rc::new(RefCell::new(InternalNode::Unresolved(1))); - let right = Rc::new(RefCell::new(InternalNode::Unresolved(2))); + let left = Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new(1)))); + let right = Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new(2)))); let uut = BinaryNode { storage_index: None, @@ -336,7 +320,7 @@ mod tests { #[test] fn full() { let key = felt!("0x123456789abcdef"); - let child = Rc::new(RefCell::new(InternalNode::Unresolved(1))); + let child = Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new(1)))); let uut = EdgeNode { storage_index: None, @@ -351,7 +335,7 @@ mod tests { #[test] fn prefix() { let key = felt!("0x123456789abcdef"); - let child = Rc::new(RefCell::new(InternalNode::Unresolved(1))); + let child = Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new(1)))); let path = key.view_bits()[..45].to_bitvec(); @@ -368,7 +352,7 @@ mod tests { #[test] fn suffix() { let key = felt!("0x123456789abcdef"); - let child = Rc::new(RefCell::new(InternalNode::Unresolved(1))); + let child = Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new(1)))); let path = key.view_bits()[50..].to_bitvec(); @@ -385,7 +369,7 @@ mod tests { #[test] fn middle_slice() { let key = felt!("0x123456789abcdef"); - let child = Rc::new(RefCell::new(InternalNode::Unresolved(1))); + let child = Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new(1)))); let path = key.view_bits()[230..235].to_bitvec(); diff --git a/crates/merkle-tree/src/tree.rs b/crates/merkle-tree/src/tree.rs index 72d8b36d91..6011389316 100644 --- a/crates/merkle-tree/src/tree.rs +++ b/crates/merkle-tree/src/tree.rs @@ -59,11 +59,12 @@ use std::rc::Rc; use anyhow::Context; use bitvec::prelude::{BitSlice, BitVec, Msb0}; use pathfinder_common::hash::FeltHash; +use pathfinder_common::storage_index::StorageIndex; use pathfinder_common::trie::TrieNode; use pathfinder_crypto::Felt; use pathfinder_storage::{Node, NodeRef, StoredNode, TrieUpdate}; -use crate::merkle_node::{BinaryNode, Direction, EdgeNode, InternalNode, StorageIndex}; +use crate::merkle_node::{BinaryNode, Direction, EdgeNode, InternalNode}; use crate::storage::Storage; /// A Starknet binary Merkle-Patricia tree. @@ -79,8 +80,10 @@ pub struct MerkleTree { } impl MerkleTree { - pub fn new(root: u64) -> Self { - let root = Some(Rc::new(RefCell::new(InternalNode::Unresolved(root)))); + pub fn new(root: StorageIndex) -> Self { + let root = Some(Rc::new(RefCell::new(InternalNode::Unresolved( + StorageIndex::new(root.get()), + )))); Self { root, _hasher: std::marker::PhantomData, @@ -117,7 +120,7 @@ impl MerkleTree { // If the root node is unresolved that means that there have been no changes made // to the tree. InternalNode::Unresolved(idx) => storage - .hash(*idx) + .hash(idx.get()) .context("Fetching root node's hash")? .context("Root node's hash is missing")?, other => { @@ -165,10 +168,10 @@ impl MerkleTree { // Unresolved nodes are already committed, but we need their hash for subsequent // iterations. let hash = storage - .hash(*idx) + .hash(idx.get()) .context("Fetching stored node's hash")? .context("Stored node's hash is missing")?; - (hash, Some(NodeRef::StorageIndex(*idx))) + (hash, Some(NodeRef::StorageIndex(idx.get()))) } InternalNode::Leaf => { let hash = if let Some(value) = self.leaves.get(&path) { @@ -214,7 +217,7 @@ impl MerkleTree { }; if let Some(storage_index) = binary.storage_index { - removed.push(storage_index.value()); + removed.push(storage_index.get()); }; let node_index = added.len(); @@ -247,7 +250,7 @@ impl MerkleTree { let node_index = added.len(); added.push((hash, persisted_node)); if let Some(storage_index) = edge.storage_index { - removed.push(storage_index.value()); + removed.push(storage_index.get()); }; (hash, Some(NodeRef::Index(node_index))) @@ -371,7 +374,7 @@ impl MerkleTree { let old_node = node.replace(updated); if let Some(index) = old_node.storage_index() { - self.nodes_removed.push(index.value()); + self.nodes_removed.push(index.get()); }; } None => { @@ -438,7 +441,7 @@ impl MerkleTree { InternalNode::Binary(_) => false, _ => { if let Some(index) = node.storage_index() { - indexes_removed.push(index.value()); + indexes_removed.push(index.get()); }; true } @@ -471,7 +474,7 @@ impl MerkleTree { // Replace the old binary node with the new edge node. let old_node = node.replace(InternalNode::Edge(new_edge)); if let Some(index) = old_node.storage_index() { - self.nodes_removed.push(index.value()); + self.nodes_removed.push(index.get()); }; } None => { @@ -699,7 +702,7 @@ impl MerkleTree { let next = match current_tmp { Unresolved(idx) => { - let node = self.resolve(storage, idx, height)?; + let node = self.resolve(storage, idx.get(), height)?; current.replace(node); current } @@ -749,14 +752,20 @@ impl MerkleTree { StoredNode::Binary { left, right } => InternalNode::Binary(BinaryNode { storage_index: Some(StorageIndex::new(index)), height, - left: Rc::new(RefCell::new(InternalNode::Unresolved(left))), - right: Rc::new(RefCell::new(InternalNode::Unresolved(right))), + left: Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new( + left, + )))), + right: Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new( + right, + )))), }), StoredNode::Edge { child, path } => InternalNode::Edge(EdgeNode { storage_index: Some(StorageIndex::new(index)), height, path, - child: Rc::new(RefCell::new(InternalNode::Unresolved(child))), + child: Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new( + child, + )))), }), StoredNode::LeafBinary => InternalNode::Binary(BinaryNode { storage_index: Some(StorageIndex::new(index)), @@ -786,7 +795,7 @@ impl MerkleTree { fn merge_edges(&mut self, storage: &impl Storage, parent: &mut EdgeNode) -> anyhow::Result<()> { let resolved_child = match &*parent.child.borrow() { InternalNode::Unresolved(hash) => { - self.resolve(storage, *hash, parent.height + parent.path.len())? + self.resolve(storage, hash.get(), parent.height + parent.path.len())? } other => other.clone(), }; @@ -794,7 +803,7 @@ impl MerkleTree { if let Some(child_edge) = resolved_child.as_edge().cloned() { parent.path.extend_from_bitslice(&child_edge.path); if let Some(storage_index) = child_edge.storage_index { - self.nodes_removed.push(storage_index.value()); + self.nodes_removed.push(storage_index.get()); } parent.child = child_edge.child; } @@ -894,7 +903,7 @@ impl MerkleTree { visiting.push(VisitedNode { node: Rc::new(RefCell::new(self.resolve( storage, - *idx, + idx.get(), path.len(), )?)), path, @@ -1369,7 +1378,7 @@ mod tests { ); assert_eq!(storage.nodes.len(), 1); - let tree = TestTree::new(root.1); + let tree = TestTree::new(StorageIndex::new(root.1)); let root = commit_and_persist_without_pruning(tree, &mut storage); assert_eq!( root.0, @@ -1392,7 +1401,7 @@ mod tests { ); assert_eq!(storage.nodes.len(), 1); - let mut tree = TestTree::new(root.1); + let mut tree = TestTree::new(StorageIndex::new(root.1)); tree.set(&storage, felt!("0x1").view_bits().to_bitvec(), Felt::ZERO) .unwrap(); let root = commit_and_persist_with_pruning(tree, &mut storage); @@ -1423,7 +1432,7 @@ mod tests { let root = commit_and_persist_with_pruning(uut, &mut storage); - let uut = TestTree::new(root.1); + let uut = TestTree::new(StorageIndex::new(root.1)); assert_eq!(uut.get(&storage, key0).unwrap(), Some(val0)); assert_eq!(uut.get(&storage, key1).unwrap(), Some(val1)); @@ -1471,7 +1480,7 @@ mod tests { // Delete the final leaf; this exercises the bug as the nodes are all in storage // (unresolved). - let mut uut = TestTree::new(root.1); + let mut uut = TestTree::new(StorageIndex::new(root.1)); let key = leaves[4].0.view_bits().to_bitvec(); let val = leaves[4].1; uut.set(&storage, key, val).unwrap(); @@ -1496,25 +1505,25 @@ mod tests { uut.set(&storage, key0.clone(), val0).unwrap(); let root0 = commit_and_persist_without_pruning(uut, &mut storage); - let mut uut = TestTree::new(root0.1); + let mut uut = TestTree::new(StorageIndex::new(root0.1)); uut.set(&storage, key1.clone(), val1).unwrap(); let root1 = commit_and_persist_without_pruning(uut, &mut storage); - let mut uut = TestTree::new(root1.1); + let mut uut = TestTree::new(StorageIndex::new(root1.1)); uut.set(&storage, key2.clone(), val2).unwrap(); let root2 = commit_and_persist_without_pruning(uut, &mut storage); - let uut = TestTree::new(root0.1); + let uut = TestTree::new(StorageIndex::new(root0.1)); assert_eq!(uut.get(&storage, key0.clone()).unwrap(), Some(val0)); assert_eq!(uut.get(&storage, key1.clone()).unwrap(), None); assert_eq!(uut.get(&storage, key2.clone()).unwrap(), None); - let uut = TestTree::new(root1.1); + let uut = TestTree::new(StorageIndex::new(root1.1)); assert_eq!(uut.get(&storage, key0.clone()).unwrap(), Some(val0)); assert_eq!(uut.get(&storage, key1.clone()).unwrap(), Some(val1)); assert_eq!(uut.get(&storage, key2.clone()).unwrap(), None); - let uut = TestTree::new(root2.1); + let uut = TestTree::new(StorageIndex::new(root2.1)); assert_eq!(uut.get(&storage, key0).unwrap(), Some(val0)); assert_eq!(uut.get(&storage, key1).unwrap(), Some(val1)); assert_eq!(uut.get(&storage, key2).unwrap(), Some(val2)); @@ -1535,25 +1544,25 @@ mod tests { uut.set(&storage, key0.clone(), val0).unwrap(); let root0 = commit_and_persist_without_pruning(uut, &mut storage); - let mut uut = TestTree::new(root0.1); + let mut uut = TestTree::new(StorageIndex::new(root0.1)); uut.set(&storage, key1.clone(), val1).unwrap(); let root1 = commit_and_persist_without_pruning(uut, &mut storage); - let mut uut = TestTree::new(root0.1); + let mut uut = TestTree::new(StorageIndex::new(root0.1)); uut.set(&storage, key2.clone(), val2).unwrap(); let root2 = commit_and_persist_without_pruning(uut, &mut storage); - let uut = TestTree::new(root0.1); + let uut = TestTree::new(StorageIndex::new(root0.1)); assert_eq!(uut.get(&storage, key0.clone()).unwrap(), Some(val0)); assert_eq!(uut.get(&storage, key1.clone()).unwrap(), None); assert_eq!(uut.get(&storage, key2.clone()).unwrap(), None); - let uut = TestTree::new(root1.1); + let uut = TestTree::new(StorageIndex::new(root1.1)); assert_eq!(uut.get(&storage, key0.clone()).unwrap(), Some(val0)); assert_eq!(uut.get(&storage, key1.clone()).unwrap(), Some(val1)); assert_eq!(uut.get(&storage, key2.clone()).unwrap(), None); - let uut = TestTree::new(root2.1); + let uut = TestTree::new(StorageIndex::new(root2.1)); assert_eq!(uut.get(&storage, key0).unwrap(), Some(val0)); assert_eq!(uut.get(&storage, key1).unwrap(), None); assert_eq!(uut.get(&storage, key2).unwrap(), Some(val2)); @@ -1570,10 +1579,10 @@ mod tests { let root0 = commit_and_persist_with_pruning(uut, &mut storage); - let uut = TestTree::new(root0.1); + let uut = TestTree::new(StorageIndex::new(root0.1)); let root1 = commit_and_persist_with_pruning(uut, &mut storage); - let uut = TestTree::new(root1.1); + let uut = TestTree::new(StorageIndex::new(root1.1)); let root2 = commit_and_persist_with_pruning(uut, &mut storage); assert_eq!(root0.0, root1.0); @@ -1680,7 +1689,7 @@ mod tests { ); let root = commit_and_persist_with_pruning(uut, &mut storage); - let mut uut = TestTree::new(root.1); + let mut uut = TestTree::new(StorageIndex::new(root.1)); set!( uut, felt!("0x5c5e36947656f78c487b42ca69d96e79c01eac62f50d996f3972c9851bd5f64"), @@ -1688,7 +1697,7 @@ mod tests { ); let root = commit_and_persist_with_pruning(uut, &mut storage); - let mut uut = TestTree::new(root.1); + let mut uut = TestTree::new(StorageIndex::new(root.1)); let mut visited = vec![]; let mut visitor_fn = |node: &InternalNode, path: &BitSlice| { @@ -1704,7 +1713,7 @@ mod tests { ); let root = commit_and_persist_with_pruning(uut, &mut storage); - let mut uut = TestTree::new(root.1); + let mut uut = TestTree::new(StorageIndex::new(root.1)); let mut visited = vec![]; let mut visitor_fn = |node: &InternalNode, path: &BitSlice| { @@ -1768,7 +1777,7 @@ mod tests { assert!(tx.class_root_exists(BlockNumber::GENESIS).unwrap()); assert_eq!( tx.class_root_index(BlockNumber::GENESIS).unwrap(), - Some(root_index) + Some(StorageIndex::new(root_index)) ); // Open the tree but do no updates. @@ -1789,7 +1798,10 @@ mod tests { tx.insert_class_root(block_number, root_index_update) .unwrap(); assert!(!tx.class_root_exists(block_number).unwrap()); - assert_eq!(tx.class_root_index(block_number).unwrap(), Some(root_index)); + assert_eq!( + tx.class_root_index(block_number).unwrap(), + Some(StorageIndex::new(root_index)) + ); // Delete value let mut uut = crate::class::ClassCommitmentTree::load(&tx, block_number).unwrap(); diff --git a/crates/p2p/src/behaviour.rs b/crates/p2p/src/behaviour.rs index 3e69cc1d13..f20e62c958 100644 --- a/crates/p2p/src/behaviour.rs +++ b/crates/p2p/src/behaviour.rs @@ -11,17 +11,8 @@ use libp2p::kad::{self}; use libp2p::multiaddr::Protocol; use libp2p::swarm::behaviour::ConnectionEstablished; use libp2p::swarm::{ - CloseConnection, - ConnectionClosed, - ConnectionDenied, - ConnectionId, - DialFailure, - FromSwarm, - NetworkBehaviour, - THandler, - THandlerInEvent, - THandlerOutEvent, - ToSwarm, + CloseConnection, ConnectionClosed, ConnectionDenied, ConnectionId, DialFailure, FromSwarm, + NetworkBehaviour, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, }; use libp2p::{autonat, dcutr, identify, identity, ping, relay, Multiaddr, PeerId, StreamProtocol}; use p2p_proto::class::{ClassesRequest, ClassesResponse}; diff --git a/crates/p2p/src/client/conv.rs b/crates/p2p/src/client/conv.rs index 43f104915a..7f497075ca 100644 --- a/crates/p2p/src/client/conv.rs +++ b/crates/p2p/src/client/conv.rs @@ -10,71 +10,29 @@ use p2p_proto::class::{Cairo0Class, Cairo1Class, Cairo1EntryPoints, SierraEntryP use p2p_proto::common::{Address, Hash, Hash256}; use p2p_proto::receipt::execution_resources::BuiltinCounter; use p2p_proto::receipt::{ - DeclareTransactionReceipt, - DeployAccountTransactionReceipt, - DeployTransactionReceipt, - EthereumAddress, - InvokeTransactionReceipt, - L1HandlerTransactionReceipt, - MessageToL1, + DeclareTransactionReceipt, DeployAccountTransactionReceipt, DeployTransactionReceipt, + EthereumAddress, InvokeTransactionReceipt, L1HandlerTransactionReceipt, MessageToL1, ReceiptCommon, }; use p2p_proto::transaction::AccountSignature; use pathfinder_common::class_definition::{ - Cairo, - SelectorAndFunctionIndex, - SelectorAndOffset, - Sierra, + Cairo, SelectorAndFunctionIndex, SelectorAndOffset, Sierra, }; use pathfinder_common::event::Event; use pathfinder_common::receipt::{ - BuiltinCounters, - ExecutionResources, - ExecutionStatus, - L1Gas, - L2Gas, - L2ToL1Message, - Receipt, + BuiltinCounters, ExecutionResources, ExecutionStatus, L1Gas, L2Gas, L2ToL1Message, Receipt, }; use pathfinder_common::transaction::{ - DataAvailabilityMode, - DeclareTransactionV0V1, - DeclareTransactionV2, - DeclareTransactionV3, - DeployAccountTransactionV1, - DeployAccountTransactionV3, - DeployTransactionV0, - DeployTransactionV1, - InvokeTransactionV0, - InvokeTransactionV1, - InvokeTransactionV3, - L1HandlerTransaction, - ResourceBound, - ResourceBounds, - Transaction, - TransactionVariant, + DataAvailabilityMode, DeclareTransactionV0V1, DeclareTransactionV2, DeclareTransactionV3, + DeployAccountTransactionV1, DeployAccountTransactionV3, DeployTransactionV0, + DeployTransactionV1, InvokeTransactionV0, InvokeTransactionV1, InvokeTransactionV3, + L1HandlerTransaction, ResourceBound, ResourceBounds, Transaction, TransactionVariant, }; use pathfinder_common::{ - AccountDeploymentDataElem, - ByteCodeOffset, - CallParam, - CasmHash, - ClassHash, - ConstructorParam, - ContractAddress, - ContractAddressSalt, - EntryPoint, - EventData, - EventKey, - Fee, - GasPrice, - L1DataAvailabilityMode, - L2ToL1MessagePayloadElem, - SignedBlockHeader, - TransactionHash, - TransactionIndex, - TransactionNonce, - TransactionSignatureElem, + AccountDeploymentDataElem, ByteCodeOffset, CallParam, CasmHash, ClassHash, ConstructorParam, + ContractAddress, ContractAddressSalt, EntryPoint, EventData, EventKey, Fee, GasPrice, + L1DataAvailabilityMode, L2ToL1MessagePayloadElem, SignedBlockHeader, TransactionHash, + TransactionIndex, TransactionNonce, TransactionSignatureElem, }; use pathfinder_crypto::Felt; use serde::{Deserialize, Serialize}; @@ -450,17 +408,8 @@ impl TryFromDto for TransactionVaria Self: Sized, { use p2p_proto::transaction::TransactionVariant::{ - DeclareV0, - DeclareV1, - DeclareV2, - DeclareV3, - Deploy, - DeployAccountV1, - DeployAccountV3, - InvokeV0, - InvokeV1, - InvokeV3, - L1HandlerV0, + DeclareV0, DeclareV1, DeclareV2, DeclareV3, Deploy, DeployAccountV1, DeployAccountV3, + InvokeV0, InvokeV1, InvokeV3, L1HandlerV0, }; Ok(match dto { DeclareV0(x) => Self::DeclareV0(DeclareTransactionV0V1 { @@ -701,11 +650,8 @@ impl TryFrom<(p2p_proto::receipt::Receipt, TransactionIndex)> for crate::client: ) -> anyhow::Result { use p2p_proto::receipt::Receipt::{Declare, Deploy, DeployAccount, Invoke, L1Handler}; use p2p_proto::receipt::{ - DeclareTransactionReceipt, - DeployAccountTransactionReceipt, - DeployTransactionReceipt, - InvokeTransactionReceipt, - L1HandlerTransactionReceipt, + DeclareTransactionReceipt, DeployAccountTransactionReceipt, DeployTransactionReceipt, + InvokeTransactionReceipt, L1HandlerTransactionReceipt, }; match dto { Invoke(InvokeTransactionReceipt { common }) diff --git a/crates/p2p/src/client/peer_agnostic.rs b/crates/p2p/src/client/peer_agnostic.rs index 56cc0d3c39..0f31035097 100644 --- a/crates/p2p/src/client/peer_agnostic.rs +++ b/crates/p2p/src/client/peer_agnostic.rs @@ -13,28 +13,15 @@ use p2p_proto::common::{Direction, Iteration}; use p2p_proto::event::{EventsRequest, EventsResponse}; use p2p_proto::header::{BlockHeadersRequest, BlockHeadersResponse}; use p2p_proto::state::{ - ContractDiff, - ContractStoredValue, - DeclaredClass, - StateDiffsRequest, - StateDiffsResponse, + ContractDiff, ContractStoredValue, DeclaredClass, StateDiffsRequest, StateDiffsResponse, }; use p2p_proto::transaction::{TransactionWithReceipt, TransactionsRequest, TransactionsResponse}; use pathfinder_common::event::Event; use pathfinder_common::state_update::{ContractClassUpdate, StateUpdateData}; use pathfinder_common::transaction::Transaction; use pathfinder_common::{ - BlockNumber, - CasmHash, - ClassHash, - ContractAddress, - ContractNonce, - SierraHash, - SignedBlockHeader, - StorageAddress, - StorageValue, - TransactionHash, - TransactionIndex, + BlockNumber, CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, + SignedBlockHeader, StorageAddress, StorageValue, TransactionHash, TransactionIndex, }; use tokio::sync::{mpsc, RwLock}; @@ -45,25 +32,15 @@ mod tests; pub mod traits; use traits::{ - BlockClient, - ClassStream, - EventStream, - HeaderStream, - StateDiffStream, - StreamItem, + BlockClient, ClassStream, EventStream, HeaderStream, StateDiffStream, StreamItem, TransactionStream, }; use crate::client::conv::{CairoDefinition, FromDto, SierraDefinition, TryFromDto}; use crate::client::peer_aware; use crate::client::types::{ - ClassDefinition, - ClassDefinitionsError, - EventsForBlockByTransaction, - EventsResponseStreamFailure, - Receipt, - StateDiffsError, - TransactionData, + ClassDefinition, ClassDefinitionsError, EventsForBlockByTransaction, + EventsResponseStreamFailure, Receipt, StateDiffsError, TransactionData, }; use crate::peer_data::PeerData; diff --git a/crates/p2p/src/client/peer_agnostic/fixtures.rs b/crates/p2p/src/client/peer_agnostic/fixtures.rs index aa3fde777c..911a3b8fda 100644 --- a/crates/p2p/src/client/peer_agnostic/fixtures.rs +++ b/crates/p2p/src/client/peer_agnostic/fixtures.rs @@ -14,23 +14,12 @@ use p2p_proto::transaction::{TransactionWithReceipt, TransactionsResponse}; use pathfinder_common::event::Event; use pathfinder_common::state_update::{ContractClassUpdate, ContractUpdate, StateUpdateData}; use pathfinder_common::transaction::{ - DeployAccountTransactionV1, - DeployAccountTransactionV3, - DeployTransactionV0, - DeployTransactionV1, - TransactionVariant, + DeployAccountTransactionV1, DeployAccountTransactionV3, DeployTransactionV0, + DeployTransactionV1, TransactionVariant, }; use pathfinder_common::{ - BlockHeader, - BlockNumber, - CasmHash, - ChainId, - ClassHash, - ContractAddress, - SierraHash, - SignedBlockHeader, - TransactionHash, - TransactionIndex, + BlockHeader, BlockNumber, CasmHash, ChainId, ClassHash, ContractAddress, SierraHash, + SignedBlockHeader, TransactionHash, TransactionIndex, }; use tagged::Tagged; use tagged_debug_derive::TaggedDebug; diff --git a/crates/p2p/src/client/peer_agnostic/traits.rs b/crates/p2p/src/client/peer_agnostic/traits.rs index 035fc57ab8..3211f1a9bc 100644 --- a/crates/p2p/src/client/peer_agnostic/traits.rs +++ b/crates/p2p/src/client/peer_agnostic/traits.rs @@ -6,13 +6,8 @@ use pathfinder_common::transaction::Transaction; use pathfinder_common::{BlockNumber, SignedBlockHeader, TransactionHash}; use crate::client::types::{ - ClassDefinition, - ClassDefinitionsError, - EventsForBlockByTransaction, - EventsResponseStreamFailure, - Receipt, - StateDiffsError, - TransactionData, + ClassDefinition, ClassDefinitionsError, EventsForBlockByTransaction, + EventsResponseStreamFailure, Receipt, StateDiffsError, TransactionData, }; use crate::PeerData; diff --git a/crates/p2p/src/client/types.rs b/crates/p2p/src/client/types.rs index 53cfc5e621..213d41dd92 100644 --- a/crates/p2p/src/client/types.rs +++ b/crates/p2p/src/client/types.rs @@ -5,27 +5,10 @@ use pathfinder_common::event::Event; use pathfinder_common::receipt::{ExecutionResources, ExecutionStatus, L2ToL1Message}; use pathfinder_common::transaction::Transaction; use pathfinder_common::{ - BlockCommitmentSignature, - BlockCommitmentSignatureElem, - BlockHash, - BlockHeader, - BlockNumber, - BlockTimestamp, - ClassCommitment, - ClassHash, - EventCommitment, - Fee, - GasPrice, - ReceiptCommitment, - SequencerAddress, - SierraHash, - SignedBlockHeader, - StateCommitment, - StateDiffCommitment, - StorageCommitment, - TransactionCommitment, - TransactionHash, - TransactionIndex, + BlockCommitmentSignature, BlockCommitmentSignatureElem, BlockHash, BlockHeader, BlockNumber, + BlockTimestamp, ClassCommitment, ClassHash, EventCommitment, Fee, GasPrice, ReceiptCommitment, + SequencerAddress, SierraHash, SignedBlockHeader, StateCommitment, StateDiffCommitment, + StorageCommitment, TransactionCommitment, TransactionHash, TransactionIndex, }; use tagged::Tagged; use tagged_debug_derive::TaggedDebug; diff --git a/crates/p2p_proto/src/header.rs b/crates/p2p_proto/src/header.rs index 792953d3cf..b2719c6354 100644 --- a/crates/p2p_proto/src/header.rs +++ b/crates/p2p_proto/src/header.rs @@ -5,13 +5,7 @@ use tagged::Tagged; use tagged_debug_derive::TaggedDebug; use crate::common::{ - Address, - BlockId, - ConsensusSignature, - Hash, - Iteration, - L1DataAvailabilityMode, - Patricia, + Address, BlockId, ConsensusSignature, Hash, Iteration, L1DataAvailabilityMode, Patricia, StateDiffCommitment, }; use crate::{proto, proto_field, ToProtobuf, TryFromProtobuf}; diff --git a/crates/p2p_proto/src/receipt.rs b/crates/p2p_proto/src/receipt.rs index 5b35e57b69..38f26c2ffa 100644 --- a/crates/p2p_proto/src/receipt.rs +++ b/crates/p2p_proto/src/receipt.rs @@ -179,11 +179,7 @@ impl TryFromProtobuf for Receipt { field_name: &'static str, ) -> Result { use proto::receipt::receipt::Type::{ - Declare, - DeployAccount, - DeprecatedDeploy, - Invoke, - L1Handler, + Declare, DeployAccount, DeprecatedDeploy, Invoke, L1Handler, }; Ok(match proto_field(input.r#type, field_name)? { @@ -201,11 +197,7 @@ impl TryFromProtobuf for Receipt { impl ToProtobuf for Receipt { fn to_protobuf(self) -> proto::receipt::Receipt { use proto::receipt::receipt::Type::{ - Declare, - DeployAccount, - DeprecatedDeploy, - Invoke, - L1Handler, + Declare, DeployAccount, DeprecatedDeploy, Invoke, L1Handler, }; let r#type = Some(match self { diff --git a/crates/p2p_proto/src/state.rs b/crates/p2p_proto/src/state.rs index 055181aebf..89644632f7 100644 --- a/crates/p2p_proto/src/state.rs +++ b/crates/p2p_proto/src/state.rs @@ -53,9 +53,7 @@ pub enum StateDiffsResponse { impl ToProtobuf for StateDiffsResponse { fn to_protobuf(self) -> proto::state::StateDiffsResponse { use proto::state::state_diffs_response::StateDiffMessage::{ - ContractDiff, - DeclaredClass, - Fin, + ContractDiff, DeclaredClass, Fin, }; proto::state::StateDiffsResponse { state_diff_message: Some(match self { @@ -73,9 +71,7 @@ impl TryFromProtobuf for StateDiffsResponse { field_name: &'static str, ) -> Result { use proto::state::state_diffs_response::StateDiffMessage::{ - ContractDiff, - DeclaredClass, - Fin, + ContractDiff, DeclaredClass, Fin, }; match proto_field(input.state_diff_message, field_name)? { ContractDiff(x) => { diff --git a/crates/p2p_proto/src/transaction.rs b/crates/p2p_proto/src/transaction.rs index 2ca00b2f50..67d3c7390d 100644 --- a/crates/p2p_proto/src/transaction.rs +++ b/crates/p2p_proto/src/transaction.rs @@ -206,17 +206,8 @@ pub enum TransactionsResponse { impl ToProtobuf for TransactionVariant { fn to_protobuf(self) -> proto::transaction::transaction::Txn { use proto::transaction::transaction::Txn::{ - DeclareV0, - DeclareV1, - DeclareV2, - DeclareV3, - Deploy, - DeployAccountV1, - DeployAccountV3, - InvokeV0, - InvokeV1, - InvokeV3, - L1Handler, + DeclareV0, DeclareV1, DeclareV2, DeclareV3, Deploy, DeployAccountV1, DeployAccountV3, + InvokeV0, InvokeV1, InvokeV3, L1Handler, }; match self { Self::DeclareV0(txn) => DeclareV0(txn.to_protobuf()), @@ -240,17 +231,8 @@ impl TryFromProtobuf for TransactionVarian field_name: &'static str, ) -> Result { use proto::transaction::transaction::Txn::{ - DeclareV0, - DeclareV1, - DeclareV2, - DeclareV3, - Deploy, - DeployAccountV1, - DeployAccountV3, - InvokeV0, - InvokeV1, - InvokeV3, - L1Handler, + DeclareV0, DeclareV1, DeclareV2, DeclareV3, Deploy, DeployAccountV1, DeployAccountV3, + InvokeV0, InvokeV1, InvokeV3, L1Handler, }; match input { DeclareV0(t) => TryFromProtobuf::try_from_protobuf(t, field_name).map(Self::DeclareV0), @@ -277,8 +259,7 @@ impl TryFromProtobuf for TransactionVarian impl ToProtobuf for TransactionsResponse { fn to_protobuf(self) -> proto::transaction::TransactionsResponse { use proto::transaction::transactions_response::TransactionMessage::{ - Fin, - TransactionWithReceipt, + Fin, TransactionWithReceipt, }; proto::transaction::TransactionsResponse { transaction_message: Some(match self { @@ -295,8 +276,7 @@ impl TryFromProtobuf for TransactionsR field_name: &'static str, ) -> Result { use proto::transaction::transactions_response::TransactionMessage::{ - Fin, - TransactionWithReceipt, + Fin, TransactionWithReceipt, }; Ok(match proto_field(input.transaction_message, field_name)? { TransactionWithReceipt(t) => { diff --git a/crates/p2p_stream/src/handler.rs b/crates/p2p_stream/src/handler.rs index fbfc192e24..56c8552995 100644 --- a/crates/p2p_stream/src/handler.rs +++ b/crates/p2p_stream/src/handler.rs @@ -34,14 +34,8 @@ use std::{fmt, io}; use futures::channel::mpsc; use futures::prelude::*; use libp2p::swarm::handler::{ - ConnectionEvent, - ConnectionHandler, - ConnectionHandlerEvent, - DialUpgradeError, - FullyNegotiatedInbound, - FullyNegotiatedOutbound, - ListenUpgradeError, - StreamUpgradeError, + ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, DialUpgradeError, + FullyNegotiatedInbound, FullyNegotiatedOutbound, ListenUpgradeError, StreamUpgradeError, }; use libp2p::swarm::SubstreamProtocol; diff --git a/crates/p2p_stream/src/lib.rs b/crates/p2p_stream/src/lib.rs index 8124ea513a..54a8441526 100644 --- a/crates/p2p_stream/src/lib.rs +++ b/crates/p2p_stream/src/lib.rs @@ -69,15 +69,8 @@ use libp2p::identity::PeerId; use libp2p::swarm::behaviour::{AddressChange, ConnectionClosed, DialFailure, FromSwarm}; use libp2p::swarm::dial_opts::DialOpts; use libp2p::swarm::{ - ConnectionDenied, - ConnectionHandler, - ConnectionId, - NetworkBehaviour, - NotifyHandler, - THandler, - THandlerInEvent, - THandlerOutEvent, - ToSwarm, + ConnectionDenied, ConnectionHandler, ConnectionId, NetworkBehaviour, NotifyHandler, THandler, + THandlerInEvent, THandlerOutEvent, ToSwarm, }; use crate::handler::OutboundMessage; diff --git a/crates/p2p_stream/tests/error_reporting.rs b/crates/p2p_stream/tests/error_reporting.rs index e9f1aecbd1..59c815bec5 100644 --- a/crates/p2p_stream/tests/error_reporting.rs +++ b/crates/p2p_stream/tests/error_reporting.rs @@ -8,15 +8,9 @@ use p2p_stream::{InboundFailure, OutboundFailure}; pub mod utils; use utils::{ - new_swarm, - new_swarm_with_timeout, - wait_inbound_failure, - wait_inbound_request, - wait_inbound_response_stream_closed, - wait_no_events, - wait_outbound_failure, - wait_outbound_request_sent_awaiting_responses, - Action, + new_swarm, new_swarm_with_timeout, wait_inbound_failure, wait_inbound_request, + wait_inbound_response_stream_closed, wait_no_events, wait_outbound_failure, + wait_outbound_request_sent_awaiting_responses, Action, }; #[test_log::test(tokio::test)] diff --git a/crates/p2p_stream/tests/sanity.rs b/crates/p2p_stream/tests/sanity.rs index 636597f068..e92818f667 100644 --- a/crates/p2p_stream/tests/sanity.rs +++ b/crates/p2p_stream/tests/sanity.rs @@ -9,12 +9,8 @@ use rstest::rstest; pub mod utils; use utils::{ - new_swarm_with_timeout, - wait_inbound_request, - wait_inbound_response_stream_closed, - wait_outbound_request_sent_awaiting_responses, - wait_outbound_response_stream_closed, - Action, + new_swarm_with_timeout, wait_inbound_request, wait_inbound_response_stream_closed, + wait_outbound_request_sent_awaiting_responses, wait_outbound_response_stream_closed, Action, TestSwarm, }; diff --git a/crates/pathfinder/examples/compute_pre0132_hashes.rs b/crates/pathfinder/examples/compute_pre0132_hashes.rs index 3c49935573..9ef95c4c17 100644 --- a/crates/pathfinder/examples/compute_pre0132_hashes.rs +++ b/crates/pathfinder/examples/compute_pre0132_hashes.rs @@ -3,19 +3,12 @@ use std::num::NonZeroU32; use anyhow::{ensure, Context}; use pathfinder_common::{ - BlockHeader, - BlockNumber, - ReceiptCommitment, - StarknetVersion, - StateCommitment, + BlockHeader, BlockNumber, ReceiptCommitment, StarknetVersion, StateCommitment, StorageCommitment, }; use pathfinder_lib::state::block_hash::{ - calculate_event_commitment, - calculate_receipt_commitment, - calculate_transaction_commitment, - compute_final_hash, - BlockHeaderData, + calculate_event_commitment, calculate_receipt_commitment, calculate_transaction_commitment, + compute_final_hash, BlockHeaderData, }; const VERSION_CUTOFF: StarknetVersion = StarknetVersion::V_0_13_2; diff --git a/crates/pathfinder/examples/feeder_gateway.rs b/crates/pathfinder/examples/feeder_gateway.rs index f1c1203eca..9e3e7a1403 100644 --- a/crates/pathfinder/examples/feeder_gateway.rs +++ b/crates/pathfinder/examples/feeder_gateway.rs @@ -31,11 +31,7 @@ use anyhow::Context; use clap::{Args, Parser}; use pathfinder_common::state_update::ContractClassUpdate; use pathfinder_common::{ - BlockCommitmentSignature, - BlockCommitmentSignatureElem, - BlockHash, - BlockNumber, - Chain, + BlockCommitmentSignature, BlockCommitmentSignatureElem, BlockHash, BlockNumber, Chain, ClassHash, }; use pathfinder_lib::state::block_hash::calculate_receipt_commitment; @@ -43,10 +39,7 @@ use pathfinder_storage::BlockId; use primitive_types::H160; use serde::{Deserialize, Serialize}; use starknet_gateway_types::reply::state_update::{ - DeclaredSierraClass, - DeployedContract, - ReplacedClass, - StorageDiff, + DeclaredSierraClass, DeployedContract, ReplacedClass, StorageDiff, }; use starknet_gateway_types::reply::{GasPrices, Status}; use tracing_subscriber::prelude::*; @@ -354,9 +347,7 @@ async fn serve(cli: Cli) -> anyhow::Result<()> { fn get_chain(tx: &pathfinder_storage::Transaction<'_>) -> anyhow::Result { use pathfinder_common::consts::{ - MAINNET_GENESIS_HASH, - SEPOLIA_INTEGRATION_GENESIS_HASH, - SEPOLIA_TESTNET_GENESIS_HASH, + MAINNET_GENESIS_HASH, SEPOLIA_INTEGRATION_GENESIS_HASH, SEPOLIA_TESTNET_GENESIS_HASH, }; let genesis_hash = tx diff --git a/crates/pathfinder/examples/re_execute.rs b/crates/pathfinder/examples/re_execute.rs index 93f2e66cec..50a2d4b479 100644 --- a/crates/pathfinder/examples/re_execute.rs +++ b/crates/pathfinder/examples/re_execute.rs @@ -97,9 +97,7 @@ fn main() -> anyhow::Result<()> { fn get_chain_id(tx: &pathfinder_storage::Transaction<'_>) -> anyhow::Result { use pathfinder_common::consts::{ - MAINNET_GENESIS_HASH, - SEPOLIA_INTEGRATION_GENESIS_HASH, - SEPOLIA_TESTNET_GENESIS_HASH, + MAINNET_GENESIS_HASH, SEPOLIA_INTEGRATION_GENESIS_HASH, SEPOLIA_TESTNET_GENESIS_HASH, }; let (_, genesis_hash) = tx diff --git a/crates/pathfinder/examples/verify_block_hashes.rs b/crates/pathfinder/examples/verify_block_hashes.rs index c606825de8..0078fdc5d6 100644 --- a/crates/pathfinder/examples/verify_block_hashes.rs +++ b/crates/pathfinder/examples/verify_block_hashes.rs @@ -3,10 +3,7 @@ use std::num::NonZeroU32; use anyhow::Context; use pathfinder_common::{BlockNumber, Chain, ChainId, ReceiptCommitment}; use pathfinder_lib::state::block_hash::{ - calculate_receipt_commitment, - verify_block_hash, - BlockHeaderData, - VerifyResult, + calculate_receipt_commitment, verify_block_hash, BlockHeaderData, VerifyResult, }; /// Verify block hashes in a pathfinder database. diff --git a/crates/pathfinder/src/bin/pathfinder/main.rs b/crates/pathfinder/src/bin/pathfinder/main.rs index 641b71a07c..fd230b2922 100644 --- a/crates/pathfinder/src/bin/pathfinder/main.rs +++ b/crates/pathfinder/src/bin/pathfinder/main.rs @@ -891,9 +891,7 @@ async fn verify_database( if let Some(database_genesis) = db_genesis { use pathfinder_common::consts::{ - MAINNET_GENESIS_HASH, - SEPOLIA_INTEGRATION_GENESIS_HASH, - SEPOLIA_TESTNET_GENESIS_HASH, + MAINNET_GENESIS_HASH, SEPOLIA_INTEGRATION_GENESIS_HASH, SEPOLIA_TESTNET_GENESIS_HASH, }; let db_network = match database_genesis { diff --git a/crates/pathfinder/src/p2p_network/sync_handlers.rs b/crates/pathfinder/src/p2p_network/sync_handlers.rs index fe59b3a680..cd9a465366 100644 --- a/crates/pathfinder/src/p2p_network/sync_handlers.rs +++ b/crates/pathfinder/src/p2p_network/sync_handlers.rs @@ -3,22 +3,12 @@ use futures::SinkExt; use p2p::client::conv::ToDto; use p2p_proto::class::{Class, ClassesRequest, ClassesResponse}; use p2p_proto::common::{ - Address, - BlockNumberOrHash, - Direction, - Hash, - Iteration, - Step, - VolitionDomain, + Address, BlockNumberOrHash, Direction, Hash, Iteration, Step, VolitionDomain, }; use p2p_proto::event::{EventsRequest, EventsResponse}; use p2p_proto::header::{BlockHeadersRequest, BlockHeadersResponse}; use p2p_proto::state::{ - ContractDiff, - ContractStoredValue, - DeclaredClass, - StateDiffsRequest, - StateDiffsResponse, + ContractDiff, ContractStoredValue, DeclaredClass, StateDiffsRequest, StateDiffsResponse, }; use p2p_proto::transaction::{TransactionWithReceipt, TransactionsRequest, TransactionsResponse}; use pathfinder_common::{class_definition, BlockHash, BlockNumber, SignedBlockHeader}; diff --git a/crates/pathfinder/src/p2p_network/sync_handlers/tests.rs b/crates/pathfinder/src/p2p_network/sync_handlers/tests.rs index 36a287c1b4..496b2c7912 100644 --- a/crates/pathfinder/src/p2p_network/sync_handlers/tests.rs +++ b/crates/pathfinder/src/p2p_network/sync_handlers/tests.rs @@ -47,11 +47,7 @@ mod boundary_conditions { use super::I64_MAX; use crate::p2p_network::sync_handlers::{ - get_classes, - get_events, - get_headers, - get_state_diffs, - get_transactions, + get_classes, get_events, get_headers, get_state_diffs, get_transactions, }; mod zero_limit_yields_fin_invalid_start_yields_fin { @@ -110,32 +106,17 @@ mod prop { use p2p_proto::event::{EventsRequest, EventsResponse}; use p2p_proto::header::{BlockHeadersRequest, BlockHeadersResponse}; use p2p_proto::state::{ - ContractDiff, - ContractStoredValue, - DeclaredClass, - StateDiffsRequest, - StateDiffsResponse, + ContractDiff, ContractStoredValue, DeclaredClass, StateDiffsRequest, StateDiffsResponse, }; use p2p_proto::transaction::{ - TransactionWithReceipt, - TransactionsRequest, - TransactionsResponse, + TransactionWithReceipt, TransactionsRequest, TransactionsResponse, }; use pathfinder_common::event::Event; use pathfinder_common::state_update::SystemContractUpdate; use pathfinder_common::transaction::TransactionVariant; use pathfinder_common::{ - BlockNumber, - CasmHash, - ClassHash, - ContractAddress, - ContractNonce, - SierraHash, - SignedBlockHeader, - StorageAddress, - StorageValue, - TransactionHash, - TransactionIndex, + BlockNumber, CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, + SignedBlockHeader, StorageAddress, StorageValue, TransactionHash, TransactionIndex, }; use pathfinder_crypto::Felt; use pathfinder_storage::fake::Block; @@ -389,10 +370,7 @@ mod prop { mod workaround { use pathfinder_common::transaction::{ - EntryPointType, - InvokeTransactionV0, - L1HandlerTransaction, - TransactionVariant, + EntryPointType, InvokeTransactionV0, L1HandlerTransaction, TransactionVariant, }; use pathfinder_common::TransactionNonce; diff --git a/crates/pathfinder/src/state.rs b/crates/pathfinder/src/state.rs index a827ac7f33..6b13f35b92 100644 --- a/crates/pathfinder/src/state.rs +++ b/crates/pathfinder/src/state.rs @@ -2,12 +2,5 @@ pub mod block_hash; mod sync; pub use sync::{ - l1, - l2, - revert, - sync, - update_starknet_state, - Gossiper, - SyncContext, - RESET_DELAY_ON_FAILURE, + l1, l2, revert, sync, update_starknet_state, Gossiper, SyncContext, RESET_DELAY_ON_FAILURE, }; diff --git a/crates/pathfinder/src/state/block_hash.rs b/crates/pathfinder/src/state/block_hash.rs index 838fb59ce7..aff7747ade 100644 --- a/crates/pathfinder/src/state/block_hash.rs +++ b/crates/pathfinder/src/state/block_hash.rs @@ -7,23 +7,9 @@ use pathfinder_common::hash::{FeltHash, PedersenHash, PoseidonHash}; use pathfinder_common::receipt::{ExecutionStatus, Receipt}; use pathfinder_common::transaction::{Transaction, TransactionVariant}; use pathfinder_common::{ - felt_bytes, - BlockHash, - BlockHeader, - BlockNumber, - BlockTimestamp, - Chain, - ChainId, - EventCommitment, - GasPrice, - L1DataAvailabilityMode, - ReceiptCommitment, - SequencerAddress, - StarknetVersion, - StateCommitment, - StateDiffCommitment, - TransactionCommitment, - TransactionHash, + felt_bytes, BlockHash, BlockHeader, BlockNumber, BlockTimestamp, Chain, ChainId, + EventCommitment, GasPrice, L1DataAvailabilityMode, ReceiptCommitment, SequencerAddress, + StarknetVersion, StateCommitment, StateDiffCommitment, TransactionCommitment, TransactionHash, TransactionSignatureElem, }; use pathfinder_crypto::hash::{pedersen_hash, poseidon_hash_many, HashChain, PoseidonHasher}; @@ -807,18 +793,10 @@ mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::receipt::{ExecutionResources, L1Gas, L2ToL1Message}; use pathfinder_common::transaction::{ - EntryPointType, - InvokeTransactionV0, - InvokeTransactionV3, + EntryPointType, InvokeTransactionV0, InvokeTransactionV3, }; use pathfinder_common::{ - felt, - ContractAddress, - EventData, - EventKey, - Fee, - L2ToL1MessagePayloadElem, - TransactionHash, + felt, ContractAddress, EventData, EventKey, Fee, L2ToL1MessagePayloadElem, TransactionHash, }; use pathfinder_crypto::Felt; use starknet_gateway_test_fixtures::v0_13_2; diff --git a/crates/pathfinder/src/state/sync.rs b/crates/pathfinder/src/state/sync.rs index 9715085e4f..1f454e94e9 100644 --- a/crates/pathfinder/src/state/sync.rs +++ b/crates/pathfinder/src/state/sync.rs @@ -12,11 +12,7 @@ use anyhow::Context; use pathfinder_common::prelude::*; use pathfinder_common::state_update::StateUpdateRef; use pathfinder_common::{ - BlockCommitmentSignature, - Chain, - PublicKey, - ReceiptCommitment, - StateDiffCommitment, + BlockCommitmentSignature, Chain, PublicKey, ReceiptCommitment, StateDiffCommitment, }; use pathfinder_crypto::Felt; use pathfinder_ethereum::{EthereumApi, EthereumStateUpdate}; @@ -1268,20 +1264,9 @@ mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - felt_bytes, - BlockCommitmentSignature, - BlockCommitmentSignatureElem, - BlockHash, - BlockHeader, - BlockNumber, - ClassHash, - EventCommitment, - ReceiptCommitment, - SierraHash, - StateCommitment, - StateDiffCommitment, - StateUpdate, - TransactionCommitment, + felt_bytes, BlockCommitmentSignature, BlockCommitmentSignatureElem, BlockHash, BlockHeader, + BlockNumber, ClassHash, EventCommitment, ReceiptCommitment, SierraHash, StateCommitment, + StateDiffCommitment, StateUpdate, TransactionCommitment, }; use pathfinder_crypto::Felt; use pathfinder_rpc::SyncState; diff --git a/crates/pathfinder/src/state/sync/l2.rs b/crates/pathfinder/src/state/sync/l2.rs index 8d1908e791..2da51fa9b7 100644 --- a/crates/pathfinder/src/state/sync/l2.rs +++ b/crates/pathfinder/src/state/sync/l2.rs @@ -5,22 +5,9 @@ use anyhow::{anyhow, Context}; use futures::{StreamExt, TryStreamExt}; use pathfinder_common::state_update::{ContractClassUpdate, StateUpdateData}; use pathfinder_common::{ - BlockCommitmentSignature, - BlockHash, - BlockNumber, - CasmHash, - Chain, - ChainId, - ClassHash, - EventCommitment, - PublicKey, - ReceiptCommitment, - SierraHash, - StarknetVersion, - StateCommitment, - StateDiffCommitment, - StateUpdate, - TransactionCommitment, + BlockCommitmentSignature, BlockHash, BlockNumber, CasmHash, Chain, ChainId, ClassHash, + EventCommitment, PublicKey, ReceiptCommitment, SierraHash, StarknetVersion, StateCommitment, + StateDiffCommitment, StateUpdate, TransactionCommitment, }; use pathfinder_storage::Storage; use starknet_gateway_client::GatewayApi; @@ -30,11 +17,8 @@ use tokio::sync::mpsc; use tracing::Instrument; use crate::state::block_hash::{ - calculate_event_commitment, - calculate_receipt_commitment, - calculate_transaction_commitment, - verify_block_hash, - BlockHeaderData, + calculate_event_commitment, calculate_receipt_commitment, calculate_transaction_commitment, + verify_block_hash, BlockHeaderData, }; use crate::state::sync::class::{download_class, DownloadedClass}; use crate::state::sync::SyncEvent; @@ -1177,30 +1161,15 @@ mod tests { use assert_matches::assert_matches; use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - BlockHash, - BlockId, - BlockNumber, - BlockTimestamp, - Chain, - ChainId, - ClassHash, - ContractAddress, - GasPrice, - PublicKey, - SequencerAddress, - StarknetVersion, - StateCommitment, - StateUpdate, - StorageAddress, - StorageValue, + BlockHash, BlockId, BlockNumber, BlockTimestamp, Chain, ChainId, ClassHash, + ContractAddress, GasPrice, PublicKey, SequencerAddress, StarknetVersion, + StateCommitment, StateUpdate, StorageAddress, StorageValue, }; use pathfinder_crypto::Felt; use pathfinder_storage::StorageBuilder; use starknet_gateway_client::MockGatewayApi; use starknet_gateway_types::error::{ - KnownStarknetErrorCode, - SequencerError, - StarknetError, + KnownStarknetErrorCode, SequencerError, StarknetError, }; use starknet_gateway_types::reply; use starknet_gateway_types::reply::GasPrices; diff --git a/crates/pathfinder/src/state/sync/pending.rs b/crates/pathfinder/src/state/sync/pending.rs index 03a15b0559..41c4190ee6 100644 --- a/crates/pathfinder/src/state/sync/pending.rs +++ b/crates/pathfinder/src/state/sync/pending.rs @@ -105,22 +105,13 @@ mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::transaction::{L1HandlerTransaction, Transaction, TransactionVariant}; use pathfinder_common::{ - BlockHash, - BlockNumber, - BlockTimestamp, - GasPrice, - StarknetVersion, - StateCommitment, + BlockHash, BlockNumber, BlockTimestamp, GasPrice, StarknetVersion, StateCommitment, StateUpdate, }; use pathfinder_storage::StorageBuilder; use starknet_gateway_client::MockGatewayApi; use starknet_gateway_types::reply::{ - Block, - GasPrices, - L1DataAvailabilityMode, - PendingBlock, - Status, + Block, GasPrices, L1DataAvailabilityMode, PendingBlock, Status, }; use tokio::sync::watch; diff --git a/crates/pathfinder/src/state/sync/revert.rs b/crates/pathfinder/src/state/sync/revert.rs index 6abe0c2042..0d0e0b7bee 100644 --- a/crates/pathfinder/src/state/sync/revert.rs +++ b/crates/pathfinder/src/state/sync/revert.rs @@ -1,10 +1,6 @@ use anyhow::Context; use pathfinder_common::{ - BlockHeader, - BlockNumber, - ClassCommitment, - ClassCommitmentLeafHash, - StorageCommitment, + BlockHeader, BlockNumber, ClassCommitment, ClassCommitmentLeafHash, StorageCommitment, }; use pathfinder_merkle_tree::{ClassCommitmentTree, StorageCommitmentTree}; use pathfinder_storage::Transaction; diff --git a/crates/pathfinder/src/sync.rs b/crates/pathfinder/src/sync.rs index 0f20ec2695..68ca23d344 100644 --- a/crates/pathfinder/src/sync.rs +++ b/crates/pathfinder/src/sync.rs @@ -6,25 +6,14 @@ use anyhow::Context; use error::SyncError; use futures::{pin_mut, Stream, StreamExt}; use p2p::client::peer_agnostic::traits::{ - BlockClient, - ClassStream, - EventStream, - HeaderStream, - StateDiffStream, - StreamItem, + BlockClient, ClassStream, EventStream, HeaderStream, StateDiffStream, StreamItem, TransactionStream, }; use p2p::PeerData; use pathfinder_block_hashes::BlockHashDb; use pathfinder_common::error::AnyhowExt; use pathfinder_common::{ - block_hash, - BlockHash, - BlockNumber, - Chain, - ChainId, - PublicKey, - StarknetVersion, + block_hash, BlockHash, BlockNumber, Chain, ChainId, PublicKey, StarknetVersion, }; use pathfinder_ethereum::EthereumStateUpdate; use pathfinder_storage::Transaction; @@ -306,12 +295,8 @@ mod tests { use futures::stream; use http::header; use p2p::client::types::{ - ClassDefinition, - ClassDefinitionsError, - EventsForBlockByTransaction, - EventsResponseStreamFailure, - Receipt as P2PReceipt, - StateDiffsError, + ClassDefinition, ClassDefinitionsError, EventsForBlockByTransaction, + EventsResponseStreamFailure, Receipt as P2PReceipt, StateDiffsError, }; use p2p::libp2p::PeerId; use pathfinder_common::event::Event; @@ -319,12 +304,7 @@ mod tests { use pathfinder_common::state_update::StateUpdateData; use pathfinder_common::transaction::Transaction; use pathfinder_common::{ - BlockHeader, - BlockId, - ClassHash, - SierraHash, - SignedBlockHeader, - TransactionHash, + BlockHeader, BlockId, ClassHash, SierraHash, SignedBlockHeader, TransactionHash, }; use pathfinder_crypto::signature::ecdsa_sign; use pathfinder_crypto::Felt; @@ -339,11 +319,8 @@ mod tests { use super::*; use crate::state::block_hash::{ - calculate_event_commitment, - calculate_receipt_commitment, - calculate_transaction_commitment, - compute_final_hash, - BlockHeaderData, + calculate_event_commitment, calculate_receipt_commitment, calculate_transaction_commitment, + compute_final_hash, BlockHeaderData, }; use crate::state::update_starknet_state; diff --git a/crates/pathfinder/src/sync/checkpoint.rs b/crates/pathfinder/src/sync/checkpoint.rs index 2a76e12685..e21746f57a 100644 --- a/crates/pathfinder/src/sync/checkpoint.rs +++ b/crates/pathfinder/src/sync/checkpoint.rs @@ -6,12 +6,7 @@ use anyhow::Context; use futures::{Stream, StreamExt, TryStreamExt}; use p2p::client::conv::TryFromDto; use p2p::client::peer_agnostic::traits::{ - BlockClient, - ClassStream, - EventStream, - HeaderStream, - StateDiffStream, - StreamItem, + BlockClient, ClassStream, EventStream, HeaderStream, StateDiffStream, StreamItem, TransactionStream, }; use p2p::client::types::{ClassDefinition, EventsForBlockByTransaction, TransactionData}; @@ -23,13 +18,7 @@ use pathfinder_common::receipt::Receipt; use pathfinder_common::state_update::StateUpdateData; use pathfinder_common::transaction::{Transaction, TransactionVariant}; use pathfinder_common::{ - BlockHash, - BlockNumber, - Chain, - ChainId, - ClassHash, - PublicKey, - SignedBlockHeader, + BlockHash, BlockNumber, Chain, ChainId, ClassHash, PublicKey, SignedBlockHeader, TransactionIndex, }; use pathfinder_ethereum::EthereumStateUpdate; @@ -723,23 +712,10 @@ mod tests { use assert_matches::assert_matches; use futures::stream; use pathfinder_common::{ - public_key, - BlockCommitmentSignature, - BlockCommitmentSignatureElem, - BlockHash, - BlockHeader, - BlockTimestamp, - ClassCommitment, - EventCommitment, - GasPrice, - L1DataAvailabilityMode, - ReceiptCommitment, - SequencerAddress, - StarknetVersion, - StateCommitment, - StateDiffCommitment, - StorageCommitment, - TransactionCommitment, + public_key, BlockCommitmentSignature, BlockCommitmentSignatureElem, BlockHash, + BlockHeader, BlockTimestamp, ClassCommitment, EventCommitment, GasPrice, + L1DataAvailabilityMode, ReceiptCommitment, SequencerAddress, StarknetVersion, + StateCommitment, StateDiffCommitment, StorageCommitment, TransactionCommitment, }; use pathfinder_storage::StorageBuilder; use rstest::rstest; @@ -1403,22 +1379,14 @@ mod tests { use pathfinder_common::event::Event; use pathfinder_common::transaction::TransactionVariant; use pathfinder_common::{ - class_hash, - felt, - sierra_hash, - BlockHeader, - CasmHash, - ClassHash, - SierraHash, - SignedBlockHeader, - TransactionHash, + class_hash, felt, sierra_hash, BlockHeader, CasmHash, ClassHash, SierraHash, + SignedBlockHeader, TransactionHash, }; use pathfinder_crypto::Felt; use pathfinder_storage::fake::{self as fake_storage, Block}; use pathfinder_storage::StorageBuilder; use starknet_gateway_test_fixtures::class_definitions::{ - CAIRO_0_10_TUPLES_INTEGRATION as CAIRO, - CAIRO_0_11_SIERRA as SIERRA0, + CAIRO_0_10_TUPLES_INTEGRATION as CAIRO, CAIRO_0_11_SIERRA as SIERRA0, CAIRO_2_0_0_STACK_OVERFLOW as SIERRA2, }; use starknet_gateway_types::error::SequencerError; diff --git a/crates/pathfinder/src/sync/class_definitions.rs b/crates/pathfinder/src/sync/class_definitions.rs index 4db1522c39..30673b307f 100644 --- a/crates/pathfinder/src/sync/class_definitions.rs +++ b/crates/pathfinder/src/sync/class_definitions.rs @@ -17,8 +17,7 @@ use rayon::iter::{IntoParallelIterator, ParallelIterator}; use serde_json::de; use starknet_gateway_client::GatewayApi; use starknet_gateway_types::class_hash::from_parts::{ - compute_cairo_class_hash, - compute_sierra_class_hash, + compute_cairo_class_hash, compute_sierra_class_hash, }; use starknet_gateway_types::error::SequencerError; use starknet_gateway_types::reply::call; diff --git a/crates/pathfinder/src/sync/events.rs b/crates/pathfinder/src/sync/events.rs index 6726f77f18..aa4d6ad131 100644 --- a/crates/pathfinder/src/sync/events.rs +++ b/crates/pathfinder/src/sync/events.rs @@ -9,11 +9,7 @@ use pathfinder_common::event::Event; use pathfinder_common::receipt::Receipt; use pathfinder_common::transaction::Transaction; use pathfinder_common::{ - BlockHeader, - BlockNumber, - EventCommitment, - StarknetVersion, - TransactionHash, + BlockHeader, BlockNumber, EventCommitment, StarknetVersion, TransactionHash, }; use pathfinder_storage::Storage; use tokio::sync::mpsc; diff --git a/crates/pathfinder/src/sync/headers.rs b/crates/pathfinder/src/sync/headers.rs index a0589230a5..e3aaebd1d5 100644 --- a/crates/pathfinder/src/sync/headers.rs +++ b/crates/pathfinder/src/sync/headers.rs @@ -5,16 +5,8 @@ use p2p::libp2p::PeerId; use p2p::PeerData; use p2p_proto::header; use pathfinder_common::{ - BlockHash, - BlockHeader, - BlockNumber, - Chain, - ChainId, - ClassCommitment, - PublicKey, - SignedBlockHeader, - StarknetVersion, - StorageCommitment, + BlockHash, BlockHeader, BlockNumber, Chain, ChainId, ClassCommitment, PublicKey, + SignedBlockHeader, StarknetVersion, StorageCommitment, }; use pathfinder_storage::Storage; use tokio::task::spawn_blocking; diff --git a/crates/pathfinder/src/sync/state_updates.rs b/crates/pathfinder/src/sync/state_updates.rs index 26ba3b2e8f..ea6debaced 100644 --- a/crates/pathfinder/src/sync/state_updates.rs +++ b/crates/pathfinder/src/sync/state_updates.rs @@ -6,26 +6,12 @@ use anyhow::Context; use p2p::libp2p::PeerId; use p2p::PeerData; use pathfinder_common::state_update::{ - self, - ContractClassUpdate, - ContractUpdate, - StateUpdateData, - StateUpdateRef, + self, ContractClassUpdate, ContractUpdate, StateUpdateData, StateUpdateRef, SystemContractUpdate, }; use pathfinder_common::{ - BlockHash, - BlockHeader, - BlockNumber, - CasmHash, - ClassCommitment, - ClassHash, - ContractAddress, - SierraHash, - StarknetVersion, - StateCommitment, - StateDiffCommitment, - StateUpdate, + BlockHash, BlockHeader, BlockNumber, CasmHash, ClassCommitment, ClassHash, ContractAddress, + SierraHash, StarknetVersion, StateCommitment, StateDiffCommitment, StateUpdate, StorageCommitment, }; use pathfinder_merkle_tree::contract_state::ContractStateUpdateResult; @@ -147,19 +133,10 @@ mod multi_block { use std::collections::{HashMap, HashSet}; use pathfinder_common::state_update::{ - ContractClassUpdate, - ContractUpdateRef, - StateUpdateRef, - StorageRef, - SystemContractUpdateRef, + ContractClassUpdate, ContractUpdateRef, StateUpdateRef, StorageRef, SystemContractUpdateRef, }; use pathfinder_common::{ - CasmHash, - ClassHash, - ContractAddress, - ContractNonce, - SierraHash, - StorageAddress, + CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, StorageAddress, StorageValue, }; diff --git a/crates/pathfinder/src/sync/track.rs b/crates/pathfinder/src/sync/track.rs index 0b69f909ee..fded0da4da 100644 --- a/crates/pathfinder/src/sync/track.rs +++ b/crates/pathfinder/src/sync/track.rs @@ -7,11 +7,8 @@ use futures::{pin_mut, Stream, StreamExt, TryStreamExt}; use p2p::client::peer_agnostic::traits::{BlockClient, HeaderStream}; use p2p::client::peer_agnostic::Client as P2PClient; use p2p::client::types::{ - ClassDefinition as P2PClassDefinition, - ClassDefinitionsError, - EventsResponseStreamFailure, - StateDiffsError, - TransactionData, + ClassDefinition as P2PClassDefinition, ClassDefinitionsError, EventsResponseStreamFailure, + StateDiffsError, TransactionData, }; use p2p::libp2p::PeerId; use p2p::PeerData; @@ -20,24 +17,9 @@ use pathfinder_common::receipt::Receipt; use pathfinder_common::state_update::{DeclaredClasses, StateUpdateData}; use pathfinder_common::transaction::{Transaction, TransactionVariant}; use pathfinder_common::{ - BlockHash, - BlockHeader, - BlockNumber, - Chain, - ChainId, - ClassCommitment, - ClassHash, - EventCommitment, - PublicKey, - ReceiptCommitment, - SierraHash, - SignedBlockHeader, - StarknetVersion, - StateCommitment, - StateDiffCommitment, - StateUpdate, - StorageCommitment, - TransactionCommitment, + BlockHash, BlockHeader, BlockNumber, Chain, ChainId, ClassCommitment, ClassHash, + EventCommitment, PublicKey, ReceiptCommitment, SierraHash, SignedBlockHeader, StarknetVersion, + StateCommitment, StateDiffCommitment, StateUpdate, StorageCommitment, TransactionCommitment, TransactionHash, }; use pathfinder_storage::Storage; diff --git a/crates/pathfinder/src/sync/transactions.rs b/crates/pathfinder/src/sync/transactions.rs index c947ec9487..e4845f9e7b 100644 --- a/crates/pathfinder/src/sync/transactions.rs +++ b/crates/pathfinder/src/sync/transactions.rs @@ -7,22 +7,12 @@ use p2p::libp2p::PeerId; use p2p::PeerData; use pathfinder_common::receipt::Receipt; use pathfinder_common::transaction::{ - DeployAccountTransactionV1, - DeployAccountTransactionV3, - DeployTransactionV0, - DeployTransactionV1, - Transaction, - TransactionVariant, + DeployAccountTransactionV1, DeployAccountTransactionV3, DeployTransactionV0, + DeployTransactionV1, Transaction, TransactionVariant, }; use pathfinder_common::{ - BlockHeader, - BlockNumber, - CallParam, - ChainId, - ContractAddress, - StarknetVersion, - TransactionCommitment, - TransactionHash, + BlockHeader, BlockNumber, CallParam, ChainId, ContractAddress, StarknetVersion, + TransactionCommitment, TransactionHash, }; use pathfinder_storage::Storage; use tokio::sync::mpsc; diff --git a/crates/rpc/src/dto/state_update.rs b/crates/rpc/src/dto/state_update.rs index 0c2f2bad04..2ad8de2a02 100644 --- a/crates/rpc/src/dto/state_update.rs +++ b/crates/rpc/src/dto/state_update.rs @@ -1,13 +1,7 @@ use std::collections::HashMap; use pathfinder_common::{ - CasmHash, - ClassHash, - ContractAddress, - ContractNonce, - SierraHash, - StorageAddress, - StorageValue, + CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, StorageAddress, StorageValue, }; use crate::dto; diff --git a/crates/rpc/src/executor.rs b/crates/rpc/src/executor.rs index 4c9699738b..6ada865baa 100644 --- a/crates/rpc/src/executor.rs +++ b/crates/rpc/src/executor.rs @@ -5,9 +5,7 @@ use pathfinder_executor::{ClassInfo, IntoStarkFelt}; use starknet_api::core::PatriciaKey; use crate::types::request::{ - BroadcastedDeployAccountTransaction, - BroadcastedInvokeTransaction, - BroadcastedTransaction, + BroadcastedDeployAccountTransaction, BroadcastedInvokeTransaction, BroadcastedTransaction, }; use crate::types::SierraContractClass; diff --git a/crates/rpc/src/felt.rs b/crates/rpc/src/felt.rs index 29833ad8b9..f69fd13aae 100644 --- a/crates/rpc/src/felt.rs +++ b/crates/rpc/src/felt.rs @@ -22,31 +22,11 @@ //! ``` use pathfinder_common::{ - AccountDeploymentDataElem, - BlockHash, - CallParam, - CallResultValue, - CasmHash, - ChainId, - ClassHash, - ConstructorParam, - ContractAddress, - ContractAddressSalt, - ContractNonce, - EntryPoint, - EventData, - EventKey, - L1ToL2MessagePayloadElem, - L2ToL1MessagePayloadElem, - PaymasterDataElem, - SequencerAddress, - SierraHash, - StateCommitment, - StorageAddress, - StorageValue, - TransactionHash, - TransactionNonce, - TransactionSignatureElem, + AccountDeploymentDataElem, BlockHash, CallParam, CallResultValue, CasmHash, ChainId, ClassHash, + ConstructorParam, ContractAddress, ContractAddressSalt, ContractNonce, EntryPoint, EventData, + EventKey, L1ToL2MessagePayloadElem, L2ToL1MessagePayloadElem, PaymasterDataElem, + SequencerAddress, SierraHash, StateCommitment, StorageAddress, StorageValue, TransactionHash, + TransactionNonce, TransactionSignatureElem, }; use pathfinder_crypto::Felt; diff --git a/crates/rpc/src/jsonrpc.rs b/crates/rpc/src/jsonrpc.rs index b579b90bb6..672eaa6b48 100644 --- a/crates/rpc/src/jsonrpc.rs +++ b/crates/rpc/src/jsonrpc.rs @@ -13,12 +13,7 @@ pub use response::RpcResponse; #[cfg(test)] pub use router::{handle_json_rpc_socket, CATCH_UP_BATCH_SIZE}; pub use router::{ - rpc_handler, - CatchUp, - RpcRouter, - RpcRouterBuilder, - RpcSubscriptionFlow, - SubscriptionMessage, + rpc_handler, CatchUp, RpcRouter, RpcRouterBuilder, RpcSubscriptionFlow, SubscriptionMessage, }; use starknet_gateway_types::reply::Block; use tokio::sync::broadcast; diff --git a/crates/rpc/src/jsonrpc/router/method.rs b/crates/rpc/src/jsonrpc/router/method.rs index df37ff9b40..041d84be7d 100644 --- a/crates/rpc/src/jsonrpc/router/method.rs +++ b/crates/rpc/src/jsonrpc/router/method.rs @@ -8,12 +8,7 @@ use serde_json::value::RawValue; use tracing::Instrument; use super::{ - run_concurrently, - IntoRpcEndpoint, - RpcEndpoint, - RpcRequestError, - RpcResponses, - RpcRouter, + run_concurrently, IntoRpcEndpoint, RpcEndpoint, RpcRequestError, RpcResponses, RpcRouter, }; use crate::context::RpcContext; use crate::dto::serialize::{SerializeForVersion, Serializer}; diff --git a/crates/rpc/src/jsonrpc/router/subscription.rs b/crates/rpc/src/jsonrpc/router/subscription.rs index b293351d82..20ecad8f1c 100644 --- a/crates/rpc/src/jsonrpc/router/subscription.rs +++ b/crates/rpc/src/jsonrpc/router/subscription.rs @@ -811,11 +811,7 @@ mod tests { use crate::context::{RpcConfig, RpcContext}; use crate::dto::DeserializeForVersion; use crate::jsonrpc::{ - handle_json_rpc_socket, - CatchUp, - RpcRouter, - RpcSubscriptionFlow, - SubscriptionMessage, + handle_json_rpc_socket, CatchUp, RpcRouter, RpcSubscriptionFlow, SubscriptionMessage, }; use crate::pending::PendingWatcher; use crate::types::syncing::Syncing; diff --git a/crates/rpc/src/jsonrpc/websocket/data.rs b/crates/rpc/src/jsonrpc/websocket/data.rs index ab650a49c0..758be480d4 100644 --- a/crates/rpc/src/jsonrpc/websocket/data.rs +++ b/crates/rpc/src/jsonrpc/websocket/data.rs @@ -3,12 +3,7 @@ use std::sync::Arc; use pathfinder_common::{ - BlockHash, - BlockNumber, - ContractAddress, - EventData, - EventKey, - TransactionHash, + BlockHash, BlockNumber, ContractAddress, EventData, EventKey, TransactionHash, }; use serde::ser::Error; use serde::Deserialize; diff --git a/crates/rpc/src/jsonrpc/websocket/logic.rs b/crates/rpc/src/jsonrpc/websocket/logic.rs index 471f3475c1..b2a8e63e99 100644 --- a/crates/rpc/src/jsonrpc/websocket/logic.rs +++ b/crates/rpc/src/jsonrpc/websocket/logic.rs @@ -29,10 +29,7 @@ use crate::error::ApplicationError; use crate::jsonrpc::request::RawParams; use crate::jsonrpc::router::RpcRequestError; use crate::jsonrpc::websocket::data::{ - EventFilterParams, - ResponseEvent, - SubscriptionId, - SubscriptionItem, + EventFilterParams, ResponseEvent, SubscriptionId, SubscriptionItem, }; use crate::jsonrpc::{RequestId, RpcError, RpcRequest, RpcRouter}; use crate::{BlockHeader, PendingData, RpcVersion}; @@ -666,21 +663,9 @@ mod tests { use pathfinder_common::event::Event; use pathfinder_common::transaction::Transaction; use pathfinder_common::{ - block_hash, - event_commitment, - event_key, - receipt_commitment, - state_commitment, - state_diff_commitment, - transaction_commitment, - transaction_hash, - BlockNumber, - BlockTimestamp, - ContractAddress, - EventData, - EventKey, - GasPrice, - SequencerAddress, + block_hash, event_commitment, event_key, receipt_commitment, state_commitment, + state_diff_commitment, transaction_commitment, transaction_hash, BlockNumber, + BlockTimestamp, ContractAddress, EventData, EventKey, GasPrice, SequencerAddress, StarknetVersion, }; use pathfinder_crypto::Felt; diff --git a/crates/rpc/src/lib.rs b/crates/rpc/src/lib.rs index 5df688323a..0d7b13cbe7 100644 --- a/crates/rpc/src/lib.rs +++ b/crates/rpc/src/lib.rs @@ -257,11 +257,7 @@ pub mod test_utils { use pathfinder_common::macro_prelude::*; use pathfinder_common::prelude::*; use pathfinder_common::receipt::{ - BuiltinCounters, - ExecutionResources, - ExecutionStatus, - L2ToL1Message, - Receipt, + BuiltinCounters, ExecutionResources, ExecutionStatus, L2ToL1Message, Receipt, }; use pathfinder_common::transaction::*; use pathfinder_merkle_tree::{ClassCommitmentTree, StorageCommitmentTree}; diff --git a/crates/rpc/src/method/add_declare_transaction.rs b/crates/rpc/src/method/add_declare_transaction.rs index 449814a77a..95ea16b13e 100644 --- a/crates/rpc/src/method/add_declare_transaction.rs +++ b/crates/rpc/src/method/add_declare_transaction.rs @@ -2,9 +2,7 @@ use pathfinder_common::{ClassHash, TransactionHash}; use starknet_gateway_client::GatewayApi; use starknet_gateway_types::error::SequencerError; use starknet_gateway_types::request::add_transaction::{ - CairoContractDefinition, - ContractDefinition, - SierraContractDefinition, + CairoContractDefinition, ContractDefinition, SierraContractDefinition, }; use crate::context::RpcContext; @@ -68,18 +66,10 @@ impl From for AddDeclareTransactionError { impl From for AddDeclareTransactionError { fn from(e: SequencerError) -> Self { use starknet_gateway_types::error::KnownStarknetErrorCode::{ - ClassAlreadyDeclared, - CompilationFailed, - ContractBytecodeSizeTooLarge, - ContractClassObjectSizeTooLarge, - DuplicatedTransaction, - EntryPointNotFound, - InsufficientAccountBalance, - InsufficientMaxFee, - InvalidCompiledClassHash, - InvalidContractClassVersion, - InvalidTransactionNonce, - InvalidTransactionVersion, + ClassAlreadyDeclared, CompilationFailed, ContractBytecodeSizeTooLarge, + ContractClassObjectSizeTooLarge, DuplicatedTransaction, EntryPointNotFound, + InsufficientAccountBalance, InsufficientMaxFee, InvalidCompiledClassHash, + InvalidContractClassVersion, InvalidTransactionNonce, InvalidTransactionVersion, ValidateFailure, }; match e { @@ -303,34 +293,21 @@ mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - CasmHash, - ContractAddress, - Fee, - ResourceAmount, - ResourcePricePerUnit, - Tip, - TransactionNonce, - TransactionVersion, + CasmHash, ContractAddress, Fee, ResourceAmount, ResourcePricePerUnit, Tip, + TransactionNonce, TransactionVersion, }; use pathfinder_crypto::Felt; use starknet_gateway_test_fixtures::class_definitions::{ - CAIRO_2_0_0_STACK_OVERFLOW, - CONTRACT_DEFINITION, + CAIRO_2_0_0_STACK_OVERFLOW, CONTRACT_DEFINITION, }; use super::*; use crate::types::request::{ - BroadcastedDeclareTransaction, - BroadcastedDeclareTransactionV1, - BroadcastedDeclareTransactionV2, - BroadcastedDeclareTransactionV3, + BroadcastedDeclareTransaction, BroadcastedDeclareTransactionV1, + BroadcastedDeclareTransactionV2, BroadcastedDeclareTransactionV3, }; use crate::types::{ - CairoContractClass, - ContractClass, - DataAvailabilityMode, - ResourceBound, - ResourceBounds, + CairoContractClass, ContractClass, DataAvailabilityMode, ResourceBound, ResourceBounds, SierraContractClass, }; @@ -445,9 +422,7 @@ mod tests { #[test] fn unexpected_error_message() { use starknet_gateway_types::error::{ - KnownStarknetErrorCode, - StarknetError, - StarknetErrorCode, + KnownStarknetErrorCode, StarknetError, StarknetErrorCode, }; let starknet_error = SequencerError::StarknetError(StarknetError { code: StarknetErrorCode::Known( diff --git a/crates/rpc/src/method/add_deploy_account_transaction.rs b/crates/rpc/src/method/add_deploy_account_transaction.rs index d7e794b40a..4285e75964 100644 --- a/crates/rpc/src/method/add_deploy_account_transaction.rs +++ b/crates/rpc/src/method/add_deploy_account_transaction.rs @@ -5,8 +5,7 @@ use starknet_gateway_types::error::{KnownStarknetErrorCode, SequencerError}; use crate::context::RpcContext; use crate::types::request::{ - BroadcastedDeployAccountTransaction, - BroadcastedDeployAccountTransactionV1, + BroadcastedDeployAccountTransaction, BroadcastedDeployAccountTransactionV1, }; #[derive(Debug, PartialEq, Eq)] @@ -80,14 +79,9 @@ impl From for crate::error::ApplicationError { impl From for AddDeployAccountTransactionError { fn from(e: SequencerError) -> Self { use starknet_gateway_types::error::KnownStarknetErrorCode::{ - DuplicatedTransaction, - EntryPointNotFound, - InsufficientAccountBalance, - InsufficientMaxFee, - InvalidTransactionNonce, - InvalidTransactionVersion, - UndeclaredClass, - ValidateFailure, + DuplicatedTransaction, EntryPointNotFound, InsufficientAccountBalance, + InsufficientMaxFee, InvalidTransactionNonce, InvalidTransactionVersion, + UndeclaredClass, ValidateFailure, }; match e { SequencerError::StarknetError(e) if e.code == UndeclaredClass.into() => { @@ -237,11 +231,7 @@ impl crate::dto::serialize::SerializeForVersion for Output { mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - ResourceAmount, - ResourcePricePerUnit, - Tip, - TransactionNonce, - TransactionVersion, + ResourceAmount, ResourcePricePerUnit, Tip, TransactionNonce, TransactionVersion, }; use super::*; @@ -290,9 +280,7 @@ mod tests { #[test] fn unexpected_error_message() { use starknet_gateway_types::error::{ - KnownStarknetErrorCode, - StarknetError, - StarknetErrorCode, + KnownStarknetErrorCode, StarknetError, StarknetErrorCode, }; let starknet_error = SequencerError::StarknetError(StarknetError { code: StarknetErrorCode::Known(KnownStarknetErrorCode::TransactionLimitExceeded), diff --git a/crates/rpc/src/method/add_invoke_transaction.rs b/crates/rpc/src/method/add_invoke_transaction.rs index 562a9ccbcf..e0fb903d75 100644 --- a/crates/rpc/src/method/add_invoke_transaction.rs +++ b/crates/rpc/src/method/add_invoke_transaction.rs @@ -79,12 +79,8 @@ impl From for crate::error::ApplicationError { impl From for AddInvokeTransactionError { fn from(e: SequencerError) -> Self { use starknet_gateway_types::error::KnownStarknetErrorCode::{ - DuplicatedTransaction, - EntryPointNotFound, - InsufficientAccountBalance, - InsufficientMaxFee, - InvalidTransactionNonce, - InvalidTransactionVersion, + DuplicatedTransaction, EntryPointNotFound, InsufficientAccountBalance, + InsufficientMaxFee, InvalidTransactionNonce, InvalidTransactionVersion, ValidateFailure, }; match e { @@ -329,9 +325,7 @@ mod tests { #[test] fn unexpected_error_message() { use starknet_gateway_types::error::{ - KnownStarknetErrorCode, - StarknetError, - StarknetErrorCode, + KnownStarknetErrorCode, StarknetError, StarknetErrorCode, }; let starknet_error = SequencerError::StarknetError(StarknetError { code: StarknetErrorCode::Known(KnownStarknetErrorCode::TransactionLimitExceeded), diff --git a/crates/rpc/src/method/call.rs b/crates/rpc/src/method/call.rs index 31353c188c..45125be9a9 100644 --- a/crates/rpc/src/method/call.rs +++ b/crates/rpc/src/method/call.rs @@ -224,21 +224,11 @@ mod tests { mod in_memory { use pathfinder_common::{ - felt, - BlockHash, - BlockHeader, - BlockNumber, - BlockTimestamp, - ClassHash, - ContractAddress, - GasPrice, - StateUpdate, - StorageAddress, - StorageValue, + felt, BlockHash, BlockHeader, BlockNumber, BlockTimestamp, ClassHash, ContractAddress, + GasPrice, StateUpdate, StorageAddress, StorageValue, }; use starknet_gateway_test_fixtures::class_definitions::{ - CONTRACT_DEFINITION, - CONTRACT_DEFINITION_CLASS_HASH, + CONTRACT_DEFINITION, CONTRACT_DEFINITION_CLASS_HASH, }; use starknet_gateway_types::reply::{GasPrices, L1DataAvailabilityMode, PendingBlock}; diff --git a/crates/rpc/src/method/estimate_fee.rs b/crates/rpc/src/method/estimate_fee.rs index f94f90c862..0b3ab7b964 100644 --- a/crates/rpc/src/method/estimate_fee.rs +++ b/crates/rpc/src/method/estimate_fee.rs @@ -194,13 +194,9 @@ mod tests { use super::*; use crate::types::request::{ - BroadcastedDeclareTransaction, - BroadcastedDeclareTransactionV2, - BroadcastedInvokeTransaction, - BroadcastedInvokeTransactionV0, - BroadcastedInvokeTransactionV1, - BroadcastedInvokeTransactionV3, - BroadcastedTransaction, + BroadcastedDeclareTransaction, BroadcastedDeclareTransactionV2, + BroadcastedInvokeTransaction, BroadcastedInvokeTransactionV0, + BroadcastedInvokeTransactionV1, BroadcastedInvokeTransactionV3, BroadcastedTransaction, }; use crate::types::{ContractClass, DataAvailabilityMode, ResourceBounds, SierraContractClass}; diff --git a/crates/rpc/src/method/get_compiled_casm.rs b/crates/rpc/src/method/get_compiled_casm.rs index 393113f2e0..3a46036bbf 100644 --- a/crates/rpc/src/method/get_compiled_casm.rs +++ b/crates/rpc/src/method/get_compiled_casm.rs @@ -99,15 +99,12 @@ pub async fn get_compiled_casm(context: RpcContext, input: Input) -> Result Result Result return Err(Error::StorageProofNotSupported), @@ -324,17 +319,21 @@ pub async fn get_storage_proof(context: RpcContext, input: Input) -> Result = - ClassCommitmentTree::get_proofs(&tx, header.number, &class_hashes, class_root_idx)? - .into_iter() - .flatten() - .map(|(node, node_hash)| NodeHashToNodeMapping { - node_hash, - node: ProofNode(node), - }) - .collect::>() - .into_iter() - .collect(); + let nodes: Vec = ClassCommitmentTree::get_proofs( + &tx, + header.number, + &class_hashes, + class_root_idx.get(), + )? + .into_iter() + .flatten() + .map(|(node, node_hash)| NodeHashToNodeMapping { + node_hash, + node: ProofNode(node), + }) + .collect::>() + .into_iter() + .collect(); NodeHashToNodeMappings(nodes) } else { @@ -347,7 +346,7 @@ pub async fn get_storage_proof(context: RpcContext, input: Input) -> Result { @@ -363,7 +362,7 @@ pub async fn get_storage_proof(context: RpcContext, input: Input) -> Result Result .map_err(Error::Internal) .and_then(|tx| { use starknet_gateway_types::reply::transaction_status::{ - ExecutionStatus as GatewayExecutionStatus, - FinalityStatus as GatewayFinalityStatus, + ExecutionStatus as GatewayExecutionStatus, FinalityStatus as GatewayFinalityStatus, }; let execution_status = tx.execution_status.unwrap_or_default(); diff --git a/crates/rpc/src/method/simulate_transactions.rs b/crates/rpc/src/method/simulate_transactions.rs index 3ccee4645c..c684384d11 100644 --- a/crates/rpc/src/method/simulate_transactions.rs +++ b/crates/rpc/src/method/simulate_transactions.rs @@ -179,20 +179,13 @@ impl From for SimulateTransactionError { pub(crate) mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - felt, - BlockId, - CallParam, - ClassHash, - EntryPoint, - StarknetVersion, - StorageValue, + felt, BlockId, CallParam, ClassHash, EntryPoint, StarknetVersion, StorageValue, TransactionVersion, }; use pathfinder_crypto::Felt; use serde::Deserialize; use starknet_gateway_test_fixtures::class_definitions::{ - DUMMY_ACCOUNT_CLASS_HASH, - ERC20_CONTRACT_DEFINITION_CLASS_HASH, + DUMMY_ACCOUNT_CLASS_HASH, ERC20_CONTRACT_DEFINITION_CLASS_HASH, }; use super::simulate_transactions; @@ -200,9 +193,7 @@ pub(crate) mod tests { use crate::dto::serialize::{SerializeForVersion, Serializer}; use crate::method::get_state_update::types::{DeployedContract, Nonce, StateDiff}; use crate::types::request::{ - BroadcastedDeclareTransaction, - BroadcastedDeclareTransactionV1, - BroadcastedTransaction, + BroadcastedDeclareTransaction, BroadcastedDeclareTransactionV1, BroadcastedTransaction, }; use crate::types::ContractClass; use crate::v06::method::call::FunctionCall; @@ -497,11 +488,7 @@ pub(crate) mod tests { pub(crate) mod fixtures { use super::*; pub use crate::v06::method::simulate_transactions::tests::fixtures::{ - CASM_DEFINITION, - CASM_HASH, - DEPLOYED_CONTRACT_ADDRESS, - SIERRA_DEFINITION, - SIERRA_HASH, + CASM_DEFINITION, CASM_HASH, DEPLOYED_CONTRACT_ADDRESS, SIERRA_DEFINITION, SIERRA_HASH, UNIVERSAL_DEPLOYER_CLASS_HASH, }; @@ -516,9 +503,7 @@ pub(crate) mod tests { use super::dto::*; use super::*; use crate::method::get_state_update::types::{ - DeclaredSierraClass, - StorageDiff, - StorageEntry, + DeclaredSierraClass, StorageDiff, StorageEntry, }; const DECLARE_OVERALL_FEE: u64 = 1262; diff --git a/crates/rpc/src/method/subscribe_events.rs b/crates/rpc/src/method/subscribe_events.rs index f1b9e9a8a7..990c56380c 100644 --- a/crates/rpc/src/method/subscribe_events.rs +++ b/crates/rpc/src/method/subscribe_events.rs @@ -259,16 +259,8 @@ mod tests { use pathfinder_common::receipt::Receipt; use pathfinder_common::transaction::{Transaction, TransactionVariant}; use pathfinder_common::{ - felt, - BlockHash, - BlockHeader, - BlockNumber, - ChainId, - ContractAddress, - EventData, - EventKey, - TransactionHash, - TransactionIndex, + felt, BlockHash, BlockHeader, BlockNumber, ChainId, ContractAddress, EventData, EventKey, + TransactionHash, TransactionIndex, }; use pathfinder_crypto::Felt; use pathfinder_ethereum::EthereumClient; diff --git a/crates/rpc/src/method/subscribe_pending_transactions.rs b/crates/rpc/src/method/subscribe_pending_transactions.rs index 9fe150c366..6a11a32f76 100644 --- a/crates/rpc/src/method/subscribe_pending_transactions.rs +++ b/crates/rpc/src/method/subscribe_pending_transactions.rs @@ -141,12 +141,7 @@ mod tests { use axum::extract::ws::Message; use pathfinder_common::transaction::{DeclareTransactionV0V1, Transaction, TransactionVariant}; use pathfinder_common::{ - contract_address, - transaction_hash, - BlockNumber, - ChainId, - ContractAddress, - TransactionHash, + contract_address, transaction_hash, BlockNumber, ChainId, ContractAddress, TransactionHash, }; use pathfinder_ethereum::EthereumClient; use pathfinder_storage::StorageBuilder; diff --git a/crates/rpc/src/method/subscribe_transaction_status.rs b/crates/rpc/src/method/subscribe_transaction_status.rs index b8aca06d25..fd563b48e9 100644 --- a/crates/rpc/src/method/subscribe_transaction_status.rs +++ b/crates/rpc/src/method/subscribe_transaction_status.rs @@ -438,12 +438,7 @@ mod tests { use pathfinder_common::receipt::{ExecutionStatus, Receipt}; use pathfinder_common::transaction::Transaction; use pathfinder_common::{ - BlockHash, - BlockHeader, - BlockNumber, - ChainId, - TransactionHash, - TransactionIndex, + BlockHash, BlockHeader, BlockNumber, ChainId, TransactionHash, TransactionIndex, }; use pathfinder_crypto::Felt; use pathfinder_ethereum::{EthereumClient, EthereumStateUpdate}; diff --git a/crates/rpc/src/method/trace_block_transactions.rs b/crates/rpc/src/method/trace_block_transactions.rs index e21e5c0870..e54c386168 100644 --- a/crates/rpc/src/method/trace_block_transactions.rs +++ b/crates/rpc/src/method/trace_block_transactions.rs @@ -7,8 +7,7 @@ use starknet_gateway_client::GatewayApi; use crate::compose_executor_transaction; use crate::context::RpcContext; use crate::executor::{ - ExecutionStateError, - VERSIONS_LOWER_THAN_THIS_SHOULD_FALL_BACK_TO_FETCHING_TRACE_FROM_GATEWAY, + ExecutionStateError, VERSIONS_LOWER_THAN_THIS_SHOULD_FALL_BACK_TO_FETCHING_TRACE_FROM_GATEWAY, }; use crate::v06::method::trace_block_transactions as v06; @@ -613,15 +612,8 @@ impl From for TraceBlockTransactionsError { pub(crate) mod tests { use pathfinder_common::receipt::Receipt; use pathfinder_common::{ - block_hash, - transaction_hash, - BlockHeader, - BlockId, - GasPrice, - L1DataAvailabilityMode, - SierraHash, - StarknetVersion, - TransactionIndex, + block_hash, transaction_hash, BlockHeader, BlockId, GasPrice, L1DataAvailabilityMode, + SierraHash, StarknetVersion, TransactionIndex, }; use starknet_gateway_types::reply::GasPrices; use tokio::task::JoinSet; diff --git a/crates/rpc/src/method/trace_transaction.rs b/crates/rpc/src/method/trace_transaction.rs index d57fd0136a..d270c74f0f 100644 --- a/crates/rpc/src/method/trace_transaction.rs +++ b/crates/rpc/src/method/trace_transaction.rs @@ -6,8 +6,7 @@ use crate::compose_executor_transaction; use crate::context::RpcContext; use crate::error::{ApplicationError, TraceError}; use crate::executor::{ - ExecutionStateError, - VERSIONS_LOWER_THAN_THIS_SHOULD_FALL_BACK_TO_FETCHING_TRACE_FROM_GATEWAY, + ExecutionStateError, VERSIONS_LOWER_THAN_THIS_SHOULD_FALL_BACK_TO_FETCHING_TRACE_FROM_GATEWAY, }; use crate::method::trace_block_transactions::map_gateway_trace; use crate::v06::method::trace_transaction as v06; @@ -252,8 +251,7 @@ impl From for ApplicationError { #[cfg(test)] pub mod tests { use super::super::trace_block_transactions::tests::{ - setup_multi_tx_trace_pending_test, - setup_multi_tx_trace_test, + setup_multi_tx_trace_pending_test, setup_multi_tx_trace_test, }; use super::v06::{TraceTransactionInput, TraceTransactionOutput}; use super::*; diff --git a/crates/rpc/src/pathfinder/methods/get_proof.rs b/crates/rpc/src/pathfinder/methods/get_proof.rs index 7d4103be00..a80dfe8d7c 100644 --- a/crates/rpc/src/pathfinder/methods/get_proof.rs +++ b/crates/rpc/src/pathfinder/methods/get_proof.rs @@ -4,10 +4,7 @@ use pathfinder_common::trie::TrieNode; use pathfinder_common::BlockId; use pathfinder_crypto::Felt; use pathfinder_merkle_tree::{ - tree, - ClassCommitmentTree, - ContractsStorageTree, - StorageCommitmentTree, + tree, ClassCommitmentTree, ContractsStorageTree, StorageCommitmentTree, }; use serde::{Deserialize, Serialize}; use serde_with::skip_serializing_none; @@ -272,7 +269,7 @@ pub async fn get_proof( &tx, header.number, &input.contract_address, - storage_root_idx, + storage_root_idx.get(), )? .into_iter() .map(|(node, _)| node) @@ -398,11 +395,15 @@ pub async fn get_proof_class( // Generate a proof for this class. If the class does not exist, this will // be a "non membership" proof. - let class_proof = - ClassCommitmentTree::get_proof(&tx, header.number, input.class_hash, class_root_idx)? - .into_iter() - .map(|(node, _)| node) - .collect(); + let class_proof = ClassCommitmentTree::get_proof( + &tx, + header.number, + input.class_hash, + class_root_idx.get(), + )? + .into_iter() + .map(|(node, _)| node) + .collect(); let class_proof = ProofNodes(class_proof); diff --git a/crates/rpc/src/test_setup.rs b/crates/rpc/src/test_setup.rs index ee73a2ac76..fe049681f2 100644 --- a/crates/rpc/src/test_setup.rs +++ b/crates/rpc/src/test_setup.rs @@ -1,15 +1,7 @@ use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - felt, - BlockHash, - BlockHeader, - BlockNumber, - BlockTimestamp, - ContractAddress, - GasPrice, - StarknetVersion, - StateUpdate, - StorageAddress, + felt, BlockHash, BlockHeader, BlockNumber, BlockTimestamp, ContractAddress, GasPrice, + StarknetVersion, StateUpdate, StorageAddress, }; use pathfinder_storage::Storage; use starknet_gateway_test_fixtures::class_definitions::{DUMMY_ACCOUNT, DUMMY_ACCOUNT_CLASS_HASH}; diff --git a/crates/rpc/src/types.rs b/crates/rpc/src/types.rs index 5dcdcf82f0..de239b6a70 100644 --- a/crates/rpc/src/types.rs +++ b/crates/rpc/src/types.rs @@ -110,20 +110,9 @@ impl From for starknet_api::data_availability::DataAvailab /// Groups all strictly input types of the RPC API. pub mod request { use pathfinder_common::{ - AccountDeploymentDataElem, - CallParam, - CasmHash, - ChainId, - ClassHash, - ContractAddress, - ContractAddressSalt, - EntryPoint, - Fee, - PaymasterDataElem, - Tip, - TransactionNonce, - TransactionSignatureElem, - TransactionVersion, + AccountDeploymentDataElem, CallParam, CasmHash, ChainId, ClassHash, ContractAddress, + ContractAddressSalt, EntryPoint, Fee, PaymasterDataElem, Tip, TransactionNonce, + TransactionSignatureElem, TransactionVersion, }; use serde::de::Error; use serde::Deserialize; @@ -837,14 +826,8 @@ pub mod request { use super::super::*; use crate::dto::DeserializeForVersion; use crate::types::{ - CairoContractClass, - ContractEntryPoints, - DataAvailabilityMode, - ResourceBound, - ResourceBounds, - SierraContractClass, - SierraEntryPoint, - SierraEntryPoints, + CairoContractClass, ContractEntryPoints, DataAvailabilityMode, ResourceBound, + ResourceBounds, SierraContractClass, SierraEntryPoint, SierraEntryPoints, }; #[test] diff --git a/crates/rpc/src/types/class.rs b/crates/rpc/src/types/class.rs index ef2efa3849..c81d7e0a80 100644 --- a/crates/rpc/src/types/class.rs +++ b/crates/rpc/src/types/class.rs @@ -532,8 +532,7 @@ mod tests { mod declare_class_hash { use starknet_gateway_test_fixtures::class_definitions::{ - CAIRO_0_11_SIERRA, - CONTRACT_DEFINITION, + CAIRO_0_11_SIERRA, CONTRACT_DEFINITION, }; use starknet_gateway_types::class_hash::compute_class_hash; diff --git a/crates/rpc/src/v06/method/add_declare_transaction.rs b/crates/rpc/src/v06/method/add_declare_transaction.rs index 8c08323b4b..7850b34347 100644 --- a/crates/rpc/src/v06/method/add_declare_transaction.rs +++ b/crates/rpc/src/v06/method/add_declare_transaction.rs @@ -2,9 +2,7 @@ use pathfinder_common::{ClassHash, TransactionHash}; use starknet_gateway_client::GatewayApi; use starknet_gateway_types::error::SequencerError; use starknet_gateway_types::request::add_transaction::{ - CairoContractDefinition, - ContractDefinition, - SierraContractDefinition, + CairoContractDefinition, ContractDefinition, SierraContractDefinition, }; use crate::context::RpcContext; @@ -69,18 +67,10 @@ impl From for AddDeclareTransactionError { impl From for AddDeclareTransactionError { fn from(e: SequencerError) -> Self { use starknet_gateway_types::error::KnownStarknetErrorCode::{ - ClassAlreadyDeclared, - CompilationFailed, - ContractBytecodeSizeTooLarge, - ContractClassObjectSizeTooLarge, - DuplicatedTransaction, - EntryPointNotFound, - InsufficientAccountBalance, - InsufficientMaxFee, - InvalidCompiledClassHash, - InvalidContractClassVersion, - InvalidTransactionNonce, - InvalidTransactionVersion, + ClassAlreadyDeclared, CompilationFailed, ContractBytecodeSizeTooLarge, + ContractClassObjectSizeTooLarge, DuplicatedTransaction, EntryPointNotFound, + InsufficientAccountBalance, InsufficientMaxFee, InvalidCompiledClassHash, + InvalidContractClassVersion, InvalidTransactionNonce, InvalidTransactionVersion, ValidateFailure, }; match e { @@ -275,34 +265,21 @@ mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - CasmHash, - ContractAddress, - Fee, - ResourceAmount, - ResourcePricePerUnit, - Tip, - TransactionNonce, - TransactionVersion, + CasmHash, ContractAddress, Fee, ResourceAmount, ResourcePricePerUnit, Tip, + TransactionNonce, TransactionVersion, }; use pathfinder_crypto::Felt; use starknet_gateway_test_fixtures::class_definitions::{ - CAIRO_2_0_0_STACK_OVERFLOW, - CONTRACT_DEFINITION, + CAIRO_2_0_0_STACK_OVERFLOW, CONTRACT_DEFINITION, }; use super::*; use crate::types::request::{ - BroadcastedDeclareTransaction, - BroadcastedDeclareTransactionV1, - BroadcastedDeclareTransactionV2, - BroadcastedDeclareTransactionV3, + BroadcastedDeclareTransaction, BroadcastedDeclareTransactionV1, + BroadcastedDeclareTransactionV2, BroadcastedDeclareTransactionV3, }; use crate::types::{ - CairoContractClass, - ContractClass, - DataAvailabilityMode, - ResourceBound, - ResourceBounds, + CairoContractClass, ContractClass, DataAvailabilityMode, ResourceBound, ResourceBounds, SierraContractClass, }; @@ -414,9 +391,7 @@ mod tests { #[test] fn unexpected_error_message() { use starknet_gateway_types::error::{ - KnownStarknetErrorCode, - StarknetError, - StarknetErrorCode, + KnownStarknetErrorCode, StarknetError, StarknetErrorCode, }; let starknet_error = SequencerError::StarknetError(StarknetError { code: StarknetErrorCode::Known( diff --git a/crates/rpc/src/v06/method/add_deploy_account_transaction.rs b/crates/rpc/src/v06/method/add_deploy_account_transaction.rs index 4d4839b3e9..4960784199 100644 --- a/crates/rpc/src/v06/method/add_deploy_account_transaction.rs +++ b/crates/rpc/src/v06/method/add_deploy_account_transaction.rs @@ -5,8 +5,7 @@ use starknet_gateway_types::error::{KnownStarknetErrorCode, SequencerError}; use crate::context::RpcContext; use crate::felt::{RpcFelt, RpcFelt251}; use crate::types::request::{ - BroadcastedDeployAccountTransaction, - BroadcastedDeployAccountTransactionV1, + BroadcastedDeployAccountTransaction, BroadcastedDeployAccountTransactionV1, }; #[derive(serde::Deserialize, Debug, PartialEq, Eq)] @@ -70,14 +69,9 @@ impl From for crate::error::ApplicationError { impl From for AddDeployAccountTransactionError { fn from(e: SequencerError) -> Self { use starknet_gateway_types::error::KnownStarknetErrorCode::{ - DuplicatedTransaction, - EntryPointNotFound, - InsufficientAccountBalance, - InsufficientMaxFee, - InvalidTransactionNonce, - InvalidTransactionVersion, - UndeclaredClass, - ValidateFailure, + DuplicatedTransaction, EntryPointNotFound, InsufficientAccountBalance, + InsufficientMaxFee, InvalidTransactionNonce, InvalidTransactionVersion, + UndeclaredClass, ValidateFailure, }; match e { SequencerError::StarknetError(e) if e.code == UndeclaredClass.into() => { @@ -209,11 +203,7 @@ pub(crate) async fn add_deploy_account_transaction_impl( mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - ResourceAmount, - ResourcePricePerUnit, - Tip, - TransactionNonce, - TransactionVersion, + ResourceAmount, ResourcePricePerUnit, Tip, TransactionNonce, TransactionVersion, }; use super::*; @@ -258,9 +248,7 @@ mod tests { #[test] fn unexpected_error_message() { use starknet_gateway_types::error::{ - KnownStarknetErrorCode, - StarknetError, - StarknetErrorCode, + KnownStarknetErrorCode, StarknetError, StarknetErrorCode, }; let starknet_error = SequencerError::StarknetError(StarknetError { code: StarknetErrorCode::Known(KnownStarknetErrorCode::TransactionLimitExceeded), diff --git a/crates/rpc/src/v06/method/add_invoke_transaction.rs b/crates/rpc/src/v06/method/add_invoke_transaction.rs index a1c480ff5f..32f938cccd 100644 --- a/crates/rpc/src/v06/method/add_invoke_transaction.rs +++ b/crates/rpc/src/v06/method/add_invoke_transaction.rs @@ -68,12 +68,8 @@ impl From for crate::error::ApplicationError { impl From for AddInvokeTransactionError { fn from(e: SequencerError) -> Self { use starknet_gateway_types::error::KnownStarknetErrorCode::{ - DuplicatedTransaction, - EntryPointNotFound, - InsufficientAccountBalance, - InsufficientMaxFee, - InvalidTransactionNonce, - InvalidTransactionVersion, + DuplicatedTransaction, EntryPointNotFound, InsufficientAccountBalance, + InsufficientMaxFee, InvalidTransactionNonce, InvalidTransactionVersion, ValidateFailure, }; match e { @@ -300,9 +296,7 @@ mod tests { #[test] fn unexpected_error_message() { use starknet_gateway_types::error::{ - KnownStarknetErrorCode, - StarknetError, - StarknetErrorCode, + KnownStarknetErrorCode, StarknetError, StarknetErrorCode, }; let starknet_error = SequencerError::StarknetError(StarknetError { code: StarknetErrorCode::Known(KnownStarknetErrorCode::TransactionLimitExceeded), diff --git a/crates/rpc/src/v06/method/call.rs b/crates/rpc/src/v06/method/call.rs index 8403d410f6..7d3f8ca319 100644 --- a/crates/rpc/src/v06/method/call.rs +++ b/crates/rpc/src/v06/method/call.rs @@ -205,21 +205,11 @@ mod tests { mod in_memory { use pathfinder_common::{ - felt, - BlockHash, - BlockHeader, - BlockNumber, - BlockTimestamp, - ClassHash, - ContractAddress, - GasPrice, - StateUpdate, - StorageAddress, - StorageValue, + felt, BlockHash, BlockHeader, BlockNumber, BlockTimestamp, ClassHash, ContractAddress, + GasPrice, StateUpdate, StorageAddress, StorageValue, }; use starknet_gateway_test_fixtures::class_definitions::{ - CONTRACT_DEFINITION, - CONTRACT_DEFINITION_CLASS_HASH, + CONTRACT_DEFINITION, CONTRACT_DEFINITION_CLASS_HASH, }; use starknet_gateway_types::reply::{GasPrices, L1DataAvailabilityMode, PendingBlock}; diff --git a/crates/rpc/src/v06/method/estimate_fee.rs b/crates/rpc/src/v06/method/estimate_fee.rs index fc24bcec86..02a0786378 100644 --- a/crates/rpc/src/v06/method/estimate_fee.rs +++ b/crates/rpc/src/v06/method/estimate_fee.rs @@ -219,14 +219,8 @@ pub async fn estimate_fee_impl( #[cfg(test)] pub(crate) mod tests { use pathfinder_common::{ - felt, - BlockHash, - CallParam, - ContractAddress, - Fee, - TransactionNonce, - TransactionSignatureElem, - TransactionVersion, + felt, BlockHash, CallParam, ContractAddress, Fee, TransactionNonce, + TransactionSignatureElem, TransactionVersion, }; use super::*; @@ -320,17 +314,12 @@ pub(crate) mod tests { use super::*; use crate::types::request::{ - BroadcastedDeclareTransaction, - BroadcastedDeclareTransactionV2, - BroadcastedInvokeTransactionV0, - BroadcastedInvokeTransactionV1, + BroadcastedDeclareTransaction, BroadcastedDeclareTransactionV2, + BroadcastedInvokeTransactionV0, BroadcastedInvokeTransactionV1, BroadcastedInvokeTransactionV3, }; use crate::types::{ - ContractClass, - DataAvailabilityMode, - ResourceBounds, - SierraContractClass, + ContractClass, DataAvailabilityMode, ResourceBounds, SierraContractClass, }; use crate::PendingData; diff --git a/crates/rpc/src/v06/method/estimate_message_fee.rs b/crates/rpc/src/v06/method/estimate_message_fee.rs index 57174b4b62..46b84ceeca 100644 --- a/crates/rpc/src/v06/method/estimate_message_fee.rs +++ b/crates/rpc/src/v06/method/estimate_message_fee.rs @@ -2,13 +2,7 @@ use std::sync::Arc; use anyhow::Context; use pathfinder_common::{ - BlockId, - CallParam, - ChainId, - ContractAddress, - EntryPoint, - EthereumAddress, - TransactionNonce, + BlockId, CallParam, ChainId, ContractAddress, EntryPoint, EthereumAddress, TransactionNonce, }; use pathfinder_crypto::Felt; use pathfinder_executor::{ExecutionState, IntoStarkFelt, L1BlobDataAvailability}; @@ -240,19 +234,12 @@ fn create_executor_transaction( mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - felt, - BlockHash, - BlockHeader, - BlockNumber, - BlockTimestamp, - GasPrice, - StateUpdate, + felt, BlockHash, BlockHeader, BlockNumber, BlockTimestamp, GasPrice, StateUpdate, }; use primitive_types::H160; use serde::Deserialize; use starknet_gateway_test_fixtures::class_definitions::{ - CAIRO_1_1_0_BALANCE_CASM_JSON, - CAIRO_1_1_0_BALANCE_SIERRA_JSON, + CAIRO_1_1_0_BALANCE_CASM_JSON, CAIRO_1_1_0_BALANCE_SIERRA_JSON, }; use tempfile::tempdir; diff --git a/crates/rpc/src/v06/method/get_transaction_by_block_id_and_index.rs b/crates/rpc/src/v06/method/get_transaction_by_block_id_and_index.rs index f9bc501f2f..6d34389582 100644 --- a/crates/rpc/src/v06/method/get_transaction_by_block_id_and_index.rs +++ b/crates/rpc/src/v06/method/get_transaction_by_block_id_and_index.rs @@ -1,8 +1,7 @@ use crate::context::RpcContext; use crate::method::get_transaction_by_block_id_and_index::{ get_transaction_by_block_id_and_index as get_transaction_by_block_id_and_index_impl, - GetTransactionByBlockIdAndIndexError, - Input, + GetTransactionByBlockIdAndIndexError, Input, }; use crate::v06::types::TransactionWithHash; diff --git a/crates/rpc/src/v06/method/get_transaction_receipt.rs b/crates/rpc/src/v06/method/get_transaction_receipt.rs index eb5f2f6788..b6706eb256 100644 --- a/crates/rpc/src/v06/method/get_transaction_receipt.rs +++ b/crates/rpc/src/v06/method/get_transaction_receipt.rs @@ -95,15 +95,8 @@ pub async fn get_transaction_receipt_impl( pub mod types { use pathfinder_common::{ - BlockHash, - BlockNumber, - ContractAddress, - EventData, - EventKey, - Fee, - L2ToL1MessagePayloadElem, - TransactionHash, - TransactionVersion, + BlockHash, BlockNumber, ContractAddress, EventData, EventKey, Fee, + L2ToL1MessagePayloadElem, TransactionHash, TransactionVersion, }; use pathfinder_serde::H256AsNoLeadingZerosHexStr; use primitive_types::H256; diff --git a/crates/rpc/src/v06/method/get_transaction_status.rs b/crates/rpc/src/v06/method/get_transaction_status.rs index 8b962fa3dd..cf15a9396c 100644 --- a/crates/rpc/src/v06/method/get_transaction_status.rs +++ b/crates/rpc/src/v06/method/get_transaction_status.rs @@ -140,8 +140,7 @@ pub async fn get_transaction_status( .map_err(GetTransactionStatusError::Internal) .and_then(|tx| { use starknet_gateway_types::reply::transaction_status::{ - ExecutionStatus as GatewayExecutionStatus, - FinalityStatus as GatewayFinalityStatus, + ExecutionStatus as GatewayExecutionStatus, FinalityStatus as GatewayFinalityStatus, }; let execution_status = tx.execution_status.unwrap_or_default(); diff --git a/crates/rpc/src/v06/method/simulate_transactions.rs b/crates/rpc/src/v06/method/simulate_transactions.rs index f464e0f3e2..1975656523 100644 --- a/crates/rpc/src/v06/method/simulate_transactions.rs +++ b/crates/rpc/src/v06/method/simulate_transactions.rs @@ -787,19 +787,12 @@ pub mod dto { pub(crate) mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - felt, - BlockHeader, - ClassHash, - ContractAddress, - StarknetVersion, - StorageAddress, - StorageValue, - TransactionVersion, + felt, BlockHeader, ClassHash, ContractAddress, StarknetVersion, StorageAddress, + StorageValue, TransactionVersion, }; use pathfinder_storage::Storage; use starknet_gateway_test_fixtures::class_definitions::{ - DUMMY_ACCOUNT_CLASS_HASH, - ERC20_CONTRACT_DEFINITION_CLASS_HASH, + DUMMY_ACCOUNT_CLASS_HASH, ERC20_CONTRACT_DEFINITION_CLASS_HASH, }; use super::*; @@ -1116,19 +1109,13 @@ pub(crate) mod tests { // The input transactions are the same as in v04. pub mod input { use pathfinder_common::{ - CallParam, - EntryPoint, - ResourceAmount, - ResourcePricePerUnit, - Tip, + CallParam, EntryPoint, ResourceAmount, ResourcePricePerUnit, Tip, }; use super::*; use crate::types::request::{ - BroadcastedDeclareTransactionV2, - BroadcastedInvokeTransaction, - BroadcastedInvokeTransactionV1, - BroadcastedInvokeTransactionV3, + BroadcastedDeclareTransactionV2, BroadcastedInvokeTransaction, + BroadcastedInvokeTransactionV1, BroadcastedInvokeTransactionV3, BroadcastedTransaction, }; use crate::types::{ResourceBound, ResourceBounds}; @@ -1250,9 +1237,7 @@ pub(crate) mod tests { use super::dto::*; use super::*; use crate::method::get_state_update::types::{ - DeclaredSierraClass, - StorageDiff, - StorageEntry, + DeclaredSierraClass, StorageDiff, StorageEntry, }; const DECLARE_GAS_CONSUMED: u64 = 3632; diff --git a/crates/rpc/src/v06/method/trace_block_transactions.rs b/crates/rpc/src/v06/method/trace_block_transactions.rs index fcfd508316..1fa6483b6c 100644 --- a/crates/rpc/src/v06/method/trace_block_transactions.rs +++ b/crates/rpc/src/v06/method/trace_block_transactions.rs @@ -10,17 +10,11 @@ use super::simulate_transactions::dto::TransactionTrace; use crate::compose_executor_transaction; use crate::context::RpcContext; use crate::executor::{ - ExecutionStateError, - VERSIONS_LOWER_THAN_THIS_SHOULD_FALL_BACK_TO_FETCHING_TRACE_FROM_GATEWAY, + ExecutionStateError, VERSIONS_LOWER_THAN_THIS_SHOULD_FALL_BACK_TO_FETCHING_TRACE_FROM_GATEWAY, }; use crate::v06::method::simulate_transactions::dto::{ - DeclareTxnTrace, - DeployAccountTxnTrace, - ExecuteInvocation, - ExecutionResources, - FunctionInvocation, - InvokeTxnTrace, - L1HandlerTxnTrace, + DeclareTxnTrace, DeployAccountTxnTrace, ExecuteInvocation, ExecutionResources, + FunctionInvocation, InvokeTxnTrace, L1HandlerTxnTrace, }; #[derive(Deserialize, Debug, Clone)] @@ -333,16 +327,8 @@ pub async fn trace_block_transactions_impl( pub(crate) mod tests { use pathfinder_common::receipt::Receipt; use pathfinder_common::{ - block_hash, - felt, - BlockHeader, - BlockNumber, - Chain, - GasPrice, - SequencerAddress, - SierraHash, - StarknetVersion, - TransactionIndex, + block_hash, felt, BlockHeader, BlockNumber, Chain, GasPrice, SequencerAddress, SierraHash, + StarknetVersion, TransactionIndex, }; use pathfinder_crypto::Felt; use starknet_gateway_types::reply::{GasPrices, L1DataAvailabilityMode}; @@ -353,8 +339,7 @@ pub(crate) mod tests { pub(crate) async fn setup_multi_tx_trace_test( ) -> anyhow::Result<(RpcContext, BlockHeader, Vec)> { use super::super::simulate_transactions::tests::{ - fixtures, - setup_storage_with_starknet_version, + fixtures, setup_storage_with_starknet_version, }; let ( @@ -500,8 +485,7 @@ pub(crate) mod tests { pub(crate) async fn setup_multi_tx_trace_pending_test( ) -> anyhow::Result<(RpcContext, Vec)> { use super::super::simulate_transactions::tests::{ - fixtures, - setup_storage_with_starknet_version, + fixtures, setup_storage_with_starknet_version, }; let ( diff --git a/crates/rpc/src/v06/method/trace_transaction.rs b/crates/rpc/src/v06/method/trace_transaction.rs index 3b8c7b565a..e51addf821 100644 --- a/crates/rpc/src/v06/method/trace_transaction.rs +++ b/crates/rpc/src/v06/method/trace_transaction.rs @@ -10,8 +10,7 @@ use crate::compose_executor_transaction; use crate::context::RpcContext; use crate::error::{ApplicationError, TraceError}; use crate::executor::{ - ExecutionStateError, - VERSIONS_LOWER_THAN_THIS_SHOULD_FALL_BACK_TO_FETCHING_TRACE_FROM_GATEWAY, + ExecutionStateError, VERSIONS_LOWER_THAN_THIS_SHOULD_FALL_BACK_TO_FETCHING_TRACE_FROM_GATEWAY, }; use crate::v06::method::trace_block_transactions::map_gateway_trace; @@ -258,18 +257,12 @@ pub async fn trace_transaction_impl( #[cfg(test)] pub mod tests { use pathfinder_common::{ - block_hash, - transaction_hash, - BlockHeader, - BlockNumber, - Chain, - SequencerAddress, + block_hash, transaction_hash, BlockHeader, BlockNumber, Chain, SequencerAddress, }; use pathfinder_crypto::Felt; use super::super::trace_block_transactions::tests::{ - setup_multi_tx_trace_pending_test, - setup_multi_tx_trace_test, + setup_multi_tx_trace_pending_test, setup_multi_tx_trace_test, }; use super::*; diff --git a/crates/rpc/src/v06/types.rs b/crates/rpc/src/v06/types.rs index 32882fd310..72b887ce26 100644 --- a/crates/rpc/src/v06/types.rs +++ b/crates/rpc/src/v06/types.rs @@ -1,14 +1,8 @@ mod transaction; use pathfinder_common::{ - BlockHash, - BlockNumber, - BlockTimestamp, - GasPrice, - SequencerAddress, - StarknetVersion, - StateCommitment, - TransactionVersion, + BlockHash, BlockNumber, BlockTimestamp, GasPrice, SequencerAddress, StarknetVersion, + StateCommitment, TransactionVersion, }; use serde::Serialize; use serde_with::{serde_as, skip_serializing_none, DisplayFromStr}; diff --git a/crates/rpc/src/v06/types/transaction.rs b/crates/rpc/src/v06/types/transaction.rs index 154fda363e..70c1ab5e21 100644 --- a/crates/rpc/src/v06/types/transaction.rs +++ b/crates/rpc/src/v06/types/transaction.rs @@ -1,25 +1,11 @@ use pathfinder_common::transaction::{ - DataAvailabilityMode, - DeclareTransactionV0V1, - DeclareTransactionV2, - DeclareTransactionV3, - DeployAccountTransactionV1, - DeployAccountTransactionV3, - DeployTransactionV0, - DeployTransactionV1, - InvokeTransactionV0, - InvokeTransactionV1, - InvokeTransactionV3, - L1HandlerTransaction, - ResourceBound, - ResourceBounds, + DataAvailabilityMode, DeclareTransactionV0V1, DeclareTransactionV2, DeclareTransactionV3, + DeployAccountTransactionV1, DeployAccountTransactionV3, DeployTransactionV0, + DeployTransactionV1, InvokeTransactionV0, InvokeTransactionV1, InvokeTransactionV3, + L1HandlerTransaction, ResourceBound, ResourceBounds, }; use pathfinder_common::{ - ResourceAmount, - ResourcePricePerUnit, - Tip, - TransactionHash, - TransactionVersion, + ResourceAmount, ResourcePricePerUnit, Tip, TransactionHash, TransactionVersion, }; use serde::ser::SerializeStruct; use serde::Serialize; diff --git a/crates/serde/src/lib.rs b/crates/serde/src/lib.rs index 1c2d8d1eec..9e347cc356 100644 --- a/crates/serde/src/lib.rs +++ b/crates/serde/src/lib.rs @@ -6,17 +6,8 @@ use std::str::FromStr; use num_bigint::BigUint; use pathfinder_common::{ - BlockNumber, - CallParam, - ConstructorParam, - EthereumAddress, - GasPrice, - L1ToL2MessagePayloadElem, - L2ToL1MessagePayloadElem, - ResourceAmount, - ResourcePricePerUnit, - Tip, - TransactionSignatureElem, + BlockNumber, CallParam, ConstructorParam, EthereumAddress, GasPrice, L1ToL2MessagePayloadElem, + L2ToL1MessagePayloadElem, ResourceAmount, ResourcePricePerUnit, Tip, TransactionSignatureElem, }; use pathfinder_crypto::{Felt, HexParseError, OverflowError}; use primitive_types::{H160, H256, U256}; diff --git a/crates/storage/src/connection.rs b/crates/storage/src/connection.rs index 3476be3be8..978c7c0340 100644 --- a/crates/storage/src/connection.rs +++ b/crates/storage/src/connection.rs @@ -16,10 +16,7 @@ mod trie; #[cfg(feature = "aggregate_bloom")] use event::RunningEventFilter; pub use event::{ - EmittedEvent, - EventFilter, - EventFilterError, - PageOfEvents, + EmittedEvent, EventFilter, EventFilterError, PageOfEvents, PAGE_SIZE_LIMIT as EVENT_PAGE_SIZE_LIMIT, }; use pathfinder_common::event::Event; diff --git a/crates/storage/src/connection/block.rs b/crates/storage/src/connection/block.rs index c2b6ddfb8f..a3d1c3c575 100644 --- a/crates/storage/src/connection/block.rs +++ b/crates/storage/src/connection/block.rs @@ -3,16 +3,8 @@ use std::num::NonZeroUsize; use anyhow::Context; use pathfinder_common::{ - BlockHash, - BlockHeader, - BlockNumber, - ClassCommitment, - GasPrice, - StarknetVersion, - StateCommitment, - StateDiffCommitment, - StorageCommitment, - TransactionCommitment, + BlockHash, BlockHeader, BlockNumber, ClassCommitment, GasPrice, StarknetVersion, + StateCommitment, StateDiffCommitment, StorageCommitment, TransactionCommitment, }; use crate::prelude::*; diff --git a/crates/storage/src/connection/event.rs b/crates/storage/src/connection/event.rs index 304ed2248c..5a2d974f7c 100644 --- a/crates/storage/src/connection/event.rs +++ b/crates/storage/src/connection/event.rs @@ -5,12 +5,7 @@ use anyhow::Context; use anyhow::Result; use pathfinder_common::event::Event; use pathfinder_common::{ - BlockHash, - BlockNumber, - ContractAddress, - EventData, - EventKey, - TransactionHash, + BlockHash, BlockNumber, ContractAddress, EventData, EventKey, TransactionHash, }; #[cfg(feature = "aggregate_bloom")] diff --git a/crates/storage/src/connection/state_update.rs b/crates/storage/src/connection/state_update.rs index b263dd5b45..e853348122 100644 --- a/crates/storage/src/connection/state_update.rs +++ b/crates/storage/src/connection/state_update.rs @@ -3,25 +3,12 @@ use std::num::NonZeroUsize; use anyhow::Context; use pathfinder_common::state_update::{ - ContractClassUpdate, - ContractUpdate, - ReverseContractUpdate, - StateUpdateData, + ContractClassUpdate, ContractUpdate, ReverseContractUpdate, StateUpdateData, SystemContractUpdate, }; use pathfinder_common::{ - BlockHash, - BlockNumber, - CasmHash, - ClassHash, - ContractAddress, - ContractNonce, - SierraHash, - StateCommitment, - StateUpdate, - StorageAddress, - StorageCommitment, - StorageValue, + BlockHash, BlockNumber, CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, + StateCommitment, StateUpdate, StorageAddress, StorageCommitment, StorageValue, }; use crate::prelude::*; diff --git a/crates/storage/src/connection/trie.rs b/crates/storage/src/connection/trie.rs index 11fe530526..20691d60f9 100644 --- a/crates/storage/src/connection/trie.rs +++ b/crates/storage/src/connection/trie.rs @@ -4,23 +4,26 @@ use anyhow::Context; use bitvec::prelude::Msb0; use bitvec::vec::BitVec; use pathfinder_common::prelude::*; +use pathfinder_common::storage_index::StorageIndex; use pathfinder_crypto::Felt; use crate::prelude::*; use crate::{BlockId, TriePruneMode}; impl Transaction<'_> { - pub fn class_root_index(&self, block_number: BlockNumber) -> anyhow::Result> { + pub fn class_root_index( + &self, + block_number: BlockNumber, + ) -> anyhow::Result> { self.inner() - .query_row( - "SELECT root_index FROM class_roots WHERE block_number <= ? ORDER BY block_number \ - DESC LIMIT 1", - params![&block_number], - |row| row.get::<_, Option>(0), - ) - .optional() - .map(|x| x.flatten()) - .map_err(Into::into) + .query_row( + "SELECT root_index FROM class_roots WHERE block_number <= ? ORDER BY block_number DESC LIMIT 1", + params![&block_number], + |row| row.get::<_, Option>(0), + ) + .optional() + .map(|option_u64| option_u64.flatten().map(StorageIndex::new)) + .map_err(Into::into) } pub fn class_root_exists(&self, block_number: BlockNumber) -> anyhow::Result { @@ -33,16 +36,19 @@ impl Transaction<'_> { .map_err(Into::into) } - pub fn storage_root_index(&self, block_number: BlockNumber) -> anyhow::Result> { + pub fn storage_root_index( + &self, + block_number: BlockNumber, + ) -> anyhow::Result> { self.inner() .query_row( "SELECT root_index FROM storage_roots WHERE block_number <= ? ORDER BY \ - block_number DESC LIMIT 1", + block_number DESC LIMIT 1", params![&block_number], |row| row.get::<_, Option>(0), ) .optional() - .map(|x| x.flatten()) + .map(|option_u64| option_u64.flatten().map(StorageIndex::new)) .map_err(Into::into) } @@ -797,25 +803,25 @@ mod tests { tx.insert_class_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(123)) .unwrap(); let result = tx.class_root_index(BlockNumber::GENESIS).unwrap(); - assert_eq!(result, Some(123)); + assert_eq!(result, Some(StorageIndex::new(123))); tx.insert_class_root(BlockNumber::GENESIS + 1, RootIndexUpdate::Updated(456)) .unwrap(); let result = tx.class_root_index(BlockNumber::GENESIS).unwrap(); - assert_eq!(result, Some(123)); + assert_eq!(result, Some(StorageIndex::new(123))); let result = tx.class_root_index(BlockNumber::GENESIS + 1).unwrap(); - assert_eq!(result, Some(456)); + assert_eq!(result, Some(StorageIndex::new(456))); let result = tx.class_root_index(BlockNumber::GENESIS + 2).unwrap(); - assert_eq!(result, Some(456)); + assert_eq!(result, Some(StorageIndex::new(456))); tx.insert_class_root(BlockNumber::GENESIS + 10, RootIndexUpdate::Updated(789)) .unwrap(); let result = tx.class_root_index(BlockNumber::GENESIS + 9).unwrap(); - assert_eq!(result, Some(456)); + assert_eq!(result, Some(StorageIndex::new(456))); let result = tx.class_root_index(BlockNumber::GENESIS + 10).unwrap(); - assert_eq!(result, Some(789)); + assert_eq!(result, Some(StorageIndex::new(789))); let result = tx.class_root_index(BlockNumber::GENESIS + 11).unwrap(); - assert_eq!(result, Some(789)); + assert_eq!(result, Some(StorageIndex::new(789))); tx.insert_class_root(BlockNumber::GENESIS + 12, RootIndexUpdate::TrieEmpty) .unwrap(); @@ -839,25 +845,25 @@ mod tests { tx.insert_storage_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(123)) .unwrap(); let result = tx.storage_root_index(BlockNumber::GENESIS).unwrap(); - assert_eq!(result, Some(123)); + assert_eq!(result, Some(StorageIndex::new(123))); tx.insert_storage_root(BlockNumber::GENESIS + 1, RootIndexUpdate::Updated(456)) .unwrap(); let result = tx.storage_root_index(BlockNumber::GENESIS).unwrap(); - assert_eq!(result, Some(123)); + assert_eq!(result, Some(StorageIndex::new(123))); let result = tx.storage_root_index(BlockNumber::GENESIS + 1).unwrap(); - assert_eq!(result, Some(456)); + assert_eq!(result, Some(StorageIndex::new(456))); let result = tx.storage_root_index(BlockNumber::GENESIS + 2).unwrap(); - assert_eq!(result, Some(456)); + assert_eq!(result, Some(StorageIndex::new(456))); tx.insert_storage_root(BlockNumber::GENESIS + 10, RootIndexUpdate::Updated(789)) .unwrap(); let result = tx.storage_root_index(BlockNumber::GENESIS + 9).unwrap(); - assert_eq!(result, Some(456)); + assert_eq!(result, Some(StorageIndex::new(456))); let result = tx.storage_root_index(BlockNumber::GENESIS + 10).unwrap(); - assert_eq!(result, Some(789)); + assert_eq!(result, Some(StorageIndex::new(789))); let result = tx.storage_root_index(BlockNumber::GENESIS + 11).unwrap(); - assert_eq!(result, Some(789)); + assert_eq!(result, Some(StorageIndex::new(789))); tx.insert_storage_root(BlockNumber::GENESIS + 12, RootIndexUpdate::TrieEmpty) .unwrap(); diff --git a/crates/storage/src/fake.rs b/crates/storage/src/fake.rs index 57403c82e2..9a8f756428 100644 --- a/crates/storage/src/fake.rs +++ b/crates/storage/src/fake.rs @@ -5,33 +5,15 @@ use fake::{Fake, Faker}; use pathfinder_common::event::Event; use pathfinder_common::receipt::Receipt; use pathfinder_common::state_update::{ - ContractClassUpdate, - ContractUpdate, - StateUpdateRef, - SystemContractUpdate, + ContractClassUpdate, ContractUpdate, StateUpdateRef, SystemContractUpdate, }; use pathfinder_common::test_utils::fake_non_empty_with_rng; use pathfinder_common::transaction::Transaction; use pathfinder_common::{ - class_definition, - BlockHash, - BlockHeader, - BlockNumber, - ChainId, - ClassCommitment, - ClassHash, - ContractAddress, - EventCommitment, - ReceiptCommitment, - SierraHash, - SignedBlockHeader, - StarknetVersion, - StateCommitment, - StateUpdate, - StorageCommitment, - TransactionCommitment, - TransactionHash, - TransactionIndex, + class_definition, BlockHash, BlockHeader, BlockNumber, ChainId, ClassCommitment, ClassHash, + ContractAddress, EventCommitment, ReceiptCommitment, SierraHash, SignedBlockHeader, + StarknetVersion, StateCommitment, StateUpdate, StorageCommitment, TransactionCommitment, + TransactionHash, TransactionIndex, }; use pathfinder_crypto::signature::SignatureError; use pathfinder_crypto::Felt; diff --git a/crates/storage/src/params.rs b/crates/storage/src/params.rs index 2a82e08754..8646eca74e 100644 --- a/crates/storage/src/params.rs +++ b/crates/storage/src/params.rs @@ -1,46 +1,13 @@ use anyhow::Result; use pathfinder_common::{ - BlockCommitmentSignatureElem, - BlockHash, - BlockNumber, - BlockTimestamp, - ByteCodeOffset, - CallParam, - CallResultValue, - CasmHash, - ClassCommitment, - ClassCommitmentLeafHash, - ClassHash, - ConstructorParam, - ContractAddress, - ContractAddressSalt, - ContractNonce, - ContractRoot, - ContractStateHash, - EntryPoint, - EventCommitment, - EventData, - EventKey, - Fee, - GasPrice, - L1BlockNumber, - L1DataAvailabilityMode, - L1ToL2MessageNonce, - L1ToL2MessagePayloadElem, - L2ToL1MessagePayloadElem, - ReceiptCommitment, - SequencerAddress, - SierraHash, - StarknetVersion, - StateCommitment, - StateDiffCommitment, - StorageAddress, - StorageCommitment, - StorageValue, - TransactionCommitment, - TransactionHash, - TransactionNonce, - TransactionSignatureElem, + BlockCommitmentSignatureElem, BlockHash, BlockNumber, BlockTimestamp, ByteCodeOffset, + CallParam, CallResultValue, CasmHash, ClassCommitment, ClassCommitmentLeafHash, ClassHash, + ConstructorParam, ContractAddress, ContractAddressSalt, ContractNonce, ContractRoot, + ContractStateHash, EntryPoint, EventCommitment, EventData, EventKey, Fee, GasPrice, + L1BlockNumber, L1DataAvailabilityMode, L1ToL2MessageNonce, L1ToL2MessagePayloadElem, + L2ToL1MessagePayloadElem, ReceiptCommitment, SequencerAddress, SierraHash, StarknetVersion, + StateCommitment, StateDiffCommitment, StorageAddress, StorageCommitment, StorageValue, + TransactionCommitment, TransactionHash, TransactionNonce, TransactionSignatureElem, }; use pathfinder_crypto::Felt; use rusqlite::types::{FromSqlError, ToSqlOutput}; @@ -504,13 +471,8 @@ macro_rules! row_felt_wrapper { } use { - row_felt_wrapper, - to_sql_builtin, - to_sql_compressed_felt, - to_sql_felt, - to_sql_int, - try_into_sql, - try_into_sql_int, + row_felt_wrapper, to_sql_builtin, to_sql_compressed_felt, to_sql_felt, to_sql_int, + try_into_sql, try_into_sql_int, }; /// Used in combination with our own [ToSql] trait to provide functionality diff --git a/crates/storage/src/schema/revision_0052.rs b/crates/storage/src/schema/revision_0052.rs index 80d439be46..32447f4fb5 100644 --- a/crates/storage/src/schema/revision_0052.rs +++ b/crates/storage/src/schema/revision_0052.rs @@ -1681,14 +1681,9 @@ pub(crate) mod old_dto { use pathfinder_common::*; use pathfinder_crypto::Felt; use pathfinder_serde::{ - CallParamAsDecimalStr, - ConstructorParamAsDecimalStr, - EthereumAddressAsHexStr, - L2ToL1MessagePayloadElemAsDecimalStr, - ResourceAmountAsHexStr, - ResourcePricePerUnitAsHexStr, - TipAsHexStr, - TransactionSignatureElemAsDecimalStr, + CallParamAsDecimalStr, ConstructorParamAsDecimalStr, EthereumAddressAsHexStr, + L2ToL1MessagePayloadElemAsDecimalStr, ResourceAmountAsHexStr, ResourcePricePerUnitAsHexStr, + TipAsHexStr, TransactionSignatureElemAsDecimalStr, }; use serde::{Deserialize, Serialize}; use serde_with::serde_as; diff --git a/crates/storage/src/test_utils.rs b/crates/storage/src/test_utils.rs index 8c36f41e86..02a51d2863 100644 --- a/crates/storage/src/test_utils.rs +++ b/crates/storage/src/test_utils.rs @@ -2,11 +2,7 @@ use pathfinder_common::event::Event; use pathfinder_common::macro_prelude::*; use pathfinder_common::receipt::{ExecutionResources, L1Gas, Receipt}; use pathfinder_common::transaction::{ - DeclareTransactionV0V1, - DeployTransactionV0, - EntryPointType, - InvokeTransactionV0, - Transaction, + DeclareTransactionV0V1, DeployTransactionV0, EntryPointType, InvokeTransactionV0, Transaction, TransactionVariant, }; use pathfinder_common::*; From dd4dbf60777b277102552e358bfcd472a7c5c436 Mon Sep 17 00:00:00 2001 From: varun-doshi Date: Wed, 4 Dec 2024 19:50:48 +0530 Subject: [PATCH 4/8] fix: fixed lint --- crates/common/src/prelude.rs | 51 +++++++++-- crates/common/src/state_update.rs | 19 +++- crates/common/src/test_utils.rs | 11 ++- crates/common/src/transaction.rs | 6 +- crates/compiler/src/lib.rs | 16 ++-- crates/crypto/src/lib.rs | 8 +- crates/crypto/src/signature/mod.rs | 7 +- crates/ethereum/src/lib.rs | 12 ++- crates/executor/src/error.rs | 3 +- crates/executor/src/error_stack.rs | 3 +- crates/executor/src/execution_state.rs | 7 +- crates/executor/src/lib.rs | 5 +- crates/executor/src/pending.rs | 7 +- crates/executor/src/simulate.rs | 28 ++++-- crates/executor/src/types.rs | 8 +- crates/gateway-client/src/lib.rs | 8 +- crates/gateway-test-fixtures/src/lib.rs | 7 +- crates/gateway-types/src/class_hash.rs | 8 +- crates/gateway-types/src/reply.rs | 67 ++++++++++++--- crates/gateway-types/src/request.rs | 22 ++++- crates/merkle-tree/src/class.rs | 6 +- crates/merkle-tree/src/contract.rs | 9 +- crates/merkle-tree/src/contract_state.rs | 7 +- crates/merkle-tree/src/tree.rs | 6 +- crates/p2p/src/behaviour.rs | 13 ++- crates/p2p/src/client/conv.rs | 86 +++++++++++++++---- crates/p2p/src/client/peer_agnostic.rs | 35 ++++++-- .../p2p/src/client/peer_agnostic/fixtures.rs | 19 +++- crates/p2p/src/client/peer_agnostic/traits.rs | 9 +- crates/p2p/src/client/types.rs | 25 +++++- crates/p2p_proto/src/header.rs | 8 +- crates/p2p_proto/src/receipt.rs | 12 ++- crates/p2p_proto/src/state.rs | 8 +- crates/p2p_proto/src/transaction.rs | 32 +++++-- crates/p2p_stream/src/handler.rs | 10 ++- crates/p2p_stream/src/lib.rs | 11 ++- crates/p2p_stream/tests/error_reporting.rs | 12 ++- crates/p2p_stream/tests/sanity.rs | 8 +- .../examples/compute_pre0132_hashes.rs | 13 ++- crates/pathfinder/examples/feeder_gateway.rs | 15 +++- crates/pathfinder/examples/re_execute.rs | 4 +- .../examples/verify_block_hashes.rs | 5 +- crates/pathfinder/src/bin/pathfinder/main.rs | 4 +- .../src/p2p_network/sync_handlers.rs | 14 ++- .../src/p2p_network/sync_handlers/tests.rs | 34 ++++++-- crates/pathfinder/src/state.rs | 9 +- crates/pathfinder/src/state/block_hash.rs | 32 +++++-- crates/pathfinder/src/state/sync.rs | 23 ++++- crates/pathfinder/src/state/sync/l2.rs | 49 +++++++++-- crates/pathfinder/src/state/sync/pending.rs | 13 ++- crates/pathfinder/src/state/sync/revert.rs | 6 +- crates/pathfinder/src/sync.rs | 37 ++++++-- crates/pathfinder/src/sync/checkpoint.rs | 50 +++++++++-- .../pathfinder/src/sync/class_definitions.rs | 3 +- crates/pathfinder/src/sync/events.rs | 6 +- crates/pathfinder/src/sync/headers.rs | 12 ++- crates/pathfinder/src/sync/state_updates.rs | 33 +++++-- crates/pathfinder/src/sync/track.rs | 28 ++++-- crates/pathfinder/src/sync/transactions.rs | 18 +++- crates/rpc/src/dto/state_update.rs | 8 +- crates/rpc/src/executor.rs | 4 +- crates/rpc/src/felt.rs | 30 +++++-- crates/rpc/src/jsonrpc.rs | 7 +- crates/rpc/src/jsonrpc/router/method.rs | 7 +- crates/rpc/src/jsonrpc/router/subscription.rs | 6 +- crates/rpc/src/jsonrpc/websocket/data.rs | 7 +- crates/rpc/src/jsonrpc/websocket/logic.rs | 23 ++++- crates/rpc/src/lib.rs | 6 +- .../rpc/src/method/add_declare_transaction.rs | 49 ++++++++--- .../method/add_deploy_account_transaction.rs | 24 ++++-- .../rpc/src/method/add_invoke_transaction.rs | 12 ++- crates/rpc/src/method/call.rs | 16 +++- crates/rpc/src/method/estimate_fee.rs | 10 ++- crates/rpc/src/method/get_compiled_casm.rs | 7 +- crates/rpc/src/method/get_events.rs | 8 +- crates/rpc/src/method/get_state_update.rs | 11 ++- crates/rpc/src/method/get_storage_proof.rs | 7 +- .../rpc/src/method/get_transaction_status.rs | 3 +- .../rpc/src/method/simulate_transactions.rs | 25 ++++-- crates/rpc/src/method/subscribe_events.rs | 12 ++- .../method/subscribe_pending_transactions.rs | 7 +- .../method/subscribe_transaction_status.rs | 7 +- .../src/method/trace_block_transactions.rs | 14 ++- crates/rpc/src/method/trace_transaction.rs | 6 +- .../rpc/src/pathfinder/methods/get_proof.rs | 5 +- crates/rpc/src/test_setup.rs | 12 ++- crates/rpc/src/types.rs | 27 ++++-- crates/rpc/src/types/class.rs | 3 +- .../src/v06/method/add_declare_transaction.rs | 49 ++++++++--- .../method/add_deploy_account_transaction.rs | 24 ++++-- .../src/v06/method/add_invoke_transaction.rs | 12 ++- crates/rpc/src/v06/method/call.rs | 16 +++- crates/rpc/src/v06/method/estimate_fee.rs | 21 +++-- .../src/v06/method/estimate_message_fee.rs | 19 +++- .../get_transaction_by_block_id_and_index.rs | 3 +- .../src/v06/method/get_transaction_receipt.rs | 11 ++- .../src/v06/method/get_transaction_status.rs | 3 +- .../src/v06/method/simulate_transactions.rs | 29 +++++-- .../v06/method/trace_block_transactions.rs | 30 +++++-- .../rpc/src/v06/method/trace_transaction.rs | 13 ++- crates/rpc/src/v06/types.rs | 10 ++- crates/rpc/src/v06/types/transaction.rs | 24 ++++-- crates/serde/src/lib.rs | 13 ++- crates/storage/src/connection.rs | 5 +- crates/storage/src/connection/block.rs | 12 ++- crates/storage/src/connection/event.rs | 7 +- crates/storage/src/connection/state_update.rs | 19 +++- crates/storage/src/connection/trie.rs | 19 ++-- crates/storage/src/fake.rs | 28 ++++-- crates/storage/src/params.rs | 58 ++++++++++--- crates/storage/src/schema/revision_0052.rs | 11 ++- crates/storage/src/test_utils.rs | 6 +- 112 files changed, 1475 insertions(+), 357 deletions(-) diff --git a/crates/common/src/prelude.rs b/crates/common/src/prelude.rs index ff2b393854..0fda3c2135 100644 --- a/crates/common/src/prelude.rs +++ b/crates/common/src/prelude.rs @@ -1,11 +1,46 @@ pub use crate::{ - BlockHash, BlockHeader, BlockNumber, BlockTimestamp, ByteCodeOffset, CallParam, - CallResultValue, CasmHash, ChainId, ClassCommitment, ClassCommitmentLeafHash, ClassHash, - ConstructorParam, ContractAddress, ContractAddressSalt, ContractClass, ContractNonce, - ContractRoot, ContractStateHash, EntryPoint, EthereumAddress, EventCommitment, EventData, - EventKey, Fee, FromSliceError, GasPrice, L1ToL2MessageNonce, L1ToL2MessagePayloadElem, - L2ToL1MessagePayloadElem, SequencerAddress, SierraHash, StarknetVersion, StateCommitment, - StateUpdate, StorageAddress, StorageCommitment, StorageValue, TransactionCommitment, - TransactionHash, TransactionIndex, TransactionNonce, TransactionSignatureElem, + BlockHash, + BlockHeader, + BlockNumber, + BlockTimestamp, + ByteCodeOffset, + CallParam, + CallResultValue, + CasmHash, + ChainId, + ClassCommitment, + ClassCommitmentLeafHash, + ClassHash, + ConstructorParam, + ContractAddress, + ContractAddressSalt, + ContractClass, + ContractNonce, + ContractRoot, + ContractStateHash, + EntryPoint, + EthereumAddress, + EventCommitment, + EventData, + EventKey, + Fee, + FromSliceError, + GasPrice, + L1ToL2MessageNonce, + L1ToL2MessagePayloadElem, + L2ToL1MessagePayloadElem, + SequencerAddress, + SierraHash, + StarknetVersion, + StateCommitment, + StateUpdate, + StorageAddress, + StorageCommitment, + StorageValue, + TransactionCommitment, + TransactionHash, + TransactionIndex, + TransactionNonce, + TransactionSignatureElem, TransactionVersion, }; diff --git a/crates/common/src/state_update.rs b/crates/common/src/state_update.rs index 7a23fd1a5f..e44b64adf7 100644 --- a/crates/common/src/state_update.rs +++ b/crates/common/src/state_update.rs @@ -4,8 +4,16 @@ use std::slice; use fake::Dummy; use crate::{ - BlockHash, CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, StateCommitment, - StateDiffCommitment, StorageAddress, StorageValue, + BlockHash, + CasmHash, + ClassHash, + ContractAddress, + ContractNonce, + SierraHash, + StateCommitment, + StateDiffCommitment, + StorageAddress, + StorageValue, }; #[derive(Default, Debug, Clone, PartialEq)] @@ -510,7 +518,12 @@ mod state_diff_commitment { use super::{ContractUpdate, SystemContractUpdate}; use crate::{ - felt_bytes, CasmHash, ClassHash, ContractAddress, SierraHash, StateDiffCommitment, + felt_bytes, + CasmHash, + ClassHash, + ContractAddress, + SierraHash, + StateDiffCommitment, }; /// Compute the state diff commitment used in block commitment signatures. diff --git a/crates/common/src/test_utils.rs b/crates/common/src/test_utils.rs index 588985806e..9805638ad9 100644 --- a/crates/common/src/test_utils.rs +++ b/crates/common/src/test_utils.rs @@ -24,7 +24,16 @@ pub mod metrics { use std::sync::{Arc, RwLock}; use metrics::{ - Counter, CounterFn, Gauge, Histogram, Key, KeyName, Label, Recorder, SharedString, Unit, + Counter, + CounterFn, + Gauge, + Histogram, + Key, + KeyName, + Label, + Recorder, + SharedString, + Unit, }; /// # Purpose diff --git a/crates/common/src/transaction.rs b/crates/common/src/transaction.rs index 38c18ed538..4490650d23 100644 --- a/crates/common/src/transaction.rs +++ b/crates/common/src/transaction.rs @@ -5,7 +5,11 @@ use primitive_types::H256; use crate::prelude::*; use crate::{ - felt_bytes, AccountDeploymentDataElem, PaymasterDataElem, ResourceAmount, ResourcePricePerUnit, + felt_bytes, + AccountDeploymentDataElem, + PaymasterDataElem, + ResourceAmount, + ResourcePricePerUnit, Tip, }; diff --git a/crates/compiler/src/lib.rs b/crates/compiler/src/lib.rs index 55ca5edb68..97d5c6015e 100644 --- a/crates/compiler/src/lib.rs +++ b/crates/compiler/src/lib.rs @@ -78,7 +78,8 @@ pub fn casm_class_hash(casm_definition: &[u8]) -> anyhow::Result { mod v1_0_0_alpha6 { use anyhow::Context; use casm_compiler_v1_0_0_alpha6::allowed_libfuncs::{ - validate_compatible_sierra_version, ListSelector, + validate_compatible_sierra_version, + ListSelector, }; use casm_compiler_v1_0_0_alpha6::casm_contract_class::CasmContractClass; use casm_compiler_v1_0_0_alpha6::contract_class::ContractClass; @@ -124,7 +125,8 @@ mod v1_0_0_alpha6 { mod v1_0_0_rc0 { use anyhow::Context; use casm_compiler_v1_0_0_rc0::allowed_libfuncs::{ - validate_compatible_sierra_version, ListSelector, + validate_compatible_sierra_version, + ListSelector, }; use casm_compiler_v1_0_0_rc0::casm_contract_class::CasmContractClass; use casm_compiler_v1_0_0_rc0::contract_class::ContractClass; @@ -170,7 +172,8 @@ mod v1_0_0_rc0 { mod v1_1_1 { use anyhow::Context; use casm_compiler_v1_1_1::allowed_libfuncs::{ - validate_compatible_sierra_version, ListSelector, + validate_compatible_sierra_version, + ListSelector, }; use casm_compiler_v1_1_1::casm_contract_class::CasmContractClass; use casm_compiler_v1_1_1::contract_class::ContractClass; @@ -293,7 +296,9 @@ mod tests { mod parse_version { use rstest::rstest; use starknet_gateway_test_fixtures::class_definitions::{ - CAIRO_1_0_0_ALPHA5_SIERRA, CAIRO_1_0_0_RC0_SIERRA, CAIRO_1_1_0_RC0_SIERRA, + CAIRO_1_0_0_ALPHA5_SIERRA, + CAIRO_1_0_0_RC0_SIERRA, + CAIRO_1_1_0_RC0_SIERRA, CAIRO_2_0_0_STACK_OVERFLOW, }; @@ -356,7 +361,8 @@ mod tests { mod starknet_v0_11_2_onwards { use starknet_gateway_test_fixtures::class_definitions::{ - CAIRO_1_1_0_RC0_SIERRA, CAIRO_2_0_0_STACK_OVERFLOW, + CAIRO_1_1_0_RC0_SIERRA, + CAIRO_2_0_0_STACK_OVERFLOW, }; use super::*; diff --git a/crates/crypto/src/lib.rs b/crates/crypto/src/lib.rs index 5a6e71f974..543a4cee54 100644 --- a/crates/crypto/src/lib.rs +++ b/crates/crypto/src/lib.rs @@ -11,5 +11,11 @@ pub mod hash; pub mod signature; pub use algebra::{ - AffinePoint, CurveOrderMontFelt, Felt, HexParseError, MontFelt, OverflowError, ProjectivePoint, + AffinePoint, + CurveOrderMontFelt, + Felt, + HexParseError, + MontFelt, + OverflowError, + ProjectivePoint, }; diff --git a/crates/crypto/src/signature/mod.rs b/crates/crypto/src/signature/mod.rs index b9963a7968..0621d619b3 100644 --- a/crates/crypto/src/signature/mod.rs +++ b/crates/crypto/src/signature/mod.rs @@ -1,5 +1,10 @@ mod ecdsa; pub use ecdsa::{ - ecdsa_sign, ecdsa_sign_k, ecdsa_verify, ecdsa_verify_partial, get_pk, SignatureError, + ecdsa_sign, + ecdsa_sign_k, + ecdsa_verify, + ecdsa_verify_partial, + get_pk, + SignatureError, }; diff --git a/crates/ethereum/src/lib.rs b/crates/ethereum/src/lib.rs index cea9fbdf6d..f12e435c88 100644 --- a/crates/ethereum/src/lib.rs +++ b/crates/ethereum/src/lib.rs @@ -10,8 +10,16 @@ use anyhow::Context; use futures::StreamExt; use pathfinder_common::transaction::L1HandlerTransaction; use pathfinder_common::{ - BlockHash, BlockNumber, CallParam, ContractAddress, EntryPoint, EthereumChain, L1BlockNumber, - L1TransactionHash, StateCommitment, TransactionNonce, + BlockHash, + BlockNumber, + CallParam, + ContractAddress, + EntryPoint, + EthereumChain, + L1BlockNumber, + L1TransactionHash, + StateCommitment, + TransactionNonce, }; use pathfinder_crypto::Felt; use primitive_types::{H160, U256}; diff --git a/crates/executor/src/error.rs b/crates/executor/src/error.rs index 2934b202a1..b32a85f4a4 100644 --- a/crates/executor/src/error.rs +++ b/crates/executor/src/error.rs @@ -1,6 +1,7 @@ use blockifier::execution::errors::{ ConstructorEntryPointExecutionError, - EntryPointExecutionError as BlockifierEntryPointExecutionError, PreExecutionError, + EntryPointExecutionError as BlockifierEntryPointExecutionError, + PreExecutionError, }; use blockifier::execution::stack_trace::gen_transaction_execution_error_trace; use blockifier::state::errors::StateError; diff --git a/crates/executor/src/error_stack.rs b/crates/executor/src/error_stack.rs index 630ffe1035..0128cfa8a7 100644 --- a/crates/executor/src/error_stack.rs +++ b/crates/executor/src/error_stack.rs @@ -1,5 +1,6 @@ use blockifier::execution::stack_trace::{ - gen_transaction_execution_error_trace, ErrorStack as BlockifierErrorStack, + gen_transaction_execution_error_trace, + ErrorStack as BlockifierErrorStack, }; use blockifier::transaction::errors::TransactionExecutionError; use pathfinder_common::{ClassHash, ContractAddress, EntryPoint}; diff --git a/crates/executor/src/execution_state.rs b/crates/executor/src/execution_state.rs index 8d359c4327..739fb46dbc 100644 --- a/crates/executor/src/execution_state.rs +++ b/crates/executor/src/execution_state.rs @@ -7,7 +7,12 @@ use blockifier::context::{BlockContext, ChainInfo}; use blockifier::state::cached_state::CachedState; use blockifier::versioned_constants::VersionedConstants; use pathfinder_common::{ - contract_address, BlockHeader, ChainId, ContractAddress, L1DataAvailabilityMode, StateUpdate, + contract_address, + BlockHeader, + ChainId, + ContractAddress, + L1DataAvailabilityMode, + StateUpdate, }; use starknet_api::core::PatriciaKey; diff --git a/crates/executor/src/lib.rs b/crates/executor/src/lib.rs index ec7c679fed..a73edd1e2f 100644 --- a/crates/executor/src/lib.rs +++ b/crates/executor/src/lib.rs @@ -23,7 +23,10 @@ pub use error::{CallError, TransactionExecutionError}; pub use error_stack::{CallFrame, ErrorStack, Frame}; pub use estimate::estimate; pub use execution_state::{ - ExecutionState, L1BlobDataAvailability, ETH_FEE_TOKEN_ADDRESS, STRK_FEE_TOKEN_ADDRESS, + ExecutionState, + L1BlobDataAvailability, + ETH_FEE_TOKEN_ADDRESS, + STRK_FEE_TOKEN_ADDRESS, }; pub use felt::{IntoFelt, IntoStarkFelt}; pub use simulate::{simulate, trace, TraceCache}; diff --git a/crates/executor/src/pending.rs b/crates/executor/src/pending.rs index 6c962ca596..1d9a632da3 100644 --- a/crates/executor/src/pending.rs +++ b/crates/executor/src/pending.rs @@ -105,7 +105,12 @@ impl StateReader for PendingStateReader { mod tests { use blockifier::state::state_api::StateReader; use pathfinder_common::{ - class_hash, contract_address, contract_nonce, storage_address, storage_value, StateUpdate, + class_hash, + contract_address, + contract_nonce, + storage_address, + storage_value, + StateUpdate, }; use starknet_types_core::felt::Felt as CoreFelt; diff --git a/crates/executor/src/simulate.rs b/crates/executor/src/simulate.rs index 94943c4784..3656002bd8 100644 --- a/crates/executor/src/simulate.rs +++ b/crates/executor/src/simulate.rs @@ -8,8 +8,15 @@ use blockifier::transaction::transaction_execution::Transaction; use blockifier::transaction::transactions::ExecutableTransaction; use cached::{Cached, SizedCache}; use pathfinder_common::{ - BlockHash, CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, StorageAddress, - StorageValue, TransactionHash, + BlockHash, + CasmHash, + ClassHash, + ContractAddress, + ContractNonce, + SierraHash, + StorageAddress, + StorageValue, + TransactionHash, }; use super::error::TransactionExecutionError; @@ -18,10 +25,19 @@ use super::types::{FeeEstimate, TransactionSimulation, TransactionTrace}; use crate::error_stack::ErrorStack; use crate::transaction::transaction_hash; use crate::types::{ - DataAvailabilityResources, DeclareTransactionTrace, DeclaredSierraClass, - DeployAccountTransactionTrace, DeployedContract, ExecuteInvocation, ExecutionResources, - FunctionInvocation, InvokeTransactionTrace, L1HandlerTransactionTrace, ReplacedClass, - StateDiff, StorageDiff, + DataAvailabilityResources, + DeclareTransactionTrace, + DeclaredSierraClass, + DeployAccountTransactionTrace, + DeployedContract, + ExecuteInvocation, + ExecutionResources, + FunctionInvocation, + InvokeTransactionTrace, + L1HandlerTransactionTrace, + ReplacedClass, + StateDiff, + StorageDiff, }; use crate::IntoFelt; diff --git a/crates/executor/src/types.rs b/crates/executor/src/types.rs index 39698a2995..fb5edb846d 100644 --- a/crates/executor/src/types.rs +++ b/crates/executor/src/types.rs @@ -4,7 +4,13 @@ use blockifier::blockifier::block::BlockInfo; use blockifier::execution::call_info::OrderedL2ToL1Message; use blockifier::transaction::objects::{FeeType, GasVector, TransactionExecutionInfo}; use pathfinder_common::{ - CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, StorageAddress, StorageValue, + CasmHash, + ClassHash, + ContractAddress, + ContractNonce, + SierraHash, + StorageAddress, + StorageValue, }; use pathfinder_crypto::Felt; diff --git a/crates/gateway-client/src/lib.rs b/crates/gateway-client/src/lib.rs index e0369767ab..abf73d8f1b 100644 --- a/crates/gateway-client/src/lib.rs +++ b/crates/gateway-client/src/lib.rs @@ -4,7 +4,13 @@ use std::result::Result; use std::time::Duration; use pathfinder_common::{ - BlockHash, BlockId, BlockNumber, ClassHash, PublicKey, StateUpdate, TransactionHash, + BlockHash, + BlockId, + BlockNumber, + ClassHash, + PublicKey, + StateUpdate, + TransactionHash, }; use reqwest::Url; use starknet_gateway_types::error::SequencerError; diff --git a/crates/gateway-test-fixtures/src/lib.rs b/crates/gateway-test-fixtures/src/lib.rs index 406594c467..5776b1f109 100644 --- a/crates/gateway-test-fixtures/src/lib.rs +++ b/crates/gateway-test-fixtures/src/lib.rs @@ -168,7 +168,12 @@ pub mod class_definitions { pub mod testnet { use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - CallParam, ClassHash, ContractAddress, EntryPoint, StorageAddress, TransactionHash, + CallParam, + ClassHash, + ContractAddress, + EntryPoint, + StorageAddress, + TransactionHash, }; use pathfinder_crypto::Felt; diff --git a/crates/gateway-types/src/class_hash.rs b/crates/gateway-types/src/class_hash.rs index bc5e32d920..d19b3b8ffd 100644 --- a/crates/gateway-types/src/class_hash.rs +++ b/crates/gateway-types/src/class_hash.rs @@ -60,7 +60,9 @@ pub mod from_parts { use anyhow::Result; use pathfinder_common::class_definition::{ - EntryPointType, SelectorAndOffset, SierraEntryPoints, + EntryPointType, + SelectorAndOffset, + SierraEntryPoints, }; use pathfinder_common::ClassHash; use pathfinder_crypto::Felt; @@ -499,7 +501,9 @@ mod json { use std::collections::{BTreeMap, HashMap}; use pathfinder_common::class_definition::{ - EntryPointType, SelectorAndFunctionIndex, SelectorAndOffset, + EntryPointType, + SelectorAndFunctionIndex, + SelectorAndOffset, }; pub enum ContractDefinition<'a> { diff --git a/crates/gateway-types/src/reply.rs b/crates/gateway-types/src/reply.rs index 9671f1abb2..024aad5833 100644 --- a/crates/gateway-types/src/reply.rs +++ b/crates/gateway-types/src/reply.rs @@ -1,9 +1,20 @@ //! Structures used for deserializing replies from Starkware's sequencer REST //! API. use pathfinder_common::{ - BlockCommitmentSignatureElem, BlockHash, BlockNumber, BlockTimestamp, ContractAddress, - EthereumAddress, EventCommitment, GasPrice, ReceiptCommitment, SequencerAddress, - StarknetVersion, StateCommitment, StateDiffCommitment, TransactionCommitment, + BlockCommitmentSignatureElem, + BlockHash, + BlockNumber, + BlockTimestamp, + ContractAddress, + EthereumAddress, + EventCommitment, + GasPrice, + ReceiptCommitment, + SequencerAddress, + StarknetVersion, + StateCommitment, + StateDiffCommitment, + TransactionCommitment, }; use pathfinder_serde::{EthereumAddressAsHexStr, GasPriceAsHexStr}; use serde::{Deserialize, Serialize}; @@ -228,17 +239,39 @@ pub mod transaction_status { pub mod transaction { use fake::{Dummy, Fake, Faker}; use pathfinder_common::{ - AccountDeploymentDataElem, CallParam, CasmHash, ClassHash, ConstructorParam, - ContractAddress, ContractAddressSalt, EntryPoint, EthereumAddress, Fee, L1ToL2MessageNonce, - L1ToL2MessagePayloadElem, L2ToL1MessagePayloadElem, PaymasterDataElem, ResourceAmount, - ResourcePricePerUnit, Tip, TransactionHash, TransactionIndex, TransactionNonce, - TransactionSignatureElem, TransactionVersion, + AccountDeploymentDataElem, + CallParam, + CasmHash, + ClassHash, + ConstructorParam, + ContractAddress, + ContractAddressSalt, + EntryPoint, + EthereumAddress, + Fee, + L1ToL2MessageNonce, + L1ToL2MessagePayloadElem, + L2ToL1MessagePayloadElem, + PaymasterDataElem, + ResourceAmount, + ResourcePricePerUnit, + Tip, + TransactionHash, + TransactionIndex, + TransactionNonce, + TransactionSignatureElem, + TransactionVersion, }; use pathfinder_crypto::Felt; use pathfinder_serde::{ - CallParamAsDecimalStr, ConstructorParamAsDecimalStr, EthereumAddressAsHexStr, - L1ToL2MessagePayloadElemAsDecimalStr, L2ToL1MessagePayloadElemAsDecimalStr, - ResourceAmountAsHexStr, ResourcePricePerUnitAsHexStr, TipAsHexStr, + CallParamAsDecimalStr, + ConstructorParamAsDecimalStr, + EthereumAddressAsHexStr, + L1ToL2MessagePayloadElemAsDecimalStr, + L2ToL1MessagePayloadElemAsDecimalStr, + ResourceAmountAsHexStr, + ResourcePricePerUnitAsHexStr, + TipAsHexStr, TransactionSignatureElemAsDecimalStr, }; use primitive_types::H256; @@ -2054,7 +2087,12 @@ pub mod state_update { use std::collections::{HashMap, HashSet}; use pathfinder_common::{ - CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, StorageAddress, + CasmHash, + ClassHash, + ContractAddress, + ContractNonce, + SierraHash, + StorageAddress, StorageValue, }; use serde::{Deserialize, Serialize}; @@ -2210,7 +2248,10 @@ mod tests { use primitive_types::H256; use crate::reply::state_update::{ - DeclaredSierraClass, DeployedContract, ReplacedClass, StorageDiff, + DeclaredSierraClass, + DeployedContract, + ReplacedClass, + StorageDiff, }; use crate::reply::transaction::L1HandlerTransaction; diff --git a/crates/gateway-types/src/request.rs b/crates/gateway-types/src/request.rs index c724fc8445..4cf781794c 100644 --- a/crates/gateway-types/src/request.rs +++ b/crates/gateway-types/src/request.rs @@ -1,6 +1,11 @@ //! Structures used for serializing requests to Starkware's sequencer REST API. use pathfinder_common::{ - BlockHash, BlockNumber, CallParam, ContractAddress, Fee, TransactionSignatureElem, + BlockHash, + BlockNumber, + CallParam, + ContractAddress, + Fee, + TransactionSignatureElem, }; use serde::{Deserialize, Serialize}; @@ -118,11 +123,20 @@ pub mod add_transaction { use std::collections::HashMap; use pathfinder_common::class_definition::{ - EntryPointType, SelectorAndFunctionIndex, SelectorAndOffset, + EntryPointType, + SelectorAndFunctionIndex, + SelectorAndOffset, }; use pathfinder_common::{ - AccountDeploymentDataElem, CasmHash, ClassHash, ContractAddressSalt, EntryPoint, - PaymasterDataElem, Tip, TransactionNonce, TransactionVersion, + AccountDeploymentDataElem, + CasmHash, + ClassHash, + ContractAddressSalt, + EntryPoint, + PaymasterDataElem, + Tip, + TransactionNonce, + TransactionVersion, }; use pathfinder_serde::{CallParamAsDecimalStr, TransactionSignatureElemAsDecimalStr}; use serde_with::serde_as; diff --git a/crates/merkle-tree/src/class.rs b/crates/merkle-tree/src/class.rs index 9cd5610bd7..83ca0360ff 100644 --- a/crates/merkle-tree/src/class.rs +++ b/crates/merkle-tree/src/class.rs @@ -1,7 +1,11 @@ use anyhow::Context; use pathfinder_common::hash::PoseidonHash; use pathfinder_common::{ - BlockNumber, ClassCommitment, ClassCommitmentLeafHash, ClassHash, SierraHash, + BlockNumber, + ClassCommitment, + ClassCommitmentLeafHash, + ClassHash, + SierraHash, }; use pathfinder_crypto::Felt; use pathfinder_storage::{Transaction, TrieUpdate}; diff --git a/crates/merkle-tree/src/contract.rs b/crates/merkle-tree/src/contract.rs index 90c64ed605..87f2aecc7b 100644 --- a/crates/merkle-tree/src/contract.rs +++ b/crates/merkle-tree/src/contract.rs @@ -12,8 +12,13 @@ use bitvec::slice::BitSlice; use pathfinder_common::hash::PedersenHash; use pathfinder_common::storage_index::StorageIndex; use pathfinder_common::{ - BlockNumber, ContractAddress, ContractRoot, ContractStateHash, StorageAddress, - StorageCommitment, StorageValue, + BlockNumber, + ContractAddress, + ContractRoot, + ContractStateHash, + StorageAddress, + StorageCommitment, + StorageValue, }; use pathfinder_crypto::Felt; use pathfinder_storage::{Transaction, TrieUpdate}; diff --git a/crates/merkle-tree/src/contract_state.rs b/crates/merkle-tree/src/contract_state.rs index 8ba5fd00a1..710bd82926 100644 --- a/crates/merkle-tree/src/contract_state.rs +++ b/crates/merkle-tree/src/contract_state.rs @@ -1,7 +1,12 @@ use anyhow::Context; use pathfinder_common::state_update::{ReverseContractUpdate, StorageRef}; use pathfinder_common::{ - BlockNumber, ClassHash, ContractAddress, ContractNonce, ContractRoot, ContractStateHash, + BlockNumber, + ClassHash, + ContractAddress, + ContractNonce, + ContractRoot, + ContractStateHash, }; use pathfinder_crypto::hash::pedersen_hash; use pathfinder_crypto::Felt; diff --git a/crates/merkle-tree/src/tree.rs b/crates/merkle-tree/src/tree.rs index 6011389316..25db480802 100644 --- a/crates/merkle-tree/src/tree.rs +++ b/crates/merkle-tree/src/tree.rs @@ -1592,7 +1592,11 @@ mod tests { mod real_world { use pathfinder_common::{ - class_commitment, class_commitment_leaf_hash, felt, sierra_hash, BlockNumber, + class_commitment, + class_commitment_leaf_hash, + felt, + sierra_hash, + BlockNumber, ClassCommitmentLeafHash, }; use pathfinder_storage::RootIndexUpdate; diff --git a/crates/p2p/src/behaviour.rs b/crates/p2p/src/behaviour.rs index f20e62c958..3e69cc1d13 100644 --- a/crates/p2p/src/behaviour.rs +++ b/crates/p2p/src/behaviour.rs @@ -11,8 +11,17 @@ use libp2p::kad::{self}; use libp2p::multiaddr::Protocol; use libp2p::swarm::behaviour::ConnectionEstablished; use libp2p::swarm::{ - CloseConnection, ConnectionClosed, ConnectionDenied, ConnectionId, DialFailure, FromSwarm, - NetworkBehaviour, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, + CloseConnection, + ConnectionClosed, + ConnectionDenied, + ConnectionId, + DialFailure, + FromSwarm, + NetworkBehaviour, + THandler, + THandlerInEvent, + THandlerOutEvent, + ToSwarm, }; use libp2p::{autonat, dcutr, identify, identity, ping, relay, Multiaddr, PeerId, StreamProtocol}; use p2p_proto::class::{ClassesRequest, ClassesResponse}; diff --git a/crates/p2p/src/client/conv.rs b/crates/p2p/src/client/conv.rs index 7f497075ca..43f104915a 100644 --- a/crates/p2p/src/client/conv.rs +++ b/crates/p2p/src/client/conv.rs @@ -10,29 +10,71 @@ use p2p_proto::class::{Cairo0Class, Cairo1Class, Cairo1EntryPoints, SierraEntryP use p2p_proto::common::{Address, Hash, Hash256}; use p2p_proto::receipt::execution_resources::BuiltinCounter; use p2p_proto::receipt::{ - DeclareTransactionReceipt, DeployAccountTransactionReceipt, DeployTransactionReceipt, - EthereumAddress, InvokeTransactionReceipt, L1HandlerTransactionReceipt, MessageToL1, + DeclareTransactionReceipt, + DeployAccountTransactionReceipt, + DeployTransactionReceipt, + EthereumAddress, + InvokeTransactionReceipt, + L1HandlerTransactionReceipt, + MessageToL1, ReceiptCommon, }; use p2p_proto::transaction::AccountSignature; use pathfinder_common::class_definition::{ - Cairo, SelectorAndFunctionIndex, SelectorAndOffset, Sierra, + Cairo, + SelectorAndFunctionIndex, + SelectorAndOffset, + Sierra, }; use pathfinder_common::event::Event; use pathfinder_common::receipt::{ - BuiltinCounters, ExecutionResources, ExecutionStatus, L1Gas, L2Gas, L2ToL1Message, Receipt, + BuiltinCounters, + ExecutionResources, + ExecutionStatus, + L1Gas, + L2Gas, + L2ToL1Message, + Receipt, }; use pathfinder_common::transaction::{ - DataAvailabilityMode, DeclareTransactionV0V1, DeclareTransactionV2, DeclareTransactionV3, - DeployAccountTransactionV1, DeployAccountTransactionV3, DeployTransactionV0, - DeployTransactionV1, InvokeTransactionV0, InvokeTransactionV1, InvokeTransactionV3, - L1HandlerTransaction, ResourceBound, ResourceBounds, Transaction, TransactionVariant, + DataAvailabilityMode, + DeclareTransactionV0V1, + DeclareTransactionV2, + DeclareTransactionV3, + DeployAccountTransactionV1, + DeployAccountTransactionV3, + DeployTransactionV0, + DeployTransactionV1, + InvokeTransactionV0, + InvokeTransactionV1, + InvokeTransactionV3, + L1HandlerTransaction, + ResourceBound, + ResourceBounds, + Transaction, + TransactionVariant, }; use pathfinder_common::{ - AccountDeploymentDataElem, ByteCodeOffset, CallParam, CasmHash, ClassHash, ConstructorParam, - ContractAddress, ContractAddressSalt, EntryPoint, EventData, EventKey, Fee, GasPrice, - L1DataAvailabilityMode, L2ToL1MessagePayloadElem, SignedBlockHeader, TransactionHash, - TransactionIndex, TransactionNonce, TransactionSignatureElem, + AccountDeploymentDataElem, + ByteCodeOffset, + CallParam, + CasmHash, + ClassHash, + ConstructorParam, + ContractAddress, + ContractAddressSalt, + EntryPoint, + EventData, + EventKey, + Fee, + GasPrice, + L1DataAvailabilityMode, + L2ToL1MessagePayloadElem, + SignedBlockHeader, + TransactionHash, + TransactionIndex, + TransactionNonce, + TransactionSignatureElem, }; use pathfinder_crypto::Felt; use serde::{Deserialize, Serialize}; @@ -408,8 +450,17 @@ impl TryFromDto for TransactionVaria Self: Sized, { use p2p_proto::transaction::TransactionVariant::{ - DeclareV0, DeclareV1, DeclareV2, DeclareV3, Deploy, DeployAccountV1, DeployAccountV3, - InvokeV0, InvokeV1, InvokeV3, L1HandlerV0, + DeclareV0, + DeclareV1, + DeclareV2, + DeclareV3, + Deploy, + DeployAccountV1, + DeployAccountV3, + InvokeV0, + InvokeV1, + InvokeV3, + L1HandlerV0, }; Ok(match dto { DeclareV0(x) => Self::DeclareV0(DeclareTransactionV0V1 { @@ -650,8 +701,11 @@ impl TryFrom<(p2p_proto::receipt::Receipt, TransactionIndex)> for crate::client: ) -> anyhow::Result { use p2p_proto::receipt::Receipt::{Declare, Deploy, DeployAccount, Invoke, L1Handler}; use p2p_proto::receipt::{ - DeclareTransactionReceipt, DeployAccountTransactionReceipt, DeployTransactionReceipt, - InvokeTransactionReceipt, L1HandlerTransactionReceipt, + DeclareTransactionReceipt, + DeployAccountTransactionReceipt, + DeployTransactionReceipt, + InvokeTransactionReceipt, + L1HandlerTransactionReceipt, }; match dto { Invoke(InvokeTransactionReceipt { common }) diff --git a/crates/p2p/src/client/peer_agnostic.rs b/crates/p2p/src/client/peer_agnostic.rs index 0f31035097..56cc0d3c39 100644 --- a/crates/p2p/src/client/peer_agnostic.rs +++ b/crates/p2p/src/client/peer_agnostic.rs @@ -13,15 +13,28 @@ use p2p_proto::common::{Direction, Iteration}; use p2p_proto::event::{EventsRequest, EventsResponse}; use p2p_proto::header::{BlockHeadersRequest, BlockHeadersResponse}; use p2p_proto::state::{ - ContractDiff, ContractStoredValue, DeclaredClass, StateDiffsRequest, StateDiffsResponse, + ContractDiff, + ContractStoredValue, + DeclaredClass, + StateDiffsRequest, + StateDiffsResponse, }; use p2p_proto::transaction::{TransactionWithReceipt, TransactionsRequest, TransactionsResponse}; use pathfinder_common::event::Event; use pathfinder_common::state_update::{ContractClassUpdate, StateUpdateData}; use pathfinder_common::transaction::Transaction; use pathfinder_common::{ - BlockNumber, CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, - SignedBlockHeader, StorageAddress, StorageValue, TransactionHash, TransactionIndex, + BlockNumber, + CasmHash, + ClassHash, + ContractAddress, + ContractNonce, + SierraHash, + SignedBlockHeader, + StorageAddress, + StorageValue, + TransactionHash, + TransactionIndex, }; use tokio::sync::{mpsc, RwLock}; @@ -32,15 +45,25 @@ mod tests; pub mod traits; use traits::{ - BlockClient, ClassStream, EventStream, HeaderStream, StateDiffStream, StreamItem, + BlockClient, + ClassStream, + EventStream, + HeaderStream, + StateDiffStream, + StreamItem, TransactionStream, }; use crate::client::conv::{CairoDefinition, FromDto, SierraDefinition, TryFromDto}; use crate::client::peer_aware; use crate::client::types::{ - ClassDefinition, ClassDefinitionsError, EventsForBlockByTransaction, - EventsResponseStreamFailure, Receipt, StateDiffsError, TransactionData, + ClassDefinition, + ClassDefinitionsError, + EventsForBlockByTransaction, + EventsResponseStreamFailure, + Receipt, + StateDiffsError, + TransactionData, }; use crate::peer_data::PeerData; diff --git a/crates/p2p/src/client/peer_agnostic/fixtures.rs b/crates/p2p/src/client/peer_agnostic/fixtures.rs index 911a3b8fda..aa3fde777c 100644 --- a/crates/p2p/src/client/peer_agnostic/fixtures.rs +++ b/crates/p2p/src/client/peer_agnostic/fixtures.rs @@ -14,12 +14,23 @@ use p2p_proto::transaction::{TransactionWithReceipt, TransactionsResponse}; use pathfinder_common::event::Event; use pathfinder_common::state_update::{ContractClassUpdate, ContractUpdate, StateUpdateData}; use pathfinder_common::transaction::{ - DeployAccountTransactionV1, DeployAccountTransactionV3, DeployTransactionV0, - DeployTransactionV1, TransactionVariant, + DeployAccountTransactionV1, + DeployAccountTransactionV3, + DeployTransactionV0, + DeployTransactionV1, + TransactionVariant, }; use pathfinder_common::{ - BlockHeader, BlockNumber, CasmHash, ChainId, ClassHash, ContractAddress, SierraHash, - SignedBlockHeader, TransactionHash, TransactionIndex, + BlockHeader, + BlockNumber, + CasmHash, + ChainId, + ClassHash, + ContractAddress, + SierraHash, + SignedBlockHeader, + TransactionHash, + TransactionIndex, }; use tagged::Tagged; use tagged_debug_derive::TaggedDebug; diff --git a/crates/p2p/src/client/peer_agnostic/traits.rs b/crates/p2p/src/client/peer_agnostic/traits.rs index 3211f1a9bc..035fc57ab8 100644 --- a/crates/p2p/src/client/peer_agnostic/traits.rs +++ b/crates/p2p/src/client/peer_agnostic/traits.rs @@ -6,8 +6,13 @@ use pathfinder_common::transaction::Transaction; use pathfinder_common::{BlockNumber, SignedBlockHeader, TransactionHash}; use crate::client::types::{ - ClassDefinition, ClassDefinitionsError, EventsForBlockByTransaction, - EventsResponseStreamFailure, Receipt, StateDiffsError, TransactionData, + ClassDefinition, + ClassDefinitionsError, + EventsForBlockByTransaction, + EventsResponseStreamFailure, + Receipt, + StateDiffsError, + TransactionData, }; use crate::PeerData; diff --git a/crates/p2p/src/client/types.rs b/crates/p2p/src/client/types.rs index 213d41dd92..53cfc5e621 100644 --- a/crates/p2p/src/client/types.rs +++ b/crates/p2p/src/client/types.rs @@ -5,10 +5,27 @@ use pathfinder_common::event::Event; use pathfinder_common::receipt::{ExecutionResources, ExecutionStatus, L2ToL1Message}; use pathfinder_common::transaction::Transaction; use pathfinder_common::{ - BlockCommitmentSignature, BlockCommitmentSignatureElem, BlockHash, BlockHeader, BlockNumber, - BlockTimestamp, ClassCommitment, ClassHash, EventCommitment, Fee, GasPrice, ReceiptCommitment, - SequencerAddress, SierraHash, SignedBlockHeader, StateCommitment, StateDiffCommitment, - StorageCommitment, TransactionCommitment, TransactionHash, TransactionIndex, + BlockCommitmentSignature, + BlockCommitmentSignatureElem, + BlockHash, + BlockHeader, + BlockNumber, + BlockTimestamp, + ClassCommitment, + ClassHash, + EventCommitment, + Fee, + GasPrice, + ReceiptCommitment, + SequencerAddress, + SierraHash, + SignedBlockHeader, + StateCommitment, + StateDiffCommitment, + StorageCommitment, + TransactionCommitment, + TransactionHash, + TransactionIndex, }; use tagged::Tagged; use tagged_debug_derive::TaggedDebug; diff --git a/crates/p2p_proto/src/header.rs b/crates/p2p_proto/src/header.rs index b2719c6354..792953d3cf 100644 --- a/crates/p2p_proto/src/header.rs +++ b/crates/p2p_proto/src/header.rs @@ -5,7 +5,13 @@ use tagged::Tagged; use tagged_debug_derive::TaggedDebug; use crate::common::{ - Address, BlockId, ConsensusSignature, Hash, Iteration, L1DataAvailabilityMode, Patricia, + Address, + BlockId, + ConsensusSignature, + Hash, + Iteration, + L1DataAvailabilityMode, + Patricia, StateDiffCommitment, }; use crate::{proto, proto_field, ToProtobuf, TryFromProtobuf}; diff --git a/crates/p2p_proto/src/receipt.rs b/crates/p2p_proto/src/receipt.rs index 38f26c2ffa..5b35e57b69 100644 --- a/crates/p2p_proto/src/receipt.rs +++ b/crates/p2p_proto/src/receipt.rs @@ -179,7 +179,11 @@ impl TryFromProtobuf for Receipt { field_name: &'static str, ) -> Result { use proto::receipt::receipt::Type::{ - Declare, DeployAccount, DeprecatedDeploy, Invoke, L1Handler, + Declare, + DeployAccount, + DeprecatedDeploy, + Invoke, + L1Handler, }; Ok(match proto_field(input.r#type, field_name)? { @@ -197,7 +201,11 @@ impl TryFromProtobuf for Receipt { impl ToProtobuf for Receipt { fn to_protobuf(self) -> proto::receipt::Receipt { use proto::receipt::receipt::Type::{ - Declare, DeployAccount, DeprecatedDeploy, Invoke, L1Handler, + Declare, + DeployAccount, + DeprecatedDeploy, + Invoke, + L1Handler, }; let r#type = Some(match self { diff --git a/crates/p2p_proto/src/state.rs b/crates/p2p_proto/src/state.rs index 89644632f7..055181aebf 100644 --- a/crates/p2p_proto/src/state.rs +++ b/crates/p2p_proto/src/state.rs @@ -53,7 +53,9 @@ pub enum StateDiffsResponse { impl ToProtobuf for StateDiffsResponse { fn to_protobuf(self) -> proto::state::StateDiffsResponse { use proto::state::state_diffs_response::StateDiffMessage::{ - ContractDiff, DeclaredClass, Fin, + ContractDiff, + DeclaredClass, + Fin, }; proto::state::StateDiffsResponse { state_diff_message: Some(match self { @@ -71,7 +73,9 @@ impl TryFromProtobuf for StateDiffsResponse { field_name: &'static str, ) -> Result { use proto::state::state_diffs_response::StateDiffMessage::{ - ContractDiff, DeclaredClass, Fin, + ContractDiff, + DeclaredClass, + Fin, }; match proto_field(input.state_diff_message, field_name)? { ContractDiff(x) => { diff --git a/crates/p2p_proto/src/transaction.rs b/crates/p2p_proto/src/transaction.rs index 67d3c7390d..2ca00b2f50 100644 --- a/crates/p2p_proto/src/transaction.rs +++ b/crates/p2p_proto/src/transaction.rs @@ -206,8 +206,17 @@ pub enum TransactionsResponse { impl ToProtobuf for TransactionVariant { fn to_protobuf(self) -> proto::transaction::transaction::Txn { use proto::transaction::transaction::Txn::{ - DeclareV0, DeclareV1, DeclareV2, DeclareV3, Deploy, DeployAccountV1, DeployAccountV3, - InvokeV0, InvokeV1, InvokeV3, L1Handler, + DeclareV0, + DeclareV1, + DeclareV2, + DeclareV3, + Deploy, + DeployAccountV1, + DeployAccountV3, + InvokeV0, + InvokeV1, + InvokeV3, + L1Handler, }; match self { Self::DeclareV0(txn) => DeclareV0(txn.to_protobuf()), @@ -231,8 +240,17 @@ impl TryFromProtobuf for TransactionVarian field_name: &'static str, ) -> Result { use proto::transaction::transaction::Txn::{ - DeclareV0, DeclareV1, DeclareV2, DeclareV3, Deploy, DeployAccountV1, DeployAccountV3, - InvokeV0, InvokeV1, InvokeV3, L1Handler, + DeclareV0, + DeclareV1, + DeclareV2, + DeclareV3, + Deploy, + DeployAccountV1, + DeployAccountV3, + InvokeV0, + InvokeV1, + InvokeV3, + L1Handler, }; match input { DeclareV0(t) => TryFromProtobuf::try_from_protobuf(t, field_name).map(Self::DeclareV0), @@ -259,7 +277,8 @@ impl TryFromProtobuf for TransactionVarian impl ToProtobuf for TransactionsResponse { fn to_protobuf(self) -> proto::transaction::TransactionsResponse { use proto::transaction::transactions_response::TransactionMessage::{ - Fin, TransactionWithReceipt, + Fin, + TransactionWithReceipt, }; proto::transaction::TransactionsResponse { transaction_message: Some(match self { @@ -276,7 +295,8 @@ impl TryFromProtobuf for TransactionsR field_name: &'static str, ) -> Result { use proto::transaction::transactions_response::TransactionMessage::{ - Fin, TransactionWithReceipt, + Fin, + TransactionWithReceipt, }; Ok(match proto_field(input.transaction_message, field_name)? { TransactionWithReceipt(t) => { diff --git a/crates/p2p_stream/src/handler.rs b/crates/p2p_stream/src/handler.rs index 56c8552995..fbfc192e24 100644 --- a/crates/p2p_stream/src/handler.rs +++ b/crates/p2p_stream/src/handler.rs @@ -34,8 +34,14 @@ use std::{fmt, io}; use futures::channel::mpsc; use futures::prelude::*; use libp2p::swarm::handler::{ - ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, DialUpgradeError, - FullyNegotiatedInbound, FullyNegotiatedOutbound, ListenUpgradeError, StreamUpgradeError, + ConnectionEvent, + ConnectionHandler, + ConnectionHandlerEvent, + DialUpgradeError, + FullyNegotiatedInbound, + FullyNegotiatedOutbound, + ListenUpgradeError, + StreamUpgradeError, }; use libp2p::swarm::SubstreamProtocol; diff --git a/crates/p2p_stream/src/lib.rs b/crates/p2p_stream/src/lib.rs index 54a8441526..8124ea513a 100644 --- a/crates/p2p_stream/src/lib.rs +++ b/crates/p2p_stream/src/lib.rs @@ -69,8 +69,15 @@ use libp2p::identity::PeerId; use libp2p::swarm::behaviour::{AddressChange, ConnectionClosed, DialFailure, FromSwarm}; use libp2p::swarm::dial_opts::DialOpts; use libp2p::swarm::{ - ConnectionDenied, ConnectionHandler, ConnectionId, NetworkBehaviour, NotifyHandler, THandler, - THandlerInEvent, THandlerOutEvent, ToSwarm, + ConnectionDenied, + ConnectionHandler, + ConnectionId, + NetworkBehaviour, + NotifyHandler, + THandler, + THandlerInEvent, + THandlerOutEvent, + ToSwarm, }; use crate::handler::OutboundMessage; diff --git a/crates/p2p_stream/tests/error_reporting.rs b/crates/p2p_stream/tests/error_reporting.rs index 59c815bec5..e9f1aecbd1 100644 --- a/crates/p2p_stream/tests/error_reporting.rs +++ b/crates/p2p_stream/tests/error_reporting.rs @@ -8,9 +8,15 @@ use p2p_stream::{InboundFailure, OutboundFailure}; pub mod utils; use utils::{ - new_swarm, new_swarm_with_timeout, wait_inbound_failure, wait_inbound_request, - wait_inbound_response_stream_closed, wait_no_events, wait_outbound_failure, - wait_outbound_request_sent_awaiting_responses, Action, + new_swarm, + new_swarm_with_timeout, + wait_inbound_failure, + wait_inbound_request, + wait_inbound_response_stream_closed, + wait_no_events, + wait_outbound_failure, + wait_outbound_request_sent_awaiting_responses, + Action, }; #[test_log::test(tokio::test)] diff --git a/crates/p2p_stream/tests/sanity.rs b/crates/p2p_stream/tests/sanity.rs index e92818f667..636597f068 100644 --- a/crates/p2p_stream/tests/sanity.rs +++ b/crates/p2p_stream/tests/sanity.rs @@ -9,8 +9,12 @@ use rstest::rstest; pub mod utils; use utils::{ - new_swarm_with_timeout, wait_inbound_request, wait_inbound_response_stream_closed, - wait_outbound_request_sent_awaiting_responses, wait_outbound_response_stream_closed, Action, + new_swarm_with_timeout, + wait_inbound_request, + wait_inbound_response_stream_closed, + wait_outbound_request_sent_awaiting_responses, + wait_outbound_response_stream_closed, + Action, TestSwarm, }; diff --git a/crates/pathfinder/examples/compute_pre0132_hashes.rs b/crates/pathfinder/examples/compute_pre0132_hashes.rs index 9ef95c4c17..3c49935573 100644 --- a/crates/pathfinder/examples/compute_pre0132_hashes.rs +++ b/crates/pathfinder/examples/compute_pre0132_hashes.rs @@ -3,12 +3,19 @@ use std::num::NonZeroU32; use anyhow::{ensure, Context}; use pathfinder_common::{ - BlockHeader, BlockNumber, ReceiptCommitment, StarknetVersion, StateCommitment, + BlockHeader, + BlockNumber, + ReceiptCommitment, + StarknetVersion, + StateCommitment, StorageCommitment, }; use pathfinder_lib::state::block_hash::{ - calculate_event_commitment, calculate_receipt_commitment, calculate_transaction_commitment, - compute_final_hash, BlockHeaderData, + calculate_event_commitment, + calculate_receipt_commitment, + calculate_transaction_commitment, + compute_final_hash, + BlockHeaderData, }; const VERSION_CUTOFF: StarknetVersion = StarknetVersion::V_0_13_2; diff --git a/crates/pathfinder/examples/feeder_gateway.rs b/crates/pathfinder/examples/feeder_gateway.rs index 9e3e7a1403..f1c1203eca 100644 --- a/crates/pathfinder/examples/feeder_gateway.rs +++ b/crates/pathfinder/examples/feeder_gateway.rs @@ -31,7 +31,11 @@ use anyhow::Context; use clap::{Args, Parser}; use pathfinder_common::state_update::ContractClassUpdate; use pathfinder_common::{ - BlockCommitmentSignature, BlockCommitmentSignatureElem, BlockHash, BlockNumber, Chain, + BlockCommitmentSignature, + BlockCommitmentSignatureElem, + BlockHash, + BlockNumber, + Chain, ClassHash, }; use pathfinder_lib::state::block_hash::calculate_receipt_commitment; @@ -39,7 +43,10 @@ use pathfinder_storage::BlockId; use primitive_types::H160; use serde::{Deserialize, Serialize}; use starknet_gateway_types::reply::state_update::{ - DeclaredSierraClass, DeployedContract, ReplacedClass, StorageDiff, + DeclaredSierraClass, + DeployedContract, + ReplacedClass, + StorageDiff, }; use starknet_gateway_types::reply::{GasPrices, Status}; use tracing_subscriber::prelude::*; @@ -347,7 +354,9 @@ async fn serve(cli: Cli) -> anyhow::Result<()> { fn get_chain(tx: &pathfinder_storage::Transaction<'_>) -> anyhow::Result { use pathfinder_common::consts::{ - MAINNET_GENESIS_HASH, SEPOLIA_INTEGRATION_GENESIS_HASH, SEPOLIA_TESTNET_GENESIS_HASH, + MAINNET_GENESIS_HASH, + SEPOLIA_INTEGRATION_GENESIS_HASH, + SEPOLIA_TESTNET_GENESIS_HASH, }; let genesis_hash = tx diff --git a/crates/pathfinder/examples/re_execute.rs b/crates/pathfinder/examples/re_execute.rs index 50a2d4b479..93f2e66cec 100644 --- a/crates/pathfinder/examples/re_execute.rs +++ b/crates/pathfinder/examples/re_execute.rs @@ -97,7 +97,9 @@ fn main() -> anyhow::Result<()> { fn get_chain_id(tx: &pathfinder_storage::Transaction<'_>) -> anyhow::Result { use pathfinder_common::consts::{ - MAINNET_GENESIS_HASH, SEPOLIA_INTEGRATION_GENESIS_HASH, SEPOLIA_TESTNET_GENESIS_HASH, + MAINNET_GENESIS_HASH, + SEPOLIA_INTEGRATION_GENESIS_HASH, + SEPOLIA_TESTNET_GENESIS_HASH, }; let (_, genesis_hash) = tx diff --git a/crates/pathfinder/examples/verify_block_hashes.rs b/crates/pathfinder/examples/verify_block_hashes.rs index 0078fdc5d6..c606825de8 100644 --- a/crates/pathfinder/examples/verify_block_hashes.rs +++ b/crates/pathfinder/examples/verify_block_hashes.rs @@ -3,7 +3,10 @@ use std::num::NonZeroU32; use anyhow::Context; use pathfinder_common::{BlockNumber, Chain, ChainId, ReceiptCommitment}; use pathfinder_lib::state::block_hash::{ - calculate_receipt_commitment, verify_block_hash, BlockHeaderData, VerifyResult, + calculate_receipt_commitment, + verify_block_hash, + BlockHeaderData, + VerifyResult, }; /// Verify block hashes in a pathfinder database. diff --git a/crates/pathfinder/src/bin/pathfinder/main.rs b/crates/pathfinder/src/bin/pathfinder/main.rs index fd230b2922..641b71a07c 100644 --- a/crates/pathfinder/src/bin/pathfinder/main.rs +++ b/crates/pathfinder/src/bin/pathfinder/main.rs @@ -891,7 +891,9 @@ async fn verify_database( if let Some(database_genesis) = db_genesis { use pathfinder_common::consts::{ - MAINNET_GENESIS_HASH, SEPOLIA_INTEGRATION_GENESIS_HASH, SEPOLIA_TESTNET_GENESIS_HASH, + MAINNET_GENESIS_HASH, + SEPOLIA_INTEGRATION_GENESIS_HASH, + SEPOLIA_TESTNET_GENESIS_HASH, }; let db_network = match database_genesis { diff --git a/crates/pathfinder/src/p2p_network/sync_handlers.rs b/crates/pathfinder/src/p2p_network/sync_handlers.rs index cd9a465366..fe59b3a680 100644 --- a/crates/pathfinder/src/p2p_network/sync_handlers.rs +++ b/crates/pathfinder/src/p2p_network/sync_handlers.rs @@ -3,12 +3,22 @@ use futures::SinkExt; use p2p::client::conv::ToDto; use p2p_proto::class::{Class, ClassesRequest, ClassesResponse}; use p2p_proto::common::{ - Address, BlockNumberOrHash, Direction, Hash, Iteration, Step, VolitionDomain, + Address, + BlockNumberOrHash, + Direction, + Hash, + Iteration, + Step, + VolitionDomain, }; use p2p_proto::event::{EventsRequest, EventsResponse}; use p2p_proto::header::{BlockHeadersRequest, BlockHeadersResponse}; use p2p_proto::state::{ - ContractDiff, ContractStoredValue, DeclaredClass, StateDiffsRequest, StateDiffsResponse, + ContractDiff, + ContractStoredValue, + DeclaredClass, + StateDiffsRequest, + StateDiffsResponse, }; use p2p_proto::transaction::{TransactionWithReceipt, TransactionsRequest, TransactionsResponse}; use pathfinder_common::{class_definition, BlockHash, BlockNumber, SignedBlockHeader}; diff --git a/crates/pathfinder/src/p2p_network/sync_handlers/tests.rs b/crates/pathfinder/src/p2p_network/sync_handlers/tests.rs index 496b2c7912..36a287c1b4 100644 --- a/crates/pathfinder/src/p2p_network/sync_handlers/tests.rs +++ b/crates/pathfinder/src/p2p_network/sync_handlers/tests.rs @@ -47,7 +47,11 @@ mod boundary_conditions { use super::I64_MAX; use crate::p2p_network::sync_handlers::{ - get_classes, get_events, get_headers, get_state_diffs, get_transactions, + get_classes, + get_events, + get_headers, + get_state_diffs, + get_transactions, }; mod zero_limit_yields_fin_invalid_start_yields_fin { @@ -106,17 +110,32 @@ mod prop { use p2p_proto::event::{EventsRequest, EventsResponse}; use p2p_proto::header::{BlockHeadersRequest, BlockHeadersResponse}; use p2p_proto::state::{ - ContractDiff, ContractStoredValue, DeclaredClass, StateDiffsRequest, StateDiffsResponse, + ContractDiff, + ContractStoredValue, + DeclaredClass, + StateDiffsRequest, + StateDiffsResponse, }; use p2p_proto::transaction::{ - TransactionWithReceipt, TransactionsRequest, TransactionsResponse, + TransactionWithReceipt, + TransactionsRequest, + TransactionsResponse, }; use pathfinder_common::event::Event; use pathfinder_common::state_update::SystemContractUpdate; use pathfinder_common::transaction::TransactionVariant; use pathfinder_common::{ - BlockNumber, CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, - SignedBlockHeader, StorageAddress, StorageValue, TransactionHash, TransactionIndex, + BlockNumber, + CasmHash, + ClassHash, + ContractAddress, + ContractNonce, + SierraHash, + SignedBlockHeader, + StorageAddress, + StorageValue, + TransactionHash, + TransactionIndex, }; use pathfinder_crypto::Felt; use pathfinder_storage::fake::Block; @@ -370,7 +389,10 @@ mod prop { mod workaround { use pathfinder_common::transaction::{ - EntryPointType, InvokeTransactionV0, L1HandlerTransaction, TransactionVariant, + EntryPointType, + InvokeTransactionV0, + L1HandlerTransaction, + TransactionVariant, }; use pathfinder_common::TransactionNonce; diff --git a/crates/pathfinder/src/state.rs b/crates/pathfinder/src/state.rs index 6b13f35b92..a827ac7f33 100644 --- a/crates/pathfinder/src/state.rs +++ b/crates/pathfinder/src/state.rs @@ -2,5 +2,12 @@ pub mod block_hash; mod sync; pub use sync::{ - l1, l2, revert, sync, update_starknet_state, Gossiper, SyncContext, RESET_DELAY_ON_FAILURE, + l1, + l2, + revert, + sync, + update_starknet_state, + Gossiper, + SyncContext, + RESET_DELAY_ON_FAILURE, }; diff --git a/crates/pathfinder/src/state/block_hash.rs b/crates/pathfinder/src/state/block_hash.rs index aff7747ade..838fb59ce7 100644 --- a/crates/pathfinder/src/state/block_hash.rs +++ b/crates/pathfinder/src/state/block_hash.rs @@ -7,9 +7,23 @@ use pathfinder_common::hash::{FeltHash, PedersenHash, PoseidonHash}; use pathfinder_common::receipt::{ExecutionStatus, Receipt}; use pathfinder_common::transaction::{Transaction, TransactionVariant}; use pathfinder_common::{ - felt_bytes, BlockHash, BlockHeader, BlockNumber, BlockTimestamp, Chain, ChainId, - EventCommitment, GasPrice, L1DataAvailabilityMode, ReceiptCommitment, SequencerAddress, - StarknetVersion, StateCommitment, StateDiffCommitment, TransactionCommitment, TransactionHash, + felt_bytes, + BlockHash, + BlockHeader, + BlockNumber, + BlockTimestamp, + Chain, + ChainId, + EventCommitment, + GasPrice, + L1DataAvailabilityMode, + ReceiptCommitment, + SequencerAddress, + StarknetVersion, + StateCommitment, + StateDiffCommitment, + TransactionCommitment, + TransactionHash, TransactionSignatureElem, }; use pathfinder_crypto::hash::{pedersen_hash, poseidon_hash_many, HashChain, PoseidonHasher}; @@ -793,10 +807,18 @@ mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::receipt::{ExecutionResources, L1Gas, L2ToL1Message}; use pathfinder_common::transaction::{ - EntryPointType, InvokeTransactionV0, InvokeTransactionV3, + EntryPointType, + InvokeTransactionV0, + InvokeTransactionV3, }; use pathfinder_common::{ - felt, ContractAddress, EventData, EventKey, Fee, L2ToL1MessagePayloadElem, TransactionHash, + felt, + ContractAddress, + EventData, + EventKey, + Fee, + L2ToL1MessagePayloadElem, + TransactionHash, }; use pathfinder_crypto::Felt; use starknet_gateway_test_fixtures::v0_13_2; diff --git a/crates/pathfinder/src/state/sync.rs b/crates/pathfinder/src/state/sync.rs index 1f454e94e9..9715085e4f 100644 --- a/crates/pathfinder/src/state/sync.rs +++ b/crates/pathfinder/src/state/sync.rs @@ -12,7 +12,11 @@ use anyhow::Context; use pathfinder_common::prelude::*; use pathfinder_common::state_update::StateUpdateRef; use pathfinder_common::{ - BlockCommitmentSignature, Chain, PublicKey, ReceiptCommitment, StateDiffCommitment, + BlockCommitmentSignature, + Chain, + PublicKey, + ReceiptCommitment, + StateDiffCommitment, }; use pathfinder_crypto::Felt; use pathfinder_ethereum::{EthereumApi, EthereumStateUpdate}; @@ -1264,9 +1268,20 @@ mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - felt_bytes, BlockCommitmentSignature, BlockCommitmentSignatureElem, BlockHash, BlockHeader, - BlockNumber, ClassHash, EventCommitment, ReceiptCommitment, SierraHash, StateCommitment, - StateDiffCommitment, StateUpdate, TransactionCommitment, + felt_bytes, + BlockCommitmentSignature, + BlockCommitmentSignatureElem, + BlockHash, + BlockHeader, + BlockNumber, + ClassHash, + EventCommitment, + ReceiptCommitment, + SierraHash, + StateCommitment, + StateDiffCommitment, + StateUpdate, + TransactionCommitment, }; use pathfinder_crypto::Felt; use pathfinder_rpc::SyncState; diff --git a/crates/pathfinder/src/state/sync/l2.rs b/crates/pathfinder/src/state/sync/l2.rs index 2da51fa9b7..8d1908e791 100644 --- a/crates/pathfinder/src/state/sync/l2.rs +++ b/crates/pathfinder/src/state/sync/l2.rs @@ -5,9 +5,22 @@ use anyhow::{anyhow, Context}; use futures::{StreamExt, TryStreamExt}; use pathfinder_common::state_update::{ContractClassUpdate, StateUpdateData}; use pathfinder_common::{ - BlockCommitmentSignature, BlockHash, BlockNumber, CasmHash, Chain, ChainId, ClassHash, - EventCommitment, PublicKey, ReceiptCommitment, SierraHash, StarknetVersion, StateCommitment, - StateDiffCommitment, StateUpdate, TransactionCommitment, + BlockCommitmentSignature, + BlockHash, + BlockNumber, + CasmHash, + Chain, + ChainId, + ClassHash, + EventCommitment, + PublicKey, + ReceiptCommitment, + SierraHash, + StarknetVersion, + StateCommitment, + StateDiffCommitment, + StateUpdate, + TransactionCommitment, }; use pathfinder_storage::Storage; use starknet_gateway_client::GatewayApi; @@ -17,8 +30,11 @@ use tokio::sync::mpsc; use tracing::Instrument; use crate::state::block_hash::{ - calculate_event_commitment, calculate_receipt_commitment, calculate_transaction_commitment, - verify_block_hash, BlockHeaderData, + calculate_event_commitment, + calculate_receipt_commitment, + calculate_transaction_commitment, + verify_block_hash, + BlockHeaderData, }; use crate::state::sync::class::{download_class, DownloadedClass}; use crate::state::sync::SyncEvent; @@ -1161,15 +1177,30 @@ mod tests { use assert_matches::assert_matches; use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - BlockHash, BlockId, BlockNumber, BlockTimestamp, Chain, ChainId, ClassHash, - ContractAddress, GasPrice, PublicKey, SequencerAddress, StarknetVersion, - StateCommitment, StateUpdate, StorageAddress, StorageValue, + BlockHash, + BlockId, + BlockNumber, + BlockTimestamp, + Chain, + ChainId, + ClassHash, + ContractAddress, + GasPrice, + PublicKey, + SequencerAddress, + StarknetVersion, + StateCommitment, + StateUpdate, + StorageAddress, + StorageValue, }; use pathfinder_crypto::Felt; use pathfinder_storage::StorageBuilder; use starknet_gateway_client::MockGatewayApi; use starknet_gateway_types::error::{ - KnownStarknetErrorCode, SequencerError, StarknetError, + KnownStarknetErrorCode, + SequencerError, + StarknetError, }; use starknet_gateway_types::reply; use starknet_gateway_types::reply::GasPrices; diff --git a/crates/pathfinder/src/state/sync/pending.rs b/crates/pathfinder/src/state/sync/pending.rs index 41c4190ee6..03a15b0559 100644 --- a/crates/pathfinder/src/state/sync/pending.rs +++ b/crates/pathfinder/src/state/sync/pending.rs @@ -105,13 +105,22 @@ mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::transaction::{L1HandlerTransaction, Transaction, TransactionVariant}; use pathfinder_common::{ - BlockHash, BlockNumber, BlockTimestamp, GasPrice, StarknetVersion, StateCommitment, + BlockHash, + BlockNumber, + BlockTimestamp, + GasPrice, + StarknetVersion, + StateCommitment, StateUpdate, }; use pathfinder_storage::StorageBuilder; use starknet_gateway_client::MockGatewayApi; use starknet_gateway_types::reply::{ - Block, GasPrices, L1DataAvailabilityMode, PendingBlock, Status, + Block, + GasPrices, + L1DataAvailabilityMode, + PendingBlock, + Status, }; use tokio::sync::watch; diff --git a/crates/pathfinder/src/state/sync/revert.rs b/crates/pathfinder/src/state/sync/revert.rs index 0d0e0b7bee..6abe0c2042 100644 --- a/crates/pathfinder/src/state/sync/revert.rs +++ b/crates/pathfinder/src/state/sync/revert.rs @@ -1,6 +1,10 @@ use anyhow::Context; use pathfinder_common::{ - BlockHeader, BlockNumber, ClassCommitment, ClassCommitmentLeafHash, StorageCommitment, + BlockHeader, + BlockNumber, + ClassCommitment, + ClassCommitmentLeafHash, + StorageCommitment, }; use pathfinder_merkle_tree::{ClassCommitmentTree, StorageCommitmentTree}; use pathfinder_storage::Transaction; diff --git a/crates/pathfinder/src/sync.rs b/crates/pathfinder/src/sync.rs index 68ca23d344..0f20ec2695 100644 --- a/crates/pathfinder/src/sync.rs +++ b/crates/pathfinder/src/sync.rs @@ -6,14 +6,25 @@ use anyhow::Context; use error::SyncError; use futures::{pin_mut, Stream, StreamExt}; use p2p::client::peer_agnostic::traits::{ - BlockClient, ClassStream, EventStream, HeaderStream, StateDiffStream, StreamItem, + BlockClient, + ClassStream, + EventStream, + HeaderStream, + StateDiffStream, + StreamItem, TransactionStream, }; use p2p::PeerData; use pathfinder_block_hashes::BlockHashDb; use pathfinder_common::error::AnyhowExt; use pathfinder_common::{ - block_hash, BlockHash, BlockNumber, Chain, ChainId, PublicKey, StarknetVersion, + block_hash, + BlockHash, + BlockNumber, + Chain, + ChainId, + PublicKey, + StarknetVersion, }; use pathfinder_ethereum::EthereumStateUpdate; use pathfinder_storage::Transaction; @@ -295,8 +306,12 @@ mod tests { use futures::stream; use http::header; use p2p::client::types::{ - ClassDefinition, ClassDefinitionsError, EventsForBlockByTransaction, - EventsResponseStreamFailure, Receipt as P2PReceipt, StateDiffsError, + ClassDefinition, + ClassDefinitionsError, + EventsForBlockByTransaction, + EventsResponseStreamFailure, + Receipt as P2PReceipt, + StateDiffsError, }; use p2p::libp2p::PeerId; use pathfinder_common::event::Event; @@ -304,7 +319,12 @@ mod tests { use pathfinder_common::state_update::StateUpdateData; use pathfinder_common::transaction::Transaction; use pathfinder_common::{ - BlockHeader, BlockId, ClassHash, SierraHash, SignedBlockHeader, TransactionHash, + BlockHeader, + BlockId, + ClassHash, + SierraHash, + SignedBlockHeader, + TransactionHash, }; use pathfinder_crypto::signature::ecdsa_sign; use pathfinder_crypto::Felt; @@ -319,8 +339,11 @@ mod tests { use super::*; use crate::state::block_hash::{ - calculate_event_commitment, calculate_receipt_commitment, calculate_transaction_commitment, - compute_final_hash, BlockHeaderData, + calculate_event_commitment, + calculate_receipt_commitment, + calculate_transaction_commitment, + compute_final_hash, + BlockHeaderData, }; use crate::state::update_starknet_state; diff --git a/crates/pathfinder/src/sync/checkpoint.rs b/crates/pathfinder/src/sync/checkpoint.rs index e21746f57a..2a76e12685 100644 --- a/crates/pathfinder/src/sync/checkpoint.rs +++ b/crates/pathfinder/src/sync/checkpoint.rs @@ -6,7 +6,12 @@ use anyhow::Context; use futures::{Stream, StreamExt, TryStreamExt}; use p2p::client::conv::TryFromDto; use p2p::client::peer_agnostic::traits::{ - BlockClient, ClassStream, EventStream, HeaderStream, StateDiffStream, StreamItem, + BlockClient, + ClassStream, + EventStream, + HeaderStream, + StateDiffStream, + StreamItem, TransactionStream, }; use p2p::client::types::{ClassDefinition, EventsForBlockByTransaction, TransactionData}; @@ -18,7 +23,13 @@ use pathfinder_common::receipt::Receipt; use pathfinder_common::state_update::StateUpdateData; use pathfinder_common::transaction::{Transaction, TransactionVariant}; use pathfinder_common::{ - BlockHash, BlockNumber, Chain, ChainId, ClassHash, PublicKey, SignedBlockHeader, + BlockHash, + BlockNumber, + Chain, + ChainId, + ClassHash, + PublicKey, + SignedBlockHeader, TransactionIndex, }; use pathfinder_ethereum::EthereumStateUpdate; @@ -712,10 +723,23 @@ mod tests { use assert_matches::assert_matches; use futures::stream; use pathfinder_common::{ - public_key, BlockCommitmentSignature, BlockCommitmentSignatureElem, BlockHash, - BlockHeader, BlockTimestamp, ClassCommitment, EventCommitment, GasPrice, - L1DataAvailabilityMode, ReceiptCommitment, SequencerAddress, StarknetVersion, - StateCommitment, StateDiffCommitment, StorageCommitment, TransactionCommitment, + public_key, + BlockCommitmentSignature, + BlockCommitmentSignatureElem, + BlockHash, + BlockHeader, + BlockTimestamp, + ClassCommitment, + EventCommitment, + GasPrice, + L1DataAvailabilityMode, + ReceiptCommitment, + SequencerAddress, + StarknetVersion, + StateCommitment, + StateDiffCommitment, + StorageCommitment, + TransactionCommitment, }; use pathfinder_storage::StorageBuilder; use rstest::rstest; @@ -1379,14 +1403,22 @@ mod tests { use pathfinder_common::event::Event; use pathfinder_common::transaction::TransactionVariant; use pathfinder_common::{ - class_hash, felt, sierra_hash, BlockHeader, CasmHash, ClassHash, SierraHash, - SignedBlockHeader, TransactionHash, + class_hash, + felt, + sierra_hash, + BlockHeader, + CasmHash, + ClassHash, + SierraHash, + SignedBlockHeader, + TransactionHash, }; use pathfinder_crypto::Felt; use pathfinder_storage::fake::{self as fake_storage, Block}; use pathfinder_storage::StorageBuilder; use starknet_gateway_test_fixtures::class_definitions::{ - CAIRO_0_10_TUPLES_INTEGRATION as CAIRO, CAIRO_0_11_SIERRA as SIERRA0, + CAIRO_0_10_TUPLES_INTEGRATION as CAIRO, + CAIRO_0_11_SIERRA as SIERRA0, CAIRO_2_0_0_STACK_OVERFLOW as SIERRA2, }; use starknet_gateway_types::error::SequencerError; diff --git a/crates/pathfinder/src/sync/class_definitions.rs b/crates/pathfinder/src/sync/class_definitions.rs index 30673b307f..4db1522c39 100644 --- a/crates/pathfinder/src/sync/class_definitions.rs +++ b/crates/pathfinder/src/sync/class_definitions.rs @@ -17,7 +17,8 @@ use rayon::iter::{IntoParallelIterator, ParallelIterator}; use serde_json::de; use starknet_gateway_client::GatewayApi; use starknet_gateway_types::class_hash::from_parts::{ - compute_cairo_class_hash, compute_sierra_class_hash, + compute_cairo_class_hash, + compute_sierra_class_hash, }; use starknet_gateway_types::error::SequencerError; use starknet_gateway_types::reply::call; diff --git a/crates/pathfinder/src/sync/events.rs b/crates/pathfinder/src/sync/events.rs index aa4d6ad131..6726f77f18 100644 --- a/crates/pathfinder/src/sync/events.rs +++ b/crates/pathfinder/src/sync/events.rs @@ -9,7 +9,11 @@ use pathfinder_common::event::Event; use pathfinder_common::receipt::Receipt; use pathfinder_common::transaction::Transaction; use pathfinder_common::{ - BlockHeader, BlockNumber, EventCommitment, StarknetVersion, TransactionHash, + BlockHeader, + BlockNumber, + EventCommitment, + StarknetVersion, + TransactionHash, }; use pathfinder_storage::Storage; use tokio::sync::mpsc; diff --git a/crates/pathfinder/src/sync/headers.rs b/crates/pathfinder/src/sync/headers.rs index e3aaebd1d5..a0589230a5 100644 --- a/crates/pathfinder/src/sync/headers.rs +++ b/crates/pathfinder/src/sync/headers.rs @@ -5,8 +5,16 @@ use p2p::libp2p::PeerId; use p2p::PeerData; use p2p_proto::header; use pathfinder_common::{ - BlockHash, BlockHeader, BlockNumber, Chain, ChainId, ClassCommitment, PublicKey, - SignedBlockHeader, StarknetVersion, StorageCommitment, + BlockHash, + BlockHeader, + BlockNumber, + Chain, + ChainId, + ClassCommitment, + PublicKey, + SignedBlockHeader, + StarknetVersion, + StorageCommitment, }; use pathfinder_storage::Storage; use tokio::task::spawn_blocking; diff --git a/crates/pathfinder/src/sync/state_updates.rs b/crates/pathfinder/src/sync/state_updates.rs index ea6debaced..26ba3b2e8f 100644 --- a/crates/pathfinder/src/sync/state_updates.rs +++ b/crates/pathfinder/src/sync/state_updates.rs @@ -6,12 +6,26 @@ use anyhow::Context; use p2p::libp2p::PeerId; use p2p::PeerData; use pathfinder_common::state_update::{ - self, ContractClassUpdate, ContractUpdate, StateUpdateData, StateUpdateRef, + self, + ContractClassUpdate, + ContractUpdate, + StateUpdateData, + StateUpdateRef, SystemContractUpdate, }; use pathfinder_common::{ - BlockHash, BlockHeader, BlockNumber, CasmHash, ClassCommitment, ClassHash, ContractAddress, - SierraHash, StarknetVersion, StateCommitment, StateDiffCommitment, StateUpdate, + BlockHash, + BlockHeader, + BlockNumber, + CasmHash, + ClassCommitment, + ClassHash, + ContractAddress, + SierraHash, + StarknetVersion, + StateCommitment, + StateDiffCommitment, + StateUpdate, StorageCommitment, }; use pathfinder_merkle_tree::contract_state::ContractStateUpdateResult; @@ -133,10 +147,19 @@ mod multi_block { use std::collections::{HashMap, HashSet}; use pathfinder_common::state_update::{ - ContractClassUpdate, ContractUpdateRef, StateUpdateRef, StorageRef, SystemContractUpdateRef, + ContractClassUpdate, + ContractUpdateRef, + StateUpdateRef, + StorageRef, + SystemContractUpdateRef, }; use pathfinder_common::{ - CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, StorageAddress, + CasmHash, + ClassHash, + ContractAddress, + ContractNonce, + SierraHash, + StorageAddress, StorageValue, }; diff --git a/crates/pathfinder/src/sync/track.rs b/crates/pathfinder/src/sync/track.rs index fded0da4da..0b69f909ee 100644 --- a/crates/pathfinder/src/sync/track.rs +++ b/crates/pathfinder/src/sync/track.rs @@ -7,8 +7,11 @@ use futures::{pin_mut, Stream, StreamExt, TryStreamExt}; use p2p::client::peer_agnostic::traits::{BlockClient, HeaderStream}; use p2p::client::peer_agnostic::Client as P2PClient; use p2p::client::types::{ - ClassDefinition as P2PClassDefinition, ClassDefinitionsError, EventsResponseStreamFailure, - StateDiffsError, TransactionData, + ClassDefinition as P2PClassDefinition, + ClassDefinitionsError, + EventsResponseStreamFailure, + StateDiffsError, + TransactionData, }; use p2p::libp2p::PeerId; use p2p::PeerData; @@ -17,9 +20,24 @@ use pathfinder_common::receipt::Receipt; use pathfinder_common::state_update::{DeclaredClasses, StateUpdateData}; use pathfinder_common::transaction::{Transaction, TransactionVariant}; use pathfinder_common::{ - BlockHash, BlockHeader, BlockNumber, Chain, ChainId, ClassCommitment, ClassHash, - EventCommitment, PublicKey, ReceiptCommitment, SierraHash, SignedBlockHeader, StarknetVersion, - StateCommitment, StateDiffCommitment, StateUpdate, StorageCommitment, TransactionCommitment, + BlockHash, + BlockHeader, + BlockNumber, + Chain, + ChainId, + ClassCommitment, + ClassHash, + EventCommitment, + PublicKey, + ReceiptCommitment, + SierraHash, + SignedBlockHeader, + StarknetVersion, + StateCommitment, + StateDiffCommitment, + StateUpdate, + StorageCommitment, + TransactionCommitment, TransactionHash, }; use pathfinder_storage::Storage; diff --git a/crates/pathfinder/src/sync/transactions.rs b/crates/pathfinder/src/sync/transactions.rs index e4845f9e7b..c947ec9487 100644 --- a/crates/pathfinder/src/sync/transactions.rs +++ b/crates/pathfinder/src/sync/transactions.rs @@ -7,12 +7,22 @@ use p2p::libp2p::PeerId; use p2p::PeerData; use pathfinder_common::receipt::Receipt; use pathfinder_common::transaction::{ - DeployAccountTransactionV1, DeployAccountTransactionV3, DeployTransactionV0, - DeployTransactionV1, Transaction, TransactionVariant, + DeployAccountTransactionV1, + DeployAccountTransactionV3, + DeployTransactionV0, + DeployTransactionV1, + Transaction, + TransactionVariant, }; use pathfinder_common::{ - BlockHeader, BlockNumber, CallParam, ChainId, ContractAddress, StarknetVersion, - TransactionCommitment, TransactionHash, + BlockHeader, + BlockNumber, + CallParam, + ChainId, + ContractAddress, + StarknetVersion, + TransactionCommitment, + TransactionHash, }; use pathfinder_storage::Storage; use tokio::sync::mpsc; diff --git a/crates/rpc/src/dto/state_update.rs b/crates/rpc/src/dto/state_update.rs index 2ad8de2a02..0c2f2bad04 100644 --- a/crates/rpc/src/dto/state_update.rs +++ b/crates/rpc/src/dto/state_update.rs @@ -1,7 +1,13 @@ use std::collections::HashMap; use pathfinder_common::{ - CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, StorageAddress, StorageValue, + CasmHash, + ClassHash, + ContractAddress, + ContractNonce, + SierraHash, + StorageAddress, + StorageValue, }; use crate::dto; diff --git a/crates/rpc/src/executor.rs b/crates/rpc/src/executor.rs index 6ada865baa..4c9699738b 100644 --- a/crates/rpc/src/executor.rs +++ b/crates/rpc/src/executor.rs @@ -5,7 +5,9 @@ use pathfinder_executor::{ClassInfo, IntoStarkFelt}; use starknet_api::core::PatriciaKey; use crate::types::request::{ - BroadcastedDeployAccountTransaction, BroadcastedInvokeTransaction, BroadcastedTransaction, + BroadcastedDeployAccountTransaction, + BroadcastedInvokeTransaction, + BroadcastedTransaction, }; use crate::types::SierraContractClass; diff --git a/crates/rpc/src/felt.rs b/crates/rpc/src/felt.rs index f69fd13aae..29833ad8b9 100644 --- a/crates/rpc/src/felt.rs +++ b/crates/rpc/src/felt.rs @@ -22,11 +22,31 @@ //! ``` use pathfinder_common::{ - AccountDeploymentDataElem, BlockHash, CallParam, CallResultValue, CasmHash, ChainId, ClassHash, - ConstructorParam, ContractAddress, ContractAddressSalt, ContractNonce, EntryPoint, EventData, - EventKey, L1ToL2MessagePayloadElem, L2ToL1MessagePayloadElem, PaymasterDataElem, - SequencerAddress, SierraHash, StateCommitment, StorageAddress, StorageValue, TransactionHash, - TransactionNonce, TransactionSignatureElem, + AccountDeploymentDataElem, + BlockHash, + CallParam, + CallResultValue, + CasmHash, + ChainId, + ClassHash, + ConstructorParam, + ContractAddress, + ContractAddressSalt, + ContractNonce, + EntryPoint, + EventData, + EventKey, + L1ToL2MessagePayloadElem, + L2ToL1MessagePayloadElem, + PaymasterDataElem, + SequencerAddress, + SierraHash, + StateCommitment, + StorageAddress, + StorageValue, + TransactionHash, + TransactionNonce, + TransactionSignatureElem, }; use pathfinder_crypto::Felt; diff --git a/crates/rpc/src/jsonrpc.rs b/crates/rpc/src/jsonrpc.rs index 672eaa6b48..b579b90bb6 100644 --- a/crates/rpc/src/jsonrpc.rs +++ b/crates/rpc/src/jsonrpc.rs @@ -13,7 +13,12 @@ pub use response::RpcResponse; #[cfg(test)] pub use router::{handle_json_rpc_socket, CATCH_UP_BATCH_SIZE}; pub use router::{ - rpc_handler, CatchUp, RpcRouter, RpcRouterBuilder, RpcSubscriptionFlow, SubscriptionMessage, + rpc_handler, + CatchUp, + RpcRouter, + RpcRouterBuilder, + RpcSubscriptionFlow, + SubscriptionMessage, }; use starknet_gateway_types::reply::Block; use tokio::sync::broadcast; diff --git a/crates/rpc/src/jsonrpc/router/method.rs b/crates/rpc/src/jsonrpc/router/method.rs index 041d84be7d..df37ff9b40 100644 --- a/crates/rpc/src/jsonrpc/router/method.rs +++ b/crates/rpc/src/jsonrpc/router/method.rs @@ -8,7 +8,12 @@ use serde_json::value::RawValue; use tracing::Instrument; use super::{ - run_concurrently, IntoRpcEndpoint, RpcEndpoint, RpcRequestError, RpcResponses, RpcRouter, + run_concurrently, + IntoRpcEndpoint, + RpcEndpoint, + RpcRequestError, + RpcResponses, + RpcRouter, }; use crate::context::RpcContext; use crate::dto::serialize::{SerializeForVersion, Serializer}; diff --git a/crates/rpc/src/jsonrpc/router/subscription.rs b/crates/rpc/src/jsonrpc/router/subscription.rs index 20ecad8f1c..b293351d82 100644 --- a/crates/rpc/src/jsonrpc/router/subscription.rs +++ b/crates/rpc/src/jsonrpc/router/subscription.rs @@ -811,7 +811,11 @@ mod tests { use crate::context::{RpcConfig, RpcContext}; use crate::dto::DeserializeForVersion; use crate::jsonrpc::{ - handle_json_rpc_socket, CatchUp, RpcRouter, RpcSubscriptionFlow, SubscriptionMessage, + handle_json_rpc_socket, + CatchUp, + RpcRouter, + RpcSubscriptionFlow, + SubscriptionMessage, }; use crate::pending::PendingWatcher; use crate::types::syncing::Syncing; diff --git a/crates/rpc/src/jsonrpc/websocket/data.rs b/crates/rpc/src/jsonrpc/websocket/data.rs index 758be480d4..ab650a49c0 100644 --- a/crates/rpc/src/jsonrpc/websocket/data.rs +++ b/crates/rpc/src/jsonrpc/websocket/data.rs @@ -3,7 +3,12 @@ use std::sync::Arc; use pathfinder_common::{ - BlockHash, BlockNumber, ContractAddress, EventData, EventKey, TransactionHash, + BlockHash, + BlockNumber, + ContractAddress, + EventData, + EventKey, + TransactionHash, }; use serde::ser::Error; use serde::Deserialize; diff --git a/crates/rpc/src/jsonrpc/websocket/logic.rs b/crates/rpc/src/jsonrpc/websocket/logic.rs index b2a8e63e99..471f3475c1 100644 --- a/crates/rpc/src/jsonrpc/websocket/logic.rs +++ b/crates/rpc/src/jsonrpc/websocket/logic.rs @@ -29,7 +29,10 @@ use crate::error::ApplicationError; use crate::jsonrpc::request::RawParams; use crate::jsonrpc::router::RpcRequestError; use crate::jsonrpc::websocket::data::{ - EventFilterParams, ResponseEvent, SubscriptionId, SubscriptionItem, + EventFilterParams, + ResponseEvent, + SubscriptionId, + SubscriptionItem, }; use crate::jsonrpc::{RequestId, RpcError, RpcRequest, RpcRouter}; use crate::{BlockHeader, PendingData, RpcVersion}; @@ -663,9 +666,21 @@ mod tests { use pathfinder_common::event::Event; use pathfinder_common::transaction::Transaction; use pathfinder_common::{ - block_hash, event_commitment, event_key, receipt_commitment, state_commitment, - state_diff_commitment, transaction_commitment, transaction_hash, BlockNumber, - BlockTimestamp, ContractAddress, EventData, EventKey, GasPrice, SequencerAddress, + block_hash, + event_commitment, + event_key, + receipt_commitment, + state_commitment, + state_diff_commitment, + transaction_commitment, + transaction_hash, + BlockNumber, + BlockTimestamp, + ContractAddress, + EventData, + EventKey, + GasPrice, + SequencerAddress, StarknetVersion, }; use pathfinder_crypto::Felt; diff --git a/crates/rpc/src/lib.rs b/crates/rpc/src/lib.rs index 0d7b13cbe7..5df688323a 100644 --- a/crates/rpc/src/lib.rs +++ b/crates/rpc/src/lib.rs @@ -257,7 +257,11 @@ pub mod test_utils { use pathfinder_common::macro_prelude::*; use pathfinder_common::prelude::*; use pathfinder_common::receipt::{ - BuiltinCounters, ExecutionResources, ExecutionStatus, L2ToL1Message, Receipt, + BuiltinCounters, + ExecutionResources, + ExecutionStatus, + L2ToL1Message, + Receipt, }; use pathfinder_common::transaction::*; use pathfinder_merkle_tree::{ClassCommitmentTree, StorageCommitmentTree}; diff --git a/crates/rpc/src/method/add_declare_transaction.rs b/crates/rpc/src/method/add_declare_transaction.rs index 95ea16b13e..449814a77a 100644 --- a/crates/rpc/src/method/add_declare_transaction.rs +++ b/crates/rpc/src/method/add_declare_transaction.rs @@ -2,7 +2,9 @@ use pathfinder_common::{ClassHash, TransactionHash}; use starknet_gateway_client::GatewayApi; use starknet_gateway_types::error::SequencerError; use starknet_gateway_types::request::add_transaction::{ - CairoContractDefinition, ContractDefinition, SierraContractDefinition, + CairoContractDefinition, + ContractDefinition, + SierraContractDefinition, }; use crate::context::RpcContext; @@ -66,10 +68,18 @@ impl From for AddDeclareTransactionError { impl From for AddDeclareTransactionError { fn from(e: SequencerError) -> Self { use starknet_gateway_types::error::KnownStarknetErrorCode::{ - ClassAlreadyDeclared, CompilationFailed, ContractBytecodeSizeTooLarge, - ContractClassObjectSizeTooLarge, DuplicatedTransaction, EntryPointNotFound, - InsufficientAccountBalance, InsufficientMaxFee, InvalidCompiledClassHash, - InvalidContractClassVersion, InvalidTransactionNonce, InvalidTransactionVersion, + ClassAlreadyDeclared, + CompilationFailed, + ContractBytecodeSizeTooLarge, + ContractClassObjectSizeTooLarge, + DuplicatedTransaction, + EntryPointNotFound, + InsufficientAccountBalance, + InsufficientMaxFee, + InvalidCompiledClassHash, + InvalidContractClassVersion, + InvalidTransactionNonce, + InvalidTransactionVersion, ValidateFailure, }; match e { @@ -293,21 +303,34 @@ mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - CasmHash, ContractAddress, Fee, ResourceAmount, ResourcePricePerUnit, Tip, - TransactionNonce, TransactionVersion, + CasmHash, + ContractAddress, + Fee, + ResourceAmount, + ResourcePricePerUnit, + Tip, + TransactionNonce, + TransactionVersion, }; use pathfinder_crypto::Felt; use starknet_gateway_test_fixtures::class_definitions::{ - CAIRO_2_0_0_STACK_OVERFLOW, CONTRACT_DEFINITION, + CAIRO_2_0_0_STACK_OVERFLOW, + CONTRACT_DEFINITION, }; use super::*; use crate::types::request::{ - BroadcastedDeclareTransaction, BroadcastedDeclareTransactionV1, - BroadcastedDeclareTransactionV2, BroadcastedDeclareTransactionV3, + BroadcastedDeclareTransaction, + BroadcastedDeclareTransactionV1, + BroadcastedDeclareTransactionV2, + BroadcastedDeclareTransactionV3, }; use crate::types::{ - CairoContractClass, ContractClass, DataAvailabilityMode, ResourceBound, ResourceBounds, + CairoContractClass, + ContractClass, + DataAvailabilityMode, + ResourceBound, + ResourceBounds, SierraContractClass, }; @@ -422,7 +445,9 @@ mod tests { #[test] fn unexpected_error_message() { use starknet_gateway_types::error::{ - KnownStarknetErrorCode, StarknetError, StarknetErrorCode, + KnownStarknetErrorCode, + StarknetError, + StarknetErrorCode, }; let starknet_error = SequencerError::StarknetError(StarknetError { code: StarknetErrorCode::Known( diff --git a/crates/rpc/src/method/add_deploy_account_transaction.rs b/crates/rpc/src/method/add_deploy_account_transaction.rs index 4285e75964..d7e794b40a 100644 --- a/crates/rpc/src/method/add_deploy_account_transaction.rs +++ b/crates/rpc/src/method/add_deploy_account_transaction.rs @@ -5,7 +5,8 @@ use starknet_gateway_types::error::{KnownStarknetErrorCode, SequencerError}; use crate::context::RpcContext; use crate::types::request::{ - BroadcastedDeployAccountTransaction, BroadcastedDeployAccountTransactionV1, + BroadcastedDeployAccountTransaction, + BroadcastedDeployAccountTransactionV1, }; #[derive(Debug, PartialEq, Eq)] @@ -79,9 +80,14 @@ impl From for crate::error::ApplicationError { impl From for AddDeployAccountTransactionError { fn from(e: SequencerError) -> Self { use starknet_gateway_types::error::KnownStarknetErrorCode::{ - DuplicatedTransaction, EntryPointNotFound, InsufficientAccountBalance, - InsufficientMaxFee, InvalidTransactionNonce, InvalidTransactionVersion, - UndeclaredClass, ValidateFailure, + DuplicatedTransaction, + EntryPointNotFound, + InsufficientAccountBalance, + InsufficientMaxFee, + InvalidTransactionNonce, + InvalidTransactionVersion, + UndeclaredClass, + ValidateFailure, }; match e { SequencerError::StarknetError(e) if e.code == UndeclaredClass.into() => { @@ -231,7 +237,11 @@ impl crate::dto::serialize::SerializeForVersion for Output { mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - ResourceAmount, ResourcePricePerUnit, Tip, TransactionNonce, TransactionVersion, + ResourceAmount, + ResourcePricePerUnit, + Tip, + TransactionNonce, + TransactionVersion, }; use super::*; @@ -280,7 +290,9 @@ mod tests { #[test] fn unexpected_error_message() { use starknet_gateway_types::error::{ - KnownStarknetErrorCode, StarknetError, StarknetErrorCode, + KnownStarknetErrorCode, + StarknetError, + StarknetErrorCode, }; let starknet_error = SequencerError::StarknetError(StarknetError { code: StarknetErrorCode::Known(KnownStarknetErrorCode::TransactionLimitExceeded), diff --git a/crates/rpc/src/method/add_invoke_transaction.rs b/crates/rpc/src/method/add_invoke_transaction.rs index e0fb903d75..562a9ccbcf 100644 --- a/crates/rpc/src/method/add_invoke_transaction.rs +++ b/crates/rpc/src/method/add_invoke_transaction.rs @@ -79,8 +79,12 @@ impl From for crate::error::ApplicationError { impl From for AddInvokeTransactionError { fn from(e: SequencerError) -> Self { use starknet_gateway_types::error::KnownStarknetErrorCode::{ - DuplicatedTransaction, EntryPointNotFound, InsufficientAccountBalance, - InsufficientMaxFee, InvalidTransactionNonce, InvalidTransactionVersion, + DuplicatedTransaction, + EntryPointNotFound, + InsufficientAccountBalance, + InsufficientMaxFee, + InvalidTransactionNonce, + InvalidTransactionVersion, ValidateFailure, }; match e { @@ -325,7 +329,9 @@ mod tests { #[test] fn unexpected_error_message() { use starknet_gateway_types::error::{ - KnownStarknetErrorCode, StarknetError, StarknetErrorCode, + KnownStarknetErrorCode, + StarknetError, + StarknetErrorCode, }; let starknet_error = SequencerError::StarknetError(StarknetError { code: StarknetErrorCode::Known(KnownStarknetErrorCode::TransactionLimitExceeded), diff --git a/crates/rpc/src/method/call.rs b/crates/rpc/src/method/call.rs index 45125be9a9..31353c188c 100644 --- a/crates/rpc/src/method/call.rs +++ b/crates/rpc/src/method/call.rs @@ -224,11 +224,21 @@ mod tests { mod in_memory { use pathfinder_common::{ - felt, BlockHash, BlockHeader, BlockNumber, BlockTimestamp, ClassHash, ContractAddress, - GasPrice, StateUpdate, StorageAddress, StorageValue, + felt, + BlockHash, + BlockHeader, + BlockNumber, + BlockTimestamp, + ClassHash, + ContractAddress, + GasPrice, + StateUpdate, + StorageAddress, + StorageValue, }; use starknet_gateway_test_fixtures::class_definitions::{ - CONTRACT_DEFINITION, CONTRACT_DEFINITION_CLASS_HASH, + CONTRACT_DEFINITION, + CONTRACT_DEFINITION_CLASS_HASH, }; use starknet_gateway_types::reply::{GasPrices, L1DataAvailabilityMode, PendingBlock}; diff --git a/crates/rpc/src/method/estimate_fee.rs b/crates/rpc/src/method/estimate_fee.rs index 0b3ab7b964..f94f90c862 100644 --- a/crates/rpc/src/method/estimate_fee.rs +++ b/crates/rpc/src/method/estimate_fee.rs @@ -194,9 +194,13 @@ mod tests { use super::*; use crate::types::request::{ - BroadcastedDeclareTransaction, BroadcastedDeclareTransactionV2, - BroadcastedInvokeTransaction, BroadcastedInvokeTransactionV0, - BroadcastedInvokeTransactionV1, BroadcastedInvokeTransactionV3, BroadcastedTransaction, + BroadcastedDeclareTransaction, + BroadcastedDeclareTransactionV2, + BroadcastedInvokeTransaction, + BroadcastedInvokeTransactionV0, + BroadcastedInvokeTransactionV1, + BroadcastedInvokeTransactionV3, + BroadcastedTransaction, }; use crate::types::{ContractClass, DataAvailabilityMode, ResourceBounds, SierraContractClass}; diff --git a/crates/rpc/src/method/get_compiled_casm.rs b/crates/rpc/src/method/get_compiled_casm.rs index 3a46036bbf..393113f2e0 100644 --- a/crates/rpc/src/method/get_compiled_casm.rs +++ b/crates/rpc/src/method/get_compiled_casm.rs @@ -99,12 +99,15 @@ pub async fn get_compiled_casm(context: RpcContext, input: Input) -> Result Result Result .map_err(Error::Internal) .and_then(|tx| { use starknet_gateway_types::reply::transaction_status::{ - ExecutionStatus as GatewayExecutionStatus, FinalityStatus as GatewayFinalityStatus, + ExecutionStatus as GatewayExecutionStatus, + FinalityStatus as GatewayFinalityStatus, }; let execution_status = tx.execution_status.unwrap_or_default(); diff --git a/crates/rpc/src/method/simulate_transactions.rs b/crates/rpc/src/method/simulate_transactions.rs index c684384d11..3ccee4645c 100644 --- a/crates/rpc/src/method/simulate_transactions.rs +++ b/crates/rpc/src/method/simulate_transactions.rs @@ -179,13 +179,20 @@ impl From for SimulateTransactionError { pub(crate) mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - felt, BlockId, CallParam, ClassHash, EntryPoint, StarknetVersion, StorageValue, + felt, + BlockId, + CallParam, + ClassHash, + EntryPoint, + StarknetVersion, + StorageValue, TransactionVersion, }; use pathfinder_crypto::Felt; use serde::Deserialize; use starknet_gateway_test_fixtures::class_definitions::{ - DUMMY_ACCOUNT_CLASS_HASH, ERC20_CONTRACT_DEFINITION_CLASS_HASH, + DUMMY_ACCOUNT_CLASS_HASH, + ERC20_CONTRACT_DEFINITION_CLASS_HASH, }; use super::simulate_transactions; @@ -193,7 +200,9 @@ pub(crate) mod tests { use crate::dto::serialize::{SerializeForVersion, Serializer}; use crate::method::get_state_update::types::{DeployedContract, Nonce, StateDiff}; use crate::types::request::{ - BroadcastedDeclareTransaction, BroadcastedDeclareTransactionV1, BroadcastedTransaction, + BroadcastedDeclareTransaction, + BroadcastedDeclareTransactionV1, + BroadcastedTransaction, }; use crate::types::ContractClass; use crate::v06::method::call::FunctionCall; @@ -488,7 +497,11 @@ pub(crate) mod tests { pub(crate) mod fixtures { use super::*; pub use crate::v06::method::simulate_transactions::tests::fixtures::{ - CASM_DEFINITION, CASM_HASH, DEPLOYED_CONTRACT_ADDRESS, SIERRA_DEFINITION, SIERRA_HASH, + CASM_DEFINITION, + CASM_HASH, + DEPLOYED_CONTRACT_ADDRESS, + SIERRA_DEFINITION, + SIERRA_HASH, UNIVERSAL_DEPLOYER_CLASS_HASH, }; @@ -503,7 +516,9 @@ pub(crate) mod tests { use super::dto::*; use super::*; use crate::method::get_state_update::types::{ - DeclaredSierraClass, StorageDiff, StorageEntry, + DeclaredSierraClass, + StorageDiff, + StorageEntry, }; const DECLARE_OVERALL_FEE: u64 = 1262; diff --git a/crates/rpc/src/method/subscribe_events.rs b/crates/rpc/src/method/subscribe_events.rs index 990c56380c..f1b9e9a8a7 100644 --- a/crates/rpc/src/method/subscribe_events.rs +++ b/crates/rpc/src/method/subscribe_events.rs @@ -259,8 +259,16 @@ mod tests { use pathfinder_common::receipt::Receipt; use pathfinder_common::transaction::{Transaction, TransactionVariant}; use pathfinder_common::{ - felt, BlockHash, BlockHeader, BlockNumber, ChainId, ContractAddress, EventData, EventKey, - TransactionHash, TransactionIndex, + felt, + BlockHash, + BlockHeader, + BlockNumber, + ChainId, + ContractAddress, + EventData, + EventKey, + TransactionHash, + TransactionIndex, }; use pathfinder_crypto::Felt; use pathfinder_ethereum::EthereumClient; diff --git a/crates/rpc/src/method/subscribe_pending_transactions.rs b/crates/rpc/src/method/subscribe_pending_transactions.rs index 6a11a32f76..9fe150c366 100644 --- a/crates/rpc/src/method/subscribe_pending_transactions.rs +++ b/crates/rpc/src/method/subscribe_pending_transactions.rs @@ -141,7 +141,12 @@ mod tests { use axum::extract::ws::Message; use pathfinder_common::transaction::{DeclareTransactionV0V1, Transaction, TransactionVariant}; use pathfinder_common::{ - contract_address, transaction_hash, BlockNumber, ChainId, ContractAddress, TransactionHash, + contract_address, + transaction_hash, + BlockNumber, + ChainId, + ContractAddress, + TransactionHash, }; use pathfinder_ethereum::EthereumClient; use pathfinder_storage::StorageBuilder; diff --git a/crates/rpc/src/method/subscribe_transaction_status.rs b/crates/rpc/src/method/subscribe_transaction_status.rs index fd563b48e9..b8aca06d25 100644 --- a/crates/rpc/src/method/subscribe_transaction_status.rs +++ b/crates/rpc/src/method/subscribe_transaction_status.rs @@ -438,7 +438,12 @@ mod tests { use pathfinder_common::receipt::{ExecutionStatus, Receipt}; use pathfinder_common::transaction::Transaction; use pathfinder_common::{ - BlockHash, BlockHeader, BlockNumber, ChainId, TransactionHash, TransactionIndex, + BlockHash, + BlockHeader, + BlockNumber, + ChainId, + TransactionHash, + TransactionIndex, }; use pathfinder_crypto::Felt; use pathfinder_ethereum::{EthereumClient, EthereumStateUpdate}; diff --git a/crates/rpc/src/method/trace_block_transactions.rs b/crates/rpc/src/method/trace_block_transactions.rs index e54c386168..e21e5c0870 100644 --- a/crates/rpc/src/method/trace_block_transactions.rs +++ b/crates/rpc/src/method/trace_block_transactions.rs @@ -7,7 +7,8 @@ use starknet_gateway_client::GatewayApi; use crate::compose_executor_transaction; use crate::context::RpcContext; use crate::executor::{ - ExecutionStateError, VERSIONS_LOWER_THAN_THIS_SHOULD_FALL_BACK_TO_FETCHING_TRACE_FROM_GATEWAY, + ExecutionStateError, + VERSIONS_LOWER_THAN_THIS_SHOULD_FALL_BACK_TO_FETCHING_TRACE_FROM_GATEWAY, }; use crate::v06::method::trace_block_transactions as v06; @@ -612,8 +613,15 @@ impl From for TraceBlockTransactionsError { pub(crate) mod tests { use pathfinder_common::receipt::Receipt; use pathfinder_common::{ - block_hash, transaction_hash, BlockHeader, BlockId, GasPrice, L1DataAvailabilityMode, - SierraHash, StarknetVersion, TransactionIndex, + block_hash, + transaction_hash, + BlockHeader, + BlockId, + GasPrice, + L1DataAvailabilityMode, + SierraHash, + StarknetVersion, + TransactionIndex, }; use starknet_gateway_types::reply::GasPrices; use tokio::task::JoinSet; diff --git a/crates/rpc/src/method/trace_transaction.rs b/crates/rpc/src/method/trace_transaction.rs index d270c74f0f..d57fd0136a 100644 --- a/crates/rpc/src/method/trace_transaction.rs +++ b/crates/rpc/src/method/trace_transaction.rs @@ -6,7 +6,8 @@ use crate::compose_executor_transaction; use crate::context::RpcContext; use crate::error::{ApplicationError, TraceError}; use crate::executor::{ - ExecutionStateError, VERSIONS_LOWER_THAN_THIS_SHOULD_FALL_BACK_TO_FETCHING_TRACE_FROM_GATEWAY, + ExecutionStateError, + VERSIONS_LOWER_THAN_THIS_SHOULD_FALL_BACK_TO_FETCHING_TRACE_FROM_GATEWAY, }; use crate::method::trace_block_transactions::map_gateway_trace; use crate::v06::method::trace_transaction as v06; @@ -251,7 +252,8 @@ impl From for ApplicationError { #[cfg(test)] pub mod tests { use super::super::trace_block_transactions::tests::{ - setup_multi_tx_trace_pending_test, setup_multi_tx_trace_test, + setup_multi_tx_trace_pending_test, + setup_multi_tx_trace_test, }; use super::v06::{TraceTransactionInput, TraceTransactionOutput}; use super::*; diff --git a/crates/rpc/src/pathfinder/methods/get_proof.rs b/crates/rpc/src/pathfinder/methods/get_proof.rs index a80dfe8d7c..0d1ccf3074 100644 --- a/crates/rpc/src/pathfinder/methods/get_proof.rs +++ b/crates/rpc/src/pathfinder/methods/get_proof.rs @@ -4,7 +4,10 @@ use pathfinder_common::trie::TrieNode; use pathfinder_common::BlockId; use pathfinder_crypto::Felt; use pathfinder_merkle_tree::{ - tree, ClassCommitmentTree, ContractsStorageTree, StorageCommitmentTree, + tree, + ClassCommitmentTree, + ContractsStorageTree, + StorageCommitmentTree, }; use serde::{Deserialize, Serialize}; use serde_with::skip_serializing_none; diff --git a/crates/rpc/src/test_setup.rs b/crates/rpc/src/test_setup.rs index fe049681f2..ee73a2ac76 100644 --- a/crates/rpc/src/test_setup.rs +++ b/crates/rpc/src/test_setup.rs @@ -1,7 +1,15 @@ use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - felt, BlockHash, BlockHeader, BlockNumber, BlockTimestamp, ContractAddress, GasPrice, - StarknetVersion, StateUpdate, StorageAddress, + felt, + BlockHash, + BlockHeader, + BlockNumber, + BlockTimestamp, + ContractAddress, + GasPrice, + StarknetVersion, + StateUpdate, + StorageAddress, }; use pathfinder_storage::Storage; use starknet_gateway_test_fixtures::class_definitions::{DUMMY_ACCOUNT, DUMMY_ACCOUNT_CLASS_HASH}; diff --git a/crates/rpc/src/types.rs b/crates/rpc/src/types.rs index de239b6a70..5dcdcf82f0 100644 --- a/crates/rpc/src/types.rs +++ b/crates/rpc/src/types.rs @@ -110,9 +110,20 @@ impl From for starknet_api::data_availability::DataAvailab /// Groups all strictly input types of the RPC API. pub mod request { use pathfinder_common::{ - AccountDeploymentDataElem, CallParam, CasmHash, ChainId, ClassHash, ContractAddress, - ContractAddressSalt, EntryPoint, Fee, PaymasterDataElem, Tip, TransactionNonce, - TransactionSignatureElem, TransactionVersion, + AccountDeploymentDataElem, + CallParam, + CasmHash, + ChainId, + ClassHash, + ContractAddress, + ContractAddressSalt, + EntryPoint, + Fee, + PaymasterDataElem, + Tip, + TransactionNonce, + TransactionSignatureElem, + TransactionVersion, }; use serde::de::Error; use serde::Deserialize; @@ -826,8 +837,14 @@ pub mod request { use super::super::*; use crate::dto::DeserializeForVersion; use crate::types::{ - CairoContractClass, ContractEntryPoints, DataAvailabilityMode, ResourceBound, - ResourceBounds, SierraContractClass, SierraEntryPoint, SierraEntryPoints, + CairoContractClass, + ContractEntryPoints, + DataAvailabilityMode, + ResourceBound, + ResourceBounds, + SierraContractClass, + SierraEntryPoint, + SierraEntryPoints, }; #[test] diff --git a/crates/rpc/src/types/class.rs b/crates/rpc/src/types/class.rs index c81d7e0a80..ef2efa3849 100644 --- a/crates/rpc/src/types/class.rs +++ b/crates/rpc/src/types/class.rs @@ -532,7 +532,8 @@ mod tests { mod declare_class_hash { use starknet_gateway_test_fixtures::class_definitions::{ - CAIRO_0_11_SIERRA, CONTRACT_DEFINITION, + CAIRO_0_11_SIERRA, + CONTRACT_DEFINITION, }; use starknet_gateway_types::class_hash::compute_class_hash; diff --git a/crates/rpc/src/v06/method/add_declare_transaction.rs b/crates/rpc/src/v06/method/add_declare_transaction.rs index 7850b34347..8c08323b4b 100644 --- a/crates/rpc/src/v06/method/add_declare_transaction.rs +++ b/crates/rpc/src/v06/method/add_declare_transaction.rs @@ -2,7 +2,9 @@ use pathfinder_common::{ClassHash, TransactionHash}; use starknet_gateway_client::GatewayApi; use starknet_gateway_types::error::SequencerError; use starknet_gateway_types::request::add_transaction::{ - CairoContractDefinition, ContractDefinition, SierraContractDefinition, + CairoContractDefinition, + ContractDefinition, + SierraContractDefinition, }; use crate::context::RpcContext; @@ -67,10 +69,18 @@ impl From for AddDeclareTransactionError { impl From for AddDeclareTransactionError { fn from(e: SequencerError) -> Self { use starknet_gateway_types::error::KnownStarknetErrorCode::{ - ClassAlreadyDeclared, CompilationFailed, ContractBytecodeSizeTooLarge, - ContractClassObjectSizeTooLarge, DuplicatedTransaction, EntryPointNotFound, - InsufficientAccountBalance, InsufficientMaxFee, InvalidCompiledClassHash, - InvalidContractClassVersion, InvalidTransactionNonce, InvalidTransactionVersion, + ClassAlreadyDeclared, + CompilationFailed, + ContractBytecodeSizeTooLarge, + ContractClassObjectSizeTooLarge, + DuplicatedTransaction, + EntryPointNotFound, + InsufficientAccountBalance, + InsufficientMaxFee, + InvalidCompiledClassHash, + InvalidContractClassVersion, + InvalidTransactionNonce, + InvalidTransactionVersion, ValidateFailure, }; match e { @@ -265,21 +275,34 @@ mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - CasmHash, ContractAddress, Fee, ResourceAmount, ResourcePricePerUnit, Tip, - TransactionNonce, TransactionVersion, + CasmHash, + ContractAddress, + Fee, + ResourceAmount, + ResourcePricePerUnit, + Tip, + TransactionNonce, + TransactionVersion, }; use pathfinder_crypto::Felt; use starknet_gateway_test_fixtures::class_definitions::{ - CAIRO_2_0_0_STACK_OVERFLOW, CONTRACT_DEFINITION, + CAIRO_2_0_0_STACK_OVERFLOW, + CONTRACT_DEFINITION, }; use super::*; use crate::types::request::{ - BroadcastedDeclareTransaction, BroadcastedDeclareTransactionV1, - BroadcastedDeclareTransactionV2, BroadcastedDeclareTransactionV3, + BroadcastedDeclareTransaction, + BroadcastedDeclareTransactionV1, + BroadcastedDeclareTransactionV2, + BroadcastedDeclareTransactionV3, }; use crate::types::{ - CairoContractClass, ContractClass, DataAvailabilityMode, ResourceBound, ResourceBounds, + CairoContractClass, + ContractClass, + DataAvailabilityMode, + ResourceBound, + ResourceBounds, SierraContractClass, }; @@ -391,7 +414,9 @@ mod tests { #[test] fn unexpected_error_message() { use starknet_gateway_types::error::{ - KnownStarknetErrorCode, StarknetError, StarknetErrorCode, + KnownStarknetErrorCode, + StarknetError, + StarknetErrorCode, }; let starknet_error = SequencerError::StarknetError(StarknetError { code: StarknetErrorCode::Known( diff --git a/crates/rpc/src/v06/method/add_deploy_account_transaction.rs b/crates/rpc/src/v06/method/add_deploy_account_transaction.rs index 4960784199..4d4839b3e9 100644 --- a/crates/rpc/src/v06/method/add_deploy_account_transaction.rs +++ b/crates/rpc/src/v06/method/add_deploy_account_transaction.rs @@ -5,7 +5,8 @@ use starknet_gateway_types::error::{KnownStarknetErrorCode, SequencerError}; use crate::context::RpcContext; use crate::felt::{RpcFelt, RpcFelt251}; use crate::types::request::{ - BroadcastedDeployAccountTransaction, BroadcastedDeployAccountTransactionV1, + BroadcastedDeployAccountTransaction, + BroadcastedDeployAccountTransactionV1, }; #[derive(serde::Deserialize, Debug, PartialEq, Eq)] @@ -69,9 +70,14 @@ impl From for crate::error::ApplicationError { impl From for AddDeployAccountTransactionError { fn from(e: SequencerError) -> Self { use starknet_gateway_types::error::KnownStarknetErrorCode::{ - DuplicatedTransaction, EntryPointNotFound, InsufficientAccountBalance, - InsufficientMaxFee, InvalidTransactionNonce, InvalidTransactionVersion, - UndeclaredClass, ValidateFailure, + DuplicatedTransaction, + EntryPointNotFound, + InsufficientAccountBalance, + InsufficientMaxFee, + InvalidTransactionNonce, + InvalidTransactionVersion, + UndeclaredClass, + ValidateFailure, }; match e { SequencerError::StarknetError(e) if e.code == UndeclaredClass.into() => { @@ -203,7 +209,11 @@ pub(crate) async fn add_deploy_account_transaction_impl( mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - ResourceAmount, ResourcePricePerUnit, Tip, TransactionNonce, TransactionVersion, + ResourceAmount, + ResourcePricePerUnit, + Tip, + TransactionNonce, + TransactionVersion, }; use super::*; @@ -248,7 +258,9 @@ mod tests { #[test] fn unexpected_error_message() { use starknet_gateway_types::error::{ - KnownStarknetErrorCode, StarknetError, StarknetErrorCode, + KnownStarknetErrorCode, + StarknetError, + StarknetErrorCode, }; let starknet_error = SequencerError::StarknetError(StarknetError { code: StarknetErrorCode::Known(KnownStarknetErrorCode::TransactionLimitExceeded), diff --git a/crates/rpc/src/v06/method/add_invoke_transaction.rs b/crates/rpc/src/v06/method/add_invoke_transaction.rs index 32f938cccd..a1c480ff5f 100644 --- a/crates/rpc/src/v06/method/add_invoke_transaction.rs +++ b/crates/rpc/src/v06/method/add_invoke_transaction.rs @@ -68,8 +68,12 @@ impl From for crate::error::ApplicationError { impl From for AddInvokeTransactionError { fn from(e: SequencerError) -> Self { use starknet_gateway_types::error::KnownStarknetErrorCode::{ - DuplicatedTransaction, EntryPointNotFound, InsufficientAccountBalance, - InsufficientMaxFee, InvalidTransactionNonce, InvalidTransactionVersion, + DuplicatedTransaction, + EntryPointNotFound, + InsufficientAccountBalance, + InsufficientMaxFee, + InvalidTransactionNonce, + InvalidTransactionVersion, ValidateFailure, }; match e { @@ -296,7 +300,9 @@ mod tests { #[test] fn unexpected_error_message() { use starknet_gateway_types::error::{ - KnownStarknetErrorCode, StarknetError, StarknetErrorCode, + KnownStarknetErrorCode, + StarknetError, + StarknetErrorCode, }; let starknet_error = SequencerError::StarknetError(StarknetError { code: StarknetErrorCode::Known(KnownStarknetErrorCode::TransactionLimitExceeded), diff --git a/crates/rpc/src/v06/method/call.rs b/crates/rpc/src/v06/method/call.rs index 7d3f8ca319..8403d410f6 100644 --- a/crates/rpc/src/v06/method/call.rs +++ b/crates/rpc/src/v06/method/call.rs @@ -205,11 +205,21 @@ mod tests { mod in_memory { use pathfinder_common::{ - felt, BlockHash, BlockHeader, BlockNumber, BlockTimestamp, ClassHash, ContractAddress, - GasPrice, StateUpdate, StorageAddress, StorageValue, + felt, + BlockHash, + BlockHeader, + BlockNumber, + BlockTimestamp, + ClassHash, + ContractAddress, + GasPrice, + StateUpdate, + StorageAddress, + StorageValue, }; use starknet_gateway_test_fixtures::class_definitions::{ - CONTRACT_DEFINITION, CONTRACT_DEFINITION_CLASS_HASH, + CONTRACT_DEFINITION, + CONTRACT_DEFINITION_CLASS_HASH, }; use starknet_gateway_types::reply::{GasPrices, L1DataAvailabilityMode, PendingBlock}; diff --git a/crates/rpc/src/v06/method/estimate_fee.rs b/crates/rpc/src/v06/method/estimate_fee.rs index 02a0786378..fc24bcec86 100644 --- a/crates/rpc/src/v06/method/estimate_fee.rs +++ b/crates/rpc/src/v06/method/estimate_fee.rs @@ -219,8 +219,14 @@ pub async fn estimate_fee_impl( #[cfg(test)] pub(crate) mod tests { use pathfinder_common::{ - felt, BlockHash, CallParam, ContractAddress, Fee, TransactionNonce, - TransactionSignatureElem, TransactionVersion, + felt, + BlockHash, + CallParam, + ContractAddress, + Fee, + TransactionNonce, + TransactionSignatureElem, + TransactionVersion, }; use super::*; @@ -314,12 +320,17 @@ pub(crate) mod tests { use super::*; use crate::types::request::{ - BroadcastedDeclareTransaction, BroadcastedDeclareTransactionV2, - BroadcastedInvokeTransactionV0, BroadcastedInvokeTransactionV1, + BroadcastedDeclareTransaction, + BroadcastedDeclareTransactionV2, + BroadcastedInvokeTransactionV0, + BroadcastedInvokeTransactionV1, BroadcastedInvokeTransactionV3, }; use crate::types::{ - ContractClass, DataAvailabilityMode, ResourceBounds, SierraContractClass, + ContractClass, + DataAvailabilityMode, + ResourceBounds, + SierraContractClass, }; use crate::PendingData; diff --git a/crates/rpc/src/v06/method/estimate_message_fee.rs b/crates/rpc/src/v06/method/estimate_message_fee.rs index 46b84ceeca..57174b4b62 100644 --- a/crates/rpc/src/v06/method/estimate_message_fee.rs +++ b/crates/rpc/src/v06/method/estimate_message_fee.rs @@ -2,7 +2,13 @@ use std::sync::Arc; use anyhow::Context; use pathfinder_common::{ - BlockId, CallParam, ChainId, ContractAddress, EntryPoint, EthereumAddress, TransactionNonce, + BlockId, + CallParam, + ChainId, + ContractAddress, + EntryPoint, + EthereumAddress, + TransactionNonce, }; use pathfinder_crypto::Felt; use pathfinder_executor::{ExecutionState, IntoStarkFelt, L1BlobDataAvailability}; @@ -234,12 +240,19 @@ fn create_executor_transaction( mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - felt, BlockHash, BlockHeader, BlockNumber, BlockTimestamp, GasPrice, StateUpdate, + felt, + BlockHash, + BlockHeader, + BlockNumber, + BlockTimestamp, + GasPrice, + StateUpdate, }; use primitive_types::H160; use serde::Deserialize; use starknet_gateway_test_fixtures::class_definitions::{ - CAIRO_1_1_0_BALANCE_CASM_JSON, CAIRO_1_1_0_BALANCE_SIERRA_JSON, + CAIRO_1_1_0_BALANCE_CASM_JSON, + CAIRO_1_1_0_BALANCE_SIERRA_JSON, }; use tempfile::tempdir; diff --git a/crates/rpc/src/v06/method/get_transaction_by_block_id_and_index.rs b/crates/rpc/src/v06/method/get_transaction_by_block_id_and_index.rs index 6d34389582..f9bc501f2f 100644 --- a/crates/rpc/src/v06/method/get_transaction_by_block_id_and_index.rs +++ b/crates/rpc/src/v06/method/get_transaction_by_block_id_and_index.rs @@ -1,7 +1,8 @@ use crate::context::RpcContext; use crate::method::get_transaction_by_block_id_and_index::{ get_transaction_by_block_id_and_index as get_transaction_by_block_id_and_index_impl, - GetTransactionByBlockIdAndIndexError, Input, + GetTransactionByBlockIdAndIndexError, + Input, }; use crate::v06::types::TransactionWithHash; diff --git a/crates/rpc/src/v06/method/get_transaction_receipt.rs b/crates/rpc/src/v06/method/get_transaction_receipt.rs index b6706eb256..eb5f2f6788 100644 --- a/crates/rpc/src/v06/method/get_transaction_receipt.rs +++ b/crates/rpc/src/v06/method/get_transaction_receipt.rs @@ -95,8 +95,15 @@ pub async fn get_transaction_receipt_impl( pub mod types { use pathfinder_common::{ - BlockHash, BlockNumber, ContractAddress, EventData, EventKey, Fee, - L2ToL1MessagePayloadElem, TransactionHash, TransactionVersion, + BlockHash, + BlockNumber, + ContractAddress, + EventData, + EventKey, + Fee, + L2ToL1MessagePayloadElem, + TransactionHash, + TransactionVersion, }; use pathfinder_serde::H256AsNoLeadingZerosHexStr; use primitive_types::H256; diff --git a/crates/rpc/src/v06/method/get_transaction_status.rs b/crates/rpc/src/v06/method/get_transaction_status.rs index cf15a9396c..8b962fa3dd 100644 --- a/crates/rpc/src/v06/method/get_transaction_status.rs +++ b/crates/rpc/src/v06/method/get_transaction_status.rs @@ -140,7 +140,8 @@ pub async fn get_transaction_status( .map_err(GetTransactionStatusError::Internal) .and_then(|tx| { use starknet_gateway_types::reply::transaction_status::{ - ExecutionStatus as GatewayExecutionStatus, FinalityStatus as GatewayFinalityStatus, + ExecutionStatus as GatewayExecutionStatus, + FinalityStatus as GatewayFinalityStatus, }; let execution_status = tx.execution_status.unwrap_or_default(); diff --git a/crates/rpc/src/v06/method/simulate_transactions.rs b/crates/rpc/src/v06/method/simulate_transactions.rs index 1975656523..f464e0f3e2 100644 --- a/crates/rpc/src/v06/method/simulate_transactions.rs +++ b/crates/rpc/src/v06/method/simulate_transactions.rs @@ -787,12 +787,19 @@ pub mod dto { pub(crate) mod tests { use pathfinder_common::macro_prelude::*; use pathfinder_common::{ - felt, BlockHeader, ClassHash, ContractAddress, StarknetVersion, StorageAddress, - StorageValue, TransactionVersion, + felt, + BlockHeader, + ClassHash, + ContractAddress, + StarknetVersion, + StorageAddress, + StorageValue, + TransactionVersion, }; use pathfinder_storage::Storage; use starknet_gateway_test_fixtures::class_definitions::{ - DUMMY_ACCOUNT_CLASS_HASH, ERC20_CONTRACT_DEFINITION_CLASS_HASH, + DUMMY_ACCOUNT_CLASS_HASH, + ERC20_CONTRACT_DEFINITION_CLASS_HASH, }; use super::*; @@ -1109,13 +1116,19 @@ pub(crate) mod tests { // The input transactions are the same as in v04. pub mod input { use pathfinder_common::{ - CallParam, EntryPoint, ResourceAmount, ResourcePricePerUnit, Tip, + CallParam, + EntryPoint, + ResourceAmount, + ResourcePricePerUnit, + Tip, }; use super::*; use crate::types::request::{ - BroadcastedDeclareTransactionV2, BroadcastedInvokeTransaction, - BroadcastedInvokeTransactionV1, BroadcastedInvokeTransactionV3, + BroadcastedDeclareTransactionV2, + BroadcastedInvokeTransaction, + BroadcastedInvokeTransactionV1, + BroadcastedInvokeTransactionV3, BroadcastedTransaction, }; use crate::types::{ResourceBound, ResourceBounds}; @@ -1237,7 +1250,9 @@ pub(crate) mod tests { use super::dto::*; use super::*; use crate::method::get_state_update::types::{ - DeclaredSierraClass, StorageDiff, StorageEntry, + DeclaredSierraClass, + StorageDiff, + StorageEntry, }; const DECLARE_GAS_CONSUMED: u64 = 3632; diff --git a/crates/rpc/src/v06/method/trace_block_transactions.rs b/crates/rpc/src/v06/method/trace_block_transactions.rs index 1fa6483b6c..fcfd508316 100644 --- a/crates/rpc/src/v06/method/trace_block_transactions.rs +++ b/crates/rpc/src/v06/method/trace_block_transactions.rs @@ -10,11 +10,17 @@ use super::simulate_transactions::dto::TransactionTrace; use crate::compose_executor_transaction; use crate::context::RpcContext; use crate::executor::{ - ExecutionStateError, VERSIONS_LOWER_THAN_THIS_SHOULD_FALL_BACK_TO_FETCHING_TRACE_FROM_GATEWAY, + ExecutionStateError, + VERSIONS_LOWER_THAN_THIS_SHOULD_FALL_BACK_TO_FETCHING_TRACE_FROM_GATEWAY, }; use crate::v06::method::simulate_transactions::dto::{ - DeclareTxnTrace, DeployAccountTxnTrace, ExecuteInvocation, ExecutionResources, - FunctionInvocation, InvokeTxnTrace, L1HandlerTxnTrace, + DeclareTxnTrace, + DeployAccountTxnTrace, + ExecuteInvocation, + ExecutionResources, + FunctionInvocation, + InvokeTxnTrace, + L1HandlerTxnTrace, }; #[derive(Deserialize, Debug, Clone)] @@ -327,8 +333,16 @@ pub async fn trace_block_transactions_impl( pub(crate) mod tests { use pathfinder_common::receipt::Receipt; use pathfinder_common::{ - block_hash, felt, BlockHeader, BlockNumber, Chain, GasPrice, SequencerAddress, SierraHash, - StarknetVersion, TransactionIndex, + block_hash, + felt, + BlockHeader, + BlockNumber, + Chain, + GasPrice, + SequencerAddress, + SierraHash, + StarknetVersion, + TransactionIndex, }; use pathfinder_crypto::Felt; use starknet_gateway_types::reply::{GasPrices, L1DataAvailabilityMode}; @@ -339,7 +353,8 @@ pub(crate) mod tests { pub(crate) async fn setup_multi_tx_trace_test( ) -> anyhow::Result<(RpcContext, BlockHeader, Vec)> { use super::super::simulate_transactions::tests::{ - fixtures, setup_storage_with_starknet_version, + fixtures, + setup_storage_with_starknet_version, }; let ( @@ -485,7 +500,8 @@ pub(crate) mod tests { pub(crate) async fn setup_multi_tx_trace_pending_test( ) -> anyhow::Result<(RpcContext, Vec)> { use super::super::simulate_transactions::tests::{ - fixtures, setup_storage_with_starknet_version, + fixtures, + setup_storage_with_starknet_version, }; let ( diff --git a/crates/rpc/src/v06/method/trace_transaction.rs b/crates/rpc/src/v06/method/trace_transaction.rs index e51addf821..3b8c7b565a 100644 --- a/crates/rpc/src/v06/method/trace_transaction.rs +++ b/crates/rpc/src/v06/method/trace_transaction.rs @@ -10,7 +10,8 @@ use crate::compose_executor_transaction; use crate::context::RpcContext; use crate::error::{ApplicationError, TraceError}; use crate::executor::{ - ExecutionStateError, VERSIONS_LOWER_THAN_THIS_SHOULD_FALL_BACK_TO_FETCHING_TRACE_FROM_GATEWAY, + ExecutionStateError, + VERSIONS_LOWER_THAN_THIS_SHOULD_FALL_BACK_TO_FETCHING_TRACE_FROM_GATEWAY, }; use crate::v06::method::trace_block_transactions::map_gateway_trace; @@ -257,12 +258,18 @@ pub async fn trace_transaction_impl( #[cfg(test)] pub mod tests { use pathfinder_common::{ - block_hash, transaction_hash, BlockHeader, BlockNumber, Chain, SequencerAddress, + block_hash, + transaction_hash, + BlockHeader, + BlockNumber, + Chain, + SequencerAddress, }; use pathfinder_crypto::Felt; use super::super::trace_block_transactions::tests::{ - setup_multi_tx_trace_pending_test, setup_multi_tx_trace_test, + setup_multi_tx_trace_pending_test, + setup_multi_tx_trace_test, }; use super::*; diff --git a/crates/rpc/src/v06/types.rs b/crates/rpc/src/v06/types.rs index 72b887ce26..32882fd310 100644 --- a/crates/rpc/src/v06/types.rs +++ b/crates/rpc/src/v06/types.rs @@ -1,8 +1,14 @@ mod transaction; use pathfinder_common::{ - BlockHash, BlockNumber, BlockTimestamp, GasPrice, SequencerAddress, StarknetVersion, - StateCommitment, TransactionVersion, + BlockHash, + BlockNumber, + BlockTimestamp, + GasPrice, + SequencerAddress, + StarknetVersion, + StateCommitment, + TransactionVersion, }; use serde::Serialize; use serde_with::{serde_as, skip_serializing_none, DisplayFromStr}; diff --git a/crates/rpc/src/v06/types/transaction.rs b/crates/rpc/src/v06/types/transaction.rs index 70c1ab5e21..154fda363e 100644 --- a/crates/rpc/src/v06/types/transaction.rs +++ b/crates/rpc/src/v06/types/transaction.rs @@ -1,11 +1,25 @@ use pathfinder_common::transaction::{ - DataAvailabilityMode, DeclareTransactionV0V1, DeclareTransactionV2, DeclareTransactionV3, - DeployAccountTransactionV1, DeployAccountTransactionV3, DeployTransactionV0, - DeployTransactionV1, InvokeTransactionV0, InvokeTransactionV1, InvokeTransactionV3, - L1HandlerTransaction, ResourceBound, ResourceBounds, + DataAvailabilityMode, + DeclareTransactionV0V1, + DeclareTransactionV2, + DeclareTransactionV3, + DeployAccountTransactionV1, + DeployAccountTransactionV3, + DeployTransactionV0, + DeployTransactionV1, + InvokeTransactionV0, + InvokeTransactionV1, + InvokeTransactionV3, + L1HandlerTransaction, + ResourceBound, + ResourceBounds, }; use pathfinder_common::{ - ResourceAmount, ResourcePricePerUnit, Tip, TransactionHash, TransactionVersion, + ResourceAmount, + ResourcePricePerUnit, + Tip, + TransactionHash, + TransactionVersion, }; use serde::ser::SerializeStruct; use serde::Serialize; diff --git a/crates/serde/src/lib.rs b/crates/serde/src/lib.rs index 9e347cc356..1c2d8d1eec 100644 --- a/crates/serde/src/lib.rs +++ b/crates/serde/src/lib.rs @@ -6,8 +6,17 @@ use std::str::FromStr; use num_bigint::BigUint; use pathfinder_common::{ - BlockNumber, CallParam, ConstructorParam, EthereumAddress, GasPrice, L1ToL2MessagePayloadElem, - L2ToL1MessagePayloadElem, ResourceAmount, ResourcePricePerUnit, Tip, TransactionSignatureElem, + BlockNumber, + CallParam, + ConstructorParam, + EthereumAddress, + GasPrice, + L1ToL2MessagePayloadElem, + L2ToL1MessagePayloadElem, + ResourceAmount, + ResourcePricePerUnit, + Tip, + TransactionSignatureElem, }; use pathfinder_crypto::{Felt, HexParseError, OverflowError}; use primitive_types::{H160, H256, U256}; diff --git a/crates/storage/src/connection.rs b/crates/storage/src/connection.rs index 978c7c0340..3476be3be8 100644 --- a/crates/storage/src/connection.rs +++ b/crates/storage/src/connection.rs @@ -16,7 +16,10 @@ mod trie; #[cfg(feature = "aggregate_bloom")] use event::RunningEventFilter; pub use event::{ - EmittedEvent, EventFilter, EventFilterError, PageOfEvents, + EmittedEvent, + EventFilter, + EventFilterError, + PageOfEvents, PAGE_SIZE_LIMIT as EVENT_PAGE_SIZE_LIMIT, }; use pathfinder_common::event::Event; diff --git a/crates/storage/src/connection/block.rs b/crates/storage/src/connection/block.rs index a3d1c3c575..c2b6ddfb8f 100644 --- a/crates/storage/src/connection/block.rs +++ b/crates/storage/src/connection/block.rs @@ -3,8 +3,16 @@ use std::num::NonZeroUsize; use anyhow::Context; use pathfinder_common::{ - BlockHash, BlockHeader, BlockNumber, ClassCommitment, GasPrice, StarknetVersion, - StateCommitment, StateDiffCommitment, StorageCommitment, TransactionCommitment, + BlockHash, + BlockHeader, + BlockNumber, + ClassCommitment, + GasPrice, + StarknetVersion, + StateCommitment, + StateDiffCommitment, + StorageCommitment, + TransactionCommitment, }; use crate::prelude::*; diff --git a/crates/storage/src/connection/event.rs b/crates/storage/src/connection/event.rs index 5a2d974f7c..304ed2248c 100644 --- a/crates/storage/src/connection/event.rs +++ b/crates/storage/src/connection/event.rs @@ -5,7 +5,12 @@ use anyhow::Context; use anyhow::Result; use pathfinder_common::event::Event; use pathfinder_common::{ - BlockHash, BlockNumber, ContractAddress, EventData, EventKey, TransactionHash, + BlockHash, + BlockNumber, + ContractAddress, + EventData, + EventKey, + TransactionHash, }; #[cfg(feature = "aggregate_bloom")] diff --git a/crates/storage/src/connection/state_update.rs b/crates/storage/src/connection/state_update.rs index e853348122..b263dd5b45 100644 --- a/crates/storage/src/connection/state_update.rs +++ b/crates/storage/src/connection/state_update.rs @@ -3,12 +3,25 @@ use std::num::NonZeroUsize; use anyhow::Context; use pathfinder_common::state_update::{ - ContractClassUpdate, ContractUpdate, ReverseContractUpdate, StateUpdateData, + ContractClassUpdate, + ContractUpdate, + ReverseContractUpdate, + StateUpdateData, SystemContractUpdate, }; use pathfinder_common::{ - BlockHash, BlockNumber, CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, - StateCommitment, StateUpdate, StorageAddress, StorageCommitment, StorageValue, + BlockHash, + BlockNumber, + CasmHash, + ClassHash, + ContractAddress, + ContractNonce, + SierraHash, + StateCommitment, + StateUpdate, + StorageAddress, + StorageCommitment, + StorageValue, }; use crate::prelude::*; diff --git a/crates/storage/src/connection/trie.rs b/crates/storage/src/connection/trie.rs index 20691d60f9..88797355a0 100644 --- a/crates/storage/src/connection/trie.rs +++ b/crates/storage/src/connection/trie.rs @@ -16,14 +16,15 @@ impl Transaction<'_> { block_number: BlockNumber, ) -> anyhow::Result> { self.inner() - .query_row( - "SELECT root_index FROM class_roots WHERE block_number <= ? ORDER BY block_number DESC LIMIT 1", - params![&block_number], - |row| row.get::<_, Option>(0), - ) - .optional() - .map(|option_u64| option_u64.flatten().map(StorageIndex::new)) - .map_err(Into::into) + .query_row( + "SELECT root_index FROM class_roots WHERE block_number <= ? ORDER BY block_number \ + DESC LIMIT 1", + params![&block_number], + |row| row.get::<_, Option>(0), + ) + .optional() + .map(|option_u64| option_u64.flatten().map(StorageIndex::new)) + .map_err(Into::into) } pub fn class_root_exists(&self, block_number: BlockNumber) -> anyhow::Result { @@ -43,7 +44,7 @@ impl Transaction<'_> { self.inner() .query_row( "SELECT root_index FROM storage_roots WHERE block_number <= ? ORDER BY \ - block_number DESC LIMIT 1", + block_number DESC LIMIT 1", params![&block_number], |row| row.get::<_, Option>(0), ) diff --git a/crates/storage/src/fake.rs b/crates/storage/src/fake.rs index 9a8f756428..57403c82e2 100644 --- a/crates/storage/src/fake.rs +++ b/crates/storage/src/fake.rs @@ -5,15 +5,33 @@ use fake::{Fake, Faker}; use pathfinder_common::event::Event; use pathfinder_common::receipt::Receipt; use pathfinder_common::state_update::{ - ContractClassUpdate, ContractUpdate, StateUpdateRef, SystemContractUpdate, + ContractClassUpdate, + ContractUpdate, + StateUpdateRef, + SystemContractUpdate, }; use pathfinder_common::test_utils::fake_non_empty_with_rng; use pathfinder_common::transaction::Transaction; use pathfinder_common::{ - class_definition, BlockHash, BlockHeader, BlockNumber, ChainId, ClassCommitment, ClassHash, - ContractAddress, EventCommitment, ReceiptCommitment, SierraHash, SignedBlockHeader, - StarknetVersion, StateCommitment, StateUpdate, StorageCommitment, TransactionCommitment, - TransactionHash, TransactionIndex, + class_definition, + BlockHash, + BlockHeader, + BlockNumber, + ChainId, + ClassCommitment, + ClassHash, + ContractAddress, + EventCommitment, + ReceiptCommitment, + SierraHash, + SignedBlockHeader, + StarknetVersion, + StateCommitment, + StateUpdate, + StorageCommitment, + TransactionCommitment, + TransactionHash, + TransactionIndex, }; use pathfinder_crypto::signature::SignatureError; use pathfinder_crypto::Felt; diff --git a/crates/storage/src/params.rs b/crates/storage/src/params.rs index 8646eca74e..2a82e08754 100644 --- a/crates/storage/src/params.rs +++ b/crates/storage/src/params.rs @@ -1,13 +1,46 @@ use anyhow::Result; use pathfinder_common::{ - BlockCommitmentSignatureElem, BlockHash, BlockNumber, BlockTimestamp, ByteCodeOffset, - CallParam, CallResultValue, CasmHash, ClassCommitment, ClassCommitmentLeafHash, ClassHash, - ConstructorParam, ContractAddress, ContractAddressSalt, ContractNonce, ContractRoot, - ContractStateHash, EntryPoint, EventCommitment, EventData, EventKey, Fee, GasPrice, - L1BlockNumber, L1DataAvailabilityMode, L1ToL2MessageNonce, L1ToL2MessagePayloadElem, - L2ToL1MessagePayloadElem, ReceiptCommitment, SequencerAddress, SierraHash, StarknetVersion, - StateCommitment, StateDiffCommitment, StorageAddress, StorageCommitment, StorageValue, - TransactionCommitment, TransactionHash, TransactionNonce, TransactionSignatureElem, + BlockCommitmentSignatureElem, + BlockHash, + BlockNumber, + BlockTimestamp, + ByteCodeOffset, + CallParam, + CallResultValue, + CasmHash, + ClassCommitment, + ClassCommitmentLeafHash, + ClassHash, + ConstructorParam, + ContractAddress, + ContractAddressSalt, + ContractNonce, + ContractRoot, + ContractStateHash, + EntryPoint, + EventCommitment, + EventData, + EventKey, + Fee, + GasPrice, + L1BlockNumber, + L1DataAvailabilityMode, + L1ToL2MessageNonce, + L1ToL2MessagePayloadElem, + L2ToL1MessagePayloadElem, + ReceiptCommitment, + SequencerAddress, + SierraHash, + StarknetVersion, + StateCommitment, + StateDiffCommitment, + StorageAddress, + StorageCommitment, + StorageValue, + TransactionCommitment, + TransactionHash, + TransactionNonce, + TransactionSignatureElem, }; use pathfinder_crypto::Felt; use rusqlite::types::{FromSqlError, ToSqlOutput}; @@ -471,8 +504,13 @@ macro_rules! row_felt_wrapper { } use { - row_felt_wrapper, to_sql_builtin, to_sql_compressed_felt, to_sql_felt, to_sql_int, - try_into_sql, try_into_sql_int, + row_felt_wrapper, + to_sql_builtin, + to_sql_compressed_felt, + to_sql_felt, + to_sql_int, + try_into_sql, + try_into_sql_int, }; /// Used in combination with our own [ToSql] trait to provide functionality diff --git a/crates/storage/src/schema/revision_0052.rs b/crates/storage/src/schema/revision_0052.rs index 32447f4fb5..80d439be46 100644 --- a/crates/storage/src/schema/revision_0052.rs +++ b/crates/storage/src/schema/revision_0052.rs @@ -1681,9 +1681,14 @@ pub(crate) mod old_dto { use pathfinder_common::*; use pathfinder_crypto::Felt; use pathfinder_serde::{ - CallParamAsDecimalStr, ConstructorParamAsDecimalStr, EthereumAddressAsHexStr, - L2ToL1MessagePayloadElemAsDecimalStr, ResourceAmountAsHexStr, ResourcePricePerUnitAsHexStr, - TipAsHexStr, TransactionSignatureElemAsDecimalStr, + CallParamAsDecimalStr, + ConstructorParamAsDecimalStr, + EthereumAddressAsHexStr, + L2ToL1MessagePayloadElemAsDecimalStr, + ResourceAmountAsHexStr, + ResourcePricePerUnitAsHexStr, + TipAsHexStr, + TransactionSignatureElemAsDecimalStr, }; use serde::{Deserialize, Serialize}; use serde_with::serde_as; diff --git a/crates/storage/src/test_utils.rs b/crates/storage/src/test_utils.rs index 02a51d2863..8c36f41e86 100644 --- a/crates/storage/src/test_utils.rs +++ b/crates/storage/src/test_utils.rs @@ -2,7 +2,11 @@ use pathfinder_common::event::Event; use pathfinder_common::macro_prelude::*; use pathfinder_common::receipt::{ExecutionResources, L1Gas, Receipt}; use pathfinder_common::transaction::{ - DeclareTransactionV0V1, DeployTransactionV0, EntryPointType, InvokeTransactionV0, Transaction, + DeclareTransactionV0V1, + DeployTransactionV0, + EntryPointType, + InvokeTransactionV0, + Transaction, TransactionVariant, }; use pathfinder_common::*; From 20e82d957a0bedc955ce01369e3c6968c4d5095d Mon Sep 17 00:00:00 2001 From: varun-doshi Date: Tue, 10 Dec 2024 13:27:11 +0530 Subject: [PATCH 5/8] renamed to TrieStorageIndex and moved to Storage crate --- crates/common/src/lib.rs | 1 - crates/merkle-tree/src/contract.rs | 6 +- crates/merkle-tree/src/merkle_node.rs | 46 +++++++---- crates/merkle-tree/src/tree.rs | 82 +++++++++---------- crates/storage/src/connection.rs | 1 + .../src/connection}/storage_index.rs | 4 +- crates/storage/src/connection/trie.rs | 46 +++++------ crates/storage/src/lib.rs | 2 +- 8 files changed, 103 insertions(+), 85 deletions(-) rename crates/{common/src => storage/src/connection}/storage_index.rs (83%) diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index c3112f38f9..ed226143c1 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -27,7 +27,6 @@ pub mod prelude; pub mod receipt; pub mod signature; pub mod state_update; -pub mod storage_index; pub mod test_utils; pub mod transaction; pub mod trie; diff --git a/crates/merkle-tree/src/contract.rs b/crates/merkle-tree/src/contract.rs index 87f2aecc7b..c8fb6bf742 100644 --- a/crates/merkle-tree/src/contract.rs +++ b/crates/merkle-tree/src/contract.rs @@ -10,7 +10,6 @@ use anyhow::Context; use bitvec::prelude::Msb0; use bitvec::slice::BitSlice; use pathfinder_common::hash::PedersenHash; -use pathfinder_common::storage_index::StorageIndex; use pathfinder_common::{ BlockNumber, ContractAddress, @@ -21,6 +20,7 @@ use pathfinder_common::{ StorageValue, }; use pathfinder_crypto::Felt; +use pathfinder_storage::connection::storage_index::TrieStorageIndex; use pathfinder_storage::{Transaction, TrieUpdate}; use crate::merkle_node::InternalNode; @@ -67,7 +67,7 @@ impl<'tx> ContractsStorageTree<'tx> { block: Some(block), contract, }; - let tree = MerkleTree::new(StorageIndex::new(root)); + let tree = MerkleTree::new(TrieStorageIndex::new(root)); Ok(Self { tree, storage }) } @@ -174,7 +174,7 @@ impl<'tx> StorageCommitmentTree<'tx> { block: Some(block), }; - let tree = MerkleTree::new(StorageIndex::new(root.get())); + let tree = MerkleTree::new(TrieStorageIndex::new(root.get())); Ok(Self { tree, storage }) } diff --git a/crates/merkle-tree/src/merkle_node.rs b/crates/merkle-tree/src/merkle_node.rs index 1b801c2b24..30ffc8feff 100644 --- a/crates/merkle-tree/src/merkle_node.rs +++ b/crates/merkle-tree/src/merkle_node.rs @@ -11,8 +11,8 @@ use bitvec::order::Msb0; use bitvec::prelude::BitVec; use bitvec::slice::BitSlice; use pathfinder_common::hash::FeltHash; -use pathfinder_common::storage_index::StorageIndex; use pathfinder_crypto::Felt; +use pathfinder_storage::connection::storage_index::TrieStorageIndex; /// A node in a Binary Merkle-Patricia Tree graph. #[derive(Clone, Debug, PartialEq)] @@ -20,7 +20,7 @@ pub enum InternalNode { /// A node that has not been fetched from storage yet. /// /// As such, all we know is its index. - Unresolved(StorageIndex), + Unresolved(TrieStorageIndex), /// A branch node with exactly two children. Binary(BinaryNode), /// Describes a path connecting two other nodes. @@ -33,7 +33,7 @@ pub enum InternalNode { #[derive(Clone, Debug, PartialEq)] pub struct BinaryNode { /// The storage index of this node (if it was loaded from storage). - pub storage_index: Option, + pub storage_index: Option, /// The height of this node in the tree. pub height: usize, /// [Left](Direction::Left) child. @@ -45,7 +45,7 @@ pub struct BinaryNode { #[derive(Clone, Debug, PartialEq)] pub struct EdgeNode { /// The storage index of this node (if it was loaded from storage). - pub storage_index: Option, + pub storage_index: Option, /// The starting height of this node in the tree. pub height: usize, /// The path this edge takes. @@ -145,9 +145,11 @@ impl InternalNode { matches!(self, InternalNode::Leaf) } - pub fn storage_index(&self) -> Option { + pub fn storage_index(&self) -> Option { match self { - InternalNode::Unresolved(storage_index) => Some(StorageIndex::new(storage_index.get())), + InternalNode::Unresolved(storage_index) => { + Some(TrieStorageIndex::new(storage_index.get())) + } InternalNode::Binary(binary) => binary.storage_index, InternalNode::Edge(edge) => edge.storage_index, InternalNode::Leaf => None, @@ -232,8 +234,12 @@ mod tests { let uut = BinaryNode { storage_index: None, height: 1, - left: Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new(1)))), - right: Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new(2)))), + left: Rc::new(RefCell::new(InternalNode::Unresolved( + TrieStorageIndex::new(1), + ))), + right: Rc::new(RefCell::new(InternalNode::Unresolved( + TrieStorageIndex::new(2), + ))), }; let mut zero_key = bitvec![u8, Msb0; 1; 251]; @@ -251,8 +257,12 @@ mod tests { #[test] fn get_child() { - let left = Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new(1)))); - let right = Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new(2)))); + let left = Rc::new(RefCell::new(InternalNode::Unresolved( + TrieStorageIndex::new(1), + ))); + let right = Rc::new(RefCell::new(InternalNode::Unresolved( + TrieStorageIndex::new(2), + ))); let uut = BinaryNode { storage_index: None, @@ -320,7 +330,9 @@ mod tests { #[test] fn full() { let key = felt!("0x123456789abcdef"); - let child = Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new(1)))); + let child = Rc::new(RefCell::new(InternalNode::Unresolved( + TrieStorageIndex::new(1), + ))); let uut = EdgeNode { storage_index: None, @@ -335,7 +347,9 @@ mod tests { #[test] fn prefix() { let key = felt!("0x123456789abcdef"); - let child = Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new(1)))); + let child = Rc::new(RefCell::new(InternalNode::Unresolved( + TrieStorageIndex::new(1), + ))); let path = key.view_bits()[..45].to_bitvec(); @@ -352,7 +366,9 @@ mod tests { #[test] fn suffix() { let key = felt!("0x123456789abcdef"); - let child = Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new(1)))); + let child = Rc::new(RefCell::new(InternalNode::Unresolved( + TrieStorageIndex::new(1), + ))); let path = key.view_bits()[50..].to_bitvec(); @@ -369,7 +385,9 @@ mod tests { #[test] fn middle_slice() { let key = felt!("0x123456789abcdef"); - let child = Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new(1)))); + let child = Rc::new(RefCell::new(InternalNode::Unresolved( + TrieStorageIndex::new(1), + ))); let path = key.view_bits()[230..235].to_bitvec(); diff --git a/crates/merkle-tree/src/tree.rs b/crates/merkle-tree/src/tree.rs index 25db480802..cd87acfe83 100644 --- a/crates/merkle-tree/src/tree.rs +++ b/crates/merkle-tree/src/tree.rs @@ -59,9 +59,9 @@ use std::rc::Rc; use anyhow::Context; use bitvec::prelude::{BitSlice, BitVec, Msb0}; use pathfinder_common::hash::FeltHash; -use pathfinder_common::storage_index::StorageIndex; use pathfinder_common::trie::TrieNode; use pathfinder_crypto::Felt; +use pathfinder_storage::connection::storage_index::TrieStorageIndex; use pathfinder_storage::{Node, NodeRef, StoredNode, TrieUpdate}; use crate::merkle_node::{BinaryNode, Direction, EdgeNode, InternalNode}; @@ -80,9 +80,9 @@ pub struct MerkleTree { } impl MerkleTree { - pub fn new(root: StorageIndex) -> Self { + pub fn new(root: TrieStorageIndex) -> Self { let root = Some(Rc::new(RefCell::new(InternalNode::Unresolved( - StorageIndex::new(root.get()), + TrieStorageIndex::new(root.get()), )))); Self { root, @@ -171,7 +171,7 @@ impl MerkleTree { .hash(idx.get()) .context("Fetching stored node's hash")? .context("Stored node's hash is missing")?; - (hash, Some(NodeRef::StorageIndex(idx.get()))) + (hash, Some(NodeRef::TrieStorageIndex(idx.get()))) } InternalNode::Leaf => { let hash = if let Some(value) = self.leaves.get(&path) { @@ -750,31 +750,31 @@ impl MerkleTree { let node = match node { StoredNode::Binary { left, right } => InternalNode::Binary(BinaryNode { - storage_index: Some(StorageIndex::new(index)), + storage_index: Some(TrieStorageIndex::new(index)), height, - left: Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new( - left, - )))), - right: Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new( - right, - )))), + left: Rc::new(RefCell::new(InternalNode::Unresolved( + TrieStorageIndex::new(left), + ))), + right: Rc::new(RefCell::new(InternalNode::Unresolved( + TrieStorageIndex::new(right), + ))), }), StoredNode::Edge { child, path } => InternalNode::Edge(EdgeNode { - storage_index: Some(StorageIndex::new(index)), + storage_index: Some(TrieStorageIndex::new(index)), height, path, - child: Rc::new(RefCell::new(InternalNode::Unresolved(StorageIndex::new( - child, - )))), + child: Rc::new(RefCell::new(InternalNode::Unresolved( + TrieStorageIndex::new(child), + ))), }), StoredNode::LeafBinary => InternalNode::Binary(BinaryNode { - storage_index: Some(StorageIndex::new(index)), + storage_index: Some(TrieStorageIndex::new(index)), height, left: Rc::new(RefCell::new(InternalNode::Leaf)), right: Rc::new(RefCell::new(InternalNode::Leaf)), }), StoredNode::LeafEdge { path } => InternalNode::Edge(EdgeNode { - storage_index: Some(StorageIndex::new(index)), + storage_index: Some(TrieStorageIndex::new(index)), height, path, child: Rc::new(RefCell::new(InternalNode::Leaf)), @@ -1023,12 +1023,12 @@ mod tests { let node = match node { Node::Binary { left, right } => { let left = match left { - NodeRef::StorageIndex(idx) => idx, + NodeRef::TrieStorageIndex(idx) => idx, NodeRef::Index(idx) => storage.next_index + (idx as u64), }; let right = match right { - NodeRef::StorageIndex(idx) => idx, + NodeRef::TrieStorageIndex(idx) => idx, NodeRef::Index(idx) => storage.next_index + (idx as u64), }; @@ -1036,7 +1036,7 @@ mod tests { } Node::Edge { child, path } => { let child = match child { - NodeRef::StorageIndex(idx) => idx, + NodeRef::TrieStorageIndex(idx) => idx, NodeRef::Index(idx) => storage.next_index + (idx as u64), }; @@ -1378,7 +1378,7 @@ mod tests { ); assert_eq!(storage.nodes.len(), 1); - let tree = TestTree::new(StorageIndex::new(root.1)); + let tree = TestTree::new(TrieStorageIndex::new(root.1)); let root = commit_and_persist_without_pruning(tree, &mut storage); assert_eq!( root.0, @@ -1401,7 +1401,7 @@ mod tests { ); assert_eq!(storage.nodes.len(), 1); - let mut tree = TestTree::new(StorageIndex::new(root.1)); + let mut tree = TestTree::new(TrieStorageIndex::new(root.1)); tree.set(&storage, felt!("0x1").view_bits().to_bitvec(), Felt::ZERO) .unwrap(); let root = commit_and_persist_with_pruning(tree, &mut storage); @@ -1432,7 +1432,7 @@ mod tests { let root = commit_and_persist_with_pruning(uut, &mut storage); - let uut = TestTree::new(StorageIndex::new(root.1)); + let uut = TestTree::new(TrieStorageIndex::new(root.1)); assert_eq!(uut.get(&storage, key0).unwrap(), Some(val0)); assert_eq!(uut.get(&storage, key1).unwrap(), Some(val1)); @@ -1480,7 +1480,7 @@ mod tests { // Delete the final leaf; this exercises the bug as the nodes are all in storage // (unresolved). - let mut uut = TestTree::new(StorageIndex::new(root.1)); + let mut uut = TestTree::new(TrieStorageIndex::new(root.1)); let key = leaves[4].0.view_bits().to_bitvec(); let val = leaves[4].1; uut.set(&storage, key, val).unwrap(); @@ -1505,25 +1505,25 @@ mod tests { uut.set(&storage, key0.clone(), val0).unwrap(); let root0 = commit_and_persist_without_pruning(uut, &mut storage); - let mut uut = TestTree::new(StorageIndex::new(root0.1)); + let mut uut = TestTree::new(TrieStorageIndex::new(root0.1)); uut.set(&storage, key1.clone(), val1).unwrap(); let root1 = commit_and_persist_without_pruning(uut, &mut storage); - let mut uut = TestTree::new(StorageIndex::new(root1.1)); + let mut uut = TestTree::new(TrieStorageIndex::new(root1.1)); uut.set(&storage, key2.clone(), val2).unwrap(); let root2 = commit_and_persist_without_pruning(uut, &mut storage); - let uut = TestTree::new(StorageIndex::new(root0.1)); + let uut = TestTree::new(TrieStorageIndex::new(root0.1)); assert_eq!(uut.get(&storage, key0.clone()).unwrap(), Some(val0)); assert_eq!(uut.get(&storage, key1.clone()).unwrap(), None); assert_eq!(uut.get(&storage, key2.clone()).unwrap(), None); - let uut = TestTree::new(StorageIndex::new(root1.1)); + let uut = TestTree::new(TrieStorageIndex::new(root1.1)); assert_eq!(uut.get(&storage, key0.clone()).unwrap(), Some(val0)); assert_eq!(uut.get(&storage, key1.clone()).unwrap(), Some(val1)); assert_eq!(uut.get(&storage, key2.clone()).unwrap(), None); - let uut = TestTree::new(StorageIndex::new(root2.1)); + let uut = TestTree::new(TrieStorageIndex::new(root2.1)); assert_eq!(uut.get(&storage, key0).unwrap(), Some(val0)); assert_eq!(uut.get(&storage, key1).unwrap(), Some(val1)); assert_eq!(uut.get(&storage, key2).unwrap(), Some(val2)); @@ -1544,25 +1544,25 @@ mod tests { uut.set(&storage, key0.clone(), val0).unwrap(); let root0 = commit_and_persist_without_pruning(uut, &mut storage); - let mut uut = TestTree::new(StorageIndex::new(root0.1)); + let mut uut = TestTree::new(TrieStorageIndex::new(root0.1)); uut.set(&storage, key1.clone(), val1).unwrap(); let root1 = commit_and_persist_without_pruning(uut, &mut storage); - let mut uut = TestTree::new(StorageIndex::new(root0.1)); + let mut uut = TestTree::new(TrieStorageIndex::new(root0.1)); uut.set(&storage, key2.clone(), val2).unwrap(); let root2 = commit_and_persist_without_pruning(uut, &mut storage); - let uut = TestTree::new(StorageIndex::new(root0.1)); + let uut = TestTree::new(TrieStorageIndex::new(root0.1)); assert_eq!(uut.get(&storage, key0.clone()).unwrap(), Some(val0)); assert_eq!(uut.get(&storage, key1.clone()).unwrap(), None); assert_eq!(uut.get(&storage, key2.clone()).unwrap(), None); - let uut = TestTree::new(StorageIndex::new(root1.1)); + let uut = TestTree::new(TrieStorageIndex::new(root1.1)); assert_eq!(uut.get(&storage, key0.clone()).unwrap(), Some(val0)); assert_eq!(uut.get(&storage, key1.clone()).unwrap(), Some(val1)); assert_eq!(uut.get(&storage, key2.clone()).unwrap(), None); - let uut = TestTree::new(StorageIndex::new(root2.1)); + let uut = TestTree::new(TrieStorageIndex::new(root2.1)); assert_eq!(uut.get(&storage, key0).unwrap(), Some(val0)); assert_eq!(uut.get(&storage, key1).unwrap(), None); assert_eq!(uut.get(&storage, key2).unwrap(), Some(val2)); @@ -1579,10 +1579,10 @@ mod tests { let root0 = commit_and_persist_with_pruning(uut, &mut storage); - let uut = TestTree::new(StorageIndex::new(root0.1)); + let uut = TestTree::new(TrieStorageIndex::new(root0.1)); let root1 = commit_and_persist_with_pruning(uut, &mut storage); - let uut = TestTree::new(StorageIndex::new(root1.1)); + let uut = TestTree::new(TrieStorageIndex::new(root1.1)); let root2 = commit_and_persist_with_pruning(uut, &mut storage); assert_eq!(root0.0, root1.0); @@ -1693,7 +1693,7 @@ mod tests { ); let root = commit_and_persist_with_pruning(uut, &mut storage); - let mut uut = TestTree::new(StorageIndex::new(root.1)); + let mut uut = TestTree::new(TrieStorageIndex::new(root.1)); set!( uut, felt!("0x5c5e36947656f78c487b42ca69d96e79c01eac62f50d996f3972c9851bd5f64"), @@ -1701,7 +1701,7 @@ mod tests { ); let root = commit_and_persist_with_pruning(uut, &mut storage); - let mut uut = TestTree::new(StorageIndex::new(root.1)); + let mut uut = TestTree::new(TrieStorageIndex::new(root.1)); let mut visited = vec![]; let mut visitor_fn = |node: &InternalNode, path: &BitSlice| { @@ -1717,7 +1717,7 @@ mod tests { ); let root = commit_and_persist_with_pruning(uut, &mut storage); - let mut uut = TestTree::new(StorageIndex::new(root.1)); + let mut uut = TestTree::new(TrieStorageIndex::new(root.1)); let mut visited = vec![]; let mut visitor_fn = |node: &InternalNode, path: &BitSlice| { @@ -1781,7 +1781,7 @@ mod tests { assert!(tx.class_root_exists(BlockNumber::GENESIS).unwrap()); assert_eq!( tx.class_root_index(BlockNumber::GENESIS).unwrap(), - Some(StorageIndex::new(root_index)) + Some(TrieStorageIndex::new(root_index)) ); // Open the tree but do no updates. @@ -1804,7 +1804,7 @@ mod tests { assert!(!tx.class_root_exists(block_number).unwrap()); assert_eq!( tx.class_root_index(block_number).unwrap(), - Some(StorageIndex::new(root_index)) + Some(TrieStorageIndex::new(root_index)) ); // Delete value diff --git a/crates/storage/src/connection.rs b/crates/storage/src/connection.rs index 3476be3be8..5efb260f40 100644 --- a/crates/storage/src/connection.rs +++ b/crates/storage/src/connection.rs @@ -10,6 +10,7 @@ mod reference; mod reorg_counter; mod signature; mod state_update; +pub mod storage_index; pub(crate) mod transaction; mod trie; diff --git a/crates/common/src/storage_index.rs b/crates/storage/src/connection/storage_index.rs similarity index 83% rename from crates/common/src/storage_index.rs rename to crates/storage/src/connection/storage_index.rs index b18843e6c1..68b8db8b0d 100644 --- a/crates/common/src/storage_index.rs +++ b/crates/storage/src/connection/storage_index.rs @@ -1,8 +1,8 @@ /// A newtype for the storage index of a trie node. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct StorageIndex(u64); +pub struct TrieStorageIndex(u64); -impl StorageIndex { +impl TrieStorageIndex { /// Create a new StorageIndex. pub fn new(index: u64) -> Self { Self(index) diff --git a/crates/storage/src/connection/trie.rs b/crates/storage/src/connection/trie.rs index 88797355a0..352381d5aa 100644 --- a/crates/storage/src/connection/trie.rs +++ b/crates/storage/src/connection/trie.rs @@ -4,9 +4,9 @@ use anyhow::Context; use bitvec::prelude::Msb0; use bitvec::vec::BitVec; use pathfinder_common::prelude::*; -use pathfinder_common::storage_index::StorageIndex; use pathfinder_crypto::Felt; +use super::storage_index::TrieStorageIndex; use crate::prelude::*; use crate::{BlockId, TriePruneMode}; @@ -14,7 +14,7 @@ impl Transaction<'_> { pub fn class_root_index( &self, block_number: BlockNumber, - ) -> anyhow::Result> { + ) -> anyhow::Result> { self.inner() .query_row( "SELECT root_index FROM class_roots WHERE block_number <= ? ORDER BY block_number \ @@ -23,7 +23,7 @@ impl Transaction<'_> { |row| row.get::<_, Option>(0), ) .optional() - .map(|option_u64| option_u64.flatten().map(StorageIndex::new)) + .map(|option_u64| option_u64.flatten().map(TrieStorageIndex::new)) .map_err(Into::into) } @@ -40,7 +40,7 @@ impl Transaction<'_> { pub fn storage_root_index( &self, block_number: BlockNumber, - ) -> anyhow::Result> { + ) -> anyhow::Result> { self.inner() .query_row( "SELECT root_index FROM storage_roots WHERE block_number <= ? ORDER BY \ @@ -49,7 +49,7 @@ impl Transaction<'_> { |row| row.get::<_, Option>(0), ) .optional() - .map(|option_u64| option_u64.flatten().map(StorageIndex::new)) + .map(|option_u64| option_u64.flatten().map(TrieStorageIndex::new)) .map_err(Into::into) } @@ -652,7 +652,7 @@ pub enum Node { #[derive(Copy, Clone, Debug)] pub enum NodeRef { // A reference to a node that has already been committed to storage. - StorageIndex(u64), + TrieStorageIndex(u64), // A reference to a node that has not yet been committed to storage. // The index within the `nodes_added` vector is used as a reference. Index(usize), @@ -748,14 +748,14 @@ impl Node { let node = match self { Node::Binary { left, right } => { let left = match left { - NodeRef::StorageIndex(id) => *id, + NodeRef::TrieStorageIndex(id) => *id, NodeRef::Index(idx) => *storage_indices .get(idx) .context("Left child index missing")?, }; let right = match right { - NodeRef::StorageIndex(id) => *id, + NodeRef::TrieStorageIndex(id) => *id, NodeRef::Index(idx) => *storage_indices .get(idx) .context("Right child index missing")?, @@ -765,7 +765,7 @@ impl Node { } Node::Edge { child, path } => { let child = match child { - NodeRef::StorageIndex(id) => id, + NodeRef::TrieStorageIndex(id) => id, NodeRef::Index(idx) => { storage_indices.get(idx).context("Child index missing")? } @@ -804,25 +804,25 @@ mod tests { tx.insert_class_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(123)) .unwrap(); let result = tx.class_root_index(BlockNumber::GENESIS).unwrap(); - assert_eq!(result, Some(StorageIndex::new(123))); + assert_eq!(result, Some(TrieStorageIndex::new(123))); tx.insert_class_root(BlockNumber::GENESIS + 1, RootIndexUpdate::Updated(456)) .unwrap(); let result = tx.class_root_index(BlockNumber::GENESIS).unwrap(); - assert_eq!(result, Some(StorageIndex::new(123))); + assert_eq!(result, Some(TrieStorageIndex::new(123))); let result = tx.class_root_index(BlockNumber::GENESIS + 1).unwrap(); - assert_eq!(result, Some(StorageIndex::new(456))); + assert_eq!(result, Some(TrieStorageIndex::new(456))); let result = tx.class_root_index(BlockNumber::GENESIS + 2).unwrap(); - assert_eq!(result, Some(StorageIndex::new(456))); + assert_eq!(result, Some(TrieStorageIndex::new(456))); tx.insert_class_root(BlockNumber::GENESIS + 10, RootIndexUpdate::Updated(789)) .unwrap(); let result = tx.class_root_index(BlockNumber::GENESIS + 9).unwrap(); - assert_eq!(result, Some(StorageIndex::new(456))); + assert_eq!(result, Some(TrieStorageIndex::new(456))); let result = tx.class_root_index(BlockNumber::GENESIS + 10).unwrap(); - assert_eq!(result, Some(StorageIndex::new(789))); + assert_eq!(result, Some(TrieStorageIndex::new(789))); let result = tx.class_root_index(BlockNumber::GENESIS + 11).unwrap(); - assert_eq!(result, Some(StorageIndex::new(789))); + assert_eq!(result, Some(TrieStorageIndex::new(789))); tx.insert_class_root(BlockNumber::GENESIS + 12, RootIndexUpdate::TrieEmpty) .unwrap(); @@ -846,25 +846,25 @@ mod tests { tx.insert_storage_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(123)) .unwrap(); let result = tx.storage_root_index(BlockNumber::GENESIS).unwrap(); - assert_eq!(result, Some(StorageIndex::new(123))); + assert_eq!(result, Some(TrieStorageIndex::new(123))); tx.insert_storage_root(BlockNumber::GENESIS + 1, RootIndexUpdate::Updated(456)) .unwrap(); let result = tx.storage_root_index(BlockNumber::GENESIS).unwrap(); - assert_eq!(result, Some(StorageIndex::new(123))); + assert_eq!(result, Some(TrieStorageIndex::new(123))); let result = tx.storage_root_index(BlockNumber::GENESIS + 1).unwrap(); - assert_eq!(result, Some(StorageIndex::new(456))); + assert_eq!(result, Some(TrieStorageIndex::new(456))); let result = tx.storage_root_index(BlockNumber::GENESIS + 2).unwrap(); - assert_eq!(result, Some(StorageIndex::new(456))); + assert_eq!(result, Some(TrieStorageIndex::new(456))); tx.insert_storage_root(BlockNumber::GENESIS + 10, RootIndexUpdate::Updated(789)) .unwrap(); let result = tx.storage_root_index(BlockNumber::GENESIS + 9).unwrap(); - assert_eq!(result, Some(StorageIndex::new(456))); + assert_eq!(result, Some(TrieStorageIndex::new(456))); let result = tx.storage_root_index(BlockNumber::GENESIS + 10).unwrap(); - assert_eq!(result, Some(StorageIndex::new(789))); + assert_eq!(result, Some(TrieStorageIndex::new(789))); let result = tx.storage_root_index(BlockNumber::GENESIS + 11).unwrap(); - assert_eq!(result, Some(StorageIndex::new(789))); + assert_eq!(result, Some(TrieStorageIndex::new(789))); tx.insert_storage_root(BlockNumber::GENESIS + 12, RootIndexUpdate::TrieEmpty) .unwrap(); diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index 5078081c7e..74d3fcb346 100644 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -7,7 +7,7 @@ mod prelude; mod bloom; pub use bloom::BLOCK_RANGE_LEN; -mod connection; +pub mod connection; pub mod fake; mod params; mod schema; From a4152a9aef959df6132e13bda77b664cdeeae402 Mon Sep 17 00:00:00 2001 From: varun-doshi Date: Wed, 11 Dec 2024 20:33:37 +0530 Subject: [PATCH 6/8] convert u64 index types to TrieStorageIndex --- crates/merkle-tree/src/contract.rs | 2 +- crates/merkle-tree/src/tree.rs | 46 +++--- crates/rpc/src/method/get_storage_proof.rs | 2 +- .../rpc/src/pathfinder/methods/get_proof.rs | 7 +- crates/storage/src/connection/trie.rs | 141 +++++++++--------- 5 files changed, 101 insertions(+), 97 deletions(-) diff --git a/crates/merkle-tree/src/contract.rs b/crates/merkle-tree/src/contract.rs index c8fb6bf742..650429211d 100644 --- a/crates/merkle-tree/src/contract.rs +++ b/crates/merkle-tree/src/contract.rs @@ -67,7 +67,7 @@ impl<'tx> ContractsStorageTree<'tx> { block: Some(block), contract, }; - let tree = MerkleTree::new(TrieStorageIndex::new(root)); + let tree = MerkleTree::new(root); Ok(Self { tree, storage }) } diff --git a/crates/merkle-tree/src/tree.rs b/crates/merkle-tree/src/tree.rs index cd87acfe83..d2110c9cda 100644 --- a/crates/merkle-tree/src/tree.rs +++ b/crates/merkle-tree/src/tree.rs @@ -72,7 +72,7 @@ use crate::storage::Storage; pub struct MerkleTree { root: Option>>, leaves: HashMap, Felt>, - nodes_removed: Vec, + nodes_removed: Vec, _hasher: std::marker::PhantomData, /// If enables, node hashes are verified as they are resolved. This allows /// testing for database corruption. @@ -139,11 +139,11 @@ impl MerkleTree { Felt::ZERO }; - removed.extend(self.nodes_removed); + removed.extend(self.nodes_removed.iter().map(|value|value.get())); Ok(TrieUpdate { nodes_added: added, - nodes_removed: removed, + nodes_removed: removed.into_iter().map(|value|TrieStorageIndex::new(value)).collect(), root_commitment: root_hash, }) } @@ -374,7 +374,7 @@ impl MerkleTree { let old_node = node.replace(updated); if let Some(index) = old_node.storage_index() { - self.nodes_removed.push(index.get()); + self.nodes_removed.push(index); }; } None => { @@ -474,14 +474,14 @@ impl MerkleTree { // Replace the old binary node with the new edge node. let old_node = node.replace(InternalNode::Edge(new_edge)); if let Some(index) = old_node.storage_index() { - self.nodes_removed.push(index.get()); + self.nodes_removed.push(index); }; } None => { // We reached the root without a hitting binary node. The new tree // must therefore be empty. self.root = None; - self.nodes_removed.extend(indexes_removed); + self.nodes_removed.extend(indexes_removed.iter().map(|value|TrieStorageIndex::new(*value))); return Ok(()); } }; @@ -495,7 +495,7 @@ impl MerkleTree { } // All nodes below the binary node were deleted - self.nodes_removed.extend(indexes_removed); + self.nodes_removed.extend(indexes_removed.iter().map(|value|TrieStorageIndex::new(*value))); Ok(()) } @@ -581,8 +581,8 @@ impl MerkleTree { StoredNode::Binary { left, right } => { // Choose the direction to go in. next = match key.get(height).map(|b| Direction::from(*b)) { - Some(Direction::Left) => Some(left), - Some(Direction::Right) => Some(right), + Some(Direction::Left) => Some(left.get()), + Some(Direction::Right) => Some(right.get()), None => { return Err( anyhow::anyhow!("Key path too short for binary node").into() @@ -592,12 +592,12 @@ impl MerkleTree { height += 1; let left = storage - .hash(left) + .hash(left.get()) .context("Querying left child's hash")? .context("Left child's hash is missing")?; let right = storage - .hash(right) + .hash(right.get()) .context("Querying right child's hash")? .context("Right child's hash is missing")?; @@ -611,11 +611,11 @@ impl MerkleTree { // If the path matches then we continue otherwise the proof is complete. if key == path { - next = Some(child); + next = Some(child.get()); } let child = storage - .hash(child) + .hash(child.get()) .context("Querying child child's hash")? .context("Child's hash is missing")?; @@ -753,10 +753,10 @@ impl MerkleTree { storage_index: Some(TrieStorageIndex::new(index)), height, left: Rc::new(RefCell::new(InternalNode::Unresolved( - TrieStorageIndex::new(left), + left, ))), right: Rc::new(RefCell::new(InternalNode::Unresolved( - TrieStorageIndex::new(right), + right, ))), }), StoredNode::Edge { child, path } => InternalNode::Edge(EdgeNode { @@ -764,7 +764,7 @@ impl MerkleTree { height, path, child: Rc::new(RefCell::new(InternalNode::Unresolved( - TrieStorageIndex::new(child), + child, ))), }), StoredNode::LeafBinary => InternalNode::Binary(BinaryNode { @@ -803,7 +803,7 @@ impl MerkleTree { if let Some(child_edge) = resolved_child.as_edge().cloned() { parent.path.extend_from_bitslice(&child_edge.path); if let Some(storage_index) = child_edge.storage_index { - self.nodes_removed.push(storage_index.get()); + self.nodes_removed.push(storage_index); } parent.child = child_edge.child; } @@ -1013,7 +1013,7 @@ mod tests { if prune_nodes { for idx in update.nodes_removed { - storage.nodes.remove(&idx); + storage.nodes.remove(&idx.get()); } } @@ -1032,7 +1032,7 @@ mod tests { NodeRef::Index(idx) => storage.next_index + (idx as u64), }; - StoredNode::Binary { left, right } + StoredNode::Binary { left:TrieStorageIndex::new(left), right:TrieStorageIndex::new(right) } } Node::Edge { child, path } => { let child = match child { @@ -1040,7 +1040,7 @@ mod tests { NodeRef::Index(idx) => storage.next_index + (idx as u64), }; - StoredNode::Edge { child, path } + StoredNode::Edge { child:TrieStorageIndex::new(child), path } } Node::LeafBinary => StoredNode::LeafBinary, Node::LeafEdge { path } => StoredNode::LeafEdge { path }, @@ -1775,13 +1775,13 @@ mod tests { let RootIndexUpdate::Updated(root_index) = root_index_update else { panic!("Expected root index to be updated"); }; - assert_eq!(root_index, 1); + assert_eq!(root_index,TrieStorageIndex::new(1)); tx.insert_class_root(BlockNumber::GENESIS, root_index_update) .unwrap(); assert!(tx.class_root_exists(BlockNumber::GENESIS).unwrap()); assert_eq!( tx.class_root_index(BlockNumber::GENESIS).unwrap(), - Some(TrieStorageIndex::new(root_index)) + Some(TrieStorageIndex::new(root_index.get())) ); // Open the tree but do no updates. @@ -1804,7 +1804,7 @@ mod tests { assert!(!tx.class_root_exists(block_number).unwrap()); assert_eq!( tx.class_root_index(block_number).unwrap(), - Some(TrieStorageIndex::new(root_index)) + Some(TrieStorageIndex::new(root_index.get())) ); // Delete value diff --git a/crates/rpc/src/method/get_storage_proof.rs b/crates/rpc/src/method/get_storage_proof.rs index 5528bf69b0..ce78fa479b 100644 --- a/crates/rpc/src/method/get_storage_proof.rs +++ b/crates/rpc/src/method/get_storage_proof.rs @@ -416,7 +416,7 @@ pub async fn get_storage_proof(context: RpcContext, input: Input) -> Result { &self, block_number: BlockNumber, contract: ContractAddress, - ) -> anyhow::Result> { + ) -> anyhow::Result> { self.inner() .query_row( "SELECT root_index FROM contract_roots WHERE contract_address = ? AND \ @@ -76,7 +76,7 @@ impl Transaction<'_> { |row| row.get::<_, Option>(0), ) .optional() - .map(|x| x.flatten()) + .map(|x| x.flatten().map(TrieStorageIndex::new)) .map_err(Into::into) } @@ -110,7 +110,7 @@ impl Transaction<'_> { self.inner().execute( "INSERT OR REPLACE INTO class_roots (block_number, root_index) VALUES(?, ?)", - params![&block_number, &new_root_index], + params![&block_number, &new_root_index.unwrap().get()], )?; if let TriePruneMode::Prune { num_blocks_kept } = self.trie_prune_mode { @@ -221,7 +221,7 @@ impl Transaction<'_> { }; self.inner().execute( "INSERT OR REPLACE INTO storage_roots (block_number, root_index) VALUES(?, ?)", - params![&block_number, &new_root_index], + params![&block_number, &new_root_index.unwrap().get()], )?; if let TriePruneMode::Prune { num_blocks_kept } = self.trie_prune_mode { @@ -269,7 +269,7 @@ impl Transaction<'_> { self.inner().execute( "INSERT OR REPLACE INTO contract_roots (block_number, contract_address, root_index) \ VALUES(?, ?, ?)", - params![&block_number, &contract, &new_root_index], + params![&block_number, &contract, &new_root_index.unwrap().get()], )?; if let TriePruneMode::Prune { num_blocks_kept } = self.trie_prune_mode { @@ -318,11 +318,11 @@ impl Transaction<'_> { } pub fn contract_trie_node(&self, index: u64) -> anyhow::Result> { - self.trie_node(index, "trie_contracts") + self.trie_node(TrieStorageIndex::new(index), "trie_contracts") } pub fn contract_trie_node_hash(&self, index: u64) -> anyhow::Result> { - self.trie_node_hash(index, "trie_contracts") + self.trie_node_hash(TrieStorageIndex::new(index), "trie_contracts") } pub fn insert_class_trie( @@ -334,11 +334,11 @@ impl Transaction<'_> { } pub fn class_trie_node(&self, index: u64) -> anyhow::Result> { - self.trie_node(index, "trie_class") + self.trie_node(TrieStorageIndex::new(index), "trie_class") } pub fn class_trie_node_hash(&self, index: u64) -> anyhow::Result> { - self.trie_node_hash(index, "trie_class") + self.trie_node_hash(TrieStorageIndex::new(index), "trie_class") } pub fn insert_storage_trie( @@ -350,11 +350,11 @@ impl Transaction<'_> { } pub fn storage_trie_node(&self, index: u64) -> anyhow::Result> { - self.trie_node(index, "trie_storage") + self.trie_node(TrieStorageIndex::new(index), "trie_storage") } pub fn storage_trie_node_hash(&self, index: u64) -> anyhow::Result> { - self.trie_node_hash(index, "trie_storage") + self.trie_node_hash(TrieStorageIndex::new(index), "trie_storage") } /// Prune tries by removing nodes that are no longer needed at the given @@ -382,7 +382,7 @@ impl Transaction<'_> { /// Mark the input nodes as ready for removal. fn remove_trie( &self, - removed: &[u64], + removed: &[TrieStorageIndex], block_number: BlockNumber, table: &'static str, ) -> anyhow::Result<()> { @@ -395,7 +395,7 @@ impl Transaction<'_> { .context("Creating statement to insert removal marker")?; stmt.execute(params![ &block_number, - &bincode::encode_to_vec(removed, bincode::config::standard()) + &bincode::encode_to_vec(removed.into_iter().map(|trie_storaage_index|trie_storaage_index.get()).collect::>(), bincode::config::standard()) .context("Serializing indices")? ]) .context("Inserting removal marker")?; @@ -563,14 +563,14 @@ impl Transaction<'_> { } Ok(RootIndexUpdate::Updated( - *indices - .get(&(update.nodes_added.len() - 1)) - .expect("Root index must exist as we just inserted it"), + TrieStorageIndex::new(*(indices + .get(&(update.nodes_added.len() - 1))) + .expect("Root index must exist as we just inserted it")), )) } /// Returns the node with the given index. - fn trie_node(&self, index: u64, table: &'static str) -> anyhow::Result> { + fn trie_node(&self, index: TrieStorageIndex, table: &'static str) -> anyhow::Result> { // We rely on sqlite caching the statement here. Storing the statement would be // nice, however that leads to &mut requirements or interior mutable // work-arounds. @@ -580,7 +580,7 @@ impl Transaction<'_> { .context("Creating get statement")?; let Some(data): Option> = stmt - .query_row(params![&index], |row| row.get(0)) + .query_row(params![&index.get()], |row| row.get(0)) .optional()? else { return Ok(None); @@ -592,7 +592,7 @@ impl Transaction<'_> { } /// Returns the hash of the node with the given index. - fn trie_node_hash(&self, index: u64, table: &'static str) -> anyhow::Result> { + fn trie_node_hash(&self, index: TrieStorageIndex, table: &'static str) -> anyhow::Result> { // We rely on sqlite caching the statement here. Storing the statement would be // nice, however that leads to &mut requirements or interior mutable // work-arounds. @@ -601,7 +601,7 @@ impl Transaction<'_> { .prepare_cached(&format!("SELECT hash FROM {table} WHERE idx = ?")) .context("Creating get statement")?; - stmt.query_row(params![&index], |row| row.get_felt(0)) + stmt.query_row(params![&index.get()], |row| row.get_felt(0)) .optional() .map_err(Into::into) } @@ -620,7 +620,7 @@ pub struct TrieUpdate { /// The last node is the root of the trie. pub nodes_added: Vec<(Felt, Node)>, /// Nodes committed to storage that have been removed. - pub nodes_removed: Vec, + pub nodes_removed: Vec, /// New root commitment of the trie. pub root_commitment: Felt, } @@ -629,7 +629,7 @@ pub struct TrieUpdate { #[derive(Debug, PartialEq)] pub enum RootIndexUpdate { Unchanged, - Updated(u64), + Updated(TrieStorageIndex), TrieEmpty, } @@ -660,8 +660,8 @@ pub enum NodeRef { #[derive(Clone, Debug, PartialEq)] pub enum StoredNode { - Binary { left: u64, right: u64 }, - Edge { child: u64, path: BitVec }, + Binary { left: TrieStorageIndex, right: TrieStorageIndex }, + Edge { child: TrieStorageIndex, path: BitVec }, LeafBinary, LeafEdge { path: BitVec }, } @@ -682,8 +682,8 @@ impl StoredNode { fn encode(&self, buffer: &mut [u8]) -> Result { let helper = match self { Self::Binary { left, right } => StoredSerde::Binary { - left: *left, - right: *right, + left: left.get(), + right: right.get(), }, Self::Edge { child, path } => { let path_length = path.len() as u8; @@ -694,7 +694,7 @@ impl StoredNode { path.push(path_length); StoredSerde::Edge { - child: *child, + child: child.get(), path, } } @@ -719,14 +719,14 @@ impl StoredNode { let helper = bincode::borrow_decode_from_slice(data, Self::CODEC_CFG)?; let node = match helper.0 { - StoredSerde::Binary { left, right } => Self::Binary { left, right }, + StoredSerde::Binary { left, right } => Self::Binary { left:TrieStorageIndex::new(left), right:TrieStorageIndex::new(right) }, StoredSerde::Edge { child, mut path } => { let path_length = path.pop().ok_or(bincode::error::DecodeError::Other( "Edge node's path length is missing", ))?; let mut path = bitvec::vec::BitVec::from_vec(path); path.resize(path_length as usize, false); - Self::Edge { child, path } + Self::Edge { child:TrieStorageIndex::new(child), path } } StoredSerde::LeafBinary => Self::LeafBinary, StoredSerde::LeafEdge { mut path } => { @@ -761,7 +761,7 @@ impl Node { .context("Right child index missing")?, }; - StoredNode::Binary { left, right } + StoredNode::Binary { left:TrieStorageIndex::new(left), right:TrieStorageIndex::new(right) } } Node::Edge { child, path } => { let child = match child { @@ -772,7 +772,7 @@ impl Node { }; StoredNode::Edge { - child: *child, + child: TrieStorageIndex::new(*child), path: path.clone(), } } @@ -801,12 +801,12 @@ mod tests { let result = tx.class_root_index(BlockNumber::GENESIS).unwrap(); assert_eq!(result, None); - tx.insert_class_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(123)) + tx.insert_class_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(TrieStorageIndex::new(123))) .unwrap(); let result = tx.class_root_index(BlockNumber::GENESIS).unwrap(); assert_eq!(result, Some(TrieStorageIndex::new(123))); - tx.insert_class_root(BlockNumber::GENESIS + 1, RootIndexUpdate::Updated(456)) + tx.insert_class_root(BlockNumber::GENESIS + 1, RootIndexUpdate::Updated(TrieStorageIndex::new(456))) .unwrap(); let result = tx.class_root_index(BlockNumber::GENESIS).unwrap(); assert_eq!(result, Some(TrieStorageIndex::new(123))); @@ -815,7 +815,7 @@ mod tests { let result = tx.class_root_index(BlockNumber::GENESIS + 2).unwrap(); assert_eq!(result, Some(TrieStorageIndex::new(456))); - tx.insert_class_root(BlockNumber::GENESIS + 10, RootIndexUpdate::Updated(789)) + tx.insert_class_root(BlockNumber::GENESIS + 10, RootIndexUpdate::Updated(TrieStorageIndex::new(789))) .unwrap(); let result = tx.class_root_index(BlockNumber::GENESIS + 9).unwrap(); assert_eq!(result, Some(TrieStorageIndex::new(456))); @@ -843,12 +843,12 @@ mod tests { let result = tx.storage_root_index(BlockNumber::GENESIS).unwrap(); assert_eq!(result, None); - tx.insert_storage_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(123)) + tx.insert_storage_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(TrieStorageIndex::new(123))) .unwrap(); let result = tx.storage_root_index(BlockNumber::GENESIS).unwrap(); assert_eq!(result, Some(TrieStorageIndex::new(123))); - tx.insert_storage_root(BlockNumber::GENESIS + 1, RootIndexUpdate::Updated(456)) + tx.insert_storage_root(BlockNumber::GENESIS + 1, RootIndexUpdate::Updated(TrieStorageIndex::new(456))) .unwrap(); let result = tx.storage_root_index(BlockNumber::GENESIS).unwrap(); assert_eq!(result, Some(TrieStorageIndex::new(123))); @@ -857,7 +857,7 @@ mod tests { let result = tx.storage_root_index(BlockNumber::GENESIS + 2).unwrap(); assert_eq!(result, Some(TrieStorageIndex::new(456))); - tx.insert_storage_root(BlockNumber::GENESIS + 10, RootIndexUpdate::Updated(789)) + tx.insert_storage_root(BlockNumber::GENESIS + 10, RootIndexUpdate::Updated(TrieStorageIndex::new(789))) .unwrap(); let result = tx.storage_root_index(BlockNumber::GENESIS + 9).unwrap(); assert_eq!(result, Some(TrieStorageIndex::new(456))); @@ -931,7 +931,7 @@ mod tests { tx.insert_contract_root(BlockNumber::GENESIS + 1, c1, idx1_update) .unwrap(); - tx.insert_contract_root(BlockNumber::GENESIS + 1, c2, RootIndexUpdate::Updated(888)) + tx.insert_contract_root(BlockNumber::GENESIS + 1, c2, RootIndexUpdate::Updated(TrieStorageIndex::new(888))) .unwrap(); let result1 = tx.contract_root_index(BlockNumber::GENESIS, c1).unwrap(); let result2 = tx.contract_root_index(BlockNumber::GENESIS, c2).unwrap(); @@ -947,7 +947,7 @@ mod tests { .unwrap(); let hash1 = tx.contract_root(BlockNumber::GENESIS + 1, c1).unwrap(); assert_eq!(result1, Some(idx1)); - assert_eq!(result2, Some(888)); + assert_eq!(result2, Some(TrieStorageIndex::new(888))); assert_eq!(hash1, Some(root1)); let result1 = tx .contract_root_index(BlockNumber::GENESIS + 2, c1) @@ -957,7 +957,7 @@ mod tests { .unwrap(); let hash1 = tx.contract_root(BlockNumber::GENESIS + 2, c1).unwrap(); assert_eq!(result1, Some(idx1)); - assert_eq!(result2, Some(888)); + assert_eq!(result2, Some(TrieStorageIndex::new(888))); assert_eq!(hash1, Some(root1)); let root2 = contract_root_bytes!(b"root 2"); @@ -975,7 +975,7 @@ mod tests { tx.insert_contract_root(BlockNumber::GENESIS + 10, c1, idx2_update) .unwrap(); - tx.insert_contract_root(BlockNumber::GENESIS + 11, c2, RootIndexUpdate::Updated(999)) + tx.insert_contract_root(BlockNumber::GENESIS + 11, c2, RootIndexUpdate::Updated(TrieStorageIndex::new(999))) .unwrap(); let result1 = tx .contract_root_index(BlockNumber::GENESIS + 9, c1) @@ -985,7 +985,7 @@ mod tests { .unwrap(); let hash1 = tx.contract_root(BlockNumber::GENESIS + 9, c1).unwrap(); assert_eq!(result1, Some(idx1)); - assert_eq!(result2, Some(888)); + assert_eq!(result2, Some(TrieStorageIndex::new(888))); assert_eq!(hash1, Some(root1)); let result1 = tx .contract_root_index(BlockNumber::GENESIS + 10, c1) @@ -995,13 +995,13 @@ mod tests { .unwrap(); let hash1 = tx.contract_root(BlockNumber::GENESIS + 10, c1).unwrap(); assert_eq!(result1, Some(idx2)); - assert_eq!(result2, Some(888)); + assert_eq!(result2, Some(TrieStorageIndex::new(888))); assert_eq!(hash1, Some(root2)); let result2 = tx .contract_root_index(BlockNumber::GENESIS + 11, c2) .unwrap(); let hash1 = tx.contract_root(BlockNumber::GENESIS + 11, c1).unwrap(); - assert_eq!(result2, Some(999)); + assert_eq!(result2, Some(TrieStorageIndex::new(999))); assert_eq!(hash1, Some(root2)); tx.insert_contract_root(BlockNumber::GENESIS + 12, c1, RootIndexUpdate::TrieEmpty) @@ -1022,10 +1022,10 @@ mod tests { #[rstest::rstest] #[case::binary(StoredNode::Binary { - left: 12, right: 34 + left: TrieStorageIndex::new(12), right: TrieStorageIndex::new(34) })] #[case::edge(StoredNode::Edge { - child: 123, + child: TrieStorageIndex::new(123), path: bitvec::bitvec![u8, Msb0; 1,0,0,1,0,1,0,0,0,0,0,1,1,1,1] })] #[case::binary(StoredNode::LeafBinary)] @@ -1033,11 +1033,11 @@ mod tests { path: bitvec::bitvec![u8, Msb0; 1,0,0,1,0,1,0,0,0,0,0,1,1,1,1] })] #[case::edge_max_path(StoredNode::Edge { - child: 123, + child: TrieStorageIndex::new(123), path: bitvec::bitvec![u8, Msb0; 1; 251] })] #[case::edge_min_path(StoredNode::Edge { - child: 123, + child: TrieStorageIndex::new(123), path: bitvec::bitvec![u8, Msb0; 0] })] fn serde(#[case] node: StoredNode) { @@ -1128,7 +1128,7 @@ mod tests { (felt!("4"), Node::LeafBinary), (felt!("5"), Node::LeafBinary), ], - nodes_removed: vec![1], + nodes_removed: vec![TrieStorageIndex::new(1)], root_commitment: Felt::ZERO, }, BlockNumber::GENESIS + 1, @@ -1242,7 +1242,7 @@ mod tests { (felt!("4"), Node::LeafBinary), (felt!("5"), Node::LeafBinary), ], - nodes_removed: vec![1], + nodes_removed: vec![TrieStorageIndex::new( 1)], root_commitment: Felt::ZERO, }, BlockNumber::GENESIS + 1, @@ -1409,7 +1409,7 @@ mod tests { (felt!("4"), Node::LeafBinary), (felt!("5"), Node::LeafBinary), ], - nodes_removed: vec![1, 2, 3], + nodes_removed: vec![TrieStorageIndex::new(1), TrieStorageIndex::new(2), TrieStorageIndex::new(3)], root_commitment: Felt::ZERO, }, BlockNumber::GENESIS + 1, @@ -1471,7 +1471,8 @@ mod tests { BlockNumber::GENESIS, ) .unwrap(); - assert_eq!(root_update, RootIndexUpdate::Updated(1)); + assert_eq!(root_update, RootIndexUpdate::Updated(TrieStorageIndex::new( + TrieStorageIndex::new(1).get()))); } #[test] @@ -1484,12 +1485,12 @@ mod tests { .unwrap(); let tx = db.transaction().unwrap(); - tx.insert_class_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(1)) + tx.insert_class_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(TrieStorageIndex::new(1))) .unwrap(); - tx.insert_class_root(BlockNumber::new_or_panic(1), RootIndexUpdate::Updated(2)) + tx.insert_class_root(BlockNumber::new_or_panic(1), RootIndexUpdate::Updated(TrieStorageIndex::new(2))) .unwrap(); // no root inserted for block 2 - tx.insert_class_root(BlockNumber::new_or_panic(3), RootIndexUpdate::Updated(3)) + tx.insert_class_root(BlockNumber::new_or_panic(3), RootIndexUpdate::Updated(TrieStorageIndex::new(3))) .unwrap(); assert!(!tx.class_root_exists(BlockNumber::GENESIS).unwrap()); @@ -1509,9 +1510,9 @@ mod tests { .unwrap(); let tx = db.transaction().unwrap(); - tx.insert_class_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(1)) + tx.insert_class_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(TrieStorageIndex::new(1))) .unwrap(); - tx.insert_class_root(BlockNumber::new_or_panic(1), RootIndexUpdate::Updated(2)) + tx.insert_class_root(BlockNumber::new_or_panic(1), RootIndexUpdate::Updated(TrieStorageIndex::new(2))) .unwrap(); assert!(!tx.class_root_exists(BlockNumber::GENESIS).unwrap()); @@ -1604,12 +1605,12 @@ mod tests { .unwrap(); let tx = db.transaction().unwrap(); - tx.insert_storage_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(1)) + tx.insert_storage_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(TrieStorageIndex::new(1))) .unwrap(); - tx.insert_storage_root(BlockNumber::new_or_panic(1), RootIndexUpdate::Updated(2)) + tx.insert_storage_root(BlockNumber::new_or_panic(1), RootIndexUpdate::Updated(TrieStorageIndex::new(2))) .unwrap(); // no new root index for block 2 - tx.insert_storage_root(BlockNumber::new_or_panic(3), RootIndexUpdate::Updated(3)) + tx.insert_storage_root(BlockNumber::new_or_panic(3), RootIndexUpdate::Updated(TrieStorageIndex::new(3))) .unwrap(); assert!(!tx.storage_root_exists(BlockNumber::GENESIS).unwrap()); @@ -1631,9 +1632,9 @@ mod tests { .unwrap(); let tx = db.transaction().unwrap(); - tx.insert_storage_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(1)) + tx.insert_storage_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(TrieStorageIndex::new(1))) .unwrap(); - tx.insert_storage_root(BlockNumber::new_or_panic(1), RootIndexUpdate::Updated(2)) + tx.insert_storage_root(BlockNumber::new_or_panic(1), RootIndexUpdate::Updated(TrieStorageIndex::new(2))) .unwrap(); assert!(!tx.storage_root_exists(BlockNumber::GENESIS).unwrap()); @@ -1653,19 +1654,19 @@ mod tests { let tx = db.transaction().unwrap(); let contract = contract_address!("0xdeadbeef"); - tx.insert_contract_root(BlockNumber::GENESIS, contract, RootIndexUpdate::Updated(1)) + tx.insert_contract_root(BlockNumber::GENESIS, contract, RootIndexUpdate::Updated(TrieStorageIndex::new(1))) .unwrap(); tx.insert_contract_root( BlockNumber::new_or_panic(1), contract, - RootIndexUpdate::Updated(2), + RootIndexUpdate::Updated(TrieStorageIndex::new(2)), ) .unwrap(); // no new root for block 2 tx.insert_contract_root( BlockNumber::new_or_panic(3), contract, - RootIndexUpdate::Updated(3), + RootIndexUpdate::Updated(TrieStorageIndex::new(3)), ) .unwrap(); @@ -1677,12 +1678,12 @@ mod tests { assert_eq!( tx.contract_root_index(BlockNumber::new_or_panic(2), contract) .unwrap(), - Some(2) + Some(TrieStorageIndex::new(2)) ); assert_eq!( tx.contract_root_index(BlockNumber::new_or_panic(3), contract) .unwrap(), - Some(3) + Some(TrieStorageIndex::new(3)) ); } @@ -1697,12 +1698,12 @@ mod tests { let tx = db.transaction().unwrap(); let contract = contract_address!("0xdeadbeef"); - tx.insert_contract_root(BlockNumber::GENESIS, contract, RootIndexUpdate::Updated(1)) + tx.insert_contract_root(BlockNumber::GENESIS, contract, RootIndexUpdate::Updated(TrieStorageIndex::new(1))) .unwrap(); tx.insert_contract_root( BlockNumber::new_or_panic(1), contract, - RootIndexUpdate::Updated(2), + RootIndexUpdate::Updated(TrieStorageIndex::new(2)), ) .unwrap(); @@ -1714,7 +1715,7 @@ mod tests { assert_eq!( tx.contract_root_index(BlockNumber::new_or_panic(1), contract) .unwrap(), - Some(2) + Some(TrieStorageIndex::new(2)) ); } } From 596af2e17a2389057afb7fcc80513bdccbbab6e9 Mon Sep 17 00:00:00 2001 From: varun-doshi Date: Wed, 11 Dec 2024 20:40:29 +0530 Subject: [PATCH 7/8] fmt --- crates/merkle-tree/src/tree.rs | 43 ++-- crates/rpc/src/method/get_storage_proof.rs | 26 ++- .../rpc/src/pathfinder/methods/get_proof.rs | 4 +- crates/storage/src/connection/trie.rs | 218 +++++++++++++----- 4 files changed, 203 insertions(+), 88 deletions(-) diff --git a/crates/merkle-tree/src/tree.rs b/crates/merkle-tree/src/tree.rs index f58acbdb97..ae9855fb33 100644 --- a/crates/merkle-tree/src/tree.rs +++ b/crates/merkle-tree/src/tree.rs @@ -139,11 +139,14 @@ impl MerkleTree { Felt::ZERO }; - removed.extend(self.nodes_removed.iter().map(|value|value.get())); + removed.extend(self.nodes_removed.iter().map(|value| value.get())); Ok(TrieUpdate { nodes_added: added, - nodes_removed: removed.into_iter().map(|value|TrieStorageIndex::new(value)).collect(), + nodes_removed: removed + .into_iter() + .map(|value| TrieStorageIndex::new(value)) + .collect(), root_commitment: root_hash, }) } @@ -481,7 +484,11 @@ impl MerkleTree { // We reached the root without a hitting binary node. The new tree // must therefore be empty. self.root = None; - self.nodes_removed.extend(indexes_removed.iter().map(|value|TrieStorageIndex::new(*value))); + self.nodes_removed.extend( + indexes_removed + .iter() + .map(|value| TrieStorageIndex::new(*value)), + ); return Ok(()); } }; @@ -495,7 +502,11 @@ impl MerkleTree { } // All nodes below the binary node were deleted - self.nodes_removed.extend(indexes_removed.iter().map(|value|TrieStorageIndex::new(*value))); + self.nodes_removed.extend( + indexes_removed + .iter() + .map(|value| TrieStorageIndex::new(*value)), + ); Ok(()) } @@ -752,20 +763,14 @@ impl MerkleTree { StoredNode::Binary { left, right } => InternalNode::Binary(BinaryNode { storage_index: Some(TrieStorageIndex::new(index)), height, - left: Rc::new(RefCell::new(InternalNode::Unresolved( - left, - ))), - right: Rc::new(RefCell::new(InternalNode::Unresolved( - right, - ))), + left: Rc::new(RefCell::new(InternalNode::Unresolved(left))), + right: Rc::new(RefCell::new(InternalNode::Unresolved(right))), }), StoredNode::Edge { child, path } => InternalNode::Edge(EdgeNode { storage_index: Some(TrieStorageIndex::new(index)), height, path, - child: Rc::new(RefCell::new(InternalNode::Unresolved( - child, - ))), + child: Rc::new(RefCell::new(InternalNode::Unresolved(child))), }), StoredNode::LeafBinary => InternalNode::Binary(BinaryNode { storage_index: Some(TrieStorageIndex::new(index)), @@ -1032,7 +1037,10 @@ mod tests { NodeRef::Index(idx) => storage.next_index + (idx as u64), }; - StoredNode::Binary { left:TrieStorageIndex::new(left), right:TrieStorageIndex::new(right) } + StoredNode::Binary { + left: TrieStorageIndex::new(left), + right: TrieStorageIndex::new(right), + } } Node::Edge { child, path } => { let child = match child { @@ -1040,7 +1048,10 @@ mod tests { NodeRef::Index(idx) => storage.next_index + (idx as u64), }; - StoredNode::Edge { child:TrieStorageIndex::new(child), path } + StoredNode::Edge { + child: TrieStorageIndex::new(child), + path, + } } Node::LeafBinary => StoredNode::LeafBinary, Node::LeafEdge { path } => StoredNode::LeafEdge { path }, @@ -1775,7 +1786,7 @@ mod tests { let RootIndexUpdate::Updated(root_index) = root_index_update else { panic!("Expected root index to be updated"); }; - assert_eq!(root_index,TrieStorageIndex::new(1)); + assert_eq!(root_index, TrieStorageIndex::new(1)); tx.insert_class_root(BlockNumber::GENESIS, root_index_update) .unwrap(); assert!(tx.class_root_exists(BlockNumber::GENESIS).unwrap()); diff --git a/crates/rpc/src/method/get_storage_proof.rs b/crates/rpc/src/method/get_storage_proof.rs index 7f02f2b9ad..6da7810406 100644 --- a/crates/rpc/src/method/get_storage_proof.rs +++ b/crates/rpc/src/method/get_storage_proof.rs @@ -414,17 +414,21 @@ fn get_contract_proofs( return Ok((storage_root_hash, NodeHashToNodeMappings(vec![]), vec![])); }; - let nodes = - StorageCommitmentTree::get_proofs(tx, block_number, contract_addresses, storage_root_idx.get())? - .into_iter() - .flatten() - .map(|(node, node_hash)| NodeHashToNodeMapping { - node_hash, - node: ProofNode(node), - }) - .collect::>() - .into_iter() - .collect(); + let nodes = StorageCommitmentTree::get_proofs( + tx, + block_number, + contract_addresses, + storage_root_idx.get(), + )? + .into_iter() + .flatten() + .map(|(node, node_hash)| NodeHashToNodeMapping { + node_hash, + node: ProofNode(node), + }) + .collect::>() + .into_iter() + .collect(); let contract_proof_nodes = NodeHashToNodeMappings(nodes); diff --git a/crates/rpc/src/pathfinder/methods/get_proof.rs b/crates/rpc/src/pathfinder/methods/get_proof.rs index b948192350..5924614974 100644 --- a/crates/rpc/src/pathfinder/methods/get_proof.rs +++ b/crates/rpc/src/pathfinder/methods/get_proof.rs @@ -505,8 +505,8 @@ mod tests { &pathfinder_storage::TrieUpdate { nodes_added: vec![(Felt::from_u64(0), pathfinder_storage::Node::LeafBinary)], nodes_removed: (0..100) - .map(|value| TrieStorageIndex::new(value as u64)) - .collect(), + .map(|value| TrieStorageIndex::new(value as u64)) + .collect(), root_commitment: Felt::ZERO, }, BlockNumber::GENESIS + 3, diff --git a/crates/storage/src/connection/trie.rs b/crates/storage/src/connection/trie.rs index fd896187c0..3ebd76cf93 100644 --- a/crates/storage/src/connection/trie.rs +++ b/crates/storage/src/connection/trie.rs @@ -395,8 +395,14 @@ impl Transaction<'_> { .context("Creating statement to insert removal marker")?; stmt.execute(params![ &block_number, - &bincode::encode_to_vec(removed.into_iter().map(|trie_storaage_index|trie_storaage_index.get()).collect::>(), bincode::config::standard()) - .context("Serializing indices")? + &bincode::encode_to_vec( + removed + .into_iter() + .map(|trie_storaage_index| trie_storaage_index.get()) + .collect::>(), + bincode::config::standard() + ) + .context("Serializing indices")? ]) .context("Inserting removal marker")?; } @@ -562,15 +568,18 @@ impl Transaction<'_> { metrics::increment_counter!(METRIC_TRIE_NODES_ADDED, "table" => table); } - Ok(RootIndexUpdate::Updated( - TrieStorageIndex::new(*(indices - .get(&(update.nodes_added.len() - 1))) - .expect("Root index must exist as we just inserted it")), - )) + Ok(RootIndexUpdate::Updated(TrieStorageIndex::new( + *(indices.get(&(update.nodes_added.len() - 1))) + .expect("Root index must exist as we just inserted it"), + ))) } /// Returns the node with the given index. - fn trie_node(&self, index: TrieStorageIndex, table: &'static str) -> anyhow::Result> { + fn trie_node( + &self, + index: TrieStorageIndex, + table: &'static str, + ) -> anyhow::Result> { // We rely on sqlite caching the statement here. Storing the statement would be // nice, however that leads to &mut requirements or interior mutable // work-arounds. @@ -592,7 +601,11 @@ impl Transaction<'_> { } /// Returns the hash of the node with the given index. - fn trie_node_hash(&self, index: TrieStorageIndex, table: &'static str) -> anyhow::Result> { + fn trie_node_hash( + &self, + index: TrieStorageIndex, + table: &'static str, + ) -> anyhow::Result> { // We rely on sqlite caching the statement here. Storing the statement would be // nice, however that leads to &mut requirements or interior mutable // work-arounds. @@ -660,10 +673,18 @@ pub enum NodeRef { #[derive(Clone, Debug, PartialEq)] pub enum StoredNode { - Binary { left: TrieStorageIndex, right: TrieStorageIndex }, - Edge { child: TrieStorageIndex, path: BitVec }, + Binary { + left: TrieStorageIndex, + right: TrieStorageIndex, + }, + Edge { + child: TrieStorageIndex, + path: BitVec, + }, LeafBinary, - LeafEdge { path: BitVec }, + LeafEdge { + path: BitVec, + }, } #[derive(Clone, Debug, bincode::Encode, bincode::BorrowDecode)] @@ -719,14 +740,20 @@ impl StoredNode { let helper = bincode::borrow_decode_from_slice(data, Self::CODEC_CFG)?; let node = match helper.0 { - StoredSerde::Binary { left, right } => Self::Binary { left:TrieStorageIndex::new(left), right:TrieStorageIndex::new(right) }, + StoredSerde::Binary { left, right } => Self::Binary { + left: TrieStorageIndex::new(left), + right: TrieStorageIndex::new(right), + }, StoredSerde::Edge { child, mut path } => { let path_length = path.pop().ok_or(bincode::error::DecodeError::Other( "Edge node's path length is missing", ))?; let mut path = bitvec::vec::BitVec::from_vec(path); path.resize(path_length as usize, false); - Self::Edge { child:TrieStorageIndex::new(child), path } + Self::Edge { + child: TrieStorageIndex::new(child), + path, + } } StoredSerde::LeafBinary => Self::LeafBinary, StoredSerde::LeafEdge { mut path } => { @@ -761,7 +788,10 @@ impl Node { .context("Right child index missing")?, }; - StoredNode::Binary { left:TrieStorageIndex::new(left), right:TrieStorageIndex::new(right) } + StoredNode::Binary { + left: TrieStorageIndex::new(left), + right: TrieStorageIndex::new(right), + } } Node::Edge { child, path } => { let child = match child { @@ -801,13 +831,19 @@ mod tests { let result = tx.class_root_index(BlockNumber::GENESIS).unwrap(); assert_eq!(result, None); - tx.insert_class_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(TrieStorageIndex::new(123))) - .unwrap(); + tx.insert_class_root( + BlockNumber::GENESIS, + RootIndexUpdate::Updated(TrieStorageIndex::new(123)), + ) + .unwrap(); let result = tx.class_root_index(BlockNumber::GENESIS).unwrap(); assert_eq!(result, Some(TrieStorageIndex::new(123))); - tx.insert_class_root(BlockNumber::GENESIS + 1, RootIndexUpdate::Updated(TrieStorageIndex::new(456))) - .unwrap(); + tx.insert_class_root( + BlockNumber::GENESIS + 1, + RootIndexUpdate::Updated(TrieStorageIndex::new(456)), + ) + .unwrap(); let result = tx.class_root_index(BlockNumber::GENESIS).unwrap(); assert_eq!(result, Some(TrieStorageIndex::new(123))); let result = tx.class_root_index(BlockNumber::GENESIS + 1).unwrap(); @@ -815,8 +851,11 @@ mod tests { let result = tx.class_root_index(BlockNumber::GENESIS + 2).unwrap(); assert_eq!(result, Some(TrieStorageIndex::new(456))); - tx.insert_class_root(BlockNumber::GENESIS + 10, RootIndexUpdate::Updated(TrieStorageIndex::new(789))) - .unwrap(); + tx.insert_class_root( + BlockNumber::GENESIS + 10, + RootIndexUpdate::Updated(TrieStorageIndex::new(789)), + ) + .unwrap(); let result = tx.class_root_index(BlockNumber::GENESIS + 9).unwrap(); assert_eq!(result, Some(TrieStorageIndex::new(456))); let result = tx.class_root_index(BlockNumber::GENESIS + 10).unwrap(); @@ -843,13 +882,19 @@ mod tests { let result = tx.storage_root_index(BlockNumber::GENESIS).unwrap(); assert_eq!(result, None); - tx.insert_storage_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(TrieStorageIndex::new(123))) - .unwrap(); + tx.insert_storage_root( + BlockNumber::GENESIS, + RootIndexUpdate::Updated(TrieStorageIndex::new(123)), + ) + .unwrap(); let result = tx.storage_root_index(BlockNumber::GENESIS).unwrap(); assert_eq!(result, Some(TrieStorageIndex::new(123))); - tx.insert_storage_root(BlockNumber::GENESIS + 1, RootIndexUpdate::Updated(TrieStorageIndex::new(456))) - .unwrap(); + tx.insert_storage_root( + BlockNumber::GENESIS + 1, + RootIndexUpdate::Updated(TrieStorageIndex::new(456)), + ) + .unwrap(); let result = tx.storage_root_index(BlockNumber::GENESIS).unwrap(); assert_eq!(result, Some(TrieStorageIndex::new(123))); let result = tx.storage_root_index(BlockNumber::GENESIS + 1).unwrap(); @@ -857,8 +902,11 @@ mod tests { let result = tx.storage_root_index(BlockNumber::GENESIS + 2).unwrap(); assert_eq!(result, Some(TrieStorageIndex::new(456))); - tx.insert_storage_root(BlockNumber::GENESIS + 10, RootIndexUpdate::Updated(TrieStorageIndex::new(789))) - .unwrap(); + tx.insert_storage_root( + BlockNumber::GENESIS + 10, + RootIndexUpdate::Updated(TrieStorageIndex::new(789)), + ) + .unwrap(); let result = tx.storage_root_index(BlockNumber::GENESIS + 9).unwrap(); assert_eq!(result, Some(TrieStorageIndex::new(456))); let result = tx.storage_root_index(BlockNumber::GENESIS + 10).unwrap(); @@ -931,8 +979,12 @@ mod tests { tx.insert_contract_root(BlockNumber::GENESIS + 1, c1, idx1_update) .unwrap(); - tx.insert_contract_root(BlockNumber::GENESIS + 1, c2, RootIndexUpdate::Updated(TrieStorageIndex::new(888))) - .unwrap(); + tx.insert_contract_root( + BlockNumber::GENESIS + 1, + c2, + RootIndexUpdate::Updated(TrieStorageIndex::new(888)), + ) + .unwrap(); let result1 = tx.contract_root_index(BlockNumber::GENESIS, c1).unwrap(); let result2 = tx.contract_root_index(BlockNumber::GENESIS, c2).unwrap(); let hash1 = tx.contract_root(BlockNumber::GENESIS, c1).unwrap(); @@ -975,8 +1027,12 @@ mod tests { tx.insert_contract_root(BlockNumber::GENESIS + 10, c1, idx2_update) .unwrap(); - tx.insert_contract_root(BlockNumber::GENESIS + 11, c2, RootIndexUpdate::Updated(TrieStorageIndex::new(999))) - .unwrap(); + tx.insert_contract_root( + BlockNumber::GENESIS + 11, + c2, + RootIndexUpdate::Updated(TrieStorageIndex::new(999)), + ) + .unwrap(); let result1 = tx .contract_root_index(BlockNumber::GENESIS + 9, c1) .unwrap(); @@ -1242,7 +1298,7 @@ mod tests { (felt!("4"), Node::LeafBinary), (felt!("5"), Node::LeafBinary), ], - nodes_removed: vec![TrieStorageIndex::new( 1)], + nodes_removed: vec![TrieStorageIndex::new(1)], root_commitment: Felt::ZERO, }, BlockNumber::GENESIS + 1, @@ -1409,7 +1465,11 @@ mod tests { (felt!("4"), Node::LeafBinary), (felt!("5"), Node::LeafBinary), ], - nodes_removed: vec![TrieStorageIndex::new(1), TrieStorageIndex::new(2), TrieStorageIndex::new(3)], + nodes_removed: vec![ + TrieStorageIndex::new(1), + TrieStorageIndex::new(2), + TrieStorageIndex::new(3), + ], root_commitment: Felt::ZERO, }, BlockNumber::GENESIS + 1, @@ -1471,8 +1531,10 @@ mod tests { BlockNumber::GENESIS, ) .unwrap(); - assert_eq!(root_update, RootIndexUpdate::Updated(TrieStorageIndex::new( - TrieStorageIndex::new(1).get()))); + assert_eq!( + root_update, + RootIndexUpdate::Updated(TrieStorageIndex::new(TrieStorageIndex::new(1).get())) + ); } #[test] @@ -1485,13 +1547,22 @@ mod tests { .unwrap(); let tx = db.transaction().unwrap(); - tx.insert_class_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(TrieStorageIndex::new(1))) - .unwrap(); - tx.insert_class_root(BlockNumber::new_or_panic(1), RootIndexUpdate::Updated(TrieStorageIndex::new(2))) - .unwrap(); + tx.insert_class_root( + BlockNumber::GENESIS, + RootIndexUpdate::Updated(TrieStorageIndex::new(1)), + ) + .unwrap(); + tx.insert_class_root( + BlockNumber::new_or_panic(1), + RootIndexUpdate::Updated(TrieStorageIndex::new(2)), + ) + .unwrap(); // no root inserted for block 2 - tx.insert_class_root(BlockNumber::new_or_panic(3), RootIndexUpdate::Updated(TrieStorageIndex::new(3))) - .unwrap(); + tx.insert_class_root( + BlockNumber::new_or_panic(3), + RootIndexUpdate::Updated(TrieStorageIndex::new(3)), + ) + .unwrap(); assert!(!tx.class_root_exists(BlockNumber::GENESIS).unwrap()); // root at block 1 cannot be deleted because it is still required for @@ -1510,10 +1581,16 @@ mod tests { .unwrap(); let tx = db.transaction().unwrap(); - tx.insert_class_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(TrieStorageIndex::new(1))) - .unwrap(); - tx.insert_class_root(BlockNumber::new_or_panic(1), RootIndexUpdate::Updated(TrieStorageIndex::new(2))) - .unwrap(); + tx.insert_class_root( + BlockNumber::GENESIS, + RootIndexUpdate::Updated(TrieStorageIndex::new(1)), + ) + .unwrap(); + tx.insert_class_root( + BlockNumber::new_or_panic(1), + RootIndexUpdate::Updated(TrieStorageIndex::new(2)), + ) + .unwrap(); assert!(!tx.class_root_exists(BlockNumber::GENESIS).unwrap()); assert!(tx.class_root_exists(BlockNumber::new_or_panic(1)).unwrap()); @@ -1605,13 +1682,22 @@ mod tests { .unwrap(); let tx = db.transaction().unwrap(); - tx.insert_storage_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(TrieStorageIndex::new(1))) - .unwrap(); - tx.insert_storage_root(BlockNumber::new_or_panic(1), RootIndexUpdate::Updated(TrieStorageIndex::new(2))) - .unwrap(); + tx.insert_storage_root( + BlockNumber::GENESIS, + RootIndexUpdate::Updated(TrieStorageIndex::new(1)), + ) + .unwrap(); + tx.insert_storage_root( + BlockNumber::new_or_panic(1), + RootIndexUpdate::Updated(TrieStorageIndex::new(2)), + ) + .unwrap(); // no new root index for block 2 - tx.insert_storage_root(BlockNumber::new_or_panic(3), RootIndexUpdate::Updated(TrieStorageIndex::new(3))) - .unwrap(); + tx.insert_storage_root( + BlockNumber::new_or_panic(3), + RootIndexUpdate::Updated(TrieStorageIndex::new(3)), + ) + .unwrap(); assert!(!tx.storage_root_exists(BlockNumber::GENESIS).unwrap()); assert!(tx @@ -1632,10 +1718,16 @@ mod tests { .unwrap(); let tx = db.transaction().unwrap(); - tx.insert_storage_root(BlockNumber::GENESIS, RootIndexUpdate::Updated(TrieStorageIndex::new(1))) - .unwrap(); - tx.insert_storage_root(BlockNumber::new_or_panic(1), RootIndexUpdate::Updated(TrieStorageIndex::new(2))) - .unwrap(); + tx.insert_storage_root( + BlockNumber::GENESIS, + RootIndexUpdate::Updated(TrieStorageIndex::new(1)), + ) + .unwrap(); + tx.insert_storage_root( + BlockNumber::new_or_panic(1), + RootIndexUpdate::Updated(TrieStorageIndex::new(2)), + ) + .unwrap(); assert!(!tx.storage_root_exists(BlockNumber::GENESIS).unwrap()); assert!(tx @@ -1654,8 +1746,12 @@ mod tests { let tx = db.transaction().unwrap(); let contract = contract_address!("0xdeadbeef"); - tx.insert_contract_root(BlockNumber::GENESIS, contract, RootIndexUpdate::Updated(TrieStorageIndex::new(1))) - .unwrap(); + tx.insert_contract_root( + BlockNumber::GENESIS, + contract, + RootIndexUpdate::Updated(TrieStorageIndex::new(1)), + ) + .unwrap(); tx.insert_contract_root( BlockNumber::new_or_panic(1), contract, @@ -1698,8 +1794,12 @@ mod tests { let tx = db.transaction().unwrap(); let contract = contract_address!("0xdeadbeef"); - tx.insert_contract_root(BlockNumber::GENESIS, contract, RootIndexUpdate::Updated(TrieStorageIndex::new(1))) - .unwrap(); + tx.insert_contract_root( + BlockNumber::GENESIS, + contract, + RootIndexUpdate::Updated(TrieStorageIndex::new(1)), + ) + .unwrap(); tx.insert_contract_root( BlockNumber::new_or_panic(1), contract, From d818c5ac9e022ad33abadf033acbaacc76eeecac Mon Sep 17 00:00:00 2001 From: varun-doshi Date: Fri, 13 Dec 2024 21:33:58 +0530 Subject: [PATCH 8/8] updated to pass tests --- crates/storage/src/connection/trie.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/storage/src/connection/trie.rs b/crates/storage/src/connection/trie.rs index 3ebd76cf93..ca4fc5bffe 100644 --- a/crates/storage/src/connection/trie.rs +++ b/crates/storage/src/connection/trie.rs @@ -104,13 +104,13 @@ impl Transaction<'_> { ) -> anyhow::Result<()> { let new_root_index = match update { RootIndexUpdate::Unchanged => return Ok(()), - RootIndexUpdate::Updated(idx) => Some(idx), + RootIndexUpdate::Updated(idx) => Some(idx.get()), RootIndexUpdate::TrieEmpty => None, }; self.inner().execute( "INSERT OR REPLACE INTO class_roots (block_number, root_index) VALUES(?, ?)", - params![&block_number, &new_root_index.unwrap().get()], + params![&block_number, &new_root_index], )?; if let TriePruneMode::Prune { num_blocks_kept } = self.trie_prune_mode { @@ -216,12 +216,12 @@ impl Transaction<'_> { ) -> anyhow::Result<()> { let new_root_index = match update { RootIndexUpdate::Unchanged => return Ok(()), - RootIndexUpdate::Updated(idx) => Some(idx), + RootIndexUpdate::Updated(idx) => Some(idx.get()), RootIndexUpdate::TrieEmpty => None, }; self.inner().execute( "INSERT OR REPLACE INTO storage_roots (block_number, root_index) VALUES(?, ?)", - params![&block_number, &new_root_index.unwrap().get()], + params![&block_number, &new_root_index], )?; if let TriePruneMode::Prune { num_blocks_kept } = self.trie_prune_mode { @@ -263,13 +263,13 @@ impl Transaction<'_> { ) -> anyhow::Result<()> { let new_root_index = match update { RootIndexUpdate::Unchanged => return Ok(()), - RootIndexUpdate::Updated(idx) => Some(idx), + RootIndexUpdate::Updated(idx) => Some(idx.get()), RootIndexUpdate::TrieEmpty => None, }; self.inner().execute( "INSERT OR REPLACE INTO contract_roots (block_number, contract_address, root_index) \ VALUES(?, ?, ?)", - params![&block_number, &contract, &new_root_index.unwrap().get()], + params![&block_number, &contract, &new_root_index], )?; if let TriePruneMode::Prune { num_blocks_kept } = self.trie_prune_mode { @@ -397,7 +397,7 @@ impl Transaction<'_> { &block_number, &bincode::encode_to_vec( removed - .into_iter() + .iter() .map(|trie_storaage_index| trie_storaage_index.get()) .collect::>(), bincode::config::standard()