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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
// Copyright 2019 Conflux Foundation. All rights reserved.
// Conflux is free software and distributed under GNU General Public License.
// See http://www.gnu.org/licenses/

mod base_price;
pub use base_price::{
    compute_next_price, compute_next_price_tuple, estimate_gas_used_boundary,
    estimate_max_possible_gas,
};

use crate::{
    block::BlockHeight, bytes::Bytes, hash::keccak, pos::PosBlockId,
    receipt::BlockReceipts, MERKLE_NULL_NODE, NULL_EPOCH,
};
use cfx_parameters::block::{cspace_block_gas_limit, espace_block_gas_limit};
use cfx_types::{
    Address, Bloom, Space, SpaceMap, H256, KECCAK_EMPTY_BLOOM, U256,
};
use malloc_size_of::{new_malloc_size_ops, MallocSizeOf, MallocSizeOfOps};
use once_cell::sync::OnceCell;
use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream};
use rlp_derive::{RlpDecodable, RlpEncodable};
use std::{
    mem,
    ops::{Deref, DerefMut},
    sync::Arc,
};

const HEADER_LIST_MIN_LEN: usize = 13;
/// The height to start fixing the wrong encoding/decoding of the `custom`
/// field.
pub static CIP112_TRANSITION_HEIGHT: OnceCell<u64> = OnceCell::new();

pub const BASE_PRICE_CHANGE_DENOMINATOR: usize = 8;

#[derive(Clone, Debug, Eq)]
pub struct BlockHeaderRlpPart {
    /// Parent hash.
    parent_hash: H256,
    /// Block height
    height: BlockHeight,
    /// Block timestamp.
    timestamp: u64,
    /// Block author.
    author: Address,
    /// Transactions root.
    transactions_root: H256,
    /// Deferred state root.
    deferred_state_root: H256,
    /// Deferred block receipts root.
    deferred_receipts_root: H256,
    /// Deferred block logs bloom hash.
    deferred_logs_bloom_hash: H256,
    /// Blame indicates the number of ancestors whose
    /// state_root/receipts_root/logs_bloom_hash/blame are not correct.
    /// It acts as a vote to help light client determining the
    /// state_root/receipts_root/logs_bloom_hash are correct or not.
    blame: u32,
    /// Block difficulty.
    difficulty: U256,
    /// Whether it is an adaptive block (from GHAST algorithm)
    adaptive: bool,
    /// Gas limit.
    gas_limit: U256,
    /// Referee hashes
    referee_hashes: Vec<H256>,
    /// Customized information
    custom: Vec<Bytes>,
    /// Nonce of the block
    nonce: U256,
    /// Referred PoS block ID.
    pos_reference: Option<H256>,
    /// `[core_space_base_price, espace_base_price]`.
    base_price: Option<BasePrice>,
}

impl PartialEq for BlockHeaderRlpPart {
    fn eq(&self, o: &BlockHeaderRlpPart) -> bool {
        self.parent_hash == o.parent_hash
            && self.height == o.height
            && self.timestamp == o.timestamp
            && self.author == o.author
            && self.transactions_root == o.transactions_root
            && self.deferred_state_root == o.deferred_state_root
            && self.deferred_receipts_root == o.deferred_receipts_root
            && self.deferred_logs_bloom_hash == o.deferred_logs_bloom_hash
            && self.blame == o.blame
            && self.difficulty == o.difficulty
            && self.adaptive == o.adaptive
            && self.gas_limit == o.gas_limit
            && self.referee_hashes == o.referee_hashes
            && self.custom == o.custom
            && self.pos_reference == o.pos_reference
            && self.base_price == o.base_price
    }
}

/// A block header.
#[derive(Clone, Debug, Eq)]
pub struct BlockHeader {
    rlp_part: BlockHeaderRlpPart,
    /// Hash of the block
    hash: Option<H256>,
    /// POW quality of the block
    pub pow_hash: Option<H256>,
    /// Approximated rlp size of the block header
    pub approximated_rlp_size: usize,
}

