alloy-eip7928 0.3.4

Implementation of EIP-7928 type definitions
Documentation
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
//! Contains the [`BlockAccessList`] type, which represents a simple list of account changes.

use crate::account_changes::AccountChanges;
use alloc::vec::Vec;

#[cfg(not(feature = "std"))]
use once_cell::race::OnceBox as OnceLock;
#[cfg(feature = "std")]
use std::sync::OnceLock;

/// This struct is used to store `account_changes` in a block.
pub type BlockAccessList = Vec<AccountChanges>;

/// Computes the hash of the given block access list.
#[cfg(feature = "rlp")]
pub fn compute_block_access_list_hash(bal: &[AccountChanges]) -> alloy_primitives::B256 {
    let mut buf = Vec::new();
    alloy_rlp::encode_list(bal, &mut buf);
    alloy_primitives::keccak256(&buf)
}

/// Computes the total number of items in the block access list, counting each account and unique
/// storage slot.
pub fn total_bal_items(bal: &[AccountChanges]) -> u64 {
    let mut bal_items: u64 = 0;

    for account in bal {
        // Count address
        bal_items += 1;

        // Collect unique storage slots across reads + writes
        let mut unique_slots = alloy_primitives::map::HashSet::new();

        for change in account.storage_changes() {
            unique_slots.insert(change.slot);
        }

        for slot in account.storage_reads() {
            unique_slots.insert(*slot);
        }

        // Count unique storage keys
        bal_items += unique_slots.len() as u64;
    }
    bal_items
}

/// Block-Level Access List wrapper type with helper methods for metrics and validation.
pub mod bal {
    use super::OnceLock;
    use crate::account_changes::AccountChanges;
    use alloc::vec::{IntoIter, Vec};
    use alloy_primitives::Bytes;
    use core::{
        ops::{Deref, Index},
        slice::Iter,
    };

