/*! 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=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;_i0&&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;i32)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=Math.pow(2,from))throw new Error("convertRadix2: invalid data word=".concat(n," from=").concat(from));if(carry=carry<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<=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>25,chk=(33554431&pre)<<5,i=0;i>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;i126)throw new Error("Invalid prefix (".concat(prefix,")"));chk=bech32Polymod(chk)^c>>5}chk=bech32Polymod(chk);for(i=0;ilimit)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>=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;ii.toString(16).padStart(2,"0")));function bytesToHex(uint8a){if(!(uint8a instanceof Uint8Array))throw new Error("Expected Uint8Array");let hex="";for(let i=0;i0)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 _0n0)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{};async function asyncLoop(iters,tick,cb){let ts=Date.now();for(let i=0;i=0&&diff"[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.lengthkeyLen)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;posout32[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;iBigInt(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<>>32-s,rotlSL:(h,l,s)=>l<>>32-s,rotlBH:(h,l,s)=>l<>>64-s,rotlBL:(h,l,s)=>h<>>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;inew 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=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;inew 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= 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;posblockLen-pos&&(this.process(view,0),pos=0);for(let i=pos;i>_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<>>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<>>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;i0&&(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;piBigInt(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<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=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;posnew 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{PRF._cloneInto(prfW).update(u).digestInto(u);for(let i=0;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;kthis.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<>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=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<>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;iBigInt(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>=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;i6)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;_iw.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.leftBytesvalue||value>stop)){w.byte(flag);for(var i=0;i>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;i128)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;_d1||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.length1||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=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;in)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;i40)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=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;idxidx||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-1idx||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)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;cnt0&&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=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=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;inew 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=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;