impl Deref for BlockHeader {
    type Target = BlockHeaderRlpPart;

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

impl DerefMut for BlockHeader {
    fn deref_mut(&mut self) -> &mut BlockHeaderRlpPart { &mut self.rlp_part }
}

impl MallocSizeOf for BlockHeader {
    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
        self.referee_hashes.size_of(ops) + self.custom.size_of(ops)
    }
}

impl PartialEq for BlockHeader {
    fn eq(&self, o: &BlockHeader) -> bool { self.rlp_part == o.rlp_part }
}

impl BlockHeader {
    /// Approximated rlp size of the block header.
    pub fn approximated_rlp_size(&self) -> usize { self.approximated_rlp_size }

    /// Get the parent_hash field of the header.
    pub fn parent_hash(&self) -> &H256 { &self.parent_hash }

    /// Get the block height
    pub fn height(&self) -> u64 { self.height }

    /// Get the timestamp field of the header.
    pub fn timestamp(&self) -> u64 { self.timestamp }

    /// Get the author field of the header.
    pub fn author(&self) -> &Address { &self.author }

    /// Get the transactions root field of the header.
    pub fn transactions_root(&self) -> &H256 { &self.transactions_root }

    /// Get the deferred state root field of the header.
    pub fn deferred_state_root(&self) -> &H256 { &self.deferred_state_root }

    /// Get the deferred block receipts root field of the header.
    pub fn deferred_receipts_root(&self) -> &H256 {
        &self.deferred_receipts_root
    }

    /// Get the deferred block logs bloom hash field of the header.
    pub fn deferred_logs_bloom_hash(&self) -> &H256 {
        &self.deferred_logs_bloom_hash
    }

    /// Get the blame field of the header
    pub fn blame(&self) -> u32 { self.blame }

    /// Get the difficulty field of the header.
    pub fn difficulty(&self) -> &U256 { &self.difficulty }

    /// Get the adaptive field of the header
    pub fn adaptive(&self) -> bool { self.adaptive }

    /// Get the gas limit field of the header.
    pub fn gas_limit(&self) -> &U256 { &self.gas_limit }

    pub fn core_space_gas_limit(&self) -> U256 {
        cspace_block_gas_limit(
            self.base_price.is_some(),
            self.gas_limit().to_owned(),
        )
    }

    pub fn espace_gas_limit(&self, can_pack: bool) -> U256 {
        espace_block_gas_limit(can_pack, self.gas_limit().to_owned())
    }

    /// Get the referee hashes field of the header.
    pub fn referee_hashes(&self) -> &Vec<H256> { &self.referee_hashes }

    /// Get the custom data field of the header.
    pub fn custom(&self) -> &Vec<Bytes> { &self.custom }

    /// Get the nonce field of the header.
    pub fn nonce(&self) -> U256 { self.nonce }

    /// Get the PoS reference.
    pub fn pos_reference(&self) -> &Option<PosBlockId> { &self.pos_reference }

    pub fn base_price(&self) -> Option<SpaceMap<U256>> {
        self.base_price.map(
            |BasePrice {
                 core_base_price,
                 espace_base_price,
             }| SpaceMap::new(core_base_price, espace_base_price),
        )
    }

    // Get the base price for the given space after 1559 hardfork.
    pub fn space_base_price(&self, space: Space) -> Option<U256> {
        self.base_price.map(|x| match space {
            Space::Native => x.core_base_price,
            Space::Ethereum => x.espace_base_price,
        })
    }

    /// Set the nonce field of the header.
    pub fn set_nonce(&mut self, nonce: U256) { self.nonce = nonce; }

    /// Set the timestamp filed of the header.
    pub fn set_timestamp(&mut self, timestamp: u64) {
        self.timestamp = timestamp;
    }

    /// Set the custom filed of the header.
    pub fn set_custom(&mut self, custom: Vec<Bytes>) { self.custom = custom; }

    /// Compute the hash of the block.
    pub fn compute_hash(&mut self) -> H256 {
        let hash = self.hash();
        self.hash = Some(hash);
        hash
    }

    /// Get the hash of the block.
    pub fn hash(&self) -> H256 {
        self.hash.unwrap_or_else(|| keccak(self.rlp()))
    }