    /// A wrapper around [`Vec<AccountChanges>`] that provides helper methods for
    /// computing metrics and statistics about the block access list.
    ///
    /// This type implements `Deref` to `[AccountChanges]` for easy access to the
    /// underlying data while providing additional utility methods for BAL analysis.
    #[derive(Clone, Debug, Default, PartialEq, Eq)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    #[cfg_attr(
        feature = "rlp",
        derive(alloy_rlp::RlpEncodableWrapper, alloy_rlp::RlpDecodableWrapper)
    )]
    #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
    #[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
    pub struct Bal(Vec<AccountChanges>);

    impl From<Bal> for Vec<AccountChanges> {
        fn from(this: Bal) -> Self {
            this.0
        }
    }

    impl From<Vec<AccountChanges>> for Bal {
        fn from(list: Vec<AccountChanges>) -> Self {
            Self(list)
        }
    }

    #[cfg(feature = "rlp")]
    impl alloy_primitives::Sealable for Bal {
        fn hash_slow(&self) -> alloy_primitives::B256 {
            self.compute_hash()
        }
    }

    impl Deref for Bal {
        type Target = [AccountChanges];

        fn deref(&self) -> &Self::Target {
            self.as_slice()
        }
    }

    impl IntoIterator for Bal {
        type Item = AccountChanges;
        type IntoIter = IntoIter<AccountChanges>;

        fn into_iter(self) -> Self::IntoIter {
            self.0.into_iter()
        }
    }

    impl<'a> IntoIterator for &'a Bal {
        type Item = &'a AccountChanges;
        type IntoIter = Iter<'a, AccountChanges>;

        fn into_iter(self) -> Self::IntoIter {
            self.iter()
        }
    }

    impl FromIterator<AccountChanges> for Bal {
        fn from_iter<I: IntoIterator<Item = AccountChanges>>(iter: I) -> Self {
            Self(iter.into_iter().collect())
        }
    }

    impl<I> Index<I> for Bal
    where
        I: core::slice::SliceIndex<[AccountChanges]>,
    {
        type Output = I::Output;

        #[inline]
        fn index(&self, index: I) -> &Self::Output {
            &self.0[index]
        }
    }

    impl Bal {
        /// Creates a new [`Bal`] from the provided account changes.
        pub const fn new(account_changes: Vec<AccountChanges>) -> Self {
            Self(account_changes)
        }

        /// Adds a new [`AccountChanges`] entry to the list.
        pub fn push(&mut self, account_changes: AccountChanges) {
            self.0.push(account_changes)
        }

        /// Returns `true` if the list contains no elements.
        #[inline]
        pub const fn is_empty(&self) -> bool {
            self.0.is_empty()
        }

        /// Returns the number of account change entries contained in the list.
        #[inline]
        pub const fn len(&self) -> usize {
            self.0.len()
        }

        /// Returns an iterator over the [`AccountChanges`] entries.
        #[inline]
        pub fn iter(&self) -> Iter<'_, AccountChanges> {
            self.0.iter()
        }

        /// Returns a slice of the contained [`AccountChanges`].
        #[inline]
        pub const fn as_slice(&self) -> &[AccountChanges] {
            self.0.as_slice()
        }

        /// Returns a vector of [`AccountChanges`].
        pub fn into_inner(self) -> Vec<AccountChanges> {
            self.0
        }

        /// Returns the total number of accounts with changes in this BAL.
        #[inline]
        pub const fn account_count(&self) -> usize {
            self.0.len()
        }

        /// Returns the total number of storage changes across all accounts.
        pub fn total_storage_changes(&self) -> usize {
            self.0.iter().map(|a| a.storage_changes.len()).sum()
        }

        /// Returns the total number of storage reads across all accounts.
        pub fn total_storage_reads(&self) -> usize {
            self.0.iter().map(|a| a.storage_reads.len()).sum()
        }

        /// Returns the total number of storage slots (both changes and reads) across all accounts.
        pub fn total_slots(&self) -> usize {
            self.0.iter().map(|a| a.storage_changes.len() + a.storage_reads.len()).sum()
        }

        /// Returns the total number of balance changes across all accounts.
        pub fn total_balance_changes(&self) -> usize {
            self.0.iter().map(|a| a.balance_changes.len()).sum()
        }

        /// Returns the total number of nonce changes across all accounts.
        pub fn total_nonce_changes(&self) -> usize {
            self.0.iter().map(|a| a.nonce_changes.len()).sum()
        }

        /// Returns the total number of code changes across all accounts.
        pub fn total_code_changes(&self) -> usize {
            self.0.iter().map(|a| a.code_changes.len()).sum()
        }

        /// Returns a summary of all change counts for metrics reporting.
        pub fn change_counts(&self) -> BalChangeCounts {
            let mut counts = BalChangeCounts::default();
            for account in &self.0 {
                counts.accounts += 1;
                counts.storage += account.storage_changes.len();
                counts.balance += account.balance_changes.len();
                counts.nonce += account.nonce_changes.len();
                counts.code += account.code_changes.len();
            }
            counts
        }

        /// Computes the total number of items in this block access list, counting each account and
        /// unique storage slot.
        pub fn total_bal_items(&self) -> u64 {
            super::total_bal_items(&self.0)
        }

        /// Computes the hash of this block access list.
        #[cfg(feature = "rlp")]
        pub fn compute_hash(&self) -> alloy_primitives::B256 {
            if self.0.is_empty() {
                return crate::constants::EMPTY_BLOCK_ACCESS_LIST_HASH;
            }
            super::compute_block_access_list_hash(&self.0)
        }
    }

    /// Summary of change counts in a BAL for metrics reporting.
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
    pub struct BalChangeCounts {
        /// Number of accounts with changes.
        pub accounts: usize,
        /// Total number of storage changes.
        pub storage: usize,
        /// Total number of balance changes.
        pub balance: usize,
        /// Total number of nonce changes.
        pub nonce: usize,
        /// Total number of code changes.
        pub code: usize,
    }

    /// A decoded block access list with lazy hash computation.
    ///
    /// This type wraps a decoded [`Bal`] along with the original raw RLP bytes,
    /// allowing efficient hash computation on demand without re-encoding.
    #[derive(Clone, Debug)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    pub struct DecodedBal {
        /// The decoded block access list.
        decoded: Bal,
        /// The original raw RLP bytes.
        raw: Bytes,
        /// Lazily computed hash of the block access list.
        #[cfg_attr(feature = "serde", serde(skip, default))]
        hash: OnceLock<alloy_primitives::B256>,
    }

    impl PartialEq for DecodedBal {
        fn eq(&self, other: &Self) -> bool {
            self.decoded == other.decoded && self.raw == other.raw
        }
    }

    impl Eq for DecodedBal {}

    impl DecodedBal {
        /// Creates a new [`DecodedBal`] from decoded data and raw bytes.
        pub const fn new(decoded: Bal, raw: Bytes) -> Self {
            Self { decoded, raw, hash: OnceLock::new() }
        }

        /// Creates a new [`DecodedBal`] by decoding from raw RLP bytes.
        #[cfg(feature = "rlp")]
        pub fn from_rlp_bytes(raw: Bytes) -> Result<Self, alloy_rlp::Error> {
            let mut slice = raw.as_ref();
            let decoded = <Bal as alloy_rlp::Decodable>::decode(&mut slice)?;
            if !slice.is_empty() {
                return Err(alloy_rlp::Error::UnexpectedLength);
            }
            Ok(Self::new(decoded, raw))
        }

        /// Returns a reference to the decoded block access list.
        pub const fn as_bal(&self) -> &Bal {
            &self.decoded
        }

        /// Returns the original raw RLP bytes.
        pub const fn as_raw(&self) -> &Bytes {
            &self.raw
        }

        /// Returns the decoded BAL as a sealed borrowed value.
        #[cfg(feature = "rlp")]
        pub fn as_sealed_bal(&self) -> alloy_primitives::Sealed<&Bal> {
            alloy_primitives::Sealable::seal_ref_unchecked(&self.decoded, self.hash())
        }

        /// Splits this struct into the decoded BAL and raw bytes.
        pub fn split(self) -> (Bal, Bytes) {
            (self.decoded, self.raw)
        }

        /// Splits this struct into the decoded BAL, raw bytes, and hash.
        pub fn into_parts(self) -> (Bal, Bytes, alloy_primitives::B256) {
            let hash = self.hash();
            let (decoded, raw) = self.split();
            (decoded, raw, hash)
        }

        /// Consumes this struct and returns the decoded BAL together with its hash.
        #[cfg(feature = "rlp")]
        pub fn into_sealed(self) -> alloy_primitives::Sealed<Bal> {
            let seal = self.hash();
            let (decoded, _) = self.split();
            alloy_primitives::Sealable::seal_unchecked(decoded, seal)
        }

        /// Returns the hash of this block access list.
        ///
        /// The hash is computed lazily on first call and cached for subsequent calls.
        pub fn hash(&self) -> alloy_primitives::B256 {
            #[allow(clippy::useless_conversion)]
            *self.hash.get_or_init(|| alloy_primitives::keccak256(self.raw.as_ref()).into())
        }
    }

    #[cfg(feature = "rlp")]
    impl alloy_rlp::Decodable for DecodedBal {
        fn decode(buf: &mut &[u8]) -> Result<Self, alloy_rlp::Error> {
            let original = *buf;
            let decoded = <Bal as alloy_rlp::Decodable>::decode(buf)?;
            let consumed = original.len() - buf.len();
            let raw = Bytes::copy_from_slice(&original[..consumed]);
            Ok(Self::new(decoded, raw))
        }
    }

    #[cfg(feature = "rlp")]
    impl alloy_rlp::Encodable for DecodedBal {
        fn encode(&self, out: &mut dyn alloy_rlp::BufMut) {
            out.put_slice(&self.raw);
        }

        fn length(&self) -> usize {
            self.raw.len()
        }
    }
}

