utils. merkle tree.

This commit is contained in:
Christopher Jeffrey 2016-02-23 16:53:05 -08:00
parent abcd174bd3
commit 0fac957da3
5 changed files with 54 additions and 5 deletions

View File

@ -22,8 +22,6 @@ function Block(data, subtype) {
if (!(this instanceof Block))
return new Block(data, subtype);
assert(typeof data.hash !== 'string');
this.type = 'block';
this.subtype = subtype || data.subtype;
this.version = data.version;
@ -235,6 +233,18 @@ Block.prototype.getMerkleRoot = function getMerkleRoot() {
return utils.toHex(tree[tree.length - 1]);
};
Block.prototype.getMerkleRoot = function getMerkleRoot() {
var hashes = [];
var i;
assert(this.subtype === 'block');
for (i = 0; i < this.txs.length; i++)
hashes.push(this.txs[i].hash());
return utils.getMerkleRoot(hashes);
};
Block.prototype._verify = function _verify() {
var uniq = {};
var i, tx, hash;

View File

@ -38,6 +38,10 @@ ec.random = function random(size) {
return new Buffer(elliptic.rand(size));
};
bn.prototype.toBuffer = function toBuffer(order, size) {
return new Buffer(this.toArray(order, size));
};
ec.verify = function verify(msg, sig, key, historical) {
if (key.getPublicKey)
key = key.getPublicKey();

View File

@ -403,7 +403,9 @@ Framer.block = function _block(block, type) {
p = new Buffer(80 + utils.sizeIntv(block.txs.length));
} else {
for (i = 0; i < block.txs.length; i++) {
tx = block.txs[i].render();
tx = block.txs[i].render
? block.txs[i].render()
: Framer.tx(block.txs[i]);
txs.push(tx);
txSize += tx.length;
}

View File

@ -22,8 +22,6 @@ function TX(data, block) {
if (!data)
data = {};
assert(typeof data.hash !== 'string');
this.type = 'tx';
this.version = data.version || 1;
this.inputs = [];

View File

@ -1587,3 +1587,38 @@ utils.once = function once(callback) {
return onceFn;
};
utils.buildMerkleTree = function buildMerkleTree(items) {
var tree = items.slice();
var i, j, size, i2, hash;
j = 0;
size = items.length;
for (; size > 1; size = ((size + 1) / 2) | 0) {
for (i = 0; i < size; i += 2) {
i2 = Math.min(i + 1, size - 1);
if (i2 === i + 1 && i2 + 1 === size
&& tree[j + i] === tree[j + i2]) {
return;
}
hash = Buffer.concat([tree[j + i], tree[j + i2]]);
hash = utils.dsha256(hash);
tree.push(hash);
}
j += size;
}
if (!tree.length)
return;
return tree;
};
utils.getMerkleRoot = function getMerkleRoot(items) {
var tree = utils.buildMerkleTree(items);
if (!tree)
return;
return utils.toHex(tree[tree.length - 1]);
};