1use crate::{
4 table::{Compress, Decode, Decompress, Encode},
5 DatabaseError,
6};
7use alloy_consensus::Header;
8use alloy_genesis::GenesisAccount;
9use alloy_primitives::{Address, Bytes, Log, B256, U256};
10use reth_codecs::{add_arbitrary_tests, Compact};
11use reth_primitives::{Receipt, StorageEntry, TransactionSigned, TxType};
12use reth_primitives_traits::{Account, Bytecode};
13use reth_prune_types::{PruneCheckpoint, PruneSegment};
14use reth_stages_types::StageCheckpoint;
15use reth_trie_common::{StoredNibbles, StoredNibblesSubKey, *};
16use serde::{Deserialize, Serialize};
17
18pub mod accounts;
19pub mod blocks;
20pub mod integer_list;
21pub mod sharded_key;
22pub mod storage_sharded_key;
23
24pub use accounts::*;
25pub use blocks::*;
26pub use integer_list::IntegerList;
27pub use reth_db_models::{
28 AccountBeforeTx, ClientVersion, StaticFileBlockWithdrawals, StoredBlockBodyIndices,
29 StoredBlockWithdrawals,
30};
31pub use sharded_key::ShardedKey;
32
33macro_rules! impl_uints {
35 ($($name:tt),+) => {
36 $(
37 impl Encode for $name {
38 type Encoded = [u8; std::mem::size_of::<$name>()];
39
40 fn encode(self) -> Self::Encoded {
41 self.to_be_bytes()
42 }
43 }
44
45 impl Decode for $name {
46 fn decode(value: &[u8]) -> Result<Self, $crate::DatabaseError> {
47 Ok(
48 $name::from_be_bytes(
49 value.try_into().map_err(|_| $crate::DatabaseError::Decode)?
50 )
51 )
52 }
53 }
54 )+
55 };
56}
57
58impl_uints!(u64, u32, u16, u8);
59
60impl Encode for Vec<u8> {
61 type Encoded = Self;
62
63 fn encode(self) -> Self::Encoded {
64 self
65 }
66}
67
68impl Decode for Vec<u8> {
69 fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
70 Ok(value.to_vec())
71 }
72
73 fn decode_owned(value: Vec<u8>) -> Result<Self, DatabaseError> {
74 Ok(value)
75 }
76}
77
78impl Encode for Address {
79 type Encoded = [u8; 20];
80
81 fn encode(self) -> Self::Encoded {
82 self.0 .0
83 }
84}
85
86impl Decode for Address {
87 fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
88 Ok(Self::from_slice(value))
89 }
90}
91
92impl Encode for B256 {
93 type Encoded = [u8; 32];
94
95 fn encode(self) -> Self::Encoded {
96 self.0
97 }
98}
99
100impl Decode for B256 {
101 fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
102 Ok(Self::new(value.try_into().map_err(|_| DatabaseError::Decode)?))
103 }
104}
105
106impl Encode for String {
107 type Encoded = Vec<u8>;
108
109 fn encode(self) -> Self::Encoded {
110 self.into_bytes()
111 }
112}
113
114impl Decode for String {
115 fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
116 Self::decode_owned(value.to_vec())
117 }
118
119 fn decode_owned(value: Vec<u8>) -> Result<Self, DatabaseError> {
120 Self::from_utf8(value).map_err(|_| DatabaseError::Decode)
121 }
122}
123
124impl Encode for StoredNibbles {
125 type Encoded = Vec<u8>;
126
127 fn encode(self) -> Self::Encoded {
129 self.0.into()
132 }
133}
134
135impl Decode for StoredNibbles {
136 fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
137 Ok(Self::from_compact(value, value.len()).0)
138 }
139}
140
141impl Encode for StoredNibblesSubKey {
142 type Encoded = Vec<u8>;
143
144 fn encode(self) -> Self::Encoded {
146 let mut buf = Vec::with_capacity(65);
147 self.to_compact(&mut buf);
148 buf
149 }
150}
151
152impl Decode for StoredNibblesSubKey {
153 fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
154 Ok(Self::from_compact(value, value.len()).0)
155 }
156}
157
158impl Encode for PruneSegment {
159 type Encoded = [u8; 1];
160
161 fn encode(self) -> Self::Encoded {
162 let mut buf = [0u8];
163 self.to_compact(&mut buf.as_mut());
164 buf
165 }
166}
167
168impl Decode for PruneSegment {
169 fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
170 Ok(Self::from_compact(value, value.len()).0)
171 }
172}
173
174impl Encode for ClientVersion {
175 type Encoded = Vec<u8>;
176
177 fn encode(self) -> Self::Encoded {
179 let mut buf = vec![];
180 self.to_compact(&mut buf);
181 buf
182 }
183}
184
185impl Decode for ClientVersion {
186 fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
187 Ok(Self::from_compact(value, value.len()).0)
188 }
189}
190
191macro_rules! impl_compression_for_compact {
193 ($($name:ident$(<$($generic:ident),*>)?),+) => {
194 $(
195 impl$(<$($generic: core::fmt::Debug + Send + Sync + Compact),*>)? Compress for $name$(<$($generic),*>)? {
196 type Compressed = Vec<u8>;
197
198 fn compress_to_buf<B: bytes::BufMut + AsMut<[u8]>>(&self, buf: &mut B) {
199 let _ = Compact::to_compact(self, buf);
200 }
201 }
202
203 impl$(<$($generic: core::fmt::Debug + Send + Sync + Compact),*>)? Decompress for $name$(<$($generic),*>)? {
204 fn decompress(value: &[u8]) -> Result<$name$(<$($generic),*>)?, $crate::DatabaseError> {
205 let (obj, _) = Compact::from_compact(value, value.len());
206 Ok(obj)
207 }
208 }
209 )+
210 };
211}
212
213impl_compression_for_compact!(
214 Bytes,
215 Header,
216 Account,
217 Log,
218 Receipt,
219 TxType,
220 StorageEntry,
221 BranchNodeCompact,
222 StoredNibbles,
223 StoredNibblesSubKey,
224 StorageTrieEntry,
225 StoredBlockBodyIndices,
226 StoredBlockOmmers<H>,
227 StoredBlockWithdrawals,
228 StaticFileBlockWithdrawals,
229 Bytecode,
230 AccountBeforeTx,
231 TransactionSigned,
232 CompactU256,
233 StageCheckpoint,
234 PruneCheckpoint,
235 ClientVersion,
236 GenesisAccount
238);
239
240#[cfg(feature = "op")]
241mod op {
242 use super::*;
243 use reth_optimism_primitives::{OpReceipt, OpTransactionSigned};
244
245 impl_compression_for_compact!(OpTransactionSigned, OpReceipt);
246}
247
248macro_rules! impl_compression_fixed_compact {
249 ($($name:tt),+) => {
250 $(
251 impl Compress for $name {
252 type Compressed = Vec<u8>;
253
254 fn uncompressable_ref(&self) -> Option<&[u8]> {
255 Some(self.as_ref())
256 }
257
258 fn compress_to_buf<B: bytes::BufMut + AsMut<[u8]>>(&self, buf: &mut B) {
259 let _ = Compact::to_compact(self, buf);
260 }
261 }
262
263 impl Decompress for $name {
264 fn decompress(value: &[u8]) -> Result<$name, $crate::DatabaseError> {
265 let (obj, _) = Compact::from_compact(&value, value.len());
266 Ok(obj)
267 }
268 }
269
270 )+
271 };
272}
273
274impl_compression_fixed_compact!(B256, Address);
275
276macro_rules! add_wrapper_struct {
279 ($(($name:tt, $wrapper:tt)),+) => {
280 $(
281 #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, Compact)]
283 #[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
284 #[add_arbitrary_tests(compact)]
285 pub struct $wrapper(pub $name);
286
287 impl From<$name> for $wrapper {
288 fn from(value: $name) -> Self {
289 $wrapper(value)
290 }
291 }
292
293 impl From<$wrapper> for $name {
294 fn from(value: $wrapper) -> Self {
295 value.0
296 }
297 }
298
299 impl std::ops::Deref for $wrapper {
300 type Target = $name;
301
302 fn deref(&self) -> &Self::Target {
303 &self.0
304 }
305 }
306
307 )+
308 };
309}
310
311add_wrapper_struct!((U256, CompactU256));
312add_wrapper_struct!((u64, CompactU64));
313add_wrapper_struct!((ClientVersion, CompactClientVersion));
314
315#[cfg(test)]
316mod tests {
317 #[test]
323 fn test_ensure_backwards_compatibility() {
324 use super::*;
325 use reth_codecs::{test_utils::UnusedBits, validate_bitflag_backwards_compat};
326 use reth_primitives::{Account, Receipt};
327 use reth_prune_types::{PruneCheckpoint, PruneMode, PruneSegment};
328 use reth_stages_types::{
329 AccountHashingCheckpoint, CheckpointBlockRange, EntitiesCheckpoint,
330 ExecutionCheckpoint, HeadersCheckpoint, IndexHistoryCheckpoint, StageCheckpoint,
331 StageUnitCheckpoint, StorageHashingCheckpoint,
332 };
333 assert_eq!(Account::bitflag_encoded_bytes(), 2);
334 assert_eq!(AccountHashingCheckpoint::bitflag_encoded_bytes(), 1);
335 assert_eq!(CheckpointBlockRange::bitflag_encoded_bytes(), 1);
336 assert_eq!(CompactClientVersion::bitflag_encoded_bytes(), 0);
337 assert_eq!(CompactU256::bitflag_encoded_bytes(), 1);
338 assert_eq!(CompactU64::bitflag_encoded_bytes(), 1);
339 assert_eq!(EntitiesCheckpoint::bitflag_encoded_bytes(), 1);
340 assert_eq!(ExecutionCheckpoint::bitflag_encoded_bytes(), 0);
341 assert_eq!(HeadersCheckpoint::bitflag_encoded_bytes(), 0);
342 assert_eq!(IndexHistoryCheckpoint::bitflag_encoded_bytes(), 0);
343 assert_eq!(PruneCheckpoint::bitflag_encoded_bytes(), 1);
344 assert_eq!(PruneMode::bitflag_encoded_bytes(), 1);
345 assert_eq!(PruneSegment::bitflag_encoded_bytes(), 1);
346 assert_eq!(Receipt::bitflag_encoded_bytes(), 1);
347 assert_eq!(StageCheckpoint::bitflag_encoded_bytes(), 1);
348 assert_eq!(StageUnitCheckpoint::bitflag_encoded_bytes(), 1);
349 assert_eq!(StoredBlockBodyIndices::bitflag_encoded_bytes(), 1);
350 assert_eq!(StoredBlockWithdrawals::bitflag_encoded_bytes(), 0);
351 assert_eq!(StorageHashingCheckpoint::bitflag_encoded_bytes(), 1);
352
353 validate_bitflag_backwards_compat!(Account, UnusedBits::NotZero);
354 validate_bitflag_backwards_compat!(AccountHashingCheckpoint, UnusedBits::NotZero);
355 validate_bitflag_backwards_compat!(CheckpointBlockRange, UnusedBits::Zero);
356 validate_bitflag_backwards_compat!(CompactClientVersion, UnusedBits::Zero);
357 validate_bitflag_backwards_compat!(CompactU256, UnusedBits::NotZero);
358 validate_bitflag_backwards_compat!(CompactU64, UnusedBits::NotZero);
359 validate_bitflag_backwards_compat!(EntitiesCheckpoint, UnusedBits::Zero);
360 validate_bitflag_backwards_compat!(ExecutionCheckpoint, UnusedBits::Zero);
361 validate_bitflag_backwards_compat!(HeadersCheckpoint, UnusedBits::Zero);
362 validate_bitflag_backwards_compat!(IndexHistoryCheckpoint, UnusedBits::Zero);
363 validate_bitflag_backwards_compat!(PruneCheckpoint, UnusedBits::NotZero);
364 validate_bitflag_backwards_compat!(PruneMode, UnusedBits::Zero);
365 validate_bitflag_backwards_compat!(PruneSegment, UnusedBits::Zero);
366 validate_bitflag_backwards_compat!(Receipt, UnusedBits::Zero);
367 validate_bitflag_backwards_compat!(StageCheckpoint, UnusedBits::NotZero);
368 validate_bitflag_backwards_compat!(StageUnitCheckpoint, UnusedBits::Zero);
369 validate_bitflag_backwards_compat!(StoredBlockBodyIndices, UnusedBits::Zero);
370 validate_bitflag_backwards_compat!(StoredBlockWithdrawals, UnusedBits::Zero);
371 validate_bitflag_backwards_compat!(StorageHashingCheckpoint, UnusedBits::NotZero);
372 }
373}