-
Notifications
You must be signed in to change notification settings - Fork 750
/
header.ts
365 lines (330 loc) · 10.1 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
import Common from 'ethereumjs-common'
import * as utils from 'ethereumjs-util'
import { BN } from 'ethereumjs-util'
import { Blockchain, BlockHeaderData, BufferLike, ChainOptions, PrefixedHexString } from './types'
import { Buffer } from 'buffer'
import { Block } from './block'
/**
* An object that represents the block header
*/
export class BlockHeader {
public raw!: Buffer[]
public parentHash!: Buffer
public uncleHash!: Buffer
public coinbase!: Buffer
public stateRoot!: Buffer
public transactionsTrie!: Buffer
public receiptTrie!: Buffer
public bloom!: Buffer
public difficulty!: Buffer
public number!: Buffer
public gasLimit!: Buffer
public gasUsed!: Buffer
public timestamp!: Buffer
public extraData!: Buffer
public mixHash!: Buffer
public nonce!: Buffer
private readonly _common: Common
/**
* Creates a new block header.
* @param data - The data of the block header.
* @param opts - The network options for this block, and its header, uncle headers and txs.
*/
constructor(
data: Buffer | PrefixedHexString | BufferLike[] | BlockHeaderData = {},
opts: ChainOptions = {},
) {
if (opts.common !== undefined) {
if (opts.chain !== undefined || opts.hardfork !== undefined) {
throw new Error(
'Instantiation with both opts.common and opts.chain / opts.hardfork parameter not allowed!',
)
}
this._common = opts.common
} else {
const chain = opts.chain ? opts.chain : 'mainnet'
const hardfork = opts.hardfork ? opts.hardfork : null
this._common = new Common(chain, hardfork)
}
const fields = [
{
name: 'parentHash',
length: 32,
default: utils.zeros(32),
},
{
name: 'uncleHash',
default: utils.KECCAK256_RLP_ARRAY,
},
{
name: 'coinbase',
length: 20,
default: utils.zeros(20),
},
{
name: 'stateRoot',
length: 32,
default: utils.zeros(32),
},
{
name: 'transactionsTrie',
length: 32,
default: utils.KECCAK256_RLP,
},
{
name: 'receiptTrie',
length: 32,
default: utils.KECCAK256_RLP,
},
{
name: 'bloom',
default: utils.zeros(256),
},
{
name: 'difficulty',
default: Buffer.from([]),
},
{
name: 'number',
// TODO: params.homeSteadForkNumber.v left for legacy reasons, replace on future release
default: utils.toBuffer(1150000),
},
{
name: 'gasLimit',
default: Buffer.from('ffffffffffffff', 'hex'),
},
{
name: 'gasUsed',
empty: true,
default: Buffer.from([]),
},
{
name: 'timestamp',
default: Buffer.from([]),
},
{
name: 'extraData',
allowZero: true,
empty: true,
default: Buffer.from([]),
},
{
name: 'mixHash',
default: utils.zeros(32),
// length: 32
},
{
name: 'nonce',
default: utils.zeros(8), // sha3(42)
},
]
utils.defineProperties(this, fields, data)
}
/**
* 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 = new BN(this.timestamp)
const parentTs = new BN(parentBlock.header.timestamp)
const parentDif = new BN(parentBlock.header.difficulty)
const minimumDifficulty = new BN(this._common.param('pow', 'minimumDifficulty', hardfork))
const offset = parentDif.div(
new BN(this._common.param('pow', 'difficultyBoundDivisor', hardfork)),
)
let num = new BN(this.number)
// We use a ! here as TS can follow this hardforks-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(utils.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.param('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.param('gasConfig', 'gasLimitBoundDivisor', hardfork)),
)
const maxGasLimit = pGasLimit.add(a)
const minGasLimit = pGasLimit.sub(a)
return (
gasLimit.lt(maxGasLimit) &&
gasLimit.gt(minGasLimit) &&
gasLimit.gte(this._common.param('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 (utils.bufferToInt(parentBlock.header.number) + 1 !== utils.bufferToInt(this.number)) {
throw new Error('invalid height')
}
if (utils.bufferToInt(this.timestamp) <= utils.bufferToInt(parentBlock.header.timestamp)) {
throw new Error('invalid timestamp')
}
const hardfork = this._getHardfork()
if (this.extraData.length > this._common.param('vm', 'maxExtraDataSize', hardfork)) {
throw new Error('invalid amount of extra data')
}
}
/**
* Returns the hash of the block header.
*/
hash(): Buffer {
return utils.rlphash(this.raw)
}
/**
* Checks if the block header is a genesis header.
*/
isGenesis(): boolean {
return this.number.length === 0
}
/**
* Turns the header into the canonical genesis block header.
*/
setGenesisParams(): void {
this.timestamp = this._common.genesis().timestamp
this.gasLimit = this._common.genesis().gasLimit
this.difficulty = this._common.genesis().difficulty
this.extraData = this._common.genesis().extraData
this.nonce = this._common.genesis().nonce
this.stateRoot = this._common.genesis().stateRoot
this.number = Buffer.from([])
}
/**
* 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
*
* @see {@link https://github.com/ethereumjs/ethereumjs-util/blob/master/docs/index.md#defineproperties|ethereumjs-util}
*/
toJSON(_labels: boolean = false): { [key: string]: string } | string[] {
// Note: This never gets executed, defineProperties overwrites it.
return {}
}
private _getHardfork(): string {
const commonHardFork = this._common.hardfork()
return commonHardFork !== null
? commonHardFork
: this._common.activeHardfork(utils.bufferToInt(this.number))
}
private async _getBlockByHash(blockchain: Blockchain, hash: Buffer): Promise<Block | undefined> {
return new Promise((resolve, reject) => {
blockchain.getBlock(hash, (err, block) => {
if (err) {
reject(err)
return
}
resolve(block)
})
})
}
}