1use std::fmt::Display;
2use std::sync::Arc;
3
4use borsh::{BorshDeserialize, BorshSerialize};
5use hex;
6use jmt::Version;
7use serde::de::DeserializeOwned;
8use serde::{Deserialize, Serialize};
9use sov_first_read_last_write_cache::{CacheKey, CacheValue};
10
11use crate::codec::{EncodeKeyLike, StateValueCodec};
12use crate::internal_cache::OrderedReadsAndWrites;
13use crate::utils::AlignedVec;
14use crate::witness::Witness;
15use crate::Prefix;
16
17#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize, BorshDeserialize, BorshSerialize)]
20pub struct StorageKey {
21 key: Arc<Vec<u8>>,
22}
23
24impl From<CacheKey> for StorageKey {
25 fn from(cache_key: CacheKey) -> Self {
26 Self { key: cache_key.key }
27 }
28}
29
30impl StorageKey {
31 pub fn key(&self) -> Arc<Vec<u8>> {
33 self.key.clone()
34 }
35
36 pub fn to_cache_key(&self) -> CacheKey {
38 CacheKey {
39 key: self.key.clone(),
40 }
41 }
42
43 pub fn into_cache_key(self) -> CacheKey {
45 CacheKey { key: self.key }
46 }
47}
48
49impl AsRef<Vec<u8>> for StorageKey {
50 fn as_ref(&self) -> &Vec<u8> {
51 &self.key
52 }
53}
54
55impl Display for StorageKey {
56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57 write!(f, "{:x?}", hex::encode(self.key().as_ref()))
58 }
59}
60
61impl StorageKey {
62 pub fn new<K, Q, KC>(prefix: &Prefix, key: &Q, codec: &KC) -> Self
64 where
65 KC: EncodeKeyLike<Q, K>,
66 Q: ?Sized,
67 {
68 let encoded_key = codec.encode_key_like(key);
69 let encoded_key = AlignedVec::new(encoded_key);
70
71 let full_key = Vec::<u8>::with_capacity(prefix.len() + encoded_key.len());
72 let mut full_key = AlignedVec::new(full_key);
73 full_key.extend(prefix.as_aligned_vec());
74 full_key.extend(&encoded_key);
75
76 Self {
77 key: Arc::new(full_key.into_inner()),
78 }
79 }
80
81 pub fn singleton(prefix: &Prefix) -> Self {
83 Self {
84 key: Arc::new(prefix.as_aligned_vec().clone().into_inner()),
85 }
86 }
87}
88
89#[derive(
92 Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize, Serialize, Deserialize, Default,
93)]
94pub struct StorageValue {
95 value: Arc<Vec<u8>>,
96}
97
98impl From<CacheValue> for StorageValue {
99 fn from(cache_value: CacheValue) -> Self {
100 Self {
101 value: cache_value.value,
102 }
103 }
104}
105
106impl From<Vec<u8>> for StorageValue {
107 fn from(value: Vec<u8>) -> Self {
108 Self {
109 value: Arc::new(value),
110 }
111 }
112}
113
114impl StorageValue {
115 pub fn new<V, VC>(value: &V, codec: &VC) -> Self
117 where
118 VC: StateValueCodec<V>,
119 {
120 let encoded_value = codec.encode_value(value);
121 Self {
122 value: Arc::new(encoded_value),
123 }
124 }
125
126 pub fn value(&self) -> &[u8] {
128 &self.value
129 }
130
131 pub fn into_cache_value(self) -> CacheValue {
133 CacheValue { value: self.value }
134 }
135}
136
137#[derive(Debug, Clone, Serialize, Deserialize, BorshDeserialize, BorshSerialize)]
138pub struct StorageProof<P> {
140 pub key: StorageKey,
142 pub value: Option<StorageValue>,
144 pub proof: P,
146}
147
148pub trait Storage: Clone {
150 type Witness: Witness + Send + Sync;
152
153 type RuntimeConfig;
155
156 type Proof: Serialize
158 + DeserializeOwned
159 + core::fmt::Debug
160 + Clone
161 + BorshSerialize
162 + BorshDeserialize;
163
164 type Root: Serialize
166 + DeserializeOwned
167 + core::fmt::Debug
168 + Clone
169 + BorshSerialize
170 + BorshDeserialize
171 + Eq
172 + AsRef<[u8]>
173 + Into<[u8; 32]>; type StateUpdate;
178
179 fn with_config(config: Self::RuntimeConfig) -> Result<Self, anyhow::Error>;
182
183 fn get(&self, key: &StorageKey, witness: &Self::Witness) -> Option<StorageValue>;
185
186 fn get_accessory(&self, _key: &StorageKey) -> Option<StorageValue> {
194 None
195 }
196
197 fn compute_state_update(
199 &self,
200 state_accesses: OrderedReadsAndWrites,
201 witness: &Self::Witness,
202 ) -> Result<(Self::Root, Self::StateUpdate), anyhow::Error>;
203
204 fn commit(&self, node_batch: &Self::StateUpdate, accessory_update: &OrderedReadsAndWrites);
206
207 fn validate_and_commit(
212 &self,
213 state_accesses: OrderedReadsAndWrites,
214 witness: &Self::Witness,
215 ) -> Result<Self::Root, anyhow::Error> {
216 Self::validate_and_commit_with_accessory_update(
217 self,
218 state_accesses,
219 witness,
220 &Default::default(),
221 )
222 }
223
224 fn validate_and_commit_with_accessory_update(
228 &self,
229 state_accesses: OrderedReadsAndWrites,
230 witness: &Self::Witness,
231 accessory_update: &OrderedReadsAndWrites,
232 ) -> Result<Self::Root, anyhow::Error> {
233 let (root_hash, node_batch) = self.compute_state_update(state_accesses, witness)?;
234 self.commit(&node_batch, accessory_update);
235
236 Ok(root_hash)
237 }
238
239 fn open_proof(
242 state_root: Self::Root,
243 proof: StorageProof<Self::Proof>,
244 ) -> Result<(StorageKey, Option<StorageValue>), anyhow::Error>;
245
246 fn is_empty(&self) -> bool;
249}
250
251impl From<&str> for StorageKey {
253 fn from(key: &str) -> Self {
254 Self {
255 key: Arc::new(key.as_bytes().to_vec()),
256 }
257 }
258}
259
260impl From<&str> for StorageValue {
262 fn from(value: &str) -> Self {
263 Self {
264 value: Arc::new(value.as_bytes().to_vec()),
265 }
266 }
267}
268
269pub trait NativeStorage: Storage {
272 fn get_with_proof(&self, key: StorageKey) -> StorageProof<Self::Proof>;
275
276 fn get_root_hash(&self, version: Version) -> Result<Self::Root, anyhow::Error>;
278}