diff --git a/build.js b/build.js index 6c0949e..57d1a90 100644 --- a/build.js +++ b/build.js @@ -1,23 +1,25 @@ /* * nwjs builder script */ -var NwBuilder = require('nw-builder'); -var nw = new NwBuilder({ - files: './build/**', // use the glob format - platforms: ['osx64', 'win32', 'win64', 'linux32', 'linux64'], - cacheDir: './cache', - buildDir: './builds/', - macIcns: './build/images/FreeWallet.icns', - // macCredits: './build/html/credits.html' - // winIco: '', -}); +import nwbuilder from 'nw-builder'; -// Output logs to the console -nw.on('log', console.log); +async function init(){ -// Build returns a promise -nw.build().then(function () { - console.log('all done!'); -}).catch(function (error) { - console.error(error); -}); \ No newline at end of file + var nw = await nwbuilder({ + srcDir: './build/**', // use the glob format + platform: "win", + arch: "x64", + cacheDir: './cache', + outDir: './builds/', + icon: './build/images/FreeWallet.icns', + // macCredits: './build/html/credits.html' //no longer exists + // winIco: '', //no longer exists + }); + + // Output logs to the console + //nw.on('log', console.log); //This event no longer exists + + console.log('all done!'); +} + +init() diff --git a/build.sh b/build.sh index 4671ab0..b1b11a1 100755 --- a/build.sh +++ b/build.sh @@ -15,8 +15,8 @@ nwjs=/Applications/nwjs.app/Contents/MacOS/nwjs ### # Verify we are building on a mac -if [ "$OSTYPE" != "darwin" ] ; then - echo "Build script is meant to be run on MacOS!" +if [ "$OSTYPE" != "darwin" ] && [ "$OSTYPE" != "linux-gnu" ]; then + echo "Build script is meant to be run on MacOS or Linux!" exit fi diff --git a/js/bitcoinjs-lib.min.js b/js/bitcoinjs-lib.min.js index ff70003..41a22ab 100644 --- a/js/bitcoinjs-lib.min.js +++ b/js/bitcoinjs-lib.min.js @@ -1,2 +1,16583 @@ -/*----------------vendors/bitcoinjs-lib/bitcoinjs.min.js---------------*/ -!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).bitcoinjs=t()}}(function(){return function(){return function t(e,r,n){function i(o,f){if(!r[o]){if(!e[o]){var a="function"==typeof require&&require;if(!f&&a)return a(o,!0);if(s)return s(o,!0);var u=new Error("Cannot find module '"+o+"'");throw u.code="MODULE_NOT_FOUND",u}var c=r[o]={exports:{}};e[o][0].call(c.exports,function(t){return i(e[o][1][t]||t)},c,c.exports,t,e,r,n)}return r[o].exports}for(var s="function"==typeof require&&require,o=0;o=255)throw new TypeError("Alphabet too long");var e=new Uint8Array(256);e.fill(255);for(var r=0;r>>0,c=new Uint8Array(u);t[r];){var h=e[t.charCodeAt(r)];if(255===h)return;for(var d=0,p=u-1;(0!==h||d>>0,c[p]=h%256>>>0,h=h/256>>>0;if(0!==h)throw new Error("Non-zero carry");s=d,r++}if(" "!==t[r]){for(var l=u-s;l!==u&&0===c[l];)l++;var b=n.allocUnsafe(i+(u-l));b.fill(0,0,i);for(var m=i;l!==u;)b[m++]=c[l++];return b}}}return{encode:function(e){if(!n.isBuffer(e))throw new TypeError("Expected Buffer");if(0===e.length)return"";for(var r=0,i=0,s=0,a=e.length;s!==a&&0===e[s];)s++,r++;for(var c=(a-s)*u+1>>>0,h=new Uint8Array(c);s!==a;){for(var d=e[s],p=0,l=c-1;(0!==d||p>>0,h[l]=d%o>>>0,d=d/o>>>0;if(0!==d)throw new Error("Non-zero carry");i=p,s++}for(var b=c-i;b!==c&&0===h[b];)b++;for(var m=f.repeat(r);b>25;return(33554431&t)<<5^996825010&-(e>>0&1)^642813549&-(e>>1&1)^513874426&-(e>>2&1)^1027748829&-(e>>3&1)^705979059&-(e>>4&1)}function a(t){for(var e=1,r=0;r126)throw new Error("Invalid prefix ("+t+")");e=f(e)^n>>5}for(e=f(e),r=0;r=r;)s-=r,f.push(i>>s&o);if(n)s>0&&f.push(i<=e)throw new Error("Excess padding");if(i<e)throw new TypeError("Exceeds length limit");var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)throw new Error("Mixed-case string "+t);var s=(t=r).lastIndexOf("1");if(-1===s)throw new Error("No separator character for "+t);if(0===s)throw new Error("Missing prefix for "+t);var o=t.slice(0,s),u=t.slice(s+1);if(u.length<6)throw new Error("Data too short");for(var c=a(o),h=[],d=0;d=u.length||h.push(l)}if(1!==c)throw new Error("Invalid checksum for "+t);return{prefix:o,words:h}},encode:function(t,e,r){if(r=r||90,t.length+7+e.length>r)throw new TypeError("Exceeds length limit");for(var i=a(t=t.toLowerCase()),s=t+"1",o=0;o>5!=0)throw new Error("Non 5-bit word");i=f(i)^u,s+=n.charAt(u)}for(o=0;o<6;++o)i=f(i);for(i^=1,o=0;o<6;++o){var c=i>>5*(5-o)&31;s+=n.charAt(c)}return s},toWords:function(t){return u(t,8,5,!0)},fromWords:function(t){return u(t,5,8,!1)}}},{}],3:[function(t,e,r){let n=t("create-hash"),i=t("create-hmac");e.exports={hash160:function(t){const e=n("sha256").update(t).digest();try{return n("rmd160").update(e).digest()}catch(t){return n("ripemd160").update(e).digest()}},hmacSHA512:function(t,e){return i("sha512",t).update(e).digest()}}},{"create-hash":14,"create-hmac":16}],4:[function(t,e,r){let n=t("safe-buffer").Buffer,i=t("bs58check"),s=t("./crypto"),o=t("tiny-secp256k1"),f=t("typeforce"),a=t("wif"),u=f.BufferN(32),c=f.compile({wif:f.UInt8,bip32:{public:f.UInt32,private:f.UInt32}}),h={wif:128,bip32:{public:76067358,private:76066276}};function d(t,e,r,n){f(c,n),this.__d=t||null,this.__Q=e||null,this.chainCode=r,this.depth=0,this.index=0,this.network=n,this.parentFingerprint=0}Object.defineProperty(d.prototype,"identifier",{get:function(){return s.hash160(this.publicKey)}}),Object.defineProperty(d.prototype,"fingerprint",{get:function(){return this.identifier.slice(0,4)}}),Object.defineProperty(d.prototype,"privateKey",{enumerable:!1,get:function(){return this.__d}}),Object.defineProperty(d.prototype,"publicKey",{get:function(){return this.__Q||(this.__Q=o.pointFromScalar(this.__d,this.compressed)),this.__Q}}),d.prototype.isNeutered=function(){return null===this.__d},d.prototype.neutered=function(){let t=y(this.publicKey,this.chainCode,this.network);return t.depth=this.depth,t.index=this.index,t.parentFingerprint=this.parentFingerprint,t},d.prototype.toBase58=function(){let t=this.network,e=this.isNeutered()?t.bip32.public:t.bip32.private,r=n.allocUnsafe(78);return r.writeUInt32BE(e,0),r.writeUInt8(this.depth,4),r.writeUInt32BE(this.parentFingerprint,5),r.writeUInt32BE(this.index,9),this.chainCode.copy(r,13),this.isNeutered()?this.publicKey.copy(r,45):(r.writeUInt8(0,45),this.privateKey.copy(r,46)),i.encode(r)},d.prototype.toWIF=function(){if(!this.privateKey)throw new TypeError("Missing private key");return a.encode(this.network.wif,this.privateKey,!0)};d.prototype.derive=function(t){f(f.UInt32,t);let e=t>=2147483648,r=n.allocUnsafe(37);if(e){if(this.isNeutered())throw new TypeError("Missing private key for hardened child key");r[0]=0,this.privateKey.copy(r,1),r.writeUInt32BE(t,33)}else this.publicKey.copy(r,0),r.writeUInt32BE(t,33);let i,a=s.hmacSHA512(this.chainCode,r),u=a.slice(0,32),c=a.slice(32);if(!o.isPrivate(u))return this.derive(t+1);if(this.isNeutered()){let e=o.pointAddScalar(this.publicKey,u,!0);if(null===e)return this.derive(t+1);i=y(e,c,this.network)}else{let e=o.privateAdd(this.privateKey,u);if(null==e)return this.derive(t+1);i=m(e,c,this.network)}return i.depth=this.depth+1,i.index=t,i.parentFingerprint=this.fingerprint.readUInt32BE(0),i};let p=Math.pow(2,31)-1;function l(t){return f.UInt32(t)&&t<=p}function b(t){return f.String(t)&&t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}function m(t,e,r){if(f({privateKey:u,chainCode:u},{privateKey:t,chainCode:e}),r=r||h,!o.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return new d(t,null,e,r)}function y(t,e,r){if(f({publicKey:f.BufferN(33),chainCode:u},{publicKey:t,chainCode:e}),r=r||h,!o.isPoint(t))throw new TypeError("Point is not on the curve");return new d(null,t,e,r)}d.prototype.deriveHardened=function(t){return f(l,t),this.derive(t+2147483648)},d.prototype.derivePath=function(t){f(b,t);let e=t.split("/");if("m"===e[0]){if(this.parentFingerprint)throw new TypeError("Expected master, got child");e=e.slice(1)}return e.reduce(function(t,e){let r;return"'"===e.slice(-1)?(r=parseInt(e.slice(0,-1),10),t.deriveHardened(r)):(r=parseInt(e,10),t.derive(r))},this)},d.prototype.sign=function(t){return o.sign(t,this.privateKey)},d.prototype.verify=function(t,e){return o.verify(t,this.publicKey,e)},e.exports={fromBase58:function(t,e){let r=i.decode(t);if(78!==r.length)throw new TypeError("Invalid buffer length");e=e||h;let n=r.readUInt32BE(0);if(n!==e.bip32.private&&n!==e.bip32.public)throw new TypeError("Invalid network version");let s=r[4],o=r.readUInt32BE(5);if(0===s&&0!==o)throw new TypeError("Invalid parent fingerprint");let f=r.readUInt32BE(9);if(0===s&&0!==f)throw new TypeError("Invalid index");let a,u=r.slice(13,45);if(n===e.bip32.private){if(0!==r.readUInt8(45))throw new TypeError("Invalid private key");a=m(r.slice(46,78),u,e)}else a=y(r.slice(45,78),u,e);return a.depth=s,a.index=f,a.parentFingerprint=o,a},fromPrivateKey:m,fromPublicKey:y,fromSeed:function(t,e){if(f(f.Buffer,t),t.length<16)throw new TypeError("Seed should be at least 128 bits");if(t.length>64)throw new TypeError("Seed should be at most 512 bits");e=e||h;let r=s.hmacSHA512("Bitcoin seed",t);return m(r.slice(0,32),r.slice(32),e)}}},{"./crypto":3,bs58check:12,"safe-buffer":56,"tiny-secp256k1":65,typeforce:69,wif:72}],5:[function(t,e,r){var n=t("safe-buffer").Buffer;e.exports={check:function(t){if(t.length<8)return!1;if(t.length>72)return!1;if(48!==t[0])return!1;if(t[1]!==t.length-2)return!1;if(2!==t[2])return!1;var e=t[3];if(0===e)return!1;if(5+e>=t.length)return!1;if(2!==t[4+e])return!1;var r=t[5+e];return!(0===r||6+e+r!==t.length||128&t[4]||e>1&&0===t[4]&&!(128&t[5])||128&t[e+6]||r>1&&0===t[e+6]&&!(128&t[e+7]))},decode:function(t){if(t.length<8)throw new Error("DER sequence length is too short");if(t.length>72)throw new Error("DER sequence length is too long");if(48!==t[0])throw new Error("Expected DER sequence");if(t[1]!==t.length-2)throw new Error("DER sequence length is invalid");if(2!==t[2])throw new Error("Expected DER integer");var e=t[3];if(0===e)throw new Error("R length is zero");if(5+e>=t.length)throw new Error("R length is too long");if(2!==t[4+e])throw new Error("Expected DER integer (2)");var r=t[5+e];if(0===r)throw new Error("S length is zero");if(6+e+r!==t.length)throw new Error("S length is invalid");if(128&t[4])throw new Error("R value is negative");if(e>1&&0===t[4]&&!(128&t[5]))throw new Error("R value excessively padded");if(128&t[e+6])throw new Error("S value is negative");if(r>1&&0===t[e+6]&&!(128&t[e+7]))throw new Error("S value excessively padded");return{r:t.slice(4,4+e),s:t.slice(6+e)}},encode:function(t,e){var r=t.length,i=e.length;if(0===r)throw new Error("R length is zero");if(0===i)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(i>33)throw new Error("S length is too long");if(128&t[0])throw new Error("R value is negative");if(128&e[0])throw new Error("S value is negative");if(r>1&&0===t[0]&&!(128&t[1]))throw new Error("R value excessively padded");if(i>1&&0===e[0]&&!(128&e[1]))throw new Error("S value excessively padded");var s=n.allocUnsafe(6+r+i);return s[0]=48,s[1]=s.length-2,s[2]=2,s[3]=t.length,t.copy(s,4),s[4+r]=2,s[5+r]=e.length,e.copy(s,6+r),s}}},{"safe-buffer":56}],6:[function(t,e,r){e.exports={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255}},{}],7:[function(t,e,r){var n=t("./index.json"),i={};for(var s in n){i[n[s]]=s}e.exports=i},{"./index.json":6}],8:[function(t,e,r){!function(e,r){"use strict";function n(t,e){if(!t)throw new Error(e||"Assertion failed")}function i(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}function s(t,e,r){if(s.isBN(t))return t;this.negative=0,this.words=null,this.length=0,this.red=null,null!==t&&("le"!==e&&"be"!==e||(r=e,e=10),this._init(t||0,e||10,r||"be"))}var o;"object"==typeof e?e.exports=s:r.BN=s,s.BN=s,s.wordSize=26;try{o=t("buffer").Buffer}catch(t){}function f(t,e,r){for(var n=0,i=Math.min(t.length,r),s=e;s=49&&o<=54?o-49+10:o>=17&&o<=22?o-17+10:15&o}return n}function a(t,e,r,n){for(var i=0,s=Math.min(t.length,r),o=e;o=49?f-49+10:f>=17?f-17+10:f}return i}s.isBN=function(t){return t instanceof s||null!==t&&"object"==typeof t&&t.constructor.wordSize===s.wordSize&&Array.isArray(t.words)},s.max=function(t,e){return t.cmp(e)>0?t:e},s.min=function(t,e){return t.cmp(e)<0?t:e},s.prototype._init=function(t,e,r){if("number"==typeof t)return this._initNumber(t,e,r);if("object"==typeof t)return this._initArray(t,e,r);"hex"===e&&(e=16),n(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&i++,16===e?this._parseHex(t,i):this._parseBase(t,e,i),"-"===t[0]&&(this.negative=1),this.strip(),"le"===r&&this._initArray(this.toArray(),e,r)},s.prototype._initNumber=function(t,e,r){t<0&&(this.negative=1,t=-t),t<67108864?(this.words=[67108863&t],this.length=1):t<4503599627370496?(this.words=[67108863&t,t/67108864&67108863],this.length=2):(n(t<9007199254740992),this.words=[67108863&t,t/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),e,r)},s.prototype._initArray=function(t,e,r){if(n("number"==typeof t.length),t.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(t.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)o=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[s]|=o<>>26-f&67108863,(f+=24)>=26&&(f-=26,s++);else if("le"===r)for(i=0,s=0;i>>26-f&67108863,(f+=24)>=26&&(f-=26,s++);return this.strip()},s.prototype._parseHex=function(t,e){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var r=0;r=e;r-=6)i=f(t,r,r+6),this.words[n]|=i<>>26-s&4194303,(s+=24)>=26&&(s-=26,n++);r+6!==e&&(i=f(t,e,r+6),this.words[n]|=i<>>26-s&4194303),this.strip()},s.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var s=t.length-r,o=s%n,f=Math.min(s,s-o)+r,u=0,c=r;c1&&0===this.words[this.length-1];)this.length--;return this._normSign()},s.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},s.prototype.inspect=function(){return(this.red?""};var u=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],c=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function d(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],s=0|e.words[0],o=i*s,f=67108863&o,a=o/67108864|0;r.words[0]=f;for(var u=1;u>>26,h=67108863&a,d=Math.min(u,e.length-1),p=Math.max(0,u-t.length+1);p<=d;p++){var l=u-p|0;c+=(o=(i=0|t.words[l])*(s=0|e.words[p])+h)/67108864|0,h=67108863&o}r.words[u]=0|h,a=0|c}return 0!==a?r.words[u]=0|a:r.length--,r.strip()}s.prototype.toString=function(t,e){var r;if(t=t||10,e=0|e||1,16===t||"hex"===t){r="";for(var i=0,s=0,o=0;o>>24-i&16777215)||o!==this.length-1?u[6-a.length]+a+r:a+r,(i+=2)>=26&&(i-=26,o--)}for(0!==s&&(r=s.toString(16)+r);r.length%e!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(t===(0|t)&&t>=2&&t<=36){var d=c[t],p=h[t];r="";var l=this.clone();for(l.negative=0;!l.isZero();){var b=l.modn(p).toString(t);r=(l=l.idivn(p)).isZero()?b+r:u[d-b.length]+b+r}for(this.isZero()&&(r="0"+r);r.length%e!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},s.prototype.toJSON=function(){return this.toString(16)},s.prototype.toBuffer=function(t,e){return n(void 0!==o),this.toArrayLike(o,t,e)},s.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},s.prototype.toArrayLike=function(t,e,r){var i=this.byteLength(),s=r||Math.max(1,i);n(i<=s,"byte array longer than desired length"),n(s>0,"Requested array length <= 0"),this.strip();var o,f,a="le"===e,u=new t(s),c=this.clone();if(a){for(f=0;!c.isZero();f++)o=c.andln(255),c.iushrn(8),u[f]=o;for(;f=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},s.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},s.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},s.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},s.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},s.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},s.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},s.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},s.prototype.inotn=function(t){n("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),r=t%26;this._expand(e),r>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this.strip()},s.prototype.notn=function(t){return this.clone().inotn(t)},s.prototype.setn=function(t,e){n("number"==typeof t&&t>=0);var r=t/26|0,i=t%26;return this._expand(r+1),this.words[r]=e?this.words[r]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,s=0;s>>26;for(;0!==i&&s>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;st.length?this.clone().iadd(t):t.clone().iadd(this)},s.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var s=0,o=0;o>26,this.words[o]=67108863&e;for(;0!==s&&o>26,this.words[o]=67108863&e;if(0===s&&o>>13,p=0|o[1],l=8191&p,b=p>>>13,m=0|o[2],y=8191&m,g=m>>>13,v=0|o[3],w=8191&v,_=v>>>13,S=0|o[4],E=8191&S,M=S>>>13,k=0|o[5],A=8191&k,x=k>>>13,I=0|o[6],O=8191&I,P=I>>>13,T=0|o[7],B=8191&T,N=T>>>13,R=0|o[8],L=8191&R,U=R>>>13,j=0|o[9],C=8191&j,H=j>>>13,q=0|f[0],z=8191&q,D=q>>>13,K=0|f[1],W=8191&K,F=K>>>13,J=0|f[2],V=8191&J,G=J>>>13,Y=0|f[3],Z=8191&Y,Q=Y>>>13,X=0|f[4],$=8191&X,tt=X>>>13,et=0|f[5],rt=8191&et,nt=et>>>13,it=0|f[6],st=8191&it,ot=it>>>13,ft=0|f[7],at=8191&ft,ut=ft>>>13,ct=0|f[8],ht=8191&ct,dt=ct>>>13,pt=0|f[9],lt=8191&pt,bt=pt>>>13;r.negative=t.negative^e.negative,r.length=19;var mt=(u+(n=Math.imul(h,z))|0)+((8191&(i=(i=Math.imul(h,D))+Math.imul(d,z)|0))<<13)|0;u=((s=Math.imul(d,D))+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(l,z),i=(i=Math.imul(l,D))+Math.imul(b,z)|0,s=Math.imul(b,D);var yt=(u+(n=n+Math.imul(h,W)|0)|0)+((8191&(i=(i=i+Math.imul(h,F)|0)+Math.imul(d,W)|0))<<13)|0;u=((s=s+Math.imul(d,F)|0)+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(y,z),i=(i=Math.imul(y,D))+Math.imul(g,z)|0,s=Math.imul(g,D),n=n+Math.imul(l,W)|0,i=(i=i+Math.imul(l,F)|0)+Math.imul(b,W)|0,s=s+Math.imul(b,F)|0;var gt=(u+(n=n+Math.imul(h,V)|0)|0)+((8191&(i=(i=i+Math.imul(h,G)|0)+Math.imul(d,V)|0))<<13)|0;u=((s=s+Math.imul(d,G)|0)+(i>>>13)|0)+(gt>>>26)|0,gt&=67108863,n=Math.imul(w,z),i=(i=Math.imul(w,D))+Math.imul(_,z)|0,s=Math.imul(_,D),n=n+Math.imul(y,W)|0,i=(i=i+Math.imul(y,F)|0)+Math.imul(g,W)|0,s=s+Math.imul(g,F)|0,n=n+Math.imul(l,V)|0,i=(i=i+Math.imul(l,G)|0)+Math.imul(b,V)|0,s=s+Math.imul(b,G)|0;var vt=(u+(n=n+Math.imul(h,Z)|0)|0)+((8191&(i=(i=i+Math.imul(h,Q)|0)+Math.imul(d,Z)|0))<<13)|0;u=((s=s+Math.imul(d,Q)|0)+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(E,z),i=(i=Math.imul(E,D))+Math.imul(M,z)|0,s=Math.imul(M,D),n=n+Math.imul(w,W)|0,i=(i=i+Math.imul(w,F)|0)+Math.imul(_,W)|0,s=s+Math.imul(_,F)|0,n=n+Math.imul(y,V)|0,i=(i=i+Math.imul(y,G)|0)+Math.imul(g,V)|0,s=s+Math.imul(g,G)|0,n=n+Math.imul(l,Z)|0,i=(i=i+Math.imul(l,Q)|0)+Math.imul(b,Z)|0,s=s+Math.imul(b,Q)|0;var wt=(u+(n=n+Math.imul(h,$)|0)|0)+((8191&(i=(i=i+Math.imul(h,tt)|0)+Math.imul(d,$)|0))<<13)|0;u=((s=s+Math.imul(d,tt)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(A,z),i=(i=Math.imul(A,D))+Math.imul(x,z)|0,s=Math.imul(x,D),n=n+Math.imul(E,W)|0,i=(i=i+Math.imul(E,F)|0)+Math.imul(M,W)|0,s=s+Math.imul(M,F)|0,n=n+Math.imul(w,V)|0,i=(i=i+Math.imul(w,G)|0)+Math.imul(_,V)|0,s=s+Math.imul(_,G)|0,n=n+Math.imul(y,Z)|0,i=(i=i+Math.imul(y,Q)|0)+Math.imul(g,Z)|0,s=s+Math.imul(g,Q)|0,n=n+Math.imul(l,$)|0,i=(i=i+Math.imul(l,tt)|0)+Math.imul(b,$)|0,s=s+Math.imul(b,tt)|0;var _t=(u+(n=n+Math.imul(h,rt)|0)|0)+((8191&(i=(i=i+Math.imul(h,nt)|0)+Math.imul(d,rt)|0))<<13)|0;u=((s=s+Math.imul(d,nt)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(O,z),i=(i=Math.imul(O,D))+Math.imul(P,z)|0,s=Math.imul(P,D),n=n+Math.imul(A,W)|0,i=(i=i+Math.imul(A,F)|0)+Math.imul(x,W)|0,s=s+Math.imul(x,F)|0,n=n+Math.imul(E,V)|0,i=(i=i+Math.imul(E,G)|0)+Math.imul(M,V)|0,s=s+Math.imul(M,G)|0,n=n+Math.imul(w,Z)|0,i=(i=i+Math.imul(w,Q)|0)+Math.imul(_,Z)|0,s=s+Math.imul(_,Q)|0,n=n+Math.imul(y,$)|0,i=(i=i+Math.imul(y,tt)|0)+Math.imul(g,$)|0,s=s+Math.imul(g,tt)|0,n=n+Math.imul(l,rt)|0,i=(i=i+Math.imul(l,nt)|0)+Math.imul(b,rt)|0,s=s+Math.imul(b,nt)|0;var St=(u+(n=n+Math.imul(h,st)|0)|0)+((8191&(i=(i=i+Math.imul(h,ot)|0)+Math.imul(d,st)|0))<<13)|0;u=((s=s+Math.imul(d,ot)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(B,z),i=(i=Math.imul(B,D))+Math.imul(N,z)|0,s=Math.imul(N,D),n=n+Math.imul(O,W)|0,i=(i=i+Math.imul(O,F)|0)+Math.imul(P,W)|0,s=s+Math.imul(P,F)|0,n=n+Math.imul(A,V)|0,i=(i=i+Math.imul(A,G)|0)+Math.imul(x,V)|0,s=s+Math.imul(x,G)|0,n=n+Math.imul(E,Z)|0,i=(i=i+Math.imul(E,Q)|0)+Math.imul(M,Z)|0,s=s+Math.imul(M,Q)|0,n=n+Math.imul(w,$)|0,i=(i=i+Math.imul(w,tt)|0)+Math.imul(_,$)|0,s=s+Math.imul(_,tt)|0,n=n+Math.imul(y,rt)|0,i=(i=i+Math.imul(y,nt)|0)+Math.imul(g,rt)|0,s=s+Math.imul(g,nt)|0,n=n+Math.imul(l,st)|0,i=(i=i+Math.imul(l,ot)|0)+Math.imul(b,st)|0,s=s+Math.imul(b,ot)|0;var Et=(u+(n=n+Math.imul(h,at)|0)|0)+((8191&(i=(i=i+Math.imul(h,ut)|0)+Math.imul(d,at)|0))<<13)|0;u=((s=s+Math.imul(d,ut)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(L,z),i=(i=Math.imul(L,D))+Math.imul(U,z)|0,s=Math.imul(U,D),n=n+Math.imul(B,W)|0,i=(i=i+Math.imul(B,F)|0)+Math.imul(N,W)|0,s=s+Math.imul(N,F)|0,n=n+Math.imul(O,V)|0,i=(i=i+Math.imul(O,G)|0)+Math.imul(P,V)|0,s=s+Math.imul(P,G)|0,n=n+Math.imul(A,Z)|0,i=(i=i+Math.imul(A,Q)|0)+Math.imul(x,Z)|0,s=s+Math.imul(x,Q)|0,n=n+Math.imul(E,$)|0,i=(i=i+Math.imul(E,tt)|0)+Math.imul(M,$)|0,s=s+Math.imul(M,tt)|0,n=n+Math.imul(w,rt)|0,i=(i=i+Math.imul(w,nt)|0)+Math.imul(_,rt)|0,s=s+Math.imul(_,nt)|0,n=n+Math.imul(y,st)|0,i=(i=i+Math.imul(y,ot)|0)+Math.imul(g,st)|0,s=s+Math.imul(g,ot)|0,n=n+Math.imul(l,at)|0,i=(i=i+Math.imul(l,ut)|0)+Math.imul(b,at)|0,s=s+Math.imul(b,ut)|0;var Mt=(u+(n=n+Math.imul(h,ht)|0)|0)+((8191&(i=(i=i+Math.imul(h,dt)|0)+Math.imul(d,ht)|0))<<13)|0;u=((s=s+Math.imul(d,dt)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(C,z),i=(i=Math.imul(C,D))+Math.imul(H,z)|0,s=Math.imul(H,D),n=n+Math.imul(L,W)|0,i=(i=i+Math.imul(L,F)|0)+Math.imul(U,W)|0,s=s+Math.imul(U,F)|0,n=n+Math.imul(B,V)|0,i=(i=i+Math.imul(B,G)|0)+Math.imul(N,V)|0,s=s+Math.imul(N,G)|0,n=n+Math.imul(O,Z)|0,i=(i=i+Math.imul(O,Q)|0)+Math.imul(P,Z)|0,s=s+Math.imul(P,Q)|0,n=n+Math.imul(A,$)|0,i=(i=i+Math.imul(A,tt)|0)+Math.imul(x,$)|0,s=s+Math.imul(x,tt)|0,n=n+Math.imul(E,rt)|0,i=(i=i+Math.imul(E,nt)|0)+Math.imul(M,rt)|0,s=s+Math.imul(M,nt)|0,n=n+Math.imul(w,st)|0,i=(i=i+Math.imul(w,ot)|0)+Math.imul(_,st)|0,s=s+Math.imul(_,ot)|0,n=n+Math.imul(y,at)|0,i=(i=i+Math.imul(y,ut)|0)+Math.imul(g,at)|0,s=s+Math.imul(g,ut)|0,n=n+Math.imul(l,ht)|0,i=(i=i+Math.imul(l,dt)|0)+Math.imul(b,ht)|0,s=s+Math.imul(b,dt)|0;var kt=(u+(n=n+Math.imul(h,lt)|0)|0)+((8191&(i=(i=i+Math.imul(h,bt)|0)+Math.imul(d,lt)|0))<<13)|0;u=((s=s+Math.imul(d,bt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(C,W),i=(i=Math.imul(C,F))+Math.imul(H,W)|0,s=Math.imul(H,F),n=n+Math.imul(L,V)|0,i=(i=i+Math.imul(L,G)|0)+Math.imul(U,V)|0,s=s+Math.imul(U,G)|0,n=n+Math.imul(B,Z)|0,i=(i=i+Math.imul(B,Q)|0)+Math.imul(N,Z)|0,s=s+Math.imul(N,Q)|0,n=n+Math.imul(O,$)|0,i=(i=i+Math.imul(O,tt)|0)+Math.imul(P,$)|0,s=s+Math.imul(P,tt)|0,n=n+Math.imul(A,rt)|0,i=(i=i+Math.imul(A,nt)|0)+Math.imul(x,rt)|0,s=s+Math.imul(x,nt)|0,n=n+Math.imul(E,st)|0,i=(i=i+Math.imul(E,ot)|0)+Math.imul(M,st)|0,s=s+Math.imul(M,ot)|0,n=n+Math.imul(w,at)|0,i=(i=i+Math.imul(w,ut)|0)+Math.imul(_,at)|0,s=s+Math.imul(_,ut)|0,n=n+Math.imul(y,ht)|0,i=(i=i+Math.imul(y,dt)|0)+Math.imul(g,ht)|0,s=s+Math.imul(g,dt)|0;var At=(u+(n=n+Math.imul(l,lt)|0)|0)+((8191&(i=(i=i+Math.imul(l,bt)|0)+Math.imul(b,lt)|0))<<13)|0;u=((s=s+Math.imul(b,bt)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(C,V),i=(i=Math.imul(C,G))+Math.imul(H,V)|0,s=Math.imul(H,G),n=n+Math.imul(L,Z)|0,i=(i=i+Math.imul(L,Q)|0)+Math.imul(U,Z)|0,s=s+Math.imul(U,Q)|0,n=n+Math.imul(B,$)|0,i=(i=i+Math.imul(B,tt)|0)+Math.imul(N,$)|0,s=s+Math.imul(N,tt)|0,n=n+Math.imul(O,rt)|0,i=(i=i+Math.imul(O,nt)|0)+Math.imul(P,rt)|0,s=s+Math.imul(P,nt)|0,n=n+Math.imul(A,st)|0,i=(i=i+Math.imul(A,ot)|0)+Math.imul(x,st)|0,s=s+Math.imul(x,ot)|0,n=n+Math.imul(E,at)|0,i=(i=i+Math.imul(E,ut)|0)+Math.imul(M,at)|0,s=s+Math.imul(M,ut)|0,n=n+Math.imul(w,ht)|0,i=(i=i+Math.imul(w,dt)|0)+Math.imul(_,ht)|0,s=s+Math.imul(_,dt)|0;var xt=(u+(n=n+Math.imul(y,lt)|0)|0)+((8191&(i=(i=i+Math.imul(y,bt)|0)+Math.imul(g,lt)|0))<<13)|0;u=((s=s+Math.imul(g,bt)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(C,Z),i=(i=Math.imul(C,Q))+Math.imul(H,Z)|0,s=Math.imul(H,Q),n=n+Math.imul(L,$)|0,i=(i=i+Math.imul(L,tt)|0)+Math.imul(U,$)|0,s=s+Math.imul(U,tt)|0,n=n+Math.imul(B,rt)|0,i=(i=i+Math.imul(B,nt)|0)+Math.imul(N,rt)|0,s=s+Math.imul(N,nt)|0,n=n+Math.imul(O,st)|0,i=(i=i+Math.imul(O,ot)|0)+Math.imul(P,st)|0,s=s+Math.imul(P,ot)|0,n=n+Math.imul(A,at)|0,i=(i=i+Math.imul(A,ut)|0)+Math.imul(x,at)|0,s=s+Math.imul(x,ut)|0,n=n+Math.imul(E,ht)|0,i=(i=i+Math.imul(E,dt)|0)+Math.imul(M,ht)|0,s=s+Math.imul(M,dt)|0;var It=(u+(n=n+Math.imul(w,lt)|0)|0)+((8191&(i=(i=i+Math.imul(w,bt)|0)+Math.imul(_,lt)|0))<<13)|0;u=((s=s+Math.imul(_,bt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863,n=Math.imul(C,$),i=(i=Math.imul(C,tt))+Math.imul(H,$)|0,s=Math.imul(H,tt),n=n+Math.imul(L,rt)|0,i=(i=i+Math.imul(L,nt)|0)+Math.imul(U,rt)|0,s=s+Math.imul(U,nt)|0,n=n+Math.imul(B,st)|0,i=(i=i+Math.imul(B,ot)|0)+Math.imul(N,st)|0,s=s+Math.imul(N,ot)|0,n=n+Math.imul(O,at)|0,i=(i=i+Math.imul(O,ut)|0)+Math.imul(P,at)|0,s=s+Math.imul(P,ut)|0,n=n+Math.imul(A,ht)|0,i=(i=i+Math.imul(A,dt)|0)+Math.imul(x,ht)|0,s=s+Math.imul(x,dt)|0;var Ot=(u+(n=n+Math.imul(E,lt)|0)|0)+((8191&(i=(i=i+Math.imul(E,bt)|0)+Math.imul(M,lt)|0))<<13)|0;u=((s=s+Math.imul(M,bt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(C,rt),i=(i=Math.imul(C,nt))+Math.imul(H,rt)|0,s=Math.imul(H,nt),n=n+Math.imul(L,st)|0,i=(i=i+Math.imul(L,ot)|0)+Math.imul(U,st)|0,s=s+Math.imul(U,ot)|0,n=n+Math.imul(B,at)|0,i=(i=i+Math.imul(B,ut)|0)+Math.imul(N,at)|0,s=s+Math.imul(N,ut)|0,n=n+Math.imul(O,ht)|0,i=(i=i+Math.imul(O,dt)|0)+Math.imul(P,ht)|0,s=s+Math.imul(P,dt)|0;var Pt=(u+(n=n+Math.imul(A,lt)|0)|0)+((8191&(i=(i=i+Math.imul(A,bt)|0)+Math.imul(x,lt)|0))<<13)|0;u=((s=s+Math.imul(x,bt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(C,st),i=(i=Math.imul(C,ot))+Math.imul(H,st)|0,s=Math.imul(H,ot),n=n+Math.imul(L,at)|0,i=(i=i+Math.imul(L,ut)|0)+Math.imul(U,at)|0,s=s+Math.imul(U,ut)|0,n=n+Math.imul(B,ht)|0,i=(i=i+Math.imul(B,dt)|0)+Math.imul(N,ht)|0,s=s+Math.imul(N,dt)|0;var Tt=(u+(n=n+Math.imul(O,lt)|0)|0)+((8191&(i=(i=i+Math.imul(O,bt)|0)+Math.imul(P,lt)|0))<<13)|0;u=((s=s+Math.imul(P,bt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(C,at),i=(i=Math.imul(C,ut))+Math.imul(H,at)|0,s=Math.imul(H,ut),n=n+Math.imul(L,ht)|0,i=(i=i+Math.imul(L,dt)|0)+Math.imul(U,ht)|0,s=s+Math.imul(U,dt)|0;var Bt=(u+(n=n+Math.imul(B,lt)|0)|0)+((8191&(i=(i=i+Math.imul(B,bt)|0)+Math.imul(N,lt)|0))<<13)|0;u=((s=s+Math.imul(N,bt)|0)+(i>>>13)|0)+(Bt>>>26)|0,Bt&=67108863,n=Math.imul(C,ht),i=(i=Math.imul(C,dt))+Math.imul(H,ht)|0,s=Math.imul(H,dt);var Nt=(u+(n=n+Math.imul(L,lt)|0)|0)+((8191&(i=(i=i+Math.imul(L,bt)|0)+Math.imul(U,lt)|0))<<13)|0;u=((s=s+Math.imul(U,bt)|0)+(i>>>13)|0)+(Nt>>>26)|0,Nt&=67108863;var Rt=(u+(n=Math.imul(C,lt))|0)+((8191&(i=(i=Math.imul(C,bt))+Math.imul(H,lt)|0))<<13)|0;return u=((s=Math.imul(H,bt))+(i>>>13)|0)+(Rt>>>26)|0,Rt&=67108863,a[0]=mt,a[1]=yt,a[2]=gt,a[3]=vt,a[4]=wt,a[5]=_t,a[6]=St,a[7]=Et,a[8]=Mt,a[9]=kt,a[10]=At,a[11]=xt,a[12]=It,a[13]=Ot,a[14]=Pt,a[15]=Tt,a[16]=Bt,a[17]=Nt,a[18]=Rt,0!==u&&(a[19]=u,r.length++),r};function l(t,e,r){return(new b).mulp(t,e,r)}function b(t,e){this.x=t,this.y=e}Math.imul||(p=d),s.prototype.mulTo=function(t,e){var r=this.length+t.length;return 10===this.length&&10===t.length?p(this,t,e):r<63?d(this,t,e):r<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,s=0;s>>26)|0)>>>26,o&=67108863}r.words[s]=f,n=o,o=i}return 0!==n?r.words[s]=n:r.length--,r.strip()}(this,t,e):l(this,t,e)},b.prototype.makeRBT=function(t){for(var e=new Array(t),r=s.prototype._countBits(t)-1,n=0;n>=1;return n},b.prototype.permute=function(t,e,r,n,i,s){for(var o=0;o>>=1)i++;return 1<>>=13,r[2*o+1]=8191&s,s>>>=13;for(o=2*e;o>=26,e+=i/67108864|0,e+=s>>>26,this.words[r]=67108863&s}return 0!==e&&(this.words[r]=e,this.length++),this},s.prototype.muln=function(t){return this.clone().imuln(t)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new s(1);for(var r=this,n=0;n=0);var e,r=t%26,i=(t-r)/26,s=67108863>>>26-r<<26-r;if(0!==r){var o=0;for(e=0;e>>26-r}o&&(this.words[e]=o,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var s=t%26,o=Math.min((t-s)/26,this.length),f=67108863^67108863>>>s<o)for(this.length-=o,u=0;u=0&&(0!==c||u>=i);u--){var h=0|this.words[u];this.words[u]=c<<26-s|h>>>s,c=h&f}return a&&0!==c&&(a.words[a.length++]=c),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},s.prototype.ishrn=function(t,e,r){return n(0===this.negative),this.iushrn(t,e,r)},s.prototype.shln=function(t){return this.clone().ishln(t)},s.prototype.ushln=function(t){return this.clone().iushln(t)},s.prototype.shrn=function(t){return this.clone().ishrn(t)},s.prototype.ushrn=function(t){return this.clone().iushrn(t)},s.prototype.testn=function(t){n("number"==typeof t&&t>=0);var e=t%26,r=(t-e)/26,i=1<=0);var e=t%26,r=(t-e)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==e&&r++,this.length=Math.min(r,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},s.prototype.isubn=function(t){if(n("number"==typeof t),n(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(a/67108864|0),this.words[i+r]=67108863&s}for(;i>26,this.words[i+r]=67108863&s;if(0===f)return this.strip();for(n(-1===f),f=0,i=0;i>26,this.words[i]=67108863&s;return this.negative=1,this.strip()},s.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),i=t,o=0|i.words[i.length-1];0!==(r=26-this._countBits(o))&&(i=i.ushln(r),n.iushln(r),o=0|i.words[i.length-1]);var f,a=n.length-i.length;if("mod"!==e){(f=new s(null)).length=a+1,f.words=new Array(f.length);for(var u=0;u=0;h--){var d=67108864*(0|n.words[i.length+h])+(0|n.words[i.length+h-1]);for(d=Math.min(d/o|0,67108863),n._ishlnsubmul(i,d,h);0!==n.negative;)d--,n.negative=0,n._ishlnsubmul(i,1,h),n.isZero()||(n.negative^=1);f&&(f.words[h]=d)}return f&&f.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:f||null,mod:n}},s.prototype.divmod=function(t,e,r){return n(!t.isZero()),this.isZero()?{div:new s(0),mod:new s(0)}:0!==this.negative&&0===t.negative?(f=this.neg().divmod(t,e),"mod"!==e&&(i=f.div.neg()),"div"!==e&&(o=f.mod.neg(),r&&0!==o.negative&&o.iadd(t)),{div:i,mod:o}):0===this.negative&&0!==t.negative?(f=this.divmod(t.neg(),e),"mod"!==e&&(i=f.div.neg()),{div:i,mod:f.mod}):0!=(this.negative&t.negative)?(f=this.neg().divmod(t.neg(),e),"div"!==e&&(o=f.mod.neg(),r&&0!==o.negative&&o.isub(t)),{div:f.div,mod:o}):t.length>this.length||this.cmp(t)<0?{div:new s(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new s(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new s(this.modn(t.words[0]))}:this._wordDiv(t,e);var i,o,f},s.prototype.div=function(t){return this.divmod(t,"div",!1).div},s.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},s.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},s.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),s=r.cmp(n);return s<0||1===i&&0===s?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},s.prototype.modn=function(t){n(t<=67108863);for(var e=(1<<26)%t,r=0,i=this.length-1;i>=0;i--)r=(e*r+(0|this.words[i]))%t;return r},s.prototype.idivn=function(t){n(t<=67108863);for(var e=0,r=this.length-1;r>=0;r--){var i=(0|this.words[r])+67108864*e;this.words[r]=i/t|0,e=i%t}return this.strip()},s.prototype.divn=function(t){return this.clone().idivn(t)},s.prototype.egcd=function(t){n(0===t.negative),n(!t.isZero());var e=this,r=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var i=new s(1),o=new s(0),f=new s(0),a=new s(1),u=0;e.isEven()&&r.isEven();)e.iushrn(1),r.iushrn(1),++u;for(var c=r.clone(),h=e.clone();!e.isZero();){for(var d=0,p=1;0==(e.words[0]&p)&&d<26;++d,p<<=1);if(d>0)for(e.iushrn(d);d-- >0;)(i.isOdd()||o.isOdd())&&(i.iadd(c),o.isub(h)),i.iushrn(1),o.iushrn(1);for(var l=0,b=1;0==(r.words[0]&b)&&l<26;++l,b<<=1);if(l>0)for(r.iushrn(l);l-- >0;)(f.isOdd()||a.isOdd())&&(f.iadd(c),a.isub(h)),f.iushrn(1),a.iushrn(1);e.cmp(r)>=0?(e.isub(r),i.isub(f),o.isub(a)):(r.isub(e),f.isub(i),a.isub(o))}return{a:f,b:a,gcd:r.iushln(u)}},s.prototype._invmp=function(t){n(0===t.negative),n(!t.isZero());var e=this,r=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var i,o=new s(1),f=new s(0),a=r.clone();e.cmpn(1)>0&&r.cmpn(1)>0;){for(var u=0,c=1;0==(e.words[0]&c)&&u<26;++u,c<<=1);if(u>0)for(e.iushrn(u);u-- >0;)o.isOdd()&&o.iadd(a),o.iushrn(1);for(var h=0,d=1;0==(r.words[0]&d)&&h<26;++h,d<<=1);if(h>0)for(r.iushrn(h);h-- >0;)f.isOdd()&&f.iadd(a),f.iushrn(1);e.cmp(r)>=0?(e.isub(r),o.isub(f)):(r.isub(e),f.isub(o))}return(i=0===e.cmpn(1)?o:f).cmpn(0)<0&&i.iadd(t),i},s.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var s=e;e=r,r=s}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},s.prototype.invm=function(t){return this.egcd(t).a.umod(t)},s.prototype.isEven=function(){return 0==(1&this.words[0])},s.prototype.isOdd=function(){return 1==(1&this.words[0])},s.prototype.andln=function(t){return this.words[0]&t},s.prototype.bincn=function(t){n("number"==typeof t);var e=t%26,r=(t-e)/26,i=1<>>26,f&=67108863,this.words[o]=f}return 0!==s&&(this.words[o]=s,this.length++),this},s.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},s.prototype.cmpn=function(t){var e,r=t<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this.strip(),this.length>1)e=1;else{r&&(t=-t),n(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},s.prototype.gtn=function(t){return 1===this.cmpn(t)},s.prototype.gt=function(t){return 1===this.cmp(t)},s.prototype.gten=function(t){return this.cmpn(t)>=0},s.prototype.gte=function(t){return this.cmp(t)>=0},s.prototype.ltn=function(t){return-1===this.cmpn(t)},s.prototype.lt=function(t){return-1===this.cmp(t)},s.prototype.lten=function(t){return this.cmpn(t)<=0},s.prototype.lte=function(t){return this.cmp(t)<=0},s.prototype.eqn=function(t){return 0===this.cmpn(t)},s.prototype.eq=function(t){return 0===this.cmp(t)},s.red=function(t){return new S(t)},s.prototype.toRed=function(t){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},s.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(t){return this.red=t,this},s.prototype.forceRed=function(t){return n(!this.red,"Already a number in reduction context"),this._forceRed(t)},s.prototype.redAdd=function(t){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},s.prototype.redIAdd=function(t){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},s.prototype.redSub=function(t){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},s.prototype.redISub=function(t){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},s.prototype.redShl=function(t){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},s.prototype.redMul=function(t){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},s.prototype.redIMul=function(t){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},s.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},s.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},s.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},s.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},s.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},s.prototype.redPow=function(t){return n(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var m={k256:null,p224:null,p192:null,p25519:null};function y(t,e){this.name=t,this.p=new s(e,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function g(){y.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function v(){y.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){y.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){y.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function S(t){if("string"==typeof t){var e=s._prime(t);this.m=e.p,this.prime=e}else n(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function E(t){S.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new s(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}y.prototype._tmp=function(){var t=new s(null);return t.words=new Array(Math.ceil(this.n/13)),t},y.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):r.strip(),r},y.prototype.split=function(t,e){t.iushrn(this.n,0,e)},y.prototype.imulK=function(t){return t.imul(this.k)},i(g,y),g.prototype.split=function(t,e){for(var r=Math.min(t.length,9),n=0;n>>22,i=s}i>>>=22,t.words[n-10]=i,0===i&&t.length>10?t.length-=10:t.length-=9},g.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},s._prime=function(t){if(m[t])return m[t];var e;if("k256"===t)e=new g;else if("p224"===t)e=new v;else if("p192"===t)e=new w;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new _}return m[t]=e,e},S.prototype._verify1=function(t){n(0===t.negative,"red works only with positives"),n(t.red,"red works only with red numbers")},S.prototype._verify2=function(t,e){n(0==(t.negative|e.negative),"red works only with positives"),n(t.red&&t.red===e.red,"red works only with red numbers")},S.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},S.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},S.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},S.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},S.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},S.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},S.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},S.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},S.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},S.prototype.isqr=function(t){return this.imul(t,t.clone())},S.prototype.sqr=function(t){return this.mul(t,t)},S.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(n(e%2==1),3===e){var r=this.m.add(new s(1)).iushrn(2);return this.pow(t,r)}for(var i=this.m.subn(1),o=0;!i.isZero()&&0===i.andln(1);)o++,i.iushrn(1);n(!i.isZero());var f=new s(1).toRed(this),a=f.redNeg(),u=this.m.subn(1).iushrn(1),c=this.m.bitLength();for(c=new s(2*c*c).toRed(this);0!==this.pow(c,u).cmp(a);)c.redIAdd(a);for(var h=this.pow(c,i),d=this.pow(t,i.addn(1).iushrn(1)),p=this.pow(t,i),l=o;0!==p.cmp(f);){for(var b=p,m=0;0!==b.cmp(f);m++)b=b.redSqr();n(m=0;n--){for(var u=e.words[n],c=a-1;c>=0;c--){var h=u>>c&1;i!==r[0]&&(i=this.sqr(i)),0!==h||0!==o?(o<<=1,o|=h,(4===++f||0===n&&0===c)&&(i=this.mul(i,r[o]),f=0,o=0)):f=0}a=26}return i},S.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},S.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},s.mont=function(t){return new E(t)},i(E,S),E.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},E.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},E.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),s=i;return i.cmp(this.m)>=0?s=i.isub(this.m):i.cmpn(0)<0&&(s=i.iadd(this.m)),s._forceRed(this)},E.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new s(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},E.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===e||e,this)},{buffer:118}],9:[function(t,e,r){var n;function i(t){this.rand=t}if(e.exports=function(t){return n||(n=new i(null)),n.generate(t)},e.exports.Rand=i,i.prototype.generate=function(t){return this._rand(t)},i.prototype._rand=function(t){if(this.rand.getBytes)return this.rand.getBytes(t);for(var e=new Uint8Array(t),r=0;rr)?e=("rmd160"===t?new a:u(t)).update(e).digest():e.lengthf?e=t(e):e.length0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}function u(t,e){this.curve=t,this.type=e,this.precomputed=null}e.exports=a,a.prototype.point=function(){throw new Error("Not implemented")},a.prototype.validate=function(){throw new Error("Not implemented")},a.prototype._fixedNafMul=function(t,e){f(t.precomputed);var r=t._getDoubles(),n=s(e,1),i=(1<=a;e--)u=(u<<1)+n[e];o.push(u)}for(var c=this.jpoint(null,null,null),h=this.jpoint(null,null,null),d=i;d>0;d--){for(a=0;a=0;u--){for(e=0;u>=0&&0===o[u];u--)e++;if(u>=0&&e++,a=a.dblp(e),u<0)break;var c=o[u];f(0!==c),a="affine"===t.type?c>0?a.mixedAdd(i[c-1>>1]):a.mixedAdd(i[-c-1>>1].neg()):c>0?a.add(i[c-1>>1]):a.add(i[-c-1>>1].neg())}return"affine"===t.type?a.toP():a},a.prototype._wnafMulAdd=function(t,e,r,n,i){for(var f=this._wnafT1,a=this._wnafT2,u=this._wnafT3,c=0,h=0;h=1;h-=2){var p=h-1,l=h;if(1===f[p]&&1===f[l]){var b=[e[p],null,null,e[l]];0===e[p].y.cmp(e[l].y)?(b[1]=e[p].add(e[l]),b[2]=e[p].toJ().mixedAdd(e[l].neg())):0===e[p].y.cmp(e[l].y.redNeg())?(b[1]=e[p].toJ().mixedAdd(e[l]),b[2]=e[p].add(e[l].neg())):(b[1]=e[p].toJ().mixedAdd(e[l]),b[2]=e[p].toJ().mixedAdd(e[l].neg()));var m=[-3,-1,-5,-7,0,7,5,1,3],y=o(r[p],r[l]);c=Math.max(y[0].length,c),u[p]=new Array(c),u[l]=new Array(c);for(var g=0;g=0;h--){for(var E=0;h>=0;){var M=!0;for(g=0;g=0&&E++,_=_.dblp(E),h<0)break;for(g=0;g0?k=a[g][A-1>>1]:A<0&&(k=a[g][-A-1>>1].neg()),_="affine"===k.type?_.mixedAdd(k):_.add(k))}}for(h=0;h=Math.ceil((t.bitLength()+1)/e.step)},u.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i":""},Point.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},Point.prototype._extDbl=function(){var t=this.x.redSqr(),e=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var n=this.curve._mulA(t),i=this.x.redAdd(this.y).redSqr().redISub(t).redISub(e),s=n.redAdd(e),o=s.redSub(r),f=n.redSub(e),a=i.redMul(o),u=s.redMul(f),c=i.redMul(f),h=o.redMul(s);return this.curve.point(a,u,h,c)},Point.prototype._projDbl=function(){var t,e,r,n=this.x.redAdd(this.y).redSqr(),i=this.x.redSqr(),s=this.y.redSqr();if(this.curve.twisted){var o=(u=this.curve._mulA(i)).redAdd(s);if(this.zOne)t=n.redSub(i).redSub(s).redMul(o.redSub(this.curve.two)),e=o.redMul(u.redSub(s)),r=o.redSqr().redSub(o).redSub(o);else{var f=this.z.redSqr(),a=o.redSub(f).redISub(f);t=n.redSub(i).redISub(s).redMul(a),e=o.redMul(u.redSub(s)),r=o.redMul(a)}}else{var u=i.redAdd(s);f=this.curve._mulC(this.z).redSqr(),a=u.redSub(f).redSub(f);t=this.curve._mulC(n.redISub(u)).redMul(a),e=this.curve._mulC(u).redMul(i.redISub(s)),r=u.redMul(a)}return this.curve.point(t,e,r)},Point.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},Point.prototype._extAdd=function(t){var e=this.y.redSub(this.x).redMul(t.y.redSub(t.x)),r=this.y.redAdd(this.x).redMul(t.y.redAdd(t.x)),n=this.t.redMul(this.curve.dd).redMul(t.t),i=this.z.redMul(t.z.redAdd(t.z)),s=r.redSub(e),o=i.redSub(n),f=i.redAdd(n),a=r.redAdd(e),u=s.redMul(o),c=f.redMul(a),h=s.redMul(a),d=o.redMul(f);return this.curve.point(u,c,d,h)},Point.prototype._projAdd=function(t){var e,r,n=this.z.redMul(t.z),i=n.redSqr(),s=this.x.redMul(t.x),o=this.y.redMul(t.y),f=this.curve.d.redMul(s).redMul(o),a=i.redSub(f),u=i.redAdd(f),c=this.x.redAdd(this.y).redMul(t.x.redAdd(t.y)).redISub(s).redISub(o),h=n.redMul(a).redMul(c);return this.curve.twisted?(e=n.redMul(u).redMul(o.redSub(this.curve._mulA(s))),r=a.redMul(u)):(e=n.redMul(u).redMul(o.redSub(s)),r=this.curve._mulC(a).redMul(u)),this.curve.point(h,e,r)},Point.prototype.add=function(t){return this.isInfinity()?t:t.isInfinity()?this:this.curve.extended?this._extAdd(t):this._projAdd(t)},Point.prototype.mul=function(t){return this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve._wnafMul(this,t)},Point.prototype.mulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!1)},Point.prototype.jmulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!0)},Point.prototype.normalize=function(){if(this.zOne)return this;var t=this.z.redInvm();return this.x=this.x.redMul(t),this.y=this.y.redMul(t),this.t&&(this.t=this.t.redMul(t)),this.z=this.curve.one,this.zOne=!0,this},Point.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Point.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Point.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Point.prototype.eq=function(t){return this===t||0===this.getX().cmp(t.getX())&&0===this.getY().cmp(t.getY())},Point.prototype.eqXToP=function(t){var e=t.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(e))return!0;for(var r=t.clone(),n=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(e.redIAdd(n),0===this.x.cmp(e))return!0}},Point.prototype.toP=Point.prototype.normalize,Point.prototype.mixedAdd=Point.prototype.add},{"../utils":32,"./base":19,"bn.js":8,inherits:48}],21:[function(t,e,r){"use strict";var n=r;n.base=t("./base"),n.short=t("./short"),n.mont=t("./mont"),n.edwards=t("./edwards")},{"./base":19,"./edwards":20,"./mont":22,"./short":23}],22:[function(t,e,r){"use strict";var n=t("bn.js"),i=t("inherits"),s=t("./base"),o=t("../utils");function f(t){s.call(this,"mont",t),this.a=new n(t.a,16).toRed(this.red),this.b=new n(t.b,16).toRed(this.red),this.i4=new n(4).toRed(this.red).redInvm(),this.two=new n(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}function Point(t,e,r){s.BasePoint.call(this,t,"projective"),null===e&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new n(e,16),this.z=new n(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}i(f,s),e.exports=f,f.prototype.validate=function(t){var e=t.normalize().x,r=e.redSqr(),n=r.redMul(e).redAdd(r.redMul(this.a)).redAdd(e);return 0===n.redSqrt().redSqr().cmp(n)},i(Point,s.BasePoint),f.prototype.decodePoint=function(t,e){return this.point(o.toArray(t,e),1)},f.prototype.point=function(t,e){return new Point(this,t,e)},f.prototype.pointFromJSON=function(t){return Point.fromJSON(this,t)},Point.prototype.precompute=function(){},Point.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},Point.fromJSON=function(t,e){return new Point(t,e[0],e[1]||t.one)},Point.prototype.inspect=function(){return this.isInfinity()?"":""},Point.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},Point.prototype.dbl=function(){var t=this.x.redAdd(this.z).redSqr(),e=this.x.redSub(this.z).redSqr(),r=t.redSub(e),n=t.redMul(e),i=r.redMul(e.redAdd(this.curve.a24.redMul(r)));return this.curve.point(n,i)},Point.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},Point.prototype.diffAdd=function(t,e){var r=this.x.redAdd(this.z),n=this.x.redSub(this.z),i=t.x.redAdd(t.z),s=t.x.redSub(t.z).redMul(r),o=i.redMul(n),f=e.z.redMul(s.redAdd(o).redSqr()),a=e.x.redMul(s.redISub(o).redSqr());return this.curve.point(f,a)},Point.prototype.mul=function(t){for(var e=t.clone(),r=this,n=this.curve.point(null,null),i=[];0!==e.cmpn(0);e.iushrn(1))i.push(e.andln(1));for(var s=i.length-1;s>=0;s--)0===i[s]?(r=r.diffAdd(n,this),n=n.dbl()):(n=r.diffAdd(n,this),r=r.dbl());return n},Point.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},Point.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},Point.prototype.eq=function(t){return 0===this.getX().cmp(t.getX())},Point.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},Point.prototype.getX=function(){return this.normalize(),this.x.fromRed()}},{"../utils":32,"./base":19,"bn.js":8,inherits:48}],23:[function(t,e,r){"use strict";var n=t("../utils"),i=t("bn.js"),s=t("inherits"),o=t("./base"),f=n.assert;function a(t){o.call(this,"short",t),this.a=new i(t.a,16).toRed(this.red),this.b=new i(t.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(t),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}function Point(t,e,r,n){o.BasePoint.call(this,t,"affine"),null===e&&null===r?(this.x=null,this.y=null,this.inf=!0):(this.x=new i(e,16),this.y=new i(r,16),n&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}function u(t,e,r,n){o.BasePoint.call(this,t,"jacobian"),null===e&&null===r&&null===n?(this.x=this.curve.one,this.y=this.curve.one,this.z=new i(0)):(this.x=new i(e,16),this.y=new i(r,16),this.z=new i(n,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}s(a,o),e.exports=a,a.prototype._getEndomorphism=function(t){if(this.zeroA&&this.g&&this.n&&1===this.p.modn(3)){var e,r;if(t.beta)e=new i(t.beta,16).toRed(this.red);else{var n=this._getEndoRoots(this.p);e=(e=n[0].cmp(n[1])<0?n[0]:n[1]).toRed(this.red)}if(t.lambda)r=new i(t.lambda,16);else{var s=this._getEndoRoots(this.n);0===this.g.mul(s[0]).x.cmp(this.g.x.redMul(e))?r=s[0]:(r=s[1],f(0===this.g.mul(r).x.cmp(this.g.x.redMul(e))))}return{beta:e,lambda:r,basis:t.basis?t.basis.map(function(t){return{a:new i(t.a,16),b:new i(t.b,16)}}):this._getEndoBasis(r)}}},a.prototype._getEndoRoots=function(t){var e=t===this.p?this.red:i.mont(t),r=new i(2).toRed(e).redInvm(),n=r.redNeg(),s=new i(3).toRed(e).redNeg().redSqrt().redMul(r);return[n.redAdd(s).fromRed(),n.redSub(s).fromRed()]},a.prototype._getEndoBasis=function(t){for(var e,r,n,s,o,f,a,u,c,h=this.n.ushrn(Math.floor(this.n.bitLength()/2)),d=t,p=this.n.clone(),l=new i(1),b=new i(0),m=new i(0),y=new i(1),g=0;0!==d.cmpn(0);){var v=p.div(d);u=p.sub(v.mul(d)),c=m.sub(v.mul(l));var w=y.sub(v.mul(b));if(!n&&u.cmp(h)<0)e=a.neg(),r=l,n=u.neg(),s=c;else if(n&&2==++g)break;a=u,p=d,d=u,m=l,l=c,y=b,b=w}o=u.neg(),f=c;var _=n.sqr().add(s.sqr());return o.sqr().add(f.sqr()).cmp(_)>=0&&(o=e,f=r),n.negative&&(n=n.neg(),s=s.neg()),o.negative&&(o=o.neg(),f=f.neg()),[{a:n,b:s},{a:o,b:f}]},a.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],n=e[1],i=n.b.mul(t).divRound(this.n),s=r.b.neg().mul(t).divRound(this.n),o=i.mul(r.a),f=s.mul(n.a),a=i.mul(r.b),u=s.mul(n.b);return{k1:t.sub(o).sub(f),k2:a.add(u).neg()}},a.prototype.pointFromX=function(t,e){(t=new i(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var s=n.fromRed().isOdd();return(e&&!s||!e&&s)&&(n=n.redNeg()),this.point(t,n)},a.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,n=this.a.redMul(e),i=e.redSqr().redMul(e).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},a.prototype._endoWnafMulAdd=function(t,e,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,s=0;s":""},Point.prototype.isInfinity=function(){return this.inf},Point.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(0===this.x.cmp(t.x))return this.curve.point(null,null);var e=this.y.redSub(t.y);0!==e.cmpn(0)&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),n=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},Point.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(0===t.cmpn(0))return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),n=t.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(n),s=i.redSqr().redISub(this.x.redAdd(this.x)),o=i.redMul(this.x.redSub(s)).redISub(this.y);return this.curve.point(s,o)},Point.prototype.getX=function(){return this.x.fromRed()},Point.prototype.getY=function(){return this.y.fromRed()},Point.prototype.mul=function(t){return t=new i(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},Point.prototype.mulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},Point.prototype.jmulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},Point.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||0===this.x.cmp(t.x)&&0===this.y.cmp(t.y))},Point.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,n=function(t){return t.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return e},Point.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},s(u,o.BasePoint),a.prototype.jpoint=function(t,e,r){return new u(this,t,e,r)},u.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),n=this.y.redMul(e).redMul(t);return this.curve.point(r,n)},u.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},u.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(e),i=t.x.redMul(r),s=this.y.redMul(e.redMul(t.z)),o=t.y.redMul(r.redMul(this.z)),f=n.redSub(i),a=s.redSub(o);if(0===f.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var u=f.redSqr(),c=u.redMul(f),h=n.redMul(u),d=a.redSqr().redIAdd(c).redISub(h).redISub(h),p=a.redMul(h.redISub(d)).redISub(s.redMul(c)),l=this.z.redMul(t.z).redMul(f);return this.curve.jpoint(d,p,l)},u.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,n=t.x.redMul(e),i=this.y,s=t.y.redMul(e).redMul(this.z),o=r.redSub(n),f=i.redSub(s);if(0===o.cmpn(0))return 0!==f.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var a=o.redSqr(),u=a.redMul(o),c=r.redMul(a),h=f.redSqr().redIAdd(u).redISub(c).redISub(c),d=f.redMul(c.redISub(h)).redISub(i.redMul(u)),p=this.z.redMul(o);return this.curve.jpoint(h,d,p)},u.prototype.dblp=function(t){if(0===t)return this;if(this.isInfinity())return this;if(!t)return this.dbl();if(this.curve.zeroA||this.curve.threeA){for(var e=this,r=0;r=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}},u.prototype.inspect=function(){return this.isInfinity()?"":""},u.prototype.isInfinity=function(){return 0===this.z.cmpn(0)}},{"../utils":32,"./base":19,"bn.js":8,inherits:48}],24:[function(t,e,r){"use strict";var n,i=r,s=t("hash.js"),o=t("./curve"),f=t("./utils").assert;function a(t){"short"===t.type?this.curve=new o.short(t):"edwards"===t.type?this.curve=new o.edwards(t):this.curve=new o.mont(t),this.g=this.curve.g,this.n=this.curve.n,this.hash=t.hash,f(this.g.validate(),"Invalid curve"),f(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}function u(t,e){Object.defineProperty(i,t,{configurable:!0,enumerable:!0,get:function(){var r=new a(e);return Object.defineProperty(i,t,{configurable:!0,enumerable:!0,value:r}),r}})}i.PresetCurve=a,u("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:s.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),u("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:s.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),u("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:s.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),u("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:s.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),u("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:s.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),u("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:s.sha256,gRed:!1,g:["9"]}),u("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:s.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});try{n=t("./precomputed/secp256k1")}catch(t){n=void 0}u("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:s.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",n]})},{"./curve":21,"./precomputed/secp256k1":31,"./utils":32,"hash.js":35}],25:[function(t,e,r){"use strict";var n=t("bn.js"),i=t("hmac-drbg"),s=t("../utils"),o=t("../curves"),f=t("brorand"),a=s.assert,u=t("./key"),c=t("./signature");function h(t){if(!(this instanceof h))return new h(t);"string"==typeof t&&(a(o.hasOwnProperty(t),"Unknown curve "+t),t=o[t]),t instanceof o.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}e.exports=h,h.prototype.keyPair=function(t){return new u(this,t)},h.prototype.keyFromPrivate=function(t,e){return u.fromPrivate(this,t,e)},h.prototype.keyFromPublic=function(t,e){return u.fromPublic(this,t,e)},h.prototype.genKeyPair=function(t){t||(t={});for(var e=new i({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||f(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),s=this.n.sub(new n(2));;){var o=new n(e.generate(r));if(!(o.cmp(s)>0))return o.iaddn(1),this.keyFromPrivate(o)}},h.prototype._truncateToN=function(t,e){var r=8*t.byteLength()-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},h.prototype.sign=function(t,e,r,s){"object"==typeof r&&(s=r,r=null),s||(s={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new n(t,16));for(var o=this.n.byteLength(),f=e.getPrivate().toArray("be",o),a=t.toArray("be",o),u=new i({hash:this.hash,entropy:f,nonce:a,pers:s.pers,persEnc:s.persEnc||"utf8"}),h=this.n.sub(new n(1)),d=0;;d++){var p=s.k?s.k(d):new n(u.generate(this.n.byteLength()));if(!((p=this._truncateToN(p,!0)).cmpn(1)<=0||p.cmp(h)>=0)){var l=this.g.mul(p);if(!l.isInfinity()){var b=l.getX(),m=b.umod(this.n);if(0!==m.cmpn(0)){var y=p.invm(this.n).mul(m.mul(e.getPrivate()).iadd(t));if(0!==(y=y.umod(this.n)).cmpn(0)){var g=(l.getY().isOdd()?1:0)|(0!==b.cmp(m)?2:0);return s.canonical&&y.cmp(this.nh)>0&&(y=this.n.sub(y),g^=1),new c({r:m,s:y,recoveryParam:g})}}}}}},h.prototype.verify=function(t,e,r,i){t=this._truncateToN(new n(t,16)),r=this.keyFromPublic(r,i);var s=(e=new c(e,"hex")).r,o=e.s;if(s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;var f,a=o.invm(this.n),u=a.mul(t).umod(this.n),h=a.mul(s).umod(this.n);return this.curve._maxwellTrick?!(f=this.g.jmulAdd(u,r.getPublic(),h)).isInfinity()&&f.eqXToP(s):!(f=this.g.mulAdd(u,r.getPublic(),h)).isInfinity()&&0===f.getX().umod(this.n).cmp(s)},h.prototype.recoverPubKey=function(t,e,r,i){a((3&r)===r,"The recovery param is more than two bits"),e=new c(e,i);var s=this.n,o=new n(t),f=e.r,u=e.s,h=1&r,d=r>>1;if(f.cmp(this.curve.p.umod(this.curve.n))>=0&&d)throw new Error("Unable to find sencond key candinate");f=d?this.curve.pointFromX(f.add(this.curve.n),h):this.curve.pointFromX(f,h);var p=e.r.invm(s),l=s.sub(o).mul(p).umod(s),b=u.mul(p).umod(s);return this.g.mulAdd(l,f,b)},h.prototype.getKeyRecoveryParam=function(t,e,r,n){if(null!==(e=new c(e,n)).recoveryParam)return e.recoveryParam;for(var i=0;i<4;i++){var s;try{s=this.recoverPubKey(t,e,i)}catch(t){continue}if(s.eq(r))return i}throw new Error("Unable to find valid recovery factor")}},{"../curves":24,"../utils":32,"./key":26,"./signature":27,"bn.js":8,brorand:9,"hmac-drbg":47}],26:[function(t,e,r){"use strict";var n=t("bn.js"),i=t("../utils").assert;function s(t,e){this.ec=t,this.priv=null,this.pub=null,e.priv&&this._importPrivate(e.priv,e.privEnc),e.pub&&this._importPublic(e.pub,e.pubEnc)}e.exports=s,s.fromPublic=function(t,e,r){return e instanceof s?e:new s(t,{pub:e,pubEnc:r})},s.fromPrivate=function(t,e,r){return e instanceof s?e:new s(t,{priv:e,privEnc:r})},s.prototype.validate=function(){var t=this.getPublic();return t.isInfinity()?{result:!1,reason:"Invalid public key"}:t.validate()?t.mul(this.ec.curve.n).isInfinity()?{result:!0,reason:null}:{result:!1,reason:"Public key * N != O"}:{result:!1,reason:"Public key is not a point"}},s.prototype.getPublic=function(t,e){return"string"==typeof t&&(e=t,t=null),this.pub||(this.pub=this.ec.g.mul(this.priv)),e?this.pub.encode(e,t):this.pub},s.prototype.getPrivate=function(t){return"hex"===t?this.priv.toString(16,2):this.priv},s.prototype._importPrivate=function(t,e){this.priv=new n(t,e||16),this.priv=this.priv.umod(this.ec.curve.n)},s.prototype._importPublic=function(t,e){if(t.x||t.y)return"mont"===this.ec.curve.type?i(t.x,"Need x coordinate"):"short"!==this.ec.curve.type&&"edwards"!==this.ec.curve.type||i(t.x&&t.y,"Need both x and y coordinate"),void(this.pub=this.ec.curve.point(t.x,t.y));this.pub=this.ec.curve.decodePoint(t,e)},s.prototype.derive=function(t){return t.mul(this.priv).getX()},s.prototype.sign=function(t,e,r){return this.ec.sign(t,this,e,r)},s.prototype.verify=function(t,e){return this.ec.verify(t,e,this)},s.prototype.inspect=function(){return""}},{"../utils":32,"bn.js":8}],27:[function(t,e,r){"use strict";var n=t("bn.js"),i=t("../utils"),s=i.assert;function o(t,e){if(t instanceof o)return t;this._importDER(t,e)||(s(t.r&&t.s,"Signature without r or s"),this.r=new n(t.r,16),this.s=new n(t.s,16),void 0===t.recoveryParam?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}function f(t,e){var r=t[e.place++];if(!(128&r))return r;for(var n=15&r,i=0,s=0,o=e.place;s>>3);for(t.push(128|r);--r;)t.push(e>>>(r<<3)&255);t.push(e)}}e.exports=o,o.prototype._importDER=function(t,e){t=i.toArray(t,e);var r=new function(){this.place=0};if(48!==t[r.place++])return!1;if(f(t,r)+r.place!==t.length)return!1;if(2!==t[r.place++])return!1;var s=f(t,r),o=t.slice(r.place,s+r.place);if(r.place+=s,2!==t[r.place++])return!1;var a=f(t,r);if(t.length!==a+r.place)return!1;var u=t.slice(r.place,a+r.place);return 0===o[0]&&128&o[1]&&(o=o.slice(1)),0===u[0]&&128&u[1]&&(u=u.slice(1)),this.r=new n(o),this.s=new n(u),this.recoveryParam=null,!0},o.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(128&e[0]&&(e=[0].concat(e)),128&r[0]&&(r=[0].concat(r)),e=a(e),r=a(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];u(n,e.length),(n=n.concat(e)).push(2),u(n,r.length);var s=n.concat(r),o=[48];return u(o,s.length),o=o.concat(s),i.encode(o,t)}},{"../utils":32,"bn.js":8}],28:[function(t,e,r){"use strict";var n=t("hash.js"),i=t("../curves"),s=t("../utils"),o=s.assert,f=s.parseBytes,a=t("./key"),u=t("./signature");function c(t){if(o("ed25519"===t,"only tested with ed25519 so far"),!(this instanceof c))return new c(t);t=i[t].curve;this.curve=t,this.g=t.g,this.g.precompute(t.n.bitLength()+1),this.pointClass=t.point().constructor,this.encodingLength=Math.ceil(t.n.bitLength()/8),this.hash=n.sha512}e.exports=c,c.prototype.sign=function(t,e){t=f(t);var r=this.keyFromSecret(e),n=this.hashInt(r.messagePrefix(),t),i=this.g.mul(n),s=this.encodePoint(i),o=this.hashInt(s,r.pubBytes(),t).mul(r.priv()),a=n.add(o).umod(this.curve.n);return this.makeSignature({R:i,S:a,Rencoded:s})},c.prototype.verify=function(t,e,r){t=f(t),e=this.makeSignature(e);var n=this.keyFromPublic(r),i=this.hashInt(e.Rencoded(),n.pubBytes(),t),s=this.g.mul(e.S());return e.R().add(n.pub().mul(i)).eq(s)},c.prototype.hashInt=function(){for(var t=this.hash(),e=0;e=0;){var s;if(i.isOdd()){var o=i.andln(n-1);s=o>(n>>1)-1?(n>>1)-o:o,i.isubn(s)}else s=0;r.push(s);for(var f=0!==i.cmpn(0)&&0===i.andln(n-1)?e+1:1,a=1;a0||e.cmpn(-i)>0;){var s,o,f,a=t.andln(3)+n&3,u=e.andln(3)+i&3;3===a&&(a=-1),3===u&&(u=-1),s=0==(1&a)?0:3!=(f=t.andln(7)+n&7)&&5!==f||2!==u?a:-a,r[0].push(s),o=0==(1&u)?0:3!=(f=e.andln(7)+i&7)&&5!==f||2!==a?u:-u,r[1].push(o),2*n===s+1&&(n=1-n),2*i===o+1&&(i=1-i),t.iushrn(1),e.iushrn(1)}return r},n.cachedProperty=function(t,e,r){var n="_"+e;t.prototype[e]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},n.parseBytes=function(t){return"string"==typeof t?n.toArray(t,"hex"):t},n.intFromLE=function(t){return new i(t,"hex","le")}},{"bn.js":8,"minimalistic-assert":51,"minimalistic-crypto-utils":52}],33:[function(t,e,r){e.exports={_from:"elliptic@^6.4.0",_id:"elliptic@6.5.1",_inBundle:!1,_integrity:"sha512-xvJINNLbTeWQjrl6X+7eQCrIy/YPv5XCpKW6kB5mKvtnGILoLDcySuwomfdzt0BMdLNVnuRNTuzKNHj0bva1Cg==",_location:"/elliptic",_phantomChildren:{},_requested:{type:"range",registry:!0,raw:"elliptic@^6.4.0",name:"elliptic",escapedName:"elliptic",rawSpec:"^6.4.0",saveSpec:null,fetchSpec:"^6.4.0"},_requiredBy:["/tiny-secp256k1"],_resolved:"https://registry.npmjs.org/elliptic/-/elliptic-6.5.1.tgz",_shasum:"c380f5f909bf1b9b4428d028cd18d3b0efd6b52b",_spec:"elliptic@^6.4.0",_where:"/counterwallet/src/vendors/bitcoinjs-lib/node_modules/tiny-secp256k1",author:{name:"Fedor Indutny",email:"fedor@indutny.com"},bugs:{url:"https://github.com/indutny/elliptic/issues"},bundleDependencies:!1,dependencies:{"bn.js":"^4.4.0",brorand:"^1.0.1","hash.js":"^1.0.0","hmac-drbg":"^1.0.0",inherits:"^2.0.1","minimalistic-assert":"^1.0.0","minimalistic-crypto-utils":"^1.0.0"},deprecated:!1,description:"EC cryptography",devDependencies:{brfs:"^1.4.3",coveralls:"^3.0.4",grunt:"^1.0.4","grunt-browserify":"^5.0.0","grunt-cli":"^1.2.0","grunt-contrib-connect":"^1.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^1.0.1","grunt-mocha-istanbul":"^3.0.1","grunt-saucelabs":"^9.0.1",istanbul:"^0.4.2",jscs:"^3.0.7",jshint:"^2.6.0",mocha:"^6.1.4"},files:["lib"],homepage:"https://github.com/indutny/elliptic",keywords:["EC","Elliptic","curve","Cryptography"],license:"MIT",main:"lib/elliptic.js",name:"elliptic",repository:{type:"git",url:"git+ssh://git@github.com/indutny/elliptic.git"},scripts:{jscs:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",jshint:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",lint:"npm run jscs && npm run jshint",test:"npm run lint && npm run unit",unit:"istanbul test _mocha --reporter=spec test/index.js",version:"grunt dist && git add dist/"},version:"6.5.1"}},{}],34:[function(t,e,r){"use strict";var n=t("safe-buffer").Buffer,i=t("stream").Transform;function s(t){i.call(this),this._block=n.allocUnsafe(t),this._blockSize=t,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}t("inherits")(s,i),s.prototype._transform=function(t,e,r){var n=null;try{this.update(t,e)}catch(t){n=t}r(n)},s.prototype._flush=function(t){var e=null;try{this.push(this.digest())}catch(t){e=t}t(e)},s.prototype.update=function(t,e){if(function(t,e){if(!n.isBuffer(t)&&"string"!=typeof t)throw new TypeError(e+" must be a string or a buffer")}(t,"Data"),this._finalized)throw new Error("Digest already called");n.isBuffer(t)||(t=n.from(t,e));for(var r=this._block,i=0;this._blockOffset+t.length-i>=this._blockSize;){for(var s=this._blockOffset;s0;++o)this._length[o]+=f,(f=this._length[o]/4294967296|0)>0&&(this._length[o]-=4294967296*f);return this},s.prototype._update=function(){throw new Error("_update is not implemented")},s.prototype.digest=function(t){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var e=this._digest();void 0!==t&&(e=e.toString(t)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return e},s.prototype._digest=function(){throw new Error("_digest is not implemented")},e.exports=s},{inherits:48,"safe-buffer":56,stream:144}],35:[function(t,e,r){var n=r;n.utils=t("./hash/utils"),n.common=t("./hash/common"),n.sha=t("./hash/sha"),n.ripemd=t("./hash/ripemd"),n.hmac=t("./hash/hmac"),n.sha1=n.sha.sha1,n.sha256=n.sha.sha256,n.sha224=n.sha.sha224,n.sha384=n.sha.sha384,n.sha512=n.sha.sha512,n.ripemd160=n.ripemd.ripemd160},{"./hash/common":36,"./hash/hmac":37,"./hash/ripemd":38,"./hash/sha":39,"./hash/utils":46}],36:[function(t,e,r){"use strict";var n=t("./utils"),i=t("minimalistic-assert");function s(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}r.BlockHash=s,s.prototype.update=function(t,e){if(t=n.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){var r=(t=this.pending).length%this._delta8;this.pending=t.slice(t.length-r,t.length),0===this.pending.length&&(this.pending=null),t=n.join32(t,0,t.length-r,this.endian);for(var i=0;i>>24&255,n[i++]=t>>>16&255,n[i++]=t>>>8&255,n[i++]=255&t}else for(n[i++]=255&t,n[i++]=t>>>8&255,n[i++]=t>>>16&255,n[i++]=t>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,s=8;sthis.blockSize&&(t=(new this.Hash).update(t).digest()),i(t.length<=this.blockSize);for(var e=t.length;e>>3},r.g1_256=function(t){return n(t,17)^n(t,19)^t>>>10}},{"../utils":46}],46:[function(t,e,r){"use strict";var n=t("minimalistic-assert"),i=t("inherits");function s(t,e){return 55296==(64512&t.charCodeAt(e))&&(!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1)))}function o(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}function f(t){return 1===t.length?"0"+t:t}function a(t){return 7===t.length?"0"+t:6===t.length?"00"+t:5===t.length?"000"+t:4===t.length?"0000"+t:3===t.length?"00000"+t:2===t.length?"000000"+t:1===t.length?"0000000"+t:t}r.inherits=i,r.toArray=function(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if("string"==typeof t)if(e){if("hex"===e)for((t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t),i=0;i>6|192,r[n++]=63&o|128):s(t,i)?(o=65536+((1023&o)<<10)+(1023&t.charCodeAt(++i)),r[n++]=o>>18|240,r[n++]=o>>12&63|128,r[n++]=o>>6&63|128,r[n++]=63&o|128):(r[n++]=o>>12|224,r[n++]=o>>6&63|128,r[n++]=63&o|128)}else for(i=0;i>>0}return o},r.split32=function(t,e){for(var r=new Array(4*t.length),n=0,i=0;n>>24,r[i+1]=s>>>16&255,r[i+2]=s>>>8&255,r[i+3]=255&s):(r[i+3]=s>>>24,r[i+2]=s>>>16&255,r[i+1]=s>>>8&255,r[i]=255&s)}return r},r.rotr32=function(t,e){return t>>>e|t<<32-e},r.rotl32=function(t,e){return t<>>32-e},r.sum32=function(t,e){return t+e>>>0},r.sum32_3=function(t,e,r){return t+e+r>>>0},r.sum32_4=function(t,e,r,n){return t+e+r+n>>>0},r.sum32_5=function(t,e,r,n,i){return t+e+r+n+i>>>0},r.sum64=function(t,e,r,n){var i=t[e],s=n+t[e+1]>>>0,o=(s>>0,t[e+1]=s},r.sum64_hi=function(t,e,r,n){return(e+n>>>0>>0},r.sum64_lo=function(t,e,r,n){return e+n>>>0},r.sum64_4_hi=function(t,e,r,n,i,s,o,f){var a=0,u=e;return a+=(u=u+n>>>0)>>0)>>0)>>0},r.sum64_4_lo=function(t,e,r,n,i,s,o,f){return e+n+s+f>>>0},r.sum64_5_hi=function(t,e,r,n,i,s,o,f,a,u){var c=0,h=e;return c+=(h=h+n>>>0)>>0)>>0)>>0)>>0},r.sum64_5_lo=function(t,e,r,n,i,s,o,f,a,u){return e+n+s+f+u>>>0},r.rotr64_hi=function(t,e,r){return(e<<32-r|t>>>r)>>>0},r.rotr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0},r.shr64_hi=function(t,e,r){return t>>>r},r.shr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0}},{inherits:48,"minimalistic-assert":51}],47:[function(t,e,r){"use strict";var n=t("hash.js"),i=t("minimalistic-crypto-utils"),s=t("minimalistic-assert");function o(t){if(!(this instanceof o))return new o(t);this.hash=t.hash,this.predResist=!!t.predResist,this.outLen=this.hash.outSize,this.minEntropy=t.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var e=i.toArray(t.entropy,t.entropyEnc||"hex"),r=i.toArray(t.nonce,t.nonceEnc||"hex"),n=i.toArray(t.pers,t.persEnc||"hex");s(e.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,n)}e.exports=o,o.prototype._init=function(t,e,r){var n=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},o.prototype.generate=function(t,e,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof e&&(n=r,r=e,e=null),r&&(r=i.toArray(r,n||"hex"),this._update(r));for(var s=[];s.length>>32-e}function u(t,e,r,n,i,s,o){return a(t+(e&r|~e&n)+i+s|0,o)+e|0}function c(t,e,r,n,i,s,o){return a(t+(e&n|r&~n)+i+s|0,o)+e|0}function h(t,e,r,n,i,s,o){return a(t+(e^r^n)+i+s|0,o)+e|0}function d(t,e,r,n,i,s,o){return a(t+(r^(e|~n))+i+s|0,o)+e|0}n(f,i),f.prototype._update=function(){for(var t=o,e=0;e<16;++e)t[e]=this._block.readInt32LE(4*e);var r=this._a,n=this._b,i=this._c,s=this._d;n=d(n=d(n=d(n=d(n=h(n=h(n=h(n=h(n=c(n=c(n=c(n=c(n=u(n=u(n=u(n=u(n,i=u(i,s=u(s,r=u(r,n,i,s,t[0],3614090360,7),n,i,t[1],3905402710,12),r,n,t[2],606105819,17),s,r,t[3],3250441966,22),i=u(i,s=u(s,r=u(r,n,i,s,t[4],4118548399,7),n,i,t[5],1200080426,12),r,n,t[6],2821735955,17),s,r,t[7],4249261313,22),i=u(i,s=u(s,r=u(r,n,i,s,t[8],1770035416,7),n,i,t[9],2336552879,12),r,n,t[10],4294925233,17),s,r,t[11],2304563134,22),i=u(i,s=u(s,r=u(r,n,i,s,t[12],1804603682,7),n,i,t[13],4254626195,12),r,n,t[14],2792965006,17),s,r,t[15],1236535329,22),i=c(i,s=c(s,r=c(r,n,i,s,t[1],4129170786,5),n,i,t[6],3225465664,9),r,n,t[11],643717713,14),s,r,t[0],3921069994,20),i=c(i,s=c(s,r=c(r,n,i,s,t[5],3593408605,5),n,i,t[10],38016083,9),r,n,t[15],3634488961,14),s,r,t[4],3889429448,20),i=c(i,s=c(s,r=c(r,n,i,s,t[9],568446438,5),n,i,t[14],3275163606,9),r,n,t[3],4107603335,14),s,r,t[8],1163531501,20),i=c(i,s=c(s,r=c(r,n,i,s,t[13],2850285829,5),n,i,t[2],4243563512,9),r,n,t[7],1735328473,14),s,r,t[12],2368359562,20),i=h(i,s=h(s,r=h(r,n,i,s,t[5],4294588738,4),n,i,t[8],2272392833,11),r,n,t[11],1839030562,16),s,r,t[14],4259657740,23),i=h(i,s=h(s,r=h(r,n,i,s,t[1],2763975236,4),n,i,t[4],1272893353,11),r,n,t[7],4139469664,16),s,r,t[10],3200236656,23),i=h(i,s=h(s,r=h(r,n,i,s,t[13],681279174,4),n,i,t[0],3936430074,11),r,n,t[3],3572445317,16),s,r,t[6],76029189,23),i=h(i,s=h(s,r=h(r,n,i,s,t[9],3654602809,4),n,i,t[12],3873151461,11),r,n,t[15],530742520,16),s,r,t[2],3299628645,23),i=d(i,s=d(s,r=d(r,n,i,s,t[0],4096336452,6),n,i,t[7],1126891415,10),r,n,t[14],2878612391,15),s,r,t[5],4237533241,21),i=d(i,s=d(s,r=d(r,n,i,s,t[12],1700485571,6),n,i,t[3],2399980690,10),r,n,t[10],4293915773,15),s,r,t[1],2240044497,21),i=d(i,s=d(s,r=d(r,n,i,s,t[8],1873313359,6),n,i,t[15],4264355552,10),r,n,t[6],2734768916,15),s,r,t[13],1309151649,21),i=d(i,s=d(s,r=d(r,n,i,s,t[4],4149444226,6),n,i,t[11],3174756917,10),r,n,t[2],718787259,15),s,r,t[9],3951481745,21),this._a=this._a+r|0,this._b=this._b+n|0,this._c=this._c+i|0,this._d=this._d+s|0},f.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var t=s.allocUnsafe(16);return t.writeInt32LE(this._a,0),t.writeInt32LE(this._b,4),t.writeInt32LE(this._c,8),t.writeInt32LE(this._d,12),t},e.exports=f},{"hash-base":34,inherits:48,"safe-buffer":56}],50:[function(t,e,r){(function(t){e.exports=function(e,r){if(!Array.isArray(e))throw TypeError("Expected values Array");if("function"!=typeof r)throw TypeError("Expected digest Function");for(var n=e.length,i=e.concat();n>1;){for(var s=0,o=0;o>8,o=255&i;s?r.push(s,o):r.push(o)}return r},n.zero2=i,n.toHex=s,n.encode=function(t,e){return"hex"===e?s(t):t}},{}],53:[function(t,e,r){var n=t("bitcoin-ops");function i(t){return tt.length)return null;r=t.readUInt8(e+1),i=2}else if(s===n.OP_PUSHDATA2){if(e+3>t.length)return null;r=t.readUInt16LE(e+1),i=3}else{if(e+5>t.length)return null;if(s!==n.OP_PUSHDATA4)throw new Error("Unexpected opcode");r=t.readUInt32LE(e+1),i=5}return{opcode:s,number:r,size:i}}}},{"bitcoin-ops":6}],54:[function(t,e,r){(function(r,n){"use strict";var i=65536,s=4294967295;var o=t("safe-buffer").Buffer,f=n.crypto||n.msCrypto;f&&f.getRandomValues?e.exports=function(t,e){if(t>s)throw new RangeError("requested too many random bytes");var n=o.allocUnsafe(t);if(t>0)if(t>i)for(var a=0;a>>32-e}function b(t,e,r,n,i,s,o,f){return l(t+(e^r^n)+s+o|0,f)+i|0}function m(t,e,r,n,i,s,o,f){return l(t+(e&r|~e&n)+s+o|0,f)+i|0}function y(t,e,r,n,i,s,o,f){return l(t+((e|~r)^n)+s+o|0,f)+i|0}function g(t,e,r,n,i,s,o,f){return l(t+(e&n|r&~n)+s+o|0,f)+i|0}function v(t,e,r,n,i,s,o,f){return l(t+(e^(r|~n))+s+o|0,f)+i|0}i(p,s),p.prototype._update=function(){for(var t=o,e=0;e<16;++e)t[e]=this._block.readInt32LE(4*e);for(var r=0|this._a,n=0|this._b,i=0|this._c,s=0|this._d,p=0|this._e,w=0|this._a,_=0|this._b,S=0|this._c,E=0|this._d,M=0|this._e,k=0;k<80;k+=1){var A,x;k<16?(A=b(r,n,i,s,p,t[f[k]],h[0],u[k]),x=v(w,_,S,E,M,t[a[k]],d[0],c[k])):k<32?(A=m(r,n,i,s,p,t[f[k]],h[1],u[k]),x=g(w,_,S,E,M,t[a[k]],d[1],c[k])):k<48?(A=y(r,n,i,s,p,t[f[k]],h[2],u[k]),x=y(w,_,S,E,M,t[a[k]],d[2],c[k])):k<64?(A=g(r,n,i,s,p,t[f[k]],h[3],u[k]),x=m(w,_,S,E,M,t[a[k]],d[3],c[k])):(A=v(r,n,i,s,p,t[f[k]],h[4],u[k]),x=b(w,_,S,E,M,t[a[k]],d[4],c[k])),r=p,p=s,s=l(i,10),i=n,n=A,w=M,M=E,E=l(S,10),S=_,_=x}var I=this._b+i+E|0;this._b=this._c+s+M|0,this._c=this._d+p+w|0,this._d=this._e+r+_|0,this._e=this._a+n+S|0,this._a=I},p.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var t=n.alloc?n.alloc(20):new n(20);return t.writeInt32LE(this._a,0),t.writeInt32LE(this._b,4),t.writeInt32LE(this._c,8),t.writeInt32LE(this._d,12),t.writeInt32LE(this._e,16),t},e.exports=p},{buffer:119,"hash-base":34,inherits:48}],56:[function(t,e,r){var n=t("buffer"),i=n.Buffer;function s(t,e){for(var r in t)e[r]=t[r]}function o(t,e,r){return i(t,e,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?e.exports=n:(s(n,r),r.Buffer=o),o.prototype=Object.create(i.prototype),s(i,o),o.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return i(t,e,r)},o.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var n=i(t);return void 0!==e?"string"==typeof r?n.fill(e,r):n.fill(e):n.fill(0),n},o.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return i(t)},o.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return n.SlowBuffer(t)}},{buffer:119}],57:[function(t,e,r){var n=t("safe-buffer").Buffer;function i(t,e){this._block=n.alloc(t),this._finalSize=e,this._blockSize=t,this._len=0}i.prototype.update=function(t,e){"string"==typeof t&&(e=e||"utf8",t=n.from(t,e));for(var r=this._block,i=this._blockSize,s=t.length,o=this._len,f=0;f=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var s=this._hash();return t?s.toString(t):s},i.prototype._update=function(){throw new Error("_update must be implemented by subclass")},e.exports=i},{"safe-buffer":56}],58:[function(t,e,r){(r=e.exports=function(t){t=t.toLowerCase();var e=r[t];if(!e)throw new Error(t+" is not supported (we accept pull requests)");return new e}).sha=t("./sha"),r.sha1=t("./sha1"),r.sha224=t("./sha224"),r.sha256=t("./sha256"),r.sha384=t("./sha384"),r.sha512=t("./sha512")},{"./sha":59,"./sha1":60,"./sha224":61,"./sha256":62,"./sha384":63,"./sha512":64}],59:[function(t,e,r){var n=t("inherits"),i=t("./hash"),s=t("safe-buffer").Buffer,o=[1518500249,1859775393,-1894007588,-899497514],f=new Array(80);function a(){this.init(),this._w=f,i.call(this,64,56)}function u(t){return t<<30|t>>>2}function c(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}n(a,i),a.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},a.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,s=0|this._c,f=0|this._d,a=0|this._e,h=0;h<16;++h)r[h]=t.readInt32BE(4*h);for(;h<80;++h)r[h]=r[h-3]^r[h-8]^r[h-14]^r[h-16];for(var d=0;d<80;++d){var p=~~(d/20),l=0|((e=n)<<5|e>>>27)+c(p,i,s,f)+a+r[d]+o[p];a=f,f=s,s=u(i),i=n,n=l}this._a=n+this._a|0,this._b=i+this._b|0,this._c=s+this._c|0,this._d=f+this._d|0,this._e=a+this._e|0},a.prototype._hash=function(){var t=s.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t},e.exports=a},{"./hash":57,inherits:48,"safe-buffer":56}],60:[function(t,e,r){var n=t("inherits"),i=t("./hash"),s=t("safe-buffer").Buffer,o=[1518500249,1859775393,-1894007588,-899497514],f=new Array(80);function a(){this.init(),this._w=f,i.call(this,64,56)}function u(t){return t<<5|t>>>27}function c(t){return t<<30|t>>>2}function h(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}n(a,i),a.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},a.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,s=0|this._c,f=0|this._d,a=0|this._e,d=0;d<16;++d)r[d]=t.readInt32BE(4*d);for(;d<80;++d)r[d]=(e=r[d-3]^r[d-8]^r[d-14]^r[d-16])<<1|e>>>31;for(var p=0;p<80;++p){var l=~~(p/20),b=u(n)+h(l,i,s,f)+a+r[p]+o[l]|0;a=f,f=s,s=c(i),i=n,n=b}this._a=n+this._a|0,this._b=i+this._b|0,this._c=s+this._c|0,this._d=f+this._d|0,this._e=a+this._e|0},a.prototype._hash=function(){var t=s.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t},e.exports=a},{"./hash":57,inherits:48,"safe-buffer":56}],61:[function(t,e,r){var n=t("inherits"),i=t("./sha256"),s=t("./hash"),o=t("safe-buffer").Buffer,f=new Array(64);function a(){this.init(),this._w=f,s.call(this,64,56)}n(a,i),a.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},a.prototype._hash=function(){var t=o.allocUnsafe(28);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t},e.exports=a},{"./hash":57,"./sha256":62,inherits:48,"safe-buffer":56}],62:[function(t,e,r){var n=t("inherits"),i=t("./hash"),s=t("safe-buffer").Buffer,o=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],f=new Array(64);function a(){this.init(),this._w=f,i.call(this,64,56)}function u(t,e,r){return r^t&(e^r)}function c(t,e,r){return t&e|r&(t|e)}function h(t){return(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10)}function d(t){return(t>>>6|t<<26)^(t>>>11|t<<21)^(t>>>25|t<<7)}function p(t){return(t>>>7|t<<25)^(t>>>18|t<<14)^t>>>3}n(a,i),a.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},a.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,s=0|this._c,f=0|this._d,a=0|this._e,l=0|this._f,b=0|this._g,m=0|this._h,y=0;y<16;++y)r[y]=t.readInt32BE(4*y);for(;y<64;++y)r[y]=0|(((e=r[y-2])>>>17|e<<15)^(e>>>19|e<<13)^e>>>10)+r[y-7]+p(r[y-15])+r[y-16];for(var g=0;g<64;++g){var v=m+d(a)+u(a,l,b)+o[g]+r[g]|0,w=h(n)+c(n,i,s)|0;m=b,b=l,l=a,a=f+v|0,f=s,s=i,i=n,n=v+w|0}this._a=n+this._a|0,this._b=i+this._b|0,this._c=s+this._c|0,this._d=f+this._d|0,this._e=a+this._e|0,this._f=l+this._f|0,this._g=b+this._g|0,this._h=m+this._h|0},a.prototype._hash=function(){var t=s.allocUnsafe(32);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t.writeInt32BE(this._h,28),t},e.exports=a},{"./hash":57,inherits:48,"safe-buffer":56}],63:[function(t,e,r){var n=t("inherits"),i=t("./sha512"),s=t("./hash"),o=t("safe-buffer").Buffer,f=new Array(160);function a(){this.init(),this._w=f,s.call(this,128,112)}n(a,i),a.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},a.prototype._hash=function(){var t=o.allocUnsafe(48);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),t},e.exports=a},{"./hash":57,"./sha512":64,inherits:48,"safe-buffer":56}],64:[function(t,e,r){var n=t("inherits"),i=t("./hash"),s=t("safe-buffer").Buffer,o=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],f=new Array(160);function a(){this.init(),this._w=f,i.call(this,128,112)}function u(t,e,r){return r^t&(e^r)}function c(t,e,r){return t&e|r&(t|e)}function h(t,e){return(t>>>28|e<<4)^(e>>>2|t<<30)^(e>>>7|t<<25)}function d(t,e){return(t>>>14|e<<18)^(t>>>18|e<<14)^(e>>>9|t<<23)}function p(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^t>>>7}function l(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^(t>>>7|e<<25)}function b(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^t>>>6}function m(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^(t>>>6|e<<26)}function y(t,e){return t>>>0>>0?1:0}n(a,i),a.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},a.prototype._update=function(t){for(var e=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,s=0|this._dh,f=0|this._eh,a=0|this._fh,g=0|this._gh,v=0|this._hh,w=0|this._al,_=0|this._bl,S=0|this._cl,E=0|this._dl,M=0|this._el,k=0|this._fl,A=0|this._gl,x=0|this._hl,I=0;I<32;I+=2)e[I]=t.readInt32BE(4*I),e[I+1]=t.readInt32BE(4*I+4);for(;I<160;I+=2){var O=e[I-30],P=e[I-30+1],T=p(O,P),B=l(P,O),N=b(O=e[I-4],P=e[I-4+1]),R=m(P,O),L=e[I-14],U=e[I-14+1],j=e[I-32],C=e[I-32+1],H=B+U|0,q=T+L+y(H,B)|0;q=(q=q+N+y(H=H+R|0,R)|0)+j+y(H=H+C|0,C)|0,e[I]=q,e[I+1]=H}for(var z=0;z<160;z+=2){q=e[z],H=e[z+1];var D=c(r,n,i),K=c(w,_,S),W=h(r,w),F=h(w,r),J=d(f,M),V=d(M,f),G=o[z],Y=o[z+1],Z=u(f,a,g),Q=u(M,k,A),X=x+V|0,$=v+J+y(X,x)|0;$=($=($=$+Z+y(X=X+Q|0,Q)|0)+G+y(X=X+Y|0,Y)|0)+q+y(X=X+H|0,H)|0;var tt=F+K|0,et=W+D+y(tt,F)|0;v=g,x=A,g=a,A=k,a=f,k=M,f=s+$+y(M=E+X|0,E)|0,s=i,E=S,i=n,S=_,n=r,_=w,r=$+et+y(w=X+tt|0,X)|0}this._al=this._al+w|0,this._bl=this._bl+_|0,this._cl=this._cl+S|0,this._dl=this._dl+E|0,this._el=this._el+M|0,this._fl=this._fl+k|0,this._gl=this._gl+A|0,this._hl=this._hl+x|0,this._ah=this._ah+r+y(this._al,w)|0,this._bh=this._bh+n+y(this._bl,_)|0,this._ch=this._ch+i+y(this._cl,S)|0,this._dh=this._dh+s+y(this._dl,E)|0,this._eh=this._eh+f+y(this._el,M)|0,this._fh=this._fh+a+y(this._fl,k)|0,this._gh=this._gh+g+y(this._gl,A)|0,this._hh=this._hh+v+y(this._hl,x)|0},a.prototype._hash=function(){var t=s.allocUnsafe(64);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),e(this._gh,this._gl,48),e(this._hh,this._hl,56),t},e.exports=a},{"./hash":57,inherits:48,"safe-buffer":56}],65:[function(t,e,r){(function(r){const n=t("bn.js"),i=new(0,t("elliptic").ec)("secp256k1"),s=t("./rfc6979"),o=r.alloc(32,0),f=r.from("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141","hex"),a=r.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex"),u=i.curve.n,c=u.shrn(1),h=i.curve.g,d="Expected Private",p="Expected Point",l="Expected Tweak",b="Expected Hash",m="Expected Signature",y="Expected Extra Data (32 bytes)";function g(t){return r.isBuffer(t)&&32===t.length}function v(t){return!!g(t)&&t.compare(f)<0}function w(t){if(!r.isBuffer(t))return!1;if(t.length<33)return!1;const e=t[0],n=t.slice(1,33);if(0===n.compare(o))return!1;if(n.compare(a)>=0)return!1;if((2===e||3===e)&&33===t.length){try{A(t)}catch(t){return!1}return!0}const i=t.slice(33);return 0!==i.compare(o)&&(!(i.compare(a)>=0)&&(4===e&&65===t.length))}function _(t){return 4!==t[0]}function S(t){return!!g(t)&&(t.compare(o)>0&&t.compare(f)<0)}function E(t,e){return void 0===t&&void 0!==e?_(e):void 0===t||t}function M(t){return new n(t)}function k(t){return t.toArrayLike(r,"be",32)}function A(t){return i.curve.decodePoint(t)}function x(t,e){return r.from(t._encode(e))}function I(t,e,n){if(!g(t))throw new TypeError(b);if(!S(e))throw new TypeError(d);if(void 0!==n&&!g(n))throw new TypeError(y);const i=M(e),o=M(t);let f,a;s(t,e,function(t){const e=M(t),r=h.mul(e);return!r.isInfinity()&&0!==(f=r.x.umod(u)).isZero()&&0!==(a=e.invm(u).mul(o.add(i.mul(f))).umod(u)).isZero()},S,n),a.cmp(c)>0&&(a=u.sub(a));const p=r.allocUnsafe(64);return k(f).copy(p,0),k(a).copy(p,32),p}e.exports={isPoint:w,isPointCompressed:function(t){return!!w(t)&&_(t)},isPrivate:S,pointAdd:function(t,e,r){if(!w(t))throw new TypeError(p);if(!w(e))throw new TypeError(p);const n=A(t),i=A(e),s=n.add(i);return s.isInfinity()?null:x(s,E(r,t))},pointAddScalar:function(t,e,r){if(!w(t))throw new TypeError(p);if(!v(e))throw new TypeError(l);const n=E(r,t),i=A(t);if(0===e.compare(o))return x(i,n);const s=M(e),f=h.mul(s),a=i.add(f);return a.isInfinity()?null:x(a,n)},pointCompress:function(t,e){if(!w(t))throw new TypeError(p);const r=A(t);if(r.isInfinity())throw new TypeError(p);return x(r,e)},pointFromScalar:function(t,e){if(!S(t))throw new TypeError(d);const r=M(t),n=h.mul(r);return n.isInfinity()?null:x(n,E(e))},pointMultiply:function(t,e,r){if(!w(t))throw new TypeError(p);if(!v(e))throw new TypeError(l);const n=E(r,t),i=A(t),s=M(e),o=i.mul(s);return o.isInfinity()?null:x(o,n)},privateAdd:function(t,e){if(!S(t))throw new TypeError(d);if(!v(e))throw new TypeError(l);const r=M(t),n=M(e),i=k(r.add(n).umod(u));return S(i)?i:null},privateSub:function(t,e){if(!S(t))throw new TypeError(d);if(!v(e))throw new TypeError(l);const r=M(t),n=M(e),i=k(r.sub(n).umod(u));return S(i)?i:null},sign:function(t,e){return I(t,e)},signWithEntropy:function(t,e,r){return I(t,e,r)},verify:function(t,e,n){if(!g(t))throw new TypeError(b);if(!w(e))throw new TypeError(p);if(!function(t){const e=t.slice(0,32),n=t.slice(32,64);return r.isBuffer(t)&&64===t.length&&e.compare(f)<0&&n.compare(f)<0}(n))throw new TypeError(m);const i=A(e),s=M(n.slice(0,32)),o=M(n.slice(32,64));if(s.gtn(0)<=0)return!1;if(o.gtn(0)<=0)return!1;const a=M(t),c=o.invm(u),d=a.mul(c).umod(u),l=s.mul(c).umod(u),y=h.mulAdd(d,i,l);return!y.isInfinity()&&y.x.umod(u).eq(s)}}}).call(this,t("buffer").Buffer)},{"./rfc6979":66,"bn.js":8,buffer:119,elliptic:18}],66:[function(t,e,r){(function(r){const n=t("create-hmac"),i=r.alloc(1,1),s=r.alloc(1,0);e.exports=function(t,e,o,f,a){let u=r.alloc(32,0),c=r.alloc(32,1);u=n("sha256",u).update(c).update(s).update(e).update(t).update(a||"").digest(),c=n("sha256",u).update(c).digest(),u=n("sha256",u).update(c).update(i).update(e).update(t).update(a||"").digest(),c=n("sha256",u).update(c).digest();let h=c=n("sha256",u).update(c).digest();for(;!f(h)||!o(h);)u=n("sha256",u).update(c).update(s).digest(),c=n("sha256",u).update(c).digest(),h=c=n("sha256",u).update(c).digest();return h}}).call(this,t("buffer").Buffer)},{buffer:119,"create-hmac":16}],67:[function(t,e,r){var n=t("./native");function i(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function s(t){return n.Nil(t)?"":i(t.constructor)}function o(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function f(t){return n.Function(t)?t.toJSON?t.toJSON():i(t):n.Array(t)?"Array":t&&n.Object(t)?"Object":void 0!==t?t:""}function a(t,e,r){var i=function(t){return n.Function(t)?"":n.String(t)?JSON.stringify(t):t&&n.Object(t)?"":t}(e);return"Expected "+f(t)+", got"+(""!==r?" "+r:"")+(""!==i?" "+i:"")}function u(t,e,r){r=r||s(e),this.message=a(t,e,r),o(this,u),this.__type=t,this.__value=e,this.__valueTypeName=r}function c(t,e,r,n,i){t?(i=i||s(n),this.message=function(t,e,r,n,i){var s='" of type ';return"key"===e&&(s='" with key type '),a('property "'+f(r)+s+f(t),n,i)}(t,r,e,n,i)):this.message='Unexpected property "'+e+'"',o(this,u),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=i}u.prototype=Object.create(Error.prototype),u.prototype.constructor=u,c.prototype=Object.create(Error.prototype),c.prototype.constructor=u,e.exports={TfTypeError:u,TfPropertyTypeError:c,tfCustomError:function(t,e){return new u(t,{},e)},tfSubError:function(t,e,r){return t instanceof c?(e=e+"."+t.__property,t=new c(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof u&&(t=new c(t.__type,e,r,t.__value,t.__valueTypeName)),o(t),t},tfJSON:f,getValueTypeName:s}},{"./native":70}],68:[function(t,e,r){(function(r){var n=t("./native"),i=t("./errors");function s(t){return r.isBuffer(t)}function o(t){return"string"==typeof t&&/^([0-9a-f]{2})+$/i.test(t)}function f(t,e){var r=t.toJSON();function n(n){if(!t(n))return!1;if(n.length===e)return!0;throw i.tfCustomError(r+"(Length: "+e+")",r+"(Length: "+n.length+")")}return n.toJSON=function(){return r},n}var a=f.bind(null,n.Array),u=f.bind(null,s),c=f.bind(null,o),h=f.bind(null,n.String);var d=Math.pow(2,53)-1;var p={ArrayN:a,Buffer:s,BufferN:u,Finite:function(t){return"number"==typeof t&&isFinite(t)},Hex:o,HexN:c,Int8:function(t){return t<<24>>24===t},Int16:function(t){return t<<16>>16===t},Int32:function(t){return(0|t)===t},Int53:function(t){return"number"==typeof t&&t>=-d&&t<=d&&Math.floor(t)===t},Range:function(t,e,r){function i(n,i){return r(n,i)&&n>t&&n>>0===t},UInt53:function(t){return"number"==typeof t&&t>=0&&t<=d&&Math.floor(t)===t}};for(var l in p)p[l].toJSON=function(t){return t}.bind(null,l);e.exports=p}).call(this,{isBuffer:t("../../../../../../usr/lib/node_modules/browserify/node_modules/is-buffer/index.js")})},{"../../../../../../usr/lib/node_modules/browserify/node_modules/is-buffer/index.js":124,"./errors":67,"./native":70}],69:[function(t,e,r){var n=t("./errors"),i=t("./native"),s=n.tfJSON,o=n.TfTypeError,f=n.TfPropertyTypeError,a=n.tfSubError,u=n.getValueTypeName,c={arrayOf:function(t,e){function r(r,n){return!!i.Array(r)&&(!i.Nil(r)&&(!(void 0!==e.minLength&&r.lengthe.maxLength)&&((void 0===e.length||r.length===e.length)&&r.every(function(e,r){try{return d(t,e,n)}catch(t){throw a(t,r)}})))))}return t=h(t),e=e||{},r.toJSON=function(){var r="["+s(t)+"]";return void 0!==e.length?r+="{"+e.length+"}":void 0===e.minLength&&void 0===e.maxLength||(r+="{"+(void 0===e.minLength?0:e.minLength)+","+(void 0===e.maxLength?1/0:e.maxLength)+"}"),r},r},maybe:function t(e){function r(r,n){return i.Nil(r)||e(r,n,t)}return e=h(e),r.toJSON=function(){return"?"+s(e)},r},map:function(t,e){function r(r,n){if(!i.Object(r))return!1;if(i.Nil(r))return!1;for(var s in r){try{e&&d(e,s,n)}catch(t){throw a(t,s,"key")}try{var o=r[s];d(t,o,n)}catch(t){throw a(t,s)}}return!0}return t=h(t),e&&(e=h(e)),r.toJSON=e?function(){return"{"+s(e)+": "+s(t)+"}"}:function(){return"{"+s(t)+"}"},r},object:function(t){var e={};for(var r in t)e[r]=h(t[r]);function n(t,r){if(!i.Object(t))return!1;if(i.Nil(t))return!1;var n;try{for(n in e){d(e[n],t[n],r)}}catch(t){throw a(t,n)}if(r)for(n in t)if(!e[n])throw new f(void 0,n);return!0}return n.toJSON=function(){return s(e)},n},anyOf:function(){var t=[].slice.call(arguments).map(h);function e(e,r){return t.some(function(t){try{return d(t,e,r)}catch(t){return!1}})}return e.toJSON=function(){return t.map(s).join("|")},e},allOf:function(){var t=[].slice.call(arguments).map(h);function e(e,r){return t.every(function(t){try{return d(t,e,r)}catch(t){return!1}})}return e.toJSON=function(){return t.map(s).join(" & ")},e},quacksLike:function(t){function e(e){return t===u(e)}return e.toJSON=function(){return t},e},tuple:function(){var t=[].slice.call(arguments).map(h);function e(e,r){return!i.Nil(e)&&(!i.Nil(e.length)&&((!r||e.length===t.length)&&t.every(function(t,n){try{return d(t,e[n],r)}catch(t){throw a(t,n)}})))}return e.toJSON=function(){return"("+t.map(s).join(", ")+")"},e},value:function(t){function e(e){return e===t}return e.toJSON=function(){return t},e}};function h(t){if(i.String(t))return"?"===t[0]?c.maybe(t.slice(1)):i[t]||c.quacksLike(t);if(t&&i.Object(t)){if(i.Array(t)){if(1!==t.length)throw new TypeError("Expected compile() parameter of type Array of length 1");return c.arrayOf(t[0])}return c.object(t)}return i.Function(t)?t:c.value(t)}function d(t,e,r,n){if(i.Function(t)){if(t(e,r))return!0;throw new o(n||t,e)}return d(h(t),e,r)}for(var p in c.oneOf=c.anyOf,i)d[p]=i[p];for(p in c)d[p]=c[p];var l=t("./extra");for(p in l)d[p]=l[p];d.compile=h,d.TfTypeError=o,d.TfPropertyTypeError=f,e.exports=d},{"./errors":67,"./extra":68,"./native":70}],70:[function(t,e,r){var n={Array:function(t){return null!==t&&void 0!==t&&t.constructor===Array},Boolean:function(t){return"boolean"==typeof t},Function:function(t){return"function"==typeof t},Nil:function(t){return void 0===t||null===t},Number:function(t){return"number"==typeof t},Object:function(t){return"object"==typeof t},String:function(t){return"string"==typeof t},"":function(){return!0}};for(var i in n.Null=n.Nil,n)n[i].toJSON=function(t){return t}.bind(null,i);e.exports=n},{}],71:[function(t,e,r){"use strict";var n=t("safe-buffer").Buffer,i=9007199254740991;function s(t){if(t<0||t>i||t%1!=0)throw new RangeError("value out of range")}function o(t){return s(t),t<253?1:t<=65535?3:t<=4294967295?5:9}e.exports={encode:function t(e,r,i){if(s(e),r||(r=n.allocUnsafe(o(e))),!n.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return i||(i=0),e<253?(r.writeUInt8(e,i),t.bytes=1):e<=65535?(r.writeUInt8(253,i),r.writeUInt16LE(e,i+1),t.bytes=3):e<=4294967295?(r.writeUInt8(254,i),r.writeUInt32LE(e,i+1),t.bytes=5):(r.writeUInt8(255,i),r.writeUInt32LE(e>>>0,i+1),r.writeUInt32LE(e/4294967296|0,i+5),t.bytes=9),r},decode:function t(e,r){if(!n.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);var i=e.readUInt8(r);if(i<253)return t.bytes=1,i;if(253===i)return t.bytes=3,e.readUInt16LE(r+1);if(254===i)return t.bytes=5,e.readUInt32LE(r+1);t.bytes=9;var o=e.readUInt32LE(r+1),f=4294967296*e.readUInt32LE(r+5)+o;return s(f),f},encodingLength:o}},{"safe-buffer":56}],72:[function(t,e,r){(function(r){var n=t("bs58check");function i(t,e){if(void 0!==e&&t[0]!==e)throw new Error("Invalid network version");if(33===t.length)return{version:t[0],privateKey:t.slice(1,33),compressed:!1};if(34!==t.length)throw new Error("Invalid WIF length");if(1!==t[33])throw new Error("Invalid compression flag");return{version:t[0],privateKey:t.slice(1,33),compressed:!0}}function s(t,e,n){var i=new r(n?34:33);return i.writeUInt8(t,0),e.copy(i,1),n&&(i[33]=1),i}e.exports={decode:function(t,e){return i(n.decode(t),e)},decodeRaw:i,encode:function(t,e,r){return"number"==typeof t?n.encode(s(t,e,r)):n.encode(s(t.version,t.privateKey,t.compressed))},encodeRaw:s}}).call(this,t("buffer").Buffer)},{bs58check:12,buffer:119}],73:[function(t,e,r){const n=t("safe-buffer").Buffer,i=t("bech32"),s=t("bs58check"),o=t("./script"),f=t("./networks"),a=t("typeforce"),u=t("./types"),c=t("./payments");function h(t){const e=s.decode(t);if(e.length<21)throw new TypeError(t+" is too short");if(e.length>21)throw new TypeError(t+" is too long");return{version:e.readUInt8(0),hash:e.slice(1)}}function d(t){const e=i.decode(t),r=i.fromWords(e.words.slice(1));return{version:e.words[0],prefix:e.prefix,data:n.from(r)}}e.exports={fromBase58Check:h,fromBech32:d,fromOutputScript:function(t,e){e=e||f.bitcoin;try{return c.p2pkh({output:t,network:e}).address}catch(t){}try{return c.p2sh({output:t,network:e}).address}catch(t){}try{return c.p2wpkh({output:t,network:e}).address}catch(t){}try{return c.p2wsh({output:t,network:e}).address}catch(t){}throw new Error(o.toASM(t)+" has no matching Address")},toBase58Check:function(t,e){a(u.tuple(u.Hash160bit,u.UInt8),arguments);const r=n.allocUnsafe(21);return r.writeUInt8(e,0),t.copy(r,1),s.encode(r)},toBech32:function(t,e,r){const n=i.toWords(t);return n.unshift(e),i.encode(r,n)},toOutputScript:function(t,e){let r;e=e||f.bitcoin;try{r=h(t)}catch(t){}if(r){if(r.version===e.pubKeyHash)return c.p2pkh({hash:r.hash}).output;if(r.version===e.scriptHash)return c.p2sh({hash:r.hash}).output}else{try{r=d(t)}catch(t){}if(r){if(r.prefix!==e.bech32)throw new Error(t+" has an invalid prefix");if(0===r.version){if(20===r.data.length)return c.p2wpkh({hash:r.data}).output;if(32===r.data.length)return c.p2wsh({hash:r.data}).output}}}throw new Error(t+" has no matching Script")}}},{"./networks":80,"./payments":82,"./script":90,"./types":116,bech32:2,bs58check:12,"safe-buffer":56,typeforce:69}],74:[function(t,e,r){const n=t("safe-buffer").Buffer,i=t("./crypto"),s=t("merkle-lib/fastRoot"),o=t("typeforce"),f=t("./types"),a=t("varuint-bitcoin"),u=t("./transaction");function c(){this.version=1,this.prevHash=null,this.merkleRoot=null,this.timestamp=0,this.bits=0,this.nonce=0}c.fromBuffer=function(t){if(t.length<80)throw new Error("Buffer too small (< 80 bytes)");let e=0;function r(r){return e+=r,t.slice(e-r,e)}function n(){const r=t.readUInt32LE(e);return e+=4,r}const i=new c;if(i.version=function(){const r=t.readInt32LE(e);return e+=4,r}(),i.prevHash=r(32),i.merkleRoot=r(32),i.timestamp=n(),i.bits=n(),i.nonce=n(),80===t.length)return i;function s(){const r=u.fromBuffer(t.slice(e),!0);return e+=r.byteLength(),r}const o=function(){const r=a.decode(t,e);return e+=a.decode.bytes,r}();i.transactions=[];for(var f=0;f>24)-3,r=8388607&t,i=n.alloc(32,0);return i.writeUInt32BE(r,28-e),i},c.calculateMerkleRoot=function(t){if(o([{getHash:f.Function}],t),0===t.length)throw TypeError("Cannot compute merkle root for zero transactions");const e=t.map(function(t){return t.getHash()});return s(e,i.hash256)},c.prototype.checkMerkleRoot=function(){if(!this.transactions)return!1;const t=c.calculateMerkleRoot(this.transactions);return 0===this.merkleRoot.compare(t)},c.prototype.checkProofOfWork=function(){const t=this.getHash().reverse(),e=c.calculateTarget(this.bits);return t.compare(e)<=0},e.exports=c},{"./crypto":77,"./transaction":114,"./types":116,"merkle-lib/fastRoot":50,"safe-buffer":56,typeforce:69,"varuint-bitcoin":71}],75:[function(t,e,r){function n(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}e.exports={readUInt64LE:function(t,e){const r=t.readUInt32LE(e);let i=t.readUInt32LE(e+4);return n((i*=4294967296)+r,9007199254740991),i+r},writeUInt64LE:function(t,e,r){return n(e,9007199254740991),t.writeInt32LE(-1&e,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}}},{}],76:[function(t,e,r){const n=t("./script").decompile,i=t("./templates/multisig"),s=t("./templates/nulldata"),o=t("./templates/pubkey"),f=t("./templates/pubkeyhash"),a=t("./templates/scripthash"),u=t("./templates/witnesspubkeyhash"),c=t("./templates/witnessscripthash"),h=t("./templates/witnesscommitment"),d={MULTISIG:"multisig",NONSTANDARD:"nonstandard",NULLDATA:"nulldata",P2PK:"pubkey",P2PKH:"pubkeyhash",P2SH:"scripthash",P2WPKH:"witnesspubkeyhash",P2WSH:"witnessscripthash",WITNESS_COMMITMENT:"witnesscommitment"};e.exports={input:function(t,e){const r=n(t);if(!r)throw new TypeError("Invalid script");return f.input.check(r)?d.P2PKH:a.input.check(r,e)?d.P2SH:i.input.check(r,e)?d.MULTISIG:o.input.check(r)?d.P2PK:d.NONSTANDARD},output:function(t){if(u.output.check(t))return d.P2WPKH;if(c.output.check(t))return d.P2WSH;if(f.output.check(t))return d.P2PKH;if(a.output.check(t))return d.P2SH;const e=n(t);if(!e)throw new TypeError("Invalid script");return i.output.check(e)?d.MULTISIG:o.output.check(e)?d.P2PK:h.output.check(e)?d.WITNESS_COMMITMENT:s.output.check(e)?d.NULLDATA:d.NONSTANDARD},witness:function(t,e){const r=n(t);if(!r)throw new TypeError("Invalid script");return u.input.check(r)?d.P2WPKH:c.input.check(r,e)?d.P2WSH:d.NONSTANDARD},types:d}},{"./script":90,"./templates/multisig":93,"./templates/nulldata":96,"./templates/pubkey":97,"./templates/pubkeyhash":100,"./templates/scripthash":103,"./templates/witnesscommitment":106,"./templates/witnesspubkeyhash":108,"./templates/witnessscripthash":111}],77:[function(t,e,r){const n=t("create-hash");function i(t){return n("rmd160").update(t).digest()}function s(t){return n("sha256").update(t).digest()}e.exports={hash160:function(t){return i(s(t))},hash256:function(t){return s(s(t))},ripemd160:i,sha1:function(t){return n("sha1").update(t).digest()},sha256:s}},{"create-hash":14}],78:[function(t,e,r){const n=t("tiny-secp256k1"),i=t("randombytes"),s=t("typeforce"),o=t("./types"),f=t("wif"),a=t("./networks"),u=s.maybe(s.compile({compressed:o.maybe(o.Boolean),network:o.maybe(o.Network)}));function ECPair(t,e,r){r=r||{},this.compressed=void 0===r.compressed||r.compressed,this.network=r.network||a.bitcoin,this.__d=t||null,this.__Q=null,e&&(this.__Q=n.pointCompress(e,this.compressed))}function c(t,e){if(s(o.Buffer256bit,t),!n.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return s(u,e),new ECPair(t,null,e)}Object.defineProperty(ECPair.prototype,"privateKey",{enumerable:!1,get:function(){return this.__d}}),Object.defineProperty(ECPair.prototype,"publicKey",{get:function(){return this.__Q||(this.__Q=n.pointFromScalar(this.__d,this.compressed)),this.__Q}}),ECPair.prototype.toWIF=function(){if(!this.__d)throw new Error("Missing private key");return f.encode(this.network.wif,this.__d,this.compressed)},ECPair.prototype.sign=function(t){if(!this.__d)throw new Error("Missing private key");return n.sign(t,this.__d)},ECPair.prototype.verify=function(t,e){return n.verify(t,this.publicKey,e)},e.exports={makeRandom:function(t){s(u,t);const e=(t=t||{}).rng||i;let r;do{r=e(32),s(o.Buffer256bit,r)}while(!n.isPrivate(r));return c(r,t)},fromPrivateKey:c,fromPublicKey:function(t,e){return s(n.isPoint,t),s(u,e),new ECPair(null,t,e)},fromWIF:function(t,e){const r=f.decode(t),n=r.version;if(o.Array(e)){if(!(e=e.filter(function(t){return n===t.wif}).pop()))throw new Error("Unknown network version")}else if(e=e||a.bitcoin,n!==e.wif)throw new Error("Invalid network version");return c(r.privateKey,{compressed:r.compressed,network:e})}}},{"./networks":80,"./types":116,randombytes:54,"tiny-secp256k1":65,typeforce:69,wif:72}],79:[function(t,e,r){const n=t("./script");e.exports={Block:t("./block"),ECPair:t("./ecpair"),Transaction:t("./transaction"),TransactionBuilder:t("./transaction_builder"),address:t("./address"),bip32:t("bip32"),crypto:t("./crypto"),networks:t("./networks"),opcodes:t("bitcoin-ops"),payments:t("./payments"),script:n}},{"./address":73,"./block":74,"./crypto":77,"./ecpair":78,"./networks":80,"./payments":82,"./script":90,"./transaction":114,"./transaction_builder":115,bip32:4,"bitcoin-ops":6}],80:[function(t,e,r){e.exports={bitcoin:{messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},testnet:{messagePrefix:"Bitcoin Signed Message:\n",bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239}}},{}],81:[function(t,e,r){const n=t("./lazy"),i=t("typeforce"),s=t("bitcoin-ops"),o=t("../script"),f=t("../networks").bitcoin;e.exports=function(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),i({network:i.maybe(i.Object),output:i.maybe(i.Buffer),data:i.maybe(i.arrayOf(i.Buffer))},t);const r={network:t.network||f};if(n.prop(r,"output",function(){if(t.data)return o.compile([s.OP_RETURN].concat(t.data))}),n.prop(r,"data",function(){if(t.output)return o.decompile(t.output).slice(1)}),e.validate&&t.output){const e=o.decompile(t.output);if(e[0]!==s.OP_RETURN)throw new TypeError("Output is invalid");if(!e.slice(1).every(i.Buffer))throw new TypeError("Output is invalid");if(t.data&&!function(t,e){return t.length===e.length&&t.every(function(t,r){return t.equals(e[r])})}(t.data,r.data))throw new TypeError("Data mismatch")}return Object.assign(r,t)}},{"../networks":80,"../script":90,"./lazy":83,"bitcoin-ops":6,typeforce:69}],82:[function(t,e,r){const n=t("./embed"),i=t("./p2ms"),s=t("./p2pk"),o=t("./p2pkh"),f=t("./p2sh"),a=t("./p2wpkh"),u=t("./p2wsh");e.exports={embed:n,p2ms:i,p2pk:s,p2pkh:o,p2sh:f,p2wpkh:a,p2wsh:u}},{"./embed":81,"./p2ms":84,"./p2pk":85,"./p2pkh":86,"./p2sh":87,"./p2wpkh":88,"./p2wsh":89}],83:[function(t,e,r){e.exports={prop:function(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get:function(){let t=r.call(this);return this[e]=t,t},set:function(t){Object.defineProperty(this,e,{configurable:!0,enumerable:!0,value:t,writable:!0})}})},value:function(t){let e;return function(){return void 0!==e?e:e=t()}}}},{}],84:[function(t,e,r){const n=t("./lazy"),i=t("typeforce"),s=t("bitcoin-ops"),o=t("tiny-secp256k1"),f=t("../script"),a=t("../networks").bitcoin,u=s.OP_RESERVED;function c(t,e){return t.length===e.length&&t.every(function(t,r){return t.equals(e[r])})}e.exports=function(t,e){if(!(t.input||t.output||t.pubkeys&&void 0!==t.m||t.signatures))throw new TypeError("Not enough data");function r(t){return f.isCanonicalScriptSignature(t)||e.allowIncomplete&&t===s.OP_0}e=Object.assign({validate:!0},e||{}),i({network:i.maybe(i.Object),m:i.maybe(i.Number),n:i.maybe(i.Number),output:i.maybe(i.Buffer),pubkeys:i.maybe(i.arrayOf(o.isPoint)),signatures:i.maybe(i.arrayOf(r)),input:i.maybe(i.Buffer)},t);const h={network:t.network||a};let d,p=!1;function l(t){p||(p=!0,d=f.decompile(t),h.m=d[0]-u,h.n=d[d.length-2]-u,h.pubkeys=d.slice(1,-2))}if(n.prop(h,"output",function(){if(t.m&&h.n&&t.pubkeys)return f.compile([].concat(u+t.m,t.pubkeys,u+h.n,s.OP_CHECKMULTISIG))}),n.prop(h,"m",function(){if(h.output)return l(h.output),h.m}),n.prop(h,"n",function(){if(h.pubkeys)return h.pubkeys.length}),n.prop(h,"pubkeys",function(){if(t.output)return l(t.output),h.pubkeys}),n.prop(h,"signatures",function(){if(t.input)return f.decompile(t.input).slice(1)}),n.prop(h,"input",function(){if(t.signatures)return f.compile([s.OP_0].concat(t.signatures))}),n.prop(h,"witness",function(){if(h.input)return[]}),e.validate){if(t.output){if(l(t.output),!i.Number(d[0]))throw new TypeError("Output is invalid");if(!i.Number(d[d.length-2]))throw new TypeError("Output is invalid");if(d[d.length-1]!==s.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(h.m<=0||h.n>16||h.m>h.n||h.n!==d.length-3)throw new TypeError("Output is invalid");if(!h.pubkeys.every(t=>o.isPoint(t)))throw new TypeError("Output is invalid");if(void 0!==t.m&&t.m!==h.m)throw new TypeError("m mismatch");if(void 0!==t.n&&t.n!==h.n)throw new TypeError("n mismatch");if(t.pubkeys&&!c(t.pubkeys,h.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(void 0!==t.n&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(h.n=t.pubkeys.length,h.nh.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==s.OP_0)throw new TypeError("Input is invalid");if(0===h.signatures.length||!h.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!c(t.signatures.equals(h.signatures)))throw new TypeError("Signature mismatch");if(void 0!==t.m&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(h,t)}},{"../networks":80,"../script":90,"./lazy":83,"bitcoin-ops":6,"tiny-secp256k1":65,typeforce:69}],85:[function(t,e,r){const n=t("./lazy"),i=t("typeforce"),s=t("bitcoin-ops"),o=t("tiny-secp256k1"),f=t("../script"),a=t("../networks").bitcoin;e.exports=function(t,e){if(!(t.input||t.output||t.pubkey||t.input||t.signature))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),i({network:i.maybe(i.Object),output:i.maybe(i.Buffer),pubkey:i.maybe(o.isPoint),signature:i.maybe(f.isCanonicalScriptSignature),input:i.maybe(i.Buffer)},t);const r=n.value(function(){return f.decompile(t.input)}),u={network:t.network||a};if(n.prop(u,"output",function(){if(t.pubkey)return f.compile([t.pubkey,s.OP_CHECKSIG])}),n.prop(u,"pubkey",function(){if(t.output)return t.output.slice(1,-1)}),n.prop(u,"signature",function(){if(t.input)return r()[0]}),n.prop(u,"input",function(){if(t.signature)return f.compile([t.signature])}),n.prop(u,"witness",function(){if(u.input)return[]}),e.validate){if(t.output){if(t.output[t.output.length-1]!==s.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!o.isPoint(u.pubkey))throw new TypeError("Output pubkey is invalid");if(t.pubkey&&!t.pubkey.equals(u.pubkey))throw new TypeError("Pubkey mismatch")}if(t.signature&&t.input&&!t.input.equals(u.input))throw new TypeError("Signature mismatch");if(t.input){if(1!==r().length)throw new TypeError("Input is invalid");if(!f.isCanonicalScriptSignature(u.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(u,t)}},{"../networks":80,"../script":90,"./lazy":83,"bitcoin-ops":6,"tiny-secp256k1":65,typeforce:69}],86:[function(t,e,r){(function(r){const n=t("./lazy"),i=t("typeforce"),s=t("bitcoin-ops"),o=t("tiny-secp256k1"),f=t("../crypto"),a=t("../script"),u=t("../networks").bitcoin,c=t("bs58check");e.exports=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),i({network:i.maybe(i.Object),address:i.maybe(i.String),hash:i.maybe(i.BufferN(20)),output:i.maybe(i.BufferN(25)),pubkey:i.maybe(o.isPoint),signature:i.maybe(a.isCanonicalScriptSignature),input:i.maybe(i.Buffer)},t);const h=n.value(function(){const e=c.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}}),d=n.value(function(){return a.decompile(t.input)}),p=t.network||u,l={network:p};if(n.prop(l,"address",function(){if(!l.hash)return;const t=r.allocUnsafe(21);return t.writeUInt8(p.pubKeyHash,0),l.hash.copy(t,1),c.encode(t)}),n.prop(l,"hash",function(){return t.output?t.output.slice(3,23):t.address?h().hash:t.pubkey||l.pubkey?f.hash160(t.pubkey||l.pubkey):void 0}),n.prop(l,"output",function(){if(l.hash)return a.compile([s.OP_DUP,s.OP_HASH160,l.hash,s.OP_EQUALVERIFY,s.OP_CHECKSIG])}),n.prop(l,"pubkey",function(){if(t.input)return d()[1]}),n.prop(l,"signature",function(){if(t.input)return d()[0]}),n.prop(l,"input",function(){if(t.pubkey&&t.signature)return a.compile([t.signature,t.pubkey])}),n.prop(l,"witness",function(){if(l.input)return[]}),e.validate){let e;if(t.address){if(h().version!==p.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(20!==h().hash.length)throw new TypeError("Invalid address");e=h().hash}if(t.hash){if(e&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(25!==t.output.length||t.output[0]!==s.OP_DUP||t.output[1]!==s.OP_HASH160||20!==t.output[2]||t.output[23]!==s.OP_EQUALVERIFY||t.output[24]!==s.OP_CHECKSIG)throw new TypeError("Output is invalid");const r=t.output.slice(3,23);if(e&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.pubkey){const r=f.hash160(t.pubkey);if(e&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.input){const r=d();if(2!==r.length)throw new TypeError("Input is invalid");if(!a.isCanonicalScriptSignature(r[0]))throw new TypeError("Input has invalid signature");if(!o.isPoint(r[1]))throw new TypeError("Input has invalid pubkey");if(t.signature&&!t.signature.equals(r[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(r[1]))throw new TypeError("Pubkey mismatch");const n=f.hash160(r[1]);if(e&&!e.equals(n))throw new TypeError("Hash mismatch")}}return Object.assign(l,t)}}).call(this,t("buffer").Buffer)},{"../crypto":77,"../networks":80,"../script":90,"./lazy":83,"bitcoin-ops":6,bs58check:12,buffer:119,"tiny-secp256k1":65,typeforce:69}],87:[function(t,e,r){(function(r){const n=t("./lazy"),i=t("typeforce"),s=t("bitcoin-ops"),o=t("../crypto"),f=t("../script"),a=t("../networks").bitcoin,u=t("bs58check");e.exports=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),i({network:i.maybe(i.Object),address:i.maybe(i.String),hash:i.maybe(i.BufferN(20)),output:i.maybe(i.BufferN(23)),redeem:i.maybe({network:i.maybe(i.Object),output:i.maybe(i.Buffer),input:i.maybe(i.Buffer),witness:i.maybe(i.arrayOf(i.Buffer))}),input:i.maybe(i.Buffer),witness:i.maybe(i.arrayOf(i.Buffer))},t);const c=t.network||a,h={network:c},d=n.value(function(){const e=u.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}}),p=n.value(function(){return f.decompile(t.input)}),l=n.value(function(){const e=p();return{network:c,output:e[e.length-1],input:f.compile(e.slice(0,-1)),witness:t.witness||[]}});if(n.prop(h,"address",function(){if(!h.hash)return;const t=r.allocUnsafe(21);return t.writeUInt8(c.scriptHash,0),h.hash.copy(t,1),u.encode(t)}),n.prop(h,"hash",function(){return t.output?t.output.slice(2,22):t.address?d().hash:h.redeem&&h.redeem.output?o.hash160(h.redeem.output):void 0}),n.prop(h,"output",function(){if(h.hash)return f.compile([s.OP_HASH160,h.hash,s.OP_EQUAL])}),n.prop(h,"redeem",function(){if(t.input)return l()}),n.prop(h,"input",function(){if(t.redeem&&t.redeem.input&&t.redeem.output)return f.compile([].concat(f.decompile(t.redeem.input),t.redeem.output))}),n.prop(h,"witness",function(){return h.redeem&&h.redeem.witness?h.redeem.witness:h.input?[]:void 0}),e.validate){let e;if(t.address){if(d().version!==c.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(20!==d().hash.length)throw new TypeError("Invalid address");e=d().hash}if(t.hash){if(e&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(23!==t.output.length||t.output[0]!==s.OP_HASH160||20!==t.output[1]||t.output[22]!==s.OP_EQUAL)throw new TypeError("Output is invalid");const r=t.output.slice(2,22);if(e&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}const n=function(t){if(t.output){const r=f.decompile(t.output);if(!r||r.length<1)throw new TypeError("Redeem.output too short");const n=o.hash160(t.output);if(e&&!e.equals(n))throw new TypeError("Hash mismatch");e=n}if(t.input){const e=t.input.length>0,r=t.witness&&t.witness.length>0;if(!e&&!r)throw new TypeError("Empty input");if(e&&r)throw new TypeError("Input and witness provided");if(e){const e=f.decompile(t.input);if(!f.isPushOnly(e))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const t=p();if(!t||t.length<1)throw new TypeError("Input too short");if(!r.isBuffer(l().output))throw new TypeError("Input is invalid");n(l())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==c)throw new TypeError("Network mismatch");if(t.input){const e=l();if(t.redeem.output&&!t.redeem.output.equals(e.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(e.input))throw new TypeError("Redeem.input mismatch")}n(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(function(t,r){return t.equals(e[r])})}(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(h,t)}}).call(this,t("buffer").Buffer)},{"../crypto":77,"../networks":80,"../script":90,"./lazy":83,"bitcoin-ops":6,bs58check:12,buffer:119,typeforce:69}],88:[function(t,e,r){(function(r){const n=t("./lazy"),i=t("typeforce"),s=t("bitcoin-ops"),o=t("tiny-secp256k1"),f=t("../crypto"),a=t("bech32"),u=t("../script"),c=t("../networks").bitcoin,h=r.alloc(0);e.exports=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),i({address:i.maybe(i.String),hash:i.maybe(i.BufferN(20)),input:i.maybe(i.BufferN(0)),network:i.maybe(i.Object),output:i.maybe(i.BufferN(22)),pubkey:i.maybe(o.isPoint),signature:i.maybe(u.isCanonicalScriptSignature),witness:i.maybe(i.arrayOf(i.Buffer))},t);const d=n.value(function(){const e=a.decode(t.address),n=e.words.shift(),i=a.fromWords(e.words);return{version:n,prefix:e.prefix,data:r.from(i)}}),p=t.network||c,l={network:p};if(n.prop(l,"address",function(){if(!l.hash)return;const t=a.toWords(l.hash);return t.unshift(0),a.encode(p.bech32,t)}),n.prop(l,"hash",function(){return t.output?t.output.slice(2,22):t.address?d().data:t.pubkey||l.pubkey?f.hash160(t.pubkey||l.pubkey):void 0}),n.prop(l,"output",function(){if(l.hash)return u.compile([s.OP_0,l.hash])}),n.prop(l,"pubkey",function(){return t.pubkey?t.pubkey:t.witness?t.witness[1]:void 0}),n.prop(l,"signature",function(){if(t.witness)return t.witness[0]}),n.prop(l,"input",function(){if(l.witness)return h}),n.prop(l,"witness",function(){if(t.pubkey&&t.signature)return[t.signature,t.pubkey]}),e.validate){let e;if(t.address){if(p&&p.bech32!==d().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(0!==d().version)throw new TypeError("Invalid address version");if(20!==d().data.length)throw new TypeError("Invalid address data");e=d().data}if(t.hash){if(e&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(22!==t.output.length||t.output[0]!==s.OP_0||20!==t.output[1])throw new TypeError("Output is invalid");if(e&&!e.equals(t.output.slice(2)))throw new TypeError("Hash mismatch");e=t.output.slice(2)}if(t.pubkey){const r=f.hash160(t.pubkey);if(e&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.witness){if(2!==t.witness.length)throw new TypeError("Witness is invalid");if(!u.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!o.isPoint(t.witness[1]))throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const r=f.hash160(t.witness[1]);if(e&&!e.equals(r))throw new TypeError("Hash mismatch")}}return Object.assign(l,t)}}).call(this,t("buffer").Buffer)},{"../crypto":77,"../networks":80,"../script":90,"./lazy":83,bech32:2,"bitcoin-ops":6,buffer:119,"tiny-secp256k1":65,typeforce:69}],89:[function(t,e,r){(function(r){const n=t("./lazy"),i=t("typeforce"),s=t("bitcoin-ops"),o=t("bech32"),f=t("../crypto"),a=t("../script"),u=t("../networks").bitcoin,c=r.alloc(0);e.exports=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),i({network:i.maybe(i.Object),address:i.maybe(i.String),hash:i.maybe(i.BufferN(32)),output:i.maybe(i.BufferN(34)),redeem:i.maybe({input:i.maybe(i.Buffer),network:i.maybe(i.Object),output:i.maybe(i.Buffer),witness:i.maybe(i.arrayOf(i.Buffer))}),input:i.maybe(i.BufferN(0)),witness:i.maybe(i.arrayOf(i.Buffer))},t);const h=n.value(function(){const e=o.decode(t.address),n=e.words.shift(),i=o.fromWords(e.words);return{version:n,prefix:e.prefix,data:r.from(i)}}),d=n.value(function(){return a.decompile(t.redeem.input)}),p=t.network||u,l={network:p};if(n.prop(l,"address",function(){if(!l.hash)return;const t=o.toWords(l.hash);return t.unshift(0),o.encode(p.bech32,t)}),n.prop(l,"hash",function(){return t.output?t.output.slice(2):t.address?h().data:l.redeem&&l.redeem.output?f.sha256(l.redeem.output):void 0}),n.prop(l,"output",function(){if(l.hash)return a.compile([s.OP_0,l.hash])}),n.prop(l,"redeem",function(){if(t.witness)return{output:t.witness[t.witness.length-1],input:c,witness:t.witness.slice(0,-1)}}),n.prop(l,"input",function(){if(l.witness)return c}),n.prop(l,"witness",function(){if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const e=a.toStack(d());return l.redeem=Object.assign({witness:e},t.redeem),l.redeem.input=c,[].concat(e,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)}),e.validate){let e;if(t.address){if(h().prefix!==p.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(0!==h().version)throw new TypeError("Invalid address version");if(32!==h().data.length)throw new TypeError("Invalid address data");e=h().data}if(t.hash){if(e&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(34!==t.output.length||t.output[0]!==s.OP_0||32!==t.output[1])throw new TypeError("Output is invalid");const r=t.output.slice(2);if(e&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem){if(t.redeem.network&&t.redeem.network!==p)throw new TypeError("Network mismatch");if(t.redeem.input&&t.redeem.input.length>0&&t.redeem.witness&&t.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(t.redeem.output){if(0===a.decompile(t.redeem.output).length)throw new TypeError("Redeem.output is invalid");const r=f.sha256(t.redeem.output);if(e&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem.input&&!a.isPushOnly(d()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(function(t,r){return t.equals(e[r])})}(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch")}if(t.witness&&t.redeem&&t.redeem.output&&!t.redeem.output.equals(t.witness[t.witness.length-1]))throw new TypeError("Witness and redeem.output mismatch")}return Object.assign(l,t)}}).call(this,t("buffer").Buffer)},{"../crypto":77,"../networks":80,"../script":90,"./lazy":83,bech32:2,"bitcoin-ops":6,buffer:119,typeforce:69}],90:[function(t,e,r){const n=t("safe-buffer").Buffer,i=t("bip66"),s=t("tiny-secp256k1"),o=t("pushdata-bitcoin"),f=t("typeforce"),a=t("./types"),u=t("./script_number"),c=t("bitcoin-ops"),h=t("bitcoin-ops/map"),d=c.OP_RESERVED;function p(t){return a.Buffer(t)||function(t){return a.Number(t)&&(t===c.OP_0||t>=c.OP_1&&t<=c.OP_16||t===c.OP_1NEGATE)}(t)}function l(t){return a.Array(t)&&t.every(p)}function b(t){return 0===t.length?c.OP_0:1===t.length?t[0]>=1&&t[0]<=16?d+t[0]:129===t[0]?c.OP_1NEGATE:void 0:void 0}function m(t){if(n.isBuffer(t))return t;f(a.Array,t);const e=t.reduce(function(t,e){return n.isBuffer(e)?1===e.length&&void 0!==b(e)?t+1:t+o.encodingLength(e.length)+e.length:t+1},0),r=n.allocUnsafe(e);let i=0;if(t.forEach(function(t){if(n.isBuffer(t)){const e=b(t);if(void 0!==e)return r.writeUInt8(e,i),void(i+=1);i+=o.encode(r,t.length,i),t.copy(r,i),i+=t.length}else r.writeUInt8(t,i),i+=1}),i!==r.length)throw new Error("Could not decode chunks");return r}function y(t){if(a.Array(t))return t;f(a.Buffer,t);const e=[];let r=0;for(;rc.OP_0&&n<=c.OP_PUSHDATA4){const n=o.decode(t,r);if(null===n)return null;if((r+=n.size)+n.number>t.length)return null;const i=t.slice(r,r+n.number);r+=n.number;const s=b(i);void 0!==s?e.push(s):e.push(i)}else e.push(n),r+=1}return e}function g(t){const e=-129&t;return e>0&&e<4}e.exports={compile:m,decompile:y,fromASM:function(t){return f(a.String,t),m(t.split(" ").map(function(t){return void 0!==c[t]?c[t]:(f(a.Hex,t),n.from(t,"hex"))}))},toASM:function(t){return n.isBuffer(t)&&(t=y(t)),t.map(function(t){if(n.isBuffer(t)){const e=b(t);if(void 0===e)return t.toString("hex");t=e}return h[t]}).join(" ")},toStack:function(t){return t=y(t),f(l,t),t.map(function(t){return n.isBuffer(t)?t:t===c.OP_0?n.allocUnsafe(0):u.encode(t-d)})},number:t("./script_number"),signature:t("./script_signature"),isCanonicalPubKey:function(t){return s.isPoint(t)},isCanonicalScriptSignature:function(t){return!!n.isBuffer(t)&&!!g(t[t.length-1])&&i.check(t.slice(0,-1))},isPushOnly:l,isDefinedHashType:g}},{"./script_number":91,"./script_signature":92,"./types":116,bip66:5,"bitcoin-ops":6,"bitcoin-ops/map":7,"pushdata-bitcoin":53,"safe-buffer":56,"tiny-secp256k1":65,typeforce:69}],91:[function(t,e,r){const n=t("safe-buffer").Buffer;e.exports={decode:function(t,e,r){e=e||4,r=void 0===r||r;const n=t.length;if(0===n)return 0;if(n>e)throw new TypeError("Script number overflow");if(r&&0==(127&t[n-1])&&(n<=1||0==(128&t[n-2])))throw new Error("Non-minimally encoded script number");if(5===n){const e=t.readUInt32LE(0),r=t.readUInt8(4);return 128&r?-(4294967296*(-129&r)+e):4294967296*r+e}let i=0;for(var s=0;s2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}(e),i=n.allocUnsafe(r),s=t<0;for(var o=0;o>=8;return 128&i[r-1]?i.writeUInt8(s?128:0,r-1):s&&(i[r-1]|=128),i}}},{"safe-buffer":56}],92:[function(t,e,r){const n=t("bip66"),i=t("safe-buffer").Buffer,s=t("typeforce"),o=t("./types"),f=i.alloc(1,0);function a(t){let e=0;for(;0===t[e];)++e;return e===t.length?f:128&(t=t.slice(e))[0]?i.concat([f,t],1+t.length):t}function u(t){0===t[0]&&(t=t.slice(1));const e=i.alloc(32,0),r=Math.max(0,32-t.length);return t.copy(e,r),e}e.exports={decode:function(t){const e=t.readUInt8(t.length-1),r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const s=n.decode(t.slice(0,-1)),o=u(s.r),f=u(s.s);return{signature:i.concat([o,f],64),hashType:e}},encode:function(t,e){s({signature:o.BufferN(64),hashType:o.UInt8},{signature:t,hashType:e});const r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const f=i.allocUnsafe(1);f.writeUInt8(e,0);const u=a(t.slice(0,32)),c=a(t.slice(32,64));return i.concat([n.encode(u,c),f])}}},{"./types":116,bip66:5,"safe-buffer":56,typeforce:69}],93:[function(t,e,r){e.exports={input:t("./input"),output:t("./output")}},{"./input":94,"./output":95}],94:[function(t,e,r){const n=t("../../script"),i=t("bitcoin-ops");function s(t){return t===i.OP_0||n.isCanonicalScriptSignature(t)}function o(t,e){const r=n.decompile(t);return!(r.length<2)&&(r[0]===i.OP_0&&(e?r.slice(1).every(s):r.slice(1).every(n.isCanonicalScriptSignature)))}o.toJSON=function(){return"multisig input"},e.exports={check:o}},{"../../script":90,"bitcoin-ops":6}],95:[function(t,e,r){const n=t("../../script"),i=t("../../types"),s=t("bitcoin-ops"),o=s.OP_RESERVED;function f(t,e){const r=n.decompile(t);if(r.length<4)return!1;if(r[r.length-1]!==s.OP_CHECKMULTISIG)return!1;if(!i.Number(r[0]))return!1;if(!i.Number(r[r.length-2]))return!1;const f=r[0]-o,a=r[r.length-2]-o;return!(f<=0)&&(!(a>16)&&(!(f>a)&&(a===r.length-3&&(!!e||r.slice(1,-2).every(n.isCanonicalPubKey)))))}f.toJSON=function(){return"multi-sig output"},e.exports={check:f}},{"../../script":90,"../../types":116,"bitcoin-ops":6}],96:[function(t,e,r){const n=t("../script"),i=t("bitcoin-ops");function s(t){const e=n.compile(t);return e.length>1&&e[0]===i.OP_RETURN}s.toJSON=function(){return"null data output"},e.exports={output:{check:s}}},{"../script":90,"bitcoin-ops":6}],97:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{"./input":98,"./output":99,dup:93}],98:[function(t,e,r){const n=t("../../script");function i(t){const e=n.decompile(t);return 1===e.length&&n.isCanonicalScriptSignature(e[0])}i.toJSON=function(){return"pubKey input"},e.exports={check:i}},{"../../script":90}],99:[function(t,e,r){const n=t("../../script"),i=t("bitcoin-ops");function s(t){const e=n.decompile(t);return 2===e.length&&n.isCanonicalPubKey(e[0])&&e[1]===i.OP_CHECKSIG}s.toJSON=function(){return"pubKey output"},e.exports={check:s}},{"../../script":90,"bitcoin-ops":6}],100:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{"./input":101,"./output":102,dup:93}],101:[function(t,e,r){const n=t("../../script");function i(t){const e=n.decompile(t);return 2===e.length&&n.isCanonicalScriptSignature(e[0])&&n.isCanonicalPubKey(e[1])}i.toJSON=function(){return"pubKeyHash input"},e.exports={check:i}},{"../../script":90}],102:[function(t,e,r){const n=t("../../script"),i=t("bitcoin-ops");function s(t){const e=n.compile(t);return 25===e.length&&e[0]===i.OP_DUP&&e[1]===i.OP_HASH160&&20===e[2]&&e[23]===i.OP_EQUALVERIFY&&e[24]===i.OP_CHECKSIG}s.toJSON=function(){return"pubKeyHash output"},e.exports={check:s}},{"../../script":90,"bitcoin-ops":6}],103:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{"./input":104,"./output":105,dup:93}],104:[function(t,e,r){const n=t("safe-buffer").Buffer,i=t("../../script"),s=t("../multisig/"),o=t("../pubkey/"),f=t("../pubkeyhash/"),a=t("../witnesspubkeyhash/output"),u=t("../witnessscripthash/output");function c(t,e){const r=i.decompile(t);if(r.length<1)return!1;const c=r[r.length-1];if(!n.isBuffer(c))return!1;const h=i.decompile(i.compile(r.slice(0,-1))),d=i.decompile(c);return!!d&&(!!i.isPushOnly(h)&&(1===r.length?u.check(d)||a.check(d):!(!f.input.check(h)||!f.output.check(d))||(!(!s.input.check(h,e)||!s.output.check(d))||!(!o.input.check(h)||!o.output.check(d)))))}c.toJSON=function(){return"scriptHash input"},e.exports={check:c}},{"../../script":90,"../multisig/":93,"../pubkey/":97,"../pubkeyhash/":100,"../witnesspubkeyhash/output":110,"../witnessscripthash/output":113,"safe-buffer":56}],105:[function(t,e,r){const n=t("../../script"),i=t("bitcoin-ops");function s(t){const e=n.compile(t);return 23===e.length&&e[0]===i.OP_HASH160&&20===e[1]&&e[22]===i.OP_EQUAL}s.toJSON=function(){return"scriptHash output"},e.exports={check:s}},{"../../script":90,"bitcoin-ops":6}],106:[function(t,e,r){e.exports={output:t("./output")}},{"./output":107}],107:[function(t,e,r){const n=t("safe-buffer").Buffer,i=t("../../script"),s=t("../../types"),o=t("typeforce"),f=t("bitcoin-ops"),a=n.from("aa21a9ed","hex");function u(t){const e=i.compile(t);return e.length>37&&e[0]===f.OP_RETURN&&36===e[1]&&e.slice(2,6).equals(a)}u.toJSON=function(){return"Witness commitment output"},e.exports={check:u,decode:function(t){return o(u,t),i.decompile(t)[1].slice(4,36)},encode:function(t){o(s.Hash256bit,t);const e=n.allocUnsafe(36);return a.copy(e,0),t.copy(e,4),i.compile([f.OP_RETURN,e])}}},{"../../script":90,"../../types":116,"bitcoin-ops":6,"safe-buffer":56,typeforce:69}],108:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{"./input":109,"./output":110,dup:93}],109:[function(t,e,r){const n=t("../../script");function i(t){const e=n.decompile(t);return 2===e.length&&n.isCanonicalScriptSignature(e[0])&&(r=e[1],n.isCanonicalPubKey(r)&&33===r.length);var r}i.toJSON=function(){return"witnessPubKeyHash input"},e.exports={check:i}},{"../../script":90}],110:[function(t,e,r){const n=t("../../script"),i=t("bitcoin-ops");function s(t){const e=n.compile(t);return 22===e.length&&e[0]===i.OP_0&&20===e[1]}s.toJSON=function(){return"Witness pubKeyHash output"},e.exports={check:s}},{"../../script":90,"bitcoin-ops":6}],111:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{"./input":112,"./output":113,dup:93}],112:[function(t,e,r){(function(r){const n=t("../../script"),i=t("../../types"),s=t("typeforce"),o=t("../multisig/"),f=t("../pubkey/"),a=t("../pubkeyhash/");function u(t,e){if(s(i.Array,t),t.length<1)return!1;const u=t[t.length-1];if(!r.isBuffer(u))return!1;const c=n.decompile(u);if(!c||0===c.length)return!1;const h=n.compile(t.slice(0,-1));return!(!a.input.check(h)||!a.output.check(c))||(!(!o.input.check(h,e)||!o.output.check(c))||!(!f.input.check(h)||!f.output.check(c)))}u.toJSON=function(){return"witnessScriptHash input"},e.exports={check:u}}).call(this,{isBuffer:t("../../../../../../../usr/lib/node_modules/browserify/node_modules/is-buffer/index.js")})},{"../../../../../../../usr/lib/node_modules/browserify/node_modules/is-buffer/index.js":124,"../../script":90,"../../types":116,"../multisig/":93,"../pubkey/":97,"../pubkeyhash/":100,typeforce:69}],113:[function(t,e,r){const n=t("../../script"),i=t("bitcoin-ops");function s(t){const e=n.compile(t);return 34===e.length&&e[0]===i.OP_0&&32===e[1]}s.toJSON=function(){return"Witness scriptHash output"},e.exports={check:s}},{"../../script":90,"bitcoin-ops":6}],114:[function(t,e,r){const n=t("safe-buffer").Buffer,i=t("./crypto"),s=t("./script"),o=t("./bufferutils"),f=t("bitcoin-ops"),a=t("typeforce"),u=t("./types"),c=t("varuint-bitcoin");function h(t){const e=t.length;return c.encodingLength(e)+e}function d(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}d.DEFAULT_SEQUENCE=4294967295,d.SIGHASH_ALL=1,d.SIGHASH_NONE=2,d.SIGHASH_SINGLE=3,d.SIGHASH_ANYONECANPAY=128,d.ADVANCED_TRANSACTION_MARKER=0,d.ADVANCED_TRANSACTION_FLAG=1;const p=n.allocUnsafe(0),l=[],b=n.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),m=n.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),y=n.from("ffffffffffffffff","hex"),g={script:p,valueBuffer:y};d.fromBuffer=function(t,e){let r=0;function n(e){return r+=e,t.slice(r-e,r)}function i(){const e=t.readUInt32LE(r);return r+=4,e}function s(){const e=o.readUInt64LE(t,r);return r+=8,e}function f(){const e=c.decode(t,r);return r+=c.decode.bytes,e}function a(){return n(f())}function u(){const t=f(),e=[];for(var r=0;r=this.ins.length)return m;const o=s.compile(s.decompile(e).filter(function(t){return t!==f.OP_CODESEPARATOR})),c=this.clone();if((31&r)===d.SIGHASH_NONE)c.outs=[],c.ins.forEach(function(e,r){r!==t&&(e.sequence=0)});else if((31&r)===d.SIGHASH_SINGLE){if(t>=this.outs.length)return m;c.outs.length=t+1;for(var h=0;hvoid 0)}}}return{type:r}}function m(t,e){this.__prevTxSet={},this.network=t||f.bitcoin,this.maximumFeeRate=e||2500,this.__inputs=[],this.__tx=new l,this.__tx.version=2}function y(t){return void 0!==t.signScript&&void 0!==t.signType&&void 0!==t.pubkeys&&void 0!==t.signatures&&t.signatures.length===t.pubkeys.length&&t.pubkeys.length>0&&(!1===t.hasWitness||void 0!==t.value)}function g(t){return t.readUInt8(t.length-1)}m.prototype.setLockTime=function(t){if(c(h.UInt32,t),this.__inputs.some(function(t){return!!t.signatures&&t.signatures.some(function(t){return t})}))throw new Error("No, this would invalidate signatures");this.__tx.locktime=t},m.prototype.setVersion=function(t){c(h.UInt32,t),this.__tx.version=t},m.fromTransaction=function(t,e){const r=new m(e);return r.setVersion(t.version),r.setLockTime(t.locktime),t.outs.forEach(function(t){r.addOutput(t.script,t.value)}),t.ins.forEach(function(t){r.__addInputUnsafe(t.hash,t.index,{sequence:t.sequence,script:t.script,witness:t.witness})}),r.__inputs.forEach(function(e,r){!function(t,e,r){if(t.redeemScriptType!==p.MULTISIG||!t.redeemScript)return;if(t.pubkeys.length===t.signatures.length)return;const n=t.signatures.concat();t.signatures=t.pubkeys.map(function(i){const s=ECPair.fromPublicKey(i);let f;return n.some(function(i,a){if(!i)return!1;const u=o.signature.decode(i),c=e.hashForSignature(r,t.redeemScript,u.hashType);return!!s.verify(c,u.signature)&&(n[a]=void 0,f=i,!0)}),f})}(e,t,r)}),r},m.prototype.addInput=function(t,e,r,i){if(!this.__canModifyInputs())throw new Error("No, this would invalidate signatures");let s;if("string"==typeof t)t=n.from(t,"hex").reverse();else if(t instanceof l){const r=t.outs[e];i=r.script,s=r.value,t=t.getHash()}return this.__addInputUnsafe(t,e,{sequence:r,prevOutScript:i,value:s})},m.prototype.__addInputUnsafe=function(t,e,r){if(l.isCoinbaseHash(t))throw new Error("coinbase inputs not supported");const n=t.toString("hex")+":"+e;if(void 0!==this.__prevTxSet[n])throw new Error("Duplicate TxOut: "+n);let i={};if(void 0!==r.script&&(i=function t(e,r,n,i){if(0===e.length&&0===r.length)return{};if(!n){let t=d.input(e,!0),i=d.witness(r,!0);t===p.NONSTANDARD&&(t=void 0),i===p.NONSTANDARD&&(i=void 0),n=t||i}switch(n){case p.P2WPKH:{const{output:t,pubkey:e,signature:n}=u.p2wpkh({witness:r});return{prevOutScript:t,prevOutType:p.P2WPKH,pubkeys:[e],signatures:[n]}}case p.P2PKH:{const{output:t,pubkey:r,signature:n}=u.p2pkh({input:e});return{prevOutScript:t,prevOutType:p.P2PKH,pubkeys:[r],signatures:[n]}}case p.P2PK:{const{signature:t}=u.p2pk({input:e});return{prevOutType:p.P2PK,pubkeys:[void 0],signatures:[t]}}case p.MULTISIG:{const{pubkeys:t,signatures:r}=u.p2ms({input:e,output:i},{allowIncomplete:!0});return{prevOutType:p.MULTISIG,pubkeys:t,signatures:r}}}if(n===p.P2SH){const{output:n,redeem:i}=u.p2sh({input:e,witness:r}),s=d.output(i.output),o=t(i.input,i.witness,s,i.output);return o.prevOutType?{prevOutScript:n,prevOutType:p.P2SH,redeemScript:i.output,redeemScriptType:o.prevOutType,witnessScript:o.witnessScript,witnessScriptType:o.witnessScriptType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}if(n===p.P2WSH){const{output:n,redeem:i}=u.p2wsh({input:e,witness:r}),s=d.output(i.output);let f;return(f=s===p.P2WPKH?t(i.input,i.witness,s):t(o.compile(i.witness),[],s,i.output)).prevOutType?{prevOutScript:n,prevOutType:p.P2WSH,witnessScript:i.output,witnessScriptType:f.prevOutType,pubkeys:f.pubkeys,signatures:f.signatures}:{}}return{prevOutType:p.NONSTANDARD,prevOutScript:e}}(r.script,r.witness||[])),void 0!==r.value&&(i.value=r.value),!i.prevOutScript&&r.prevOutScript){let t;if(!i.pubkeys&&!i.signatures){const e=b(r.prevOutScript);e.pubkeys&&(i.pubkeys=e.pubkeys,i.signatures=e.signatures),t=e.type}i.prevOutScript=r.prevOutScript,i.prevOutType=t||d.output(r.prevOutScript)}const s=this.__tx.addInput(t,e,r.sequence,r.scriptSig);return this.__inputs[s]=i,this.__prevTxSet[n]=!0,s},m.prototype.addOutput=function(t,e){if(!this.__canModifyOutputs())throw new Error("No, this would invalidate signatures");return"string"==typeof t&&(t=i.toOutputScript(t,this.network)),this.__tx.addOutput(t,e)},m.prototype.build=function(){return this.__build(!1)},m.prototype.buildIncomplete=function(){return this.__build(!0)},m.prototype.__build=function(t){if(!t){if(!this.__tx.ins.length)throw new Error("Transaction has no inputs");if(!this.__tx.outs.length)throw new Error("Transaction has no outputs")}const e=this.__tx.clone();if(this.__inputs.forEach(function(r,n){if(!r.prevOutType&&!t)throw new Error("Transaction is not complete");const i=function t(e,r,n){const i=r.pubkeys||[];let s=r.signatures||[];switch(e){case p.P2PKH:if(0===i.length)break;if(0===s.length)break;return u.p2pkh({pubkey:i[0],signature:s[0]});case p.P2WPKH:if(0===i.length)break;if(0===s.length)break;return u.p2wpkh({pubkey:i[0],signature:s[0]});case p.P2PK:if(0===i.length)break;if(0===s.length)break;return u.p2pk({signature:s[0]});case p.MULTISIG:return s=n?s.map(t=>t||a.OP_0):s.filter(t=>t),u.p2ms({signatures:s},{allowIncomplete:n});case p.P2SH:{const e=t(r.redeemScriptType,r,n);if(!e)return;return u.p2sh({redeem:{output:e.output||r.redeemScript,input:e.input,witness:e.witness}})}case p.P2WSH:{const e=t(r.witnessScriptType,r,n);if(!e)return;return u.p2wsh({redeem:{output:r.witnessScript,input:e.input,witness:e.witness}})}}}(r.prevOutType,r,t);if(i)e.setInputScript(n,i.input),e.setWitness(n,i.witness);else{if(!t&&r.prevOutType===p.NONSTANDARD)throw new Error("Unknown input type");if(!t)throw new Error("Not enough information")}}),!t&&this.__overMaximumFees(e.virtualSize()))throw new Error("Transaction has absurd fees");return e},m.prototype.sign=function(t,e,r,n,i,s){if(e.network&&e.network!==this.network)throw new TypeError("Inconsistent network");if(!this.__inputs[t])throw new Error("No input at index: "+t);n=n||l.SIGHASH_ALL;const f=this.__inputs[t];if(void 0!==f.redeemScript&&r&&!f.redeemScript.equals(r))throw new Error("Inconsistent redeemScript");const a=e.publicKey||e.getPublicKey();if(!y(f)){if(void 0!==i){if(void 0!==f.value&&f.value!==i)throw new Error("Input didn't match witnessValue");c(h.Satoshi,i),f.value=i}if(!y(f)){const t=function(t,e,r,n,i){if(r&&i){const n=u.p2wsh({redeem:{output:i}}),s=u.p2wsh({output:r}),f=u.p2sh({redeem:{output:r}}),a=u.p2sh({redeem:n});if(!n.hash.equals(s.hash))throw new Error("Witness script inconsistent with prevOutScript");if(!f.hash.equals(a.hash))throw new Error("Redeem script inconsistent with prevOutScript");const c=b(n.redeem.output,e);if(!c.pubkeys)throw new Error(c.type+" not supported as witnessScript ("+o.toASM(i)+")");t.signatures&&t.signatures.some(t=>t)&&(c.signatures=t.signatures);let h=i;if(c.type===p.P2WPKH)throw new Error("P2SH(P2WSH(P2WPKH)) is a consensus failure");return{redeemScript:r,redeemScriptType:p.P2WSH,witnessScript:i,witnessScriptType:c.type,prevOutType:p.P2SH,prevOutScript:f.output,hasWitness:!0,signScript:h,signType:c.type,pubkeys:c.pubkeys,signatures:c.signatures}}if(r){const n=u.p2sh({redeem:{output:r}});if(t.prevOutScript){let e;try{e=u.p2sh({output:t.prevOutScript})}catch(t){throw new Error("PrevOutScript must be P2SH")}if(!n.hash.equals(e.hash))throw new Error("Redeem script inconsistent with prevOutScript")}const i=b(n.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as redeemScript ("+o.toASM(r)+")");t.signatures&&t.signatures.some(t=>t)&&(i.signatures=t.signatures);let s=r;return i.type===p.P2WPKH&&(s=u.p2pkh({pubkey:i.pubkeys[0]}).output),{redeemScript:r,redeemScriptType:i.type,prevOutType:p.P2SH,prevOutScript:n.output,hasWitness:i.type===p.P2WPKH,signScript:s,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures}}if(i){const r=u.p2wsh({redeem:{output:i}});if(t.prevOutScript){const e=u.p2wsh({output:t.prevOutScript});if(!r.hash.equals(e.hash))throw new Error("Witness script inconsistent with prevOutScript")}const n=b(r.redeem.output,e);if(!n.pubkeys)throw new Error(n.type+" not supported as witnessScript ("+o.toASM(i)+")");t.signatures&&t.signatures.some(t=>t)&&(n.signatures=t.signatures);let s=i;if(n.type===p.P2WPKH)throw new Error("P2WSH(P2WPKH) is a consensus failure");return{witnessScript:i,witnessScriptType:n.type,prevOutType:p.P2WSH,prevOutScript:r.output,hasWitness:!0,signScript:s,signType:n.type,pubkeys:n.pubkeys,signatures:n.signatures}}if(t.prevOutType&&t.prevOutScript){if(t.prevOutType===p.P2SH)throw new Error("PrevOutScript is "+t.prevOutType+", requires redeemScript");if(t.prevOutType===p.P2WSH)throw new Error("PrevOutScript is "+t.prevOutType+", requires witnessScript");if(!t.prevOutScript)throw new Error("PrevOutScript is missing");const r=b(t.prevOutScript,e);if(!r.pubkeys)throw new Error(r.type+" not supported ("+o.toASM(t.prevOutScript)+")");t.signatures&&t.signatures.some(t=>t)&&(r.signatures=t.signatures);let n=t.prevOutScript;return r.type===p.P2WPKH&&(n=u.p2pkh({pubkey:r.pubkeys[0]}).output),{prevOutType:r.type,prevOutScript:t.prevOutScript,hasWitness:r.type===p.P2WPKH,signScript:n,signType:r.type,pubkeys:r.pubkeys,signatures:r.signatures}}const s=u.p2pkh({pubkey:e}).output;return{prevOutType:p.P2PKH,prevOutScript:s,hasWitness:!1,signScript:s,signType:p.P2PKH,pubkeys:[e],signatures:[void 0]}}(f,a,r,0,s);Object.assign(f,t)}if(!y(f))throw Error(f.prevOutType+" not supported")}let d;if(d=f.hasWitness?this.__tx.hashForWitnessV0(t,f.signScript,f.value,n):this.__tx.hashForSignature(t,f.signScript,n),!f.pubkeys.some(function(t,r){if(!a.equals(t))return!1;if(f.signatures[r])throw new Error("Signature already exists");if(33!==a.length&&f.hasWitness)throw new Error("BIP143 rejects uncompressed public keys in P2WPKH or P2WSH");const i=e.sign(d);return f.signatures[r]=o.signature.encode(i,n),!0}))throw new Error("Key pair cannot sign for this input")},m.prototype.__canModifyInputs=function(){return this.__inputs.every(function(t){return void 0===t.signatures||t.signatures.every(function(t){if(!t)return!0;return g(t)&l.SIGHASH_ANYONECANPAY})})},m.prototype.__canModifyOutputs=function(){const t=this.__tx.ins.length,e=this.__tx.outs.length;return this.__inputs.every(function(r){return void 0===r.signatures||r.signatures.every(function(r){if(!r)return!0;const n=31&g(r);return n===l.SIGHASH_NONE||(n===l.SIGHASH_SINGLE?t<=e:void 0)})})},m.prototype.__overMaximumFees=function(t){return(this.__inputs.reduce(function(t,e){return t+(e.value>>>0)},0)-this.__tx.outs.reduce(function(t,e){return t+e.value},0))/t>this.maximumFeeRate},e.exports=m},{"./address":73,"./classify":76,"./crypto":77,"./ecpair":78,"./networks":80,"./payments":82,"./script":90,"./transaction":114,"./types":116,"bitcoin-ops":6,"safe-buffer":56,typeforce:69}],116:[function(t,e,r){const n=t("typeforce"),i=Math.pow(2,31)-1;function s(t){return n.String(t)&&t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}s.toJSON=function(){return"BIP32 derivation path"};const o=21e14;const f=n.quacksLike("Point"),a=n.compile({messagePrefix:n.oneOf(n.Buffer,n.String),bip32:{public:n.UInt32,private:n.UInt32},pubKeyHash:n.UInt8,scriptHash:n.UInt8,wif:n.UInt8}),u={BIP32Path:s,Buffer256bit:n.BufferN(32),ECPoint:f,Hash160bit:n.BufferN(20),Hash256bit:n.BufferN(32),Network:a,Satoshi:function(t){return n.UInt53(t)&&t<=o},UInt31:function(t){return n.UInt32(t)&&t<=i}};for(var c in n)u[c]=n[c];e.exports=u},{typeforce:69}],117:[function(t,e,r){"use strict";r.byteLength=function(t){var e=u(t),r=e[0],n=e[1];return 3*(r+n)/4-n},r.toByteArray=function(t){var e,r,n=u(t),o=n[0],f=n[1],a=new s(function(t,e,r){return 3*(e+r)/4-r}(0,o,f)),c=0,h=f>0?o-4:o;for(r=0;r>16&255,a[c++]=e>>8&255,a[c++]=255&e;2===f&&(e=i[t.charCodeAt(r)]<<2|i[t.charCodeAt(r+1)]>>4,a[c++]=255&e);1===f&&(e=i[t.charCodeAt(r)]<<10|i[t.charCodeAt(r+1)]<<4|i[t.charCodeAt(r+2)]>>2,a[c++]=e>>8&255,a[c++]=255&e);return a},r.fromByteArray=function(t){for(var e,r=t.length,i=r%3,s=[],o=0,f=r-i;of?f:o+16383));1===i?(e=t[r-1],s.push(n[e>>2]+n[e<<4&63]+"==")):2===i&&(e=(t[r-2]<<8)+t[r-1],s.push(n[e>>10]+n[e>>4&63]+n[e<<2&63]+"="));return s.join("")};for(var n=[],i=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",f=0,a=o.length;f0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function c(t,e,r){for(var i,s,o=[],f=e;f>18&63]+n[s>>12&63]+n[s>>6&63]+n[63&s]);return o.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],118:[function(t,e,r){},{}],119:[function(t,e,r){(function(e){"use strict";var n=t("base64-js"),i=t("ieee754"),s="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;r.Buffer=e,r.SlowBuffer=function(t){+t!=t&&(t=0);return e.alloc(+t)},r.INSPECT_MAX_BYTES=50;var o=2147483647;function f(t){if(t>o)throw new RangeError('The value "'+t+'" is invalid for option "size"');var r=new Uint8Array(t);return Object.setPrototypeOf(r,e.prototype),r}function e(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return c(t)}return a(t,e,r)}function a(t,r,n){if("string"==typeof t)return function(t,r){"string"==typeof r&&""!==r||(r="utf8");if(!e.isEncoding(r))throw new TypeError("Unknown encoding: "+r);var n=0|p(t,r),i=f(n),s=i.write(t,r);s!==n&&(i=i.slice(0,s));return i}(t,r);if(ArrayBuffer.isView(t))return h(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(H(t,ArrayBuffer)||t&&H(t.buffer,ArrayBuffer))return function(t,r,n){if(r<0||t.byteLength=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|t}function p(t,r){if(e.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||H(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var n=t.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===n)return 0;for(var s=!1;;)switch(r){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return U(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return j(t).length;default:if(s)return i?-1:U(t).length;r=(""+r).toLowerCase(),s=!0}}function l(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function b(t,r,n,i,s){if(0===t.length)return-1;if("string"==typeof n?(i=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),q(n=+n)&&(n=s?0:t.length-1),n<0&&(n=t.length+n),n>=t.length){if(s)return-1;n=t.length-1}else if(n<0){if(!s)return-1;n=0}if("string"==typeof r&&(r=e.from(r,i)),e.isBuffer(r))return 0===r.length?-1:m(t,r,n,i,s);if("number"==typeof r)return r&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(t,r,n):Uint8Array.prototype.lastIndexOf.call(t,r,n):m(t,[r],n,i,s);throw new TypeError("val must be string, number or Buffer")}function m(t,e,r,n,i){var s,o=1,f=t.length,a=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;o=2,f/=2,a/=2,r/=2}function u(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(i){var c=-1;for(s=r;sf&&(r=f-a),s=r;s>=0;s--){for(var h=!0,d=0;di&&(n=i):n=i;var s=e.length;n>s/2&&(n=s/2);for(var o=0;o>8,i=r%256,s.push(i),s.push(n);return s}(e,t.length-r),t,r,n)}function E(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function M(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:u>223?3:u>191?2:1;if(i+h<=r)switch(h){case 1:u<128&&(c=u);break;case 2:128==(192&(s=t[i+1]))&&(a=(31&u)<<6|63&s)>127&&(c=a);break;case 3:s=t[i+1],o=t[i+2],128==(192&s)&&128==(192&o)&&(a=(15&u)<<12|(63&s)<<6|63&o)>2047&&(a<55296||a>57343)&&(c=a);break;case 4:s=t[i+1],o=t[i+2],f=t[i+3],128==(192&s)&&128==(192&o)&&128==(192&f)&&(a=(15&u)<<18|(63&s)<<12|(63&o)<<6|63&f)>65535&&a<1114112&&(c=a)}null===c?(c=65533,h=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),i+=h}return function(t){var e=t.length;if(e<=k)return String.fromCharCode.apply(String,t);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return I(this,e,r);case"utf8":case"utf-8":return M(this,e,r);case"ascii":return A(this,e,r);case"latin1":case"binary":return x(this,e,r);case"base64":return E(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return O(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},e.prototype.toLocaleString=e.prototype.toString,e.prototype.equals=function(t){if(!e.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===e.compare(this,t)},e.prototype.inspect=function(){var t="",e=r.INSPECT_MAX_BYTES;return t=this.toString("hex",0,e).replace(/(.{2})/g,"$1 ").trim(),this.length>e&&(t+=" ... "),""},s&&(e.prototype[s]=e.prototype.inspect),e.prototype.compare=function(t,r,n,i,s){if(H(t,Uint8Array)&&(t=e.from(t,t.offset,t.byteLength)),!e.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===r&&(r=0),void 0===n&&(n=t?t.length:0),void 0===i&&(i=0),void 0===s&&(s=this.length),r<0||n>t.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,s>>>=0,this===t)return 0;for(var o=s-i,f=n-r,a=Math.min(o,f),u=this.slice(i,s),c=t.slice(r,n),h=0;h>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var s=!1;;)switch(n){case"hex":return y(this,t,e,r);case"utf8":case"utf-8":return g(this,t,e,r);case"ascii":return v(this,t,e,r);case"latin1":case"binary":return w(this,t,e,r);case"base64":return _(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,t,e,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var k=4096;function A(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",s=e;sr)throw new RangeError("Trying to access beyond buffer length")}function T(t,r,n,i,s,o){if(!e.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(r>s||rt.length)throw new RangeError("Index out of range")}function B(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function N(t,e,r,n,s){return e=+e,r>>>=0,s||B(t,0,r,4),i.write(t,e,r,n,23,4),r+4}function R(t,e,r,n,s){return e=+e,r>>>=0,s||B(t,0,r,8),i.write(t,e,r,n,52,8),r+8}e.prototype.slice=function(t,r){var n=this.length;t=~~t,r=void 0===r?n:~~r,t<0?(t+=n)<0&&(t=0):t>n&&(t=n),r<0?(r+=n)<0&&(r=0):r>n&&(r=n),r>>=0,e>>>=0,r||P(t,e,this.length);for(var n=this[t],i=1,s=0;++s>>=0,e>>>=0,r||P(t,e,this.length);for(var n=this[t+--e],i=1;e>0&&(i*=256);)n+=this[t+--e]*i;return n},e.prototype.readUInt8=function(t,e){return t>>>=0,e||P(t,1,this.length),this[t]},e.prototype.readUInt16LE=function(t,e){return t>>>=0,e||P(t,2,this.length),this[t]|this[t+1]<<8},e.prototype.readUInt16BE=function(t,e){return t>>>=0,e||P(t,2,this.length),this[t]<<8|this[t+1]},e.prototype.readUInt32LE=function(t,e){return t>>>=0,e||P(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},e.prototype.readUInt32BE=function(t,e){return t>>>=0,e||P(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},e.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||P(t,e,this.length);for(var n=this[t],i=1,s=0;++s=(i*=128)&&(n-=Math.pow(2,8*e)),n},e.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||P(t,e,this.length);for(var n=e,i=1,s=this[t+--n];n>0&&(i*=256);)s+=this[t+--n]*i;return s>=(i*=128)&&(s-=Math.pow(2,8*e)),s},e.prototype.readInt8=function(t,e){return t>>>=0,e||P(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},e.prototype.readInt16LE=function(t,e){t>>>=0,e||P(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},e.prototype.readInt16BE=function(t,e){t>>>=0,e||P(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},e.prototype.readInt32LE=function(t,e){return t>>>=0,e||P(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},e.prototype.readInt32BE=function(t,e){return t>>>=0,e||P(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},e.prototype.readFloatLE=function(t,e){return t>>>=0,e||P(t,4,this.length),i.read(this,t,!0,23,4)},e.prototype.readFloatBE=function(t,e){return t>>>=0,e||P(t,4,this.length),i.read(this,t,!1,23,4)},e.prototype.readDoubleLE=function(t,e){return t>>>=0,e||P(t,8,this.length),i.read(this,t,!0,52,8)},e.prototype.readDoubleBE=function(t,e){return t>>>=0,e||P(t,8,this.length),i.read(this,t,!1,52,8)},e.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e>>>=0,r>>>=0,n)||T(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,s=0;for(this[e]=255&t;++s>>=0,r>>>=0,n)||T(this,t,e,r,Math.pow(2,8*r)-1,0);var i=r-1,s=1;for(this[e+i]=255&t;--i>=0&&(s*=256);)this[e+i]=t/s&255;return e+r},e.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,1,255,0),this[e]=255&t,e+1},e.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},e.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},e.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},e.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},e.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);T(this,t,e,r,i-1,-i)}var s=0,o=1,f=0;for(this[e]=255&t;++s>0)-f&255;return e+r},e.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);T(this,t,e,r,i-1,-i)}var s=r-1,o=1,f=0;for(this[e+s]=255&t;--s>=0&&(o*=256);)t<0&&0===f&&0!==this[e+s+1]&&(f=1),this[e+s]=(t/o>>0)-f&255;return e+r},e.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},e.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},e.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},e.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},e.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||T(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},e.prototype.writeFloatLE=function(t,e,r){return N(this,t,e,!0,r)},e.prototype.writeFloatBE=function(t,e,r){return N(this,t,e,!1,r)},e.prototype.writeDoubleLE=function(t,e,r){return R(this,t,e,!0,r)},e.prototype.writeDoubleBE=function(t,e,r){return R(this,t,e,!1,r)},e.prototype.copy=function(t,r,n,i){if(!e.isBuffer(t))throw new TypeError("argument should be a Buffer");if(n||(n=0),i||0===i||(i=this.length),r>=t.length&&(r=t.length),r||(r=0),i>0&&i=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),t.length-r=0;--o)t[o+r]=this[o+n];else Uint8Array.prototype.set.call(t,this.subarray(n,i),r);return s},e.prototype.fill=function(t,r,n,i){if("string"==typeof t){if("string"==typeof r?(i=r,r=0,n=this.length):"string"==typeof n&&(i=n,n=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!e.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===t.length){var s=t.charCodeAt(0);("utf8"===i&&s<128||"latin1"===i)&&(t=s)}}else"number"==typeof t?t&=255:"boolean"==typeof t&&(t=Number(t));if(r<0||this.length>>=0,n=void 0===n?this.length:n>>>0,t||(t=0),"number"==typeof t)for(o=r;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function j(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(L,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function C(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function H(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function q(t){return t!=t}var z=function(){for(var t=new Array(256),e=0;e<16;++e)for(var r=16*e,n=0;n<16;++n)t[r+n]="0123456789abcdef"[e]+"0123456789abcdef"[n];return t}()}).call(this,t("buffer").Buffer)},{"base64-js":117,buffer:119,ieee754:122}],120:[function(t,e,r){(function(t){function e(t){return Object.prototype.toString.call(t)}r.isArray=function(t){return Array.isArray?Array.isArray(t):"[object Array]"===e(t)},r.isBoolean=function(t){return"boolean"==typeof t},r.isNull=function(t){return null===t},r.isNullOrUndefined=function(t){return null==t},r.isNumber=function(t){return"number"==typeof t},r.isString=function(t){return"string"==typeof t},r.isSymbol=function(t){return"symbol"==typeof t},r.isUndefined=function(t){return void 0===t},r.isRegExp=function(t){return"[object RegExp]"===e(t)},r.isObject=function(t){return"object"==typeof t&&null!==t},r.isDate=function(t){return"[object Date]"===e(t)},r.isError=function(t){return"[object Error]"===e(t)||t instanceof Error},r.isFunction=function(t){return"function"==typeof t},r.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},r.isBuffer=t.isBuffer}).call(this,{isBuffer:t("../../is-buffer/index.js")})},{"../../is-buffer/index.js":124}],121:[function(t,e,r){var n=Object.create||function(t){var e=function(){};return e.prototype=t,new e},i=Object.keys||function(t){var e=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.push(r);return r},s=Function.prototype.bind||function(t){var e=this;return function(){return e.apply(t,arguments)}};function o(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=n(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}e.exports=o,o.EventEmitter=o,o.prototype._events=void 0,o.prototype._maxListeners=void 0;var f,a=10;try{var u={};Object.defineProperty&&Object.defineProperty(u,"x",{value:0}),f=0===u.x}catch(t){f=!1}function c(t){return void 0===t._maxListeners?o.defaultMaxListeners:t._maxListeners}function h(t,e,r,i){var s,o,f;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((o=t._events)?(o.newListener&&(t.emit("newListener",e,r.listener?r.listener:r),o=t._events),f=o[e]):(o=t._events=n(null),t._eventsCount=0),f){if("function"==typeof f?f=o[e]=i?[r,f]:[f,r]:i?f.unshift(r):f.push(r),!f.warned&&(s=c(t))&&s>0&&f.length>s){f.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+f.length+' "'+String(e)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=f.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",a.name,a.message)}}else f=o[e]=r,++t._eventsCount;return t}function d(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var t=new Array(arguments.length),e=0;e1&&(e=arguments[1]),e instanceof Error)throw e;var a=new Error('Unhandled "error" event. ('+e+")");throw a.context=e,a}if(!(r=o[t]))return!1;var u="function"==typeof r;switch(n=arguments.length){case 1:!function(t,e,r){if(e)t.call(r);else for(var n=t.length,i=m(t,n),s=0;s=0;o--)if(r[o]===e||r[o].listener===e){f=r[o].listener,s=o;break}if(s<0)return this;0===s?r.shift():function(t,e){for(var r=e,n=r+1,i=t.length;n=0;s--)this.removeListener(t,e[s]);return this},o.prototype.listeners=function(t){return l(this,t,!0)},o.prototype.rawListeners=function(t){return l(this,t,!1)},o.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):b.call(t,e)},o.prototype.listenerCount=b,o.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],122:[function(t,e,r){r.read=function(t,e,r,n,i){var s,o,f=8*i-n-1,a=(1<>1,c=-7,h=r?i-1:0,d=r?-1:1,p=t[e+h];for(h+=d,s=p&(1<<-c)-1,p>>=-c,c+=f;c>0;s=256*s+t[e+h],h+=d,c-=8);for(o=s&(1<<-c)-1,s>>=-c,c+=n;c>0;o=256*o+t[e+h],h+=d,c-=8);if(0===s)s=1-u;else{if(s===a)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,n),s-=u}return(p?-1:1)*o*Math.pow(2,s-n)},r.write=function(t,e,r,n,i,s){var o,f,a,u=8*s-i-1,c=(1<>1,d=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:s-1,l=n?1:-1,b=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(f=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-o))<1&&(o--,a*=2),(e+=o+h>=1?d/a:d*Math.pow(2,1-h))*a>=2&&(o++,a/=2),o+h>=c?(f=0,o=c):o+h>=1?(f=(e*a-1)*Math.pow(2,i),o+=h):(f=e*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;t[r+p]=255&f,p+=l,f/=256,i-=8);for(o=o<0;t[r+p]=255&o,p+=l,o/=256,u-=8);t[r+p-l]|=128*b}},{}],123:[function(t,e,r){arguments[4][48][0].apply(r,arguments)},{dup:48}],124:[function(t,e,r){function n(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}e.exports=function(t){return null!=t&&(n(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&n(t.slice(0,0))}(t)||!!t._isBuffer)}},{}],125:[function(t,e,r){var n={}.toString;e.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},{}],126:[function(t,e,r){(function(t){"use strict";void 0===t||!t.version||0===t.version.indexOf("v0.")||0===t.version.indexOf("v1.")&&0!==t.version.indexOf("v1.8.")?e.exports={nextTick:function(e,r,n,i){if("function"!=typeof e)throw new TypeError('"callback" argument must be a function');var s,o,f=arguments.length;switch(f){case 0:case 1:return t.nextTick(e);case 2:return t.nextTick(function(){e.call(null,r)});case 3:return t.nextTick(function(){e.call(null,r,n)});case 4:return t.nextTick(function(){e.call(null,r,n,i)});default:for(s=new Array(f-1),o=0;o1)for(var r=1;r0?("string"==typeof e||o.objectMode||Object.getPrototypeOf(e)===u.prototype||(e=function(t){return u.from(t)}(e)),n?o.endEmitted?t.emit("error",new Error("stream.unshift() after end event")):_(t,o,e,!0):o.ended?t.emit("error",new Error("stream.push() after EOF")):(o.reading=!1,o.decoder&&!r?(e=o.decoder.write(e),o.objectMode||0!==e.length?_(t,o,e,!1):A(t,o)):_(t,o,e,!1))):n||(o.reading=!1));return function(t){return!t.ended&&(t.needReadable||t.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=S?t=S:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function M(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(p("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?i.nextTick(k,t):k(t))}function k(t){p("emit readable"),t.emit("readable"),P(t)}function A(t,e){e.readingMore||(e.readingMore=!0,i.nextTick(x,t,e))}function x(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=function(t,e,r){var n;ts.length?s.length:t;if(o===s.length?i+=s:i+=s.slice(0,t),0===(t-=o)){o===s.length?(++n,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=s.slice(o));break}++n}return e.length-=n,i}(t,e):function(t,e){var r=u.allocUnsafe(t),n=e.head,i=1;n.data.copy(r),t-=n.data.length;for(;n=n.next;){var s=n.data,o=t>s.length?s.length:t;if(s.copy(r,r.length-t,0,o),0===(t-=o)){o===s.length?(++i,n.next?e.head=n.next:e.head=e.tail=null):(e.head=n,n.data=s.slice(o));break}++i}return e.length-=i,r}(t,e);return n}(t,e.buffer,e.decoder),r);var r}function B(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,i.nextTick(N,e,t))}function N(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function R(t,e){for(var r=0,n=t.length;r=e.highWaterMark||e.ended))return p("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?B(this):M(this),null;if(0===(t=E(t,e))&&e.ended)return 0===e.length&&B(this),null;var n,i=e.needReadable;return p("need readable",i),(0===e.length||e.length-t0?T(t,e):null)?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&B(this)),null!==n&&this.emit("data",n),n},v.prototype._read=function(t){this.emit("error",new Error("_read() is not implemented"))},v.prototype.pipe=function(t,e){var n=this,s=this._readableState;switch(s.pipesCount){case 0:s.pipes=t;break;case 1:s.pipes=[s.pipes,t];break;default:s.pipes.push(t)}s.pipesCount+=1,p("pipe count=%d opts=%j",s.pipesCount,e);var a=(!e||!1!==e.end)&&t!==r.stdout&&t!==r.stderr?c:v;function u(e,r){p("onunpipe"),e===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,p("cleanup"),t.removeListener("close",y),t.removeListener("finish",g),t.removeListener("drain",h),t.removeListener("error",m),t.removeListener("unpipe",u),n.removeListener("end",c),n.removeListener("end",v),n.removeListener("data",b),d=!0,!s.awaitDrain||t._writableState&&!t._writableState.needDrain||h())}function c(){p("onend"),t.end()}s.endEmitted?i.nextTick(a):n.once("end",a),t.on("unpipe",u);var h=function(t){return function(){var e=t._readableState;p("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&f(t,"data")&&(e.flowing=!0,P(t))}}(n);t.on("drain",h);var d=!1;var l=!1;function b(e){p("ondata"),l=!1,!1!==t.write(e)||l||((1===s.pipesCount&&s.pipes===t||s.pipesCount>1&&-1!==R(s.pipes,t))&&!d&&(p("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,l=!0),n.pause())}function m(e){p("onerror",e),v(),t.removeListener("error",m),0===f(t,"error")&&t.emit("error",e)}function y(){t.removeListener("finish",g),v()}function g(){p("onfinish"),t.removeListener("close",y),v()}function v(){p("unpipe"),n.unpipe(t)}return n.on("data",b),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?o(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",m),t.once("close",y),t.once("finish",g),t.emit("pipe",n),s.flowing||(p("pipe resume"),n.resume()),t},v.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r),this);if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var s=0;s-1?i:s.nextTick;g.WritableState=y;var u=t("core-util-is");u.inherits=t("inherits");var c={deprecate:t("util-deprecate")},h=t("./internal/streams/stream"),d=t("safe-buffer").Buffer,p=n.Uint8Array||function(){};var l,b=t("./internal/streams/destroy");function m(){}function y(e,r){f=f||t("./_stream_duplex"),e=e||{};var n=r instanceof f;this.objectMode=!!e.objectMode,n&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var i=e.highWaterMark,u=e.writableHighWaterMark,c=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:n&&(u||0===u)?u:c,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var h=!1===e.decodeStrings;this.decodeStrings=!h,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var r=t._writableState,n=r.sync,i=r.writecb;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(r),e)!function(t,e,r,n,i){--e.pendingcb,r?(s.nextTick(i,n),s.nextTick(M,t,e),t._writableState.errorEmitted=!0,t.emit("error",n)):(i(n),t._writableState.errorEmitted=!0,t.emit("error",n),M(t,e))}(t,r,n,e,i);else{var o=S(r);o||r.corked||r.bufferProcessing||!r.bufferedRequest||_(t,r),n?a(w,t,r,o,i):w(t,r,o,i)}}(r,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new o(this)}function g(e){if(f=f||t("./_stream_duplex"),!(l.call(g,this)||this instanceof f))return new g(e);this._writableState=new y(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),h.call(this)}function v(t,e,r,n,i,s,o){e.writelen=n,e.writecb=o,e.writing=!0,e.sync=!0,r?t._writev(i,e.onwrite):t._write(i,s,e.onwrite),e.sync=!1}function w(t,e,r,n){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,n(),M(t,e)}function _(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var n=e.bufferedRequestCount,i=new Array(n),s=e.corkedRequestsFree;s.entry=r;for(var f=0,a=!0;r;)i[f]=r,r.isBuf||(a=!1),r=r.next,f+=1;i.allBuffers=a,v(t,e,!0,e.length,i,"",s.finish),e.pendingcb++,e.lastBufferedRequest=null,s.next?(e.corkedRequestsFree=s.next,s.next=null):e.corkedRequestsFree=new o(e),e.bufferedRequestCount=0}else{for(;r;){var u=r.chunk,c=r.encoding,h=r.callback;if(v(t,e,!1,e.objectMode?1:u.length,u,c,h),r=r.next,e.bufferedRequestCount--,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequest=r,e.bufferProcessing=!1}function S(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function E(t,e){t._final(function(r){e.pendingcb--,r&&t.emit("error",r),e.prefinished=!0,t.emit("prefinish"),M(t,e)})}function M(t,e){var r=S(e);return r&&(!function(t,e){e.prefinished||e.finalCalled||("function"==typeof t._final?(e.pendingcb++,e.finalCalled=!0,s.nextTick(E,t,e)):(e.prefinished=!0,t.emit("prefinish")))}(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"))),r}u.inherits(g,h),y.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(y.prototype,"buffer",{get:c.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(l=Function.prototype[Symbol.hasInstance],Object.defineProperty(g,Symbol.hasInstance,{value:function(t){return!!l.call(this,t)||this===g&&(t&&t._writableState instanceof y)}})):l=function(t){return t instanceof this},g.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},g.prototype.write=function(t,e,r){var n,i=this._writableState,o=!1,f=!i.objectMode&&(n=t,d.isBuffer(n)||n instanceof p);return f&&!d.isBuffer(t)&&(t=function(t){return d.from(t)}(t)),"function"==typeof e&&(r=e,e=null),f?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=m),i.ended?function(t,e){var r=new Error("write after end");t.emit("error",r),s.nextTick(e,r)}(this,r):(f||function(t,e,r,n){var i=!0,o=!1;return null===r?o=new TypeError("May not write null values to stream"):"string"==typeof r||void 0===r||e.objectMode||(o=new TypeError("Invalid non-string/buffer chunk")),o&&(t.emit("error",o),s.nextTick(n,o),i=!1),i}(this,i,t,r))&&(i.pendingcb++,o=function(t,e,r,n,i,s){if(!r){var o=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=d.from(e,r));return e}(e,n,i);n!==o&&(r=!0,i="buffer",n=o)}var f=e.objectMode?1:n.length;e.length+=f;var a=e.length-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(g.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),g.prototype._write=function(t,e,r){r(new Error("_write() is not implemented"))},g.prototype._writev=null,g.prototype.end=function(t,e,r){var n=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!==t&&void 0!==t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(t,e,r){e.ending=!0,M(t,e),r&&(e.finished?s.nextTick(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r)},Object.defineProperty(g.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),g.prototype.destroy=b.destroy,g.prototype._undestroy=b.undestroy,g.prototype._destroy=function(t,e){this.end(),e(t)}}).call(this,t("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},t("timers").setImmediate)},{"./_stream_duplex":129,"./internal/streams/destroy":135,"./internal/streams/stream":136,_process:127,"core-util-is":120,inherits:123,"process-nextick-args":126,"safe-buffer":137,timers:146,"util-deprecate":147}],134:[function(t,e,r){"use strict";var n=t("safe-buffer").Buffer,i=t("util");e.exports=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.head=null,this.tail=null,this.length=0}return t.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},t.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},t.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},t.prototype.clear=function(){this.head=this.tail=null,this.length=0},t.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r},t.prototype.concat=function(t){if(0===this.length)return n.alloc(0);if(1===this.length)return this.head.data;for(var e,r,i,s=n.allocUnsafe(t>>>0),o=this.head,f=0;o;)e=o.data,r=s,i=f,e.copy(r,i),f+=o.data.length,o=o.next;return s},t}(),i&&i.inspect&&i.inspect.custom&&(e.exports.prototype[i.inspect.custom]=function(){var t=i.inspect({length:this.length});return this.constructor.name+" "+t})},{"safe-buffer":137,util:118}],135:[function(t,e,r){"use strict";var n=t("process-nextick-args");function i(t,e){t.emit("error",e)}e.exports={destroy:function(t,e){var r=this,s=this._readableState&&this._readableState.destroyed,o=this._writableState&&this._writableState.destroyed;return s||o?(e?e(t):!t||this._writableState&&this._writableState.errorEmitted||n.nextTick(i,this,t),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(t){!e&&t?(n.nextTick(i,r,t),r._writableState&&(r._writableState.errorEmitted=!0)):e&&e(t)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}},{"process-nextick-args":126}],136:[function(t,e,r){e.exports=t("events").EventEmitter},{events:121}],137:[function(t,e,r){var n=t("buffer"),i=n.Buffer;function s(t,e){for(var r in t)e[r]=t[r]}function o(t,e,r){return i(t,e,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?e.exports=n:(s(n,r),r.Buffer=o),s(i,o),o.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return i(t,e,r)},o.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var n=i(t);return void 0!==e?"string"==typeof r?n.fill(e,r):n.fill(e):n.fill(0),n},o.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return i(t)},o.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return n.SlowBuffer(t)}},{buffer:119}],138:[function(t,e,r){"use strict";var n=t("safe-buffer").Buffer,i=n.isEncoding||function(t){switch((t=""+t)&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function s(t){var e;switch(this.encoding=function(t){var e=function(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}(t);if("string"!=typeof e&&(n.isEncoding===i||!i(t)))throw new Error("Unknown encoding: "+t);return e||t}(t),this.encoding){case"utf16le":this.text=a,this.end=u,e=4;break;case"utf8":this.fillLast=f,e=4;break;case"base64":this.text=c,this.end=h,e=3;break;default:return this.write=d,void(this.end=p)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(e)}function o(t){return t<=127?0:t>>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function f(t){var e=this.lastTotal-this.lastNeed,r=function(t,e,r){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function a(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function u(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function c(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function h(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function d(t){return t.toString(this.encoding)}function p(t){return t&&t.length?this.write(t):""}r.StringDecoder=s,s.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(t.lastNeed=i-1),i;if(--n=0)return i>0&&(t.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:t.lastNeed=i-3),i;return 0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)},s.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length}},{"safe-buffer":137}],139:[function(t,e,r){e.exports=t("./readable").PassThrough},{"./readable":140}],140:[function(t,e,r){(r=e.exports=t("./lib/_stream_readable.js")).Stream=r,r.Readable=r,r.Writable=t("./lib/_stream_writable.js"),r.Duplex=t("./lib/_stream_duplex.js"),r.Transform=t("./lib/_stream_transform.js"),r.PassThrough=t("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":129,"./lib/_stream_passthrough.js":130,"./lib/_stream_readable.js":131,"./lib/_stream_transform.js":132,"./lib/_stream_writable.js":133}],141:[function(t,e,r){e.exports=t("./readable").Transform},{"./readable":140}],142:[function(t,e,r){e.exports=t("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":133}],143:[function(t,e,r){arguments[4][56][0].apply(r,arguments)},{buffer:119,dup:56}],144:[function(t,e,r){e.exports=i;var n=t("events").EventEmitter;function i(){n.call(this)}t("inherits")(i,n),i.Readable=t("readable-stream/readable.js"),i.Writable=t("readable-stream/writable.js"),i.Duplex=t("readable-stream/duplex.js"),i.Transform=t("readable-stream/transform.js"),i.PassThrough=t("readable-stream/passthrough.js"),i.Stream=i,i.prototype.pipe=function(t,e){var r=this;function i(e){t.writable&&!1===t.write(e)&&r.pause&&r.pause()}function s(){r.readable&&r.resume&&r.resume()}r.on("data",i),t.on("drain",s),t._isStdio||e&&!1===e.end||(r.on("end",f),r.on("close",a));var o=!1;function f(){o||(o=!0,t.end())}function a(){o||(o=!0,"function"==typeof t.destroy&&t.destroy())}function u(t){if(c(),0===n.listenerCount(this,"error"))throw t}function c(){r.removeListener("data",i),t.removeListener("drain",s),r.removeListener("end",f),r.removeListener("close",a),r.removeListener("error",u),t.removeListener("error",u),r.removeListener("end",c),r.removeListener("close",c),t.removeListener("close",c)}return r.on("error",u),t.on("error",u),r.on("end",c),r.on("close",c),t.on("close",c),t.emit("pipe",r),t}},{events:121,inherits:123,"readable-stream/duplex.js":128,"readable-stream/passthrough.js":139,"readable-stream/readable.js":140,"readable-stream/transform.js":141,"readable-stream/writable.js":142}],145:[function(t,e,r){arguments[4][138][0].apply(r,arguments)},{dup:138,"safe-buffer":143}],146:[function(t,e,r){(function(e,n){var i=t("process/browser.js").nextTick,s=Function.prototype.apply,o=Array.prototype.slice,f={},a=0;function u(t,e){this._id=t,this._clearFn=e}r.setTimeout=function(){return new u(s.call(setTimeout,window,arguments),clearTimeout)},r.setInterval=function(){return new u(s.call(setInterval,window,arguments),clearInterval)},r.clearTimeout=r.clearInterval=function(t){t.close()},u.prototype.unref=u.prototype.ref=function(){},u.prototype.close=function(){this._clearFn.call(window,this._id)},r.enroll=function(t,e){clearTimeout(t._idleTimeoutId),t._idleTimeout=e},r.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},r._unrefActive=r.active=function(t){clearTimeout(t._idleTimeoutId);var e=t._idleTimeout;e>=0&&(t._idleTimeoutId=setTimeout(function(){t._onTimeout&&t._onTimeout()},e))},r.setImmediate="function"==typeof e?e:function(t){var e=a++,n=!(arguments.length<2)&&o.call(arguments,1);return f[e]=!0,i(function(){f[e]&&(n?t.apply(null,n):t.call(null),r.clearImmediate(e))}),e},r.clearImmediate="function"==typeof n?n:function(t){delete f[t]}}).call(this,t("timers").setImmediate,t("timers").clearImmediate)},{"process/browser.js":127,timers:146}],147:[function(t,e,r){(function(t){function r(e){try{if(!t.localStorage)return!1}catch(t){return!1}var r=t.localStorage[e];return null!=r&&"true"===String(r).toLowerCase()}e.exports=function(t,e){if(r("noDeprecation"))return t;var n=!1;return function(){if(!n){if(r("throwDeprecation"))throw new Error(e);r("traceDeprecation")?console.trace(e):console.warn(e),n=!0}return t.apply(this,arguments)}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[79])(79)});; \ No newline at end of file +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.bitcoinjs = f()}})(function(){var define,module,exports;return (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 + hmac.hmac(sha256.sha256, key, necc__namespace.utils.concatBytes(...msgs)); +necc__namespace.utils.sha256Sync = (...msgs) => sha256.sha256(necc__namespace.utils.concatBytes(...msgs)); + +const normalizePrivateKey = necc__namespace.utils._normalizePrivateKey; + +const HASH_SIZE = 32; +const TWEAK_SIZE = 32; +const BN32_N = new Uint8Array([ + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 254, 186, 174, 220, 230, 175, 72, 160, 59, 191, 210, 94, 140, 208, 54, 65, 65 +]); +const EXTRA_DATA_SIZE = 32; + +function cmpBN32(data1, data2) { + for (let i = 0; i < 32; ++i) { + if (data1[i] !== data2[i]) { + return data1[i] < data2[i] ? -1 : 1; + } + } + return 0; +} + +function isTweak(tweak) { + // Check that the tweak is a Uint8Array of the correct length + if ( + !(tweak instanceof Uint8Array) || + tweak.length !== TWEAK_SIZE || + cmpBN32(tweak, BN32_N) >= 0 + ) { + return false; + } + return true; +} + +function isSignature(signature) { + return ( + signature instanceof Uint8Array && + signature.length === 64 && + cmpBN32(signature.subarray(0, 32), BN32_N) < 0 && + cmpBN32(signature.subarray(32, 64), BN32_N) < 0 + ); +} + +function isHash(h) { + return h instanceof Uint8Array && h.length === HASH_SIZE; +} + +function isExtraData(e) { + return ( + e === undefined || (e instanceof Uint8Array && e.length === EXTRA_DATA_SIZE) + ); +} + +function hexToNumber(hex) { + if (typeof hex !== 'string') { + throw new TypeError('hexToNumber: expected string, got ' + typeof hex); + } + return BigInt(`0x${hex}`); +} + +function bytesToNumber(bytes) { + return hexToNumber(necc__namespace.utils.bytesToHex(bytes)); +} + +function normalizeScalar(scalar) { + let num; + if (typeof scalar === 'bigint') { + num = scalar; + } else if ( + typeof scalar === 'number' && + Number.isSafeInteger(scalar) && + scalar >= 0 + ) { + num = BigInt(scalar); + } else if (typeof scalar === 'string') { + if (scalar.length !== 64) + throw new Error('Expected 32 bytes of private scalar'); + num = hexToNumber(scalar); + } else if (scalar instanceof Uint8Array) { + if (scalar.length !== 32) + throw new Error('Expected 32 bytes of private scalar'); + num = bytesToNumber(scalar); + } else { + throw new TypeError('Expected valid private scalar'); + } + if (num < 0) throw new Error('Expected private scalar >= 0'); + return num; +} + +const _privateAdd = (privateKey, tweak) => { + const p = normalizePrivateKey(privateKey); + const t = normalizeScalar(tweak); + const add = necc__namespace.utils._bigintTo32Bytes(necc__namespace.utils.mod(p + t, necc__namespace.CURVE.n)); + if (necc__namespace.utils.isValidPrivateKey(add)) return add; + else return null; +}; + +const _privateSub = (privateKey, tweak) => { + const p = normalizePrivateKey(privateKey); + const t = normalizeScalar(tweak); + const sub = necc__namespace.utils._bigintTo32Bytes(necc__namespace.utils.mod(p - t, necc__namespace.CURVE.n)); + if (necc__namespace.utils.isValidPrivateKey(sub)) return sub; + else return null; +}; + +const _privateNegate = privateKey => { + const p = normalizePrivateKey(privateKey); + const not = necc__namespace.utils._bigintTo32Bytes(necc__namespace.CURVE.n - p); + if (necc__namespace.utils.isValidPrivateKey(not)) return not; + else return null; +}; + +const _pointAddScalar = (p, tweak, isCompressed) => { + const P = necc__namespace.Point.fromHex(p); + const t = normalizeScalar(tweak); + const Q = necc__namespace.Point.BASE.multiplyAndAddUnsafe(P, t, 1n); + if (!Q) throw new Error('Tweaked point at infinity'); + return Q.toRawBytes(isCompressed); +}; + +const _pointMultiply = (p, tweak, isCompressed) => { + const P = necc__namespace.Point.fromHex(p); + const h = typeof tweak === 'string' ? tweak : necc__namespace.utils.bytesToHex(tweak); + const t = BigInt(`0x${h}`); + return P.multiply(t).toRawBytes(isCompressed); +}; + +function assumeCompression(compressed, p) { + if (compressed === undefined) { + return p !== undefined ? isPointCompressed(p) : true; + } + return compressed ? true : false; +} + +function throwToNull(fn) { + try { + return fn(); + } catch (e) { + return null; + } +} + +function _isPoint(p, xOnly) { + if ((p.length === 32) !== xOnly) return false; + try { + return !!necc__namespace.Point.fromHex(p); + } catch (e) { + return false; + } +} + +function isPoint(p) { + return _isPoint(p, false); +} + +function isPointCompressed(p) { + const PUBLIC_KEY_COMPRESSED_SIZE = 33; + return _isPoint(p, false) && p.length === PUBLIC_KEY_COMPRESSED_SIZE; +} + +function isPrivate(d) { + return necc__namespace.utils.isValidPrivateKey(d); +} + +function isXOnlyPoint(p) { + return _isPoint(p, true); +} + +function xOnlyPointAddTweak(p, tweak) { + if (!isXOnlyPoint(p)) { + throw new Error('Expected Point'); + } + if (!isTweak(tweak)) { + throw new Error('Expected Tweak'); + } + return throwToNull(() => { + const P = _pointAddScalar(p, tweak, true); + const parity = P[0] % 2 === 1 ? 1 : 0; + return { parity, xOnlyPubkey: P.slice(1) }; + }); +} + +function xOnlyPointFromPoint(p) { + if (!isPoint(p)) { + throw new Error('Expected Point'); + } + return p.slice(1, 33); +} + +function pointFromScalar(sk, compressed) { + if (!isPrivate(sk)) { + throw new Error('Expected Private'); + } + return throwToNull(() => + necc__namespace.getPublicKey(sk, assumeCompression(compressed)) + ); +} + +function xOnlyPointFromScalar(d) { + if (!isPrivate(d)) { + throw new Error('Expected Private'); + } + return xOnlyPointFromPoint(pointFromScalar(d)); +} + +function pointCompress(p, compressed) { + if (!isPoint(p)) { + throw new Error('Expected Point'); + } + return necc__namespace.Point.fromHex(p).toRawBytes(assumeCompression(compressed, p)); +} + +function pointMultiply(a, tweak, compressed) { + if (!isPoint(a)) { + throw new Error('Expected Point'); + } + if (!isTweak(tweak)) { + throw new Error('Expected Tweak'); + } + return throwToNull(() => + _pointMultiply(a, tweak, assumeCompression(compressed, a)) + ); +} + +function pointAdd(a, b, compressed) { + if (!isPoint(a) || !isPoint(b)) { + throw new Error('Expected Point'); + } + return throwToNull(() => { + const A = necc__namespace.Point.fromHex(a); + const B = necc__namespace.Point.fromHex(b); + if (A.equals(B.negate())) { + //https://github.com/paulmillr/noble-secp256k1/issues/91 + return null; + } else { + return A.add(B).toRawBytes(assumeCompression(compressed, a)); + } + }); +} +function pointAddScalar(p, tweak, compressed) { + if (!isPoint(p)) { + throw new Error('Expected Point'); + } + if (!isTweak(tweak)) { + throw new Error('Expected Tweak'); + } + return throwToNull(() => + _pointAddScalar(p, tweak, assumeCompression(compressed, p)) + ); +} + +function privateAdd(d, tweak) { + if (isPrivate(d) === false) { + throw new Error('Expected Private'); + } + if (isTweak(tweak) === false) { + throw new Error('Expected Tweak'); + } + return throwToNull(() => _privateAdd(d, tweak)); +} + +function privateSub(d, tweak) { + if (isPrivate(d) === false) { + throw new Error('Expected Private'); + } + if (isTweak(tweak) === false) { + throw new Error('Expected Tweak'); + } + return throwToNull(() => _privateSub(d, tweak)); +} + +function privateNegate(d) { + if (isPrivate(d) === false) { + throw new Error('Expected Private'); + } + return _privateNegate(d); +} + +function sign(h, d, e) { + if (!isPrivate(d)) { + throw new Error('Expected Private'); + } + if (!isHash(h)) { + throw new Error('Expected Scalar'); + } + if (!isExtraData(e)) { + throw new Error('Expected Extra Data (32 bytes)'); + } + return necc__namespace.signSync(h, d, { der: false, extraEntropy: e }); +} + +function signSchnorr(h, d, e = Buffer.alloc(32, 0x00)) { + if (!isPrivate(d)) { + throw new Error('Expected Private'); + } + if (!isHash(h)) { + throw new Error('Expected Scalar'); + } + if (!isExtraData(e)) { + throw new Error('Expected Extra Data (32 bytes)'); + } + return necc__namespace.schnorr.signSync(h, d, e); +} + +function verify(h, Q, signature, strict) { + if (!isPoint(Q)) { + throw new Error('Expected Point'); + } + if (!isSignature(signature)) { + throw new Error('Expected Signature'); + } + if (!isHash(h)) { + throw new Error('Expected Scalar'); + } + return necc__namespace.verify(signature, h, Q, { strict }); +} + +function verifySchnorr(h, Q, signature) { + if (!isXOnlyPoint(Q)) { + throw new Error('Expected Point'); + } + if (!isSignature(signature)) { + throw new Error('Expected Signature'); + } + if (!isHash(h)) { + throw new Error('Expected Scalar'); + } + return necc__namespace.schnorr.verifySync(signature, h, Q); +} + +exports.isPoint = isPoint; +exports.isPointCompressed = isPointCompressed; +exports.isPrivate = isPrivate; +exports.isXOnlyPoint = isXOnlyPoint; +exports.pointAdd = pointAdd; +exports.pointAddScalar = pointAddScalar; +exports.pointCompress = pointCompress; +exports.pointFromScalar = pointFromScalar; +exports.pointMultiply = pointMultiply; +exports.privateAdd = privateAdd; +exports.privateNegate = privateNegate; +exports.privateSub = privateSub; +exports.sign = sign; +exports.signSchnorr = signSchnorr; +exports.verify = verify; +exports.verifySchnorr = verifySchnorr; +exports.xOnlyPointAddTweak = xOnlyPointAddTweak; +exports.xOnlyPointFromPoint = xOnlyPointFromPoint; +exports.xOnlyPointFromScalar = xOnlyPointFromScalar; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"@noble/hashes/hmac":5,"@noble/hashes/sha256":8,"@noble/secp256k1":10,"buffer":92}],2:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = void 0; +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +exports.number = number; +function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`Expected boolean, not ${b}`); +} +exports.bool = bool; +function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new Error('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +exports.bytes = bytes; +function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} +exports.hash = hash; +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +exports.exists = exists; +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +exports.output = output; +const assert = { + number, + bool, + bytes, + hash, + exists, + output, +}; +exports.default = assert; + +},{}],3:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SHA2 = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// Polyfill for Safari 14 +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +// Base SHA2 class (RFC 6234) +class SHA2 extends utils_js_1.Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = (0, utils_js_1.createView)(this.buffer); + } + update(data) { + _assert_js_1.default.exists(this); + const { view, buffer, blockLen } = this; + data = (0, utils_js_1.toBytes)(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = (0, utils_js_1.createView)(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + _assert_js_1.default.exists(this); + _assert_js_1.default.output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = (0, utils_js_1.createView)(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) + throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} +exports.SHA2 = SHA2; + +},{"./_assert.js":2,"./utils.js":9}],4:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.crypto = void 0; +exports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; + +},{}],5:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hmac = exports.HMAC = void 0; +const _assert_js_1 = require("./_assert.js"); +const utils_js_1 = require("./utils.js"); +// HMAC (RFC 2104) +class HMAC extends utils_js_1.Hash { + constructor(hash, _key) { + super(); + this.finished = false; + this.destroyed = false; + _assert_js_1.default.hash(hash); + const key = (0, utils_js_1.toBytes)(_key); + this.iHash = hash.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + _assert_js_1.default.exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + _assert_js_1.default.exists(this); + _assert_js_1.default.bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +exports.HMAC = HMAC; +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +exports.hmac = hmac; +exports.hmac.create = (hash, key) => new HMAC(hash, key); + +},{"./_assert.js":2,"./utils.js":9}],6:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ripemd160 = exports.RIPEMD160 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const utils_js_1 = require("./utils.js"); +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = new Uint32Array([0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]); +const Kr = new Uint32Array([0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | (word >>> (32 - shift)); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const BUF = new Uint32Array(16); +class RIPEMD160 extends _sha2_js_1.SHA2 { + constructor() { + super(64, 20, 8, true); + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +exports.RIPEMD160 = RIPEMD160; +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +exports.ripemd160 = (0, utils_js_1.wrapConstructor)(() => new RIPEMD160()); + +},{"./_sha2.js":3,"./utils.js":9}],7:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha1 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const utils_js_1 = require("./utils.js"); +// SHA1 was cryptographically broken. +// It is still widely used in legacy apps. Don't use it for a new protocol. +// RFC 3174 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Initial state +const IV = new Uint32Array([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = new Uint32Array(80); +class SHA1 extends _sha2_js_1.SHA2 { + constructor() { + super(64, 20, 8, false); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +exports.sha1 = (0, utils_js_1.wrapConstructor)(() => new SHA1()); + +},{"./_sha2.js":3,"./utils.js":9}],8:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha224 = exports.sha256 = void 0; +const _sha2_js_1 = require("./_sha2.js"); +const utils_js_1 = require("./utils.js"); +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); +// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): +// prettier-ignore +const IV = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = new Uint32Array(64); +class SHA256 extends _sha2_js_1.SHA2 { + constructor() { + super(64, 32, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = (0, utils_js_1.rotr)(W15, 7) ^ (0, utils_js_1.rotr)(W15, 18) ^ (W15 >>> 3); + const s1 = (0, utils_js_1.rotr)(W2, 17) ^ (0, utils_js_1.rotr)(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = (0, utils_js_1.rotr)(E, 6) ^ (0, utils_js_1.rotr)(E, 11) ^ (0, utils_js_1.rotr)(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = (0, utils_js_1.rotr)(A, 2) ^ (0, utils_js_1.rotr)(A, 13) ^ (0, utils_js_1.rotr)(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf +class SHA224 extends SHA256 { + constructor() { + super(); + this.A = 0xc1059ed8 | 0; + this.B = 0x367cd507 | 0; + this.C = 0x3070dd17 | 0; + this.D = 0xf70e5939 | 0; + this.E = 0xffc00b31 | 0; + this.F = 0x68581511 | 0; + this.G = 0x64f98fa7 | 0; + this.H = 0xbefa4fa4 | 0; + this.outputLen = 28; + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +exports.sha256 = (0, utils_js_1.wrapConstructor)(() => new SHA256()); +exports.sha224 = (0, utils_js_1.wrapConstructor)(() => new SHA224()); + +},{"./_sha2.js":3,"./utils.js":9}],9:[function(require,module,exports){ +"use strict"; +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.randomBytes = exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.checkOpts = exports.Hash = exports.concatBytes = exports.toBytes = exports.utf8ToBytes = exports.asyncLoop = exports.nextTick = exports.hexToBytes = exports.bytesToHex = exports.isLE = exports.rotr = exports.createView = exports.u32 = exports.u8 = void 0; +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated, we can just drop the import. +const crypto_1 = require("@noble/hashes/crypto"); +const u8a = (a) => a instanceof Uint8Array; +// Cast array to different type +const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +exports.u8 = u8; +const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +exports.u32 = u32; +// Cast array to view +const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +exports.createView = createView; +// The rotate right (circular right shift) operation for uint32 +const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +exports.rotr = rotr; +// big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. +exports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!exports.isLE) + throw new Error('Non little-endian hardware is not supported'); +const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' + */ +function bytesToHex(bytes) { + if (!u8a(bytes)) + throw new Error('Uint8Array expected'); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +exports.bytesToHex = bytesToHex; +/** + * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + */ +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const len = hex.length; + if (len % 2) + throw new Error('padded hex string expected, got unpadded hex of length ' + len); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +exports.hexToBytes = hexToBytes; +// There is no setImmediate in browser and setTimeout is slow. +// call of async fn will return Promise, which will be fullfiled only on +// next scheduler queue processing step and this is exactly what we need. +const nextTick = async () => { }; +exports.nextTick = nextTick; +// Returns control to thread each 'tick' ms to avoid blocking +async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await (0, exports.nextTick)(); + ts += diff; + } +} +exports.asyncLoop = asyncLoop; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +exports.utf8ToBytes = utf8ToBytes; +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + if (!u8a(data)) + throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} +exports.toBytes = toBytes; +/** + * Copies several Uint8Arrays into one. + */ +function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; // walk through each item, ensure they have proper type + arrays.forEach((a) => { + if (!u8a(a)) + throw new Error('Uint8Array expected'); + r.set(a, pad); + pad += a.length; + }); + return r; +} +exports.concatBytes = concatBytes; +// For runtime check if class implements interface +class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +exports.Hash = Hash; +// Check if object doens't have custom constructor (like Uint8Array/Array) +const isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object; +function checkOpts(defaults, opts) { + if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts))) + throw new Error('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged; +} +exports.checkOpts = checkOpts; +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +exports.wrapConstructor = wrapConstructor; +function wrapConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +exports.wrapConstructorWithOpts = wrapConstructorWithOpts; +function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +exports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts; +/** + * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. + */ +function randomBytes(bytesLength = 32) { + if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') { + return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error('crypto.getRandomValues must be defined'); +} +exports.randomBytes = randomBytes; + +},{"@noble/hashes/crypto":4}],10:[function(require,module,exports){ +"use strict"; +/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.utils = exports.schnorr = exports.verify = exports.signSync = exports.sign = exports.getSharedSecret = exports.recoverPublicKey = exports.getPublicKey = exports.Signature = exports.Point = exports.CURVE = void 0; +const nodeCrypto = require("crypto"); +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const _3n = BigInt(3); +const _8n = BigInt(8); +const CURVE = Object.freeze({ + a: _0n, + b: BigInt(7), + P: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'), + n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'), + h: _1n, + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), +}); +exports.CURVE = CURVE; +const divNearest = (a, b) => (a + b / _2n) / b; +const endo = { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar(k) { + const { n } = CURVE; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const POW_2_128 = BigInt('0x100000000000000000000000000000000'); + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalarEndo: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; + }, +}; +const fieldLen = 32; +const groupLen = 32; +const hashLen = 32; +const compressedLen = fieldLen + 1; +const uncompressedLen = 2 * fieldLen + 1; +function weierstrass(x) { + const { a, b } = CURVE; + const x2 = mod(x * x); + const x3 = mod(x2 * x); + return mod(x3 + a * x + b); +} +const USE_ENDOMORPHISM = CURVE.a === _0n; +class ShaError extends Error { + constructor(message) { + super(message); + } +} +function assertJacPoint(other) { + if (!(other instanceof JacobianPoint)) + throw new TypeError('JacobianPoint expected'); +} +class JacobianPoint { + constructor(x, y, z) { + this.x = x; + this.y = y; + this.z = z; + } + static fromAffine(p) { + if (!(p instanceof Point)) { + throw new TypeError('JacobianPoint#fromAffine: expected Point'); + } + if (p.equals(Point.ZERO)) + return JacobianPoint.ZERO; + return new JacobianPoint(p.x, p.y, _1n); + } + static toAffineBatch(points) { + const toInv = invertBatch(points.map((p) => p.z)); + return points.map((p, i) => p.toAffine(toInv[i])); + } + static normalizeZ(points) { + return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine); + } + equals(other) { + assertJacPoint(other); + const { x: X1, y: Y1, z: Z1 } = this; + const { x: X2, y: Y2, z: Z2 } = other; + const Z1Z1 = mod(Z1 * Z1); + const Z2Z2 = mod(Z2 * Z2); + const U1 = mod(X1 * Z2Z2); + const U2 = mod(X2 * Z1Z1); + const S1 = mod(mod(Y1 * Z2) * Z2Z2); + const S2 = mod(mod(Y2 * Z1) * Z1Z1); + return U1 === U2 && S1 === S2; + } + negate() { + return new JacobianPoint(this.x, mod(-this.y), this.z); + } + double() { + const { x: X1, y: Y1, z: Z1 } = this; + const A = mod(X1 * X1); + const B = mod(Y1 * Y1); + const C = mod(B * B); + const x1b = X1 + B; + const D = mod(_2n * (mod(x1b * x1b) - A - C)); + const E = mod(_3n * A); + const F = mod(E * E); + const X3 = mod(F - _2n * D); + const Y3 = mod(E * (D - X3) - _8n * C); + const Z3 = mod(_2n * Y1 * Z1); + return new JacobianPoint(X3, Y3, Z3); + } + add(other) { + assertJacPoint(other); + const { x: X1, y: Y1, z: Z1 } = this; + const { x: X2, y: Y2, z: Z2 } = other; + if (X2 === _0n || Y2 === _0n) + return this; + if (X1 === _0n || Y1 === _0n) + return other; + const Z1Z1 = mod(Z1 * Z1); + const Z2Z2 = mod(Z2 * Z2); + const U1 = mod(X1 * Z2Z2); + const U2 = mod(X2 * Z1Z1); + const S1 = mod(mod(Y1 * Z2) * Z2Z2); + const S2 = mod(mod(Y2 * Z1) * Z1Z1); + const H = mod(U2 - U1); + const r = mod(S2 - S1); + if (H === _0n) { + if (r === _0n) { + return this.double(); + } + else { + return JacobianPoint.ZERO; + } + } + const HH = mod(H * H); + const HHH = mod(H * HH); + const V = mod(U1 * HH); + const X3 = mod(r * r - HHH - _2n * V); + const Y3 = mod(r * (V - X3) - S1 * HHH); + const Z3 = mod(Z1 * Z2 * H); + return new JacobianPoint(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + multiplyUnsafe(scalar) { + const P0 = JacobianPoint.ZERO; + if (typeof scalar === 'bigint' && scalar === _0n) + return P0; + let n = normalizeScalar(scalar); + if (n === _1n) + return this; + if (!USE_ENDOMORPHISM) { + let p = P0; + let d = this; + while (n > _0n) { + if (n & _1n) + p = p.add(d); + d = d.double(); + n >>= _1n; + } + return p; + } + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let k1p = P0; + let k2p = P0; + let d = this; + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) + k1p = k1p.add(d); + if (k2 & _1n) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n; + k2 >>= _1n; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z); + return k1p.add(k2p); + } + precomputeWindow(W) { + const windows = USE_ENDOMORPHISM ? 128 / W + 1 : 256 / W + 1; + const points = []; + let p = this; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + for (let i = 1; i < 2 ** (W - 1); i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + } + wNAF(n, affinePoint) { + if (!affinePoint && this.equals(JacobianPoint.BASE)) + affinePoint = Point.BASE; + const W = (affinePoint && affinePoint._WINDOW_SIZE) || 1; + if (256 % W) { + throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2'); + } + let precomputes = affinePoint && pointPrecomputes.get(affinePoint); + if (!precomputes) { + precomputes = this.precomputeWindow(W); + if (affinePoint && W !== 1) { + precomputes = JacobianPoint.normalizeZ(precomputes); + pointPrecomputes.set(affinePoint, precomputes); + } + } + let p = JacobianPoint.ZERO; + let f = JacobianPoint.BASE; + const windows = 1 + (USE_ENDOMORPHISM ? 128 / W : 256 / W); + const windowSize = 2 ** (W - 1); + const mask = BigInt(2 ** W - 1); + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + let wbits = Number(n & mask); + n >>= shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n; + } + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } + else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + return { p, f }; + } + multiply(scalar, affinePoint) { + let n = normalizeScalar(scalar); + let point; + let fake; + if (USE_ENDOMORPHISM) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let { p: k1p, f: f1p } = this.wNAF(k1, affinePoint); + let { p: k2p, f: f2p } = this.wNAF(k2, affinePoint); + k1p = constTimeNegate(k1neg, k1p); + k2p = constTimeNegate(k2neg, k2p); + k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } + else { + const { p, f } = this.wNAF(n, affinePoint); + point = p; + fake = f; + } + return JacobianPoint.normalizeZ([point, fake])[0]; + } + toAffine(invZ) { + const { x, y, z } = this; + const is0 = this.equals(JacobianPoint.ZERO); + if (invZ == null) + invZ = is0 ? _8n : invert(z); + const iz1 = invZ; + const iz2 = mod(iz1 * iz1); + const iz3 = mod(iz2 * iz1); + const ax = mod(x * iz2); + const ay = mod(y * iz3); + const zz = mod(z * iz1); + if (is0) + return Point.ZERO; + if (zz !== _1n) + throw new Error('invZ was invalid'); + return new Point(ax, ay); + } +} +JacobianPoint.BASE = new JacobianPoint(CURVE.Gx, CURVE.Gy, _1n); +JacobianPoint.ZERO = new JacobianPoint(_0n, _1n, _0n); +function constTimeNegate(condition, item) { + const neg = item.negate(); + return condition ? neg : item; +} +const pointPrecomputes = new WeakMap(); +class Point { + constructor(x, y) { + this.x = x; + this.y = y; + } + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + hasEvenY() { + return this.y % _2n === _0n; + } + static fromCompressedHex(bytes) { + const isShort = bytes.length === 32; + const x = bytesToNumber(isShort ? bytes : bytes.subarray(1)); + if (!isValidFieldElement(x)) + throw new Error('Point is not on curve'); + const y2 = weierstrass(x); + let y = sqrtMod(y2); + const isYOdd = (y & _1n) === _1n; + if (isShort) { + if (isYOdd) + y = mod(-y); + } + else { + const isFirstByteOdd = (bytes[0] & 1) === 1; + if (isFirstByteOdd !== isYOdd) + y = mod(-y); + } + const point = new Point(x, y); + point.assertValidity(); + return point; + } + static fromUncompressedHex(bytes) { + const x = bytesToNumber(bytes.subarray(1, fieldLen + 1)); + const y = bytesToNumber(bytes.subarray(fieldLen + 1, fieldLen * 2 + 1)); + const point = new Point(x, y); + point.assertValidity(); + return point; + } + static fromHex(hex) { + const bytes = ensureBytes(hex); + const len = bytes.length; + const header = bytes[0]; + if (len === fieldLen) + return this.fromCompressedHex(bytes); + if (len === compressedLen && (header === 0x02 || header === 0x03)) { + return this.fromCompressedHex(bytes); + } + if (len === uncompressedLen && header === 0x04) + return this.fromUncompressedHex(bytes); + throw new Error(`Point.fromHex: received invalid point. Expected 32-${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes, not ${len}`); + } + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normalizePrivateKey(privateKey)); + } + static fromSignature(msgHash, signature, recovery) { + const { r, s } = normalizeSignature(signature); + if (![0, 1, 2, 3].includes(recovery)) + throw new Error('Cannot recover: invalid recovery bit'); + const h = truncateHash(ensureBytes(msgHash)); + const { n } = CURVE; + const radj = recovery === 2 || recovery === 3 ? r + n : r; + const rinv = invert(radj, n); + const u1 = mod(-h * rinv, n); + const u2 = mod(s * rinv, n); + const prefix = recovery & 1 ? '03' : '02'; + const R = Point.fromHex(prefix + numTo32bStr(radj)); + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); + if (!Q) + throw new Error('Cannot recover signature: point at infinify'); + Q.assertValidity(); + return Q; + } + toRawBytes(isCompressed = false) { + return hexToBytes(this.toHex(isCompressed)); + } + toHex(isCompressed = false) { + const x = numTo32bStr(this.x); + if (isCompressed) { + const prefix = this.hasEvenY() ? '02' : '03'; + return `${prefix}${x}`; + } + else { + return `04${x}${numTo32bStr(this.y)}`; + } + } + toHexX() { + return this.toHex(true).slice(2); + } + toRawX() { + return this.toRawBytes(true).slice(1); + } + assertValidity() { + const msg = 'Point is not on elliptic curve'; + const { x, y } = this; + if (!isValidFieldElement(x) || !isValidFieldElement(y)) + throw new Error(msg); + const left = mod(y * y); + const right = weierstrass(x); + if (mod(left - right) !== _0n) + throw new Error(msg); + } + equals(other) { + return this.x === other.x && this.y === other.y; + } + negate() { + return new Point(this.x, mod(-this.y)); + } + double() { + return JacobianPoint.fromAffine(this).double().toAffine(); + } + add(other) { + return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine(); + } + subtract(other) { + return this.add(other.negate()); + } + multiply(scalar) { + return JacobianPoint.fromAffine(this).multiply(scalar, this).toAffine(); + } + multiplyAndAddUnsafe(Q, a, b) { + const P = JacobianPoint.fromAffine(this); + const aP = a === _0n || a === _1n || this !== Point.BASE ? P.multiplyUnsafe(a) : P.multiply(a); + const bQ = JacobianPoint.fromAffine(Q).multiplyUnsafe(b); + const sum = aP.add(bQ); + return sum.equals(JacobianPoint.ZERO) ? undefined : sum.toAffine(); + } +} +exports.Point = Point; +Point.BASE = new Point(CURVE.Gx, CURVE.Gy); +Point.ZERO = new Point(_0n, _0n); +function sliceDER(s) { + return Number.parseInt(s[0], 16) >= 8 ? '00' + s : s; +} +function parseDERInt(data) { + if (data.length < 2 || data[0] !== 0x02) { + throw new Error(`Invalid signature integer tag: ${bytesToHex(data)}`); + } + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) { + throw new Error(`Invalid signature integer: wrong length`); + } + if (res[0] === 0x00 && res[1] <= 0x7f) { + throw new Error('Invalid signature integer: trailing length'); + } + return { data: bytesToNumber(res), left: data.subarray(len + 2) }; +} +function parseDERSignature(data) { + if (data.length < 2 || data[0] != 0x30) { + throw new Error(`Invalid signature tag: ${bytesToHex(data)}`); + } + if (data[1] !== data.length - 2) { + throw new Error('Invalid signature: incorrect length'); + } + const { data: r, left: sBytes } = parseDERInt(data.subarray(2)); + const { data: s, left: rBytesLeft } = parseDERInt(sBytes); + if (rBytesLeft.length) { + throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(rBytesLeft)}`); + } + return { r, s }; +} +class Signature { + constructor(r, s) { + this.r = r; + this.s = s; + this.assertValidity(); + } + static fromCompact(hex) { + const arr = hex instanceof Uint8Array; + const name = 'Signature.fromCompact'; + if (typeof hex !== 'string' && !arr) + throw new TypeError(`${name}: Expected string or Uint8Array`); + const str = arr ? bytesToHex(hex) : hex; + if (str.length !== 128) + throw new Error(`${name}: Expected 64-byte hex`); + return new Signature(hexToNumber(str.slice(0, 64)), hexToNumber(str.slice(64, 128))); + } + static fromDER(hex) { + const arr = hex instanceof Uint8Array; + if (typeof hex !== 'string' && !arr) + throw new TypeError(`Signature.fromDER: Expected string or Uint8Array`); + const { r, s } = parseDERSignature(arr ? hex : hexToBytes(hex)); + return new Signature(r, s); + } + static fromHex(hex) { + return this.fromDER(hex); + } + assertValidity() { + const { r, s } = this; + if (!isWithinCurveOrder(r)) + throw new Error('Invalid Signature: r must be 0 < r < n'); + if (!isWithinCurveOrder(s)) + throw new Error('Invalid Signature: s must be 0 < s < n'); + } + hasHighS() { + const HALF = CURVE.n >> _1n; + return this.s > HALF; + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, mod(-this.s, CURVE.n)) : this; + } + toDERRawBytes() { + return hexToBytes(this.toDERHex()); + } + toDERHex() { + const sHex = sliceDER(numberToHexUnpadded(this.s)); + const rHex = sliceDER(numberToHexUnpadded(this.r)); + const sHexL = sHex.length / 2; + const rHexL = rHex.length / 2; + const sLen = numberToHexUnpadded(sHexL); + const rLen = numberToHexUnpadded(rHexL); + const length = numberToHexUnpadded(rHexL + sHexL + 4); + return `30${length}02${rLen}${rHex}02${sLen}${sHex}`; + } + toRawBytes() { + return this.toDERRawBytes(); + } + toHex() { + return this.toDERHex(); + } + toCompactRawBytes() { + return hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numTo32bStr(this.r) + numTo32bStr(this.s); + } +} +exports.Signature = Signature; +function concatBytes(...arrays) { + if (!arrays.every((b) => b instanceof Uint8Array)) + throw new Error('Uint8Array list expected'); + if (arrays.length === 1) + return arrays[0]; + const length = arrays.reduce((a, arr) => a + arr.length, 0); + const result = new Uint8Array(length); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const arr = arrays[i]; + result.set(arr, pad); + pad += arr.length; + } + return result; +} +const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); +function bytesToHex(uint8a) { + if (!(uint8a instanceof Uint8Array)) + throw new Error('Expected Uint8Array'); + let hex = ''; + for (let i = 0; i < uint8a.length; i++) { + hex += hexes[uint8a[i]]; + } + return hex; +} +const POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000'); +function numTo32bStr(num) { + if (typeof num !== 'bigint') + throw new Error('Expected bigint'); + if (!(_0n <= num && num < POW_2_256)) + throw new Error('Expected number 0 <= n < 2^256'); + return num.toString(16).padStart(64, '0'); +} +function numTo32b(num) { + const b = hexToBytes(numTo32bStr(num)); + if (b.length !== 32) + throw new Error('Error: expected 32 bytes'); + return b; +} +function numberToHexUnpadded(num) { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} +function hexToNumber(hex) { + if (typeof hex !== 'string') { + throw new TypeError('hexToNumber: expected string, got ' + typeof hex); + } + return BigInt(`0x${hex}`); +} +function hexToBytes(hex) { + if (typeof hex !== 'string') { + throw new TypeError('hexToBytes: expected string, got ' + typeof hex); + } + if (hex.length % 2) + throw new Error('hexToBytes: received invalid unpadded hex' + hex.length); + const array = new Uint8Array(hex.length / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +function bytesToNumber(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +function ensureBytes(hex) { + return hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex); +} +function normalizeScalar(num) { + if (typeof num === 'number' && Number.isSafeInteger(num) && num > 0) + return BigInt(num); + if (typeof num === 'bigint' && isWithinCurveOrder(num)) + return num; + throw new TypeError('Expected valid private scalar: 0 < scalar < curve.n'); +} +function mod(a, b = CURVE.P) { + const result = a % b; + return result >= _0n ? result : b + result; +} +function pow2(x, power) { + const { P } = CURVE; + let res = x; + while (power-- > _0n) { + res *= res; + res %= P; + } + return res; +} +function sqrtMod(x) { + const { P } = CURVE; + const _6n = BigInt(6); + const _11n = BigInt(11); + const _22n = BigInt(22); + const _23n = BigInt(23); + const _44n = BigInt(44); + const _88n = BigInt(88); + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = (pow2(b3, _3n) * b3) % P; + const b9 = (pow2(b6, _3n) * b3) % P; + const b11 = (pow2(b9, _2n) * b2) % P; + const b22 = (pow2(b11, _11n) * b11) % P; + const b44 = (pow2(b22, _22n) * b22) % P; + const b88 = (pow2(b44, _44n) * b44) % P; + const b176 = (pow2(b88, _88n) * b88) % P; + const b220 = (pow2(b176, _44n) * b44) % P; + const b223 = (pow2(b220, _3n) * b3) % P; + const t1 = (pow2(b223, _23n) * b22) % P; + const t2 = (pow2(t1, _6n) * b2) % P; + const rt = pow2(t2, _2n); + const xc = (rt * rt) % P; + if (xc !== x) + throw new Error('Cannot find square root'); + return rt; +} +function invert(number, modulo = CURVE.P) { + if (number === _0n || modulo <= _0n) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + let a = mod(number, modulo); + let b = modulo; + let x = _0n, y = _1n, u = _1n, v = _0n; + while (a !== _0n) { + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== _1n) + throw new Error('invert: does not exist'); + return mod(x, modulo); +} +function invertBatch(nums, p = CURVE.P) { + const scratch = new Array(nums.length); + const lastMultiplied = nums.reduce((acc, num, i) => { + if (num === _0n) + return acc; + scratch[i] = acc; + return mod(acc * num, p); + }, _1n); + const inverted = invert(lastMultiplied, p); + nums.reduceRight((acc, num, i) => { + if (num === _0n) + return acc; + scratch[i] = mod(acc * scratch[i], p); + return mod(acc * num, p); + }, inverted); + return scratch; +} +function bits2int_2(bytes) { + const delta = bytes.length * 8 - groupLen * 8; + const num = bytesToNumber(bytes); + return delta > 0 ? num >> BigInt(delta) : num; +} +function truncateHash(hash, truncateOnly = false) { + const h = bits2int_2(hash); + if (truncateOnly) + return h; + const { n } = CURVE; + return h >= n ? h - n : h; +} +let _sha256Sync; +let _hmacSha256Sync; +class HmacDrbg { + constructor(hashLen, qByteLen) { + this.hashLen = hashLen; + this.qByteLen = qByteLen; + if (typeof hashLen !== 'number' || hashLen < 2) + throw new Error('hashLen must be a number'); + if (typeof qByteLen !== 'number' || qByteLen < 2) + throw new Error('qByteLen must be a number'); + this.v = new Uint8Array(hashLen).fill(1); + this.k = new Uint8Array(hashLen).fill(0); + this.counter = 0; + } + hmac(...values) { + return exports.utils.hmacSha256(this.k, ...values); + } + hmacSync(...values) { + return _hmacSha256Sync(this.k, ...values); + } + checkSync() { + if (typeof _hmacSha256Sync !== 'function') + throw new ShaError('hmacSha256Sync needs to be set'); + } + incr() { + if (this.counter >= 1000) + throw new Error('Tried 1,000 k values for sign(), all were invalid'); + this.counter += 1; + } + async reseed(seed = new Uint8Array()) { + this.k = await this.hmac(this.v, Uint8Array.from([0x00]), seed); + this.v = await this.hmac(this.v); + if (seed.length === 0) + return; + this.k = await this.hmac(this.v, Uint8Array.from([0x01]), seed); + this.v = await this.hmac(this.v); + } + reseedSync(seed = new Uint8Array()) { + this.checkSync(); + this.k = this.hmacSync(this.v, Uint8Array.from([0x00]), seed); + this.v = this.hmacSync(this.v); + if (seed.length === 0) + return; + this.k = this.hmacSync(this.v, Uint8Array.from([0x01]), seed); + this.v = this.hmacSync(this.v); + } + async generate() { + this.incr(); + let len = 0; + const out = []; + while (len < this.qByteLen) { + this.v = await this.hmac(this.v); + const sl = this.v.slice(); + out.push(sl); + len += this.v.length; + } + return concatBytes(...out); + } + generateSync() { + this.checkSync(); + this.incr(); + let len = 0; + const out = []; + while (len < this.qByteLen) { + this.v = this.hmacSync(this.v); + const sl = this.v.slice(); + out.push(sl); + len += this.v.length; + } + return concatBytes(...out); + } +} +function isWithinCurveOrder(num) { + return _0n < num && num < CURVE.n; +} +function isValidFieldElement(num) { + return _0n < num && num < CURVE.P; +} +function kmdToSig(kBytes, m, d, lowS = true) { + const { n } = CURVE; + const k = truncateHash(kBytes, true); + if (!isWithinCurveOrder(k)) + return; + const kinv = invert(k, n); + const q = Point.BASE.multiply(k); + const r = mod(q.x, n); + if (r === _0n) + return; + const s = mod(kinv * mod(m + d * r, n), n); + if (s === _0n) + return; + let sig = new Signature(r, s); + let recovery = (q.x === sig.r ? 0 : 2) | Number(q.y & _1n); + if (lowS && sig.hasHighS()) { + sig = sig.normalizeS(); + recovery ^= 1; + } + return { sig, recovery }; +} +function normalizePrivateKey(key) { + let num; + if (typeof key === 'bigint') { + num = key; + } + else if (typeof key === 'number' && Number.isSafeInteger(key) && key > 0) { + num = BigInt(key); + } + else if (typeof key === 'string') { + if (key.length !== 2 * groupLen) + throw new Error('Expected 32 bytes of private key'); + num = hexToNumber(key); + } + else if (key instanceof Uint8Array) { + if (key.length !== groupLen) + throw new Error('Expected 32 bytes of private key'); + num = bytesToNumber(key); + } + else { + throw new TypeError('Expected valid private key'); + } + if (!isWithinCurveOrder(num)) + throw new Error('Expected private key: 0 < key < n'); + return num; +} +function normalizePublicKey(publicKey) { + if (publicKey instanceof Point) { + publicKey.assertValidity(); + return publicKey; + } + else { + return Point.fromHex(publicKey); + } +} +function normalizeSignature(signature) { + if (signature instanceof Signature) { + signature.assertValidity(); + return signature; + } + try { + return Signature.fromDER(signature); + } + catch (error) { + return Signature.fromCompact(signature); + } +} +function getPublicKey(privateKey, isCompressed = false) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); +} +exports.getPublicKey = getPublicKey; +function recoverPublicKey(msgHash, signature, recovery, isCompressed = false) { + return Point.fromSignature(msgHash, signature, recovery).toRawBytes(isCompressed); +} +exports.recoverPublicKey = recoverPublicKey; +function isProbPub(item) { + const arr = item instanceof Uint8Array; + const str = typeof item === 'string'; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === compressedLen * 2 || len === uncompressedLen * 2; + if (item instanceof Point) + return true; + return false; +} +function getSharedSecret(privateA, publicB, isCompressed = false) { + if (isProbPub(privateA)) + throw new TypeError('getSharedSecret: first arg must be private key'); + if (!isProbPub(publicB)) + throw new TypeError('getSharedSecret: second arg must be public key'); + const b = normalizePublicKey(publicB); + b.assertValidity(); + return b.multiply(normalizePrivateKey(privateA)).toRawBytes(isCompressed); +} +exports.getSharedSecret = getSharedSecret; +function bits2int(bytes) { + const slice = bytes.length > fieldLen ? bytes.slice(0, fieldLen) : bytes; + return bytesToNumber(slice); +} +function bits2octets(bytes) { + const z1 = bits2int(bytes); + const z2 = mod(z1, CURVE.n); + return int2octets(z2 < _0n ? z1 : z2); +} +function int2octets(num) { + return numTo32b(num); +} +function initSigArgs(msgHash, privateKey, extraEntropy) { + if (msgHash == null) + throw new Error(`sign: expected valid message hash, not "${msgHash}"`); + const h1 = ensureBytes(msgHash); + const d = normalizePrivateKey(privateKey); + const seedArgs = [int2octets(d), bits2octets(h1)]; + if (extraEntropy != null) { + if (extraEntropy === true) + extraEntropy = exports.utils.randomBytes(fieldLen); + const e = ensureBytes(extraEntropy); + if (e.length !== fieldLen) + throw new Error(`sign: Expected ${fieldLen} bytes of extra data`); + seedArgs.push(e); + } + const seed = concatBytes(...seedArgs); + const m = bits2int(h1); + return { seed, m, d }; +} +function finalizeSig(recSig, opts) { + const { sig, recovery } = recSig; + const { der, recovered } = Object.assign({ canonical: true, der: true }, opts); + const hashed = der ? sig.toDERRawBytes() : sig.toCompactRawBytes(); + return recovered ? [hashed, recovery] : hashed; +} +async function sign(msgHash, privKey, opts = {}) { + const { seed, m, d } = initSigArgs(msgHash, privKey, opts.extraEntropy); + const drbg = new HmacDrbg(hashLen, groupLen); + await drbg.reseed(seed); + let sig; + while (!(sig = kmdToSig(await drbg.generate(), m, d, opts.canonical))) + await drbg.reseed(); + return finalizeSig(sig, opts); +} +exports.sign = sign; +function signSync(msgHash, privKey, opts = {}) { + const { seed, m, d } = initSigArgs(msgHash, privKey, opts.extraEntropy); + const drbg = new HmacDrbg(hashLen, groupLen); + drbg.reseedSync(seed); + let sig; + while (!(sig = kmdToSig(drbg.generateSync(), m, d, opts.canonical))) + drbg.reseedSync(); + return finalizeSig(sig, opts); +} +exports.signSync = signSync; +const vopts = { strict: true }; +function verify(signature, msgHash, publicKey, opts = vopts) { + let sig; + try { + sig = normalizeSignature(signature); + msgHash = ensureBytes(msgHash); + } + catch (error) { + return false; + } + const { r, s } = sig; + if (opts.strict && sig.hasHighS()) + return false; + const h = truncateHash(msgHash); + let P; + try { + P = normalizePublicKey(publicKey); + } + catch (error) { + return false; + } + const { n } = CURVE; + const sinv = invert(s, n); + const u1 = mod(h * sinv, n); + const u2 = mod(r * sinv, n); + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2); + if (!R) + return false; + const v = mod(R.x, n); + return v === r; +} +exports.verify = verify; +function schnorrChallengeFinalize(ch) { + return mod(bytesToNumber(ch), CURVE.n); +} +class SchnorrSignature { + constructor(r, s) { + this.r = r; + this.s = s; + this.assertValidity(); + } + static fromHex(hex) { + const bytes = ensureBytes(hex); + if (bytes.length !== 64) + throw new TypeError(`SchnorrSignature.fromHex: expected 64 bytes, not ${bytes.length}`); + const r = bytesToNumber(bytes.subarray(0, 32)); + const s = bytesToNumber(bytes.subarray(32, 64)); + return new SchnorrSignature(r, s); + } + assertValidity() { + const { r, s } = this; + if (!isValidFieldElement(r) || !isWithinCurveOrder(s)) + throw new Error('Invalid signature'); + } + toHex() { + return numTo32bStr(this.r) + numTo32bStr(this.s); + } + toRawBytes() { + return hexToBytes(this.toHex()); + } +} +function schnorrGetPublicKey(privateKey) { + return Point.fromPrivateKey(privateKey).toRawX(); +} +class InternalSchnorrSignature { + constructor(message, privateKey, auxRand = exports.utils.randomBytes()) { + if (message == null) + throw new TypeError(`sign: Expected valid message, not "${message}"`); + this.m = ensureBytes(message); + const { x, scalar } = this.getScalar(normalizePrivateKey(privateKey)); + this.px = x; + this.d = scalar; + this.rand = ensureBytes(auxRand); + if (this.rand.length !== 32) + throw new TypeError('sign: Expected 32 bytes of aux randomness'); + } + getScalar(priv) { + const point = Point.fromPrivateKey(priv); + const scalar = point.hasEvenY() ? priv : CURVE.n - priv; + return { point, scalar, x: point.toRawX() }; + } + initNonce(d, t0h) { + return numTo32b(d ^ bytesToNumber(t0h)); + } + finalizeNonce(k0h) { + const k0 = mod(bytesToNumber(k0h), CURVE.n); + if (k0 === _0n) + throw new Error('sign: Creation of signature failed. k is zero'); + const { point: R, x: rx, scalar: k } = this.getScalar(k0); + return { R, rx, k }; + } + finalizeSig(R, k, e, d) { + return new SchnorrSignature(R.x, mod(k + e * d, CURVE.n)).toRawBytes(); + } + error() { + throw new Error('sign: Invalid signature produced'); + } + async calc() { + const { m, d, px, rand } = this; + const tag = exports.utils.taggedHash; + const t = this.initNonce(d, await tag(TAGS.aux, rand)); + const { R, rx, k } = this.finalizeNonce(await tag(TAGS.nonce, t, px, m)); + const e = schnorrChallengeFinalize(await tag(TAGS.challenge, rx, px, m)); + const sig = this.finalizeSig(R, k, e, d); + if (!(await schnorrVerify(sig, m, px))) + this.error(); + return sig; + } + calcSync() { + const { m, d, px, rand } = this; + const tag = exports.utils.taggedHashSync; + const t = this.initNonce(d, tag(TAGS.aux, rand)); + const { R, rx, k } = this.finalizeNonce(tag(TAGS.nonce, t, px, m)); + const e = schnorrChallengeFinalize(tag(TAGS.challenge, rx, px, m)); + const sig = this.finalizeSig(R, k, e, d); + if (!schnorrVerifySync(sig, m, px)) + this.error(); + return sig; + } +} +async function schnorrSign(msg, privKey, auxRand) { + return new InternalSchnorrSignature(msg, privKey, auxRand).calc(); +} +function schnorrSignSync(msg, privKey, auxRand) { + return new InternalSchnorrSignature(msg, privKey, auxRand).calcSync(); +} +function initSchnorrVerify(signature, message, publicKey) { + const raw = signature instanceof SchnorrSignature; + const sig = raw ? signature : SchnorrSignature.fromHex(signature); + if (raw) + sig.assertValidity(); + return { + ...sig, + m: ensureBytes(message), + P: normalizePublicKey(publicKey), + }; +} +function finalizeSchnorrVerify(r, P, s, e) { + const R = Point.BASE.multiplyAndAddUnsafe(P, normalizePrivateKey(s), mod(-e, CURVE.n)); + if (!R || !R.hasEvenY() || R.x !== r) + return false; + return true; +} +async function schnorrVerify(signature, message, publicKey) { + try { + const { r, s, m, P } = initSchnorrVerify(signature, message, publicKey); + const e = schnorrChallengeFinalize(await exports.utils.taggedHash(TAGS.challenge, numTo32b(r), P.toRawX(), m)); + return finalizeSchnorrVerify(r, P, s, e); + } + catch (error) { + return false; + } +} +function schnorrVerifySync(signature, message, publicKey) { + try { + const { r, s, m, P } = initSchnorrVerify(signature, message, publicKey); + const e = schnorrChallengeFinalize(exports.utils.taggedHashSync(TAGS.challenge, numTo32b(r), P.toRawX(), m)); + return finalizeSchnorrVerify(r, P, s, e); + } + catch (error) { + if (error instanceof ShaError) + throw error; + return false; + } +} +exports.schnorr = { + Signature: SchnorrSignature, + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + signSync: schnorrSignSync, + verifySync: schnorrVerifySync, +}; +Point.BASE._setWindowSize(8); +const crypto = { + node: nodeCrypto, + web: typeof self === 'object' && 'crypto' in self ? self.crypto : undefined, +}; +const TAGS = { + challenge: 'BIP0340/challenge', + aux: 'BIP0340/aux', + nonce: 'BIP0340/nonce', +}; +const TAGGED_HASH_PREFIXES = {}; +exports.utils = { + bytesToHex, + hexToBytes, + concatBytes, + mod, + invert, + isValidPrivateKey(privateKey) { + try { + normalizePrivateKey(privateKey); + return true; + } + catch (error) { + return false; + } + }, + _bigintTo32Bytes: numTo32b, + _normalizePrivateKey: normalizePrivateKey, + hashToPrivateKey: (hash) => { + hash = ensureBytes(hash); + const minLen = groupLen + 8; + if (hash.length < minLen || hash.length > 1024) { + throw new Error(`Expected valid bytes of private key as per FIPS 186`); + } + const num = mod(bytesToNumber(hash), CURVE.n - _1n) + _1n; + return numTo32b(num); + }, + randomBytes: (bytesLength = 32) => { + if (crypto.web) { + return crypto.web.getRandomValues(new Uint8Array(bytesLength)); + } + else if (crypto.node) { + const { randomBytes } = crypto.node; + return Uint8Array.from(randomBytes(bytesLength)); + } + else { + throw new Error("The environment doesn't have randomBytes function"); + } + }, + randomPrivateKey: () => exports.utils.hashToPrivateKey(exports.utils.randomBytes(groupLen + 8)), + precompute(windowSize = 8, point = Point.BASE) { + const cached = point === Point.BASE ? point : new Point(point.x, point.y); + cached._setWindowSize(windowSize); + cached.multiply(_3n); + return cached; + }, + sha256: async (...messages) => { + if (crypto.web) { + const buffer = await crypto.web.subtle.digest('SHA-256', concatBytes(...messages)); + return new Uint8Array(buffer); + } + else if (crypto.node) { + const { createHash } = crypto.node; + const hash = createHash('sha256'); + messages.forEach((m) => hash.update(m)); + return Uint8Array.from(hash.digest()); + } + else { + throw new Error("The environment doesn't have sha256 function"); + } + }, + hmacSha256: async (key, ...messages) => { + if (crypto.web) { + const ckey = await crypto.web.subtle.importKey('raw', key, { name: 'HMAC', hash: { name: 'SHA-256' } }, false, ['sign']); + const message = concatBytes(...messages); + const buffer = await crypto.web.subtle.sign('HMAC', ckey, message); + return new Uint8Array(buffer); + } + else if (crypto.node) { + const { createHmac } = crypto.node; + const hash = createHmac('sha256', key); + messages.forEach((m) => hash.update(m)); + return Uint8Array.from(hash.digest()); + } + else { + throw new Error("The environment doesn't have hmac-sha256 function"); + } + }, + sha256Sync: undefined, + hmacSha256Sync: undefined, + taggedHash: async (tag, ...messages) => { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = await exports.utils.sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = concatBytes(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return exports.utils.sha256(tagP, ...messages); + }, + taggedHashSync: (tag, ...messages) => { + if (typeof _sha256Sync !== 'function') + throw new ShaError('sha256Sync is undefined, you need to set it'); + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = _sha256Sync(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = concatBytes(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return _sha256Sync(tagP, ...messages); + }, + _JacobianPoint: JacobianPoint, +}; +Object.defineProperties(exports.utils, { + sha256Sync: { + configurable: false, + get() { + return _sha256Sync; + }, + set(val) { + if (!_sha256Sync) + _sha256Sync = val; + }, + }, + hmacSha256Sync: { + configurable: false, + get() { + return _hmacSha256Sync; + }, + set(val) { + if (!_hmacSha256Sync) + _hmacSha256Sync = val; + }, + }, +}); + +},{"crypto":91}],11:[function(require,module,exports){ +'use strict' +// base-x encoding / decoding +// Copyright (c) 2018 base-x contributors +// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) +// Distributed under the MIT software license, see the accompanying +// file LICENSE or http://www.opensource.org/licenses/mit-license.php. +function base (ALPHABET) { + if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') } + var BASE_MAP = new Uint8Array(256) + for (var j = 0; j < BASE_MAP.length; j++) { + BASE_MAP[j] = 255 + } + for (var i = 0; i < ALPHABET.length; i++) { + var x = ALPHABET.charAt(i) + var xc = x.charCodeAt(0) + if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') } + BASE_MAP[xc] = i + } + var BASE = ALPHABET.length + var LEADER = ALPHABET.charAt(0) + var FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up + var iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up + function encode (source) { + if (source instanceof Uint8Array) { + } else if (ArrayBuffer.isView(source)) { + source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength) + } else if (Array.isArray(source)) { + source = Uint8Array.from(source) + } + if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') } + if (source.length === 0) { return '' } + // Skip & count leading zeroes. + var zeroes = 0 + var length = 0 + var pbegin = 0 + var pend = source.length + while (pbegin !== pend && source[pbegin] === 0) { + pbegin++ + zeroes++ + } + // Allocate enough space in big-endian base58 representation. + var size = ((pend - pbegin) * iFACTOR + 1) >>> 0 + var b58 = new Uint8Array(size) + // Process the bytes. + while (pbegin !== pend) { + var carry = source[pbegin] + // Apply "b58 = b58 * 256 + ch". + var i = 0 + for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) { + carry += (256 * b58[it1]) >>> 0 + b58[it1] = (carry % BASE) >>> 0 + carry = (carry / BASE) >>> 0 + } + if (carry !== 0) { throw new Error('Non-zero carry') } + length = i + pbegin++ + } + // Skip leading zeroes in base58 result. + var it2 = size - length + while (it2 !== size && b58[it2] === 0) { + it2++ + } + // Translate the result into a string. + var str = LEADER.repeat(zeroes) + for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) } + return str + } + function decodeUnsafe (source) { + if (typeof source !== 'string') { throw new TypeError('Expected String') } + if (source.length === 0) { return new Uint8Array() } + var psz = 0 + // Skip and count leading '1's. + var zeroes = 0 + var length = 0 + while (source[psz] === LEADER) { + zeroes++ + psz++ + } + // Allocate enough space in big-endian base256 representation. + var size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up. + var b256 = new Uint8Array(size) + // Process the characters. + while (source[psz]) { + // Decode character + var carry = BASE_MAP[source.charCodeAt(psz)] + // Invalid character + if (carry === 255) { return } + var i = 0 + for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) { + carry += (BASE * b256[it3]) >>> 0 + b256[it3] = (carry % 256) >>> 0 + carry = (carry / 256) >>> 0 + } + if (carry !== 0) { throw new Error('Non-zero carry') } + length = i + psz++ + } + // Skip leading zeroes in b256. + var it4 = size - length + while (it4 !== size && b256[it4] === 0) { + it4++ + } + var vch = new Uint8Array(zeroes + (size - it4)) + var j = zeroes + while (it4 !== size) { + vch[j++] = b256[it4++] + } + return vch + } + function decode (string) { + var buffer = decodeUnsafe(string) + if (buffer) { return buffer } + throw new Error('Non-base' + BASE + ' character') + } + return { + encode: encode, + decodeUnsafe: decodeUnsafe, + decode: decode + } +} +module.exports = base + +},{}],12:[function(require,module,exports){ +'use strict'; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bech32m = exports.bech32 = void 0; +const ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; +const ALPHABET_MAP = {}; +for (let z = 0; z < ALPHABET.length; z++) { + const x = ALPHABET.charAt(z); + ALPHABET_MAP[x] = z; +} +function polymodStep(pre) { + const b = pre >> 25; + return (((pre & 0x1ffffff) << 5) ^ + (-((b >> 0) & 1) & 0x3b6a57b2) ^ + (-((b >> 1) & 1) & 0x26508e6d) ^ + (-((b >> 2) & 1) & 0x1ea119fa) ^ + (-((b >> 3) & 1) & 0x3d4233dd) ^ + (-((b >> 4) & 1) & 0x2a1462b3)); +} +function prefixChk(prefix) { + let chk = 1; + for (let i = 0; i < prefix.length; ++i) { + const c = prefix.charCodeAt(i); + if (c < 33 || c > 126) + return 'Invalid prefix (' + prefix + ')'; + chk = polymodStep(chk) ^ (c >> 5); + } + chk = polymodStep(chk); + for (let i = 0; i < prefix.length; ++i) { + const v = prefix.charCodeAt(i); + chk = polymodStep(chk) ^ (v & 0x1f); + } + return chk; +} +function convert(data, inBits, outBits, pad) { + let value = 0; + let bits = 0; + const maxV = (1 << outBits) - 1; + const result = []; + for (let i = 0; i < data.length; ++i) { + value = (value << inBits) | data[i]; + bits += inBits; + while (bits >= outBits) { + bits -= outBits; + result.push((value >> bits) & maxV); + } + } + if (pad) { + if (bits > 0) { + result.push((value << (outBits - bits)) & maxV); + } + } + else { + if (bits >= inBits) + return 'Excess padding'; + if ((value << (outBits - bits)) & maxV) + return 'Non-zero padding'; + } + return result; +} +function toWords(bytes) { + return convert(bytes, 8, 5, true); +} +function fromWordsUnsafe(words) { + const res = convert(words, 5, 8, false); + if (Array.isArray(res)) + return res; +} +function fromWords(words) { + const res = convert(words, 5, 8, false); + if (Array.isArray(res)) + return res; + throw new Error(res); +} +function getLibraryFromEncoding(encoding) { + let ENCODING_CONST; + if (encoding === 'bech32') { + ENCODING_CONST = 1; + } + else { + ENCODING_CONST = 0x2bc830a3; + } + function encode(prefix, words, LIMIT) { + LIMIT = LIMIT || 90; + if (prefix.length + 7 + words.length > LIMIT) + throw new TypeError('Exceeds length limit'); + prefix = prefix.toLowerCase(); + // determine chk mod + let chk = prefixChk(prefix); + if (typeof chk === 'string') + throw new Error(chk); + let result = prefix + '1'; + for (let i = 0; i < words.length; ++i) { + const x = words[i]; + if (x >> 5 !== 0) + throw new Error('Non 5-bit word'); + chk = polymodStep(chk) ^ x; + result += ALPHABET.charAt(x); + } + for (let i = 0; i < 6; ++i) { + chk = polymodStep(chk); + } + chk ^= ENCODING_CONST; + for (let i = 0; i < 6; ++i) { + const v = (chk >> ((5 - i) * 5)) & 0x1f; + result += ALPHABET.charAt(v); + } + return result; + } + function __decode(str, LIMIT) { + LIMIT = LIMIT || 90; + if (str.length < 8) + return str + ' too short'; + if (str.length > LIMIT) + return 'Exceeds length limit'; + // don't allow mixed case + const lowered = str.toLowerCase(); + const uppered = str.toUpperCase(); + if (str !== lowered && str !== uppered) + return 'Mixed-case string ' + str; + str = lowered; + const split = str.lastIndexOf('1'); + if (split === -1) + return 'No separator character for ' + str; + if (split === 0) + return 'Missing prefix for ' + str; + const prefix = str.slice(0, split); + const wordChars = str.slice(split + 1); + if (wordChars.length < 6) + return 'Data too short'; + let chk = prefixChk(prefix); + if (typeof chk === 'string') + return chk; + const words = []; + for (let i = 0; i < wordChars.length; ++i) { + const c = wordChars.charAt(i); + const v = ALPHABET_MAP[c]; + if (v === undefined) + return 'Unknown character ' + c; + chk = polymodStep(chk) ^ v; + // not in the checksum? + if (i + 6 >= wordChars.length) + continue; + words.push(v); + } + if (chk !== ENCODING_CONST) + return 'Invalid checksum for ' + str; + return { prefix, words }; + } + function decodeUnsafe(str, LIMIT) { + const res = __decode(str, LIMIT); + if (typeof res === 'object') + return res; + } + function decode(str, LIMIT) { + const res = __decode(str, LIMIT); + if (typeof res === 'object') + return res; + throw new Error(res); + } + return { + decodeUnsafe, + decode, + encode, + toWords, + fromWordsUnsafe, + fromWords, + }; +} +exports.bech32 = getLibraryFromEncoding('bech32'); +exports.bech32m = getLibraryFromEncoding('bech32m'); + +},{}],13:[function(require,module,exports){ +// (public) Constructor +function BigInteger(a, b, c) { + if (!(this instanceof BigInteger)) + return new BigInteger(a, b, c) + + if (a != null) { + if ("number" == typeof a) this.fromNumber(a, b, c) + else if (b == null && "string" != typeof a) this.fromString(a, 256) + else this.fromString(a, b) + } +} + +var proto = BigInteger.prototype + +// duck-typed isBigInteger +proto.__bigi = require('../package.json').version +BigInteger.isBigInteger = function (obj, check_ver) { + return obj && obj.__bigi && (!check_ver || obj.__bigi === proto.__bigi) +} + +// Bits per digit +var dbits + +// am: Compute w_j += (x*this_i), propagate carries, +// c is initial carry, returns final carry. +// c < 3*dvalue, x < 2*dvalue, this_i < dvalue +// We need to select the fastest one that works in this environment. + +// am1: use a single mult and divide to get the high bits, +// max digit bits should be 26 because +// max internal value = 2*dvalue^2-2*dvalue (< 2^53) +function am1(i, x, w, j, c, n) { + while (--n >= 0) { + var v = x * this[i++] + w[j] + c + c = Math.floor(v / 0x4000000) + w[j++] = v & 0x3ffffff + } + return c +} +// am2 avoids a big mult-and-extract completely. +// Max digit bits should be <= 30 because we do bitwise ops +// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) +function am2(i, x, w, j, c, n) { + var xl = x & 0x7fff, + xh = x >> 15 + while (--n >= 0) { + var l = this[i] & 0x7fff + var h = this[i++] >> 15 + var m = xh * l + h * xl + l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff) + c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30) + w[j++] = l & 0x3fffffff + } + return c +} +// Alternately, set max digit bits to 28 since some +// browsers slow down when dealing with 32-bit numbers. +function am3(i, x, w, j, c, n) { + var xl = x & 0x3fff, + xh = x >> 14 + while (--n >= 0) { + var l = this[i] & 0x3fff + var h = this[i++] >> 14 + var m = xh * l + h * xl + l = xl * l + ((m & 0x3fff) << 14) + w[j] + c + c = (l >> 28) + (m >> 14) + xh * h + w[j++] = l & 0xfffffff + } + return c +} + +// wtf? +BigInteger.prototype.am = am1 +dbits = 26 + +BigInteger.prototype.DB = dbits +BigInteger.prototype.DM = ((1 << dbits) - 1) +var DV = BigInteger.prototype.DV = (1 << dbits) + +var BI_FP = 52 +BigInteger.prototype.FV = Math.pow(2, BI_FP) +BigInteger.prototype.F1 = BI_FP - dbits +BigInteger.prototype.F2 = 2 * dbits - BI_FP + +// Digit conversions +var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz" +var BI_RC = new Array() +var rr, vv +rr = "0".charCodeAt(0) +for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv +rr = "a".charCodeAt(0) +for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv +rr = "A".charCodeAt(0) +for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv + +function int2char(n) { + return BI_RM.charAt(n) +} + +function intAt(s, i) { + var c = BI_RC[s.charCodeAt(i)] + return (c == null) ? -1 : c +} + +// (protected) copy this to r +function bnpCopyTo(r) { + for (var i = this.t - 1; i >= 0; --i) r[i] = this[i] + r.t = this.t + r.s = this.s +} + +// (protected) set from integer value x, -DV <= x < DV +function bnpFromInt(x) { + this.t = 1 + this.s = (x < 0) ? -1 : 0 + if (x > 0) this[0] = x + else if (x < -1) this[0] = x + DV + else this.t = 0 +} + +// return bigint initialized to value +function nbv(i) { + var r = new BigInteger() + r.fromInt(i) + return r +} + +// (protected) set from string and radix +function bnpFromString(s, b) { + var self = this + + var k + if (b == 16) k = 4 + else if (b == 8) k = 3 + else if (b == 256) k = 8; // byte array + else if (b == 2) k = 1 + else if (b == 32) k = 5 + else if (b == 4) k = 2 + else { + self.fromRadix(s, b) + return + } + self.t = 0 + self.s = 0 + var i = s.length, + mi = false, + sh = 0 + while (--i >= 0) { + var x = (k == 8) ? s[i] & 0xff : intAt(s, i) + if (x < 0) { + if (s.charAt(i) == "-") mi = true + continue + } + mi = false + if (sh == 0) + self[self.t++] = x + else if (sh + k > self.DB) { + self[self.t - 1] |= (x & ((1 << (self.DB - sh)) - 1)) << sh + self[self.t++] = (x >> (self.DB - sh)) + } else + self[self.t - 1] |= x << sh + sh += k + if (sh >= self.DB) sh -= self.DB + } + if (k == 8 && (s[0] & 0x80) != 0) { + self.s = -1 + if (sh > 0) self[self.t - 1] |= ((1 << (self.DB - sh)) - 1) << sh + } + self.clamp() + if (mi) BigInteger.ZERO.subTo(self, self) +} + +// (protected) clamp off excess high words +function bnpClamp() { + var c = this.s & this.DM + while (this.t > 0 && this[this.t - 1] == c)--this.t +} + +// (public) return string representation in given radix +function bnToString(b) { + var self = this + if (self.s < 0) return "-" + self.negate() + .toString(b) + var k + if (b == 16) k = 4 + else if (b == 8) k = 3 + else if (b == 2) k = 1 + else if (b == 32) k = 5 + else if (b == 4) k = 2 + else return self.toRadix(b) + var km = (1 << k) - 1, + d, m = false, + r = "", + i = self.t + var p = self.DB - (i * self.DB) % k + if (i-- > 0) { + if (p < self.DB && (d = self[i] >> p) > 0) { + m = true + r = int2char(d) + } + while (i >= 0) { + if (p < k) { + d = (self[i] & ((1 << p) - 1)) << (k - p) + d |= self[--i] >> (p += self.DB - k) + } else { + d = (self[i] >> (p -= k)) & km + if (p <= 0) { + p += self.DB + --i + } + } + if (d > 0) m = true + if (m) r += int2char(d) + } + } + return m ? r : "0" +} + +// (public) -this +function bnNegate() { + var r = new BigInteger() + BigInteger.ZERO.subTo(this, r) + return r +} + +// (public) |this| +function bnAbs() { + return (this.s < 0) ? this.negate() : this +} + +// (public) return + if this > a, - if this < a, 0 if equal +function bnCompareTo(a) { + var r = this.s - a.s + if (r != 0) return r + var i = this.t + r = i - a.t + if (r != 0) return (this.s < 0) ? -r : r + while (--i >= 0) + if ((r = this[i] - a[i]) != 0) return r + return 0 +} + +// returns bit length of the integer x +function nbits(x) { + var r = 1, + t + if ((t = x >>> 16) != 0) { + x = t + r += 16 + } + if ((t = x >> 8) != 0) { + x = t + r += 8 + } + if ((t = x >> 4) != 0) { + x = t + r += 4 + } + if ((t = x >> 2) != 0) { + x = t + r += 2 + } + if ((t = x >> 1) != 0) { + x = t + r += 1 + } + return r +} + +// (public) return the number of bits in "this" +function bnBitLength() { + if (this.t <= 0) return 0 + return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)) +} + +// (public) return the number of bytes in "this" +function bnByteLength() { + return this.bitLength() >> 3 +} + +// (protected) r = this << n*DB +function bnpDLShiftTo(n, r) { + var i + for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i] + for (i = n - 1; i >= 0; --i) r[i] = 0 + r.t = this.t + n + r.s = this.s +} + +// (protected) r = this >> n*DB +function bnpDRShiftTo(n, r) { + for (var i = n; i < this.t; ++i) r[i - n] = this[i] + r.t = Math.max(this.t - n, 0) + r.s = this.s +} + +// (protected) r = this << n +function bnpLShiftTo(n, r) { + var self = this + var bs = n % self.DB + var cbs = self.DB - bs + var bm = (1 << cbs) - 1 + var ds = Math.floor(n / self.DB), + c = (self.s << bs) & self.DM, + i + for (i = self.t - 1; i >= 0; --i) { + r[i + ds + 1] = (self[i] >> cbs) | c + c = (self[i] & bm) << bs + } + for (i = ds - 1; i >= 0; --i) r[i] = 0 + r[ds] = c + r.t = self.t + ds + 1 + r.s = self.s + r.clamp() +} + +// (protected) r = this >> n +function bnpRShiftTo(n, r) { + var self = this + r.s = self.s + var ds = Math.floor(n / self.DB) + if (ds >= self.t) { + r.t = 0 + return + } + var bs = n % self.DB + var cbs = self.DB - bs + var bm = (1 << bs) - 1 + r[0] = self[ds] >> bs + for (var i = ds + 1; i < self.t; ++i) { + r[i - ds - 1] |= (self[i] & bm) << cbs + r[i - ds] = self[i] >> bs + } + if (bs > 0) r[self.t - ds - 1] |= (self.s & bm) << cbs + r.t = self.t - ds + r.clamp() +} + +// (protected) r = this - a +function bnpSubTo(a, r) { + var self = this + var i = 0, + c = 0, + m = Math.min(a.t, self.t) + while (i < m) { + c += self[i] - a[i] + r[i++] = c & self.DM + c >>= self.DB + } + if (a.t < self.t) { + c -= a.s + while (i < self.t) { + c += self[i] + r[i++] = c & self.DM + c >>= self.DB + } + c += self.s + } else { + c += self.s + while (i < a.t) { + c -= a[i] + r[i++] = c & self.DM + c >>= self.DB + } + c -= a.s + } + r.s = (c < 0) ? -1 : 0 + if (c < -1) r[i++] = self.DV + c + else if (c > 0) r[i++] = c + r.t = i + r.clamp() +} + +// (protected) r = this * a, r != this,a (HAC 14.12) +// "this" should be the larger one if appropriate. +function bnpMultiplyTo(a, r) { + var x = this.abs(), + y = a.abs() + var i = x.t + r.t = i + y.t + while (--i >= 0) r[i] = 0 + for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t) + r.s = 0 + r.clamp() + if (this.s != a.s) BigInteger.ZERO.subTo(r, r) +} + +// (protected) r = this^2, r != this (HAC 14.16) +function bnpSquareTo(r) { + var x = this.abs() + var i = r.t = 2 * x.t + while (--i >= 0) r[i] = 0 + for (i = 0; i < x.t - 1; ++i) { + var c = x.am(i, x[i], r, 2 * i, 0, 1) + if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { + r[i + x.t] -= x.DV + r[i + x.t + 1] = 1 + } + } + if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1) + r.s = 0 + r.clamp() +} + +// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) +// r != q, this != m. q or r may be null. +function bnpDivRemTo(m, q, r) { + var self = this + var pm = m.abs() + if (pm.t <= 0) return + var pt = self.abs() + if (pt.t < pm.t) { + if (q != null) q.fromInt(0) + if (r != null) self.copyTo(r) + return + } + if (r == null) r = new BigInteger() + var y = new BigInteger(), + ts = self.s, + ms = m.s + var nsh = self.DB - nbits(pm[pm.t - 1]); // normalize modulus + if (nsh > 0) { + pm.lShiftTo(nsh, y) + pt.lShiftTo(nsh, r) + } else { + pm.copyTo(y) + pt.copyTo(r) + } + var ys = y.t + var y0 = y[ys - 1] + if (y0 == 0) return + var yt = y0 * (1 << self.F1) + ((ys > 1) ? y[ys - 2] >> self.F2 : 0) + var d1 = self.FV / yt, + d2 = (1 << self.F1) / yt, + e = 1 << self.F2 + var i = r.t, + j = i - ys, + t = (q == null) ? new BigInteger() : q + y.dlShiftTo(j, t) + if (r.compareTo(t) >= 0) { + r[r.t++] = 1 + r.subTo(t, r) + } + BigInteger.ONE.dlShiftTo(ys, t) + t.subTo(y, y); // "negative" y so we can replace sub with am later + while (y.t < ys) y[y.t++] = 0 + while (--j >= 0) { + // Estimate quotient digit + var qd = (r[--i] == y0) ? self.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2) + if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out + y.dlShiftTo(j, t) + r.subTo(t, r) + while (r[i] < --qd) r.subTo(t, r) + } + } + if (q != null) { + r.drShiftTo(ys, q) + if (ts != ms) BigInteger.ZERO.subTo(q, q) + } + r.t = ys + r.clamp() + if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder + if (ts < 0) BigInteger.ZERO.subTo(r, r) +} + +// (public) this mod a +function bnMod(a) { + var r = new BigInteger() + this.abs() + .divRemTo(a, null, r) + if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r) + return r +} + +// Modular reduction using "classic" algorithm +function Classic(m) { + this.m = m +} + +function cConvert(x) { + if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m) + else return x +} + +function cRevert(x) { + return x +} + +function cReduce(x) { + x.divRemTo(this.m, null, x) +} + +function cMulTo(x, y, r) { + x.multiplyTo(y, r) + this.reduce(r) +} + +function cSqrTo(x, r) { + x.squareTo(r) + this.reduce(r) +} + +Classic.prototype.convert = cConvert +Classic.prototype.revert = cRevert +Classic.prototype.reduce = cReduce +Classic.prototype.mulTo = cMulTo +Classic.prototype.sqrTo = cSqrTo + +// (protected) return "-1/this % 2^DB"; useful for Mont. reduction +// justification: +// xy == 1 (mod m) +// xy = 1+km +// xy(2-xy) = (1+km)(1-km) +// x[y(2-xy)] = 1-k^2m^2 +// x[y(2-xy)] == 1 (mod m^2) +// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 +// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. +// JS multiply "overflows" differently from C/C++, so care is needed here. +function bnpInvDigit() { + if (this.t < 1) return 0 + var x = this[0] + if ((x & 1) == 0) return 0 + var y = x & 3; // y == 1/x mod 2^2 + y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 + y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 + y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 + // last step - calculate inverse mod DV directly + // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints + y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits + // we really want the negative inverse, and -DV < y < DV + return (y > 0) ? this.DV - y : -y +} + +// Montgomery reduction +function Montgomery(m) { + this.m = m + this.mp = m.invDigit() + this.mpl = this.mp & 0x7fff + this.mph = this.mp >> 15 + this.um = (1 << (m.DB - 15)) - 1 + this.mt2 = 2 * m.t +} + +// xR mod m +function montConvert(x) { + var r = new BigInteger() + x.abs() + .dlShiftTo(this.m.t, r) + r.divRemTo(this.m, null, r) + if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r) + return r +} + +// x/R mod m +function montRevert(x) { + var r = new BigInteger() + x.copyTo(r) + this.reduce(r) + return r +} + +// x = x/R mod m (HAC 14.32) +function montReduce(x) { + while (x.t <= this.mt2) // pad x so am has enough room later + x[x.t++] = 0 + for (var i = 0; i < this.m.t; ++i) { + // faster way of calculating u0 = x[i]*mp mod DV + var j = x[i] & 0x7fff + var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM + // use am to combine the multiply-shift-add into one call + j = i + this.m.t + x[j] += this.m.am(0, u0, x, i, 0, this.m.t) + // propagate carry + while (x[j] >= x.DV) { + x[j] -= x.DV + x[++j]++ + } + } + x.clamp() + x.drShiftTo(this.m.t, x) + if (x.compareTo(this.m) >= 0) x.subTo(this.m, x) +} + +// r = "x^2/R mod m"; x != r +function montSqrTo(x, r) { + x.squareTo(r) + this.reduce(r) +} + +// r = "xy/R mod m"; x,y != r +function montMulTo(x, y, r) { + x.multiplyTo(y, r) + this.reduce(r) +} + +Montgomery.prototype.convert = montConvert +Montgomery.prototype.revert = montRevert +Montgomery.prototype.reduce = montReduce +Montgomery.prototype.mulTo = montMulTo +Montgomery.prototype.sqrTo = montSqrTo + +// (protected) true iff this is even +function bnpIsEven() { + return ((this.t > 0) ? (this[0] & 1) : this.s) == 0 +} + +// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) +function bnpExp(e, z) { + if (e > 0xffffffff || e < 1) return BigInteger.ONE + var r = new BigInteger(), + r2 = new BigInteger(), + g = z.convert(this), + i = nbits(e) - 1 + g.copyTo(r) + while (--i >= 0) { + z.sqrTo(r, r2) + if ((e & (1 << i)) > 0) z.mulTo(r2, g, r) + else { + var t = r + r = r2 + r2 = t + } + } + return z.revert(r) +} + +// (public) this^e % m, 0 <= e < 2^32 +function bnModPowInt(e, m) { + var z + if (e < 256 || m.isEven()) z = new Classic(m) + else z = new Montgomery(m) + return this.exp(e, z) +} + +// protected +proto.copyTo = bnpCopyTo +proto.fromInt = bnpFromInt +proto.fromString = bnpFromString +proto.clamp = bnpClamp +proto.dlShiftTo = bnpDLShiftTo +proto.drShiftTo = bnpDRShiftTo +proto.lShiftTo = bnpLShiftTo +proto.rShiftTo = bnpRShiftTo +proto.subTo = bnpSubTo +proto.multiplyTo = bnpMultiplyTo +proto.squareTo = bnpSquareTo +proto.divRemTo = bnpDivRemTo +proto.invDigit = bnpInvDigit +proto.isEven = bnpIsEven +proto.exp = bnpExp + +// public +proto.toString = bnToString +proto.negate = bnNegate +proto.abs = bnAbs +proto.compareTo = bnCompareTo +proto.bitLength = bnBitLength +proto.byteLength = bnByteLength +proto.mod = bnMod +proto.modPowInt = bnModPowInt + +// (public) +function bnClone() { + var r = new BigInteger() + this.copyTo(r) + return r +} + +// (public) return value as integer +function bnIntValue() { + if (this.s < 0) { + if (this.t == 1) return this[0] - this.DV + else if (this.t == 0) return -1 + } else if (this.t == 1) return this[0] + else if (this.t == 0) return 0 + // assumes 16 < DB < 32 + return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0] +} + +// (public) return value as byte +function bnByteValue() { + return (this.t == 0) ? this.s : (this[0] << 24) >> 24 +} + +// (public) return value as short (assumes DB>=16) +function bnShortValue() { + return (this.t == 0) ? this.s : (this[0] << 16) >> 16 +} + +// (protected) return x s.t. r^x < DV +function bnpChunkSize(r) { + return Math.floor(Math.LN2 * this.DB / Math.log(r)) +} + +// (public) 0 if this == 0, 1 if this > 0 +function bnSigNum() { + if (this.s < 0) return -1 + else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0 + else return 1 +} + +// (protected) convert to radix string +function bnpToRadix(b) { + if (b == null) b = 10 + if (this.signum() == 0 || b < 2 || b > 36) return "0" + var cs = this.chunkSize(b) + var a = Math.pow(b, cs) + var d = nbv(a), + y = new BigInteger(), + z = new BigInteger(), + r = "" + this.divRemTo(d, y, z) + while (y.signum() > 0) { + r = (a + z.intValue()) + .toString(b) + .substr(1) + r + y.divRemTo(d, y, z) + } + return z.intValue() + .toString(b) + r +} + +// (protected) convert from radix string +function bnpFromRadix(s, b) { + var self = this + self.fromInt(0) + if (b == null) b = 10 + var cs = self.chunkSize(b) + var d = Math.pow(b, cs), + mi = false, + j = 0, + w = 0 + for (var i = 0; i < s.length; ++i) { + var x = intAt(s, i) + if (x < 0) { + if (s.charAt(i) == "-" && self.signum() == 0) mi = true + continue + } + w = b * w + x + if (++j >= cs) { + self.dMultiply(d) + self.dAddOffset(w, 0) + j = 0 + w = 0 + } + } + if (j > 0) { + self.dMultiply(Math.pow(b, j)) + self.dAddOffset(w, 0) + } + if (mi) BigInteger.ZERO.subTo(self, self) +} + +// (protected) alternate constructor +function bnpFromNumber(a, b, c) { + var self = this + if ("number" == typeof b) { + // new BigInteger(int,int,RNG) + if (a < 2) self.fromInt(1) + else { + self.fromNumber(a, c) + if (!self.testBit(a - 1)) // force MSB set + self.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, self) + if (self.isEven()) self.dAddOffset(1, 0); // force odd + while (!self.isProbablePrime(b)) { + self.dAddOffset(2, 0) + if (self.bitLength() > a) self.subTo(BigInteger.ONE.shiftLeft(a - 1), self) + } + } + } else { + // new BigInteger(int,RNG) + var x = new Array(), + t = a & 7 + x.length = (a >> 3) + 1 + b.nextBytes(x) + if (t > 0) x[0] &= ((1 << t) - 1) + else x[0] = 0 + self.fromString(x, 256) + } +} + +// (public) convert to bigendian byte array +function bnToByteArray() { + var self = this + var i = self.t, + r = new Array() + r[0] = self.s + var p = self.DB - (i * self.DB) % 8, + d, k = 0 + if (i-- > 0) { + if (p < self.DB && (d = self[i] >> p) != (self.s & self.DM) >> p) + r[k++] = d | (self.s << (self.DB - p)) + while (i >= 0) { + if (p < 8) { + d = (self[i] & ((1 << p) - 1)) << (8 - p) + d |= self[--i] >> (p += self.DB - 8) + } else { + d = (self[i] >> (p -= 8)) & 0xff + if (p <= 0) { + p += self.DB + --i + } + } + if ((d & 0x80) != 0) d |= -256 + if (k === 0 && (self.s & 0x80) != (d & 0x80))++k + if (k > 0 || d != self.s) r[k++] = d + } + } + return r +} + +function bnEquals(a) { + return (this.compareTo(a) == 0) +} + +function bnMin(a) { + return (this.compareTo(a) < 0) ? this : a +} + +function bnMax(a) { + return (this.compareTo(a) > 0) ? this : a +} + +// (protected) r = this op a (bitwise) +function bnpBitwiseTo(a, op, r) { + var self = this + var i, f, m = Math.min(a.t, self.t) + for (i = 0; i < m; ++i) r[i] = op(self[i], a[i]) + if (a.t < self.t) { + f = a.s & self.DM + for (i = m; i < self.t; ++i) r[i] = op(self[i], f) + r.t = self.t + } else { + f = self.s & self.DM + for (i = m; i < a.t; ++i) r[i] = op(f, a[i]) + r.t = a.t + } + r.s = op(self.s, a.s) + r.clamp() +} + +// (public) this & a +function op_and(x, y) { + return x & y +} + +function bnAnd(a) { + var r = new BigInteger() + this.bitwiseTo(a, op_and, r) + return r +} + +// (public) this | a +function op_or(x, y) { + return x | y +} + +function bnOr(a) { + var r = new BigInteger() + this.bitwiseTo(a, op_or, r) + return r +} + +// (public) this ^ a +function op_xor(x, y) { + return x ^ y +} + +function bnXor(a) { + var r = new BigInteger() + this.bitwiseTo(a, op_xor, r) + return r +} + +// (public) this & ~a +function op_andnot(x, y) { + return x & ~y +} + +function bnAndNot(a) { + var r = new BigInteger() + this.bitwiseTo(a, op_andnot, r) + return r +} + +// (public) ~this +function bnNot() { + var r = new BigInteger() + for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i] + r.t = this.t + r.s = ~this.s + return r +} + +// (public) this << n +function bnShiftLeft(n) { + var r = new BigInteger() + if (n < 0) this.rShiftTo(-n, r) + else this.lShiftTo(n, r) + return r +} + +// (public) this >> n +function bnShiftRight(n) { + var r = new BigInteger() + if (n < 0) this.lShiftTo(-n, r) + else this.rShiftTo(n, r) + return r +} + +// return index of lowest 1-bit in x, x < 2^31 +function lbit(x) { + if (x == 0) return -1 + var r = 0 + if ((x & 0xffff) == 0) { + x >>= 16 + r += 16 + } + if ((x & 0xff) == 0) { + x >>= 8 + r += 8 + } + if ((x & 0xf) == 0) { + x >>= 4 + r += 4 + } + if ((x & 3) == 0) { + x >>= 2 + r += 2 + } + if ((x & 1) == 0)++r + return r +} + +// (public) returns index of lowest 1-bit (or -1 if none) +function bnGetLowestSetBit() { + for (var i = 0; i < this.t; ++i) + if (this[i] != 0) return i * this.DB + lbit(this[i]) + if (this.s < 0) return this.t * this.DB + return -1 +} + +// return number of 1 bits in x +function cbit(x) { + var r = 0 + while (x != 0) { + x &= x - 1 + ++r + } + return r +} + +// (public) return number of set bits +function bnBitCount() { + var r = 0, + x = this.s & this.DM + for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x) + return r +} + +// (public) true iff nth bit is set +function bnTestBit(n) { + var j = Math.floor(n / this.DB) + if (j >= this.t) return (this.s != 0) + return ((this[j] & (1 << (n % this.DB))) != 0) +} + +// (protected) this op (1<>= self.DB + } + if (a.t < self.t) { + c += a.s + while (i < self.t) { + c += self[i] + r[i++] = c & self.DM + c >>= self.DB + } + c += self.s + } else { + c += self.s + while (i < a.t) { + c += a[i] + r[i++] = c & self.DM + c >>= self.DB + } + c += a.s + } + r.s = (c < 0) ? -1 : 0 + if (c > 0) r[i++] = c + else if (c < -1) r[i++] = self.DV + c + r.t = i + r.clamp() +} + +// (public) this + a +function bnAdd(a) { + var r = new BigInteger() + this.addTo(a, r) + return r +} + +// (public) this - a +function bnSubtract(a) { + var r = new BigInteger() + this.subTo(a, r) + return r +} + +// (public) this * a +function bnMultiply(a) { + var r = new BigInteger() + this.multiplyTo(a, r) + return r +} + +// (public) this^2 +function bnSquare() { + var r = new BigInteger() + this.squareTo(r) + return r +} + +// (public) this / a +function bnDivide(a) { + var r = new BigInteger() + this.divRemTo(a, r, null) + return r +} + +// (public) this % a +function bnRemainder(a) { + var r = new BigInteger() + this.divRemTo(a, null, r) + return r +} + +// (public) [this/a,this%a] +function bnDivideAndRemainder(a) { + var q = new BigInteger(), + r = new BigInteger() + this.divRemTo(a, q, r) + return new Array(q, r) +} + +// (protected) this *= n, this >= 0, 1 < n < DV +function bnpDMultiply(n) { + this[this.t] = this.am(0, n - 1, this, 0, 0, this.t) + ++this.t + this.clamp() +} + +// (protected) this += n << w words, this >= 0 +function bnpDAddOffset(n, w) { + if (n == 0) return + while (this.t <= w) this[this.t++] = 0 + this[w] += n + while (this[w] >= this.DV) { + this[w] -= this.DV + if (++w >= this.t) this[this.t++] = 0 + ++this[w] + } +} + +// A "null" reducer +function NullExp() {} + +function nNop(x) { + return x +} + +function nMulTo(x, y, r) { + x.multiplyTo(y, r) +} + +function nSqrTo(x, r) { + x.squareTo(r) +} + +NullExp.prototype.convert = nNop +NullExp.prototype.revert = nNop +NullExp.prototype.mulTo = nMulTo +NullExp.prototype.sqrTo = nSqrTo + +// (public) this^e +function bnPow(e) { + return this.exp(e, new NullExp()) +} + +// (protected) r = lower n words of "this * a", a.t <= n +// "this" should be the larger one if appropriate. +function bnpMultiplyLowerTo(a, n, r) { + var i = Math.min(this.t + a.t, n) + r.s = 0; // assumes a,this >= 0 + r.t = i + while (i > 0) r[--i] = 0 + var j + for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t) + for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i) + r.clamp() +} + +// (protected) r = "this * a" without lower n words, n > 0 +// "this" should be the larger one if appropriate. +function bnpMultiplyUpperTo(a, n, r) { + --n + var i = r.t = this.t + a.t - n + r.s = 0; // assumes a,this >= 0 + while (--i >= 0) r[i] = 0 + for (i = Math.max(n - this.t, 0); i < a.t; ++i) + r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n) + r.clamp() + r.drShiftTo(1, r) +} + +// Barrett modular reduction +function Barrett(m) { + // setup Barrett + this.r2 = new BigInteger() + this.q3 = new BigInteger() + BigInteger.ONE.dlShiftTo(2 * m.t, this.r2) + this.mu = this.r2.divide(m) + this.m = m +} + +function barrettConvert(x) { + if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m) + else if (x.compareTo(this.m) < 0) return x + else { + var r = new BigInteger() + x.copyTo(r) + this.reduce(r) + return r + } +} + +function barrettRevert(x) { + return x +} + +// x = x mod m (HAC 14.42) +function barrettReduce(x) { + var self = this + x.drShiftTo(self.m.t - 1, self.r2) + if (x.t > self.m.t + 1) { + x.t = self.m.t + 1 + x.clamp() + } + self.mu.multiplyUpperTo(self.r2, self.m.t + 1, self.q3) + self.m.multiplyLowerTo(self.q3, self.m.t + 1, self.r2) + while (x.compareTo(self.r2) < 0) x.dAddOffset(1, self.m.t + 1) + x.subTo(self.r2, x) + while (x.compareTo(self.m) >= 0) x.subTo(self.m, x) +} + +// r = x^2 mod m; x != r +function barrettSqrTo(x, r) { + x.squareTo(r) + this.reduce(r) +} + +// r = x*y mod m; x,y != r +function barrettMulTo(x, y, r) { + x.multiplyTo(y, r) + this.reduce(r) +} + +Barrett.prototype.convert = barrettConvert +Barrett.prototype.revert = barrettRevert +Barrett.prototype.reduce = barrettReduce +Barrett.prototype.mulTo = barrettMulTo +Barrett.prototype.sqrTo = barrettSqrTo + +// (public) this^e % m (HAC 14.85) +function bnModPow(e, m) { + var i = e.bitLength(), + k, r = nbv(1), + z + if (i <= 0) return r + else if (i < 18) k = 1 + else if (i < 48) k = 3 + else if (i < 144) k = 4 + else if (i < 768) k = 5 + else k = 6 + if (i < 8) + z = new Classic(m) + else if (m.isEven()) + z = new Barrett(m) + else + z = new Montgomery(m) + + // precomputation + var g = new Array(), + n = 3, + k1 = k - 1, + km = (1 << k) - 1 + g[1] = z.convert(this) + if (k > 1) { + var g2 = new BigInteger() + z.sqrTo(g[1], g2) + while (n <= km) { + g[n] = new BigInteger() + z.mulTo(g2, g[n - 2], g[n]) + n += 2 + } + } + + var j = e.t - 1, + w, is1 = true, + r2 = new BigInteger(), + t + i = nbits(e[j]) - 1 + while (j >= 0) { + if (i >= k1) w = (e[j] >> (i - k1)) & km + else { + w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i) + if (j > 0) w |= e[j - 1] >> (this.DB + i - k1) + } + + n = k + while ((w & 1) == 0) { + w >>= 1 + --n + } + if ((i -= n) < 0) { + i += this.DB + --j + } + if (is1) { // ret == 1, don't bother squaring or multiplying it + g[w].copyTo(r) + is1 = false + } else { + while (n > 1) { + z.sqrTo(r, r2) + z.sqrTo(r2, r) + n -= 2 + } + if (n > 0) z.sqrTo(r, r2) + else { + t = r + r = r2 + r2 = t + } + z.mulTo(r2, g[w], r) + } + + while (j >= 0 && (e[j] & (1 << i)) == 0) { + z.sqrTo(r, r2) + t = r + r = r2 + r2 = t + if (--i < 0) { + i = this.DB - 1 + --j + } + } + } + return z.revert(r) +} + +// (public) gcd(this,a) (HAC 14.54) +function bnGCD(a) { + var x = (this.s < 0) ? this.negate() : this.clone() + var y = (a.s < 0) ? a.negate() : a.clone() + if (x.compareTo(y) < 0) { + var t = x + x = y + y = t + } + var i = x.getLowestSetBit(), + g = y.getLowestSetBit() + if (g < 0) return x + if (i < g) g = i + if (g > 0) { + x.rShiftTo(g, x) + y.rShiftTo(g, y) + } + while (x.signum() > 0) { + if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x) + if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y) + if (x.compareTo(y) >= 0) { + x.subTo(y, x) + x.rShiftTo(1, x) + } else { + y.subTo(x, y) + y.rShiftTo(1, y) + } + } + if (g > 0) y.lShiftTo(g, y) + return y +} + +// (protected) this % n, n < 2^26 +function bnpModInt(n) { + if (n <= 0) return 0 + var d = this.DV % n, + r = (this.s < 0) ? n - 1 : 0 + if (this.t > 0) + if (d == 0) r = this[0] % n + else + for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n + return r +} + +// (public) 1/this % m (HAC 14.61) +function bnModInverse(m) { + var ac = m.isEven() + if (this.signum() === 0) throw new Error('division by zero') + if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO + var u = m.clone(), + v = this.clone() + var a = nbv(1), + b = nbv(0), + c = nbv(0), + d = nbv(1) + while (u.signum() != 0) { + while (u.isEven()) { + u.rShiftTo(1, u) + if (ac) { + if (!a.isEven() || !b.isEven()) { + a.addTo(this, a) + b.subTo(m, b) + } + a.rShiftTo(1, a) + } else if (!b.isEven()) b.subTo(m, b) + b.rShiftTo(1, b) + } + while (v.isEven()) { + v.rShiftTo(1, v) + if (ac) { + if (!c.isEven() || !d.isEven()) { + c.addTo(this, c) + d.subTo(m, d) + } + c.rShiftTo(1, c) + } else if (!d.isEven()) d.subTo(m, d) + d.rShiftTo(1, d) + } + if (u.compareTo(v) >= 0) { + u.subTo(v, u) + if (ac) a.subTo(c, a) + b.subTo(d, b) + } else { + v.subTo(u, v) + if (ac) c.subTo(a, c) + d.subTo(b, d) + } + } + if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO + while (d.compareTo(m) >= 0) d.subTo(m, d) + while (d.signum() < 0) d.addTo(m, d) + return d +} + +var lowprimes = [ + 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, + 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, + 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, + 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, + 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, + 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, + 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, + 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, + 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, + 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, + 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 +] + +var lplim = (1 << 26) / lowprimes[lowprimes.length - 1] + +// (public) test primality with certainty >= 1-.5^t +function bnIsProbablePrime(t) { + var i, x = this.abs() + if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { + for (i = 0; i < lowprimes.length; ++i) + if (x[0] == lowprimes[i]) return true + return false + } + if (x.isEven()) return false + i = 1 + while (i < lowprimes.length) { + var m = lowprimes[i], + j = i + 1 + while (j < lowprimes.length && m < lplim) m *= lowprimes[j++] + m = x.modInt(m) + while (i < j) if (m % lowprimes[i++] == 0) return false + } + return x.millerRabin(t) +} + +// (protected) true if probably prime (HAC 4.24, Miller-Rabin) +function bnpMillerRabin(t) { + var n1 = this.subtract(BigInteger.ONE) + var k = n1.getLowestSetBit() + if (k <= 0) return false + var r = n1.shiftRight(k) + t = (t + 1) >> 1 + if (t > lowprimes.length) t = lowprimes.length + var a = new BigInteger(null) + var j, bases = [] + for (var i = 0; i < t; ++i) { + for (;;) { + j = lowprimes[Math.floor(Math.random() * lowprimes.length)] + if (bases.indexOf(j) == -1) break + } + bases.push(j) + a.fromInt(j) + var y = a.modPow(r, this) + if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1 + while (j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2, this) + if (y.compareTo(BigInteger.ONE) == 0) return false + } + if (y.compareTo(n1) != 0) return false + } + } + return true +} + +// protected +proto.chunkSize = bnpChunkSize +proto.toRadix = bnpToRadix +proto.fromRadix = bnpFromRadix +proto.fromNumber = bnpFromNumber +proto.bitwiseTo = bnpBitwiseTo +proto.changeBit = bnpChangeBit +proto.addTo = bnpAddTo +proto.dMultiply = bnpDMultiply +proto.dAddOffset = bnpDAddOffset +proto.multiplyLowerTo = bnpMultiplyLowerTo +proto.multiplyUpperTo = bnpMultiplyUpperTo +proto.modInt = bnpModInt +proto.millerRabin = bnpMillerRabin + +// public +proto.clone = bnClone +proto.intValue = bnIntValue +proto.byteValue = bnByteValue +proto.shortValue = bnShortValue +proto.signum = bnSigNum +proto.toByteArray = bnToByteArray +proto.equals = bnEquals +proto.min = bnMin +proto.max = bnMax +proto.and = bnAnd +proto.or = bnOr +proto.xor = bnXor +proto.andNot = bnAndNot +proto.not = bnNot +proto.shiftLeft = bnShiftLeft +proto.shiftRight = bnShiftRight +proto.getLowestSetBit = bnGetLowestSetBit +proto.bitCount = bnBitCount +proto.testBit = bnTestBit +proto.setBit = bnSetBit +proto.clearBit = bnClearBit +proto.flipBit = bnFlipBit +proto.add = bnAdd +proto.subtract = bnSubtract +proto.multiply = bnMultiply +proto.divide = bnDivide +proto.remainder = bnRemainder +proto.divideAndRemainder = bnDivideAndRemainder +proto.modPow = bnModPow +proto.modInverse = bnModInverse +proto.pow = bnPow +proto.gcd = bnGCD +proto.isProbablePrime = bnIsProbablePrime + +// JSBN-specific extension +proto.square = bnSquare + +// constants +BigInteger.ZERO = nbv(0) +BigInteger.ONE = nbv(1) +BigInteger.valueOf = nbv + +module.exports = BigInteger + +},{"../package.json":16}],14:[function(require,module,exports){ +(function (Buffer){(function (){ +// FIXME: Kind of a weird way to throw exceptions, consider removing +var assert = require('assert') +var BigInteger = require('./bigi') + +/** + * Turns a byte array into a big integer. + * + * This function will interpret a byte array as a big integer in big + * endian notation. + */ +BigInteger.fromByteArrayUnsigned = function(byteArray) { + // BigInteger expects a DER integer conformant byte array + if (byteArray[0] & 0x80) { + return new BigInteger([0].concat(byteArray)) + } + + return new BigInteger(byteArray) +} + +/** + * Returns a byte array representation of the big integer. + * + * This returns the absolute of the contained value in big endian + * form. A value of zero results in an empty array. + */ +BigInteger.prototype.toByteArrayUnsigned = function() { + var byteArray = this.toByteArray() + return byteArray[0] === 0 ? byteArray.slice(1) : byteArray +} + +BigInteger.fromDERInteger = function(byteArray) { + return new BigInteger(byteArray) +} + +/* + * Converts BigInteger to a DER integer representation. + * + * The format for this value uses the most significant bit as a sign + * bit. If the most significant bit is already set and the integer is + * positive, a 0x00 is prepended. + * + * Examples: + * + * 0 => 0x00 + * 1 => 0x01 + * -1 => 0xff + * 127 => 0x7f + * -127 => 0x81 + * 128 => 0x0080 + * -128 => 0x80 + * 255 => 0x00ff + * -255 => 0xff01 + * 16300 => 0x3fac + * -16300 => 0xc054 + * 62300 => 0x00f35c + * -62300 => 0xff0ca4 +*/ +BigInteger.prototype.toDERInteger = BigInteger.prototype.toByteArray + +BigInteger.fromBuffer = function(buffer) { + // BigInteger expects a DER integer conformant byte array + if (buffer[0] & 0x80) { + var byteArray = Array.prototype.slice.call(buffer) + + return new BigInteger([0].concat(byteArray)) + } + + return new BigInteger(buffer) +} + +BigInteger.fromHex = function(hex) { + if (hex === '') return BigInteger.ZERO + + assert.equal(hex, hex.match(/^[A-Fa-f0-9]+/), 'Invalid hex string') + assert.equal(hex.length % 2, 0, 'Incomplete hex') + return new BigInteger(hex, 16) +} + +BigInteger.prototype.toBuffer = function(size) { + var byteArray = this.toByteArrayUnsigned() + var zeros = [] + + var padding = size - byteArray.length + while (zeros.length < padding) zeros.push(0) + + return new Buffer(zeros.concat(byteArray)) +} + +BigInteger.prototype.toHex = function(size) { + return this.toBuffer(size).toString('hex') +} + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./bigi":13,"assert":86,"buffer":92}],15:[function(require,module,exports){ +var BigInteger = require('./bigi') + +//addons +require('./convert') + +module.exports = BigInteger +},{"./bigi":13,"./convert":14}],16:[function(require,module,exports){ +module.exports={ + "name": "bigi", + "version": "1.4.2", + "description": "Big integers.", + "keywords": [ + "cryptography", + "math", + "bitcoin", + "arbitrary", + "precision", + "arithmetic", + "big", + "integer", + "int", + "number", + "biginteger", + "bigint", + "bignumber", + "decimal", + "float" + ], + "devDependencies": { + "coveralls": "^2.11.2", + "istanbul": "^0.3.5", + "jshint": "^2.5.1", + "mocha": "^2.1.0", + "mochify": "^2.1.0" + }, + "repository": { + "url": "https://github.com/cryptocoinjs/bigi", + "type": "git" + }, + "main": "./lib/index.js", + "scripts": { + "browser-test": "./node_modules/.bin/mochify --wd -R spec", + "test": "./node_modules/.bin/_mocha -- test/*.js", + "jshint": "./node_modules/.bin/jshint --config jshint.json lib/*.js ; true", + "unit": "./node_modules/.bin/mocha", + "coverage": "./node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha -- --reporter list test/*.js", + "coveralls": "npm run-script coverage && node ./node_modules/.bin/coveralls < coverage/lcov.info" + }, + "dependencies": {}, + "testling": { + "files": "test/*.js", + "harness": "mocha", + "browsers": [ + "ie/9..latest", + "firefox/latest", + "chrome/latest", + "safari/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} + +},{}],17:[function(require,module,exports){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const parser_1 = require('../parser'); +function combine(psbts) { + const self = psbts[0]; + const selfKeyVals = parser_1.psbtToKeyVals(self); + const others = psbts.slice(1); + if (others.length === 0) throw new Error('Combine: Nothing to combine'); + const selfTx = getTx(self); + if (selfTx === undefined) { + throw new Error('Combine: Self missing transaction'); + } + const selfGlobalSet = getKeySet(selfKeyVals.globalKeyVals); + const selfInputSets = selfKeyVals.inputKeyVals.map(getKeySet); + const selfOutputSets = selfKeyVals.outputKeyVals.map(getKeySet); + for (const other of others) { + const otherTx = getTx(other); + if ( + otherTx === undefined || + !otherTx.toBuffer().equals(selfTx.toBuffer()) + ) { + throw new Error( + 'Combine: One of the Psbts does not have the same transaction.', + ); + } + const otherKeyVals = parser_1.psbtToKeyVals(other); + const otherGlobalSet = getKeySet(otherKeyVals.globalKeyVals); + otherGlobalSet.forEach( + keyPusher( + selfGlobalSet, + selfKeyVals.globalKeyVals, + otherKeyVals.globalKeyVals, + ), + ); + const otherInputSets = otherKeyVals.inputKeyVals.map(getKeySet); + otherInputSets.forEach((inputSet, idx) => + inputSet.forEach( + keyPusher( + selfInputSets[idx], + selfKeyVals.inputKeyVals[idx], + otherKeyVals.inputKeyVals[idx], + ), + ), + ); + const otherOutputSets = otherKeyVals.outputKeyVals.map(getKeySet); + otherOutputSets.forEach((outputSet, idx) => + outputSet.forEach( + keyPusher( + selfOutputSets[idx], + selfKeyVals.outputKeyVals[idx], + otherKeyVals.outputKeyVals[idx], + ), + ), + ); + } + return parser_1.psbtFromKeyVals(selfTx, { + globalMapKeyVals: selfKeyVals.globalKeyVals, + inputKeyVals: selfKeyVals.inputKeyVals, + outputKeyVals: selfKeyVals.outputKeyVals, + }); +} +exports.combine = combine; +function keyPusher(selfSet, selfKeyVals, otherKeyVals) { + return key => { + if (selfSet.has(key)) return; + const newKv = otherKeyVals.filter(kv => kv.key.toString('hex') === key)[0]; + selfKeyVals.push(newKv); + selfSet.add(key); + }; +} +function getTx(psbt) { + return psbt.globalMap.unsignedTx; +} +function getKeySet(keyVals) { + const set = new Set(); + keyVals.forEach(keyVal => { + const hex = keyVal.key.toString('hex'); + if (set.has(hex)) + throw new Error('Combine: KeyValue Map keys should be unique'); + set.add(hex); + }); + return set; +} + +},{"../parser":42}],18:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_1 = require('../../typeFields'); +const range = n => [...Array(n).keys()]; +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_1.GlobalTypes.GLOBAL_XPUB) { + throw new Error( + 'Decode Error: could not decode globalXpub with key 0x' + + keyVal.key.toString('hex'), + ); + } + if (keyVal.key.length !== 79 || ![2, 3].includes(keyVal.key[46])) { + throw new Error( + 'Decode Error: globalXpub has invalid extended pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Global GLOBAL_XPUB value length should be multiple of 4', + ); + } + const extendedPubkey = keyVal.key.slice(1); + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + extendedPubkey, + path: 'm', + }; + for (const i of range(keyVal.value.length / 4 - 1)) { + const val = keyVal.value.readUInt32LE(i * 4 + 4); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + } + return data; +} +exports.decode = decode; +function encode(data) { + const head = Buffer.from([typeFields_1.GlobalTypes.GLOBAL_XPUB]); + const key = Buffer.concat([head, data.extendedPubkey]); + const splitPath = data.path.split('/'); + const value = Buffer.allocUnsafe(splitPath.length * 4); + data.masterFingerprint.copy(value, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + value.writeUInt32LE(num, offset); + offset += 4; + }); + return { + key, + value, + }; +} +exports.encode = encode; +exports.expected = + '{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }'; +function check(data) { + const epk = data.extendedPubkey; + const mfp = data.masterFingerprint; + const p = data.path; + return ( + Buffer.isBuffer(epk) && + epk.length === 78 && + [2, 3].indexOf(epk[45]) > -1 && + Buffer.isBuffer(mfp) && + mfp.length === 4 && + typeof p === 'string' && + !!p.match(/^m(\/\d+'?)*$/) + ); +} +exports.check = check; +function canAddToArray(array, item, dupeSet) { + const dupeString = item.extendedPubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter(v => v.extendedPubkey.equals(item.extendedPubkey)).length === 0 + ); +} +exports.canAddToArray = canAddToArray; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../../typeFields":45,"buffer":92}],19:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_1 = require('../../typeFields'); +function encode(data) { + return { + key: Buffer.from([typeFields_1.GlobalTypes.UNSIGNED_TX]), + value: data.toBuffer(), + }; +} +exports.encode = encode; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../../typeFields":45,"buffer":92}],20:[function(require,module,exports){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_1 = require('../typeFields'); +const globalXpub = require('./global/globalXpub'); +const unsignedTx = require('./global/unsignedTx'); +const finalScriptSig = require('./input/finalScriptSig'); +const finalScriptWitness = require('./input/finalScriptWitness'); +const nonWitnessUtxo = require('./input/nonWitnessUtxo'); +const partialSig = require('./input/partialSig'); +const porCommitment = require('./input/porCommitment'); +const sighashType = require('./input/sighashType'); +const tapKeySig = require('./input/tapKeySig'); +const tapLeafScript = require('./input/tapLeafScript'); +const tapMerkleRoot = require('./input/tapMerkleRoot'); +const tapScriptSig = require('./input/tapScriptSig'); +const witnessUtxo = require('./input/witnessUtxo'); +const tapTree = require('./output/tapTree'); +const bip32Derivation = require('./shared/bip32Derivation'); +const checkPubkey = require('./shared/checkPubkey'); +const redeemScript = require('./shared/redeemScript'); +const tapBip32Derivation = require('./shared/tapBip32Derivation'); +const tapInternalKey = require('./shared/tapInternalKey'); +const witnessScript = require('./shared/witnessScript'); +const globals = { + unsignedTx, + globalXpub, + // pass an Array of key bytes that require pubkey beside the key + checkPubkey: checkPubkey.makeChecker([]), +}; +exports.globals = globals; +const inputs = { + nonWitnessUtxo, + partialSig, + sighashType, + finalScriptSig, + finalScriptWitness, + porCommitment, + witnessUtxo, + bip32Derivation: bip32Derivation.makeConverter( + typeFields_1.InputTypes.BIP32_DERIVATION, + ), + redeemScript: redeemScript.makeConverter( + typeFields_1.InputTypes.REDEEM_SCRIPT, + ), + witnessScript: witnessScript.makeConverter( + typeFields_1.InputTypes.WITNESS_SCRIPT, + ), + checkPubkey: checkPubkey.makeChecker([ + typeFields_1.InputTypes.PARTIAL_SIG, + typeFields_1.InputTypes.BIP32_DERIVATION, + ]), + tapKeySig, + tapScriptSig, + tapLeafScript, + tapBip32Derivation: tapBip32Derivation.makeConverter( + typeFields_1.InputTypes.TAP_BIP32_DERIVATION, + ), + tapInternalKey: tapInternalKey.makeConverter( + typeFields_1.InputTypes.TAP_INTERNAL_KEY, + ), + tapMerkleRoot, +}; +exports.inputs = inputs; +const outputs = { + bip32Derivation: bip32Derivation.makeConverter( + typeFields_1.OutputTypes.BIP32_DERIVATION, + ), + redeemScript: redeemScript.makeConverter( + typeFields_1.OutputTypes.REDEEM_SCRIPT, + ), + witnessScript: witnessScript.makeConverter( + typeFields_1.OutputTypes.WITNESS_SCRIPT, + ), + checkPubkey: checkPubkey.makeChecker([ + typeFields_1.OutputTypes.BIP32_DERIVATION, + ]), + tapBip32Derivation: tapBip32Derivation.makeConverter( + typeFields_1.OutputTypes.TAP_BIP32_DERIVATION, + ), + tapTree, + tapInternalKey: tapInternalKey.makeConverter( + typeFields_1.OutputTypes.TAP_INTERNAL_KEY, + ), +}; +exports.outputs = outputs; + +},{"../typeFields":45,"./global/globalXpub":18,"./global/unsignedTx":19,"./input/finalScriptSig":21,"./input/finalScriptWitness":22,"./input/nonWitnessUtxo":23,"./input/partialSig":24,"./input/porCommitment":25,"./input/sighashType":26,"./input/tapKeySig":27,"./input/tapLeafScript":28,"./input/tapMerkleRoot":29,"./input/tapScriptSig":30,"./input/witnessUtxo":31,"./output/tapTree":32,"./shared/bip32Derivation":33,"./shared/checkPubkey":34,"./shared/redeemScript":35,"./shared/tapBip32Derivation":36,"./shared/tapInternalKey":37,"./shared/witnessScript":38}],21:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_1 = require('../../typeFields'); +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_1.InputTypes.FINAL_SCRIPTSIG) { + throw new Error( + 'Decode Error: could not decode finalScriptSig with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; +} +exports.decode = decode; +function encode(data) { + const key = Buffer.from([typeFields_1.InputTypes.FINAL_SCRIPTSIG]); + return { + key, + value: data, + }; +} +exports.encode = encode; +exports.expected = 'Buffer'; +function check(data) { + return Buffer.isBuffer(data); +} +exports.check = check; +function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.finalScriptSig === undefined; +} +exports.canAdd = canAdd; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../../typeFields":45,"buffer":92}],22:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_1 = require('../../typeFields'); +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_1.InputTypes.FINAL_SCRIPTWITNESS) { + throw new Error( + 'Decode Error: could not decode finalScriptWitness with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; +} +exports.decode = decode; +function encode(data) { + const key = Buffer.from([typeFields_1.InputTypes.FINAL_SCRIPTWITNESS]); + return { + key, + value: data, + }; +} +exports.encode = encode; +exports.expected = 'Buffer'; +function check(data) { + return Buffer.isBuffer(data); +} +exports.check = check; +function canAdd(currentData, newData) { + return ( + !!currentData && !!newData && currentData.finalScriptWitness === undefined + ); +} +exports.canAdd = canAdd; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../../typeFields":45,"buffer":92}],23:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_1 = require('../../typeFields'); +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_1.InputTypes.NON_WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode nonWitnessUtxo with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; +} +exports.decode = decode; +function encode(data) { + return { + key: Buffer.from([typeFields_1.InputTypes.NON_WITNESS_UTXO]), + value: data, + }; +} +exports.encode = encode; +exports.expected = 'Buffer'; +function check(data) { + return Buffer.isBuffer(data); +} +exports.check = check; +function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.nonWitnessUtxo === undefined; +} +exports.canAdd = canAdd; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../../typeFields":45,"buffer":92}],24:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_1 = require('../../typeFields'); +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_1.InputTypes.PARTIAL_SIG) { + throw new Error( + 'Decode Error: could not decode partialSig with key 0x' + + keyVal.key.toString('hex'), + ); + } + if ( + !(keyVal.key.length === 34 || keyVal.key.length === 66) || + ![2, 3, 4].includes(keyVal.key[1]) + ) { + throw new Error( + 'Decode Error: partialSig has invalid pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + const pubkey = keyVal.key.slice(1); + return { + pubkey, + signature: keyVal.value, + }; +} +exports.decode = decode; +function encode(pSig) { + const head = Buffer.from([typeFields_1.InputTypes.PARTIAL_SIG]); + return { + key: Buffer.concat([head, pSig.pubkey]), + value: pSig.signature, + }; +} +exports.encode = encode; +exports.expected = '{ pubkey: Buffer; signature: Buffer; }'; +function check(data) { + return ( + Buffer.isBuffer(data.pubkey) && + Buffer.isBuffer(data.signature) && + [33, 65].includes(data.pubkey.length) && + [2, 3, 4].includes(data.pubkey[0]) && + isDerSigWithSighash(data.signature) + ); +} +exports.check = check; +function isDerSigWithSighash(buf) { + if (!Buffer.isBuffer(buf) || buf.length < 9) return false; + if (buf[0] !== 0x30) return false; + if (buf.length !== buf[1] + 3) return false; + if (buf[2] !== 0x02) return false; + const rLen = buf[3]; + if (rLen > 33 || rLen < 1) return false; + if (buf[3 + rLen + 1] !== 0x02) return false; + const sLen = buf[3 + rLen + 2]; + if (sLen > 33 || sLen < 1) return false; + if (buf.length !== 3 + rLen + 2 + sLen + 2) return false; + return true; +} +function canAddToArray(array, item, dupeSet) { + const dupeString = item.pubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; +} +exports.canAddToArray = canAddToArray; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../../typeFields":45,"buffer":92}],25:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_1 = require('../../typeFields'); +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_1.InputTypes.POR_COMMITMENT) { + throw new Error( + 'Decode Error: could not decode porCommitment with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value.toString('utf8'); +} +exports.decode = decode; +function encode(data) { + const key = Buffer.from([typeFields_1.InputTypes.POR_COMMITMENT]); + return { + key, + value: Buffer.from(data, 'utf8'), + }; +} +exports.encode = encode; +exports.expected = 'string'; +function check(data) { + return typeof data === 'string'; +} +exports.check = check; +function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.porCommitment === undefined; +} +exports.canAdd = canAdd; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../../typeFields":45,"buffer":92}],26:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_1 = require('../../typeFields'); +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_1.InputTypes.SIGHASH_TYPE) { + throw new Error( + 'Decode Error: could not decode sighashType with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value.readUInt32LE(0); +} +exports.decode = decode; +function encode(data) { + const key = Buffer.from([typeFields_1.InputTypes.SIGHASH_TYPE]); + const value = Buffer.allocUnsafe(4); + value.writeUInt32LE(data, 0); + return { + key, + value, + }; +} +exports.encode = encode; +exports.expected = 'number'; +function check(data) { + return typeof data === 'number'; +} +exports.check = check; +function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.sighashType === undefined; +} +exports.canAdd = canAdd; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../../typeFields":45,"buffer":92}],27:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_1 = require('../../typeFields'); +function decode(keyVal) { + if ( + keyVal.key[0] !== typeFields_1.InputTypes.TAP_KEY_SIG || + keyVal.key.length !== 1 + ) { + throw new Error( + 'Decode Error: could not decode tapKeySig with key 0x' + + keyVal.key.toString('hex'), + ); + } + if (!check(keyVal.value)) { + throw new Error( + 'Decode Error: tapKeySig not a valid 64-65-byte BIP340 signature', + ); + } + return keyVal.value; +} +exports.decode = decode; +function encode(value) { + const key = Buffer.from([typeFields_1.InputTypes.TAP_KEY_SIG]); + return { key, value }; +} +exports.encode = encode; +exports.expected = 'Buffer'; +function check(data) { + return Buffer.isBuffer(data) && (data.length === 64 || data.length === 65); +} +exports.check = check; +function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.tapKeySig === undefined; +} +exports.canAdd = canAdd; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../../typeFields":45,"buffer":92}],28:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_1 = require('../../typeFields'); +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_1.InputTypes.TAP_LEAF_SCRIPT) { + throw new Error( + 'Decode Error: could not decode tapLeafScript with key 0x' + + keyVal.key.toString('hex'), + ); + } + if ((keyVal.key.length - 2) % 32 !== 0) { + throw new Error( + 'Decode Error: tapLeafScript has invalid control block in key 0x' + + keyVal.key.toString('hex'), + ); + } + const leafVersion = keyVal.value[keyVal.value.length - 1]; + if ((keyVal.key[1] & 0xfe) !== leafVersion) { + throw new Error( + 'Decode Error: tapLeafScript bad leaf version in key 0x' + + keyVal.key.toString('hex'), + ); + } + const script = keyVal.value.slice(0, -1); + const controlBlock = keyVal.key.slice(1); + return { controlBlock, script, leafVersion }; +} +exports.decode = decode; +function encode(tScript) { + const head = Buffer.from([typeFields_1.InputTypes.TAP_LEAF_SCRIPT]); + const verBuf = Buffer.from([tScript.leafVersion]); + return { + key: Buffer.concat([head, tScript.controlBlock]), + value: Buffer.concat([tScript.script, verBuf]), + }; +} +exports.encode = encode; +exports.expected = + '{ controlBlock: Buffer; leafVersion: number, script: Buffer; }'; +function check(data) { + return ( + Buffer.isBuffer(data.controlBlock) && + (data.controlBlock.length - 1) % 32 === 0 && + (data.controlBlock[0] & 0xfe) === data.leafVersion && + Buffer.isBuffer(data.script) + ); +} +exports.check = check; +function canAddToArray(array, item, dupeSet) { + const dupeString = item.controlBlock.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter(v => v.controlBlock.equals(item.controlBlock)).length === 0 + ); +} +exports.canAddToArray = canAddToArray; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../../typeFields":45,"buffer":92}],29:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_1 = require('../../typeFields'); +function decode(keyVal) { + if ( + keyVal.key[0] !== typeFields_1.InputTypes.TAP_MERKLE_ROOT || + keyVal.key.length !== 1 + ) { + throw new Error( + 'Decode Error: could not decode tapMerkleRoot with key 0x' + + keyVal.key.toString('hex'), + ); + } + if (!check(keyVal.value)) { + throw new Error('Decode Error: tapMerkleRoot not a 32-byte hash'); + } + return keyVal.value; +} +exports.decode = decode; +function encode(value) { + const key = Buffer.from([typeFields_1.InputTypes.TAP_MERKLE_ROOT]); + return { key, value }; +} +exports.encode = encode; +exports.expected = 'Buffer'; +function check(data) { + return Buffer.isBuffer(data) && data.length === 32; +} +exports.check = check; +function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.tapMerkleRoot === undefined; +} +exports.canAdd = canAdd; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../../typeFields":45,"buffer":92}],30:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_1 = require('../../typeFields'); +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_1.InputTypes.TAP_SCRIPT_SIG) { + throw new Error( + 'Decode Error: could not decode tapScriptSig with key 0x' + + keyVal.key.toString('hex'), + ); + } + if (keyVal.key.length !== 65) { + throw new Error( + 'Decode Error: tapScriptSig has invalid key 0x' + + keyVal.key.toString('hex'), + ); + } + if (keyVal.value.length !== 64 && keyVal.value.length !== 65) { + throw new Error( + 'Decode Error: tapScriptSig has invalid signature in key 0x' + + keyVal.key.toString('hex'), + ); + } + const pubkey = keyVal.key.slice(1, 33); + const leafHash = keyVal.key.slice(33); + return { + pubkey, + leafHash, + signature: keyVal.value, + }; +} +exports.decode = decode; +function encode(tSig) { + const head = Buffer.from([typeFields_1.InputTypes.TAP_SCRIPT_SIG]); + return { + key: Buffer.concat([head, tSig.pubkey, tSig.leafHash]), + value: tSig.signature, + }; +} +exports.encode = encode; +exports.expected = '{ pubkey: Buffer; leafHash: Buffer; signature: Buffer; }'; +function check(data) { + return ( + Buffer.isBuffer(data.pubkey) && + Buffer.isBuffer(data.leafHash) && + Buffer.isBuffer(data.signature) && + data.pubkey.length === 32 && + data.leafHash.length === 32 && + (data.signature.length === 64 || data.signature.length === 65) + ); +} +exports.check = check; +function canAddToArray(array, item, dupeSet) { + const dupeString = + item.pubkey.toString('hex') + item.leafHash.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter( + v => v.pubkey.equals(item.pubkey) && v.leafHash.equals(item.leafHash), + ).length === 0 + ); +} +exports.canAddToArray = canAddToArray; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../../typeFields":45,"buffer":92}],31:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_1 = require('../../typeFields'); +const tools_1 = require('../tools'); +const varuint = require('../varint'); +function decode(keyVal) { + if (keyVal.key[0] !== typeFields_1.InputTypes.WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode witnessUtxo with key 0x' + + keyVal.key.toString('hex'), + ); + } + const value = tools_1.readUInt64LE(keyVal.value, 0); + let _offset = 8; + const scriptLen = varuint.decode(keyVal.value, _offset); + _offset += varuint.encodingLength(scriptLen); + const script = keyVal.value.slice(_offset); + if (script.length !== scriptLen) { + throw new Error('Decode Error: WITNESS_UTXO script is not proper length'); + } + return { + script, + value, + }; +} +exports.decode = decode; +function encode(data) { + const { script, value } = data; + const varintLen = varuint.encodingLength(script.length); + const result = Buffer.allocUnsafe(8 + varintLen + script.length); + tools_1.writeUInt64LE(result, value, 0); + varuint.encode(script.length, result, 8); + script.copy(result, 8 + varintLen); + return { + key: Buffer.from([typeFields_1.InputTypes.WITNESS_UTXO]), + value: result, + }; +} +exports.encode = encode; +exports.expected = '{ script: Buffer; value: number; }'; +function check(data) { + return Buffer.isBuffer(data.script) && typeof data.value === 'number'; +} +exports.check = check; +function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.witnessUtxo === undefined; +} +exports.canAdd = canAdd; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../../typeFields":45,"../tools":39,"../varint":40,"buffer":92}],32:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const typeFields_1 = require('../../typeFields'); +const varuint = require('../varint'); +function decode(keyVal) { + if ( + keyVal.key[0] !== typeFields_1.OutputTypes.TAP_TREE || + keyVal.key.length !== 1 + ) { + throw new Error( + 'Decode Error: could not decode tapTree with key 0x' + + keyVal.key.toString('hex'), + ); + } + let _offset = 0; + const data = []; + while (_offset < keyVal.value.length) { + const depth = keyVal.value[_offset++]; + const leafVersion = keyVal.value[_offset++]; + const scriptLen = varuint.decode(keyVal.value, _offset); + _offset += varuint.encodingLength(scriptLen); + data.push({ + depth, + leafVersion, + script: keyVal.value.slice(_offset, _offset + scriptLen), + }); + _offset += scriptLen; + } + return { leaves: data }; +} +exports.decode = decode; +function encode(tree) { + const key = Buffer.from([typeFields_1.OutputTypes.TAP_TREE]); + const bufs = [].concat( + ...tree.leaves.map(tapLeaf => [ + Buffer.of(tapLeaf.depth, tapLeaf.leafVersion), + varuint.encode(tapLeaf.script.length), + tapLeaf.script, + ]), + ); + return { + key, + value: Buffer.concat(bufs), + }; +} +exports.encode = encode; +exports.expected = + '{ leaves: [{ depth: number; leafVersion: number, script: Buffer; }] }'; +function check(data) { + return ( + Array.isArray(data.leaves) && + data.leaves.every( + tapLeaf => + tapLeaf.depth >= 0 && + tapLeaf.depth <= 128 && + (tapLeaf.leafVersion & 0xfe) === tapLeaf.leafVersion && + Buffer.isBuffer(tapLeaf.script), + ) + ); +} +exports.check = check; +function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.tapTree === undefined; +} +exports.canAdd = canAdd; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../../typeFields":45,"../varint":40,"buffer":92}],33:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const range = n => [...Array(n).keys()]; +const isValidDERKey = pubkey => + (pubkey.length === 33 && [2, 3].includes(pubkey[0])) || + (pubkey.length === 65 && 4 === pubkey[0]); +function makeConverter(TYPE_BYTE, isValidPubkey = isValidDERKey) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode bip32Derivation with key 0x' + + keyVal.key.toString('hex'), + ); + } + const pubkey = keyVal.key.slice(1); + if (!isValidPubkey(pubkey)) { + throw new Error( + 'Decode Error: bip32Derivation has invalid pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Input BIP32_DERIVATION value length should be multiple of 4', + ); + } + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + pubkey, + path: 'm', + }; + for (const i of range(keyVal.value.length / 4 - 1)) { + const val = keyVal.value.readUInt32LE(i * 4 + 4); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + } + return data; + } + function encode(data) { + const head = Buffer.from([TYPE_BYTE]); + const key = Buffer.concat([head, data.pubkey]); + const splitPath = data.path.split('/'); + const value = Buffer.allocUnsafe(splitPath.length * 4); + data.masterFingerprint.copy(value, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + value.writeUInt32LE(num, offset); + offset += 4; + }); + return { + key, + value, + }; + } + const expected = + '{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }'; + function check(data) { + return ( + Buffer.isBuffer(data.pubkey) && + Buffer.isBuffer(data.masterFingerprint) && + typeof data.path === 'string' && + isValidPubkey(data.pubkey) && + data.masterFingerprint.length === 4 + ); + } + function canAddToArray(array, item, dupeSet) { + const dupeString = item.pubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; + } + return { + decode, + encode, + check, + expected, + canAddToArray, + }; +} +exports.makeConverter = makeConverter; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"buffer":92}],34:[function(require,module,exports){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +function makeChecker(pubkeyTypes) { + return checkPubkey; + function checkPubkey(keyVal) { + let pubkey; + if (pubkeyTypes.includes(keyVal.key[0])) { + pubkey = keyVal.key.slice(1); + if ( + !(pubkey.length === 33 || pubkey.length === 65) || + ![2, 3, 4].includes(pubkey[0]) + ) { + throw new Error( + 'Format Error: invalid pubkey in key 0x' + keyVal.key.toString('hex'), + ); + } + } + return pubkey; + } +} +exports.makeChecker = makeChecker; + +},{}],35:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +function makeConverter(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode redeemScript with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + function encode(data) { + const key = Buffer.from([TYPE_BYTE]); + return { + key, + value: data, + }; + } + const expected = 'Buffer'; + function check(data) { + return Buffer.isBuffer(data); + } + function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.redeemScript === undefined; + } + return { + decode, + encode, + check, + expected, + canAdd, + }; +} +exports.makeConverter = makeConverter; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"buffer":92}],36:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const varuint = require('../varint'); +const bip32Derivation = require('./bip32Derivation'); +const isValidBIP340Key = pubkey => pubkey.length === 32; +function makeConverter(TYPE_BYTE) { + const parent = bip32Derivation.makeConverter(TYPE_BYTE, isValidBIP340Key); + function decode(keyVal) { + const nHashes = varuint.decode(keyVal.value); + const nHashesLen = varuint.encodingLength(nHashes); + const base = parent.decode({ + key: keyVal.key, + value: keyVal.value.slice(nHashesLen + nHashes * 32), + }); + const leafHashes = new Array(nHashes); + for (let i = 0, _offset = nHashesLen; i < nHashes; i++, _offset += 32) { + leafHashes[i] = keyVal.value.slice(_offset, _offset + 32); + } + return Object.assign({}, base, { leafHashes }); + } + function encode(data) { + const base = parent.encode(data); + const nHashesLen = varuint.encodingLength(data.leafHashes.length); + const nHashesBuf = Buffer.allocUnsafe(nHashesLen); + varuint.encode(data.leafHashes.length, nHashesBuf); + const value = Buffer.concat([nHashesBuf, ...data.leafHashes, base.value]); + return Object.assign({}, base, { value }); + } + const expected = + '{ ' + + 'masterFingerprint: Buffer; ' + + 'pubkey: Buffer; ' + + 'path: string; ' + + 'leafHashes: Buffer[]; ' + + '}'; + function check(data) { + return ( + Array.isArray(data.leafHashes) && + data.leafHashes.every( + leafHash => Buffer.isBuffer(leafHash) && leafHash.length === 32, + ) && + parent.check(data) + ); + } + return { + decode, + encode, + check, + expected, + canAddToArray: parent.canAddToArray, + }; +} +exports.makeConverter = makeConverter; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../varint":40,"./bip32Derivation":33,"buffer":92}],37:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +function makeConverter(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE || keyVal.key.length !== 1) { + throw new Error( + 'Decode Error: could not decode tapInternalKey with key 0x' + + keyVal.key.toString('hex'), + ); + } + if (keyVal.value.length !== 32) { + throw new Error( + 'Decode Error: tapInternalKey not a 32-byte x-only pubkey', + ); + } + return keyVal.value; + } + function encode(value) { + const key = Buffer.from([TYPE_BYTE]); + return { key, value }; + } + const expected = 'Buffer'; + function check(data) { + return Buffer.isBuffer(data) && data.length === 32; + } + function canAdd(currentData, newData) { + return ( + !!currentData && !!newData && currentData.tapInternalKey === undefined + ); + } + return { + decode, + encode, + check, + expected, + canAdd, + }; +} +exports.makeConverter = makeConverter; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"buffer":92}],38:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +function makeConverter(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode witnessScript with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + function encode(data) { + const key = Buffer.from([TYPE_BYTE]); + return { + key, + value: data, + }; + } + const expected = 'Buffer'; + function check(data) { + return Buffer.isBuffer(data); + } + function canAdd(currentData, newData) { + return ( + !!currentData && !!newData && currentData.witnessScript === undefined + ); + } + return { + decode, + encode, + check, + expected, + canAdd, + }; +} +exports.makeConverter = makeConverter; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"buffer":92}],39:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const varuint = require('./varint'); +exports.range = n => [...Array(n).keys()]; +function reverseBuffer(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; + } + return buffer; +} +exports.reverseBuffer = reverseBuffer; +function keyValsToBuffer(keyVals) { + const buffers = keyVals.map(keyValToBuffer); + buffers.push(Buffer.from([0])); + return Buffer.concat(buffers); +} +exports.keyValsToBuffer = keyValsToBuffer; +function keyValToBuffer(keyVal) { + const keyLen = keyVal.key.length; + const valLen = keyVal.value.length; + const keyVarIntLen = varuint.encodingLength(keyLen); + const valVarIntLen = varuint.encodingLength(valLen); + const buffer = Buffer.allocUnsafe( + keyVarIntLen + keyLen + valVarIntLen + valLen, + ); + varuint.encode(keyLen, buffer, 0); + keyVal.key.copy(buffer, keyVarIntLen); + varuint.encode(valLen, buffer, keyVarIntLen + keyLen); + keyVal.value.copy(buffer, keyVarIntLen + keyLen + valVarIntLen); + return buffer; +} +exports.keyValToBuffer = keyValToBuffer; +// https://github.com/feross/buffer/blob/master/index.js#L1127 +function verifuint(value, max) { + if (typeof value !== 'number') + throw new Error('cannot write a non-number as a number'); + if (value < 0) + throw new Error('specified a negative value for writing an unsigned value'); + if (value > max) throw new Error('RangeError: value out of range'); + if (Math.floor(value) !== value) + throw new Error('value has a fractional component'); +} +function readUInt64LE(buffer, offset) { + const a = buffer.readUInt32LE(offset); + let b = buffer.readUInt32LE(offset + 4); + b *= 0x100000000; + verifuint(b + a, 0x001fffffffffffff); + return b + a; +} +exports.readUInt64LE = readUInt64LE; +function writeUInt64LE(buffer, value, offset) { + verifuint(value, 0x001fffffffffffff); + buffer.writeInt32LE(value & -1, offset); + buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); + return offset + 8; +} +exports.writeUInt64LE = writeUInt64LE; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./varint":40,"buffer":92}],40:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +// Number.MAX_SAFE_INTEGER +const MAX_SAFE_INTEGER = 9007199254740991; +function checkUInt53(n) { + if (n < 0 || n > MAX_SAFE_INTEGER || n % 1 !== 0) + throw new RangeError('value out of range'); +} +function encode(_number, buffer, offset) { + checkUInt53(_number); + if (!buffer) buffer = Buffer.allocUnsafe(encodingLength(_number)); + if (!Buffer.isBuffer(buffer)) + throw new TypeError('buffer must be a Buffer instance'); + if (!offset) offset = 0; + // 8 bit + if (_number < 0xfd) { + buffer.writeUInt8(_number, offset); + Object.assign(encode, { bytes: 1 }); + // 16 bit + } else if (_number <= 0xffff) { + buffer.writeUInt8(0xfd, offset); + buffer.writeUInt16LE(_number, offset + 1); + Object.assign(encode, { bytes: 3 }); + // 32 bit + } else if (_number <= 0xffffffff) { + buffer.writeUInt8(0xfe, offset); + buffer.writeUInt32LE(_number, offset + 1); + Object.assign(encode, { bytes: 5 }); + // 64 bit + } else { + buffer.writeUInt8(0xff, offset); + buffer.writeUInt32LE(_number >>> 0, offset + 1); + buffer.writeUInt32LE((_number / 0x100000000) | 0, offset + 5); + Object.assign(encode, { bytes: 9 }); + } + return buffer; +} +exports.encode = encode; +function decode(buffer, offset) { + if (!Buffer.isBuffer(buffer)) + throw new TypeError('buffer must be a Buffer instance'); + if (!offset) offset = 0; + const first = buffer.readUInt8(offset); + // 8 bit + if (first < 0xfd) { + Object.assign(decode, { bytes: 1 }); + return first; + // 16 bit + } else if (first === 0xfd) { + Object.assign(decode, { bytes: 3 }); + return buffer.readUInt16LE(offset + 1); + // 32 bit + } else if (first === 0xfe) { + Object.assign(decode, { bytes: 5 }); + return buffer.readUInt32LE(offset + 1); + // 64 bit + } else { + Object.assign(decode, { bytes: 9 }); + const lo = buffer.readUInt32LE(offset + 1); + const hi = buffer.readUInt32LE(offset + 5); + const _number = hi * 0x0100000000 + lo; + checkUInt53(_number); + return _number; + } +} +exports.decode = decode; +function encodingLength(_number) { + checkUInt53(_number); + return _number < 0xfd + ? 1 + : _number <= 0xffff + ? 3 + : _number <= 0xffffffff + ? 5 + : 9; +} +exports.encodingLength = encodingLength; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"buffer":92}],41:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const convert = require('../converter'); +const tools_1 = require('../converter/tools'); +const varuint = require('../converter/varint'); +const typeFields_1 = require('../typeFields'); +function psbtFromBuffer(buffer, txGetter) { + let offset = 0; + function varSlice() { + const keyLen = varuint.decode(buffer, offset); + offset += varuint.encodingLength(keyLen); + const key = buffer.slice(offset, offset + keyLen); + offset += keyLen; + return key; + } + function readUInt32BE() { + const num = buffer.readUInt32BE(offset); + offset += 4; + return num; + } + function readUInt8() { + const num = buffer.readUInt8(offset); + offset += 1; + return num; + } + function getKeyValue() { + const key = varSlice(); + const value = varSlice(); + return { + key, + value, + }; + } + function checkEndOfKeyValPairs() { + if (offset >= buffer.length) { + throw new Error('Format Error: Unexpected End of PSBT'); + } + const isEnd = buffer.readUInt8(offset) === 0; + if (isEnd) { + offset++; + } + return isEnd; + } + if (readUInt32BE() !== 0x70736274) { + throw new Error('Format Error: Invalid Magic Number'); + } + if (readUInt8() !== 0xff) { + throw new Error( + 'Format Error: Magic Number must be followed by 0xff separator', + ); + } + const globalMapKeyVals = []; + const globalKeyIndex = {}; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (globalKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for global keymap: key ' + hexKey, + ); + } + globalKeyIndex[hexKey] = 1; + globalMapKeyVals.push(keyVal); + } + const unsignedTxMaps = globalMapKeyVals.filter( + keyVal => keyVal.key[0] === typeFields_1.GlobalTypes.UNSIGNED_TX, + ); + if (unsignedTxMaps.length !== 1) { + throw new Error('Format Error: Only one UNSIGNED_TX allowed'); + } + const unsignedTx = txGetter(unsignedTxMaps[0].value); + // Get input and output counts to loop the respective fields + const { inputCount, outputCount } = unsignedTx.getInputOutputCounts(); + const inputKeyVals = []; + const outputKeyVals = []; + // Get input fields + for (const index of tools_1.range(inputCount)) { + const inputKeyIndex = {}; + const input = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (inputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each input: ' + + 'input index ' + + index + + ' key ' + + hexKey, + ); + } + inputKeyIndex[hexKey] = 1; + input.push(keyVal); + } + inputKeyVals.push(input); + } + for (const index of tools_1.range(outputCount)) { + const outputKeyIndex = {}; + const output = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (outputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each output: ' + + 'output index ' + + index + + ' key ' + + hexKey, + ); + } + outputKeyIndex[hexKey] = 1; + output.push(keyVal); + } + outputKeyVals.push(output); + } + return psbtFromKeyVals(unsignedTx, { + globalMapKeyVals, + inputKeyVals, + outputKeyVals, + }); +} +exports.psbtFromBuffer = psbtFromBuffer; +function checkKeyBuffer(type, keyBuf, keyNum) { + if (!keyBuf.equals(Buffer.from([keyNum]))) { + throw new Error( + `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, + ); + } +} +exports.checkKeyBuffer = checkKeyBuffer; +function psbtFromKeyVals( + unsignedTx, + { globalMapKeyVals, inputKeyVals, outputKeyVals }, +) { + // That was easy :-) + const globalMap = { + unsignedTx, + }; + let txCount = 0; + for (const keyVal of globalMapKeyVals) { + // If a globalMap item needs pubkey, uncomment + // const pubkey = convert.globals.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1.GlobalTypes.UNSIGNED_TX: + checkKeyBuffer( + 'global', + keyVal.key, + typeFields_1.GlobalTypes.UNSIGNED_TX, + ); + if (txCount > 0) { + throw new Error('Format Error: GlobalMap has multiple UNSIGNED_TX'); + } + txCount++; + break; + case typeFields_1.GlobalTypes.GLOBAL_XPUB: + if (globalMap.globalXpub === undefined) { + globalMap.globalXpub = []; + } + globalMap.globalXpub.push(convert.globals.globalXpub.decode(keyVal)); + break; + default: + // This will allow inclusion during serialization. + if (!globalMap.unknownKeyVals) globalMap.unknownKeyVals = []; + globalMap.unknownKeyVals.push(keyVal); + } + } + // Get input and output counts to loop the respective fields + const inputCount = inputKeyVals.length; + const outputCount = outputKeyVals.length; + const inputs = []; + const outputs = []; + // Get input fields + for (const index of tools_1.range(inputCount)) { + const input = {}; + for (const keyVal of inputKeyVals[index]) { + convert.inputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1.InputTypes.NON_WITNESS_UTXO: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1.InputTypes.NON_WITNESS_UTXO, + ); + if (input.nonWitnessUtxo !== undefined) { + throw new Error( + 'Format Error: Input has multiple NON_WITNESS_UTXO', + ); + } + input.nonWitnessUtxo = convert.inputs.nonWitnessUtxo.decode(keyVal); + break; + case typeFields_1.InputTypes.WITNESS_UTXO: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1.InputTypes.WITNESS_UTXO, + ); + if (input.witnessUtxo !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_UTXO'); + } + input.witnessUtxo = convert.inputs.witnessUtxo.decode(keyVal); + break; + case typeFields_1.InputTypes.PARTIAL_SIG: + if (input.partialSig === undefined) { + input.partialSig = []; + } + input.partialSig.push(convert.inputs.partialSig.decode(keyVal)); + break; + case typeFields_1.InputTypes.SIGHASH_TYPE: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1.InputTypes.SIGHASH_TYPE, + ); + if (input.sighashType !== undefined) { + throw new Error('Format Error: Input has multiple SIGHASH_TYPE'); + } + input.sighashType = convert.inputs.sighashType.decode(keyVal); + break; + case typeFields_1.InputTypes.REDEEM_SCRIPT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1.InputTypes.REDEEM_SCRIPT, + ); + if (input.redeemScript !== undefined) { + throw new Error('Format Error: Input has multiple REDEEM_SCRIPT'); + } + input.redeemScript = convert.inputs.redeemScript.decode(keyVal); + break; + case typeFields_1.InputTypes.WITNESS_SCRIPT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1.InputTypes.WITNESS_SCRIPT, + ); + if (input.witnessScript !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_SCRIPT'); + } + input.witnessScript = convert.inputs.witnessScript.decode(keyVal); + break; + case typeFields_1.InputTypes.BIP32_DERIVATION: + if (input.bip32Derivation === undefined) { + input.bip32Derivation = []; + } + input.bip32Derivation.push( + convert.inputs.bip32Derivation.decode(keyVal), + ); + break; + case typeFields_1.InputTypes.FINAL_SCRIPTSIG: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1.InputTypes.FINAL_SCRIPTSIG, + ); + input.finalScriptSig = convert.inputs.finalScriptSig.decode(keyVal); + break; + case typeFields_1.InputTypes.FINAL_SCRIPTWITNESS: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1.InputTypes.FINAL_SCRIPTWITNESS, + ); + input.finalScriptWitness = convert.inputs.finalScriptWitness.decode( + keyVal, + ); + break; + case typeFields_1.InputTypes.POR_COMMITMENT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1.InputTypes.POR_COMMITMENT, + ); + input.porCommitment = convert.inputs.porCommitment.decode(keyVal); + break; + case typeFields_1.InputTypes.TAP_KEY_SIG: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1.InputTypes.TAP_KEY_SIG, + ); + input.tapKeySig = convert.inputs.tapKeySig.decode(keyVal); + break; + case typeFields_1.InputTypes.TAP_SCRIPT_SIG: + if (input.tapScriptSig === undefined) { + input.tapScriptSig = []; + } + input.tapScriptSig.push(convert.inputs.tapScriptSig.decode(keyVal)); + break; + case typeFields_1.InputTypes.TAP_LEAF_SCRIPT: + if (input.tapLeafScript === undefined) { + input.tapLeafScript = []; + } + input.tapLeafScript.push(convert.inputs.tapLeafScript.decode(keyVal)); + break; + case typeFields_1.InputTypes.TAP_BIP32_DERIVATION: + if (input.tapBip32Derivation === undefined) { + input.tapBip32Derivation = []; + } + input.tapBip32Derivation.push( + convert.inputs.tapBip32Derivation.decode(keyVal), + ); + break; + case typeFields_1.InputTypes.TAP_INTERNAL_KEY: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1.InputTypes.TAP_INTERNAL_KEY, + ); + input.tapInternalKey = convert.inputs.tapInternalKey.decode(keyVal); + break; + case typeFields_1.InputTypes.TAP_MERKLE_ROOT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1.InputTypes.TAP_MERKLE_ROOT, + ); + input.tapMerkleRoot = convert.inputs.tapMerkleRoot.decode(keyVal); + break; + default: + // This will allow inclusion during serialization. + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + } + } + inputs.push(input); + } + for (const index of tools_1.range(outputCount)) { + const output = {}; + for (const keyVal of outputKeyVals[index]) { + convert.outputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1.OutputTypes.REDEEM_SCRIPT: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_1.OutputTypes.REDEEM_SCRIPT, + ); + if (output.redeemScript !== undefined) { + throw new Error('Format Error: Output has multiple REDEEM_SCRIPT'); + } + output.redeemScript = convert.outputs.redeemScript.decode(keyVal); + break; + case typeFields_1.OutputTypes.WITNESS_SCRIPT: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_1.OutputTypes.WITNESS_SCRIPT, + ); + if (output.witnessScript !== undefined) { + throw new Error('Format Error: Output has multiple WITNESS_SCRIPT'); + } + output.witnessScript = convert.outputs.witnessScript.decode(keyVal); + break; + case typeFields_1.OutputTypes.BIP32_DERIVATION: + if (output.bip32Derivation === undefined) { + output.bip32Derivation = []; + } + output.bip32Derivation.push( + convert.outputs.bip32Derivation.decode(keyVal), + ); + break; + case typeFields_1.OutputTypes.TAP_INTERNAL_KEY: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_1.OutputTypes.TAP_INTERNAL_KEY, + ); + output.tapInternalKey = convert.outputs.tapInternalKey.decode(keyVal); + break; + case typeFields_1.OutputTypes.TAP_TREE: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_1.OutputTypes.TAP_TREE, + ); + output.tapTree = convert.outputs.tapTree.decode(keyVal); + break; + case typeFields_1.OutputTypes.TAP_BIP32_DERIVATION: + if (output.tapBip32Derivation === undefined) { + output.tapBip32Derivation = []; + } + output.tapBip32Derivation.push( + convert.outputs.tapBip32Derivation.decode(keyVal), + ); + break; + default: + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + } + } + outputs.push(output); + } + return { globalMap, inputs, outputs }; +} +exports.psbtFromKeyVals = psbtFromKeyVals; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../converter":20,"../converter/tools":39,"../converter/varint":40,"../typeFields":45,"buffer":92}],42:[function(require,module,exports){ +'use strict'; +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, '__esModule', { value: true }); +__export(require('./fromBuffer')); +__export(require('./toBuffer')); + +},{"./fromBuffer":41,"./toBuffer":43}],43:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const convert = require('../converter'); +const tools_1 = require('../converter/tools'); +function psbtToBuffer({ globalMap, inputs, outputs }) { + const { globalKeyVals, inputKeyVals, outputKeyVals } = psbtToKeyVals({ + globalMap, + inputs, + outputs, + }); + const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); + const keyValsOrEmptyToBuffer = keyVals => + keyVals.length === 0 + ? [Buffer.from([0])] + : keyVals.map(tools_1.keyValsToBuffer); + const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); + const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); + const header = Buffer.allocUnsafe(5); + header.writeUIntBE(0x70736274ff, 0, 5); + return Buffer.concat( + [header, globalBuffer].concat(inputBuffers, outputBuffers), + ); +} +exports.psbtToBuffer = psbtToBuffer; +const sortKeyVals = (a, b) => { + return a.key.compare(b.key); +}; +function keyValsFromMap(keyValMap, converterFactory) { + const keyHexSet = new Set(); + const keyVals = Object.entries(keyValMap).reduce((result, [key, value]) => { + if (key === 'unknownKeyVals') return result; + // We are checking for undefined anyways. So ignore TS error + // @ts-ignore + const converter = converterFactory[key]; + if (converter === undefined) return result; + const encodedKeyVals = (Array.isArray(value) ? value : [value]).map( + converter.encode, + ); + const keyHexes = encodedKeyVals.map(kv => kv.key.toString('hex')); + keyHexes.forEach(hex => { + if (keyHexSet.has(hex)) + throw new Error('Serialize Error: Duplicate key: ' + hex); + keyHexSet.add(hex); + }); + return result.concat(encodedKeyVals); + }, []); + // Get other keyVals that have not yet been gotten + const otherKeyVals = keyValMap.unknownKeyVals + ? keyValMap.unknownKeyVals.filter(keyVal => { + return !keyHexSet.has(keyVal.key.toString('hex')); + }) + : []; + return keyVals.concat(otherKeyVals).sort(sortKeyVals); +} +function psbtToKeyVals({ globalMap, inputs, outputs }) { + // First parse the global keyVals + // Get any extra keyvals to pass along + return { + globalKeyVals: keyValsFromMap(globalMap, convert.globals), + inputKeyVals: inputs.map(i => keyValsFromMap(i, convert.inputs)), + outputKeyVals: outputs.map(o => keyValsFromMap(o, convert.outputs)), + }; +} +exports.psbtToKeyVals = psbtToKeyVals; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../converter":20,"../converter/tools":39,"buffer":92}],44:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const combiner_1 = require('./combiner'); +const parser_1 = require('./parser'); +const typeFields_1 = require('./typeFields'); +const utils_1 = require('./utils'); +class Psbt { + constructor(tx) { + this.inputs = []; + this.outputs = []; + this.globalMap = { + unsignedTx: tx, + }; + } + static fromBase64(data, txFromBuffer) { + const buffer = Buffer.from(data, 'base64'); + return this.fromBuffer(buffer, txFromBuffer); + } + static fromHex(data, txFromBuffer) { + const buffer = Buffer.from(data, 'hex'); + return this.fromBuffer(buffer, txFromBuffer); + } + static fromBuffer(buffer, txFromBuffer) { + const results = parser_1.psbtFromBuffer(buffer, txFromBuffer); + const psbt = new this(results.globalMap.unsignedTx); + Object.assign(psbt, results); + return psbt; + } + toBase64() { + const buffer = this.toBuffer(); + return buffer.toString('base64'); + } + toHex() { + const buffer = this.toBuffer(); + return buffer.toString('hex'); + } + toBuffer() { + return parser_1.psbtToBuffer(this); + } + updateGlobal(updateData) { + utils_1.updateGlobal(updateData, this.globalMap); + return this; + } + updateInput(inputIndex, updateData) { + const input = utils_1.checkForInput(this.inputs, inputIndex); + utils_1.updateInput(updateData, input); + return this; + } + updateOutput(outputIndex, updateData) { + const output = utils_1.checkForOutput(this.outputs, outputIndex); + utils_1.updateOutput(updateData, output); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + utils_1.checkHasKey( + keyVal, + this.globalMap.unknownKeyVals, + utils_1.getEnumLength(typeFields_1.GlobalTypes), + ); + if (!this.globalMap.unknownKeyVals) this.globalMap.unknownKeyVals = []; + this.globalMap.unknownKeyVals.push(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + const input = utils_1.checkForInput(this.inputs, inputIndex); + utils_1.checkHasKey( + keyVal, + input.unknownKeyVals, + utils_1.getEnumLength(typeFields_1.InputTypes), + ); + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + return this; + } + addUnknownKeyValToOutput(outputIndex, keyVal) { + const output = utils_1.checkForOutput(this.outputs, outputIndex); + utils_1.checkHasKey( + keyVal, + output.unknownKeyVals, + utils_1.getEnumLength(typeFields_1.OutputTypes), + ); + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + return this; + } + addInput(inputData) { + this.globalMap.unsignedTx.addInput(inputData); + this.inputs.push({ + unknownKeyVals: [], + }); + const addKeyVals = inputData.unknownKeyVals || []; + const inputIndex = this.inputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); + } + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToInput(inputIndex, keyVal), + ); + utils_1.addInputAttributes(this.inputs, inputData); + return this; + } + addOutput(outputData) { + this.globalMap.unsignedTx.addOutput(outputData); + this.outputs.push({ + unknownKeyVals: [], + }); + const addKeyVals = outputData.unknownKeyVals || []; + const outputIndex = this.outputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); + } + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToInput(outputIndex, keyVal), + ); + utils_1.addOutputAttributes(this.outputs, outputData); + return this; + } + clearFinalizedInput(inputIndex) { + const input = utils_1.checkForInput(this.inputs, inputIndex); + utils_1.inputCheckUncleanFinalized(inputIndex, input); + for (const key of Object.keys(input)) { + if ( + ![ + 'witnessUtxo', + 'nonWitnessUtxo', + 'finalScriptSig', + 'finalScriptWitness', + 'unknownKeyVals', + ].includes(key) + ) { + // @ts-ignore + delete input[key]; + } + } + return this; + } + combine(...those) { + // Combine this with those. + // Return self for chaining. + const result = combiner_1.combine([this].concat(those)); + Object.assign(this, result); + return this; + } + getTransaction() { + return this.globalMap.unsignedTx.toBuffer(); + } +} +exports.Psbt = Psbt; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./combiner":17,"./parser":42,"./typeFields":45,"./utils":46,"buffer":92}],45:[function(require,module,exports){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +var GlobalTypes; +(function(GlobalTypes) { + GlobalTypes[(GlobalTypes['UNSIGNED_TX'] = 0)] = 'UNSIGNED_TX'; + GlobalTypes[(GlobalTypes['GLOBAL_XPUB'] = 1)] = 'GLOBAL_XPUB'; +})((GlobalTypes = exports.GlobalTypes || (exports.GlobalTypes = {}))); +exports.GLOBAL_TYPE_NAMES = ['unsignedTx', 'globalXpub']; +var InputTypes; +(function(InputTypes) { + InputTypes[(InputTypes['NON_WITNESS_UTXO'] = 0)] = 'NON_WITNESS_UTXO'; + InputTypes[(InputTypes['WITNESS_UTXO'] = 1)] = 'WITNESS_UTXO'; + InputTypes[(InputTypes['PARTIAL_SIG'] = 2)] = 'PARTIAL_SIG'; + InputTypes[(InputTypes['SIGHASH_TYPE'] = 3)] = 'SIGHASH_TYPE'; + InputTypes[(InputTypes['REDEEM_SCRIPT'] = 4)] = 'REDEEM_SCRIPT'; + InputTypes[(InputTypes['WITNESS_SCRIPT'] = 5)] = 'WITNESS_SCRIPT'; + InputTypes[(InputTypes['BIP32_DERIVATION'] = 6)] = 'BIP32_DERIVATION'; + InputTypes[(InputTypes['FINAL_SCRIPTSIG'] = 7)] = 'FINAL_SCRIPTSIG'; + InputTypes[(InputTypes['FINAL_SCRIPTWITNESS'] = 8)] = 'FINAL_SCRIPTWITNESS'; + InputTypes[(InputTypes['POR_COMMITMENT'] = 9)] = 'POR_COMMITMENT'; + InputTypes[(InputTypes['TAP_KEY_SIG'] = 19)] = 'TAP_KEY_SIG'; + InputTypes[(InputTypes['TAP_SCRIPT_SIG'] = 20)] = 'TAP_SCRIPT_SIG'; + InputTypes[(InputTypes['TAP_LEAF_SCRIPT'] = 21)] = 'TAP_LEAF_SCRIPT'; + InputTypes[(InputTypes['TAP_BIP32_DERIVATION'] = 22)] = + 'TAP_BIP32_DERIVATION'; + InputTypes[(InputTypes['TAP_INTERNAL_KEY'] = 23)] = 'TAP_INTERNAL_KEY'; + InputTypes[(InputTypes['TAP_MERKLE_ROOT'] = 24)] = 'TAP_MERKLE_ROOT'; +})((InputTypes = exports.InputTypes || (exports.InputTypes = {}))); +exports.INPUT_TYPE_NAMES = [ + 'nonWitnessUtxo', + 'witnessUtxo', + 'partialSig', + 'sighashType', + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + 'finalScriptSig', + 'finalScriptWitness', + 'porCommitment', + 'tapKeySig', + 'tapScriptSig', + 'tapLeafScript', + 'tapBip32Derivation', + 'tapInternalKey', + 'tapMerkleRoot', +]; +var OutputTypes; +(function(OutputTypes) { + OutputTypes[(OutputTypes['REDEEM_SCRIPT'] = 0)] = 'REDEEM_SCRIPT'; + OutputTypes[(OutputTypes['WITNESS_SCRIPT'] = 1)] = 'WITNESS_SCRIPT'; + OutputTypes[(OutputTypes['BIP32_DERIVATION'] = 2)] = 'BIP32_DERIVATION'; + OutputTypes[(OutputTypes['TAP_INTERNAL_KEY'] = 5)] = 'TAP_INTERNAL_KEY'; + OutputTypes[(OutputTypes['TAP_TREE'] = 6)] = 'TAP_TREE'; + OutputTypes[(OutputTypes['TAP_BIP32_DERIVATION'] = 7)] = + 'TAP_BIP32_DERIVATION'; +})((OutputTypes = exports.OutputTypes || (exports.OutputTypes = {}))); +exports.OUTPUT_TYPE_NAMES = [ + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + 'tapInternalKey', + 'tapTree', + 'tapBip32Derivation', +]; + +},{}],46:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +const converter = require('./converter'); +function checkForInput(inputs, inputIndex) { + const input = inputs[inputIndex]; + if (input === undefined) throw new Error(`No input #${inputIndex}`); + return input; +} +exports.checkForInput = checkForInput; +function checkForOutput(outputs, outputIndex) { + const output = outputs[outputIndex]; + if (output === undefined) throw new Error(`No output #${outputIndex}`); + return output; +} +exports.checkForOutput = checkForOutput; +function checkHasKey(checkKeyVal, keyVals, enumLength) { + if (checkKeyVal.key[0] < enumLength) { + throw new Error( + `Use the method for your specific key instead of addUnknownKeyVal*`, + ); + } + if ( + keyVals && + keyVals.filter(kv => kv.key.equals(checkKeyVal.key)).length !== 0 + ) { + throw new Error(`Duplicate Key: ${checkKeyVal.key.toString('hex')}`); + } +} +exports.checkHasKey = checkHasKey; +function getEnumLength(myenum) { + let count = 0; + Object.keys(myenum).forEach(val => { + if (Number(isNaN(Number(val)))) { + count++; + } + }); + return count; +} +exports.getEnumLength = getEnumLength; +function inputCheckUncleanFinalized(inputIndex, input) { + let result = false; + if (input.nonWitnessUtxo || input.witnessUtxo) { + const needScriptSig = !!input.redeemScript; + const needWitnessScript = !!input.witnessScript; + const scriptSigOK = !needScriptSig || !!input.finalScriptSig; + const witnessScriptOK = !needWitnessScript || !!input.finalScriptWitness; + const hasOneFinal = !!input.finalScriptSig || !!input.finalScriptWitness; + result = scriptSigOK && witnessScriptOK && hasOneFinal; + } + if (result === false) { + throw new Error( + `Input #${inputIndex} has too much or too little data to clean`, + ); + } +} +exports.inputCheckUncleanFinalized = inputCheckUncleanFinalized; +function throwForUpdateMaker(typeName, name, expected, data) { + throw new Error( + `Data for ${typeName} key ${name} is incorrect: Expected ` + + `${expected} and got ${JSON.stringify(data)}`, + ); +} +function updateMaker(typeName) { + return (updateData, mainData) => { + for (const name of Object.keys(updateData)) { + // @ts-ignore + const data = updateData[name]; + // @ts-ignore + const { canAdd, canAddToArray, check, expected } = + // @ts-ignore + converter[typeName + 's'][name] || {}; + const isArray = !!canAddToArray; + // If unknown data. ignore and do not add + if (check) { + if (isArray) { + if ( + !Array.isArray(data) || + // @ts-ignore + (mainData[name] && !Array.isArray(mainData[name])) + ) { + throw new Error(`Key type ${name} must be an array`); + } + if (!data.every(check)) { + throwForUpdateMaker(typeName, name, expected, data); + } + // @ts-ignore + const arr = mainData[name] || []; + const dupeCheckSet = new Set(); + if (!data.every(v => canAddToArray(arr, v, dupeCheckSet))) { + throw new Error('Can not add duplicate data to array'); + } + // @ts-ignore + mainData[name] = arr.concat(data); + } else { + if (!check(data)) { + throwForUpdateMaker(typeName, name, expected, data); + } + if (!canAdd(mainData, data)) { + throw new Error(`Can not add duplicate data to ${typeName}`); + } + // @ts-ignore + mainData[name] = data; + } + } + } + }; +} +exports.updateGlobal = updateMaker('global'); +exports.updateInput = updateMaker('input'); +exports.updateOutput = updateMaker('output'); +function addInputAttributes(inputs, data) { + const index = inputs.length - 1; + const input = checkForInput(inputs, index); + exports.updateInput(data, input); +} +exports.addInputAttributes = addInputAttributes; +function addOutputAttributes(outputs, data) { + const index = outputs.length - 1; + const output = checkForOutput(outputs, index); + exports.updateOutput(data, output); +} +exports.addOutputAttributes = addOutputAttributes; +function defaultVersionSetter(version, txBuf) { + if (!Buffer.isBuffer(txBuf) || txBuf.length < 4) { + throw new Error('Set Version: Invalid Transaction'); + } + txBuf.writeUInt32LE(version, 0); + return txBuf; +} +exports.defaultVersionSetter = defaultVersionSetter; +function defaultLocktimeSetter(locktime, txBuf) { + if (!Buffer.isBuffer(txBuf) || txBuf.length < 4) { + throw new Error('Set Locktime: Invalid Transaction'); + } + txBuf.writeUInt32LE(locktime, txBuf.length - 4); + return txBuf; +} +exports.defaultLocktimeSetter = defaultLocktimeSetter; + +}).call(this)}).call(this,{"isBuffer":require("../../../../../../../usr/lib/node_modules/browserify/node_modules/is-buffer/index.js")}) +},{"../../../../../../../usr/lib/node_modules/browserify/node_modules/is-buffer/index.js":94,"./converter":20}],47:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.toOutputScript = + exports.fromOutputScript = + exports.toBech32 = + exports.toBase58Check = + exports.fromBech32 = + exports.fromBase58Check = + void 0; +const networks = require('./networks'); +const payments = require('./payments'); +const bscript = require('./script'); +const types_1 = require('./types'); +const bech32_1 = require('bech32'); +const bs58check = require('bs58check'); +const FUTURE_SEGWIT_MAX_SIZE = 40; +const FUTURE_SEGWIT_MIN_SIZE = 2; +const FUTURE_SEGWIT_MAX_VERSION = 16; +const FUTURE_SEGWIT_MIN_VERSION = 2; +const FUTURE_SEGWIT_VERSION_DIFF = 0x50; +const FUTURE_SEGWIT_VERSION_WARNING = + 'WARNING: Sending to a future segwit version address can lead to loss of funds. ' + + 'End users MUST be warned carefully in the GUI and asked if they wish to proceed ' + + 'with caution. Wallets should verify the segwit version from the output of fromBech32, ' + + 'then decide when it is safe to use which version of segwit.'; +function _toFutureSegwitAddress(output, network) { + const data = output.slice(2); + if ( + data.length < FUTURE_SEGWIT_MIN_SIZE || + data.length > FUTURE_SEGWIT_MAX_SIZE + ) + throw new TypeError('Invalid program length for segwit address'); + const version = output[0] - FUTURE_SEGWIT_VERSION_DIFF; + if ( + version < FUTURE_SEGWIT_MIN_VERSION || + version > FUTURE_SEGWIT_MAX_VERSION + ) + throw new TypeError('Invalid version for segwit address'); + if (output[1] !== data.length) + throw new TypeError('Invalid script for segwit address'); + console.warn(FUTURE_SEGWIT_VERSION_WARNING); + return toBech32(data, version, network.bech32); +} +function fromBase58Check(address) { + const payload = Buffer.from(bs58check.decode(address)); + // TODO: 4.0.0, move to "toOutputScript" + if (payload.length < 21) throw new TypeError(address + ' is too short'); + if (payload.length > 21) throw new TypeError(address + ' is too long'); + const version = payload.readUint8(0); + const hash = payload.slice(1); + return { version, hash }; +} +exports.fromBase58Check = fromBase58Check; +function fromBech32(address) { + let result; + let version; + try { + result = bech32_1.bech32.decode(address); + } catch (e) {} + if (result) { + version = result.words[0]; + if (version !== 0) throw new TypeError(address + ' uses wrong encoding'); + } else { + result = bech32_1.bech32m.decode(address); + version = result.words[0]; + if (version === 0) throw new TypeError(address + ' uses wrong encoding'); + } + const data = bech32_1.bech32.fromWords(result.words.slice(1)); + return { + version, + prefix: result.prefix, + data: Buffer.from(data), + }; +} +exports.fromBech32 = fromBech32; +function toBase58Check(hash, version) { + (0, types_1.typeforce)( + (0, types_1.tuple)(types_1.Hash160bit, types_1.UInt8), + arguments, + ); + const payload = Buffer.allocUnsafe(21); + payload.writeUInt8(version, 0); + hash.copy(payload, 1); + return bs58check.encode(payload); +} +exports.toBase58Check = toBase58Check; +function toBech32(data, version, prefix) { + const words = bech32_1.bech32.toWords(data); + words.unshift(version); + return version === 0 + ? bech32_1.bech32.encode(prefix, words) + : bech32_1.bech32m.encode(prefix, words); +} +exports.toBech32 = toBech32; +function fromOutputScript(output, network) { + // TODO: Network + network = network || networks.bitcoin; + try { + return payments.p2pkh({ output, network }).address; + } catch (e) {} + try { + return payments.p2sh({ output, network }).address; + } catch (e) {} + try { + return payments.p2wpkh({ output, network }).address; + } catch (e) {} + try { + return payments.p2wsh({ output, network }).address; + } catch (e) {} + try { + return payments.p2tr({ output, network }).address; + } catch (e) {} + try { + return _toFutureSegwitAddress(output, network); + } catch (e) {} + throw new Error(bscript.toASM(output) + ' has no matching Address'); +} +exports.fromOutputScript = fromOutputScript; +function toOutputScript(address, network) { + network = network || networks.bitcoin; + let decodeBase58; + let decodeBech32; + try { + decodeBase58 = fromBase58Check(address); + } catch (e) {} + if (decodeBase58) { + if (decodeBase58.version === network.pubKeyHash) + return payments.p2pkh({ hash: decodeBase58.hash }).output; + if (decodeBase58.version === network.scriptHash) + return payments.p2sh({ hash: decodeBase58.hash }).output; + } else { + try { + decodeBech32 = fromBech32(address); + } catch (e) {} + if (decodeBech32) { + if (decodeBech32.prefix !== network.bech32) + throw new Error(address + ' has an invalid prefix'); + if (decodeBech32.version === 0) { + if (decodeBech32.data.length === 20) + return payments.p2wpkh({ hash: decodeBech32.data }).output; + if (decodeBech32.data.length === 32) + return payments.p2wsh({ hash: decodeBech32.data }).output; + } else if (decodeBech32.version === 1) { + if (decodeBech32.data.length === 32) + return payments.p2tr({ pubkey: decodeBech32.data }).output; + } else if ( + decodeBech32.version >= FUTURE_SEGWIT_MIN_VERSION && + decodeBech32.version <= FUTURE_SEGWIT_MAX_VERSION && + decodeBech32.data.length >= FUTURE_SEGWIT_MIN_SIZE && + decodeBech32.data.length <= FUTURE_SEGWIT_MAX_SIZE + ) { + console.warn(FUTURE_SEGWIT_VERSION_WARNING); + return bscript.compile([ + decodeBech32.version + FUTURE_SEGWIT_VERSION_DIFF, + decodeBech32.data, + ]); + } + } + } + throw new Error(address + ' has no matching Script'); +} +exports.toOutputScript = toOutputScript; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./networks":55,"./payments":59,"./script":72,"./types":76,"bech32":12,"bs58check":79,"buffer":92}],48:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +// Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki +// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] +// NOTE: SIGHASH byte ignored AND restricted, truncate before use +Object.defineProperty(exports, '__esModule', { value: true }); +exports.encode = exports.decode = exports.check = void 0; +function check(buffer) { + if (buffer.length < 8) return false; + if (buffer.length > 72) return false; + if (buffer[0] !== 0x30) return false; + if (buffer[1] !== buffer.length - 2) return false; + if (buffer[2] !== 0x02) return false; + const lenR = buffer[3]; + if (lenR === 0) return false; + if (5 + lenR >= buffer.length) return false; + if (buffer[4 + lenR] !== 0x02) return false; + const lenS = buffer[5 + lenR]; + if (lenS === 0) return false; + if (6 + lenR + lenS !== buffer.length) return false; + if (buffer[4] & 0x80) return false; + if (lenR > 1 && buffer[4] === 0x00 && !(buffer[5] & 0x80)) return false; + if (buffer[lenR + 6] & 0x80) return false; + if (lenS > 1 && buffer[lenR + 6] === 0x00 && !(buffer[lenR + 7] & 0x80)) + return false; + return true; +} +exports.check = check; +function decode(buffer) { + if (buffer.length < 8) throw new Error('DER sequence length is too short'); + if (buffer.length > 72) throw new Error('DER sequence length is too long'); + if (buffer[0] !== 0x30) throw new Error('Expected DER sequence'); + if (buffer[1] !== buffer.length - 2) + throw new Error('DER sequence length is invalid'); + if (buffer[2] !== 0x02) throw new Error('Expected DER integer'); + const lenR = buffer[3]; + if (lenR === 0) throw new Error('R length is zero'); + if (5 + lenR >= buffer.length) throw new Error('R length is too long'); + if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)'); + const lenS = buffer[5 + lenR]; + if (lenS === 0) throw new Error('S length is zero'); + if (6 + lenR + lenS !== buffer.length) throw new Error('S length is invalid'); + if (buffer[4] & 0x80) throw new Error('R value is negative'); + if (lenR > 1 && buffer[4] === 0x00 && !(buffer[5] & 0x80)) + throw new Error('R value excessively padded'); + if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative'); + if (lenS > 1 && buffer[lenR + 6] === 0x00 && !(buffer[lenR + 7] & 0x80)) + throw new Error('S value excessively padded'); + // non-BIP66 - extract R, S values + return { + r: buffer.slice(4, 4 + lenR), + s: buffer.slice(6 + lenR), + }; +} +exports.decode = decode; +/* + * Expects r and s to be positive DER integers. + * + * The DER format uses the most significant bit as a sign bit (& 0x80). + * If the significant bit is set AND the integer is positive, a 0x00 is prepended. + * + * Examples: + * + * 0 => 0x00 + * 1 => 0x01 + * -1 => 0xff + * 127 => 0x7f + * -127 => 0x81 + * 128 => 0x0080 + * -128 => 0x80 + * 255 => 0x00ff + * -255 => 0xff01 + * 16300 => 0x3fac + * -16300 => 0xc054 + * 62300 => 0x00f35c + * -62300 => 0xff0ca4 + */ +function encode(r, s) { + const lenR = r.length; + const lenS = s.length; + if (lenR === 0) throw new Error('R length is zero'); + if (lenS === 0) throw new Error('S length is zero'); + if (lenR > 33) throw new Error('R length is too long'); + if (lenS > 33) throw new Error('S length is too long'); + if (r[0] & 0x80) throw new Error('R value is negative'); + if (s[0] & 0x80) throw new Error('S value is negative'); + if (lenR > 1 && r[0] === 0x00 && !(r[1] & 0x80)) + throw new Error('R value excessively padded'); + if (lenS > 1 && s[0] === 0x00 && !(s[1] & 0x80)) + throw new Error('S value excessively padded'); + const signature = Buffer.allocUnsafe(6 + lenR + lenS); + // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + signature[0] = 0x30; + signature[1] = signature.length - 2; + signature[2] = 0x02; + signature[3] = r.length; + r.copy(signature, 4); + signature[4 + lenR] = 0x02; + signature[5 + lenR] = s.length; + s.copy(signature, 6 + lenR); + return signature; +} +exports.encode = encode; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"buffer":92}],49:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.Block = void 0; +const bufferutils_1 = require('./bufferutils'); +const bcrypto = require('./crypto'); +const merkle_1 = require('./merkle'); +const transaction_1 = require('./transaction'); +const types = require('./types'); +const { typeforce } = types; +const errorMerkleNoTxes = new TypeError( + 'Cannot compute merkle root for zero transactions', +); +const errorWitnessNotSegwit = new TypeError( + 'Cannot compute witness commit for non-segwit block', +); +class Block { + constructor() { + this.version = 1; + this.prevHash = undefined; + this.merkleRoot = undefined; + this.timestamp = 0; + this.witnessCommit = undefined; + this.bits = 0; + this.nonce = 0; + this.transactions = undefined; + } + static fromBuffer(buffer) { + if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)'); + const bufferReader = new bufferutils_1.BufferReader(buffer); + const block = new Block(); + block.version = bufferReader.readInt32(); + block.prevHash = bufferReader.readSlice(32); + block.merkleRoot = bufferReader.readSlice(32); + block.timestamp = bufferReader.readUInt32(); + block.bits = bufferReader.readUInt32(); + block.nonce = bufferReader.readUInt32(); + if (buffer.length === 80) return block; + const readTransaction = () => { + const tx = transaction_1.Transaction.fromBuffer( + bufferReader.buffer.slice(bufferReader.offset), + true, + ); + bufferReader.offset += tx.byteLength(); + return tx; + }; + const nTransactions = bufferReader.readVarInt(); + block.transactions = []; + for (let i = 0; i < nTransactions; ++i) { + const tx = readTransaction(); + block.transactions.push(tx); + } + const witnessCommit = block.getWitnessCommit(); + // This Block contains a witness commit + if (witnessCommit) block.witnessCommit = witnessCommit; + return block; + } + static fromHex(hex) { + return Block.fromBuffer(Buffer.from(hex, 'hex')); + } + static calculateTarget(bits) { + const exponent = ((bits & 0xff000000) >> 24) - 3; + const mantissa = bits & 0x007fffff; + const target = Buffer.alloc(32, 0); + target.writeUIntBE(mantissa, 29 - exponent, 3); + return target; + } + static calculateMerkleRoot(transactions, forWitness) { + typeforce([{ getHash: types.Function }], transactions); + if (transactions.length === 0) throw errorMerkleNoTxes; + if (forWitness && !txesHaveWitnessCommit(transactions)) + throw errorWitnessNotSegwit; + const hashes = transactions.map(transaction => + transaction.getHash(forWitness), + ); + const rootHash = (0, merkle_1.fastMerkleRoot)(hashes, bcrypto.hash256); + return forWitness + ? bcrypto.hash256( + Buffer.concat([rootHash, transactions[0].ins[0].witness[0]]), + ) + : rootHash; + } + getWitnessCommit() { + if (!txesHaveWitnessCommit(this.transactions)) return null; + // The merkle root for the witness data is in an OP_RETURN output. + // There is no rule for the index of the output, so use filter to find it. + // The root is prepended with 0xaa21a9ed so check for 0x6a24aa21a9ed + // If multiple commits are found, the output with highest index is assumed. + const witnessCommits = this.transactions[0].outs + .filter(out => + out.script.slice(0, 6).equals(Buffer.from('6a24aa21a9ed', 'hex')), + ) + .map(out => out.script.slice(6, 38)); + if (witnessCommits.length === 0) return null; + // Use the commit with the highest output (should only be one though) + const result = witnessCommits[witnessCommits.length - 1]; + if (!(result instanceof Buffer && result.length === 32)) return null; + return result; + } + hasWitnessCommit() { + if ( + this.witnessCommit instanceof Buffer && + this.witnessCommit.length === 32 + ) + return true; + if (this.getWitnessCommit() !== null) return true; + return false; + } + hasWitness() { + return anyTxHasWitness(this.transactions); + } + weight() { + const base = this.byteLength(false, false); + const total = this.byteLength(false, true); + return base * 3 + total; + } + byteLength(headersOnly, allowWitness = true) { + if (headersOnly || !this.transactions) return 80; + return ( + 80 + + bufferutils_1.varuint.encodingLength(this.transactions.length) + + this.transactions.reduce((a, x) => a + x.byteLength(allowWitness), 0) + ); + } + getHash() { + return bcrypto.hash256(this.toBuffer(true)); + } + getId() { + return (0, bufferutils_1.reverseBuffer)(this.getHash()).toString('hex'); + } + getUTCDate() { + const date = new Date(0); // epoch + date.setUTCSeconds(this.timestamp); + return date; + } + // TODO: buffer, offset compatibility + toBuffer(headersOnly) { + const buffer = Buffer.allocUnsafe(this.byteLength(headersOnly)); + const bufferWriter = new bufferutils_1.BufferWriter(buffer); + bufferWriter.writeInt32(this.version); + bufferWriter.writeSlice(this.prevHash); + bufferWriter.writeSlice(this.merkleRoot); + bufferWriter.writeUInt32(this.timestamp); + bufferWriter.writeUInt32(this.bits); + bufferWriter.writeUInt32(this.nonce); + if (headersOnly || !this.transactions) return buffer; + bufferutils_1.varuint.encode( + this.transactions.length, + buffer, + bufferWriter.offset, + ); + bufferWriter.offset += bufferutils_1.varuint.encode.bytes; + this.transactions.forEach(tx => { + const txSize = tx.byteLength(); // TODO: extract from toBuffer? + tx.toBuffer(buffer, bufferWriter.offset); + bufferWriter.offset += txSize; + }); + return buffer; + } + toHex(headersOnly) { + return this.toBuffer(headersOnly).toString('hex'); + } + checkTxRoots() { + // If the Block has segwit transactions but no witness commit, + // there's no way it can be valid, so fail the check. + const hasWitnessCommit = this.hasWitnessCommit(); + if (!hasWitnessCommit && this.hasWitness()) return false; + return ( + this.__checkMerkleRoot() && + (hasWitnessCommit ? this.__checkWitnessCommit() : true) + ); + } + checkProofOfWork() { + const hash = (0, bufferutils_1.reverseBuffer)(this.getHash()); + const target = Block.calculateTarget(this.bits); + return hash.compare(target) <= 0; + } + __checkMerkleRoot() { + if (!this.transactions) throw errorMerkleNoTxes; + const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions); + return this.merkleRoot.compare(actualMerkleRoot) === 0; + } + __checkWitnessCommit() { + if (!this.transactions) throw errorMerkleNoTxes; + if (!this.hasWitnessCommit()) throw errorWitnessNotSegwit; + const actualWitnessCommit = Block.calculateMerkleRoot( + this.transactions, + true, + ); + return this.witnessCommit.compare(actualWitnessCommit) === 0; + } +} +exports.Block = Block; +function txesHaveWitnessCommit(transactions) { + return ( + transactions instanceof Array && + transactions[0] && + transactions[0].ins && + transactions[0].ins instanceof Array && + transactions[0].ins[0] && + transactions[0].ins[0].witness && + transactions[0].ins[0].witness instanceof Array && + transactions[0].ins[0].witness.length > 0 + ); +} +function anyTxHasWitness(transactions) { + return ( + transactions instanceof Array && + transactions.some( + tx => + typeof tx === 'object' && + tx.ins instanceof Array && + tx.ins.some( + input => + typeof input === 'object' && + input.witness instanceof Array && + input.witness.length > 0, + ), + ) + ); +} + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./bufferutils":50,"./crypto":51,"./merkle":54,"./transaction":75,"./types":76,"buffer":92}],50:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.BufferReader = + exports.BufferWriter = + exports.cloneBuffer = + exports.reverseBuffer = + exports.writeUInt64LE = + exports.readUInt64LE = + exports.varuint = + void 0; +const types = require('./types'); +const { typeforce } = types; +const varuint = require('varuint-bitcoin'); +exports.varuint = varuint; +// https://github.com/feross/buffer/blob/master/index.js#L1127 +function verifuint(value, max) { + if (typeof value !== 'number') + throw new Error('cannot write a non-number as a number'); + if (value < 0) + throw new Error('specified a negative value for writing an unsigned value'); + if (value > max) throw new Error('RangeError: value out of range'); + if (Math.floor(value) !== value) + throw new Error('value has a fractional component'); +} +function readUInt64LE(buffer, offset) { + const a = buffer.readUInt32LE(offset); + let b = buffer.readUInt32LE(offset + 4); + b *= 0x100000000; + verifuint(b + a, 0x001fffffffffffff); + return b + a; +} +exports.readUInt64LE = readUInt64LE; +function writeUInt64LE(buffer, value, offset) { + verifuint(value, 0x001fffffffffffff); + buffer.writeInt32LE(value & -1, offset); + buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); + return offset + 8; +} +exports.writeUInt64LE = writeUInt64LE; +function reverseBuffer(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; + } + return buffer; +} +exports.reverseBuffer = reverseBuffer; +function cloneBuffer(buffer) { + const clone = Buffer.allocUnsafe(buffer.length); + buffer.copy(clone); + return clone; +} +exports.cloneBuffer = cloneBuffer; +/** + * Helper class for serialization of bitcoin data types into a pre-allocated buffer. + */ +class BufferWriter { + static withCapacity(size) { + return new BufferWriter(Buffer.alloc(size)); + } + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + typeforce(types.tuple(types.Buffer, types.UInt32), [buffer, offset]); + } + writeUInt8(i) { + this.offset = this.buffer.writeUInt8(i, this.offset); + } + writeInt32(i) { + this.offset = this.buffer.writeInt32LE(i, this.offset); + } + writeUInt32(i) { + this.offset = this.buffer.writeUInt32LE(i, this.offset); + } + writeUInt64(i) { + this.offset = writeUInt64LE(this.buffer, i, this.offset); + } + writeVarInt(i) { + varuint.encode(i, this.buffer, this.offset); + this.offset += varuint.encode.bytes; + } + writeSlice(slice) { + if (this.buffer.length < this.offset + slice.length) { + throw new Error('Cannot write slice out of bounds'); + } + this.offset += slice.copy(this.buffer, this.offset); + } + writeVarSlice(slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); + } + writeVector(vector) { + this.writeVarInt(vector.length); + vector.forEach(buf => this.writeVarSlice(buf)); + } + end() { + if (this.buffer.length === this.offset) { + return this.buffer; + } + throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`); + } +} +exports.BufferWriter = BufferWriter; +/** + * Helper class for reading of bitcoin data types from a buffer. + */ +class BufferReader { + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + typeforce(types.tuple(types.Buffer, types.UInt32), [buffer, offset]); + } + readUInt8() { + const result = this.buffer.readUInt8(this.offset); + this.offset++; + return result; + } + readInt32() { + const result = this.buffer.readInt32LE(this.offset); + this.offset += 4; + return result; + } + readUInt32() { + const result = this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return result; + } + readUInt64() { + const result = readUInt64LE(this.buffer, this.offset); + this.offset += 8; + return result; + } + readVarInt() { + const vi = varuint.decode(this.buffer, this.offset); + this.offset += varuint.decode.bytes; + return vi; + } + readSlice(n) { + if (this.buffer.length < this.offset + n) { + throw new Error('Cannot read slice out of bounds'); + } + const result = this.buffer.slice(this.offset, this.offset + n); + this.offset += n; + return result; + } + readVarSlice() { + return this.readSlice(this.readVarInt()); + } + readVector() { + const count = this.readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(this.readVarSlice()); + return vector; + } +} +exports.BufferReader = BufferReader; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./types":76,"buffer":92,"varuint-bitcoin":85}],51:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.taggedHash = + exports.TAGGED_HASH_PREFIXES = + exports.TAGS = + exports.hash256 = + exports.hash160 = + exports.sha256 = + exports.sha1 = + exports.ripemd160 = + void 0; +const ripemd160_1 = require('@noble/hashes/ripemd160'); +const sha1_1 = require('@noble/hashes/sha1'); +const sha256_1 = require('@noble/hashes/sha256'); +function ripemd160(buffer) { + return Buffer.from((0, ripemd160_1.ripemd160)(Uint8Array.from(buffer))); +} +exports.ripemd160 = ripemd160; +function sha1(buffer) { + return Buffer.from((0, sha1_1.sha1)(Uint8Array.from(buffer))); +} +exports.sha1 = sha1; +function sha256(buffer) { + return Buffer.from((0, sha256_1.sha256)(Uint8Array.from(buffer))); +} +exports.sha256 = sha256; +function hash160(buffer) { + return Buffer.from( + (0, ripemd160_1.ripemd160)((0, sha256_1.sha256)(Uint8Array.from(buffer))), + ); +} +exports.hash160 = hash160; +function hash256(buffer) { + return Buffer.from( + (0, sha256_1.sha256)((0, sha256_1.sha256)(Uint8Array.from(buffer))), + ); +} +exports.hash256 = hash256; +exports.TAGS = [ + 'BIP0340/challenge', + 'BIP0340/aux', + 'BIP0340/nonce', + 'TapLeaf', + 'TapBranch', + 'TapSighash', + 'TapTweak', + 'KeyAgg list', + 'KeyAgg coefficient', +]; +/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ +exports.TAGGED_HASH_PREFIXES = { + 'BIP0340/challenge': Buffer.from([ + 123, 181, 45, 122, 159, 239, 88, 50, 62, 177, 191, 122, 64, 125, 179, 130, + 210, 243, 242, 216, 27, 177, 34, 79, 73, 254, 81, 143, 109, 72, 211, 124, + 123, 181, 45, 122, 159, 239, 88, 50, 62, 177, 191, 122, 64, 125, 179, 130, + 210, 243, 242, 216, 27, 177, 34, 79, 73, 254, 81, 143, 109, 72, 211, 124, + ]), + 'BIP0340/aux': Buffer.from([ + 241, 239, 78, 94, 192, 99, 202, 218, 109, 148, 202, 250, 157, 152, 126, 160, + 105, 38, 88, 57, 236, 193, 31, 151, 45, 119, 165, 46, 216, 193, 204, 144, + 241, 239, 78, 94, 192, 99, 202, 218, 109, 148, 202, 250, 157, 152, 126, 160, + 105, 38, 88, 57, 236, 193, 31, 151, 45, 119, 165, 46, 216, 193, 204, 144, + ]), + 'BIP0340/nonce': Buffer.from([ + 7, 73, 119, 52, 167, 155, 203, 53, 91, 155, 140, 125, 3, 79, 18, 28, 244, + 52, 215, 62, 247, 45, 218, 25, 135, 0, 97, 251, 82, 191, 235, 47, 7, 73, + 119, 52, 167, 155, 203, 53, 91, 155, 140, 125, 3, 79, 18, 28, 244, 52, 215, + 62, 247, 45, 218, 25, 135, 0, 97, 251, 82, 191, 235, 47, + ]), + TapLeaf: Buffer.from([ + 174, 234, 143, 220, 66, 8, 152, 49, 5, 115, 75, 88, 8, 29, 30, 38, 56, 211, + 95, 28, 181, 64, 8, 212, 211, 87, 202, 3, 190, 120, 233, 238, 174, 234, 143, + 220, 66, 8, 152, 49, 5, 115, 75, 88, 8, 29, 30, 38, 56, 211, 95, 28, 181, + 64, 8, 212, 211, 87, 202, 3, 190, 120, 233, 238, + ]), + TapBranch: Buffer.from([ + 25, 65, 161, 242, 229, 110, 185, 95, 162, 169, 241, 148, 190, 92, 1, 247, + 33, 111, 51, 237, 130, 176, 145, 70, 52, 144, 208, 91, 245, 22, 160, 21, 25, + 65, 161, 242, 229, 110, 185, 95, 162, 169, 241, 148, 190, 92, 1, 247, 33, + 111, 51, 237, 130, 176, 145, 70, 52, 144, 208, 91, 245, 22, 160, 21, + ]), + TapSighash: Buffer.from([ + 244, 10, 72, 223, 75, 42, 112, 200, 180, 146, 75, 242, 101, 70, 97, 237, 61, + 149, 253, 102, 163, 19, 235, 135, 35, 117, 151, 198, 40, 228, 160, 49, 244, + 10, 72, 223, 75, 42, 112, 200, 180, 146, 75, 242, 101, 70, 97, 237, 61, 149, + 253, 102, 163, 19, 235, 135, 35, 117, 151, 198, 40, 228, 160, 49, + ]), + TapTweak: Buffer.from([ + 232, 15, 225, 99, 156, 156, 160, 80, 227, 175, 27, 57, 193, 67, 198, 62, 66, + 156, 188, 235, 21, 217, 64, 251, 181, 197, 161, 244, 175, 87, 197, 233, 232, + 15, 225, 99, 156, 156, 160, 80, 227, 175, 27, 57, 193, 67, 198, 62, 66, 156, + 188, 235, 21, 217, 64, 251, 181, 197, 161, 244, 175, 87, 197, 233, + ]), + 'KeyAgg list': Buffer.from([ + 72, 28, 151, 28, 60, 11, 70, 215, 240, 178, 117, 174, 89, 141, 78, 44, 126, + 215, 49, 156, 89, 74, 92, 110, 199, 158, 160, 212, 153, 2, 148, 240, 72, 28, + 151, 28, 60, 11, 70, 215, 240, 178, 117, 174, 89, 141, 78, 44, 126, 215, 49, + 156, 89, 74, 92, 110, 199, 158, 160, 212, 153, 2, 148, 240, + ]), + 'KeyAgg coefficient': Buffer.from([ + 191, 201, 4, 3, 77, 28, 136, 232, 200, 14, 34, 229, 61, 36, 86, 109, 100, + 130, 78, 214, 66, 114, 129, 192, 145, 0, 249, 77, 205, 82, 201, 129, 191, + 201, 4, 3, 77, 28, 136, 232, 200, 14, 34, 229, 61, 36, 86, 109, 100, 130, + 78, 214, 66, 114, 129, 192, 145, 0, 249, 77, 205, 82, 201, 129, + ]), +}; +function taggedHash(prefix, data) { + return sha256(Buffer.concat([exports.TAGGED_HASH_PREFIXES[prefix], data])); +} +exports.taggedHash = taggedHash; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"@noble/hashes/ripemd160":6,"@noble/hashes/sha1":7,"@noble/hashes/sha256":8,"buffer":92}],52:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.getEccLib = exports.initEccLib = void 0; +const _ECCLIB_CACHE = {}; +function initEccLib(eccLib) { + if (!eccLib) { + // allow clearing the library + _ECCLIB_CACHE.eccLib = eccLib; + } else if (eccLib !== _ECCLIB_CACHE.eccLib) { + // new instance, verify it + verifyEcc(eccLib); + _ECCLIB_CACHE.eccLib = eccLib; + } +} +exports.initEccLib = initEccLib; +function getEccLib() { + if (!_ECCLIB_CACHE.eccLib) + throw new Error( + 'No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance', + ); + return _ECCLIB_CACHE.eccLib; +} +exports.getEccLib = getEccLib; +const h = hex => Buffer.from(hex, 'hex'); +function verifyEcc(ecc) { + assert(typeof ecc.isXOnlyPoint === 'function'); + assert( + ecc.isXOnlyPoint( + h('79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'), + ), + ); + assert( + ecc.isXOnlyPoint( + h('fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e'), + ), + ); + assert( + ecc.isXOnlyPoint( + h('f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9'), + ), + ); + assert( + ecc.isXOnlyPoint( + h('0000000000000000000000000000000000000000000000000000000000000001'), + ), + ); + assert( + !ecc.isXOnlyPoint( + h('0000000000000000000000000000000000000000000000000000000000000000'), + ), + ); + assert( + !ecc.isXOnlyPoint( + h('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'), + ), + ); + assert(typeof ecc.xOnlyPointAddTweak === 'function'); + tweakAddVectors.forEach(t => { + const r = ecc.xOnlyPointAddTweak(h(t.pubkey), h(t.tweak)); + if (t.result === null) { + assert(r === null); + } else { + assert(r !== null); + assert(r.parity === t.parity); + assert(Buffer.from(r.xOnlyPubkey).equals(h(t.result))); + } + }); +} +function assert(bool) { + if (!bool) throw new Error('ecc library invalid'); +} +const tweakAddVectors = [ + { + pubkey: '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + tweak: 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140', + parity: -1, + result: null, + }, + { + pubkey: '1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b', + tweak: 'a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac', + parity: 1, + result: 'e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf', + }, + { + pubkey: '2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991', + tweak: '823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47', + parity: 0, + result: '9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c', + }, +]; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"buffer":92}],53:[function(require,module,exports){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.initEccLib = + exports.Transaction = + exports.opcodes = + exports.Psbt = + exports.Block = + exports.script = + exports.payments = + exports.networks = + exports.crypto = + exports.address = + void 0; +const address = require('./address'); +exports.address = address; +const crypto = require('./crypto'); +exports.crypto = crypto; +const networks = require('./networks'); +exports.networks = networks; +const payments = require('./payments'); +exports.payments = payments; +const script = require('./script'); +exports.script = script; +var block_1 = require('./block'); +Object.defineProperty(exports, 'Block', { + enumerable: true, + get: function () { + return block_1.Block; + }, +}); +var psbt_1 = require('./psbt'); +Object.defineProperty(exports, 'Psbt', { + enumerable: true, + get: function () { + return psbt_1.Psbt; + }, +}); +var ops_1 = require('./ops'); +Object.defineProperty(exports, 'opcodes', { + enumerable: true, + get: function () { + return ops_1.OPS; + }, +}); +var transaction_1 = require('./transaction'); +Object.defineProperty(exports, 'Transaction', { + enumerable: true, + get: function () { + return transaction_1.Transaction; + }, +}); +var ecc_lib_1 = require('./ecc_lib'); +Object.defineProperty(exports, 'initEccLib', { + enumerable: true, + get: function () { + return ecc_lib_1.initEccLib; + }, +}); + +},{"./address":47,"./block":49,"./crypto":51,"./ecc_lib":52,"./networks":55,"./ops":56,"./payments":59,"./psbt":68,"./script":72,"./transaction":75}],54:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.fastMerkleRoot = void 0; +function fastMerkleRoot(values, digestFn) { + if (!Array.isArray(values)) throw TypeError('Expected values Array'); + if (typeof digestFn !== 'function') + throw TypeError('Expected digest Function'); + let length = values.length; + const results = values.concat(); + while (length > 1) { + let j = 0; + for (let i = 0; i < length; i += 2, ++j) { + const left = results[i]; + const right = i + 1 === length ? left : results[i + 1]; + const data = Buffer.concat([left, right]); + results[j] = digestFn(data); + } + length = j; + } + return results[0]; +} +exports.fastMerkleRoot = fastMerkleRoot; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"buffer":92}],55:[function(require,module,exports){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.testnet = exports.regtest = exports.bitcoin = void 0; +exports.bitcoin = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bc', + bip32: { + public: 0x0488b21e, + private: 0x0488ade4, + }, + pubKeyHash: 0x00, + scriptHash: 0x05, + wif: 0x80, +}; +exports.regtest = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bcrt', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, +}; +exports.testnet = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'tb', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, +}; + +},{}],56:[function(require,module,exports){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.REVERSE_OPS = exports.OPS = void 0; +const OPS = { + OP_FALSE: 0, + OP_0: 0, + OP_PUSHDATA1: 76, + OP_PUSHDATA2: 77, + OP_PUSHDATA4: 78, + OP_1NEGATE: 79, + OP_RESERVED: 80, + OP_TRUE: 81, + OP_1: 81, + OP_2: 82, + OP_3: 83, + OP_4: 84, + OP_5: 85, + OP_6: 86, + OP_7: 87, + OP_8: 88, + OP_9: 89, + OP_10: 90, + OP_11: 91, + OP_12: 92, + OP_13: 93, + OP_14: 94, + OP_15: 95, + OP_16: 96, + OP_NOP: 97, + OP_VER: 98, + OP_IF: 99, + OP_NOTIF: 100, + OP_VERIF: 101, + OP_VERNOTIF: 102, + OP_ELSE: 103, + OP_ENDIF: 104, + OP_VERIFY: 105, + OP_RETURN: 106, + OP_TOALTSTACK: 107, + OP_FROMALTSTACK: 108, + OP_2DROP: 109, + OP_2DUP: 110, + OP_3DUP: 111, + OP_2OVER: 112, + OP_2ROT: 113, + OP_2SWAP: 114, + OP_IFDUP: 115, + OP_DEPTH: 116, + OP_DROP: 117, + OP_DUP: 118, + OP_NIP: 119, + OP_OVER: 120, + OP_PICK: 121, + OP_ROLL: 122, + OP_ROT: 123, + OP_SWAP: 124, + OP_TUCK: 125, + OP_CAT: 126, + OP_SUBSTR: 127, + OP_LEFT: 128, + OP_RIGHT: 129, + OP_SIZE: 130, + OP_INVERT: 131, + OP_AND: 132, + OP_OR: 133, + OP_XOR: 134, + OP_EQUAL: 135, + OP_EQUALVERIFY: 136, + OP_RESERVED1: 137, + OP_RESERVED2: 138, + OP_1ADD: 139, + OP_1SUB: 140, + OP_2MUL: 141, + OP_2DIV: 142, + OP_NEGATE: 143, + OP_ABS: 144, + OP_NOT: 145, + OP_0NOTEQUAL: 146, + OP_ADD: 147, + OP_SUB: 148, + OP_MUL: 149, + OP_DIV: 150, + OP_MOD: 151, + OP_LSHIFT: 152, + OP_RSHIFT: 153, + OP_BOOLAND: 154, + OP_BOOLOR: 155, + OP_NUMEQUAL: 156, + OP_NUMEQUALVERIFY: 157, + OP_NUMNOTEQUAL: 158, + OP_LESSTHAN: 159, + OP_GREATERTHAN: 160, + OP_LESSTHANOREQUAL: 161, + OP_GREATERTHANOREQUAL: 162, + OP_MIN: 163, + OP_MAX: 164, + OP_WITHIN: 165, + OP_RIPEMD160: 166, + OP_SHA1: 167, + OP_SHA256: 168, + OP_HASH160: 169, + OP_HASH256: 170, + OP_CODESEPARATOR: 171, + OP_CHECKSIG: 172, + OP_CHECKSIGVERIFY: 173, + OP_CHECKMULTISIG: 174, + OP_CHECKMULTISIGVERIFY: 175, + OP_NOP1: 176, + OP_NOP2: 177, + OP_CHECKLOCKTIMEVERIFY: 177, + OP_NOP3: 178, + OP_CHECKSEQUENCEVERIFY: 178, + OP_NOP4: 179, + OP_NOP5: 180, + OP_NOP6: 181, + OP_NOP7: 182, + OP_NOP8: 183, + OP_NOP9: 184, + OP_NOP10: 185, + OP_CHECKSIGADD: 186, + OP_PUBKEYHASH: 253, + OP_PUBKEY: 254, + OP_INVALIDOPCODE: 255, +}; +exports.OPS = OPS; +const REVERSE_OPS = {}; +exports.REVERSE_OPS = REVERSE_OPS; +for (const op of Object.keys(OPS)) { + const code = OPS[op]; + REVERSE_OPS[code] = op; +} + +},{}],57:[function(require,module,exports){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.tweakKey = + exports.tapTweakHash = + exports.tapleafHash = + exports.findScriptPath = + exports.toHashTree = + exports.rootHashFromPath = + exports.MAX_TAPTREE_DEPTH = + exports.LEAF_VERSION_TAPSCRIPT = + void 0; +const buffer_1 = require('buffer'); +const ecc_lib_1 = require('../ecc_lib'); +const bcrypto = require('../crypto'); +const bufferutils_1 = require('../bufferutils'); +const types_1 = require('../types'); +exports.LEAF_VERSION_TAPSCRIPT = 0xc0; +exports.MAX_TAPTREE_DEPTH = 128; +const isHashBranch = ht => 'left' in ht && 'right' in ht; +function rootHashFromPath(controlBlock, leafHash) { + if (controlBlock.length < 33) + throw new TypeError( + `The control-block length is too small. Got ${controlBlock.length}, expected min 33.`, + ); + const m = (controlBlock.length - 33) / 32; + let kj = leafHash; + for (let j = 0; j < m; j++) { + const ej = controlBlock.slice(33 + 32 * j, 65 + 32 * j); + if (kj.compare(ej) < 0) { + kj = tapBranchHash(kj, ej); + } else { + kj = tapBranchHash(ej, kj); + } + } + return kj; +} +exports.rootHashFromPath = rootHashFromPath; +/** + * Build a hash tree of merkle nodes from the scripts binary tree. + * @param scriptTree - the tree of scripts to pairwise hash. + */ +function toHashTree(scriptTree) { + if ((0, types_1.isTapleaf)(scriptTree)) + return { hash: tapleafHash(scriptTree) }; + const hashes = [toHashTree(scriptTree[0]), toHashTree(scriptTree[1])]; + hashes.sort((a, b) => a.hash.compare(b.hash)); + const [left, right] = hashes; + return { + hash: tapBranchHash(left.hash, right.hash), + left, + right, + }; +} +exports.toHashTree = toHashTree; +/** + * Given a HashTree, finds the path from a particular hash to the root. + * @param node - the root of the tree + * @param hash - the hash to search for + * @returns - array of sibling hashes, from leaf (inclusive) to root + * (exclusive) needed to prove inclusion of the specified hash. undefined if no + * path is found + */ +function findScriptPath(node, hash) { + if (isHashBranch(node)) { + const leftPath = findScriptPath(node.left, hash); + if (leftPath !== undefined) return [...leftPath, node.right.hash]; + const rightPath = findScriptPath(node.right, hash); + if (rightPath !== undefined) return [...rightPath, node.left.hash]; + } else if (node.hash.equals(hash)) { + return []; + } + return undefined; +} +exports.findScriptPath = findScriptPath; +function tapleafHash(leaf) { + const version = leaf.version || exports.LEAF_VERSION_TAPSCRIPT; + return bcrypto.taggedHash( + 'TapLeaf', + buffer_1.Buffer.concat([ + buffer_1.Buffer.from([version]), + serializeScript(leaf.output), + ]), + ); +} +exports.tapleafHash = tapleafHash; +function tapTweakHash(pubKey, h) { + return bcrypto.taggedHash( + 'TapTweak', + buffer_1.Buffer.concat(h ? [pubKey, h] : [pubKey]), + ); +} +exports.tapTweakHash = tapTweakHash; +function tweakKey(pubKey, h) { + if (!buffer_1.Buffer.isBuffer(pubKey)) return null; + if (pubKey.length !== 32) return null; + if (h && h.length !== 32) return null; + const tweakHash = tapTweakHash(pubKey, h); + const res = (0, ecc_lib_1.getEccLib)().xOnlyPointAddTweak(pubKey, tweakHash); + if (!res || res.xOnlyPubkey === null) return null; + return { + parity: res.parity, + x: buffer_1.Buffer.from(res.xOnlyPubkey), + }; +} +exports.tweakKey = tweakKey; +function tapBranchHash(a, b) { + return bcrypto.taggedHash('TapBranch', buffer_1.Buffer.concat([a, b])); +} +function serializeScript(s) { + const varintLen = bufferutils_1.varuint.encodingLength(s.length); + const buffer = buffer_1.Buffer.allocUnsafe(varintLen); // better + bufferutils_1.varuint.encode(s.length, buffer); + return buffer_1.Buffer.concat([buffer, s]); +} + +},{"../bufferutils":50,"../crypto":51,"../ecc_lib":52,"../types":76,"buffer":92}],58:[function(require,module,exports){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.p2data = void 0; +const networks_1 = require('../networks'); +const bscript = require('../script'); +const types_1 = require('../types'); +const lazy = require('./lazy'); +const OPS = bscript.OPS; +function stacksEqual(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); +} +// output: OP_RETURN ... +function p2data(a, opts) { + if (!a.data && !a.output) throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + (0, types_1.typeforce)( + { + network: types_1.typeforce.maybe(types_1.typeforce.Object), + output: types_1.typeforce.maybe(types_1.typeforce.Buffer), + data: types_1.typeforce.maybe( + types_1.typeforce.arrayOf(types_1.typeforce.Buffer), + ), + }, + a, + ); + const network = a.network || networks_1.bitcoin; + const o = { name: 'embed', network }; + lazy.prop(o, 'output', () => { + if (!a.data) return; + return bscript.compile([OPS.OP_RETURN].concat(a.data)); + }); + lazy.prop(o, 'data', () => { + if (!a.output) return; + return bscript.decompile(a.output).slice(1); + }); + // extended validation + if (opts.validate) { + if (a.output) { + const chunks = bscript.decompile(a.output); + if (chunks[0] !== OPS.OP_RETURN) throw new TypeError('Output is invalid'); + if (!chunks.slice(1).every(types_1.typeforce.Buffer)) + throw new TypeError('Output is invalid'); + if (a.data && !stacksEqual(a.data, o.data)) + throw new TypeError('Data mismatch'); + } + } + return Object.assign(o, a); +} +exports.p2data = p2data; + +},{"../networks":55,"../script":72,"../types":76,"./lazy":60}],59:[function(require,module,exports){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.p2tr = + exports.p2wsh = + exports.p2wpkh = + exports.p2sh = + exports.p2pkh = + exports.p2pk = + exports.p2ms = + exports.embed = + void 0; +const embed_1 = require('./embed'); +Object.defineProperty(exports, 'embed', { + enumerable: true, + get: function () { + return embed_1.p2data; + }, +}); +const p2ms_1 = require('./p2ms'); +Object.defineProperty(exports, 'p2ms', { + enumerable: true, + get: function () { + return p2ms_1.p2ms; + }, +}); +const p2pk_1 = require('./p2pk'); +Object.defineProperty(exports, 'p2pk', { + enumerable: true, + get: function () { + return p2pk_1.p2pk; + }, +}); +const p2pkh_1 = require('./p2pkh'); +Object.defineProperty(exports, 'p2pkh', { + enumerable: true, + get: function () { + return p2pkh_1.p2pkh; + }, +}); +const p2sh_1 = require('./p2sh'); +Object.defineProperty(exports, 'p2sh', { + enumerable: true, + get: function () { + return p2sh_1.p2sh; + }, +}); +const p2wpkh_1 = require('./p2wpkh'); +Object.defineProperty(exports, 'p2wpkh', { + enumerable: true, + get: function () { + return p2wpkh_1.p2wpkh; + }, +}); +const p2wsh_1 = require('./p2wsh'); +Object.defineProperty(exports, 'p2wsh', { + enumerable: true, + get: function () { + return p2wsh_1.p2wsh; + }, +}); +const p2tr_1 = require('./p2tr'); +Object.defineProperty(exports, 'p2tr', { + enumerable: true, + get: function () { + return p2tr_1.p2tr; + }, +}); +// TODO +// witness commitment + +},{"./embed":58,"./p2ms":61,"./p2pk":62,"./p2pkh":63,"./p2sh":64,"./p2tr":65,"./p2wpkh":66,"./p2wsh":67}],60:[function(require,module,exports){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.value = exports.prop = void 0; +function prop(object, name, f) { + Object.defineProperty(object, name, { + configurable: true, + enumerable: true, + get() { + const _value = f.call(this); + this[name] = _value; + return _value; + }, + set(_value) { + Object.defineProperty(this, name, { + configurable: true, + enumerable: true, + value: _value, + writable: true, + }); + }, + }); +} +exports.prop = prop; +function value(f) { + let _value; + return () => { + if (_value !== undefined) return _value; + _value = f(); + return _value; + }; +} +exports.value = value; + +},{}],61:[function(require,module,exports){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.p2ms = void 0; +const networks_1 = require('../networks'); +const bscript = require('../script'); +const types_1 = require('../types'); +const lazy = require('./lazy'); +const OPS = bscript.OPS; +const OP_INT_BASE = OPS.OP_RESERVED; // OP_1 - 1 +function stacksEqual(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); +} +// input: OP_0 [signatures ...] +// output: m [pubKeys ...] n OP_CHECKMULTISIG +function p2ms(a, opts) { + if ( + !a.input && + !a.output && + !(a.pubkeys && a.m !== undefined) && + !a.signatures + ) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + function isAcceptableSignature(x) { + return ( + bscript.isCanonicalScriptSignature(x) || + (opts.allowIncomplete && x === OPS.OP_0) !== undefined + ); + } + (0, types_1.typeforce)( + { + network: types_1.typeforce.maybe(types_1.typeforce.Object), + m: types_1.typeforce.maybe(types_1.typeforce.Number), + n: types_1.typeforce.maybe(types_1.typeforce.Number), + output: types_1.typeforce.maybe(types_1.typeforce.Buffer), + pubkeys: types_1.typeforce.maybe( + types_1.typeforce.arrayOf(types_1.isPoint), + ), + signatures: types_1.typeforce.maybe( + types_1.typeforce.arrayOf(isAcceptableSignature), + ), + input: types_1.typeforce.maybe(types_1.typeforce.Buffer), + }, + a, + ); + const network = a.network || networks_1.bitcoin; + const o = { network }; + let chunks = []; + let decoded = false; + function decode(output) { + if (decoded) return; + decoded = true; + chunks = bscript.decompile(output); + o.m = chunks[0] - OP_INT_BASE; + o.n = chunks[chunks.length - 2] - OP_INT_BASE; + o.pubkeys = chunks.slice(1, -2); + } + lazy.prop(o, 'output', () => { + if (!a.m) return; + if (!o.n) return; + if (!a.pubkeys) return; + return bscript.compile( + [].concat( + OP_INT_BASE + a.m, + a.pubkeys, + OP_INT_BASE + o.n, + OPS.OP_CHECKMULTISIG, + ), + ); + }); + lazy.prop(o, 'm', () => { + if (!o.output) return; + decode(o.output); + return o.m; + }); + lazy.prop(o, 'n', () => { + if (!o.pubkeys) return; + return o.pubkeys.length; + }); + lazy.prop(o, 'pubkeys', () => { + if (!a.output) return; + decode(a.output); + return o.pubkeys; + }); + lazy.prop(o, 'signatures', () => { + if (!a.input) return; + return bscript.decompile(a.input).slice(1); + }); + lazy.prop(o, 'input', () => { + if (!a.signatures) return; + return bscript.compile([OPS.OP_0].concat(a.signatures)); + }); + lazy.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + lazy.prop(o, 'name', () => { + if (!o.m || !o.n) return; + return `p2ms(${o.m} of ${o.n})`; + }); + // extended validation + if (opts.validate) { + if (a.output) { + decode(a.output); + if (!types_1.typeforce.Number(chunks[0])) + throw new TypeError('Output is invalid'); + if (!types_1.typeforce.Number(chunks[chunks.length - 2])) + throw new TypeError('Output is invalid'); + if (chunks[chunks.length - 1] !== OPS.OP_CHECKMULTISIG) + throw new TypeError('Output is invalid'); + if (o.m <= 0 || o.n > 16 || o.m > o.n || o.n !== chunks.length - 3) + throw new TypeError('Output is invalid'); + if (!o.pubkeys.every(x => (0, types_1.isPoint)(x))) + throw new TypeError('Output is invalid'); + if (a.m !== undefined && a.m !== o.m) throw new TypeError('m mismatch'); + if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch'); + if (a.pubkeys && !stacksEqual(a.pubkeys, o.pubkeys)) + throw new TypeError('Pubkeys mismatch'); + } + if (a.pubkeys) { + if (a.n !== undefined && a.n !== a.pubkeys.length) + throw new TypeError('Pubkey count mismatch'); + o.n = a.pubkeys.length; + if (o.n < o.m) throw new TypeError('Pubkey count cannot be less than m'); + } + if (a.signatures) { + if (a.signatures.length < o.m) + throw new TypeError('Not enough signatures provided'); + if (a.signatures.length > o.m) + throw new TypeError('Too many signatures provided'); + } + if (a.input) { + if (a.input[0] !== OPS.OP_0) throw new TypeError('Input is invalid'); + if ( + o.signatures.length === 0 || + !o.signatures.every(isAcceptableSignature) + ) + throw new TypeError('Input has invalid signature(s)'); + if (a.signatures && !stacksEqual(a.signatures, o.signatures)) + throw new TypeError('Signature mismatch'); + if (a.m !== undefined && a.m !== a.signatures.length) + throw new TypeError('Signature count mismatch'); + } + } + return Object.assign(o, a); +} +exports.p2ms = p2ms; + +},{"../networks":55,"../script":72,"../types":76,"./lazy":60}],62:[function(require,module,exports){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.p2pk = void 0; +const networks_1 = require('../networks'); +const bscript = require('../script'); +const types_1 = require('../types'); +const lazy = require('./lazy'); +const OPS = bscript.OPS; +// input: {signature} +// output: {pubKey} OP_CHECKSIG +function p2pk(a, opts) { + if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + (0, types_1.typeforce)( + { + network: types_1.typeforce.maybe(types_1.typeforce.Object), + output: types_1.typeforce.maybe(types_1.typeforce.Buffer), + pubkey: types_1.typeforce.maybe(types_1.isPoint), + signature: types_1.typeforce.maybe(bscript.isCanonicalScriptSignature), + input: types_1.typeforce.maybe(types_1.typeforce.Buffer), + }, + a, + ); + const _chunks = lazy.value(() => { + return bscript.decompile(a.input); + }); + const network = a.network || networks_1.bitcoin; + const o = { name: 'p2pk', network }; + lazy.prop(o, 'output', () => { + if (!a.pubkey) return; + return bscript.compile([a.pubkey, OPS.OP_CHECKSIG]); + }); + lazy.prop(o, 'pubkey', () => { + if (!a.output) return; + return a.output.slice(1, -1); + }); + lazy.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy.prop(o, 'input', () => { + if (!a.signature) return; + return bscript.compile([a.signature]); + }); + lazy.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + if (a.output) { + if (a.output[a.output.length - 1] !== OPS.OP_CHECKSIG) + throw new TypeError('Output is invalid'); + if (!(0, types_1.isPoint)(o.pubkey)) + throw new TypeError('Output pubkey is invalid'); + if (a.pubkey && !a.pubkey.equals(o.pubkey)) + throw new TypeError('Pubkey mismatch'); + } + if (a.signature) { + if (a.input && !a.input.equals(o.input)) + throw new TypeError('Signature mismatch'); + } + if (a.input) { + if (_chunks().length !== 1) throw new TypeError('Input is invalid'); + if (!bscript.isCanonicalScriptSignature(o.signature)) + throw new TypeError('Input has invalid signature'); + } + } + return Object.assign(o, a); +} +exports.p2pk = p2pk; + +},{"../networks":55,"../script":72,"../types":76,"./lazy":60}],63:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.p2pkh = void 0; +const bcrypto = require('../crypto'); +const networks_1 = require('../networks'); +const bscript = require('../script'); +const types_1 = require('../types'); +const lazy = require('./lazy'); +const bs58check = require('bs58check'); +const OPS = bscript.OPS; +// input: {signature} {pubkey} +// output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG +function p2pkh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + (0, types_1.typeforce)( + { + network: types_1.typeforce.maybe(types_1.typeforce.Object), + address: types_1.typeforce.maybe(types_1.typeforce.String), + hash: types_1.typeforce.maybe(types_1.typeforce.BufferN(20)), + output: types_1.typeforce.maybe(types_1.typeforce.BufferN(25)), + pubkey: types_1.typeforce.maybe(types_1.isPoint), + signature: types_1.typeforce.maybe(bscript.isCanonicalScriptSignature), + input: types_1.typeforce.maybe(types_1.typeforce.Buffer), + }, + a, + ); + const _address = lazy.value(() => { + const payload = Buffer.from(bs58check.decode(a.address)); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy.value(() => { + return bscript.decompile(a.input); + }); + const network = a.network || networks_1.bitcoin; + const o = { name: 'p2pkh', network }; + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const payload = Buffer.allocUnsafe(21); + payload.writeUInt8(network.pubKeyHash, 0); + o.hash.copy(payload, 1); + return bs58check.encode(payload); + }); + lazy.prop(o, 'hash', () => { + if (a.output) return a.output.slice(3, 23); + if (a.address) return _address().hash; + if (a.pubkey || o.pubkey) return bcrypto.hash160(a.pubkey || o.pubkey); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript.compile([ + OPS.OP_DUP, + OPS.OP_HASH160, + o.hash, + OPS.OP_EQUALVERIFY, + OPS.OP_CHECKSIG, + ]); + }); + lazy.prop(o, 'pubkey', () => { + if (!a.input) return; + return _chunks()[1]; + }); + lazy.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy.prop(o, 'input', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return bscript.compile([a.signature, a.pubkey]); + }); + lazy.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + let hash = Buffer.from([]); + if (a.address) { + if (_address().version !== network.pubKeyHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 25 || + a.output[0] !== OPS.OP_DUP || + a.output[1] !== OPS.OP_HASH160 || + a.output[2] !== 0x14 || + a.output[23] !== OPS.OP_EQUALVERIFY || + a.output[24] !== OPS.OP_CHECKSIG + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(3, 23); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.pubkey) { + const pkh = bcrypto.hash160(a.pubkey); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + else hash = pkh; + } + if (a.input) { + const chunks = _chunks(); + if (chunks.length !== 2) throw new TypeError('Input is invalid'); + if (!bscript.isCanonicalScriptSignature(chunks[0])) + throw new TypeError('Input has invalid signature'); + if (!(0, types_1.isPoint)(chunks[1])) + throw new TypeError('Input has invalid pubkey'); + if (a.signature && !a.signature.equals(chunks[0])) + throw new TypeError('Signature mismatch'); + if (a.pubkey && !a.pubkey.equals(chunks[1])) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto.hash160(chunks[1]); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + } + } + return Object.assign(o, a); +} +exports.p2pkh = p2pkh; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../crypto":51,"../networks":55,"../script":72,"../types":76,"./lazy":60,"bs58check":79,"buffer":92}],64:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.p2sh = void 0; +const bcrypto = require('../crypto'); +const networks_1 = require('../networks'); +const bscript = require('../script'); +const types_1 = require('../types'); +const lazy = require('./lazy'); +const bs58check = require('bs58check'); +const OPS = bscript.OPS; +function stacksEqual(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); +} +// input: [redeemScriptSig ...] {redeemScript} +// witness: +// output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL +function p2sh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + (0, types_1.typeforce)( + { + network: types_1.typeforce.maybe(types_1.typeforce.Object), + address: types_1.typeforce.maybe(types_1.typeforce.String), + hash: types_1.typeforce.maybe(types_1.typeforce.BufferN(20)), + output: types_1.typeforce.maybe(types_1.typeforce.BufferN(23)), + redeem: types_1.typeforce.maybe({ + network: types_1.typeforce.maybe(types_1.typeforce.Object), + output: types_1.typeforce.maybe(types_1.typeforce.Buffer), + input: types_1.typeforce.maybe(types_1.typeforce.Buffer), + witness: types_1.typeforce.maybe( + types_1.typeforce.arrayOf(types_1.typeforce.Buffer), + ), + }), + input: types_1.typeforce.maybe(types_1.typeforce.Buffer), + witness: types_1.typeforce.maybe( + types_1.typeforce.arrayOf(types_1.typeforce.Buffer), + ), + }, + a, + ); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || networks_1.bitcoin; + } + const o = { network }; + const _address = lazy.value(() => { + const payload = Buffer.from(bs58check.decode(a.address)); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy.value(() => { + return bscript.decompile(a.input); + }); + const _redeem = lazy.value(() => { + const chunks = _chunks(); + const lastChunk = chunks[chunks.length - 1]; + return { + network, + output: lastChunk === OPS.OP_FALSE ? Buffer.from([]) : lastChunk, + input: bscript.compile(chunks.slice(0, -1)), + witness: a.witness || [], + }; + }); + // output dependents + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const payload = Buffer.allocUnsafe(21); + payload.writeUInt8(o.network.scriptHash, 0); + o.hash.copy(payload, 1); + return bs58check.encode(payload); + }); + lazy.prop(o, 'hash', () => { + // in order of least effort + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().hash; + if (o.redeem && o.redeem.output) return bcrypto.hash160(o.redeem.output); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript.compile([OPS.OP_HASH160, o.hash, OPS.OP_EQUAL]); + }); + // input dependents + lazy.prop(o, 'redeem', () => { + if (!a.input) return; + return _redeem(); + }); + lazy.prop(o, 'input', () => { + if (!a.redeem || !a.redeem.input || !a.redeem.output) return; + return bscript.compile( + [].concat(bscript.decompile(a.redeem.input), a.redeem.output), + ); + }); + lazy.prop(o, 'witness', () => { + if (o.redeem && o.redeem.witness) return o.redeem.witness; + if (o.input) return []; + }); + lazy.prop(o, 'name', () => { + const nameParts = ['p2sh']; + if (o.redeem !== undefined && o.redeem.name !== undefined) + nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + if (opts.validate) { + let hash = Buffer.from([]); + if (a.address) { + if (_address().version !== network.scriptHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 23 || + a.output[0] !== OPS.OP_HASH160 || + a.output[1] !== 0x14 || + a.output[22] !== OPS.OP_EQUAL + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2, 22); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + // inlined to prevent 'no-inner-declarations' failing + const checkRedeem = redeem => { + // is the redeem output empty/invalid? + if (redeem.output) { + const decompile = bscript.decompile(redeem.output); + if (!decompile || decompile.length < 1) + throw new TypeError('Redeem.output too short'); + if (redeem.output.byteLength > 520) + throw new TypeError( + 'Redeem.output unspendable if larger than 520 bytes', + ); + if (bscript.countNonPushOnlyOPs(decompile) > 201) + throw new TypeError( + 'Redeem.output unspendable with more than 201 non-push ops', + ); + // match hash against other sources + const hash2 = bcrypto.hash160(redeem.output); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (redeem.input) { + const hasInput = redeem.input.length > 0; + const hasWitness = redeem.witness && redeem.witness.length > 0; + if (!hasInput && !hasWitness) throw new TypeError('Empty input'); + if (hasInput && hasWitness) + throw new TypeError('Input and witness provided'); + if (hasInput) { + const richunks = bscript.decompile(redeem.input); + if (!bscript.isPushOnly(richunks)) + throw new TypeError('Non push-only scriptSig'); + } + } + }; + if (a.input) { + const chunks = _chunks(); + if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); + if (!Buffer.isBuffer(_redeem().output)) + throw new TypeError('Input is invalid'); + checkRedeem(_redeem()); + } + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + if (a.input) { + const redeem = _redeem(); + if (a.redeem.output && !a.redeem.output.equals(redeem.output)) + throw new TypeError('Redeem.output mismatch'); + if (a.redeem.input && !a.redeem.input.equals(redeem.input)) + throw new TypeError('Redeem.input mismatch'); + } + checkRedeem(a.redeem); + } + if (a.witness) { + if ( + a.redeem && + a.redeem.witness && + !stacksEqual(a.redeem.witness, a.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); + } + } + return Object.assign(o, a); +} +exports.p2sh = p2sh; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../crypto":51,"../networks":55,"../script":72,"../types":76,"./lazy":60,"bs58check":79,"buffer":92}],65:[function(require,module,exports){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.p2tr = void 0; +const buffer_1 = require('buffer'); +const networks_1 = require('../networks'); +const bscript = require('../script'); +const types_1 = require('../types'); +const ecc_lib_1 = require('../ecc_lib'); +const bip341_1 = require('./bip341'); +const lazy = require('./lazy'); +const bech32_1 = require('bech32'); +const OPS = bscript.OPS; +const TAPROOT_WITNESS_VERSION = 0x01; +const ANNEX_PREFIX = 0x50; +function p2tr(a, opts) { + if ( + !a.address && + !a.output && + !a.pubkey && + !a.internalPubkey && + !(a.witness && a.witness.length > 1) + ) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + (0, types_1.typeforce)( + { + address: types_1.typeforce.maybe(types_1.typeforce.String), + input: types_1.typeforce.maybe(types_1.typeforce.BufferN(0)), + network: types_1.typeforce.maybe(types_1.typeforce.Object), + output: types_1.typeforce.maybe(types_1.typeforce.BufferN(34)), + internalPubkey: types_1.typeforce.maybe(types_1.typeforce.BufferN(32)), + hash: types_1.typeforce.maybe(types_1.typeforce.BufferN(32)), + pubkey: types_1.typeforce.maybe(types_1.typeforce.BufferN(32)), + signature: types_1.typeforce.maybe( + types_1.typeforce.anyOf( + types_1.typeforce.BufferN(64), + types_1.typeforce.BufferN(65), + ), + ), + witness: types_1.typeforce.maybe( + types_1.typeforce.arrayOf(types_1.typeforce.Buffer), + ), + scriptTree: types_1.typeforce.maybe(types_1.isTaptree), + redeem: types_1.typeforce.maybe({ + output: types_1.typeforce.maybe(types_1.typeforce.Buffer), + redeemVersion: types_1.typeforce.maybe(types_1.typeforce.Number), + witness: types_1.typeforce.maybe( + types_1.typeforce.arrayOf(types_1.typeforce.Buffer), + ), + }), + redeemVersion: types_1.typeforce.maybe(types_1.typeforce.Number), + }, + a, + ); + const _address = lazy.value(() => { + const result = bech32_1.bech32m.decode(a.address); + const version = result.words.shift(); + const data = bech32_1.bech32m.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: buffer_1.Buffer.from(data), + }; + }); + // remove annex if present, ignored by taproot + const _witness = lazy.value(() => { + if (!a.witness || !a.witness.length) return; + if ( + a.witness.length >= 2 && + a.witness[a.witness.length - 1][0] === ANNEX_PREFIX + ) { + return a.witness.slice(0, -1); + } + return a.witness.slice(); + }); + const _hashTree = lazy.value(() => { + if (a.scriptTree) return (0, bip341_1.toHashTree)(a.scriptTree); + if (a.hash) return { hash: a.hash }; + return; + }); + const network = a.network || networks_1.bitcoin; + const o = { name: 'p2tr', network }; + lazy.prop(o, 'address', () => { + if (!o.pubkey) return; + const words = bech32_1.bech32m.toWords(o.pubkey); + words.unshift(TAPROOT_WITNESS_VERSION); + return bech32_1.bech32m.encode(network.bech32, words); + }); + lazy.prop(o, 'hash', () => { + const hashTree = _hashTree(); + if (hashTree) return hashTree.hash; + const w = _witness(); + if (w && w.length > 1) { + const controlBlock = w[w.length - 1]; + const leafVersion = controlBlock[0] & types_1.TAPLEAF_VERSION_MASK; + const script = w[w.length - 2]; + const leafHash = (0, bip341_1.tapleafHash)({ + output: script, + version: leafVersion, + }); + return (0, bip341_1.rootHashFromPath)(controlBlock, leafHash); + } + return null; + }); + lazy.prop(o, 'output', () => { + if (!o.pubkey) return; + return bscript.compile([OPS.OP_1, o.pubkey]); + }); + lazy.prop(o, 'redeemVersion', () => { + if (a.redeemVersion) return a.redeemVersion; + if ( + a.redeem && + a.redeem.redeemVersion !== undefined && + a.redeem.redeemVersion !== null + ) { + return a.redeem.redeemVersion; + } + return bip341_1.LEAF_VERSION_TAPSCRIPT; + }); + lazy.prop(o, 'redeem', () => { + const witness = _witness(); // witness without annex + if (!witness || witness.length < 2) return; + return { + output: witness[witness.length - 2], + witness: witness.slice(0, -2), + redeemVersion: + witness[witness.length - 1][0] & types_1.TAPLEAF_VERSION_MASK, + }; + }); + lazy.prop(o, 'pubkey', () => { + if (a.pubkey) return a.pubkey; + if (a.output) return a.output.slice(2); + if (a.address) return _address().data; + if (o.internalPubkey) { + const tweakedKey = (0, bip341_1.tweakKey)(o.internalPubkey, o.hash); + if (tweakedKey) return tweakedKey.x; + } + }); + lazy.prop(o, 'internalPubkey', () => { + if (a.internalPubkey) return a.internalPubkey; + const witness = _witness(); + if (witness && witness.length > 1) + return witness[witness.length - 1].slice(1, 33); + }); + lazy.prop(o, 'signature', () => { + if (a.signature) return a.signature; + const witness = _witness(); // witness without annex + if (!witness || witness.length !== 1) return; + return witness[0]; + }); + lazy.prop(o, 'witness', () => { + if (a.witness) return a.witness; + const hashTree = _hashTree(); + if (hashTree && a.redeem && a.redeem.output && a.internalPubkey) { + const leafHash = (0, bip341_1.tapleafHash)({ + output: a.redeem.output, + version: o.redeemVersion, + }); + const path = (0, bip341_1.findScriptPath)(hashTree, leafHash); + if (!path) return; + const outputKey = (0, bip341_1.tweakKey)(a.internalPubkey, hashTree.hash); + if (!outputKey) return; + const controlBock = buffer_1.Buffer.concat( + [ + buffer_1.Buffer.from([o.redeemVersion | outputKey.parity]), + a.internalPubkey, + ].concat(path), + ); + return [a.redeem.output, controlBock]; + } + if (a.signature) return [a.signature]; + }); + // extended validation + if (opts.validate) { + let pubkey = buffer_1.Buffer.from([]); + if (a.address) { + if (network && network.bech32 !== _address().prefix) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== TAPROOT_WITNESS_VERSION) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 32) + throw new TypeError('Invalid address data'); + pubkey = _address().data; + } + if (a.pubkey) { + if (pubkey.length > 0 && !pubkey.equals(a.pubkey)) + throw new TypeError('Pubkey mismatch'); + else pubkey = a.pubkey; + } + if (a.output) { + if ( + a.output.length !== 34 || + a.output[0] !== OPS.OP_1 || + a.output[1] !== 0x20 + ) + throw new TypeError('Output is invalid'); + if (pubkey.length > 0 && !pubkey.equals(a.output.slice(2))) + throw new TypeError('Pubkey mismatch'); + else pubkey = a.output.slice(2); + } + if (a.internalPubkey) { + const tweakedKey = (0, bip341_1.tweakKey)(a.internalPubkey, o.hash); + if (pubkey.length > 0 && !pubkey.equals(tweakedKey.x)) + throw new TypeError('Pubkey mismatch'); + else pubkey = tweakedKey.x; + } + if (pubkey && pubkey.length) { + if (!(0, ecc_lib_1.getEccLib)().isXOnlyPoint(pubkey)) + throw new TypeError('Invalid pubkey for p2tr'); + } + const hashTree = _hashTree(); + if (a.hash && hashTree) { + if (!a.hash.equals(hashTree.hash)) throw new TypeError('Hash mismatch'); + } + if (a.redeem && a.redeem.output && hashTree) { + const leafHash = (0, bip341_1.tapleafHash)({ + output: a.redeem.output, + version: o.redeemVersion, + }); + if (!(0, bip341_1.findScriptPath)(hashTree, leafHash)) + throw new TypeError('Redeem script not in tree'); + } + const witness = _witness(); + // compare the provided redeem data with the one computed from witness + if (a.redeem && o.redeem) { + if (a.redeem.redeemVersion) { + if (a.redeem.redeemVersion !== o.redeem.redeemVersion) + throw new TypeError('Redeem.redeemVersion and witness mismatch'); + } + if (a.redeem.output) { + if (bscript.decompile(a.redeem.output).length === 0) + throw new TypeError('Redeem.output is invalid'); + // output redeem is constructed from the witness + if (o.redeem.output && !a.redeem.output.equals(o.redeem.output)) + throw new TypeError('Redeem.output and witness mismatch'); + } + if (a.redeem.witness) { + if ( + o.redeem.witness && + !stacksEqual(a.redeem.witness, o.redeem.witness) + ) + throw new TypeError('Redeem.witness and witness mismatch'); + } + } + if (witness && witness.length) { + if (witness.length === 1) { + // key spending + if (a.signature && !a.signature.equals(witness[0])) + throw new TypeError('Signature mismatch'); + } else { + // script path spending + const controlBlock = witness[witness.length - 1]; + if (controlBlock.length < 33) + throw new TypeError( + `The control-block length is too small. Got ${controlBlock.length}, expected min 33.`, + ); + if ((controlBlock.length - 33) % 32 !== 0) + throw new TypeError( + `The control-block length of ${controlBlock.length} is incorrect!`, + ); + const m = (controlBlock.length - 33) / 32; + if (m > 128) + throw new TypeError( + `The script path is too long. Got ${m}, expected max 128.`, + ); + const internalPubkey = controlBlock.slice(1, 33); + if (a.internalPubkey && !a.internalPubkey.equals(internalPubkey)) + throw new TypeError('Internal pubkey mismatch'); + if (!(0, ecc_lib_1.getEccLib)().isXOnlyPoint(internalPubkey)) + throw new TypeError('Invalid internalPubkey for p2tr witness'); + const leafVersion = controlBlock[0] & types_1.TAPLEAF_VERSION_MASK; + const script = witness[witness.length - 2]; + const leafHash = (0, bip341_1.tapleafHash)({ + output: script, + version: leafVersion, + }); + const hash = (0, bip341_1.rootHashFromPath)(controlBlock, leafHash); + const outputKey = (0, bip341_1.tweakKey)(internalPubkey, hash); + if (!outputKey) + // todo: needs test data + throw new TypeError('Invalid outputKey for p2tr witness'); + if (pubkey.length && !pubkey.equals(outputKey.x)) + throw new TypeError('Pubkey mismatch for p2tr witness'); + if (outputKey.parity !== (controlBlock[0] & 1)) + throw new Error('Incorrect parity'); + } + } + } + return Object.assign(o, a); +} +exports.p2tr = p2tr; +function stacksEqual(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); +} + +},{"../ecc_lib":52,"../networks":55,"../script":72,"../types":76,"./bip341":57,"./lazy":60,"bech32":12,"buffer":92}],66:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.p2wpkh = void 0; +const bcrypto = require('../crypto'); +const networks_1 = require('../networks'); +const bscript = require('../script'); +const types_1 = require('../types'); +const lazy = require('./lazy'); +const bech32_1 = require('bech32'); +const OPS = bscript.OPS; +const EMPTY_BUFFER = Buffer.alloc(0); +// witness: {signature} {pubKey} +// input: <> +// output: OP_0 {pubKeyHash} +function p2wpkh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + (0, types_1.typeforce)( + { + address: types_1.typeforce.maybe(types_1.typeforce.String), + hash: types_1.typeforce.maybe(types_1.typeforce.BufferN(20)), + input: types_1.typeforce.maybe(types_1.typeforce.BufferN(0)), + network: types_1.typeforce.maybe(types_1.typeforce.Object), + output: types_1.typeforce.maybe(types_1.typeforce.BufferN(22)), + pubkey: types_1.typeforce.maybe(types_1.isPoint), + signature: types_1.typeforce.maybe(bscript.isCanonicalScriptSignature), + witness: types_1.typeforce.maybe( + types_1.typeforce.arrayOf(types_1.typeforce.Buffer), + ), + }, + a, + ); + const _address = lazy.value(() => { + const result = bech32_1.bech32.decode(a.address); + const version = result.words.shift(); + const data = bech32_1.bech32.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Buffer.from(data), + }; + }); + const network = a.network || networks_1.bitcoin; + const o = { name: 'p2wpkh', network }; + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32_1.bech32.toWords(o.hash); + words.unshift(0x00); + return bech32_1.bech32.encode(network.bech32, words); + }); + lazy.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().data; + if (a.pubkey || o.pubkey) return bcrypto.hash160(a.pubkey || o.pubkey); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript.compile([OPS.OP_0, o.hash]); + }); + lazy.prop(o, 'pubkey', () => { + if (a.pubkey) return a.pubkey; + if (!a.witness) return; + return a.witness[1]; + }); + lazy.prop(o, 'signature', () => { + if (!a.witness) return; + return a.witness[0]; + }); + lazy.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER; + }); + lazy.prop(o, 'witness', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return [a.signature, a.pubkey]; + }); + // extended validation + if (opts.validate) { + let hash = Buffer.from([]); + if (a.address) { + if (network && network.bech32 !== _address().prefix) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 20) + throw new TypeError('Invalid address data'); + hash = _address().data; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 22 || + a.output[0] !== OPS.OP_0 || + a.output[1] !== 0x14 + ) + throw new TypeError('Output is invalid'); + if (hash.length > 0 && !hash.equals(a.output.slice(2))) + throw new TypeError('Hash mismatch'); + else hash = a.output.slice(2); + } + if (a.pubkey) { + const pkh = bcrypto.hash160(a.pubkey); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + else hash = pkh; + if (!(0, types_1.isPoint)(a.pubkey) || a.pubkey.length !== 33) + throw new TypeError('Invalid pubkey for p2wpkh'); + } + if (a.witness) { + if (a.witness.length !== 2) throw new TypeError('Witness is invalid'); + if (!bscript.isCanonicalScriptSignature(a.witness[0])) + throw new TypeError('Witness has invalid signature'); + if (!(0, types_1.isPoint)(a.witness[1]) || a.witness[1].length !== 33) + throw new TypeError('Witness has invalid pubkey'); + if (a.signature && !a.signature.equals(a.witness[0])) + throw new TypeError('Signature mismatch'); + if (a.pubkey && !a.pubkey.equals(a.witness[1])) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto.hash160(a.witness[1]); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + } + } + return Object.assign(o, a); +} +exports.p2wpkh = p2wpkh; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../crypto":51,"../networks":55,"../script":72,"../types":76,"./lazy":60,"bech32":12,"buffer":92}],67:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.p2wsh = void 0; +const bcrypto = require('../crypto'); +const networks_1 = require('../networks'); +const bscript = require('../script'); +const types_1 = require('../types'); +const lazy = require('./lazy'); +const bech32_1 = require('bech32'); +const OPS = bscript.OPS; +const EMPTY_BUFFER = Buffer.alloc(0); +function stacksEqual(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); +} +function chunkHasUncompressedPubkey(chunk) { + if ( + Buffer.isBuffer(chunk) && + chunk.length === 65 && + chunk[0] === 0x04 && + (0, types_1.isPoint)(chunk) + ) { + return true; + } else { + return false; + } +} +// input: <> +// witness: [redeemScriptSig ...] {redeemScript} +// output: OP_0 {sha256(redeemScript)} +function p2wsh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + (0, types_1.typeforce)( + { + network: types_1.typeforce.maybe(types_1.typeforce.Object), + address: types_1.typeforce.maybe(types_1.typeforce.String), + hash: types_1.typeforce.maybe(types_1.typeforce.BufferN(32)), + output: types_1.typeforce.maybe(types_1.typeforce.BufferN(34)), + redeem: types_1.typeforce.maybe({ + input: types_1.typeforce.maybe(types_1.typeforce.Buffer), + network: types_1.typeforce.maybe(types_1.typeforce.Object), + output: types_1.typeforce.maybe(types_1.typeforce.Buffer), + witness: types_1.typeforce.maybe( + types_1.typeforce.arrayOf(types_1.typeforce.Buffer), + ), + }), + input: types_1.typeforce.maybe(types_1.typeforce.BufferN(0)), + witness: types_1.typeforce.maybe( + types_1.typeforce.arrayOf(types_1.typeforce.Buffer), + ), + }, + a, + ); + const _address = lazy.value(() => { + const result = bech32_1.bech32.decode(a.address); + const version = result.words.shift(); + const data = bech32_1.bech32.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Buffer.from(data), + }; + }); + const _rchunks = lazy.value(() => { + return bscript.decompile(a.redeem.input); + }); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || networks_1.bitcoin; + } + const o = { network }; + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32_1.bech32.toWords(o.hash); + words.unshift(0x00); + return bech32_1.bech32.encode(network.bech32, words); + }); + lazy.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2); + if (a.address) return _address().data; + if (o.redeem && o.redeem.output) return bcrypto.sha256(o.redeem.output); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript.compile([OPS.OP_0, o.hash]); + }); + lazy.prop(o, 'redeem', () => { + if (!a.witness) return; + return { + output: a.witness[a.witness.length - 1], + input: EMPTY_BUFFER, + witness: a.witness.slice(0, -1), + }; + }); + lazy.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER; + }); + lazy.prop(o, 'witness', () => { + // transform redeem input to witness stack? + if ( + a.redeem && + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.output && + a.redeem.output.length > 0 + ) { + const stack = bscript.toStack(_rchunks()); + // assign, and blank the existing input + o.redeem = Object.assign({ witness: stack }, a.redeem); + o.redeem.input = EMPTY_BUFFER; + return [].concat(stack, a.redeem.output); + } + if (!a.redeem) return; + if (!a.redeem.output) return; + if (!a.redeem.witness) return; + return [].concat(a.redeem.witness, a.redeem.output); + }); + lazy.prop(o, 'name', () => { + const nameParts = ['p2wsh']; + if (o.redeem !== undefined && o.redeem.name !== undefined) + nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + // extended validation + if (opts.validate) { + let hash = Buffer.from([]); + if (a.address) { + if (_address().prefix !== network.bech32) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 32) + throw new TypeError('Invalid address data'); + hash = _address().data; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 34 || + a.output[0] !== OPS.OP_0 || + a.output[1] !== 0x20 + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + // is there two redeem sources? + if ( + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.witness && + a.redeem.witness.length > 0 + ) + throw new TypeError('Ambiguous witness source'); + // is the redeem output non-empty/valid? + if (a.redeem.output) { + const decompile = bscript.decompile(a.redeem.output); + if (!decompile || decompile.length < 1) + throw new TypeError('Redeem.output is invalid'); + if (a.redeem.output.byteLength > 3600) + throw new TypeError( + 'Redeem.output unspendable if larger than 3600 bytes', + ); + if (bscript.countNonPushOnlyOPs(decompile) > 201) + throw new TypeError( + 'Redeem.output unspendable with more than 201 non-push ops', + ); + // match hash against other sources + const hash2 = bcrypto.sha256(a.redeem.output); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.redeem.input && !bscript.isPushOnly(_rchunks())) + throw new TypeError('Non push-only scriptSig'); + if ( + a.witness && + a.redeem.witness && + !stacksEqual(a.witness, a.redeem.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); + if ( + (a.redeem.input && _rchunks().some(chunkHasUncompressedPubkey)) || + (a.redeem.output && + (bscript.decompile(a.redeem.output) || []).some( + chunkHasUncompressedPubkey, + )) + ) { + throw new TypeError( + 'redeem.input or redeem.output contains uncompressed pubkey', + ); + } + } + if (a.witness && a.witness.length > 0) { + const wScript = a.witness[a.witness.length - 1]; + if (a.redeem && a.redeem.output && !a.redeem.output.equals(wScript)) + throw new TypeError('Witness and redeem.output mismatch'); + if ( + a.witness.some(chunkHasUncompressedPubkey) || + (bscript.decompile(wScript) || []).some(chunkHasUncompressedPubkey) + ) + throw new TypeError('Witness contains uncompressed pubkey'); + } + } + return Object.assign(o, a); +} +exports.p2wsh = p2wsh; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../crypto":51,"../networks":55,"../script":72,"../types":76,"./lazy":60,"bech32":12,"buffer":92}],68:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.Psbt = void 0; +const bip174_1 = require('bip174'); +const varuint = require('bip174/src/lib/converter/varint'); +const utils_1 = require('bip174/src/lib/utils'); +const address_1 = require('./address'); +const bufferutils_1 = require('./bufferutils'); +const networks_1 = require('./networks'); +const payments = require('./payments'); +const bip341_1 = require('./payments/bip341'); +const bscript = require('./script'); +const transaction_1 = require('./transaction'); +const bip371_1 = require('./psbt/bip371'); +const psbtutils_1 = require('./psbt/psbtutils'); +/** + * These are the default arguments for a Psbt instance. + */ +const DEFAULT_OPTS = { + /** + * A bitcoinjs Network object. This is only used if you pass an `address` + * parameter to addOutput. Otherwise it is not needed and can be left default. + */ + network: networks_1.bitcoin, + /** + * When extractTransaction is called, the fee rate is checked. + * THIS IS NOT TO BE RELIED ON. + * It is only here as a last ditch effort to prevent sending a 500 BTC fee etc. + */ + maximumFeeRate: 5000, // satoshi per byte +}; +/** + * Psbt class can parse and generate a PSBT binary based off of the BIP174. + * There are 6 roles that this class fulfills. (Explained in BIP174) + * + * Creator: This can be done with `new Psbt()` + * Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`, + * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to + * add new inputs and outputs to the PSBT, and `psbt.updateGlobal(itemObject)`, + * `psbt.updateInput(itemObject)`, `psbt.updateOutput(itemObject)` + * addInput requires hash: Buffer | string; and index: number; as attributes + * and can also include any attributes that are used in updateInput method. + * addOutput requires script: Buffer; and value: number; and likewise can include + * data for updateOutput. + * For a list of what attributes should be what types. Check the bip174 library. + * Also, check the integration tests for some examples of usage. + * Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input + * information for your pubkey or pubkeyhash, and only sign inputs where it finds + * your info. Or you can explicitly sign a specific input with signInput and + * signInputAsync. For the async methods you can create a SignerAsync object + * and use something like a hardware wallet to sign with. (You must implement this) + * Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)` + * the psbt calling combine will always have precedence when a conflict occurs. + * Combine checks if the internal bitcoin transaction is the same, so be sure that + * all sequences, version, locktime, etc. are the same before combining. + * Input Finalizer: This role is fairly important. Not only does it need to construct + * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc. + * Before running `psbt.finalizeAllInputs()` please run `psbt.validateSignaturesOfAllInputs()` + * Running any finalize method will delete any data in the input(s) that are no longer + * needed due to the finalized scripts containing the information. + * Transaction Extractor: This role will perform some checks before returning a + * Transaction object. Such as fee rate not being larger than maximumFeeRate etc. + */ +class Psbt { + static fromBase64(data, opts = {}) { + const buffer = Buffer.from(data, 'base64'); + return this.fromBuffer(buffer, opts); + } + static fromHex(data, opts = {}) { + const buffer = Buffer.from(data, 'hex'); + return this.fromBuffer(buffer, opts); + } + static fromBuffer(buffer, opts = {}) { + const psbtBase = bip174_1.Psbt.fromBuffer(buffer, transactionFromBuffer); + const psbt = new Psbt(opts, psbtBase); + checkTxForDupeIns(psbt.__CACHE.__TX, psbt.__CACHE); + return psbt; + } + constructor(opts = {}, data = new bip174_1.Psbt(new PsbtTransaction())) { + this.data = data; + // set defaults + this.opts = Object.assign({}, DEFAULT_OPTS, opts); + this.__CACHE = { + __NON_WITNESS_UTXO_TX_CACHE: [], + __NON_WITNESS_UTXO_BUF_CACHE: [], + __TX_IN_CACHE: {}, + __TX: this.data.globalMap.unsignedTx.tx, + // Psbt's predecesor (TransactionBuilder - now removed) behavior + // was to not confirm input values before signing. + // Even though we highly encourage people to get + // the full parent transaction to verify values, the ability to + // sign non-segwit inputs without the full transaction was often + // requested. So the only way to activate is to use @ts-ignore. + // We will disable exporting the Psbt when unsafe sign is active. + // because it is not BIP174 compliant. + __UNSAFE_SIGN_NONSEGWIT: false, + }; + if (this.data.inputs.length === 0) this.setVersion(2); + // Make data hidden when enumerating + const dpew = (obj, attr, enumerable, writable) => + Object.defineProperty(obj, attr, { + enumerable, + writable, + }); + dpew(this, '__CACHE', false, true); + dpew(this, 'opts', false, true); + } + get inputCount() { + return this.data.inputs.length; + } + get version() { + return this.__CACHE.__TX.version; + } + set version(version) { + this.setVersion(version); + } + get locktime() { + return this.__CACHE.__TX.locktime; + } + set locktime(locktime) { + this.setLocktime(locktime); + } + get txInputs() { + return this.__CACHE.__TX.ins.map(input => ({ + hash: (0, bufferutils_1.cloneBuffer)(input.hash), + index: input.index, + sequence: input.sequence, + })); + } + get txOutputs() { + return this.__CACHE.__TX.outs.map(output => { + let address; + try { + address = (0, address_1.fromOutputScript)( + output.script, + this.opts.network, + ); + } catch (_) {} + return { + script: (0, bufferutils_1.cloneBuffer)(output.script), + value: output.value, + address, + }; + }); + } + combine(...those) { + this.data.combine(...those.map(o => o.data)); + return this; + } + clone() { + // TODO: more efficient cloning + const res = Psbt.fromBuffer(this.data.toBuffer()); + res.opts = JSON.parse(JSON.stringify(this.opts)); + return res; + } + setMaximumFeeRate(satoshiPerByte) { + check32Bit(satoshiPerByte); // 42.9 BTC per byte IS excessive... so throw + this.opts.maximumFeeRate = satoshiPerByte; + } + setVersion(version) { + check32Bit(version); + checkInputsForPartialSig(this.data.inputs, 'setVersion'); + const c = this.__CACHE; + c.__TX.version = version; + c.__EXTRACTED_TX = undefined; + return this; + } + setLocktime(locktime) { + check32Bit(locktime); + checkInputsForPartialSig(this.data.inputs, 'setLocktime'); + const c = this.__CACHE; + c.__TX.locktime = locktime; + c.__EXTRACTED_TX = undefined; + return this; + } + setInputSequence(inputIndex, sequence) { + check32Bit(sequence); + checkInputsForPartialSig(this.data.inputs, 'setInputSequence'); + const c = this.__CACHE; + if (c.__TX.ins.length <= inputIndex) { + throw new Error('Input index too high'); + } + c.__TX.ins[inputIndex].sequence = sequence; + c.__EXTRACTED_TX = undefined; + return this; + } + addInputs(inputDatas) { + inputDatas.forEach(inputData => this.addInput(inputData)); + return this; + } + addInput(inputData) { + if ( + arguments.length > 1 || + !inputData || + inputData.hash === undefined || + inputData.index === undefined + ) { + throw new Error( + `Invalid arguments for Psbt.addInput. ` + + `Requires single object with at least [hash] and [index]`, + ); + } + (0, bip371_1.checkTaprootInputFields)(inputData, inputData, 'addInput'); + checkInputsForPartialSig(this.data.inputs, 'addInput'); + if (inputData.witnessScript) checkInvalidP2WSH(inputData.witnessScript); + const c = this.__CACHE; + this.data.addInput(inputData); + const txIn = c.__TX.ins[c.__TX.ins.length - 1]; + checkTxInputCache(c, txIn); + const inputIndex = this.data.inputs.length - 1; + const input = this.data.inputs[inputIndex]; + if (input.nonWitnessUtxo) { + addNonWitnessTxCache(this.__CACHE, input, inputIndex); + } + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; + } + addOutputs(outputDatas) { + outputDatas.forEach(outputData => this.addOutput(outputData)); + return this; + } + addOutput(outputData) { + if ( + arguments.length > 1 || + !outputData || + outputData.value === undefined || + (outputData.address === undefined && outputData.script === undefined) + ) { + throw new Error( + `Invalid arguments for Psbt.addOutput. ` + + `Requires single object with at least [script or address] and [value]`, + ); + } + checkInputsForPartialSig(this.data.inputs, 'addOutput'); + const { address } = outputData; + if (typeof address === 'string') { + const { network } = this.opts; + const script = (0, address_1.toOutputScript)(address, network); + outputData = Object.assign(outputData, { script }); + } + (0, bip371_1.checkTaprootOutputFields)(outputData, outputData, 'addOutput'); + const c = this.__CACHE; + this.data.addOutput(outputData); + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; + } + extractTransaction(disableFeeCheck) { + if (!this.data.inputs.every(isFinalized)) throw new Error('Not finalized'); + const c = this.__CACHE; + if (!disableFeeCheck) { + checkFees(this, c, this.opts); + } + if (c.__EXTRACTED_TX) return c.__EXTRACTED_TX; + const tx = c.__TX.clone(); + inputFinalizeGetAmts(this.data.inputs, tx, c, true); + return tx; + } + getFeeRate() { + return getTxCacheValue( + '__FEE_RATE', + 'fee rate', + this.data.inputs, + this.__CACHE, + ); + } + getFee() { + return getTxCacheValue('__FEE', 'fee', this.data.inputs, this.__CACHE); + } + finalizeAllInputs() { + (0, utils_1.checkForInput)(this.data.inputs, 0); // making sure we have at least one + range(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); + return this; + } + finalizeInput(inputIndex, finalScriptsFunc) { + const input = (0, utils_1.checkForInput)(this.data.inputs, inputIndex); + if ((0, bip371_1.isTaprootInput)(input)) + return this._finalizeTaprootInput( + inputIndex, + input, + undefined, + finalScriptsFunc, + ); + return this._finalizeInput(inputIndex, input, finalScriptsFunc); + } + finalizeTaprootInput( + inputIndex, + tapLeafHashToFinalize, + finalScriptsFunc = bip371_1.tapScriptFinalizer, + ) { + const input = (0, utils_1.checkForInput)(this.data.inputs, inputIndex); + if ((0, bip371_1.isTaprootInput)(input)) + return this._finalizeTaprootInput( + inputIndex, + input, + tapLeafHashToFinalize, + finalScriptsFunc, + ); + throw new Error(`Cannot finalize input #${inputIndex}. Not Taproot.`); + } + _finalizeInput(inputIndex, input, finalScriptsFunc = getFinalScripts) { + const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput( + inputIndex, + input, + this.__CACHE, + ); + if (!script) throw new Error(`No script found for input #${inputIndex}`); + checkPartialSigSighashes(input); + const { finalScriptSig, finalScriptWitness } = finalScriptsFunc( + inputIndex, + input, + script, + isSegwit, + isP2SH, + isP2WSH, + ); + if (finalScriptSig) this.data.updateInput(inputIndex, { finalScriptSig }); + if (finalScriptWitness) + this.data.updateInput(inputIndex, { finalScriptWitness }); + if (!finalScriptSig && !finalScriptWitness) + throw new Error(`Unknown error finalizing input #${inputIndex}`); + this.data.clearFinalizedInput(inputIndex); + return this; + } + _finalizeTaprootInput( + inputIndex, + input, + tapLeafHashToFinalize, + finalScriptsFunc = bip371_1.tapScriptFinalizer, + ) { + if (!input.witnessUtxo) + throw new Error( + `Cannot finalize input #${inputIndex}. Missing withness utxo.`, + ); + // Check key spend first. Increased privacy and reduced block space. + if (input.tapKeySig) { + const payment = payments.p2tr({ + output: input.witnessUtxo.script, + signature: input.tapKeySig, + }); + const finalScriptWitness = (0, psbtutils_1.witnessStackToScriptWitness)( + payment.witness, + ); + this.data.updateInput(inputIndex, { finalScriptWitness }); + } else { + const { finalScriptWitness } = finalScriptsFunc( + inputIndex, + input, + tapLeafHashToFinalize, + ); + this.data.updateInput(inputIndex, { finalScriptWitness }); + } + this.data.clearFinalizedInput(inputIndex); + return this; + } + getInputType(inputIndex) { + const input = (0, utils_1.checkForInput)(this.data.inputs, inputIndex); + const script = getScriptFromUtxo(inputIndex, input, this.__CACHE); + const result = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), + input.witnessScript || + redeemFromFinalWitnessScript(input.finalScriptWitness), + ); + const type = result.type === 'raw' ? '' : result.type + '-'; + const mainType = classifyScript(result.meaningfulScript); + return type + mainType; + } + inputHasPubkey(inputIndex, pubkey) { + const input = (0, utils_1.checkForInput)(this.data.inputs, inputIndex); + return pubkeyInInput(pubkey, input, inputIndex, this.__CACHE); + } + inputHasHDKey(inputIndex, root) { + const input = (0, utils_1.checkForInput)(this.data.inputs, inputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine) + ); + } + outputHasPubkey(outputIndex, pubkey) { + const output = (0, utils_1.checkForOutput)(this.data.outputs, outputIndex); + return pubkeyInOutput(pubkey, output, outputIndex, this.__CACHE); + } + outputHasHDKey(outputIndex, root) { + const output = (0, utils_1.checkForOutput)(this.data.outputs, outputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine) + ); + } + validateSignaturesOfAllInputs(validator) { + (0, utils_1.checkForInput)(this.data.inputs, 0); // making sure we have at least one + const results = range(this.data.inputs.length).map(idx => + this.validateSignaturesOfInput(idx, validator), + ); + return results.reduce((final, res) => res === true && final, true); + } + validateSignaturesOfInput(inputIndex, validator, pubkey) { + const input = this.data.inputs[inputIndex]; + if ((0, bip371_1.isTaprootInput)(input)) + return this.validateSignaturesOfTaprootInput( + inputIndex, + validator, + pubkey, + ); + return this._validateSignaturesOfInput(inputIndex, validator, pubkey); + } + _validateSignaturesOfInput(inputIndex, validator, pubkey) { + const input = this.data.inputs[inputIndex]; + const partialSig = (input || {}).partialSig; + if (!input || !partialSig || partialSig.length < 1) + throw new Error('No signatures to validate'); + if (typeof validator !== 'function') + throw new Error('Need validator function to validate signatures'); + const mySigs = pubkey + ? partialSig.filter(sig => sig.pubkey.equals(pubkey)) + : partialSig; + if (mySigs.length < 1) throw new Error('No signatures for this pubkey'); + const results = []; + let hashCache; + let scriptCache; + let sighashCache; + for (const pSig of mySigs) { + const sig = bscript.signature.decode(pSig.signature); + const { hash, script } = + sighashCache !== sig.hashType + ? getHashForSig( + inputIndex, + Object.assign({}, input, { sighashType: sig.hashType }), + this.__CACHE, + true, + ) + : { hash: hashCache, script: scriptCache }; + sighashCache = sig.hashType; + hashCache = hash; + scriptCache = script; + checkScriptForPubkey(pSig.pubkey, script, 'verify'); + results.push(validator(pSig.pubkey, hash, sig.signature)); + } + return results.every(res => res === true); + } + validateSignaturesOfTaprootInput(inputIndex, validator, pubkey) { + const input = this.data.inputs[inputIndex]; + const tapKeySig = (input || {}).tapKeySig; + const tapScriptSig = (input || {}).tapScriptSig; + if (!input && !tapKeySig && !(tapScriptSig && !tapScriptSig.length)) + throw new Error('No signatures to validate'); + if (typeof validator !== 'function') + throw new Error('Need validator function to validate signatures'); + pubkey = pubkey && (0, bip371_1.toXOnly)(pubkey); + const allHashses = pubkey + ? getTaprootHashesForSig( + inputIndex, + input, + this.data.inputs, + pubkey, + this.__CACHE, + ) + : getAllTaprootHashesForSig( + inputIndex, + input, + this.data.inputs, + this.__CACHE, + ); + if (!allHashses.length) throw new Error('No signatures for this pubkey'); + const tapKeyHash = allHashses.find(h => !h.leafHash); + let validationResultCount = 0; + if (tapKeySig && tapKeyHash) { + const isValidTapkeySig = validator( + tapKeyHash.pubkey, + tapKeyHash.hash, + trimTaprootSig(tapKeySig), + ); + if (!isValidTapkeySig) return false; + validationResultCount++; + } + if (tapScriptSig) { + for (const tapSig of tapScriptSig) { + const tapSigHash = allHashses.find(h => tapSig.pubkey.equals(h.pubkey)); + if (tapSigHash) { + const isValidTapScriptSig = validator( + tapSig.pubkey, + tapSigHash.hash, + trimTaprootSig(tapSig.signature), + ); + if (!isValidTapScriptSig) return false; + validationResultCount++; + } + } + } + return validationResultCount > 0; + } + signAllInputsHD( + hdKeyPair, + sighashTypes = [transaction_1.Transaction.SIGHASH_ALL], + ) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const results = []; + for (const i of range(this.data.inputs.length)) { + try { + this.signInputHD(i, hdKeyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); + } + } + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); + } + return this; + } + signAllInputsHDAsync( + hdKeyPair, + sighashTypes = [transaction_1.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); + } + const results = []; + const promises = []; + for (const i of range(this.data.inputs.length)) { + promises.push( + this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), + ); + } + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); + } + signInputHD( + inputIndex, + hdKeyPair, + sighashTypes = [transaction_1.Transaction.SIGHASH_ALL], + ) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + signers.forEach(signer => this.signInput(inputIndex, signer, sighashTypes)); + return this; + } + signInputHDAsync( + inputIndex, + hdKeyPair, + sighashTypes = [transaction_1.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); + } + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + const promises = signers.map(signer => + this.signInputAsync(inputIndex, signer, sighashTypes), + ); + return Promise.all(promises) + .then(() => { + resolve(); + }) + .catch(reject); + }); + } + signAllInputs(keyPair, sighashTypes) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + for (const i of range(this.data.inputs.length)) { + try { + this.signInput(i, keyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); + } + } + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); + } + return this; + } + signAllInputsAsync(keyPair, sighashTypes) { + return new Promise((resolve, reject) => { + if (!keyPair || !keyPair.publicKey) + return reject(new Error('Need Signer to sign input')); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + const promises = []; + for (const [i] of this.data.inputs.entries()) { + promises.push( + this.signInputAsync(i, keyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), + ); + } + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); + } + signInput(inputIndex, keyPair, sighashTypes) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const input = (0, utils_1.checkForInput)(this.data.inputs, inputIndex); + if ((0, bip371_1.isTaprootInput)(input)) { + return this._signTaprootInput( + inputIndex, + input, + keyPair, + undefined, + sighashTypes, + ); + } + return this._signInput(inputIndex, keyPair, sighashTypes); + } + signTaprootInput(inputIndex, keyPair, tapLeafHashToSign, sighashTypes) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const input = (0, utils_1.checkForInput)(this.data.inputs, inputIndex); + if ((0, bip371_1.isTaprootInput)(input)) + return this._signTaprootInput( + inputIndex, + input, + keyPair, + tapLeafHashToSign, + sighashTypes, + ); + throw new Error(`Input #${inputIndex} is not of type Taproot.`); + } + _signInput( + inputIndex, + keyPair, + sighashTypes = [transaction_1.Transaction.SIGHASH_ALL], + ) { + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, + ); + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript.signature.encode(keyPair.sign(hash), sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + return this; + } + _signTaprootInput( + inputIndex, + input, + keyPair, + tapLeafHashToSign, + allowedSighashTypes = [transaction_1.Transaction.SIGHASH_DEFAULT], + ) { + const hashesForSig = this.checkTaprootHashesForSig( + inputIndex, + input, + keyPair, + tapLeafHashToSign, + allowedSighashTypes, + ); + const tapKeySig = hashesForSig + .filter(h => !h.leafHash) + .map(h => + (0, bip371_1.serializeTaprootSignature)( + keyPair.signSchnorr(h.hash), + input.sighashType, + ), + )[0]; + const tapScriptSig = hashesForSig + .filter(h => !!h.leafHash) + .map(h => ({ + pubkey: (0, bip371_1.toXOnly)(keyPair.publicKey), + signature: (0, bip371_1.serializeTaprootSignature)( + keyPair.signSchnorr(h.hash), + input.sighashType, + ), + leafHash: h.leafHash, + })); + if (tapKeySig) { + this.data.updateInput(inputIndex, { tapKeySig }); + } + if (tapScriptSig.length) { + this.data.updateInput(inputIndex, { tapScriptSig }); + } + return this; + } + signInputAsync(inputIndex, keyPair, sighashTypes) { + return Promise.resolve().then(() => { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const input = (0, utils_1.checkForInput)(this.data.inputs, inputIndex); + if ((0, bip371_1.isTaprootInput)(input)) + return this._signTaprootInputAsync( + inputIndex, + input, + keyPair, + undefined, + sighashTypes, + ); + return this._signInputAsync(inputIndex, keyPair, sighashTypes); + }); + } + signTaprootInputAsync(inputIndex, keyPair, tapLeafHash, sighashTypes) { + return Promise.resolve().then(() => { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const input = (0, utils_1.checkForInput)(this.data.inputs, inputIndex); + if ((0, bip371_1.isTaprootInput)(input)) + return this._signTaprootInputAsync( + inputIndex, + input, + keyPair, + tapLeafHash, + sighashTypes, + ); + throw new Error(`Input #${inputIndex} is not of type Taproot.`); + }); + } + _signInputAsync( + inputIndex, + keyPair, + sighashTypes = [transaction_1.Transaction.SIGHASH_ALL], + ) { + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, + ); + return Promise.resolve(keyPair.sign(hash)).then(signature => { + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript.signature.encode(signature, sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + }); + } + async _signTaprootInputAsync( + inputIndex, + input, + keyPair, + tapLeafHash, + sighashTypes = [transaction_1.Transaction.SIGHASH_DEFAULT], + ) { + const hashesForSig = this.checkTaprootHashesForSig( + inputIndex, + input, + keyPair, + tapLeafHash, + sighashTypes, + ); + const signaturePromises = []; + const tapKeyHash = hashesForSig.filter(h => !h.leafHash)[0]; + if (tapKeyHash) { + const tapKeySigPromise = Promise.resolve( + keyPair.signSchnorr(tapKeyHash.hash), + ).then(sig => { + return { + tapKeySig: (0, bip371_1.serializeTaprootSignature)( + sig, + input.sighashType, + ), + }; + }); + signaturePromises.push(tapKeySigPromise); + } + const tapScriptHashes = hashesForSig.filter(h => !!h.leafHash); + if (tapScriptHashes.length) { + const tapScriptSigPromises = tapScriptHashes.map(tsh => { + return Promise.resolve(keyPair.signSchnorr(tsh.hash)).then( + signature => { + const tapScriptSig = [ + { + pubkey: (0, bip371_1.toXOnly)(keyPair.publicKey), + signature: (0, bip371_1.serializeTaprootSignature)( + signature, + input.sighashType, + ), + leafHash: tsh.leafHash, + }, + ]; + return { tapScriptSig }; + }, + ); + }); + signaturePromises.push(...tapScriptSigPromises); + } + return Promise.all(signaturePromises).then(results => { + results.forEach(v => this.data.updateInput(inputIndex, v)); + }); + } + checkTaprootHashesForSig( + inputIndex, + input, + keyPair, + tapLeafHashToSign, + allowedSighashTypes, + ) { + if (typeof keyPair.signSchnorr !== 'function') + throw new Error( + `Need Schnorr Signer to sign taproot input #${inputIndex}.`, + ); + const hashesForSig = getTaprootHashesForSig( + inputIndex, + input, + this.data.inputs, + keyPair.publicKey, + this.__CACHE, + tapLeafHashToSign, + allowedSighashTypes, + ); + if (!hashesForSig || !hashesForSig.length) + throw new Error( + `Can not sign for input #${inputIndex} with the key ${keyPair.publicKey.toString( + 'hex', + )}`, + ); + return hashesForSig; + } + toBuffer() { + checkCache(this.__CACHE); + return this.data.toBuffer(); + } + toHex() { + checkCache(this.__CACHE); + return this.data.toHex(); + } + toBase64() { + checkCache(this.__CACHE); + return this.data.toBase64(); + } + updateGlobal(updateData) { + this.data.updateGlobal(updateData); + return this; + } + updateInput(inputIndex, updateData) { + if (updateData.witnessScript) checkInvalidP2WSH(updateData.witnessScript); + (0, bip371_1.checkTaprootInputFields)( + this.data.inputs[inputIndex], + updateData, + 'updateInput', + ); + this.data.updateInput(inputIndex, updateData); + if (updateData.nonWitnessUtxo) { + addNonWitnessTxCache( + this.__CACHE, + this.data.inputs[inputIndex], + inputIndex, + ); + } + return this; + } + updateOutput(outputIndex, updateData) { + const outputData = this.data.outputs[outputIndex]; + (0, bip371_1.checkTaprootOutputFields)( + outputData, + updateData, + 'updateOutput', + ); + this.data.updateOutput(outputIndex, updateData); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + this.data.addUnknownKeyValToGlobal(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + this.data.addUnknownKeyValToInput(inputIndex, keyVal); + return this; + } + addUnknownKeyValToOutput(outputIndex, keyVal) { + this.data.addUnknownKeyValToOutput(outputIndex, keyVal); + return this; + } + clearFinalizedInput(inputIndex) { + this.data.clearFinalizedInput(inputIndex); + return this; + } +} +exports.Psbt = Psbt; +/** + * This function is needed to pass to the bip174 base class's fromBuffer. + * It takes the "transaction buffer" portion of the psbt buffer and returns a + * Transaction (From the bip174 library) interface. + */ +const transactionFromBuffer = buffer => new PsbtTransaction(buffer); +/** + * This class implements the Transaction interface from bip174 library. + * It contains a bitcoinjs-lib Transaction object. + */ +class PsbtTransaction { + constructor(buffer = Buffer.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { + this.tx = transaction_1.Transaction.fromBuffer(buffer); + checkTxEmpty(this.tx); + Object.defineProperty(this, 'tx', { + enumerable: false, + writable: true, + }); + } + getInputOutputCounts() { + return { + inputCount: this.tx.ins.length, + outputCount: this.tx.outs.length, + }; + } + addInput(input) { + if ( + input.hash === undefined || + input.index === undefined || + (!Buffer.isBuffer(input.hash) && typeof input.hash !== 'string') || + typeof input.index !== 'number' + ) { + throw new Error('Error adding input.'); + } + const hash = + typeof input.hash === 'string' + ? (0, bufferutils_1.reverseBuffer)(Buffer.from(input.hash, 'hex')) + : input.hash; + this.tx.addInput(hash, input.index, input.sequence); + } + addOutput(output) { + if ( + output.script === undefined || + output.value === undefined || + !Buffer.isBuffer(output.script) || + typeof output.value !== 'number' + ) { + throw new Error('Error adding output.'); + } + this.tx.addOutput(output.script, output.value); + } + toBuffer() { + return this.tx.toBuffer(); + } +} +function canFinalize(input, script, scriptType) { + switch (scriptType) { + case 'pubkey': + case 'pubkeyhash': + case 'witnesspubkeyhash': + return hasSigs(1, input.partialSig); + case 'multisig': + const p2ms = payments.p2ms({ output: script }); + return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys); + default: + return false; + } +} +function checkCache(cache) { + if (cache.__UNSAFE_SIGN_NONSEGWIT !== false) { + throw new Error('Not BIP174 compliant, can not export'); + } +} +function hasSigs(neededSigs, partialSig, pubkeys) { + if (!partialSig) return false; + let sigs; + if (pubkeys) { + sigs = pubkeys + .map(pkey => { + const pubkey = compressPubkey(pkey); + return partialSig.find(pSig => pSig.pubkey.equals(pubkey)); + }) + .filter(v => !!v); + } else { + sigs = partialSig; + } + if (sigs.length > neededSigs) throw new Error('Too many signatures'); + return sigs.length === neededSigs; +} +function isFinalized(input) { + return !!input.finalScriptSig || !!input.finalScriptWitness; +} +function bip32DerivationIsMine(root) { + return d => { + if (!d.masterFingerprint.equals(root.fingerprint)) return false; + if (!root.derivePath(d.path).publicKey.equals(d.pubkey)) return false; + return true; + }; +} +function check32Bit(num) { + if ( + typeof num !== 'number' || + num !== Math.floor(num) || + num > 0xffffffff || + num < 0 + ) { + throw new Error('Invalid 32 bit integer'); + } +} +function checkFees(psbt, cache, opts) { + const feeRate = cache.__FEE_RATE || psbt.getFeeRate(); + const vsize = cache.__EXTRACTED_TX.virtualSize(); + const satoshis = feeRate * vsize; + if (feeRate >= opts.maximumFeeRate) { + throw new Error( + `Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` + + `fees, which is ${feeRate} satoshi per byte for a transaction ` + + `with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` + + `byte). Use setMaximumFeeRate method to raise your threshold, or ` + + `pass true to the first arg of extractTransaction.`, + ); + } +} +function checkInputsForPartialSig(inputs, action) { + inputs.forEach(input => { + const throws = (0, bip371_1.isTaprootInput)(input) + ? (0, bip371_1.checkTaprootInputForSigs)(input, action) + : (0, psbtutils_1.checkInputForSig)(input, action); + if (throws) + throw new Error('Can not modify transaction, signatures exist.'); + }); +} +function checkPartialSigSighashes(input) { + if (!input.sighashType || !input.partialSig) return; + const { partialSig, sighashType } = input; + partialSig.forEach(pSig => { + const { hashType } = bscript.signature.decode(pSig.signature); + if (sighashType !== hashType) { + throw new Error('Signature sighash does not match input sighash type'); + } + }); +} +function checkScriptForPubkey(pubkey, script, action) { + if (!(0, psbtutils_1.pubkeyInScript)(pubkey, script)) { + throw new Error( + `Can not ${action} for this input with the key ${pubkey.toString('hex')}`, + ); + } +} +function checkTxEmpty(tx) { + const isEmpty = tx.ins.every( + input => + input.script && + input.script.length === 0 && + input.witness && + input.witness.length === 0, + ); + if (!isEmpty) { + throw new Error('Format Error: Transaction ScriptSigs are not empty'); + } +} +function checkTxForDupeIns(tx, cache) { + tx.ins.forEach(input => { + checkTxInputCache(cache, input); + }); +} +function checkTxInputCache(cache, input) { + const key = + (0, bufferutils_1.reverseBuffer)(Buffer.from(input.hash)).toString('hex') + + ':' + + input.index; + if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); + cache.__TX_IN_CACHE[key] = 1; +} +function scriptCheckerFactory(payment, paymentScriptName) { + return (inputIndex, scriptPubKey, redeemScript, ioType) => { + const redeemScriptOutput = payment({ + redeem: { output: redeemScript }, + }).output; + if (!scriptPubKey.equals(redeemScriptOutput)) { + throw new Error( + `${paymentScriptName} for ${ioType} #${inputIndex} doesn't match the scriptPubKey in the prevout`, + ); + } + }; +} +const checkRedeemScript = scriptCheckerFactory(payments.p2sh, 'Redeem script'); +const checkWitnessScript = scriptCheckerFactory( + payments.p2wsh, + 'Witness script', +); +function getTxCacheValue(key, name, inputs, c) { + if (!inputs.every(isFinalized)) + throw new Error(`PSBT must be finalized to calculate ${name}`); + if (key === '__FEE_RATE' && c.__FEE_RATE) return c.__FEE_RATE; + if (key === '__FEE' && c.__FEE) return c.__FEE; + let tx; + let mustFinalize = true; + if (c.__EXTRACTED_TX) { + tx = c.__EXTRACTED_TX; + mustFinalize = false; + } else { + tx = c.__TX.clone(); + } + inputFinalizeGetAmts(inputs, tx, c, mustFinalize); + if (key === '__FEE_RATE') return c.__FEE_RATE; + else if (key === '__FEE') return c.__FEE; +} +function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH) { + const scriptType = classifyScript(script); + if (!canFinalize(input, script, scriptType)) + throw new Error(`Can not finalize input #${inputIndex}`); + return prepareFinalScripts( + script, + scriptType, + input.partialSig, + isSegwit, + isP2SH, + isP2WSH, + ); +} +function prepareFinalScripts( + script, + scriptType, + partialSig, + isSegwit, + isP2SH, + isP2WSH, +) { + let finalScriptSig; + let finalScriptWitness; + // Wow, the payments API is very handy + const payment = getPayment(script, scriptType, partialSig); + const p2wsh = !isP2WSH ? null : payments.p2wsh({ redeem: payment }); + const p2sh = !isP2SH ? null : payments.p2sh({ redeem: p2wsh || payment }); + if (isSegwit) { + if (p2wsh) { + finalScriptWitness = (0, psbtutils_1.witnessStackToScriptWitness)( + p2wsh.witness, + ); + } else { + finalScriptWitness = (0, psbtutils_1.witnessStackToScriptWitness)( + payment.witness, + ); + } + if (p2sh) { + finalScriptSig = p2sh.input; + } + } else { + if (p2sh) { + finalScriptSig = p2sh.input; + } else { + finalScriptSig = payment.input; + } + } + return { + finalScriptSig, + finalScriptWitness, + }; +} +function getHashAndSighashType( + inputs, + inputIndex, + pubkey, + cache, + sighashTypes, +) { + const input = (0, utils_1.checkForInput)(inputs, inputIndex); + const { hash, sighashType, script } = getHashForSig( + inputIndex, + input, + cache, + false, + sighashTypes, + ); + checkScriptForPubkey(pubkey, script, 'sign'); + return { + hash, + sighashType, + }; +} +function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) { + const unsignedTx = cache.__TX; + const sighashType = + input.sighashType || transaction_1.Transaction.SIGHASH_ALL; + checkSighashTypeAllowed(sighashType, sighashTypes); + let hash; + let prevout; + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutHash = unsignedTx.ins[inputIndex].hash; + const utxoHash = nonWitnessUtxoTx.getHash(); + // If a non-witness UTXO is provided, its hash must match the hash specified in the prevout + if (!prevoutHash.equals(utxoHash)) { + throw new Error( + `Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`, + ); + } + const prevoutIndex = unsignedTx.ins[inputIndex].index; + prevout = nonWitnessUtxoTx.outs[prevoutIndex]; + } else if (input.witnessUtxo) { + prevout = input.witnessUtxo; + } else { + throw new Error('Need a Utxo input item for signing'); + } + const { meaningfulScript, type } = getMeaningfulScript( + prevout.script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) { + hash = unsignedTx.hashForWitnessV0( + inputIndex, + meaningfulScript, + prevout.value, + sighashType, + ); + } else if ((0, psbtutils_1.isP2WPKH)(meaningfulScript)) { + // P2WPKH uses the P2PKH template for prevoutScript when signing + const signingScript = payments.p2pkh({ + hash: meaningfulScript.slice(2), + }).output; + hash = unsignedTx.hashForWitnessV0( + inputIndex, + signingScript, + prevout.value, + sighashType, + ); + } else { + // non-segwit + if ( + input.nonWitnessUtxo === undefined && + cache.__UNSAFE_SIGN_NONSEGWIT === false + ) + throw new Error( + `Input #${inputIndex} has witnessUtxo but non-segwit script: ` + + `${meaningfulScript.toString('hex')}`, + ); + if (!forValidate && cache.__UNSAFE_SIGN_NONSEGWIT !== false) + console.warn( + 'Warning: Signing non-segwit inputs without the full parent transaction ' + + 'means there is a chance that a miner could feed you incorrect information ' + + "to trick you into paying large fees. This behavior is the same as Psbt's predecesor " + + '(TransactionBuilder - now removed) when signing non-segwit scripts. You are not ' + + 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' + + 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' + + '*********************', + ); + hash = unsignedTx.hashForSignature( + inputIndex, + meaningfulScript, + sighashType, + ); + } + return { + script: meaningfulScript, + sighashType, + hash, + }; +} +function getAllTaprootHashesForSig(inputIndex, input, inputs, cache) { + const allPublicKeys = []; + if (input.tapInternalKey) { + const key = getPrevoutTaprootKey(inputIndex, input, cache); + if (key) { + allPublicKeys.push(key); + } + } + if (input.tapScriptSig) { + const tapScriptPubkeys = input.tapScriptSig.map(tss => tss.pubkey); + allPublicKeys.push(...tapScriptPubkeys); + } + const allHashes = allPublicKeys.map(pubicKey => + getTaprootHashesForSig(inputIndex, input, inputs, pubicKey, cache), + ); + return allHashes.flat(); +} +function getPrevoutTaprootKey(inputIndex, input, cache) { + const { script } = getScriptAndAmountFromUtxo(inputIndex, input, cache); + return (0, psbtutils_1.isP2TR)(script) ? script.subarray(2, 34) : null; +} +function trimTaprootSig(signature) { + return signature.length === 64 ? signature : signature.subarray(0, 64); +} +function getTaprootHashesForSig( + inputIndex, + input, + inputs, + pubkey, + cache, + tapLeafHashToSign, + allowedSighashTypes, +) { + const unsignedTx = cache.__TX; + const sighashType = + input.sighashType || transaction_1.Transaction.SIGHASH_DEFAULT; + checkSighashTypeAllowed(sighashType, allowedSighashTypes); + const prevOuts = inputs.map((i, index) => + getScriptAndAmountFromUtxo(index, i, cache), + ); + const signingScripts = prevOuts.map(o => o.script); + const values = prevOuts.map(o => o.value); + const hashes = []; + if (input.tapInternalKey && !tapLeafHashToSign) { + const outputKey = + getPrevoutTaprootKey(inputIndex, input, cache) || Buffer.from([]); + if ((0, bip371_1.toXOnly)(pubkey).equals(outputKey)) { + const tapKeyHash = unsignedTx.hashForWitnessV1( + inputIndex, + signingScripts, + values, + sighashType, + ); + hashes.push({ pubkey, hash: tapKeyHash }); + } + } + const tapLeafHashes = (input.tapLeafScript || []) + .filter(tapLeaf => (0, psbtutils_1.pubkeyInScript)(pubkey, tapLeaf.script)) + .map(tapLeaf => { + const hash = (0, bip341_1.tapleafHash)({ + output: tapLeaf.script, + version: tapLeaf.leafVersion, + }); + return Object.assign({ hash }, tapLeaf); + }) + .filter( + tapLeaf => !tapLeafHashToSign || tapLeafHashToSign.equals(tapLeaf.hash), + ) + .map(tapLeaf => { + const tapScriptHash = unsignedTx.hashForWitnessV1( + inputIndex, + signingScripts, + values, + transaction_1.Transaction.SIGHASH_DEFAULT, + tapLeaf.hash, + ); + return { + pubkey, + hash: tapScriptHash, + leafHash: tapLeaf.hash, + }; + }); + return hashes.concat(tapLeafHashes); +} +function checkSighashTypeAllowed(sighashType, sighashTypes) { + if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) { + const str = sighashTypeToString(sighashType); + throw new Error( + `Sighash type is not allowed. Retry the sign method passing the ` + + `sighashTypes array of whitelisted types. Sighash type: ${str}`, + ); + } +} +function getPayment(script, scriptType, partialSig) { + let payment; + switch (scriptType) { + case 'multisig': + const sigs = getSortedSigs(script, partialSig); + payment = payments.p2ms({ + output: script, + signatures: sigs, + }); + break; + case 'pubkey': + payment = payments.p2pk({ + output: script, + signature: partialSig[0].signature, + }); + break; + case 'pubkeyhash': + payment = payments.p2pkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; + case 'witnesspubkeyhash': + payment = payments.p2wpkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; + } + return payment; +} +function getScriptFromInput(inputIndex, input, cache) { + const unsignedTx = cache.__TX; + const res = { + script: null, + isSegwit: false, + isP2SH: false, + isP2WSH: false, + }; + res.isP2SH = !!input.redeemScript; + res.isP2WSH = !!input.witnessScript; + if (input.witnessScript) { + res.script = input.witnessScript; + } else if (input.redeemScript) { + res.script = input.redeemScript; + } else { + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutIndex = unsignedTx.ins[inputIndex].index; + res.script = nonWitnessUtxoTx.outs[prevoutIndex].script; + } else if (input.witnessUtxo) { + res.script = input.witnessUtxo.script; + } + } + if (input.witnessScript || (0, psbtutils_1.isP2WPKH)(res.script)) { + res.isSegwit = true; + } + return res; +} +function getSignersFromHD(inputIndex, inputs, hdKeyPair) { + const input = (0, utils_1.checkForInput)(inputs, inputIndex); + if (!input.bip32Derivation || input.bip32Derivation.length === 0) { + throw new Error('Need bip32Derivation to sign with HD'); + } + const myDerivations = input.bip32Derivation + .map(bipDv => { + if (bipDv.masterFingerprint.equals(hdKeyPair.fingerprint)) { + return bipDv; + } else { + return; + } + }) + .filter(v => !!v); + if (myDerivations.length === 0) { + throw new Error( + 'Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint', + ); + } + const signers = myDerivations.map(bipDv => { + const node = hdKeyPair.derivePath(bipDv.path); + if (!bipDv.pubkey.equals(node.publicKey)) { + throw new Error('pubkey did not match bip32Derivation'); + } + return node; + }); + return signers; +} +function getSortedSigs(script, partialSig) { + const p2ms = payments.p2ms({ output: script }); + // for each pubkey in order of p2ms script + return p2ms.pubkeys + .map(pk => { + // filter partialSig array by pubkey being equal + return ( + partialSig.filter(ps => { + return ps.pubkey.equals(pk); + })[0] || {} + ).signature; + // Any pubkey without a match will return undefined + // this last filter removes all the undefined items in the array. + }) + .filter(v => !!v); +} +function scriptWitnessToWitnessStack(buffer) { + let offset = 0; + function readSlice(n) { + offset += n; + return buffer.slice(offset - n, offset); + } + function readVarInt() { + const vi = varuint.decode(buffer, offset); + offset += varuint.decode.bytes; + return vi; + } + function readVarSlice() { + return readSlice(readVarInt()); + } + function readVector() { + const count = readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(readVarSlice()); + return vector; + } + return readVector(); +} +function sighashTypeToString(sighashType) { + let text = + sighashType & transaction_1.Transaction.SIGHASH_ANYONECANPAY + ? 'SIGHASH_ANYONECANPAY | ' + : ''; + const sigMod = sighashType & 0x1f; + switch (sigMod) { + case transaction_1.Transaction.SIGHASH_ALL: + text += 'SIGHASH_ALL'; + break; + case transaction_1.Transaction.SIGHASH_SINGLE: + text += 'SIGHASH_SINGLE'; + break; + case transaction_1.Transaction.SIGHASH_NONE: + text += 'SIGHASH_NONE'; + break; + } + return text; +} +function addNonWitnessTxCache(cache, input, inputIndex) { + cache.__NON_WITNESS_UTXO_BUF_CACHE[inputIndex] = input.nonWitnessUtxo; + const tx = transaction_1.Transaction.fromBuffer(input.nonWitnessUtxo); + cache.__NON_WITNESS_UTXO_TX_CACHE[inputIndex] = tx; + const self = cache; + const selfIndex = inputIndex; + delete input.nonWitnessUtxo; + Object.defineProperty(input, 'nonWitnessUtxo', { + enumerable: true, + get() { + const buf = self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex]; + const txCache = self.__NON_WITNESS_UTXO_TX_CACHE[selfIndex]; + if (buf !== undefined) { + return buf; + } else { + const newBuf = txCache.toBuffer(); + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = newBuf; + return newBuf; + } + }, + set(data) { + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = data; + }, + }); +} +function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize) { + let inputAmount = 0; + inputs.forEach((input, idx) => { + if (mustFinalize && input.finalScriptSig) + tx.ins[idx].script = input.finalScriptSig; + if (mustFinalize && input.finalScriptWitness) { + tx.ins[idx].witness = scriptWitnessToWitnessStack( + input.finalScriptWitness, + ); + } + if (input.witnessUtxo) { + inputAmount += input.witnessUtxo.value; + } else if (input.nonWitnessUtxo) { + const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx); + const vout = tx.ins[idx].index; + const out = nwTx.outs[vout]; + inputAmount += out.value; + } + }); + const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0); + const fee = inputAmount - outputAmount; + if (fee < 0) { + throw new Error('Outputs are spending more than Inputs'); + } + const bytes = tx.virtualSize(); + cache.__FEE = fee; + cache.__EXTRACTED_TX = tx; + cache.__FEE_RATE = Math.floor(fee / bytes); +} +function nonWitnessUtxoTxFromCache(cache, input, inputIndex) { + const c = cache.__NON_WITNESS_UTXO_TX_CACHE; + if (!c[inputIndex]) { + addNonWitnessTxCache(cache, input, inputIndex); + } + return c[inputIndex]; +} +function getScriptFromUtxo(inputIndex, input, cache) { + const { script } = getScriptAndAmountFromUtxo(inputIndex, input, cache); + return script; +} +function getScriptAndAmountFromUtxo(inputIndex, input, cache) { + if (input.witnessUtxo !== undefined) { + return { + script: input.witnessUtxo.script, + value: input.witnessUtxo.value, + }; + } else if (input.nonWitnessUtxo !== undefined) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const o = nonWitnessUtxoTx.outs[cache.__TX.ins[inputIndex].index]; + return { script: o.script, value: o.value }; + } else { + throw new Error("Can't find pubkey in input without Utxo data"); + } +} +function pubkeyInInput(pubkey, input, inputIndex, cache) { + const script = getScriptFromUtxo(inputIndex, input, cache); + const { meaningfulScript } = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + return (0, psbtutils_1.pubkeyInScript)(pubkey, meaningfulScript); +} +function pubkeyInOutput(pubkey, output, outputIndex, cache) { + const script = cache.__TX.outs[outputIndex].script; + const { meaningfulScript } = getMeaningfulScript( + script, + outputIndex, + 'output', + output.redeemScript, + output.witnessScript, + ); + return (0, psbtutils_1.pubkeyInScript)(pubkey, meaningfulScript); +} +function redeemFromFinalScriptSig(finalScript) { + if (!finalScript) return; + const decomp = bscript.decompile(finalScript); + if (!decomp) return; + const lastItem = decomp[decomp.length - 1]; + if ( + !Buffer.isBuffer(lastItem) || + isPubkeyLike(lastItem) || + isSigLike(lastItem) + ) + return; + const sDecomp = bscript.decompile(lastItem); + if (!sDecomp) return; + return lastItem; +} +function redeemFromFinalWitnessScript(finalScript) { + if (!finalScript) return; + const decomp = scriptWitnessToWitnessStack(finalScript); + const lastItem = decomp[decomp.length - 1]; + if (isPubkeyLike(lastItem)) return; + const sDecomp = bscript.decompile(lastItem); + if (!sDecomp) return; + return lastItem; +} +function compressPubkey(pubkey) { + if (pubkey.length === 65) { + const parity = pubkey[64] & 1; + const newKey = pubkey.slice(0, 33); + newKey[0] = 2 | parity; + return newKey; + } + return pubkey.slice(); +} +function isPubkeyLike(buf) { + return buf.length === 33 && bscript.isCanonicalPubKey(buf); +} +function isSigLike(buf) { + return bscript.isCanonicalScriptSignature(buf); +} +function getMeaningfulScript( + script, + index, + ioType, + redeemScript, + witnessScript, +) { + const isP2SH = (0, psbtutils_1.isP2SHScript)(script); + const isP2SHP2WSH = + isP2SH && redeemScript && (0, psbtutils_1.isP2WSHScript)(redeemScript); + const isP2WSH = (0, psbtutils_1.isP2WSHScript)(script); + if (isP2SH && redeemScript === undefined) + throw new Error('scriptPubkey is P2SH but redeemScript missing'); + if ((isP2WSH || isP2SHP2WSH) && witnessScript === undefined) + throw new Error( + 'scriptPubkey or redeemScript is P2WSH but witnessScript missing', + ); + let meaningfulScript; + if (isP2SHP2WSH) { + meaningfulScript = witnessScript; + checkRedeemScript(index, script, redeemScript, ioType); + checkWitnessScript(index, redeemScript, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2WSH) { + meaningfulScript = witnessScript; + checkWitnessScript(index, script, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2SH) { + meaningfulScript = redeemScript; + checkRedeemScript(index, script, redeemScript, ioType); + } else { + meaningfulScript = script; + } + return { + meaningfulScript, + type: isP2SHP2WSH + ? 'p2sh-p2wsh' + : isP2SH + ? 'p2sh' + : isP2WSH + ? 'p2wsh' + : 'raw', + }; +} +function checkInvalidP2WSH(script) { + if ( + (0, psbtutils_1.isP2WPKH)(script) || + (0, psbtutils_1.isP2SHScript)(script) + ) { + throw new Error('P2WPKH or P2SH can not be contained within P2WSH'); + } +} +function classifyScript(script) { + if ((0, psbtutils_1.isP2WPKH)(script)) return 'witnesspubkeyhash'; + if ((0, psbtutils_1.isP2PKH)(script)) return 'pubkeyhash'; + if ((0, psbtutils_1.isP2MS)(script)) return 'multisig'; + if ((0, psbtutils_1.isP2PK)(script)) return 'pubkey'; + return 'nonstandard'; +} +function range(n) { + return [...Array(n).keys()]; +} + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./address":47,"./bufferutils":50,"./networks":55,"./payments":59,"./payments/bip341":57,"./psbt/bip371":69,"./psbt/psbtutils":70,"./script":72,"./transaction":75,"bip174":44,"bip174/src/lib/converter/varint":40,"bip174/src/lib/utils":46,"buffer":92}],69:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.checkTaprootInputForSigs = + exports.tapTreeFromList = + exports.tapTreeToList = + exports.tweakInternalPubKey = + exports.checkTaprootOutputFields = + exports.checkTaprootInputFields = + exports.isTaprootOutput = + exports.isTaprootInput = + exports.serializeTaprootSignature = + exports.tapScriptFinalizer = + exports.toXOnly = + void 0; +const types_1 = require('../types'); +const transaction_1 = require('../transaction'); +const psbtutils_1 = require('./psbtutils'); +const bip341_1 = require('../payments/bip341'); +const payments_1 = require('../payments'); +const psbtutils_2 = require('./psbtutils'); +const toXOnly = pubKey => (pubKey.length === 32 ? pubKey : pubKey.slice(1, 33)); +exports.toXOnly = toXOnly; +/** + * Default tapscript finalizer. It searches for the `tapLeafHashToFinalize` if provided. + * Otherwise it will search for the tapleaf that has at least one signature and has the shortest path. + * @param inputIndex the position of the PSBT input. + * @param input the PSBT input. + * @param tapLeafHashToFinalize optional, if provided the finalizer will search for a tapleaf that has this hash + * and will try to build the finalScriptWitness. + * @returns the finalScriptWitness or throws an exception if no tapleaf found. + */ +function tapScriptFinalizer(inputIndex, input, tapLeafHashToFinalize) { + const tapLeaf = findTapLeafToFinalize( + input, + inputIndex, + tapLeafHashToFinalize, + ); + try { + const sigs = sortSignatures(input, tapLeaf); + const witness = sigs.concat(tapLeaf.script).concat(tapLeaf.controlBlock); + return { + finalScriptWitness: (0, psbtutils_1.witnessStackToScriptWitness)(witness), + }; + } catch (err) { + throw new Error(`Can not finalize taproot input #${inputIndex}: ${err}`); + } +} +exports.tapScriptFinalizer = tapScriptFinalizer; +function serializeTaprootSignature(sig, sighashType) { + const sighashTypeByte = sighashType + ? Buffer.from([sighashType]) + : Buffer.from([]); + return Buffer.concat([sig, sighashTypeByte]); +} +exports.serializeTaprootSignature = serializeTaprootSignature; +function isTaprootInput(input) { + return ( + input && + !!( + input.tapInternalKey || + input.tapMerkleRoot || + (input.tapLeafScript && input.tapLeafScript.length) || + (input.tapBip32Derivation && input.tapBip32Derivation.length) || + (input.witnessUtxo && (0, psbtutils_1.isP2TR)(input.witnessUtxo.script)) + ) + ); +} +exports.isTaprootInput = isTaprootInput; +function isTaprootOutput(output, script) { + return ( + output && + !!( + output.tapInternalKey || + output.tapTree || + (output.tapBip32Derivation && output.tapBip32Derivation.length) || + (script && (0, psbtutils_1.isP2TR)(script)) + ) + ); +} +exports.isTaprootOutput = isTaprootOutput; +function checkTaprootInputFields(inputData, newInputData, action) { + checkMixedTaprootAndNonTaprootInputFields(inputData, newInputData, action); + checkIfTapLeafInTree(inputData, newInputData, action); +} +exports.checkTaprootInputFields = checkTaprootInputFields; +function checkTaprootOutputFields(outputData, newOutputData, action) { + checkMixedTaprootAndNonTaprootOutputFields(outputData, newOutputData, action); + checkTaprootScriptPubkey(outputData, newOutputData); +} +exports.checkTaprootOutputFields = checkTaprootOutputFields; +function checkTaprootScriptPubkey(outputData, newOutputData) { + if (!newOutputData.tapTree && !newOutputData.tapInternalKey) return; + const tapInternalKey = + newOutputData.tapInternalKey || outputData.tapInternalKey; + const tapTree = newOutputData.tapTree || outputData.tapTree; + if (tapInternalKey) { + const { script: scriptPubkey } = outputData; + const script = getTaprootScripPubkey(tapInternalKey, tapTree); + if (scriptPubkey && !scriptPubkey.equals(script)) + throw new Error('Error adding output. Script or address missmatch.'); + } +} +function getTaprootScripPubkey(tapInternalKey, tapTree) { + const scriptTree = tapTree && tapTreeFromList(tapTree.leaves); + const { output } = (0, payments_1.p2tr)({ + internalPubkey: tapInternalKey, + scriptTree, + }); + return output; +} +function tweakInternalPubKey(inputIndex, input) { + const tapInternalKey = input.tapInternalKey; + const outputKey = + tapInternalKey && + (0, bip341_1.tweakKey)(tapInternalKey, input.tapMerkleRoot); + if (!outputKey) + throw new Error( + `Cannot tweak tap internal key for input #${inputIndex}. Public key: ${ + tapInternalKey && tapInternalKey.toString('hex') + }`, + ); + return outputKey.x; +} +exports.tweakInternalPubKey = tweakInternalPubKey; +/** + * Convert a binary tree to a BIP371 type list. Each element of the list is (according to BIP371): + * One or more tuples representing the depth, leaf version, and script for a leaf in the Taproot tree, + * allowing the entire tree to be reconstructed. The tuples must be in depth first search order so that + * the tree is correctly reconstructed. + * @param tree the binary tap tree + * @returns a list of BIP 371 tapleaves + */ +function tapTreeToList(tree) { + if (!(0, types_1.isTaptree)(tree)) + throw new Error( + 'Cannot convert taptree to tapleaf list. Expecting a tapree structure.', + ); + return _tapTreeToList(tree); +} +exports.tapTreeToList = tapTreeToList; +/** + * Convert a BIP371 TapLeaf list to a TapTree (binary). + * @param leaves a list of tapleaves where each element of the list is (according to BIP371): + * One or more tuples representing the depth, leaf version, and script for a leaf in the Taproot tree, + * allowing the entire tree to be reconstructed. The tuples must be in depth first search order so that + * the tree is correctly reconstructed. + * @returns the corresponding taptree, or throws an exception if the tree cannot be reconstructed + */ +function tapTreeFromList(leaves = []) { + if (leaves.length === 1 && leaves[0].depth === 0) + return { + output: leaves[0].script, + version: leaves[0].leafVersion, + }; + return instertLeavesInTree(leaves); +} +exports.tapTreeFromList = tapTreeFromList; +function checkTaprootInputForSigs(input, action) { + const sigs = extractTaprootSigs(input); + return sigs.some(sig => + (0, psbtutils_2.signatureBlocksAction)(sig, decodeSchnorrSignature, action), + ); +} +exports.checkTaprootInputForSigs = checkTaprootInputForSigs; +function decodeSchnorrSignature(signature) { + return { + signature: signature.slice(0, 64), + hashType: + signature.slice(64)[0] || transaction_1.Transaction.SIGHASH_DEFAULT, + }; +} +function extractTaprootSigs(input) { + const sigs = []; + if (input.tapKeySig) sigs.push(input.tapKeySig); + if (input.tapScriptSig) + sigs.push(...input.tapScriptSig.map(s => s.signature)); + if (!sigs.length) { + const finalTapKeySig = getTapKeySigFromWithness(input.finalScriptWitness); + if (finalTapKeySig) sigs.push(finalTapKeySig); + } + return sigs; +} +function getTapKeySigFromWithness(finalScriptWitness) { + if (!finalScriptWitness) return; + const witness = finalScriptWitness.slice(2); + // todo: add schnorr signature validation + if (witness.length === 64 || witness.length === 65) return witness; +} +function _tapTreeToList(tree, leaves = [], depth = 0) { + if (depth > bip341_1.MAX_TAPTREE_DEPTH) + throw new Error('Max taptree depth exceeded.'); + if (!tree) return []; + if ((0, types_1.isTapleaf)(tree)) { + leaves.push({ + depth, + leafVersion: tree.version || bip341_1.LEAF_VERSION_TAPSCRIPT, + script: tree.output, + }); + return leaves; + } + if (tree[0]) _tapTreeToList(tree[0], leaves, depth + 1); + if (tree[1]) _tapTreeToList(tree[1], leaves, depth + 1); + return leaves; +} +function instertLeavesInTree(leaves) { + let tree; + for (const leaf of leaves) { + tree = instertLeafInTree(leaf, tree); + if (!tree) throw new Error(`No room left to insert tapleaf in tree`); + } + return tree; +} +function instertLeafInTree(leaf, tree, depth = 0) { + if (depth > bip341_1.MAX_TAPTREE_DEPTH) + throw new Error('Max taptree depth exceeded.'); + if (leaf.depth === depth) { + if (!tree) + return { + output: leaf.script, + version: leaf.leafVersion, + }; + return; + } + if ((0, types_1.isTapleaf)(tree)) return; + const leftSide = instertLeafInTree(leaf, tree && tree[0], depth + 1); + if (leftSide) return [leftSide, tree && tree[1]]; + const rightSide = instertLeafInTree(leaf, tree && tree[1], depth + 1); + if (rightSide) return [tree && tree[0], rightSide]; +} +function checkMixedTaprootAndNonTaprootInputFields( + inputData, + newInputData, + action, +) { + const isBadTaprootUpdate = + isTaprootInput(inputData) && hasNonTaprootFields(newInputData); + const isBadNonTaprootUpdate = + hasNonTaprootFields(inputData) && isTaprootInput(newInputData); + const hasMixedFields = + inputData === newInputData && + isTaprootInput(newInputData) && + hasNonTaprootFields(newInputData); // todo: bad? use !=== + if (isBadTaprootUpdate || isBadNonTaprootUpdate || hasMixedFields) + throw new Error( + `Invalid arguments for Psbt.${action}. ` + + `Cannot use both taproot and non-taproot fields.`, + ); +} +function checkMixedTaprootAndNonTaprootOutputFields( + inputData, + newInputData, + action, +) { + const isBadTaprootUpdate = + isTaprootOutput(inputData) && hasNonTaprootFields(newInputData); + const isBadNonTaprootUpdate = + hasNonTaprootFields(inputData) && isTaprootOutput(newInputData); + const hasMixedFields = + inputData === newInputData && + isTaprootOutput(newInputData) && + hasNonTaprootFields(newInputData); + if (isBadTaprootUpdate || isBadNonTaprootUpdate || hasMixedFields) + throw new Error( + `Invalid arguments for Psbt.${action}. ` + + `Cannot use both taproot and non-taproot fields.`, + ); +} +function checkIfTapLeafInTree(inputData, newInputData, action) { + if (newInputData.tapMerkleRoot) { + const newLeafsInTree = (newInputData.tapLeafScript || []).every(l => + isTapLeafInTree(l, newInputData.tapMerkleRoot), + ); + const oldLeafsInTree = (inputData.tapLeafScript || []).every(l => + isTapLeafInTree(l, newInputData.tapMerkleRoot), + ); + if (!newLeafsInTree || !oldLeafsInTree) + throw new Error( + `Invalid arguments for Psbt.${action}. Tapleaf not part of taptree.`, + ); + } else if (inputData.tapMerkleRoot) { + const newLeafsInTree = (newInputData.tapLeafScript || []).every(l => + isTapLeafInTree(l, inputData.tapMerkleRoot), + ); + if (!newLeafsInTree) + throw new Error( + `Invalid arguments for Psbt.${action}. Tapleaf not part of taptree.`, + ); + } +} +function isTapLeafInTree(tapLeaf, merkleRoot) { + if (!merkleRoot) return true; + const leafHash = (0, bip341_1.tapleafHash)({ + output: tapLeaf.script, + version: tapLeaf.leafVersion, + }); + const rootHash = (0, bip341_1.rootHashFromPath)( + tapLeaf.controlBlock, + leafHash, + ); + return rootHash.equals(merkleRoot); +} +function sortSignatures(input, tapLeaf) { + const leafHash = (0, bip341_1.tapleafHash)({ + output: tapLeaf.script, + version: tapLeaf.leafVersion, + }); + return (input.tapScriptSig || []) + .filter(tss => tss.leafHash.equals(leafHash)) + .map(tss => addPubkeyPositionInScript(tapLeaf.script, tss)) + .sort((t1, t2) => t2.positionInScript - t1.positionInScript) + .map(t => t.signature); +} +function addPubkeyPositionInScript(script, tss) { + return Object.assign( + { + positionInScript: (0, psbtutils_1.pubkeyPositionInScript)( + tss.pubkey, + script, + ), + }, + tss, + ); +} +/** + * Find tapleaf by hash, or get the signed tapleaf with the shortest path. + */ +function findTapLeafToFinalize(input, inputIndex, leafHashToFinalize) { + if (!input.tapScriptSig || !input.tapScriptSig.length) + throw new Error( + `Can not finalize taproot input #${inputIndex}. No tapleaf script signature provided.`, + ); + const tapLeaf = (input.tapLeafScript || []) + .sort((a, b) => a.controlBlock.length - b.controlBlock.length) + .find(leaf => + canFinalizeLeaf(leaf, input.tapScriptSig, leafHashToFinalize), + ); + if (!tapLeaf) + throw new Error( + `Can not finalize taproot input #${inputIndex}. Signature for tapleaf script not found.`, + ); + return tapLeaf; +} +function canFinalizeLeaf(leaf, tapScriptSig, hash) { + const leafHash = (0, bip341_1.tapleafHash)({ + output: leaf.script, + version: leaf.leafVersion, + }); + const whiteListedHash = !hash || hash.equals(leafHash); + return ( + whiteListedHash && + tapScriptSig.find(tss => tss.leafHash.equals(leafHash)) !== undefined + ); +} +function hasNonTaprootFields(io) { + return ( + io && + !!( + io.redeemScript || + io.witnessScript || + (io.bip32Derivation && io.bip32Derivation.length) + ) + ); +} + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../payments":59,"../payments/bip341":57,"../transaction":75,"../types":76,"./psbtutils":70,"buffer":92}],70:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.signatureBlocksAction = + exports.checkInputForSig = + exports.pubkeyInScript = + exports.pubkeyPositionInScript = + exports.witnessStackToScriptWitness = + exports.isP2TR = + exports.isP2SHScript = + exports.isP2WSHScript = + exports.isP2WPKH = + exports.isP2PKH = + exports.isP2PK = + exports.isP2MS = + void 0; +const varuint = require('bip174/src/lib/converter/varint'); +const bscript = require('../script'); +const transaction_1 = require('../transaction'); +const crypto_1 = require('../crypto'); +const payments = require('../payments'); +function isPaymentFactory(payment) { + return script => { + try { + payment({ output: script }); + return true; + } catch (err) { + return false; + } + }; +} +exports.isP2MS = isPaymentFactory(payments.p2ms); +exports.isP2PK = isPaymentFactory(payments.p2pk); +exports.isP2PKH = isPaymentFactory(payments.p2pkh); +exports.isP2WPKH = isPaymentFactory(payments.p2wpkh); +exports.isP2WSHScript = isPaymentFactory(payments.p2wsh); +exports.isP2SHScript = isPaymentFactory(payments.p2sh); +exports.isP2TR = isPaymentFactory(payments.p2tr); +function witnessStackToScriptWitness(witness) { + let buffer = Buffer.allocUnsafe(0); + function writeSlice(slice) { + buffer = Buffer.concat([buffer, Buffer.from(slice)]); + } + function writeVarInt(i) { + const currentLen = buffer.length; + const varintLen = varuint.encodingLength(i); + buffer = Buffer.concat([buffer, Buffer.allocUnsafe(varintLen)]); + varuint.encode(i, buffer, currentLen); + } + function writeVarSlice(slice) { + writeVarInt(slice.length); + writeSlice(slice); + } + function writeVector(vector) { + writeVarInt(vector.length); + vector.forEach(writeVarSlice); + } + writeVector(witness); + return buffer; +} +exports.witnessStackToScriptWitness = witnessStackToScriptWitness; +function pubkeyPositionInScript(pubkey, script) { + const pubkeyHash = (0, crypto_1.hash160)(pubkey); + const pubkeyXOnly = pubkey.slice(1, 33); // slice before calling? + const decompiled = bscript.decompile(script); + if (decompiled === null) throw new Error('Unknown script error'); + return decompiled.findIndex(element => { + if (typeof element === 'number') return false; + return ( + element.equals(pubkey) || + element.equals(pubkeyHash) || + element.equals(pubkeyXOnly) + ); + }); +} +exports.pubkeyPositionInScript = pubkeyPositionInScript; +function pubkeyInScript(pubkey, script) { + return pubkeyPositionInScript(pubkey, script) !== -1; +} +exports.pubkeyInScript = pubkeyInScript; +function checkInputForSig(input, action) { + const pSigs = extractPartialSigs(input); + return pSigs.some(pSig => + signatureBlocksAction(pSig, bscript.signature.decode, action), + ); +} +exports.checkInputForSig = checkInputForSig; +function signatureBlocksAction(signature, signatureDecodeFn, action) { + const { hashType } = signatureDecodeFn(signature); + const whitelist = []; + const isAnyoneCanPay = + hashType & transaction_1.Transaction.SIGHASH_ANYONECANPAY; + if (isAnyoneCanPay) whitelist.push('addInput'); + const hashMod = hashType & 0x1f; + switch (hashMod) { + case transaction_1.Transaction.SIGHASH_ALL: + break; + case transaction_1.Transaction.SIGHASH_SINGLE: + case transaction_1.Transaction.SIGHASH_NONE: + whitelist.push('addOutput'); + whitelist.push('setInputSequence'); + break; + } + if (whitelist.indexOf(action) === -1) { + return true; + } + return false; +} +exports.signatureBlocksAction = signatureBlocksAction; +function extractPartialSigs(input) { + let pSigs = []; + if ((input.partialSig || []).length === 0) { + if (!input.finalScriptSig && !input.finalScriptWitness) return []; + pSigs = getPsigsFromInputFinalScripts(input); + } else { + pSigs = input.partialSig; + } + return pSigs.map(p => p.signature); +} +function getPsigsFromInputFinalScripts(input) { + const scriptItems = !input.finalScriptSig + ? [] + : bscript.decompile(input.finalScriptSig) || []; + const witnessItems = !input.finalScriptWitness + ? [] + : bscript.decompile(input.finalScriptWitness) || []; + return scriptItems + .concat(witnessItems) + .filter(item => { + return Buffer.isBuffer(item) && bscript.isCanonicalScriptSignature(item); + }) + .map(sig => ({ signature: sig })); +} + +}).call(this)}).call(this,require("buffer").Buffer) +},{"../crypto":51,"../payments":59,"../script":72,"../transaction":75,"bip174/src/lib/converter/varint":40,"buffer":92}],71:[function(require,module,exports){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.decode = exports.encode = exports.encodingLength = void 0; +const ops_1 = require('./ops'); +function encodingLength(i) { + return i < ops_1.OPS.OP_PUSHDATA1 ? 1 : i <= 0xff ? 2 : i <= 0xffff ? 3 : 5; +} +exports.encodingLength = encodingLength; +function encode(buffer, num, offset) { + const size = encodingLength(num); + // ~6 bit + if (size === 1) { + buffer.writeUInt8(num, offset); + // 8 bit + } else if (size === 2) { + buffer.writeUInt8(ops_1.OPS.OP_PUSHDATA1, offset); + buffer.writeUInt8(num, offset + 1); + // 16 bit + } else if (size === 3) { + buffer.writeUInt8(ops_1.OPS.OP_PUSHDATA2, offset); + buffer.writeUInt16LE(num, offset + 1); + // 32 bit + } else { + buffer.writeUInt8(ops_1.OPS.OP_PUSHDATA4, offset); + buffer.writeUInt32LE(num, offset + 1); + } + return size; +} +exports.encode = encode; +function decode(buffer, offset) { + const opcode = buffer.readUInt8(offset); + let num; + let size; + // ~6 bit + if (opcode < ops_1.OPS.OP_PUSHDATA1) { + num = opcode; + size = 1; + // 8 bit + } else if (opcode === ops_1.OPS.OP_PUSHDATA1) { + if (offset + 2 > buffer.length) return null; + num = buffer.readUInt8(offset + 1); + size = 2; + // 16 bit + } else if (opcode === ops_1.OPS.OP_PUSHDATA2) { + if (offset + 3 > buffer.length) return null; + num = buffer.readUInt16LE(offset + 1); + size = 3; + // 32 bit + } else { + if (offset + 5 > buffer.length) return null; + if (opcode !== ops_1.OPS.OP_PUSHDATA4) throw new Error('Unexpected opcode'); + num = buffer.readUInt32LE(offset + 1); + size = 5; + } + return { + opcode, + number: num, + size, + }; +} +exports.decode = decode; + +},{"./ops":56}],72:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.signature = + exports.number = + exports.isCanonicalScriptSignature = + exports.isDefinedHashType = + exports.isCanonicalPubKey = + exports.toStack = + exports.fromASM = + exports.toASM = + exports.decompile = + exports.compile = + exports.countNonPushOnlyOPs = + exports.isPushOnly = + exports.OPS = + void 0; +const bip66 = require('./bip66'); +const ops_1 = require('./ops'); +Object.defineProperty(exports, 'OPS', { + enumerable: true, + get: function () { + return ops_1.OPS; + }, +}); +const pushdata = require('./push_data'); +const scriptNumber = require('./script_number'); +const scriptSignature = require('./script_signature'); +const types = require('./types'); +const { typeforce } = types; +const OP_INT_BASE = ops_1.OPS.OP_RESERVED; // OP_1 - 1 +function isOPInt(value) { + return ( + types.Number(value) && + (value === ops_1.OPS.OP_0 || + (value >= ops_1.OPS.OP_1 && value <= ops_1.OPS.OP_16) || + value === ops_1.OPS.OP_1NEGATE) + ); +} +function isPushOnlyChunk(value) { + return types.Buffer(value) || isOPInt(value); +} +function isPushOnly(value) { + return types.Array(value) && value.every(isPushOnlyChunk); +} +exports.isPushOnly = isPushOnly; +function countNonPushOnlyOPs(value) { + return value.length - value.filter(isPushOnlyChunk).length; +} +exports.countNonPushOnlyOPs = countNonPushOnlyOPs; +function asMinimalOP(buffer) { + if (buffer.length === 0) return ops_1.OPS.OP_0; + if (buffer.length !== 1) return; + if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]; + if (buffer[0] === 0x81) return ops_1.OPS.OP_1NEGATE; +} +function chunksIsBuffer(buf) { + return Buffer.isBuffer(buf); +} +function chunksIsArray(buf) { + return types.Array(buf); +} +function singleChunkIsBuffer(buf) { + return Buffer.isBuffer(buf); +} +function compile(chunks) { + // TODO: remove me + if (chunksIsBuffer(chunks)) return chunks; + typeforce(types.Array, chunks); + const bufferSize = chunks.reduce((accum, chunk) => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { + return accum + 1; + } + return accum + pushdata.encodingLength(chunk.length) + chunk.length; + } + // opcode + return accum + 1; + }, 0.0); + const buffer = Buffer.allocUnsafe(bufferSize); + let offset = 0; + chunks.forEach(chunk => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + const opcode = asMinimalOP(chunk); + if (opcode !== undefined) { + buffer.writeUInt8(opcode, offset); + offset += 1; + return; + } + offset += pushdata.encode(buffer, chunk.length, offset); + chunk.copy(buffer, offset); + offset += chunk.length; + // opcode + } else { + buffer.writeUInt8(chunk, offset); + offset += 1; + } + }); + if (offset !== buffer.length) throw new Error('Could not decode chunks'); + return buffer; +} +exports.compile = compile; +function decompile(buffer) { + // TODO: remove me + if (chunksIsArray(buffer)) return buffer; + typeforce(types.Buffer, buffer); + const chunks = []; + let i = 0; + while (i < buffer.length) { + const opcode = buffer[i]; + // data chunk + if (opcode > ops_1.OPS.OP_0 && opcode <= ops_1.OPS.OP_PUSHDATA4) { + const d = pushdata.decode(buffer, i); + // did reading a pushDataInt fail? + if (d === null) return null; + i += d.size; + // attempt to read too much data? + if (i + d.number > buffer.length) return null; + const data = buffer.slice(i, i + d.number); + i += d.number; + // decompile minimally + const op = asMinimalOP(data); + if (op !== undefined) { + chunks.push(op); + } else { + chunks.push(data); + } + // opcode + } else { + chunks.push(opcode); + i += 1; + } + } + return chunks; +} +exports.decompile = decompile; +function toASM(chunks) { + if (chunksIsBuffer(chunks)) { + chunks = decompile(chunks); + } + return chunks + .map(chunk => { + // data? + if (singleChunkIsBuffer(chunk)) { + const op = asMinimalOP(chunk); + if (op === undefined) return chunk.toString('hex'); + chunk = op; + } + // opcode! + return ops_1.REVERSE_OPS[chunk]; + }) + .join(' '); +} +exports.toASM = toASM; +function fromASM(asm) { + typeforce(types.String, asm); + return compile( + asm.split(' ').map(chunkStr => { + // opcode? + if (ops_1.OPS[chunkStr] !== undefined) return ops_1.OPS[chunkStr]; + typeforce(types.Hex, chunkStr); + // data! + return Buffer.from(chunkStr, 'hex'); + }), + ); +} +exports.fromASM = fromASM; +function toStack(chunks) { + chunks = decompile(chunks); + typeforce(isPushOnly, chunks); + return chunks.map(op => { + if (singleChunkIsBuffer(op)) return op; + if (op === ops_1.OPS.OP_0) return Buffer.allocUnsafe(0); + return scriptNumber.encode(op - OP_INT_BASE); + }); +} +exports.toStack = toStack; +function isCanonicalPubKey(buffer) { + return types.isPoint(buffer); +} +exports.isCanonicalPubKey = isCanonicalPubKey; +function isDefinedHashType(hashType) { + const hashTypeMod = hashType & ~0x80; + // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE + return hashTypeMod > 0x00 && hashTypeMod < 0x04; +} +exports.isDefinedHashType = isDefinedHashType; +function isCanonicalScriptSignature(buffer) { + if (!Buffer.isBuffer(buffer)) return false; + if (!isDefinedHashType(buffer[buffer.length - 1])) return false; + return bip66.check(buffer.slice(0, -1)); +} +exports.isCanonicalScriptSignature = isCanonicalScriptSignature; +exports.number = scriptNumber; +exports.signature = scriptSignature; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./bip66":48,"./ops":56,"./push_data":71,"./script_number":73,"./script_signature":74,"./types":76,"buffer":92}],73:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.encode = exports.decode = void 0; +function decode(buffer, maxLength, minimal) { + maxLength = maxLength || 4; + minimal = minimal === undefined ? true : minimal; + const length = buffer.length; + if (length === 0) return 0; + if (length > maxLength) throw new TypeError('Script number overflow'); + if (minimal) { + if ((buffer[length - 1] & 0x7f) === 0) { + if (length <= 1 || (buffer[length - 2] & 0x80) === 0) + throw new Error('Non-minimally encoded script number'); + } + } + // 40-bit + if (length === 5) { + const a = buffer.readUInt32LE(0); + const b = buffer.readUInt8(4); + if (b & 0x80) return -((b & ~0x80) * 0x100000000 + a); + return b * 0x100000000 + a; + } + // 32-bit / 24-bit / 16-bit / 8-bit + let result = 0; + for (let i = 0; i < length; ++i) { + result |= buffer[i] << (8 * i); + } + if (buffer[length - 1] & 0x80) + return -(result & ~(0x80 << (8 * (length - 1)))); + return result; +} +exports.decode = decode; +function scriptNumSize(i) { + return i > 0x7fffffff + ? 5 + : i > 0x7fffff + ? 4 + : i > 0x7fff + ? 3 + : i > 0x7f + ? 2 + : i > 0x00 + ? 1 + : 0; +} +function encode(_number) { + let value = Math.abs(_number); + const size = scriptNumSize(value); + const buffer = Buffer.allocUnsafe(size); + const negative = _number < 0; + for (let i = 0; i < size; ++i) { + buffer.writeUInt8(value & 0xff, i); + value >>= 8; + } + if (buffer[size - 1] & 0x80) { + buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1); + } else if (negative) { + buffer[size - 1] |= 0x80; + } + return buffer; +} +exports.encode = encode; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"buffer":92}],74:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.encode = exports.decode = void 0; +const bip66 = require('./bip66'); +const types = require('./types'); +const { typeforce } = types; +const ZERO = Buffer.alloc(1, 0); +function toDER(x) { + let i = 0; + while (x[i] === 0) ++i; + if (i === x.length) return ZERO; + x = x.slice(i); + if (x[0] & 0x80) return Buffer.concat([ZERO, x], 1 + x.length); + return x; +} +function fromDER(x) { + if (x[0] === 0x00) x = x.slice(1); + const buffer = Buffer.alloc(32, 0); + const bstart = Math.max(0, 32 - x.length); + x.copy(buffer, bstart); + return buffer; +} +// BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) +function decode(buffer) { + const hashType = buffer.readUInt8(buffer.length - 1); + const hashTypeMod = hashType & ~0x80; + if (hashTypeMod <= 0 || hashTypeMod >= 4) + throw new Error('Invalid hashType ' + hashType); + const decoded = bip66.decode(buffer.slice(0, -1)); + const r = fromDER(decoded.r); + const s = fromDER(decoded.s); + const signature = Buffer.concat([r, s], 64); + return { signature, hashType }; +} +exports.decode = decode; +function encode(signature, hashType) { + typeforce( + { + signature: types.BufferN(64), + hashType: types.UInt8, + }, + { signature, hashType }, + ); + const hashTypeMod = hashType & ~0x80; + if (hashTypeMod <= 0 || hashTypeMod >= 4) + throw new Error('Invalid hashType ' + hashType); + const hashTypeBuffer = Buffer.allocUnsafe(1); + hashTypeBuffer.writeUInt8(hashType, 0); + const r = toDER(signature.slice(0, 32)); + const s = toDER(signature.slice(32, 64)); + return Buffer.concat([bip66.encode(r, s), hashTypeBuffer]); +} +exports.encode = encode; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./bip66":48,"./types":76,"buffer":92}],75:[function(require,module,exports){ +(function (Buffer){(function (){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.Transaction = void 0; +const bufferutils_1 = require('./bufferutils'); +const bcrypto = require('./crypto'); +const bscript = require('./script'); +const script_1 = require('./script'); +const types = require('./types'); +const { typeforce } = types; +function varSliceSize(someScript) { + const length = someScript.length; + return bufferutils_1.varuint.encodingLength(length) + length; +} +function vectorSize(someVector) { + const length = someVector.length; + return ( + bufferutils_1.varuint.encodingLength(length) + + someVector.reduce((sum, witness) => { + return sum + varSliceSize(witness); + }, 0) + ); +} +const EMPTY_BUFFER = Buffer.allocUnsafe(0); +const EMPTY_WITNESS = []; +const ZERO = Buffer.from( + '0000000000000000000000000000000000000000000000000000000000000000', + 'hex', +); +const ONE = Buffer.from( + '0000000000000000000000000000000000000000000000000000000000000001', + 'hex', +); +const VALUE_UINT64_MAX = Buffer.from('ffffffffffffffff', 'hex'); +const BLANK_OUTPUT = { + script: EMPTY_BUFFER, + valueBuffer: VALUE_UINT64_MAX, +}; +function isOutput(out) { + return out.value !== undefined; +} +class Transaction { + constructor() { + this.version = 1; + this.locktime = 0; + this.ins = []; + this.outs = []; + } + static fromBuffer(buffer, _NO_STRICT) { + const bufferReader = new bufferutils_1.BufferReader(buffer); + const tx = new Transaction(); + tx.version = bufferReader.readInt32(); + const marker = bufferReader.readUInt8(); + const flag = bufferReader.readUInt8(); + let hasWitnesses = false; + if ( + marker === Transaction.ADVANCED_TRANSACTION_MARKER && + flag === Transaction.ADVANCED_TRANSACTION_FLAG + ) { + hasWitnesses = true; + } else { + bufferReader.offset -= 2; + } + const vinLen = bufferReader.readVarInt(); + for (let i = 0; i < vinLen; ++i) { + tx.ins.push({ + hash: bufferReader.readSlice(32), + index: bufferReader.readUInt32(), + script: bufferReader.readVarSlice(), + sequence: bufferReader.readUInt32(), + witness: EMPTY_WITNESS, + }); + } + const voutLen = bufferReader.readVarInt(); + for (let i = 0; i < voutLen; ++i) { + tx.outs.push({ + value: bufferReader.readUInt64(), + script: bufferReader.readVarSlice(), + }); + } + if (hasWitnesses) { + for (let i = 0; i < vinLen; ++i) { + tx.ins[i].witness = bufferReader.readVector(); + } + // was this pointless? + if (!tx.hasWitnesses()) + throw new Error('Transaction has superfluous witness data'); + } + tx.locktime = bufferReader.readUInt32(); + if (_NO_STRICT) return tx; + if (bufferReader.offset !== buffer.length) + throw new Error('Transaction has unexpected data'); + return tx; + } + static fromHex(hex) { + return Transaction.fromBuffer(Buffer.from(hex, 'hex'), false); + } + static isCoinbaseHash(buffer) { + typeforce(types.Hash256bit, buffer); + for (let i = 0; i < 32; ++i) { + if (buffer[i] !== 0) return false; + } + return true; + } + isCoinbase() { + return ( + this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) + ); + } + addInput(hash, index, sequence, scriptSig) { + typeforce( + types.tuple( + types.Hash256bit, + types.UInt32, + types.maybe(types.UInt32), + types.maybe(types.Buffer), + ), + arguments, + ); + if (types.Null(sequence)) { + sequence = Transaction.DEFAULT_SEQUENCE; + } + // Add the input and return the input's index + return ( + this.ins.push({ + hash, + index, + script: scriptSig || EMPTY_BUFFER, + sequence: sequence, + witness: EMPTY_WITNESS, + }) - 1 + ); + } + addOutput(scriptPubKey, value) { + typeforce(types.tuple(types.Buffer, types.Satoshi), arguments); + // Add the output and return the output's index + return ( + this.outs.push({ + script: scriptPubKey, + value, + }) - 1 + ); + } + hasWitnesses() { + return this.ins.some(x => { + return x.witness.length !== 0; + }); + } + weight() { + const base = this.byteLength(false); + const total = this.byteLength(true); + return base * 3 + total; + } + virtualSize() { + return Math.ceil(this.weight() / 4); + } + byteLength(_ALLOW_WITNESS = true) { + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + return ( + (hasWitnesses ? 10 : 8) + + bufferutils_1.varuint.encodingLength(this.ins.length) + + bufferutils_1.varuint.encodingLength(this.outs.length) + + this.ins.reduce((sum, input) => { + return sum + 40 + varSliceSize(input.script); + }, 0) + + this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0) + + (hasWitnesses + ? this.ins.reduce((sum, input) => { + return sum + vectorSize(input.witness); + }, 0) + : 0) + ); + } + clone() { + const newTx = new Transaction(); + newTx.version = this.version; + newTx.locktime = this.locktime; + newTx.ins = this.ins.map(txIn => { + return { + hash: txIn.hash, + index: txIn.index, + script: txIn.script, + sequence: txIn.sequence, + witness: txIn.witness, + }; + }); + newTx.outs = this.outs.map(txOut => { + return { + script: txOut.script, + value: txOut.value, + }; + }); + return newTx; + } + /** + * Hash transaction for signing a specific input. + * + * Bitcoin uses a different hash for each signed transaction input. + * This method copies the transaction, makes the necessary changes based on the + * hashType, and then hashes the result. + * This hash can then be used to sign the provided transaction input. + */ + hashForSignature(inIndex, prevOutScript, hashType) { + typeforce( + types.tuple(types.UInt32, types.Buffer, /* types.UInt8 */ types.Number), + arguments, + ); + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 + if (inIndex >= this.ins.length) return ONE; + // ignore OP_CODESEPARATOR + const ourScript = bscript.compile( + bscript.decompile(prevOutScript).filter(x => { + return x !== script_1.OPS.OP_CODESEPARATOR; + }), + ); + const txTmp = this.clone(); + // SIGHASH_NONE: ignore all outputs? (wildcard payee) + if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { + txTmp.outs = []; + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, i) => { + if (i === inIndex) return; + input.sequence = 0; + }); + // SIGHASH_SINGLE: ignore all outputs, except at the same index? + } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 + if (inIndex >= this.outs.length) return ONE; + // truncate outputs after + txTmp.outs.length = inIndex + 1; + // "blank" outputs before + for (let i = 0; i < inIndex; i++) { + txTmp.outs[i] = BLANK_OUTPUT; + } + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, y) => { + if (y === inIndex) return; + input.sequence = 0; + }); + } + // SIGHASH_ANYONECANPAY: ignore inputs entirely? + if (hashType & Transaction.SIGHASH_ANYONECANPAY) { + txTmp.ins = [txTmp.ins[inIndex]]; + txTmp.ins[0].script = ourScript; + // SIGHASH_ALL: only ignore input scripts + } else { + // "blank" others input scripts + txTmp.ins.forEach(input => { + input.script = EMPTY_BUFFER; + }); + txTmp.ins[inIndex].script = ourScript; + } + // serialize and hash + const buffer = Buffer.allocUnsafe(txTmp.byteLength(false) + 4); + buffer.writeInt32LE(hashType, buffer.length - 4); + txTmp.__toBuffer(buffer, 0, false); + return bcrypto.hash256(buffer); + } + hashForWitnessV1(inIndex, prevOutScripts, values, hashType, leafHash, annex) { + // https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#common-signature-message + typeforce( + types.tuple( + types.UInt32, + typeforce.arrayOf(types.Buffer), + typeforce.arrayOf(types.Satoshi), + types.UInt32, + ), + arguments, + ); + if ( + values.length !== this.ins.length || + prevOutScripts.length !== this.ins.length + ) { + throw new Error('Must supply prevout script and value for all inputs'); + } + const outputType = + hashType === Transaction.SIGHASH_DEFAULT + ? Transaction.SIGHASH_ALL + : hashType & Transaction.SIGHASH_OUTPUT_MASK; + const inputType = hashType & Transaction.SIGHASH_INPUT_MASK; + const isAnyoneCanPay = inputType === Transaction.SIGHASH_ANYONECANPAY; + const isNone = outputType === Transaction.SIGHASH_NONE; + const isSingle = outputType === Transaction.SIGHASH_SINGLE; + let hashPrevouts = EMPTY_BUFFER; + let hashAmounts = EMPTY_BUFFER; + let hashScriptPubKeys = EMPTY_BUFFER; + let hashSequences = EMPTY_BUFFER; + let hashOutputs = EMPTY_BUFFER; + if (!isAnyoneCanPay) { + let bufferWriter = bufferutils_1.BufferWriter.withCapacity( + 36 * this.ins.length, + ); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + }); + hashPrevouts = bcrypto.sha256(bufferWriter.end()); + bufferWriter = bufferutils_1.BufferWriter.withCapacity( + 8 * this.ins.length, + ); + values.forEach(value => bufferWriter.writeUInt64(value)); + hashAmounts = bcrypto.sha256(bufferWriter.end()); + bufferWriter = bufferutils_1.BufferWriter.withCapacity( + prevOutScripts.map(varSliceSize).reduce((a, b) => a + b), + ); + prevOutScripts.forEach(prevOutScript => + bufferWriter.writeVarSlice(prevOutScript), + ); + hashScriptPubKeys = bcrypto.sha256(bufferWriter.end()); + bufferWriter = bufferutils_1.BufferWriter.withCapacity( + 4 * this.ins.length, + ); + this.ins.forEach(txIn => bufferWriter.writeUInt32(txIn.sequence)); + hashSequences = bcrypto.sha256(bufferWriter.end()); + } + if (!(isNone || isSingle)) { + const txOutsSize = this.outs + .map(output => 8 + varSliceSize(output.script)) + .reduce((a, b) => a + b); + const bufferWriter = bufferutils_1.BufferWriter.withCapacity(txOutsSize); + this.outs.forEach(out => { + bufferWriter.writeUInt64(out.value); + bufferWriter.writeVarSlice(out.script); + }); + hashOutputs = bcrypto.sha256(bufferWriter.end()); + } else if (isSingle && inIndex < this.outs.length) { + const output = this.outs[inIndex]; + const bufferWriter = bufferutils_1.BufferWriter.withCapacity( + 8 + varSliceSize(output.script), + ); + bufferWriter.writeUInt64(output.value); + bufferWriter.writeVarSlice(output.script); + hashOutputs = bcrypto.sha256(bufferWriter.end()); + } + const spendType = (leafHash ? 2 : 0) + (annex ? 1 : 0); + // Length calculation from: + // https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_note-14 + // With extension from: + // https://github.com/bitcoin/bips/blob/master/bip-0342.mediawiki#signature-validation + const sigMsgSize = + 174 - + (isAnyoneCanPay ? 49 : 0) - + (isNone ? 32 : 0) + + (annex ? 32 : 0) + + (leafHash ? 37 : 0); + const sigMsgWriter = bufferutils_1.BufferWriter.withCapacity(sigMsgSize); + sigMsgWriter.writeUInt8(hashType); + // Transaction + sigMsgWriter.writeInt32(this.version); + sigMsgWriter.writeUInt32(this.locktime); + sigMsgWriter.writeSlice(hashPrevouts); + sigMsgWriter.writeSlice(hashAmounts); + sigMsgWriter.writeSlice(hashScriptPubKeys); + sigMsgWriter.writeSlice(hashSequences); + if (!(isNone || isSingle)) { + sigMsgWriter.writeSlice(hashOutputs); + } + // Input + sigMsgWriter.writeUInt8(spendType); + if (isAnyoneCanPay) { + const input = this.ins[inIndex]; + sigMsgWriter.writeSlice(input.hash); + sigMsgWriter.writeUInt32(input.index); + sigMsgWriter.writeUInt64(values[inIndex]); + sigMsgWriter.writeVarSlice(prevOutScripts[inIndex]); + sigMsgWriter.writeUInt32(input.sequence); + } else { + sigMsgWriter.writeUInt32(inIndex); + } + if (annex) { + const bufferWriter = bufferutils_1.BufferWriter.withCapacity( + varSliceSize(annex), + ); + bufferWriter.writeVarSlice(annex); + sigMsgWriter.writeSlice(bcrypto.sha256(bufferWriter.end())); + } + // Output + if (isSingle) { + sigMsgWriter.writeSlice(hashOutputs); + } + // BIP342 extension + if (leafHash) { + sigMsgWriter.writeSlice(leafHash); + sigMsgWriter.writeUInt8(0); + sigMsgWriter.writeUInt32(0xffffffff); + } + // Extra zero byte because: + // https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_note-19 + return bcrypto.taggedHash( + 'TapSighash', + Buffer.concat([Buffer.from([0x00]), sigMsgWriter.end()]), + ); + } + hashForWitnessV0(inIndex, prevOutScript, value, hashType) { + typeforce( + types.tuple(types.UInt32, types.Buffer, types.Satoshi, types.UInt32), + arguments, + ); + let tbuffer = Buffer.from([]); + let bufferWriter; + let hashOutputs = ZERO; + let hashPrevouts = ZERO; + let hashSequence = ZERO; + if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { + tbuffer = Buffer.allocUnsafe(36 * this.ins.length); + bufferWriter = new bufferutils_1.BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + }); + hashPrevouts = bcrypto.hash256(tbuffer); + } + if ( + !(hashType & Transaction.SIGHASH_ANYONECANPAY) && + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + tbuffer = Buffer.allocUnsafe(4 * this.ins.length); + bufferWriter = new bufferutils_1.BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeUInt32(txIn.sequence); + }); + hashSequence = bcrypto.hash256(tbuffer); + } + if ( + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + const txOutsSize = this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0); + tbuffer = Buffer.allocUnsafe(txOutsSize); + bufferWriter = new bufferutils_1.BufferWriter(tbuffer, 0); + this.outs.forEach(out => { + bufferWriter.writeUInt64(out.value); + bufferWriter.writeVarSlice(out.script); + }); + hashOutputs = bcrypto.hash256(tbuffer); + } else if ( + (hashType & 0x1f) === Transaction.SIGHASH_SINGLE && + inIndex < this.outs.length + ) { + const output = this.outs[inIndex]; + tbuffer = Buffer.allocUnsafe(8 + varSliceSize(output.script)); + bufferWriter = new bufferutils_1.BufferWriter(tbuffer, 0); + bufferWriter.writeUInt64(output.value); + bufferWriter.writeVarSlice(output.script); + hashOutputs = bcrypto.hash256(tbuffer); + } + tbuffer = Buffer.allocUnsafe(156 + varSliceSize(prevOutScript)); + bufferWriter = new bufferutils_1.BufferWriter(tbuffer, 0); + const input = this.ins[inIndex]; + bufferWriter.writeInt32(this.version); + bufferWriter.writeSlice(hashPrevouts); + bufferWriter.writeSlice(hashSequence); + bufferWriter.writeSlice(input.hash); + bufferWriter.writeUInt32(input.index); + bufferWriter.writeVarSlice(prevOutScript); + bufferWriter.writeUInt64(value); + bufferWriter.writeUInt32(input.sequence); + bufferWriter.writeSlice(hashOutputs); + bufferWriter.writeUInt32(this.locktime); + bufferWriter.writeUInt32(hashType); + return bcrypto.hash256(tbuffer); + } + getHash(forWitness) { + // wtxid for coinbase is always 32 bytes of 0x00 + if (forWitness && this.isCoinbase()) return Buffer.alloc(32, 0); + return bcrypto.hash256(this.__toBuffer(undefined, undefined, forWitness)); + } + getId() { + // transaction hash's are displayed in reverse order + return (0, bufferutils_1.reverseBuffer)(this.getHash(false)).toString( + 'hex', + ); + } + toBuffer(buffer, initialOffset) { + return this.__toBuffer(buffer, initialOffset, true); + } + toHex() { + return this.toBuffer(undefined, undefined).toString('hex'); + } + setInputScript(index, scriptSig) { + typeforce(types.tuple(types.Number, types.Buffer), arguments); + this.ins[index].script = scriptSig; + } + setWitness(index, witness) { + typeforce(types.tuple(types.Number, [types.Buffer]), arguments); + this.ins[index].witness = witness; + } + __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { + if (!buffer) buffer = Buffer.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); + const bufferWriter = new bufferutils_1.BufferWriter( + buffer, + initialOffset || 0, + ); + bufferWriter.writeInt32(this.version); + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + if (hasWitnesses) { + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER); + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG); + } + bufferWriter.writeVarInt(this.ins.length); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + bufferWriter.writeVarSlice(txIn.script); + bufferWriter.writeUInt32(txIn.sequence); + }); + bufferWriter.writeVarInt(this.outs.length); + this.outs.forEach(txOut => { + if (isOutput(txOut)) { + bufferWriter.writeUInt64(txOut.value); + } else { + bufferWriter.writeSlice(txOut.valueBuffer); + } + bufferWriter.writeVarSlice(txOut.script); + }); + if (hasWitnesses) { + this.ins.forEach(input => { + bufferWriter.writeVector(input.witness); + }); + } + bufferWriter.writeUInt32(this.locktime); + // avoid slicing unless necessary + if (initialOffset !== undefined) + return buffer.slice(initialOffset, bufferWriter.offset); + return buffer; + } +} +exports.Transaction = Transaction; +Transaction.DEFAULT_SEQUENCE = 0xffffffff; +Transaction.SIGHASH_DEFAULT = 0x00; +Transaction.SIGHASH_ALL = 0x01; +Transaction.SIGHASH_NONE = 0x02; +Transaction.SIGHASH_SINGLE = 0x03; +Transaction.SIGHASH_ANYONECANPAY = 0x80; +Transaction.SIGHASH_OUTPUT_MASK = 0x03; +Transaction.SIGHASH_INPUT_MASK = 0x80; +Transaction.ADVANCED_TRANSACTION_MARKER = 0x00; +Transaction.ADVANCED_TRANSACTION_FLAG = 0x01; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./bufferutils":50,"./crypto":51,"./script":72,"./types":76,"buffer":92}],76:[function(require,module,exports){ +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.oneOf = + exports.Null = + exports.BufferN = + exports.Function = + exports.UInt32 = + exports.UInt8 = + exports.tuple = + exports.maybe = + exports.Hex = + exports.Buffer = + exports.String = + exports.Boolean = + exports.Array = + exports.Number = + exports.Hash256bit = + exports.Hash160bit = + exports.Buffer256bit = + exports.isTaptree = + exports.isTapleaf = + exports.TAPLEAF_VERSION_MASK = + exports.Network = + exports.ECPoint = + exports.Satoshi = + exports.Signer = + exports.BIP32Path = + exports.UInt31 = + exports.isPoint = + exports.typeforce = + void 0; +const buffer_1 = require('buffer'); +exports.typeforce = require('typeforce'); +const ZERO32 = buffer_1.Buffer.alloc(32, 0); +const EC_P = buffer_1.Buffer.from( + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', + 'hex', +); +function isPoint(p) { + if (!buffer_1.Buffer.isBuffer(p)) return false; + if (p.length < 33) return false; + const t = p[0]; + const x = p.slice(1, 33); + if (x.compare(ZERO32) === 0) return false; + if (x.compare(EC_P) >= 0) return false; + if ((t === 0x02 || t === 0x03) && p.length === 33) { + return true; + } + const y = p.slice(33); + if (y.compare(ZERO32) === 0) return false; + if (y.compare(EC_P) >= 0) return false; + if (t === 0x04 && p.length === 65) return true; + return false; +} +exports.isPoint = isPoint; +const UINT31_MAX = Math.pow(2, 31) - 1; +function UInt31(value) { + return exports.typeforce.UInt32(value) && value <= UINT31_MAX; +} +exports.UInt31 = UInt31; +function BIP32Path(value) { + return ( + exports.typeforce.String(value) && !!value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) + ); +} +exports.BIP32Path = BIP32Path; +BIP32Path.toJSON = () => { + return 'BIP32 derivation path'; +}; +function Signer(obj) { + return ( + (exports.typeforce.Buffer(obj.publicKey) || + typeof obj.getPublicKey === 'function') && + typeof obj.sign === 'function' + ); +} +exports.Signer = Signer; +const SATOSHI_MAX = 21 * 1e14; +function Satoshi(value) { + return exports.typeforce.UInt53(value) && value <= SATOSHI_MAX; +} +exports.Satoshi = Satoshi; +// external dependent types +exports.ECPoint = exports.typeforce.quacksLike('Point'); +// exposed, external API +exports.Network = exports.typeforce.compile({ + messagePrefix: exports.typeforce.oneOf( + exports.typeforce.Buffer, + exports.typeforce.String, + ), + bip32: { + public: exports.typeforce.UInt32, + private: exports.typeforce.UInt32, + }, + pubKeyHash: exports.typeforce.UInt8, + scriptHash: exports.typeforce.UInt8, + wif: exports.typeforce.UInt8, +}); +exports.TAPLEAF_VERSION_MASK = 0xfe; +function isTapleaf(o) { + if (!o || !('output' in o)) return false; + if (!buffer_1.Buffer.isBuffer(o.output)) return false; + if (o.version !== undefined) + return (o.version & exports.TAPLEAF_VERSION_MASK) === o.version; + return true; +} +exports.isTapleaf = isTapleaf; +function isTaptree(scriptTree) { + if (!(0, exports.Array)(scriptTree)) return isTapleaf(scriptTree); + if (scriptTree.length !== 2) return false; + return scriptTree.every(t => isTaptree(t)); +} +exports.isTaptree = isTaptree; +exports.Buffer256bit = exports.typeforce.BufferN(32); +exports.Hash160bit = exports.typeforce.BufferN(20); +exports.Hash256bit = exports.typeforce.BufferN(32); +exports.Number = exports.typeforce.Number; +exports.Array = exports.typeforce.Array; +exports.Boolean = exports.typeforce.Boolean; +exports.String = exports.typeforce.String; +exports.Buffer = exports.typeforce.Buffer; +exports.Hex = exports.typeforce.Hex; +exports.maybe = exports.typeforce.maybe; +exports.tuple = exports.typeforce.tuple; +exports.UInt8 = exports.typeforce.UInt8; +exports.UInt32 = exports.typeforce.UInt32; +exports.Function = exports.typeforce.Function; +exports.BufferN = exports.typeforce.BufferN; +exports.Null = exports.typeforce.Null; +exports.oneOf = exports.typeforce.oneOf; + +},{"buffer":92,"typeforce":83}],77:[function(require,module,exports){ +const basex = require('base-x') +const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' + +module.exports = basex(ALPHABET) + +},{"base-x":11}],78:[function(require,module,exports){ +'use strict' + +var base58 = require('bs58') + +module.exports = function (checksumFn) { + // Encode a buffer as a base58-check encoded string + function encode (payload) { + var payloadU8 = Uint8Array.from(payload) + var checksum = checksumFn(payloadU8) + var length = payloadU8.length + 4 + var both = new Uint8Array(length) + both.set(payloadU8, 0) + both.set(checksum.subarray(0, 4), payloadU8.length) + return base58.encode(both, length) + } + + function decodeRaw (buffer) { + var payload = buffer.slice(0, -4) + var checksum = buffer.slice(-4) + var newChecksum = checksumFn(payload) + + if (checksum[0] ^ newChecksum[0] | + checksum[1] ^ newChecksum[1] | + checksum[2] ^ newChecksum[2] | + checksum[3] ^ newChecksum[3]) return + + return payload + } + + // Decode a base58-check encoded string to a buffer, no result if checksum is wrong + function decodeUnsafe (string) { + var buffer = base58.decodeUnsafe(string) + if (!buffer) return + + return decodeRaw(buffer) + } + + function decode (string) { + var buffer = base58.decode(string) + var payload = decodeRaw(buffer, checksumFn) + if (!payload) throw new Error('Invalid checksum') + return payload + } + + return { + encode: encode, + decode: decode, + decodeUnsafe: decodeUnsafe + } +} + +},{"bs58":77}],79:[function(require,module,exports){ +'use strict' + +var { sha256 } = require('@noble/hashes/sha256') +var bs58checkBase = require('./base') + +// SHA256(SHA256(buffer)) +function sha256x2 (buffer) { + return sha256(sha256(buffer)) +} + +module.exports = bs58checkBase(sha256x2) + +},{"./base":78,"@noble/hashes/sha256":8}],80:[function(require,module,exports){ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + +},{"buffer":92}],81:[function(require,module,exports){ +var native = require('./native') + +function getTypeName (fn) { + return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1] +} + +function getValueTypeName (value) { + return native.Nil(value) ? '' : getTypeName(value.constructor) +} + +function getValue (value) { + if (native.Function(value)) return '' + if (native.String(value)) return JSON.stringify(value) + if (value && native.Object(value)) return '' + return value +} + +function captureStackTrace (e, t) { + if (Error.captureStackTrace) { + Error.captureStackTrace(e, t) + } +} + +function tfJSON (type) { + if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type) + if (native.Array(type)) return 'Array' + if (type && native.Object(type)) return 'Object' + + return type !== undefined ? type : '' +} + +function tfErrorString (type, value, valueTypeName) { + var valueJson = getValue(value) + + return 'Expected ' + tfJSON(type) + ', got' + + (valueTypeName !== '' ? ' ' + valueTypeName : '') + + (valueJson !== '' ? ' ' + valueJson : '') +} + +function TfTypeError (type, value, valueTypeName) { + valueTypeName = valueTypeName || getValueTypeName(value) + this.message = tfErrorString(type, value, valueTypeName) + + captureStackTrace(this, TfTypeError) + this.__type = type + this.__value = value + this.__valueTypeName = valueTypeName +} + +TfTypeError.prototype = Object.create(Error.prototype) +TfTypeError.prototype.constructor = TfTypeError + +function tfPropertyErrorString (type, label, name, value, valueTypeName) { + var description = '" of type ' + if (label === 'key') description = '" with key type ' + + return tfErrorString('property "' + tfJSON(name) + description + tfJSON(type), value, valueTypeName) +} + +function TfPropertyTypeError (type, property, label, value, valueTypeName) { + if (type) { + valueTypeName = valueTypeName || getValueTypeName(value) + this.message = tfPropertyErrorString(type, label, property, value, valueTypeName) + } else { + this.message = 'Unexpected property "' + property + '"' + } + + captureStackTrace(this, TfTypeError) + this.__label = label + this.__property = property + this.__type = type + this.__value = value + this.__valueTypeName = valueTypeName +} + +TfPropertyTypeError.prototype = Object.create(Error.prototype) +TfPropertyTypeError.prototype.constructor = TfTypeError + +function tfCustomError (expected, actual) { + return new TfTypeError(expected, {}, actual) +} + +function tfSubError (e, property, label) { + // sub child? + if (e instanceof TfPropertyTypeError) { + property = property + '.' + e.__property + + e = new TfPropertyTypeError( + e.__type, property, e.__label, e.__value, e.__valueTypeName + ) + + // child? + } else if (e instanceof TfTypeError) { + e = new TfPropertyTypeError( + e.__type, property, label, e.__value, e.__valueTypeName + ) + } + + captureStackTrace(e) + return e +} + +module.exports = { + TfTypeError: TfTypeError, + TfPropertyTypeError: TfPropertyTypeError, + tfCustomError: tfCustomError, + tfSubError: tfSubError, + tfJSON: tfJSON, + getValueTypeName: getValueTypeName +} + +},{"./native":84}],82:[function(require,module,exports){ +(function (Buffer){(function (){ +var NATIVE = require('./native') +var ERRORS = require('./errors') + +function _Buffer (value) { + return Buffer.isBuffer(value) +} + +function Hex (value) { + return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value) +} + +function _LengthN (type, length) { + var name = type.toJSON() + + function Length (value) { + if (!type(value)) return false + if (value.length === length) return true + + throw ERRORS.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')') + } + Length.toJSON = function () { return name } + + return Length +} + +var _ArrayN = _LengthN.bind(null, NATIVE.Array) +var _BufferN = _LengthN.bind(null, _Buffer) +var _HexN = _LengthN.bind(null, Hex) +var _StringN = _LengthN.bind(null, NATIVE.String) + +function Range (a, b, f) { + f = f || NATIVE.Number + function _range (value, strict) { + return f(value, strict) && (value > a) && (value < b) + } + _range.toJSON = function () { + return `${f.toJSON()} between [${a}, ${b}]` + } + return _range +} + +var INT53_MAX = Math.pow(2, 53) - 1 + +function Finite (value) { + return typeof value === 'number' && isFinite(value) +} +function Int8 (value) { return ((value << 24) >> 24) === value } +function Int16 (value) { return ((value << 16) >> 16) === value } +function Int32 (value) { return (value | 0) === value } +function Int53 (value) { + return typeof value === 'number' && + value >= -INT53_MAX && + value <= INT53_MAX && + Math.floor(value) === value +} +function UInt8 (value) { return (value & 0xff) === value } +function UInt16 (value) { return (value & 0xffff) === value } +function UInt32 (value) { return (value >>> 0) === value } +function UInt53 (value) { + return typeof value === 'number' && + value >= 0 && + value <= INT53_MAX && + Math.floor(value) === value +} + +var types = { + ArrayN: _ArrayN, + Buffer: _Buffer, + BufferN: _BufferN, + Finite: Finite, + Hex: Hex, + HexN: _HexN, + Int8: Int8, + Int16: Int16, + Int32: Int32, + Int53: Int53, + Range: Range, + StringN: _StringN, + UInt8: UInt8, + UInt16: UInt16, + UInt32: UInt32, + UInt53: UInt53 +} + +for (var typeName in types) { + types[typeName].toJSON = function (t) { + return t + }.bind(null, typeName) +} + +module.exports = types + +}).call(this)}).call(this,{"isBuffer":require("../../../../../usr/lib/node_modules/browserify/node_modules/is-buffer/index.js")}) +},{"../../../../../usr/lib/node_modules/browserify/node_modules/is-buffer/index.js":94,"./errors":81,"./native":84}],83:[function(require,module,exports){ +var ERRORS = require('./errors') +var NATIVE = require('./native') + +// short-hand +var tfJSON = ERRORS.tfJSON +var TfTypeError = ERRORS.TfTypeError +var TfPropertyTypeError = ERRORS.TfPropertyTypeError +var tfSubError = ERRORS.tfSubError +var getValueTypeName = ERRORS.getValueTypeName + +var TYPES = { + arrayOf: function arrayOf (type, options) { + type = compile(type) + options = options || {} + + function _arrayOf (array, strict) { + if (!NATIVE.Array(array)) return false + if (NATIVE.Nil(array)) return false + if (options.minLength !== undefined && array.length < options.minLength) return false + if (options.maxLength !== undefined && array.length > options.maxLength) return false + if (options.length !== undefined && array.length !== options.length) return false + + return array.every(function (value, i) { + try { + return typeforce(type, value, strict) + } catch (e) { + throw tfSubError(e, i) + } + }) + } + _arrayOf.toJSON = function () { + var str = '[' + tfJSON(type) + ']' + if (options.length !== undefined) { + str += '{' + options.length + '}' + } else if (options.minLength !== undefined || options.maxLength !== undefined) { + str += '{' + + (options.minLength === undefined ? 0 : options.minLength) + ',' + + (options.maxLength === undefined ? Infinity : options.maxLength) + '}' + } + return str + } + + return _arrayOf + }, + + maybe: function maybe (type) { + type = compile(type) + + function _maybe (value, strict) { + return NATIVE.Nil(value) || type(value, strict, maybe) + } + _maybe.toJSON = function () { return '?' + tfJSON(type) } + + return _maybe + }, + + map: function map (propertyType, propertyKeyType) { + propertyType = compile(propertyType) + if (propertyKeyType) propertyKeyType = compile(propertyKeyType) + + function _map (value, strict) { + if (!NATIVE.Object(value)) return false + if (NATIVE.Nil(value)) return false + + for (var propertyName in value) { + try { + if (propertyKeyType) { + typeforce(propertyKeyType, propertyName, strict) + } + } catch (e) { + throw tfSubError(e, propertyName, 'key') + } + + try { + var propertyValue = value[propertyName] + typeforce(propertyType, propertyValue, strict) + } catch (e) { + throw tfSubError(e, propertyName) + } + } + + return true + } + + if (propertyKeyType) { + _map.toJSON = function () { + return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}' + } + } else { + _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' } + } + + return _map + }, + + object: function object (uncompiled) { + var type = {} + + for (var typePropertyName in uncompiled) { + type[typePropertyName] = compile(uncompiled[typePropertyName]) + } + + function _object (value, strict) { + if (!NATIVE.Object(value)) return false + if (NATIVE.Nil(value)) return false + + var propertyName + + try { + for (propertyName in type) { + var propertyType = type[propertyName] + var propertyValue = value[propertyName] + + typeforce(propertyType, propertyValue, strict) + } + } catch (e) { + throw tfSubError(e, propertyName) + } + + if (strict) { + for (propertyName in value) { + if (type[propertyName]) continue + + throw new TfPropertyTypeError(undefined, propertyName) + } + } + + return true + } + _object.toJSON = function () { return tfJSON(type) } + + return _object + }, + + anyOf: function anyOf () { + var types = [].slice.call(arguments).map(compile) + + function _anyOf (value, strict) { + return types.some(function (type) { + try { + return typeforce(type, value, strict) + } catch (e) { + return false + } + }) + } + _anyOf.toJSON = function () { return types.map(tfJSON).join('|') } + + return _anyOf + }, + + allOf: function allOf () { + var types = [].slice.call(arguments).map(compile) + + function _allOf (value, strict) { + return types.every(function (type) { + try { + return typeforce(type, value, strict) + } catch (e) { + return false + } + }) + } + _allOf.toJSON = function () { return types.map(tfJSON).join(' & ') } + + return _allOf + }, + + quacksLike: function quacksLike (type) { + function _quacksLike (value) { + return type === getValueTypeName(value) + } + _quacksLike.toJSON = function () { return type } + + return _quacksLike + }, + + tuple: function tuple () { + var types = [].slice.call(arguments).map(compile) + + function _tuple (values, strict) { + if (NATIVE.Nil(values)) return false + if (NATIVE.Nil(values.length)) return false + if (strict && (values.length !== types.length)) return false + + return types.every(function (type, i) { + try { + return typeforce(type, values[i], strict) + } catch (e) { + throw tfSubError(e, i) + } + }) + } + _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' } + + return _tuple + }, + + value: function value (expected) { + function _value (actual) { + return actual === expected + } + _value.toJSON = function () { return expected } + + return _value + } +} + +// TODO: deprecate +TYPES.oneOf = TYPES.anyOf + +function compile (type) { + if (NATIVE.String(type)) { + if (type[0] === '?') return TYPES.maybe(type.slice(1)) + + return NATIVE[type] || TYPES.quacksLike(type) + } else if (type && NATIVE.Object(type)) { + if (NATIVE.Array(type)) { + if (type.length !== 1) throw new TypeError('Expected compile() parameter of type Array of length 1') + return TYPES.arrayOf(type[0]) + } + + return TYPES.object(type) + } else if (NATIVE.Function(type)) { + return type + } + + return TYPES.value(type) +} + +function typeforce (type, value, strict, surrogate) { + if (NATIVE.Function(type)) { + if (type(value, strict)) return true + + throw new TfTypeError(surrogate || type, value) + } + + // JIT + return typeforce(compile(type), value, strict) +} + +// assign types to typeforce function +for (var typeName in NATIVE) { + typeforce[typeName] = NATIVE[typeName] +} + +for (typeName in TYPES) { + typeforce[typeName] = TYPES[typeName] +} + +var EXTRA = require('./extra') +for (typeName in EXTRA) { + typeforce[typeName] = EXTRA[typeName] +} + +typeforce.compile = compile +typeforce.TfTypeError = TfTypeError +typeforce.TfPropertyTypeError = TfPropertyTypeError + +module.exports = typeforce + +},{"./errors":81,"./extra":82,"./native":84}],84:[function(require,module,exports){ +var types = { + Array: function (value) { return value !== null && value !== undefined && value.constructor === Array }, + Boolean: function (value) { return typeof value === 'boolean' }, + Function: function (value) { return typeof value === 'function' }, + Nil: function (value) { return value === undefined || value === null }, + Number: function (value) { return typeof value === 'number' }, + Object: function (value) { return typeof value === 'object' }, + String: function (value) { return typeof value === 'string' }, + '': function () { return true } +} + +// TODO: deprecate +types.Null = types.Nil + +for (var typeName in types) { + types[typeName].toJSON = function (t) { + return t + }.bind(null, typeName) +} + +module.exports = types + +},{}],85:[function(require,module,exports){ +'use strict' +var Buffer = require('safe-buffer').Buffer + +// Number.MAX_SAFE_INTEGER +var MAX_SAFE_INTEGER = 9007199254740991 + +function checkUInt53 (n) { + if (n < 0 || n > MAX_SAFE_INTEGER || n % 1 !== 0) throw new RangeError('value out of range') +} + +function encode (number, buffer, offset) { + checkUInt53(number) + + if (!buffer) buffer = Buffer.allocUnsafe(encodingLength(number)) + if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') + if (!offset) offset = 0 + + // 8 bit + if (number < 0xfd) { + buffer.writeUInt8(number, offset) + encode.bytes = 1 + + // 16 bit + } else if (number <= 0xffff) { + buffer.writeUInt8(0xfd, offset) + buffer.writeUInt16LE(number, offset + 1) + encode.bytes = 3 + + // 32 bit + } else if (number <= 0xffffffff) { + buffer.writeUInt8(0xfe, offset) + buffer.writeUInt32LE(number, offset + 1) + encode.bytes = 5 + + // 64 bit + } else { + buffer.writeUInt8(0xff, offset) + buffer.writeUInt32LE(number >>> 0, offset + 1) + buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5) + encode.bytes = 9 + } + + return buffer +} + +function decode (buffer, offset) { + if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') + if (!offset) offset = 0 + + var first = buffer.readUInt8(offset) + + // 8 bit + if (first < 0xfd) { + decode.bytes = 1 + return first + + // 16 bit + } else if (first === 0xfd) { + decode.bytes = 3 + return buffer.readUInt16LE(offset + 1) + + // 32 bit + } else if (first === 0xfe) { + decode.bytes = 5 + return buffer.readUInt32LE(offset + 1) + + // 64 bit + } else { + decode.bytes = 9 + var lo = buffer.readUInt32LE(offset + 1) + var hi = buffer.readUInt32LE(offset + 5) + var number = hi * 0x0100000000 + lo + checkUInt53(number) + + return number + } +} + +function encodingLength (number) { + checkUInt53(number) + + return ( + number < 0xfd ? 1 + : number <= 0xffff ? 3 + : number <= 0xffffffff ? 5 + : 9 + ) +} + +module.exports = { encode: encode, decode: decode, encodingLength: encodingLength } + +},{"safe-buffer":80}],"/":[function(require,module,exports){ +var bitcoin_js = require('bitcoinjs-lib') +bitcoin_js.bigi = require('bigi') +bitcoin_js.Buffer = require('safe-buffer').Buffer +bitcoin_js.tiny_secp256k1 = require('@bitcoinerlab/secp256k1') +module.exports = bitcoin_js + +},{"@bitcoinerlab/secp256k1":1,"bigi":15,"bitcoinjs-lib":53,"safe-buffer":80}],86:[function(require,module,exports){ +(function (global){(function (){ +'use strict'; + +var objectAssign = require('object-assign'); + +// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js +// original notice: + +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +function compare(a, b) { + if (a === b) { + return 0; + } + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; +} +function isBuffer(b) { + if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { + return global.Buffer.isBuffer(b); + } + return !!(b != null && b._isBuffer); +} + +// based on node assert, original notice: +// NB: The URL to the CommonJS spec is kept just for tradition. +// node-assert has evolved a lot since then, both in API and behavior. + +// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 +// +// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! +// +// Originally from narwhal.js (http://narwhaljs.org) +// Copyright (c) 2009 Thomas Robinson <280north.com> +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the 'Software'), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +var util = require('util/'); +var hasOwn = Object.prototype.hasOwnProperty; +var pSlice = Array.prototype.slice; +var functionsHaveNames = (function () { + return function foo() {}.name === 'foo'; +}()); +function pToString (obj) { + return Object.prototype.toString.call(obj); +} +function isView(arrbuf) { + if (isBuffer(arrbuf)) { + return false; + } + if (typeof global.ArrayBuffer !== 'function') { + return false; + } + if (typeof ArrayBuffer.isView === 'function') { + return ArrayBuffer.isView(arrbuf); + } + if (!arrbuf) { + return false; + } + if (arrbuf instanceof DataView) { + return true; + } + if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { + return true; + } + return false; +} +// 1. The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. + +var assert = module.exports = ok; + +// 2. The AssertionError is defined in assert. +// new assert.AssertionError({ message: message, +// actual: actual, +// expected: expected }) + +var regex = /\s*function\s+([^\(\s]*)\s*/; +// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js +function getName(func) { + if (!util.isFunction(func)) { + return; + } + if (functionsHaveNames) { + return func.name; + } + var str = func.toString(); + var match = str.match(regex); + return match && match[1]; +} +assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; + + // try to strip useless frames + var fn_name = getName(stackStartFunction); + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } + + this.stack = out; + } + } +}; + +// assert.AssertionError instanceof Error +util.inherits(assert.AssertionError, Error); + +function truncate(s, n) { + if (typeof s === 'string') { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } +} +function inspect(something) { + if (functionsHaveNames || !util.isFunction(something)) { + return util.inspect(something); + } + var rawname = getName(something); + var name = rawname ? ': ' + rawname : ''; + return '[Function' + name + ']'; +} +function getMessage(self) { + return truncate(inspect(self.actual), 128) + ' ' + + self.operator + ' ' + + truncate(inspect(self.expected), 128); +} + +// At present only the three keys mentioned above are used and +// understood by the spec. Implementations or sub modules can pass +// other keys to the AssertionError's constructor - they will be +// ignored. + +// 3. All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. + +function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); +} + +// EXTENSION! allows for well behaved errors defined elsewhere. +assert.fail = fail; + +// 4. Pure assertion tests whether a value is truthy, as determined +// by !!guard. +// assert.ok(guard, message_opt); +// This statement is equivalent to assert.equal(true, !!guard, +// message_opt);. To test strictly for the value true, use +// assert.strictEqual(true, guard, message_opt);. + +function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); +} +assert.ok = ok; + +// 5. The equality assertion tests shallow, coercive equality with +// ==. +// assert.equal(actual, expected, message_opt); + +assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); +}; + +// 6. The non-equality assertion tests for whether two objects are not equal +// with != assert.notEqual(actual, expected, message_opt); + +assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); + } +}; + +// 7. The equivalence assertion tests a deep equality relation. +// assert.deepEqual(actual, expected, message_opt); + +assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } +}; + +assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); + } +}; + +function _deepEqual(actual, expected, strict, memos) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + } else if (isBuffer(actual) && isBuffer(expected)) { + return compare(actual, expected) === 0; + + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); + + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; + + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if ((actual === null || typeof actual !== 'object') && + (expected === null || typeof expected !== 'object')) { + return strict ? actual === expected : actual == expected; + + // If both values are instances of typed arrays, wrap their underlying + // ArrayBuffers in a Buffer each to increase performance + // This optimization requires the arrays to have the same type as checked by + // Object.prototype.toString (aka pToString). Never perform binary + // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their + // bit patterns are not identical. + } else if (isView(actual) && isView(expected) && + pToString(actual) === pToString(expected) && + !(actual instanceof Float32Array || + actual instanceof Float64Array)) { + return compare(new Uint8Array(actual.buffer), + new Uint8Array(expected.buffer)) === 0; + + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else if (isBuffer(actual) !== isBuffer(expected)) { + return false; + } else { + memos = memos || {actual: [], expected: []}; + + var actualIndex = memos.actual.indexOf(actual); + if (actualIndex !== -1) { + if (actualIndex === memos.expected.indexOf(expected)) { + return true; + } + } + + memos.actual.push(actual); + memos.expected.push(expected); + + return objEquiv(actual, expected, strict, memos); + } +} + +function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +} + +function objEquiv(a, b, strict, actualVisitedObjects) { + if (a === null || a === undefined || b === null || b === undefined) + return false; + // if one is a primitive, the other must be same + if (util.isPrimitive(a) || util.isPrimitive(b)) + return a === b; + if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) + return false; + var aIsArgs = isArguments(a); + var bIsArgs = isArguments(b); + if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) + return false; + if (aIsArgs) { + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b, strict); + } + var ka = objectKeys(a); + var kb = objectKeys(b); + var key, i; + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length !== kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] !== kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) + return false; + } + return true; +} + +// 8. The non-equivalence assertion tests for any deep inequality. +// assert.notDeepEqual(actual, expected, message_opt); + +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } +}; + +assert.notDeepStrictEqual = notDeepStrictEqual; +function notDeepStrictEqual(actual, expected, message) { + if (_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); + } +} + + +// 9. The strict equality assertion tests strict equality, as determined by ===. +// assert.strictEqual(actual, expected, message_opt); + +assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } +}; + +// 10. The strict non-equality assertion tests for strict inequality, as +// determined by !==. assert.notStrictEqual(actual, expected, message_opt); + +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } +}; + +function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } + + try { + if (actual instanceof expected) { + return true; + } + } catch (e) { + // Ignore. The instanceof check doesn't work for arrow functions. + } + + if (Error.isPrototypeOf(expected)) { + return false; + } + + return expected.call({}, actual) === true; +} + +function _tryBlock(block) { + var error; + try { + block(); + } catch (e) { + error = e; + } + return error; +} + +function _throws(shouldThrow, block, expected, message) { + var actual; + + if (typeof block !== 'function') { + throw new TypeError('"block" argument must be a function'); + } + + if (typeof expected === 'string') { + message = expected; + expected = null; + } + + actual = _tryBlock(block); + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + var userProvidedMessage = typeof message === 'string'; + var isUnwantedException = !shouldThrow && util.isError(actual); + var isUnexpectedException = !shouldThrow && actual && !expected; + + if ((isUnwantedException && + userProvidedMessage && + expectedException(actual, expected)) || + isUnexpectedException) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } +} + +// 11. Expected to throw an error: +// assert.throws(block, Error_opt, message_opt); + +assert.throws = function(block, /*optional*/error, /*optional*/message) { + _throws(true, block, error, message); +}; + +// EXTENSION! This is annoying to write outside this module. +assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { + _throws(false, block, error, message); +}; + +assert.ifError = function(err) { if (err) throw err; }; + +// Expose a strict only variant of assert +function strict(value, message) { + if (!value) fail(value, true, message, '==', strict); +} +assert.strict = objectAssign(strict, assert, { + equal: assert.strictEqual, + deepEqual: assert.deepStrictEqual, + notEqual: assert.notStrictEqual, + notDeepEqual: assert.notDeepStrictEqual +}); +assert.strict.strict = assert.strict; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; +}; + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"object-assign":95,"util/":89}],87:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],88:[function(require,module,exports){ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} +},{}],89:[function(require,module,exports){ +(function (process,global){(function (){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = require('./support/isBuffer'); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":88,"_process":96,"inherits":87}],90:[function(require,module,exports){ +'use strict' + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + +},{}],91:[function(require,module,exports){ + +},{}],92:[function(require,module,exports){ +(function (Buffer){(function (){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 +if (typeof Symbol !== 'undefined' && Symbol.species != null && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayLike(value) + } + + if (value == null) { + throw TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + var valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + var b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from( + value[Symbol.toPrimitive]('string'), encodingOrOffset, length + ) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Buffer.prototype.__proto__ = Uint8Array.prototype +Buffer.__proto__ = Uint8Array + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) + + var actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (isInstance(buf, Uint8Array)) { + buf = Buffer.from(buf) + } + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + var len = string.length + var mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + var strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (var i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + var len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +}).call(this)}).call(this,require("buffer").Buffer) +},{"base64-js":90,"buffer":92,"ieee754":93}],93:[function(require,module,exports){ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}],94:[function(require,module,exports){ +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} + +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} + +},{}],95:[function(require,module,exports){ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],96:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}]},{},[])("/") +}); diff --git a/js/freewallet-desktop.js b/js/freewallet-desktop.js index 044dd87..02e2689 100644 --- a/js/freewallet-desktop.js +++ b/js/freewallet-desktop.js @@ -164,6 +164,11 @@ FW.ASSET_DIVISIBLE = {}; FW.ASSET_DIVISIBLE['BTC'] = true; FW.ASSET_DIVISIBLE['XCP'] = true; +//Init ecc lib for new bitcoin-lib version +bitcoinjs.initEccLib(bitcoinjs.tiny_secp256k1) +ECPairFactory = bitcoinjs.ecpairfactory +ECPair = ECPairFactory(bitcoinjs.tiny_secp256k1) + // Start loading the wallet $(document).ready(function(){ @@ -3258,8 +3263,8 @@ function signTransaction(network, source, destination, unsignedTx, callback){ var tx = bitcoinjs.Transaction.fromHex(unsignedTx), netName = (net=='testnet') ? 'testnet' : 'bitcoin', // bitcoinjs network = bitcoinjs.networks[netName], - txb = new bitcoinjs.TransactionBuilder(network), - keypair = bitcoinjs.ECPair.fromWIF(cwKey.getWIF(), network); + txb = new bitcoinjs.Psbt(network), + keypair = ECPair.fromWIF(cwKey.getWIF(), network); // Callback to modify transaction after we get a list of UTXOs back var utxoCb = function(data){ var utxoMap = {}; @@ -3276,13 +3281,30 @@ function signTransaction(network, source, destination, unsignedTx, callback){ // We get reversed tx hashes somehow after parsing var txhash = tx.ins[i].hash.reverse().toString('hex'); var prev = utxoMap[txhash]; - if(prev) - txb.addInput(tx.ins[i].hash.toString('hex'), prev.vout, null, input.output); + if(prev){ + var nextInput = null + if (sourceIsBech32){ + var witness = {script:input.output,value:prev.value} + nextInput = {hash:tx.ins[i].hash.toString('hex'), index:prev.vout, witnessUtxo:witness}; + } else { + var prev_tx_hex_buffer = bitcoinjs.Buffer.from(prev.prev_tx_hex,"hex") + nextInput = {hash:tx.ins[i].hash.toString('hex'), index:prev.vout, nonWitnessUtxo:prev_tx_hex_buffer}; + } + + if (nextInput){ + txb.addInput(nextInput); + } else { + console.log("Failed to sign input: script type not implemented") + return + } + } } // Handle adding outputs for(var i=0; i < tx.outs.length; i++){ var txout = tx.outs[i]; - txb.addOutput(txout.script, txout.value); + var outputScript = bitcoinjs.Buffer.from(txout.script.buffer.slice(txout.script.byteOffset, txout.script.byteLength + txout.script.byteOffset)); + + txb.addOutput({script:outputScript, value:txout.value}); } // var signedHex = txb.build().toHex(); // console.log('signedHex before=',signedHex); @@ -3296,7 +3318,7 @@ function signTransaction(network, source, destination, unsignedTx, callback){ redeemScript = // Future support for P2WSH }*/ // Math.floor is less than ideal in this scenario, we need to get the raw satoshi value in the utxo map - txb.sign(i, keypair, null, null, prev.value, redeemScript); + txb.signInput(i, keypair); } else { // Throw error that we couldn't sign tx console.log("Failed to sign transaction: " + "Incomplete SegWit inputs"); @@ -3306,14 +3328,15 @@ function signTransaction(network, source, destination, unsignedTx, callback){ var signedHex = false, error = false; try { - signedHex = txb.build().toHex(); + txb.finalizeAllInputs(); + signedHex = txb.extractTransaction().toHex(); } catch(e){ error = e; } cb(error, signedHex); } - // Get list of utxo - getUTXOs(net, source, utxoCb); + // Get list of utxo with tx hex + getUtxosWithRawTransactions(net, source, utxoCb); } else { // Sign using bitcore CWBitcore.signRawTransaction(unsignedTx, cwKey, cb); @@ -3368,6 +3391,54 @@ function getUTXOs(network, address, callback){ }); } +// Handle getting a raw transaction for a given tx hash +function getRawTransactions(network, hashList, callback){ + var txs = []; + var data = { + method: "getrawtransaction_batch", + params: { + txhash_list: hashList + }, + jsonrpc: "2.0", + id: 0 + }; + cpRequest(network, data, function(o){ + if(o && o.result){ + if(callback) + callback(o.result); + }; + }); +} + +//Handle getting utxos and their respectives prevout tx hex +function getUtxosWithRawTransactions(network, address, callback){ + var utxosCb = function(dataUtxos){ + //Adding hex data to the utxos + var rawTransactionCb = function (dataRawTransactions){ + for (var nextUtxoIndex in dataUtxos){ + var nextUtxo = dataUtxos[nextUtxoIndex] + nextUtxo["prev_tx_hex"] = dataRawTransactions[nextUtxo.txid] + } + + if (callback){ + callback(dataUtxos) + } + } + + //Preparing the list with all obtained utxos hashes + var hashList = [] + for (var nextUtxoIndex in dataUtxos){ + var nextUtxo = dataUtxos[nextUtxoIndex] + hashList.push(nextUtxo.txid) + } + + getRawTransactions(network, hashList, rawTransactionCb) + } + + //Obtaining utxos + getUTXOs(network, address, utxosCb) +} + // Handle signing a message and returning the signature function signMessage(network, source, message){ var net = (network=='testnet') ? 'testnet' : 'mainnet', diff --git a/package.json b/package.json index 43f753c..fd069f6 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,7 @@ "dependencies": { "@bassettsj/livestamp": "^2.0.0", "async": "^2.5.0", - "bitcoinjs-lib": "^4.0.2", + "bitcoinjs-lib": "^6.1.0", "bootstrap": "^3.3.7", "bootstrap-3-typeahead": "^4.0.2", "bootstrap-dialog": "^1.34.6", @@ -40,6 +40,8 @@ "jquery.qrcode": "^1.0.3", "jquery.rateit": "^1.1.1", "moment": "^2.18.1", - "numeraljs": "^1.5.6" + "numeraljs": "^1.5.6", + "nw-builder": "^4.2.7", + "tiny-secp256k1": "^2.2.2" } }