    /// Get the hash of PoW problem.
    pub fn problem_hash(&self) -> H256 { keccak(self.rlp_without_nonce()) }

    /// Get the RLP representation of this header(except nonce).
    pub fn rlp_without_nonce(&self) -> Bytes {
        let mut stream = RlpStream::new();
        self.stream_rlp_without_nonce(&mut stream);
        stream.out()
    }

    /// Get the RLP representation of this header.
    pub fn rlp(&self) -> Bytes {
        let mut stream = RlpStream::new();
        self.stream_rlp(&mut stream);
        stream.out()
    }

    /// Place this header(except nonce) into an RLP stream `stream`.
    fn stream_rlp_without_nonce(&self, stream: &mut RlpStream) {
        let adaptive_n = if self.adaptive { 1 as u8 } else { 0 as u8 };
        let list_len = HEADER_LIST_MIN_LEN
            + self.pos_reference.is_some() as usize
            + self.base_price.is_some() as usize
            + self.custom.len();
        stream
            .begin_list(list_len)
            .append(&self.parent_hash)
            .append(&self.height)
            .append(&self.timestamp)
            .append(&self.author)
            .append(&self.transactions_root)
            .append(&self.deferred_state_root)
            .append(&self.deferred_receipts_root)
            .append(&self.deferred_logs_bloom_hash)
            .append(&self.blame)
            .append(&self.difficulty)
            .append(&adaptive_n)
            .append(&self.gas_limit)
            .append_list(&self.referee_hashes);
        if self.pos_reference.is_some() {
            stream.append(&self.pos_reference);
        }
        if self.base_price.is_some() {
            stream.append(&self.base_price);
        }

        for b in &self.custom {
            if self.height
                >= *CIP112_TRANSITION_HEIGHT.get().expect("initialized")
            {
                stream.append(b);
            } else {
                stream.append_raw(b, 1);
            }
        }
    }

    /// Place this header into an RLP stream `stream`.
    fn stream_rlp(&self, stream: &mut RlpStream) {
        let adaptive_n = if self.adaptive { 1 as u8 } else { 0 as u8 };
        let list_len = HEADER_LIST_MIN_LEN
            + 1
            + self.pos_reference.is_some() as usize
            + self.base_price.is_some() as usize
            + self.custom.len();
        stream
            .begin_list(list_len)
            .append(&self.parent_hash)
            .append(&self.height)
            .append(&self.timestamp)
            .append(&self.author)
            .append(&self.transactions_root)
            .append(&self.deferred_state_root)
            .append(&self.deferred_receipts_root)
            .append(&self.deferred_logs_bloom_hash)
            .append(&self.blame)
            .append(&self.difficulty)
            .append(&adaptive_n)
            .append(&self.gas_limit)
            .append_list(&self.referee_hashes)
            .append(&self.nonce);
        if self.pos_reference.is_some() {
            stream.append(&self.pos_reference);
        }
        if self.base_price.is_some() {
            stream.append(&self.base_price);
        }
        for b in &self.custom {
            if self.height
                >= *CIP112_TRANSITION_HEIGHT.get().expect("initialized")
            {
                stream.append(b);
            } else {
                stream.append_raw(b, 1);
            }
        }
    }

    /// Place this header and its `pow_hash` into an RLP stream `stream`.
    pub fn stream_rlp_with_pow_hash(&self, stream: &mut RlpStream) {
        let adaptive_n = if self.adaptive { 1 as u8 } else { 0 as u8 };
        let list_len = HEADER_LIST_MIN_LEN
            + 2
            + self.pos_reference.is_some() as usize
            + self.base_price.is_some() as usize
            + self.custom.len();
        stream
            .begin_list(list_len)
            .append(&self.parent_hash)
            .append(&self.height)
            .append(&self.timestamp)
            .append(&self.author)
            .append(&self.transactions_root)
            .append(&self.deferred_state_root)
            .append(&self.deferred_receipts_root)
            .append(&self.deferred_logs_bloom_hash)
            .append(&self.blame)
            .append(&self.difficulty)
            .append(&adaptive_n)
            .append(&self.gas_limit)
            .append_list(&self.referee_hashes)
            .append(&self.nonce)
            // Just encode the Option for future compatibility.
            // It should always be Some when it is being inserted to db.
            .append(&self.pow_hash);
        if self.pos_reference.is_some() {
            stream.append(&self.pos_reference);
        }
        if self.base_price.is_some() {
            stream.append(&self.base_price);
        }

        for b in &self.custom {
            if self.height
                >= *CIP112_TRANSITION_HEIGHT.get().expect("initialized")
            {
                stream.append(b);
            } else {
                stream.append_raw(b, 1);
            }
        }
    }