#[cfg(test)]
mod hash_tests {
    use super::bal::{Bal, DecodedBal};
    use alloy_primitives::Bytes;

    #[test]
    fn decoded_bal_hash_uses_raw_bytes_without_rlp_feature() {
        let raw = Bytes::from_static(&[0xc0]);
        let decoded = DecodedBal::new(Bal::default(), raw.clone());

        assert_eq!(decoded.hash(), alloy_primitives::keccak256(raw.as_ref()));

        let (bal, split_raw, split_hash) = decoded.into_parts();
        assert!(bal.is_empty());
        assert_eq!(split_raw, raw);
        assert_eq!(split_hash, alloy_primitives::keccak256(raw.as_ref()));
    }
}

#[cfg(all(test, feature = "rlp"))]
mod tests {
    use super::bal::{Bal, DecodedBal};
    use crate::{
        AccountChanges, BalanceChange, CodeChange, NonceChange, SlotChanges, StorageChange,
        constants::EMPTY_BLOCK_ACCESS_LIST_HASH,
    };
    use alloy_primitives::{Address, Bytes, U256};

    fn sample_bal() -> Bal {
        Bal::new(vec![
            AccountChanges::new(Address::from([0x11; 20]))
                .with_storage_read(U256::from(0x10))
                .with_storage_change(SlotChanges::new(
                    U256::from(0x01),
                    vec![StorageChange::new(0, U256::from(0xaa))],
                ))
                .with_balance_change(BalanceChange::new(1, U256::from(1_000)))
                .with_nonce_change(NonceChange::new(2, 7))
                .with_code_change(CodeChange::new(3, Bytes::from(vec![0x60, 0x00]))),
            AccountChanges::new(Address::from([0x22; 20]))
                .with_storage_read(U256::from(0x20))
                .with_storage_change(SlotChanges::new(
                    U256::from(0x02),
                    vec![StorageChange::new(4, U256::from(0xbb))],
                )),
        ])
    }

