|
@ -1,3 +1,4 @@ |
|
|
|
|
|
var createHash = require('create-hash') |
|
|
var bufferutils = require('./bufferutils') |
|
|
var bufferutils = require('./bufferutils') |
|
|
var bcrypto = require('./crypto') |
|
|
var bcrypto = require('./crypto') |
|
|
var bufferCompare = require('buffer-compare') |
|
|
var bufferCompare = require('buffer-compare') |
|
@ -133,6 +134,35 @@ Block.calculateTarget = function (bits) { |
|
|
return target |
|
|
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 () { |
|
|
Block.prototype.checkProofOfWork = function () { |
|
|
var hash = bufferReverse(this.getHash()) |
|
|
var hash = bufferReverse(this.getHash()) |
|
|
var target = Block.calculateTarget(this.bits) |
|
|
var target = Block.calculateTarget(this.bits) |
|
|