    pub fn decode_with_pow_hash(bytes: &[u8]) -> Result<Self, DecoderError> {
        let r = Rlp::new(bytes);
        let mut rlp_part = BlockHeaderRlpPart {
            parent_hash: r.val_at(0)?,
            height: r.val_at(1)?,
            timestamp: r.val_at(2)?,
            author: r.val_at(3)?,
            transactions_root: r.val_at(4)?,
            deferred_state_root: r.val_at(5)?,
            deferred_receipts_root: r.val_at(6)?,
            deferred_logs_bloom_hash: r.val_at(7)?,
            blame: r.val_at(8)?,
            difficulty: r.val_at(9)?,
            adaptive: r.val_at::<u8>(10)? == 1,
            gas_limit: r.val_at(11)?,
            referee_hashes: r.list_at(12)?,
            custom: vec![],
            nonce: r.val_at(13)?,
            pos_reference: r.val_at(15).unwrap_or(None),
            base_price: r.val_at(16).unwrap_or(None),
        };
        let pow_hash = r.val_at(14)?;

        for i in (15
            + rlp_part.pos_reference.is_some() as usize
            + rlp_part.base_price.is_some() as usize)
            ..r.item_count()?
        {
            if rlp_part.height
                >= *CIP112_TRANSITION_HEIGHT.get().expect("initialized")
            {
                rlp_part.custom.push(r.val_at(i)?);
            } else {
                rlp_part.custom.push(r.at(i)?.as_raw().to_vec());
            }
        }

        let mut header = BlockHeader {
            rlp_part,
            hash: None,
            pow_hash,
            approximated_rlp_size: bytes.len(),
        };
        header.compute_hash();
        Ok(header)
    }

    pub fn size(&self) -> usize {
        // FIXME: We need to revisit the size of block header once we finished
        // the persistent storage part
        0
    }
}

pub struct BlockHeaderBuilder {
    parent_hash: H256,
    height: u64,
    timestamp: u64,
    author: Address,
    transactions_root: H256,
    deferred_state_root: H256,
    deferred_receipts_root: H256,
    deferred_logs_bloom_hash: H256,
    blame: u32,
    difficulty: U256,
    adaptive: bool,
    gas_limit: U256,
    referee_hashes: Vec<H256>,
    custom: Vec<Bytes>,
    nonce: U256,
    pos_reference: Option<PosBlockId>,
    base_price: Option<BasePrice>,
}

impl BlockHeaderBuilder {
    pub fn new() -> Self {
        Self {
            parent_hash: NULL_EPOCH,
            height: 0,
            timestamp: 0,
            author: Address::default(),
            transactions_root: MERKLE_NULL_NODE,
            deferred_state_root: Default::default(),
            deferred_receipts_root: Default::default(),
            deferred_logs_bloom_hash: KECCAK_EMPTY_BLOOM,
            blame: 0,
            difficulty: U256::default(),
            adaptive: false,
            gas_limit: U256::zero(),
            referee_hashes: Vec::new(),
            custom: Vec::new(),
            nonce: U256::zero(),
            pos_reference: None,
            base_price: None,
        }
    }

    pub fn with_parent_hash(&mut self, parent_hash: H256) -> &mut Self {
        self.parent_hash = parent_hash;
        self
    }

    pub fn with_height(&mut self, height: u64) -> &mut Self {
        self.height = height;
        self
    }

    pub fn with_timestamp(&mut self, timestamp: u64) -> &mut Self {
        self.timestamp = timestamp;
        self
    }

    pub fn with_author(&mut self, author: Address) -> &mut Self {
        self.author = author;
        self
    }

