-
Notifications
You must be signed in to change notification settings - Fork 51
/
state.rs
348 lines (302 loc) · 10.4 KB
/
state.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
use cairo_rs::vm::runners::cairo_runner::ExecutionResources;
use felt::Felt;
use num_traits::Zero;
use std::{
borrow::Borrow,
cell::RefCell,
collections::{HashMap, HashSet},
hash,
ops::Deref,
rc::Rc,
thread::current,
};
use crate::{
business_logic::state::{
cached_state::CachedState,
state_api::{State, StateReader},
state_api_objects::BlockInfo,
state_cache,
},
core::errors::state_errors::StateError,
definitions::general_config::{self, StarknetGeneralConfig},
services::api::contract_class::ContractClass,
starknet_storage::storage::{self, FactFetchingContext, Storage},
starkware_utils::starkware_errors::StarkwareError,
utils::{
get_keys, subtract_mappings, to_cache_state_storage_mapping, to_state_diff_storage_mapping,
Address,
},
};
use super::contract_state::ContractState;
#[derive(Debug, Default)]
pub struct ExecutionResourcesManager {
pub(crate) syscall_counter: HashMap<String, u64>,
pub(crate) cairo_usage: ExecutionResources,
}
impl ExecutionResourcesManager {
pub fn new(syscalls: Vec<String>, cairo_usage: ExecutionResources) -> Self {
let mut syscall_counter = HashMap::new();
for syscall in syscalls {
syscall_counter.insert(syscall, 0);
}
ExecutionResourcesManager {
syscall_counter,
cairo_usage,
}
}
pub fn increment_syscall_counter(&mut self, syscall_name: &str, amount: u64) -> Option<()> {
self.syscall_counter
.get_mut(syscall_name)
.map(|val| *val += amount)
}
pub fn get_syscall_counter(&self, syscall_name: &str) -> Option<u64> {
self.syscall_counter
.get(syscall_name)
.map(ToOwned::to_owned)
}
}
// TODO: this functions should be in cairo-rs
// Returns a copy of the execution resources where all the builtins with a usage counter
// of 0 are omitted.
pub fn filter_unused_builtins(resources: ExecutionResources) -> ExecutionResources {
ExecutionResources {
n_steps: resources.n_steps,
n_memory_holes: resources.n_memory_holes,
builtin_instance_counter: resources
.builtin_instance_counter
.into_iter()
.filter(|builtin| !builtin.1.is_zero())
.collect(),
}
}
pub fn calculate_additional_resources(
current_resources: ExecutionResources,
additional_resources: ExecutionResources,
) -> ExecutionResources {
let mut builtin_instance_counter = current_resources.builtin_instance_counter.clone();
let n_steps = current_resources.n_steps + additional_resources.n_steps;
let n_memory_holes = current_resources.n_memory_holes + additional_resources.n_memory_holes;
for (k, v) in additional_resources.builtin_instance_counter {
if builtin_instance_counter.contains_key(&k) {
let val = builtin_instance_counter.get(&k).unwrap_or(&0).to_owned();
builtin_instance_counter.insert(k, val + v);
} else {
builtin_instance_counter.remove(&k);
}
}
ExecutionResources {
n_steps,
n_memory_holes,
builtin_instance_counter,
}
}
// ----------------------
// SHARED STATE
// ----------------------
#[derive(Debug, Clone)]
pub(crate) struct CarriedState<T>
where
T: StateReader + Clone,
{
parent_state: Option<Rc<RefCell<CarriedState<T>>>>,
state: CachedState<T>,
}
impl<T: StateReader + Clone> CarriedState<T> {
pub fn create_from_parent_state(parent_state: CarriedState<T>) -> Self {
let cached_state = parent_state.state.clone();
let new_state = Some(Rc::new(RefCell::new(parent_state)));
CarriedState {
parent_state: new_state,
state: cached_state,
}
}
pub fn create_child_state_for_querying(&self) -> Result<Self, StateError> {
match &self.parent_state {
Some(parent_state) => Ok(CarriedState::create_from_parent_state(
parent_state.as_ref().borrow().clone(),
)),
None => Err(StateError::ParentCarriedStateIsNone),
}
}
fn apply(&mut self) -> Result<(), StateError> {
match &self.parent_state {
Some(parent_state) => {
self.state.apply(&mut parent_state.borrow_mut().state);
Ok(())
}
None => Err(StateError::ParentCarriedStateIsNone),
}
}
pub fn get_block_info(&self) -> &BlockInfo {
&self.state.block_info
}
}
// ----------------------
// SHARED STATE
// ----------------------
pub(crate) struct SharedState {
contract_states: HashMap<Felt, ContractState>,
block_info: BlockInfo,
}
impl SharedState {
pub fn empty<S>(ffc: FactFetchingContext<S>, general_config: StarknetGeneralConfig) -> Self
where
S: Storage,
{
todo!()
}
pub fn to_carried_state<S, R>(&self, ffc: FactFetchingContext<S>) -> CarriedState<R>
where
S: Storage,
R: StateReader + Clone,
{
// let state_reader = "Patricia_state_reader"; // TODO: change it to patricia reader once it is available
// let state = CachedState::new(self.block_info, state_reader, None);
// CarriedState {
// parent_state: None,
// state,
// }
todo!()
}
pub fn apply_state_updates<S, R>(
&self,
ffc: FactFetchingContext<S>,
previous_carried_state: CarriedState<R>,
current_carried_state: CarriedState<R>,
) -> Result<Self, StateError>
where
S: Storage,
R: StateReader + Clone,
{
let state_cache = current_carried_state.state.cache;
Ok(self.apply_updates(
ffc,
state_cache.class_hash_writes,
state_cache.nonce_writes,
to_state_diff_storage_mapping(state_cache.storage_writes)?,
current_carried_state.state.block_info,
))
}
pub fn apply_updates<S>(
&self,
ffc: FactFetchingContext<S>,
address_to_class_hash: HashMap<Address, [u8; 32]>,
address_to_nonce: HashMap<Address, Felt>,
storage_updates: HashMap<Felt, HashMap<[u8; 32], Address>>,
block_info: BlockInfo,
) -> Self
where
S: Storage,
{
let class_addresses: HashSet<Address> = address_to_class_hash.into_keys().collect();
let nonce_addresses: HashSet<Address> = address_to_nonce.into_keys().collect();
let storage_addresses: HashSet<Address> =
storage_updates.into_keys().map(Address).collect();
let mut accesed_addresses: HashSet<Address> = HashSet::new();
accesed_addresses.extend(class_addresses);
accesed_addresses.extend(nonce_addresses);
accesed_addresses.extend(storage_addresses);
// TODO:
// let current_contract_states = self.contract_states.get_leaves(ffc, accesed_addresses)
todo!()
}
}
pub(crate) struct StateDiff {
address_to_class_hash: HashMap<Address, [u8; 32]>,
address_to_nonce: HashMap<Address, Felt>,
storage_updates: HashMap<Felt, HashMap<[u8; 32], Address>>,
block_info: BlockInfo,
}
impl StateDiff {
pub fn empty(block_info: BlockInfo) -> Self {
StateDiff {
address_to_class_hash: HashMap::new(),
address_to_nonce: HashMap::new(),
storage_updates: HashMap::new(),
block_info,
}
}
pub fn from_cached_state<T>(cached_state: CachedState<T>) -> Result<Self, StateError>
where
T: StateReader + Clone,
{
let state_cache = cached_state.cache;
let substracted_maps = subtract_mappings(
state_cache.storage_writes,
state_cache.storage_initial_values,
);
let storage_updates = to_state_diff_storage_mapping(substracted_maps)?;
let address_to_nonce =
subtract_mappings(state_cache.nonce_writes, state_cache.nonce_initial_values);
let address_to_class_hash = subtract_mappings(
state_cache.class_hash_writes,
state_cache.class_hash_initial_values,
);
let block_info = cached_state.block_info;
Ok(StateDiff {
address_to_class_hash,
address_to_nonce,
storage_updates,
block_info,
})
}
pub fn to_cached_state<T>(&self, state_reader: T) -> CachedState<T>
where
T: StateReader + Clone,
{
let mut cache_state = CachedState::new(self.block_info.clone(), state_reader, None);
let cache_storage_mapping = to_cache_state_storage_mapping(self.storage_updates.clone());
cache_state.cache.set_initial_values(
&self.address_to_class_hash,
&self.address_to_nonce,
&cache_storage_mapping,
);
cache_state
}
pub fn squash(&mut self, other: StateDiff) -> Result<Self, StarkwareError> {
self.address_to_class_hash
.extend(other.address_to_class_hash);
let address_to_class_hash = self.address_to_class_hash.clone();
self.address_to_nonce.extend(other.address_to_nonce);
let address_to_nonce = self.address_to_nonce.clone();
let mut storage_updates = HashMap::new();
let addresses: Vec<Felt> =
get_keys(self.storage_updates.clone(), other.storage_updates.clone());
for address in addresses {
let default: HashMap<[u8; 32], Address> = HashMap::new();
let mut map_a = self
.storage_updates
.get(&address)
.unwrap_or(&default)
.to_owned();
let map_b = other
.storage_updates
.get(&address)
.unwrap_or(&default)
.to_owned();
map_a.extend(map_b);
storage_updates.insert(address, map_a.clone());
}
self.block_info
.validate_legal_progress(other.block_info.clone())?;
Ok(StateDiff {
address_to_class_hash,
address_to_nonce,
storage_updates,
block_info: other.block_info,
})
}
pub fn commit<T: Storage>(
&self,
ffc: FactFetchingContext<T>,
previos_state: SharedState,
) -> SharedState {
previos_state.apply_updates(
ffc,
self.address_to_class_hash.clone(),
self.address_to_nonce.clone(),
self.storage_updates.clone(),
self.block_info.clone(),
)
}
}