From 747cbd3b8d47cf124a9f121d5e8b7fc94521ecc1 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Fri, 27 Nov 2015 22:02:33 -0800 Subject: Implement send transaction function --- public/js/bitcoinjs-lib.min.js | 7 + public/js/buffer.js | 1567 ++++++++++++++++++++++++++++++++++++++++ public/js/calculator.coffee | 2 +- public/js/wallet.coffee | 85 ++- routes/users.js | 12 +- src/routes/users.coffee | 10 +- views/users/wallet.html | 53 +- 7 files changed, 1686 insertions(+), 50 deletions(-) create mode 100644 public/js/bitcoinjs-lib.min.js create mode 100644 public/js/buffer.js diff --git a/public/js/bitcoinjs-lib.min.js b/public/js/bitcoinjs-lib.min.js new file mode 100644 index 00000000..2be74a51 --- /dev/null +++ b/public/js/bitcoinjs-lib.min.js @@ -0,0 +1,7 @@ +!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{var g;g="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,g.bitcoin=f()}}(function(){return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o=0;){var v=x*this[i++]+w[j]+c;c=Math.floor(v/67108864),w[j++]=67108863&v}return c}function int2char(n){return BI_RM.charAt(n)}function intAt(s,i){var c=BI_RC[s.charCodeAt(i)];return null==c?-1:c}function bnpCopyTo(r){for(var i=this.t-1;i>=0;--i)r[i]=this[i];r.t=this.t,r.s=this.s}function bnpFromInt(x){this.t=1,this.s=0>x?-1:0,x>0?this[0]=x:-1>x?this[0]=x+DV:this.t=0}function nbv(i){var r=new BigInteger;return r.fromInt(i),r}function bnpFromString(s,b){var k,self=this;if(16==b)k=4;else if(8==b)k=3;else if(256==b)k=8;else if(2==b)k=1;else if(32==b)k=5;else{if(4!=b)return void self.fromRadix(s,b);k=2}self.t=0,self.s=0;for(var i=s.length,mi=!1,sh=0;--i>=0;){var x=8==k?255&s[i]:intAt(s,i);0>x?"-"==s.charAt(i)&&(mi=!0):(mi=!1,0==sh?self[self.t++]=x:sh+k>self.DB?(self[self.t-1]|=(x&(1<>self.DB-sh):self[self.t-1]|=x<=self.DB&&(sh-=self.DB))}8==k&&0!=(128&s[0])&&(self.s=-1,sh>0&&(self[self.t-1]|=(1<0&&this[this.t-1]==c;)--this.t}function bnToString(b){var self=this;if(self.s<0)return"-"+self.negate().toString(b);var k;if(16==b)k=4;else if(8==b)k=3;else if(2==b)k=1;else if(32==b)k=5;else{if(4!=b)return self.toRadix(b);k=2}var d,km=(1<0)for(p>p)>0&&(m=!0,r=int2char(d));i>=0;)k>p?(d=(self[i]&(1<>(p+=self.DB-k)):(d=self[i]>>(p-=k)&km,0>=p&&(p+=self.DB,--i)),d>0&&(m=!0),m&&(r+=int2char(d));return m?r:"0"}function bnNegate(){var r=new BigInteger;return BigInteger.ZERO.subTo(this,r),r}function bnAbs(){return this.s<0?this.negate():this}function bnCompareTo(a){var r=this.s-a.s;if(0!=r)return r;var i=this.t;if(r=i-a.t,0!=r)return this.s<0?-r:r;for(;--i>=0;)if(0!=(r=this[i]-a[i]))return r;return 0}function nbits(x){var t,r=1;return 0!=(t=x>>>16)&&(x=t,r+=16),0!=(t=x>>8)&&(x=t,r+=8),0!=(t=x>>4)&&(x=t,r+=4),0!=(t=x>>2)&&(x=t,r+=2),0!=(t=x>>1)&&(x=t,r+=1),r}function bnBitLength(){return this.t<=0?0:this.DB*(this.t-1)+nbits(this[this.t-1]^this.s&this.DM)}function bnByteLength(){return this.bitLength()>>3}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}function bnpDRShiftTo(n,r){for(var i=n;i=0;--i)r[i+ds+1]=self[i]>>cbs|c,c=(self[i]&bm)<=0;--i)r[i]=0;r[ds]=c,r.t=self.t+ds+1,r.s=self.s,r.clamp()}function bnpRShiftTo(n,r){var self=this;r.s=self.s;var ds=Math.floor(n/self.DB);if(ds>=self.t)return void(r.t=0);var bs=n%self.DB,cbs=self.DB-bs,bm=(1<>bs;for(var i=ds+1;i>bs;bs>0&&(r[self.t-ds-1]|=(self.s&bm)<i;)c+=self[i]-a[i],r[i++]=c&self.DM,c>>=self.DB;if(a.t>=self.DB;c+=self.s}else{for(c+=self.s;i>=self.DB;c-=a.s}r.s=0>c?-1:0,-1>c?r[i++]=self.DV+c:c>0&&(r[i++]=c),r.t=i,r.clamp()}function bnpMultiplyTo(a,r){var x=this.abs(),y=a.abs(),i=x.t;for(r.t=i+y.t;--i>=0;)r[i]=0;for(i=0;i=0;)r[i]=0;for(i=0;i=x.DV&&(r[i+x.t]-=x.DV,r[i+x.t+1]=1)}r.t>0&&(r[r.t-1]+=x.am(i,x[i],r,2*i,0,1)),r.s=0,r.clamp()}function bnpDivRemTo(m,q,r){var self=this,pm=m.abs();if(!(pm.t<=0)){var pt=self.abs();if(pt.t0?(pm.lShiftTo(nsh,y),pt.lShiftTo(nsh,r)):(pm.copyTo(y),pt.copyTo(r));var ys=y.t,y0=y[ys-1];if(0!=y0){var yt=y0*(1<1?y[ys-2]>>self.F2:0),d1=self.FV/yt,d2=(1<=0&&(r[r.t++]=1,r.subTo(t,r)),BigInteger.ONE.dlShiftTo(ys,t),t.subTo(y,y);y.t=0;){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))0&&r.rShiftTo(nsh,r),0>ts&&BigInteger.ZERO.subTo(r,r)}}}function bnMod(a){var r=new BigInteger;return this.abs().divRemTo(a,null,r),this.s<0&&r.compareTo(BigInteger.ZERO)>0&&a.subTo(r,r),r}function Classic(m){this.m=m}function cConvert(x){return x.s<0||x.compareTo(this.m)>=0?x.mod(this.m):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)}function bnpInvDigit(){if(this.t<1)return 0;var x=this[0];if(0==(1&x))return 0;var y=3&x;return y=y*(2-(15&x)*y)&15,y=y*(2-(255&x)*y)&255,y=y*(2-((65535&x)*y&65535))&65535,y=y*(2-x*y%this.DV)%this.DV,y>0?this.DV-y:-y}function Montgomery(m){this.m=m,this.mp=m.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(r,r),r}function montRevert(x){var r=new BigInteger;return x.copyTo(r),this.reduce(r),r}function montReduce(x){for(;x.t<=this.mt2;)x[x.t++]=0;for(var i=0;i>15)*this.mpl&this.um)<<15)&x.DM;for(j=i+this.m.t,x[j]+=this.m.am(0,u0,x,i,0,this.m.t);x[j]>=x.DV;)x[j]-=x.DV,x[++j]++}x.clamp(),x.drShiftTo(this.m.t,x),x.compareTo(this.m)>=0&&x.subTo(this.m,x)}function montSqrTo(x,r){x.squareTo(r),this.reduce(r)}function montMulTo(x,y,r){x.multiplyTo(y,r),this.reduce(r)}function bnpIsEven(){return 0==(this.t>0?1&this[0]:this.s)}function bnpExp(e,z){if(e>4294967295||1>e)return BigInteger.ONE;var r=new BigInteger,r2=new BigInteger,g=z.convert(this),i=nbits(e)-1;for(g.copyTo(r);--i>=0;)if(z.sqrTo(r,r2),(e&1<0)z.mulTo(r2,g,r);else{var t=r;r=r2,r2=t}return z.revert(r)}function bnModPowInt(e,m){var z;return z=256>e||m.isEven()?new Classic(m):new Montgomery(m),this.exp(e,z)}function bnClone(){var r=new BigInteger;return this.copyTo(r),r}function bnIntValue(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<>24}function bnShortValue(){return 0==this.t?this.s:this[0]<<16>>16}function bnpChunkSize(r){return Math.floor(Math.LN2*this.DB/Math.log(r))}function bnSigNum(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1}function bnpToRadix(b){if(null==b&&(b=10),0==this.signum()||2>b||b>36)return"0";var cs=this.chunkSize(b),a=Math.pow(b,cs),d=nbv(a),y=new BigInteger,z=new BigInteger,r="";for(this.divRemTo(d,y,z);y.signum()>0;)r=(a+z.intValue()).toString(b).substr(1)+r,y.divRemTo(d,y,z);return z.intValue().toString(b)+r}function bnpFromRadix(s,b){var self=this;self.fromInt(0),null==b&&(b=10);for(var cs=self.chunkSize(b),d=Math.pow(b,cs),mi=!1,j=0,w=0,i=0;ix?"-"==s.charAt(i)&&0==self.signum()&&(mi=!0):(w=b*w+x,++j>=cs&&(self.dMultiply(d),self.dAddOffset(w,0),j=0,w=0))}j>0&&(self.dMultiply(Math.pow(b,j)),self.dAddOffset(w,0)),mi&&BigInteger.ZERO.subTo(self,self)}function bnpFromNumber(a,b,c){var self=this;if("number"==typeof b)if(2>a)self.fromInt(1);else for(self.fromNumber(a,c),self.testBit(a-1)||self.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,self),self.isEven()&&self.dAddOffset(1,0);!self.isProbablePrime(b);)self.dAddOffset(2,0),self.bitLength()>a&&self.subTo(BigInteger.ONE.shiftLeft(a-1),self);else{var x=new Array,t=7&a;x.length=(a>>3)+1,b.nextBytes(x),t>0?x[0]&=(1<0)for(p>p)!=(self.s&self.DM)>>p&&(r[k++]=d|self.s<=0;)8>p?(d=(self[i]&(1<>(p+=self.DB-8)):(d=self[i]>>(p-=8)&255,0>=p&&(p+=self.DB,--i)),0!=(128&d)&&(d|=-256),0===k&&(128&self.s)!=(128&d)&&++k,(k>0||d!=self.s)&&(r[k++]=d);return r}function bnEquals(a){return 0==this.compareTo(a)}function bnMin(a){return this.compareTo(a)<0?this:a}function bnMax(a){return this.compareTo(a)>0?this:a}function bnpBitwiseTo(a,op,r){var i,f,self=this,m=Math.min(a.t,self.t);for(i=0;m>i;++i)r[i]=op(self[i],a[i]);if(a.tn?this.rShiftTo(-n,r):this.lShiftTo(n,r),r}function bnShiftRight(n){var r=new BigInteger;return 0>n?this.lShiftTo(-n,r):this.rShiftTo(n,r),r}function lbit(x){if(0==x)return-1;var r=0;return 0==(65535&x)&&(x>>=16,r+=16),0==(255&x)&&(x>>=8,r+=8),0==(15&x)&&(x>>=4,r+=4),0==(3&x)&&(x>>=2,r+=2),0==(1&x)&&++r,r}function bnGetLowestSetBit(){for(var i=0;i=this.t?0!=this.s:0!=(this[j]&1<i;)c+=self[i]+a[i],r[i++]=c&self.DM,c>>=self.DB;if(a.t>=self.DB;c+=self.s}else{for(c+=self.s;i>=self.DB;c+=a.s}r.s=0>c?-1:0,c>0?r[i++]=c:-1>c&&(r[i++]=self.DV+c),r.t=i,r.clamp()}function bnAdd(a){var r=new BigInteger;return this.addTo(a,r),r}function bnSubtract(a){var r=new BigInteger;return this.subTo(a,r),r}function bnMultiply(a){var r=new BigInteger;return this.multiplyTo(a,r),r}function bnSquare(){var r=new BigInteger;return this.squareTo(r),r}function bnDivide(a){var r=new BigInteger;return this.divRemTo(a,r,null),r}function bnRemainder(a){var r=new BigInteger;return this.divRemTo(a,null,r),r}function bnDivideAndRemainder(a){var q=new BigInteger,r=new BigInteger;return this.divRemTo(a,q,r),new Array(q,r)}function bnpDMultiply(n){this[this.t]=this.am(0,n-1,this,0,0,this.t),++this.t,this.clamp()}function bnpDAddOffset(n,w){if(0!=n){for(;this.t<=w;)this[this.t++]=0;for(this[w]+=n;this[w]>=this.DV;)this[w]-=this.DV,++w>=this.t&&(this[this.t++]=0),++this[w]}}function NullExp(){}function nNop(x){return x}function nMulTo(x,y,r){x.multiplyTo(y,r)}function nSqrTo(x,r){x.squareTo(r)}function bnPow(e){return this.exp(e,new NullExp)}function bnpMultiplyLowerTo(a,n,r){var i=Math.min(this.t+a.t,n);for(r.s=0,r.t=i;i>0;)r[--i]=0;var j;for(j=r.t-this.t;j>i;++i)r[i+this.t]=this.am(0,a[i],r,i,0,this.t);for(j=Math.min(a.t,n);j>i;++i)this.am(0,a[i],r,i,0,n-i);r.clamp()}function bnpMultiplyUpperTo(a,n,r){--n;var i=r.t=this.t+a.t-n;for(r.s=0;--i>=0;)r[i]=0;for(i=Math.max(n-this.t,0);i2*this.m.t)return x.mod(this.m);if(x.compareTo(this.m)<0)return x;var r=new BigInteger;return x.copyTo(r),this.reduce(r),r}function barrettRevert(x){return x}function barrettReduce(x){var self=this;for(x.drShiftTo(self.m.t-1,self.r2),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);x.compareTo(self.r2)<0;)x.dAddOffset(1,self.m.t+1);for(x.subTo(self.r2,x);x.compareTo(self.m)>=0;)x.subTo(self.m,x)}function barrettSqrTo(x,r){x.squareTo(r),this.reduce(r)}function barrettMulTo(x,y,r){x.multiplyTo(y,r),this.reduce(r)}function bnModPow(e,m){var k,z,i=e.bitLength(),r=nbv(1);if(0>=i)return r;k=18>i?1:48>i?3:144>i?4:768>i?5:6,z=8>i?new Classic(m):m.isEven()?new Barrett(m):new Montgomery(m);var g=new Array,n=3,k1=k-1,km=(1<1){var g2=new BigInteger;for(z.sqrTo(g[1],g2);km>=n;)g[n]=new BigInteger,z.mulTo(g2,g[n-2],g[n]),n+=2}var w,t,j=e.t-1,is1=!0,r2=new BigInteger;for(i=nbits(e[j])-1;j>=0;){for(i>=k1?w=e[j]>>i-k1&km:(w=(e[j]&(1<0&&(w|=e[j-1]>>this.DB+i-k1)),n=k;0==(1&w);)w>>=1,--n;if((i-=n)<0&&(i+=this.DB,--j),is1)g[w].copyTo(r),is1=!1;else{for(;n>1;)z.sqrTo(r,r2),z.sqrTo(r2,r),n-=2;n>0?z.sqrTo(r,r2):(t=r,r=r2,r2=t),z.mulTo(r2,g[w],r)}for(;j>=0&&0==(e[j]&1<g)return x;for(g>i&&(g=i),g>0&&(x.rShiftTo(g,x),y.rShiftTo(g,y));x.signum()>0;)(i=x.getLowestSetBit())>0&&x.rShiftTo(i,x),(i=y.getLowestSetBit())>0&&y.rShiftTo(i,y),x.compareTo(y)>=0?(x.subTo(y,x),x.rShiftTo(1,x)):(y.subTo(x,y),y.rShiftTo(1,y));return g>0&&y.lShiftTo(g,y),y}function bnpModInt(n){if(0>=n)return 0;var d=this.DV%n,r=this.s<0?n-1:0;if(this.t>0)if(0==d)r=this[0]%n;else for(var i=this.t-1;i>=0;--i)r=(d*r+this[i])%n;return r}function bnModInverse(m){var ac=m.isEven();if(0===this.signum())throw new Error("division by zero");if(this.isEven()&&ac||0==m.signum())return BigInteger.ZERO;for(var u=m.clone(),v=this.clone(),a=nbv(1),b=nbv(0),c=nbv(0),d=nbv(1);0!=u.signum();){for(;u.isEven();)u.rShiftTo(1,u),ac?(a.isEven()&&b.isEven()||(a.addTo(this,a),b.subTo(m,b)),a.rShiftTo(1,a)):b.isEven()||b.subTo(m,b),b.rShiftTo(1,b);for(;v.isEven();)v.rShiftTo(1,v),ac?(c.isEven()&&d.isEven()||(c.addTo(this,c),d.subTo(m,d)),c.rShiftTo(1,c)):d.isEven()||d.subTo(m,d),d.rShiftTo(1,d);u.compareTo(v)>=0?(u.subTo(v,u),ac&&a.subTo(c,a),b.subTo(d,b)):(v.subTo(u,v),ac&&c.subTo(a,c),d.subTo(b,d))}return 0!=v.compareTo(BigInteger.ONE)?BigInteger.ZERO:d.compareTo(m)>=0?d.subtract(m):d.signum()<0?(d.addTo(m,d),d.signum()<0?d.add(m):d):d}function bnIsProbablePrime(t){var i,x=this.abs();if(1==x.t&&x[0]<=lowprimes[lowprimes.length-1]){for(i=0;im;)m*=lowprimes[j++];for(m=x.modInt(m);j>i;)if(m%lowprimes[i++]==0)return!1}return x.millerRabin(t)}function bnpMillerRabin(t){var n1=this.subtract(BigInteger.ONE),k=n1.getLowestSetBit();if(0>=k)return!1;var r=n1.shiftRight(k);t=t+1>>1,t>lowprimes.length&&(t=lowprimes.length);for(var j,a=new BigInteger(null),bases=[],i=0;t>i;++i){for(;j=lowprimes[Math.floor(Math.random()*lowprimes.length)],-1!=bases.indexOf(j););bases.push(j),a.fromInt(j);var y=a.modPow(r,this);if(0!=y.compareTo(BigInteger.ONE)&&0!=y.compareTo(n1)){for(var j=1;j++=vv;++vv)BI_RC[rr++]=vv;for(rr="a".charCodeAt(0),vv=10;36>vv;++vv)BI_RC[rr++]=vv;for(rr="A".charCodeAt(0),vv=10;36>vv;++vv)BI_RC[rr++]=vv;Classic.prototype.convert=cConvert,Classic.prototype.revert=cRevert,Classic.prototype.reduce=cReduce,Classic.prototype.mulTo=cMulTo,Classic.prototype.sqrTo=cSqrTo,Montgomery.prototype.convert=montConvert,Montgomery.prototype.revert=montRevert,Montgomery.prototype.reduce=montReduce,Montgomery.prototype.mulTo=montMulTo,Montgomery.prototype.sqrTo=montSqrTo,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,proto.toString=bnToString,proto.negate=bnNegate,proto.abs=bnAbs,proto.compareTo=bnCompareTo,proto.bitLength=bnBitLength,proto.byteLength=bnByteLength,proto.mod=bnMod,proto.modPowInt=bnModPowInt,NullExp.prototype.convert=nNop,NullExp.prototype.revert=nNop,NullExp.prototype.mulTo=nMulTo,NullExp.prototype.sqrTo=nSqrTo,Barrett.prototype.convert=barrettConvert,Barrett.prototype.revert=barrettRevert,Barrett.prototype.reduce=barrettReduce,Barrett.prototype.mulTo=barrettMulTo,Barrett.prototype.sqrTo=barrettSqrTo;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],lplim=(1<<26)/lowprimes[lowprimes.length-1];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,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,proto.square=bnSquare,BigInteger.ZERO=nbv(0),BigInteger.ONE=nbv(1),BigInteger.valueOf=nbv,module.exports=BigInteger},{"../package.json":4}],2:[function(require,module,exports){(function(Buffer){var assert=require("assert"),BigInteger=require("./bigi");BigInteger.fromByteArrayUnsigned=function(byteArray){return new BigInteger(128&byteArray[0]?[0].concat(byteArray):byteArray)},BigInteger.prototype.toByteArrayUnsigned=function(){var byteArray=this.toByteArray();return 0===byteArray[0]?byteArray.slice(1):byteArray},BigInteger.fromDERInteger=function(byteArray){return new BigInteger(byteArray)},BigInteger.prototype.toDERInteger=BigInteger.prototype.toByteArray,BigInteger.fromBuffer=function(buffer){if(128&buffer[0]){var byteArray=Array.prototype.slice.call(buffer);return new BigInteger([0].concat(byteArray))}return new BigInteger(buffer)},BigInteger.fromHex=function(hex){return""===hex?BigInteger.ZERO:(assert.equal(hex,hex.match(/^[A-Fa-f0-9]+/),"Invalid hex string"),assert.equal(hex.length%2,0,"Incomplete hex"),new BigInteger(hex,16))},BigInteger.prototype.toBuffer=function(size){for(var byteArray=this.toByteArrayUnsigned(),zeros=[],padding=size-byteArray.length;zeros.length72)return!1;if(48!==buffer[0])return!1;if(buffer[1]!==buffer.length-2)return!1;if(2!==buffer[2])return!1;var lenR=buffer[3];if(0===lenR)return!1;if(5+lenR>=buffer.length)return!1;if(2!==buffer[4+lenR])return!1;var lenS=buffer[5+lenR];return 0===lenS?!1:6+lenR+lenS!==buffer.length?!1:128&buffer[4]?!1:lenR>1&&0===buffer[4]&&!(128&buffer[5])?!1:128&buffer[lenR+6]?!1:lenS>1&&0===buffer[lenR+6]&&!(128&buffer[lenR+7])?!1:!0}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(48!==buffer[0])throw new Error("Expected DER sequence");if(buffer[1]!==buffer.length-2)throw new Error("DER sequence length is invalid");if(2!==buffer[2])throw new Error("Expected DER integer");var lenR=buffer[3];if(0===lenR)throw new Error("R length is zero");if(5+lenR>=buffer.length)throw new Error("R length is too long");if(2!==buffer[4+lenR])throw new Error("Expected DER integer (2)");var lenS=buffer[5+lenR];if(0===lenS)throw new Error("S length is zero");if(6+lenR+lenS!==buffer.length)throw new Error("S length is invalid");if(128&buffer[4])throw new Error("R value is negative");if(lenR>1&&0===buffer[4]&&!(128&buffer[5]))throw new Error("R value excessively padded");if(128&buffer[lenR+6])throw new Error("S value is negative");if(lenS>1&&0===buffer[lenR+6]&&!(128&buffer[lenR+7]))throw new Error("S value excessively padded");return{r:buffer.slice(4,4+lenR),s:buffer.slice(6+lenR)}}function encode(r,s){var lenR=r.length,lenS=s.length;if(0===lenR)throw new Error("R length is zero");if(0===lenS)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(128&r[0])throw new Error("R value is negative");if(128&s[0])throw new Error("S value is negative");if(lenR>1&&0===r[0]&&!(128&r[1]))throw new Error("R value excessively padded");if(lenS>1&&0===s[0]&&!(128&s[1]))throw new Error("S value excessively padded");var signature=new Buffer(6+lenR+lenS);return signature[0]=48,signature[1]=signature.length-2,signature[2]=2,signature[3]=r.length,r.copy(signature,4),signature[4+lenR]=2,signature[5+lenR]=s.length,s.copy(signature,6+lenR),signature}module.exports={check:check,decode:decode,encode:encode}}).call(this,require("buffer").Buffer)},{buffer:52}],6:[function(require,module,exports){function encode(buffer){if(0===buffer.length)return"";var i,j,digits=[0];for(i=0;i=0;i--)stringOutput+=ALPHABET[digits[i]];return stringOutput}function decode(string){if(0===string.length)return[];var i,j,bytes=[0];for(i=0;i>8,bytes[j]&=255;for(;carry;)bytes.push(255&carry),carry>>=8}for(i=0;"1"===string[i]&&ii;++i,--j)buffer[i]=a[j];return buffer}}).call(this,require("buffer").Buffer)},{buffer:52}],10:[function(require,module,exports){(function(Buffer){"use strict";function HashNoConstructor(hash){Base.call(this,"digest"),this._hash=hash,this.buffers=[]}function Hash(hash){Base.call(this,"digest"),this._hash=hash}var inherits=require("inherits"),md5=require("./md5"),rmd160=require("ripemd160"),sha=require("sha.js"),Base=require("cipher-base");inherits(HashNoConstructor,Base),HashNoConstructor.prototype._update=function(data){this.buffers.push(data)},HashNoConstructor.prototype._final=function(){var buf=Buffer.concat(this.buffers),r=this._hash(buf);return this.buffers=null,r},inherits(Hash,Base),Hash.prototype._update=function(data){this._hash.update(data)},Hash.prototype._final=function(){return this._hash.digest()},module.exports=function(alg){return alg=alg.toLowerCase(),"md5"===alg?new HashNoConstructor(md5):"rmd160"===alg||"ripemd160"===alg?new HashNoConstructor(rmd160):new Hash(sha(alg))}}).call(this,require("buffer").Buffer)},{"./md5":12,buffer:52,"cipher-base":13,inherits:14,ripemd160:15,"sha.js":17}],11:[function(require,module,exports){(function(Buffer){"use strict";function toArray(buf,bigEndian){if(buf.length%intSize!==0){var len=buf.length+(intSize-buf.length%intSize);buf=Buffer.concat([buf,zeroBuffer],len)}for(var arr=[],fn=bigEndian?buf.readInt32BE:buf.readInt32LE,i=0;i>5]|=128<>>9<<4)+14]=len;for(var a=1732584193,b=-271733879,c=-1732584194,d=271733878,i=0;i>16)+(y>>16)+(lsw>>16);return msw<<16|65535&lsw}function bit_rol(num,cnt){return num<>>32-cnt}var helpers=require("./helpers");module.exports=function(buf){return helpers.hash(buf,core_md5,16)}},{"./helpers":11}],13:[function(require,module,exports){(function(Buffer){function CipherBase(hashMode){Transform.call(this),this.hashMode="string"==typeof hashMode,this.hashMode?this[hashMode]=this._finalOrDigest:this["final"]=this._finalOrDigest,this._decoder=null,this._encoding=null}var Transform=require("stream").Transform,inherits=require("inherits"),StringDecoder=require("string_decoder").StringDecoder;module.exports=CipherBase,inherits(CipherBase,Transform),CipherBase.prototype.update=function(data,inputEnc,outputEnc){"string"==typeof data&&(data=new Buffer(data,inputEnc));var outData=this._update(data);return this.hashMode?this:(outputEnc&&(outData=this._toString(outData,outputEnc)),outData)},CipherBase.prototype.setAutoPadding=function(){},CipherBase.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")},CipherBase.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")},CipherBase.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")},CipherBase.prototype._transform=function(data,_,next){var err;try{this.hashMode?this._update(data):this.push(this._update(data))}catch(e){err=e}finally{next(err)}},CipherBase.prototype._flush=function(done){var err;try{this.push(this._final())}catch(e){err=e}finally{done(err)}},CipherBase.prototype._finalOrDigest=function(outputEnc){var outData=this._final()||new Buffer("");return outputEnc&&(outData=this._toString(outData,outputEnc,!0)),outData},CipherBase.prototype._toString=function(value,enc,final){if(this._decoder||(this._decoder=new StringDecoder(enc),this._encoding=enc),this._encoding!==enc)throw new Error("can't switch encodings");var out=this._decoder.write(value);return final&&(out+=this._decoder.end()),out}}).call(this,require("buffer").Buffer)},{buffer:52,inherits:14,stream:74,string_decoder:75}],14:[function(require,module,exports){"function"==typeof Object.create?module.exports=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:module.exports=function(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},{}],15:[function(require,module,exports){(function(Buffer){function bytesToWords(bytes){for(var words=[],i=0,b=0;i>>5]|=bytes[i]<<24-b%32;return words}function wordsToBytes(words){for(var bytes=[],b=0;b<32*words.length;b+=8)bytes.push(words[b>>>5]>>>24-b%32&255);return bytes}function processBlock(H,M,offset){for(var i=0;16>i;i++){var offset_i=offset+i,M_offset_i=M[offset_i];M[offset_i]=16711935&(M_offset_i<<8|M_offset_i>>>24)|4278255360&(M_offset_i<<24|M_offset_i>>>8)}var al,bl,cl,dl,el,ar,br,cr,dr,er;ar=al=H[0],br=bl=H[1],cr=cl=H[2],dr=dl=H[3],er=el=H[4];var t;for(i=0;80>i;i+=1)t=al+M[offset+zl[i]]|0,t+=16>i?f1(bl,cl,dl)+hl[0]:32>i?f2(bl,cl,dl)+hl[1]:48>i?f3(bl,cl,dl)+hl[2]:64>i?f4(bl,cl,dl)+hl[3]:f5(bl,cl,dl)+hl[4],t=0|t,t=rotl(t,sl[i]),t=t+el|0,al=el,el=dl,dl=rotl(cl,10),cl=bl,bl=t,t=ar+M[offset+zr[i]]|0,t+=16>i?f5(br,cr,dr)+hr[0]:32>i?f4(br,cr,dr)+hr[1]:48>i?f3(br,cr,dr)+hr[2]:64>i?f2(br,cr,dr)+hr[3]:f1(br,cr,dr)+hr[4],t=0|t,t=rotl(t,sr[i]),t=t+er|0,ar=er,er=dr,dr=rotl(cr,10),cr=br,br=t;t=H[1]+cl+dr|0,H[1]=H[2]+dl+er|0,H[2]=H[3]+el+ar|0,H[3]=H[4]+al+br|0,H[4]=H[0]+bl+cr|0,H[0]=t}function f1(x,y,z){return x^y^z}function f2(x,y,z){return x&y|~x&z}function f3(x,y,z){return(x|~y)^z}function f4(x,y,z){return x&z|y&~z}function f5(x,y,z){return x^(y|~z)}function rotl(x,n){return x<>>32-n}function ripemd160(message){var H=[1732584193,4023233417,2562383102,271733878,3285377520];"string"==typeof message&&(message=new Buffer(message,"utf8"));var m=bytesToWords(message),nBitsLeft=8*message.length,nBitsTotal=8*message.length;m[nBitsLeft>>>5]|=128<<24-nBitsLeft%32,m[(nBitsLeft+64>>>9<<4)+14]=16711935&(nBitsTotal<<8|nBitsTotal>>>24)|4278255360&(nBitsTotal<<24|nBitsTotal>>>8);for(var i=0;ii;i++){var H_i=H[i];H[i]=16711935&(H_i<<8|H_i>>>24)|4278255360&(H_i<<24|H_i>>>8)}var digestbytes=wordsToBytes(H);return new Buffer(digestbytes)}var zl=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],zr=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],sl=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],sr=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],hl=[0,1518500249,1859775393,2400959708,2840853838],hr=[1352829926,1548603684,1836072691,2053994217,0];module.exports=ripemd160}).call(this,require("buffer").Buffer)},{buffer:52}],16:[function(require,module,exports){(function(Buffer){function Hash(blockSize,finalSize){this._block=new Buffer(blockSize),this._finalSize=finalSize,this._blockSize=blockSize,this._len=0,this._s=0}Hash.prototype.update=function(data,enc){"string"==typeof data&&(enc=enc||"utf8",data=new Buffer(data,enc));for(var l=this._len+=data.length,s=this._s||0,f=0,buffer=this._block;l>s;){for(var t=Math.min(data.length,f+this._blockSize-s%this._blockSize),ch=t-f,i=0;ch>i;i++)buffer[s%this._blockSize+i]=data[i+f];s+=ch,f+=ch,s%this._blockSize===0&&this._update(buffer)}return this._s=s,this},Hash.prototype.digest=function(enc){var l=8*this._len;this._block[this._len%this._blockSize]=128,this._block.fill(0,this._len%this._blockSize+1),l%(8*this._blockSize)>=8*this._finalSize&&(this._update(this._block),this._block.fill(0)),this._block.writeInt32BE(l,this._blockSize-4);var hash=this._update(this._block)||this._hash();return enc?hash.toString(enc):hash},Hash.prototype._update=function(){throw new Error("_update must be implemented by subclass")},module.exports=Hash}).call(this,require("buffer").Buffer)},{buffer:52}],17:[function(require,module,exports){var exports=module.exports=function(algorithm){algorithm=algorithm.toLowerCase();var Algorithm=exports[algorithm];if(!Algorithm)throw new Error(algorithm+" is not supported (we accept pull requests)");return new Algorithm};exports.sha=require("./sha"),exports.sha1=require("./sha1"),exports.sha224=require("./sha224"),exports.sha256=require("./sha256"),exports.sha384=require("./sha384"),exports.sha512=require("./sha512")},{"./sha":18,"./sha1":19,"./sha224":20,"./sha256":21,"./sha384":22,"./sha512":23}],18:[function(require,module,exports){(function(Buffer){function Sha(){this.init(),this._w=W,Hash.call(this,64,56)}function rol(num,cnt){return num<>>32-cnt}var inherits=require("inherits"),Hash=require("./hash"),W=new Array(80);inherits(Sha,Hash),Sha.prototype.init=function(){return this._a=1732584193,this._b=-271733879,this._c=-1732584194,this._d=271733878,this._e=-1009589776,this},Sha.prototype._update=function(M){function calcW(){return W[j-3]^W[j-8]^W[j-14]^W[j-16]}function loop(w,f){W[j]=w;var t=rol(a,5)+f+e+w+k;e=d,d=c,c=rol(b,30),b=a,a=t,j++}var k,W=this._w,a=this._a,b=this._b,c=this._c,d=this._d,e=this._e,j=0;for(k=1518500249;16>j;)loop(M.readInt32BE(4*j),b&c|~b&d);for(;20>j;)loop(calcW(),b&c|~b&d);for(k=1859775393;40>j;)loop(calcW(),b^c^d);for(k=-1894007588;60>j;)loop(calcW(),b&c|b&d|c&d);for(k=-899497514;80>j;)loop(calcW(),b^c^d);this._a=a+this._a|0,this._b=b+this._b|0,this._c=c+this._c|0,this._d=d+this._d|0,this._e=e+this._e|0},Sha.prototype._hash=function(){var H=new Buffer(20);return H.writeInt32BE(0|this._a,0),H.writeInt32BE(0|this._b,4),H.writeInt32BE(0|this._c,8),H.writeInt32BE(0|this._d,12),H.writeInt32BE(0|this._e,16),H},module.exports=Sha}).call(this,require("buffer").Buffer)},{"./hash":16,buffer:52,inherits:14}],19:[function(require,module,exports){(function(Buffer){function Sha1(){this.init(),this._w=W,Hash.call(this,64,56)}function rol(num,cnt){return num<>>32-cnt}var inherits=require("inherits"),Hash=require("./hash"),W=new Array(80);inherits(Sha1,Hash),Sha1.prototype.init=function(){return this._a=1732584193,this._b=-271733879,this._c=-1732584194,this._d=271733878,this._e=-1009589776,this},Sha1.prototype._update=function(M){function calcW(){return rol(W[j-3]^W[j-8]^W[j-14]^W[j-16],1)}function loop(w,f){W[j]=w;var t=rol(a,5)+f+e+w+k;e=d,d=c,c=rol(b,30),b=a,a=t,j++}var k,W=this._w,a=this._a,b=this._b,c=this._c,d=this._d,e=this._e,j=0;for(k=1518500249;16>j;)loop(M.readInt32BE(4*j),b&c|~b&d);for(;20>j;)loop(calcW(),b&c|~b&d);for(k=1859775393;40>j;)loop(calcW(),b^c^d);for(k=-1894007588;60>j;)loop(calcW(),b&c|b&d|c&d);for(k=-899497514;80>j;)loop(calcW(),b^c^d);this._a=a+this._a|0,this._b=b+this._b|0,this._c=c+this._c|0,this._d=d+this._d|0,this._e=e+this._e|0},Sha1.prototype._hash=function(){var H=new Buffer(20);return H.writeInt32BE(0|this._a,0),H.writeInt32BE(0|this._b,4),H.writeInt32BE(0|this._c,8),H.writeInt32BE(0|this._d,12),H.writeInt32BE(0|this._e,16),H},module.exports=Sha1}).call(this,require("buffer").Buffer)},{"./hash":16,buffer:52,inherits:14}],20:[function(require,module,exports){(function(Buffer){function Sha224(){this.init(),this._w=W,Hash.call(this,64,56)}var inherits=require("inherits"),Sha256=require("./sha256"),Hash=require("./hash"),W=new Array(64);inherits(Sha224,Sha256),Sha224.prototype.init=function(){return this._a=-1056596264,this._b=914150663,this._c=812702999,this._d=-150054599,this._e=-4191439,this._f=1750603025,this._g=1694076839,this._h=-1090891868,this},Sha224.prototype._hash=function(){var H=new Buffer(28);return H.writeInt32BE(this._a,0),H.writeInt32BE(this._b,4),H.writeInt32BE(this._c,8),H.writeInt32BE(this._d,12),H.writeInt32BE(this._e,16),H.writeInt32BE(this._f,20),H.writeInt32BE(this._g,24),H},module.exports=Sha224}).call(this,require("buffer").Buffer)},{"./hash":16,"./sha256":21,buffer:52,inherits:14}],21:[function(require,module,exports){(function(Buffer){function Sha256(){this.init(),this._w=W,Hash.call(this,64,56)}function Ch(x,y,z){return z^x&(y^z)}function Maj(x,y,z){return x&y|z&(x|y)}function Sigma0(x){return(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10)}function Sigma1(x){return(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7)}function Gamma0(x){return(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3}function Gamma1(x){return(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10}var inherits=require("inherits"),Hash=require("./hash"),K=[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],W=new Array(64);inherits(Sha256,Hash),Sha256.prototype.init=function(){return this._a=1779033703,this._b=-1150833019,this._c=1013904242,this._d=-1521486534,this._e=1359893119,this._f=-1694144372,this._g=528734635,this._h=1541459225,this},Sha256.prototype._update=function(M){function calcW(){return Gamma1(W[j-2])+W[j-7]+Gamma0(W[j-15])+W[j-16]}function loop(w){W[j]=w;var T1=h+Sigma1(e)+Ch(e,f,g)+K[j]+w,T2=Sigma0(a)+Maj(a,b,c);h=g,g=f,f=e,e=d+T1,d=c,c=b,b=a,a=T1+T2,j++}for(var W=this._w,a=0|this._a,b=0|this._b,c=0|this._c,d=0|this._d,e=0|this._e,f=0|this._f,g=0|this._g,h=0|this._h,j=0;16>j;)loop(M.readInt32BE(4*j));for(;64>j;)loop(calcW());this._a=a+this._a|0,this._b=b+this._b|0,this._c=c+this._c|0,this._d=d+this._d|0,this._e=e+this._e|0,this._f=f+this._f|0,this._g=g+this._g|0,this._h=h+this._h|0},Sha256.prototype._hash=function(){var H=new Buffer(32);return H.writeInt32BE(this._a,0),H.writeInt32BE(this._b,4),H.writeInt32BE(this._c,8),H.writeInt32BE(this._d,12),H.writeInt32BE(this._e,16),H.writeInt32BE(this._f,20),H.writeInt32BE(this._g,24),H.writeInt32BE(this._h,28),H},module.exports=Sha256}).call(this,require("buffer").Buffer)},{"./hash":16,buffer:52,inherits:14}],22:[function(require,module,exports){(function(Buffer){function Sha384(){this.init(),this._w=W,Hash.call(this,128,112)}var inherits=require("inherits"),SHA512=require("./sha512"),Hash=require("./hash"),W=new Array(160);inherits(Sha384,SHA512),Sha384.prototype.init=function(){return this._a=-876896931,this._b=1654270250,this._c=-1856437926,this._d=355462360,this._e=1731405415,this._f=-1900787065,this._g=-619958771,this._h=1203062813,this._al=-1056596264,this._bl=914150663,this._cl=812702999,this._dl=-150054599,this._el=-4191439,this._fl=1750603025,this._gl=1694076839,this._hl=-1090891868,this},Sha384.prototype._hash=function(){function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset),H.writeInt32BE(l,offset+4)}var H=new Buffer(48);return writeInt64BE(this._a,this._al,0),writeInt64BE(this._b,this._bl,8),writeInt64BE(this._c,this._cl,16),writeInt64BE(this._d,this._dl,24),writeInt64BE(this._e,this._el,32),writeInt64BE(this._f,this._fl,40),H},module.exports=Sha384}).call(this,require("buffer").Buffer)},{"./hash":16,"./sha512":23,buffer:52,inherits:14}],23:[function(require,module,exports){(function(Buffer){function Sha512(){this.init(),this._w=W,Hash.call(this,128,112)}function Ch(x,y,z){return z^x&(y^z)}function Maj(x,y,z){return x&y|z&(x|y)}function Sigma0(x,xl){return(x>>>28|xl<<4)^(xl>>>2|x<<30)^(xl>>>7|x<<25)}function Sigma1(x,xl){return(x>>>14|xl<<18)^(x>>>18|xl<<14)^(xl>>>9|x<<23)}function Gamma0(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^x>>>7}function Gamma0l(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^(x>>>7|xl<<25)}function Gamma1(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^x>>>6}function Gamma1l(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^(x>>>6|xl<<26)}var inherits=require("inherits"),Hash=require("./hash"),K=[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],W=new Array(160);inherits(Sha512,Hash),Sha512.prototype.init=function(){return this._a=1779033703,this._b=-1150833019,this._c=1013904242,this._d=-1521486534,this._e=1359893119,this._f=-1694144372,this._g=528734635,this._h=1541459225,this._al=-205731576,this._bl=-2067093701,this._cl=-23791573,this._dl=1595750129,this._el=-1377402159,this._fl=725511199,this._gl=-79577749,this._hl=327033209,this},Sha512.prototype._update=function(M){function calcW(){var x=W[j-30],xl=W[j-30+1],gamma0=Gamma0(x,xl),gamma0l=Gamma0l(xl,x);x=W[j-4],xl=W[j-4+1];var gamma1=Gamma1(x,xl),gamma1l=Gamma1l(xl,x),Wi7=W[j-14],Wi7l=W[j-14+1],Wi16=W[j-32],Wi16l=W[j-32+1];Wil=gamma0l+Wi7l,Wi=gamma0+Wi7+(gamma0l>>>0>Wil>>>0?1:0),Wil+=gamma1l,Wi=Wi+gamma1+(gamma1l>>>0>Wil>>>0?1:0),Wil+=Wi16l,Wi=Wi+Wi16+(Wi16l>>>0>Wil>>>0?1:0)}function loop(){W[j]=Wi,W[j+1]=Wil;var maj=Maj(a,b,c),majl=Maj(al,bl,cl),sigma0h=Sigma0(a,al),sigma0l=Sigma0(al,a),sigma1h=Sigma1(e,el),sigma1l=Sigma1(el,e),Ki=K[j],Kil=K[j+1],ch=Ch(e,f,g),chl=Ch(el,fl,gl),t1l=hl+sigma1l,t1=h+sigma1h+(hl>>>0>t1l>>>0?1:0);t1l+=chl,t1=t1+ch+(chl>>>0>t1l>>>0?1:0),t1l+=Kil,t1=t1+Ki+(Kil>>>0>t1l>>>0?1:0),t1l+=Wil,t1=t1+Wi+(Wil>>>0>t1l>>>0?1:0);var t2l=sigma0l+majl,t2=sigma0h+maj+(sigma0l>>>0>t2l>>>0?1:0);h=g,hl=gl,g=f,gl=fl,f=e,fl=el,el=dl+t1l|0,e=d+t1+(dl>>>0>el>>>0?1:0)|0,d=c,dl=cl,c=b,cl=bl,b=a,bl=al,al=t1l+t2l|0,a=t1+t2+(t1l>>>0>al>>>0?1:0)|0,i++,j+=2}for(var Wi,Wil,W=this._w,a=0|this._a,b=0|this._b,c=0|this._c,d=0|this._d,e=0|this._e,f=0|this._f,g=0|this._g,h=0|this._h,al=0|this._al,bl=0|this._bl,cl=0|this._cl,dl=0|this._dl,el=0|this._el,fl=0|this._fl,gl=0|this._gl,hl=0|this._hl,i=0,j=0;16>i;)Wi=M.readInt32BE(4*j),Wil=M.readInt32BE(4*j+4),loop();for(;80>i;)calcW(),loop();this._al=this._al+al|0,this._bl=this._bl+bl|0,this._cl=this._cl+cl|0,this._dl=this._dl+dl|0,this._el=this._el+el|0,this._fl=this._fl+fl|0,this._gl=this._gl+gl|0,this._hl=this._hl+hl|0,this._a=this._a+a+(this._al>>>0>>0?1:0)|0,this._b=this._b+b+(this._bl>>>0>>0?1:0)|0,this._c=this._c+c+(this._cl>>>0>>0?1:0)|0,this._d=this._d+d+(this._dl>>>0
>>0?1:0)|0,this._e=this._e+e+(this._el>>>0>>0?1:0)|0,this._f=this._f+f+(this._fl>>>0>>0?1:0)|0,this._g=this._g+g+(this._gl>>>0>>0?1:0)|0,this._h=this._h+h+(this._hl>>>0>>0?1:0)|0},Sha512.prototype._hash=function(){function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset),H.writeInt32BE(l,offset+4)}var H=new Buffer(64);return writeInt64BE(this._a,this._al,0),writeInt64BE(this._b,this._bl,8),writeInt64BE(this._c,this._cl,16),writeInt64BE(this._d,this._dl,24),writeInt64BE(this._e,this._el,32),writeInt64BE(this._f,this._fl,40),writeInt64BE(this._g,this._gl,48),writeInt64BE(this._h,this._hl,56),H},module.exports=Sha512}).call(this,require("buffer").Buffer)},{"./hash":16,buffer:52,inherits:14}],24:[function(require,module,exports){(function(Buffer){"use strict";function Hmac(alg,key){Transform.call(this),alg=alg.toLowerCase(),"string"==typeof key&&(key=new Buffer(key));var blocksize="sha512"===alg||"sha384"===alg?128:64;this._alg=alg,this._key=key,key.length>blocksize?key=createHash(alg).update(key).digest():key.lengthi;i++)ipad[i]=54^key[i],opad[i]=92^key[i];this._hash=createHash(alg).update(ipad)}var createHash=require("create-hash/browser"),inherits=require("inherits"),Transform=require("stream").Transform,ZEROS=new Buffer(128);ZEROS.fill(0),inherits(Hmac,Transform),Hmac.prototype.update=function(data,enc){return this._hash.update(data,enc),this},Hmac.prototype._transform=function(data,_,next){this._hash.update(data),next()},Hmac.prototype._flush=function(next){this.push(this.digest()),next()},Hmac.prototype.digest=function(enc){var h=this._hash.digest();return createHash(this._alg).update(this._opad).update(h).digest(enc)},module.exports=function(alg,key){return new Hmac(alg,key)}}).call(this,require("buffer").Buffer)},{buffer:52,"create-hash/browser":10,inherits:25,stream:74}],25:[function(require,module,exports){arguments[4][14][0].apply(exports,arguments)},{dup:14}],26:[function(require,module,exports){function Curve(p,a,b,Gx,Gy,n,h){this.p=p,this.a=a,this.b=b,this.G=Point.fromAffine(this,Gx,Gy),this.n=n,this.h=h,this.infinity=new Point(this,null,null,BigInteger.ZERO),this.pOverFour=p.add(BigInteger.ONE).shiftRight(2)}var assert=require("assert"),BigInteger=require("bigi"),Point=require("./point");Curve.prototype.pointFromX=function(isOdd,x){var alpha=x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p),beta=alpha.modPow(this.pOverFour,this.p),y=beta;return beta.isEven()^!isOdd&&(y=this.p.subtract(y)),Point.fromAffine(this,x,y)},Curve.prototype.isInfinity=function(Q){return Q===this.infinity?!0:0===Q.z.signum()&&0!==Q.y.signum()},Curve.prototype.isOnCurve=function(Q){if(this.isInfinity(Q))return!0;var x=Q.affineX,y=Q.affineY,a=this.a,b=this.b,p=this.p;if(x.signum()<0||x.compareTo(p)>=0)return!1;if(y.signum()<0||y.compareTo(p)>=0)return!1;var lhs=y.square().mod(p),rhs=x.pow(3).add(a.multiply(x)).add(b).mod(p);return lhs.equals(rhs)},Curve.prototype.validate=function(Q){assert(!this.isInfinity(Q),"Point is at infinity"),assert(this.isOnCurve(Q),"Point is not on the curve");var nQ=Q.multiply(this.n);return assert(this.isInfinity(nQ),"Point is not a scalar multiple of G"),!0},module.exports=Curve},{"./point":30,assert:50,bigi:3}],27:[function(require,module,exports){module.exports={secp128r1:{p:"fffffffdffffffffffffffffffffffff",a:"fffffffdfffffffffffffffffffffffc",b:"e87579c11079f43dd824993c2cee5ed3",n:"fffffffe0000000075a30d1b9038a115",h:"01",Gx:"161ff7528b899b2d0c28607ca52c5b86",Gy:"cf5ac8395bafeb13c02da292dded7a83"},secp160k1:{p:"fffffffffffffffffffffffffffffffeffffac73",a:"00",b:"07",n:"0100000000000000000001b8fa16dfab9aca16b6b3",h:"01",Gx:"3b4c382ce37aa192a4019e763036f4f5dd4d7ebb",Gy:"938cf935318fdced6bc28286531733c3f03c4fee"},secp160r1:{p:"ffffffffffffffffffffffffffffffff7fffffff",a:"ffffffffffffffffffffffffffffffff7ffffffc",b:"1c97befc54bd7a8b65acf89f81d4d4adc565fa45",n:"0100000000000000000001f4c8f927aed3ca752257",h:"01",Gx:"4a96b5688ef573284664698968c38bb913cbfc82",Gy:"23a628553168947d59dcc912042351377ac5fb32"},secp192k1:{p:"fffffffffffffffffffffffffffffffffffffffeffffee37",a:"00",b:"03",n:"fffffffffffffffffffffffe26f2fc170f69466a74defd8d",h:"01",Gx:"db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",Gy:"9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d"},secp192r1:{p:"fffffffffffffffffffffffffffffffeffffffffffffffff",a:"fffffffffffffffffffffffffffffffefffffffffffffffc",b:"64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",n:"ffffffffffffffffffffffff99def836146bc9b1b4d22831",h:"01",Gx:"188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",Gy:"07192b95ffc8da78631011ed6b24cdd573f977a11e794811"},secp256k1:{p:"fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",a:"00",b:"07",n:"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",h:"01",Gx:"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",Gy:"483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"},secp256r1:{p:"ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",a:"ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",b:"5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",n:"ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",h:"01",Gx:"6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",Gy:"4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"}}},{}],28:[function(require,module,exports){var Point=require("./point"),Curve=require("./curve"),getCurveByName=require("./names");module.exports={Curve:Curve,Point:Point,getCurveByName:getCurveByName}},{"./curve":26,"./names":29,"./point":30}],29:[function(require,module,exports){function getCurveByName(name){var curve=curves[name];if(!curve)return null;var p=new BigInteger(curve.p,16),a=new BigInteger(curve.a,16),b=new BigInteger(curve.b,16),n=new BigInteger(curve.n,16),h=new BigInteger(curve.h,16),Gx=new BigInteger(curve.Gx,16),Gy=new BigInteger(curve.Gy,16);return new Curve(p,a,b,Gx,Gy,n,h)}var BigInteger=require("bigi"),curves=require("./curves"),Curve=require("./curve");module.exports=getCurveByName},{"./curve":26,"./curves":27,bigi:3}],30:[function(require,module,exports){(function(Buffer){function Point(curve,x,y,z){assert.notStrictEqual(z,void 0,"Missing Z coordinate"),this.curve=curve,this.x=x,this.y=y,this.z=z,this._zInv=null,this.compressed=!0}var assert=require("assert"),BigInteger=require("bigi"),THREE=BigInteger.valueOf(3);Object.defineProperty(Point.prototype,"zInv",{get:function(){return null===this._zInv&&(this._zInv=this.z.modInverse(this.curve.p)),this._zInv}}),Object.defineProperty(Point.prototype,"affineX",{get:function(){return this.x.multiply(this.zInv).mod(this.curve.p)}}),Object.defineProperty(Point.prototype,"affineY",{get:function(){return this.y.multiply(this.zInv).mod(this.curve.p)}}),Point.fromAffine=function(curve,x,y){return new Point(curve,x,y,BigInteger.ONE)},Point.prototype.equals=function(other){if(other===this)return!0;if(this.curve.isInfinity(this))return this.curve.isInfinity(other);if(this.curve.isInfinity(other))return this.curve.isInfinity(this);var u=other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p);if(0!==u.signum())return!1;var v=other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p);return 0===v.signum()},Point.prototype.negate=function(){var y=this.curve.p.subtract(this.y);return new Point(this.curve,this.x,y,this.z)},Point.prototype.add=function(b){if(this.curve.isInfinity(this))return b;if(this.curve.isInfinity(b))return this;var x1=this.x,y1=this.y,x2=b.x,y2=b.y,u=y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.p),v=x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.p);if(0===v.signum())return 0===u.signum()?this.twice():this.curve.infinity;var v2=v.square(),v3=v2.multiply(v),x1v2=x1.multiply(v2),zu2=u.square().multiply(this.z),x3=zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.p),y3=x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.p),z3=v3.multiply(this.z).multiply(b.z).mod(this.curve.p);return new Point(this.curve,x3,y3,z3)},Point.prototype.twice=function(){if(this.curve.isInfinity(this))return this;if(0===this.y.signum())return this.curve.infinity;var x1=this.x,y1=this.y,y1z1=y1.multiply(this.z),y1sqz1=y1z1.multiply(y1).mod(this.curve.p),a=this.curve.a,w=x1.square().multiply(THREE);0!==a.signum()&&(w=w.add(this.z.square().multiply(a))),w=w.mod(this.curve.p);var x3=w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.p),y3=w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.p),z3=y1z1.pow(3).shiftLeft(3).mod(this.curve.p);return new Point(this.curve,x3,y3,z3)},Point.prototype.multiply=function(k){if(this.curve.isInfinity(this))return this;if(0===k.signum())return this.curve.infinity;for(var e=k,h=e.multiply(THREE),neg=this.negate(),R=this,i=h.bitLength()-2;i>0;--i){R=R.twice();var hBit=h.testBit(i),eBit=e.testBit(i);hBit!=eBit&&(R=R.add(hBit?this:neg))}return R},Point.prototype.multiplyTwo=function(j,x,k){var i;i=j.bitLength()>k.bitLength()?j.bitLength()-1:k.bitLength()-1;for(var R=this.curve.infinity,both=this.add(x);i>=0;){R=R.twice();var jBit=j.testBit(i),kBit=k.testBit(i);jBit?R=kBit?R.add(both):R.add(this):kBit&&(R=R.add(x)),--i}return R},Point.prototype.getEncoded=function(compressed){if(void 0==compressed&&(compressed=this.compressed),this.curve.isInfinity(this))return new Buffer("00","hex");var buffer,x=this.affineX,y=this.affineY,byteLength=Math.floor((this.curve.p.bitLength()+7)/8);return compressed?(buffer=new Buffer(1+byteLength),buffer.writeUInt8(y.isEven()?2:3,0)):(buffer=new Buffer(1+byteLength+byteLength),buffer.writeUInt8(4,0),y.toBuffer(byteLength).copy(buffer,1+byteLength)),x.toBuffer(byteLength).copy(buffer,1),buffer},Point.decodeFrom=function(curve,buffer){var Q,type=buffer.readUInt8(0),compressed=4!==type,x=BigInteger.fromBuffer(buffer.slice(1,33)),byteLength=Math.floor((curve.p.bitLength()+7)/8);if(compressed){assert.equal(buffer.length,byteLength+1,"Invalid sequence length"),assert(2===type||3===type,"Invalid sequence tag");var isOdd=3===type;Q=curve.pointFromX(isOdd,x)}else{assert.equal(buffer.length,1+byteLength+byteLength,"Invalid sequence length"); +var y=BigInteger.fromBuffer(buffer.slice(1+byteLength));Q=Point.fromAffine(curve,x,y)}return Q.compressed=compressed,Q},Point.prototype.toString=function(){return this.curve.isInfinity(this)?"(INFINITY)":"("+this.affineX.toString()+","+this.affineY.toString()+")"},module.exports=Point}).call(this,require("buffer").Buffer)},{assert:50,bigi:3,buffer:52}],31:[function(require,module,exports){(function(process,global,Buffer){"use strict";function randomBytes(size,cb){var bytes=new Buffer(size);return crypto.getRandomValues(bytes),"function"==typeof cb?process.nextTick(function(){cb(null,bytes)}):bytes}function oldBrowser(){throw new Error("secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11")}var crypto=global.crypto||global.msCrypto;crypto&&crypto.getRandomValues?module.exports=randomBytes:module.exports=oldBrowser}).call(this,require("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},require("buffer").Buffer)},{_process:60,buffer:52}],32:[function(require,module,exports){(function(Buffer){function getFunctionName(fn){return fn.name||fn.toString().match(/function (.*?)\s*\(/)[1]}function getValueTypeName(value){return nativeTypes.Null(value)?"":getFunctionName(value.constructor)}function getValue(value){return nativeTypes.Function(value)?"":nativeTypes.String(value)?JSON.stringify(value):value&&nativeTypes.Object(value)?"":value}function tfJSON(type){return nativeTypes.Function(type)?type.toJSON?type.toJSON():getFunctionName(type):nativeTypes.Array(type)?"Array":type&&nativeTypes.Object(type)?"Object":type||""}function stfJSON(type){return type=tfJSON(type),nativeTypes.Object(type)?JSON.stringify(type):type}function tfErrorString(type,value){var valueTypeName=getValueTypeName(value),valueValue=getValue(value);return"Expected "+stfJSON(type)+", got"+(""!==valueTypeName?" "+valueTypeName:"")+(""!==valueValue?" "+valueValue:"")}function tfPropertyErrorString(type,name,value){return tfErrorString('property "'+stfJSON(name)+'" of type '+stfJSON(type),value)}function compile(type){if(nativeTypes.String(type))return"?"===type[0]?otherTypes.maybe(compile(type.slice(1))):nativeTypes[type]||otherTypes.quacksLike(type);if(type&&nativeTypes.Object(type)){if(nativeTypes.Array(type))return otherTypes.arrayOf(compile(type[0]));var compiled={};for(var propertyName in type)compiled[propertyName]=compile(type[propertyName]);return otherTypes.object(compiled)}return nativeTypes.Function(type)?type:otherTypes.value(type)}function typeforce(type,value,strict){if(nativeTypes.Function(type)){if(type(value,strict))return!0;throw new TypeError(tfErrorString(type,value))}return typeforce(compile(type),value,strict)}var typeName,nativeTypes={Array:function(value){return null!==value&&void 0!==value&&value.constructor===Array},Boolean:function(value){return"boolean"==typeof value},Buffer:function(value){return Buffer.isBuffer(value)},Function:function(value){return"function"==typeof value},Null:function(value){return void 0===value||null===value},Number:function(value){return"number"==typeof value},Object:function(value){return"object"==typeof value},String:function(value){return"string"==typeof value},"":function(){return!0}},otherTypes={arrayOf:function arrayOf(type){function arrayOf(value,strict){try{return nativeTypes.Array(value)&&value.every(function(x){return typeforce(type,x,strict)})}catch(e){return!1}}return arrayOf.toJSON=function(){return[tfJSON(type)]},arrayOf},maybe:function maybe(type){function maybe(value,strict){return nativeTypes.Null(value)||typeforce(type,value,strict)}return maybe.toJSON=function(){return"?"+stfJSON(type)},maybe},object:function object(type){function object(value,strict){typeforce(nativeTypes.Object,value,strict);var propertyName,propertyType,propertyValue;try{for(propertyName in type)propertyType=type[propertyName],propertyValue=value[propertyName],typeforce(propertyType,propertyValue,strict)}catch(e){if(/Expected property "/.test(e.message))throw e.message=e.message.replace(/Expected property "(.+)" of/,'Expected property "'+propertyName+'.$1" of'),e;throw new TypeError(tfPropertyErrorString(propertyType,propertyName,propertyValue))}if(strict)for(propertyName in value)if(!type[propertyName])throw new TypeError('Unexpected property "'+propertyName+'"');return!0}return object.toJSON=function(){return tfJSON(type)},object},map:function map(propertyType,propertyKeyType){function map(value,strict){typeforce(nativeTypes.Object,value,strict);var propertyName,propertyValue;try{for(propertyName in value)propertyKeyType&&typeforce(propertyKeyType,propertyName,strict),propertyValue=value[propertyName],typeforce(propertyType,propertyValue,strict)}catch(e){if(/Expected property "/.test(e.message))throw e.message=e.message.replace(/Expected property "(.+)" of/,'Expected property "'+propertyName+'.$1" of'),e;throw new TypeError(tfPropertyErrorString(propertyType,propertyKeyType||propertyName,propertyValue))}return!0}return propertyKeyType?map.toJSON=function(){return"{"+stfJSON(propertyKeyType)+": "+stfJSON(propertyType)+"}"}:map.toJSON=function(){return"{"+stfJSON(propertyType)+"}"},map},oneOf:function oneOf(){function oneOf(value,strict){return types.some(function(type){try{return typeforce(type,value,strict)}catch(e){return!1}})}var types=[].slice.call(arguments);return oneOf.toJSON=function(){return types.map(stfJSON).join("|")},oneOf},quacksLike:function quacksLike(type){function quacksLike(value,strict){return type===getValueTypeName(value)}return quacksLike.toJSON=function(){return type},quacksLike},tuple:function tuple(){function tuple(value,strict){return types.every(function(type,i){return typeforce(type,value[i],strict)})}var types=[].slice.call(arguments);return tuple.toJSON=function(){return"("+types.map(stfJSON).join(", ")+")"},tuple},value:function value(expected){function value(actual){return actual===expected}return value.toJSON=function(){return expected},value}};Object.keys(nativeTypes).forEach(function(typeName){var nativeType=nativeTypes[typeName];nativeType.toJSON=function(){return typeName},typeforce[typeName]=nativeType});for(typeName in otherTypes)typeforce[typeName]=otherTypes[typeName];module.exports=typeforce,module.exports.compile=compile}).call(this,{isBuffer:require("../../../../../usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js")})},{"../../../../../usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js":58}],33:[function(require,module,exports){(function(Buffer){function decodeRaw(version,buffer){if(buffer[0]!==version)throw new Error("Invalid network version");if(34===buffer.length){if(1!==buffer[33])throw new Error("Invalid compression flag");return{version:buffer[0],d:buffer.slice(1,-1),compressed:!0}}if(33!==buffer.length)throw new Error("Invalid WIF length");return{version:buffer[0],d:buffer.slice(1),compressed:!1}}function decode(version,string){return decodeRaw(version,bs58check.decode(string))}function encodeRaw(version,d,compressed){var buffer=new Buffer(compressed?34:33);return buffer.writeUInt8(version,0),d.copy(buffer,1),compressed&&(buffer[33]=1),buffer}function encode(version,d,compressed){return bs58check.encode(encodeRaw(version,d,compressed))}var bs58check=require("bs58check");module.exports={decode:decode,decodeRaw:decodeRaw,encode:encode,encodeRaw:encodeRaw}}).call(this,require("buffer").Buffer)},{bs58check:7,buffer:52}],34:[function(require,module,exports){(function(Buffer){function fromBase58Check(address){var payload=bs58check.decode(address);if(payload.length<21)throw new TypeError(address+" is too short");if(payload.length>21)throw new TypeError(address+" is too long");var version=payload[0],hash=payload.slice(1);return{hash:hash,version:version}}function fromOutputScript(scriptPubKey,network){network=network||networks.bitcoin;var chunks=bscript.decompile(scriptPubKey);if(bscript.isPubKeyHashOutput(chunks))return toBase58Check(chunks[2],network.pubKeyHash);if(bscript.isScriptHashOutput(chunks))return toBase58Check(chunks[1],network.scriptHash);throw new Error(bscript.toASM(chunks)+" has no matching Address")}function toBase58Check(hash,version){typeforce(types.tuple(types.Hash160bit,types.UInt8),arguments);var payload=new Buffer(21);return payload.writeUInt8(version,0),hash.copy(payload,1),bs58check.encode(payload)}function toOutputScript(address,network){network=network||networks.bitcoin;var decode=fromBase58Check(address);if(decode.version===network.pubKeyHash)return bscript.pubKeyHashOutput(decode.hash);if(decode.version===network.scriptHash)return bscript.scriptHashOutput(decode.hash);throw new Error(address+" has no matching Script")}var bs58check=require("bs58check"),bscript=require("./script"),networks=require("./networks"),typeforce=require("typeforce"),types=require("./types");module.exports={fromBase58Check:fromBase58Check,fromOutputScript:fromOutputScript,toBase58Check:toBase58Check,toOutputScript:toOutputScript}}).call(this,require("buffer").Buffer)},{"./networks":44,"./script":46,"./types":49,bs58check:7,buffer:52,typeforce:32}],35:[function(require,module,exports){(function(Buffer){function Block(){this.version=1,this.prevHash=null,this.merkleRoot=null,this.timestamp=0,this.bits=0,this.nonce=0}var bufferutils=require("./bufferutils"),bcrypto=require("./crypto"),Transaction=require("./transaction");Block.fromBuffer=function(buffer){function readSlice(n){return offset+=n,buffer.slice(offset-n,offset)}function readUInt32(){var i=buffer.readUInt32LE(offset);return offset+=4,i}function readVarInt(){var vi=bufferutils.readVarInt(buffer,offset);return offset+=vi.size,vi.number}function readTransaction(){var tx=Transaction.fromBuffer(buffer.slice(offset),!0);return offset+=tx.byteLength(),tx}if(buffer.length<80)throw new Error("Buffer too small (< 80 bytes)");var offset=0,block=new Block;if(block.version=readUInt32(),block.prevHash=readSlice(32),block.merkleRoot=readSlice(32),block.timestamp=readUInt32(),block.bits=readUInt32(),block.nonce=readUInt32(),80===buffer.length)return block;var nTransactions=readVarInt();block.transactions=[];for(var i=0;nTransactions>i;++i){var tx=readTransaction();block.transactions.push(tx)}return block},Block.fromHex=function(hex){return Block.fromBuffer(new Buffer(hex,"hex"))},Block.prototype.getHash=function(){return bcrypto.hash256(this.toBuffer(!0))},Block.prototype.getId=function(){return[].reverse.call(this.getHash()).toString("hex")},Block.prototype.getUTCDate=function(){var date=new Date(0);return date.setUTCSeconds(this.timestamp),date},Block.prototype.toBuffer=function(headersOnly){function writeSlice(slice){slice.copy(buffer,offset),offset+=slice.length}function writeUInt32(i){buffer.writeUInt32LE(i,offset),offset+=4}var buffer=new Buffer(80),offset=0;if(writeUInt32(this.version),writeSlice(this.prevHash),writeSlice(this.merkleRoot),writeUInt32(this.timestamp),writeUInt32(this.bits),writeUInt32(this.nonce),headersOnly||!this.transactions)return buffer;var txLenBuffer=bufferutils.varIntBuffer(this.transactions.length),txBuffers=this.transactions.map(function(tx){return tx.toBuffer()});return Buffer.concat([buffer,txLenBuffer].concat(txBuffers))},Block.prototype.toHex=function(headersOnly){return this.toBuffer(headersOnly).toString("hex")},module.exports=Block}).call(this,require("buffer").Buffer)},{"./bufferutils":36,"./crypto":37,"./transaction":47,buffer:52}],36:[function(require,module,exports){(function(Buffer){function verifuint(value,max){if("number"!=typeof value)throw new Error("cannot write a non-number as a number");if(0>value)throw new Error("specified a negative value for writing an unsigned value");if(value>max)throw new Error("value is larger than maximum value for type");if(Math.floor(value)!==value)throw new Error("value has a fractional component")}function pushDataSize(i){return ii?2:65535>i?3:5}function readPushDataInt(buffer,offset){var number,size,opcode=buffer.readUInt8(offset);if(opcodebuffer.length)return null;number=buffer.readUInt8(offset+1),size=2}else if(opcode===opcodes.OP_PUSHDATA2){if(offset+3>buffer.length)return null;number=buffer.readUInt16LE(offset+1),size=3}else{if(offset+5>buffer.length)return null;if(opcode!==opcodes.OP_PUSHDATA4)throw new Error("Unexpected opcode");number=buffer.readUInt32LE(offset+1),size=5}return{opcode:opcode,number:number,size:size}}function readUInt64LE(buffer,offset){var a=buffer.readUInt32LE(offset),b=buffer.readUInt32LE(offset+4);return b*=4294967296,verifuint(b+a,9007199254740991),b+a}function readVarInt(buffer,offset){var number,size,t=buffer.readUInt8(offset);return 253>t?(number=t,size=1):254>t?(number=buffer.readUInt16LE(offset+1),size=3):255>t?(number=buffer.readUInt32LE(offset+1),size=5):(number=readUInt64LE(buffer,offset+1),size=9),{number:number,size:size}}function writePushDataInt(buffer,number,offset){var size=pushDataSize(number);return 1===size?buffer.writeUInt8(number,offset):2===size?(buffer.writeUInt8(opcodes.OP_PUSHDATA1,offset),buffer.writeUInt8(number,offset+1)):3===size?(buffer.writeUInt8(opcodes.OP_PUSHDATA2,offset),buffer.writeUInt16LE(number,offset+1)):(buffer.writeUInt8(opcodes.OP_PUSHDATA4,offset),buffer.writeUInt32LE(number,offset+1)),size}function writeUInt64LE(buffer,value,offset){verifuint(value,9007199254740991),buffer.writeInt32LE(-1&value,offset),buffer.writeUInt32LE(Math.floor(value/4294967296),offset+4)}function varIntSize(i){return 253>i?1:65536>i?3:4294967296>i?5:9}function writeVarInt(buffer,number,offset){var size=varIntSize(number);return 1===size?buffer.writeUInt8(number,offset):3===size?(buffer.writeUInt8(253,offset),buffer.writeUInt16LE(number,offset+1)):5===size?(buffer.writeUInt8(254,offset),buffer.writeUInt32LE(number,offset+1)):(buffer.writeUInt8(255,offset),writeUInt64LE(buffer,number,offset+1)),size}function varIntBuffer(i){var size=varIntSize(i),buffer=new Buffer(size);return writeVarInt(buffer,i,0),buffer}var opcodes=require("./opcodes");module.exports={equal:require("buffer-equals"),pushDataSize:pushDataSize,readPushDataInt:readPushDataInt,readUInt64LE:readUInt64LE,readVarInt:readVarInt,reverse:require("buffer-reverse"),varIntBuffer:varIntBuffer,varIntSize:varIntSize,writePushDataInt:writePushDataInt,writeUInt64LE:writeUInt64LE,writeVarInt:writeVarInt}}).call(this,require("buffer").Buffer)},{"./opcodes":45,buffer:52,"buffer-equals":8,"buffer-reverse":9}],37:[function(require,module,exports){function hash160(buffer){return ripemd160(sha256(buffer))}function hash256(buffer){return sha256(sha256(buffer))}function ripemd160(buffer){return createHash("rmd160").update(buffer).digest()}function sha1(buffer){return createHash("sha1").update(buffer).digest()}function sha256(buffer){return createHash("sha256").update(buffer).digest()}var createHash=require("create-hash");module.exports={hash160:hash160,hash256:hash256,ripemd160:ripemd160,sha1:sha1,sha256:sha256}},{"create-hash":10}],38:[function(require,module,exports){(function(Buffer){function deterministicGenerateK(hash,x,checkSig){typeforce(types.tuple(types.Hash256bit,types.Buffer256bit,types.Function),arguments);var k=new Buffer(32),v=new Buffer(32);v.fill(1),k.fill(0),k=createHmac("sha256",k).update(v).update(ZERO).update(x).update(hash).digest(),v=createHmac("sha256",k).update(v).digest(),k=createHmac("sha256",k).update(v).update(ONE).update(x).update(hash).digest(),v=createHmac("sha256",k).update(v).digest(),v=createHmac("sha256",k).update(v).digest();for(var T=BigInteger.fromBuffer(v);T.signum()<=0||T.compareTo(secp256k1.n)>=0||!checkSig(T);)k=createHmac("sha256",k).update(v).update(ZERO).digest(),v=createHmac("sha256",k).update(v).digest(),v=createHmac("sha256",k).update(v).digest(),T=BigInteger.fromBuffer(v);return T}function sign(hash,d){typeforce(types.tuple(types.Hash256bit,types.BigInt),arguments);var r,s,x=d.toBuffer(32),e=BigInteger.fromBuffer(hash),n=secp256k1.n,G=secp256k1.G;return deterministicGenerateK(hash,x,function(k){var Q=G.multiply(k);return secp256k1.isInfinity(Q)?!1:(r=Q.affineX.mod(n),0===r.signum()?!1:(s=k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n),0===s.signum()?!1:!0))}),s.compareTo(N_OVER_TWO)>0&&(s=n.subtract(s)),new ECSignature(r,s)}function verify(hash,signature,Q){typeforce(types.tuple(types.Hash256bit,types.ECSignature,types.ECPoint),arguments);var n=secp256k1.n,G=secp256k1.G,r=signature.r,s=signature.s;if(r.signum()<=0||r.compareTo(n)>=0)return!1;if(s.signum()<=0||s.compareTo(n)>=0)return!1;var e=BigInteger.fromBuffer(hash),sInv=s.modInverse(n),u1=e.multiply(sInv).mod(n),u2=r.multiply(sInv).mod(n),R=G.multiplyTwo(u1,Q,u2);if(secp256k1.isInfinity(R))return!1;var xR=R.affineX,v=xR.mod(n);return v.equals(r)}function recoverPubKey(e,signature,i){typeforce(types.tuple(types.BigInt,types.ECSignature,types.UInt2),arguments);var n=secp256k1.n,G=secp256k1.G,r=signature.r,s=signature.s;if(r.signum()<=0||r.compareTo(n)>=0)throw new Error("Invalid r value");if(s.signum()<=0||s.compareTo(n)>=0)throw new Error("Invalid s value");var isYOdd=1&i,isSecondKey=i>>1,x=isSecondKey?r.add(n):r,R=secp256k1.pointFromX(isYOdd,x),nR=R.multiply(n);if(!secp256k1.isInfinity(nR))throw new Error("nR is not a valid curve point");var rInv=r.modInverse(n),eNeg=e.negate().mod(n),Q=R.multiplyTwo(s,G,eNeg).multiply(rInv);return secp256k1.validate(Q),Q}function calcPubKeyRecoveryParam(e,signature,Q){typeforce(types.tuple(types.BigInt,types.ECSignature,types.ECPoint),arguments);for(var i=0;4>i;i++){var Qprime=recoverPubKey(e,signature,i);if(Qprime.equals(Q))return i}throw new Error("Unable to find valid recovery factor")}var createHmac=require("create-hmac"),typeforce=require("typeforce"),types=require("./types"),BigInteger=require("bigi"),ECSignature=require("./ecsignature"),ZERO=new Buffer([0]),ONE=new Buffer([1]),ecurve=require("ecurve"),secp256k1=ecurve.getCurveByName("secp256k1"),N_OVER_TWO=secp256k1.n.shiftRight(1);module.exports={calcPubKeyRecoveryParam:calcPubKeyRecoveryParam,deterministicGenerateK:deterministicGenerateK,recoverPubKey:recoverPubKey,sign:sign,verify:verify,__curve:secp256k1}}).call(this,require("buffer").Buffer)},{"./ecsignature":40,"./types":49,bigi:3,buffer:52,"create-hmac":24,ecurve:28,typeforce:32}],39:[function(require,module,exports){(function(Buffer){function ECPair(d,Q,options){if(options&&typeforce({compressed:types.maybe(types.Boolean),network:types.maybe(types.Network)},options),options=options||{},d){if(d.signum()<=0)throw new Error("Private key must be greater than 0");if(d.compareTo(secp256k1.n)>=0)throw new Error("Private key must be less than the curve order");if(Q)throw new TypeError("Unexpected publicKey parameter");this.d=d}else typeforce(types.ECPoint,Q),this.__Q=Q;this.compressed=void 0===options.compressed?!0:options.compressed,this.network=options.network||NETWORKS.bitcoin}var bcrypto=require("./crypto"),bs58check=require("bs58check"),ecdsa=require("./ecdsa"),randomBytes=require("randombytes"),typeforce=require("typeforce"),types=require("./types"),wif=require("wif"),NETWORKS=require("./networks"),BigInteger=require("bigi"),ecurve=require("ecurve"),secp256k1=ecdsa.__curve;Object.defineProperty(ECPair.prototype,"Q",{get:function(){return!this.__Q&&this.d&&(this.__Q=secp256k1.G.multiply(this.d)),this.__Q}}),ECPair.fromPublicKeyBuffer=function(buffer,network){var Q=ecurve.Point.decodeFrom(secp256k1,buffer);return new ECPair(null,Q,{compressed:Q.compressed,network:network})},ECPair.fromWIF=function(string,network){network=network||NETWORKS.bitcoin;var buffer=bs58check.decode(string);if(types.Array(network)){var version=buffer[0];network=network.filter(function(network){return version===network.wif}).pop()||{}}var decoded=wif.decodeRaw(network.wif,buffer),d=BigInteger.fromBuffer(decoded.d);return new ECPair(d,null,{compressed:decoded.compressed,network:network})},ECPair.makeRandom=function(options){options=options||{};var d,rng=options.rng||randomBytes;do{var buffer=rng(32);typeforce(types.Buffer256bit,buffer),d=BigInteger.fromBuffer(buffer)}while(d.signum()<=0||d.compareTo(secp256k1.n)>=0);return new ECPair(d,null,options)},ECPair.prototype.getAddress=function(){var pubKey=this.getPublicKeyBuffer(),pubKeyHash=bcrypto.hash160(pubKey),payload=new Buffer(21);return payload.writeUInt8(this.network.pubKeyHash,0),pubKeyHash.copy(payload,1),bs58check.encode(payload)},ECPair.prototype.getNetwork=function(){return this.network},ECPair.prototype.getPublicKeyBuffer=function(){return this.Q.getEncoded(this.compressed)},ECPair.prototype.sign=function(hash){if(!this.d)throw new Error("Missing private key");return ecdsa.sign(hash,this.d)},ECPair.prototype.toWIF=function(){if(!this.d)throw new Error("Missing private key");return wif.encode(this.network.wif,this.d.toBuffer(32),this.compressed)},ECPair.prototype.verify=function(hash,signature){return ecdsa.verify(hash,signature,this.Q)},module.exports=ECPair}).call(this,require("buffer").Buffer)},{"./crypto":37,"./ecdsa":38,"./networks":44,"./types":49,bigi:3,bs58check:7,buffer:52,ecurve:28,randombytes:31,typeforce:32,wif:33}],40:[function(require,module,exports){(function(Buffer){function ECSignature(r,s){typeforce(types.tuple(types.BigInt,types.BigInt),arguments),this.r=r,this.s=s}var bip66=require("bip66"),typeforce=require("typeforce"),types=require("./types"),BigInteger=require("bigi");ECSignature.parseCompact=function(buffer){if(65!==buffer.length)throw new Error("Invalid signature length");var flagByte=buffer.readUInt8(0)-27;if(flagByte!==(7&flagByte))throw new Error("Invalid signature parameter");var compressed=!!(4&flagByte),recoveryParam=3&flagByte,r=BigInteger.fromBuffer(buffer.slice(1,33)),s=BigInteger.fromBuffer(buffer.slice(33));return{compressed:compressed,i:recoveryParam,signature:new ECSignature(r,s)}},ECSignature.fromDER=function(buffer){var decode=bip66.decode(buffer),r=BigInteger.fromDERInteger(decode.r),s=BigInteger.fromDERInteger(decode.s);return new ECSignature(r,s)},ECSignature.parseScriptSignature=function(buffer){var hashType=buffer.readUInt8(buffer.length-1),hashTypeMod=-129&hashType;if(0>=hashTypeMod||hashTypeMod>=4)throw new Error("Invalid hashType "+hashType);return{signature:ECSignature.fromDER(buffer.slice(0,-1)),hashType:hashType}},ECSignature.prototype.toCompact=function(i,compressed){compressed&&(i+=4),i+=27;var buffer=new Buffer(65);return buffer.writeUInt8(i,0),this.r.toBuffer(32).copy(buffer,1),this.s.toBuffer(32).copy(buffer,33),buffer},ECSignature.prototype.toDER=function(){var r=new Buffer(this.r.toDERInteger()),s=new Buffer(this.s.toDERInteger());return bip66.encode(r,s)},ECSignature.prototype.toScriptSignature=function(hashType){var hashTypeMod=-129&hashType;if(0>=hashTypeMod||hashTypeMod>=4)throw new Error("Invalid hashType "+hashType);var hashTypeBuffer=new Buffer(1);return hashTypeBuffer.writeUInt8(hashType,0),Buffer.concat([this.toDER(),hashTypeBuffer])},module.exports=ECSignature}).call(this,require("buffer").Buffer)},{"./types":49,bigi:3,bip66:5,buffer:52,typeforce:32}],41:[function(require,module,exports){(function(Buffer){function HDNode(keyPair,chainCode){if(typeforce(types.tuple("ECPair",types.Buffer256bit),arguments),!keyPair.compressed)throw new TypeError("BIP32 only allows compressed keyPairs");this.keyPair=keyPair,this.chainCode=chainCode,this.depth=0,this.index=0,this.parentFingerprint=0}var base58check=require("bs58check"),bcrypto=require("./crypto"),createHmac=require("create-hmac"),typeforce=require("typeforce"),types=require("./types"),NETWORKS=require("./networks"),BigInteger=require("bigi"),ECPair=require("./ecpair"),ecurve=require("ecurve"),curve=ecurve.getCurveByName("secp256k1");HDNode.HIGHEST_BIT=2147483648,HDNode.LENGTH=78,HDNode.MASTER_SECRET=new Buffer("Bitcoin seed"),HDNode.fromSeedBuffer=function(seed,network){if(typeforce(types.tuple(types.Buffer,types.maybe(types.Network)),arguments),seed.length<16)throw new TypeError("Seed should be at least 128 bits");if(seed.length>64)throw new TypeError("Seed should be at most 512 bits");var I=createHmac("sha512",HDNode.MASTER_SECRET).update(seed).digest(),IL=I.slice(0,32),IR=I.slice(32),pIL=BigInteger.fromBuffer(IL),keyPair=new ECPair(pIL,null,{network:network});return new HDNode(keyPair,IR)},HDNode.fromSeedHex=function(hex,network){return HDNode.fromSeedBuffer(new Buffer(hex,"hex"),network)},HDNode.fromBase58=function(string,networks){var buffer=base58check.decode(string);if(78!==buffer.length)throw new Error("Invalid buffer length");var network,version=buffer.readUInt32BE(0);if(network=Array.isArray(networks)?networks.filter(function(network){return version===network.bip32["private"]||version===network.bip32["public"]}).pop()||{}:networks||NETWORKS.bitcoin,version!==network.bip32["private"]&&version!==network.bip32["public"])throw new Error("Invalid network");var depth=buffer[4],parentFingerprint=buffer.readUInt32BE(5);if(0===depth&&0!==parentFingerprint)throw new Error("Invalid parent fingerprint");var index=buffer.readUInt32BE(9);if(0===depth&&0!==index)throw new Error("Invalid index");var keyPair,chainCode=buffer.slice(13,45);if(version===network.bip32["private"]){if(0!==buffer.readUInt8(45))throw new Error("Invalid private key");var d=BigInteger.fromBuffer(buffer.slice(46,78));keyPair=new ECPair(d,null,{network:network})}else{var Q=ecurve.Point.decodeFrom(curve,buffer.slice(45,78));if(!Q.compressed)throw new Error("Invalid public key");curve.validate(Q),keyPair=new ECPair(null,Q,{network:network})}var hd=new HDNode(keyPair,chainCode);return hd.depth=depth,hd.index=index,hd.parentFingerprint=parentFingerprint,hd},HDNode.prototype.getAddress=function(){return this.keyPair.getAddress()},HDNode.prototype.getIdentifier=function(){return bcrypto.hash160(this.keyPair.getPublicKeyBuffer())},HDNode.prototype.getFingerprint=function(){return this.getIdentifier().slice(0,4)},HDNode.prototype.getNetwork=function(){return this.keyPair.getNetwork()},HDNode.prototype.getPublicKeyBuffer=function(){return this.keyPair.getPublicKeyBuffer()},HDNode.prototype.neutered=function(){var neuteredKeyPair=new ECPair(null,this.keyPair.Q,{network:this.keyPair.network}),neutered=new HDNode(neuteredKeyPair,this.chainCode);return neutered.depth=this.depth,neutered.index=this.index,neutered.parentFingerprint=this.parentFingerprint,neutered},HDNode.prototype.sign=function(hash){return this.keyPair.sign(hash)},HDNode.prototype.verify=function(hash,signature){return this.keyPair.verify(hash,signature)},HDNode.prototype.toBase58=function(__isPrivate){if(void 0!==__isPrivate)throw new TypeError("Unsupported argument in 2.0.0");var network=this.keyPair.network,version=this.keyPair.d?network.bip32["private"]:network.bip32["public"],buffer=new Buffer(78);return buffer.writeUInt32BE(version,0),buffer.writeUInt8(this.depth,4),buffer.writeUInt32BE(this.parentFingerprint,5),buffer.writeUInt32BE(this.index,9),this.chainCode.copy(buffer,13),this.keyPair.d?(buffer.writeUInt8(0,45),this.keyPair.d.toBuffer(32).copy(buffer,46)):this.keyPair.getPublicKeyBuffer().copy(buffer,45),base58check.encode(buffer)},HDNode.prototype.derive=function(index){var isHardened=index>=HDNode.HIGHEST_BIT,data=new Buffer(37);if(isHardened){if(!this.keyPair.d)throw new TypeError("Could not derive hardened child key");data[0]=0,this.keyPair.d.toBuffer(32).copy(data,1),data.writeUInt32BE(index,33)}else this.keyPair.getPublicKeyBuffer().copy(data,0),data.writeUInt32BE(index,33);var I=createHmac("sha512",this.chainCode).update(data).digest(),IL=I.slice(0,32),IR=I.slice(32),pIL=BigInteger.fromBuffer(IL);if(pIL.compareTo(curve.n)>=0)return this.derive(index+1);var derivedKeyPair;if(this.keyPair.d){var ki=pIL.add(this.keyPair.d).mod(curve.n);if(0===ki.signum())return this.derive(index+1);derivedKeyPair=new ECPair(ki,null,{network:this.keyPair.network})}else{var Ki=curve.G.multiply(pIL).add(this.keyPair.Q);if(curve.isInfinity(Ki))return this.derive(index+1);derivedKeyPair=new ECPair(null,Ki,{network:this.keyPair.network})}var hd=new HDNode(derivedKeyPair,IR);return hd.depth=this.depth+1,hd.index=index,hd.parentFingerprint=this.getFingerprint().readUInt32BE(0),hd},HDNode.prototype.deriveHardened=function(index){return this.derive(index+HDNode.HIGHEST_BIT)},HDNode.prototype.toString=HDNode.prototype.toBase58,module.exports=HDNode}).call(this,require("buffer").Buffer)},{"./crypto":37,"./ecpair":39,"./networks":44,"./types":49,bigi:3,bs58check:7,buffer:52,"create-hmac":24,ecurve:28,typeforce:32}],42:[function(require,module,exports){module.exports={Block:require("./block"),ECPair:require("./ecpair"),ECSignature:require("./ecsignature"),HDNode:require("./hdnode"),Transaction:require("./transaction"),TransactionBuilder:require("./transaction_builder"),address:require("./address"),bufferutils:require("./bufferutils"),crypto:require("./crypto"),message:require("./message"),networks:require("./networks"),opcodes:require("./opcodes"),script:require("./script")}},{"./address":34,"./block":35,"./bufferutils":36,"./crypto":37,"./ecpair":39,"./ecsignature":40,"./hdnode":41,"./message":43,"./networks":44,"./opcodes":45,"./script":46,"./transaction":47,"./transaction_builder":48}],43:[function(require,module,exports){(function(Buffer){function magicHash(message,network){var messagePrefix=new Buffer(network.messagePrefix),messageBuffer=new Buffer(message),lengthBuffer=bufferutils.varIntBuffer(messageBuffer.length),buffer=Buffer.concat([messagePrefix,lengthBuffer,messageBuffer]);return bcrypto.hash256(buffer)}function sign(keyPair,message,network){network=network||networks.bitcoin;var hash=magicHash(message,network),signature=keyPair.sign(hash),e=BigInteger.fromBuffer(hash),i=ecdsa.calcPubKeyRecoveryParam(e,signature,keyPair.Q);return signature.toCompact(i,keyPair.compressed)}function verify(address,signature,message,network){Buffer.isBuffer(signature)||(signature=new Buffer(signature,"base64")),network=network||networks.bitcoin;var hash=magicHash(message,network),parsed=ECSignature.parseCompact(signature),e=BigInteger.fromBuffer(hash),Q=ecdsa.recoverPubKey(e,parsed.signature,parsed.i),keyPair=new ECPair(null,Q,{compressed:parsed.compressed,network:network});return keyPair.getAddress()===address}var bufferutils=require("./bufferutils"),bcrypto=require("./crypto"),ecdsa=require("./ecdsa"),networks=require("./networks"),BigInteger=require("bigi"),ECPair=require("./ecpair"),ECSignature=require("./ecsignature");module.exports={magicHash:magicHash,sign:sign,verify:verify}}).call(this,require("buffer").Buffer)},{"./bufferutils":36,"./crypto":37,"./ecdsa":38,"./ecpair":39,"./ecsignature":40,"./networks":44,bigi:3,buffer:52}],44:[function(require,module,exports){module.exports={bitcoin:{messagePrefix:"Bitcoin Signed Message:\n",bip32:{"public":76067358,"private":76066276},pubKeyHash:0,scriptHash:5,wif:128,dustThreshold:546},testnet:{messagePrefix:"Bitcoin Signed Message:\n",bip32:{"public":70617039,"private":70615956},pubKeyHash:111,scriptHash:196,wif:239,dustThreshold:546},litecoin:{messagePrefix:"Litecoin Signed Message:\n",bip32:{"public":27108450,"private":27106558},pubKeyHash:48,scriptHash:5,wif:176,dustThreshold:0},dogecoin:{messagePrefix:"Dogecoin Signed Message:\n",bip32:{"public":49990397,"private":49988504},pubKeyHash:30,scriptHash:22,wif:158,dustThreshold:0}}},{}],45:[function(require,module,exports){module.exports={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_1:81,OP_TRUE: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_NOP3: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}},{}],46:[function(require,module,exports){(function(Buffer){function toASM(chunks){return types.Buffer(chunks)&&(chunks=decompile(chunks)),chunks.map(function(chunk){return Buffer.isBuffer(chunk)?chunk.toString("hex"):REVERSE_OPS[chunk]}).join(" ")}function fromASM(asm){return typeforce(types.String,asm),compile(asm.split(" ").map(function(chunkStr){return void 0!==OPS[chunkStr]?OPS[chunkStr]:new Buffer(chunkStr,"hex")}))}function compile(chunks){if(types.Buffer(chunks))return chunks;typeforce(types.Array,chunks);var bufferSize=chunks.reduce(function(accum,chunk){return Buffer.isBuffer(chunk)?accum+bufferutils.pushDataSize(chunk.length)+chunk.length:accum+1},0),buffer=new Buffer(bufferSize),offset=0;if(chunks.forEach(function(chunk){Buffer.isBuffer(chunk)?(offset+=bufferutils.writePushDataInt(buffer,chunk.length,offset),chunk.copy(buffer,offset),offset+=chunk.length):(buffer.writeUInt8(chunk,offset),offset+=1)}),offset!==buffer.length)throw new Error("Could not decode chunks");return buffer}function decompile(buffer){if(types.Array(buffer))return buffer;typeforce(types.Buffer,buffer);for(var chunks=[],i=0;iOPS.OP_0&&opcode<=OPS.OP_PUSHDATA4){var d=bufferutils.readPushDataInt(buffer,i);if(null===d)return[];if(i+=d.size,i+d.number>buffer.length)return[];var data=buffer.slice(i,i+d.number);i+=d.number,chunks.push(data)}else chunks.push(opcode),i+=1}return chunks}function isCanonicalPubKey(buffer){if(!Buffer.isBuffer(buffer))return!1;if(buffer.length<33)return!1;switch(buffer[0]){case 2:case 3:return 33===buffer.length;case 4:return 65===buffer.length}return!1}function isCanonicalSignature(buffer){return Buffer.isBuffer(buffer)&&isDefinedHashType(buffer[buffer.length-1])?bip66.check(buffer.slice(0,-1)):!1}function isDefinedHashType(hashType){var hashTypeMod=-129&hashType;return hashTypeMod>0&&4>hashTypeMod}function isPubKeyHashInput(script){var chunks=decompile(script);return 2===chunks.length&&isCanonicalSignature(chunks[0])&&isCanonicalPubKey(chunks[1])}function isPubKeyHashOutput(script){var chunks=decompile(script);return 5===chunks.length&&chunks[0]===OPS.OP_DUP&&chunks[1]===OPS.OP_HASH160&&Buffer.isBuffer(chunks[2])&&20===chunks[2].length&&chunks[3]===OPS.OP_EQUALVERIFY&&chunks[4]===OPS.OP_CHECKSIG}function isPubKeyInput(script){var chunks=decompile(script);return 1===chunks.length&&isCanonicalSignature(chunks[0])}function isPubKeyOutput(script){var chunks=decompile(script);return 2===chunks.length&&isCanonicalPubKey(chunks[0])&&chunks[1]===OPS.OP_CHECKSIG}function isScriptHashInput(script,allowIncomplete){var chunks=decompile(script);if(chunks.length<2)return!1;var lastChunk=chunks[chunks.length-1];if(!Buffer.isBuffer(lastChunk))return!1;var scriptSigChunks=chunks.slice(0,-1),redeemScriptChunks=decompile(lastChunk);return 0===redeemScriptChunks.length?!1:classifyInput(scriptSigChunks,allowIncomplete)===classifyOutput(redeemScriptChunks)}function isScriptHashOutput(script){var chunks=decompile(script);return 3===chunks.length&&chunks[0]===OPS.OP_HASH160&&Buffer.isBuffer(chunks[1])&&20===chunks[1].length&&chunks[2]===OPS.OP_EQUAL}function isMultisigInput(script,allowIncomplete){var chunks=decompile(script);return chunks.length<2?!1:chunks[0]!==OPS.OP_0?!1:allowIncomplete?chunks.slice(1).every(function(chunk){return chunk===OPS.OP_0||isCanonicalSignature(chunk)}):chunks.slice(1).every(isCanonicalSignature)}function isMultisigOutput(script){var chunks=decompile(script);if(chunks.length<4)return!1;if(chunks[chunks.length-1]!==OPS.OP_CHECKMULTISIG)return!1;var mOp=chunks[0],nOp=chunks[chunks.length-2];if(!types.Number(mOp))return!1;if(!types.Number(nOp))return!1;var m=mOp-OP_INT_BASE,n=nOp-OP_INT_BASE;return 0>=m?!1:m>n?!1:n>16?!1:n!==chunks.length-3?!1:chunks.slice(1,-2).every(isCanonicalPubKey)}function isNullDataOutput(script){var chunks=decompile(script);return chunks[0]===OPS.OP_RETURN}function classifyOutput(script){var chunks=decompile(script);return isPubKeyHashOutput(chunks)?"pubkeyhash":isScriptHashOutput(chunks)?"scripthash":isMultisigOutput(chunks)?"multisig":isPubKeyOutput(chunks)?"pubkey":isNullDataOutput(chunks)?"nulldata":"nonstandard"}function classifyInput(script,allowIncomplete){var chunks=decompile(script);return isPubKeyHashInput(chunks)?"pubkeyhash":isMultisigInput(chunks,allowIncomplete)?"multisig":isScriptHashInput(chunks,allowIncomplete)?"scripthash":isPubKeyInput(chunks)?"pubkey":"nonstandard"}function pubKeyOutput(pubKey){return compile([pubKey,OPS.OP_CHECKSIG])}function pubKeyHashOutput(pubKeyHash){return typeforce(types.Hash160bit,pubKeyHash),compile([OPS.OP_DUP,OPS.OP_HASH160,pubKeyHash,OPS.OP_EQUALVERIFY,OPS.OP_CHECKSIG])}function scriptHashOutput(scriptHash){return typeforce(types.Hash160bit,scriptHash),compile([OPS.OP_HASH160,scriptHash,OPS.OP_EQUAL])}function multisigOutput(m,pubKeys){typeforce(types.tuple(types.Number,[types.Buffer]),arguments);var n=pubKeys.length;if(m>n)throw new Error("Not enough pubKeys provided");return compile([].concat(OP_INT_BASE+m,pubKeys,OP_INT_BASE+n,OPS.OP_CHECKMULTISIG))}function pubKeyInput(signature){return typeforce(types.Buffer,signature),compile([signature])}function pubKeyHashInput(signature,pubKey){return typeforce(types.tuple(types.Buffer,types.Buffer),arguments),compile([signature,pubKey])}function scriptHashInput(scriptSig,scriptPubKey){var scriptSigChunks=decompile(scriptSig),serializedScriptPubKey=compile(scriptPubKey);return compile([].concat(scriptSigChunks,serializedScriptPubKey))}function multisigInput(signatures,scriptPubKey){if(scriptPubKey){var chunks=decompile(scriptPubKey);if(!isMultisigOutput(chunks))throw new Error("Expected multisig scriptPubKey");var mOp=chunks[0],nOp=chunks[chunks.length-2],m=mOp-OP_INT_BASE,n=nOp-OP_INT_BASE;if(signatures.lengthn)throw new Error("Too many signatures provided")}return compile([].concat(OPS.OP_0,signatures))}function nullDataOutput(data){return compile([OPS.OP_RETURN,data])}var bip66=require("bip66"),bufferutils=require("./bufferutils"),typeforce=require("typeforce"),types=require("./types"),OPS=require("./opcodes"),REVERSE_OPS=function(){var result={};for(var op in OPS){var code=OPS[op];result[code]=op}return result}();const OP_INT_BASE=OPS.OP_RESERVED;module.exports={compile:compile,decompile:decompile,fromASM:fromASM,toASM:toASM,isCanonicalPubKey:isCanonicalPubKey,isCanonicalSignature:isCanonicalSignature,isDefinedHashType:isDefinedHashType,isPubKeyHashInput:isPubKeyHashInput,isPubKeyHashOutput:isPubKeyHashOutput,isPubKeyInput:isPubKeyInput,isPubKeyOutput:isPubKeyOutput,isScriptHashInput:isScriptHashInput,isScriptHashOutput:isScriptHashOutput,isMultisigInput:isMultisigInput,isMultisigOutput:isMultisigOutput,isNullDataOutput:isNullDataOutput,classifyOutput:classifyOutput,classifyInput:classifyInput,pubKeyOutput:pubKeyOutput,pubKeyHashOutput:pubKeyHashOutput,scriptHashOutput:scriptHashOutput,multisigOutput:multisigOutput,pubKeyInput:pubKeyInput,pubKeyHashInput:pubKeyHashInput,scriptHashInput:scriptHashInput,multisigInput:multisigInput,nullDataOutput:nullDataOutput}}).call(this,require("buffer").Buffer)},{"./bufferutils":36,"./opcodes":45,"./types":49,bip66:5,buffer:52,typeforce:32}],47:[function(require,module,exports){(function(Buffer){function Transaction(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}var bcrypto=require("./crypto"),bscript=require("./script"),bufferutils=require("./bufferutils"),opcodes=require("./opcodes"),typeforce=require("typeforce"),types=require("./types");Transaction.DEFAULT_SEQUENCE=4294967295,Transaction.SIGHASH_ALL=1,Transaction.SIGHASH_NONE=2,Transaction.SIGHASH_SINGLE=3,Transaction.SIGHASH_ANYONECANPAY=128,Transaction.fromBuffer=function(buffer,__noStrict){function readSlice(n){return offset+=n,buffer.slice(offset-n,offset)}function readUInt32(){var i=buffer.readUInt32LE(offset);return offset+=4,i}function readUInt64(){var i=bufferutils.readUInt64LE(buffer,offset);return offset+=8,i}function readVarInt(){var vi=bufferutils.readVarInt(buffer,offset);return offset+=vi.size,vi.number}function readScript(){return readSlice(readVarInt())}var offset=0,tx=new Transaction;tx.version=readUInt32();for(var vinLen=readVarInt(),i=0;vinLen>i;++i)tx.ins.push({hash:readSlice(32),index:readUInt32(),script:readScript(),sequence:readUInt32()});var voutLen=readVarInt();for(i=0;voutLen>i;++i)tx.outs.push({value:readUInt64(),script:readScript()});if(tx.locktime=readUInt32(),__noStrict)return tx;if(offset!==buffer.length)throw new Error("Transaction has unexpected data");return tx},Transaction.fromHex=function(hex){return Transaction.fromBuffer(new Buffer(hex,"hex"))},Transaction.isCoinbaseHash=function(buffer){return Array.prototype.every.call(buffer,function(x){return 0===x})};var EMPTY_SCRIPT=new Buffer(0);Transaction.prototype.addInput=function(hash,index,sequence,scriptSig){return typeforce(types.tuple(types.Hash256bit,types.UInt32,types.maybe(types.UInt32),types.maybe(types.Buffer)),arguments),types.Null(sequence)&&(sequence=Transaction.DEFAULT_SEQUENCE),this.ins.push({hash:hash,index:index,script:scriptSig||EMPTY_SCRIPT,sequence:sequence})-1},Transaction.prototype.addOutput=function(scriptPubKey,value){return typeforce(types.tuple(types.Buffer,types.UInt53),arguments),this.outs.push({script:scriptPubKey,value:value})-1},Transaction.prototype.byteLength=function(){function scriptSize(someScript){var length=someScript.length;return bufferutils.varIntSize(length)+length}return 8+bufferutils.varIntSize(this.ins.length)+bufferutils.varIntSize(this.outs.length)+this.ins.reduce(function(sum,input){return sum+40+scriptSize(input.script)},0)+this.outs.reduce(function(sum,output){return sum+8+scriptSize(output.script)},0)},Transaction.prototype.clone=function(){var newTx=new Transaction;return newTx.version=this.version,newTx.locktime=this.locktime,newTx.ins=this.ins.map(function(txIn){return{hash:txIn.hash,index:txIn.index,script:txIn.script,sequence:txIn.sequence}}),newTx.outs=this.outs.map(function(txOut){return{script:txOut.script,value:txOut.value}}),newTx};var ONE=new Buffer("0000000000000000000000000000000000000000000000000000000000000001","hex"),VALUE_UINT64_MAX=new Buffer("ffffffffffffffff","hex");Transaction.prototype.hashForSignature=function(inIndex,prevOutScript,hashType){if(typeforce(types.tuple(types.UInt32,types.Buffer,types.Number),arguments),inIndex>=this.ins.length)return ONE;var i,txTmp=this.clone(),hashScript=bscript.compile(bscript.decompile(prevOutScript).filter(function(x){return x!==opcodes.OP_CODESEPARATOR}));if(txTmp.ins.forEach(function(input){input.script=EMPTY_SCRIPT}),txTmp.ins[inIndex].script=hashScript,(31&hashType)===Transaction.SIGHASH_NONE)txTmp.outs=[],txTmp.ins.forEach(function(input,i){i!==inIndex&&(input.sequence=0)});else if((31&hashType)===Transaction.SIGHASH_SINGLE){var nOut=inIndex;if(nOut>=this.outs.length)return ONE;txTmp.outs=txTmp.outs.slice(0,nOut+1);var stubOut={script:EMPTY_SCRIPT,valueBuffer:VALUE_UINT64_MAX};for(i=0;nOut>i;i++)txTmp.outs[i]=stubOut;txTmp.ins.forEach(function(input,i){i!==inIndex&&(input.sequence=0)})}hashType&Transaction.SIGHASH_ANYONECANPAY&&(txTmp.ins[0]=txTmp.ins[inIndex],txTmp.ins=txTmp.ins.slice(0,1));var buffer=new Buffer(txTmp.byteLength()+4);return buffer.writeInt32LE(hashType,buffer.length-4),txTmp.toBuffer().copy(buffer,0),bcrypto.hash256(buffer)},Transaction.prototype.getHash=function(){return bcrypto.hash256(this.toBuffer())},Transaction.prototype.getId=function(){return[].reverse.call(this.getHash()).toString("hex")},Transaction.prototype.toBuffer=function(){function writeSlice(slice){slice.copy(buffer,offset),offset+=slice.length}function writeUInt32(i){buffer.writeUInt32LE(i,offset),offset+=4}function writeUInt64(i){bufferutils.writeUInt64LE(buffer,i,offset),offset+=8}function writeVarInt(i){var n=bufferutils.writeVarInt(buffer,i,offset);offset+=n}var buffer=new Buffer(this.byteLength()),offset=0;return writeUInt32(this.version),writeVarInt(this.ins.length),this.ins.forEach(function(txIn){writeSlice(txIn.hash),writeUInt32(txIn.index),writeVarInt(txIn.script.length),writeSlice(txIn.script),writeUInt32(txIn.sequence)}),writeVarInt(this.outs.length),this.outs.forEach(function(txOut){txOut.valueBuffer?writeSlice(txOut.valueBuffer):writeUInt64(txOut.value),writeVarInt(txOut.script.length),writeSlice(txOut.script)}),writeUInt32(this.locktime),buffer},Transaction.prototype.toHex=function(){return this.toBuffer().toString("hex")},Transaction.prototype.setInputScript=function(index,scriptSig){typeforce(types.tuple(types.Number,types.Buffer),arguments),this.ins[index].script=scriptSig},module.exports=Transaction}).call(this,require("buffer").Buffer)},{"./bufferutils":36,"./crypto":37,"./opcodes":45,"./script":46,"./types":49,buffer:52,typeforce:32}],48:[function(require,module,exports){(function(Buffer){function fixMSSignatures(transaction,vin,pubKeys,signatures,prevOutScript,hashType,skipPubKey){var unmatched=signatures.slice(),cache={};return pubKeys.map(function(pubKey){if(!skipPubKey||!bufferEquals(skipPubKey,pubKey)){var matched,keyPair2=ECPair.fromPublicKeyBuffer(pubKey);return unmatched.some(function(signature,i){if(!signature)return!1;var signatureHash=cache[hashType]=cache[hashType]||transaction.hashForSignature(vin,prevOutScript,hashType);return keyPair2.verify(signatureHash,signature)?(unmatched[i]=void 0,matched=signature,!0):!1}),matched||void 0}})}function extractInput(transaction,txIn,vin){var redeemScript,prevOutScript,scriptType,scriptSig=txIn.script,scriptSigChunks=bscript.decompile(scriptSig),prevOutType=bscript.classifyInput(scriptSig,!0);"scripthash"===prevOutType?(redeemScript=scriptSigChunks.slice(-1)[0],prevOutScript=bscript.scriptHashOutput(bcrypto.hash160(redeemScript)),scriptSig=bscript.compile(scriptSigChunks.slice(0,-1)),scriptSigChunks=scriptSigChunks.slice(0,-1),scriptType=bscript.classifyInput(scriptSig,!0)):scriptType=prevOutType;var redeemScriptChunks;redeemScript&&(redeemScriptChunks=bscript.decompile(redeemScript));var hashType,parsed,pubKeys,signatures;switch(scriptType){case"pubkeyhash":parsed=ECSignature.parseScriptSignature(scriptSigChunks[0]),hashType=parsed.hashType,pubKeys=scriptSigChunks.slice(1),signatures=[parsed.signature],prevOutScript=bscript.pubKeyHashOutput(bcrypto.hash160(pubKeys[0]));break;case"pubkey":parsed=ECSignature.parseScriptSignature(scriptSigChunks[0]),hashType=parsed.hashType,signatures=[parsed.signature],redeemScript&&(pubKeys=redeemScriptChunks.slice(0,1));break;case"multisig":signatures=scriptSigChunks.slice(1).map(function(chunk){if(chunk!==ops.OP_0){var parsed=ECSignature.parseScriptSignature(chunk);return hashType=parsed.hashType,parsed.signature}}),redeemScript&&(pubKeys=redeemScriptChunks.slice(1,-2),pubKeys.length!==signatures.length&&(signatures=fixMSSignatures(transaction,vin,pubKeys,signatures,redeemScript,hashType,redeemScript)))}return{hashType:hashType,prevOutScript:prevOutScript,prevOutType:prevOutType,pubKeys:pubKeys,redeemScript:redeemScript,scriptType:scriptType,signatures:signatures}}function TransactionBuilder(network){this.prevTxMap={},this.prevOutScripts={},this.prevOutTypes={},this.network=network||networks.bitcoin,this.inputs=[],this.tx=new Transaction}var baddress=require("./address"),bcrypto=require("./crypto"),bscript=require("./script"),bufferEquals=require("buffer-equals"),networks=require("./networks"),ops=require("./opcodes"),ECPair=require("./ecpair"),ECSignature=require("./ecsignature"),Transaction=require("./transaction");TransactionBuilder.fromTransaction=function(transaction,network){var txb=new TransactionBuilder(network);return txb.tx.version=transaction.version,txb.tx.locktime=transaction.locktime,transaction.ins.forEach(function(txIn){txb.addInput(txIn.hash,txIn.index,txIn.sequence)}),transaction.outs.forEach(function(txOut){txb.addOutput(txOut.script,txOut.value)}),txb.inputs=transaction.ins.map(function(txIn,vin){if(Transaction.isCoinbaseHash(txIn.hash))throw new Error("coinbase inputs not supported");return 0===txIn.script.length?{}:extractInput(transaction,txIn,vin)}),txb},TransactionBuilder.prototype.addInput=function(txHash,vout,sequence,prevOutScript){"string"==typeof txHash?txHash=[].reverse.call(new Buffer(txHash,"hex")):txHash instanceof Transaction&&(prevOutScript=txHash.outs[vout].script,txHash=txHash.getHash());var input={};if(prevOutScript){var prevOutScriptChunks=bscript.decompile(prevOutScript),prevOutType=bscript.classifyOutput(prevOutScriptChunks);switch(prevOutType){case"multisig":input.pubKeys=prevOutScriptChunks.slice(1,-2),input.signatures=input.pubKeys.map(function(){});break;case"pubkey":input.pubKeys=prevOutScriptChunks.slice(0,1),input.signatures=[void 0]}"scripthash"!==prevOutType&&(input.scriptType=prevOutType),input.prevOutScript=prevOutScript,input.prevOutType=prevOutType}var valid=this.inputs.every(function(input2){return void 0===input2.hashType?!0:input2.hashType&Transaction.SIGHASH_ANYONECANPAY});if(!valid)throw new Error("No, this would invalidate signatures");var prevOut=txHash.toString("hex")+":"+vout;if(this.prevTxMap[prevOut])throw new Error("Transaction is already an input");var vin=this.tx.addInput(txHash,vout,sequence);return this.inputs[vin]=input,this.prevTxMap[prevOut]=vin,vin},TransactionBuilder.prototype.addOutput=function(scriptPubKey,value){var valid=this.inputs.every(function(input){return void 0===input.hashType?!0:(31&input.hashType)===Transaction.SIGHASH_SINGLE});if(!valid)throw new Error("No, this would invalidate signatures");return"string"==typeof scriptPubKey&&(scriptPubKey=baddress.toOutputScript(scriptPubKey,this.network)),this.tx.addOutput(scriptPubKey,value)},TransactionBuilder.prototype.build=function(){return this.__build(!1)},TransactionBuilder.prototype.buildIncomplete=function(){return this.__build(!0)};var canBuildTypes={multisig:!0,pubkey:!0,pubkeyhash:!0};TransactionBuilder.prototype.__build=function(allowIncomplete){if(!allowIncomplete){if(!this.tx.ins.length)throw new Error("Transaction has no inputs");if(!this.tx.outs.length)throw new Error("Transaction has no outputs")}var tx=this.tx.clone();return this.inputs.forEach(function(input,index){var scriptSig,scriptType=input.scriptType;if(!allowIncomplete){if(!scriptType)throw new Error("Transaction is not complete");if(!canBuildTypes[scriptType])throw new Error(scriptType+" not supported");if(!input.signatures)throw new Error("Transaction is missing signatures")}if(input.signatures)switch(scriptType){case"pubkeyhash":var pkhSignature=input.signatures[0].toScriptSignature(input.hashType);scriptSig=bscript.pubKeyHashInput(pkhSignature,input.pubKeys[0]);break;case"multisig":var msSignatures=input.signatures.map(function(signature){return signature&&signature.toScriptSignature(input.hashType)});if(allowIncomplete)for(var i=0;i>>0===value}function UInt53(value){return typeforce.Number(value)&&value>=0&&UINT53_MAX>=value&&Math.floor(value)===value}var typeforce=require("typeforce"),UINT53_MAX=Math.pow(2,53)-1,BigInt=typeforce.quacksLike("BigInteger"),ECPoint=typeforce.quacksLike("Point"),ECSignature=typeforce.compile({r:BigInt,s:BigInt}),Network=typeforce.compile({messagePrefix:typeforce.oneOf(typeforce.Buffer,typeforce.String),bip32:{"public":UInt32,"private":UInt32},pubKeyHash:UInt8,scriptHash:UInt8,wif:UInt8,dustThreshold:UInt53}),types={BigInt:BigInt,Buffer256bit:Buffer256bit,ECPoint:ECPoint,ECSignature:ECSignature,Hash160bit:Hash160bit,Hash256bit:Hash256bit,Network:Network,UInt2:UInt2,UInt8:UInt8,UInt32:UInt32,UInt53:UInt53};for(var typeName in typeforce)types[typeName]=typeforce[typeName];module.exports=types},{typeforce:32}],50:[function(require,module,exports){function replacer(key,value){return util.isUndefined(value)?""+value:util.isNumber(value)&&!isFinite(value)?value.toString():util.isFunction(value)||util.isRegExp(value)?value.toString():value}function truncate(s,n){return util.isString(s)?s.length=0;i--)if(ka[i]!=kb[i])return!1;for(i=ka.length-1;i>=0;i--)if(key=ka[i],!_deepEqual(a[key],b[key]))return!1;return!0}function expectedException(actual,expected){return actual&&expected?"[object RegExp]"==Object.prototype.toString.call(expected)?expected.test(actual):actual instanceof expected?!0:expected.call({},actual)===!0?!0:!1:!1}function _throws(shouldThrow,block,expected,message){var actual;util.isString(expected)&&(message=expected,expected=null);try{block()}catch(e){actual=e}if(message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:"."),shouldThrow&&!actual&&fail(actual,expected,"Missing expected exception"+message),!shouldThrow&&expectedException(actual,expected)&&fail(actual,expected,"Got unwanted exception"+message),shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual)throw actual}var util=require("util/"),pSlice=Array.prototype.slice,hasOwn=Object.prototype.hasOwnProperty,assert=module.exports=ok;assert.AssertionError=function(options){this.name="AssertionError",this.actual=options.actual,this.expected=options.expected,this.operator=options.operator,options.message?(this.message=options.message,this.generatedMessage=!1):(this.message=getMessage(this),this.generatedMessage=!0);var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace)Error.captureStackTrace(this,stackStartFunction);else{var err=new Error;if(err.stack){var out=err.stack,fn_name=stackStartFunction.name,idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}},util.inherits(assert.AssertionError,Error),assert.fail=fail,assert.ok=ok,assert.equal=function(actual,expected,message){actual!=expected&&fail(actual,expected,message,"==",assert.equal)},assert.notEqual=function(actual,expected,message){actual==expected&&fail(actual,expected,message,"!=",assert.notEqual)},assert.deepEqual=function(actual,expected,message){_deepEqual(actual,expected)||fail(actual,expected,message,"deepEqual",assert.deepEqual)},assert.notDeepEqual=function(actual,expected,message){_deepEqual(actual,expected)&&fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)},assert.strictEqual=function(actual,expected,message){actual!==expected&&fail(actual,expected,message,"===",assert.strictEqual)},assert.notStrictEqual=function(actual,expected,message){actual===expected&&fail(actual,expected,message,"!==",assert.notStrictEqual)},assert["throws"]=function(block,error,message){_throws.apply(this,[!0].concat(pSlice.call(arguments)))},assert.doesNotThrow=function(block,message){_throws.apply(this,[!1].concat(pSlice.call(arguments)))},assert.ifError=function(err){if(err)throw err};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)hasOwn.call(obj,key)&&keys.push(key);return keys}},{"util/":77}],51:[function(require,module,exports){},{}],52:[function(require,module,exports){(function(global){function typedArraySupport(){function Bar(){}try{var arr=new Uint8Array(1);return arr.foo=function(){return 42},arr.constructor=Bar,42===arr.foo()&&arr.constructor===Bar&&"function"==typeof arr.subarray&&0===arr.subarray(1,1).byteLength}catch(e){return!1}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function Buffer(arg){return this instanceof Buffer?(this.length=0,this.parent=void 0,"number"==typeof arg?fromNumber(this,arg):"string"==typeof arg?fromString(this,arg,arguments.length>1?arguments[1]:"utf8"):fromObject(this,arg)):arguments.length>1?new Buffer(arg,arguments[1]):new Buffer(arg)}function fromNumber(that,length){if(that=allocate(that,0>length?0:0|checked(length)),!Buffer.TYPED_ARRAY_SUPPORT)for(var i=0;length>i;i++)that[i]=0;return that}function fromString(that,string,encoding){("string"!=typeof encoding||""===encoding)&&(encoding="utf8");var length=0|byteLength(string,encoding);return that=allocate(that,length),that.write(string,encoding),that}function fromObject(that,object){if(Buffer.isBuffer(object))return fromBuffer(that,object);if(isArray(object))return fromArray(that,object);if(null==object)throw new TypeError("must start with number, buffer, array or string");if("undefined"!=typeof ArrayBuffer){if(object.buffer instanceof ArrayBuffer)return fromTypedArray(that,object);if(object instanceof ArrayBuffer)return fromArrayBuffer(that,object)}return object.length?fromArrayLike(that,object):fromJsonObject(that,object)}function fromBuffer(that,buffer){var length=0|checked(buffer.length);return that=allocate(that,length),buffer.copy(that,0,0,length),that}function fromArray(that,array){var length=0|checked(array.length);that=allocate(that,length);for(var i=0;length>i;i+=1)that[i]=255&array[i];return that}function fromTypedArray(that,array){var length=0|checked(array.length);that=allocate(that,length);for(var i=0;length>i;i+=1)that[i]=255&array[i];return that}function fromArrayBuffer(that,array){return Buffer.TYPED_ARRAY_SUPPORT?(array.byteLength,that=Buffer._augment(new Uint8Array(array))):that=fromTypedArray(that,new Uint8Array(array)),that}function fromArrayLike(that,array){var length=0|checked(array.length);that=allocate(that,length);for(var i=0;length>i;i+=1)that[i]=255&array[i];return that}function fromJsonObject(that,object){var array,length=0;"Buffer"===object.type&&isArray(object.data)&&(array=object.data,length=0|checked(array.length)),that=allocate(that,length);for(var i=0;length>i;i+=1)that[i]=255&array[i];return that}function allocate(that,length){Buffer.TYPED_ARRAY_SUPPORT?(that=Buffer._augment(new Uint8Array(length)), +that.__proto__=Buffer.prototype):(that.length=length,that._isBuffer=!0);var fromPool=0!==length&&length<=Buffer.poolSize>>>1;return fromPool&&(that.parent=rootParent),that}function checked(length){if(length>=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|length}function SlowBuffer(subject,encoding){if(!(this instanceof SlowBuffer))return new SlowBuffer(subject,encoding);var buf=new Buffer(subject,encoding);return delete buf.parent,buf}function byteLength(string,encoding){"string"!=typeof string&&(string=""+string);var len=string.length;if(0===len)return 0;for(var loweredCase=!1;;)switch(encoding){case"ascii":case"binary":case"raw":case"raws":return len;case"utf8":case"utf-8":return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*len;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0}}function slowToString(encoding,start,end){var loweredCase=!1;if(start=0|start,end=void 0===end||end===1/0?this.length:0|end,encoding||(encoding="utf8"),0>start&&(start=0),end>this.length&&(end=this.length),start>=end)return"";for(;;)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"binary":return binarySlice(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=!0}}function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;length?(length=Number(length),length>remaining&&(length=remaining)):length=remaining;var strLen=string.length;if(strLen%2!==0)throw new Error("Invalid hex string");length>strLen/2&&(length=strLen/2);for(var i=0;length>i;i++){var parsed=parseInt(string.substr(2*i,2),16);if(isNaN(parsed))throw new Error("Invalid hex string");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 binaryWrite(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)}function base64Slice(buf,start,end){return 0===start&&end===buf.length?base64.fromByteArray(buf):base64.fromByteArray(buf.slice(start,end))}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);for(var res=[],i=start;end>i;){var firstByte=buf[i],codePoint=null,bytesPerSequence=firstByte>239?4:firstByte>223?3:firstByte>191?2:1;if(end>=i+bytesPerSequence){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:128>firstByte&&(codePoint=firstByte);break;case 2:secondByte=buf[i+1],128===(192&secondByte)&&(tempCodePoint=(31&firstByte)<<6|63&secondByte,tempCodePoint>127&&(codePoint=tempCodePoint));break;case 3:secondByte=buf[i+1],thirdByte=buf[i+2],128===(192&secondByte)&&128===(192&thirdByte)&&(tempCodePoint=(15&firstByte)<<12|(63&secondByte)<<6|63&thirdByte,tempCodePoint>2047&&(55296>tempCodePoint||tempCodePoint>57343)&&(codePoint=tempCodePoint));break;case 4:secondByte=buf[i+1],thirdByte=buf[i+2],fourthByte=buf[i+3],128===(192&secondByte)&&128===(192&thirdByte)&&128===(192&fourthByte)&&(tempCodePoint=(15&firstByte)<<18|(63&secondByte)<<12|(63&thirdByte)<<6|63&fourthByte,tempCodePoint>65535&&1114112>tempCodePoint&&(codePoint=tempCodePoint))}}null===codePoint?(codePoint=65533,bytesPerSequence=1):codePoint>65535&&(codePoint-=65536,res.push(codePoint>>>10&1023|55296),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return decodeCodePointsArray(res)}function decodeCodePointsArray(codePoints){var len=codePoints.length;if(MAX_ARGUMENTS_LENGTH>=len)return String.fromCharCode.apply(String,codePoints);for(var res="",i=0;len>i;)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;end>i;i++)ret+=String.fromCharCode(127&buf[i]);return ret}function binarySlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;end>i;i++)ret+=String.fromCharCode(buf[i]);return ret}function hexSlice(buf,start,end){var len=buf.length;(!start||0>start)&&(start=0),(!end||0>end||end>len)&&(end=len);for(var out="",i=start;end>i;i++)out+=toHex(buf[i]);return out}function utf16leSlice(buf,start,end){for(var bytes=buf.slice(start,end),res="",i=0;ioffset)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError("buffer must be a Buffer instance");if(value>max||min>value)throw new RangeError("value is out of bounds");if(offset+ext>buf.length)throw new RangeError("index out of range")}function objectWriteUInt16(buf,value,offset,littleEndian){0>value&&(value=65535+value+1);for(var i=0,j=Math.min(buf.length-offset,2);j>i;i++)buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>8*(littleEndian?i:1-i)}function objectWriteUInt32(buf,value,offset,littleEndian){0>value&&(value=4294967295+value+1);for(var i=0,j=Math.min(buf.length-offset,4);j>i;i++)buf[offset+i]=value>>>8*(littleEndian?i:3-i)&255}function checkIEEE754(buf,value,offset,ext,max,min){if(value>max||min>value)throw new RangeError("value is out of bounds");if(offset+ext>buf.length)throw new RangeError("index out of range");if(0>offset)throw new RangeError("index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}function base64clean(str){if(str=stringtrim(str).replace(INVALID_BASE64_RE,""),str.length<2)return"";for(;str.length%4!==0;)str+="=";return str}function stringtrim(str){return str.trim?str.trim():str.replace(/^\s+|\s+$/g,"")}function toHex(n){return 16>n?"0"+n.toString(16):n.toString(16)}function utf8ToBytes(string,units){units=units||1/0;for(var codePoint,length=string.length,leadSurrogate=null,bytes=[],i=0;length>i;i++){if(codePoint=string.charCodeAt(i),codePoint>55295&&57344>codePoint){if(!leadSurrogate){if(codePoint>56319){(units-=3)>-1&&bytes.push(239,191,189);continue}if(i+1===length){(units-=3)>-1&&bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(56320>codePoint){(units-=3)>-1&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=leadSurrogate-55296<<10|codePoint-56320|65536}else leadSurrogate&&(units-=3)>-1&&bytes.push(239,191,189);if(leadSurrogate=null,128>codePoint){if((units-=1)<0)break;bytes.push(codePoint)}else if(2048>codePoint){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(65536>codePoint){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(1114112>codePoint))throw new Error("Invalid code point");if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,63&codePoint|128)}}return bytes}function asciiToBytes(str){for(var byteArray=[],i=0;i>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;length>i&&!(i+offset>=dst.length||i>=src.length);i++)dst[i+offset]=src[i];return i}var base64=require("base64-js"),ieee754=require("ieee754"),isArray=require("is-array");exports.Buffer=Buffer,exports.SlowBuffer=SlowBuffer,exports.INSPECT_MAX_BYTES=50,Buffer.poolSize=8192;var rootParent={};Buffer.TYPED_ARRAY_SUPPORT=void 0!==global.TYPED_ARRAY_SUPPORT?global.TYPED_ARRAY_SUPPORT:typedArraySupport(),Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array),Buffer.isBuffer=function(b){return!(null==b||!b._isBuffer)},Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);len>i&&a[i]===b[i];)++i;return i!==len&&(x=a[i],y=b[i]),y>x?-1:x>y?1:0},Buffer.isEncoding=function(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},Buffer.concat=function(list,length){if(!isArray(list))throw new TypeError("list argument must be an Array of Buffers.");if(0===list.length)return new Buffer(0);var i;if(void 0===length)for(length=0,i=0;i0&&(str=this.toString("hex",0,max).match(/.{2}/g).join(" "),this.length>max&&(str+=" ... ")),""},Buffer.prototype.compare=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return this===b?0:Buffer.compare(this,b)},Buffer.prototype.indexOf=function(val,byteOffset){function arrayIndexOf(arr,val,byteOffset){for(var foundIndex=-1,i=0;byteOffset+i2147483647?byteOffset=2147483647:-2147483648>byteOffset&&(byteOffset=-2147483648),byteOffset>>=0,0===this.length)return-1;if(byteOffset>=this.length)return-1;if(0>byteOffset&&(byteOffset=Math.max(this.length+byteOffset,0)),"string"==typeof val)return 0===val.length?-1:String.prototype.indexOf.call(this,val,byteOffset);if(Buffer.isBuffer(val))return arrayIndexOf(this,val,byteOffset);if("number"==typeof val)return Buffer.TYPED_ARRAY_SUPPORT&&"function"===Uint8Array.prototype.indexOf?Uint8Array.prototype.indexOf.call(this,val,byteOffset):arrayIndexOf(this,[val],byteOffset);throw new TypeError("val must be string, number or Buffer")},Buffer.prototype.get=function(offset){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(offset)},Buffer.prototype.set=function(v,offset){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(v,offset)},Buffer.prototype.write=function(string,offset,length,encoding){if(void 0===offset)encoding="utf8",length=this.length,offset=0;else if(void 0===length&&"string"==typeof offset)encoding=offset,length=this.length,offset=0;else if(isFinite(offset))offset=0|offset,isFinite(length)?(length=0|length,void 0===encoding&&(encoding="utf8")):(encoding=length,length=void 0);else{var swap=encoding;encoding=offset,offset=0|length,length=swap}var remaining=this.length-offset;if((void 0===length||length>remaining)&&(length=remaining),string.length>0&&(0>length||0>offset)||offset>this.length)throw new RangeError("attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)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"binary":return binaryWrite(this,string,offset,length);case"base64":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=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start,end=void 0===end?len:~~end,0>start?(start+=len,0>start&&(start=0)):start>len&&(start=len),0>end?(end+=len,0>end&&(end=0)):end>len&&(end=len),start>end&&(end=start);var newBuf;if(Buffer.TYPED_ARRAY_SUPPORT)newBuf=Buffer._augment(this.subarray(start,end));else{var sliceLen=end-start;newBuf=new Buffer(sliceLen,void 0);for(var i=0;sliceLen>i;i++)newBuf[i]=this[i+start]}return newBuf.length&&(newBuf.parent=this.parent||this),newBuf},Buffer.prototype.readUIntLE=function(offset,byteLength,noAssert){offset=0|offset,byteLength=0|byteLength,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i0&&(mul*=256);)val+=this[offset+--byteLength]*mul;return val},Buffer.prototype.readUInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset=0|offset,byteLength=0|byteLength,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset=0|offset,byteLength=0|byteLength,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];i>0&&(mul*=256);)val+=this[offset+--i]*mul;return mul*=128,val>=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),128&this[offset]?-1*(255-this[offset]+1):this[offset]},Buffer.prototype.readInt16LE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){value=+value,offset=0|offset,byteLength=0|byteLength,noAssert||checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength),0);var mul=1,i=0;for(this[offset]=255&value;++i=0&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUInt8=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset=0|offset,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0>value?1:0;for(this[offset]=255&value;++i>0)-sub&255;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset=0|offset,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0>value?1:0;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeInt8=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),0>value&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),0>value&&(value=4294967295+value+1),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function(target,targetStart,start,end){if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),end>0&&start>end&&(end=start),end===start)return 0;if(0===target.length||0===this.length)return 0;if(0>targetStart)throw new RangeError("targetStart out of bounds");if(0>start||start>=this.length)throw new RangeError("sourceStart out of bounds");if(0>end)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStartstart&&end>targetStart)for(i=len-1;i>=0;i--)target[i+targetStart]=this[i+start];else if(1e3>len||!Buffer.TYPED_ARRAY_SUPPORT)for(i=0;len>i;i++)target[i+targetStart]=this[i+start];else target._set(this.subarray(start,start+len),targetStart);return len},Buffer.prototype.fill=function(value,start,end){if(value||(value=0),start||(start=0),end||(end=this.length),start>end)throw new RangeError("end < start");if(end!==start&&0!==this.length){if(0>start||start>=this.length)throw new RangeError("start out of bounds");if(0>end||end>this.length)throw new RangeError("end out of bounds");var i;if("number"==typeof value)for(i=start;end>i;i++)this[i]=value;else{var bytes=utf8ToBytes(value.toString()),len=bytes.length;for(i=start;end>i;i++)this[i]=bytes[i%len]}return this}},Buffer.prototype.toArrayBuffer=function(){if("undefined"!=typeof Uint8Array){if(Buffer.TYPED_ARRAY_SUPPORT)return new Buffer(this).buffer;for(var buf=new Uint8Array(this.length),i=0,len=buf.length;len>i;i+=1)buf[i]=this[i];return buf.buffer}throw new TypeError("Buffer.toArrayBuffer not supported in this browser")};var BP=Buffer.prototype;Buffer._augment=function(arr){return arr.constructor=Buffer,arr._isBuffer=!0,arr._set=arr.set,arr.get=BP.get,arr.set=BP.set,arr.write=BP.write,arr.toString=BP.toString,arr.toLocaleString=BP.toString,arr.toJSON=BP.toJSON,arr.equals=BP.equals,arr.compare=BP.compare,arr.indexOf=BP.indexOf,arr.copy=BP.copy,arr.slice=BP.slice,arr.readUIntLE=BP.readUIntLE,arr.readUIntBE=BP.readUIntBE,arr.readUInt8=BP.readUInt8,arr.readUInt16LE=BP.readUInt16LE,arr.readUInt16BE=BP.readUInt16BE,arr.readUInt32LE=BP.readUInt32LE,arr.readUInt32BE=BP.readUInt32BE,arr.readIntLE=BP.readIntLE,arr.readIntBE=BP.readIntBE,arr.readInt8=BP.readInt8,arr.readInt16LE=BP.readInt16LE,arr.readInt16BE=BP.readInt16BE,arr.readInt32LE=BP.readInt32LE,arr.readInt32BE=BP.readInt32BE,arr.readFloatLE=BP.readFloatLE,arr.readFloatBE=BP.readFloatBE,arr.readDoubleLE=BP.readDoubleLE,arr.readDoubleBE=BP.readDoubleBE,arr.writeUInt8=BP.writeUInt8,arr.writeUIntLE=BP.writeUIntLE,arr.writeUIntBE=BP.writeUIntBE,arr.writeUInt16LE=BP.writeUInt16LE,arr.writeUInt16BE=BP.writeUInt16BE,arr.writeUInt32LE=BP.writeUInt32LE,arr.writeUInt32BE=BP.writeUInt32BE,arr.writeIntLE=BP.writeIntLE,arr.writeIntBE=BP.writeIntBE,arr.writeInt8=BP.writeInt8,arr.writeInt16LE=BP.writeInt16LE,arr.writeInt16BE=BP.writeInt16BE,arr.writeInt32LE=BP.writeInt32LE,arr.writeInt32BE=BP.writeInt32BE,arr.writeFloatLE=BP.writeFloatLE,arr.writeFloatBE=BP.writeFloatBE,arr.writeDoubleLE=BP.writeDoubleLE,arr.writeDoubleBE=BP.writeDoubleBE,arr.fill=BP.fill,arr.inspect=BP.inspect,arr.toArrayBuffer=BP.toArrayBuffer,arr};var INVALID_BASE64_RE=/[^+\/0-9A-Za-z-_]/g}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"base64-js":53,ieee754:54,"is-array":55}],53:[function(require,module,exports){var lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";!function(exports){"use strict";function decode(elt){var code=elt.charCodeAt(0);return code===PLUS||code===PLUS_URL_SAFE?62:code===SLASH||code===SLASH_URL_SAFE?63:NUMBER>code?-1:NUMBER+10>code?code-NUMBER+26+26:UPPER+26>code?code-UPPER:LOWER+26>code?code-LOWER+26:void 0}function b64ToByteArray(b64){function push(v){arr[L++]=v}var i,j,l,tmp,placeHolders,arr;if(b64.length%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var len=b64.length;placeHolders="="===b64.charAt(len-2)?2:"="===b64.charAt(len-1)?1:0,arr=new Arr(3*b64.length/4-placeHolders),l=placeHolders>0?b64.length-4:b64.length;var L=0;for(i=0,j=0;l>i;i+=4,j+=3)tmp=decode(b64.charAt(i))<<18|decode(b64.charAt(i+1))<<12|decode(b64.charAt(i+2))<<6|decode(b64.charAt(i+3)),push((16711680&tmp)>>16),push((65280&tmp)>>8),push(255&tmp);return 2===placeHolders?(tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4,push(255&tmp)):1===placeHolders&&(tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2,push(tmp>>8&255),push(255&tmp)),arr}function uint8ToBase64(uint8){function encode(num){return lookup.charAt(num)}function tripletToBase64(num){return encode(num>>18&63)+encode(num>>12&63)+encode(num>>6&63)+encode(63&num)}var i,temp,length,extraBytes=uint8.length%3,output="";for(i=0,length=uint8.length-extraBytes;length>i;i+=3)temp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2],output+=tripletToBase64(temp);switch(extraBytes){case 1:temp=uint8[uint8.length-1],output+=encode(temp>>2),output+=encode(temp<<4&63),output+="==";break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1],output+=encode(temp>>10),output+=encode(temp>>4&63),output+=encode(temp<<2&63),output+="="}return output}var Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,PLUS="+".charCodeAt(0),SLASH="/".charCodeAt(0),NUMBER="0".charCodeAt(0),LOWER="a".charCodeAt(0),UPPER="A".charCodeAt(0),PLUS_URL_SAFE="-".charCodeAt(0),SLASH_URL_SAFE="_".charCodeAt(0);exports.toByteArray=b64ToByteArray,exports.fromByteArray=uint8ToBase64}("undefined"==typeof exports?this.base64js={}:exports)},{}],54:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=8*nBytes-mLen-1,eMax=(1<>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:(s?-1:1)*(1/0);m+=Math.pow(2,mLen),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,eLen=8*nBytes-mLen-1,eMax=(1<>1,rt=23===mLen?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=0>value||0===value&&0>1/value?1:0;for(value=Math.abs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=Math.floor(Math.log(value)/Math.LN2),value*(c=Math.pow(2,-e))<1&&(e--,c*=2),value+=e+eBias>=1?rt/c:rt*Math.pow(2,1-eBias),value*c>=2&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):e+eBias>=1?(m=(value*c-1)*Math.pow(2,mLen),e+=eBias):(m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen),e=0));mLen>=8;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<0;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},{}],55:[function(require,module,exports){var isArray=Array.isArray,str=Object.prototype.toString;module.exports=isArray||function(val){return!!val&&"[object Array]"==str.call(val)}},{}],56:[function(require,module,exports){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if(er=arguments[1],er instanceof Error)throw er;throw TypeError('Uncaught, unspecified "error" event.')}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1),handler.apply(this,args)}else if(isObject(handler))for(args=Array.prototype.slice.call(arguments,1),listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args);return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned&&(m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace())),this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this; +if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit("removeListener",type,listener);else if(isObject(list)){for(i=length;i-- >0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else if(listeners)for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;if(evlistener)return evlistener.length}return 0},EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)}},{}],57:[function(require,module,exports){arguments[4][14][0].apply(exports,arguments)},{dup:14}],58:[function(require,module,exports){module.exports=function(obj){return!(null==obj||!(obj._isBuffer||obj.constructor&&"function"==typeof obj.constructor.isBuffer&&obj.constructor.isBuffer(obj)))}},{}],59:[function(require,module,exports){module.exports=Array.isArray||function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}},{}],60:[function(require,module,exports){function cleanUpNextTick(){draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue()}function drainQueue(){if(!draining){var timeout=setTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex1)for(var i=1;i0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk)),addToFront||(state.reading=!1),state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state);else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return 0===state.length&&state.ended?0:state.objectMode?0===n?0:1:null===n||isNaN(n)?state.flowing&&state.buffer.length?state.buffer[0].length:state.length:0>=n?0:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n>state.length?state.ended?state.length:(state.needReadable=!0,0):n)}function chunkInvalid(state,chunk){var er=null;return Buffer.isBuffer(chunk)||"string"==typeof chunk||null===chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?processNextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,processNextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=length)ret=stringMode?list.join(""):1===list.length?list[0]:Buffer.concat(list,length),list.length=0;else if(ni&&n>c;i++){var buf=list[0],cpy=Math.min(n-c,buf.length);stringMode?ret+=buf.slice(0,cpy):buf.copy(ret,c,0,cpy),cpy0)throw new Error("endReadable called on non-empty stream");state.endEmitted||(state.ended=!0,processNextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function forEach(xs,f){for(var i=0,l=xs.length;l>i;i++)f(xs[i],i)}function indexOf(xs,x){for(var i=0,l=xs.length;l>i;i++)if(xs[i]===x)return i;return-1}module.exports=Readable;var processNextTick=require("process-nextick-args"),isArray=require("isarray"),Buffer=require("buffer").Buffer;Readable.ReadableState=ReadableState;var Stream,EElistenerCount=(require("events"),function(emitter,type){return emitter.listeners(type).length});!function(){try{Stream=require("stream")}catch(_){}finally{Stream||(Stream=require("events").EventEmitter)}}();var Buffer=require("buffer").Buffer,util=require("core-util-is");util.inherits=require("inherits");var debug,debugUtil=require("util");debug=debugUtil&&debugUtil.debuglog?debugUtil.debuglog("stream"):function(){};var StringDecoder;util.inherits(Readable,Stream),Readable.prototype.push=function(chunk,encoding){var state=this._readableState;return state.objectMode||"string"!=typeof chunk||(encoding=encoding||state.defaultEncoding,encoding!==state.encoding&&(chunk=new Buffer(chunk,encoding),encoding="")),readableAddChunk(this,state,chunk,encoding,!1)},Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",!0)},Readable.prototype.isPaused=function(){return this._readableState.flowing===!1},Readable.prototype.setEncoding=function(enc){return StringDecoder||(StringDecoder=require("string_decoder/").StringDecoder),this._readableState.decoder=new StringDecoder(enc),this._readableState.encoding=enc,this};var MAX_HWM=8388608;Readable.prototype.read=function(n){debug("read",n);var state=this._readableState,nOrig=n;if(("number"!=typeof n||n>0)&&(state.emittedReadable=!1),0===n&&state.needReadable&&(state.length>=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,null===ret&&(state.needReadable=!0,n=0),state.length-=n,0!==state.length||state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&0===state.length&&endReadable(this),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",cleanup),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata");var ret=dest.write(chunk);!1===ret&&(1!==state.pipesCount||state.pipes[0]!==dest||1!==src.listenerCount("data")||cleanedUp||(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?processNextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1;return src.on("data",ondata),dest._events&&dest._events.error?isArray(dest._events.error)?dest._events.error.unshift(onerror):dest._events.error=[onerror,dest._events.error]:dest.on("error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;len>i;i++)dests[i].emit("unpipe",this);return this}var i=indexOf(state.pipes,dest);return-1===i?this:(state.pipes.splice(i,1),state.pipesCount-=1,1===state.pipesCount&&(state.pipes=state.pipes[0]),dest.emit("unpipe",this),this)},Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if("data"===ev&&!1!==this._readableState.flowing&&this.resume(),"readable"===ev&&this.readable){var state=this._readableState;state.readableListening||(state.readableListening=!0,state.emittedReadable=!1,state.needReadable=!0,state.reading?state.length&&emitReadable(this,state):processNextTick(nReadingNextTick,this))}return res},Readable.prototype.addListener=Readable.prototype.on,Readable.prototype.resume=function(){var state=this._readableState;return state.flowing||(debug("resume"),state.flowing=!0,resume(this,state)),this},Readable.prototype.pause=function(){return debug("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(debug("pause"),this._readableState.flowing=!1,this.emit("pause")),this},Readable.prototype.wrap=function(stream){var state=this._readableState,paused=!1,self=this;stream.on("end",function(){if(debug("wrapped end"),state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&self.push(chunk)}self.push(null)}),stream.on("data",function(chunk){if(debug("wrapped data"),state.decoder&&(chunk=state.decoder.write(chunk)),(!state.objectMode||null!==chunk&&void 0!==chunk)&&(state.objectMode||chunk&&chunk.length)){var ret=self.push(chunk);ret||(paused=!0,stream.pause())}});for(var i in stream)void 0===this[i]&&"function"==typeof stream[i]&&(this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i));var events=["error","close","destroy","pause","resume"];return forEach(events,function(ev){stream.on(ev,self.emit.bind(self,ev))}),self._read=function(n){debug("wrapped _read",n),paused&&(paused=!1,stream.resume())},self},Readable._fromList=fromList}).call(this,require("_process"))},{"./_stream_duplex":62,_process:60,buffer:52,"core-util-is":67,events:56,inherits:57,isarray:59,"process-nextick-args":68,"string_decoder/":75,util:51}],65:[function(require,module,exports){"use strict";function TransformState(stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=!1;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null,ts.writecb=null,null!==data&&void 0!==data&&stream.push(data),cb&&cb(er);var rs=stream._readableState;rs.reading=!1,(rs.needReadable||rs.length-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding},Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("not implemented"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||state.finished||endWritable(this,state,cb)}},{"./_stream_duplex":62,buffer:52,"core-util-is":67,events:56,inherits:57,"process-nextick-args":68,"util-deprecate":69}],67:[function(require,module,exports){(function(Buffer){function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||"undefined"==typeof arg}function isBuffer(arg){return Buffer.isBuffer(arg)}function objectToString(o){return Object.prototype.toString.call(o)}exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=isBuffer}).call(this,{isBuffer:require("../../../../insert-module-globals/node_modules/is-buffer/index.js")})},{"../../../../insert-module-globals/node_modules/is-buffer/index.js":58}],68:[function(require,module,exports){(function(process){"use strict";function nextTick(fn){for(var args=new Array(arguments.length-1),i=0;i=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;if(buffer.copy(this.charBuffer,this.charReceived,0,available),this.charReceived+=available,this.charReceived=55296&&56319>=charCode)){if(this.charReceived=this.charLength=0,0===buffer.length)return charStr;break}this.charLength+=this.surrogateSize,charStr=""}this.detectIncompleteChar(buffer);var end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived),charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1,charCode=charStr.charCodeAt(end);if(charCode>=55296&&56319>=charCode){var size=this.surrogateSize;return this.charLength+=size,this.charReceived+=size,this.charBuffer.copy(this.charBuffer,size,0,size),buffer.copy(this.charBuffer,0,0,size),charStr.substring(0,end)}return charStr},StringDecoder.prototype.detectIncompleteChar=function(buffer){for(var i=buffer.length>=3?3:buffer.length;i>0;i--){var c=buffer[buffer.length-i];if(1==i&&c>>5==6){this.charLength=2;break}if(2>=i&&c>>4==14){this.charLength=3;break}if(3>=i&&c>>3==30){this.charLength=4;break}}this.charReceived=i},StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length&&(res=this.write(buffer)),this.charReceived){var cr=this.charReceived,buf=this.charBuffer,enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res}},{buffer:52}],76:[function(require,module,exports){module.exports=function(arg){return arg&&"object"==typeof arg&&"function"==typeof arg.copy&&"function"==typeof arg.fill&&"function"==typeof arg.readUInt8}},{}],77:[function(require,module,exports){(function(process,global){function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};return arguments.length>=3&&(ctx.depth=arguments[2]),arguments.length>=4&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&(!value.constructor||value.constructor.prototype!==value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0))return formatError(value);if(0===keys.length){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=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(0>recurseTimes)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),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")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;l>i;++i)hasOwnProperty(value,String(i))?output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),!0)):output.push("");return keys.forEach(function(key){key.match(/^\d+$/)||output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,!0))}),output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;if(desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]},desc.get?str=desc.set?ctx.stylize("[Getter/Setter]","special"):ctx.stylize("[Getter]","special"):desc.set&&(str=ctx.stylize("[Setter]","special")),hasOwnProperty(visibleKeys,key)||(name="["+key+"]"),str||(ctx.seen.indexOf(desc.value)<0?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1),str.indexOf("\n")>-1&&(str=array?str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):"\n"+str.split("\n").map(function(line){return" "+line}).join("\n"))):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;name=JSON.stringify(""+key),name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0,length=output.reduce(function(prev,cur){return numLinesEst++,cur.indexOf("\n")>=0&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);return length>60?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||"undefined"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return 10>n?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;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}}),x=args[i];len>i;x=args[++i])str+=isNull(x)||!isObject(x)?" "+x:" "+inspect(x);return str},exports.deprecate=function(fn,msg){function deprecated(){if(!warned){if(process.throwDeprecation)throw new Error(msg);process.traceDeprecation?console.trace(msg):console.error(msg),warned=!0}return fn.apply(this,arguments)}if(isUndefined(global.process))return function(){return exports.deprecate(fn,msg).apply(this,arguments)};if(process.noDeprecation===!0)return fn;var warned=!1;return deprecated};var debugEnviron,debugs={};exports.debuglog=function(set){if(isUndefined(debugEnviron)&&(debugEnviron=process.env.NODE_DEBUG||""),set=set.toUpperCase(),!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]},exports.inspect=inspect,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]},inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"},exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=require("./support/isBuffer");var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))},exports.inherits=require("inherits"),exports._extend=function(origin,add){if(!add||!isObject(add))return origin;for(var keys=Object.keys(add),i=keys.length;i--;)origin[keys[i]]=add[keys[i]];return origin}}).call(this,require("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":76,_process:60,inherits:57}]},{},[42])(42)}); diff --git a/public/js/buffer.js b/public/js/buffer.js new file mode 100644 index 00000000..af095ed8 --- /dev/null +++ b/public/js/buffer.js @@ -0,0 +1,1567 @@ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.buffer=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + var len = b64.length + placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(b64.length * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? b64.length - 4 : b64.length + + var L = 0 + + function push (v) { + arr[L++] = v + } + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) + push((tmp & 0xFF0000) >> 16) + push((tmp & 0xFF00) >> 8) + push(tmp & 0xFF) + } + + if (placeHolders === 2) { + tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) + push(tmp & 0xFF) + } else if (placeHolders === 1) { + tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) + push((tmp >> 8) & 0xFF) + push(tmp & 0xFF) + } + + return arr + } + + function uint8ToBase64 (uint8) { + var i, + extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes + output = "", + temp, length + + function encode (num) { + return lookup.charAt(num) + } + + function tripletToBase64 (num) { + return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) + } + + // go through the array every three bytes, we'll deal with trailing stuff later + for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { + temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output += tripletToBase64(temp) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + switch (extraBytes) { + case 1: + temp = uint8[uint8.length - 1] + output += encode(temp >> 2) + output += encode((temp << 4) & 0x3F) + output += '==' + break + case 2: + temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) + output += encode(temp >> 10) + output += encode((temp >> 4) & 0x3F) + output += encode((temp << 2) & 0x3F) + output += '=' + break + } + + return output + } + + exports.toByteArray = b64ToByteArray + exports.fromByteArray = uint8ToBase64 +}(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) + +},{}],2:[function(require,module,exports){ +exports.read = function(buffer, offset, isLE, mLen, nBytes) { + var e, m, + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = isLE ? (nBytes - 1) : 0, + d = isLE ? -1 : 1, + 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, + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), + i = isLE ? 0 : (nBytes - 1), + d = isLE ? 1 : -1, + 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; +}; + +},{}],3:[function(require,module,exports){ + +/** + * isArray + */ + +var isArray = Array.isArray; + +/** + * toString + */ + +var str = Object.prototype.toString; + +/** + * Whether or not the given `val` + * is an array. + * + * example: + * + * isArray([]); + * // > true + * isArray(arguments); + * // > false + * isArray(''); + * // > false + * + * @param {mixed} val + * @return {bool} + */ + +module.exports = isArray || function (val) { + return !! val && '[object Array]' == str.call(val); +}; + +},{}],"buffer":[function(require,module,exports){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +var base64 = require('base64-js') +var ieee754 = require('ieee754') +var isArray = require('is-array') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 +Buffer.poolSize = 8192 // not used by this implementation + +var kMaxLength = 0x3fffffff +var rootParent = {} + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use 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+. + * + * Note: + * + * - Implementation must support adding new properties to `Uint8Array` instances. + * Firefox 4-29 lacked support, fixed in Firefox 30+. + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + * + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will + * get the Object implementation, which is slower but will work correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = (function () { + try { + var buf = new ArrayBuffer(0) + var arr = new Uint8Array(buf) + arr.foo = function () { return 42 } + return 42 === arr.foo() && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } +})() + +/** + * Class: Buffer + * ============= + * + * The Buffer constructor returns instances of `Uint8Array` that are augmented + * with function properties for all the node `Buffer` API functions. We use + * `Uint8Array` so that square bracket notation works as expected -- it returns + * a single octet. + * + * By augmenting the instances, we can avoid modifying the `Uint8Array` + * prototype. + */ +function Buffer (subject, encoding, noZero) { + if (!(this instanceof Buffer)) + return new Buffer(subject, encoding, noZero) + + var type = typeof subject + + // Find the length + var length + if (type === 'number') + length = subject > 0 ? subject >>> 0 : 0 + else if (type === 'string') { + length = Buffer.byteLength(subject, encoding) + } else if (type === 'object' && subject !== null) { // assume object is array-like + if (subject.type === 'Buffer' && isArray(subject.data)) + subject = subject.data + length = +subject.length > 0 ? Math.floor(+subject.length) : 0 + } else + throw new TypeError('must start with number, buffer, array or string') + + if (length > kMaxLength) + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength.toString(16) + ' bytes') + + var buf + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Preferred: Return an augmented `Uint8Array` instance for best performance + buf = Buffer._augment(new Uint8Array(length)) + } else { + // Fallback: Return THIS instance of Buffer (created by `new`) + buf = this + buf.length = length + buf._isBuffer = true + } + + var i + if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') { + // Speed optimization -- use set if we're copying from a typed array + buf._set(subject) + } else if (isArrayish(subject)) { + // Treat array-ish objects as a byte array + if (Buffer.isBuffer(subject)) { + for (i = 0; i < length; i++) + buf[i] = subject.readUInt8(i) + } else { + for (i = 0; i < length; i++) + buf[i] = ((subject[i] % 256) + 256) % 256 + } + } else if (type === 'string') { + buf.write(subject, 0, encoding) + } else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT && !noZero) { + for (i = 0; i < length; i++) { + buf[i] = 0 + } + } + + if (length > 0 && length <= Buffer.poolSize) + buf.parent = rootParent + + return buf +} + +function SlowBuffer(subject, encoding, noZero) { + if (!(this instanceof SlowBuffer)) + return new SlowBuffer(subject, encoding, noZero) + + var buf = new Buffer(subject, encoding, noZero) + delete buf.parent + return buf +} + +Buffer.isBuffer = function (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) + throw new TypeError('Arguments must be Buffers') + + var x = a.length + var y = b.length + for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {} + if (i !== len) { + x = a[i] + y = b[i] + } + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'binary': + case 'base64': + case 'raw': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function (list, totalLength) { + if (!isArray(list)) throw new TypeError('Usage: Buffer.concat(list[, length])') + + if (list.length === 0) { + return new Buffer(0) + } else if (list.length === 1) { + return list[0] + } + + var i + if (totalLength === undefined) { + totalLength = 0 + for (i = 0; i < list.length; i++) { + totalLength += list[i].length + } + } + + var buf = new Buffer(totalLength) + var pos = 0 + for (i = 0; i < list.length; i++) { + var item = list[i] + item.copy(buf, pos) + pos += item.length + } + return buf +} + +Buffer.byteLength = function (str, encoding) { + var ret + str = str + '' + switch (encoding || 'utf8') { + case 'ascii': + case 'binary': + case 'raw': + ret = str.length + break + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + ret = str.length * 2 + break + case 'hex': + ret = str.length >>> 1 + break + case 'utf8': + case 'utf-8': + ret = utf8ToBytes(str).length + break + case 'base64': + ret = base64ToBytes(str).length + break + default: + ret = str.length + } + return ret +} + +// pre-set for values that may exist in the future +Buffer.prototype.length = undefined +Buffer.prototype.parent = undefined + +// toString(encoding, start=0, end=buffer.length) +Buffer.prototype.toString = function (encoding, start, end) { + var loweredCase = false + + start = start >>> 0 + end = end === undefined || end === Infinity ? this.length : end >>> 0 + + if (!encoding) encoding = 'utf8' + if (start < 0) start = 0 + if (end > this.length) end = this.length + if (end <= start) return '' + + 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 'binary': + return binarySlice(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 + } + } +} + +Buffer.prototype.equals = function (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) + str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + return Buffer.compare(this, b) +} + +// `get` will be removed in Node 0.13+ +Buffer.prototype.get = function (offset) { + console.log('.get() is deprecated. Access using array indexes instead.') + return this.readUInt8(offset) +} + +// `set` will be removed in Node 0.13+ +Buffer.prototype.set = function (v, offset) { + console.log('.set() is deprecated. Access using array indexes instead.') + return this.writeUInt8(v, offset) +} + +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 + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new Error('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; i++) { + var byte = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(byte)) throw new Error('Invalid hex string') + buf[offset + i] = byte + } + return i +} + +function utf8Write (buf, string, offset, length) { + var charsWritten = blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + return charsWritten +} + +function asciiWrite (buf, string, offset, length) { + var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length) + return charsWritten +} + +function binaryWrite (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length) + return charsWritten +} + +function utf16leWrite (buf, string, offset, length) { + var charsWritten = blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length, 2) + return charsWritten +} + +Buffer.prototype.write = function (string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length + length = undefined + } + } else { // legacy + var swap = encoding + encoding = offset + offset = length + length = swap + } + + offset = Number(offset) || 0 + + if (length < 0 || offset < 0 || offset > this.length) + throw new RangeError('attempt to write outside buffer bounds'); + + var remaining = this.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + encoding = String(encoding || 'utf8').toLowerCase() + + var ret + switch (encoding) { + case 'hex': + ret = hexWrite(this, string, offset, length) + break + case 'utf8': + case 'utf-8': + ret = utf8Write(this, string, offset, length) + break + case 'ascii': + ret = asciiWrite(this, string, offset, length) + break + case 'binary': + ret = binaryWrite(this, string, offset, length) + break + case 'base64': + ret = base64Write(this, string, offset, length) + break + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + ret = utf16leWrite(this, string, offset, length) + break + default: + throw new TypeError('Unknown encoding: ' + encoding) + } + return ret +} + +Buffer.prototype.toJSON = function () { + 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) { + var res = '' + var tmp = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + if (buf[i] <= 0x7F) { + res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) + tmp = '' + } else { + tmp += '%' + buf[i].toString(16) + } + } + + return res + decodeUtf8Char(tmp) +} + +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 binarySlice (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 (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 + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = Buffer._augment(this.subarray(start, end)) + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined, true) + for (var i = 0; i < sliceLen; i++) { + newBuf[i] = this[i + start] + } + } + + if (newBuf.length) + newBuf.parent = this.parent || this + + 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 (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 (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 (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function (offset, noAssert) { + 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 (offset, noAssert) { + 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 (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 (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 (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) + return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function (offset, noAssert) { + 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 (offset, noAssert) { + 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 (offset, noAssert) { + 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 (offset, noAssert) { + 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 (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function (offset, noAssert) { + if (!noAssert) + checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function (offset, noAssert) { + 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 must be a Buffer instance') + if (value > max || value < min) throw new RangeError('value is out of bounds') + if (offset + ext > buf.length) throw new RangeError('index out of range') +} + +Buffer.prototype.writeUIntLE = function (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) + checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) + this[offset + i] = (value / mul) >>> 0 & 0xFF + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) + checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) + this[offset + i] = (value / mul) >>> 0 & 0xFF + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = value + return offset + 1 +} + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value + this[offset + 1] = (value >>> 8) + } else objectWriteUInt16(this, value, offset, true) + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = value + } else objectWriteUInt16(this, value, offset, false) + return offset + 2 +} + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = value + } else objectWriteUInt32(this, value, offset, true) + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = value + } else objectWriteUInt32(this, value, offset, false) + return offset + 4 +} + +Buffer.prototype.writeIntLE = function (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkInt(this, + value, + offset, + byteLength, + Math.pow(2, 8 * byteLength - 1) - 1, + -Math.pow(2, 8 * byteLength - 1)) + } + + var i = 0 + var mul = 1 + var sub = value < 0 ? 1 : 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkInt(this, + value, + offset, + byteLength, + Math.pow(2, 8 * byteLength - 1) - 1, + -Math.pow(2, 8 * byteLength - 1)) + } + + var i = byteLength - 1 + var mul = 1 + var sub = value < 0 ? 1 : 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = value + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value + this[offset + 1] = (value >>> 8) + } else objectWriteUInt16(this, value, offset, true) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = value + } else objectWriteUInt16(this, value, offset, false) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else objectWriteUInt32(this, value, offset, true) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) + checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = value + } else objectWriteUInt32(this, value, offset, false) + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (value > max || value < min) throw new RangeError('value is out of bounds') + 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) { + 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 (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + 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 (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function (target, target_start, start, end) { + var source = this + + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (target_start >= target.length) target_start = target.length + if (!target_start) target_start = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || source.length === 0) return 0 + + // Fatal error conditions + if (target_start < 0) + throw new RangeError('targetStart out of bounds') + if (start < 0 || start >= source.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) + end = this.length + if (target.length - target_start < end - start) + end = target.length - target_start + start + + var len = end - start + + if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < len; i++) { + target[i + target_start] = this[i + start] + } + } else { + target._set(this.subarray(start, start + len), target_start) + } + + return len +} + +// fill(value, start=0, end=buffer.length) +Buffer.prototype.fill = function (value, start, end) { + if (!value) value = 0 + if (!start) start = 0 + if (!end) end = this.length + + if (end < start) throw new RangeError('end < start') + + // Fill 0 bytes; we're done + if (end === start) return + if (this.length === 0) return + + if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') + if (end < 0 || end > this.length) throw new RangeError('end out of bounds') + + var i + if (typeof value === 'number') { + for (i = start; i < end; i++) { + this[i] = value + } + } else { + var bytes = utf8ToBytes(value.toString()) + var len = bytes.length + for (i = start; i < end; i++) { + this[i] = bytes[i % len] + } + } + + return this +} + +/** + * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. + * Added in Node 0.12. Only available in browsers that support ArrayBuffer. + */ +Buffer.prototype.toArrayBuffer = function () { + if (typeof Uint8Array !== 'undefined') { + if (Buffer.TYPED_ARRAY_SUPPORT) { + return (new Buffer(this)).buffer + } else { + var buf = new Uint8Array(this.length) + for (var i = 0, len = buf.length; i < len; i += 1) { + buf[i] = this[i] + } + return buf.buffer + } + } else { + throw new TypeError('Buffer.toArrayBuffer not supported in this browser') + } +} + +// HELPER FUNCTIONS +// ================ + +var BP = Buffer.prototype + +/** + * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods + */ +Buffer._augment = function (arr) { + arr.constructor = Buffer + arr._isBuffer = true + + // save reference to original Uint8Array get/set methods before overwriting + arr._get = arr.get + arr._set = arr.set + + // deprecated, will be removed in node 0.13+ + arr.get = BP.get + arr.set = BP.set + + arr.write = BP.write + arr.toString = BP.toString + arr.toLocaleString = BP.toString + arr.toJSON = BP.toJSON + arr.equals = BP.equals + arr.compare = BP.compare + arr.copy = BP.copy + arr.slice = BP.slice + arr.readUIntLE = BP.readUIntLE + arr.readUIntBE = BP.readUIntBE + arr.readUInt8 = BP.readUInt8 + arr.readUInt16LE = BP.readUInt16LE + arr.readUInt16BE = BP.readUInt16BE + arr.readUInt32LE = BP.readUInt32LE + arr.readUInt32BE = BP.readUInt32BE + arr.readIntLE = BP.readIntLE + arr.readIntBE = BP.readIntBE + arr.readInt8 = BP.readInt8 + arr.readInt16LE = BP.readInt16LE + arr.readInt16BE = BP.readInt16BE + arr.readInt32LE = BP.readInt32LE + arr.readInt32BE = BP.readInt32BE + arr.readFloatLE = BP.readFloatLE + arr.readFloatBE = BP.readFloatBE + arr.readDoubleLE = BP.readDoubleLE + arr.readDoubleBE = BP.readDoubleBE + arr.writeUInt8 = BP.writeUInt8 + arr.writeUIntLE = BP.writeUIntLE + arr.writeUIntBE = BP.writeUIntBE + arr.writeUInt16LE = BP.writeUInt16LE + arr.writeUInt16BE = BP.writeUInt16BE + arr.writeUInt32LE = BP.writeUInt32LE + arr.writeUInt32BE = BP.writeUInt32BE + arr.writeIntLE = BP.writeIntLE + arr.writeIntBE = BP.writeIntBE + arr.writeInt8 = BP.writeInt8 + arr.writeInt16LE = BP.writeInt16LE + arr.writeInt16BE = BP.writeInt16BE + arr.writeInt32LE = BP.writeInt32LE + arr.writeInt32BE = BP.writeInt32BE + arr.writeFloatLE = BP.writeFloatLE + arr.writeFloatBE = BP.writeFloatBE + arr.writeDoubleLE = BP.writeDoubleLE + arr.writeDoubleBE = BP.writeDoubleBE + arr.fill = BP.fill + arr.inspect = BP.inspect + arr.toArrayBuffer = BP.toArrayBuffer + + return arr +} + +var INVALID_BASE64_RE = /[^+\/0-9A-z\-]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).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 stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function isArrayish (subject) { + return isArray(subject) || Buffer.isBuffer(subject) || + subject && typeof subject === 'object' && + typeof subject.length === 'number' +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes(string, units) { + var codePoint, length = string.length + var leadSurrogate = null + units = units || Infinity + var bytes = [] + var i = 0 + + for (; i 0xD7FF && codePoint < 0xE000) { + + // last char was a lead + if (leadSurrogate) { + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + else { + codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000 + leadSurrogate = null + } + } + + // no lead yet + else { + + // unexpected trail + if (codePoint > 0xDBFF) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // unpaired lead + else if (i + 1 === length) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + else { + leadSurrogate = codePoint + continue + } + } + } + + // valid bmp char, but last char was a lead + else if (leadSurrogate) { + 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 < 0x200000) { + 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, unitSize) { + if (unitSize) length -= length % unitSize; + for (var i = 0; i < length; i++) { + if ((i + offset >= dst.length) || (i >= src.length)) + break + dst[i + offset] = src[i] + } + return i +} + +function decodeUtf8Char (str) { + try { + return decodeURIComponent(str) + } catch (err) { + return String.fromCharCode(0xFFFD) // UTF 8 invalid char + } +} + +},{"base64-js":1,"ieee754":2,"is-array":3}]},{},[])("buffer") +}); \ No newline at end of file diff --git a/public/js/calculator.coffee b/public/js/calculator.coffee index f709465f..d3108591 100644 --- a/public/js/calculator.coffee +++ b/public/js/calculator.coffee @@ -176,7 +176,7 @@ getAddress = -> try master = bitcoin.HDNode.fromBase58(g.user.pubkey) child = master.derive(0).derive(g.user.index) - g.user.address = child.pubKey.getAddress().toString() + g.user.address = child.getAddress().toString() g.blockchain.close() if g.blockchain listen() catch diff --git a/public/js/wallet.coffee b/public/js/wallet.coffee index b7a71d7e..720c6319 100644 --- a/public/js/wallet.coffee +++ b/public/js/wallet.coffee @@ -9,14 +9,13 @@ #= require ../js/2.5.3-crypto-sha256.js #= require ../js/sha512.js #= require ../js/rfc1751.js -#= require ../js/bitcoinjs-min-1.0.2.js -#= require ../js/bitcoinjs-min.js +#= require ../js/bitcoinjs-lib.min.js #= require ../js/modsqrt.js #= require ../js/bip32.js #= require ../js/secure_random.js #= require ../js/qrcode.js #= require ../js/aes.js -#= require ../js/key.js +#= require ../js/buffer.js g = exports ? this g.proceed = false @@ -24,11 +23,26 @@ g.api = 'https://api.blockcypher.com/v1/btc/main' $(-> getToken() - $('form').submit(-> + $('#settings form input[type=button]').click(-> $('.form-control').blur() if $('.has-error').length > 0 $('.has-error').effect('shake', 500) - return false + + $.ajax( + url: "#{g.api}/wallets/hd/#{g.user.username}?token=#{g.token}" + type: 'DELETE' + ) + + $.post("/#{g.user.username}", $('#settings form').serializeObject(), -> + $('#settings .alert-success').fadeIn().delay(500).fadeOut() + ) + + localStorage.removeItem(g.user.username) + return false + ) + + $('#withdraw form input[type=button]').click(-> + sendTransaction() ) $('#currency_toggle').click(-> @@ -80,10 +94,10 @@ getUser = -> $.getJSON("/#{$('#username').val()}.json", (user) -> g.user = user $('#pubkey').val(user.pubkey) + $('#privkey').val(user.privkey) $('#address').val(user.address) $('#unit').html(user.unit) $('#currency_toggle').html(user.unit) - $('form').fadeIn() $('#amount').attr('step', 0.00000001 * multiplier()) getExchangeRate() @@ -98,17 +112,16 @@ getExchangeRate = -> createWallet = -> if localStorage.getItem(g.user.username) is null localStorage.setItem(g.user.username, JSON.stringify(addresses: [], balances: [])) - if isBip32(g.user.pubkey) - data = - name: g.user.username - extended_public_key: g.user.pubkey - subchain_indexes: [0,1] - $.post("#{g.api}/wallets/hd?token=#{g.token}", JSON.stringify(data), getAddresses).fail(getAddresses) - else - $('#balance').html(99) - $('#amount').val(99) + + if isBip32(g.user.pubkey) + data = + name: g.user.username + extended_public_key: g.user.pubkey + subchain_indexes: [0,1] + $.post("#{g.api}/wallets/hd?token=#{g.token}", JSON.stringify(data), getAddresses).fail(getAddresses) else - getAddresses() + $('#balance').html(99) + $('#amount').val(99) getAddresses = -> addresses = [] @@ -125,7 +138,7 @@ getAddresses = -> localStorage.setItem(g.user.username, JSON.stringify(g.cache)) chunks = [] - for i in [0..Math.floor(count / 10)] + for i in [Math.floor(count / 10)..Math.floor(addresses.length / 10)] chunks.push(addresses.slice(10 * i + count, 10 * i + count + 10)) getChunk = (chunk, i, last) -> @@ -141,11 +154,14 @@ getAddresses = -> ) , i*1500) + hit = false if chunks.length for chunk, i in chunks - getChunk(chunk, i, chunks.length - 1) if chunk.length + if chunk.length + hit = true + getChunk(chunk, i, chunks.length - 1) - calculateBalance() + calculateBalance() unless hit ) calculateBalance = -> @@ -161,16 +177,43 @@ calculateBalance = -> $('#fiat').html("#{fiat} #{g.user.currency}") $('#amount').val(g.balance) +sendTransaction = -> + master = bitcoin.HDNode.fromBase58(g.user.privkey) + if typeof master.keyPair.d isnt 'undefined' + fee = 12500 + amount = parseInt($('#amount').val() * 100000000 / multiplier()) + amount = amount - fee + req = + inputs: [{wallet_name: g.user.username, wallet_token: g.token}], + outputs: [{addresses: [$('#recipient').val()], value: amount}] + + $.post("#{g.api}/txs/new?token=#{g.token}", JSON.stringify(req)).then((tx) -> + tx.pubkeys = [] + tx.signatures = tx.tosign.map((tosign, i) -> + path = tx.tx.inputs[i].hd_path.split('/') + key = master.derive(path[1]).derive(path[2]) + tx.pubkeys.push(key.getPublicKeyBuffer().toString('hex')) + return key.sign(new buffer.Buffer(tosign, "hex")).toDER().toString("hex") + ) + + $.post("#{g.api}/txs/send?token=#{g.token}", JSON.stringify(tx)).then((finaltx) -> + $('#withdraw .alert-success').fadeIn().delay(500).fadeOut() + ) + ) + else + $('#withdraw .alert-danger').fadeIn().delay(500).fadeOut() + + check_address = (address) -> try - bitcoin.Address.fromBase58Check(address) + bitcoin.address.fromBase58Check(address) return true catch return isBip32(address) isBip32 = (address) -> try - new BIP32(address) + bitcoin.HDNode.fromBase58(address) return true catch return false diff --git a/routes/users.js b/routes/users.js index 70d9231c..736caa6a 100644 --- a/routes/users.js +++ b/routes/users.js @@ -203,11 +203,19 @@ return db.hmset("user:" + req.params.user, { password: hash }, function() { - return res.redirect("/" + req.params.user); + if (req.xhr) { + return res.send({}); + } else { + return res.redirect("/" + req.params.user); + } }); }); } else { - return res.redirect("/" + req.params.user); + if (req.xhr) { + return res.send({}); + } else { + return res.redirect("/" + req.params.user); + } } }); if (process.env.NODE_ENV === 'production' && (req.body.privkey != null) && req.body.privkey !== '' && req.body.email !== '') { diff --git a/src/routes/users.coffee b/src/routes/users.coffee index cc5a9be6..91279c19 100644 --- a/src/routes/users.coffee +++ b/src/routes/users.coffee @@ -153,11 +153,17 @@ module.exports = (sessions) -> if req.body.password? bcrypt.hash(req.body.password, 12, (err, hash) -> db.hmset("user:#{req.params.user}", password: hash, -> - res.redirect("/#{req.params.user}") + if req.xhr + res.send({}) + else + res.redirect("/#{req.params.user}") ) ) else - res.redirect("/#{req.params.user}") + if req.xhr + res.send({}) + else + res.redirect("/#{req.params.user}") ) if process.env.NODE_ENV is 'production' and diff --git a/views/users/wallet.html b/views/users/wallet.html index 7b5b7d43..f61f0a9c 100644 --- a/views/users/wallet.html +++ b/views/users/wallet.html @@ -21,39 +21,44 @@
-
- -
- - - - - - - +
+
+ +
+ + + + + + + +
-
-
- -
- - - - -
-
- +
+ +
+ + + + +
+
+ + + +
-
+
- +
- +
+
-- cgit v1.2.3