    pub fn with_transactions_root(
        &mut self, transactions_root: H256,
    ) -> &mut Self {
        self.transactions_root = transactions_root;
        self
    }

    pub fn with_deferred_state_root(
        &mut self, deferred_state_root: H256,
    ) -> &mut Self {
        self.deferred_state_root = deferred_state_root;
        self
    }

    pub fn with_deferred_receipts_root(
        &mut self, deferred_receipts_root: H256,
    ) -> &mut Self {
        self.deferred_receipts_root = deferred_receipts_root;
        self
    }

    pub fn with_deferred_logs_bloom_hash(
        &mut self, deferred_logs_bloom_hash: H256,
    ) -> &mut Self {
        self.deferred_logs_bloom_hash = deferred_logs_bloom_hash;
        self
    }

    pub fn with_blame(&mut self, blame: u32) -> &mut Self {
        self.blame = blame;
        self
    }

    pub fn with_difficulty(&mut self, difficulty: U256) -> &mut Self {
        self.difficulty = difficulty;
        self
    }

    pub fn with_adaptive(&mut self, adaptive: bool) -> &mut Self {
        self.adaptive = adaptive;
        self
    }

    pub fn with_gas_limit(&mut self, gas_limit: U256) -> &mut Self {
        self.gas_limit = gas_limit;
        self
    }

    pub fn with_referee_hashes(
        &mut self, referee_hashes: Vec<H256>,
    ) -> &mut Self {
        self.referee_hashes = referee_hashes;
        self
    }

    pub fn with_custom(&mut self, custom: Vec<Bytes>) -> &mut Self {
        self.custom = custom;
        self
    }

    pub fn with_nonce(&mut self, nonce: U256) -> &mut Self {
        self.nonce = nonce;
        self
    }

    pub fn with_pos_reference(
        &mut self, pos_reference: Option<PosBlockId>,
    ) -> &mut Self {
        self.pos_reference = pos_reference;
        self
    }

    pub fn with_base_price(
        &mut self, maybe_base_price: Option<SpaceMap<U256>>,
    ) -> &mut Self {
        self.base_price = maybe_base_price.map(|x| BasePrice {
            core_base_price: x[Space::Native],
            espace_base_price: x[Space::Ethereum],
        });
        self
    }

    pub fn build(&self) -> BlockHeader {
        let mut block_header = BlockHeader {
            rlp_part: BlockHeaderRlpPart {
                parent_hash: self.parent_hash,
                height: self.height,
                timestamp: self.timestamp,
                author: self.author,
                transactions_root: self.transactions_root,
                deferred_state_root: self.deferred_state_root,
                deferred_receipts_root: self.deferred_receipts_root,
                deferred_logs_bloom_hash: self.deferred_logs_bloom_hash,
                blame: self.blame,
                difficulty: self.difficulty,
                adaptive: self.adaptive,
                gas_limit: self.gas_limit,
                referee_hashes: self.referee_hashes.clone(),
                custom: self.custom.clone(),
                nonce: self.nonce,
                pos_reference: self.pos_reference,
                base_price: self.base_price.clone(),
            },
            hash: None,
            pow_hash: None,
            approximated_rlp_size: 0,
        };

        block_header.approximated_rlp_size =
            mem::size_of::<BlockHeaderRlpPart>()
                + block_header
                    .referee_hashes
                    .size_of(&mut new_malloc_size_ops());

        block_header
    }

    pub fn compute_block_logs_bloom_hash(
        receipts: &Vec<Arc<BlockReceipts>>,
    ) -> H256 {
        let bloom = receipts.iter().map(|x| &x.receipts).flatten().fold(
            Bloom::zero(),
            |mut b, r| {
                b.accrue_bloom(&r.log_bloom);
                b
            },
        );

        keccak(bloom)
    }

    pub fn compute_aggregated_bloom(blooms: Vec<Bloom>) -> Bloom {
        blooms.into_iter().fold(Bloom::zero(), |mut res, bloom| {
            res.accrue_bloom(&bloom);
            res
        })
    }

