Skip to content

Commit 0a489d1

Browse files
committed
starknet_committer,starknet_patricia,starknet_patricia_storage: add context to prefix and serde
1 parent cfe3560 commit 0a489d1

File tree

20 files changed

+184
-96
lines changed

20 files changed

+184
-96
lines changed

crates/starknet_committer/src/db/external_test_utils.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ use starknet_patricia::patricia_merkle_tree::updated_skeleton_tree::tree::{
1515
UpdatedSkeletonTree,
1616
UpdatedSkeletonTreeImpl,
1717
};
18+
use starknet_patricia_storage::db_object::HasStaticPrefix;
1819
use starknet_patricia_storage::map_storage::MapStorage;
1920

2021
use crate::db::facts_db::create_facts_tree::create_original_skeleton_tree;
@@ -27,7 +28,7 @@ pub async fn tree_computation_flow<L, TH>(
2728
) -> FilledTreeImpl<L>
2829
where
2930
TH: TreeHashFunction<L> + 'static,
30-
L: Leaf + 'static,
31+
L: Leaf + HasStaticPrefix<KeyContext = ()> + 'static,
3132
{
3233
let mut sorted_leaf_indices: Vec<NodeIndex> = leaf_modifications.keys().copied().collect();
3334
let sorted_leaf_indices = SortedLeafIndices::new(&mut sorted_leaf_indices);
@@ -37,6 +38,7 @@ where
3738
sorted_leaf_indices,
3839
&config,
3940
&leaf_modifications,
41+
&(),
4042
)
4143
.await
4244
.expect("Failed to create the original skeleton tree");
@@ -63,7 +65,10 @@ where
6365
.expect("Failed to create the filled tree")
6466
}
6567