    #[test]
    fn bal_compute_hash_returns_empty_hash_for_empty_bal() {
        let bal = Bal::default();

        assert_eq!(bal.compute_hash(), EMPTY_BLOCK_ACCESS_LIST_HASH);
    }

    #[test]
    fn bal_compute_hash_matches_free_function_for_non_empty_bal() {
        let bal = sample_bal();

        assert_eq!(bal.compute_hash(), super::compute_block_access_list_hash(bal.as_slice()));
        assert_ne!(bal.compute_hash(), EMPTY_BLOCK_ACCESS_LIST_HASH);
    }

    #[test]
    fn decoded_bal_from_rlp_bytes_preserves_raw_and_hash() {
        let bal = sample_bal();
        let raw = Bytes::from(alloy_rlp::encode(&bal));
        let decoded = DecodedBal::from_rlp_bytes(raw.clone()).unwrap();

        assert_eq!(decoded.as_bal(), &bal);
        assert_eq!(decoded.as_raw(), &raw);
        assert_eq!(decoded.hash(), bal.compute_hash());
        assert_eq!(decoded.hash(), alloy_primitives::keccak256(raw.as_ref()));
        assert_eq!(decoded.as_sealed_bal().hash(), bal.compute_hash());
        assert_eq!(decoded.as_sealed_bal().inner(), &decoded.as_bal());

        let (split_bal, split_raw) = decoded.clone().split();
        assert_eq!(split_bal, bal);
        assert_eq!(split_raw, raw);

        let (split_bal, split_raw, split_hash) = decoded.clone().into_parts();
        assert_eq!(split_bal, bal);
        assert_eq!(split_raw, raw);
        assert_eq!(split_hash, bal.compute_hash());

        let sealed = decoded.into_sealed();
        assert_eq!(sealed.hash(), bal.compute_hash());
        assert_eq!(sealed.inner(), &bal);
    }

    #[test]
    fn decoded_bal_decode_consumes_exact_raw_rlp_item() {
        let bal = sample_bal();
        let raw = alloy_rlp::encode(&bal);
        let mut buf = raw.as_ref();
        let decoded = <DecodedBal as alloy_rlp::Decodable>::decode(&mut buf).unwrap();

        assert!(buf.is_empty());
        assert_eq!(decoded.as_bal(), &bal);
        assert_eq!(decoded.as_raw().as_ref(), raw.as_slice());
        assert_eq!(alloy_rlp::encode(&decoded), raw);
    }
}