    pub fn compute_blame_state_root_vec_root(roots: Vec<H256>) -> H256 {
        let mut accumulated_root = roots.last().unwrap().clone();
        for i in (0..(roots.len() - 1)).rev() {
            accumulated_root =
                BlockHeaderBuilder::compute_blame_state_root_incremental(
                    roots[i],
                    accumulated_root,
                );
        }
        accumulated_root
    }

    pub fn compute_blame_state_root_incremental(
        first_root: H256, remaining_root: H256,
    ) -> H256 {
        let mut buffer = Vec::with_capacity(H256::len_bytes() * 2);
        buffer.extend_from_slice(first_root.as_bytes());
        buffer.extend_from_slice(remaining_root.as_bytes());
        keccak(&buffer)
    }
}

impl Encodable for BlockHeader {
    fn rlp_append(&self, stream: &mut RlpStream) { self.stream_rlp(stream); }
}

impl Decodable for BlockHeader {
    fn decode(r: &Rlp) -> Result<Self, DecoderError> {
        let rlp_size = r.as_raw().len();
        let mut rlp_part = BlockHeaderRlpPart {
            parent_hash: r.val_at(0)?,
            height: r.val_at(1)?,
            timestamp: r.val_at(2)?,
            author: r.val_at(3)?,
            transactions_root: r.val_at(4)?,
            deferred_state_root: r.val_at(5)?,
            deferred_receipts_root: r.val_at(6)?,
            deferred_logs_bloom_hash: r.val_at(7)?,
            blame: r.val_at(8)?,
            difficulty: r.val_at(9)?,
            adaptive: r.val_at::<u8>(10)? == 1,
            gas_limit: r.val_at(11)?,
            referee_hashes: r.list_at(12)?,
            custom: vec![],
            nonce: r.val_at(13)?,
            pos_reference: r.val_at(14).unwrap_or(None),
            base_price: r.val_at(15).unwrap_or(None),
        };
        for i in (14
            + rlp_part.pos_reference.is_some() as usize
            + rlp_part.base_price.is_some() as usize)
            ..r.item_count()?
        {
            if rlp_part.height
                >= *CIP112_TRANSITION_HEIGHT.get().expect("initialized")
            {
                rlp_part.custom.push(r.val_at(i)?);
            } else {
                rlp_part.custom.push(r.at(i)?.as_raw().to_vec());
            }
        }

        let mut header = BlockHeader {
            rlp_part,
            hash: None,
            pow_hash: None,
            approximated_rlp_size: rlp_size,
        };
        header.compute_hash();

        Ok(header)
    }
}

#[derive(Clone, Copy, Debug, Eq, RlpDecodable, RlpEncodable, PartialEq)]
pub struct BasePrice {
    pub core_base_price: U256,
    pub espace_base_price: U256,
}
#[cfg(test)]
mod tests {
    use super::BlockHeaderBuilder;
    use crate::{
        hash::keccak,
        receipt::{BlockReceipts, Receipt},
        TransactionStatus,
    };
    use cfx_types::{Bloom, KECCAK_EMPTY_BLOOM, U256};
    use std::{str::FromStr, sync::Arc};

    #[test]
    fn test_logs_bloom_hash_no_receipts() {
        let receipts = vec![]; // Vec<_>
        let hash = BlockHeaderBuilder::compute_block_logs_bloom_hash(&receipts);
        assert_eq!(hash, KECCAK_EMPTY_BLOOM);

        let receipts = (1..11)
            .map(|_| {
                Arc::new(BlockReceipts {
                    receipts: vec![],
                    block_number: 0,
                    secondary_reward: U256::zero(),
                    tx_execution_error_messages: vec![],
                })
            })
            .collect(); // Vec<Arc<Vec<_>>>
        let hash = BlockHeaderBuilder::compute_block_logs_bloom_hash(&receipts);
        assert_eq!(hash, KECCAK_EMPTY_BLOOM);
    }

