Skip to main content

reth_db_api/models/
accounts.rs

1//! Account related models and types.
2
3use crate::{
4    impl_fixed_arbitrary,
5    table::{Decode, Encode},
6    DatabaseError,
7};
8use alloy_primitives::{Address, BlockNumber, StorageKey};
9use serde::{Deserialize, Serialize};
10use std::ops::{Bound, Range, RangeBounds, RangeInclusive};
11
12/// [`BlockNumber`] concatenated with [`Address`].
13///
14/// Since it's used as a key, it isn't compressed when encoding it.
15#[derive(
16    Debug, Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Ord, PartialOrd, Hash,
17)]
18pub struct BlockNumberAddress(pub (BlockNumber, Address));
19
20impl BlockNumberAddress {
21    /// Create a new Range from `start` to `end`
22    ///
23    /// Note: End is inclusive
24    pub fn range(range: RangeInclusive<BlockNumber>) -> Range<Self> {
25        (*range.start(), Address::ZERO).into()..(*range.end() + 1, Address::ZERO).into()
26    }
27
28    /// Return the block number
29    pub const fn block_number(&self) -> BlockNumber {
30        self.0 .0
31    }
32
33    /// Return the address
34    pub const fn address(&self) -> Address {
35        self.0 .1
36    }
37
38    /// Consumes `Self` and returns [`BlockNumber`], [`Address`]
39    pub const fn take(self) -> (BlockNumber, Address) {
40        (self.0 .0, self.0 .1)
41    }
42}
43
44impl From<(BlockNumber, Address)> for BlockNumberAddress {
45    fn from(tpl: (u64, Address)) -> Self {
46        Self(tpl)
47    }
48}
49
50impl Encode for BlockNumberAddress {
51    type Encoded = [u8; 28];
52
53    fn encode(self) -> Self::Encoded {
54        let block_number = self.0 .0;
55        let address = self.0 .1;
56
57        let mut buf = [0u8; 28];
58
59        buf[..8].copy_from_slice(&block_number.to_be_bytes());
60        buf[8..].copy_from_slice(address.as_slice());
61        buf
62    }
63}
64
65impl Decode for BlockNumberAddress {
66    fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
67        let num = u64::from_be_bytes(value[..8].try_into().map_err(|_| DatabaseError::Decode)?);
68        let hash = Address::from_slice(&value[8..]);
69        Ok(Self((num, hash)))
70    }
71}
72
73/// A [`RangeBounds`] over a range of [`BlockNumberAddress`]s. Used to conveniently convert from a
74/// range of [`BlockNumber`]s.
75#[derive(Debug)]
76pub struct BlockNumberAddressRange {
77    /// Starting bound of the range.
78    pub start: Bound<BlockNumberAddress>,
79    /// Ending bound of the range.
80    pub end: Bound<BlockNumberAddress>,
81}
82
83impl RangeBounds<BlockNumberAddress> for BlockNumberAddressRange {
84    fn start_bound(&self) -> Bound<&BlockNumberAddress> {
85        self.start.as_ref()
86    }
87
88    fn end_bound(&self) -> Bound<&BlockNumberAddress> {
89        self.end.as_ref()
90    }
91}
92
93impl<R: RangeBounds<BlockNumber>> From<R> for BlockNumberAddressRange {
94    fn from(r: R) -> Self {
95        let start = match r.start_bound() {
96            Bound::Included(n) => Bound::Included(BlockNumberAddress((*n, Address::ZERO))),
97            Bound::Excluded(n) => {
98                let Some(next) = n.checked_add(1) else {
99                    // No key precedes the first (block, address) pair.
100                    return Self {
101                        start: Bound::Unbounded,
102                        end: Bound::Excluded((0, Address::ZERO).into()),
103                    }
104                };
105                Bound::Included((next, Address::ZERO).into())
106            }
107            Bound::Unbounded => Bound::Unbounded,
108        };
109
110        let end = match r.end_bound() {
111            Bound::Included(n) => n
112                .checked_add(1)
113                .map_or(Bound::Unbounded, |next| Bound::Excluded((next, Address::ZERO).into())),
114            Bound::Excluded(n) => Bound::Excluded(BlockNumberAddress((*n, Address::ZERO))),
115            Bound::Unbounded => Bound::Unbounded,
116        };
117
118        Self { start, end }
119    }
120}
121
122/// [`Address`] concatenated with [`StorageKey`]. Used by `reth_etl` and history stages.
123///
124/// Since it's used as a key, it isn't compressed when encoding it.
125#[derive(
126    Debug, Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Ord, PartialOrd, Hash,
127)]
128pub struct AddressStorageKey(pub (Address, StorageKey));
129
130impl Encode for AddressStorageKey {
131    type Encoded = [u8; 52];
132
133    fn encode(self) -> Self::Encoded {
134        let address = self.0 .0;
135        let storage_key = self.0 .1;
136
137        let mut buf = [0u8; 52];
138
139        buf[..20].copy_from_slice(address.as_slice());
140        buf[20..].copy_from_slice(storage_key.as_slice());
141        buf
142    }
143}
144
145impl Decode for AddressStorageKey {
146    fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
147        let address = Address::from_slice(&value[..20]);
148        let storage_key = StorageKey::from_slice(&value[20..]);
149        Ok(Self((address, storage_key)))
150    }
151}
152
153impl_fixed_arbitrary!((BlockNumberAddress, 28), (AddressStorageKey, 52));
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158    use alloy_primitives::address;
159    use rand::{rng, Rng};
160
161    #[test]
162    fn test_block_number_address() {
163        let num = 1u64;
164        let hash = address!("0xba5e000000000000000000000000000000000000");
165        let key = BlockNumberAddress((num, hash));
166
167        let mut bytes = [0u8; 28];
168        bytes[..8].copy_from_slice(&num.to_be_bytes());
169        bytes[8..].copy_from_slice(hash.as_slice());
170
171        let encoded = Encode::encode(key);
172        assert_eq!(encoded, bytes);
173
174        let decoded: BlockNumberAddress = Decode::decode(&encoded).unwrap();
175        assert_eq!(decoded, key);
176    }
177
178    #[test]
179    fn test_block_number_address_rand() {
180        let mut bytes = [0u8; 28];
181        rng().fill(bytes.as_mut_slice());
182        let key = BlockNumberAddress::arbitrary(&mut Unstructured::new(&bytes)).unwrap();
183        assert_eq!(bytes, Encode::encode(key));
184    }
185
186    #[test]
187    fn test_address_storage_key() {
188        let storage_key = StorageKey::random();
189        let address = address!("0xba5e000000000000000000000000000000000000");
190        let key = AddressStorageKey((address, storage_key));
191
192        let mut bytes = [0u8; 52];
193        bytes[..20].copy_from_slice(address.as_slice());
194        bytes[20..].copy_from_slice(storage_key.as_slice());
195
196        let encoded = Encode::encode(key);
197        assert_eq!(encoded, bytes);
198
199        let decoded: AddressStorageKey = Decode::decode(&encoded).unwrap();
200        assert_eq!(decoded, key);
201    }
202
203    #[test]
204    fn test_address_storage_key_rand() {
205        let mut bytes = [0u8; 52];
206        rng().fill(bytes.as_mut_slice());
207        let key = AddressStorageKey::arbitrary(&mut Unstructured::new(&bytes)).unwrap();
208        assert_eq!(bytes, Encode::encode(key));
209    }
210}