UNPKG

merkletreejs

Version:

Construct Merkle Trees and verify proofs

1 lines 232 kB
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){"use strict";function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function _toPropertyKey(t){var i=_toPrimitive(t,"string");return"symbol"==_typeof(i)?i:i+""}function _toPrimitive(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}var __importDefault=void 0&&(void 0).__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});exports.Base=void 0;var buffer_1=require("buffer");var crypto_js_1=__importDefault(require("crypto-js"));var Base=function(){function Base(){_classCallCheck(this,Base)}return _createClass(Base,[{key:"print",value:function print(){Base.print(this)}},{key:"bufferIndexOf",value:function bufferIndexOf(array,element){var isSorted=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;if(isSorted){return this.binarySearch(array,element,buffer_1.Buffer.compare)}var eqChecker=function eqChecker(buffer1,buffer2){return buffer1.equals(buffer2)};return this.linearSearch(array,element,eqChecker)}},{key:"binarySearch",value:function binarySearch(array,element,compareFunction){return Base.binarySearch(array,element,compareFunction)}},{key:"linearSearch",value:function linearSearch(array,element,eqChecker){return Base.linearSearch(array,element,eqChecker)}},{key:"bigNumberify",value:function bigNumberify(value){return Base.bigNumberify(value)}},{key:"bufferToHex",value:function bufferToHex(value){var withPrefix=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;return Base.bufferToHex(value,withPrefix)}},{key:"bufferify",value:function bufferify(value){return Base.bufferify(value)}},{key:"bufferifyFn",value:function bufferifyFn(f){return Base.bufferifyFn(f)}},{key:"isHexString",value:function isHexString(value){return Base.isHexString(value)}},{key:"log2",value:function log2(n){return n===1?0:1+this.log2(n/2|0)}},{key:"zip",value:function zip(a,b){return a.map(function(e,i){return[e,b[i]]})}},{key:"bufferArrayIncludes",value:function bufferArrayIncludes(bufferArray,targetBuffer){return bufferArray.some(function(buffer){return buffer.equals(targetBuffer!==null&&targetBuffer!==void 0?targetBuffer:buffer_1.Buffer.alloc(0))})}}],[{key:"binarySearch",value:function binarySearch(array,element,compareFunction){var start=0;var end=array.length-1;while(start<=end){var mid=Math.floor((start+end)/2);var ordering=compareFunction(array[mid],element);if(ordering===0){for(var i=mid-1;i>=0;i--){if(compareFunction(array[i],element)===0)continue;return i+1}return 0}else if(ordering<0){start=mid+1}else{end=mid-1}}return-1}},{key:"linearSearch",value:function linearSearch(array,element,eqChecker){for(var i=0;i<array.length;i++){if(eqChecker(array[i],element)){return i}}return-1}},{key:"bufferify",value:function bufferify(value){if(!buffer_1.Buffer.isBuffer(value)){if(_typeof(value)==="object"&&value.words){return buffer_1.Buffer.from(value.toString(crypto_js_1["default"].enc.Hex),"hex")}else if(Base.isHexString(value)){var hexString=value.replace("0x","");var paddedHexString=hexString.length%2?"0"+hexString:hexString;return buffer_1.Buffer.from(paddedHexString,"hex")}else if(typeof value==="string"){return buffer_1.Buffer.from(value)}else if(typeof value==="bigint"){var _hexString=value.toString(16).length%2?"0"+value.toString(16):value.toString(16);return buffer_1.Buffer.from(_hexString,"hex")}else if(value instanceof Uint8Array){return buffer_1.Buffer.from(value.buffer,value.byteOffset,value.byteLength)}else if(typeof value==="number"){var s=value.toString();if(s.length%2){s="0".concat(s)}return buffer_1.Buffer.from(s,"hex")}else if(ArrayBuffer.isView(value)){return buffer_1.Buffer.from(value.buffer,value.byteOffset,value.byteLength)}}return value}},{key:"bufferifyFn",value:function bufferifyFn(f){if(typeof f!=="function"){throw new Error("bufferifyFn expects a function, received: ".concat(_typeof(f)))}return function(value){var v=f(value);if(buffer_1.Buffer.isBuffer(v)){return v}if(Base.isHexString(v)){var hexString=v.replace("0x","");var paddedHexString=hexString.length%2?"0"+hexString:hexString;return buffer_1.Buffer.from(paddedHexString,"hex")}if(typeof v==="string"){return buffer_1.Buffer.from(v)}if(typeof v==="bigint"){var _hexString2=v.toString(16).length%2?"0"+v.toString(16):v.toString(16);return buffer_1.Buffer.from(_hexString2,"hex")}if(ArrayBuffer.isView(v)){return buffer_1.Buffer.from(v.buffer,v.byteOffset,v.byteLength)}return buffer_1.Buffer.from(f(crypto_js_1["default"].enc.Hex.parse(value.toString("hex"))).toString(crypto_js_1["default"].enc.Hex),"hex")}}},{key:"bigNumberify",value:function bigNumberify(value){if(typeof value==="bigint"){return value}if(typeof value==="string"){if(value.startsWith("0x")&&Base.isHexString(value)){var hexString=value.replace("0x","");var paddedHexString=hexString.length%2?"0"+hexString:hexString||"0";return BigInt("0x"+paddedHexString)}return BigInt(value)}if(buffer_1.Buffer.isBuffer(value)){var _hexString3=value.toString("hex");var _paddedHexString=_hexString3.length%2?"0"+_hexString3:_hexString3||"0";return BigInt("0x"+_paddedHexString)}if(value instanceof Uint8Array){var _hexString4=buffer_1.Buffer.from(value).toString("hex");var _paddedHexString2=_hexString4.length%2?"0"+_hexString4:_hexString4||"0";return BigInt("0x"+_paddedHexString2)}if(typeof value==="number"){return BigInt(value)}throw new Error("cannot bigNumberify")}},{key:"isHexString",value:function isHexString(v){return typeof v==="string"&&/^(0x)?[0-9A-Fa-f]*$/.test(v)}},{key:"print",value:function print(tree){console.log(tree.toString())}},{key:"bufferToHex",value:function bufferToHex(value){var withPrefix=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;return"".concat(withPrefix?"0x":"").concat((value||buffer_1.Buffer.alloc(0)).toString("hex"))}},{key:"hexZeroPad",value:function hexZeroPad(hexStr,length){return"0x"+hexStr.replace("0x","").padStart(length,"0")}}])}();exports.Base=Base;exports["default"]=Base},{buffer:12,"crypto-js":23}],2:[function(require,module,exports){"use strict";function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function _defineProperty(e,r,t){return(r=_toPropertyKey(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function F(){};return{s:F,n:function n(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]}},e:function e(r){throw r},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,u=!1;return{s:function s(){t=t.call(r)},n:function n(){var r=t.next();return a=r.done,r},e:function e(r){u=!0,o=r},f:function f(){try{a||null==t["return"]||t["return"]()}finally{if(u)throw o}}}}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function _toPropertyKey(t){var i=_toPrimitive(t,"string");return"symbol"==_typeof(i)?i:i+""}function _toPrimitive(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}function _callSuper(t,o,e){return o=_getPrototypeOf(o),_possibleConstructorReturn(t,_isNativeReflectConstruct()?Reflect.construct(o,e||[],_getPrototypeOf(t).constructor):o.apply(t,e))}function _possibleConstructorReturn(t,e){if(e&&("object"==_typeof(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized(t)}function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct=function _isNativeReflectConstruct(){return!!t})()}function _getPrototypeOf(t){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},_getPrototypeOf(t)}function _inherits(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&_setPrototypeOf(t,e)}function _setPrototypeOf(t,e){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},_setPrototypeOf(t,e)}var __importDefault=void 0&&(void 0).__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});exports.IncrementalMerkleTree=void 0;var Base_1=__importDefault(require("./Base"));var treeify_1=__importDefault(require("treeify"));var IncrementalMerkleTree=function(_Base_1$default){function IncrementalMerkleTree(hashFn,options){var _this;_classCallCheck(this,IncrementalMerkleTree);_this=_callSuper(this,IncrementalMerkleTree);_this.hashFn=hashFn;if(options.depth){_this.depth=options.depth}if(options.arity){_this.arity=options.arity}if(_this.depth<1){throw new Error("depth must be greater than 0")}if(_this.arity<1){throw new Error("arity must be greater than 0")}var nodes=[];var zeroValue=options.zeroValue;_this.zeroValue=zeroValue;_this.zeroes=[];if(_this.depth){for(var i=0;i<_this.depth;i++){_this.zeroes.push(zeroValue);nodes[i]=[];zeroValue=_this.hashFn(Array(_this.arity).fill(zeroValue))}}_this.nodes=nodes;_this.root=zeroValue;return _this}_inherits(IncrementalMerkleTree,_Base_1$default);return _createClass(IncrementalMerkleTree,[{key:"getRoot",value:function getRoot(){return this.root}},{key:"getHexRoot",value:function getHexRoot(){return this.bufferToHex(this.bufferify(this.getRoot()))}},{key:"insert",value:function insert(leaf){if(this.depth&&this.arity){if(this.nodes[0].length>=this.getMaxLeaves()){throw new Error("tree is full")}}var node=leaf;var index=this.nodes[0].length;for(var level=0;level<this.depth;level+=1){var position=index%this.arity;var levelStartIndex=index-position;var levelEndIndex=levelStartIndex+this.arity;var children=[];this.nodes[level][index]=node;for(var i=levelStartIndex;i<levelEndIndex;i+=1){if(i<this.nodes[level].length){children.push(this.nodes[level][i])}else{children.push(this.zeroes[level])}}node=this.hashFn(children);index=Math.floor(index/this.arity)}this.root=node}},{key:"delete",value:function _delete(index){this.update(index,this.zeroValue)}},{key:"update",value:function update(index,newLeaf){if(index<0||index>=this.nodes[0].length){throw new Error("out of bounds")}var node=newLeaf;for(var level=0;level<this.depth;level+=1){var position=index%this.arity;var levelStartIndex=index-position;var levelEndIndex=levelStartIndex+this.arity;var children=[];this.nodes[level][index]=node;for(var i=levelStartIndex;i<levelEndIndex;i+=1){if(i<this.nodes[level].length){children.push(this.nodes[level][i])}else{children.push(this.zeroes[level])}}node=this.hashFn(children);index=Math.floor(index/this.arity)}this.root=node}},{key:"getDepth",value:function getDepth(){return this.depth}},{key:"getArity",value:function getArity(){return this.arity}},{key:"getMaxLeaves",value:function getMaxLeaves(){return Math.pow(this.depth,this.arity)}},{key:"indexOf",value:function indexOf(leaf){return this.nodes[0].indexOf(leaf)}},{key:"getLeaves",value:function getLeaves(){var leaves=this.copyList(this.nodes[0]);var index=this.nodes[0].length;for(var i=index;i<this.getMaxLeaves();i++){leaves[i]=this.zeroValue}return leaves}},{key:"copyList",value:function copyList(list){return list.map(function(x){return BigInt(x)})}},{key:"getLayers",value:function getLayers(){var layers=[];var _iterator=_createForOfIteratorHelper(this.nodes),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var list=_step.value;layers.push(this.copyList(list))}}catch(err){_iterator.e(err)}finally{_iterator.f()}if(layers[0].length<this.getMaxLeaves()){var index=layers[0].length;for(var i=index;i<this.getMaxLeaves();i++){layers[0][i]=this.zeroValue}for(var level=0;level<this.depth;level++){var position=index%this.arity;var levelStartIndex=index-position;var levelEndIndex=levelStartIndex+this.arity;for(var _i=levelStartIndex;_i<levelEndIndex;_i++){if(_i>=layers[level].length){layers[level][_i]=this.zeroes[level]}}index=Math.floor(index/this.arity)}}layers.push([this.root]);return layers}},{key:"getHexLayers",value:function getHexLayers(){var _this2=this;return this.getLayers().reduce(function(acc,item){if(Array.isArray(item)){acc.push(item.map(function(layer){return _this2.bufferToHex(_this2.bufferify(layer))}))}else{acc.push(item)}return acc},[])}},{key:"getLayersAsObject",value:function getLayersAsObject(){var _this3=this;var layers=this.getLayers().map(function(layer){return layer.map(function(value){return _this3.bufferToHex(_this3.bufferify(value),false)})});var objs=[];for(var i=0;i<layers.length;i++){var arr=[];for(var j=0;j<layers[i].length;j++){var obj=_defineProperty({},layers[i][j],null);if(objs.length){obj[layers[i][j]]={};var a=objs.shift();var akey=Object.keys(a)[0];obj[layers[i][j]][akey]=a[akey];if(objs.length){var b=objs.shift();var bkey=Object.keys(b)[0];obj[layers[i][j]][bkey]=b[bkey]}}arr.push(obj)}objs.push.apply(objs,arr)}return objs[0]}},{key:"computeRoot",value:function computeRoot(){var node;var index=this.nodes[0].length;for(var level=0;level<this.depth;level+=1){var position=index%this.arity;var levelStartIndex=index-position;var levelEndIndex=levelStartIndex+this.arity;var children=[];for(var i=levelStartIndex;i<levelEndIndex;i+=1){if(i<this.nodes[level].length){children.push(this.nodes[level][i])}else{children.push(this.zeroes[level])}}node=this.hashFn(children);index=Math.floor(index/this.arity)}return node}},{key:"getProof",value:function getProof(index){if(index<0||index>=this.nodes[0].length){throw new Error("The leaf does not exist in this tree")}var siblings=[];var pathIndices=[];var leafIndex=index;for(var level=0;level<this.depth;level+=1){var position=index%this.arity;var levelStartIndex=index-position;var levelEndIndex=levelStartIndex+this.arity;pathIndices[level]=position;siblings[level]=[];for(var i=levelStartIndex;i<levelEndIndex;i+=1){if(i!==index){if(i<this.nodes[level].length){siblings[level].push(this.nodes[level][i])}else{siblings[level].push(this.zeroes[level])}}}index=Math.floor(index/this.arity)}return{root:this.root,leaf:this.nodes[0][leafIndex],pathIndices:pathIndices,siblings:siblings}}},{key:"verify",value:function verify(proof){var node=proof.leaf;for(var i=0;i<proof.siblings.length;i+=1){var children=proof.siblings[i].slice();children.splice(proof.pathIndices[i],0,node);node=this.hashFn(children)}return proof.root===node}},{key:"toString",value:function toString(){return this.toTreeString()}},{key:"toTreeString",value:function toTreeString(){var obj=this.getLayersAsObject();return treeify_1["default"].asTree(obj,true)}}])}(Base_1["default"]);exports.IncrementalMerkleTree=IncrementalMerkleTree;if(typeof window!=="undefined"){window.IncrementalMerkleTree=IncrementalMerkleTree}exports["default"]=IncrementalMerkleTree},{"./Base":1,treeify:50}],3:[function(require,module,exports){"use strict";function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function _slicedToArray(r,e){return _arrayWithHoles(r)||_iterableToArrayLimit(r,e)||_unsupportedIterableToArray(r,e)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArrayLimit(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t["return"]&&(u=t["return"](),Object(u)!==u))return}finally{if(o)throw n}}return a}}function _arrayWithHoles(r){if(Array.isArray(r))return r}function _toConsumableArray(r){return _arrayWithoutHoles(r)||_iterableToArray(r)||_unsupportedIterableToArray(r)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArray(r){if("undefined"!=typeof Symbol&&null!=r[Symbol.iterator]||null!=r["@@iterator"])return Array.from(r)}function _arrayWithoutHoles(r){if(Array.isArray(r))return _arrayLikeToArray(r)}function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function F(){};return{s:F,n:function n(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]}},e:function e(r){throw r},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,u=!1;return{s:function s(){t=t.call(r)},n:function n(){var r=t.next();return a=r.done,r},e:function e(r){u=!0,o=r},f:function f(){try{a||null==t["return"]||t["return"]()}finally{if(u)throw o}}}}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function _toPropertyKey(t){var i=_toPrimitive(t,"string");return"symbol"==_typeof(i)?i:i+""}function _toPrimitive(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}function _callSuper(t,o,e){return o=_getPrototypeOf(o),_possibleConstructorReturn(t,_isNativeReflectConstruct()?Reflect.construct(o,e||[],_getPrototypeOf(t).constructor):o.apply(t,e))}function _possibleConstructorReturn(t,e){if(e&&("object"==_typeof(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized(t)}function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct=function _isNativeReflectConstruct(){return!!t})()}function _getPrototypeOf(t){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},_getPrototypeOf(t)}function _inherits(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&_setPrototypeOf(t,e)}function _setPrototypeOf(t,e){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},_setPrototypeOf(t,e)}var __importDefault=void 0&&(void 0).__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});exports.MerkleMountainRange=void 0;var buffer_1=require("buffer");var sha256_1=__importDefault(require("crypto-js/sha256"));var Base_1=__importDefault(require("./Base"));var MerkleMountainRange=function(_Base_1$default){function MerkleMountainRange(){var _this;var hashFn=arguments.length>0&&arguments[0]!==undefined?arguments[0]:sha256_1["default"];var leaves=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];var hashLeafFn=arguments.length>2?arguments[2]:undefined;var peakBaggingFn=arguments.length>3?arguments[3]:undefined;var hashBranchFn=arguments.length>4?arguments[4]:undefined;_classCallCheck(this,MerkleMountainRange);_this=_callSuper(this,MerkleMountainRange);_this.root=buffer_1.Buffer.alloc(0);_this.size=0;_this.width=0;_this.hashes={};_this.data={};leaves=leaves.map(_this.bufferify);_this.hashFn=_this.bufferifyFn(hashFn);_this.hashLeafFn=hashLeafFn;_this.peakBaggingFn=peakBaggingFn;_this.hashBranchFn=hashBranchFn;var _iterator=_createForOfIteratorHelper(leaves),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var leaf=_step.value;_this.append(leaf)}}catch(err){_iterator.e(err)}finally{_iterator.f()}return _this}_inherits(MerkleMountainRange,_Base_1$default);return _createClass(MerkleMountainRange,[{key:"append",value:function append(data){data=this.bufferify(data);var dataHash=this.hashFn(data);var dataHashHex=this.bufferToHex(dataHash);if(!this.data[dataHashHex]||this.bufferToHex(this.hashFn(this.data[dataHashHex]))!==dataHashHex){this.data[dataHashHex]=data}var leaf=this.hashLeaf(this.size+1,dataHash);this.hashes[this.size+1]=leaf;this.width+=1;var peakIndexes=this.getPeakIndexes(this.width);this.size=this.getSize(this.width);var peaks=[];for(var i=0;i<peakIndexes.length;i++){peaks[i]=this._getOrCreateNode(peakIndexes[i])}this.root=this.peakBagging(this.width,peaks)}},{key:"hashLeaf",value:function hashLeaf(index,dataHash){dataHash=this.bufferify(dataHash);if(this.hashLeafFn){return this.bufferify(this.hashLeafFn(index,dataHash))}return this.hashFn(buffer_1.Buffer.concat([this.bufferify(index),dataHash]))}},{key:"hashBranch",value:function hashBranch(index,left,right){if(this.hashBranchFn){return this.bufferify(this.hashBranchFn(index,left,right))}return this.hashFn(buffer_1.Buffer.concat([this.bufferify(index),this.bufferify(left),this.bufferify(right)]))}},{key:"getPeaks",value:function getPeaks(){var peakIndexes=this.getPeakIndexes(this.width);var peaks=[];for(var i=0;i<peakIndexes.length;i++){peaks[i]=this.hashes[peakIndexes[i]]}return peaks}},{key:"getLeafIndex",value:function getLeafIndex(width){if(width%2===1){return this.getSize(width)}return this.getSize(width-1)+1}},{key:"getPeakIndexes",value:function getPeakIndexes(width){var numPeaks=this.numOfPeaks(width);var peakIndexes=[];var count=0;var size=0;for(var i=255;i>0;i--){if((width&1<<i-1)!==0){size=size+(1<<i)-1;peakIndexes[count++]=size;if(peakIndexes.length>=numPeaks){break}}}if(count!==peakIndexes.length){throw new Error("invalid bit calculation")}return peakIndexes}},{key:"numOfPeaks",value:function numOfPeaks(width){var bits=width;var num=0;while(bits>0){if(bits%2===1){num++}bits=bits>>1}return num}},{key:"peakBagging",value:function peakBagging(width,peaks){var size=this.getSize(width);if(this.numOfPeaks(width)!==peaks.length){throw new Error("received invalid number of peaks")}if(width===0&&!peaks.length){return buffer_1.Buffer.alloc(0)}if(this.peakBaggingFn){return this.bufferify(this.peakBaggingFn(size,peaks))}return this.hashFn(buffer_1.Buffer.concat([this.bufferify(size)].concat(_toConsumableArray(peaks.map(this.bufferify)))))}},{key:"getSize",value:function getSize(width){return(width<<1)-this.numOfPeaks(width)}},{key:"getRoot",value:function getRoot(){return this.root}},{key:"getHexRoot",value:function getHexRoot(){return this.bufferToHex(this.getRoot())}},{key:"getNode",value:function getNode(index){return this.hashes[index]}},{key:"mountainHeight",value:function mountainHeight(size){var height=1;while(1<<height<=size+height){height++}return height-1}},{key:"heightAt",value:function heightAt(index){var reducedIndex=index;var peakIndex=0;var height=0;while(reducedIndex>peakIndex){reducedIndex-=(1<<height)-1;height=this.mountainHeight(reducedIndex);peakIndex=(1<<height)-1}return height-(peakIndex-reducedIndex)}},{key:"isLeaf",value:function isLeaf(index){return this.heightAt(index)===1}},{key:"getChildren",value:function getChildren(index){var left=index-(1<<this.heightAt(index)-1);var right=index-1;if(left===right){throw new Error("not a parent")}return[left,right]}},{key:"getMerkleProof",value:function getMerkleProof(index){if(index>this.size){throw new Error("out of range")}if(!this.isLeaf(index)){throw new Error("not a leaf")}var root=this.root;var width=this.width;var peaks=this.getPeakIndexes(this.width);var peakBagging=[];var cursor=0;for(var i=0;i<peaks.length;i++){peakBagging[i]=this.hashes[peaks[i]];if(peaks[i]>=index&&cursor===0){cursor=peaks[i]}}var left=0;var right=0;var height=this.heightAt(cursor);var siblings=[];while(cursor!==index){height--;var _this$getChildren=this.getChildren(cursor);var _this$getChildren2=_slicedToArray(_this$getChildren,2);left=_this$getChildren2[0];right=_this$getChildren2[1];cursor=index<=left?left:right;siblings[height-1]=this.hashes[index<=left?right:left]}return{root:root,width:width,peakBagging:peakBagging,siblings:siblings}}},{key:"verify",value:function verify(root,width,index,value,peaks,siblings){value=this.bufferify(value);var size=this.getSize(width);if(size<index){throw new Error("index is out of range")}if(!root.equals(this.peakBagging(width,peaks))){throw new Error("invalid root hash from the peaks")}var cursor=0;var targetPeak;var peakIndexes=this.getPeakIndexes(width);for(var i=0;i<peakIndexes.length;i++){if(peakIndexes[i]>=index){targetPeak=peaks[i];cursor=peakIndexes[i];break}}if(!targetPeak){throw new Error("target not found")}var height=siblings.length+1;var path=new Array(height);var left=0;var right=0;while(height>0){path[--height]=cursor;if(cursor===index){break}else{var _this$getChildren3=this.getChildren(cursor);var _this$getChildren4=_slicedToArray(_this$getChildren3,2);left=_this$getChildren4[0];right=_this$getChildren4[1];cursor=index>left?right:left;continue}}var node;while(height<path.length){cursor=path[height];if(height===0){node=this.hashLeaf(cursor,this.hashFn(value))}else if(cursor-1===path[height-1]){node=this.hashBranch(cursor,siblings[height-1],node)}else{node=this.hashBranch(cursor,node,siblings[height-1])}height++}if(!node.equals(targetPeak)){throw new Error("hashed peak is invalid")}return true}},{key:"peaksToPeakMap",value:function peaksToPeakMap(width,peaks){var peakMap={};var bitIndex=0;var peakRef=0;var count=peaks.length;for(var height=1;height<=32;height++){bitIndex=32-height;peakRef=1<<height-1;if((width&peakRef)!==0){peakMap[bitIndex]=peaks[--count]}else{peakMap[bitIndex]=0}}if(count!==0){throw new Error("invalid number of peaks")}return peakMap}},{key:"peakMapToPeaks",value:function peakMapToPeaks(width,peakMap){var arrLength=this.numOfPeaks(width);var peaks=new Array(arrLength);var count=0;for(var i=0;i<32;i++){if(peakMap[i]!==0){peaks[count++]=peakMap[i]}}if(count!==arrLength){throw new Error("invalid number of peaks")}return peaks}},{key:"peakUpdate",value:function peakUpdate(width,prevPeakMap,itemHash){var nextPeakMap={};var newWidth=width+1;var cursorIndex=this.getLeafIndex(newWidth);var cursorNode=this.hashLeaf(cursorIndex,itemHash);var bitIndex=0;var peakRef=0;var prevPeakExist=false;var nextPeakExist=false;var obtained=false;for(var height=1;height<=32;height++){bitIndex=32-height;if(obtained){nextPeakMap[bitIndex]=prevPeakMap[bitIndex]}else{peakRef=1<<height-1;prevPeakExist=(width&peakRef)!==0;nextPeakExist=(newWidth&peakRef)!==0;cursorIndex++;if(prevPeakExist){cursorNode=this.hashBranch(cursorIndex,prevPeakMap[bitIndex],cursorNode)}if(nextPeakExist){if(prevPeakExist){nextPeakMap[bitIndex]=prevPeakMap[bitIndex]}else{nextPeakMap[bitIndex]=cursorNode}obtained=true}else{nextPeakMap[bitIndex]=0}}}return nextPeakMap}},{key:"rollUp",value:function rollUp(root,width,peaks,itemHashes){if(!root.equals(this.peakBagging(width,peaks))){throw new Error("invalid root hash from the peaks")}var tmpWidth=width;var tmpPeakMap=this.peaksToPeakMap(width,peaks);for(var i=0;i<itemHashes.length;i++){tmpPeakMap=this.peakUpdate(tmpWidth,tmpPeakMap,itemHashes[i]);tmpWidth++}return this.peakBagging(tmpWidth,this.peakMapToPeaks(tmpWidth,tmpPeakMap))}},{key:"_getOrCreateNode",value:function _getOrCreateNode(index){if(index>this.size){throw new Error("out of range")}if(!this.hashes[index]){var _this$getChildren5=this.getChildren(index),_this$getChildren6=_slicedToArray(_this$getChildren5,2),leftIndex=_this$getChildren6[0],rightIndex=_this$getChildren6[1];var leftHash=this._getOrCreateNode(leftIndex);var rightHash=this._getOrCreateNode(rightIndex);this.hashes[index]=this.hashBranch(index,leftHash,rightHash)}return this.hashes[index]}}])}(Base_1["default"]);exports.MerkleMountainRange=MerkleMountainRange;if(typeof window!=="undefined"){window.MerkleMountainRange=MerkleMountainRange}exports["default"]=MerkleMountainRange},{"./Base":1,buffer:12,"crypto-js/sha256":43}],4:[function(require,module,exports){(function(Buffer){(function(){"use strict";function _toConsumableArray(r){return _arrayWithoutHoles(r)||_iterableToArray(r)||_unsupportedIterableToArray(r)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArray(r){if("undefined"!=typeof Symbol&&null!=r[Symbol.iterator]||null!=r["@@iterator"])return Array.from(r)}function _arrayWithoutHoles(r){if(Array.isArray(r))return _arrayLikeToArray(r)}function _callSuper(t,o,e){return o=_getPrototypeOf(o),_possibleConstructorReturn(t,_isNativeReflectConstruct()?Reflect.construct(o,e||[],_getPrototypeOf(t).constructor):o.apply(t,e))}function _possibleConstructorReturn(t,e){if(e&&("object"==_typeof(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized(t)}function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct=function _isNativeReflectConstruct(){return!!t})()}function _getPrototypeOf(t){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},_getPrototypeOf(t)}function _inherits(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&_setPrototypeOf(t,e)}function _setPrototypeOf(t,e){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},_setPrototypeOf(t,e)}function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function F(){};return{s:F,n:function n(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]}},e:function e(r){throw r},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,u=!1;return{s:function s(){t=t.call(r)},n:function n(){var r=t.next();return a=r.done,r},e:function e(r){u=!0,o=r},f:function f(){try{a||null==t["return"]||t["return"]()}finally{if(u)throw o}}}}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function _toPropertyKey(t){var i=_toPrimitive(t,"string");return"symbol"==_typeof(i)?i:i+""}function _toPrimitive(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}var __importDefault=void 0&&(void 0).__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});exports.MerkleRadixTree=void 0;var Base_1=__importDefault(require("./Base"));var MerkleRadixNode=function(){function MerkleRadixNode(){var key=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"";var value=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var hashFn=arguments.length>2?arguments[2]:undefined;_classCallCheck(this,MerkleRadixNode);this.key=key;this.value=value;this.children=new Map;this.hashFn=hashFn;this.hash=this.computeHash()}return _createClass(MerkleRadixNode,[{key:"computeHash",value:function computeHash(){var hash=this.hashFn("");hash=Buffer.concat([hash,Base_1["default"].bufferify(this.key),this.value!=null?Base_1["default"].bufferify(this.value):Buffer.alloc(0)]);var _iterator=_createForOfIteratorHelper(this.children.values()),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var child=_step.value;hash=Buffer.concat([hash,child.hash])}}catch(err){_iterator.e(err)}finally{_iterator.f()}var result=this.hashFn(hash);return result}},{key:"updateHash",value:function updateHash(){this.hash=this.computeHash()}}])}();var MerkleRadixTree=function(_Base_1$default){function MerkleRadixTree(hashFn){var _this;_classCallCheck(this,MerkleRadixTree);_this=_callSuper(this,MerkleRadixTree);_this.hashFn=_this.bufferifyFn(hashFn);_this.root=new MerkleRadixNode("",null,_this.hashFn);return _this}_inherits(MerkleRadixTree,_Base_1$default);return _createClass(MerkleRadixTree,[{key:"insert",value:function insert(key,value){var node=this.root;var commonPrefixLength=0;while(key.length>0){var child=_toConsumableArray(node.children.values()).find(function(child){return key.startsWith(child.key)});if(!child){node.children.set(key,new MerkleRadixNode(key,value,this.hashFn));node.updateHash();return}commonPrefixLength=this.commonPrefixLength(key,child.key);if(commonPrefixLength===child.key.length){node=child;key=key.slice(commonPrefixLength)}else{var commonPrefix=key.slice(0,commonPrefixLength);var childSuffix=child.key.slice(commonPrefixLength);var newNode=new MerkleRadixNode(commonPrefix,null,this.hashFn);node.children["delete"](child.key);node.children.set(commonPrefix,newNode);newNode.children.set(childSuffix,child);child.key=childSuffix;if(commonPrefixLength<key.length){var suffix=key.slice(commonPrefixLength);newNode.children.set(suffix,new MerkleRadixNode(suffix,value,this.hashFn))}else{newNode.value=value}node.updateHash();newNode.updateHash();return}}node.value=value;node.updateHash()}},{key:"lookup",value:function lookup(key){var node=this.root;while(key.length>0){var child=_toConsumableArray(node.children.values()).find(function(child){return key.startsWith(child.key)});if(!child){return null}var commonPrefixLength=this.commonPrefixLength(key,child.key);if(commonPrefixLength===child.key.length){node=child;key=key.slice(commonPrefixLength)}else{return null}}return node.value}},{key:"commonPrefixLength",value:function commonPrefixLength(str1,str2){var length=0;while(length<str1.length&&length<str2.length&&str1[length]===str2[length]){length++}return length}},{key:"generateProof",value:function generateProof(key){var node=this.root;var proof=[];while(key.length>0){var siblings=[];var _iterator2=_createForOfIteratorHelper(node.children.values()),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var _child=_step2.value;if(_child.key!==key){siblings.push({key:_child.key,hash:_child.hash})}}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}proof.push({key:node.key,hash:node.hash,siblings:siblings});var child=_toConsumableArray(node.children.values()).find(function(child){return key.startsWith(child.key)});if(!child){return null}var commonPrefixLength=this.commonPrefixLength(key,child.key);if(commonPrefixLength===child.key.length){node=child;key=key.slice(commonPrefixLength)}else{return null}}proof.push({key:node.key,hash:node.hash,siblings:[]});return proof}},{key:"verifyProof",value:function verifyProof(proof,rootHash){if(!proof||proof.length===0){return false}var currentHash=proof[proof.length-1].hash;for(var i=proof.length-2;i>=0;i--){var item=proof[i];var concatenatedHash=Buffer.concat([this.hashFn(""),this.bufferify(item.key),currentHash]);var _iterator3=_createForOfIteratorHelper(item.siblings),_step3;try{for(_iterator3.s();!(_step3=_iterator3.n()).done;){var sibling=_step3.value;concatenatedHash=Buffer.concat([concatenatedHash,sibling.hash])}}catch(err){_iterator3.e(err)}finally{_iterator3.f()}currentHash=this.hashFn(concatenatedHash)}return currentHash.equals(rootHash)}}])}(Base_1["default"]);exports.MerkleRadixTree=MerkleRadixTree}).call(this)}).call(this,require("buffer").Buffer)},{"./Base":1,buffer:12}],5:[function(require,module,exports){(function(Buffer){(function(){"use strict";function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function F(){};return{s:F,n:function n(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]}},e:function e(r){throw r},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,u=!1;return{s:function s(){t=t.call(r)},n:function n(){var r=t.next();return a=r.done,r},e:function e(r){u=!0,o=r},f:function f(){try{a||null==t["return"]||t["return"]()}finally{if(u)throw o}}}}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _callSuper(t,o,e){return o=_getPrototypeOf(o),_possibleConstructorReturn(t,_isNativeReflectConstruct()?Reflect.construct(o,e||[],_getPrototypeOf(t).constructor):o.apply(t,e))}function _possibleConstructorReturn(t,e){if(e&&("object"==_typeof(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized(t)}function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct=function _isNativeReflectConstruct(){return!!t})()}function _getPrototypeOf(t){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},_getPrototypeOf(t)}function _inherits(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&_setPrototypeOf(t,e)}function _setPrototypeOf(t,e){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},_setPrototypeOf(t,e)}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function _toPropertyKey(t){var i=_toPrimitive(t,"string");return"symbol"==_typeof(i)?i:i+""}function _toPrimitive(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(exports,"__esModule",{value:true});exports.MerkleSumTree=exports.ProofStep=exports.Leaf=exports.Bucket=void 0;var Base_1=require("./Base");var Bucket=_createClass(function Bucket(size,hashed){_classCallCheck(this,Bucket);this.size=BigInt(size);this.hashed=hashed;this.parent=null;this.left=null;this.right=null});exports.Bucket=Bucket;var Leaf=function(){function Leaf(hashFn,rng,data){_classCallCheck(this,Leaf);this.hashFn=hashFn;this.rng=rng.map(function(x){return BigInt(x)});this.data=data}return _createClass(Leaf,[{key:"getBucket",value:function getBucket(){var hashed;if(this.data){hashed=this.hashFn(this.data)}else{hashed=Buffer.alloc(32)}return new Bucket(BigInt(this.rng[1])-BigInt(this.rng[0]),hashed)}}])}();exports.Leaf=Leaf;var ProofStep=_createClass(function ProofStep(bucket,right){_classCallCheck(this,ProofStep);this.bucket=bucket;this.right=right});exports.ProofStep=ProofStep;var MerkleSumTree=function(_Base_1$Base){function MerkleSumTree(leaves,hashFn){var _this;_classCallCheck(this,MerkleSumTree);_this=_callSuper(this,MerkleSumTree);_this.leaves=leaves;_this.hashFn=hashFn;MerkleSumTree.checkConsecutive(leaves);_this.buckets=[];var _iterator=_createForOfIteratorHelper(leaves),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var l=_step.value;_this.buckets.push(l.getBucket())}}catch(err){_iterator.e(err)}finally{_iterator.f()}var buckets=[];var _iterator2=_createForOfIteratorHelper(_this.buckets),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var bucket=_step2.value;buckets.push(bucket)}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}while(buckets.length!==1){var newBuckets=[];while(buckets.length){if(buckets.length>=2){var b1=buckets.shift();var b2=buckets.shift();var size=b1.size+b2.size;var hashed=_this.hashFn(Buffer.concat([_this.sizeToBuffer(b1.size),_this.bufferify(b1.hashed),_this.sizeToBuffer(b2.size),_this.bufferify(b2.hashed)]));var b=new Bucket(size,hashed);b2.parent=b;b1.parent=b2.parent;b1.right=b2;b2.left=b1;newBuckets.push(b)}else{newBuckets.push(buckets.shift())}}buckets=newBuckets}_this.root=buckets[0];return _this}_inherits(MerkleSumTree,_Base_1$Base);return _createClass(MerkleSumTree,[{key:"sizeToBuffer",value:function sizeToBuffer(size){var buf=Buffer.alloc(8);var view=new DataView(buf.buffer);view.setBigInt64(0,BigInt(size),false);return buf}},{key:"getProof",value:function getProof(index){var curr=this.buckets[Number(index)];var proof=[];while(curr&&curr.parent){var right=!!curr.right;var bucket=curr.right?curr.right:curr.left;curr=curr.parent;proof.push(new ProofStep(bucket,right))}return proof}},{key:"sum",value:function sum(arr){var total=BigInt(0);var _iterator3=_createForOfIteratorHelper(arr),_step3;try{for(_iterator3.s();!(_step3=_iterator3.n()).done;){var value=_step3.value;total+=BigInt(value)}}catch(err){_iterator3.e(err)}finally{_iterator3.f()}return total}},{key:"verifyProof",value:function verifyProof(root,leaf,proof){var rng=[this.sum(proof.filter(function(x){return!x.right}).map(function(x){return x.bucket.size})),BigInt(root.size)-this.sum(proof.filter(function(x){return x.right}).map(function(x){return x.bucket.size}))];if(!(rng[0]===leaf.rng[0]&&rng[1]===leaf.rng[1])){return false}var curr=leaf.getBucket();var hashed;var _iterator4=_createForOfIteratorHelper(proof),_step4;try{for(_iterator4.s();!(_step4=_iterator4.n()).done;){var step=_step4.value;if(step.right){hashed=this.hashFn(Buffer.concat([this.sizeToBuffer(curr.size),this.bufferify(curr.hashed),this.sizeToBuffer(step.bucket.size),this.bufferify(step.bucket.hashed)]))}else{hashed=this.hashFn(Buffer.concat([this.sizeToBuffer(step.bucket.size),this.bufferify(step.bucket.hashed),this.sizeToBuffer(curr.size),this.bufferify(curr.hashed)]))}curr=new Bucket(BigInt(curr.size)+BigInt(step.bucket.size),hashed)}}catch(err){_iterator4.e(err)}finally{_iterator4.f()}return curr.size===root.size&&curr.hashed.toString("hex")===root.hashed.toString("hex")}}],[{key:"checkConsecutive",value:function checkConsecutive(leaves){var curr=BigInt(0);var _iterator5=_createForOfIteratorHelper(leaves),_step5;try{for(_iterator5.s();!(_step5=_iterator5.n()).done;){var leaf=_step5.value;if(leaf.rng[0]!==curr){throw new Error("leaf ranges are invalid")}curr=BigInt(leaf.rng[1])}}catch(err){_iterator5.e(err)}finally{_iterator5.f()}}}])}(Base_1.Base);exports.MerkleSumTree=MerkleSumTree;if(typeof window!=="undefined"){window.MerkleSumTree=MerkleSumTree}exports["default"]=MerkleSumTree}).call(this)}).call(this,require("buffer").Buffer)},{"./Base":1,buffer:12}],6:[function(require,module,exports){"use strict";function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.const