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_ethereum_primitives::{Receipt, TransactionSigned, TxType};
12use reth_primitives_traits::{Account, Bytecode, StorageEntry};
13use reth_prune_types::{PruneCheckpoint, PruneSegment};
14use reth_stages_types::StageCheckpoint;
15use reth_trie_common::{StorageTrieEntry, StoredNibbles, StoredNibblesSubKey, *};
16use serde::{Deserialize, Serialize};
17
18pub mod accounts;
19pub mod blocks;
20pub mod integer_list;
21pub mod metadata;
22pub mod sharded_key;
23pub mod storage_sharded_key;
24
25pub use accounts::*;
26pub use blocks::*;
27pub use integer_list::IntegerList;
28pub use metadata::*;
29pub use reth_db_models::{
30 AccountBeforeTx, ClientVersion, StaticFileBlockWithdrawals, StorageBeforeTx,
31 StoredBlockBodyIndices, StoredBlockWithdrawals,
32};
33pub use sharded_key::ShardedKey;
34
35macro_rules! impl_uints {
37 ($($name:tt),+) => {
38 $(
39 impl Encode for $name {
40 type Encoded = [u8; std::mem::size_of::<$name>()];
41
42 fn encode(self) -> Self::Encoded {
43 self.to_be_bytes()
44 }
45 }
46
47 impl Decode for $name {
48 fn decode(value: &[u8]) -> Result<Self, $crate::DatabaseError> {
49 Ok(
50 $name::from_be_bytes(
51 value.try_into().map_err(|_| $crate::DatabaseError::Decode)?
52 )
53 )
54 }
55 }
56 )+
57 };
58}
59
60impl_uints!(u64, u32, u16, u8);
61
62impl Encode for Vec<u8> {
63 type Encoded = Self;
64
65 fn encode(self) -> Self::Encoded {
66 self
67 }
68}
69
70impl Decode for Vec<u8> {
71 fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
72 Ok(value.to_vec())
73 }
74
75 fn decode_owned(value: Vec<u8>) -> Result<Self, DatabaseError> {
76 Ok(value)
77 }
78}
79
80impl Encode for Address {
81 type Encoded = [u8; 20];
82
83 fn encode(self) -> Self::Encoded {
84 self.0 .0
85 }
86}
87
88impl Decode for Address {
89 fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
90 Ok(Self::from_slice(value))
91 }
92}
93
94impl Encode for B256 {
95 type Encoded = [u8; 32];
96
97 fn encode(self) -> Self::Encoded {
98 self.0
99 }
100}
101
102impl Decode for B256 {
103 fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
104 Ok(Self::new(value.try_into().map_err(|_| DatabaseError::Decode)?))
105 }
106}
107
108impl Encode for String {
109 type Encoded = Vec<u8>;
110
111 fn encode(self) -> Self::Encoded {
112 self.into_bytes()
113 }
114}
115
116impl Decode for String {
117 fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
118 Self::decode_owned(value.to_vec())
119 }
120
121 fn decode_owned(value: Vec<u8>) -> Result<Self, DatabaseError> {
122 Self::from_utf8(value).map_err(|_| DatabaseError::Decode)
123 }
124}
125
126impl Encode for StoredNibbles {
127 type Encoded = arrayvec::ArrayVec<u8, 64>;
128
129 fn encode(self) -> Self::Encoded {
130 self.0.iter().collect()
131 }
132}
133
134impl Decode for StoredNibbles {
135 fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
136 Ok(Self::from_compact(value, value.len()).0)
137 }
138}
139
140impl Encode for StoredNibblesSubKey {
141 type Encoded = Vec<u8>;
142
143 fn encode(self) -> Self::Encoded {
145 let mut buf = Vec::with_capacity(65);
146 self.to_compact(&mut buf);
147 buf
148 }
149}
150
151impl Decode for StoredNibblesSubKey {
152 fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
153 Ok(Self::from_compact(value, value.len()).0)
154 }
155}
156
157impl Encode for PruneSegment {
158 type Encoded = [u8; 1];
159
160 fn encode(self) -> Self::Encoded {
161 let mut buf = [0u8];
162 self.to_compact(&mut buf.as_mut());
163 buf
164 }
165}
166
167impl Decode for PruneSegment {
168 fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
169 Ok(Self::from_compact(value, value.len()).0)
170 }
171}
172
173impl Encode for ClientVersion {
174 type Encoded = Vec<u8>;
175
176 fn encode(self) -> Self::Encoded {
178 let mut buf = vec![];
179 self.to_compact(&mut buf);
180 buf
181 }
182}
183
184impl Decode for ClientVersion {
185 fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
186 Ok(Self::from_compact(value, value.len()).0)
187 }
188}
189
190macro_rules! impl_compression_for_compact {
192 ($($name:ident$(<$($generic:ident),*>)?),+) => {
193 $(
194 impl$(<$($generic: core::fmt::Debug + Send + Sync + Compact),*>)? Compress for $name$(<$($generic),*>)? {
195 type Compressed = Vec<u8>;
196
197 fn compress_to_buf<B: bytes::BufMut + AsMut<[u8]>>(&self, buf: &mut B) {
198 let _ = Compact::to_compact(self, buf);
199 }
200 }
201
202 impl$(<$($generic: core::fmt::Debug + Send + Sync + Compact),*>)? Decompress for $name$(<$($generic),*>)? {
203 fn decompress(value: &[u8]) -> Result<$name$(<$($generic),*>)?, $crate::DatabaseError> {
204 let (obj, _) = Compact::from_compact(value, value.len());
205 Ok(obj)
206 }
207 }
208 )+
209 };
210}
211
212impl_compression_for_compact!(
213 Bytes,
214 Header,
215 Account,
216 Log,
217 Receipt<T>,
218 TxType,
219 StorageEntry,
220 BranchNodeCompact,
221 StoredNibbles,
222 StoredNibblesSubKey,
223 StorageTrieEntry,
224 StoredBlockBodyIndices,
225 StoredBlockOmmers<H>,
226 StoredBlockWithdrawals,
227 StaticFileBlockWithdrawals,
228 Bytecode,
229 AccountBeforeTx,
230 StorageBeforeTx,
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 op_alloy_consensus::{OpReceipt, OpTxEnvelope};
244
245 impl_compression_for_compact!(OpTxEnvelope, 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_traits::Account;
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}