Merge pull request #509 from bitcoinjs/pow

Add Block proof-of-work validation function
This commit is contained in:
Daniel Cousens 2016-01-28 01:00:17 +11:00
commit f3913516ca
4 changed files with 112 additions and 10 deletions

View file

@ -62,6 +62,7 @@
"bigi": "^1.4.0",
"bip66": "^1.1.0",
"bs58check": "^1.0.5",
"buffer-compare": "^1.1.0",
"buffer-equals": "^1.0.3",
"buffer-reverse": "^1.0.0",
"create-hash": "^1.1.0",

View file

@ -1,5 +1,6 @@
var bufferutils = require('./bufferutils')
var bcrypto = require('./crypto')
var compare = require('buffer-compare')
var Transaction = require('./transaction')
@ -115,4 +116,27 @@ Block.prototype.toHex = function (headersOnly) {
return this.toBuffer(headersOnly).toString('hex')
}
Block.calculateTarget = function (bits) {
var exponent = ((bits & 0xff000000) >> 24) - 3
var mantissa = bits & 0x007fffff
var i = 31 - exponent
var target = new Buffer(32)
target.fill(0)
target[i] = mantissa & 0xff
target[i - 1] = mantissa >> 8
target[i - 2] = mantissa >> 16
target[i - 3] = mantissa >> 24
return target
}
Block.prototype.checkProofOfWork = function () {
var hash = [].reverse.call(this.getHash())
var target = Block.calculateTarget(this.bits)
return compare(hash, target) <= 0
}
module.exports = Block

View file

@ -1,12 +1,21 @@
/* global describe, it, beforeEach */
var assert = require('assert')
var Block = require('../src/block')
var fixtures = require('./fixtures/block')
describe('Block', function () {
describe('calculateTarget', function () {
fixtures.targets.forEach(function (f) {
it('returns ' + f.expected + ' for 0x' + f.bits, function () {
var bits = parseInt(f.bits, 16)
assert.equal(Block.calculateTarget(bits).toString('hex'), f.expected)
})
})
})
describe('fromBuffer/fromHex', function () {
fixtures.valid.forEach(function (f) {
it('imports the block: ' + f.description + ' correctly', function () {
@ -52,7 +61,7 @@ describe('Block', function () {
block = Block.fromHex(f.hex)
})
it('calculates ' + f.hash + ' for the block: ' + f.description, function () {
it('returns ' + f.hash + ' for the block: ' + f.description, function () {
assert.strictEqual(block.getHash().toString('hex'), f.hash)
})
})
@ -66,7 +75,7 @@ describe('Block', function () {
block = Block.fromHex(f.hex)
})
it('calculates ' + f.id + ' for the block: ' + f.description, function () {
it('returns ' + f.id + ' for the block: ' + f.description, function () {
assert.strictEqual(block.getId(), f.id)
})
})
@ -87,4 +96,18 @@ describe('Block', function () {
})
})
})
describe('checkProofOfWork', function () {
fixtures.valid.forEach(function (f) {
var block
beforeEach(function () {
block = Block.fromHex(f.hex)
})
it('returns ' + f.valid + ' for ' + f.id, function () {
assert.strictEqual(block.checkProofOfWork(), f.valid)
})
})
})
})

File diff suppressed because one or more lines are too long