merkletreejs/index.js

347 lines
8.7 KiB
JavaScript
Raw Normal View History

2017-07-22 15:31:30 +08:00
const reverse = require('buffer-reverse')
const CryptoJS = require('crypto-js')
2018-12-10 11:10:43 +08:00
const treeify = require('treeify')
2017-07-22 15:31:30 +08:00
/**
* Class reprensenting a Merkle Tree
* @namespace MerkleTree
*/
class MerkleTree {
/**
* @desc Constructs a Merkle Tree.
* All nodes and leaves are stored as Buffers.
* Lonely leaf nodes are promoted to the next level up without being hashed again.
2017-07-22 16:05:52 +08:00
* @param {Buffer[]} leaves - Array of hashed leaves. Each leaf must be a Buffer.
2017-07-22 15:38:06 +08:00
* @param {Function} hashAlgorithm - Algorithm used for hashing leaves and nodes
2017-07-22 15:31:30 +08:00
* @param {Object} options - Additional options
2017-07-22 15:38:06 +08:00
* @param {Boolean} options.isBitcoinTree - If set to `true`, constructs the Merkle
* Tree using the [Bitcoin Merkle Tree implementation](http://www.righto.com/2014/02/bitcoin-mining-hard-way-algorithms.html). Enable it when you need
2017-08-08 11:54:56 +08:00
* to replicate Bitcoin constructed Merkle Trees. In Bitcoin Merkle Trees, single nodes are combined with themselves, and each output hash is hashed again.
2017-07-22 15:31:30 +08:00
* @example
2018-07-10 15:08:17 +08:00
* const MerkleTree = require('merkletreejs')
2017-07-22 15:31:30 +08:00
* const crypto = require('crypto')
*
* function sha256(data) {
* // returns Buffer
* return crypto.createHash('sha256').update(data).digest()
* }
*
* const leaves = ['a', 'b', 'c'].map(x => sha3(x))
*
* const tree = new MerkleTree(leaves, sha256)
*/
2017-07-22 15:38:06 +08:00
constructor(leaves, hashAlgorithm, options={}) {
2018-10-27 03:42:14 +08:00
this.hashAlgo = bufferifyFn(hashAlgorithm)
this.leaves = leaves.map(bufferify)
2018-10-27 04:09:38 +08:00
this.layers = [this.leaves]
2017-07-22 15:31:30 +08:00
this.isBitcoinTree = !!options.isBitcoinTree
this.createHashes(this.leaves)
}
2018-12-10 11:57:31 +08:00
// TODO: documentation
2017-07-22 15:31:30 +08:00
createHashes(nodes) {
2018-10-26 13:04:51 +08:00
while (nodes.length > 1) {
2017-07-22 15:31:30 +08:00
const layerIndex = this.layers.length
2017-07-22 15:31:30 +08:00
this.layers.push([])
2017-07-22 15:31:30 +08:00
for (let i = 0; i < nodes.length - 1; i += 2) {
const left = nodes[i]
const right = nodes[i+1]
let data = null
if (this.isBitcoinTree) {
data = Buffer.concat([reverse(left), reverse(right)])
} else {
data = Buffer.concat([left, right])
}
2017-07-22 15:31:30 +08:00
let hash = this.hashAlgo(data)
2017-07-22 15:31:30 +08:00
// double hash if bitcoin tree
if (this.isBitcoinTree) {
hash = reverse(this.hashAlgo(hash))
}
this.layers[layerIndex].push(hash)
2017-07-22 15:31:30 +08:00
}
// is odd number of nodes
if (nodes.length % 2 === 1) {
let data = nodes[nodes.length-1]
let hash = data
// is bitcoin tree
if (this.isBitcoinTree) {
// Bitcoin method of duplicating the odd ending nodes
data = Buffer.concat([reverse(data), reverse(data)])
hash = this.hashAlgo(data)
hash = reverse(this.hashAlgo(hash))
}
2017-07-22 15:31:30 +08:00
this.layers[layerIndex].push(hash)
2017-07-22 15:31:30 +08:00
}
nodes = this.layers[layerIndex]
2017-07-22 15:31:30 +08:00
}
}
/**
* getLeaves
2017-07-22 16:05:52 +08:00
* @desc Returns array of leaves of Merkle Tree.
* @return {Buffer[]}
2017-07-22 15:31:30 +08:00
* @example
* const leaves = tree.getLeaves()
*/
getLeaves() {
return this.leaves
}
/**
* getLayers
2017-07-22 16:05:52 +08:00
* @desc Returns array of all layers of Merkle Tree, including leaves and root.
* @return {Buffer[]}
2017-07-22 15:31:30 +08:00
* @example
* const layers = tree.getLayers()
*/
getLayers() {
return this.layers
}
/**
* getRoot
2017-07-22 16:05:52 +08:00
* @desc Returns the Merkle root hash as a Buffer.
* @return {Buffer}
2017-07-22 15:31:30 +08:00
* @example
* const root = tree.getRoot()
*/
getRoot() {
2018-10-26 13:04:51 +08:00
return this.layers[this.layers.length-1][0] || Buffer.from([])
2017-07-22 15:31:30 +08:00
}
/**
* getProof
* @desc Returns the proof for a target leaf.
* @param {Buffer} leaf - Target leaf
* @param {Number} [index] - Target leaf index in leaves array.
* Use if there are leaves containing duplicate data in order to distinguish it.
* @return {Object[]} - Array of objects containing a position property of type string
* with values of 'left' or 'right' and a data property of type Buffer.
2017-07-22 15:31:30 +08:00
* @example
* const proof = tree.getProof(leaves[2])
*
* @example
* const leaves = ['a', 'b', 'a'].map(x => sha3(x))
* const tree = new MerkleTree(leaves, sha3)
* const proof = tree.getProof(leaves[2], 2)
*/
getProof(leaf, index) {
2018-10-30 04:58:49 +08:00
leaf = bufferify(leaf)
const proof = []
2017-07-22 15:31:30 +08:00
if (typeof index !== 'number') {
index = -1
for (let i = 0; i < this.leaves.length; i++) {
if (Buffer.compare(leaf, this.leaves[i]) === 0) {
index = i
}
}
}
if (index <= -1) {
return []
}
2018-07-11 07:31:09 +08:00
if (this.isBitcoinTree && index === (this.leaves.length - 1)) {
2017-07-22 15:31:30 +08:00
2018-07-11 05:29:30 +08:00
// Proof Generation for Bitcoin Trees
2017-07-22 15:31:30 +08:00
2018-07-11 05:29:30 +08:00
for (let i = 0; i < this.layers.length - 1; i++) {
const layer = this.layers[i]
const isRightNode = index % 2
2018-07-11 07:31:09 +08:00
const pairIndex = (isRightNode ? index - 1: index)
2018-07-11 05:29:30 +08:00
if (pairIndex < layer.length) {
proof.push({
position: isRightNode ? 'left': 'right',
data: layer[pairIndex]
})
}
// set index to parent index
index = (index / 2)|0
}
return proof
} else {
// Proof Generation for Non-Bitcoin Trees
for (let i = 0; i < this.layers.length; i++) {
const layer = this.layers[i]
const isRightNode = index % 2
const pairIndex = (isRightNode ? index - 1 : index + 1)
if (pairIndex < layer.length) {
proof.push({
position: isRightNode ? 'left': 'right',
data: layer[pairIndex]
})
}
// set index to parent index
index = (index / 2)|0
}
return proof
}
}
2017-07-22 15:31:30 +08:00
/**
* verify
* @desc Returns true if the proof path (array of hashes) can connect the target node
* to the Merkle root.
* @param {Object[]} proof - Array of proof objects that should connect
2017-07-22 15:31:30 +08:00
* target node to Merkle root.
* @param {Buffer} targetNode - Target node Buffer
* @param {Buffer} root - Merkle root Buffer
* @return {Boolean}
* @example
* const root = tree.getRoot()
* const proof = tree.getProof(leaves[2])
* const verified = tree.verify(proof, leaves[2], root)
*
*/
verify(proof, targetNode, root) {
2018-10-27 04:09:38 +08:00
let hash = bufferify(targetNode)
2018-12-10 11:10:43 +08:00
root = bufferify(root)
2017-07-22 15:31:30 +08:00
if (!Array.isArray(proof) ||
!proof.length ||
!targetNode ||
!root) {
return false
}
for (let i = 0; i < proof.length; i++) {
const node = proof[i]
const isLeftNode = (node.position === 'left')
const buffers = []
if (this.isBitcoinTree) {
buffers.push(reverse(hash))
buffers[isLeftNode ? 'unshift' : 'push'](reverse(node.data))
hash = this.hashAlgo(Buffer.concat(buffers))
hash = reverse(this.hashAlgo(hash))
2018-07-11 07:31:09 +08:00
2017-07-22 15:31:30 +08:00
} else {
buffers.push(hash)
buffers[isLeftNode ? 'unshift' : 'push'](node.data)
hash = this.hashAlgo(Buffer.concat(buffers))
}
}
return Buffer.compare(hash, root) === 0
}
2018-10-27 04:09:38 +08:00
2018-12-10 11:57:31 +08:00
// TODO: documentation
getLayersAsObject() {
const layers = this.getLayers().map(x => x.map(x => x.toString('hex')))
2018-12-10 11:10:43 +08:00
const objs = []
for (let i = 0; i < layers.length; i++) {
const arr = []
for (let j = 0; j < layers[i].length; j++) {
2018-12-10 11:57:31 +08:00
const obj = { [layers[i][j]]: null }
2018-12-10 11:10:43 +08:00
if (objs.length) {
2018-12-10 11:57:31 +08:00
obj[layers[i][j]] = {}
2018-12-10 11:10:43 +08:00
const a = objs.shift()
const akey = Object.keys(a)[0]
obj[layers[i][j]][akey] = a[akey]
if (objs.length) {
const b = objs.shift()
const bkey = Object.keys(b)[0]
obj[layers[i][j]][bkey] = b[bkey]
}
}
arr.push(obj)
}
objs.push(...arr)
}
2018-12-10 11:57:31 +08:00
return objs[0]
}
// TODO: documentation
print() {
MerkleTree.print(this)
}
// TODO: documentation
toTreeString() {
const obj = this.getLayersAsObject()
return treeify.asTree(obj, true)
}
// TODO: documentation
toString() {
return this.toTreeString()
}
// TODO: documentation
static bufferify(x) {
return bufferify(x)
}
2018-12-10 11:10:43 +08:00
2018-12-10 11:57:31 +08:00
// TODO: documentation
static print(tree) {
console.log(tree.toString())
2018-12-10 11:10:43 +08:00
}
2017-07-22 15:31:30 +08:00
}
2018-10-27 03:42:14 +08:00
function bufferify(x) {
if (!Buffer.isBuffer(x)) {
// crypto-js support
if (typeof x === 'object' && x.words) {
return Buffer.from(x.toString(CryptoJS.enc.Hex), 'hex')
} else if (isHexStr(x)) {
return Buffer.from(x, 'hex')
} else if (typeof x === 'string') {
return Buffer.from(x)
}
}
return x
}
function bufferifyFn (f) {
return function (x) {
const v = f(x)
if (Buffer.isBuffer(v)) {
return v
}
// crypto-js support
return Buffer.from(f(CryptoJS.enc.Hex.parse(x.toString('hex'))).toString(CryptoJS.enc.Hex), 'hex')
}
}
2018-12-10 11:57:31 +08:00
function isHexStr(v) {
2018-10-27 03:42:14 +08:00
return (typeof v === 'string' && /^(0x)?[0-9A-Fa-f]*$/.test(v))
}
2017-07-22 15:31:30 +08:00
module.exports = MerkleTree