forked from ethereumjs/ethereumjs-block
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
323 lines (280 loc) · 8.01 KB
/
index.js
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
const Common = require('ethereumjs-common').default
const ethUtil = require('ethereumjs-util')
const Tx = require('ethereumjs-tx')
const Trie = require('merkle-patricia-tree')
const BN = ethUtil.BN
const rlp = ethUtil.rlp
const async = require('async')
const BlockHeader = require('./header')
/**
* Creates a new block object
* @constructor the raw serialized or the deserialized block.
* @param {Array|Buffer|Object} data
* @param {Array} opts Options
* @param {String|Number} opts.chain The chain for the block [default: 'mainnet']
* @param {String} opts.hardfork Hardfork for the block [default: null, block number-based behaviour]
* @param {Object} opts.common Alternatively pass a Common instance (ethereumjs-common) instead of setting chain/hardfork directly
* @prop {Header} header the block's header
* @prop {Array.<Header>} uncleList an array of uncle headers
* @prop {Array.<Buffer>} raw an array of buffers containing the raw blocks.
*/
var Block = module.exports = function (data, opts) {
opts = opts || {}
if (opts.common) {
if (opts.chain) {
throw new Error('Instantiation with both opts.common and opts.chain parameter not allowed!')
}
this._common = opts.common
} else {
let chain = opts.chain ? opts.chain : 'mainnet'
let hardfork = opts.hardfork ? opts.hardfork : null
this._common = new Common(chain, hardfork)
}
this.transactions = []
this.uncleHeaders = []
this._inBlockChain = false
this.txTrie = new Trie()
Object.defineProperty(this, 'raw', {
get: function () {
return this.serialize(false)
}
})
var rawTransactions, rawUncleHeaders
// defaults
if (!data) {
data = [[], [], []]
}
if (Buffer.isBuffer(data)) {
data = rlp.decode(data)
}
if (Array.isArray(data)) {
this.header = new BlockHeader(data[0], opts)
rawTransactions = data[1]
rawUncleHeaders = data[2]
} else {
this.header = new BlockHeader(data.header, opts)
rawTransactions = data.transactions || []
rawUncleHeaders = data.uncleHeaders || []
}
// parse uncle headers
for (var i = 0; i < rawUncleHeaders.length; i++) {
this.uncleHeaders.push(new BlockHeader(rawUncleHeaders[i], opts))
}
// parse transactions
for (i = 0; i < rawTransactions.length; i++) {
var tx = new Tx(rawTransactions[i])
tx._homestead = true
this.transactions.push(tx)
}
}
Block.Header = BlockHeader
/**
* Produces a hash the RLP of the block
* @method hash
*/
Block.prototype.hash = function () {
return this.header.hash()
}
/**
* Determines if a given block is the genesis block
* @method isGenisis
* @return Boolean
*/
Block.prototype.isGenesis = function () {
return this.header.isGenesis()
}
/**
* turns the block into the canonical genesis block
* @method setGenesisParams
*/
Block.prototype.setGenesisParams = function () {
this.header.setGenesisParams()
}
/**
* Produces a serialization of the block.
* @method serialize
* @param {Boolean} rlpEncode whether to rlp encode the block or not
*/
Block.prototype.serialize = function (rlpEncode) {
var raw = [this.header.raw, [],
[]
]
// rlpEnode defaults to true
if (typeof rlpEncode === 'undefined') {
rlpEncode = true
}
this.transactions.forEach(function (tx) {
raw[1].push(tx.raw)
})
this.uncleHeaders.forEach(function (uncle) {
raw[2].push(uncle.raw)
})
return rlpEncode ? rlp.encode(raw) : raw
}
/**
* Generate transaction trie. The tx trie must be generated before the transaction trie can
* be validated with `validateTransactionTrie`
* @method genTxTrie
* @param {Function} cb the callback
*/
Block.prototype.genTxTrie = function (cb) {
var i = 0
var self = this
async.eachSeries(this.transactions, function (tx, done) {
self.txTrie.put(rlp.encode(i), tx.serialize(), done)
i++
}, cb)
}
/**
* Validates the transaction trie
* @method validateTransactionTrie
* @return {Boolean}
*/
Block.prototype.validateTransactionsTrie = function () {
var txT = this.header.transactionsTrie.toString('hex')
if (this.transactions.length) {
return txT === this.txTrie.root.toString('hex')
} else {
return txT === ethUtil.SHA3_RLP.toString('hex')
}
}
/**
* Validates the transactions
* @method validateTransactions
* @param {Boolean} [stringError=false] whether to return a string with a dscription of why the validation failed or return a Bloolean
* @return {Boolean}
*/
Block.prototype.validateTransactions = function (stringError) {
var errors = []
this.transactions.forEach(function (tx, i) {
var error = tx.validate(true)
if (error) {
errors.push(error + ' at tx ' + i)
}
})
if (stringError === undefined || stringError === false) {
return errors.length === 0
} else {
return arrayToString(errors)
}
}
/**
* Validates the entire block. Returns a string to the callback if block is invalid
* @method validate
* @param {BlockChain} blockChain the blockchain that this block wants to be part of
* @param {Function} cb the callback which is given a `String` if the block is not valid
*/
Block.prototype.validate = function (blockChain, cb) {
var self = this
var errors = []
async.parallel([
// validate uncles
self.validateUncles.bind(self, blockChain),
// validate block
self.header.validate.bind(self.header, blockChain),
// generate the transaction trie
self.genTxTrie.bind(self)
], function (err) {
if (err) {
errors.push(err)
}
if (!self.validateTransactionsTrie()) {
errors.push('invalid transaction trie')
}
var txErrors = self.validateTransactions(true)
if (txErrors !== '') {
errors.push(txErrors)
}
if (!self.validateUnclesHash()) {
errors.push('invalid uncle hash')
}
cb(arrayToString(errors))
})
}
/**
* Validates the uncle's hash
* @method validateUncleHash
* @return {Boolean}
*/
Block.prototype.validateUnclesHash = function () {
var raw = []
this.uncleHeaders.forEach(function (uncle) {
raw.push(uncle.raw)
})
raw = rlp.encode(raw)
return ethUtil.sha3(raw).toString('hex') === this.header.uncleHash.toString('hex')
}
/**
* Validates the uncles that are in the block if any. Returns a string to the callback if uncles are invalid
* @method validateUncles
* @param {Blockchain} blockChaina an instance of the Blockchain
* @param {Function} cb the callback
*/
Block.prototype.validateUncles = function (blockChain, cb) {
if (this.isGenesis()) {
return cb()
}
var self = this
if (self.uncleHeaders.length > 2) {
return cb('too many uncle headers')
}
var uncleHashes = self.uncleHeaders.map(function (header) {
return header.hash().toString('hex')
})
if (!((new Set(uncleHashes)).size === uncleHashes.length)) {
return cb('duplicate uncles')
}
async.each(self.uncleHeaders, function (uncle, cb2) {
var height = new BN(self.header.number)
async.parallel([
uncle.validate.bind(uncle, blockChain, height),
// check to make sure the uncle is not already in the blockchain
function (cb3) {
blockChain.getDetails(uncle.hash(), function (err, blockInfo) {
// TODO: remove uncles from BC
if (blockInfo && blockInfo.isUncle) {
cb3(err || 'uncle already included')
} else {
cb3()
}
})
}
], cb2)
}, cb)
}
/**
* Converts the block toJSON
* @method toJSON
* @param {Bool} labeled whether to create an labeled object or an array
* @return {Object}
*/
Block.prototype.toJSON = function (labeled) {
if (labeled) {
var obj = {
header: this.header.toJSON(true),
transactions: [],
uncleHeaders: []
}
this.transactions.forEach(function (tx) {
obj.transactions.push(tx.toJSON(labeled))
})
this.uncleHeaders.forEach(function (uh) {
obj.uncleHeaders.push(uh.toJSON())
})
return obj
} else {
return ethUtil.baToJSON(this.raw)
}
}
function arrayToString (array) {
try {
return array.reduce(function (str, err) {
if (str) {
str += ' '
}
return str + err
})
} catch (e) {
return ''
}
}