9 lines
195 KiB
JavaScript
9 lines
195 KiB
JavaScript
/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||
var base={},taproot={},secp={},hashmini={};!function(){function assertNumber(n){if(!Number.isSafeInteger(n))throw new Error("Wrong integer: ".concat(n))}function chain(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];var wrap=function(a,b){return function(c){return a(b(c))}};return{encode:Array.from(args).reverse().reduce((function(acc,i){return acc?wrap(acc,i.encode):i.encode}),void 0),decode:args.reduce((function(acc,i){return acc?wrap(acc,i.decode):i.decode}),void 0)}}function alphabet(alphabet){return{encode:function(digits){if(!Array.isArray(digits)||digits.length&&"number"!=typeof digits[0])throw new Error("alphabet.encode input should be an array of numbers");return digits.map((function(i){if(assertNumber(i),i<0||i>=alphabet.length)throw new Error("Digit index outside alphabet: ".concat(i," (alphabet: ").concat(alphabet.length,")"));return alphabet[i]}))},decode:function(input){if(!Array.isArray(input)||input.length&&"string"!=typeof input[0])throw new Error("alphabet.decode input should be array of strings");return input.map((function(letter){if("string"!=typeof letter)throw new Error("alphabet.decode: not string element=".concat(letter));var index=alphabet.indexOf(letter);if(-1===index)throw new Error('Unknown letter: "'.concat(letter,'". Allowed: ').concat(alphabet));return index}))}}}function join(separator){if(void 0===separator&&(separator=""),"string"!=typeof separator)throw new Error("join separator should be string");return{encode:function(from){if(!Array.isArray(from)||from.length&&"string"!=typeof from[0])throw new Error("join.encode input should be array of strings");for(var _i=0,from_1=from;_i<from_1.length;_i++){var i=from_1[_i];if("string"!=typeof i)throw new Error("join.encode: non-string input=".concat(i))}return from.join(separator)},decode:function(to){if("string"!=typeof to)throw new Error("join.decode input should be string");return to.split(separator)}}}function padding(bits,chr){if(void 0===chr&&(chr="="),assertNumber(bits),"string"!=typeof chr)throw new Error("padding chr should be string");return{encode:function(data){if(!Array.isArray(data)||data.length&&"string"!=typeof data[0])throw new Error("padding.encode input should be array of strings");for(var _i=0,data_1=data;_i<data_1.length;_i++){var i=data_1[_i];if("string"!=typeof i)throw new Error("padding.encode: non-string input=".concat(i))}for(;data.length*bits%8;)data.push(chr);return data},decode:function(input){if(!Array.isArray(input)||input.length&&"string"!=typeof input[0])throw new Error("padding.encode input should be array of strings");for(var _i=0,input_1=input;_i<input_1.length;_i++){var i=input_1[_i];if("string"!=typeof i)throw new Error("padding.decode: non-string input=".concat(i))}var end=input.length;if(end*bits%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;end>0&&input[end-1]===chr;end--)if(!((end-1)*bits%8))throw new Error("Invalid padding: string has too much padding");return input.slice(0,end)}}}function normalize(fn){if("function"!=typeof fn)throw new Error("normalize fn should be function");return{encode:function(from){return from},decode:function(to){return fn(to)}}}function convertRadix(data,from,to){if(from<2)throw new Error("convertRadix: wrong from=".concat(from,", base cannot be less than 2"));if(to<2)throw new Error("convertRadix: wrong to=".concat(to,", base cannot be less than 2"));if(!Array.isArray(data))throw new Error("convertRadix: data should be array");if(!data.length)return[];var pos=0,res=[],digits=Array.from(data);for(digits.forEach((function(d){if(assertNumber(d),d<0||d>=from)throw new Error("Wrong integer: ".concat(d))}));;){for(var carry=0,done=!0,i=pos;i<digits.length;i++){var digit=digits[i],digitBase=from*carry+digit;if(!Number.isSafeInteger(digitBase)||from*carry/from!==carry||digitBase-digit!=from*carry)throw new Error("convertRadix: carry overflow");if(carry=digitBase%to,digits[i]=Math.floor(digitBase/to),!Number.isSafeInteger(digits[i])||digits[i]*to+carry!==digitBase)throw new Error("convertRadix: carry overflow");done&&(digits[i]?done=!1:pos=i)}if(res.push(carry),done)break}for(i=0;i<data.length-1&&0===data[i];i++)res.push(0);return res.reverse()}base.bytes=base.stringToBytes=base.str=base.bytesToString=base.hex=base.utf8=base.bech32m=base.bech32=base.base58check=base.base58xmr=base.base58xrp=base.base58flickr=base.base58=base.base64url=base.base64=base.base32crockford=base.base32hex=base.base32=base.base16=base.utils=base.assertNumber=void 0,base.assertNumber=assertNumber;var gcd=function(a,b){return b?gcd(b,a%b):a},radix2carry=function(from,to){return from+(to-gcd(from,to))};function convertRadix2(data,from,to,padding){if(!Array.isArray(data))throw new Error("convertRadix2: data should be array");if(from<=0||from>32)throw new Error("convertRadix2: wrong from=".concat(from));if(to<=0||to>32)throw new Error("convertRadix2: wrong to=".concat(to));if(radix2carry(from,to)>32)throw new Error("convertRadix2: carry overflow from=".concat(from," to=").concat(to," carryBits=").concat(radix2carry(from,to)));for(var carry=0,pos=0,mask=Math.pow(2,to)-1,res=[],_i=0,data_2=data;_i<data_2.length;_i++){var n=data_2[_i];if(assertNumber(n),n>=Math.pow(2,from))throw new Error("convertRadix2: invalid data word=".concat(n," from=").concat(from));if(carry=carry<<from|n,pos+from>32)throw new Error("convertRadix2: carry overflow pos=".concat(pos," from=").concat(from));for(pos+=from;pos>=to;pos-=to)res.push((carry>>pos-to&mask)>>>0);carry&=Math.pow(2,pos)-1}if(carry=carry<<to-pos&mask,!padding&&pos>=from)throw new Error("Excess padding");if(!padding&&carry)throw new Error("Non-zero padding: ".concat(carry));return padding&&pos>0&&res.push(carry>>>0),res}function radix(num){return assertNumber(num),{encode:function(bytes){if(!(bytes instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return convertRadix(Array.from(bytes),Math.pow(2,8),num)},decode:function(digits){if(!Array.isArray(digits)||digits.length&&"number"!=typeof digits[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(convertRadix(digits,num,Math.pow(2,8)))}}}function radix2(bits,revPadding){if(void 0===revPadding&&(revPadding=!1),assertNumber(bits),bits<=0||bits>32)throw new Error("radix2: bits should be in (0..32]");if(radix2carry(8,bits)>32||radix2carry(bits,8)>32)throw new Error("radix2: carry overflow");return{encode:function(bytes){if(!(bytes instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return convertRadix2(Array.from(bytes),8,bits,!revPadding)},decode:function(digits){if(!Array.isArray(digits)||digits.length&&"number"!=typeof digits[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(convertRadix2(digits,bits,8,revPadding))}}}function unsafeWrapper(fn){if("function"!=typeof fn)throw new Error("unsafeWrapper fn should be function");return function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];try{return fn.apply(null,args)}catch(e){}}}function checksum(len,fn){if(assertNumber(len),"function"!=typeof fn)throw new Error("checksum fn should be function");return{encode:function(data){if(!(data instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");var checksum=fn(data).slice(0,len),res=new Uint8Array(data.length+len);return res.set(data),res.set(checksum,data.length),res},decode:function(data){if(!(data instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");for(var payload=data.slice(0,-len),newChecksum=fn(payload).slice(0,len),oldChecksum=data.slice(-len),i=0;i<len;i++)if(newChecksum[i]!==oldChecksum[i])throw new Error("Invalid checksum");return payload}}}base.utils={alphabet:alphabet,chain:chain,checksum:checksum,radix:radix,radix2:radix2,join:join,padding:padding},base.base16=chain(radix2(4),alphabet("0123456789ABCDEF"),join("")),base.base32=chain(radix2(5),alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),padding(5),join("")),base.base32hex=chain(radix2(5),alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"),padding(5),join("")),base.base32crockford=chain(radix2(5),alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),join(""),normalize((function(s){return s.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")}))),base.base64=chain(radix2(6),alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),padding(6),join("")),base.base64url=chain(radix2(6),alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),padding(6),join(""));var genBase58=function(abc){return chain(radix(58),alphabet(abc),join(""))};base.base58=genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),base.base58flickr=genBase58("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),base.base58xrp=genBase58("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");var XMR_BLOCK_LEN=[0,2,3,5,6,7,9,10,11];base.base58xmr={encode:function(data){for(var res="",i=0;i<data.length;i+=8){var block=data.subarray(i,i+8);res+=base.base58.encode(block).padStart(XMR_BLOCK_LEN[block.length],"1")}return res},decode:function(str){for(var res=[],i=0;i<str.length;i+=11){for(var slice=str.slice(i,i+11),blockLen=XMR_BLOCK_LEN.indexOf(slice.length),block=base.base58.decode(slice),j=0;j<block.length-blockLen;j++)if(0!==block[j])throw new Error("base58xmr: wrong padding");res=res.concat(Array.from(block.slice(block.length-blockLen)))}return Uint8Array.from(res)}};base.base58check=function(sha256){return chain(checksum(4,(function(data){return sha256(sha256(data))})),base.base58)};var BECH_ALPHABET=chain(alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),join("")),POLYMOD_GENERATORS=[996825010,642813549,513874426,1027748829,705979059];function bech32Polymod(pre){for(var b=pre>>25,chk=(33554431&pre)<<5,i=0;i<POLYMOD_GENERATORS.length;i++)1==(b>>i&1)&&(chk^=POLYMOD_GENERATORS[i]);return chk}function bechChecksum(prefix,words,encodingConst){void 0===encodingConst&&(encodingConst=1);for(var len=prefix.length,chk=1,i=0;i<len;i++){var c=prefix.charCodeAt(i);if(c<33||c>126)throw new Error("Invalid prefix (".concat(prefix,")"));chk=bech32Polymod(chk)^c>>5}chk=bech32Polymod(chk);for(i=0;i<len;i++)chk=bech32Polymod(chk)^31&prefix.charCodeAt(i);for(var _i=0,words_1=words;_i<words_1.length;_i++){var v=words_1[_i];chk=bech32Polymod(chk)^v}for(i=0;i<6;i++)chk=bech32Polymod(chk);return chk^=encodingConst,BECH_ALPHABET.encode(convertRadix2([chk%Math.pow(2,30)],30,5,!1))}function genBech32(encoding){var ENCODING_CONST="bech32"===encoding?1:734539939,_words=radix2(5),fromWords=_words.decode,toWords=_words.encode,fromWordsUnsafe=unsafeWrapper(fromWords);function decode(str,limit){if(void 0===limit&&(limit=90),"string"!=typeof str)throw new Error("bech32.decode input should be string, not ".concat(typeof str));if(str.length<8||!1!==limit&&str.length>limit)throw new TypeError("Wrong string length: ".concat(str.length," (").concat(str,"). Expected (8..").concat(limit,")"));var lowered=str.toLowerCase();if(str!==lowered&&str!==str.toUpperCase())throw new Error("String must be lowercase or uppercase");var sepIndex=(str=lowered).lastIndexOf("1");if(0===sepIndex||-1===sepIndex)throw new Error('Letter "1" must be present between prefix and data only');var prefix=str.slice(0,sepIndex),_words=str.slice(sepIndex+1);if(_words.length<6)throw new Error("Data must be at least 6 characters long");var words=BECH_ALPHABET.decode(_words).slice(0,-6),sum=bechChecksum(prefix,words,ENCODING_CONST);if(!_words.endsWith(sum))throw new Error("Invalid checksum in ".concat(str,': expected "').concat(sum,'"'));return{prefix:prefix,words:words}}return{encode:function(prefix,words,limit){if(void 0===limit&&(limit=90),"string"!=typeof prefix)throw new Error("bech32.encode prefix should be string, not ".concat(typeof prefix));if(!Array.isArray(words)||words.length&&"number"!=typeof words[0])throw new Error("bech32.encode words should be array of numbers, not ".concat(typeof words));var actualLength=prefix.length+7+words.length;if(!1!==limit&&actualLength>limit)throw new TypeError("Length ".concat(actualLength," exceeds limit ").concat(limit));return prefix=prefix.toLowerCase(),"".concat(prefix,"1").concat(BECH_ALPHABET.encode(words)).concat(bechChecksum(prefix,words,ENCODING_CONST))},decode:decode,decodeToBytes:function(str){var _a=decode(str,!1),prefix=_a.prefix,words=_a.words;return{prefix:prefix,words:words,bytes:fromWords(words)}},decodeUnsafe:unsafeWrapper(decode),fromWords:fromWords,fromWordsUnsafe:fromWordsUnsafe,toWords:toWords}}base.bech32=genBech32("bech32"),base.bech32m=genBech32("bech32m"),base.utf8={encode:function(data){return(new TextDecoder).decode(data)},decode:function(str){return(new TextEncoder).encode(str)}},base.hex=chain(radix2(4),alphabet("0123456789abcdef"),join(""),normalize((function(s){if("string"!=typeof s||s.length%2)throw new TypeError("hex.decode: expected string, got ".concat(typeof s," with length ").concat(s.length));return s.toLowerCase()})));var CODERS={utf8:base.utf8,hex:base.hex,base16:base.base16,base32:base.base32,base64:base.base64,base64url:base.base64url,base58:base.base58,base58xmr:base.base58xmr},coderTypeError="Invalid encoding type. Available types: ".concat(Object.keys(CODERS).join(", "));base.bytesToString=function(type,bytes){if("string"!=typeof type||!CODERS.hasOwnProperty(type))throw new TypeError(coderTypeError);if(!(bytes instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return CODERS[type].encode(bytes)},base.str=base.bytesToString;base.stringToBytes=function(type,str){if(!CODERS.hasOwnProperty(type))throw new TypeError(coderTypeError);if("string"!=typeof str)throw new TypeError("stringToBytes() expects string");return CODERS[type].decode(str)},base.bytes=base.stringToBytes;const nodeCrypto=Object.freeze({__proto__:null,default:{}});
|
||
/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */
|
||
var _0n=BigInt(0),_1n=BigInt(1),_2n=BigInt(2),_3n=BigInt(3),_8n=BigInt(8);const CURVE=Object.freeze({a:_0n,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:_1n,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")});function weistrass(x){const{a:a,b:b}=CURVE,x2=mod(x*x),x3=mod(x2*x);return mod(x3+a*x+b)}const USE_ENDOMORPHISM=CURVE.a===_0n;class ShaError extends Error{constructor(message){super(message)}}class JacobianPoint{constructor(x,y,z){this.x=x,this.y=y,this.z=z}static fromAffine(p){if(!(p instanceof Point))throw new TypeError("JacobianPoint#fromAffine: expected Point");return new JacobianPoint(p.x,p.y,_1n)}static toAffineBatch(points){const toInv=function(nums,p=CURVE.P){const scratch=new Array(nums.length),inverted=invert(nums.reduce(((acc,num,i)=>num===_0n?acc:(scratch[i]=acc,mod(acc*num,p))),_1n),p);return nums.reduceRight(((acc,num,i)=>num===_0n?acc:(scratch[i]=mod(acc*scratch[i],p),mod(acc*num,p))),inverted),scratch}(points.map((p=>p.z)));return points.map(((p,i)=>p.toAffine(toInv[i])))}static normalizeZ(points){return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine)}equals(other){if(!(other instanceof JacobianPoint))throw new TypeError("JacobianPoint expected");const{x:X1,y:Y1,z:Z1}=this,{x:X2,y:Y2,z:Z2}=other,Z1Z1=mod(Z1*Z1),Z2Z2=mod(Z2*Z2),U1=mod(X1*Z2Z2),U2=mod(X2*Z1Z1),S1=mod(mod(Y1*Z2)*Z2Z2),S2=mod(mod(Y2*Z1)*Z1Z1);return U1===U2&&S1===S2}negate(){return new JacobianPoint(this.x,mod(-this.y),this.z)}double(){const{x:X1,y:Y1,z:Z1}=this,A=mod(X1*X1),B=mod(Y1*Y1),C=mod(B*B),x1b=X1+B,D=mod(_2n*(mod(x1b*x1b)-A-C)),E=mod(_3n*A),F=mod(E*E),X3=mod(F-_2n*D),Y3=mod(E*(D-X3)-_8n*C),Z3=mod(_2n*Y1*Z1);return new JacobianPoint(X3,Y3,Z3)}add(other){if(!(other instanceof JacobianPoint))throw new TypeError("JacobianPoint expected");const{x:X1,y:Y1,z:Z1}=this,{x:X2,y:Y2,z:Z2}=other;if(X2===_0n||Y2===_0n)return this;if(X1===_0n||Y1===_0n)return other;const Z1Z1=mod(Z1*Z1),Z2Z2=mod(Z2*Z2),U1=mod(X1*Z2Z2),U2=mod(X2*Z1Z1),S1=mod(mod(Y1*Z2)*Z2Z2),S2=mod(mod(Y2*Z1)*Z1Z1),H=mod(U2-U1),r=mod(S2-S1);if(H===_0n)return r===_0n?this.double():JacobianPoint.ZERO;const HH=mod(H*H),HHH=mod(H*HH),V=mod(U1*HH),X3=mod(r*r-HHH-_2n*V),Y3=mod(r*(V-X3)-S1*HHH),Z3=mod(Z1*Z2*H);return new JacobianPoint(X3,Y3,Z3)}subtract(other){return this.add(other.negate())}multiplyUnsafe(scalar){const P0=JacobianPoint.ZERO;if("bigint"==typeof scalar&&scalar===_0n)return P0;let n=normalizeScalar(scalar);if(n===_1n)return this;if(!USE_ENDOMORPHISM){let p=P0,d=this;for(;n>_0n;)n&_1n&&(p=p.add(d)),d=d.double(),n>>=_1n;return p}let{k1neg:k1neg,k1:k1,k2neg:k2neg,k2:k2}=splitScalarEndo(n),k1p=P0,k2p=P0,d=this;for(;k1>_0n||k2>_0n;)k1&_1n&&(k1p=k1p.add(d)),k2&_1n&&(k2p=k2p.add(d)),d=d.double(),k1>>=_1n,k2>>=_1n;return k1neg&&(k1p=k1p.negate()),k2neg&&(k2p=k2p.negate()),k2p=new JacobianPoint(mod(k2p.x*CURVE.beta),k2p.y,k2p.z),k1p.add(k2p)}precomputeWindow(W){const windows=USE_ENDOMORPHISM?128/W+1:256/W+1,points=[];let p=this,base=p;for(let window=0;window<windows;window++){base=p,points.push(base);for(let i=1;i<2**(W-1);i++)base=base.add(p),points.push(base);p=base.double()}return points}wNAF(n,affinePoint){!affinePoint&&this.equals(JacobianPoint.BASE)&&(affinePoint=Point.BASE);const W=affinePoint&&affinePoint._WINDOW_SIZE||1;if(256%W)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let precomputes=affinePoint&&pointPrecomputes.get(affinePoint);precomputes||(precomputes=this.precomputeWindow(W),affinePoint&&1!==W&&(precomputes=JacobianPoint.normalizeZ(precomputes),pointPrecomputes.set(affinePoint,precomputes)));let p=JacobianPoint.ZERO,f=JacobianPoint.ZERO;const windows=1+(USE_ENDOMORPHISM?128/W:256/W),windowSize=2**(W-1),mask=BigInt(2**W-1),maxNumber=2**W,shiftBy=BigInt(W);for(let window=0;window<windows;window++){const offset=window*windowSize;let wbits=Number(n&mask);if(n>>=shiftBy,wbits>windowSize&&(wbits-=maxNumber,n+=_1n),0===wbits){let pr=precomputes[offset];window%2&&(pr=pr.negate()),f=f.add(pr)}else{let cached=precomputes[offset+Math.abs(wbits)-1];wbits<0&&(cached=cached.negate()),p=p.add(cached)}}return{p:p,f:f}}multiply(scalar,affinePoint){let point,fake,n=normalizeScalar(scalar);if(USE_ENDOMORPHISM){const{k1neg:k1neg,k1:k1,k2neg:k2neg,k2:k2}=splitScalarEndo(n);let{p:k1p,f:f1p}=this.wNAF(k1,affinePoint),{p:k2p,f:f2p}=this.wNAF(k2,affinePoint);k1neg&&(k1p=k1p.negate()),k2neg&&(k2p=k2p.negate()),k2p=new JacobianPoint(mod(k2p.x*CURVE.beta),k2p.y,k2p.z),point=k1p.add(k2p),fake=f1p.add(f2p)}else{const{p:p,f:f}=this.wNAF(n,affinePoint);point=p,fake=f}return JacobianPoint.normalizeZ([point,fake])[0]}toAffine(invZ=invert(this.z)){const{x:x,y:y,z:z}=this,iz1=invZ,iz2=mod(iz1*iz1),iz3=mod(iz2*iz1),ax=mod(x*iz2),ay=mod(y*iz3);if(mod(z*iz1)!==_1n)throw new Error("invZ was invalid");return new Point(ax,ay)}}JacobianPoint.BASE=new JacobianPoint(CURVE.Gx,CURVE.Gy,_1n),JacobianPoint.ZERO=new JacobianPoint(_0n,_1n,_0n);const pointPrecomputes=new WeakMap;class Point{constructor(x,y){this.x=x,this.y=y}_setWindowSize(windowSize){this._WINDOW_SIZE=windowSize,pointPrecomputes.delete(this)}hasEvenY(){return this.y%_2n===_0n}static fromCompressedHex(bytes){const isShort=32===bytes.length,x=bytesToNumber(isShort?bytes:bytes.subarray(1));if(!isValidFieldElement(x))throw new Error("Point is not on curve");let y=function(x){const{P:P}=CURVE,_6n=BigInt(6),_11n=BigInt(11),_22n=BigInt(22),_23n=BigInt(23),_44n=BigInt(44),_88n=BigInt(88),b2=x*x*x%P,b3=b2*b2*x%P,b6=pow2(b3,_3n)*b3%P,b9=pow2(b6,_3n)*b3%P,b11=pow2(b9,_2n)*b2%P,b22=pow2(b11,_11n)*b11%P,b44=pow2(b22,_22n)*b22%P,b88=pow2(b44,_44n)*b44%P,b176=pow2(b88,_88n)*b88%P,b220=pow2(b176,_44n)*b44%P,b223=pow2(b220,_3n)*b3%P,t1=pow2(b223,_23n)*b22%P,t2=pow2(t1,_6n)*b2%P;return pow2(t2,_2n)}(weistrass(x));const isYOdd=(y&_1n)===_1n;if(isShort)isYOdd&&(y=mod(-y));else{1==(1&bytes[0])!==isYOdd&&(y=mod(-y))}const point=new Point(x,y);return point.assertValidity(),point}static fromUncompressedHex(bytes){const x=bytesToNumber(bytes.subarray(1,33)),y=bytesToNumber(bytes.subarray(33,65)),point=new Point(x,y);return point.assertValidity(),point}static fromHex(hex){const bytes=ensureBytes(hex),len=bytes.length,header=bytes[0];if(32===len||33===len&&(2===header||3===header))return this.fromCompressedHex(bytes);if(65===len&&4===header)return this.fromUncompressedHex(bytes);throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${len}`)}static fromPrivateKey(privateKey){return Point.BASE.multiply(normalizePrivateKey(privateKey))}static fromSignature(msgHash,signature,recovery){const h=truncateHash(msgHash=ensureBytes(msgHash)),{r:r,s:s}=normalizeSignature(signature);if(0!==recovery&&1!==recovery)throw new Error("Cannot recover signature: invalid recovery bit");const prefix=1&recovery?"03":"02",R=Point.fromHex(prefix+numTo32bStr(r)),{n:n}=CURVE,rinv=invert(r,n),u1=mod(-h*rinv,n),u2=mod(s*rinv,n),Q=Point.BASE.multiplyAndAddUnsafe(R,u1,u2);if(!Q)throw new Error("Cannot recover signature: point at infinify");return Q.assertValidity(),Q}toRawBytes(isCompressed=!1){return hexToBytes(this.toHex(isCompressed))}toHex(isCompressed=!1){const x=numTo32bStr(this.x);if(isCompressed){return`${this.hasEvenY()?"02":"03"}${x}`}return`04${x}${numTo32bStr(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const msg="Point is not on elliptic curve",{x:x,y:y}=this;if(!isValidFieldElement(x)||!isValidFieldElement(y))throw new Error(msg);const left=mod(y*y);if(mod(left-weistrass(x))!==_0n)throw new Error(msg)}equals(other){return this.x===other.x&&this.y===other.y}negate(){return new Point(this.x,mod(-this.y))}double(){return JacobianPoint.fromAffine(this).double().toAffine()}add(other){return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine()}subtract(other){return this.add(other.negate())}multiply(scalar){return JacobianPoint.fromAffine(this).multiply(scalar,this).toAffine()}multiplyAndAddUnsafe(Q,a,b){const P=JacobianPoint.fromAffine(this),aP=a===_0n||a===_1n||this!==Point.BASE?P.multiplyUnsafe(a):P.multiply(a),bQ=JacobianPoint.fromAffine(Q).multiplyUnsafe(b),sum=aP.add(bQ);return sum.equals(JacobianPoint.ZERO)?void 0:sum.toAffine()}}function sliceDER(s){return Number.parseInt(s[0],16)>=8?"00"+s:s}function parseDERInt(data){if(data.length<2||2!==data[0])throw new Error(`Invalid signature integer tag: ${bytesToHex(data)}`);const len=data[1],res=data.subarray(2,len+2);if(!len||res.length!==len)throw new Error("Invalid signature integer: wrong length");if(0===res[0]&&res[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:bytesToNumber(res),left:data.subarray(len+2)}}Point.BASE=new Point(CURVE.Gx,CURVE.Gy),Point.ZERO=new Point(_0n,_0n);class Signature{constructor(r,s){this.r=r,this.s=s,this.assertValidity()}static fromCompact(hex){const arr=hex instanceof Uint8Array,name="Signature.fromCompact";if("string"!=typeof hex&&!arr)throw new TypeError(`${name}: Expected string or Uint8Array`);const str=arr?bytesToHex(hex):hex;if(128!==str.length)throw new Error(`${name}: Expected 64-byte hex`);return new Signature(hexToNumber(str.slice(0,64)),hexToNumber(str.slice(64,128)))}static fromDER(hex){const arr=hex instanceof Uint8Array;if("string"!=typeof hex&&!arr)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r:r,s:s}=function(data){if(data.length<2||48!=data[0])throw new Error(`Invalid signature tag: ${bytesToHex(data)}`);if(data[1]!==data.length-2)throw new Error("Invalid signature: incorrect length");const{data:r,left:sBytes}=parseDERInt(data.subarray(2)),{data:s,left:rBytesLeft}=parseDERInt(sBytes);if(rBytesLeft.length)throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(rBytesLeft)}`);return{r:r,s:s}}(arr?hex:hexToBytes(hex));return new Signature(r,s)}static fromHex(hex){return this.fromDER(hex)}assertValidity(){const{r:r,s:s}=this;if(!isWithinCurveOrder(r))throw new Error("Invalid Signature: r must be 0 < r < n");if(!isWithinCurveOrder(s))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const HALF=CURVE.n>>_1n;return this.s>HALF}normalizeS(){return this.hasHighS()?new Signature(this.r,CURVE.n-this.s):this}toDERRawBytes(isCompressed=!1){return hexToBytes(this.toDERHex(isCompressed))}toDERHex(isCompressed=!1){const sHex=sliceDER(numberToHexUnpadded(this.s));if(isCompressed)return sHex;const rHex=sliceDER(numberToHexUnpadded(this.r)),rLen=numberToHexUnpadded(rHex.length/2),sLen=numberToHexUnpadded(sHex.length/2);return`30${numberToHexUnpadded(rHex.length/2+sHex.length/2+4)}02${rLen}${rHex}02${sLen}${sHex}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return hexToBytes(this.toCompactHex())}toCompactHex(){return numTo32bStr(this.r)+numTo32bStr(this.s)}}function concatBytes(...arrays){if(!arrays.every((b=>b instanceof Uint8Array)))throw new Error("Uint8Array list expected");if(1===arrays.length)return arrays[0];const length=arrays.reduce(((a,arr)=>a+arr.length),0),result=new Uint8Array(length);for(let i=0,pad=0;i<arrays.length;i++){const arr=arrays[i];result.set(arr,pad),pad+=arr.length}return result}var hexes=Array.from({length:256},((v,i)=>i.toString(16).padStart(2,"0")));function bytesToHex(uint8a){if(!(uint8a instanceof Uint8Array))throw new Error("Expected Uint8Array");let hex="";for(let i=0;i<uint8a.length;i++)hex+=hexes[uint8a[i]];return hex}secp.bytesToHex=bytesToHex;const POW_2_256=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function numTo32bStr(num){if("bigint"!=typeof num)throw new Error("Expected bigint");if(!(_0n<=num&&num<POW_2_256))throw new Error("Expected number < 2^256");return num.toString(16).padStart(64,"0")}function numTo32b(num){const b=hexToBytes(numTo32bStr(num));if(32!==b.length)throw new Error("Error: expected 32 bytes");return b}function numberToHexUnpadded(num){const hex=num.toString(16);return 1&hex.length?`0${hex}`:hex}function hexToNumber(hex){if("string"!=typeof hex)throw new TypeError("hexToNumber: expected string, got "+typeof hex);return BigInt(`0x${hex}`)}function hexToBytes(hex){if("string"!=typeof hex)throw new TypeError("hexToBytes: expected string, got "+typeof hex);if(hex.length%2)throw new Error("hexToBytes: received invalid unpadded hex"+hex.length);const array=new Uint8Array(hex.length/2);for(let i=0;i<array.length;i++){const j=2*i,hexByte=hex.slice(j,j+2),byte=Number.parseInt(hexByte,16);if(Number.isNaN(byte)||byte<0)throw new Error("Invalid byte sequence");array[i]=byte}return array}function bytesToNumber(bytes){return hexToNumber(bytesToHex(bytes))}function ensureBytes(hex){return hex instanceof Uint8Array?Uint8Array.from(hex):hexToBytes(hex)}function normalizeScalar(num){if("number"==typeof num&&Number.isSafeInteger(num)&&num>0)return BigInt(num);if("bigint"==typeof num&&isWithinCurveOrder(num))return num;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function mod(a,b=CURVE.P){const result=a%b;return result>=_0n?result:b+result}function pow2(x,power){const{P:P}=CURVE;let res=x;for(;power-- >_0n;)res*=res,res%=P;return res}function invert(number,modulo=CURVE.P){if(number===_0n||modulo<=_0n)throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);let a=mod(number,modulo),b=modulo,x=_0n,u=_1n;for(;a!==_0n;){const r=b%a,m=x-u*(b/a);b=a,a=r,x=u,u=m}if(b!==_1n)throw new Error("invert: does not exist");return mod(x,modulo)}secp.hexToNumber=hexToNumber,secp.hexToBytes=hexToBytes,secp.bytesToNumber=bytesToNumber;const divNearest=(a,b)=>(a+b/_2n)/b,ENDO={a1:BigInt("0x3086d221a7d46bcde86c90e49284eb15"),b1:-_1n*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),a2:BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),b2:BigInt("0x3086d221a7d46bcde86c90e49284eb15"),POW_2_128:BigInt("0x100000000000000000000000000000000")};function splitScalarEndo(k){const{n:n}=CURVE,{a1:a1,b1:b1,a2:a2,b2:b2,POW_2_128:POW_2_128}=ENDO,c1=divNearest(b2*k,n),c2=divNearest(-b1*k,n);let k1=mod(k-c1*a1-c2*a2,n),k2=mod(-c1*b1-c2*b2,n);const k1neg=k1>POW_2_128,k2neg=k2>POW_2_128;if(k1neg&&(k1=n-k1),k2neg&&(k2=n-k2),k1>POW_2_128||k2>POW_2_128)throw new Error("splitScalarEndo: Endomorphism failed, k="+k);return{k1neg:k1neg,k1:k1,k2neg:k2neg,k2:k2}}function truncateHash(hash){const{n:n}=CURVE,delta=8*hash.length-256;let h=bytesToNumber(hash);return delta>0&&(h>>=BigInt(delta)),h>=n&&(h-=n),h}let _sha256Sync,_hmacSha256Sync;class HmacDrbg{constructor(){this.v=new Uint8Array(32).fill(1),this.k=new Uint8Array(32).fill(0),this.counter=0}hmac(...values){return utils.hmacSha256(this.k,...values)}hmacSync(...values){return _hmacSha256Sync(this.k,...values)}checkSync(){if("function"!=typeof _hmacSha256Sync)throw new ShaError("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw new Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(seed=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),seed),this.v=await this.hmac(this.v),0!==seed.length&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),seed),this.v=await this.hmac(this.v))}reseedSync(seed=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),seed),this.v=this.hmacSync(this.v),0!==seed.length&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),seed),this.v=this.hmacSync(this.v))}async generate(){return this.incr(),this.v=await this.hmac(this.v),this.v}generateSync(){return this.checkSync(),this.incr(),this.v=this.hmacSync(this.v),this.v}}function isWithinCurveOrder(num){return _0n<num&&num<CURVE.n}function isValidFieldElement(num){return _0n<num&&num<CURVE.P}function kmdToSig(kBytes,m,d){const k=bytesToNumber(kBytes);if(!isWithinCurveOrder(k))return;const{n:n}=CURVE,q=Point.BASE.multiply(k),r=mod(q.x,n);if(r===_0n)return;const s=mod(invert(k,n)*mod(m+d*r,n),n);if(s===_0n)return;const sig=new Signature(r,s);return{sig:sig,recovery:(q.x===sig.r?0:2)|Number(q.y&_1n)}}function normalizePrivateKey(key){let num;if("bigint"==typeof key)num=key;else if("number"==typeof key&&Number.isSafeInteger(key)&&key>0)num=BigInt(key);else if("string"==typeof key){if(64!==key.length)throw new Error("Expected 32 bytes of private key");num=hexToNumber(key)}else{if(!(key instanceof Uint8Array))throw new TypeError("Expected valid private key");if(32!==key.length)throw new Error("Expected 32 bytes of private key");num=bytesToNumber(key)}if(!isWithinCurveOrder(num))throw new Error("Expected private key: 0 < key < n");return num}function normalizePublicKey(publicKey){return publicKey instanceof Point?(publicKey.assertValidity(),publicKey):Point.fromHex(publicKey)}function normalizeSignature(signature){if(signature instanceof Signature)return signature.assertValidity(),signature;try{return Signature.fromDER(signature)}catch(error){return Signature.fromCompact(signature)}}function isProbPub(item){const arr=item instanceof Uint8Array,str="string"==typeof item,len=(arr||str)&&item.length;return arr?33===len||65===len:str?66===len||130===len:item instanceof Point}function bits2int(bytes){return bytesToNumber(bytes.length>32?bytes.slice(0,32):bytes)}function bits2octets(bytes){const z1=bits2int(bytes),z2=mod(z1,CURVE.n);return int2octets(z2<_0n?z1:z2)}function int2octets(num){return numTo32b(num)}function initSigArgs(msgHash,privateKey,extraEntropy){if(null==msgHash)throw new Error(`sign: expected valid message hash, not "${msgHash}"`);const h1=ensureBytes(msgHash),d=normalizePrivateKey(privateKey),seedArgs=[int2octets(d),bits2octets(h1)];if(null!=extraEntropy){!0===extraEntropy&&(extraEntropy=utils.randomBytes(32));const e=ensureBytes(extraEntropy);if(32!==e.length)throw new Error("sign: Expected 32 bytes of extra data");seedArgs.push(e)}return{seed:concatBytes(...seedArgs),m:bits2int(h1),d:d}}function finalizeSig(recSig,opts){let{sig:sig,recovery:recovery}=recSig;const{canonical:canonical,der:der,recovered:recovered}=Object.assign({canonical:!0,der:!0},opts);canonical&&sig.hasHighS()&&(sig=sig.normalizeS(),recovery^=1);const hashed=der?sig.toDERRawBytes():sig.toCompactRawBytes();return recovered?[hashed,recovery]:hashed}const vopts={strict:!0};function schnorrChallengeFinalize(ch){return mod(bytesToNumber(ch),CURVE.n)}class SchnorrSignature{constructor(r,s){this.r=r,this.s=s,this.assertValidity()}static fromHex(hex){const bytes=ensureBytes(hex);if(64!==bytes.length)throw new TypeError(`SchnorrSignature.fromHex: expected 64 bytes, not ${bytes.length}`);const r=bytesToNumber(bytes.subarray(0,32)),s=bytesToNumber(bytes.subarray(32,64));return new SchnorrSignature(r,s)}assertValidity(){const{r:r,s:s}=this;if(!isValidFieldElement(r)||!isWithinCurveOrder(s))throw new Error("Invalid signature")}toHex(){return numTo32bStr(this.r)+numTo32bStr(this.s)}toRawBytes(){return hexToBytes(this.toHex())}}class InternalSchnorrSignature{constructor(message,privateKey,auxRand=utils.randomBytes()){if(null==message)throw new TypeError(`sign: Expected valid message, not "${message}"`);this.m=ensureBytes(message);const{x:x,scalar:scalar}=this.getScalar(normalizePrivateKey(privateKey));if(this.px=x,this.d=scalar,this.rand=ensureBytes(auxRand),32!==this.rand.length)throw new TypeError("sign: Expected 32 bytes of aux randomness")}getScalar(priv){const point=Point.fromPrivateKey(priv),scalar=point.hasEvenY()?priv:CURVE.n-priv;return{point:point,scalar:scalar,x:point.toRawX()}}initNonce(d,t0h){return numTo32b(d^bytesToNumber(t0h))}finalizeNonce(k0h){const k0=mod(bytesToNumber(k0h),CURVE.n);if(k0===_0n)throw new Error("sign: Creation of signature failed. k is zero");const{point:R,x:rx,scalar:k}=this.getScalar(k0);return{R:R,rx:rx,k:k}}finalizeSig(R,k,e,d){return new SchnorrSignature(R.x,mod(k+e*d,CURVE.n)).toRawBytes()}error(){throw new Error("sign: Invalid signature produced")}async calc(){const{m:m,d:d,px:px,rand:rand}=this,tag=utils.taggedHash,t=this.initNonce(d,await tag(TAGS.aux,rand)),{R:R,rx:rx,k:k}=this.finalizeNonce(await tag(TAGS.nonce,t,px,m)),e=schnorrChallengeFinalize(await tag(TAGS.challenge,rx,px,m)),sig=this.finalizeSig(R,k,e,d);return await schnorrVerify(sig,m,px)||this.error(),sig}calcSync(){const{m:m,d:d,px:px,rand:rand}=this,tag=utils.taggedHashSync,t=this.initNonce(d,tag(TAGS.aux,rand)),{R:R,rx:rx,k:k}=this.finalizeNonce(tag(TAGS.nonce,t,px,m)),e=schnorrChallengeFinalize(tag(TAGS.challenge,rx,px,m)),sig=this.finalizeSig(R,k,e,d);return schnorrVerifySync(sig,m,px)||this.error(),sig}}function initSchnorrVerify(signature,message,publicKey){const raw=signature instanceof SchnorrSignature,sig=raw?signature:SchnorrSignature.fromHex(signature);return raw&&sig.assertValidity(),{...sig,m:ensureBytes(message),P:normalizePublicKey(publicKey)}}function finalizeSchnorrVerify(r,P,s,e){const R=Point.BASE.multiplyAndAddUnsafe(P,normalizePrivateKey(s),mod(-e,CURVE.n));return!(!R||!R.hasEvenY()||R.x!==r)}async function schnorrVerify(signature,message,publicKey){try{const{r:r,s:s,m:m,P:P}=initSchnorrVerify(signature,message,publicKey),e=schnorrChallengeFinalize(await utils.taggedHash(TAGS.challenge,numTo32b(r),P.toRawX(),m));return finalizeSchnorrVerify(r,P,s,e)}catch(error){return!1}}function schnorrVerifySync(signature,message,publicKey){try{const{r:r,s:s,m:m,P:P}=initSchnorrVerify(signature,message,publicKey),e=schnorrChallengeFinalize(utils.taggedHashSync(TAGS.challenge,numTo32b(r),P.toRawX(),m));return finalizeSchnorrVerify(r,P,s,e)}catch(error){if(error instanceof ShaError)throw error;return!1}}const schnorr={Signature:SchnorrSignature,getPublicKey:function(privateKey){return Point.fromPrivateKey(privateKey).toRawX()},sign:async function(msg,privKey,auxRand){return new InternalSchnorrSignature(msg,privKey,auxRand).calc()},verify:schnorrVerify,signSync:function(msg,privKey,auxRand){return new InternalSchnorrSignature(msg,privKey,auxRand).calcSync()},verifySync:schnorrVerifySync};Point.BASE._setWindowSize(8);const crypto={node:nodeCrypto,web:"object"==typeof self&&"crypto"in self?self.crypto:void 0},TAGS={challenge:"BIP0340/challenge",aux:"BIP0340/aux",nonce:"BIP0340/nonce"},TAGGED_HASH_PREFIXES={};var utils={bytesToHex:bytesToHex,hexToBytes:hexToBytes,randomBytes:function(bytesLength=32){if(crypto.crypto.web)return crypto.crypto.web.getRandomValues(new Uint8Array(bytesLength));if(crypto.crypto.node)return new Uint8Array(crypto.crypto.node.randomBytes(bytesLength).buffer);throw new Error("The environment doesn't have randomBytes function")},concatBytes:concatBytes,mod:mod,invert:invert,isValidPrivateKey(privateKey){try{return normalizePrivateKey(privateKey),!0}catch(error){return!1}},_bigintTo32Bytes:numTo32b,_normalizePrivateKey:normalizePrivateKey,hashToPrivateKey:hash=>{if((hash=ensureBytes(hash)).length<40||hash.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");return numTo32b(mod(bytesToNumber(hash),CURVE.n-_1n)+_1n)},randomBytes:(bytesLength=32)=>{if(crypto.web)return crypto.web.getRandomValues(new Uint8Array(bytesLength));if(crypto.node){const{randomBytes:randomBytes}=crypto.node;return Uint8Array.from(randomBytes(bytesLength))}throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>utils.hashToPrivateKey(utils.randomBytes(40)),sha256:async(...messages)=>{if(crypto.web){const buffer=await crypto.web.subtle.digest("SHA-256",concatBytes(...messages));return new Uint8Array(buffer)}if(crypto.node){const{createHash:createHash}=crypto.node,hash=createHash("sha256");return messages.forEach((m=>hash.update(m))),Uint8Array.from(hash.digest())}throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(key,...messages)=>{if(crypto.web){const ckey=await crypto.web.subtle.importKey("raw",key,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),message=concatBytes(...messages),buffer=await crypto.web.subtle.sign("HMAC",ckey,message);return new Uint8Array(buffer)}if(crypto.node){const{createHmac:createHmac}=crypto.node,hash=createHmac("sha256",key);return messages.forEach((m=>hash.update(m))),Uint8Array.from(hash.digest())}throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(tag,...messages)=>{let tagP=TAGGED_HASH_PREFIXES[tag];if(void 0===tagP){const tagH=await utils.sha256(Uint8Array.from(tag,(c=>c.charCodeAt(0))));tagP=concatBytes(tagH,tagH),TAGGED_HASH_PREFIXES[tag]=tagP}return utils.sha256(tagP,...messages)},taggedHashSync:(tag,...messages)=>{if("function"!=typeof _sha256Sync)throw new ShaError("sha256Sync is undefined, you need to set it");let tagP=TAGGED_HASH_PREFIXES[tag];if(void 0===tagP){const tagH=_sha256Sync(Uint8Array.from(tag,(c=>c.charCodeAt(0))));tagP=concatBytes(tagH,tagH),TAGGED_HASH_PREFIXES[tag]=tagP}return _sha256Sync(tagP,...messages)},precompute(windowSize=8,point=Point.BASE){const cached=point===Point.BASE?point:new Point(point.x,point.y);return cached._setWindowSize(windowSize),cached.multiply(_3n),cached}};Object.defineProperties(utils,{sha256Sync:{configurable:!1,get:()=>_sha256Sync,set(val){_sha256Sync||(_sha256Sync=val)}},hmacSha256Sync:{configurable:!1,get:()=>_hmacSha256Sync,set(val){_hmacSha256Sync||(_hmacSha256Sync=val)}}}),secp.CURVE=CURVE,secp.Point=Point,secp.Signature=Signature,secp.getPublicKey=function(privateKey,isCompressed=!1){return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed)},secp.getSharedSecret=function(privateA,publicB,isCompressed=!1){if(isProbPub(privateA))throw new TypeError("getSharedSecret: first arg must be private key");if(!isProbPub(publicB))throw new TypeError("getSharedSecret: second arg must be public key");const b=normalizePublicKey(publicB);return b.assertValidity(),b.multiply(normalizePrivateKey(privateA)).toRawBytes(isCompressed)},secp.recoverPublicKey=function(msgHash,signature,recovery,isCompressed=!1){return Point.fromSignature(msgHash,signature,recovery).toRawBytes(isCompressed)},secp.schnorr=schnorr,secp.sign=async function(msgHash,privKey,opts={}){const{seed:seed,m:m,d:d}=initSigArgs(msgHash,privKey,opts.extraEntropy);let sig;const drbg=new HmacDrbg;for(await drbg.reseed(seed);!(sig=kmdToSig(await drbg.generate(),m,d));)await drbg.reseed();return finalizeSig(sig,opts)},secp.signSync=function(msgHash,privKey,opts={}){const{seed:seed,m:m,d:d}=initSigArgs(msgHash,privKey,opts.extraEntropy);let sig;const drbg=new HmacDrbg;for(drbg.reseedSync(seed);!(sig=kmdToSig(drbg.generateSync(),m,d));)drbg.reseedSync();return finalizeSig(sig,opts)},secp.utils=utils,secp.verify=function(signature,msgHash,publicKey,opts=vopts){let sig;try{sig=normalizeSignature(signature),msgHash=ensureBytes(msgHash)}catch(error){return!1}const{r:r,s:s}=sig;if(opts.strict&&sig.hasHighS())return!1;const h=truncateHash(msgHash);let P;try{P=normalizePublicKey(publicKey)}catch(error){return!1}const{n:n}=CURVE,sinv=invert(s,n),u1=mod(h*sinv,n),u2=mod(r*sinv,n),R=Point.BASE.multiplyAndAddUnsafe(P,u1,u2);return!!R&&mod(R.x,n)===r};
|
||
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||
const u32=arr=>new Uint32Array(arr.buffer,arr.byteOffset,Math.floor(arr.byteLength/4)),createView=arr=>new DataView(arr.buffer,arr.byteOffset,arr.byteLength),rotr=(word,shift)=>word<<32-shift|word>>>shift;if(!(68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]))throw new Error("Non little-endian hardware is not supported");hexes=Array.from({length:256},((v,i)=>i.toString(16).padStart(2,"0")));function bytesToHex(uint8a){if(!(uint8a instanceof Uint8Array))throw new Error("Uint8Array expected");let hex="";for(let i=0;i<uint8a.length;i++)hex+=hexes[uint8a[i]];return hex}function hexToBytes(hex){if("string"!=typeof hex)throw new TypeError("hexToBytes: expected string, got "+typeof hex);if(hex.length%2)throw new Error("hexToBytes: received invalid unpadded hex");const array=new Uint8Array(hex.length/2);for(let i=0;i<array.length;i++){const j=2*i,hexByte=hex.slice(j,j+2),byte=Number.parseInt(hexByte,16);if(Number.isNaN(byte)||byte<0)throw new Error("Invalid byte sequence");array[i]=byte}return array}const nextTick=async()=>{};async function asyncLoop(iters,tick,cb){let ts=Date.now();for(let i=0;i<iters;i++){cb(i);const diff=Date.now()-ts;diff>=0&&diff<tick||(await nextTick(),ts+=diff)}}function toBytes(data){if("string"==typeof data&&(data=function(str){if("string"!=typeof str)throw new TypeError("utf8ToBytes expected string, got "+typeof str);return(new TextEncoder).encode(str)}(data)),!(data instanceof Uint8Array))throw new TypeError(`Expected input type is Uint8Array (got ${typeof data})`);return data}class Hash{clone(){return this._cloneInto()}}var isPlainObject=obj=>"[object Object]"===Object.prototype.toString.call(obj)&&obj.constructor===Object;function checkOpts(defaults,opts){if(void 0!==opts&&("object"!=typeof opts||!isPlainObject(opts)))throw new TypeError("Options should be object or undefined");return Object.assign(defaults,opts)}function wrapConstructor(hashConstructor){const hashC=message=>hashConstructor().update(toBytes(message)).digest(),tmp=hashConstructor();return hashC.outputLen=tmp.outputLen,hashC.blockLen=tmp.blockLen,hashC.create=()=>hashConstructor(),hashC}function wrapConstructorWithOpts(hashCons){const hashC=(msg,opts)=>hashCons(opts).update(toBytes(msg)).digest(),tmp=hashCons({});return hashC.outputLen=tmp.outputLen,hashC.blockLen=tmp.blockLen,hashC.create=opts=>hashCons(opts),hashC}function number(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`Wrong positive integer: ${n}`)}function bytes(b,...lengths){if(!(b instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(lengths.length>0&&!lengths.includes(b.length))throw new TypeError(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`)}function isNumber(inputValue){return!isNaN(parseFloat(inputValue))&&isFinite(inputValue)}const assert={number:number,bool:function(b){if("boolean"!=typeof b)throw new Error(`Expected boolean, not ${b}`)},bytes:bytes,hash:function(hash){if("function"!=typeof hash||"function"!=typeof hash.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");try{isNumber(hash.outputLen),isNumber(hash.blockLen)}catch(error){return}},exists:function(instance,checkFinished=!0){if(instance.destroyed)throw new Error("Hash instance has been destroyed");if(checkFinished&&instance.finished)throw new Error("Hash#digest() has already been called")},output:function(out,instance){bytes(out);const min=instance.outputLen;if(out.length<min)throw new Error(`digestInto() expects output buffer of length at least ${min}`)}},SIGMA$1=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3]);class BLAKE2 extends Hash{constructor(blockLen,outputLen,opts={},keyLen,saltLen,persLen){if(super(),this.blockLen=blockLen,this.outputLen=outputLen,this.length=0,this.pos=0,this.finished=!1,this.destroyed=!1,assert.number(blockLen),assert.number(outputLen),assert.number(keyLen),outputLen<0||outputLen>keyLen)throw new Error("Blake2: outputLen bigger than keyLen");if(void 0!==opts.key&&(opts.key.length<1||opts.key.length>keyLen))throw new Error(`Key should be up 1..${keyLen} byte long or undefined`);if(void 0!==opts.salt&&opts.salt.length!==saltLen)throw new Error(`Salt should be ${saltLen} byte long or undefined`);if(void 0!==opts.personalization&&opts.personalization.length!==persLen)throw new Error(`Personalization should be ${persLen} byte long or undefined`);this.buffer32=u32(this.buffer=new Uint8Array(blockLen))}update(data){assert.exists(this);const{blockLen:blockLen,buffer:buffer,buffer32:buffer32}=this,len=(data=toBytes(data)).length;for(let pos=0;pos<len;){this.pos===blockLen&&(this.compress(buffer32,0,!1),this.pos=0);const take=Math.min(blockLen-this.pos,len-pos),dataOffset=data.byteOffset+pos;if(take!==blockLen||dataOffset%4||!(pos+take<len))buffer.set(data.subarray(pos,pos+take),this.pos),this.pos+=take,this.length+=take,pos+=take;else{const data32=new Uint32Array(data.buffer,dataOffset,Math.floor((len-pos)/4));for(let pos32=0;pos+blockLen<len;pos32+=buffer32.length,pos+=blockLen)this.length+=blockLen,this.compress(data32,pos32,!1)}}return this}digestInto(out){assert.exists(this),assert.output(out,this);const{pos:pos,buffer32:buffer32}=this;this.finished=!0,this.buffer.subarray(pos).fill(0),this.compress(buffer32,0,!0);const out32=u32(out);this.get().forEach(((v,i)=>out32[i]=v))}digest(){const{buffer:buffer,outputLen:outputLen}=this;this.digestInto(buffer);const res=buffer.slice(0,outputLen);return this.destroy(),res}_cloneInto(to){const{buffer:buffer,length:length,finished:finished,destroyed:destroyed,outputLen:outputLen,pos:pos}=this;return to||(to=new this.constructor({dkLen:outputLen})),to.set(...this.get()),to.length=length,to.finished=finished,to.destroyed=destroyed,to.outputLen=outputLen,to.buffer.set(buffer),to.pos=pos,to}}const U32_MASK64=BigInt(2**32-1),_32n=BigInt(32);function fromBig(n,le=!1){return le?{h:Number(n&U32_MASK64),l:Number(n>>_32n&U32_MASK64)}:{h:0|Number(n>>_32n&U32_MASK64),l:0|Number(n&U32_MASK64)}}const u64={fromBig:fromBig,split:function(lst,le=!1){let Ah=new Uint32Array(lst.length),Al=new Uint32Array(lst.length);for(let i=0;i<lst.length;i++){const{h:h,l:l}=fromBig(lst[i],le);[Ah[i],Al[i]]=[h,l]}return[Ah,Al]},toBig:(h,l)=>BigInt(h>>>0)<<_32n|BigInt(l>>>0),shrSH:(h,l,s)=>h>>>s,shrSL:(h,l,s)=>h<<32-s|l>>>s,rotrSH:(h,l,s)=>h>>>s|l<<32-s,rotrSL:(h,l,s)=>h<<32-s|l>>>s,rotrBH:(h,l,s)=>h<<64-s|l>>>s-32,rotrBL:(h,l,s)=>h>>>s-32|l<<64-s,rotr32H:(h,l)=>l,rotr32L:(h,l)=>h,rotlSH:(h,l,s)=>h<<s|l>>>32-s,rotlSL:(h,l,s)=>l<<s|h>>>32-s,rotlBH:(h,l,s)=>l<<s-32|h>>>64-s,rotlBL:(h,l,s)=>h<<s-32|l>>>64-s,add:function(Ah,Al,Bh,Bl){const l=(Al>>>0)+(Bl>>>0);return{h:Ah+Bh+(l/2**32|0)|0,l:0|l}},add3L:(Al,Bl,Cl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0),add3H:(low,Ah,Bh,Ch)=>Ah+Bh+Ch+(low/2**32|0)|0,add4L:(Al,Bl,Cl,Dl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0),add4H:(low,Ah,Bh,Ch,Dh)=>Ah+Bh+Ch+Dh+(low/2**32|0)|0,add5H:(low,Ah,Bh,Ch,Dh,Eh)=>Ah+Bh+Ch+Dh+Eh+(low/2**32|0)|0,add5L:(Al,Bl,Cl,Dl,El)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0)+(El>>>0)},IV$2=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),BUF$1=new Uint32Array(32);function G1$1(a,b,c,d,msg,x){const Xl=msg[x],Xh=msg[x+1];let Al=BUF$1[2*a],Ah=BUF$1[2*a+1],Bl=BUF$1[2*b],Bh=BUF$1[2*b+1],Cl=BUF$1[2*c],Ch=BUF$1[2*c+1],Dl=BUF$1[2*d],Dh=BUF$1[2*d+1],ll=u64.add3L(Al,Bl,Xl);Ah=u64.add3H(ll,Ah,Bh,Xh),Al=0|ll,({Dh:Dh,Dl:Dl}={Dh:Dh^Ah,Dl:Dl^Al}),({Dh:Dh,Dl:Dl}={Dh:u64.rotr32H(Dh,Dl),Dl:u64.rotr32L(Dh,Dl)}),({h:Ch,l:Cl}=u64.add(Ch,Cl,Dh,Dl)),({Bh:Bh,Bl:Bl}={Bh:Bh^Ch,Bl:Bl^Cl}),({Bh:Bh,Bl:Bl}={Bh:u64.rotrSH(Bh,Bl,24),Bl:u64.rotrSL(Bh,Bl,24)}),BUF$1[2*a]=Al,BUF$1[2*a+1]=Ah,BUF$1[2*b]=Bl,BUF$1[2*b+1]=Bh,BUF$1[2*c]=Cl,BUF$1[2*c+1]=Ch,BUF$1[2*d]=Dl,BUF$1[2*d+1]=Dh}function G2$1(a,b,c,d,msg,x){const Xl=msg[x],Xh=msg[x+1];let Al=BUF$1[2*a],Ah=BUF$1[2*a+1],Bl=BUF$1[2*b],Bh=BUF$1[2*b+1],Cl=BUF$1[2*c],Ch=BUF$1[2*c+1],Dl=BUF$1[2*d],Dh=BUF$1[2*d+1],ll=u64.add3L(Al,Bl,Xl);Ah=u64.add3H(ll,Ah,Bh,Xh),Al=0|ll,({Dh:Dh,Dl:Dl}={Dh:Dh^Ah,Dl:Dl^Al}),({Dh:Dh,Dl:Dl}={Dh:u64.rotrSH(Dh,Dl,16),Dl:u64.rotrSL(Dh,Dl,16)}),({h:Ch,l:Cl}=u64.add(Ch,Cl,Dh,Dl)),({Bh:Bh,Bl:Bl}={Bh:Bh^Ch,Bl:Bl^Cl}),({Bh:Bh,Bl:Bl}={Bh:u64.rotrBH(Bh,Bl,63),Bl:u64.rotrBL(Bh,Bl,63)}),BUF$1[2*a]=Al,BUF$1[2*a+1]=Ah,BUF$1[2*b]=Bl,BUF$1[2*b+1]=Bh,BUF$1[2*c]=Cl,BUF$1[2*c+1]=Ch,BUF$1[2*d]=Dl,BUF$1[2*d+1]=Dh}class BLAKE2b extends BLAKE2{constructor(opts={}){super(128,void 0===opts.dkLen?64:opts.dkLen,opts,64,16,16),this.v0l=0|IV$2[0],this.v0h=0|IV$2[1],this.v1l=0|IV$2[2],this.v1h=0|IV$2[3],this.v2l=0|IV$2[4],this.v2h=0|IV$2[5],this.v3l=0|IV$2[6],this.v3h=0|IV$2[7],this.v4l=0|IV$2[8],this.v4h=0|IV$2[9],this.v5l=0|IV$2[10],this.v5h=0|IV$2[11],this.v6l=0|IV$2[12],this.v6h=0|IV$2[13],this.v7l=0|IV$2[14],this.v7h=0|IV$2[15];const keyLength=opts.key?opts.key.length:0;if(this.v0l^=this.outputLen|keyLength<<8|65536|1<<24,opts.salt){const salt=u32(toBytes(opts.salt));this.v4l^=salt[0],this.v4h^=salt[1],this.v5l^=salt[2],this.v5h^=salt[3]}if(opts.personalization){const pers=u32(toBytes(opts.personalization));this.v6l^=pers[0],this.v6h^=pers[1],this.v7l^=pers[2],this.v7h^=pers[3]}if(opts.key){const tmp=new Uint8Array(this.blockLen);tmp.set(toBytes(opts.key)),this.update(tmp)}}get(){let{v0l:v0l,v0h:v0h,v1l:v1l,v1h:v1h,v2l:v2l,v2h:v2h,v3l:v3l,v3h:v3h,v4l:v4l,v4h:v4h,v5l:v5l,v5h:v5h,v6l:v6l,v6h:v6h,v7l:v7l,v7h:v7h}=this;return[v0l,v0h,v1l,v1h,v2l,v2h,v3l,v3h,v4l,v4h,v5l,v5h,v6l,v6h,v7l,v7h]}set(v0l,v0h,v1l,v1h,v2l,v2h,v3l,v3h,v4l,v4h,v5l,v5h,v6l,v6h,v7l,v7h){this.v0l=0|v0l,this.v0h=0|v0h,this.v1l=0|v1l,this.v1h=0|v1h,this.v2l=0|v2l,this.v2h=0|v2h,this.v3l=0|v3l,this.v3h=0|v3h,this.v4l=0|v4l,this.v4h=0|v4h,this.v5l=0|v5l,this.v5h=0|v5h,this.v6l=0|v6l,this.v6h=0|v6h,this.v7l=0|v7l,this.v7h=0|v7h}compress(msg,offset,isLast){this.get().forEach(((v,i)=>BUF$1[i]=v)),BUF$1.set(IV$2,16);let{h:h,l:l}=u64.fromBig(BigInt(this.length));BUF$1[24]=IV$2[8]^l,BUF$1[25]=IV$2[9]^h,isLast&&(BUF$1[28]=~BUF$1[28],BUF$1[29]=~BUF$1[29]);let j=0;const s=SIGMA$1;for(let i=0;i<12;i++)G1$1(0,4,8,12,msg,offset+2*s[j++]),G2$1(0,4,8,12,msg,offset+2*s[j++]),G1$1(1,5,9,13,msg,offset+2*s[j++]),G2$1(1,5,9,13,msg,offset+2*s[j++]),G1$1(2,6,10,14,msg,offset+2*s[j++]),G2$1(2,6,10,14,msg,offset+2*s[j++]),G1$1(3,7,11,15,msg,offset+2*s[j++]),G2$1(3,7,11,15,msg,offset+2*s[j++]),G1$1(0,5,10,15,msg,offset+2*s[j++]),G2$1(0,5,10,15,msg,offset+2*s[j++]),G1$1(1,6,11,12,msg,offset+2*s[j++]),G2$1(1,6,11,12,msg,offset+2*s[j++]),G1$1(2,7,8,13,msg,offset+2*s[j++]),G2$1(2,7,8,13,msg,offset+2*s[j++]),G1$1(3,4,9,14,msg,offset+2*s[j++]),G2$1(3,4,9,14,msg,offset+2*s[j++]);this.v0l^=BUF$1[0]^BUF$1[16],this.v0h^=BUF$1[1]^BUF$1[17],this.v1l^=BUF$1[2]^BUF$1[18],this.v1h^=BUF$1[3]^BUF$1[19],this.v2l^=BUF$1[4]^BUF$1[20],this.v2h^=BUF$1[5]^BUF$1[21],this.v3l^=BUF$1[6]^BUF$1[22],this.v3h^=BUF$1[7]^BUF$1[23],this.v4l^=BUF$1[8]^BUF$1[24],this.v4h^=BUF$1[9]^BUF$1[25],this.v5l^=BUF$1[10]^BUF$1[26],this.v5h^=BUF$1[11]^BUF$1[27],this.v6l^=BUF$1[12]^BUF$1[28],this.v6h^=BUF$1[13]^BUF$1[29],this.v7l^=BUF$1[14]^BUF$1[30],this.v7h^=BUF$1[15]^BUF$1[31],BUF$1.fill(0)}destroy(){this.destroyed=!0,this.buffer32.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const blake2b=wrapConstructorWithOpts((opts=>new BLAKE2b(opts))),IV$1=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);function G1(a,b,c,d,x){return d=rotr(d^(a=a+b+x|0),16),{a:a,b:b=rotr(b^(c=c+d|0),12),c:c,d:d}}function G2(a,b,c,d,x){return d=rotr(d^(a=a+b+x|0),8),{a:a,b:b=rotr(b^(c=c+d|0),7),c:c,d:d}}function compress(s,offset,msg,rounds,v0,v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,v12,v13,v14,v15){let j=0;for(let i=0;i<rounds;i++)({a:v0,b:v4,c:v8,d:v12}=G1(v0,v4,v8,v12,msg[offset+s[j++]])),({a:v0,b:v4,c:v8,d:v12}=G2(v0,v4,v8,v12,msg[offset+s[j++]])),({a:v1,b:v5,c:v9,d:v13}=G1(v1,v5,v9,v13,msg[offset+s[j++]])),({a:v1,b:v5,c:v9,d:v13}=G2(v1,v5,v9,v13,msg[offset+s[j++]])),({a:v2,b:v6,c:v10,d:v14}=G1(v2,v6,v10,v14,msg[offset+s[j++]])),({a:v2,b:v6,c:v10,d:v14}=G2(v2,v6,v10,v14,msg[offset+s[j++]])),({a:v3,b:v7,c:v11,d:v15}=G1(v3,v7,v11,v15,msg[offset+s[j++]])),({a:v3,b:v7,c:v11,d:v15}=G2(v3,v7,v11,v15,msg[offset+s[j++]])),({a:v0,b:v5,c:v10,d:v15}=G1(v0,v5,v10,v15,msg[offset+s[j++]])),({a:v0,b:v5,c:v10,d:v15}=G2(v0,v5,v10,v15,msg[offset+s[j++]])),({a:v1,b:v6,c:v11,d:v12}=G1(v1,v6,v11,v12,msg[offset+s[j++]])),({a:v1,b:v6,c:v11,d:v12}=G2(v1,v6,v11,v12,msg[offset+s[j++]])),({a:v2,b:v7,c:v8,d:v13}=G1(v2,v7,v8,v13,msg[offset+s[j++]])),({a:v2,b:v7,c:v8,d:v13}=G2(v2,v7,v8,v13,msg[offset+s[j++]])),({a:v3,b:v4,c:v9,d:v14}=G1(v3,v4,v9,v14,msg[offset+s[j++]])),({a:v3,b:v4,c:v9,d:v14}=G2(v3,v4,v9,v14,msg[offset+s[j++]]));return{v0:v0,v1:v1,v2:v2,v3:v3,v4:v4,v5:v5,v6:v6,v7:v7,v8:v8,v9:v9,v10:v10,v11:v11,v12:v12,v13:v13,v14:v14,v15:v15}}class BLAKE2s extends BLAKE2{constructor(opts={}){super(64,void 0===opts.dkLen?32:opts.dkLen,opts,32,8,8),this.v0=0|IV$1[0],this.v1=0|IV$1[1],this.v2=0|IV$1[2],this.v3=0|IV$1[3],this.v4=0|IV$1[4],this.v5=0|IV$1[5],this.v6=0|IV$1[6],this.v7=0|IV$1[7];const keyLength=opts.key?opts.key.length:0;if(this.v0^=this.outputLen|keyLength<<8|65536|1<<24,opts.salt){const salt=u32(toBytes(opts.salt));this.v4^=salt[0],this.v5^=salt[1]}if(opts.personalization){const pers=u32(toBytes(opts.personalization));this.v6^=pers[0],this.v7^=pers[1]}if(opts.key){const tmp=new Uint8Array(this.blockLen);tmp.set(toBytes(opts.key)),this.update(tmp)}}get(){const{v0:v0,v1:v1,v2:v2,v3:v3,v4:v4,v5:v5,v6:v6,v7:v7}=this;return[v0,v1,v2,v3,v4,v5,v6,v7]}set(v0,v1,v2,v3,v4,v5,v6,v7){this.v0=0|v0,this.v1=0|v1,this.v2=0|v2,this.v3=0|v3,this.v4=0|v4,this.v5=0|v5,this.v6=0|v6,this.v7=0|v7}compress(msg,offset,isLast){const{h:h,l:l}=u64.fromBig(BigInt(this.length)),{v0:v0,v1:v1,v2:v2,v3:v3,v4:v4,v5:v5,v6:v6,v7:v7,v8:v8,v9:v9,v10:v10,v11:v11,v12:v12,v13:v13,v14:v14,v15:v15}=compress(SIGMA$1,offset,msg,10,this.v0,this.v1,this.v2,this.v3,this.v4,this.v5,this.v6,this.v7,IV$1[0],IV$1[1],IV$1[2],IV$1[3],l^IV$1[4],h^IV$1[5],isLast?~IV$1[6]:IV$1[6],IV$1[7]);this.v0^=v0^v8,this.v1^=v1^v9,this.v2^=v2^v10,this.v3^=v3^v11,this.v4^=v4^v12,this.v5^=v5^v13,this.v6^=v6^v14,this.v7^=v7^v15}destroy(){this.destroyed=!0,this.buffer32.fill(0),this.set(0,0,0,0,0,0,0,0)}}const blake2s=wrapConstructorWithOpts((opts=>new BLAKE2s(opts)));var Flags;!function(Flags){Flags[Flags.CHUNK_START=1]="CHUNK_START",Flags[Flags.CHUNK_END=2]="CHUNK_END",Flags[Flags.PARENT=4]="PARENT",Flags[Flags.ROOT=8]="ROOT",Flags[Flags.KEYED_HASH=16]="KEYED_HASH",Flags[Flags.DERIVE_KEY_CONTEXT=32]="DERIVE_KEY_CONTEXT",Flags[Flags.DERIVE_KEY_MATERIAL=64]="DERIVE_KEY_MATERIAL"}(Flags||(Flags={}));const SIGMA=(()=>{const Id=Array.from({length:16},((_,i)=>i)),permute=arr=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((i=>arr[i])),res=[];for(let i=0,v=Id;i<7;i++,v=permute(v))res.push(...v);return Uint8Array.from(res)})();class BLAKE3 extends BLAKE2{constructor(opts={},flags=0){if(super(64,void 0===opts.dkLen?32:opts.dkLen,{},Number.MAX_SAFE_INTEGER,0,0),this.flags=0,this.chunkPos=0,this.chunksDone=0,this.stack=[],this.posOut=0,this.bufferOut32=new Uint32Array(16),this.chunkOut=0,this.enableXOF=!0,this.outputLen=void 0===opts.dkLen?32:opts.dkLen,assert.number(this.outputLen),void 0!==opts.key&&void 0!==opts.context)throw new Error("Blake3: only key or context can be specified at same time");if(void 0!==opts.key){const key=toBytes(opts.key);if(32!==key.length)throw new Error("Blake3: key should be 32 byte");this.IV=u32(key),this.flags=flags|Flags.KEYED_HASH}else if(void 0!==opts.context){const context_key=new BLAKE3({dkLen:32},Flags.DERIVE_KEY_CONTEXT).update(opts.context).digest();this.IV=u32(context_key),this.flags=flags|Flags.DERIVE_KEY_MATERIAL}else this.IV=IV$1.slice(),this.flags=flags;var arr;this.state=this.IV.slice(),this.bufferOut=(arr=this.bufferOut32,new Uint8Array(arr.buffer,arr.byteOffset,arr.byteLength))}get(){return[]}set(){}b2Compress(counter,flags,buf,bufPos=0){const{state:s,pos:pos}=this,{h:h,l:l}=u64.fromBig(BigInt(counter),!0),{v0:v0,v1:v1,v2:v2,v3:v3,v4:v4,v5:v5,v6:v6,v7:v7,v8:v8,v9:v9,v10:v10,v11:v11,v12:v12,v13:v13,v14:v14,v15:v15}=compress(SIGMA,bufPos,buf,7,s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7],IV$1[0],IV$1[1],IV$1[2],IV$1[3],h,l,pos,flags);s[0]=v0^v8,s[1]=v1^v9,s[2]=v2^v10,s[3]=v3^v11,s[4]=v4^v12,s[5]=v5^v13,s[6]=v6^v14,s[7]=v7^v15}compress(buf,bufPos=0,isLast=!1){let flags=this.flags;if(this.chunkPos||(flags|=Flags.CHUNK_START),(15===this.chunkPos||isLast)&&(flags|=Flags.CHUNK_END),isLast||(this.pos=this.blockLen),this.b2Compress(this.chunksDone,flags,buf,bufPos),this.chunkPos+=1,16===this.chunkPos||isLast){let chunk=this.state;this.state=this.IV.slice();for(let last,chunks=this.chunksDone+1;(isLast||!(1&chunks))&&(last=this.stack.pop());chunks>>=1)this.buffer32.set(last,0),this.buffer32.set(chunk,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|Flags.PARENT,this.buffer32,0),chunk=this.state,this.state=this.IV.slice();this.chunksDone++,this.chunkPos=0,this.stack.push(chunk)}this.pos=0}_cloneInto(to){to=super._cloneInto(to);const{IV:IV,flags:flags,state:state,chunkPos:chunkPos,posOut:posOut,chunkOut:chunkOut,stack:stack,chunksDone:chunksDone}=this;return to.state.set(state.slice()),to.stack=stack.map((i=>Uint32Array.from(i))),to.IV.set(IV),to.flags=flags,to.chunkPos=chunkPos,to.chunksDone=chunksDone,to.posOut=posOut,to.chunkOut=chunkOut,to.enableXOF=this.enableXOF,to.bufferOut32.set(this.bufferOut32),to}destroy(){this.destroyed=!0,this.state.fill(0),this.buffer32.fill(0),this.IV.fill(0),this.bufferOut32.fill(0);for(let i of this.stack)i.fill(0)}b2CompressOut(){const{state:s,pos:pos,flags:flags,buffer32:buffer32,bufferOut32:out32}=this,{h:h,l:l}=u64.fromBig(BigInt(this.chunkOut++)),{v0:v0,v1:v1,v2:v2,v3:v3,v4:v4,v5:v5,v6:v6,v7:v7,v8:v8,v9:v9,v10:v10,v11:v11,v12:v12,v13:v13,v14:v14,v15:v15}=compress(SIGMA,0,buffer32,7,s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7],IV$1[0],IV$1[1],IV$1[2],IV$1[3],l,h,pos,flags);out32[0]=v0^v8,out32[1]=v1^v9,out32[2]=v2^v10,out32[3]=v3^v11,out32[4]=v4^v12,out32[5]=v5^v13,out32[6]=v6^v14,out32[7]=v7^v15,out32[8]=s[0]^v8,out32[9]=s[1]^v9,out32[10]=s[2]^v10,out32[11]=s[3]^v11,out32[12]=s[4]^v12,out32[13]=s[5]^v13,out32[14]=s[6]^v14,out32[15]=s[7]^v15,this.posOut=0}finish(){if(this.finished)return;this.finished=!0,this.buffer.fill(0,this.pos);let flags=this.flags|Flags.ROOT;this.stack.length?(flags|=Flags.PARENT,this.compress(this.buffer32,0,!0),this.chunksDone=0,this.pos=this.blockLen):flags|=(this.chunkPos?0:Flags.CHUNK_START)|Flags.CHUNK_END,this.flags=flags,this.b2CompressOut()}writeInto(out){assert.exists(this,!1),assert.bytes(out),this.finish();const{blockLen:blockLen,bufferOut:bufferOut}=this;for(let pos=0,len=out.length;pos<len;){this.posOut>=blockLen&&this.b2CompressOut();const take=Math.min(blockLen-this.posOut,len-pos);out.set(bufferOut.subarray(this.posOut,this.posOut+take),pos),this.posOut+=take,pos+=take}return out}xofInto(out){if(!this.enableXOF)throw new Error("XOF is not possible after digest call");return this.writeInto(out)}xof(bytes){return assert.number(bytes),this.xofInto(new Uint8Array(bytes))}digestInto(out){if(assert.output(out,this),this.finished)throw new Error("digest() was already called");return this.enableXOF=!1,this.writeInto(out),this.destroy(),out}digest(){return this.digestInto(new Uint8Array(this.outputLen))}}const blake3=wrapConstructorWithOpts((opts=>new BLAKE3(opts)));class HMAC extends Hash{constructor(hash,_key){super(),this.finished=!1,this.destroyed=!1,assert.hash(hash);const key=toBytes(_key);if(this.iHash=hash.create(),"function"!=typeof this.iHash.update)throw new TypeError("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const blockLen=this.blockLen,pad=new Uint8Array(blockLen);pad.set(key.length>blockLen?hash.create().update(key).digest():key);for(let i=0;i<pad.length;i++)pad[i]^=54;this.iHash.update(pad),this.oHash=hash.create();for(let i=0;i<pad.length;i++)pad[i]^=106;this.oHash.update(pad),pad.fill(0)}update(buf){return assert.exists(this),this.iHash.update(buf),this}digestInto(out){assert.exists(this),assert.bytes(out,this.outputLen),this.finished=!0,this.iHash.digestInto(out),this.oHash.update(out),this.oHash.digestInto(out),this.destroy()}digest(){const out=new Uint8Array(this.oHash.outputLen);return this.digestInto(out),out}_cloneInto(to){to||(to=Object.create(Object.getPrototypeOf(this),{}));const{oHash:oHash,iHash:iHash,finished:finished,destroyed:destroyed,blockLen:blockLen,outputLen:outputLen}=this;return to.finished=finished,to.destroyed=destroyed,to.blockLen=blockLen,to.outputLen=outputLen,to.oHash=oHash._cloneInto(to.oHash),to.iHash=iHash._cloneInto(to.iHash),to}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hmac=(hash,key,message)=>new HMAC(hash,key).update(message).digest();hmac.create=(hash,key)=>new HMAC(hash,key);const HKDF_COUNTER=new Uint8Array([0]),EMPTY_BUFFER=new Uint8Array;const hkdf=(hash,ikm,salt,info,length)=>function(hash,prk,info,length=32){if(assert.hash(hash),assert.number(length),length>255*hash.outputLen)throw new Error("Length should be <= 255*HashLen");const blocks=Math.ceil(length/hash.outputLen);void 0===info&&(info=EMPTY_BUFFER);const okm=new Uint8Array(blocks*hash.outputLen),HMAC=hmac.create(hash,prk),HMACTmp=HMAC._cloneInto(),T=new Uint8Array(HMAC.outputLen);for(let counter=0;counter<blocks;counter++)HKDF_COUNTER[0]=counter+1,HMACTmp.update(0===counter?EMPTY_BUFFER:T).update(info).update(HKDF_COUNTER).digestInto(T),okm.set(T,hash.outputLen*counter),HMAC._cloneInto(HMACTmp);return HMAC.destroy(),HMACTmp.destroy(),T.fill(0),HKDF_COUNTER.fill(0),okm.slice(0,length)}(hash,function(hash,ikm,salt){return assert.hash(hash),void 0===salt&&(salt=new Uint8Array(hash.outputLen)),hmac(hash,toBytes(salt),toBytes(ikm))}(hash,ikm,salt),info,length);function pbkdf2Init(hash,_password,_salt,_opts){assert.hash(hash);const opts=checkOpts({dkLen:32,asyncTick:10},_opts),{c:c,dkLen:dkLen,asyncTick:asyncTick}=opts;if(assert.number(c),assert.number(dkLen),assert.number(asyncTick),c<1)throw new Error("PBKDF2: iterations (c) should be >= 1");const password=toBytes(_password),salt=toBytes(_salt),DK=new Uint8Array(dkLen),PRF=hmac.create(hash,password),PRFSalt=PRF._cloneInto().update(salt);return{c:c,dkLen:dkLen,asyncTick:asyncTick,DK:DK,PRF:PRF,PRFSalt:PRFSalt}}function pbkdf2Output(PRF,PRFSalt,DK,prfW,u){return PRF.destroy(),PRFSalt.destroy(),prfW&&prfW.destroy(),u.fill(0),DK}function pbkdf2$1(hash,password,salt,opts){const{c:c,dkLen:dkLen,DK:DK,PRF:PRF,PRFSalt:PRFSalt}=pbkdf2Init(hash,password,salt,opts);let prfW;const arr=new Uint8Array(4),view=createView(arr),u=new Uint8Array(PRF.outputLen);for(let ti=1,pos=0;pos<dkLen;ti++,pos+=PRF.outputLen){const Ti=DK.subarray(pos,pos+PRF.outputLen);view.setInt32(0,ti,!1),(prfW=PRFSalt._cloneInto(prfW)).update(arr).digestInto(u),Ti.set(u.subarray(0,Ti.length));for(let ui=1;ui<c;ui++){PRF._cloneInto(prfW).update(u).digestInto(u);for(let i=0;i<Ti.length;i++)Ti[i]^=u[i]}}return pbkdf2Output(PRF,PRFSalt,DK,prfW,u)}class SHA2 extends Hash{constructor(blockLen,outputLen,padOffset,isLE){super(),this.blockLen=blockLen,this.outputLen=outputLen,this.padOffset=padOffset,this.isLE=isLE,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(blockLen),this.view=createView(this.buffer)}update(data){assert.exists(this);const{view:view,buffer:buffer,blockLen:blockLen}=this,len=(data=toBytes(data)).length;for(let pos=0;pos<len;){const take=Math.min(blockLen-this.pos,len-pos);if(take!==blockLen)buffer.set(data.subarray(pos,pos+take),this.pos),this.pos+=take,pos+=take,this.pos===blockLen&&(this.process(view,0),this.pos=0);else{const dataView=createView(data);for(;blockLen<=len-pos;pos+=blockLen)this.process(dataView,pos)}}return this.length+=data.length,this.roundClean(),this}digestInto(out){assert.exists(this),assert.output(out,this),this.finished=!0;const{buffer:buffer,view:view,blockLen:blockLen,isLE:isLE}=this;let{pos:pos}=this;buffer[pos++]=128,this.buffer.subarray(pos).fill(0),this.padOffset>blockLen-pos&&(this.process(view,0),pos=0);for(let i=pos;i<blockLen;i++)buffer[i]=0;!function(view,byteOffset,value,isLE){if("function"==typeof view.setBigUint64)return view.setBigUint64(byteOffset,value,isLE);const _32n=BigInt(32),_u32_max=BigInt(4294967295),wh=Number(value>>_32n&_u32_max),wl=Number(value&_u32_max),h=isLE?4:0,l=isLE?0:4;view.setUint32(byteOffset+h,wh,isLE),view.setUint32(byteOffset+l,wl,isLE)}(view,blockLen-8,BigInt(8*this.length),isLE),this.process(view,0);const oview=createView(out);this.get().forEach(((v,i)=>oview.setUint32(4*i,v,isLE)))}digest(){const{buffer:buffer,outputLen:outputLen}=this;this.digestInto(buffer);const res=buffer.slice(0,outputLen);return this.destroy(),res}_cloneInto(to){to||(to=new this.constructor),to.set(...this.get());const{blockLen:blockLen,buffer:buffer,length:length,finished:finished,destroyed:destroyed,pos:pos}=this;return to.length=length,to.pos=pos,to.finished=finished,to.destroyed=destroyed,length%blockLen&&to.buffer.set(buffer),to}}const Rho=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Id=Uint8Array.from({length:16},((_,i)=>i)),Pi=Id.map((i=>(9*i+5)%16));let idxL=[Id],idxR=[Pi];for(let i=0;i<4;i++)for(let j of[idxL,idxR])j.push(j[i].map((k=>Rho[k])));const shifts=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map((i=>new Uint8Array(i))),shiftsL=idxL.map(((idx,i)=>idx.map((j=>shifts[i][j])))),shiftsR=idxR.map(((idx,i)=>idx.map((j=>shifts[i][j])))),Kl=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),Kr=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]),rotl$1=(word,shift)=>word<<shift|word>>>32-shift;function f(group,x,y,z){return 0===group?x^y^z:1===group?x&y|~x&z:2===group?(x|~y)^z:3===group?x&z|y&~z:x^(y|~z)}const BUF=new Uint32Array(16);class RIPEMD160 extends SHA2{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:h0,h1:h1,h2:h2,h3:h3,h4:h4}=this;return[h0,h1,h2,h3,h4]}set(h0,h1,h2,h3,h4){this.h0=0|h0,this.h1=0|h1,this.h2=0|h2,this.h3=0|h3,this.h4=0|h4}process(view,offset){for(let i=0;i<16;i++,offset+=4)BUF[i]=view.getUint32(offset,!0);let al=0|this.h0,ar=al,bl=0|this.h1,br=bl,cl=0|this.h2,cr=cl,dl=0|this.h3,dr=dl,el=0|this.h4,er=el;for(let group=0;group<5;group++){const rGroup=4-group,hbl=Kl[group],hbr=Kr[group],rl=idxL[group],rr=idxR[group],sl=shiftsL[group],sr=shiftsR[group];for(let i=0;i<16;i++){const tl=rotl$1(al+f(group,bl,cl,dl)+BUF[rl[i]]+hbl,sl[i])+el|0;al=el,el=dl,dl=0|rotl$1(cl,10),cl=bl,bl=tl}for(let i=0;i<16;i++){const tr=rotl$1(ar+f(rGroup,br,cr,dr)+BUF[rr[i]]+hbr,sr[i])+er|0;ar=er,er=dr,dr=0|rotl$1(cr,10),cr=br,br=tr}}this.set(this.h1+cl+dr|0,this.h2+dl+er|0,this.h3+el+ar|0,this.h4+al+br|0,this.h0+bl+cr|0)}roundClean(){BUF.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}}const ripemd160=wrapConstructor((()=>new RIPEMD160)),Maj=(a,b,c)=>a&b^a&c^b&c,SHA256_K=new Uint32Array([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]),IV=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA256_W=new Uint32Array(64);class SHA256 extends SHA2{constructor(){super(64,32,8,!1),this.A=0|IV[0],this.B=0|IV[1],this.C=0|IV[2],this.D=0|IV[3],this.E=0|IV[4],this.F=0|IV[5],this.G=0|IV[6],this.H=0|IV[7]}get(){const{A:A,B:B,C:C,D:D,E:E,F:F,G:G,H:H}=this;return[A,B,C,D,E,F,G,H]}set(A,B,C,D,E,F,G,H){this.A=0|A,this.B=0|B,this.C=0|C,this.D=0|D,this.E=0|E,this.F=0|F,this.G=0|G,this.H=0|H}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA256_W[i]=view.getUint32(offset,!1);for(let i=16;i<64;i++){const W15=SHA256_W[i-15],W2=SHA256_W[i-2],s0=rotr(W15,7)^rotr(W15,18)^W15>>>3,s1=rotr(W2,17)^rotr(W2,19)^W2>>>10;SHA256_W[i]=s1+SHA256_W[i-7]+s0+SHA256_W[i-16]|0}let{A:A,B:B,C:C,D:D,E:E,F:F,G:G,H:H}=this;for(let i=0;i<64;i++){const T1=H+(rotr(E,6)^rotr(E,11)^rotr(E,25))+((a=E)&F^~a&G)+SHA256_K[i]+SHA256_W[i]|0,T2=(rotr(A,2)^rotr(A,13)^rotr(A,22))+Maj(A,B,C)|0;H=G,G=F,F=E,E=D+T1|0,D=C,C=B,B=A,A=T1+T2|0}var a;A=A+this.A|0,B=B+this.B|0,C=C+this.C|0,D=D+this.D|0,E=E+this.E|0,F=F+this.F|0,G=G+this.G|0,H=H+this.H|0,this.set(A,B,C,D,E,F,G,H)}roundClean(){SHA256_W.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const sha256=wrapConstructor((()=>new SHA256)),rotl=(a,b)=>a<<b|a>>>32-b;function XorAndSalsa(prev,pi,input,ii,out,oi){let y00=prev[pi++]^input[ii++],y01=prev[pi++]^input[ii++],y02=prev[pi++]^input[ii++],y03=prev[pi++]^input[ii++],y04=prev[pi++]^input[ii++],y05=prev[pi++]^input[ii++],y06=prev[pi++]^input[ii++],y07=prev[pi++]^input[ii++],y08=prev[pi++]^input[ii++],y09=prev[pi++]^input[ii++],y10=prev[pi++]^input[ii++],y11=prev[pi++]^input[ii++],y12=prev[pi++]^input[ii++],y13=prev[pi++]^input[ii++],y14=prev[pi++]^input[ii++],y15=prev[pi++]^input[ii++],x00=y00,x01=y01,x02=y02,x03=y03,x04=y04,x05=y05,x06=y06,x07=y07,x08=y08,x09=y09,x10=y10,x11=y11,x12=y12,x13=y13,x14=y14,x15=y15;for(let i=0;i<8;i+=2)x04^=rotl(x00+x12|0,7),x08^=rotl(x04+x00|0,9),x12^=rotl(x08+x04|0,13),x00^=rotl(x12+x08|0,18),x09^=rotl(x05+x01|0,7),x13^=rotl(x09+x05|0,9),x01^=rotl(x13+x09|0,13),x05^=rotl(x01+x13|0,18),x14^=rotl(x10+x06|0,7),x02^=rotl(x14+x10|0,9),x06^=rotl(x02+x14|0,13),x10^=rotl(x06+x02|0,18),x03^=rotl(x15+x11|0,7),x07^=rotl(x03+x15|0,9),x11^=rotl(x07+x03|0,13),x15^=rotl(x11+x07|0,18),x01^=rotl(x00+x03|0,7),x02^=rotl(x01+x00|0,9),x03^=rotl(x02+x01|0,13),x00^=rotl(x03+x02|0,18),x06^=rotl(x05+x04|0,7),x07^=rotl(x06+x05|0,9),x04^=rotl(x07+x06|0,13),x05^=rotl(x04+x07|0,18),x11^=rotl(x10+x09|0,7),x08^=rotl(x11+x10|0,9),x09^=rotl(x08+x11|0,13),x10^=rotl(x09+x08|0,18),x12^=rotl(x15+x14|0,7),x13^=rotl(x12+x15|0,9),x14^=rotl(x13+x12|0,13),x15^=rotl(x14+x13|0,18);out[oi++]=y00+x00|0,out[oi++]=y01+x01|0,out[oi++]=y02+x02|0,out[oi++]=y03+x03|0,out[oi++]=y04+x04|0,out[oi++]=y05+x05|0,out[oi++]=y06+x06|0,out[oi++]=y07+x07|0,out[oi++]=y08+x08|0,out[oi++]=y09+x09|0,out[oi++]=y10+x10|0,out[oi++]=y11+x11|0,out[oi++]=y12+x12|0,out[oi++]=y13+x13|0,out[oi++]=y14+x14|0,out[oi++]=y15+x15|0}function BlockMix(input,ii,out,oi,r){let head=oi+0,tail=oi+16*r;for(let i=0;i<16;i++)out[tail+i]=input[ii+16*(2*r-1)+i];for(let i=0;i<r;i++,head+=16,ii+=16)XorAndSalsa(out,tail,input,ii,out,head),i>0&&(tail+=16),XorAndSalsa(out,head,input,ii+=16,out,tail)}function scryptInit(password,salt,_opts){const opts=checkOpts({dkLen:32,asyncTick:10,maxmem:1073742848},_opts),{N:N,r:r,p:p,dkLen:dkLen,asyncTick:asyncTick,maxmem:maxmem,onProgress:onProgress}=opts;if(assert.number(N),assert.number(r),assert.number(p),assert.number(dkLen),assert.number(asyncTick),assert.number(maxmem),void 0!==onProgress&&"function"!=typeof onProgress)throw new Error("progressCb should be function");const blockSize=128*r,blockSize32=blockSize/4;if(N<=1||0!=(N&N-1)||N>=2**(blockSize/8)||N>2**32)throw new Error("Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32");if(p<0||p>137438953440/blockSize)throw new Error("Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)");if(dkLen<0||dkLen>137438953440)throw new Error("Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32");const memUsed=blockSize*(N+p);if(memUsed>maxmem)throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`);const B=pbkdf2$1(sha256,password,salt,{c:1,dkLen:blockSize*p}),B32=u32(B),V=u32(new Uint8Array(blockSize*N)),tmp=u32(new Uint8Array(blockSize));let blockMixCb=()=>{};if(onProgress){const totalBlockMix=2*N*p,callbackPer=Math.max(Math.floor(totalBlockMix/1e4),1);let blockMixCnt=0;blockMixCb=()=>{blockMixCnt++,!onProgress||blockMixCnt%callbackPer&&blockMixCnt!==totalBlockMix||onProgress(blockMixCnt/totalBlockMix)}}return{N:N,r:r,p:p,dkLen:dkLen,blockSize32:blockSize32,V:V,B32:B32,B:B,tmp:tmp,blockMixCb:blockMixCb,asyncTick:asyncTick}}function scryptOutput(password,dkLen,B,V,tmp){const res=pbkdf2$1(sha256,password,B,{c:1,dkLen:dkLen});return B.fill(0),V.fill(0),tmp.fill(0),res}function scrypt$1(password,salt,opts){const{N:N,r:r,p:p,dkLen:dkLen,blockSize32:blockSize32,V:V,B32:B32,B:B,tmp:tmp,blockMixCb:blockMixCb}=scryptInit(password,salt,opts);for(let pi=0;pi<p;pi++){const Pi=blockSize32*pi;for(let i=0;i<blockSize32;i++)V[i]=B32[Pi+i];for(let i=0,pos=0;i<N-1;i++)BlockMix(V,pos,V,pos+=blockSize32,r),blockMixCb();BlockMix(V,(N-1)*blockSize32,B32,Pi,r),blockMixCb();for(let i=0;i<N;i++){const j=B32[Pi+blockSize32-16]%N;for(let k=0;k<blockSize32;k++)tmp[k]=B32[Pi+k]^V[j*blockSize32+k];BlockMix(tmp,0,B32,Pi,r),blockMixCb()}}return scryptOutput(password,dkLen,B,V,tmp)}const[SHA512_Kh,SHA512_Kl]=u64.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((n=>BigInt(n)))),SHA512_W_H=new Uint32Array(80),SHA512_W_L=new Uint32Array(80);class SHA512 extends SHA2{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:Ah,Al:Al,Bh:Bh,Bl:Bl,Ch:Ch,Cl:Cl,Dh:Dh,Dl:Dl,Eh:Eh,El:El,Fh:Fh,Fl:Fl,Gh:Gh,Gl:Gl,Hh:Hh,Hl:Hl}=this;return[Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl]}set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl){this.Ah=0|Ah,this.Al=0|Al,this.Bh=0|Bh,this.Bl=0|Bl,this.Ch=0|Ch,this.Cl=0|Cl,this.Dh=0|Dh,this.Dl=0|Dl,this.Eh=0|Eh,this.El=0|El,this.Fh=0|Fh,this.Fl=0|Fl,this.Gh=0|Gh,this.Gl=0|Gl,this.Hh=0|Hh,this.Hl=0|Hl}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA512_W_H[i]=view.getUint32(offset),SHA512_W_L[i]=view.getUint32(offset+=4);for(let i=16;i<80;i++){const W15h=0|SHA512_W_H[i-15],W15l=0|SHA512_W_L[i-15],s0h=u64.rotrSH(W15h,W15l,1)^u64.rotrSH(W15h,W15l,8)^u64.shrSH(W15h,W15l,7),s0l=u64.rotrSL(W15h,W15l,1)^u64.rotrSL(W15h,W15l,8)^u64.shrSL(W15h,W15l,7),W2h=0|SHA512_W_H[i-2],W2l=0|SHA512_W_L[i-2],s1h=u64.rotrSH(W2h,W2l,19)^u64.rotrBH(W2h,W2l,61)^u64.shrSH(W2h,W2l,6),s1l=u64.rotrSL(W2h,W2l,19)^u64.rotrBL(W2h,W2l,61)^u64.shrSL(W2h,W2l,6),SUMl=u64.add4L(s0l,s1l,SHA512_W_L[i-7],SHA512_W_L[i-16]),SUMh=u64.add4H(SUMl,s0h,s1h,SHA512_W_H[i-7],SHA512_W_H[i-16]);SHA512_W_H[i]=0|SUMh,SHA512_W_L[i]=0|SUMl}let{Ah:Ah,Al:Al,Bh:Bh,Bl:Bl,Ch:Ch,Cl:Cl,Dh:Dh,Dl:Dl,Eh:Eh,El:El,Fh:Fh,Fl:Fl,Gh:Gh,Gl:Gl,Hh:Hh,Hl:Hl}=this;for(let i=0;i<80;i++){const sigma1h=u64.rotrSH(Eh,El,14)^u64.rotrSH(Eh,El,18)^u64.rotrBH(Eh,El,41),sigma1l=u64.rotrSL(Eh,El,14)^u64.rotrSL(Eh,El,18)^u64.rotrBL(Eh,El,41),CHIh=Eh&Fh^~Eh&Gh,CHIl=El&Fl^~El&Gl,T1ll=u64.add5L(Hl,sigma1l,CHIl,SHA512_Kl[i],SHA512_W_L[i]),T1h=u64.add5H(T1ll,Hh,sigma1h,CHIh,SHA512_Kh[i],SHA512_W_H[i]),T1l=0|T1ll,sigma0h=u64.rotrSH(Ah,Al,28)^u64.rotrBH(Ah,Al,34)^u64.rotrBH(Ah,Al,39),sigma0l=u64.rotrSL(Ah,Al,28)^u64.rotrBL(Ah,Al,34)^u64.rotrBL(Ah,Al,39),MAJh=Ah&Bh^Ah&Ch^Bh&Ch,MAJl=Al&Bl^Al&Cl^Bl&Cl;Hh=0|Gh,Hl=0|Gl,Gh=0|Fh,Gl=0|Fl,Fh=0|Eh,Fl=0|El,({h:Eh,l:El}=u64.add(0|Dh,0|Dl,0|T1h,0|T1l)),Dh=0|Ch,Dl=0|Cl,Ch=0|Bh,Cl=0|Bl,Bh=0|Ah,Bl=0|Al;const All=u64.add3L(T1l,sigma0l,MAJl);Ah=u64.add3H(All,T1h,sigma0h,MAJh),Al=0|All}({h:Ah,l:Al}=u64.add(0|this.Ah,0|this.Al,0|Ah,0|Al)),({h:Bh,l:Bl}=u64.add(0|this.Bh,0|this.Bl,0|Bh,0|Bl)),({h:Ch,l:Cl}=u64.add(0|this.Ch,0|this.Cl,0|Ch,0|Cl)),({h:Dh,l:Dl}=u64.add(0|this.Dh,0|this.Dl,0|Dh,0|Dl)),({h:Eh,l:El}=u64.add(0|this.Eh,0|this.El,0|Eh,0|El)),({h:Fh,l:Fl}=u64.add(0|this.Fh,0|this.Fl,0|Fh,0|Fl)),({h:Gh,l:Gl}=u64.add(0|this.Gh,0|this.Gl,0|Gh,0|Gl)),({h:Hh,l:Hl}=u64.add(0|this.Hh,0|this.Hl,0|Hh,0|Hl)),this.set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl)}roundClean(){SHA512_W_H.fill(0),SHA512_W_L.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class SHA512_256 extends SHA512{constructor(){super(),this.Ah=573645204,this.Al=-64227540,this.Bh=-1621794909,this.Bl=-934517566,this.Ch=596883563,this.Cl=1867755857,this.Dh=-1774684391,this.Dl=1497426621,this.Eh=-1775747358,this.El=-1467023389,this.Fh=-1101128155,this.Fl=1401305490,this.Gh=721525244,this.Gl=746961066,this.Hh=246885852,this.Hl=-2117784414,this.outputLen=32}}class SHA384 extends SHA512{constructor(){super(),this.Ah=-876896931,this.Al=-1056596264,this.Bh=1654270250,this.Bl=914150663,this.Ch=-1856437926,this.Cl=812702999,this.Dh=355462360,this.Dl=-150054599,this.Eh=1731405415,this.El=-4191439,this.Fh=-1900787065,this.Fl=1750603025,this.Gh=-619958771,this.Gl=1694076839,this.Hh=1203062813,this.Hl=-1090891868,this.outputLen=48}}const sha512=wrapConstructor((()=>new SHA512));wrapConstructor((()=>new SHA512_256)),wrapConstructor((()=>new SHA384));const[SHA3_PI,SHA3_ROTL,_SHA3_IOTA]=[[],[],[]];_0n=BigInt(0),_1n=BigInt(1),_2n=BigInt(2);var _7n=BigInt(7);const _256n=BigInt(256),_0x71n=BigInt(113);for(let round=0,R=_1n,x=1,y=0;round<24;round++){[x,y]=[y,(2*x+3*y)%5],SHA3_PI.push(2*(5*y+x)),SHA3_ROTL.push((round+1)*(round+2)/2%64);let t=_0n;for(let j=0;j<7;j++)R=(R<<_1n^(R>>_7n)*_0x71n)%_256n,R&_2n&&(t^=_1n<<(_1n<<BigInt(j))-_1n);_SHA3_IOTA.push(t)}const[SHA3_IOTA_H,SHA3_IOTA_L]=u64.split(_SHA3_IOTA,!0),rotlH=(h,l,s)=>s>32?u64.rotlBH(h,l,s):u64.rotlSH(h,l,s),rotlL=(h,l,s)=>s>32?u64.rotlBL(h,l,s):u64.rotlSL(h,l,s);class Keccak extends Hash{constructor(blockLen,suffix,outputLen,enableXOF=!1,rounds=24){if(super(),this.blockLen=blockLen,this.suffix=suffix,this.outputLen=outputLen,this.enableXOF=enableXOF,this.rounds=rounds,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,assert.number(outputLen),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=u32(this.state)}keccak(){!function(s,rounds=24){const B=new Uint32Array(10);for(let round=24-rounds;round<24;round++){for(let x=0;x<10;x++)B[x]=s[x]^s[x+10]^s[x+20]^s[x+30]^s[x+40];for(let x=0;x<10;x+=2){const idx1=(x+8)%10,idx0=(x+2)%10,B0=B[idx0],B1=B[idx0+1],Th=rotlH(B0,B1,1)^B[idx1],Tl=rotlL(B0,B1,1)^B[idx1+1];for(let y=0;y<50;y+=10)s[x+y]^=Th,s[x+y+1]^=Tl}let curH=s[2],curL=s[3];for(let t=0;t<24;t++){const shift=SHA3_ROTL[t],Th=rotlH(curH,curL,shift),Tl=rotlL(curH,curL,shift),PI=SHA3_PI[t];curH=s[PI],curL=s[PI+1],s[PI]=Th,s[PI+1]=Tl}for(let y=0;y<50;y+=10){for(let x=0;x<10;x++)B[x]=s[y+x];for(let x=0;x<10;x++)s[y+x]^=~B[(x+2)%10]&B[(x+4)%10]}s[0]^=SHA3_IOTA_H[round],s[1]^=SHA3_IOTA_L[round]}B.fill(0)}(this.state32,this.rounds),this.posOut=0,this.pos=0}update(data){assert.exists(this);const{blockLen:blockLen,state:state}=this,len=(data=toBytes(data)).length;for(let pos=0;pos<len;){const take=Math.min(blockLen-this.pos,len-pos);for(let i=0;i<take;i++)state[this.pos++]^=data[pos++];this.pos===blockLen&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:state,suffix:suffix,pos:pos,blockLen:blockLen}=this;state[pos]^=suffix,0!=(128&suffix)&&pos===blockLen-1&&this.keccak(),state[blockLen-1]^=128,this.keccak()}writeInto(out){assert.exists(this,!1),assert.bytes(out),this.finish();const bufferOut=this.state,{blockLen:blockLen}=this;for(let pos=0,len=out.length;pos<len;){this.posOut>=blockLen&&this.keccak();const take=Math.min(blockLen-this.posOut,len-pos);out.set(bufferOut.subarray(this.posOut,this.posOut+take),pos),this.posOut+=take,pos+=take}return out}xofInto(out){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(out)}xof(bytes){return assert.number(bytes),this.xofInto(new Uint8Array(bytes))}digestInto(out){if(assert.output(out,this),this.finished)throw new Error("digest() was already called");return this.writeInto(out),this.destroy(),out}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(to){const{blockLen:blockLen,suffix:suffix,outputLen:outputLen,rounds:rounds,enableXOF:enableXOF}=this;return to||(to=new Keccak(blockLen,suffix,outputLen,enableXOF,rounds)),to.state32.set(this.state32),to.pos=this.pos,to.posOut=this.posOut,to.finished=this.finished,to.rounds=rounds,to.suffix=suffix,to.outputLen=outputLen,to.enableXOF=enableXOF,to.destroyed=this.destroyed,to}}const gen=(suffix,blockLen,outputLen)=>wrapConstructor((()=>new Keccak(blockLen,suffix,outputLen))),sha3_224=gen(6,144,28),sha3_256=gen(6,136,32),sha3_384=gen(6,104,48),sha3_512=gen(6,72,64),keccak_224=gen(1,144,28),keccak_256=gen(1,136,32),keccak_384=gen(1,104,48),keccak_512=gen(1,72,64),genShake=(suffix,blockLen,outputLen)=>wrapConstructorWithOpts(((opts={})=>new Keccak(blockLen,suffix,void 0===opts.dkLen?outputLen:opts.dkLen,!0)));function leftEncode(n){const res=[255&n];for(n>>=8;n>0;n>>=8)res.unshift(255&n);return res.unshift(res.length),new Uint8Array(res)}function chooseLen(opts,outputLen){return void 0===opts.dkLen?outputLen:opts.dkLen}genShake(31,168,16),genShake(31,136,32);const toBytesOptional=buf=>void 0!==buf?toBytes(buf):new Uint8Array([]),getPadding=(len,block)=>new Uint8Array((block-len%block)%block);function cshakePers(hash,opts={}){if(!opts||!opts.personalization&&!opts.NISTfn)return hash;const blockLenBytes=leftEncode(hash.blockLen),fn=toBytesOptional(opts.NISTfn),fnLen=leftEncode(8*fn.length),pers=toBytesOptional(opts.personalization),persLen=leftEncode(8*pers.length);if(!fn.length&&!pers.length)return hash;hash.suffix=4,hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers);let totalLen=blockLenBytes.length+fnLen.length+fn.length+persLen.length+pers.length;return hash.update(getPadding(totalLen,hash.blockLen)),hash}const gencShake=(suffix,blockLen,outputLen)=>wrapConstructorWithOpts(((opts={})=>cshakePers(new Keccak(blockLen,suffix,chooseLen(opts,outputLen),!0),opts))),cshake128=gencShake(31,168,16),cshake256=gencShake(31,136,32);class KMAC extends Keccak{constructor(blockLen,outputLen,enableXOF,key,opts={}){super(blockLen,31,outputLen,enableXOF),cshakePers(this,{NISTfn:"KMAC",personalization:opts.personalization}),key=toBytes(key);const blockLenBytes=leftEncode(this.blockLen),keyLen=leftEncode(8*key.length);this.update(blockLenBytes).update(keyLen).update(key);const totalLen=blockLenBytes.length+keyLen.length+key.length;this.update(getPadding(totalLen,this.blockLen))}finish(){this.finished||this.update(function(n){const res=[255&n];for(n>>=8;n>0;n>>=8)res.unshift(255&n);return res.push(res.length),new Uint8Array(res)}(this.enableXOF?0:8*this.outputLen)),super.finish()}_cloneInto(to){return to||((to=Object.create(Object.getPrototypeOf(this),{})).state=this.state.slice(),to.blockLen=this.blockLen,to.state32=u32(to.state)),super._cloneInto(to)}clone(){return this._cloneInto()}}function genKmac(blockLen,outputLen,xof=!1){const kmac=(key,message,opts)=>kmac.create(key,opts).update(message).digest();return kmac.create=(key,opts={})=>new KMAC(blockLen,chooseLen(opts,outputLen),xof,key,opts),kmac}const kmac128=genKmac(168,16),kmac256=genKmac(136,32);function rightEncodeK12(n){const res=[];for(;n>0;n>>=8)res.unshift(255&n);return res.push(res.length),new Uint8Array(res)}genKmac(168,16,!0),genKmac(136,32,!0);const EMPTY=new Uint8Array([]);class KangarooTwelve extends Keccak{constructor(blockLen,leafLen,outputLen,rounds,opts){super(blockLen,7,outputLen,!0,rounds),this.leafLen=leafLen,this.chunkLen=8192,this.chunkPos=0,this.chunksDone=0;const{personalization:personalization}=opts;this.personalization=toBytesOptional(personalization)}update(data){data=toBytes(data);const{chunkLen:chunkLen,blockLen:blockLen,leafLen:leafLen,rounds:rounds}=this;for(let pos=0,len=data.length;pos<len;){this.chunkPos==chunkLen&&(this.leafHash?super.update(this.leafHash.digest()):(this.suffix=6,super.update(new Uint8Array([3,0,0,0,0,0,0,0]))),this.leafHash=new Keccak(blockLen,11,leafLen,!1,rounds),this.chunksDone++,this.chunkPos=0);const take=Math.min(chunkLen-this.chunkPos,len-pos),chunk=data.subarray(pos,pos+take);this.leafHash?this.leafHash.update(chunk):super.update(chunk),this.chunkPos+=take,pos+=take}return this}finish(){if(this.finished)return;const{personalization:personalization}=this;this.update(personalization).update(rightEncodeK12(personalization.length)),this.leafHash&&(super.update(this.leafHash.digest()),super.update(rightEncodeK12(this.chunksDone)),super.update(new Uint8Array([255,255]))),super.finish.call(this)}destroy(){super.destroy.call(this),this.leafHash&&this.leafHash.destroy(),this.personalization=EMPTY}_cloneInto(to){const{blockLen:blockLen,leafLen:leafLen,leafHash:leafHash,outputLen:outputLen,rounds:rounds}=this;return to||(to=new KangarooTwelve(blockLen,leafLen,outputLen,rounds,{})),super._cloneInto(to),leafHash&&(to.leafHash=leafHash._cloneInto(to.leafHash)),to.personalization.set(this.personalization),to.leafLen=this.leafLen,to.chunkPos=this.chunkPos,to.chunksDone=this.chunksDone,to}clone(){return this._cloneInto()}}const k12=wrapConstructorWithOpts(((opts={})=>new KangarooTwelve(168,32,chooseLen(opts,32),12,opts))),m14=wrapConstructorWithOpts(((opts={})=>new KangarooTwelve(136,64,chooseLen(opts,64),14,opts))),SCRYPT_FACTOR=2**19,PBKDF2_FACTOR=2**17;function strHasLength(str,min,max){return"string"==typeof str&&str.length>=min&&str.length<=max}function deriveMainSeed(username,password){if(!strHasLength(username,8,255))throw new Error("invalid username");if(!strHasLength(password,8,255))throw new Error("invalid password");const scr=function(password,salt){return scrypt$1(password,salt,{N:SCRYPT_FACTOR,r:8,p:1,dkLen:32})}(password+"",username+""),pbk=function(password,salt){return pbkdf2$1(sha256,password,salt,{c:PBKDF2_FACTOR,dkLen:32})}(password+"",username+""),res=function(a,b){bytes(a,32),bytes(b,32);const arr=new Uint8Array(32);for(let i=0;i<32;i++)arr[i]=a[i]^b[i];return arr}(scr,pbk);return scr.fill(0),pbk.fill(0),res}function getKeyLength(options){if(!options||"object"!=typeof options)return 32;const hasLen="keyLength"in options,hasMod="modulus"in options;if(hasLen&&hasMod)throw new Error("cannot combine keyLength and modulus options");if(!hasLen&&!hasMod)throw new Error("must have either keyLength or modulus option");const l=hasMod?function(num){if("bigint"!=typeof num||num<=BigInt(128))throw new Error("invalid number");return Math.ceil(num.toString(2).length/8)}(options.modulus)+8:options.keyLength;if(!("number"==typeof l&&l>=16&&l<=8192))throw new Error("invalid keyLength");return l}var sha256_1={};sha256_1.sha256=sha256;var hmac_1={};hmac_1.hmac=hmac;var ripemd160_1={};ripemd160_1.ripemd160=ripemd160,hashmini.blake2b=blake2b,hashmini.blake2s=blake2s,hashmini.blake3=blake3,hashmini.cshake128=cshake128,hashmini.cshake256=cshake256,hashmini.eskdf=async function(username,password){let seed=deriveMainSeed(username,password);function deriveCK(protocol,accountId=0,options){bytes(seed,32);const{salt:salt,info:info}=function(protocol,accountId=0){if(!strHasLength(protocol,3,15)||!/^[a-z0-9]{3,15}$/.test(protocol))throw new Error("invalid protocol");const allowsStr=/^password\d{0,3}|ssh|tor|file$/.test(protocol);let salt;if("string"==typeof accountId){if(!allowsStr)throw new Error("accountId must be a number");if(!strHasLength(accountId,1,255))throw new Error("accountId must be valid string");salt=toBytes(accountId)}else{if(!Number.isSafeInteger(accountId))throw new Error("accountId must be a number"+(allowsStr?" or string":""));if(accountId<0||accountId>2**32-1)throw new Error("invalid accountId");salt=new Uint8Array(4),createView(salt).setUint32(0,accountId,!1)}return{salt:salt,info:toBytes(protocol)}}(protocol,accountId),keyLength=getKeyLength(options),key=hkdf(sha256,seed,salt,info,keyLength);return options&&"modulus"in options?function(key,modulus){const _1=BigInt(1),res=BigInt("0x"+bytesToHex(key))%(modulus-_1)+_1;if(res<_1)throw new Error("expected positive number");const len=key.length-8,hex=res.toString(16).padStart(2*len,"0"),bytes=hexToBytes(hex);if(bytes.length!==len)throw new Error("invalid length of result key");return bytes}(key,options.modulus):key}const fingerprint=Array.from(deriveCK("fingerprint",0)).slice(0,6).map((char=>char.toString(16).padStart(2,"0").toUpperCase())).join(":");return Object.freeze({deriveChildKey:deriveCK,expire:function(){seed&&seed.fill(1),seed=void 0},fingerprint:fingerprint})},hashmini.hkdf=hkdf,hashmini.hmac=hmac,hashmini.k12=k12,hashmini.keccak_224=keccak_224,hashmini.keccak_256=keccak_256,hashmini.keccak_384=keccak_384,hashmini.keccak_512=keccak_512,hashmini.kmac128=kmac128,hashmini.kmac256=kmac256,hashmini.m14=m14,hashmini.pbkdf2=pbkdf2$1,hashmini.pbkdf2Async=async function(hash,password,salt,opts){const{c:c,dkLen:dkLen,asyncTick:asyncTick,DK:DK,PRF:PRF,PRFSalt:PRFSalt}=pbkdf2Init(hash,password,salt,opts);let prfW;const arr=new Uint8Array(4),view=createView(arr),u=new Uint8Array(PRF.outputLen);for(let ti=1,pos=0;pos<dkLen;ti++,pos+=PRF.outputLen){const Ti=DK.subarray(pos,pos+PRF.outputLen);view.setInt32(0,ti,!1),(prfW=PRFSalt._cloneInto(prfW)).update(arr).digestInto(u),Ti.set(u.subarray(0,Ti.length)),await asyncLoop(c-1,asyncTick,(i=>{PRF._cloneInto(prfW).update(u).digestInto(u);for(let i=0;i<Ti.length;i++)Ti[i]^=u[i]}))}return pbkdf2Output(PRF,PRFSalt,DK,prfW,u)},hashmini.ripemd160=ripemd160,hashmini.scrypt=scrypt$1,hashmini.scryptAsync=async function(password,salt,opts){const{N:N,r:r,p:p,dkLen:dkLen,blockSize32:blockSize32,V:V,B32:B32,B:B,tmp:tmp,blockMixCb:blockMixCb,asyncTick:asyncTick}=scryptInit(password,salt,opts);for(let pi=0;pi<p;pi++){const Pi=blockSize32*pi;for(let i=0;i<blockSize32;i++)V[i]=B32[Pi+i];let pos=0;await asyncLoop(N-1,asyncTick,(i=>{BlockMix(V,pos,V,pos+=blockSize32,r),blockMixCb()})),BlockMix(V,(N-1)*blockSize32,B32,Pi,r),blockMixCb(),await asyncLoop(N,asyncTick,(i=>{const j=B32[Pi+blockSize32-16]%N;for(let k=0;k<blockSize32;k++)tmp[k]=B32[Pi+k]^V[j*blockSize32+k];BlockMix(tmp,0,B32,Pi,r),blockMixCb()}))}return scryptOutput(password,dkLen,B,V,tmp)},hashmini.sha256=sha256,hashmini.sha3_224=sha3_224,hashmini.sha3_256=sha3_256,hashmini.sha3_384=sha3_384,hashmini.sha3_512=sha3_512,hashmini.sha512=sha512,hashmini.utils=utils,Object.defineProperty(hashmini,"__esModule",{value:!0});var P={},__assign=this&&this.__assign||function(){return Object.assign.apply(Object,arguments)};function equalBytes(a,b){if(a.length!==b.length)return!1;for(var i=0;i<a.length;i++)if(a[i]!==b[i])return!1;return!0}function concatBytes(){for(var arrays=[],_i=0;_i<arguments.length;_i++)arrays[_i]=arguments[_i];if(1===arrays.length)return arrays[0];for(var length=arrays.reduce((function(a,arr){return a+arr.length}),0),result=new Uint8Array(length),i=0,pad=0;i<arrays.length;i++){var arr=arrays[i];result.set(arr,pad),pad+=arr.length}return result}Object.defineProperty(P,"__esModule",{value:!0}),P.magicBytes=P.magic=P.optional=P.flagged=P.flag=P.bytesFormatted=P.lazy=P.validate=P.apply=P.hex=P.cstring=P.string=P.bytes=P.bool=P.I8=P.U8=P.I16BE=P.I16LE=P.U16BE=P.U16LE=P.I32BE=P.I32LE=P.U32BE=P.U32LE=P.int=P.I64BE=P.I64LE=P.U64BE=P.U64LE=P.I128BE=P.I128LE=P.U128BE=P.U128LE=P.I256BE=P.I256LE=P.U256BE=P.U256LE=P.bigint=P.bits=P.coders=P.isCoder=P.wrap=P.checkBounds=P.Writer=P.Reader=P.isBytes=P.concatBytes=P.equalBytes=P.NULL=P.EMPTY=void 0,P.debug=P.nothing=P.base64armor=P.pointer=P.padRight=P.padLeft=P.ZeroPad=P.bitset=P.mappedTag=P.tag=P.map=P.array=P.prefix=P.tuple=P.struct=P.constant=void 0,P.EMPTY=new Uint8Array,P.NULL=new Uint8Array([0]),P.equalBytes=equalBytes,P.concatBytes=concatBytes;var isBytes=function(b){return b instanceof Uint8Array};P.isBytes=isBytes;var Reader=function(){function Reader(data,path,fieldPath){void 0===path&&(path=[]),void 0===fieldPath&&(fieldPath=[]),this.data=data,this.path=path,this.fieldPath=fieldPath,this.pos=0,this.hasPtr=!1,this.bitBuf=0,this.bitPos=0}return Reader.prototype.err=function(msg){return new Error("Reader(".concat(this.fieldPath.join("/"),"): ").concat(msg))},Reader.prototype.absBytes=function(n){if(n>this.data.length)throw new Error("absBytes: Unexpected end of buffer");return this.data.subarray(n)},Reader.prototype.bytes=function(n,peek){if(void 0===peek&&(peek=!1),this.bitPos)throw this.err("readBytes: bitPos not empty");if(!Number.isFinite(n))throw this.err("readBytes: wrong length=".concat(n));if(this.pos+n>this.data.length)throw this.err("readBytes: Unexpected end of buffer");var slice=this.data.subarray(this.pos,this.pos+n);return peek||(this.pos+=n),slice},Reader.prototype.byte=function(peek){if(void 0===peek&&(peek=!1),this.bitPos)throw this.err("readByte: bitPos not empty");return this.data[peek?this.pos:this.pos++]},Object.defineProperty(Reader.prototype,"leftBytes",{get:function(){return this.data.length-this.pos},enumerable:!1,configurable:!0}),Reader.prototype.isEnd=function(){return this.pos>=this.data.length&&!this.bitPos},Reader.prototype.length=function(len){var byteLen;if(isCoder(len)?byteLen=Number(len.decodeStream(this)):"number"==typeof len?byteLen=len:"string"==typeof len&&(byteLen=getPath(this.path,len.split("/"))),"bigint"==typeof byteLen&&(byteLen=Number(byteLen)),"number"!=typeof byteLen)throw this.err("Wrong length: ".concat(byteLen));return byteLen},Reader.prototype.bits=function(bits){if(bits>32)throw this.err("BitReader: cannot read more than 32 bits in single call");for(var out=0;bits;){this.bitPos||(this.bitBuf=this.data[this.pos++],this.bitPos=8);var take=Math.min(bits,this.bitPos);this.bitPos-=take,out=out<<take|this.bitBuf>>this.bitPos&BigInt(2)**BigInt(take)-1,this.bitBuf&=BigInt(2)**BigInt(this.bitPos)-1,bits-=take}return out>>>0},Reader.prototype.find=function(needle,pos){if(void 0===pos&&(pos=this.pos),!(0,P.isBytes)(needle))throw this.err("find: needle is not bytes! ".concat(needle));if(this.bitPos)throw this.err("findByte: bitPos not empty");if(!needle.length)throw this.err("find: needle is empty");for(var idx=pos;-1!==(idx=this.data.indexOf(needle[0],idx));idx++){if(-1===idx)return;if(this.data.length-idx<needle.length)return;if(equalBytes(needle,this.data.subarray(idx,idx+needle.length)))return idx}},Reader.prototype.finish=function(){if(!this.isEnd()&&!this.hasPtr)throw this.err("".concat(this.leftBytes," bytes ").concat(this.bitPos," bits left after unpack: ").concat(base.hex.encode(this.data.slice(this.pos))))},Reader.prototype.fieldPathPush=function(s){this.fieldPath.push(s)},Reader.prototype.fieldPathPop=function(){this.fieldPath.pop()},Reader}();P.Reader=Reader;var Writer=function(){function Writer(path,fieldPath){void 0===path&&(path=[]),void 0===fieldPath&&(fieldPath=[]),this.path=path,this.fieldPath=fieldPath,this.buffers=[],this.pos=0,this.ptrs=[],this.bitBuf=0,this.bitPos=0}return Writer.prototype.err=function(msg){return new Error("Writer(".concat(this.fieldPath.join("/"),"): ").concat(msg))},Writer.prototype.bytes=function(b){if(this.bitPos)throw this.err("writeBytes: ends with non-empty bit buffer");this.buffers.push(b),this.pos+=b.length},Writer.prototype.byte=function(b){if(this.bitPos)throw this.err("writeByte: ends with non-empty bit buffer");this.buffers.push(new Uint8Array([b])),this.pos++},Object.defineProperty(Writer.prototype,"buffer",{get:function(){if(this.bitPos)throw this.err("buffer: ends with non-empty bit buffer");for(var buf=concatBytes.apply(void 0,this.buffers),_i=0,_a=this.ptrs;_i<_a.length;_i++){var ptr=_a[_i],pos=buf.length;buf=concatBytes(buf,ptr.buffer);for(var val=ptr.ptr.encode(pos),i=0;i<val.length;i++)buf[ptr.pos+i]=val[i]}return buf},enumerable:!1,configurable:!0}),Writer.prototype.length=function(len,value){if(null!==len){if(isCoder(len))return len.encodeStream(this,value);var byteLen;if("number"==typeof len?byteLen=len:"string"==typeof len&&(byteLen=getPath(this.path,len.split("/"))),"bigint"==typeof byteLen&&(byteLen=Number(byteLen)),void 0===byteLen||byteLen!==value)throw this.err("Wrong length: ".concat(byteLen," len=").concat(len," exp=").concat(value))}},Writer.prototype.bits=function(value,bits){if(bits>32)throw this.err("writeBits: cannot write more than 32 bits in single call");if(value>=BigInt(2)**BigInt(bits))throw this.err("writeBits: value (".concat(value,") >= 2**bits (").concat(bits,")"));for(;bits;){var take=Math.min(bits,8-this.bitPos);this.bitBuf=this.bitBuf<<take|value>>bits-take,this.bitPos+=take,bits-=take,value&=BigInt(2)**BigInt(bits)-1,8===this.bitPos&&(this.bitPos=0,this.buffers.push(new Uint8Array([this.bitBuf])),this.pos++)}},Writer.prototype.fieldPathPush=function(s){this.fieldPath.push(s)},Writer.prototype.fieldPathPop=function(){this.fieldPath.pop()},Writer}();P.Writer=Writer;var swap=function(b){return Uint8Array.from(b).reverse()};function checkBounds(p,value,bits,signed){if(signed){var signBit=BigInt(2n)**BigInt(bits-1n);if(value<-signBit||value>=signBit)throw p.err("sInt: value out of bounds")}else if(0n>value||value>=BigInt(2n)**BigInt(bits))throw p.err("uInt: value out of bounds")}function wrap(inner){return __assign(__assign({},inner),{encode:function(value){var w=new Writer;return inner.encodeStream(w,value),w.buffer},decode:function(data){var r=new Reader(data),res=inner.decodeStream(r);return r.finish(),res}})}function getPath(objPath,path){objPath=Array.from(objPath);for(var i=0;i<path.length&&".."===path[i];i++)objPath.pop();for(var cur=objPath.pop();i<path.length;i++){if(!cur||void 0===cur[path[i]])return;cur=cur[path[i]]}return cur}function isCoder(elm){return"function"==typeof elm.encode&&"function"==typeof elm.encodeStream&&"function"==typeof elm.decode&&"function"==typeof elm.decodeStream}P.checkBounds=checkBounds,P.wrap=wrap,P.isCoder=isCoder;var number={encode:function(from){if(from>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("coders.number: element bigger than MAX_SAFE_INTEGER=".concat(from));return Number(from)},decode:function(to){return BigInt(to)}};function decimal(precision){var decimalMask=BitInt(10n)**BigInt(precision);return{encode:function(from){var s=(from<0n?-from:from).toString(10),sep=s.length-precision;sep<0&&(s=s.padStart(s.length-sep,"0"),sep=0);for(var i=s.length-1;i>=sep&&"0"===s[i];i--);var _a=[s.slice(0,sep),s.slice(sep,i+1)],int=_a[0],frac=_a[1];return int||(int="0"),from<0n&&(int="-"+int),frac?"".concat(int,".").concat(frac):int},decode:function(to){var neg=!1;to.startsWith("-")&&(neg=!0,to=to.slice(1));var sep=to.indexOf(".");sep=-1===sep?to.length:sep;var _a=[to.slice(0,sep),to.slice(sep+1)],fracS=_a[1],int=BigInt(_a[0])*decimalMask,fracLen=Math.min(fracS.length,precision),value=int+BigInt(fracS.slice(0,fracLen))*BigInt(10n)**BigInt(precision-fracLen);return neg?-value:value}}}P.coders={dict:function(){return{encode:function(from){for(var to={},_i=0,from_1=from;_i<from_1.length;_i++){var _a=from_1[_i],name=_a[0],value=_a[1];if(void 0!==to[name])throw new Error("coders.dict: same key(".concat(name,") appears twice in struct"));to[name]=value}return to},decode:function(to){return Object.entries(to)}}},number:number,tsEnum:function(e){return{encode:function(from){return e[from]},decode:function(to){return e[to]}}},decimal:decimal,match:function(lst){return{encode:function(from){for(var _i=0,lst_1=lst;_i<lst_1.length;_i++){var elm=lst_1[_i].encode(from);if(void 0!==elm)return elm}throw new Error("match/encode: cannot find match in ".concat(from))},decode:function(to){for(var _i=0,lst_2=lst;_i<lst_2.length;_i++){var elm=lst_2[_i].decode(to);if(void 0!==elm)return elm}throw new Error("match/decode: cannot find match in ".concat(to))}}}};P.bits=function(len){return wrap({encodeStream:function(w,value){return w.bits(value,len)},decodeStream:function(r){return r.bits(len)}})};P.bigint=function(size,le,signed){return void 0===le&&(le=!1),void 0===signed&&(signed=!1),wrap({size:size,encodeStream:function(w,value){if("number"!=typeof value&&"bigint"!=typeof value)throw w.err("bigint: invalid value: ".concat(value));var _value=BigInt(value),bLen=BigInt(size);checkBounds(w,_value,8n*bLen,!!signed);var signBit=BigInt(2n)**BigInt(8n*bLen-1n);signed&&_value<0&&(_value|=signBit);for(var b=[],i=0;i<size;i++)b.push(Number(255n&_value)),_value>>=8n;var res=new Uint8Array(b).reverse();w.bytes(le?res.reverse():res)},decodeStream:function(r){var bLen=BigInt(size),value=r.bytes(size);le&&(value=swap(value));for(var b=swap(value),signBit=BigInt(2n)**BigInt(8n*bLen-1n),res=0n,i=0;i<b.length;i++)res|=BigInt(b[i])<<8n*BigInt(i);return signed&&res&signBit&&(res=(res^signBit)-signBit),checkBounds(r,res,8n*bLen,!!signed),res}})},P.U256LE=(0,P.bigint)(32,!0),P.U256BE=(0,P.bigint)(32,!1),P.I256LE=(0,P.bigint)(32,!0,!0),P.I256BE=(0,P.bigint)(32,!1,!0),P.U128LE=(0,P.bigint)(16,!0),P.U128BE=(0,P.bigint)(16,!1),P.I128LE=(0,P.bigint)(16,!0,!0),P.I128BE=(0,P.bigint)(16,!1,!0),P.U64LE=(0,P.bigint)(8,!0),P.U64BE=(0,P.bigint)(8,!1),P.I64LE=(0,P.bigint)(8,!0,!0),P.I64BE=(0,P.bigint)(8,!1,!0);P.int=function(size,le,signed){if(void 0===le&&(le=!1),void 0===signed&&(signed=!1),size>6)throw new Error("int supports size up to 6 bytes (48 bits), for other use bigint");return apply((0,P.bigint)(size,le,signed),P.coders.number)},P.U32LE=(0,P.int)(4,!0),P.U32BE=(0,P.int)(4,!1),P.I32LE=(0,P.int)(4,!0,!0),P.I32BE=(0,P.int)(4,!1,!0),P.U16LE=(0,P.int)(2,!0),P.U16BE=(0,P.int)(2,!1),P.I16LE=(0,P.int)(2,!0,!0),P.I16BE=(0,P.int)(2,!1,!0),P.U8=(0,P.int)(1,!1),P.I8=(0,P.int)(1,!1,!0),P.bool=wrap({size:1,encodeStream:function(w,value){return w.byte(value?1:0)},decodeStream:function(r){var value=r.byte();if(0!==value&&1!==value)throw r.err("bool: invalid value ".concat(value));return 1===value}});var bytes=function(len,le){return void 0===le&&(le=!1),wrap({size:"number"==typeof len?len:void 0,encodeStream:function(w,value){if(!(0,P.isBytes)(value))throw w.err("bytes: invalid value ".concat(value));(0,P.isBytes)(len)||w.length(len,value.length),w.bytes(le?swap(value):value),(0,P.isBytes)(len)&&w.bytes(len)},decodeStream:function(r){var bytes;if((0,P.isBytes)(len)){var tPos=r.find(len);if(!tPos)throw r.err("bytes: cannot find terminator");bytes=r.bytes(tPos-r.pos),r.bytes(len.length)}else bytes=r.bytes(null===len?r.leftBytes:r.length(len));return le?swap(bytes):bytes}})};P.bytes=bytes;P.string=function(len,le){void 0===le&&(le=!1);var inner=(0,P.bytes)(len,le);return wrap({size:inner.size,encodeStream:function(w,value){return inner.encodeStream(w,base.utf8.decode(value))},decodeStream:function(r){return base.utf8.encode(inner.decodeStream(r))}})},P.cstring=(0,P.string)(P.NULL);function apply(inner,b){if(!isCoder(inner))throw new Error("apply: invalid inner value ".concat(inner));return wrap({size:inner.size,encodeStream:function(w,value){var innerValue;try{innerValue=b.decode(value)}catch(e){throw w.err(""+e)}return inner.encodeStream(w,innerValue)},decodeStream:function(r){var innerValue=inner.decodeStream(r);try{return b.encode(innerValue)}catch(e){throw r.err(""+e)}}})}P.hex=function(len,le,withZero){void 0===le&&(le=!1),void 0===withZero&&(withZero=!1);var inner=(0,P.bytes)(len,le);return wrap({size:inner.size,encodeStream:function(w,value){if(withZero&&!value.startsWith("0x"))throw new Error("hex(withZero=true).encode input should start with 0x");var bytes=base.hex.decode(withZero?value.slice(2):value);return inner.encodeStream(w,bytes)},decodeStream:function(r){return(withZero?"0x":"")+base.hex.encode(inner.decodeStream(r))}})},P.apply=apply,P.validate=function(inner,fn){if(!isCoder(inner))throw new Error("validate: invalid inner value ".concat(inner));return wrap({size:inner.size,encodeStream:function(w,value){return inner.encodeStream(w,fn(value))},decodeStream:function(r){return fn(inner.decodeStream(r))}})},P.lazy=function(fn){return wrap({encodeStream:function(w,value){return fn().encodeStream(w,value)},decodeStream:function(r){return fn().decodeStream(r)}})};P.bytesFormatted=function(len,fmt,le){void 0===le&&(le=!1);var inner=(0,P.bytes)(len,le);return wrap({size:inner.size,encodeStream:function(w,value){return inner.encodeStream(w,base.bytes(fmt,value))},decodeStream:function(r){return base.str(fmt,inner.decodeStream(r))}})};function magic(inner,constant,check){if(void 0===check&&(check=!0),!isCoder(inner))throw new Error("flagged: invalid inner value ".concat(inner));return wrap({size:inner.size,encodeStream:function(w,value){return inner.encodeStream(w,constant)},decodeStream:function(r){var value=inner.decodeStream(r);if(check&&"object"!=typeof value&&value!==constant||(0,P.isBytes)(constant)&&!equalBytes(constant,value))throw r.err("magic: invalid value: ".concat(value," !== ").concat(constant))}})}P.flag=function(flagValue,xor){return void 0===xor&&(xor=!1),wrap({size:flagValue.length,encodeStream:function(w,value){!!value!==xor&&w.bytes(flagValue)},decodeStream:function(r){var hasFlag=r.leftBytes>=flagValue.length;return hasFlag&&(hasFlag=equalBytes(r.bytes(flagValue.length,!0),flagValue))&&r.bytes(flagValue.length),hasFlag!==xor}})},P.flagged=function(path,inner,def){if(!isCoder(inner))throw new Error("flagged: invalid inner value ".concat(inner));return wrap({encodeStream:function(w,value){"string"==typeof path?getPath(w.path,path.split("/"))?inner.encodeStream(w,value):def&&inner.encodeStream(w,def):(path.encodeStream(w,!!value),value?inner.encodeStream(w,value):def&&inner.encodeStream(w,def))},decodeStream:function(r){if("string"==typeof path?getPath(r.path,path.split("/")):path.decodeStream(r))return inner.decodeStream(r);def&&inner.decodeStream(r)}})},P.optional=function(flag,inner,def){if(!isCoder(flag)||!isCoder(inner))throw new Error("optional: invalid flag or inner value flag=".concat(flag," inner=").concat(inner));return wrap({size:void 0!==def&&flag.size&&inner.size?flag.size+inner.size:void 0,encodeStream:function(w,value){flag.encodeStream(w,!!value),value?inner.encodeStream(w,value):void 0!==def&&inner.encodeStream(w,def)},decodeStream:function(r){if(flag.decodeStream(r))return inner.decodeStream(r);void 0!==def&&inner.decodeStream(r)}})},P.magic=magic;function sizeof(fields){for(var size=0,_i=0,fields_1=fields;_i<fields_1.length;_i++){var f=fields_1[_i];if(!f.size)return;size+=f.size}return size}function array(len,inner){if(!isCoder(inner))throw new Error("array: invalid inner value ".concat(inner));return wrap({size:"number"==typeof len&&inner.size?len*inner.size:void 0,encodeStream:function(w,value){if(!Array.isArray(value))throw w.err("array: invalid value ".concat(value));(0,P.isBytes)(len)||w.length(len,value.length),w.path.push(value);for(var i=0;i<value.length;i++){w.fieldPathPush(""+i);var elm=value[i],startPos=w.pos;if(inner.encodeStream(w,elm),(0,P.isBytes)(len)){if(len.length>w.pos-startPos)continue;var data=w.buffer.subarray(startPos,w.pos);if(equalBytes(data.subarray(0,len.length),len))throw w.err("array: inner element encoding same as separator. elm=".concat(elm," data=").concat(data))}w.fieldPathPop()}w.path.pop(),(0,P.isBytes)(len)&&w.bytes(len)},decodeStream:function(r){var res=[];if(null===len){var i=0;for(r.path.push(res);!(r.isEnd()||(r.fieldPathPush(""+i++),res.push(inner.decodeStream(r)),r.fieldPathPop(),inner.size&&r.leftBytes<inner.size)););r.path.pop()}else if((0,P.isBytes)(len)){i=0;for(r.path.push(res);;){if(equalBytes(r.bytes(len.length,!0),len)){r.bytes(len.length);break}r.fieldPathPush(""+i++),res.push(inner.decodeStream(r)),r.fieldPathPop()}r.path.pop()}else{r.fieldPathPush("arrayLen");var length=r.length(len);r.fieldPathPop(),r.path.push(res);for(i=0;i<length;i++)r.fieldPathPush(""+i),res.push(inner.decodeStream(r)),r.fieldPathPop();r.path.pop()}return res}})}function map(inner,variants){if(!isCoder(inner))throw new Error("map: invalid inner value ".concat(inner));var variantNames=new Map;for(var k in variants)variantNames.set(variants[k],k);return wrap({size:inner.size,encodeStream:function(w,value){if("string"!=typeof value)throw w.err("map: invalid value ".concat(value));if(!(value in variants))throw w.err("Map: unknown variant: ".concat(value));inner.encodeStream(w,variants[value])},decodeStream:function(r){var variant=inner.decodeStream(r),name=variantNames.get(variant);if(void 0===name)throw r.err("Enum: unknown value: ".concat(variant," ").concat(Array.from(variantNames.keys())));return name}})}function tag(tag,variants){if(!isCoder(tag))throw new Error("tag: invalid tag value ".concat(tag));return wrap({size:tag.size,encodeStream:function(w,value){var TAG=value.TAG,data=value.data,dataType=variants[TAG];if(!dataType)throw w.err("Tag: invalid tag ".concat(TAG.toString()));tag.encodeStream(w,TAG),dataType.encodeStream(w,data)},decodeStream:function(r){var TAG=tag.decodeStream(r),dataType=variants[TAG];if(!dataType)throw r.err("Tag: invalid tag ".concat(TAG));return{TAG:TAG,data:dataType.decodeStream(r)}}})}P.magicBytes=function(constant){var c="string"==typeof constant?base.utf8.decode(constant):constant;return magic((0,P.bytes)(c.length),c)},P.constant=function(c){return wrap({encodeStream:function(w,value){if(value!==c)throw new Error("constant: invalid value ".concat(value," (exp: ").concat(c,")"))},decodeStream:function(r){return c}})},P.struct=function(fields){if(Array.isArray(fields))throw new Error("Packed.Struct: got array instead of object");return wrap({size:sizeof(Object.values(fields)),encodeStream:function(w,value){if("object"!=typeof value||null===value)throw w.err("struct: invalid value ".concat(value));for(var name in w.path.push(value),fields){w.fieldPathPush(name),fields[name].encodeStream(w,value[name]),w.fieldPathPop()}w.path.pop()},decodeStream:function(r){var res={};for(var name in r.path.push(res),fields)r.fieldPathPush(name),res[name]=fields[name].decodeStream(r),r.fieldPathPop();return r.path.pop(),res}})},P.tuple=function(fields){if(!Array.isArray(fields))throw new Error("Packed.Tuple: got ".concat(typeof fields," instead of array"));return wrap({size:sizeof(fields),encodeStream:function(w,value){if(!Array.isArray(value))throw w.err("tuple: invalid value ".concat(value));w.path.push(value);for(var i=0;i<fields.length;i++)w.fieldPathPush(""+i),fields[i].encodeStream(w,value[i]),w.fieldPathPop();w.path.pop()},decodeStream:function(r){var res=[];r.path.push(res);for(var i=0;i<fields.length;i++)r.fieldPathPush(""+i),res.push(fields[i].decodeStream(r)),r.fieldPathPop();return r.path.pop(),res}})},P.prefix=function(len,inner){if(!isCoder(inner))throw new Error("prefix: invalid inner value ".concat(inner));if((0,P.isBytes)(len))throw new Error("prefix: len cannot be Uint8Array");var b=(0,P.bytes)(len);return wrap({size:"number"==typeof len?len:void 0,encodeStream:function(w,value){var wChild=new Writer(w.path,w.fieldPath);inner.encodeStream(wChild,value),b.encodeStream(w,wChild.buffer)},decodeStream:function(r){var data=b.decodeStream(r);return inner.decodeStream(new Reader(data,r.path,r.fieldPath))}})},P.array=array,P.map=map,P.tag=tag,P.mappedTag=function(tagCoder,variants){if(!isCoder(tagCoder))throw new Error("mappedTag: invalid tag value ".concat(tag));var mapValue={},tagValue={};for(var key in variants)mapValue[key]=variants[key][0],tagValue[key]=variants[key][1];return tag(map(tagCoder,mapValue),tagValue)},P.bitset=function(names,pad){return void 0===pad&&(pad=!1),wrap({encodeStream:function(w,value){if("object"!=typeof value||null===value)throw w.err("bitset: invalid value ".concat(value));for(var i=0;i<names.length;i++)w.bits(+value[names[i]],1);pad&&names.length%8&&w.bits(0,8-names.length%8)},decodeStream:function(r){for(var out={},i=0;i<names.length;i++)out[names[i]]=!!r.bits(1);return pad&&names.length%8&&r.bits(8-names.length%8),out}})};function padLength(blockSize,len){return len%blockSize==0?0:blockSize-len%blockSize}P.ZeroPad=function(_){return 0},P.padLeft=function(blockSize,inner,padFn){if(!isCoder(inner))throw new Error("padLeft: invalid inner value ".concat(inner));var _padFn=padFn||P.ZeroPad;if(!inner.size)throw new Error("padLeft with dynamic size argument is impossible");return wrap({size:inner.size+padLength(blockSize,inner.size),encodeStream:function(w,value){for(var padBytes=padLength(blockSize,inner.size),i=0;i<padBytes;i++)w.byte(_padFn(i));inner.encodeStream(w,value)},decodeStream:function(r){return r.bytes(padLength(blockSize,inner.size)),inner.decodeStream(r)}})},P.padRight=function(blockSize,inner,padFn){if(!isCoder(inner))throw new Error("padRight: invalid inner value ".concat(inner));var _padFn=padFn||P.ZeroPad;return wrap({size:inner.size?inner.size+padLength(blockSize,inner.size):void 0,encodeStream:function(w,value){var pos=w.pos;inner.encodeStream(w,value);for(var padBytes=padLength(blockSize,w.pos-pos),i=0;i<padBytes;i++)w.byte(_padFn(i))},decodeStream:function(r){var start=r.pos,res=inner.decodeStream(r);return r.bytes(padLength(blockSize,r.pos-start)),res}})},P.pointer=function(ptr,inner,sized){if(void 0===sized&&(sized=!1),!isCoder(ptr))throw new Error("pointer: invalid ptr value ".concat(ptr));if(!isCoder(inner))throw new Error("pointer: invalid inner value ".concat(inner));if(!ptr.size)throw new Error("Pointer: unsized ptr");return wrap({size:sized?ptr.size:void 0,encodeStream:function(w,value){var start=w.pos;ptr.encodeStream(w,0),w.ptrs.push({pos:start,ptr:ptr,buffer:inner.encode(value)})},decodeStream:function(r){var ptrVal=ptr.decodeStream(r);if(ptrVal<r.pos)throw new Error("pointer.decodeStream pointer less than position");r.hasPtr=!0;var rChild=new Reader(r.absBytes(ptrVal),r.path,r.fieldPath);return inner.decodeStream(rChild)}})},P.base64armor=function(name,lineLen,inner,checksum){var markBegin="-----BEGIN ".concat(name.toUpperCase(),"-----"),markEnd="-----END ".concat(name.toUpperCase(),"-----");return{encode:function(value){for(var data=inner.encode(value),encoded=base.base64.encode(data),lines=[],i=0;i<encoded.length;i+=lineLen){encoded.slice(i,i+lineLen).length&&lines.push("".concat(encoded.slice(i,i+lineLen),"\n"))}var body=lines.join("");return checksum&&(body+="=".concat(base.base64.encode(checksum(data)),"\n")),"".concat(markBegin,"\n\n").concat(body).concat(markEnd,"\n")},decode:function(s){var lines=s.replace(markBegin,"").replace(markEnd,"").trim().split("\n");if(lines=lines.map((function(l){return l.replace("\r","").trim()})),checksum&&lines[lines.length-1].startsWith("=")){var body=base.base64.decode(lines.slice(0,-1).join("")),cs=lines[lines.length-1].slice(1),realCS=base.base64.encode(checksum(body));if(realCS!==cs)throw new Error("Base64Armor: invalid checksum ".concat(cs," instead of ").concat(realCS));return inner.decode(body)}return inner.decode(base.base64.decode(lines.join("")))}}},P.nothing=magic((0,P.bytes)(0),P.EMPTY),P.debug=function(inner){if(!isCoder(inner))throw new Error("debug: invalid inner value ".concat(inner));var log=function(name,rw,value){return console.log("DEBUG/".concat(name,"(").concat(rw.fieldPath.join("/"),"):"),{type:typeof value,value:value}),value};return wrap({size:inner.size,encodeStream:function(w,value){return inner.encodeStream(w,log("encode",w,value))},decodeStream:function(r){return log("decode",r,inner.decodeStream(r))}})};__assign=this&&this.__assign||function(){return __assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++)for(var p in s=arguments[i])Object.prototype.hasOwnProperty.call(s,p)&&(t[p]=s[p]);return t},__assign.apply(this,arguments)};var __spreadArray=this&&this.__spreadArray||function(to,from,pack){if(pack||2===arguments.length)for(var ar,i=0,l=from.length;i<l;i++)!ar&&i in from||(ar||(ar=Array.prototype.slice.call(from,0,i)),ar[i]=from[i]);return to.concat(ar||Array.prototype.slice.call(from))};Object.defineProperty(taproot,"__esModule",{value:!0}),taproot.Transaction=taproot.tapLeafHash=taproot.TAP_LEAF_VERSION=taproot._sortPubkeys=taproot.SigHashCoder=taproot.SignatureHash=taproot.Address=taproot.WIF=taproot.parseWitnessProgram=taproot.programToWitness=taproot.OutScript=taproot.p2tr_ms=taproot.p2tr_pk=taproot.p2tr_ns=taproot.combinations=taproot.p2tr=taproot.TAPROOT_UNSPENDABLE_KEY=taproot.taprootListToTree=taproot.p2ms=taproot.p2wpkh=taproot.p2wsh=taproot.p2sh=taproot.p2pkh=taproot.p2pk=taproot.RawPSBTV2=taproot.RawPSBTV0=taproot._DebugPSBT=taproot._RawPSBTV2=taproot._RawPSBTV0=taproot.TaprootControlBlock=taproot.RawTx=taproot.RawWitness=taproot.RawOutput=taproot.RawInput=taproot.VarBytes=taproot.BTCArray=taproot.CompactSize=taproot.Script=taproot.OPNum=taproot.OP=taproot.cmp=taproot.decimal=taproot.DEFAULT_SEQUENCE=taproot.DEFAULT_LOCKTIME=taproot.DEFAULT_VERSION=taproot.PRECISION=taproot.NETWORK=taproot.taprootTweakPubkey=taproot.taprootTweakPrivKey=taproot.base58check=void 0,taproot.PSBTCombine=taproot.bip32Path=taproot.sortedMultisig=taproot.multisig=taproot.getAddress=void 0;
|
||
/*! micro-btc-signer - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||
var hash160=function(msg){return(0,ripemd160_1.ripemd160)((0,sha256_1.sha256)(msg))},sha256x2=function(){for(var msgs=[],_i=0;_i<arguments.length;_i++)msgs[_i]=arguments[_i];return(0,sha256_1.sha256)((0,sha256_1.sha256)(concat.apply(void 0,msgs)))},concat=P.concatBytes;taproot.base58check=base.base58check(sha256_1.sha256),secp.utils.hmacSha256Sync=function(key){for(var msgs=[],_i=1;_i<arguments.length;_i++)msgs[_i-1]=arguments[_i];return(0,hmac_1.hmac)(sha256_1.sha256,key,concat.apply(void 0,msgs))},secp.utils.sha256Sync=function(){for(var msgs=[],_i=0;_i<arguments.length;_i++)msgs[_i]=arguments[_i];return(0,sha256_1.sha256)(concat.apply(void 0,msgs))};var PubT,taggedHash=secp.utils.taggedHashSync;!function(PubT){PubT[PubT.ecdsa=0]="ecdsa",PubT[PubT.schnorr=1]="schnorr"}(PubT||(PubT={}));var validatePubkey=function(pub,type){var len=pub.length;if(type===PubT.ecdsa){if(32===len)throw new Error("Expected non-Schnorr key")}else{if(type!==PubT.schnorr)throw new Error("Unknown key type");if(32!==len)throw new Error("Expected 32-byte Schnorr key")}return secp.Point.fromHex(pub),pub};function isValidPubkey(pub,type){try{return!!validatePubkey(pub,type)}catch(e){return!1}}var hasLowR=function(sig){return secp.Signature.fromHex(sig).toCompactRawBytes()[0]<128};function taprootTweakPrivKey(privKey,merkleRoot){void 0===merkleRoot&&(merkleRoot=new Uint8Array);var n=secp.CURVE.n,priv=secp.utils._normalizePrivateKey(privKey),point=secp.Point.fromPrivateKey(priv),tweak=taggedHash("TapTweak",point.toRawX(),merkleRoot),privWithProperY=point.hasEvenY()?priv:n-priv,tweaked=secp.utils.mod(privWithProperY+secp.utils._normalizePrivateKey(tweak),n);return secp.utils._bigintTo32Bytes(tweaked)}function taprootTweakPubkey(pubKey,h){var tweak=taggedHash("TapTweak",pubKey,h),tweaked=secp.Point.fromHex(pubKey).add(secp.Point.fromPrivateKey(tweak));return[tweaked.toRawX(),!tweaked.hasEvenY()]}taproot.taprootTweakPrivKey=taprootTweakPrivKey,taproot.taprootTweakPubkey=taprootTweakPubkey;var PubKeyECDSA=P.validate(P.bytes(null),(function(pub){return validatePubkey(pub,PubT.ecdsa)})),PubKeySchnorr=P.validate(P.bytes(32),(function(pub){return validatePubkey(pub,PubT.schnorr)})),SignatureSchnorr=P.validate(P.bytes(null),(function(sig){if(64!==sig.length&&65!==sig.length)throw new Error("Schnorr signature should be 64 or 65 bytes long");return sig}));function uniqPubkey(pubkeys){for(var map={},_i=0,pubkeys_1=pubkeys;_i<pubkeys_1.length;_i++){var pub=pubkeys_1[_i],key=base.hex.encode(pub);if(map[key])throw new Error("Multisig: non-uniq pubkey: ".concat(pubkeys.map(base.hex.encode)));map[key]=!0}}taproot.NETWORK={bech32:"bc",pubKeyHash:0,scriptHash:5,wif:128},taproot.PRECISION=8,taproot.DEFAULT_VERSION=2,taproot.DEFAULT_LOCKTIME=0,taproot.DEFAULT_SEQUENCE=4294967293;var OP,OPNum,EMPTY32=new Uint8Array(32),decimal={decode:function(numberAsString){return parseInt(1e8*numberAsString)}};taproot.decimal=decimal;function cmp(a,b){if(a instanceof Uint8Array&&b instanceof Uint8Array){for(var len=Math.min(a.length,b.length),i=0;i<len;i++)if(a[i]!=b[i])return Math.sign(a[i]-b[i]);return Math.sign(a.length-b.length)}if(a instanceof Uint8Array||b instanceof Uint8Array)throw new Error("cmp: wrong values a=".concat(a," b=").concat(b));if(("bigint"==typeof a&&"number"==typeof b||"number"==typeof a&&"bigint"==typeof b)&&(a=BigInt(a),b=BigInt(b)),void 0===a||void 0===b)throw new Error("cmp: wrong values a=".concat(a," b=").concat(b));return Number(a>b)-Number(a<b)}function OPtoNumber(op){if("string"==typeof op&&void 0!==OP[op]&&void 0!==OPNum[op])return OPNum[op]}taproot.Decimal=class{static decode(bitcoinAmount){return BigInt(Math.floor(1e8*parseFloat(bitcoinAmount)))}static encode(satoshis){return(Number(satoshis)/1e8).toFixed(8)}},taproot.cmp=cmp,function(OP){OP[OP.OP_0=0]="OP_0",OP[OP.PUSHDATA1=76]="PUSHDATA1",OP[OP.PUSHDATA2=77]="PUSHDATA2",OP[OP.PUSHDATA4=78]="PUSHDATA4",OP[OP["1NEGATE"]=79]="1NEGATE",OP[OP.RESERVED=80]="RESERVED",OP[OP.OP_1=81]="OP_1",OP[OP.OP_2=82]="OP_2",OP[OP.OP_3=83]="OP_3",OP[OP.OP_4=84]="OP_4",OP[OP.OP_5=85]="OP_5",OP[OP.OP_6=86]="OP_6",OP[OP.OP_7=87]="OP_7",OP[OP.OP_8=88]="OP_8",OP[OP.OP_9=89]="OP_9",OP[OP.OP_10=90]="OP_10",OP[OP.OP_11=91]="OP_11",OP[OP.OP_12=92]="OP_12",OP[OP.OP_13=93]="OP_13",OP[OP.OP_14=94]="OP_14",OP[OP.OP_15=95]="OP_15",OP[OP.OP_16=96]="OP_16",OP[OP.NOP=97]="NOP",OP[OP.VER=98]="VER",OP[OP.IF=99]="IF",OP[OP.NOTIF=100]="NOTIF",OP[OP.VERIF=101]="VERIF",OP[OP.VERNOTIF=102]="VERNOTIF",OP[OP.ELSE=103]="ELSE",OP[OP.ENDIF=104]="ENDIF",OP[OP.VERIFY=105]="VERIFY",OP[OP.RETURN=106]="RETURN",OP[OP.TOALTSTACK=107]="TOALTSTACK",OP[OP.FROMALTSTACK=108]="FROMALTSTACK",OP[OP["2DROP"]=109]="2DROP",OP[OP["2DUP"]=110]="2DUP",OP[OP["3DUP"]=111]="3DUP",OP[OP["2OVER"]=112]="2OVER",OP[OP["2ROT"]=113]="2ROT",OP[OP["2SWAP"]=114]="2SWAP",OP[OP.IFDUP=115]="IFDUP",OP[OP.DEPTH=116]="DEPTH",OP[OP.DROP=117]="DROP",OP[OP.DUP=118]="DUP",OP[OP.NIP=119]="NIP",OP[OP.OVER=120]="OVER",OP[OP.PICK=121]="PICK",OP[OP.ROLL=122]="ROLL",OP[OP.ROT=123]="ROT",OP[OP.SWAP=124]="SWAP",OP[OP.TUCK=125]="TUCK",OP[OP.CAT=126]="CAT",OP[OP.SUBSTR=127]="SUBSTR",OP[OP.LEFT=128]="LEFT",OP[OP.RIGHT=129]="RIGHT",OP[OP.SIZE=130]="SIZE",OP[OP.INVERT=131]="INVERT",OP[OP.AND=132]="AND",OP[OP.OR=133]="OR",OP[OP.XOR=134]="XOR",OP[OP.EQUAL=135]="EQUAL",OP[OP.EQUALVERIFY=136]="EQUALVERIFY",OP[OP.RESERVED1=137]="RESERVED1",OP[OP.RESERVED2=138]="RESERVED2",OP[OP["1ADD"]=139]="1ADD",OP[OP["1SUB"]=140]="1SUB",OP[OP["2MUL"]=141]="2MUL",OP[OP["2DIV"]=142]="2DIV",OP[OP.NEGATE=143]="NEGATE",OP[OP.ABS=144]="ABS",OP[OP.NOT=145]="NOT",OP[OP["0NOTEQUAL"]=146]="0NOTEQUAL",OP[OP.ADD=147]="ADD",OP[OP.SUB=148]="SUB",OP[OP.MUL=149]="MUL",OP[OP.DIV=150]="DIV",OP[OP.MOD=151]="MOD",OP[OP.LSHIFT=152]="LSHIFT",OP[OP.RSHIFT=153]="RSHIFT",OP[OP.BOOLAND=154]="BOOLAND",OP[OP.BOOLOR=155]="BOOLOR",OP[OP.NUMEQUAL=156]="NUMEQUAL",OP[OP.NUMEQUALVERIFY=157]="NUMEQUALVERIFY",OP[OP.NUMNOTEQUAL=158]="NUMNOTEQUAL",OP[OP.LESSTHAN=159]="LESSTHAN",OP[OP.GREATERTHAN=160]="GREATERTHAN",OP[OP.LESSTHANOREQUAL=161]="LESSTHANOREQUAL",OP[OP.GREATERTHANOREQUAL=162]="GREATERTHANOREQUAL",OP[OP.MIN=163]="MIN",OP[OP.MAX=164]="MAX",OP[OP.WITHIN=165]="WITHIN",OP[OP.RIPEMD160=166]="RIPEMD160",OP[OP.SHA1=167]="SHA1",OP[OP.SHA256=168]="SHA256",OP[OP.HASH160=169]="HASH160",OP[OP.HASH256=170]="HASH256",OP[OP.CODESEPARATOR=171]="CODESEPARATOR",OP[OP.CHECKSIG=172]="CHECKSIG",OP[OP.CHECKSIGVERIFY=173]="CHECKSIGVERIFY",OP[OP.CHECKMULTISIG=174]="CHECKMULTISIG",OP[OP.CHECKMULTISIGVERIFY=175]="CHECKMULTISIGVERIFY",OP[OP.NOP1=176]="NOP1",OP[OP.CHECKLOCKTIMEVERIFY=177]="CHECKLOCKTIMEVERIFY",OP[OP.CHECKSEQUENCEVERIFY=178]="CHECKSEQUENCEVERIFY",OP[OP.NOP4=179]="NOP4",OP[OP.NOP5=180]="NOP5",OP[OP.NOP6=181]="NOP6",OP[OP.NOP7=182]="NOP7",OP[OP.NOP8=183]="NOP8",OP[OP.NOP9=184]="NOP9",OP[OP.NOP10=185]="NOP10",OP[OP.CHECKSIGADD=186]="CHECKSIGADD",OP[OP.INVALID=255]="INVALID"}(OP=taproot.OP||(taproot.OP={})),function(OPNum){OPNum[OPNum.OP_0=0]="OP_0",OPNum[OPNum.OP_1=1]="OP_1",OPNum[OPNum.OP_2=2]="OP_2",OPNum[OPNum.OP_3=3]="OP_3",OPNum[OPNum.OP_4=4]="OP_4",OPNum[OPNum.OP_5=5]="OP_5",OPNum[OPNum.OP_6=6]="OP_6",OPNum[OPNum.OP_7=7]="OP_7",OPNum[OPNum.OP_8=8]="OP_8",OPNum[OPNum.OP_9=9]="OP_9",OPNum[OPNum.OP_10=10]="OP_10",OPNum[OPNum.OP_11=11]="OP_11",OPNum[OPNum.OP_12=12]="OP_12",OPNum[OPNum.OP_13=13]="OP_13",OPNum[OPNum.OP_14=14]="OP_14",OPNum[OPNum.OP_15=15]="OP_15",OPNum[OPNum.OP_16=16]="OP_16"}(OPNum=taproot.OPNum||(taproot.OPNum={})),taproot.Script=P.wrap({encodeStream:function(w,value){for(var _i=0,value_1=value;_i<value_1.length;_i++){var o=value_1[_i];if("string"!=typeof o){var len=o.length;len<OP.PUSHDATA1?w.byte(len):len<=255?(w.byte(OP.PUSHDATA1),w.byte(len)):len<=65535?(w.byte(OP.PUSHDATA2),w.bytes(P.U16LE.encode(len))):(w.byte(OP.PUSHDATA4),w.bytes(P.U32LE.encode(len))),w.bytes(o)}else{if(void 0===OP[o])throw new Error("Unknown opcode=".concat(o));w.byte(OP[o])}}},decodeStream:function(r){for(var out=[];!r.isEnd();){var cur=r.byte();if(OP.OP_0<cur&&cur<=OP.PUSHDATA4){var len=void 0;if(cur<OP.PUSHDATA1)len=cur;else if(cur===OP.PUSHDATA1)len=P.U8.decodeStream(r);else if(cur===OP.PUSHDATA2)len=P.U16LE.decodeStream(r);else{if(cur!==OP.PUSHDATA4)throw new Error("Should be not possible");len=P.U32LE.decodeStream(r)}out.push(r.bytes(len))}else{var op=OP[cur];if(void 0===op)throw new Error("Unknown opcode=".concat(cur.toString(16)));out.push(op)}}return out}});var CSLimits={253:[253,2,253n,65535n],254:[254,4,65536n,4294967295n],255:[255,8,4294967296n,18446744073709551615n]};taproot.CompactSize=P.wrap({encodeStream:function(w,value){if("number"==typeof value&&(value=BigInt(value)),0n<=value&&value<=252n)return w.byte(Number(value));for(var _i=0,_a=Object.values(CSLimits);_i<_a.length;_i++){var _b=_a[_i],flag=_b[0],bytes=_b[1],start=_b[2],stop=_b[3];if(!(start>value||value>stop)){w.byte(flag);for(var i=0;i<bytes;i++)w.byte(Number(value>>8n*BigInt(i)&0xffn));return}}throw w.err("VarInt too big: ".concat(value))},decodeStream:function(r){var b0=r.byte();if(b0<=252)return BigInt(b0);for(var _a=CSLimits[b0],bytes=(_a[0],_a[1]),start=_a[2],num=0n,i=0;i<bytes;i++)num|=BigInt(r.byte())<<8n*BigInt(i);if(num<start)throw r.err("Wrong CompactSize(".concat(8*bytes,")"));return num}});var CompactSizeLen=P.apply(taproot.CompactSize,P.coders.number);taproot.BTCArray=function(t){return P.array(taproot.CompactSize,t)},taproot.VarBytes=P.bytes(taproot.CompactSize),taproot.RawInput=P.struct({hash:P.bytes(32,!0),index:P.U32LE,finalScriptSig:taproot.VarBytes,sequence:P.U32LE}),taproot.RawOutput=P.struct({amount:P.U64LE,script:taproot.VarBytes});var EMPTY_OUTPUT={amount:0xffffffffffffffffn,script:P.EMPTY};taproot.RawWitness=P.array(CompactSizeLen,taproot.VarBytes);var _RawTx=P.struct({version:P.I32LE,segwitFlag:P.flag(new Uint8Array([0,1])),inputs:(0,taproot.BTCArray)(taproot.RawInput),outputs:(0,taproot.BTCArray)(taproot.RawOutput),witnesses:P.flagged("segwitFlag",P.array("inputs/length",taproot.RawWitness)),lockTime:P.U32LE});taproot.RawTx=P.validate(_RawTx,(function(tx){if(tx.segwitFlag&&tx.witnesses&&!tx.witnesses.length)throw new Error("Segwit flag with empty witnesses array");return tx}));var BIP32Der=P.struct({fingerprint:P.U32BE,path:P.array(null,P.U32LE)}),_TaprootControlBlock=P.struct({version:P.U8,internalKey:P.bytes(32),merklePath:P.array(null,P.bytes(32))});taproot.TaprootControlBlock=P.validate(_TaprootControlBlock,(function(cb){if(cb.merklePath.length>128)throw new Error("TaprootControlBlock: merklePath should be of length 0..128 (inclusive)");return cb}));var TaprootBIP32Der=P.struct({hashes:P.array(CompactSizeLen,P.bytes(32)),der:BIP32Der}),PSBTGlobal={unsignedTx:[0,!1,taproot.RawTx,[0],[2],[0]],xpub:[1,P.bytes(78),BIP32Der,[],[],[0,2]],txVersion:[2,!1,P.U32LE,[2],[0],[2]],fallbackLocktime:[3,!1,P.U32LE,[],[0],[2]],inputCount:[4,!1,CompactSizeLen,[2],[0],[2]],outputCount:[5,!1,CompactSizeLen,[2],[0],[2]],txModifiable:[6,!1,P.U8,[],[0],[2]],version:[251,!1,P.U32LE,[],[],[0,2]],propietary:[252,P.bytes(null),P.bytes(null),[],[],[0,2]]},PSBTInput={nonWitnessUtxo:[0,!1,taproot.RawTx,[],[],[0,2]],witnessUtxo:[1,!1,taproot.RawOutput,[],[],[0,2]],partialSig:[2,PubKeyECDSA,P.bytes(null),[],[],[0,2]],sighashType:[3,!1,P.U32LE,[],[],[0,2]],redeemScript:[4,!1,P.bytes(null),[],[],[0,2]],witnessScript:[5,!1,P.bytes(null),[],[],[0,2]],bip32Derivation:[6,PubKeyECDSA,BIP32Der,[],[],[0,2]],finalScriptSig:[7,!1,P.bytes(null),[],[],[0,2]],finalScriptWitness:[8,!1,taproot.RawWitness,[],[],[0,2]],porCommitment:[9,!1,P.bytes(null),[],[],[0,2]],ripemd160:[10,P.bytes(20),P.bytes(null),[],[],[0,2]],sha256:[11,P.bytes(32),P.bytes(null),[],[],[0,2]],hash160:[12,P.bytes(20),P.bytes(null),[],[],[0,2]],hash256:[13,P.bytes(32),P.bytes(null),[],[],[0,2]],hash:[14,!1,P.bytes(32),[2],[0],[2]],index:[15,!1,P.U32LE,[2],[0],[2]],sequence:[16,!1,P.U32LE,[],[0],[2]],requiredTimeLocktime:[17,!1,P.U32LE,[],[0],[2]],requiredHeightLocktime:[18,!1,P.U32LE,[],[0],[2]],tapKeySig:[19,!1,SignatureSchnorr,[],[],[0,2]],tapScriptSig:[20,P.struct({pubKey:PubKeySchnorr,leafHash:P.bytes(32)}),SignatureSchnorr,[],[],[0,2]],tapLeafScript:[21,taproot.TaprootControlBlock,P.bytes(null),[],[],[0,2]],tapBip32Derivation:[22,P.bytes(32),TaprootBIP32Der,[],[],[0,2]],tapInternalKey:[23,!1,PubKeySchnorr,[],[],[0,2]],tapMerkleRoot:[24,!1,P.bytes(32),[],[],[0,2]],propietary:[252,P.bytes(null),P.bytes(null),[],[],[0,2]]},PSBTInputFinalKeys=["hash","sequence","index","witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknown"],PSBTInputUnsignedKeys=["partialSig","finalScriptSig","finalScriptWitness","tapKeySig","tapScriptSig"],PSBTOutput={redeemScript:[0,!1,P.bytes(null),[],[],[0,2]],witnessScript:[1,!1,P.bytes(null),[],[],[0,2]],bip32Derivation:[2,PubKeyECDSA,BIP32Der,[],[],[0,2]],amount:[3,!1,P.I64LE,[2],[0],[2]],script:[4,!1,P.bytes(null),[2],[0],[2]],tapInternalKey:[5,!1,PubKeySchnorr,[],[],[0,2]],tapTree:[6,!1,P.array(null,P.struct({depth:P.U8,version:P.U8,script:taproot.VarBytes})),[],[],[0,2]],tapBip32Derivation:[7,PubKeySchnorr,TaprootBIP32Der,[],[],[0,2]],propietary:[252,P.bytes(null),P.bytes(null),[],[],[0,2]]},PSBTOutputUnsignedKeys=[],PSBTKeyPair=P.array(P.NULL,P.struct({key:P.prefix(CompactSizeLen,P.struct({type:CompactSizeLen,key:P.bytes(null)})),value:P.bytes(CompactSizeLen)})),PSBTUnknownKey=P.struct({type:CompactSizeLen,key:P.bytes(null)});function PSBTKeyMap(psbtEnum){var byType={};for(var k in psbtEnum){var _a=psbtEnum[k],num=_a[0],kc=_a[1],vc=_a[2];byType[num]=[k,kc,vc]}return P.wrap({encodeStream:function(w,value){var out=[],_loop_1=function(name){var val=value[name];if(void 0===val)return"continue";var _c=psbtEnum[name],type_1=_c[0],kc=_c[1],vc=_c[2];if(kc){var kv=val.map((function(_a){var k=_a[0],v=_a[1];return[kc.encode(k),vc.encode(v)]}));kv.sort((function(a,b){return cmp(a[0],b[0])}));for(var _d=0,kv_1=kv;_d<kv_1.length;_d++){var _e=kv_1[_d],key=_e[0],value_2=_e[1];out.push({key:{key:key,type:type_1},value:value_2})}}else out.push({key:{type:type_1,key:P.EMPTY},value:vc.encode(val)})};for(var name in psbtEnum)_loop_1(name);if(value.unknown){value.unknown.sort((function(a,b){return cmp(a[0],b[0])}));for(var _i=0,_a=value.unknown;_i<_a.length;_i++){var _b=_a[_i],k=_b[0],v=_b[1];out.push({key:PSBTUnknownKey.decode(k),value:v})}}PSBTKeyPair.encodeStream(w,out)},decodeStream:function(r){for(var out={},noKey={},_i=0,raw_1=PSBTKeyPair.decodeStream(r);_i<raw_1.length;_i++){var elm=raw_1[_i],name="unknown",key=elm.key.key,value=elm.value;if(byType[elm.key.type]){var _a=byType[elm.key.type],_name=_a[0],kc=_a[1],vc=_a[2];if(name=_name,!kc&&key.length)throw new Error("PSBT: Non-empty key for ".concat(name," (key=").concat(base.hex.encode(key)," value=").concat(base.hex.encode(value)));if(key=kc?kc.decode(key):void 0,value=vc.decode(value),!kc){if(out[name])throw new Error("PSBT: Same keys: ".concat(name," (key=").concat(key," value=").concat(value,")"));out[name]=value,noKey[name]=!0;continue}}else key=PSBTUnknownKey.encode({type:elm.key.type,key:elm.key.key});if(noKey[name])throw new Error("PSBT: Key type with empty key and no key=".concat(name," val=").concat(value));out[name]||(out[name]=[]),out[name].push([key,value])}return out}})}function checkWSH(s,witnessScript){if(!P.equalBytes(s.hash,(0,sha256_1.sha256)(witnessScript)))throw new Error("checkScript: wsh wrong witnessScript hash");var w=taproot.OutScript.decode(witnessScript);if("tr"===w.type||"tr_ns"===w.type||"tr_ms"===w.type)throw new Error("checkScript: P2".concat(w.type," cannot be wrapped in P2SH"));if("wpkh"===w.type||"sh"===w.type)throw new Error("checkScript: P2".concat(w.type," cannot be wrapped in P2WSH"))}function checkScript(script,redeemScript,witnessScript){if(script){var s=taproot.OutScript.decode(script);if("tr_ns"===s.type||"tr_ms"===s.type||"ms"===s.type||"pk"==s.type)throw new Error("checkScript: non-wrapped ".concat(s.type));if("sh"===s.type&&redeemScript){if(!P.equalBytes(s.hash,hash160(redeemScript)))throw new Error("checkScript: sh wrong redeemScript hash");if("tr"===(r=taproot.OutScript.decode(redeemScript)).type||"tr_ns"===r.type||"tr_ms"===r.type)throw new Error("checkScript: P2".concat(r.type," cannot be wrapped in P2SH"));if("sh"===r.type)throw new Error("checkScript: P2SH cannot be wrapped in P2SH")}"wsh"===s.type&&witnessScript&&checkWSH(s,witnessScript)}var r;redeemScript&&("wsh"===(r=taproot.OutScript.decode(redeemScript)).type&&witnessScript&&checkWSH(r,witnessScript))}var PSBTInputCoder=P.validate(PSBTKeyMap(PSBTInput),(function(i){if(i.finalScriptWitness&&!i.finalScriptWitness.length)throw new Error("validateInput: wmpty finalScriptWitness");if(i.partialSig&&!i.partialSig.length)throw new Error("Empty partialSig");if(i.partialSig)for(var _i=0,_a=i.partialSig;_i<_a.length;_i++){var _b=_a[_i],k=_b[0],v=_b[1];validatePubkey(k,PubT.ecdsa)}if(i.bip32Derivation)for(var _c=0,_d=i.bip32Derivation;_c<_d.length;_c++){var _e=_d[_c];k=_e[0],v=_e[1];validatePubkey(k,PubT.ecdsa)}if(void 0!==i.requiredTimeLocktime&&i.requiredTimeLocktime<5e8)throw new Error("validateInput: wrong timeLocktime=".concat(i.requiredTimeLocktime));if(void 0!==i.requiredHeightLocktime&&(i.requiredHeightLocktime<=0||i.requiredHeightLocktime>=5e8))throw new Error("validateInput: wrong heighLocktime=".concat(i.requiredHeightLocktime));if(i.nonWitnessUtxo&&void 0!==i.index){var last=i.nonWitnessUtxo.outputs.length-1;if(i.index>last)throw new Error("validateInput: index(".concat(i.index,") not in nonWitnessUtxo"));var prevOut=i.nonWitnessUtxo.outputs[i.index];if(i.witnessUtxo&&(!P.equalBytes(i.witnessUtxo.script,prevOut.script)||i.witnessUtxo.amount!==prevOut.amount))throw new Error("validateInput: witnessUtxo different from nonWitnessUtxo")}if(i.tapLeafScript)for(var _f=0,_g=i.tapLeafScript;_f<_g.length;_f++){var _h=_g[_f];k=_h[0],v=_h[1];if((254&k.version)!==v[v.length-1])throw new Error("validateInput: tapLeafScript version mimatch");if(1&v[v.length-1])throw new Error("validateInput: tapLeafScript version has parity bit!")}return i})),PSBTOutputCoder=P.validate(PSBTKeyMap(PSBTOutput),(function(o){if(o.bip32Derivation)for(var _i=0,_a=o.bip32Derivation;_i<_a.length;_i++){var _b=_a[_i],k=_b[0];_b[1];validatePubkey(k,PubT.ecdsa)}return o})),PSBTGlobalCoder=P.validate(PSBTKeyMap(PSBTGlobal),(function(g){if(0===(g.version||0)){if(!g.unsignedTx)throw new Error("PSBTv0: missing unsignedTx");if(g.unsignedTx.segwitFlag||g.unsignedTx.witnesses)throw new Error("PSBTv0: witness in unsingedTx");for(var _i=0,_a=g.unsignedTx.inputs;_i<_a.length;_i++){var inp=_a[_i];if(inp.finalScriptSig&&inp.finalScriptSig.length)throw new Error("PSBTv0: input scriptSig found in unsignedTx")}}return g}));function validatePSBTFields(version,info,lst){for(var k in lst)if("unknown"!==k&&info[k]){var _a=info[k].slice(-3),reqInc=_a[0],reqExc=_a[1],allowInc=_a[2];if(reqExc.includes(version)||!allowInc.includes(version))throw new Error("PSBTv".concat(version,": field ").concat(k," is not allowed"))}for(var k in info){var _b=info[k].slice(-3);reqInc=_b[0],reqExc=_b[1],allowInc=_b[2];if(reqInc.includes(version)&&void 0===lst[k])throw new Error("PSBTv".concat(version,": missing required field ").concat(k))}}function cleanPSBTFields(version,info,lst){var out={};for(var k in lst){if("unknown"!==k){if(!info[k])continue;var _a=info[k].slice(-3),reqExc=(_a[0],_a[1]),allowInc=_a[2];if(reqExc.includes(version)||!allowInc.includes(version))continue}out[k]=lst[k]}return out}function validatePSBT(tx){var version=tx&&tx.global&&tx.global.version||0;validatePSBTFields(version,PSBTGlobal,tx.global);for(var _i=0,_a=tx.inputs;_i<_a.length;_i++){var i=_a[_i];validatePSBTFields(version,PSBTInput,i)}for(var _b=0,_c=tx.outputs;_b<_c.length;_b++){var o=_c[_b];validatePSBTFields(version,PSBTOutput,o)}var inputCount=version?tx.global.inputCount:tx.global.unsignedTx.inputs.length;if(tx.inputs.length<inputCount)throw new Error("Not enough inputs");var inputsLeft=tx.inputs.slice(inputCount);if(inputsLeft.length>1||inputsLeft.length&&Object.keys(inputsLeft[0]).length)throw new Error("Unexpected inputs left in tx=".concat(inputsLeft));var outputCount=version?tx.global.outputCount:tx.global.unsignedTx.outputs.length;if(tx.outputs.length<outputCount)throw new Error("Not outputs inputs");var outputsLeft=tx.outputs.slice(outputCount);if(outputsLeft.length>1||outputsLeft.length&&Object.keys(outputsLeft[0]).length)throw new Error("Unexpected outputs left in tx=".concat(outputsLeft));return tx}taproot._RawPSBTV0=P.struct({magic:P.magic(P.string(new Uint8Array([255])),"psbt"),global:PSBTGlobalCoder,inputs:P.array("global/unsignedTx/inputs/length",PSBTInputCoder),outputs:P.array(null,PSBTOutputCoder)}),taproot._RawPSBTV2=P.struct({magic:P.magic(P.string(new Uint8Array([255])),"psbt"),global:PSBTGlobalCoder,inputs:P.array("global/inputCount",PSBTInputCoder),outputs:P.array("global/outputCount",PSBTOutputCoder)}),taproot._DebugPSBT=P.struct({magic:P.magic(P.string(new Uint8Array([255])),"psbt"),items:P.array(null,P.apply(P.array(P.NULL,P.tuple([P.hex(CompactSizeLen),P.bytes(taproot.CompactSize)])),P.coders.dict()))});isPlainObject=function(obj){return"[object Object]"===Object.prototype.toString.call(obj)&&obj.constructor===Object};function mergeKeyMap(psbtEnum,val,cur,allowedFields){var res=__assign(__assign({},cur),val),_loop_2=function(k){var key=k,_a=psbtEnum[key],kC=(_a[0],_a[1]),vC=_a[2],cannotChange=allowedFields&&!allowedFields.includes(k);if(void 0===val[k]&&k in val){if(cannotChange)throw new Error("Cannot remove signed field=".concat(k));delete res[k]}else if(kC){var oldKV=cur&&cur[k]?cur[k]:[],newKV=val[key];if(newKV){if(!Array.isArray(newKV))throw new Error("keyMap(".concat(k,"): KV pairs should be [k, v][]"));newKV=newKV.map((function(val){if(2!==val.length)throw new Error("keyMap(".concat(k,"): KV pairs should be [k, v][]"));return["string"==typeof val[0]?kC.decode(base.hex.decode(val[0])):val[0],"string"==typeof val[1]?vC.decode(base.hex.decode(val[1])):val[1]]}));for(var map_1={},add=function(kStr,k,v){if(void 0!==map_1[kStr]){var oldVal=base.hex.encode(vC.encode(map_1[kStr][1])),newVal=base.hex.encode(vC.encode(v));if(oldVal!==newVal)throw new Error("keyMap(".concat(key,"): same key=").concat(kStr," oldVal=").concat(oldVal," newVal=").concat(newVal))}else map_1[kStr]=[k,v]},_i=0,oldKV_1=oldKV;_i<oldKV_1.length;_i++){var _b=oldKV_1[_i],k_1=_b[0],v=_b[1];add(kStr=base.hex.encode(kC.encode(k_1)),k_1,v)}for(var _c=0,newKV_1=newKV;_c<newKV_1.length;_c++){var _d=newKV_1[_c],k_2=_d[0],kStr=(v=_d[1],base.hex.encode(kC.encode(k_2)));void 0===v?delete map_1[kStr]:add(kStr,k_2,v)}res[key]=Object.values(map_1)}}else"string"==typeof res[k]&&(res[k]=vC.decode(base.hex.decode(res[k])))};for(var k in psbtEnum)_loop_2(k);for(var k in res)psbtEnum[k]||delete res[k];return res}taproot.RawPSBTV0=P.validate(taproot._RawPSBTV0,validatePSBT),taproot.RawPSBTV2=P.validate(taproot._RawPSBTV2,validatePSBT);var TxHashIdx=P.struct({hash:P.bytes(32,!0),index:P.U32LE}),OutPK=(isBytes=function(b){return b instanceof Uint8Array},{encode:function(from){if(2===from.length&&P.isBytes(from[0])&&isValidPubkey(from[0],PubT.ecdsa)&&"CHECKSIG"===from[1])return{type:"pk",pubkey:from[0]}},decode:function(to){return"pk"===to.type?[to.pubkey,"CHECKSIG"]:void 0}});taproot.p2pk=function(pubkey,network){if(void 0===network&&(network=taproot.NETWORK),!isValidPubkey(pubkey,PubT.ecdsa))throw new Error("P2PK: invalid publicKey");return{type:"pk",script:taproot.OutScript.encode({type:"pk",pubkey:pubkey})}};var OutPKH={encode:function(from){if(5===from.length&&"DUP"===from[0]&&"HASH160"===from[1]&&isBytes(from[2])&&"EQUALVERIFY"===from[3]&&"CHECKSIG"===from[4])return{type:"pkh",hash:from[2]}},decode:function(to){return"pkh"===to.type?["DUP","HASH160",to.hash,"EQUALVERIFY","CHECKSIG"]:void 0}};taproot.p2pkh=function(publicKey,network){if(void 0===network&&(network=taproot.NETWORK),!isValidPubkey(publicKey,PubT.ecdsa))throw new Error("P2PKH: invalid publicKey");var hash=hash160(publicKey);return{type:"pkh",script:taproot.OutScript.encode({type:"pkh",hash:hash}),address:Address(network).encode({type:"pkh",hash:hash})}};var OutSH={encode:function(from){if(3===from.length&&"HASH160"===from[0]&&isBytes(from[1])&&"EQUAL"===from[2])return{type:"sh",hash:from[1]}},decode:function(to){return"sh"===to.type?["HASH160",to.hash,"EQUAL"]:void 0}};taproot.p2sh=function(child,network){void 0===network&&(network=taproot.NETWORK);var hash=hash160(child.script);checkScript(taproot.OutScript.encode({type:"sh",hash:hash}),child.script,child.witnessScript);var res={type:"sh",redeemScript:child.script,script:taproot.OutScript.encode({type:"sh",hash:hash}),address:Address(network).encode({type:"sh",hash:hash})};return child.witnessScript&&(res.witnessScript=child.witnessScript),res};var OutWSH={encode:function(from){if(2===from.length&&"OP_0"===from[0]&&isBytes(from[1])&&32===from[1].length)return{type:"wsh",hash:from[1]}},decode:function(to){return"wsh"===to.type?["OP_0",to.hash]:void 0}};taproot.p2wsh=function(child,network){void 0===network&&(network=taproot.NETWORK);var hash=(0,sha256_1.sha256)(child.script);return checkScript(taproot.OutScript.encode({type:"wsh",hash:hash}),void 0,child.script),{type:"wsh",witnessScript:child.script,script:taproot.OutScript.encode({type:"wsh",hash:hash}),address:Address(network).encode({type:"wsh",hash:hash})}};var OutWPKH={encode:function(from){if(2===from.length&&"OP_0"===from[0]&&isBytes(from[1])&&20===from[1].length)return{type:"wpkh",hash:from[1]}},decode:function(to){return"wpkh"===to.type?["OP_0",to.hash]:void 0}};taproot.p2wpkh=function(publicKey,network){if(void 0===network&&(network=taproot.NETWORK),!isValidPubkey(publicKey,PubT.ecdsa))throw new Error("P2WPKH: invalid publicKey");if(65===publicKey.length)throw new Error("P2WPKH: uncompressed public key");var hash=hash160(publicKey);return{type:"wpkh",script:taproot.OutScript.encode({type:"wpkh",hash:hash}),address:Address(network).encode({type:"wpkh",hash:hash})}};var OutMS={encode:function(from){var last=from.length-1;if("CHECKMULTISIG"===from[last]){var m=OPtoNumber(from[0]),n=OPtoNumber(from[last-1]);if(void 0===m||void 0===n)throw new Error("OutScript.encode/multisig wrong params");var pubkeys=from.slice(1,-2);if(n!==pubkeys.length)throw new Error("OutScript.encode/multisig: wrong length");return{type:"ms",m:m,pubkeys:pubkeys}}},decode:function(to){return"ms"===to.type?__spreadArray(__spreadArray(["OP_".concat(to.m)],to.pubkeys,!0),["OP_".concat(to.pubkeys.length),"CHECKMULTISIG"],!1):void 0}};taproot.p2ms=function(m,pubkeys,allowSamePubkeys){return void 0===allowSamePubkeys&&(allowSamePubkeys=!1),allowSamePubkeys||uniqPubkey(pubkeys),{type:"ms",script:taproot.OutScript.encode({type:"ms",pubkeys:pubkeys,m:m})}};var OutTR={encode:function(from){if(2===from.length&&"OP_1"===from[0]&&isBytes(from[1]))return{type:"tr",pubkey:from[1]}},decode:function(to){return"tr"===to.type?["OP_1",to.pubkey]:void 0}};function taprootListToTree(taprootList){for(var lst=Array.from(taprootList);lst.length>=2;){lst.sort((function(a,b){return(b.weight||1)-(a.weight||1)}));var b=lst.pop(),a=lst.pop(),weight=((null==a?void 0:a.weight)||1)+((null==b?void 0:b.weight)||1);lst.push({weight:weight,childs:[a.childs||a,b.childs||b]})}var last=lst[0];return last.childs||last}function taprootHashTree(tree,allowUnknowOutput){var _a;if(void 0===allowUnknowOutput&&(allowUnknowOutput=!1),!tree)throw new Error("taprootHashTree: empty tree");if(Array.isArray(tree)&&1===tree.length&&(tree=tree[0]),!Array.isArray(tree)){var version=tree.leafVersion,leafScript=tree.script,tapInternalKey=tree.tapInternalKey;if(tree.tapLeafScript||tree.tapMerkleRoot&&!P.equalBytes(tree.tapMerkleRoot,P.EMPTY))throw new Error("P2TR: tapRoot leafScript cannot have tree");if(tapInternalKey&&P.equalBytes(tapInternalKey,taproot.TAPROOT_UNSPENDABLE_KEY))throw new Error("P2TR: tapRoot leafScript cannot have unspendble key");var script="string"==typeof leafScript?base.hex.decode(leafScript):leafScript;return function(script,allowUnknowOutput){void 0===allowUnknowOutput&&(allowUnknowOutput=!1);var out=taproot.OutScript.decode(script);if(!("unknown"===out.type&&allowUnknowOutput||["tr_ns","tr_ms"].includes(out.type)))throw new Error("P2TR: invalid leaf script=".concat(out.type))}(script,allowUnknowOutput),{type:"leaf",tapInternalKey:tapInternalKey,version:version,script:script,hash:(0,taproot.tapLeafHash)(script,version)}}if(2!==tree.length&&(tree=taprootListToTree(tree)),2!==tree.length)throw new Error("hashTree: non binary tree!");var left=taprootHashTree(tree[0],allowUnknowOutput),right=taprootHashTree(tree[1],allowUnknowOutput),_b=[left.hash,right.hash],lH=_b[0],rH=_b[1];return-1===cmp(rH,lH)&&(lH=(_a=[rH,lH])[0],rH=_a[1]),{type:"branch",left:left,right:right,hash:taggedHash("TapBranch",lH,rH)}}function taprootAddPath(tree,path){if(void 0===path&&(path=[]),!tree)throw new Error("taprootAddPath: empty tree");if("leaf"===tree.type)return __assign(__assign({},tree),{path:path});if("branch"!==tree.type)throw new Error("taprootAddPath: wrong type=".concat(tree));return __assign(__assign({},tree),{path:path,left:taprootAddPath(tree.left,__spreadArray([tree.right.hash],path,!0)),right:taprootAddPath(tree.right,__spreadArray([tree.left.hash],path,!0))})}function taprootWalkTree(tree){if(!tree)throw new Error("taprootAddPath: empty tree");if("leaf"===tree.type)return[tree];if("branch"!==tree.type)throw new Error("taprootWalkTree: wrong type=".concat(tree));return __spreadArray(__spreadArray([],taprootWalkTree(tree.left),!0),taprootWalkTree(tree.right),!0)}function p2tr(internalPubKey,tree,network,allowUnknowOutput){if(void 0===network&&(network=taproot.NETWORK),void 0===allowUnknowOutput&&(allowUnknowOutput=!1),!internalPubKey&&!tree)throw new Error("p2tr: should have pubKey or scriptTree (or both)");var pubKey="string"==typeof internalPubKey?base.hex.decode(internalPubKey):internalPubKey||taproot.TAPROOT_UNSPENDABLE_KEY;if(!isValidPubkey(pubKey,PubT.schnorr))throw new Error("p2tr: non-schnorr pubkey");var leaves,tapLeafScript,hashedTree=tree?taprootAddPath(taprootHashTree(tree,allowUnknowOutput)):void 0,tapMerkleRoot=hashedTree?hashedTree.hash:void 0,_a=taprootTweakPubkey(pubKey,tapMerkleRoot||P.EMPTY),tweakedPubkey=_a[0],parity=_a[1];hashedTree&&(leaves=taprootWalkTree(hashedTree).map((function(l){return __assign(__assign({},l),{controlBlock:taproot.TaprootControlBlock.encode({version:(l.version||taproot.TAP_LEAF_VERSION)+ +parity,internalKey:l.tapInternalKey||pubKey,merklePath:l.path})})}))),leaves&&(tapLeafScript=leaves.map((function(l){return[taproot.TaprootControlBlock.decode(l.controlBlock),concat(l.script,new Uint8Array([l.version||taproot.TAP_LEAF_VERSION]))]})));var res={type:"tr",script:taproot.OutScript.encode({type:"tr",pubkey:tweakedPubkey}),address:Address(network).encode({type:"tr",pubkey:tweakedPubkey}),tweakedPubkey:tweakedPubkey,tapInternalKey:pubKey};return leaves&&(res.leaves=leaves),tapLeafScript&&(res.tapLeafScript=tapLeafScript),tapMerkleRoot&&(res.tapMerkleRoot=tapMerkleRoot),res}taproot.taprootListToTree=taprootListToTree,taproot.taprootHashTree=taprootHashTree,taproot.taprootAddPath=taprootAddPath,taproot.taprootWalkTree=taprootWalkTree,taproot.TAPROOT_UNSPENDABLE_KEY=(0,sha256_1.sha256)(secp.Point.BASE.toRawBytes(!1)),taproot.p2tr=p2tr;var OutTRNS={encode:function(from){var last=from.length-1;if("CHECKSIG"===from[last]){for(var pubkeys=[],i=0;i<last;i++){var elm=from[i];if(1&i){if("CHECKSIGVERIFY"!==elm)return;if(i===last-1)return}else{if(!isBytes(elm))return;pubkeys.push(elm)}}return{type:"tr_ns",pubkeys:pubkeys}}},decode:function(to){if("tr_ns"===to.type){for(var out=[],i=0;i<to.pubkeys.length-1;i++)out.push(to.pubkeys[i],"CHECKSIGVERIFY");return out.push(to.pubkeys[to.pubkeys.length-1],"CHECKSIG"),out}}};function combinations(m,list){var res=[];if(!Array.isArray(list))throw new Error("combinations: lst arg should be array");var n=list.length;if(m>n)throw new Error("combinations: m > lst.length, no combinations possible");var idx=Array.from({length:m},(function(_,i){return i})),last=idx.length-1;main:for(;;){res.push(idx.map((function(i){return list[i]}))),idx[last]+=1;for(var i=last;i>=0&&idx[i]>n-m+i;i--){if(idx[i]=0,0===i)break main;idx[i-1]+=1}for(i+=1;i<idx.length;i++)idx[i]=idx[i-1]+1}return res}taproot.combinations=combinations;taproot.p2tr_ns=function(m,pubkeys,allowSamePubkeys){return void 0===allowSamePubkeys&&(allowSamePubkeys=!1),allowSamePubkeys||uniqPubkey(pubkeys),combinations(m,pubkeys).map((function(i){return{type:"tr_ns",script:taproot.OutScript.encode({type:"tr_ns",pubkeys:i})}}))};taproot.p2tr_pk=function(pubkey){return(0,taproot.p2tr_ns)(1,[pubkey],void 0)[0]};var OutTRMS={encode:function(from){var last=from.length-1;if("NUMEQUAL"===from[last]&&"CHECKSIG"===from[1]){var pubkeys=[],m=OPtoNumber(from[last-1]);if(void 0!==m){for(var i=0;i<last-1;i++){var elm=from[i];if(1&i){if(elm!==(1===i?"CHECKSIG":"CHECKSIGADD"))throw new Error("OutScript.encode/tr_ms: wrong element")}else{if(!isBytes(elm))throw new Error("OutScript.encode/tr_ms: wrong key element");pubkeys.push(elm)}}return{type:"tr_ms",pubkeys:pubkeys,m:m}}}},decode:function(to){if("tr_ms"===to.type){for(var out=[to.pubkeys[0],"CHECKSIG"],i=1;i<to.pubkeys.length;i++)out.push(to.pubkeys[i],"CHECKSIGADD");return out.push("OP_".concat(to.m),"NUMEQUAL"),out}}};taproot.p2tr_ms=function(m,pubkeys,allowSamePubkeys){return void 0===allowSamePubkeys&&(allowSamePubkeys=!1),allowSamePubkeys||uniqPubkey(pubkeys),{type:"tr_ms",script:taproot.OutScript.encode({type:"tr_ms",pubkeys:pubkeys,m:m})}};var SignatureHash,OutScripts=[OutPK,OutPKH,OutSH,OutWSH,OutWPKH,OutMS,OutTR,OutTRNS,OutTRMS,{encode:function(from){return{type:"unknown",script:taproot.Script.encode(from)}},decode:function(to){return"unknown"===to.type?taproot.Script.decode(to.script):void 0}}],_OutScript=P.apply(taproot.Script,P.coders.match(OutScripts));function validateWitness(version,data){if(data.length<2||data.length>40)throw new Error("Witness: invalid length");if(version>16)throw new Error("Witness: invalid version");if(0===version&&20!==data.length&&32!==data.length)throw new Error("Witness: invalid length for version")}function programToWitness(version,data,network){void 0===network&&(network=taproot.NETWORK),validateWitness(version,data);var coder=0===version?base.bech32:base.bech32m;return coder.encode(network.bech32,[version].concat(coder.toWords(data)))}function formatKey(hashed,prefix){return taproot.base58check.encode(concat(Uint8Array.from(prefix),hashed))}function Address(network){return void 0===network&&(network=taproot.NETWORK),{encode:function(from){var type=from.type;return"wpkh"===type||"wsh"===type?programToWitness(0,from.hash,network):"tr"===type?programToWitness(1,from.pubkey,network):"pkh"===type?formatKey(from.hash,[network.pubKeyHash]):"sh"===type?formatKey(from.hash,[network.scriptHash]):1},decode:function(address){if(address.length<14||address.length>74)throw new Error("Invalid address length");if(network.bech32&&address.toLowerCase().startsWith(network.bech32)){var res=void 0;try{if(0!==(res=base.bech32.decode(address)).words[0])throw new Error("bech32: wrong version=".concat(res.words[0]))}catch(_){if(0===(res=base.bech32m.decode(address)).words[0])throw new Error("bech32m: wrong version=".concat(res.words[0]))}if(res.prefix!==network.bech32)throw new Error("wrong bech32 prefix=".concat(res.prefix));var _a=res.words,version=_a[0],program=_a.slice(1),data_1=base.bech32.fromWords(program);if(validateWitness(version,data_1),0===version&&32===data_1.length)return{type:"wsh",hash:data_1};if(0===version&&20===data_1.length)return{type:"wpkh",hash:data_1};if(1===version&&32===data_1.length)return{type:"tr",pubkey:data_1};throw new Error("Unkown witness program")}var data=base.base58.decode(address);if(25!==data.length)throw new Error("Invalid base58 address");if(data[0]===network.pubKeyHash)return{type:"pkh",hash:(bytes=base.base58.decode(address)).slice(1,bytes.length-4)};if(data[0]===network.scriptHash){var bytes=base.base58.decode(address);return{type:"sh",hash:base.base58.decode(address).slice(1,bytes.length-4)}}throw new Error("Invalid address prefix=".concat(data[0]))}}}function unpackSighash(hashType){var masked=31&hashType;return{isAny:!!(128&hashType),isNone:2===masked,isSingle:3===masked}}taproot.OutScript=P.validate(_OutScript,(function(i){if("pk"===i.type&&!isValidPubkey(i.pubkey,PubT.ecdsa))throw new Error("OutScript/pk: wrong key");if(!("pkh"!==i.type&&"sh"!==i.type&&"wpkh"!==i.type||isBytes(i.hash)&&20===i.hash.length))throw new Error("OutScript/".concat(i.type,": wrong hash"));if("wsh"===i.type&&(!isBytes(i.hash)||32!==i.hash.length))throw new Error("OutScript/wsh: wrong hash");if(!("tr"!==i.type||isBytes(i.pubkey)&&isValidPubkey(i.pubkey,PubT.schnorr)))throw new Error("OutScript/tr: wrong taproot public key");if(("ms"===i.type||"tr_ns"===i.type||"tr_ms"===i.type)&&!Array.isArray(i.pubkeys))throw new Error("OutScript/multisig: wrong pubkeys array");if("ms"===i.type){for(var n=i.pubkeys.length,_i=0,_a=i.pubkeys;_i<_a.length;_i++){if(!isValidPubkey(_a[_i],PubT.ecdsa))throw new Error("OutScript/multisig: wrong pubkey")}if(i.m<=0||n>16||i.m>n)throw new Error("OutScript/multisig: invalid params")}if("tr_ns"===i.type||"tr_ms"===i.type)for(var _b=0,_c=i.pubkeys;_b<_c.length;_b++){if(!isValidPubkey(_c[_b],PubT.schnorr))throw new Error("OutScript/".concat(i.type,": wrong pubkey"))}if("tr_ms"===i.type){n=i.pubkeys.length;if(i.m<=0||n>16||i.m>n)throw new Error("OutScript/tr_ms: invalid params")}return i})),taproot.validateWitness=validateWitness,taproot.programToWitness=programToWitness,taproot.parseWitnessProgram=function(version,data){return validateWitness(version,data),concat(new Uint8Array([version>0?version+80:version]),taproot.VarBytes.encode(Uint8Array.from(data)))},taproot.WIF=function(network){return void 0===network&&(network=taproot.NETWORK),{encode:function(privKey){return formatKey(concat(privKey,new Uint8Array([1])).subarray(0,33),[network.wif])},decode:function(wif){var parsed=taproot.base58check.decode(wif);if(parsed[0]!==network.wif)throw new Error("Wrong WIF prefix");if(33!==(parsed=parsed.subarray(1)).length)throw new Error("Wrong WIF length");if(1!==parsed[32])throw new Error("Wrong WIF postfix");return parsed.subarray(0,-1)}}},taproot.Address=Address,function(SignatureHash){SignatureHash[SignatureHash.DEFAULT=0]="DEFAULT",SignatureHash[SignatureHash.ALL=1]="ALL",SignatureHash[SignatureHash.NONE=2]="NONE",SignatureHash[SignatureHash.SINGLE=3]="SINGLE",SignatureHash[SignatureHash.ANYONECANPAY=128]="ANYONECANPAY",SignatureHash[SignatureHash.ALL_SIGHASH_ANYONECANPAY=129]="ALL_SIGHASH_ANYONECANPAY",SignatureHash[SignatureHash.NONE_SIGHASH_ANYONECANPAY=130]="NONE_SIGHASH_ANYONECANPAY",SignatureHash[SignatureHash.SINGLE_SIGHASH_ANYONECANPAY=131]="SINGLE_SIGHASH_ANYONECANPAY"}(SignatureHash=taproot.SignatureHash||(taproot.SignatureHash={})),taproot.SigHashCoder=P.apply(P.U32LE,P.coders.tsEnum(SignatureHash));taproot._sortPubkeys=function(pubkeys){return Array.from(pubkeys).sort(cmp)};var def_sequence=function(n){return void 0===n?taproot.DEFAULT_SEQUENCE:n};taproot.TAP_LEAF_VERSION=192;function getTaprootKeys(privKey,pubKey,internalKey,merkleRoot){return void 0===merkleRoot&&(merkleRoot=P.EMPTY),P.equalBytes(internalKey,pubKey)&&(privKey=taprootTweakPrivKey(privKey,merkleRoot),pubKey=secp.schnorr.getPublicKey(privKey)),{privKey:privKey,pubKey:pubKey}}taproot.tapLeafHash=function(script,version){return void 0===version&&(version=taproot.TAP_LEAF_VERSION),taggedHash("TapLeaf",new Uint8Array([version]),taproot.VarBytes.encode(script))},taproot.getTaprootKeys=getTaprootKeys;var Transaction=function(){function Transaction(opts,version,lockTime,PSBTVersion){void 0===version&&(version=taproot.DEFAULT_VERSION),void 0===lockTime&&(lockTime=0),void 0===PSBTVersion&&(PSBTVersion=0),void 0===opts&&(opts={}),this.PSBTVersion=PSBTVersion,this.opts=opts,this.global={},this.inputs=[],this.outputs=[],lockTime!==taproot.DEFAULT_LOCKTIME&&(this.global.fallbackLocktime=lockTime),this.global.txVersion=version}return Transaction.fromRaw=function(raw,opts){void 0===opts&&(opts={});for(var parsed=taproot.RawTx.decode(raw),tx=new Transaction(parsed.version,parsed.lockTime,void 0,opts),_i=0,_a=parsed.outputs;_i<_a.length;_i++){var o=_a[_i];tx.addOutput(o)}if(tx.outputs=parsed.outputs,tx.inputs=parsed.inputs,parsed.witnesses)for(var i=0;i<parsed.witnesses.length;i++)tx.inputs[i].finalScriptWitness=parsed.witnesses[i];return tx},Transaction.fromPSBT=function(psbt,opts){var parsed;void 0===opts&&(opts={});try{parsed=taproot.RawPSBTV0.decode(psbt)}catch(e0){try{parsed=taproot.RawPSBTV2.decode(psbt)}catch(e2){throw e0}}var version=parsed.global.version||0,unsigned=parsed.global.unsignedTx,txVersion=version?parsed.global.txVersion:null==unsigned?void 0:unsigned.version,lockTime=version?parsed.global.fallbackLocktime:null==unsigned?void 0:unsigned.lockTime,tx=new Transaction(txVersion,lockTime,version,opts),inputCount=version?parsed.global.inputCount:null==unsigned?void 0:unsigned.inputs.length;tx.inputs=parsed.inputs.slice(0,inputCount).map((function(i,j){var _a;return __assign(__assign({finalScriptSig:P.EMPTY},null===(_a=parsed.global.unsignedTx)||void 0===_a?void 0:_a.inputs[j]),i)}));var outputCount=version?parsed.global.outputCount:null==unsigned?void 0:unsigned.outputs.length;return tx.outputs=parsed.outputs.slice(0,outputCount).map((function(i,j){var _a;return __assign(__assign({},i),null===(_a=parsed.global.unsignedTx)||void 0===_a?void 0:_a.outputs[j])})),tx.global=__assign(__assign({},parsed.global),{txVersion:txVersion}),lockTime!==taproot.DEFAULT_LOCKTIME&&(tx.global.fallbackLocktime=lockTime),tx},Transaction.prototype.toPSBT=function(ver){void 0===ver&&(ver=this.PSBTVersion);for(var inputs=this.inputs.map((function(i){return cleanPSBTFields(ver,PSBTInput,i)})),_i=0,inputs_1=inputs;_i<inputs_1.length;_i++){var inp=inputs_1[_i];inp.partialSig&&!inp.partialSig.length&&delete inp.partialSig,inp.finalScriptSig&&!inp.finalScriptSig.length&&delete inp.finalScriptSig,inp.finalScriptWitness&&!inp.finalScriptWitness.length&&delete inp.finalScriptWitness}var outputs=this.outputs.map((function(i){return cleanPSBTFields(ver,PSBTOutput,i)}));if(ver&&2!==ver)throw new Error("Wrong PSBT version=".concat(ver));var global=__assign({},this.global);return ver?(global.version=ver,global.txVersion=this.version,global.inputCount=this.inputs.length,global.outputCount=this.outputs.length,global.fallbackLocktime&&global.fallbackLocktime===taproot.DEFAULT_LOCKTIME&&delete global.fallbackLocktime):(global.unsignedTx=taproot.RawTx.decode(this.unsignedTx),delete global.fallbackLocktime,delete global.txVersion),this.opts.bip174jsCompat&&(inputs.length||inputs.push({}),outputs.length||outputs.push({})),(2===ver?taproot.RawPSBTV2:taproot.RawPSBTV0).encode({global:global,inputs:inputs,outputs:outputs})},Object.defineProperty(Transaction.prototype,"lockTime",{get:function(){for(var height=taproot.DEFAULT_LOCKTIME,heightCnt=0,time=taproot.DEFAULT_LOCKTIME,timeCnt=0,_i=0,_a=this.inputs;_i<_a.length;_i++){var i=_a[_i];i.requiredHeightLocktime&&(height=Math.max(height,i.requiredHeightLocktime),heightCnt++),i.requiredTimeLocktime&&(time=Math.max(time,i.requiredTimeLocktime),timeCnt++)}return heightCnt&&heightCnt>=timeCnt?height:time!==taproot.DEFAULT_LOCKTIME?time:this.global.fallbackLocktime||taproot.DEFAULT_LOCKTIME},enumerable:!1,configurable:!0}),Object.defineProperty(Transaction.prototype,"version",{get:function(){if(void 0===this.global.txVersion)throw new Error("No global.txVersion");return this.global.txVersion},enumerable:!1,configurable:!0}),Transaction.prototype.inputStatus=function(idx){this.checkInputIdx(idx);var input=this.inputs[idx];return input.finalScriptSig&&input.finalScriptSig.length||input.finalScriptWitness&&input.finalScriptWitness.length?"finalized":input.tapKeySig||input.tapScriptSig&&input.tapScriptSig.length||input.partialSig&&input.partialSig.length?"signed":"unsigned"},Transaction.prototype.inputSighash=function(idx){this.checkInputIdx(idx);var sighash=this.inputType(this.inputs[idx]).sighash,sigOutputs=sighash===SignatureHash.DEFAULT?SignatureHash.ALL:3&sighash;return{sigInputs:sighash&SignatureHash.ANYONECANPAY,sigOutputs:sigOutputs}},Transaction.prototype.signStatus=function(){for(var addInput=!0,addOutput=!0,inputs=[],outputs=[],idx=0;idx<this.inputs.length;idx++){if("unsigned"!==this.inputStatus(idx)){var _a=this.inputSighash(idx),sigInputs=_a.sigInputs,sigOutputs=_a.sigOutputs;if(sigInputs===SignatureHash.ANYONECANPAY?inputs.push(idx):addInput=!1,sigOutputs===SignatureHash.ALL)addOutput=!1;else if(sigOutputs===SignatureHash.SINGLE)outputs.push(idx);else if(sigOutputs!==SignatureHash.NONE)throw new Error("Wrong signature hash output type: ".concat(sigOutputs))}}return{addInput:addInput,addOutput:addOutput,inputs:inputs,outputs:outputs}},Object.defineProperty(Transaction.prototype,"isFinal",{get:function(){for(var idx=0;idx<this.inputs.length;idx++)if("finalized"!==this.inputStatus(idx))return!1;return!0},enumerable:!1,configurable:!0}),Object.defineProperty(Transaction.prototype,"hasWitnesses",{get:function(){for(var out=!1,_i=0,_a=this.inputs;_i<_a.length;_i++){var i=_a[_i];i.finalScriptWitness&&i.finalScriptWitness.length&&(out=!0)}return out},enumerable:!1,configurable:!0}),Object.defineProperty(Transaction.prototype,"weight",{get:function(){if(!this.isFinal)throw new Error("Transaction is not finalized");var out=32;this.hasWitnesses&&(out+=2),out+=4*CompactSizeLen.encode(this.inputs.length).length,out+=4*CompactSizeLen.encode(this.outputs.length).length;for(var _i=0,_a=this.inputs;_i<_a.length;_i++){var i=_a[_i];out+=160+4*taproot.VarBytes.encode(i.finalScriptSig).length}for(var _b=0,_c=this.outputs;_b<_c.length;_b++){var o=_c[_b];out+=32+4*taproot.VarBytes.encode(o.script).length}if(this.hasWitnesses)for(var _d=0,_e=this.inputs;_d<_e.length;_d++){(i=_e[_d]).finalScriptWitness&&(out+=taproot.RawWitness.encode(i.finalScriptWitness).length)}return out},enumerable:!1,configurable:!0}),Object.defineProperty(Transaction.prototype,"vsize",{get:function(){return Math.ceil(this.weight/4)},enumerable:!1,configurable:!0}),Transaction.prototype.toBytes=function(withScriptSig,withWitness){return void 0===withScriptSig&&(withScriptSig=!1),void 0===withWitness&&(withWitness=!1),taproot.RawTx.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map((function(i){return __assign(__assign({},i),{finalScriptSig:withScriptSig&&i.finalScriptSig||P.EMPTY})})),outputs:this.outputs,witnesses:this.inputs.map((function(i){return i.finalScriptWitness||[]})),segwitFlag:withWitness&&this.hasWitnesses})},Object.defineProperty(Transaction.prototype,"unsignedTx",{get:function(){return this.toBytes(!1,!1)},enumerable:!1,configurable:!0}),Object.defineProperty(Transaction.prototype,"hex",{get:function(){return base.hex.encode(this.toBytes(!0,this.hasWitnesses))},enumerable:!1,configurable:!0}),Object.defineProperty(Transaction.prototype,"hash",{get:function(){if(!this.isFinal)throw new Error("Transaction is not finalized");return base.hex.encode(sha256x2(this.toBytes(!0)))},enumerable:!1,configurable:!0}),Object.defineProperty(Transaction.prototype,"id",{get:function(){if(!this.isFinal)throw new Error("Transaction is not finalized");return base.hex.encode(sha256x2(this.toBytes(!0)).reverse())},enumerable:!1,configurable:!0}),Transaction.prototype.checkInputIdx=function(idx){if(!Number.isSafeInteger(idx)||0>idx||idx>=this.inputs.length)throw new Error("Wrong input index=".concat(idx))},Transaction.prototype.normalizeInput=function(i,cur,allowedFields){var prevOut,res=__assign(__assign({},cur),i);if(void 0===res.sequence&&(res.sequence=taproot.DEFAULT_SEQUENCE),void 0===res.hash&&"string"==typeof res.txid&&(res.hash=base.hex.decode(res.txid)),void 0===res.hash&&"object"==typeof res.txid&&(res.hash=res.txid),"string"==typeof res.hash&&(res.hash=base.hex.decode(res.hash).reverse()),null===res.tapMerkleRoot&&delete res.tapMerkleRoot,void 0===res.hash||void 0===res.index)throw new Error("Transaction/input: hash and index required");if(res=mergeKeyMap(PSBTInput,res,cur,allowedFields),PSBTInputCoder.encode(res),res.nonWitnessUtxo){if(res.nonWitnessUtxo.outputs.length-1<res.index)throw new Error("nonWitnessUtxo: incorect output index");var tx=Transaction.fromRaw(taproot.RawTx.encode(res.nonWitnessUtxo),this.opts),hash=base.hex.encode(res.hash);if(tx.id!==hash)throw new Error("nonWitnessUtxo: wrong hash, exp=".concat(txid," got=").concat(tx.id))}return res.nonWitnessUtxo&&void 0!==i.index?prevOut=res.nonWitnessUtxo.outputs[res.index]:res.witnessUtxo&&(prevOut=res.witnessUtxo),this.opts.disableScriptCheck||checkScript(prevOut&&prevOut.script,res.redeemScript,res.witnessScript),res},Transaction.prototype.addInput=function(input){if(!this.signStatus().addInput)throw new Error("Tx has signed inputs, cannot add new one");return this.inputs.push(this.normalizeInput(input)),this.inputs.length-1},Transaction.prototype.updateInput=function(idx,input){this.checkInputIdx(idx);var allowedFields=void 0,status=this.signStatus();status.addInput&&!status.inputs.includes(idx)||(allowedFields=PSBTInputUnsignedKeys),this.inputs[idx]=this.normalizeInput(input,this.inputs[idx],allowedFields)},Transaction.prototype.checkOutputIdx=function(idx){if(!Number.isSafeInteger(idx)||0>idx||idx>=this.outputs.length)throw new Error("Wrong output index=".concat(idx))},Transaction.prototype.normalizeOutput=function(o,cur,allowedFields){var res=__assign(__assign({},cur),o);if(void 0!==res.amount&&(res.amount="string"==typeof res.amount?taproot.decimal.decode(res.amount):res.amount),res=mergeKeyMap(PSBTOutput,res,cur,allowedFields),PSBTOutputCoder.encode(res),void 0===res.script||void 0===res.amount)throw new Error("Transaction/output: script and amount required");if(!this.opts.allowUnknowOutput&&"unknown"===taproot.OutScript.decode(res.script).type)throw new Error("Transaction/output: unknown output script type, there is a chance that input is unspendable. Pass allowUnkownScript=true, if you sure");return this.opts.disableScriptCheck||checkScript(res.script,res.redeemScript,res.witnessScript),res},Transaction.prototype.addOutput=function(o){if(!this.signStatus().addOutput)throw new Error("Tx has signed outputs, cannot add new one");return this.outputs.push(this.normalizeOutput(o)),this.outputs.length-1},Transaction.prototype.updateOutput=function(idx,output){this.checkOutputIdx(idx);var allowedFields=void 0,status=this.signStatus();status.addOutput&&!status.outputs.includes(idx)||(allowedFields=PSBTOutputUnsignedKeys),this.outputs[idx]=this.normalizeOutput(output,this.outputs[idx],allowedFields)},Transaction.prototype.addOutputAddress=function(address,amount,network){return void 0===network&&(network=taproot.NETWORK),this.addOutput({script:taproot.OutScript.encode(Address(network).decode(address)),amount:"string"==typeof amount?taproot.decimal.decode(amount):amount})},Object.defineProperty(Transaction.prototype,"fee",{get:function(){for(var res=0n,_i=0,_a=this.inputs;_i<_a.length;_i++){var i=_a[_i],prevOut=this.prevOut(i);if(!prevOut)throw new Error("Empty input amount");res+=prevOut.amount}for(var _b=0,_c=this.outputs;_b<_c.length;_b++){res-=(i=_c[_b]).amount}return res},enumerable:!1,configurable:!0}),Transaction.prototype.preimageLegacy=function(idx,prevOutScript,hashType){var _a=unpackSighash(hashType),isAny=_a.isAny,isNone=_a.isNone,isSingle=_a.isSingle;if(idx<0||!Number.isSafeInteger(idx))throw new Error("Invalid input idx=".concat(idx));if(isSingle&&idx>=this.outputs.length||idx>=this.inputs.length)return P.U256BE.encode(1n);prevOutScript=taproot.Script.encode(taproot.Script.decode(prevOutScript).filter((function(i){return"CODESEPARATOR"!==i})));var inputs=this.inputs.map((function(input,inputIdx){return __assign(__assign({},input),{finalScriptSig:inputIdx===idx?prevOutScript:P.EMPTY})}));isAny?inputs=[inputs[idx]]:(isNone||isSingle)&&(inputs=inputs.map((function(input,inputIdx){return __assign(__assign({},input),{sequence:inputIdx===idx?def_sequence(input.sequence):0})})));var outputs=this.outputs;isNone?outputs=[]:isSingle&&(outputs=this.outputs.slice(0,idx).fill(EMPTY_OUTPUT).concat([outputs[idx]]));var tmpTx=taproot.RawTx.encode({lockTime:this.lockTime,version:this.version,segwitFlag:!1,inputs:inputs,outputs:outputs});return sha256x2(tmpTx,P.I32LE.encode(hashType))},Transaction.prototype.preimageWitnessV0=function(idx,prevOutScript,hashType,amount){var _a=unpackSighash(hashType),isAny=_a.isAny,isNone=_a.isNone,isSingle=_a.isSingle,inputHash=EMPTY32,sequenceHash=EMPTY32,outputHash=EMPTY32,inputs=this.inputs;isAny||(inputHash=sha256x2.apply(void 0,inputs.map(TxHashIdx.encode))),isAny||isSingle||isNone||(sequenceHash=sha256x2.apply(void 0,inputs.map((function(i){return P.U32LE.encode(def_sequence(i.sequence))})))),isSingle||isNone?isSingle&&idx<this.outputs.length&&(outputHash=sha256x2(taproot.RawOutput.encode(this.outputs[idx]))):outputHash=sha256x2.apply(void 0,this.outputs.map(taproot.RawOutput.encode));var input=inputs[idx];return sha256x2(P.I32LE.encode(this.version),inputHash,sequenceHash,P.bytes(32,!0).encode(input.hash),P.U32LE.encode(input.index),taproot.VarBytes.encode(prevOutScript),P.U64LE.encode(amount),P.U32LE.encode(def_sequence(input.sequence)),outputHash,P.U32LE.encode(this.lockTime),P.U32LE.encode(hashType))},Transaction.prototype.preimageWitnessV1=function(idx,prevOutScript,hashType,amount,codeSeparator,leafScript,leafVer,annex){if(void 0===codeSeparator&&(codeSeparator=-1),void 0===leafVer&&(leafVer=192),!Array.isArray(amount)||this.inputs.length!==amount.length)throw new Error("Invalid amounts array=".concat(amount));if(!Array.isArray(prevOutScript)||this.inputs.length!==prevOutScript.length)throw new Error("Invalid prevOutScript array=".concat(prevOutScript));var out=[P.U8.encode(0),P.U8.encode(hashType),P.I32LE.encode(this.version),P.U32LE.encode(this.lockTime)],outType=hashType===SignatureHash.DEFAULT?SignatureHash.ALL:3&hashType,inType=hashType&SignatureHash.ANYONECANPAY;inType!==SignatureHash.ANYONECANPAY&&out.push.apply(out,[this.inputs.map(TxHashIdx.encode),amount.map(P.U64LE.encode),prevOutScript.map(taproot.VarBytes.encode),this.inputs.map((function(i){return P.U32LE.encode(def_sequence(i.sequence))}))].map((function(i){return(0,sha256_1.sha256)(concat.apply(void 0,i))}))),outType===SignatureHash.ALL&&out.push((0,sha256_1.sha256)(concat.apply(void 0,this.outputs.map(taproot.RawOutput.encode))));var spendType=(annex?1:0)|(leafScript?2:0);if(out.push(new Uint8Array([spendType])),inType===SignatureHash.ANYONECANPAY){var inp=this.inputs[idx];out.push(TxHashIdx.encode(inp),P.U64LE.encode(amount[idx]),taproot.VarBytes.encode(prevOutScript[idx]),P.U32LE.encode(def_sequence(inp.sequence)))}else out.push(P.U32LE.encode(idx));return 1&spendType&&out.push((0,sha256_1.sha256)(taproot.VarBytes.encode(annex))),outType===SignatureHash.SINGLE&&out.push(idx<this.outputs.length?(0,sha256_1.sha256)(taproot.RawOutput.encode(this.outputs[idx])):EMPTY32),leafScript&&out.push((0,taproot.tapLeafHash)(leafScript,leafVer),P.U8.encode(0),P.I32LE.encode(codeSeparator)),taggedHash.apply(void 0,__spreadArray(["TapSighash"],out,!1))},Transaction.prototype.prevOut=function(input){if(input.nonWitnessUtxo)return input.nonWitnessUtxo.outputs[input.index];if(input.witnessUtxo)return input.witnessUtxo;throw new Error("Cannot find previous output info.")},Transaction.prototype.inputType=function(input){var txType="legacy",defaultSighash=SignatureHash.ALL,prevOut=this.prevOut(input),first=taproot.OutScript.decode(prevOut.script),type=first.type,cur=first,stack=[first];if("tr"===first.type)return defaultSighash=SignatureHash.DEFAULT,{txType:"taproot",type:"tr",last:first,lastScript:prevOut.script,defaultSighash:defaultSighash,sighash:input.sighashType||defaultSighash};if("wpkh"!==first.type&&"wsh"!==first.type||(txType="segwit"),"sh"===first.type){if(!input.redeemScript)throw new Error("inputType: sh without redeemScript");"wpkh"!==(child=taproot.OutScript.decode(input.redeemScript)).type&&"wsh"!==child.type||(txType="segwit"),stack.push(child),cur=child,type+="-".concat(child.type)}if("wsh"===cur.type){if(!input.witnessScript)throw new Error("inputType: wsh without witnessScript");var child;"wsh"===(child=taproot.OutScript.decode(input.witnessScript)).type&&(txType="segwit"),stack.push(child),cur=child,type+="-".concat(child.type)}var last=stack[stack.length-1];if("sh"===last.type||"wsh"===last.type)throw new Error("inputType: sh/wsh cannot be terminal type");return{type:type,txType:txType,last:last,lastScript:taproot.OutScript.encode(last),defaultSighash:defaultSighash,sighash:input.sighashType||defaultSighash}},Transaction.prototype.signIdx=function(privateKey,idx,allowedSighash,_auxRand){this.checkInputIdx(idx);var input=this.inputs[idx],inputType=this.inputType(input);if(!(privateKey instanceof Uint8Array)){if(!input.bip32Derivation||!input.bip32Derivation.length)throw new Error("bip32Derivation: empty");var signers=input.bip32Derivation.filter((function(i){return i[1].fingerprint==privateKey.fingerprint})).map((function(_a){for(var pubKey=_a[0],path=_a[1].path,s=privateKey,_i=0,path_1=path;_i<path_1.length;_i++){var i=path_1[_i];s=s.deriveChild(i)}if(!P.equalBytes(s.publicKey,pubKey))throw new Error("bip32Derivation: wrong pubKey");if(!s.privateKey)throw new Error("bip32Derivation: no privateKey");return s}));if(!signers.length)throw new Error("bip32Derivation: no items with fingerprint=".concat(privateKey.fingerprint));for(var signed=!1,_i=0,signers_1=signers;_i<signers_1.length;_i++){var s=signers_1[_i];this.signIdx(s.privateKey,idx)&&(signed=!0)}return signed}allowedSighash||(allowedSighash=[inputType.defaultSighash]);var sighash=inputType.sighash;if(!allowedSighash.includes(sighash))throw new Error("Input with not allowed sigHash=".concat(sighash,". Allowed: ").concat(allowedSighash.join(", ")));var _a=this.inputSighash(idx);_a.sigInputs;if(_a.sigOutputs===SignatureHash.SINGLE&&idx>=this.outputs.length)throw new Error("Input with sighash SINGLE, but there is no output with corresponding index=".concat(idx));var prevOut=this.prevOut(input);if("taproot"===inputType.txType){if(input.tapBip32Derivation)throw new Error("tapBip32Derivation unsupported");var prevOuts=this.inputs.map(this.prevOut),prevOutScript=prevOuts.map((function(i){return i.script})),amount=prevOuts.map((function(i){return i.amount})),schnorrPub=(signed=!1,secp.schnorr.getPublicKey(privateKey)),merkleRoot=input.tapMerkleRoot||P.EMPTY;if(input.tapInternalKey){var _b=getTaprootKeys(privateKey,schnorrPub,input.tapInternalKey,merkleRoot),pubKey=_b.pubKey,privKey=_b.privKey,_c=taprootTweakPubkey(input.tapInternalKey,merkleRoot),taprootPubKey=_c[0];_c[1];if(P.equalBytes(taprootPubKey,pubKey)){var hash=this.preimageWitnessV1(idx,prevOutScript,sighash,amount),sig=concat(secp.schnorr.signSync(hash,privKey,_auxRand),sighash!==SignatureHash.DEFAULT?new Uint8Array([sighash]):P.EMPTY);this.updateInput(idx,{tapKeySig:sig}),signed=!0}}if(input.tapLeafScript){input.tapScriptSig=input.tapScriptSig||[];for(var _loop_3=function(cb,_script){var script=_script.subarray(0,-1),scriptDecoded=taproot.Script.decode(script),ver=_script[_script.length-1],hash=(0,taproot.tapLeafHash)(script,ver),_j=getTaprootKeys(privateKey,schnorrPub,cb.internalKey,P.EMPTY),pubKey=_j.pubKey,privKey=_j.privKey,pos=scriptDecoded.findIndex((function(i){return i instanceof Uint8Array&&P.equalBytes(i,pubKey)}));if(-1===pos)return"continue";var msg=this_1.preimageWitnessV1(idx,prevOutScript,sighash,amount,void 0,script,ver),sig=concat(secp.schnorr.signSync(msg,privKey,_auxRand),sighash!==SignatureHash.DEFAULT?new Uint8Array([sighash]):P.EMPTY);this_1.updateInput(idx,{tapScriptSig:[[{pubKey:pubKey,leafHash:hash},sig]]}),signed=!0},this_1=this,_d=0,_e=input.tapLeafScript;_d<_e.length;_d++){var _f=_e[_d];_loop_3(_f[0],_f[1])}}if(!signed)throw new Error("No taproot scripts signed");return!0}pubKey=secp.getPublicKey(privateKey,!0);for(var hasPubkey=!1,pubKeyHash=hash160(pubKey),_g=0,_h=taproot.Script.decode(inputType.lastScript);_g<_h.length;_g++){var i=_h[_g];i instanceof Uint8Array&&(P.equalBytes(i,pubKey)||P.equalBytes(i,pubKeyHash))&&(hasPubkey=!0)}if(!hasPubkey)throw new Error("Input script doesn't have pubKey: ".concat(inputType.lastScript));hash=void 0;if("legacy"===inputType.txType){if(!this.opts.allowLegacyWitnessUtxo&&!input.nonWitnessUtxo)throw new Error("Transaction/sign: legacy input without nonWitnessUtxo, can result in attack that forces paying higher fees. Pass allowLegacyWitnessUtxo=true, if you sure");hash=this.preimageLegacy(idx,inputType.lastScript,sighash)}else{if("segwit"!==inputType.txType)throw new Error("Transaction/sign: unknown tx type: ".concat(inputType.txType));var script=inputType.lastScript;"wpkh"===inputType.last.type&&(script=taproot.OutScript.encode({type:"pkh",hash:inputType.last.hash})),hash=this.preimageWitnessV0(idx,script,sighash,prevOut.amount)}sig=function(hash,privateKey,lowR){void 0===lowR&&(lowR=!1);var sig=secp.signSync(hash,privateKey,{canonical:!0});if(lowR&&!hasLowR(sig))for(var extraEntropy=new Uint8Array(32),cnt=0;cnt<Number.MAX_SAFE_INTEGER&&(extraEntropy.set(P.U32LE.encode(cnt)),sig=secp.signSync(hash,privateKey,{canonical:!0,extraEntropy:extraEntropy}),!hasLowR(sig));cnt++);return sig}(hash,privateKey,this.opts.lowR);return this.updateInput(idx,{partialSig:[[pubKey,concat(sig,new Uint8Array([sighash]))]]}),!0},Transaction.prototype.sign=function(privateKey,allowedSighash,_auxRand){for(var num=0,i=0;i<this.inputs.length;i++)try{this.signIdx(privateKey,i,allowedSighash,_auxRand)&&num++}catch(e){}if(!num)throw new Error("No inputs signed");return num},Transaction.prototype.finalizeIdx=function(idx){if(this.checkInputIdx(idx),this.fee<0n)throw new Error("Outputs spends more than inputs amount");var input=this.inputs[idx],inputType=this.inputType(input);if("taproot"!==inputType.txType){var inputScript,outScript=inputType.lastScript,isSegwit="segwit"===inputType.txType;if(!input.partialSig||!input.partialSig.length)throw new Error("Not enough partial sign");var finalScriptSig,finalScriptWitness,witness=[];if("ms"===inputType.last.type){for(var m=inputType.last.m,pubkeys=inputType.last.pubkeys,signatures=[],_loop_5=function(pub){var sign=input.partialSig.find((function(s){return P.equalBytes(pub,s[0])}));if(!sign)return"continue";signatures.push(sign[1])},_b=0,pubkeys_2=pubkeys;_b<pubkeys_2.length;_b++){_loop_5(pubkeys_2[_b])}if((signatures=signatures.slice(0,m)).length!==m)throw new Error("Multisig: wrong signatures count, m=".concat(m," n=").concat(pubkeys.length," signatures=").concat(signatures.length));inputScript=taproot.Script.encode(__spreadArray(["OP_0"],signatures,!0))}else if("pk"===inputType.last.type)inputScript=taproot.Script.encode([input.partialSig[0][1]]);else if("pkh"===inputType.last.type)inputScript=taproot.Script.encode([input.partialSig[0][1],input.partialSig[0][0]]);else if("wpkh"===inputType.last.type)inputScript=P.EMPTY,witness=[input.partialSig[0][1],input.partialSig[0][0]];else if("unknown"===inputType.last.type&&!this.opts.allowUnknowInput)throw new Error("Unknown inputs not allowed");if(input.witnessScript&&(inputScript&&inputScript.length>0&&outScript&&outScript.length>0&&(witness=taproot.Script.decode(inputScript).map((function(i){if("OP_0"===i)return P.EMPTY;if(i instanceof Uint8Array)return i;throw new Error("Wrong witness op=".concat(i))}))),witness&&outScript&&(witness=witness.concat(outScript)),outScript=taproot.Script.encode(["OP_0",(0,sha256_1.sha256)(outScript)]),inputScript=P.EMPTY),isSegwit&&(finalScriptWitness=witness),input.redeemScript?finalScriptSig=taproot.Script.encode(__spreadArray(__spreadArray([],taproot.Script.decode(inputScript),!0),[outScript],!1)):isSegwit||(finalScriptSig=inputScript),!finalScriptSig&&!finalScriptWitness)throw new Error("Unknown error finalizing input");for(var k in finalScriptSig&&(input.finalScriptSig=finalScriptSig),finalScriptWitness&&(input.finalScriptWitness=finalScriptWitness),input)PSBTInputFinalKeys.includes(k)||delete input[k]}else{if(input.tapKeySig)input.finalScriptWitness=[input.tapKeySig];else{if(!input.tapLeafScript||!input.tapScriptSig)throw new Error("finalize/taproot: unknown input");for(var leafs=input.tapLeafScript.sort((function(a,b){return taproot.TaprootControlBlock.encode(a[0]).length-taproot.TaprootControlBlock.encode(b[0]).length})),_loop_4=function(cb,_script){var script=_script.slice(0,-1),ver=_script[_script.length-1],outScript_1=taproot.OutScript.decode(script),hash=(0,taproot.tapLeafHash)(script,ver),scriptSig=input.tapScriptSig.filter((function(i){return P.equalBytes(i[0].leafHash,hash)})),signatures=[];if("tr_ms"===outScript_1.type){for(var m=outScript_1.m,pubkeys=outScript_1.pubkeys,added=0,_loop_6=function(pub){var sigIdx=scriptSig.findIndex((function(i){return P.equalBytes(i[0].pubKey,pub)}));if(added===m||-1===sigIdx)return signatures.push(P.EMPTY),"continue";signatures.push(scriptSig[sigIdx][1]),added++},_c=0,pubkeys_3=pubkeys;_c<pubkeys_3.length;_c++){_loop_6(pubkeys_3[_c])}if(added!==m)return"continue"}else if("tr_ns"===outScript_1.type){for(var _loop_7=function(pub){var sigIdx=scriptSig.findIndex((function(i){return P.equalBytes(i[0].pubKey,pub)}));if(-1===sigIdx)return"continue";signatures.push(scriptSig[sigIdx][1])},_d=0,_e=outScript_1.pubkeys;_d<_e.length;_d++){_loop_7(_e[_d])}if(signatures.length!==outScript_1.pubkeys.length)return"continue"}else{if("unknown"!==outScript_1.type||!this_2.opts.allowUnknowInput)throw new Error("Finalize: Unknown tapLeafScript");var scriptDecoded_1=taproot.Script.decode(script);if(signatures=scriptSig.map((function(_a){var pubKey=_a[0].pubKey,signature=_a[1],pos=scriptDecoded_1.findIndex((function(i){return i instanceof Uint8Array&&P.equalBytes(i,pubKey)}));if(-1===pos)throw new Error("finalize/taproot: cannot find position of pubkey in script");return{signature:signature,pos:pos}})).sort((function(a,b){return a.pos-b.pos})).map((function(i){return i.signature})),!signatures.length)return"continue"}return input.finalScriptWitness=signatures.reverse().concat([script,taproot.TaprootControlBlock.encode(cb)]),"break"},this_2=this,_i=0,leafs_1=leafs;_i<leafs_1.length;_i++){var _a=leafs_1[_i];if("break"===_loop_4(_a[0],_a[1]))break}if(!input.finalScriptWitness)throw new Error("finalize/taproot: empty witness")}for(var k in input)PSBTInputFinalKeys.includes(k)||delete input[k]}},Transaction.prototype.finalize=function(){for(var i=0;i<this.inputs.length;i++)this.finalizeIdx(i)},Transaction.prototype.extract=function(){if(!this.isFinal)throw new Error("Transaction has unfinalized inputs");if(!this.outputs.length)throw new Error("Transaction has no outputs");return this.toBytes(!0,!0)},Transaction.prototype.combine=function(other){for(var _i=0,_a=["PSBTVersion","version","lockTime"];_i<_a.length;_i++){if(this[k=_a[_i]]!==other[k])throw new Error("Transaction/combine: different ".concat(k," this=").concat(this[k]," other=").concat(other[k]))}for(var _b=0,_c=["inputs","outputs"];_b<_c.length;_b++){var k;if(this[k=_c[_b]].length!==other[k].length)throw new Error("Transaction/combine: different ".concat(k," length this=").concat(this[k].length," other=").concat(other[k].length))}var thisUnsigned=this.global.unsignedTx?taproot.RawTx.encode(this.global.unsignedTx):P.EMPTY,otherUnsigned=other.global.unsignedTx?taproot.RawTx.encode(other.global.unsignedTx):P.EMPTY;if(!P.equalBytes(thisUnsigned,otherUnsigned))throw new Error("Transaction/combine: different unsigned tx");this.global=mergeKeyMap(PSBTGlobal,this.global,other.global);for(var i=0;i<this.inputs.length;i++)this.updateInput(i,other.inputs[i]);for(i=0;i<this.outputs.length;i++)this.updateOutput(i,other.outputs[i]);return this},Transaction}();function multisig(m,pubkeys,sorted,witness){void 0===sorted&&(sorted=!1),void 0===witness&&(witness=!1);var ms=(0,taproot.p2ms)(m,sorted?(0,taproot._sortPubkeys)(pubkeys):pubkeys);return witness?(0,taproot.p2wsh)(ms):(0,taproot.p2sh)(ms)}taproot.Transaction=Transaction,taproot.getAddress=function(type,privKey,network){if(void 0===network&&(network=taproot.NETWORK),"tr"===type)return p2tr(secp.schnorr.getPublicKey(privKey),void 0,network).address;var pubKey=secp.getPublicKey(privKey,!0);if("pkh"===type)return(0,taproot.p2pkh)(pubKey,network).address;if("wpkh"===type)return(0,taproot.p2wpkh)(pubKey,network).address;throw new Error("getAddress: unknown type=".concat(type))},taproot.multisig=multisig,taproot.sortedMultisig=function(m,pubkeys,witness){return void 0===witness&&(witness=!1),multisig(m,pubkeys,!0,witness)};taproot.bip32Path=function(path){var out=[];if(!/^[mM]'?/.test(path))throw new Error('Path must start with "m" or "M"');if(/^[mM]'?$/.test(path))return out;for(var _i=0,parts_1=path.replace(/^[mM]'?\//,"").split("/");_i<parts_1.length;_i++){var c=parts_1[_i],m=/^(\d+)('?)$/.exec(c);if(!m||3!==m.length)throw new Error("Invalid child index: ".concat(c));var idx=+m[1];if(!Number.isSafeInteger(idx)||idx>=2147483648)throw new Error("Invalid index");"'"===m[2]&&(idx+=2147483648),out.push(idx)}return out},taproot.PSBTCombine=function(psbts){if(!psbts||!Array.isArray(psbts)||!psbts.length)throw new Error("PSBTCombine: wrong PSBT list");for(var tx=Transaction.fromPSBT(psbts[0]),i=1;i<psbts.length;i++)tx.combine(Transaction.fromPSBT(psbts[i]));return tx.toPSBT()},taproot.numberToScriptArray=function(number){let lastIndex=(array=coinjs.numToBytes(number)).length-1;for(;lastIndex>=0&&0===array[lastIndex];)lastIndex--;return array.splice(lastIndex+1),array}}();var hex=base.hex,btc=taproot,Transaction=taproot.Transaction,secp256k1_schnorr=secp.schnorr,secp256k1=secp,schnorr=secp.schnorr;function deepStrictEqual(actual,expected){if("object"!=typeof actual||"object"!=typeof expected){const result=actual===expected;return console.log(`deepStrictEqual: ${result?"Success":"Failure"} - Actual: ${actual}, Expected: ${expected}`),result}const actualKeys=Object.keys(actual),expectedKeys=Object.keys(expected);if(actualKeys.length!==expectedKeys.length)return console.log("deepStrictEqual: Failure - Different number of keys"),!1;for(const key of actualKeys)if(!deepStrictEqual(actual[key],expected[key]))return console.log(`deepStrictEqual: Failure - Property '${key}' mismatch`),!1;return console.log("deepStrictEqual: Success"),!0}function should(suiteDescription,tests){console.log(`Running test suite: ${suiteDescription}`),tests()}function test(testDescription,testFunction){try{testFunction()}catch(error){logResult(!1,`${testDescription} - ${error}`)}}function logResult(result,message){result?console.log(`YESSS ${message}`):console.error(`NO!!! ${message}`)}function throws(func){try{return func(),console.log("throws: Failure - No exception was thrown"),!1}catch(error){return console.log(`throws: Success - Exception was thrown: ${error}`),!0}}function demonstrateNestedArray(nestedArray){console.log("Original nestedArray:"),console.log(nestedArray),console.log("\nAccessing elements:"),console.log("\nIterating through nestedArray:");for(var i=0;i<nestedArray.length;i++)if(Array.isArray(nestedArray[i])){console.log("Element at index",i,"is an array:",nestedArray[i]);for(var j=0;j<nestedArray[i].length;j++)console.log(" Element at index",j,":",nestedArray[i][j])}else console.log("Element at index",i,":",nestedArray[i])}
|
||
/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */var bip32={};!function(){var HDKey=function(){var hmac=hashmini.hmac,ripemd160=hashmini.ripemd160,sha256=hashmini.sha256,sha512=hashmini.sha512,utils_1=hashmini.utils,modular_1=secp.utils,Point=secp.Point,base58check=(0,base.base58check)(sha256);function _assert_1(condition,message="Assertion failed"){if(!condition)throw new Error(message)}function _assert_1(value,length,message="Value is not a Uint8Array or does not have the expected length"){if(!(value instanceof Uint8Array))throw new Error(message)}const createView=arr=>new DataView(arr.buffer,arr.byteOffset,arr.byteLength);var __assign=this&&this.__assign||function(){return Object.assign.apply(Object,arguments)};function bytesToNumber(bytes){return BigInt("0x".concat((0,utils_1.bytesToHex)(bytes)))}var MASTER_SECRET=function(str){if("string"!=typeof str)throw new TypeError("utf8ToBytes expected string, got "+typeof str);return(new TextEncoder).encode(str)}("Bitcoin seed"),BITCOIN_VERSIONS={private:76066276,public:76067358},toU32=function(n){if(!Number.isSafeInteger(n)||n<0||n>Math.pow(2,32)-1)throw new Error("Invalid number=".concat(n,". Should be from 0 to 2 ** 32 - 1"));var buf=new Uint8Array(4);return createView(buf).setUint32(0,n,!1),buf};function HDKey(opt){if(this.depth=0,this.index=0,this.chainCode=null,this.parentFingerprint=0,!opt||"object"!=typeof opt)throw new Error("HDKey.constructor must not be called directly");if(this.versions=opt.versions||BITCOIN_VERSIONS,this.depth=opt.depth||0,this.chainCode=opt.chainCode,this.index=opt.index||0,this.parentFingerprint=opt.parentFingerprint||0,!this.depth&&(this.parentFingerprint||this.index))throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");if(opt.publicKey&&opt.privateKey)throw new Error("HDKey: publicKey and privateKey at same time.");if(opt.privateKey){if(!secp.utils.isValidPrivateKey(opt.privateKey))throw new Error("Invalid private key");this.privKey="bigint"==typeof opt.privateKey?opt.privateKey:bytesToNumber(opt.privateKey),this.privKeyBytes=(num=this.privKey,(0,utils_1.hexToBytes)(num.toString(16).padStart(64,"0"))),this.pubKey=secp.getPublicKey(opt.privateKey,!0)}else{if(!opt.publicKey)throw new Error("HDKey: no public or private key provided");this.pubKey=Point.fromHex(opt.publicKey).toRawBytes(!0)}var num,data;this.pubHash=(data=this.pubKey,ripemd160(sha256(data)))}return Object.defineProperty(HDKey.prototype,"fingerprint",{get:function(){if(!this.pubHash)throw new Error("No publicKey set!");return data=this.pubHash,createView(data).getUint32(0,!1);var data},enumerable:!1,configurable:!0}),Object.defineProperty(HDKey.prototype,"identifier",{get:function(){return this.pubHash},enumerable:!1,configurable:!0}),Object.defineProperty(HDKey.prototype,"pubKeyHash",{get:function(){return this.pubHash},enumerable:!1,configurable:!0}),Object.defineProperty(HDKey.prototype,"privateKey",{get:function(){return this.privKeyBytes||null},enumerable:!1,configurable:!0}),Object.defineProperty(HDKey.prototype,"publicKey",{get:function(){return this.pubKey||null},enumerable:!1,configurable:!0}),Object.defineProperty(HDKey.prototype,"privateExtendedKey",{get:function(){var priv=this.privateKey;if(!priv)throw new Error("No private key");return base58check.encode(this.serialize(this.versions.private,(0,utils_1.concatBytes)(new Uint8Array([0]),priv)))},enumerable:!1,configurable:!0}),Object.defineProperty(HDKey.prototype,"publicExtendedKey",{get:function(){if(!this.pubKey)throw new Error("No public key");return base58check.encode(this.serialize(this.versions.public,this.pubKey))},enumerable:!1,configurable:!0}),HDKey.fromMasterSeed=function(seed,versions){if(void 0===versions&&(versions=BITCOIN_VERSIONS),_assert_1(seed),8*seed.length<128||8*seed.length>512)throw new Error("HDKey: wrong seed length=".concat(seed.length,". Should be between 128 and 512 bits; 256 bits is advised)"));var I=hmac(sha512,MASTER_SECRET,seed);return new HDKey({versions:versions,chainCode:I.slice(32),privateKey:I.slice(0,32)})},HDKey.fromExtendedKey=function(base58key,versions){void 0===versions&&(versions=BITCOIN_VERSIONS);var keyBuffer=base58check.decode(base58key),keyView=createView(keyBuffer),version=keyView.getUint32(0,!1),opt={versions:versions,depth:keyBuffer[4],parentFingerprint:keyView.getUint32(5,!1),index:keyView.getUint32(9,!1),chainCode:keyBuffer.slice(13,45)},key=keyBuffer.slice(45),isPriv=0===key[0];if(version!==versions[isPriv?"private":"public"])throw new Error("Version mismatch");return new HDKey(__assign(__assign({},opt),isPriv?{privateKey:key.slice(1)}:{publicKey:key}))},HDKey.fromJSON=function(json){return HDKey.fromExtendedKey(json.xpriv)},HDKey.prototype.derive=function(path){if(!/^[mM]'?/.test(path))throw new Error('Path must start with "m" or "M"');if(/^[mM]'?$/.test(path))return this;for(var child=this,_i=0,parts_1=path.replace(/^[mM]'?\//,"").split("/");_i<parts_1.length;_i++){var c=parts_1[_i],m=/^(\d+)('?)$/.exec(c),m1=m&&m[1];if(!m||3!==m.length||"string"!=typeof m1)throw new Error("Invalid child index: ".concat(c));var idx=+m1;if(!Number.isSafeInteger(idx)||idx>=2147483648)throw new Error("Invalid index");"'"===m[2]&&(idx+=2147483648),child=child.deriveChild(idx)}return child},HDKey.prototype.deriveChild=function(index){if(!this.pubKey||!this.chainCode)throw new Error("No publicKey or chainCode set");var data=toU32(index);if(index>=2147483648){var priv=this.privateKey;if(!priv)throw new Error("Could not derive hardened child key");data=(0,utils_1.concatBytes)(new Uint8Array([0]),priv,data)}else data=(0,utils_1.concatBytes)(this.pubKey,data);var I=hmac(sha512,this.chainCode,data),childTweak=bytesToNumber(I.slice(0,32)),chainCode=I.slice(32);if(!secp.utils.isValidPrivateKey(childTweak))throw new Error("Tweak bigger than curve order");var opt={versions:this.versions,chainCode:chainCode,depth:this.depth+1,parentFingerprint:this.fingerprint,index:index};try{if(this.privateKey){var added=(0,modular_1.mod)(this.privKey+childTweak,secp.CURVE.n);if(!secp.utils.isValidPrivateKey(added))throw new Error("The tweak was out of range or the resulted private key is invalid");opt.privateKey=added}else{if((added=Point.fromHex(this.pubKey).add(Point.fromPrivateKey(childTweak))).equals(Point.ZERO))throw new Error("The tweak was equal to negative P, which made the result key invalid");opt.publicKey=added.toRawBytes(!0)}return new HDKey(opt)}catch(err){return this.deriveChild(index+1)}},HDKey.prototype.sign=function(hash){if(!this.privateKey)throw new Error("No privateKey set!");return _assert_1(hash),secp.sign(hash,this.privKey).toCompactRawBytes()},HDKey.prototype.verify=function(hash,signature){if(_assert_1(hash),_assert_1(signature),!this.publicKey)throw new Error("No publicKey set!");var sig;try{sig=secp.Signature.fromCompact(signature)}catch(error){return!1}return secp.verify(sig,hash,this.publicKey)},HDKey.prototype.wipePrivateData=function(){return this.privKey=void 0,this.privKeyBytes&&(this.privKeyBytes.fill(0),this.privKeyBytes=void 0),this},HDKey.prototype.toJSON=function(){return{xpriv:this.privateExtendedKey,xpub:this.publicExtendedKey}},HDKey.prototype.serialize=function(version,key){if(!this.chainCode)throw new Error("No chainCode set");return _assert_1(key),(0,utils_1.concatBytes)(toU32(version),new Uint8Array([this.depth]),toU32(this.parentFingerprint),toU32(this.index),this.chainCode,key)},HDKey}();bip32.HDKey=HDKey}();var HDKey=bip32.HDKey; |