alloy-eip7928 0.3.7

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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
//! 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::{
        BlockAccessListGasError, BlockAccessListHashMismatch, account_changes::AccountChanges,
        diff::BalDiff,
    };
    use alloc::vec::{IntoIter, Vec};
    use alloy_primitives::{B256, 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 compact diff describing where this BAL first diverges from `other`.
        pub fn diff(&self, other: &[AccountChanges]) -> BalDiff {
            BalDiff::between(self.as_slice(), other)
        }

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

        /// Sorts this block access list in-place according to the canonical EIP-7928 ordering
        /// rules.
        ///
        /// This applies the ordering required by the "Ordering, Uniqueness and Determinism"
        /// section of EIP-7928:
        ///
        /// - accounts are sorted lexicographically by address
        /// - `storage_changes` are sorted lexicographically by storage key
        /// - each per-slot `StorageChange` list is sorted by block access index in ascending order
        /// - `storage_reads` are sorted lexicographically by storage key
        /// - `balance_changes`, `nonce_changes`, and `code_changes` are sorted by block access
        ///   index in ascending order
        ///
        /// The account-local ordering is delegated to [`AccountChanges::sort`], so callers may
        /// sort account internals independently when a parallel sort strategy is useful.
        ///
        /// This method only canonicalizes ordering. It does not enforce the EIP-7928 uniqueness
        /// constraints for accounts, storage keys, or block access indexes.
        pub fn sort(&mut self) {
            self.0.sort_unstable_by_key(|account| account.address);

            for account in &mut self.0 {
                account.sort();
            }
        }

        /// 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)
        }

        /// Validates this block access list against the block gas limit.
        ///
        /// EIP-7928 specifies that the total cost of the block access list items must not exceed
        /// the gas limit. Each item costs [`crate::constants::ITEM_COST`] gas.
        pub fn validate_gas_limit(&self, gas_limit: u64) -> Result<(), BlockAccessListGasError> {
            let items = self.total_bal_items();
            if items > gas_limit / crate::constants::ITEM_COST as u64 {
                return Err(BlockAccessListGasError::new(items, gas_limit));
            }
            Ok(())
        }

        /// 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 block access list 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<T = Bal> {
        /// The decoded block access list.
        decoded: T,
        /// The original raw RLP bytes.
        raw: Bytes,
        /// Lazily computed hash of the block access list.
        #[cfg_attr(feature = "serde", serde(skip, default))]
        hash: OnceLock<B256>,
    }

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

    impl<T: Eq> Eq for DecodedBal<T> {}

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

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

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

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

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

        /// Ensures the raw RLP hash matches the expected block access list hash.
        ///
        /// This checks `keccak256(raw_rlp_of_received_bal) == expected` using the cached hash of
        /// the original raw RLP bytes captured at decode time.
        pub fn ensure_hash(&self, expected: B256) -> Result<(), BlockAccessListHashMismatch> {
            let computed = self.hash();
            if computed == expected {
                Ok(())
            } else {
                Err(BlockAccessListHashMismatch::new(computed, expected))
            }
        }

        /// 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) -> B256 {
            #[allow(clippy::useless_conversion)]
            *self.hash.get_or_init(|| alloy_primitives::keccak256(self.raw.as_ref()).into())
        }

        /// Converts the decoded BAL to the given alternative that is [`From<T>`].
        pub fn convert<U>(self) -> DecodedBal<U>
        where
            U: From<T>,
        {
            self.map(U::from)
        }

        /// Converts the decoded BAL to the given alternative that is [`TryFrom<T>`].
        pub fn try_convert<U>(self) -> Result<DecodedBal<U>, U::Error>
        where
            U: TryFrom<T>,
        {
            self.try_map(U::try_from)
        }

        /// Applies the given closure to the decoded BAL.
        pub fn map<U>(self, f: impl FnOnce(T) -> U) -> DecodedBal<U> {
            let Self { decoded, raw, hash } = self;
            DecodedBal { decoded: f(decoded), raw, hash }
        }

        /// Applies the given fallible closure to the decoded BAL.
        pub fn try_map<U, E>(self, f: impl FnOnce(T) -> Result<U, E>) -> Result<DecodedBal<U>, E> {
            let Self { decoded, raw, hash } = self;
            Ok(DecodedBal { decoded: f(decoded)?, raw, hash })
        }
    }

    #[cfg(feature = "rlp")]
    impl DecodedBal {
        /// Creates a new [`DecodedBal`] by decoding from raw RLP bytes.
        pub fn from_rlp_bytes(raw: Bytes) -> Result<Self, alloy_rlp::Error> {
            Self::from_rlp_bytes_as(raw)
        }

        /// Creates a new [`DecodedBal`] by decoding from raw RLP bytes into `T`.
        pub fn from_rlp_bytes_as<T>(raw: Bytes) -> Result<DecodedBal<T>, alloy_rlp::Error>
        where
            T: alloy_rlp::Decodable,
        {
            let mut slice = raw.as_ref();
            let decoded = T::decode(&mut slice)?;
            if !slice.is_empty() {
                return Err(alloy_rlp::Error::UnexpectedLength);
            }
            Ok(DecodedBal::new(decoded, raw))
        }
    }

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

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

    #[cfg(feature = "rlp")]
    impl<T> alloy_rlp::Decodable for DecodedBal<T>
    where
        T: alloy_rlp::Decodable,
    {
        fn decode(buf: &mut &[u8]) -> Result<Self, alloy_rlp::Error> {
            let original = *buf;
            let decoded = T::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<T> alloy_rlp::Encodable for DecodedBal<T> {
        fn encode(&self, out: &mut dyn alloy_rlp::BufMut) {
            out.put_slice(&self.raw);
        }

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

/// Error returned when a block access list item cost exceeds the block gas limit.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, thiserror::Error)]
#[error(
    "block access list item cost exceeds gas limit: items={items}, max_items={max_items}, gas_limit={gas_limit}"
)]
pub struct BlockAccessListGasError {
    /// Number of block access list items.
    pub items: u64,
    /// Maximum number of block access list items allowed by the gas limit.
    pub max_items: u64,
    /// Block gas limit used for validation.
    pub gas_limit: u64,
}

impl BlockAccessListGasError {
    /// Creates a new gas limit validation error for the provided item count and gas limit.
    pub const fn new(items: u64, gas_limit: u64) -> Self {
        Self { items, max_items: gas_limit / crate::constants::ITEM_COST as u64, gas_limit }
    }
}

/// Error returned when a decoded block access list hash does not match the expected hash.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, thiserror::Error)]
#[error("block access list hash mismatch: computed={computed}, expected={expected}")]
pub struct BlockAccessListHashMismatch {
    /// Hash computed from the received BAL bytes.
    pub computed: alloy_primitives::B256,
    /// Hash expected by the caller, typically `header.block_access_list_hash`.
    pub expected: alloy_primitives::B256,
}

impl BlockAccessListHashMismatch {
    /// Creates a new block access list hash validation error.
    pub const fn new(computed: alloy_primitives::B256, expected: alloy_primitives::B256) -> Self {
        Self { computed, expected }
    }
}

#[cfg(test)]
mod hash_tests {
    use super::bal::{Bal, DecodedBal};
    use crate::{
        AccountChanges, BalanceChange, CodeChange, NonceChange, SlotChanges, StorageChange,
        constants::ITEM_COST,
    };
    use alloy_primitives::{Address, B256, Bytes, U256};

    #[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()));
    }

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

        let mapped = decoded.map(|bal| bal.len());

        assert_eq!(mapped.as_bal(), &0);
        assert_eq!(mapped.as_raw(), &raw);
        assert_eq!(mapped.hash(), hash);
    }

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

        let mapped = decoded.try_map(|bal| Ok::<_, core::convert::Infallible>(bal.len())).unwrap();

        assert_eq!(mapped.as_bal(), &0);
        assert_eq!(mapped.as_raw(), &raw);

        let decoded = DecodedBal::new(Bal::default(), raw);
        let err = decoded.try_map(|_| Err::<usize, _>("expected error")).unwrap_err();

        assert_eq!(err, "expected error");
    }

    #[derive(Debug, PartialEq, Eq)]
    struct BalLen(usize);

    impl From<Bal> for BalLen {
        fn from(value: Bal) -> Self {
            Self(value.len())
        }
    }

    #[derive(Debug, PartialEq, Eq)]
    struct NonEmptyBal(Bal);

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    struct EmptyBal;

    impl TryFrom<Bal> for NonEmptyBal {
        type Error = EmptyBal;

        fn try_from(value: Bal) -> Result<Self, Self::Error> {
            if value.is_empty() { Err(EmptyBal) } else { Ok(Self(value)) }
        }
    }

    #[test]
    fn decoded_bal_convert_and_try_convert_use_inner_conversions() {
        let raw = Bytes::from_static(&[0xc0]);
        let converted: DecodedBal<BalLen> = DecodedBal::new(Bal::default(), raw.clone()).convert();

        assert_eq!(converted.as_bal(), &BalLen(0));
        assert_eq!(converted.as_raw(), &raw);

        let err = DecodedBal::new(Bal::default(), raw.clone()).try_convert::<NonEmptyBal>();
        assert_eq!(err.unwrap_err(), EmptyBal);

        let bal = Bal::new(vec![AccountChanges::new(Address::from([0x11; 20]))]);
        let converted = DecodedBal::new(bal, raw).try_convert::<NonEmptyBal>().unwrap();

        assert_eq!(converted.as_bal().0.len(), 1);
    }

    #[test]
    fn decoded_bal_ensure_hash_reports_both_hashes() {
        let raw = Bytes::from_static(&[0xc0]);
        let decoded = DecodedBal::new(Bal::default(), raw.clone());
        let computed = alloy_primitives::keccak256(raw.as_ref());
        let expected = B256::from([0x11; 32]);

        assert_eq!(decoded.ensure_hash(computed), Ok(()));
        assert_eq!(
            decoded.ensure_hash(expected),
            Err(super::BlockAccessListHashMismatch::new(computed, expected))
        );
    }

    #[test]
    fn bal_sort_orders_all_eip7928_lists() {
        let address_1 = Address::from([0x11; 20]);
        let address_2 = Address::from([0x22; 20]);
        let mut bal = Bal::new(vec![
            AccountChanges {
                address: address_2,
                storage_changes: vec![
                    SlotChanges::new(
                        U256::from(3),
                        vec![
                            StorageChange::new(8, U256::from(0x80)),
                            StorageChange::new(2, U256::from(0x20)),
                        ],
                    ),
                    SlotChanges::new(
                        U256::from(1),
                        vec![
                            StorageChange::new(5, U256::from(0x50)),
                            StorageChange::new(1, U256::from(0x10)),
                        ],
                    ),
                ],
                storage_reads: vec![U256::from(4), U256::from(2)],
                balance_changes: vec![
                    BalanceChange::new(6, U256::from(600)),
                    BalanceChange::new(3, U256::from(300)),
                ],
                nonce_changes: vec![NonceChange::new(7, 70), NonceChange::new(4, 40)],
                code_changes: vec![
                    CodeChange::new(9, Bytes::from_static(&[0x60, 0x09])),
                    CodeChange::new(5, Bytes::from_static(&[0x60, 0x05])),
                ],
            },
            AccountChanges {
                address: address_1,
                storage_changes: vec![
                    SlotChanges::new(
                        U256::from(2),
                        vec![
                            StorageChange::new(4, U256::from(0x40)),
                            StorageChange::new(0, U256::from(0x00)),
                        ],
                    ),
                    SlotChanges::new(
                        U256::from(1),
                        vec![
                            StorageChange::new(3, U256::from(0x30)),
                            StorageChange::new(1, U256::from(0x10)),
                        ],
                    ),
                ],
                storage_reads: vec![U256::from(5), U256::from(3)],
                balance_changes: vec![
                    BalanceChange::new(5, U256::from(500)),
                    BalanceChange::new(2, U256::from(200)),
                ],
                nonce_changes: vec![NonceChange::new(8, 80), NonceChange::new(1, 10)],
                code_changes: vec![
                    CodeChange::new(4, Bytes::from_static(&[0x60, 0x04])),
                    CodeChange::new(2, Bytes::from_static(&[0x60, 0x02])),
                ],
            },
        ]);

        bal.sort();

        assert_eq!(bal[0].address, address_1);
        assert_eq!(bal[1].address, address_2);

        for account in bal.iter() {
            assert!(account.storage_changes.windows(2).all(|slots| slots[0].slot <= slots[1].slot));
            for slot_changes in &account.storage_changes {
                assert!(
                    slot_changes
                        .changes
                        .windows(2)
                        .all(|changes| changes[0].block_access_index
                            <= changes[1].block_access_index)
                );
            }
            assert!(account.storage_reads.windows(2).all(|slots| slots[0] <= slots[1]));
            assert!(
                account
                    .balance_changes
                    .windows(2)
                    .all(|changes| changes[0].block_access_index <= changes[1].block_access_index)
            );
            assert!(
                account
                    .nonce_changes
                    .windows(2)
                    .all(|changes| changes[0].block_access_index <= changes[1].block_access_index)
            );
            assert!(
                account
                    .code_changes
                    .windows(2)
                    .all(|changes| changes[0].block_access_index <= changes[1].block_access_index)
            );
        }
    }

    #[test]
    fn bal_validate_gas_limit_accepts_exact_item_cost() {
        let bal = Bal::new(vec![
            AccountChanges::new(Address::from([0x11; 20]))
                .with_storage_read(U256::from(1))
                .with_storage_change(SlotChanges::new(
                    U256::from(1),
                    vec![StorageChange::new(0, U256::from(0xaa))],
                )),
        ]);

        assert_eq!(bal.total_bal_items(), 2);
        assert_eq!(bal.validate_gas_limit(2 * ITEM_COST as u64), Ok(()));
    }

    #[test]
    fn bal_validate_gas_limit_rejects_item_cost_above_limit() {
        let bal = Bal::new(vec![
            AccountChanges::new(Address::from([0x11; 20]))
                .with_storage_read(U256::from(1))
                .with_storage_read(U256::from(2)),
        ]);
        let gas_limit = 3 * ITEM_COST as u64 - 1;

        assert_eq!(bal.total_bal_items(), 3);
        assert_eq!(
            bal.validate_gas_limit(gas_limit),
            Err(super::BlockAccessListGasError::new(3, gas_limit))
        );
    }
}

#[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_from_rlp_bytes_decodes_generic_inner_type() {
        let bal = sample_bal();
        let raw = Bytes::from(alloy_rlp::encode(&bal));
        let decoded = DecodedBal::from_rlp_bytes_as::<Vec<AccountChanges>>(raw.clone()).unwrap();

        assert_eq!(decoded.as_bal().as_slice(), bal.as_slice());
        assert_eq!(decoded.as_raw(), &raw);
        assert_eq!(decoded.hash(), bal.compute_hash());
    }

    #[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);
    }
}