66-
pub async fn single_tree_flow_test<L: Leaf + 'static, TH: TreeHashFunction<L> + 'static>(
68+
pub async fn single_tree_flow_test<
69+
L: Leaf + HasStaticPrefix<KeyContext = ()> + 'static,
70+
TH: TreeHashFunction<L> + 'static,
71+
>(
6772
leaf_modifications: LeafModifications<L>,
6873
storage: &mut MapStorage,
6974
root_hash: HashOutput,
@@ -85,7 +90,7 @@ pub async fn single_tree_flow_test<L: Leaf + 'static, TH: TreeHashFunction<L> +
8590
let json_hash = &json!(hash_result.0.to_hex_string());
8691
result_map.insert("root_hash", json_hash);
8792
// Serlialize the storage modifications.
88-
let json_storage = &json!(filled_tree.serialize());
93+
let json_storage = &json!(filled_tree.serialize(&()));
8994
result_map.insert("storage_changes", json_storage);
9095
serde_json::to_string(&result_map).expect("serialization failed")
9196
}

crates/starknet_committer/src/db/facts_db/create_facts_tree.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ use starknet_patricia::patricia_merkle_tree::original_skeleton_tree::tree::{
2020
};
2121
use starknet_patricia::patricia_merkle_tree::traversal::SubTreeTrait;
2222
use starknet_patricia::patricia_merkle_tree::types::{NodeIndex, SortedLeafIndices};
23+
use starknet_patricia_storage::db_object::HasStaticPrefix;
2324
use starknet_patricia_storage::storage_trait::Storage;
2425
use tracing::warn;
2526

@@ -48,13 +49,15 @@ async fn fetch_nodes<'a, L: Leaf>(
4849
leaf_modifications: &LeafModifications<L>,
4950
config: &impl OriginalSkeletonTreeConfig<L>,
5051
mut previous_leaves: Option<&mut HashMap<NodeIndex, L>>,
52+
key_context: &<L as HasStaticPrefix>::KeyContext,
5153
) -> OriginalSkeletonTreeResult<()> {
5254
let mut current_subtrees = subtrees;
5355
let mut next_subtrees = Vec::new();
5456
while !current_subtrees.is_empty() {
5557
let should_fetch_modified_leaves =
5658
config.compare_modified_leaves() || previous_leaves.is_some();
57-
let filled_roots = calculate_subtrees_roots::<L>(&current_subtrees, storage).await?;
59+
let filled_roots =
60+
calculate_subtrees_roots::<L>(&current_subtrees, storage, key_context).await?;
5861
for (filled_root, subtree) in filled_roots.into_iter().zip(current_subtrees.iter()) {
5962
match filled_root.data {
6063
// Binary node.
@@ -150,6 +153,7 @@ pub async fn create_original_skeleton_tree<'a, L: Leaf>(
150153
sorted_leaf_indices: SortedLeafIndices<'a>,
151154
config: &impl OriginalSkeletonTreeConfig<L>,
152155
leaf_modifications: &LeafModifications<L>,
156+
key_context: &<L as HasStaticPrefix>::KeyContext,
153157
) -> OriginalSkeletonTreeResult<OriginalSkeletonTreeImpl<'a>> {
154158
if sorted_leaf_indices.is_empty() {
155159
return Ok(OriginalSkeletonTreeImpl::create_unmodified(root_hash));
@@ -171,6 +175,7 @@ pub async fn create_original_skeleton_tree<'a, L: Leaf>(
171175
leaf_modifications,
172176
config,
173177
None,
178+
key_context,
174179
)
175180
.await?;
176181
Ok(skeleton_tree)
@@ -182,6 +187,7 @@ pub async fn create_original_skeleton_tree_and_get_previous_leaves<'a, L: Leaf>(
182187
sorted_leaf_indices: SortedLeafIndices<'a>,
183188
leaf_modifications: &LeafModifications<L>,
184189
config: &impl OriginalSkeletonTreeConfig<L>,
190+
key_context: &<L as HasStaticPrefix>::KeyContext,
185191
) -> OriginalSkeletonTreeResult<(OriginalSkeletonTreeImpl<'a>, HashMap<NodeIndex, L>)> {
186192
if sorted_leaf_indices.is_empty() {
187193
let unmodified = OriginalSkeletonTreeImpl::create_unmodified(root_hash);
@@ -203,6 +209,7 @@ pub async fn create_original_skeleton_tree_and_get_previous_leaves<'a, L: Leaf>(
203209
leaf_modifications,
204210
config,
205211
Some(&mut leaves),
212+
key_context,
206213
)
207214
.await?;
208215
Ok((skeleton_tree, leaves))
@@ -212,6 +219,7 @@ pub async fn get_leaves<'a, L: Leaf>(
212219
storage: &mut impl Storage,
213220
root_hash: HashOutput,
214221
sorted_leaf_indices: SortedLeafIndices<'a>,
222+
key_context: &<L as HasStaticPrefix>::KeyContext,
215223
) -> OriginalSkeletonTreeResult<HashMap<NodeIndex, L>> {
216224
let config = NoCompareOriginalSkeletonTrieConfig::default();
217225
let leaf_modifications = LeafModifications::new();
@@ -221,6 +229,7 @@ pub async fn get_leaves<'a, L: Leaf>(
221229
sorted_leaf_indices,
222230
&leaf_modifications,
223231
&config,
232+
key_context,
224233
)
225234
.await?;
226235
Ok(previous_leaves)

crates/starknet_committer/src/db/facts_db/create_facts_tree_test.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,7 @@ async fn test_create_tree(
217217
sorted_leaf_indices,
218218
&config,
219219
&leaf_modifications,
220+
&(),
220221
)
221222
.await
222223
.unwrap();
@@ -225,7 +226,7 @@ async fn test_create_tree(
225226

226227
pub(crate) fn create_mock_leaf_entry(val: u128) -> (DbKey, DbValue) {
227228
let leaf = MockLeaf(Felt::from(val));
228-
(leaf.get_db_key(&leaf.0.to_bytes_be()), leaf.serialize())
229+
(leaf.get_db_key(&(), &leaf.0.to_bytes_be()), leaf.serialize())
229230
}
230231

231232
fn create_mock_leaf_modifications(

crates/starknet_committer/src/db/facts_db/db.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ impl<S: Storage> FactsDb<S> {
5454
contracts_trie_sorted_indices,
5555
&HashMap::new(),
5656
&OriginalSkeletonContractsTrieConfig::new(),
57+
&(),
5758
)
5859
.await?)
5960
}
@@ -82,6 +83,7 @@ impl<S: Storage> FactsDb<S> {
8283
*sorted_leaf_indices,
8384
&config,
8485
updates,
86+
&(),
8587
)
8688
.await?;
8789
storage_tries.insert(*address, original_skeleton);
@@ -104,6 +106,7 @@ impl<S: Storage> FactsDb<S> {
104106
contracts_trie_sorted_indices,
105107
&config,
106108
actual_classes_updates,
109+
&(),
107110
)
108111
.await?)
109112
}

