-
Notifications
You must be signed in to change notification settings - Fork 846
Expand file tree
/
Copy pathheader.ts
More file actions
494 lines (446 loc) · 14.4 KB
/
header.ts
File metadata and controls
494 lines (446 loc) · 14.4 KB
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
import Common from '@ethereumjs/common'
import {
Address,
BN,
zeros,
KECCAK256_RLP_ARRAY,
KECCAK256_RLP,
rlp,
toBuffer,
unpadBuffer,
rlphash,
} from 'ethereumjs-util'
import { HeaderData, JsonHeader, Blockchain, BlockOptions, bnToHex } from './types'
import { Block } from './block'
import { checkBufferLength, toBN } from './util'
/**
* 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 bloom: 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 _common: Common
public static fromHeaderData(headerData: HeaderData = {}, opts: BlockOptions = {}) {
const {
parentHash,
uncleHash,
coinbase,
stateRoot,
transactionsTrie,
receiptTrie,
bloom,
difficulty,
number,
gasLimit,
gasUsed,
timestamp,
extraData,
mixHash,
nonce,
} = 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,
bloom ? toBuffer(bloom) : zeros(256),
difficulty ? toBN(difficulty) : new BN(0),
number ? toBN(number) : new BN(0),
gasLimit ? toBN(gasLimit) : new BN(Buffer.from('ffffffffffffff', 'hex')),
gasUsed ? toBN(gasUsed) : new BN(0),
timestamp ? toBN(timestamp) : new BN(0),
extraData ? toBuffer(extraData) : Buffer.from([]),
mixHash ? toBuffer(mixHash) : zeros(32),
nonce ? toBuffer(nonce) : zeros(8),
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)
}
public static fromValuesArray(values: Buffer[], opts: BlockOptions) {
if (values.length > 15) {
throw new Error('invalid header. More values than expected were received')
}
const [
parentHash,
uncleHash,
coinbase,
stateRoot,
transactionsTrie,
receiptTrie,
bloom,
difficulty,
number,
gasLimit,
gasUsed,
timestamp,
extraData,
mixHash,
nonce,
] = values
return new BlockHeader(
toBuffer(parentHash),
toBuffer(uncleHash),
new Address(toBuffer(coinbase)),
toBuffer(stateRoot),
toBuffer(transactionsTrie),
toBuffer(receiptTrie),
toBuffer(bloom),
toBN(difficulty),
toBN(number),
toBN(gasLimit),
toBN(gasUsed),
toBN(timestamp),
toBuffer(extraData),
toBuffer(mixHash),
toBuffer(nonce),
opts,
)
}
/**
* This constructor takes the values, validates them, assigns them and freezes the object.
* Use the public static factory methods to assist in creating a Header object from
* varying data types.
* For a default empty header, use `BlockHeader.fromHeaderData()`.
*/
constructor(
parentHash: Buffer,
uncleHash: Buffer,
coinbase: Address,
stateRoot: Buffer,
transactionsTrie: Buffer,
receiptTrie: Buffer,
bloom: Buffer,
difficulty: BN,
number: BN,
gasLimit: BN,
gasUsed: BN,
timestamp: BN,
extraData: Buffer,
mixHash: Buffer,
nonce: Buffer,
options: BlockOptions = {},
) {
if (options.common) {
this._common = options.common
} else {
const DEFAULT_CHAIN = 'mainnet'
if (options.initWithGenesisHeader) {
this._common = new Common({ chain: DEFAULT_CHAIN, hardfork: 'chainstart' })
} else {
// This initializes on the Common default hardfork
this._common = new Common({ chain: DEFAULT_CHAIN })
}
}
this.parentHash = parentHash
this.uncleHash = uncleHash
this.coinbase = coinbase
this.stateRoot = stateRoot
this.transactionsTrie = transactionsTrie
this.receiptTrie = receiptTrie
this.bloom = bloom
this.difficulty = difficulty
this.number = number
this.gasLimit = gasLimit
this.gasUsed = gasUsed
this.timestamp = timestamp
this.extraData = extraData
this.mixHash = mixHash
this.nonce = nonce
if (options.hardforkByBlockNumber) {
this._common.setHardforkByBlockNumber(this.number.toNumber())
}
if (options.initWithGenesisHeader) {
if (this._common.hardfork() !== 'chainstart') {
throw new Error(
'Genesis parameters can only be set with a Common instance set to chainstart',
)
}
this.timestamp = toBN(this._common.genesis().timestamp || this.timestamp)
this.gasLimit = toBN(this._common.genesis().gasLimit || this.gasLimit)
this.difficulty = toBN(this._common.genesis().difficulty || this.difficulty)
this.extraData = toBuffer(this._common.genesis().extraData || this.extraData)
this.nonce = toBuffer(this._common.genesis().nonce || this.nonce)
this.stateRoot = toBuffer(this._common.genesis().stateRoot || this.stateRoot)
this.number = new BN(0)
}
this._validateBufferLengths()
this._checkDAOExtraData()
Object.freeze(this)
}
/**
* Validates correct buffer lengths, throws if invalid.
*/
_validateBufferLengths() {
checkBufferLength(this.parentHash, 32)
checkBufferLength(this.stateRoot, 32)
checkBufferLength(this.transactionsTrie, 32)
checkBufferLength(this.receiptTrie, 32)
}
/**
* Returns the canonical difficulty for this block.
*
* @param parentBlock - the parent `Block` of this header
*/
canonicalDifficulty(parentBlock: Block): BN {
const hardfork = this._getHardfork()
const blockTs = toBN(this.timestamp)
const parentTs = toBN(parentBlock.header.timestamp)
const parentDif = toBN(parentBlock.header.difficulty)
const minimumDifficulty = new BN(
this._common.paramByHardfork('pow', 'minimumDifficulty', hardfork),
)
const offset = parentDif.div(
new BN(this._common.paramByHardfork('pow', 'difficultyBoundDivisor', hardfork)),
)
let num = toBN(this.number)
// 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, 'byzantium')) {
// max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99) (EIP100)
const uncleAddend = parentBlock.header.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.cmp(a) === 1) {
a = cutoff
}
dif = parentDif.add(offset.mul(a))
}
if (this._common.hardforkGteHardfork(hardfork, 'muirGlacier')) {
// Istanbul/Berlin difficulty bomb delay (EIP2384)
num.isubn(9000000)
if (num.ltn(0)) {
num = new BN(0)
}
} else if (this._common.hardforkGteHardfork(hardfork, 'constantinople')) {
// Constantinople difficulty bomb delay (EIP1234)
num.isubn(5000000)
if (num.ltn(0)) {
num = new BN(0)
}
} else if (this._common.hardforkGteHardfork(hardfork, 'byzantium')) {
// Byzantium difficulty bomb delay (EIP649)
num.isubn(3000000)
if (num.ltn(0)) {
num = new BN(0)
}
} else if (this._common.hardforkGteHardfork(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.cmp(a) === 1) {
a = cutoff
}
dif = parentDif.add(offset.mul(a))
} else {
// pre-homestead
if (
parentTs
.addn(this._common.paramByHardfork('pow', 'durationLimit', hardfork))
.cmp(blockTs) === 1
) {
dif = offset.add(parentDif)
} else {
dif = parentDif.sub(offset)
}
}
const exp = num.idivn(100000).isubn(2)
if (!exp.isNeg()) {
dif.iadd(new BN(2).pow(exp))
}
if (dif.cmp(minimumDifficulty) === -1) {
dif = minimumDifficulty
}
return dif
}
/**
* Checks that the block's `difficulty` matches the canonical difficulty.
*
* @param parentBlock - this block's parent
*/
validateDifficulty(parentBlock: Block): boolean {
const dif = this.canonicalDifficulty(parentBlock)
return dif.cmp(new BN(this.difficulty)) === 0
}
/**
* Validates the gasLimit.
*
* @param parentBlock - this block's parent
*/
validateGasLimit(parentBlock: Block): boolean {
const pGasLimit = new BN(parentBlock.header.gasLimit)
const gasLimit = new BN(this.gasLimit)
const hardfork = this._getHardfork()
const a = pGasLimit.div(
new BN(this._common.paramByHardfork('gasConfig', 'gasLimitBoundDivisor', hardfork)),
)
const maxGasLimit = pGasLimit.add(a)
const minGasLimit = pGasLimit.sub(a)
return (
gasLimit.lt(maxGasLimit) &&
gasLimit.gt(minGasLimit) &&
gasLimit.gte(this._common.paramByHardfork('gasConfig', 'minGasLimit', hardfork))
)
}
/**
* Validates the entire block header, throwing if invalid.
*
* @param blockchain - the blockchain that this block is validating against
* @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 parentBlock = await this._getBlockByHash(blockchain, this.parentHash)
if (parentBlock === undefined) {
throw new Error('could not find parent block')
}
const number = new BN(this.number)
if (number.cmp(new BN(parentBlock.header.number).iaddn(1)) !== 0) {
throw new Error('invalid number')
}
if (height !== undefined && BN.isBN(height)) {
const dif = height.sub(new BN(parentBlock.header.number))
if (!(dif.cmpn(8) === -1 && dif.cmpn(1) === 1)) {
throw new Error('uncle block has a parent that is too old or too young')
}
}
if (!this.validateDifficulty(parentBlock)) {
throw new Error('invalid Difficulty')
}
if (!this.validateGasLimit(parentBlock)) {
throw new Error('invalid gas limit')
}
if (!this.number.sub(parentBlock.header.number).eqn(1)) {
throw new Error('invalid height')
}
if (this.timestamp.cmp(parentBlock.header.timestamp) <= 0) {
throw new Error('invalid timestamp')
}
const hardfork = this._getHardfork()
if (this.extraData.length > this._common.paramByHardfork('vm', 'maxExtraDataSize', hardfork)) {
throw new Error('invalid amount of extra data')
}
}
/**
* Returns the hash of the block header.
*/
hash(): Buffer {
const values: Buffer[] = this.raw()
return rlphash(values)
}
/**
* Returns a Buffer Array of the raw Buffers in this header, in order
*/
raw(): Buffer[] {
return [
this.parentHash,
this.uncleHash,
this.coinbase.buf,
this.stateRoot,
this.transactionsTrie,
this.receiptTrie,
this.bloom,
unpadBuffer(toBuffer(this.difficulty)), // we unpadBuffer, because toBuffer(new BN(0)) == <Buffer 00>
unpadBuffer(toBuffer(this.number)),
unpadBuffer(toBuffer(this.gasLimit)),
unpadBuffer(toBuffer(this.gasUsed)),
unpadBuffer(toBuffer(this.timestamp)),
this.extraData,
this.mixHash,
unpadBuffer(toBuffer(this.nonce)),
]
}
/**
* Checks if the block header is a genesis header.
*/
isGenesis(): boolean {
return this.number.isZero()
}
/**
* Returns the rlp encoding of the block header
*/
serialize(): Buffer {
// Note: This never gets executed, defineProperties overwrites it.
return Buffer.from([])
}
/**
* Returns the block header in JSON format
*/
toJSON(): JsonHeader {
return {
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'),
bloom: '0x' + this.bloom.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'),
}
}
private _getHardfork(): string {
const commonHardFork = this._common.hardfork()
return commonHardFork !== null
? commonHardFork
: this._common.activeHardfork(this.number.toNumber())
}
private async _getBlockByHash(blockchain: Blockchain, hash: Buffer): Promise<Block | undefined> {
try {
return blockchain.getBlock(hash)
} catch (e) {
return undefined
}
}
/**
* Force extra data be DAO_ExtraData for DAO_ForceExtraDataRange blocks after DAO
* activation block (see: https://blog.slock.it/hard-fork-specification-24b889e70703)
*/
private _checkDAOExtraData() {
const DAO_ExtraData = Buffer.from('64616f2d686172642d666f726b', 'hex')
const DAO_ForceExtraDataRange = 9
if (this._common.hardforkIsActiveOnChain('dao')) {
// verify the extraData field.
const blockNumber = new BN(this.number)
const DAOActivationBlock = new BN(this._common.hardforkBlock('dao'))
if (blockNumber.gte(DAOActivationBlock)) {
const drift = blockNumber.sub(DAOActivationBlock)
if (drift.lten(DAO_ForceExtraDataRange)) {
if (!this.extraData.equals(DAO_ExtraData)) {
throw new Error("extraData should be 'dao-hard-fork'")
}
}
}
}
}
}