    #[test]
    fn test_logs_bloom_hash_empty_receipts() {
        let receipt = Receipt {
            accumulated_gas_used: U256::zero(),
            gas_fee: U256::zero(),
            gas_sponsor_paid: false,
            logs: vec![],
            outcome_status: TransactionStatus::Success,
            log_bloom: Bloom::zero(),
            storage_sponsor_paid: false,
            storage_collateralized: vec![],
            storage_released: vec![],
            burnt_gas_fee: None,
        };

        // 10 blocks with 10 empty receipts each
        let receipts = (1..11)
            .map(|_| {
                Arc::new(BlockReceipts {
                    receipts: (1..11).map(|_| receipt.clone()).collect(),
                    block_number: 0,
                    secondary_reward: U256::zero(),
                    tx_execution_error_messages: vec!["".into(); 10],
                })
            })
            .collect();
        let hash = BlockHeaderBuilder::compute_block_logs_bloom_hash(&receipts);
        assert_eq!(hash, KECCAK_EMPTY_BLOOM);
    }

    #[test]
    fn test_logs_bloom_hash() {
        let block1 = BlockReceipts {
            receipts: vec![
                Receipt {
                    accumulated_gas_used: 0.into(),
                    gas_fee: 0.into(),
                    gas_sponsor_paid: false,
                    logs: vec![],
                    outcome_status: TransactionStatus::Success,
                    log_bloom: Bloom::from_str(
                        "11111111111111111111111111111111\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000",
                    )
                    .unwrap(),
                    storage_sponsor_paid: false,
                    storage_collateralized: vec![],
                    storage_released: vec![],
                    burnt_gas_fee: None,
                },
                Receipt {
                    accumulated_gas_used: U256::zero(),
                    gas_fee: U256::zero(),
                    gas_sponsor_paid: false,
                    logs: vec![],
                    outcome_status: TransactionStatus::Success,
                    log_bloom: Bloom::from_str(
                        "00000000000000000000000000000000\
                         22222222222222222222222222222222\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000\
                         00000000000000000000000000000000",
                    )
                    .unwrap(),
                    storage_sponsor_paid: false,
                    storage_collateralized: vec![],
                    storage_released: vec![],
                    burnt_gas_fee: None,
                },
            ],
            block_number: 0,
            secondary_reward: U256::zero(),
            tx_execution_error_messages: vec!["".into(); 2],
        };

        let block2 = BlockReceipts {
            receipts: vec![Receipt {
                accumulated_gas_used: U256::zero(),
                gas_fee: U256::zero(),
                gas_sponsor_paid: false,
                logs: vec![],
                outcome_status: TransactionStatus::Success,
                log_bloom: Bloom::from_str(
                    "44444444444444440000000000000000\
                     44444444444444440000000000000000\
                     44444444444444440000000000000000\
                     44444444444444440000000000000000\
                     00000000000000000000000000000000\
                     00000000000000000000000000000000\
                     00000000000000000000000000000000\
                     00000000000000000000000000000000\
                     00000000000000000000000000000000\
                     00000000000000000000000000000000\
                     00000000000000000000000000000000\
                     00000000000000000000000000000000\
                     00000000000000000000000000000000\
                     00000000000000000000000000000000\
                     00000000000000000000000000000000\
                     00000000000000000000000000000000",
                )
                .unwrap(),
                storage_sponsor_paid: false,
                storage_collateralized: vec![],
                storage_released: vec![],
                burnt_gas_fee: None,
            }],
            block_number: 0,
            secondary_reward: U256::zero(),
            tx_execution_error_messages: vec!["".into()],
        };

        let expected = keccak(
            "55555555555555551111111111111111\
             66666666666666662222222222222222\
             44444444444444440000000000000000\
             44444444444444440000000000000000\
             00000000000000000000000000000000\
             00000000000000000000000000000000\
             00000000000000000000000000000000\
             00000000000000000000000000000000\
             00000000000000000000000000000000\
             00000000000000000000000000000000\
             00000000000000000000000000000000\
             00000000000000000000000000000000\
             00000000000000000000000000000000\
             00000000000000000000000000000000\
             00000000000000000000000000000000\
             00000000000000000000000000000000"
                .parse::<Bloom>()
                .unwrap(),
        );

        let receipts = vec![Arc::new(block1), Arc::new(block2)];
        let hash = BlockHeaderBuilder::compute_block_logs_bloom_hash(&receipts);
        assert_eq!(hash, expected);
    }
}