forked from eqlabs/pathfinder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontract.rs
320 lines (269 loc) · 9.42 KB
/
contract.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
//! Contains the [StorageCommitmentTree] and [ContractsStorageTree] trees, which
//! combined store the total Starknet storage state.
//!
//! These are abstractions built-on the [Binary Merkle-Patricia
//! Tree](MerkleTree).
use std::ops::ControlFlow;
use anyhow::Context;
use bitvec::prelude::Msb0;
use bitvec::slice::BitSlice;
use pathfinder_common::hash::PedersenHash;
use pathfinder_common::{
BlockNumber,
ContractAddress,
ContractRoot,
ContractStateHash,
StorageAddress,
StorageCommitment,
StorageValue,
};
use pathfinder_crypto::Felt;
use pathfinder_storage::{Transaction, TrieUpdate};
use crate::merkle_node::InternalNode;
use crate::tree::{GetProofError, MerkleTree, TrieNodeWithHash, Visit};
/// A [Patricia Merkle tree](MerkleTree) used to calculate commitments to a
/// Starknet contract's storage.
///
/// It maps a contract's [storage addresses](StorageAddress) to their
/// [values](StorageValue).
///
/// Tree data is persisted by a sqlite table 'trie_contracts'.
pub struct ContractsStorageTree<'tx> {
tree: MerkleTree<PedersenHash, 251>,
storage: ContractStorage<'tx>,
}
impl<'tx> ContractsStorageTree<'tx> {
pub fn empty(tx: &'tx Transaction<'tx>, contract: ContractAddress) -> Self {
let storage = ContractStorage {
tx,
block: None,
contract,
};
let tree = MerkleTree::empty();
Self { tree, storage }
}
pub fn load(
tx: &'tx Transaction<'tx>,
contract: ContractAddress,
block: BlockNumber,
) -> anyhow::Result<Self> {
let root = tx
.contract_root_index(block, contract)
.context("Querying contract root index")?;
let Some(root) = root else {
return Ok(Self::empty(tx, contract));
};
let storage = ContractStorage {
tx,
block: Some(block),
contract,
};
let tree = MerkleTree::new(root);
Ok(Self { tree, storage })
}
pub fn with_verify_hashes(mut self, verify_hashes: bool) -> Self {
self.tree = self.tree.with_verify_hashes(verify_hashes);
self
}
/// Generates a proof for `key`. See [`MerkleTree::get_proof`].
pub fn get_proof(
tx: &'tx Transaction<'tx>,
contract: ContractAddress,
block: BlockNumber,
key: &BitSlice<u8, Msb0>,
root: u64,
) -> Result<Vec<TrieNodeWithHash>, GetProofError> {
let storage = ContractStorage {
tx,
block: Some(block),
contract,
};
MerkleTree::<PedersenHash, 251>::get_proof(root, &storage, key)
}
/// Generates proofs for the given list of `keys`. See
/// [`MerkleTree::get_proofs`]. Returns [(`TrieNode`,
/// `Felt`)](TrieNodeWithHash) pairs where the second element is the
/// node hash.
pub fn get_proofs(
tx: &'tx Transaction<'tx>,
contract: ContractAddress,
block: BlockNumber,
keys: &[StorageAddress],
root: u64,
) -> Result<Vec<Vec<TrieNodeWithHash>>, GetProofError> {
let storage = ContractStorage {
tx,
block: Some(block),
contract,
};
let keys = keys
.iter()
.map(|addr| addr.0.view_bits())
.collect::<Vec<_>>();
MerkleTree::<PedersenHash, 251>::get_proofs(root, &storage, &keys)
}
pub fn set(&mut self, address: StorageAddress, value: StorageValue) -> anyhow::Result<()> {
let key = address.view_bits().to_owned();
self.tree.set(&self.storage, key, value.0)
}
/// Commits the changes and calculates the new node hashes. Returns the new
/// commitment and any potentially newly created nodes.
pub fn commit(self) -> anyhow::Result<(ContractRoot, TrieUpdate)> {
let update = self.tree.commit(&self.storage)?;
let commitment = ContractRoot(update.root_commitment);
Ok((commitment, update))
}
/// See [`MerkleTree::dfs`]
pub fn dfs<B, F: FnMut(&InternalNode, &BitSlice<u8, Msb0>) -> ControlFlow<B, Visit>>(
&mut self,
f: &mut F,
) -> anyhow::Result<Option<B>> {
self.tree.dfs(&self.storage, f)
}
}
/// A [Patricia Merkle tree](MerkleTree) used to calculate commitments to all of
/// Starknet's storage.
///
/// It maps each contract's [address](ContractAddress) to it's [state
/// hash](ContractStateHash).
///
/// Tree data is persisted by a sqlite table 'trie_storage'.
pub struct StorageCommitmentTree<'tx> {
tree: MerkleTree<PedersenHash, 251>,
storage: StorageTrieStorage<'tx>,
}
impl<'tx> StorageCommitmentTree<'tx> {
pub fn empty(tx: &'tx Transaction<'tx>) -> Self {
let storage = StorageTrieStorage { tx, block: None };
let tree = MerkleTree::empty();
Self { tree, storage }
}
pub fn load(tx: &'tx Transaction<'tx>, block: BlockNumber) -> anyhow::Result<Self> {
let root = tx
.storage_root_index(block)
.context("Querying storage root index")?;
let Some(root) = root else {
return Ok(Self::empty(tx));
};
let storage = StorageTrieStorage {
tx,
block: Some(block),
};
let tree = MerkleTree::new(root);
Ok(Self { tree, storage })
}
pub fn with_verify_hashes(mut self, verify_hashes: bool) -> Self {
self.tree = self.tree.with_verify_hashes(verify_hashes);
self
}
pub fn set(
&mut self,
address: ContractAddress,
value: ContractStateHash,
) -> anyhow::Result<()> {
let key = address.view_bits().to_owned();
self.tree.set(&self.storage, key, value.0)
}
pub fn get(&self, address: &ContractAddress) -> anyhow::Result<Option<ContractStateHash>> {
let key = address.view_bits().to_owned();
let value = self.tree.get(&self.storage, key)?;
Ok(value.map(ContractStateHash))
}
/// Commits the changes and calculates the new node hashes. Returns the new
/// commitment and any potentially newly created nodes.
pub fn commit(self) -> anyhow::Result<(StorageCommitment, TrieUpdate)> {
let update = self.tree.commit(&self.storage)?;
let commitment = StorageCommitment(update.root_commitment);
Ok((commitment, update))
}
/// Generates a proof for the given `address`.
/// See [`MerkleTree::get_proof`].
pub fn get_proof(
tx: &'tx Transaction<'tx>,
block: BlockNumber,
address: &ContractAddress,
root: u64,
) -> Result<Vec<TrieNodeWithHash>, GetProofError> {
let storage = StorageTrieStorage {
tx,
block: Some(block),
};
MerkleTree::<PedersenHash, 251>::get_proof(root, &storage, address.view_bits())
}
/// Generates proofs for the given list of `addresses`. See
/// [`MerkleTree::get_proofs`]. Returns [(`TrieNode`,
/// `Felt`)](TrieNodeWithHash) pairs where the second element is the
/// node hash.
pub fn get_proofs(
tx: &'tx Transaction<'tx>,
block: BlockNumber,
addresses: &[ContractAddress],
root: u64,
) -> Result<Vec<Vec<TrieNodeWithHash>>, GetProofError> {
let storage = StorageTrieStorage {
tx,
block: Some(block),
};
let keys = addresses
.iter()
.map(|addr| addr.0.view_bits())
.collect::<Vec<_>>();
MerkleTree::<PedersenHash, 251>::get_proofs(root, &storage, &keys)
}
/// See [`MerkleTree::dfs`]
pub fn dfs<B, F: FnMut(&InternalNode, &BitSlice<u8, Msb0>) -> ControlFlow<B, Visit>>(
&mut self,
f: &mut F,
) -> anyhow::Result<Option<B>> {
self.tree.dfs(&self.storage, f)
}
}
struct ContractStorage<'tx> {
tx: &'tx Transaction<'tx>,
block: Option<BlockNumber>,
contract: ContractAddress,
}
impl crate::storage::Storage for ContractStorage<'_> {
fn get(&self, index: u64) -> anyhow::Result<Option<pathfinder_storage::StoredNode>> {
self.tx.contract_trie_node(index)
}
fn hash(&self, index: u64) -> anyhow::Result<Option<Felt>> {
self.tx.contract_trie_node_hash(index)
}
fn leaf(&self, path: &BitSlice<u8, Msb0>) -> anyhow::Result<Option<Felt>> {
assert!(path.len() == 251);
let Some(block) = self.block else {
return Ok(None);
};
let key =
StorageAddress(Felt::from_bits(path).context("Mapping leaf path to storage address")?);
let value = self
.tx
.storage_value(block.into(), self.contract, key)?
.map(|x| x.0);
Ok(value)
}
}
struct StorageTrieStorage<'tx> {
tx: &'tx Transaction<'tx>,
block: Option<BlockNumber>,
}
impl crate::storage::Storage for StorageTrieStorage<'_> {
fn get(&self, index: u64) -> anyhow::Result<Option<pathfinder_storage::StoredNode>> {
self.tx.storage_trie_node(index)
}
fn hash(&self, index: u64) -> anyhow::Result<Option<Felt>> {
self.tx.storage_trie_node_hash(index)
}
fn leaf(&self, path: &BitSlice<u8, Msb0>) -> anyhow::Result<Option<Felt>> {
assert!(path.len() == 251);
let Some(block) = self.block else {
return Ok(None);
};
let contract = ContractAddress(
Felt::from_bits(path).context("Mapping leaf path to contract address")?,
);
let value = self.tx.contract_state_hash(block, contract)?.map(|x| x.0);
Ok(value)
}
}