Block: add checkMerkleRoot
This commit is contained in:
parent
a3ec53e2d8
commit
d58e09a3a7
3 changed files with 82 additions and 0 deletions
src
30
src/block.js
30
src/block.js
|
@ -1,3 +1,4 @@
|
|||
var createHash = require('create-hash')
|
||||
var bufferutils = require('./bufferutils')
|
||||
var bcrypto = require('./crypto')
|
||||
var bufferCompare = require('buffer-compare')
|
||||
|
@ -133,6 +134,35 @@ Block.calculateTarget = function (bits) {
|
|||
return target
|
||||
}
|
||||
|
||||
Block.calculateMerkleRoot = function (transactions) {
|
||||
var length = transactions.length
|
||||
if (length === 0) throw TypeError('Cannot compute merkle root for zero transactions')
|
||||
|
||||
var hashes = transactions.map(function (transaction) { return transaction.getHash() })
|
||||
|
||||
while (length > 1) {
|
||||
var j = 0
|
||||
|
||||
for (var i = 0; i < length; i += 2, ++j) {
|
||||
var hasher = createHash('sha256')
|
||||
hasher.update(hashes[i])
|
||||
hasher.update(i + 1 !== length ? hashes[i + 1] : hashes[i])
|
||||
hashes[j] = bcrypto.sha256(hasher.digest())
|
||||
}
|
||||
|
||||
length = j
|
||||
}
|
||||
|
||||
return hashes[0]
|
||||
}
|
||||
|
||||
Block.prototype.checkMerkleRoot = function () {
|
||||
if (!this.transactions) return false
|
||||
|
||||
var actualMerkleRoot = Block.calculateMerkleRoot(this.transactions)
|
||||
return bufferCompare(this.merkleRoot, actualMerkleRoot) === 0
|
||||
}
|
||||
|
||||
Block.prototype.checkProofOfWork = function () {
|
||||
var hash = bufferReverse(this.getHash())
|
||||
var target = Block.calculateTarget(this.bits)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue