Browse Source

Merge pull request #509 from bitcoinjs/pow

Add Block proof-of-work validation function
hk-custom-address
Daniel Cousens 9 years ago
parent
commit
f3913516ca
  1. 1
      package.json
  2. 24
      src/block.js
  3. 29
      test/block.js
  4. 68
      test/fixtures/block.json

1
package.json

@ -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",

24
src/block.js

@ -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

29
test/block.js

@ -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)
})
})
})
})

68
test/fixtures/block.json

File diff suppressed because one or more lines are too long
Loading…
Cancel
Save