From cd3f04268af8b814a58e1b484c3f202b800912ac Mon Sep 17 00:00:00 2001 From: Fedor Indutny Date: Sat, 3 May 2014 16:51:16 +0400 Subject: [PATCH] block: verify --- lib/bcoin/block.js | 3 +-- lib/bcoin/chain.js | 4 ++-- lib/bcoin/utils.js | 43 +++++++++++++++++++++++++++++++++++++++++++ test/utils-test.js | 10 ++++++++++ 4 files changed, 56 insertions(+), 4 deletions(-) diff --git a/lib/bcoin/block.js b/lib/bcoin/block.js index af56cb6b..08c08091 100644 --- a/lib/bcoin/block.js +++ b/lib/bcoin/block.js @@ -37,8 +37,7 @@ Block.prototype.abbr = function abbr() { }; Block.prototype.verify = function verify() { - // TODO(indutny): verify nonce - return true; + return utils.testTarget(this.bits, this.hash()); }; Block.prototype.render = function render(framer) { diff --git a/lib/bcoin/chain.js b/lib/bcoin/chain.js index 70e02b52..30a8db70 100644 --- a/lib/bcoin/chain.js +++ b/lib/bcoin/chain.js @@ -168,11 +168,11 @@ Chain.prototype.get = function get(hash, cb) { if (this.request.map[hash]) { this.request.map[hash].push(cb); - this.request.count++; } else { this.request.map[hash] = [ cb ]; + this.request.count++; + this.emit('missing', hash); } - this.emit('missing', hash); }; Chain.prototype.isFull = function isFull() { diff --git a/lib/bcoin/utils.js b/lib/bcoin/utils.js index 3282e52c..148a82cd 100644 --- a/lib/bcoin/utils.js +++ b/lib/bcoin/utils.js @@ -223,3 +223,46 @@ function binaryInsert(list, item, compare, search) { return start; } utils.binaryInsert = binaryInsert; + +function bitsToTarget(bits) { + var len = (bits >>> 24) & 0xff; + var hi = (bits >>> 16) & 0xff; + var mid = (bits >>> 8) & 0xff; + var lo = bits & 0xff; + + var res = new Array(len); + for (var i = 0; i < len - 3; i++) + res[i] = 0; + res[i++] = lo; + res[i++] = mid; + res[i++] = hi; + + if (hi === 0) + res.pop(); + if (hi === 0 && mid === 0) + res.pop(); + + return res; +} +utils.bitsToTarget = bitsToTarget; + +function testTarget(target, hash) { + if (typeof target === 'number') + target = bitsToTarget(target); + hash = utils.toArray(hash, 'hex'); + + for (var i = hash.length - 1; i >= target.length; i--) + if (hash[i] !== 0) + return false; + + for (; i >= 0; i--) { + if (hash[i] === target[i]) + continue; + if (hash[i] > target[i]) + return false; + break; + } + + return true; +} +utils.testTarget = testTarget; diff --git a/test/utils-test.js b/test/utils-test.js index 7f6a869a..d0371998 100644 --- a/test/utils-test.js +++ b/test/utils-test.js @@ -8,4 +8,14 @@ describe('Utils', function() { assert.equal(b, '1116h8cQN'); assert.deepEqual(bcoin.utils.fromBase58(b), arr); }); + + it('should translate bits to target', function() { + var bits = 0x1900896c; + var hash = bcoin.utils.toArray( + '672b3f1bb11a994267ea4171069ba0aa4448a840f38e8f340000000000000000', + 'hex' + ); + var target = bcoin.utils.bitsToTarget(bits); + assert(bcoin.utils.testTarget(target, hash)); + }); });