-
Notifications
You must be signed in to change notification settings - Fork 773
/
header.ts
1067 lines (982 loc) · 33.7 KB
/
header.ts
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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Common, { Chain, ConsensusAlgorithm, ConsensusType, Hardfork } from '@ethereumjs/common'
import {
Address,
BN,
bnToHex,
bnToUnpaddedBuffer,
ecrecover,
ecsign,
intToBuffer,
KECCAK256_RLP_ARRAY,
KECCAK256_RLP,
rlp,
rlphash,
toBuffer,
zeros,
bufferToHex,
} from 'ethereumjs-util'
import { Blockchain, BlockHeaderBuffer, BlockOptions, HeaderData, JsonHeader } from './types'
import {
CLIQUE_EXTRA_VANITY,
CLIQUE_EXTRA_SEAL,
CLIQUE_DIFF_INTURN,
CLIQUE_DIFF_NOTURN,
} from './clique'
interface HeaderCache {
hash: Buffer | undefined
}
const DEFAULT_GAS_LIMIT = new BN(Buffer.from('ffffffffffffff', 'hex'))
/**
* An object that represents the block header.
*/
export class BlockHeader {
public readonly parentHash: Buffer
public readonly uncleHash: Buffer
public readonly coinbase: Address
public readonly stateRoot: Buffer
public readonly transactionsTrie: Buffer
public readonly receiptTrie: Buffer
public readonly logsBloom: Buffer
public readonly difficulty: BN
public readonly number: BN
public readonly gasLimit: BN
public readonly gasUsed: BN
public readonly timestamp: BN
public readonly extraData: Buffer
public readonly mixHash: Buffer
public readonly nonce: Buffer
public readonly baseFeePerGas?: BN
public readonly _common: Common
private cache: HeaderCache = {
hash: undefined,
}
/**
* Backwards compatible alias for {@link BlockHeader.logsBloom}
* (planned to be removed in next major release)
* @deprecated
*/
get bloom() {
return this.logsBloom
}
/**
* EIP-4399: Post-PoS merge, `mixHash` supplanted as `random`
*/
get random() {
if (!this._common.isActivatedEIP(4399)) {
const msg = this._errorMsg(
'The random parameter can only be accessed when EIP-4399 is activated'
)
throw new Error(msg)
}
return this.mixHash
}
/**
* Static constructor to create a block header from a header data dictionary
*
* @param headerData
* @param opts
*/
public static fromHeaderData(headerData: HeaderData = {}, opts: BlockOptions = {}) {
if (headerData.logsBloom === undefined && headerData.bloom !== undefined) {
// backwards compatible alias for deprecated `bloom` key renamed to `logsBloom`
// (planned to be removed in next major release)
headerData.logsBloom = headerData.bloom
}
const {
parentHash,
uncleHash,
coinbase,
stateRoot,
transactionsTrie,
receiptTrie,
logsBloom,
difficulty,
number,
gasLimit,
gasUsed,
timestamp,
extraData,
mixHash,
nonce,
baseFeePerGas,
} = headerData
return new BlockHeader(
parentHash ? toBuffer(parentHash) : zeros(32),
uncleHash ? toBuffer(uncleHash) : KECCAK256_RLP_ARRAY,
coinbase ? new Address(toBuffer(coinbase)) : Address.zero(),
stateRoot ? toBuffer(stateRoot) : zeros(32),
transactionsTrie ? toBuffer(transactionsTrie) : KECCAK256_RLP,
receiptTrie ? toBuffer(receiptTrie) : KECCAK256_RLP,
logsBloom ? toBuffer(logsBloom) : zeros(256),
difficulty ? new BN(toBuffer(difficulty)) : new BN(0),
number ? new BN(toBuffer(number)) : new BN(0),
gasLimit ? new BN(toBuffer(gasLimit)) : DEFAULT_GAS_LIMIT,
gasUsed ? new BN(toBuffer(gasUsed)) : new BN(0),
timestamp ? new BN(toBuffer(timestamp)) : new BN(0),
extraData ? toBuffer(extraData) : Buffer.from([]),
mixHash ? toBuffer(mixHash) : zeros(32),
nonce ? toBuffer(nonce) : zeros(8),
opts,
baseFeePerGas !== undefined && baseFeePerGas !== null
? new BN(toBuffer(baseFeePerGas))
: undefined
)
}
/**
* Static constructor to create a block header from a RLP-serialized header
*
* @param headerData
* @param opts
*/
public static fromRLPSerializedHeader(serialized: Buffer, opts: BlockOptions = {}) {
const values = rlp.decode(serialized)
if (!Array.isArray(values)) {
throw new Error('Invalid serialized header input. Must be array')
}
return BlockHeader.fromValuesArray(values, opts)
}
/**
* Static constructor to create a block header from an array of Buffer values
*
* @param headerData
* @param opts
*/
public static fromValuesArray(values: BlockHeaderBuffer, opts: BlockOptions = {}) {
const [
parentHash,
uncleHash,
coinbase,
stateRoot,
transactionsTrie,
receiptTrie,
logsBloom,
difficulty,
number,
gasLimit,
gasUsed,
timestamp,
extraData,
mixHash,
nonce,
baseFeePerGas,
] = values
if (values.length > 16) {
throw new Error('invalid header. More values than expected were received')
}
if (values.length < 15) {
throw new Error('invalid header. Less values than expected were received')
}
return new BlockHeader(
toBuffer(parentHash),
toBuffer(uncleHash),
new Address(toBuffer(coinbase)),
toBuffer(stateRoot),
toBuffer(transactionsTrie),
toBuffer(receiptTrie),
toBuffer(logsBloom),
new BN(toBuffer(difficulty)),
new BN(toBuffer(number)),
new BN(toBuffer(gasLimit)),
new BN(toBuffer(gasUsed)),
new BN(toBuffer(timestamp)),
toBuffer(extraData),
toBuffer(mixHash),
toBuffer(nonce),
opts,
baseFeePerGas !== undefined && baseFeePerGas !== null
? new BN(toBuffer(baseFeePerGas))
: undefined
)
}
/**
* Alias for {@link BlockHeader.fromHeaderData} with {@link BlockOptions.initWithGenesisHeader} set to true.
*/
public static genesis(headerData: HeaderData = {}, opts?: BlockOptions) {
opts = { ...opts, initWithGenesisHeader: true }
return BlockHeader.fromHeaderData(headerData, opts)
}
/**
* This constructor takes the values, validates them, assigns them and freezes the object.
*
* @deprecated - Use the public static factory methods to assist in creating a Header object from
* varying data types. For a default empty header, use {@link BlockHeader.fromHeaderData}.
*
*/
constructor(
parentHash: Buffer,
uncleHash: Buffer,
coinbase: Address,
stateRoot: Buffer,
transactionsTrie: Buffer,
receiptTrie: Buffer,
logsBloom: Buffer,
difficulty: BN,
number: BN,
gasLimit: BN,
gasUsed: BN,
timestamp: BN,
extraData: Buffer,
mixHash: Buffer,
nonce: Buffer,
options: BlockOptions = {},
baseFeePerGas?: BN
) {
if (options.common) {
this._common = options.common.copy()
} else {
this._common = new Common({
chain: Chain.Mainnet, // default
})
if (options.initWithGenesisHeader) {
this._common.setHardforkByBlockNumber(0)
}
}
if (options.hardforkByBlockNumber !== undefined && options.hardforkByTD !== undefined) {
throw new Error(
`The hardforkByBlockNumber and hardforkByTD options can't be used in conjunction`
)
}
const hardforkByBlockNumber = options.hardforkByBlockNumber ?? false
if (hardforkByBlockNumber || options.hardforkByTD !== undefined) {
this._common.setHardforkByBlockNumber(number, options.hardforkByTD)
}
if (this._common.isActivatedEIP(1559)) {
if (baseFeePerGas === undefined) {
const londonHfBlock = this._common.hardforkBlockBN(Hardfork.London)
const isInitialEIP1559Block = londonHfBlock && number.eq(londonHfBlock)
if (isInitialEIP1559Block) {
baseFeePerGas = new BN(this._common.param('gasConfig', 'initialBaseFee'))
} else {
// Minimum possible value for baseFeePerGas is 7,
// so we use it as the default if the field is missing.
baseFeePerGas = new BN(7)
}
}
} else {
if (baseFeePerGas) {
throw new Error('A base fee for a block can only be set with EIP1559 being activated')
}
}
if (options.initWithGenesisHeader) {
number = new BN(0)
if (gasLimit.eq(DEFAULT_GAS_LIMIT)) {
gasLimit = new BN(toBuffer(this._common.genesis().gasLimit))
}
if (timestamp.isZero()) {
timestamp = new BN(toBuffer(this._common.genesis().timestamp))
}
if (difficulty.isZero()) {
difficulty = new BN(toBuffer(this._common.genesis().difficulty))
}
if (extraData.length === 0) {
extraData = toBuffer(this._common.genesis().extraData)
}
if (nonce.equals(zeros(8))) {
nonce = toBuffer(this._common.genesis().nonce)
}
if (stateRoot.equals(zeros(32))) {
stateRoot = toBuffer(this._common.genesis().stateRoot)
}
if (
this._common.gteHardfork(Hardfork.London) &&
this._common.genesis().baseFeePerGas !== undefined
) {
baseFeePerGas = new BN(toBuffer(this._common.genesis().baseFeePerGas))
}
}
this.parentHash = parentHash
this.uncleHash = uncleHash
this.coinbase = coinbase
this.stateRoot = stateRoot
this.transactionsTrie = transactionsTrie
this.receiptTrie = receiptTrie
this.logsBloom = logsBloom
this.difficulty = difficulty
this.number = number
this.gasLimit = gasLimit
this.gasUsed = gasUsed
this.timestamp = timestamp
this.extraData = extraData
this.mixHash = mixHash
this.nonce = nonce
this.baseFeePerGas = baseFeePerGas
this._validateHeaderFields()
this._validateDAOExtraData()
// Now we have set all the values of this Header, we possibly have set a dummy
// `difficulty` value (defaults to 0). If we have a `calcDifficultyFromHeader`
// block option parameter, we instead set difficulty to this value.
if (
options.calcDifficultyFromHeader &&
this._common.consensusAlgorithm() === ConsensusAlgorithm.Ethash
) {
this.difficulty = this.canonicalDifficulty(options.calcDifficultyFromHeader)
}
// If cliqueSigner is provided, seal block with provided privateKey.
if (options.cliqueSigner) {
// Ensure extraData is at least length CLIQUE_EXTRA_VANITY + CLIQUE_EXTRA_SEAL
const minExtraDataLength = CLIQUE_EXTRA_VANITY + CLIQUE_EXTRA_SEAL
if (this.extraData.length < minExtraDataLength) {
const remainingLength = minExtraDataLength - this.extraData.length
this.extraData = Buffer.concat([this.extraData, Buffer.alloc(remainingLength)])
}
this.extraData = this.cliqueSealBlock(options.cliqueSigner)
}
const freeze = options?.freeze ?? true
if (freeze) {
Object.freeze(this)
}
}
/**
* Validates correct buffer lengths, throws if invalid.
*/
_validateHeaderFields() {
const {
parentHash,
uncleHash,
stateRoot,
transactionsTrie,
receiptTrie,
difficulty,
extraData,
mixHash,
nonce,
} = this
if (parentHash.length !== 32) {
const msg = this._errorMsg(`parentHash must be 32 bytes, received ${parentHash.length} bytes`)
throw new Error(msg)
}
if (stateRoot.length !== 32) {
const msg = this._errorMsg(`stateRoot must be 32 bytes, received ${stateRoot.length} bytes`)
throw new Error(msg)
}
if (transactionsTrie.length !== 32) {
const msg = this._errorMsg(
`transactionsTrie must be 32 bytes, received ${transactionsTrie.length} bytes`
)
throw new Error(msg)
}
if (receiptTrie.length !== 32) {
const msg = this._errorMsg(
`receiptTrie must be 32 bytes, received ${receiptTrie.length} bytes`
)
throw new Error(msg)
}
if (mixHash.length !== 32) {
const msg = this._errorMsg(`mixHash must be 32 bytes, received ${mixHash.length} bytes`)
throw new Error(msg)
}
if (nonce.length !== 8) {
// Hack to check for Kovan due to non-standard nonce length (65 bytes)
if (this._common.networkIdBN().eqn(42)) {
if (nonce.length !== 65) {
const msg = this._errorMsg(
`nonce must be 65 bytes on kovan, received ${nonce.length} bytes`
)
throw new Error(msg)
}
} else {
const msg = this._errorMsg(`nonce must be 8 bytes, received ${nonce.length} bytes`)
throw new Error(msg)
}
}
// Validation for PoS blocks (EIP-3675)
if (this._common.consensusType() === ConsensusType.ProofOfStake) {
let error = false
let errorMsg = ''
if (!uncleHash.equals(KECCAK256_RLP_ARRAY)) {
errorMsg += `, uncleHash: ${uncleHash.toString(
'hex'
)} (expected: ${KECCAK256_RLP_ARRAY.toString('hex')})`
error = true
}
if (!difficulty.eq(new BN(0))) {
errorMsg += `, difficulty: ${difficulty} (expected: 0)`
error = true
}
if (extraData.length > 32) {
errorMsg += `, extraData: ${extraData.toString(
'hex'
)} (cannot exceed 32 bytes length, received ${extraData.length} bytes)`
error = true
}
if (!nonce.equals(zeros(8))) {
errorMsg += `, nonce: ${nonce.toString('hex')} (expected: ${zeros(8).toString('hex')})`
error = true
}
if (error) {
const msg = this._errorMsg(`Invalid PoS block${errorMsg}`)
throw new Error(msg)
}
}
}
/**
* Returns the canonical difficulty for this block.
*
* @param parentBlockHeader - the header from the parent `Block` of this header
*/
canonicalDifficulty(parentBlockHeader: BlockHeader): BN {
if (this._common.consensusType() !== ConsensusType.ProofOfWork) {
const msg = this._errorMsg('difficulty calculation is only supported on PoW chains')
throw new Error(msg)
}
if (this._common.consensusAlgorithm() !== ConsensusAlgorithm.Ethash) {
const msg = this._errorMsg(
'difficulty calculation currently only supports the ethash algorithm'
)
throw new Error(msg)
}
const hardfork = this._getHardfork()
const blockTs = this.timestamp
const { timestamp: parentTs, difficulty: parentDif } = parentBlockHeader
const minimumDifficulty = new BN(
this._common.paramByHardfork('pow', 'minimumDifficulty', hardfork)
)
const offset = parentDif.div(
new BN(this._common.paramByHardfork('pow', 'difficultyBoundDivisor', hardfork))
)
let num = this.number.clone()
// We use a ! here as TS cannot follow this hardfork-dependent logic, but it always gets assigned
let dif!: BN
if (this._common.hardforkGteHardfork(hardfork, Hardfork.Byzantium)) {
// max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99) (EIP100)
const uncleAddend = parentBlockHeader.uncleHash.equals(KECCAK256_RLP_ARRAY) ? 1 : 2
let a = blockTs.sub(parentTs).idivn(9).ineg().iaddn(uncleAddend)
const cutoff = new BN(-99)
// MAX(cutoff, a)
if (cutoff.gt(a)) {
a = cutoff
}
dif = parentDif.add(offset.mul(a))
}
if (this._common.hardforkGteHardfork(hardfork, Hardfork.Byzantium)) {
// Get delay as parameter from common
num.isubn(this._common.param('pow', 'difficultyBombDelay'))
if (num.ltn(0)) {
num = new BN(0)
}
} else if (this._common.hardforkGteHardfork(hardfork, Hardfork.Homestead)) {
// 1 - (block_timestamp - parent_timestamp) // 10
let a = blockTs.sub(parentTs).idivn(10).ineg().iaddn(1)
const cutoff = new BN(-99)
// MAX(cutoff, a)
if (cutoff.gt(a)) {
a = cutoff
}
dif = parentDif.add(offset.mul(a))
} else {
// pre-homestead
if (
parentTs.addn(this._common.paramByHardfork('pow', 'durationLimit', hardfork)).gt(blockTs)
) {
dif = offset.add(parentDif)
} else {
dif = parentDif.sub(offset)
}
}
const exp = num.divn(100000).isubn(2)
if (!exp.isNeg()) {
dif.iadd(new BN(2).pow(exp))
}
if (dif.lt(minimumDifficulty)) {
dif = minimumDifficulty
}
return dif
}
/**
* Checks that the block's `difficulty` matches the canonical difficulty.
*
* @param parentBlockHeader - the header from the parent `Block` of this header
*/
validateDifficulty(parentBlockHeader: BlockHeader): boolean {
return this.canonicalDifficulty(parentBlockHeader).eq(this.difficulty)
}
/**
* For poa, validates `difficulty` is correctly identified as INTURN or NOTURN.
* Returns false if invalid.
*/
validateCliqueDifficulty(blockchain: Blockchain): boolean {
this._requireClique('validateCliqueDifficulty')
if (!this.difficulty.eq(CLIQUE_DIFF_INTURN) && !this.difficulty.eq(CLIQUE_DIFF_NOTURN)) {
const msg = this._errorMsg(
`difficulty for clique block must be INTURN (2) or NOTURN (1), received: ${this.difficulty}`
)
throw new Error(msg)
}
if ('cliqueActiveSigners' in blockchain === false) {
const msg = this._errorMsg(
'PoA blockchain requires method blockchain.cliqueActiveSigners() to validate clique difficulty'
)
throw new Error(msg)
}
const signers = (blockchain as any).cliqueActiveSigners()
if (signers.length === 0) {
// abort if signers are unavailable
return true
}
const signerIndex = signers.findIndex((address: Address) => address.equals(this.cliqueSigner()))
const inTurn = this.number.modn(signers.length) === signerIndex
if (
(inTurn && this.difficulty.eq(CLIQUE_DIFF_INTURN)) ||
(!inTurn && this.difficulty.eq(CLIQUE_DIFF_NOTURN))
) {
return true
}
return false
}
/**
* Validates if the block gasLimit remains in the
* boundaries set by the protocol.
*
* @param parentBlockHeader - the header from the parent `Block` of this header
*/
validateGasLimit(parentBlockHeader: BlockHeader): boolean {
let parentGasLimit = parentBlockHeader.gasLimit
// EIP-1559: assume double the parent gas limit on fork block
// to adopt to the new gas target centered logic
const londonHardforkBlock = this._common.hardforkBlockBN(Hardfork.London)
if (londonHardforkBlock && this.number.eq(londonHardforkBlock)) {
const elasticity = new BN(this._common.param('gasConfig', 'elasticityMultiplier'))
parentGasLimit = parentGasLimit.mul(elasticity)
}
const gasLimit = this.gasLimit
const hardfork = this._getHardfork()
const a = parentGasLimit.div(
new BN(this._common.paramByHardfork('gasConfig', 'gasLimitBoundDivisor', hardfork))
)
const maxGasLimit = parentGasLimit.add(a)
const minGasLimit = parentGasLimit.sub(a)
const result =
gasLimit.lt(maxGasLimit) &&
gasLimit.gt(minGasLimit) &&
gasLimit.gte(this._common.paramByHardfork('gasConfig', 'minGasLimit', hardfork))
return result
}
/**
* Validates the block header, throwing if invalid. It is being validated against the reported `parentHash`.
* It verifies the current block against the `parentHash`:
* - The `parentHash` is part of the blockchain (it is a valid header)
* - Current block number is parent block number + 1
* - Current block has a strictly higher timestamp
* - Additional PoW checks ->
* - Current block has valid difficulty and gas limit
* - In case that the header is an uncle header, it should not be too old or young in the chain.
* - Additional PoA clique checks ->
* - Various extraData checks
* - Checks on coinbase and mixHash
* - Current block has a timestamp diff greater or equal to PERIOD
* - Current block has difficulty correctly marked as INTURN or NOTURN
* @param blockchain - validate against an @ethereumjs/blockchain
* @param height - If this is an uncle header, this is the height of the block that is including it
*/
async validate(blockchain: Blockchain, height?: BN): Promise<void> {
if (this.isGenesis()) {
return
}
const hardfork = this._getHardfork()
// Consensus type dependent checks
if (this._common.consensusAlgorithm() === ConsensusAlgorithm.Ethash) {
// PoW/Ethash
if (
this.extraData.length > this._common.paramByHardfork('vm', 'maxExtraDataSize', hardfork)
) {
const msg = this._errorMsg('invalid amount of extra data')
throw new Error(msg)
}
}
if (this._common.consensusAlgorithm() === ConsensusAlgorithm.Clique) {
// PoA/Clique
const minLength = CLIQUE_EXTRA_VANITY + CLIQUE_EXTRA_SEAL
if (!this.cliqueIsEpochTransition()) {
// ExtraData length on epoch transition
if (this.extraData.length !== minLength) {
const msg = this._errorMsg(
`extraData must be ${minLength} bytes on non-epoch transition blocks, received ${this.extraData.length} bytes`
)
throw new Error(msg)
}
} else {
const signerLength = this.extraData.length - minLength
if (signerLength % 20 !== 0) {
const msg = this._errorMsg(
`invalid signer list length in extraData, received signer length of ${signerLength} (not divisible by 20)`
)
throw new Error(msg)
}
// coinbase (beneficiary) on epoch transition
if (!this.coinbase.isZero()) {
const msg = this._errorMsg(
`coinbase must be filled with zeros on epoch transition blocks, received ${this.coinbase}`
)
throw new Error(msg)
}
}
// MixHash format
if (!this.mixHash.equals(Buffer.alloc(32))) {
const msg = this._errorMsg(`mixHash must be filled with zeros, received ${this.mixHash}`)
throw new Error(msg)
}
if (!this.validateCliqueDifficulty(blockchain)) {
const msg = this._errorMsg(`invalid clique difficulty`)
throw new Error(msg)
}
}
const parentHeader = await this._getHeaderByHash(blockchain, this.parentHash)
if (!parentHeader) {
const msg = this._errorMsg('could not find parent header')
throw new Error(msg)
}
const { number } = this
if (!number.eq(parentHeader.number.addn(1))) {
const msg = this._errorMsg('invalid number')
throw new Error(msg)
}
if (this.timestamp.lte(parentHeader.timestamp)) {
const msg = this._errorMsg('invalid timestamp')
throw new Error(msg)
}
if (this._common.consensusAlgorithm() === ConsensusAlgorithm.Clique) {
const period = this._common.consensusConfig().period
// Timestamp diff between blocks is lower than PERIOD (clique)
if (parentHeader.timestamp.addn(period).gt(this.timestamp)) {
const msg = this._errorMsg('invalid timestamp diff (lower than period)')
throw new Error(msg)
}
}
if (this._common.consensusType() === 'pow') {
if (!this.validateDifficulty(parentHeader)) {
const msg = this._errorMsg('invalid difficulty')
throw new Error(msg)
}
}
if (!this.validateGasLimit(parentHeader)) {
const msg = this._errorMsg('invalid gas limit')
throw new Error(msg)
}
if (height) {
const dif = height.sub(parentHeader.number)
if (!(dif.ltn(8) && dif.gtn(1))) {
const msg = this._errorMsg('uncle block has a parent that is too old or too young')
throw new Error(msg)
}
}
// check if the block used too much gas
if (this.gasUsed.gt(this.gasLimit)) {
const msg = this._errorMsg('Invalid block: too much gas used')
throw new Error(msg)
}
if (this._common.isActivatedEIP(1559)) {
if (!this.baseFeePerGas) {
const msg = this._errorMsg('EIP1559 block has no base fee field')
throw new Error(msg)
}
const londonHfBlock = this._common.hardforkBlockBN(Hardfork.London)
const isInitialEIP1559Block = londonHfBlock && this.number.eq(londonHfBlock)
if (isInitialEIP1559Block) {
const initialBaseFee = new BN(this._common.param('gasConfig', 'initialBaseFee'))
if (!this.baseFeePerGas!.eq(initialBaseFee)) {
const msg = this._errorMsg('Initial EIP1559 block does not have initial base fee')
throw new Error(msg)
}
} else {
// check if the base fee is correct
const expectedBaseFee = parentHeader.calcNextBaseFee()
if (!this.baseFeePerGas!.eq(expectedBaseFee)) {
const msg = this._errorMsg('Invalid block: base fee not correct')
throw new Error(msg)
}
}
}
}
/**
* Calculates the base fee for a potential next block
*/
public calcNextBaseFee(): BN {
if (!this._common.isActivatedEIP(1559)) {
const msg = this._errorMsg(
'calcNextBaseFee() can only be called with EIP1559 being activated'
)
throw new Error(msg)
}
let nextBaseFee: BN
const elasticity = new BN(this._common.param('gasConfig', 'elasticityMultiplier'))
const parentGasTarget = this.gasLimit.div(elasticity)
if (parentGasTarget.eq(this.gasUsed)) {
nextBaseFee = this.baseFeePerGas!
} else if (this.gasUsed.gt(parentGasTarget)) {
const gasUsedDelta = this.gasUsed.sub(parentGasTarget)
const baseFeeMaxChangeDenominator = new BN(
this._common.param('gasConfig', 'baseFeeMaxChangeDenominator')
)
const calculatedDelta = this.baseFeePerGas!.mul(gasUsedDelta)
.div(parentGasTarget)
.div(baseFeeMaxChangeDenominator)
nextBaseFee = BN.max(calculatedDelta, new BN(1)).add(this.baseFeePerGas!)
} else {
const gasUsedDelta = parentGasTarget.sub(this.gasUsed)
const baseFeeMaxChangeDenominator = new BN(
this._common.param('gasConfig', 'baseFeeMaxChangeDenominator')
)
const calculatedDelta = this.baseFeePerGas!.mul(gasUsedDelta)
.div(parentGasTarget)
.div(baseFeeMaxChangeDenominator)
nextBaseFee = BN.max(this.baseFeePerGas!.sub(calculatedDelta), new BN(0))
}
return nextBaseFee
}
/**
* Returns a Buffer Array of the raw Buffers in this header, in order.
*/
raw(): BlockHeaderBuffer {
const rawItems = [
this.parentHash,
this.uncleHash,
this.coinbase.buf,
this.stateRoot,
this.transactionsTrie,
this.receiptTrie,
this.logsBloom,
bnToUnpaddedBuffer(this.difficulty),
bnToUnpaddedBuffer(this.number),
bnToUnpaddedBuffer(this.gasLimit),
bnToUnpaddedBuffer(this.gasUsed),
bnToUnpaddedBuffer(this.timestamp),
this.extraData,
this.mixHash,
this.nonce,
]
if (this._common.isActivatedEIP(1559)) {
rawItems.push(bnToUnpaddedBuffer(this.baseFeePerGas!))
}
return rawItems
}
/**
* Returns the hash of the block header.
*/
hash(): Buffer {
if (Object.isFrozen(this)) {
if (!this.cache.hash) {
this.cache.hash = rlphash(this.raw())
}
return this.cache.hash
}
return rlphash(this.raw())
}
/**
* Checks if the block header is a genesis header.
*/
isGenesis(): boolean {
return this.number.isZero()
}
private _requireClique(name: string) {
if (this._common.consensusAlgorithm() !== ConsensusAlgorithm.Clique) {
const msg = this._errorMsg(
`BlockHeader.${name}() call only supported for clique PoA networks`
)
throw new Error(msg)
}
}
/**
* PoA clique signature hash without the seal.
*/
cliqueSigHash() {
this._requireClique('cliqueSigHash')
const raw = this.raw()
raw[12] = this.extraData.slice(0, this.extraData.length - CLIQUE_EXTRA_SEAL)
return rlphash(raw)
}
/**
* Checks if the block header is an epoch transition
* header (only clique PoA, throws otherwise)
*/
cliqueIsEpochTransition(): boolean {
this._requireClique('cliqueIsEpochTransition')
const epoch = new BN(this._common.consensusConfig().epoch)
// Epoch transition block if the block number has no
// remainder on the division by the epoch length
return this.number.mod(epoch).isZero()
}
/**
* Returns extra vanity data
* (only clique PoA, throws otherwise)
*/
cliqueExtraVanity(): Buffer {
this._requireClique('cliqueExtraVanity')
return this.extraData.slice(0, CLIQUE_EXTRA_VANITY)
}
/**
* Returns extra seal data
* (only clique PoA, throws otherwise)
*/
cliqueExtraSeal(): Buffer {
this._requireClique('cliqueExtraSeal')
return this.extraData.slice(-CLIQUE_EXTRA_SEAL)
}
/**
* Seal block with the provided signer.
* Returns the final extraData field to be assigned to `this.extraData`.
* @hidden
*/
private cliqueSealBlock(privateKey: Buffer) {
this._requireClique('cliqueSealBlock')
const signature = ecsign(this.cliqueSigHash(), privateKey)
const signatureB = Buffer.concat([signature.r, signature.s, intToBuffer(signature.v - 27)])
const extraDataWithoutSeal = this.extraData.slice(0, this.extraData.length - CLIQUE_EXTRA_SEAL)
const extraData = Buffer.concat([extraDataWithoutSeal, signatureB])
return extraData
}
/**
* Returns a list of signers
* (only clique PoA, throws otherwise)
*
* This function throws if not called on an epoch
* transition block and should therefore be used
* in conjunction with {@link BlockHeader.cliqueIsEpochTransition}
*/
cliqueEpochTransitionSigners(): Address[] {
this._requireClique('cliqueEpochTransitionSigners')
if (!this.cliqueIsEpochTransition()) {
const msg = this._errorMsg('Signers are only included in epoch transition blocks (clique)')
throw new Error(msg)
}
const start = CLIQUE_EXTRA_VANITY
const end = this.extraData.length - CLIQUE_EXTRA_SEAL
const signerBuffer = this.extraData.slice(start, end)
const signerList: Buffer[] = []
const signerLength = 20
for (let start = 0; start <= signerBuffer.length - signerLength; start += signerLength) {
signerList.push(signerBuffer.slice(start, start + signerLength))
}
return signerList.map((buf) => new Address(buf))
}
/**
* Verifies the signature of the block (last 65 bytes of extraData field)
* (only clique PoA, throws otherwise)
*
* Method throws if signature is invalid
*/
cliqueVerifySignature(signerList: Address[]): boolean {
this._requireClique('cliqueVerifySignature')
const signerAddress = this.cliqueSigner()
const signerFound = signerList.find((signer) => {
return signer.equals(signerAddress)
})
return !!signerFound
}
/**
* Returns the signer address
*/
cliqueSigner(): Address {
this._requireClique('cliqueSigner')
const extraSeal = this.cliqueExtraSeal()
// Reasonable default for default blocks
if (extraSeal.length === 0) {
return Address.zero()
}
const r = extraSeal.slice(0, 32)
const s = extraSeal.slice(32, 64)
const v = new BN(extraSeal.slice(64, 65)).addn(27)
const pubKey = ecrecover(this.cliqueSigHash(), v, r, s)
return Address.fromPublicKey(pubKey)
}
/**
* Returns the rlp encoding of the block header.
*/
serialize(): Buffer {
return rlp.encode(this.raw())
}
/**
* Returns the block header in JSON format.
*/
toJSON(): JsonHeader {
const jsonDict: JsonHeader = {
parentHash: '0x' + this.parentHash.toString('hex'),
uncleHash: '0x' + this.uncleHash.toString('hex'),
coinbase: this.coinbase.toString(),
stateRoot: '0x' + this.stateRoot.toString('hex'),
transactionsTrie: '0x' + this.transactionsTrie.toString('hex'),
receiptTrie: '0x' + this.receiptTrie.toString('hex'),
logsBloom: '0x' + this.logsBloom.toString('hex'),
difficulty: bnToHex(this.difficulty),
number: bnToHex(this.number),
gasLimit: bnToHex(this.gasLimit),
gasUsed: bnToHex(this.gasUsed),
timestamp: bnToHex(this.timestamp),
extraData: '0x' + this.extraData.toString('hex'),
mixHash: '0x' + this.mixHash.toString('hex'),
nonce: '0x' + this.nonce.toString('hex'),
}
if (this._common.isActivatedEIP(1559)) {
jsonDict.baseFeePerGas = '0x' + this.baseFeePerGas!.toString('hex')
jsonDict.baseFee = '0x' + this.baseFeePerGas!.toString('hex') // deprecated alias, please use `baseFeePerGas`, will be removed in next major release
}
jsonDict.bloom = jsonDict.logsBloom // deprecated alias, please use `logsBloom`, will be removed in next major release
return jsonDict
}
private _getHardfork(): string {
return this._common.hardfork() || this._common.activeHardfork(this.number.toNumber())
}
private async _getHeaderByHash(