crates/starknet_committer/src/db/facts_db/traversal.rs

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::collections::HashMap;
22

33
use starknet_api::hash::HashOutput;
44
use starknet_patricia::patricia_merkle_tree::filled_tree::node::FilledNode;
5+
use starknet_patricia::patricia_merkle_tree::filled_tree::node_serde::NodeContext;
56
use starknet_patricia::patricia_merkle_tree::node_data::inner_node::{
67
NodeData,
78
Preimage,
@@ -10,6 +11,7 @@ use starknet_patricia::patricia_merkle_tree::node_data::inner_node::{
1011
use starknet_patricia::patricia_merkle_tree::node_data::leaf::Leaf;
1112
use starknet_patricia::patricia_merkle_tree::traversal::{SubTreeTrait, TraversalResult};
1213
use starknet_patricia::patricia_merkle_tree::types::{NodeIndex, SortedLeafIndices};
14+
use starknet_patricia_storage::db_object::{DBObject, HasStaticPrefix};
1315
use starknet_patricia_storage::errors::StorageError;
1416
use starknet_patricia_storage::storage_trait::{create_db_key, DbKey, Storage};
1517

@@ -23,19 +25,26 @@ pub mod traversal_test;
2325
pub async fn calculate_subtrees_roots<'a, L: Leaf>(
2426
subtrees: &[FactsSubTree<'a>],
2527
storage: &mut impl Storage,
28+
key_context: &<L as HasStaticPrefix>::KeyContext,
2629
) -> TraversalResult<Vec<FilledNode<L>>> {
2730
let mut subtrees_roots = vec![];
2831
let db_keys: Vec<DbKey> = subtrees
2932
.iter()
3033
.map(|subtree| {
31-
create_db_key(subtree.get_root_prefix::<L>().into(), &subtree.root_hash.0.to_bytes_be())
34+
create_db_key(
35+
subtree.get_root_prefix::<L>(key_context),
36+
&subtree.root_hash.0.to_bytes_be(),
37+
)
3238
})
3339
.collect();
3440

3541
let db_vals = storage.mget(&db_keys.iter().collect::<Vec<&DbKey>>()).await?;
3642
for ((subtree, optional_val), db_key) in subtrees.iter().zip(db_vals.iter()).zip(db_keys) {
3743
let Some(val) = optional_val else { Err(StorageError::MissingKey(db_key))? };
38-
subtrees_roots.push(FilledNode::deserialize(subtree.root_hash, val, subtree.is_leaf())?)
44+
subtrees_roots.push(FilledNode::deserialize(
45+
val,
46+
&NodeContext { is_leaf: subtree.is_leaf(), node_hash: subtree.root_hash },
47+
)?)
3948
}
4049
Ok(subtrees_roots)
4150
}
@@ -49,6 +58,7 @@ pub async fn fetch_patricia_paths<L: Leaf>(
4958
root_hash: HashOutput,
5059
sorted_leaf_indices: SortedLeafIndices<'_>,
5160
leaves: Option<&mut HashMap<NodeIndex, L>>,
61+
key_context: &<L as HasStaticPrefix>::KeyContext,
5262
) -> TraversalResult<PreimageMap> {
5363
let mut witnesses = PreimageMap::new();
5464

@@ -58,7 +68,14 @@ pub async fn fetch_patricia_paths<L: Leaf>(
5868

5969
let main_subtree = FactsSubTree { sorted_leaf_indices, root_index: NodeIndex::ROOT, root_hash };
6070

61-
fetch_patricia_paths_inner::<L>(storage, vec![main_subtree], &mut witnesses, leaves).await?;
71+
fetch_patricia_paths_inner::<L>(
72+
storage,
73+
vec![main_subtree],
74+
&mut witnesses,
75+
leaves,
76+
key_context,
77+
)
78+
.await?;
6279
Ok(witnesses)
6380
}
6481

@@ -74,11 +91,13 @@ pub(crate) async fn fetch_patricia_paths_inner<'a, L: Leaf>(
7491
subtrees: Vec<FactsSubTree<'a>>,
7592
witnesses: &mut PreimageMap,
7693
mut leaves: Option<&mut HashMap<NodeIndex, L>>,
94+
key_context: &<L as HasStaticPrefix>::KeyContext,
7795
) -> TraversalResult<()> {
7896
let mut current_subtrees = subtrees;
7997
let mut next_subtrees = Vec::new();
8098
while !current_subtrees.is_empty() {
81-
let filled_roots = calculate_subtrees_roots::<L>(&current_subtrees, storage).await?;
99+
let filled_roots =
100+
calculate_subtrees_roots::<L>(&current_subtrees, storage, key_context).await?;
82101
for (filled_root, subtree) in filled_roots.into_iter().zip(current_subtrees.iter()) {
83102
// Always insert root.
84103
// No need to insert an unmodified node (which is not the root), because its parent is

crates/starknet_committer/src/db/facts_db/traversal_test.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ use starknet_patricia::patricia_merkle_tree::node_data::inner_node::{
2525
Preimage,
2626
PreimageMap,
2727
};
28-
use starknet_patricia::patricia_merkle_tree::traversal::SubTreeTrait;
2928
use starknet_patricia::patricia_merkle_tree::types::{SortedLeafIndices, SubTreeHeight};
3029
use starknet_patricia_storage::map_storage::MapStorage;
3130
use starknet_patricia_storage::storage_trait::{DbHashMap, DbKey, DbValue};
@@ -87,6 +86,7 @@ async fn test_fetch_patricia_paths_inner_impl(
8786
vec![main_subtree],
8887
&mut nodes,
8988
Some(&mut fetched_leaves),
89+
&(),
9090
)
9191
.await
9292
.unwrap();

crates/starknet_committer/src/db/facts_db/types.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ use starknet_patricia::patricia_merkle_tree::filled_tree::node_serde::PatriciaPr
33
use starknet_patricia::patricia_merkle_tree::node_data::leaf::Leaf;
44
use starknet_patricia::patricia_merkle_tree::traversal::SubTreeTrait;
55
use starknet_patricia::patricia_merkle_tree::types::{NodeIndex, SortedLeafIndices};
6+
use starknet_patricia_storage::db_object::HasStaticPrefix;
7+
use starknet_patricia_storage::storage_trait::DbKeyPrefix;
68

79
#[derive(Debug, PartialEq)]
810
pub struct FactsSubTree<'a> {
@@ -29,14 +31,14 @@ impl<'a> SubTreeTrait<'a> for FactsSubTree<'a> {
2931
fn should_traverse_unmodified_children() -> bool {
3032
false
3133
}
32-
}
33-
34-
impl<'a> FactsSubTree<'a> {
35-
pub fn get_root_prefix<L: Leaf>(&self) -> PatriciaPrefix {
34+
fn get_root_prefix<L: Leaf>(
35+
&self,
36+
_key_context: &<L as HasStaticPrefix>::KeyContext,
37+
) -> DbKeyPrefix {
3638
if self.is_leaf() {
37-
PatriciaPrefix::Leaf(L::get_static_prefix())
39+
PatriciaPrefix::Leaf(L::get_static_prefix(_key_context)).into()
3840
} else {
39-
PatriciaPrefix::InnerNode
41+
PatriciaPrefix::InnerNode.into()
4042
}
4143
}
4244
}

crates/starknet_committer/src/forest/filled_forest.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -59,12 +59,11 @@ impl FilledForest {
5959
fn serialize_trees(&self) -> DbHashMap {
6060
self.storage_tries
6161
.values()
62-
.flat_map(|tree| tree.serialize().into_iter())
63-
.chain(self.contracts_trie.serialize())
64-
.chain(self.classes_trie.serialize())
62+
.flat_map(|tree| tree.serialize(&()).into_iter())
63+
.chain(self.contracts_trie.serialize(&()))
64+
.chain(self.classes_trie.serialize(&()))
6565
.collect()
6666
}
67-
6867
async fn write_hashmap_to_storage(
6968
&self,
7069
storage: &mut impl Storage,
@@ -164,8 +163,8 @@ impl FilledForest {
164163
contract_address_to_storage_skeleton.len(),
165164
contract_address_to_storage_updates.len()
166165
);
167-
// `contract_address_to_storage_updates` includes all modified contracts, even those with
168-
// unmodified storage, see StateDiff::actual_storage_updates().
166+
// `contract_address_to_storage_updates` includes all modified contracts, even those
167+
// with unmodified storage, see StateDiff::actual_storage_updates().
169168
for (contract_address, storage_updates) in contract_address_to_storage_updates {
170169
let node_index = contract_address_into_node_index(&contract_address);
171170
let original_contract_state = original_contracts_trie_leaves

crates/starknet_committer/src/forest/skeleton_forest_test.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,12 +50,12 @@ macro_rules! compare_skeleton_tree {
5050

5151
pub(crate) fn create_storage_leaf_entry(val: u128) -> (DbKey, DbValue) {
5252
let leaf = StarknetStorageValue(Felt::from(val));
53-
(leaf.get_db_key(&leaf.0.to_bytes_be()), leaf.serialize())
53+
(leaf.get_db_key(&(), &leaf.0.to_bytes_be()), leaf.serialize())
5454
}
5555

5656
pub(crate) fn create_compiled_class_leaf_entry(val: u128) -> (DbKey, DbValue) {
5757
let leaf = CompiledClassHash(Felt::from(val));
58-
(leaf.get_db_key(&leaf.0.to_bytes_be()), leaf.serialize())
58+
(leaf.get_db_key(&(), &leaf.0.to_bytes_be()), leaf.serialize())
5959
}
6060

6161
pub(crate) fn create_contract_state_leaf_entry(val: u128) -> (DbKey, DbValue) {
@@ -65,7 +65,7 @@ pub(crate) fn create_contract_state_leaf_entry(val: u128) -> (DbKey, DbValue) {
6565
storage_root_hash: HashOutput(felt),
6666
class_hash: ClassHash(felt),
6767
};
68-
(leaf.get_db_key(&felt.to_bytes_be()), leaf.serialize())
68+
(leaf.get_db_key(&(), &felt.to_bytes_be()), leaf.serialize())
6969
}
7070

7171
// This test uses addition hash for simplicity (i.e hash(a,b) = a + b).

crates/starknet_committer/src/patricia_merkle_tree/leaf/leaf_impl.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ pub struct ContractState {
2222
}
2323

2424
impl HasStaticPrefix for StarknetStorageValue {
25-
fn get_static_prefix() -> DbKeyPrefix {
25+
type KeyContext = ();
26+
fn get_static_prefix(_key_context: &Self::KeyContext) -> DbKeyPrefix {
2627
CommitterLeafPrefix::StorageLeaf.into()
2728
}
2829
}
@@ -41,7 +42,8 @@ impl Leaf for StarknetStorageValue {
4142
}
4243

4344
impl HasStaticPrefix for CompiledClassHash {
44-
fn get_static_prefix() -> DbKeyPrefix {
45+
type KeyContext = ();
46+
fn get_static_prefix(_key_context: &Self::KeyContext) -> DbKeyPrefix {
4547
CommitterLeafPrefix::CompiledClassLeaf.into()
4648
}
4749
}
@@ -60,7 +62,8 @@ impl Leaf for CompiledClassHash {
6062
}
6163

6264
impl HasStaticPrefix for ContractState {
63-
fn get_static_prefix() -> DbKeyPrefix {
65+
type KeyContext = ();
66+
fn get_static_prefix(_key_context: &Self::KeyContext) -> DbKeyPrefix {
6467
CommitterLeafPrefix::StateTreeLeaf.into()
6568
}
6669
}

0 commit comments

Comments
 (0)