-
Notifications
You must be signed in to change notification settings - Fork 172
Expand file tree
/
Copy pathtraits.rs
More file actions
780 lines (686 loc) · 29.1 KB
/
traits.rs
File metadata and controls
780 lines (686 loc) · 29.1 KB
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
use std::convert::Infallible;
use std::fmt::Debug;
use std::num::TryFromIntError;
use sov_metrics::StateAccessMetric;
use sov_rollup_interface::common::{SlotNumber, VisibleSlotNumber};
use sov_state::pinned_cache::PinnedCache;
#[cfg(feature = "native")]
use sov_state::StorageProof;
use sov_state::{
namespaces, Accessory, CompileTimeNamespace, EventContainer, Kernel, Namespace,
ProvableCompileTimeNamespace, SlotKey, SlotValue, StateCodec, StateItemCodec, StateItemDecoder,
User,
};
use thiserror::Error;
#[cfg(feature = "expensive-observability")]
use tracing::{enabled, instrument, Level, Span};
use super::accessors::seal::UniversalStateAccessor;
use super::accessors::{BorshSerializedSize, TempCache};
use crate::capabilities::RollupHeight;
use crate::state::accessors::StateMetricsProvider;
#[cfg(any(feature = "test-utils", feature = "evm"))]
use crate::UnmeteredStateWrapper;
use crate::{Gas, GasMeter, GasMeteringError, GasSpec, RevertableTxState, Spec};
/// A type that can both read and write the normal "user-space" state of the rollup.
///
/// ```
/// fn delete_state_string<Accessor: sov_modules_api::StateAccessor>(mut value: sov_modules_api::StateValue<String>, state: &mut Accessor)
/// -> Result<(), <Accessor as sov_modules_api::StateWriter<sov_state::User>>::Error> {
/// if let Some(original) = value.get(state)? {
/// println!("original: {}", original);
/// }
/// value.delete(state)?;
/// Ok(())
/// }
///
///
/// ```
pub trait StateAccessor: StateReaderAndWriter<User> {
/// Converts this accessor into an [`UnmeteredStateWrapper`]. This method should only be used either in tests or in the `EVM` module.
#[cfg(any(feature = "test-utils", feature = "evm"))]
fn to_unmetered(&mut self) -> UnmeteredStateWrapper<'_, Self>
where
Self: Sized,
{
UnmeteredStateWrapper { inner: self }
}
}
/// Trait to access time through sov_chain_state.
pub trait TimeStateAccessor:
StateReader<User, Error: Into<anyhow::Error>>
+ StateWriter<User, Error = <Self as StateReader<User>>::Error>
+ StateReader<Kernel, Error = <Self as StateReader<User>>::Error>
+ VersionReader
{
}
/// Auto implement trait.
impl<T> TimeStateAccessor for T where
T: StateReader<User, Error: Into<anyhow::Error>>
+ StateWriter<User, Error = <Self as StateReader<User>>::Error>
+ StateReader<Kernel, Error = <Self as StateReader<User>>::Error>
+ VersionReader
{
}
/// A trait that represents a [`StateAccessor`] that never fails on state accesses. Accessing the state with structs that implement
/// this trait will return [`Infallible`].
///
/// ## Usage example
/// ```
/// use sov_modules_api::prelude::UnwrapInfallible;
///
/// fn delete_state_string<InfallibleAccessor: sov_modules_api::InfallibleStateAccessor>(mut value: sov_modules_api::StateValue<String>, state: &mut InfallibleAccessor)
/// -> () {
/// if let Some(original) = value.get(state).unwrap_infallible() {
/// println!("original: {}", original);
/// }
/// value.delete(state).unwrap_infallible();
/// }
/// ```
pub trait InfallibleStateAccessor:
StateReader<User, Error = Infallible> + StateWriter<User, Error = Infallible>
{
}
impl<T> StateAccessor for T where T: StateReaderAndWriter<User> {}
impl<T> InfallibleStateAccessor for T where
T: StateReader<User, Error = Infallible> + StateWriter<User, Error = Infallible>
{
}
/// Like [`InfallibleStateAccessor`], but for the [`Kernel`] access.
pub trait InfallibleKernelStateAccessor:
StateReader<Kernel, Error = Infallible> + StateWriter<Kernel, Error = Infallible>
{
}
impl<T> InfallibleKernelStateAccessor for T where
T: StateReader<Kernel, Error = Infallible> + StateWriter<Kernel, Error = Infallible>
{
}
pub trait PinnedCacheAccessor<S: Spec> {
/// Returns a mutable reference to the pinned cache backing this accessor, if any exists.
fn pinned_cache_mut(&mut self) -> Option<&mut PinnedCache>;
/// Returns a reference to the storage backing this accessor.
fn storage(&self) -> &S::Storage;
}
/// The state accessor used during transaction execution. It provides unrestricted
/// access to [`User`]-space state, as well as limited visibility into the `Kernel` state.
pub trait TxState<S: Spec>:
StateReader<User, Error: Into<anyhow::Error>>
+ StateReader<Kernel, Error = <Self as StateReader<User>>::Error>
+ StateWriter<User, Error = <Self as StateReader<User>>::Error>
+ StateWriter<Kernel, Error = <Self as StateReader<User>>::Error>
+ StateWriter<Accessory, Error = Infallible>
+ VersionReader
+ EventContainer
+ PerBlockCache
+ GasMeter<Spec = S>
+ Sized
+ StateMetricsProvider
+ PinnedCacheAccessor<S>
{
/// Converts this state accessor into a [`RevertableTxState`].
///
/// You *MUST* call .commit() to save the changes from the resulting accessor if you want them to be persisted
fn to_revertable(&mut self) -> RevertableTxState<'_, S, Self> {
RevertableTxState::new(self)
}
}
impl<S: Spec, T> TxState<S> for T where
T: StateReader<User, Error: Into<anyhow::Error>>
+ StateReader<Kernel, Error = <Self as StateReader<User>>::Error>
+ StateWriter<Kernel, Error = <Self as StateReader<User>>::Error>
+ StateWriter<User, Error = <Self as StateReader<User>>::Error>
+ StateWriter<Accessory, Error = Infallible>
+ VersionReader
+ EventContainer
+ PerBlockCache
+ GasMeter<Spec = S>
+ Sized
+ StateMetricsProvider
+ PinnedCacheAccessor<S>
{
}
/// A cache that persists items *without serializing them*. Items persist for at most the duration of the block.
///
/// Note that values may be evicted from the cache at any time based on memory pressure, even if the end of the block has not yet been reached.
pub trait PerBlockCache {
/// Gets a value from the cache. This API returns &T because mutating the type would invalidate the revert
/// guarantees provided by the SDK. Be extremely careful when using interior mutability for objects stored in the cache -
/// any changes made to the object may not revert on transaction failure, causing possible cache corruption.
fn get_cached<T: 'static + Send + Sync>(&self, key: Option<SlotKey>) -> Option<&T>;
/// Puts a value in the cache. Note that values are required to provide an esimate of their size via the
/// [`BorshSerializedSize`] trait.
fn put_cached<T: 'static + Send + Sync + BorshSerializedSize>(
&mut self,
key: Option<SlotKey>,
value: T,
);
/// Deletes a value from the cache.
fn delete_cached<T: 'static + Send + Sync>(&mut self, key: Option<SlotKey>);
/// Adds all writes from another cache to this one.
fn update_cache_with(&mut self, other: TempCache);
}
/// The state accessor used during genesis. It provides unrestricted
/// access to [`User`] and `Kernel` state, as well as limited visibility into [`Accessory`] state.
pub trait GenesisState<S: Spec>:
TxState<S> + PrivilegedKernelAccessor<Error = <Self as StateReader<User>>::Error>
{
}
/// The set of errors that can be raised during state accesses. For now all these errors are
/// caused by gas metering issues, hence this error type is a wrapper around the [`GasMeteringError`].
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum StateAccessorError<GU: Gas> {
/// An error occurred when trying to get a value from the state.
#[error(
"An error occured while trying to get the value (key {key:}) from the state: {inner}, namespace: {namespace:?}"
)]
Get {
/// The key of the value that was not found.
key: SlotKey,
/// The error that occurred while trying to get the value.
inner: GasMeteringError<GU>,
/// The namespace that was queried.
namespace: Namespace,
},
/// An error occurred when trying to set a value in the state.
#[error(
"An error occurred while trying to set the value (key {key}) in the state: {inner}, namespace: {namespace:?}"
)]
Set {
/// The key of the value that was not found.
key: SlotKey,
/// The error that occurred while trying to set the value.
inner: GasMeteringError<GU>,
/// The namespace that was queried.
namespace: Namespace,
},
/// An error occurred when trying to decode a value retrieved from the state.
#[error(
"An error occured while trying to decode the value (key {key:}) in the state: {inner}, namespace: {namespace:?}"
)]
Decode {
/// The key of the value that was not found.
key: SlotKey,
/// The error that occurred while trying to decode the value.
inner: GasMeteringError<GU>,
/// The namespace that was queried.
namespace: Namespace,
},
/// An error occurred when trying to delete a value from the state.
#[error(
"An error occured while trying to delete the value (key {key:}) in the state: {inner}, namespace: {namespace:?}"
)]
Delete {
/// The key of the value that was not found.
key: SlotKey,
/// The error that occurred while trying to delete the value.
inner: GasMeteringError<GU>,
/// The namespace that was queried.
namespace: Namespace,
},
}
/// A trait that represents a [`StateReader`] and [`StateWriter`] to a given namespace that never fails on state accesses. Accessing the state with structs that implement
/// this trait will return [`Infallible`].
///
/// ## Usage example
/// ```
/// use sov_modules_api::prelude::UnwrapInfallible;
/// use sov_state::namespaces::User;
///
/// fn delete_state_string<InfallibleAccessor: sov_modules_api::InfallibleStateReaderAndWriter<User>>
/// (mut value: sov_modules_api::StateValue<String>, state: &mut InfallibleAccessor) -> () {
/// if let Some(original) = value.get(state).unwrap_infallible() {
/// println!("original: {}", original);
/// }
/// value.delete(state).unwrap_infallible();
/// }
/// ```
pub trait InfallibleStateReaderAndWriter<N: CompileTimeNamespace>:
StateReader<N, Error = Infallible> + StateWriter<N, Error = Infallible>
{
}
impl<
T: StateReader<N, Error = Infallible> + StateWriter<N, Error = Infallible>,
N: CompileTimeNamespace,
> InfallibleStateReaderAndWriter<N> for T
{
}
/// A trait that represents a [`StateReader`] and [`StateWriter`] to the accessory namespace that never fails on state accesses.
/// Basically a [`InfallibleStateReaderAndWriter<Accessory>`] for the accessory namespace.
pub trait AccessoryStateReaderAndWriter: InfallibleStateReaderAndWriter<Accessory> {}
impl<T: InfallibleStateReaderAndWriter<Accessory>> AccessoryStateReaderAndWriter for T {}
/// A wrapper trait for storage reader and writer that can be used to charge gas
/// for the read/write operations.
pub trait StateReaderAndWriter<N: CompileTimeNamespace>:
StateReader<N> + StateWriter<N, Error = <Self as StateReader<N>>::Error>
{
/// Removes a value from storage and decode the result
fn remove_decoded<V, Codec>(
&mut self,
key: &SlotKey,
codec: &Codec,
) -> Result<Option<V>, <Self as StateWriter<N>>::Error>
where
Codec: StateCodec,
Codec::ValueCodec: StateItemCodec<V>,
{
let value = self.get_decoded(key, codec)?;
<Self as StateWriter<N>>::delete(self, key)?;
Ok(value)
}
}
impl<T, N> StateReaderAndWriter<N> for T
where
T: StateReader<N> + StateWriter<N, Error = <Self as StateReader<N>>::Error>,
N: CompileTimeNamespace,
{
}
/// A storage reader which can access a particular namespace.
pub trait StateReader<N: CompileTimeNamespace>: UniversalStateAccessor {
/// The error type returned when a state read operation fails.
type Error: std::error::Error + Send + Sync + 'static;
/// Get a value from the storage. Basically a wrapper around [`StateReader::get`].
///
/// ## Error
/// This method can fail if the gas meter doesn't have enough funds to pay for the read operation.
fn get(&mut self, key: &SlotKey) -> Result<Option<SlotValue>, Self::Error>;
/// Get a decoded value from the storage.
///
/// ## Error
/// This method can fail if the gas meter doesn't have enough funds to pay for the read operation.
///
/// ## Note
/// For now this method doesn't charge an extra amount of gas for the decoding operation. This may change in the future.
fn get_decoded<V, Codec>(
&mut self,
storage_key: &SlotKey,
codec: &Codec,
) -> Result<Option<V>, Self::Error>
where
Codec: StateCodec,
Codec::ValueCodec: StateItemCodec<V>;
}
/// A storage reader which can access the accessory state.
/// Does not charge gas for read operations.
pub trait AccessoryStateReader: UniversalStateAccessor + StateMetricsProvider {}
/// A trait wrapper that replicates the functionality of [`StateReader`] but with a gas metering interface.
/// This allows a storage reader to charge gas for read operations.
pub trait ProvableStateReader<N: ProvableCompileTimeNamespace>:
UniversalStateAccessor + GasMeter + StateMetricsProvider
{
}
#[cfg(feature = "expensive-observability")]
macro_rules! maybe_trace_span {
($span_name: expr, $item:expr) => {{
tracing::trace_span!($span_name,).in_scope(|| $item)
}};
}
#[cfg(not(feature = "expensive-observability"))]
macro_rules! maybe_trace_span {
($span_name: expr, $item:expr) => {{
$item
}};
}
macro_rules! blanket_impl_metered_state_reader {
($namespace:ty) => {
type Error = StateAccessorError<<T::Spec as GasSpec>::Gas>;
fn get(&mut self, key: &SlotKey) -> Result<Option<SlotValue>, Self::Error> {
let (val, size_metric, read_metric) = get_inner(
self,
<$namespace as sov_state::CompileTimeNamespace>::NAMESPACE,
key,
)
.map_err(|e| StateAccessorError::Get {
key: key.clone(),
inner: e,
namespace: <$namespace as sov_state::CompileTimeNamespace>::NAMESPACE,
})?;
self.metrics().push(size_metric);
self.metrics().push(read_metric);
Ok(val)
}
fn get_decoded<V, Codec>(
&mut self,
storage_key: &SlotKey,
codec: &Codec,
) -> Result<Option<V>, Self::Error>
where
Codec: StateCodec,
Codec::ValueCodec: StateItemCodec<V>,
{
let storage_value = <Self as StateReader<$namespace>>::get(self, storage_key)?;
storage_value
.map(|storage_value| {
// We need to charge for the cost to deserialize the value
maybe_trace_span!("all_accesses::charge_per_byte_borsh_deserialization", {
self.charge_linear_gas(
<T::Spec as GasSpec>::gas_to_charge_per_byte_borsh_deserialization(),
storage_value.size(),
)
.map_err(|e| StateAccessorError::Decode {
key: storage_key.clone(),
inner: e,
namespace: <$namespace as sov_state::CompileTimeNamespace>::NAMESPACE,
})
})?;
#[cfg(feature = "expensive-observability")]
let deserialization_start = std::time::Instant::now();
let value = codec.value_codec().decode_unwrap(storage_value.value());
#[cfg(feature = "expensive-observability")]
{
let deserialization_duration = deserialization_start.elapsed();
self.metrics().add_deserialize_metric(
Default::default(),
None,
storage_value.size(),
deserialization_duration,
);
}
Ok(value)
})
.transpose()
}
};
}
impl<T: ProvableStateReader<Kernel>> StateReader<Kernel> for T {
blanket_impl_metered_state_reader!(Kernel);
}
impl<T: ProvableStateReader<User>> StateReader<User> for T {
blanket_impl_metered_state_reader!(User);
}
impl<T: AccessoryStateReader + StateMetricsProvider> StateReader<Accessory> for T {
type Error = Infallible;
/// Get a value from the storage.
fn get(&mut self, key: &SlotKey) -> Result<Option<SlotValue>, Self::Error> {
let mut metric = StateAccessMetric::new_read();
let val = self.get_value(Accessory::NAMESPACE, key, &mut metric);
self.metrics().push(metric);
Ok(val)
}
/// Get a decoded value from the storage.
fn get_decoded<V, Codec>(
&mut self,
storage_key: &SlotKey,
codec: &Codec,
) -> Result<Option<V>, Self::Error>
where
Codec: StateCodec,
Codec::ValueCodec: StateItemCodec<V>,
{
let storage_value = <Self as StateReader<Accessory>>::get(self, storage_key)?;
let value = storage_value.map(|storage_value| {
#[cfg(feature = "expensive-observability")]
let deserialization_start = std::time::Instant::now();
let value = codec.value_codec().decode_unwrap(storage_value.value());
#[cfg(feature = "expensive-observability")]
{
let deserialization_duration = deserialization_start.elapsed();
self.metrics().add_deserialize_metric(
Default::default(),
None,
storage_value.size(),
deserialization_duration,
);
}
value
});
Ok(value)
}
}
/// Provides write-only access to a particular namespace
pub trait StateWriter<N: CompileTimeNamespace>: UniversalStateAccessor {
/// The error type returned when a state write operation fails.
type Error: std::error::Error + Send + Sync + 'static;
/// Sets a value in the storage. Basically a wrapper around [`StateWriter::set`].
///
/// ## Error
/// This method can fail if the gas meter doesn't have enough funds to pay for the write operation.
fn set(&mut self, key: &SlotKey, value: SlotValue) -> Result<(), Self::Error>;
/// Deletes a value from the storage. Basically a wrapper around [`StateWriter::delete`].
///
/// ## Error
/// This method can fail if the gas meter doesn't have enough funds to pay for the delete operation.
fn delete(&mut self, key: &SlotKey) -> Result<(), Self::Error>;
}
/// A trait wrapper that replicates the functionality of [`StateWriter`] but with a gas metering interface.
/// This allows a storage writer to charge gas for write operations.
pub trait ProvableStateWriter<N: ProvableCompileTimeNamespace>:
UniversalStateAccessor + GasMeter
{
}
macro_rules! blanket_impl_metered_state_writer {
($namespace:ty) => {
impl<T: ProvableStateWriter<$namespace>> StateWriter<$namespace> for T {
type Error = StateAccessorError<<T::Spec as GasSpec>::Gas>;
fn set(&mut self, key: &SlotKey, value: SlotValue) -> Result<(), Self::Error> {
set_inner(
self,
<$namespace as sov_state::CompileTimeNamespace>::NAMESPACE,
key,
value,
)
.map_err(|e| StateAccessorError::Set {
key: key.clone(),
inner: e,
namespace: <$namespace as sov_state::CompileTimeNamespace>::NAMESPACE,
})?;
Ok(())
}
fn delete(&mut self, key: &SlotKey) -> Result<(), Self::Error> {
delete_inner(
self,
<$namespace as sov_state::CompileTimeNamespace>::NAMESPACE,
key,
)
.map_err(|e| StateAccessorError::Delete {
key: key.clone(),
inner: e,
namespace: <$namespace as sov_state::CompileTimeNamespace>::NAMESPACE,
})?;
Ok(())
}
}
};
}
blanket_impl_metered_state_writer!(User);
blanket_impl_metered_state_writer!(Kernel);
/// Provides write-only access to the accessory state
/// Does not charge gas for write/delete operations.
pub trait AccessoryStateWriter: UniversalStateAccessor {}
impl<T: AccessoryStateWriter> StateWriter<Accessory> for T {
type Error = Infallible;
/// Replaces a storage value.
fn set(&mut self, key: &SlotKey, value: SlotValue) -> Result<(), Self::Error> {
self.set_value(Accessory::NAMESPACE, key, value);
Ok(())
}
/// Deletes a storage value.
fn delete(&mut self, key: &SlotKey) -> Result<(), Self::Error> {
self.delete_value(Accessory::NAMESPACE, key);
Ok(())
}
}
#[cfg(feature = "native")]
/// Allows a type to retrieve state values with a proof of their presence/absence.
pub trait ProvenStateAccessor<N: ProvableCompileTimeNamespace>: StateReaderAndWriter<N> {
/// The underlying storage whose proof is returned
type Proof;
/// Fetch the value with the requested key and provide a proof of its presence/absence.
fn get_with_proof(&mut self, key: SlotKey) -> Option<StorageProof<Self::Proof>>
where
Self: StateReaderAndWriter<N>,
N: ProvableCompileTimeNamespace;
}
/// A [`StateReader`] that is version-aware.
pub trait VersionReader {
/// Returns the largest slot number that the accessor is allowed to access. During transaction execution,
/// this is the same as the value returned by [`VersionReader::current_visible_slot_number`]. When executing with kernel,
/// permissions, this is the true slot number. Note: Kernel permissions are only applicable to maintainers of the SDK.
fn max_allowed_slot_number_to_access(&self) -> SlotNumber;
/// Returns the current visible slot number.
fn current_visible_slot_number(&self) -> VisibleSlotNumber;
/// Returns the current version of the state accessor
fn rollup_height_to_access(&self) -> RollupHeight;
}
/// Helper macro to delegate VersionReader implementation to an inner field.
macro_rules! delegate_version_reader {
($ty:ty $(where [$($bounds:tt)*])? => $($field:tt).+) => {
impl$(<$($bounds)*>)? $crate::state::VersionReader for $ty {
fn rollup_height_to_access(&self) -> $crate::capabilities::RollupHeight {
self.$($field).+.rollup_height_to_access()
}
fn current_visible_slot_number(&self) -> sov_rollup_interface::common::VisibleSlotNumber {
self.$($field).+.current_visible_slot_number()
}
fn max_allowed_slot_number_to_access(&self) -> sov_rollup_interface::common::SlotNumber {
self.$($field).+.max_allowed_slot_number_to_access()
}
}
};
}
pub(crate) use delegate_version_reader;
/// A trait for state accessors that can know the true [`SlotNumber`] and use it to read/write the kernel.
/// Note that this trait should be implemented with extreme care, since misuse can cause accidental breakage of
/// soft confirmations. In particular, this trait should never be added to [`TxState`].
pub trait PrivilegedKernelAccessor: StateWriter<namespaces::Kernel> {
/// Returns the current true rollup height contained in the accessor
fn true_slot_number(&self) -> SlotNumber;
}
/// Amount to pay for access to a storage value.
fn charge_storage_access<Accessor: GasMeter>(
accessor: &mut Accessor,
key: &SlotKey,
) -> Result<(), GasMeteringError<<Accessor::Spec as Spec>::Gas>> {
// Charge:
// - cold access bias to load something from the storage (aka Merkle proof cost)
// - fixed hashing cost
// - hashing cost of the key length
maybe_trace_span!("access::charge_bias_for_access", {
accessor.charge_gas(<Accessor::Spec as GasSpec>::bias_to_charge_for_access())
})?;
maybe_trace_span!("access::charge_hash_update", {
accessor.charge_gas(<Accessor::Spec as GasSpec>::gas_to_charge_hash_update())
})?;
let key_size: u32 = key
.len()
.try_into()
.map_err(|e: TryFromIntError| GasMeteringError::Overflow(e.to_string()))?;
if key_size > 0 {
maybe_trace_span!("access::charge_per_byte_hash_update", {
accessor.charge_linear_gas(
<Accessor::Spec as GasSpec>::gas_to_charge_per_byte_hash_update(),
key_size,
)
})?;
}
Ok(())
}
fn charge_read<Accessor: UniversalStateAccessor + GasMeter>(
accessor: &mut Accessor,
namespace: Namespace,
key: &SlotKey,
) -> Result<StateAccessMetric, GasMeteringError<<Accessor::Spec as Spec>::Gas>> {
charge_storage_access(accessor, key)?;
maybe_trace_span!("access::charge_bias_for_read", {
accessor.charge_gas(<Accessor::Spec as GasSpec>::bias_to_charge_for_read())
})?;
let mut metric = StateAccessMetric::new_size();
let value_size = accessor.get_size(namespace, key, &mut metric);
match value_size {
Some(0) | None => {}
Some(value_size) => {
maybe_trace_span!("access::charge_per_byte_read", {
accessor.charge_linear_gas(
<Accessor::Spec as GasSpec>::gas_to_charge_per_byte_read(),
value_size,
)
})?;
maybe_trace_span!("access::charge_hash_update", {
accessor.charge_gas(<Accessor::Spec as GasSpec>::gas_to_charge_hash_update())
})?;
maybe_trace_span!("access::charge_per_byte_hash_update", {
accessor.charge_linear_gas(
<Accessor::Spec as GasSpec>::gas_to_charge_per_byte_hash_update(),
value_size,
)
})?;
}
}
Ok(metric)
}
/// Charge gas for state write
pub fn charge_write<Accessor: GasMeter>(
accessor: &mut Accessor,
_namespace: Namespace,
key: &SlotKey,
value_size: u32,
) -> Result<(), GasMeteringError<<Accessor::Spec as Spec>::Gas>> {
charge_storage_access(accessor, key)?;
accessor.charge_gas(<Accessor::Spec as GasSpec>::bias_to_charge_storage_update())?;
accessor.charge_linear_gas(
<Accessor::Spec as GasSpec>::gas_to_charge_per_byte_storage_update(),
value_size,
)?;
accessor.charge_gas(<Accessor::Spec as GasSpec>::gas_to_charge_hash_update())?;
accessor.charge_linear_gas(
<Accessor::Spec as GasSpec>::gas_to_charge_per_byte_hash_update(),
value_size,
)?;
Ok(())
}
type ValueWithMetrics = (Option<SlotValue>, StateAccessMetric, StateAccessMetric);
/// Returns metrics for the get_size and get_value operations, in that order.
#[cfg_attr(feature = "expensive-observability", instrument(name = "state::get", skip_all, level = Level::TRACE, fields(key = %key, value_size_bytes)))]
pub(crate) fn get_inner<Accessor: UniversalStateAccessor + GasMeter>(
accessor: &mut Accessor,
namespace: Namespace,
key: &SlotKey,
) -> Result<ValueWithMetrics, GasMeteringError<<Accessor::Spec as Spec>::Gas>> {
let size_metric = charge_read(accessor, namespace, key)?;
let mut read_metric = StateAccessMetric::new_read();
let value = accessor.get_value(namespace, key, &mut read_metric);
#[cfg(feature = "expensive-observability")]
if enabled!(Level::TRACE) {
let size = value.as_ref().map(SlotValue::size).unwrap_or(0);
Span::current().record("value_size_bytes", size);
}
Ok((value, size_metric, read_metric))
}
#[cfg_attr(feature = "expensive-observability", instrument(name = "state::set", skip_all, level = Level::TRACE, fields(key = %key, value_size_bytes = value.size())))]
pub(crate) fn set_inner<Accessor: UniversalStateAccessor + GasMeter>(
accessor: &mut Accessor,
namespace: Namespace,
key: &SlotKey,
value: SlotValue,
) -> Result<(), GasMeteringError<<Accessor::Spec as Spec>::Gas>> {
charge_write(accessor, namespace, key, value.size())?;
accessor.set_value(namespace, key, value);
Ok(())
}
/// Returns a metric for the read done if `trace` level tracking is enabled. Otherwise, no state read is performed
/// so no metric is returned.
#[cfg_attr(feature = "expensive-observability", instrument(name = "state::delete", skip_all, level = Level::TRACE, fields(key = %key, value_size_bytes)))]
pub(crate) fn delete_inner<Accessor: UniversalStateAccessor + GasMeter>(
accessor: &mut Accessor,
namespace: Namespace,
key: &SlotKey,
) -> Result<Option<StateAccessMetric>, GasMeteringError<<Accessor::Spec as Spec>::Gas>> {
// Doing a delete is the same as doing a write with a size of 0
charge_write(accessor, namespace, key, 0)?;
// avoid an extra size calculation
let metric = {
#[cfg(feature = "expensive-observability")]
if enabled!(Level::TRACE) {
let mut metric = StateAccessMetric::new_size();
let size = accessor.get_size(namespace, key, &mut metric).unwrap_or(0);
Span::current().record("value_size_bytes", size);
Some(metric)
} else {
None
}
#[cfg(not(feature = "expensive-observability"))]
{
None
}
};
accessor.delete_value(namespace, key);
Ok(metric)
}