@bsv/sdk 2.1.2 → 2.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/package.json +13 -13
- package/dist/cjs/src/auth/Peer.js +21 -18
- package/dist/cjs/src/auth/Peer.js.map +1 -1
- package/dist/cjs/src/auth/SessionManager.js.map +1 -1
- package/dist/cjs/src/auth/clients/AuthFetch.js +4 -1
- package/dist/cjs/src/auth/clients/AuthFetch.js.map +1 -1
- package/dist/cjs/src/compat/Mnemonic.js +12 -0
- package/dist/cjs/src/compat/Mnemonic.js.map +1 -1
- package/dist/cjs/src/overlay-tools/LookupResolver.js +99 -28
- package/dist/cjs/src/overlay-tools/LookupResolver.js.map +1 -1
- package/dist/cjs/src/transaction/MerklePath.js +1 -1
- package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
- package/dist/esm/src/auth/Peer.js +28 -18
- package/dist/esm/src/auth/Peer.js.map +1 -1
- package/dist/esm/src/auth/SessionManager.js.map +1 -1
- package/dist/esm/src/auth/clients/AuthFetch.js +4 -1
- package/dist/esm/src/auth/clients/AuthFetch.js.map +1 -1
- package/dist/esm/src/compat/Mnemonic.js +12 -0
- package/dist/esm/src/compat/Mnemonic.js.map +1 -1
- package/dist/esm/src/overlay-tools/LookupResolver.js +99 -28
- package/dist/esm/src/overlay-tools/LookupResolver.js.map +1 -1
- package/dist/esm/src/transaction/MerklePath.js +1 -1
- package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
- package/dist/types/src/auth/Peer.d.ts +3 -3
- package/dist/types/src/auth/Peer.d.ts.map +1 -1
- package/dist/types/src/auth/SessionManager.d.ts +21 -0
- package/dist/types/src/auth/SessionManager.d.ts.map +1 -1
- package/dist/types/src/auth/clients/AuthFetch.d.ts +2 -2
- package/dist/types/src/auth/clients/AuthFetch.d.ts.map +1 -1
- package/dist/types/src/compat/Mnemonic.d.ts +2 -0
- package/dist/types/src/compat/Mnemonic.d.ts.map +1 -1
- package/dist/types/src/overlay-tools/LookupResolver.d.ts +1 -0
- package/dist/types/src/overlay-tools/LookupResolver.d.ts.map +1 -1
- package/dist/types/tsconfig.types.tsbuildinfo +1 -1
- package/dist/umd/bundle.js +3 -3
- package/package.json +13 -13
- package/src/auth/Peer.ts +30 -20
- package/src/auth/SessionManager.ts +22 -0
- package/src/auth/__tests/Peer.test.ts +47 -1
- package/src/auth/clients/AuthFetch.ts +6 -3
- package/src/compat/Mnemonic.ts +13 -0
- package/src/compat/__tests/Mnemonic.test.ts +49 -5
- package/src/overlay-tools/LookupResolver.ts +102 -25
- package/src/overlay-tools/__tests/LookupResolver.additional.test.ts +90 -0
- package/src/script/__tests/Spend.test.ts +45 -4
- package/src/transaction/MerklePath.ts +1 -1
- package/src/transaction/__tests/Transaction.test.ts +17 -0
package/dist/umd/bundle.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.bsv=t():e.bsv=t()}(this,()=>(()=>{"use strict";let e,t,i,r,n;var s,a,o,l,c,h,d,u,f={};f.d=(e,t)=>{for(var i in t)f.o(t,i)&&!f.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},f.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),f.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var p={};f.r(p),f.d(p,{walletErrors:()=>d,BEEF_V1:()=>rh,BEEF_V2:()=>rd,SignedMessage:()=>b,KeyShares:()=>ic,RenewResiliencyError:()=>sg,ThreadHandle:()=>sH,BlockHeadersService:()=>rE,MerklePath:()=>rc,PrivateKey:()=>ih,RemittanceManager:()=>sV,XDM:()=>r0,binaryHttpClient:()=>rk,LivePolicy:()=>i7,DefaultNonceProvider:()=>s$,HD:()=>rU,Brc29RemittanceModule:()=>sW,KeyDeriver:()=>rW,defaultBroadcaster:()=>ra,verifyNonce:()=>nZ,AuthFetch:()=>n6,Secp256r1:()=>iW,UnlockingScript:()=>iG,InvokableWalletBase:()=>rQ,Random:()=>ia,WERR_REVIEW_ACTIONS:()=>r4,TOTP:()=>r$,Curve:()=>t1,VerifiableCertificate:()=>nX,SHIPCast:()=>so,WhatsOnChain:()=>ro,DEFAULT_SLAP_TRACKERS:()=>si,MasterCertificate:()=>nG,SAT_UNIT:()=>sD,defaultChainTracker:()=>rl,DEFAULT_TESTNET_SLAP_TRACKERS:()=>sr,OverlayAdminTokenTemplate:()=>n4,NodejsHttpClient:()=>rt,Schnorr:()=>iL,WERR_INSUFFICIENT_FUNDS:()=>ne,LockingScript:()=>ij,DEFAULT_IDENTITY_CLIENT_OPTIONS:()=>sw,PublicKey:()=>ii,Transaction:()=>rg,TransactionSignature:()=>iD,defaultIdentity:()=>sb,TX_DATA_FORMAT:()=>c,Signature:()=>t2,Teranode:()=>rS,PointInFiniteField:()=>io,CachedKeyDeriver:()=>rj,Polynomial:()=>il,OP:()=>iC,P2PKH:()=>i3,deserializeWalletProtocol:()=>sO,BeefParty:()=>rb,InvoiceHandle:()=>sM,Point:()=>t0,BSM:()=>v,ATOMIC_BEEF:()=>ru,SatoshisPerKilobyte:()=>i9,Validation:()=>I,HTTPWalletWire:()=>r5,TopicBroadcaster:()=>so,StorageUtils:()=>k,isBroadcastResponse:()=>ry,RPuzzle:()=>i5,StorageDownloader:()=>sm,CompletedProtoWallet:()=>nY,LookupResolver:()=>ss,LocalKVStore:()=>sP,ProtoWallet:()=>rX,FetchHttpClient:()=>ri,WalletErrors:()=>rZ,DEFAULT_UHRP_SERVERS:()=>sp,ECIES:()=>rK,WERR_INVALID_PARAMETER:()=>r7,fromUtxo:()=>rq,ARC:()=>rs,ECDSA:()=>m,GlobalKVStore:()=>sU,WindowCWISubstrate:()=>rY,SessionManager:()=>nJ,SHIPBroadcaster:()=>so,StorageUploader:()=>sy,SymmetricKey:()=>i_,validateCertificates:()=>n1,EncryptedMessage:()=>w,REMITTANCE_STATE_TRANSITIONS:()=>sF,Hash:()=>g,Spend:()=>i0,isBroadcastFailure:()=>rm,DEFAULT_REMITTANCE_MESSAGEBOX:()=>sL,Mnemonic:()=>rD,Script:()=>iU,HTTPWalletJSON:()=>nt,ScriptEvaluationError:()=>iX,PushDrop:()=>i4,WalletWireProcessor:()=>nj,WalletWireTransceiver:()=>r3,RegistryClient:()=>sT,HTTPSOverlayLookupFacilitator:()=>sn,BigNumber:()=>A,Beef:()=>rp,createNonce:()=>nQ,getVerifiableCertificates:()=>n0,BeefTx:()=>rf,Certificate:()=>r1,KNOWN_IDENTITY_TYPES:()=>sv,HTTPSOverlayBroadcastFacilitator:()=>sa,Peer:()=>n8,ReactNativeWebView:()=>ni,WhatsOnChainBroadcaster:()=>rw,defaultHttpClient:()=>rr,withDoubleSpendRetry:()=>sl,SimplifiedFetchTransport:()=>n5,WalletError:()=>rJ,SecurityLevels:()=>h,DefaultLockingScriptProvider:()=>sz,WalletClient:()=>nW,IdentityClient:()=>sA,Utils:()=>y});var g={};f.r(g),f.d(g,{RIPEMD160:()=>ec,SHA1:()=>ed,SHA1HMAC:()=>ep,SHA256:()=>eh,SHA256HMAC:()=>ef,SHA512:()=>eu,SHA512HMAC:()=>eg,hash160:()=>eS,hash256:()=>ek,htonl:()=>L,pbkdf2:()=>tn,realHtonl:()=>to,ripemd160:()=>eb,sha1:()=>ew,sha256:()=>ev,sha256hmac:()=>eE,sha512:()=>eI,sha512hmac:()=>ex,swapBytes32:()=>ts,toArray:()=>D});var y={};f.r(y),f.d(y,{Reader:()=>tN,ReaderUint8Array:()=>tc,Writer:()=>tP,WriterUint8Array:()=>tl,base64ToArray:()=>tv,constantTimeEquals:()=>tU,encode:()=>tk,fromBase58:()=>tx,fromBase58Check:()=>tO,minimallyEncode:()=>t_,toArray:()=>tm,toBase58:()=>tA,toBase58Check:()=>tT,toBase64:()=>tS,toHex:()=>tg,toUTF8:()=>tI,toUint8Array:()=>ty,verifyNotNull:()=>tB,zero2:()=>tu});var m={};f.r(m),f.d(m,{sign:()=>ie,verify:()=>it});var b={};f.r(b),f.d(b,{sign:()=>rA,verify:()=>rT});var w={};f.r(w),f.d(w,{decrypt:()=>rN,encrypt:()=>rP});var v={};f.r(v),f.d(v,{magicHash:()=>rR,sign:()=>rC,verify:()=>rB});var I={};f.r(I),f.d(I,{isHexString:()=>nw,parseWalletOutpoint:()=>nr,specOpThrowReviewActions:()=>nz,validateAbortActionArgs:()=>nA,validateAcquireDirectCertificateArgs:()=>nV,validateAcquireIssuanceCertificateArgs:()=>nL,validateBase64String:()=>ny,validateBasketInsertion:()=>nO,validateCreateActionArgs:()=>nS,validateCreateActionInput:()=>nv,validateCreateActionOptions:()=>nk,validateCreateActionOutput:()=>nI,validateDiscoverByAttributesArgs:()=>nK,validateDiscoverByIdentityKeyArgs:()=>nM,validateInteger:()=>nl,validateInternalizeActionArgs:()=>n_,validateInternalizeOutput:()=>nP,validateListActionsArgs:()=>n$,validateListCertificatesArgs:()=>nF,validateListOutputsArgs:()=>nq,validateOptionalInteger:()=>no,validateOptionalOutpointString:()=>nR,validateOriginator:()=>nN,validateOutpointString:()=>nC,validatePositiveIntegerOrZero:()=>nc,validateProveCertificateArgs:()=>nH,validateRelinquishCertificateArgs:()=>nU,validateRelinquishOutputArgs:()=>nB,validateSatoshis:()=>na,validateSignActionArgs:()=>nx,validateSignActionOptions:()=>nE,validateStringLength:()=>nh,validateWalletPayment:()=>nT});var k={};f.r(k),f.d(k,{getHashFromURL:()=>su,getURLForFile:()=>sd,getURLForHash:()=>sh,isValidURL:()=>sf,normalizeURL:()=>sc});let S="u"<typeof globalThis?void 0:globalThis.Buffer,E=null!=S&&"function"==typeof S.from,x=new Int8Array(256).fill(-1);for(let e=0;e<10;e++)x[48+e]=e;for(let e=0;e<6;e++)x[65+e]=10+e,x[97+e]=10+e;class A{static zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"];static groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5];static groupBases=[0,0,0x2000000,0x290d741,0x1000000,0x2e90edd,0x39aa400,0x267bf47,0x1000000,0x290d741,1e7,0x12959c3,0x222c000,0x3bd7765,7529536,0xadcea1,0x1000000,0x1704f61,0x206fc40,0x2cddcf9,64e6,4084101,5153632,6436343,7962624,9765625,0xb54ba0,0xdaf26b,0x1069c00,0x138f9ad,243e5,0x1b4d89f,0x2000000,0x25528a1,0x2b54a20,0x3216b93,0x39aa400];static wordSize=26;static WORD_SIZE_BIGINT=BigInt(A.wordSize);static WORD_MASK=(1n<<A.WORD_SIZE_BIGINT)-1n;static MAX_SAFE_INTEGER_BIGINT=BigInt(Number.MAX_SAFE_INTEGER);static MIN_SAFE_INTEGER_BIGINT=BigInt(Number.MIN_SAFE_INTEGER);static MAX_IMULN_ARG=0x3ffffff;static MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT=(1n<<53n)-1n;_magnitude=0n;_sign=0;_nominalWordLength=1;red;get negative(){return this._sign}set negative(e){this.assert(0===e||1===e,"Negative property must be 0 or 1"),0n===this._magnitude?this._sign=0:this._sign=+(1===e)}get _computedWordsArray(){if(0n===this._magnitude)return[0];let e=[],t=this._magnitude;for(;t>0n;)e.push(Number(t&A.WORD_MASK)),t>>=A.WORD_SIZE_BIGINT;return e.length>0?e:[0]}get words(){let e=this._computedWordsArray;if(this._nominalWordLength<=e.length)return e;let t=Array(this._nominalWordLength).fill(0);for(let i=0;i<e.length;i++)t[i]=e[i];return t}set words(e){let t=this._sign,i=0n,r=e.length>0?e.length:1;for(let t=r-1;t>=0;t--){let r=e[t]??0;i=i<<A.WORD_SIZE_BIGINT|BigInt(r&Number(A.WORD_MASK))}this._magnitude=i,this._sign=t,this._nominalWordLength=r,this.normSign()}get length(){return Math.max(1,this._nominalWordLength)}static isBN(e){return e instanceof A||null!==e&&"object"==typeof e&&e.constructor?.wordSize===A.wordSize&&Array.isArray(e.words)}static max(e,t){return e.cmp(t)>0?e:t}static min(e,t){return 0>e.cmp(t)?e:t}constructor(e=0,t=10,i="be"){if(this.red=null,null===(e??=0))return void this._initializeState(0n,0);if("bigint"==typeof e){this._initializeState(e<0n?-e:e,+(e<0n)),this.normSign();return}let r=t,n=i;if(("le"===t||"be"===t)&&(n=t,r=10),"number"==typeof e)return void this.initNumber(e,n);if(Array.isArray(e))return void this.initArray(e,n);if("string"==typeof e)return void this._initFromString(e,r,n);0!==e?this.assert(!1,"Unsupported input type for BigNumber constructor"):this._initializeState(0n,0)}_initFromString(e,t,i){"hex"===t&&(t=16),this.assert("number"==typeof t&&t===(0|t)&&t>=2&&t<=36,"Base must be an integer between 2 and 36");let r=e.toString().replace(/\s+/g,""),n=0,s=0;r.startsWith("-")?(n++,s=1):r.startsWith("+")&&n++;let a=r.substring(n);if(0===a.length){this._initializeState(0n,1===s&&r.startsWith("-")?1:0),this.normSign();return}16===t?this._initFromHexString(a,s,i):this._initFromNonHexString(a,t,s,i)}_initFromHexString(e,t,i){if("le"===i){let i=[],r=e;r.length%2!=0&&(r="0"+r);for(let e=0;e<r.length;e+=2){let t=Number.parseInt(r.substring(e,e+2),16);if(Number.isNaN(t))throw Error("Invalid character in "+r);i.push(t)}this.initArray(i,"le"),this._sign=t,this.normSign()}else{let i;try{i=BigInt("0x"+e)}catch(t){throw Error("Invalid character in "+e)}this._initializeState(i,t),this.normSign()}}_initFromNonHexString(e,t,i,r){try{if(this._parseBaseString(e,t),this._sign=i,this.normSign(),"le"===r){let e=this._sign;this.initArray(this.toArray("be"),"le"),this._sign=e,this.normSign()}}catch(e){if(e.message.includes("Invalid character in string")||e.message.includes("Invalid digit for base")||e.message.startsWith("Invalid character:"))throw Error("Invalid character");throw e}}_bigIntToStringInBase(e,t){if(0n===e)return"0";if(t<2||t>36)throw Error("Base must be between 2 and 36");let i="",r=e>0n?e:-e,n=BigInt(t);for(;r>0n;)i="0123456789abcdefghijklmnopqrstuvwxyz"[Number(r%n)]+i,r/=n;return i}_parseBaseString(e,t){if(0===e.length){this._magnitude=0n,this._finishInitialization();return}this._magnitude=0n;let i=BigInt(t),r=A.groupSizes[t],n=BigInt(A.groupBases[t]);(0===r||0n===n)&&(0===(r=Math.floor(Math.log(0x3ffffff)/Math.log(t)))&&(r=1),n=i**BigInt(r));let s=0,a=e.length,o=a%r;if(0===o&&a>0&&(o=r),o>0){let i=e.substring(s,s+o);this._magnitude=BigInt(this._parseBaseWord(i,t)),s+=o}for(;s<a;){let i=e.substring(s,s+r),a=BigInt(this._parseBaseWord(i,t));this._magnitude=this._magnitude*n+a,s+=r}this._finishInitialization()}_parseBaseWord(e,t){let i=0;for(let r=0;r<e.length;r++){let n,s=e.codePointAt(r);if(s>=48&&s<=57)n=s-48;else if(s>=65&&s<=90)n=s-65+10;else if(s>=97&&s<=122)n=s-97+10;else throw Error("Invalid character: "+e[r]);if(n>=t)throw Error("Invalid character");i=i*t+n}return i}_initializeState(e,t){this._magnitude=e,this._sign=0n===e?0:t,this._finishInitialization()}_finishInitialization(){if(0n===this._magnitude)this._nominalWordLength=1,this._sign=0;else{let e=this._magnitude.toString(2).length;this._nominalWordLength=Math.max(1,Math.ceil(e/A.wordSize))}}assert(e,t="Assertion failed"){if(!e)throw Error(t)}initNumber(e,t="be"){if(this.assert(BigInt(Math.abs(e))<=A.MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT,"The number is larger than 2 ^ 53 (unsafe)"),this.assert(e%1==0,"Number must be an integer for BigNumber conversion"),this._initializeState(BigInt(Math.abs(e)),+(e<0)),"le"===t){let e=this._sign,t=this.toArray("be");this.initArray(t,"le"),this._sign=e,this.normSign()}return this}initArray(e,t){if(0===e.length)return this._initializeState(0n,0),this;let i=0n;if("be"===t)for(let t of e)i=i<<8n|BigInt(255&t);else for(let t=e.length-1;t>=0;t--)i=i<<8n|BigInt(255&e[t]);return this._initializeState(i,0),this}copy(e){e._magnitude=this._magnitude,e._sign=this._sign,e._nominalWordLength=this._nominalWordLength,e.red=this.red}static move(e,t){e._magnitude=t._magnitude,e._sign=t._sign,e._nominalWordLength=t._nominalWordLength,e.red=t.red}clone(){let e=new A(0n);return this.copy(e),e}expand(e){return this.assert(e>=0,"Expand size must be non-negative"),this._nominalWordLength=Math.max(this._nominalWordLength,e,1),this}strip(){return this._finishInitialization(),this.normSign()}normSign(){return 0n===this._magnitude&&(this._sign=0),this}inspect(){return(null===this.red?"<BN: ":"<BN-R: ")+this.toString(16)+">"}_getMinimalHex(){return 0n===this._magnitude?"0":this._magnitude.toString(16)}toString(e=10,t=1){if(16===e||"hex"===e){let e=this._getMinimalHex();if(t>1)for("0"!==e&&e.length%2!=0&&(e="0"+e);e.length%t!=0;)e="0"+e;return(this.isNeg()?"-":"")+e}if("number"!=typeof e||e<2||e>36||e%1!=0)throw Error("Base should be an integer between 2 and 36");return this.toBaseString(e,t)}toBaseString(e,t){if(0n===this._magnitude){let e="0";if(t>1)for(;e.length<t;)e="0"+e;return e}let i=A.groupSizes[e],r=BigInt(A.groupBases[e]);(0===i||0n===r)&&(0===(i=Math.floor(Math.log(Number.MAX_SAFE_INTEGER)/Math.log(e)))&&(i=1),r=BigInt(e)**BigInt(i));let n="",s=this._magnitude;for(;s>0n;){let t=s%r;s/=r;let a=this._bigIntToStringInBase(t,e);n=(s>0n?this._zeroPaddedChunk(a,i):a)+n}if(t>0)for(;n.length<t;)n="0"+n;return(1===this._sign?"-":"")+n}_zeroPaddedChunk(e,t){let i=t-e.length;return i<=0?e:i<A.zeros.length?A.zeros[i]+e:"0".repeat(i)+e}toNumber(){let e=this._getSignedValue();if(e>A.MAX_SAFE_INTEGER_BIGINT||e<A.MIN_SAFE_INTEGER_BIGINT)throw Error("Number can only safely store up to 53 bits");return Number(e)}toBigInt(){return this._getSignedValue()}toJSON(){let e=this._getMinimalHex();return(this.isNeg()?"-":"")+e}toArrayLikeGeneric(e,t){let i=this._magnitude,r=t?0:e.length-1,n=t?1:-1;for(let t=0;t<e.length;++t){if(0n===i&&r>=0&&r<e.length)e[r]=0;else if(r>=0&&r<e.length)e[r]=Number(255n&i);else break;i>>=8n,r+=n}}toArray(e="be",t){this.strip();let i=this.byteLength(),r=t??Math.max(1,i);this.assert(i<=r,"byte array longer than desired length"),this.assert(r>0,"Requested array length <= 0");let n=Array(r).fill(0);return 0n===this._magnitude&&r>0?n:0n===this._magnitude&&0===r?[]:(this.toArrayLikeGeneric(n,"le"===e),n)}bitLength(){return 0n===this._magnitude?0:this._magnitude.toString(2).length}static toBitArray(e){let t=e.bitLength();if(0===t)return[];let i=Array(t),r=e._magnitude;for(let e=0;e<t;e++)i[e]=+((r>>BigInt(e)&1n)!==0n);return i}toBitArray(){return A.toBitArray(this)}zeroBits(){if(0n===this._magnitude)return 0;let e=0,t=this._magnitude;for(;(1n&t)===0n&&0n!==t;)e++,t>>=1n;return e}byteLength(){return 0n===this._magnitude?0:Math.ceil(this.bitLength()/8)}_getSignedValue(){return 1===this._sign?-this._magnitude:this._magnitude}_setValueFromSigned(e){e<0n?(this._magnitude=-e,this._sign=1):(this._magnitude=e,this._sign=0),this._finishInitialization(),this.normSign()}toTwos(e){this.assert(e>=0);let t=BigInt(e),i=this._getSignedValue();1===this._sign&&0n!==this._magnitude&&(i=(1n<<t)+i),i&=(1n<<t)-1n;let r=new A(0n);return r._initializeState(i,0),r}fromTwos(e){this.assert(e>=0);let t=BigInt(e),i=this._magnitude;if(e>0&&(i>>t-1n&1n)!==0n&&0===this._sign){let e=new A(0n);return e._setValueFromSigned(i-(1n<<t)),e}return this.clone()}isNeg(){return 1===this._sign&&0n!==this._magnitude}neg(){return this.clone().ineg()}ineg(){return 0n!==this._magnitude&&(this._sign=+(1!==this._sign)),this}_iuop(e,t,i=!1){let r=t(this._magnitude,e._magnitude),n=this._nominalWordLength;return i&&(n=Math.max(this.length,e.length)),this._magnitude=r,this._finishInitialization(),i&&(this._nominalWordLength=Math.max(this._nominalWordLength,n)),this.strip()}iuor(e){return this._iuop(e,(e,t)=>e|t)}iuand(e){return this._iuop(e,(e,t)=>e&t)}iuxor(e){return this._iuop(e,(e,t)=>e^t,!0)}_iop(e,t,i=!1){return this.assert(0===this._sign&&0===e._sign),this._iuop(e,t,i)}ior(e){return this._iop(e,(e,t)=>e|t)}iand(e){return this._iop(e,(e,t)=>e&t)}ixor(e){return this._iop(e,(e,t)=>e^t,!0)}_uop_new(e,t){return this.length>=e.length?this.clone()[t](e):e.clone()[t](this)}or(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuor")}uor(e){return this._uop_new(e,"iuor")}and(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuand")}uand(e){return this._uop_new(e,"iuand")}xor(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuxor")}uxor(e){return this._uop_new(e,"iuxor")}inotn(e){this.assert("number"==typeof e&&e>=0);let t=BigInt(e);this._magnitude=~this._magnitude&(1n<<t)-1n;let i=0===e?1:Math.ceil(e/A.wordSize);return this._nominalWordLength=Math.max(1,i),this.strip(),this._nominalWordLength=Math.max(this._nominalWordLength,Math.max(1,i)),this}notn(e){return this.clone().inotn(e)}setn(e,t){this.assert("number"==typeof e&&e>=0);let i=BigInt(e);1===t||!0===t?this._magnitude|=1n<<i:this._magnitude&=~(1n<<i);let r=Math.floor(e/A.wordSize)+1;return this._nominalWordLength=Math.max(this._nominalWordLength,r),this._finishInitialization(),this.strip()}iadd(e){return this._setValueFromSigned(this._getSignedValue()+e._getSignedValue()),this}add(e){let t=new A(0n);return t._setValueFromSigned(this._getSignedValue()+e._getSignedValue()),t}isub(e){return this._setValueFromSigned(this._getSignedValue()-e._getSignedValue()),this}sub(e){let t=new A(0n);return t._setValueFromSigned(this._getSignedValue()-e._getSignedValue()),t}mul(e){let t=new A(0n);return t._magnitude=this._magnitude*e._magnitude,t._sign=0n===t._magnitude?0:this._sign^e._sign,t._nominalWordLength=this.length+e.length,t.red=null,t.normSign()}imul(e){return this._magnitude*=e._magnitude,this._sign=0n===this._magnitude?0:this._sign^e._sign,this._nominalWordLength=this.length+e.length,this.red=null,this.normSign()}imuln(e){return this.assert("number"==typeof e,"Assertion failed"),this.assert(Math.abs(e)<=A.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()*BigInt(e)),this}muln(e){return this.clone().imuln(e)}sqr(){let e=new A(0n);return e._magnitude=this._magnitude*this._magnitude,e._sign=0,e._nominalWordLength=2*this.length,e.red=null,e}isqr(){return this._magnitude*=this._magnitude,this._sign=0,this._nominalWordLength=2*this.length,this.red=null,this}pow(e){if(this.assert(0===e._sign,"Exponent for pow must be non-negative"),e.isZero())return new A(1n);let t=new A(1n),i=this.clone(),r=e.clone(),n=i.isNeg(),s=r.isOdd();for(n&&i.ineg();!r.isZero();)r.isOdd()&&t.imul(i),i.isqr(),r.iushrn(1);return n&&s&&t.ineg(),t}static normalizeNonNegativeBigInt(e,t){if("number"==typeof e){if(!Number.isFinite(e)||!Number.isInteger(e)||e<0)throw Error(`${t} must be a non-negative integer`);return BigInt(e)}if(e<0n)throw Error(`${t} must be a non-negative integer`);return e}iushln(e){let t=A.normalizeNonNegativeBigInt(e,"Shift bits");return 0n===t?this:(this._magnitude<<=t,this._finishInitialization(),this.strip())}ishln(e){return this.assert(0===this._sign,"ishln requires positive number"),this.iushln(e)}iushrn(e,t,i){let r=A.normalizeNonNegativeBigInt(e,"Shift bits");if(0n===r)return null!=i&&i._initializeState(0n,0),this;if(null!=i){let e=this._magnitude&(1n<<r)-1n;i._initializeState(e,0)}return this._magnitude>>=r,this._finishInitialization(),this.strip()}ishrn(e,t,i){return this.assert(0===this._sign,"ishrn requires positive number"),this.iushrn(e,t,i)}shln(e){return this.clone().ishln(e)}ushln(e){return this.clone().iushln(e)}shrn(e){return this.clone().ishrn(e)}ushrn(e){return this.clone().iushrn(e)}testn(e){return this.assert("number"==typeof e&&e>=0),(this._magnitude>>BigInt(e)&1n)!==0n}imaskn(e){this.assert("number"==typeof e&&e>=0),this.assert(0===this._sign,"imaskn works only with positive numbers");let t=BigInt(e);this._magnitude&=0n===t?0n:(1n<<t)-1n;let i=0===e?1:Math.max(1,Math.ceil(e/A.wordSize));return this._nominalWordLength=i,this._finishInitialization(),this._nominalWordLength=Math.max(this._nominalWordLength,i),this.strip()}maskn(e){return this.clone().imaskn(e)}iaddn(e){return this.assert("number"==typeof e),this.assert(Math.abs(e)<=A.MAX_IMULN_ARG,"num is too large"),this._setValueFromSigned(this._getSignedValue()+BigInt(e)),this}_iaddn(e){return this.iaddn(e)}isubn(e){return this.assert("number"==typeof e),this.assert(Math.abs(e)<=A.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()-BigInt(e)),this}addn(e){return this.clone().iaddn(e)}subn(e){return this.clone().isubn(e)}iabs(){return this._sign=0,this}abs(){return this.clone().iabs()}divmod(e,t,i){if(this.assert(!e.isZero(),"Division by zero"),this.isZero()){let e=new A(0n);return{div:"mod"===t?null:e,mod:"div"===t?null:e}}let r=this._getSignedValue(),n=e._getSignedValue(),s="mod"!==t?r/n:null,a=this._computeMod(r,n,t,i);return{div:this._bigNumberFromSigned(s),mod:this._bigNumberFromSigned(a)}}_computeMod(e,t,i,r){if("div"===i)return null;let n=e%t;return!0===r&&n<0n&&(n+=t<0n?-t:t),n}_bigNumberFromSigned(e){if(null===e)return null;let t=new A(0n);return t._setValueFromSigned(e),t}div(e){return this.divmod(e,"div",!1).div}mod(e){return this.divmod(e,"mod",!1).mod}umod(e){return this.divmod(e,"mod",!0).mod}divRound(e){this.assert(!e.isZero());let t=this._getSignedValue(),i=e._getSignedValue(),r=t/i,n=t%i;if(0n===n){let e=new A(0n);return e._setValueFromSigned(r),e}2n*(n<0n?-n:n)>=(i<0n?-i:i)&&(t>0n&&i>0n||t<0n&&i<0n?r+=1n:r-=1n);let s=new A(0n);return s._setValueFromSigned(r),s}modrn(e){this.assert(0!==e,"Division by zero in modrn");let t=BigInt(Math.abs(e));if(0n===t)throw Error("Division by zero in modrn");let i=this._magnitude%t;return e<0?Number(-i):Number(i)}idivn(e){return this.assert(0!==e),this.assert(Math.abs(e)<=A.MAX_IMULN_ARG,"num is too large"),this._setValueFromSigned(this._getSignedValue()/BigInt(e)),this}divn(e){return this.clone().idivn(e)}egcd(e){this.assert(0===e._sign,"p must not be negative"),this.assert(!e.isZero(),"p must not be zero");let t=this._getSignedValue(),i=e._magnitude,r=1n,n=0n,s=0n,a=1n;for(;0n!==i;){let e=t/i,o=i;i=t%i,t=o,o=n,n=r-e*n,r=o,o=a,a=s-e*a,s=o}let o=new A(0n);o._setValueFromSigned(r);let l=new A(0n);l._setValueFromSigned(s);let c=new A(0n);return c._initializeState(t<0n?-t:t,0),{a:o,b:l,gcd:c}}gcd(e){let t=this._magnitude,i=e._magnitude;if(0n===t){let e=new A(0n);return e._setValueFromSigned(i),e.iabs()}if(0n===i){let e=new A(0n);return e._setValueFromSigned(t),e.iabs()}for(;0n!==i;){let e=t%i;t=i,i=e}let r=new A(0n);return r._initializeState(t,0),r}invm(e){this.assert(!e.isZero()&&0===e._sign,"Modulus for invm must be positive and non-zero");let t=this.egcd(e);if(!t.gcd.eqn(1))throw Error("Inverse does not exist (numbers are not coprime).");return t.a.umod(e)}isEven(){return this._magnitude%2n===0n}isOdd(){return this._magnitude%2n===1n}andln(e){return this.assert(e>=0),Number(this._magnitude&BigInt(e))}bincn(e){this.assert("number"==typeof e&&e>=0);let t=1n<<BigInt(e);return this._setValueFromSigned(this._getSignedValue()+t),this}isZero(){return 0n===this._magnitude}cmpn(e){this.assert(Math.abs(e)<=A.MAX_IMULN_ARG,"Number is too big");let t=this._getSignedValue(),i=BigInt(e);return t<i?-1:+(t>i)}cmp(e){let t=this._getSignedValue(),i=e._getSignedValue();return t<i?-1:+(t>i)}ucmp(e){return this._magnitude<e._magnitude?-1:+(this._magnitude>e._magnitude)}gtn(e){return 1===this.cmpn(e)}gt(e){return 1===this.cmp(e)}gten(e){return this.cmpn(e)>=0}gte(e){return this.cmp(e)>=0}ltn(e){return -1===this.cmpn(e)}lt(e){return -1===this.cmp(e)}lten(e){return 0>=this.cmpn(e)}lte(e){return 0>=this.cmp(e)}eqn(e){return 0===this.cmpn(e)}eq(e){return 0===this.cmp(e)}toRed(e){return this.assert(null==this.red,"Already a number in reduction context"),this.assert(0===this._sign,"toRed works only with positives"),e.convertTo(this).forceRed(e)}fromRed(){return this.assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)}forceRed(e){return this.red=e,this}redAdd(e){return this.assert(this.red,"redAdd works only with red numbers"),this.red.add(this,e)}redIAdd(e){return this.assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)}redSub(e){return this.assert(this.red,"redSub works only with red numbers"),this.red.sub(this,e)}redISub(e){return this.assert(this.red,"redISub works only with red numbers"),this.red.isub(this,e)}redShl(e){return this.assert(this.red,"redShl works only with red numbers"),this.red.shl(this,e)}redMul(e){return this.assert(this.red,"redMul works only with red numbers"),this.red.verify2(this,e),this.red.mul(this,e)}redIMul(e){return this.assert(this.red,"redIMul works only with red numbers"),this.red.verify2(this,e),this.red.imul(this,e)}redSqr(){return this.assert(this.red,"redSqr works only with red numbers"),this.red.verify1(this),this.red.sqr(this)}redISqr(){return this.assert(this.red,"redISqr works only with red numbers"),this.red.verify1(this),this.red.isqr(this)}redSqrt(){return this.assert(this.red,"redSqrt works only with red numbers"),this.red.verify1(this),this.red.sqrt(this)}redInvm(){return this.assert(this.red,"redInvm works only with red numbers"),this.red.verify1(this),this.red.invm(this)}redNeg(){return this.assert(this.red,"redNeg works only with red numbers"),this.red.verify1(this),this.red.neg(this)}redPow(e){return this.assert(null!=this.red&&null==e.red,"redPow(normalNum)"),this.red.verify1(this),this.red.pow(this,e)}static fromHex(e,t){let i="be";return("little"===t||"le"===t)&&(i="le"),new A(e,16,i)}toHex(e=0){if(this.isZero()&&0===e)return"";let t=this._getMinimalHex();"0"!==t&&t.length%2!=0&&(t="0"+t);let i=2*e;for(;t.length<i;)t="0"+t;return(this.isNeg()?"-":"")+t}static fromJSON(e){return new A(e,16)}static fromNumber(e){return new A(e)}static fromString(e,t){return new A(e,t)}static fromSm(e,t="big"){let i;if(0===e.length)return new A(0n);let r=e.slice();"little"===t&&r.reverse();let n=0;if(r.length>0&&(128&r[0])!=0&&(n=1,r[0]&=127),E)i=S.from(r).toString("hex");else for(let e of(i="",r))i+=e<16?"0"+e.toString(16):e.toString(16);let s=0===i.length?0n:BigInt("0x"+i),a=new A(0n);return a._initializeState(s,n),a}toSm(e="big"){let t;if(0n===this._magnitude)return 1===this._sign?[128]:[];let i=this._getMinimalHex();i.length%2!=0&&(i="0"+i);let r=Array(i.length/2);for(let e=0,t=0;e<i.length;e+=2){let n=x[i.codePointAt(e)],s=x[i.codePointAt(e+1)];r[t++]=(15&n)<<4|15&s}return 1===this._sign?(128&r[0])==0?(t=r.slice(),t[0]|=128):t=[128,...r]:t=(128&r[0])==0?r.slice():[0,...r],"little"===e?t.reverse():t}static fromBits(e,t=!1){let i=e>>>24,r=8388607&e,n=(8388608&e)!=0;if(t&&n)throw Error("negative bit set");if(0===i&&0===r){if(n&&t)throw Error("negative bit set for zero value");return new A(0n)}let s=new A(r);return i<=3?s.iushrn((3-i)*8):s.iushln((i-3)*8),n&&s.ineg(),s}toBits(){let e;if(this.strip(),this.isZero()&&!this.isNeg())return 0;let t=this.isNeg(),i=this.abs(),r=i.toArray("be"),n=0;for(;n<r.length-1&&0===r[n];)n++;let s=(r=r.slice(n)).length;if(0!==s||i.isZero()||(r=[0],s=1),i.isZero()&&(s=0,r=[]),0===s)e=0;else if(s<=3){e=0;for(let t=0;t<s;t++)e=e<<8|r[t]}else e=r[0]<<16|r[1]<<8|r[2];(8388608&e)!=0&&s<=255&&(e>>>=8,s++);let a=s<<24|e;return t&&(a|=8388608),a>>>0}static fromScriptNum(e,t=!1,i){if(void 0!==i&&e.length>i)throw Error("script number overflow");if(0===e.length)return new A(0n);if(t&&(127&e.at(-1))==0&&(e.length<=1||(128&e.at(-2))==0))throw Error("non-minimally encoded script number");return A.fromSm(e,"little")}toScriptNum(){return this.toSm("little")}_invmp(e){this.assert(0===e._sign,"p must not be negative for _invmp"),this.assert(!e.isZero(),"p must not be zero for _invmp");let t=this.umod(e),i=e.subn(2);if(null!==t.red)return t.redPow(i);let r=new A(1n),n=t.clone(),s=i.clone();for(;!s.isZero();)s.isOdd()&&(r=r.mul(n).umod(e)),n=n.sqr().umod(e),s.iushrn(1);return r}mulTo(e,t){return t._magnitude=this._magnitude*e._magnitude,t._sign=0n===t._magnitude?0:this._sign^e._sign,t._nominalWordLength=this.length+e.length,t.red=null,t.normSign(),t}}class T{name;p;k;n;tmp;constructor(e,t){this.name=e,this.p=new A(t,16),this.n=this.p.bitLength(),this.k=new A(BigInt(1)).iushln(this.n).isub(this.p),this.tmp=this._tmp()}_tmp(){let e=new A(BigInt(0)),t=Math.ceil(this.n/A.wordSize);return e.expand(Math.max(1,t)),e}ireduce(e){let t;do this.split(e,this.tmp),this.imulK(e),e.iadd(this.tmp),t=e.bitLength();while(t>this.n);let i=t<this.n?-1:e.ucmp(this.p);return 0===i?e.words=[0]:i>0&&e.isub(this.p),e.strip(),e}split(e,t){e.iushrn(this.n,0,t)}imulK(e){return e.imul(this.k)}}class O extends T{constructor(){super("k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}split(e,t){let i=e.words,r=e.length,n=Math.min(r,9),s=Array(n+ +(r>9)).fill(0);for(let e=0;e<n;e++)s[e]=i[e];let a=n;if(r<=9){let i=Array(a);for(let e=0;e<a;++e)i[e]=s[e];t.words=i,e.words=[0];return}let o=i[9];s[a++]=4194303&o;let l=Array(a);for(let e=0;e<a;++e)l[e]=s[e];t.words=l;let c=Array(Math.max(1,r-9)).fill(0),h=0;for(let e=10;e<r;e++){let t=Math.trunc(i[e]);h<c.length&&(c[h++]=(4194303&t)<<4|o>>>22),o=t}o>>>=22,h<c.length?c[h++]=o:0!==o&&c.length;let d=Array(h);for(let e=0;e<h;++e)d[e]=c[e];e.words=d}imulK(e){let t=e.words,i=e.length,r=i+2,n=Array(r).fill(0);for(let e=0;e<i;e++)n[e]=t[e];let s=0;for(let e=0;e<r;e++){let t=Math.trunc(n[e]);s+=977*t,n[e]=0x3ffffff&s,s=64*t+Math.trunc(s/0x4000000)}return e.words=n,e}}class P{prime;m;constructor(e){if("k256"===e){const e=new O;this.m=e.p,this.prime=e}else this.assert(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}assert(e,t="Assertion failed"){if(!e)throw Error(t)}verify1(e){this.assert(0===e.negative,"red works only with positives"),this.assert(e.red,"red works only with red numbers")}verify2(e,t){this.assert((e.negative|t.negative)==0,"red works only with positives"),this.assert(null!=e.red&&e.red===t.red,"red works only with red numbers")}imod(e){return null!=this.prime?this.prime.ireduce(e).forceRed(this):(A.move(e,e.umod(this.m).forceRed(this)),e)}neg(e){return e.isZero()?e.clone():this.m.sub(e).forceRed(this)}add(e,t){this.verify2(e,t);let i=e.clone();return i.iadd(t),i.isub(this.m),i.isNeg()&&i.iadd(this.m),i}iadd(e,t){return this.verify2(e,t),e.iadd(t),e.isub(this.m),e.isNeg()&&e.iadd(this.m),e}sub(e,t){this.verify2(e,t);let i=e.sub(t);return 0>i.cmpn(0)&&i.iadd(this.m),i.forceRed(this)}isub(e,t){this.verify2(e,t);let i=e.isub(t);return 0>i.cmpn(0)&&i.iadd(this.m),i}shl(e,t){return this.verify1(e),this.imod(e.ushln(t))}imul(e,t){return this.verify2(e,t),this.imod(e.imul(t))}mul(e,t){return this.verify2(e,t),this.imod(e.mul(t))}isqr(e){return this.imul(e,e.clone())}sqr(e){return this.mul(e,e)}sqrt(e){if(e.isZero())return e.clone();let t=this.m.andln(3);if(this.assert(t%2==1),3===t){let t=this.m.add(new A(1)).iushrn(2);return this.pow(e,t)}let i=this.m.subn(1),r=0;for(;!i.isZero()&&0===i.andln(1);)r++,i.iushrn(1);this.assert(!i.isZero());let n=new A(1).toRed(this),s=n.redNeg(),a=this.m.subn(1).iushrn(1),o=this.m.bitLength(),l=new A(2*o*o).toRed(this);for(;0!==this.pow(l,a).cmp(s);)l.redIAdd(s);let c=this.pow(l,i),h=this.pow(e,i.addn(1).iushrn(1)),d=this.pow(e,i),u=r;for(;0!==d.cmp(n);){let e=d,t=0;for(;0!==e.cmp(n);t++)e=e.redSqr();this.assert(t<u);let i=this.pow(c,new A(1).iushln(u-t-1));h=h.redMul(i),c=i.redSqr(),d=d.redMul(c),u=t}return h}invm(e){let t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)}pow(e,t){if(this.verify1(e),t.isZero())return new A(1).toRed(this);let i=new A(1).toRed(this),r=e.clone(),n=t.bitLength();for(let e=n-1;e>=0;e--)i=this.sqr(i),t.testn(e)&&(i=this.mul(i,r));return i}convertTo(e){let t=e.umod(this.m);return t===e?t.clone():t}convertFrom(e){let t=e.clone();return t.red=null,t}}class N extends P{shift;r;r2;rinv;minv;constructor(e){super(e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new A(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}convertTo(e){return this.imod(e.ushln(this.shift))}convertFrom(e){let t=this.imod(e.mul(this.rinv));return t.red=null,t}imul(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;let i=e.imul(t),r=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=i.isub(r).iushrn(this.shift),s=n;return n.cmp(this.m)>=0?s=n.isub(this.m):0>n.cmpn(0)&&(s=n.iadd(this.m)),s.forceRed(this)}mul(e,t){if(e.isZero()||t.isZero())return new A(0).forceRed(this);let i=e.mul(t),r=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=i.isub(r).iushrn(this.shift),s=n;return n.cmp(this.m)>=0?s=n.isub(this.m):0>n.cmpn(0)&&(s=n.iadd(this.m)),s.forceRed(this)}invm(e){return this.imod(e._invmp(this.m).mul(this.r2)).forceRed(this)}}class _{curve;type;precomputed;constructor(e){this.curve=new t1,this.type=e,this.precomputed=null}}class R extends _{x;y;z;zOne;constructor(e,t,i){super("jacobian"),null===e&&null===t&&null===i?(this.x=this.curve.one,this.y=this.curve.one,this.z=new A(0)):(A.isBN(e)||(e=new A(e,16)),this.x=e,A.isBN(t)||(t=new A(t,16)),this.y=t,A.isBN(i)||(i=new A(i,16)),this.z=i),null==this.x.red&&(this.x=this.x.toRed(this.curve.red)),null==this.y.red&&(this.y=this.y.toRed(this.curve.red)),null==this.z.red&&(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.isInfinity()&&(this.x=this.curve.one,this.y=this.curve.one,this.z=new A(0).toRed(this.curve.red),this.zOne=!1)}toP(){if(this.isInfinity())return new t0(null,null);let e=this.z.redInvm(),t=e.redSqr();return new t0(this.x.redMul(t),this.y.redMul(t).redMul(e))}neg(){return new R(this.x,this.y.redNeg(),this.z)}add(e){if(this.isInfinity())return e;if(e.isInfinity())return this;let t=e.z.redSqr(),i=this.z.redSqr(),r=this.x.redMul(t),n=e.x.redMul(i),s=this.y.redMul(t.redMul(e.z)),a=e.y.redMul(i.redMul(this.z)),o=r.redSub(n),l=s.redSub(a);if(0===o.cmpn(0))if(0===l.cmpn(0))return this.dbl();else return new R(null,null,null);let c=o.redSqr(),h=c.redMul(o),d=r.redMul(c),u=l.redSqr().redIAdd(h).redISub(d).redISub(d),f=l.redMul(d.redISub(u)).redISub(s.redMul(h));return new R(u,f,this.z.redMul(e.z).redMul(o))}mixedAdd(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;if(null===e.x||null===e.y)throw Error("Point coordinates cannot be null");let t=this.z.redSqr(),i=this.x,r=e.x.redMul(t),n=this.y,s=e.y.redMul(t).redMul(this.z),a=i.redSub(r),o=n.redSub(s);if(0===a.cmpn(0))if(0===o.cmpn(0))return this.dbl();else return new R(null,null,null);let l=a.redSqr(),c=l.redMul(a),h=i.redMul(l),d=o.redSqr().redIAdd(c).redISub(h).redISub(h),u=o.redMul(h.redISub(d)).redISub(n.redMul(c));return new R(d,u,this.z.redMul(a))}dblp(e){if(0===e||this.isInfinity())return this;if(void 0===e)return this.dbl();let t=this;for(let i=0;i<e;i++)t=t.dbl();return t}dbl(){let e,t,i;if(this.isInfinity())return this;if(this.zOne){let r=this.x.redSqr(),n=this.y.redSqr(),s=n.redSqr(),a=this.x.redAdd(n).redSqr().redISub(r).redISub(s);a=a.redIAdd(a);let o=r.redAdd(r).redIAdd(r),l=o.redSqr().redISub(a).redISub(a),c=s.redIAdd(s);c=(c=c.redIAdd(c)).redIAdd(c),e=l,t=o.redMul(a.redISub(l)).redISub(c),i=this.y.redAdd(this.y)}else{let r=this.x.redSqr(),n=this.y.redSqr(),s=n.redSqr(),a=this.x.redAdd(n).redSqr().redISub(r).redISub(s);a=a.redIAdd(a);let o=r.redAdd(r).redIAdd(r),l=o.redSqr(),c=s.redIAdd(s);c=(c=c.redIAdd(c)).redIAdd(c),e=l.redISub(a).redISub(a),t=o.redMul(a.redISub(e)).redISub(c),i=(i=this.y.redMul(this.z)).redIAdd(i)}return new R(e,t,i)}eq(e){if("affine"===e.type)return this.eq(e.toJ());if(this===e||this.isInfinity()&&e.isInfinity())return!0;if(this.isInfinity()!==e.isInfinity())return!1;let t=this.z.redSqr(),i=e.z.redSqr();if(0!==this.x.redMul(i).redISub(e.x.redMul(t)).cmpn(0))return!1;let r=t.redMul(this.z),n=i.redMul(e.z);return 0===this.y.redMul(n).redISub(e.y.redMul(r)).cmpn(0)}eqXToP(e){let t=this.z.redSqr(),i=e.toRed(this.curve?.red).redMul(t);if(0===this.x.cmp(i))return!0;let r=e.clone();if(this.curve?.redN==null)throw Error("Curve or redN is not initialized.");let n=this.curve.redN.redMul(t);for(;0>r.cmp(this.curve.p)&&(r.iadd(this.curve.n),!(r.cmp(this.curve.p)>=0));)if(i.redIAdd(n),0===this.x.cmp(i))return!0;return!1}inspect(){return this.isInfinity()?"<EC JPoint Infinity>":"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"}isInfinity(){return 0===this.z.cmpn(0)}}let C=/^[0-9a-fA-F]*$/;function B(e){if("string"!=typeof e)throw TypeError("Invalid hex string");if(0!==e.length&&!C.test(e))throw Error("Invalid hex string")}let U=(e,t="Hash assertion failed")=>{if(!e)throw Error(t)};class F{pending;pendingTotal;blockSize;outSize;endian;_delta8;_delta32;padLength;hmacStrength;constructor(e,t,i,r){this.pending=null,this.pendingTotal=0,this.blockSize=e,this.outSize=t,this.hmacStrength=i,this.padLength=r/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}_update(e,t){throw Error("Not implemented")}_digest(){throw Error("Not implemented")}_digestHex(){throw Error("Not implemented")}update(e,t){if(e=D(e,t),null==this.pending?this.pending=e:this.pending=this.pending.concat(e),this.pendingTotal+=e.length,this.pending.length>=this._delta8){let t=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-t,e.length),0===this.pending.length&&(this.pending=null),e=function(e,t,i){let r=t-0;U(r%4==0);let n=Array(r/4);for(let t=0,r=0;t<n.length;t++,r+=4){let s;s="big"===i?e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3]:e[r+3]<<24|e[r+2]<<16|e[r+1]<<8|e[r],n[t]=s>>>0}return n}(e,e.length-t,this.endian);for(let t=0;t<e.length;t+=this._delta32)this._update(e,t)}return this}digest(){return this.update(this._pad()),U(null===this.pending),this._digest()}digestHex(){return this.update(this._pad()),U(null===this.pending),this._digestHex()}_pad(){let e,t=this.pendingTotal;if(!Number.isSafeInteger(t)||t<0)throw Error("Message too long for this hash function");let i=this._delta8,r=i-(t+this.padLength)%i,n=Array(r+this.padLength);for(e=1,n[0]=128;e<r;e++)n[e]=0;let s=this.padLength,a=1n<<BigInt(8*s),o=8n*BigInt(t);if(o>=a)throw Error("Message too long for this hash function");if("big"===this.endian){let t=Array(s);for(let e=s-1;e>=0;e--)t[e]=Number(255n&o),o>>=8n;for(let i=0;i<s;i++)n[e++]=t[i]}else for(let t=0;t<s;t++)n[e++]=Number(255n&o),o>>=8n;return n}}function D(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];if("string"==typeof e)return"hex"===t?function(e){B(e);let t=function(e){if(B(e),0===e.length)return"";let t=e.toLowerCase();return t.length%2!=0&&(t="0"+t),t}(e),i=[];for(let e=0;e<t.length;e+=2)i.push(Number.parseInt(t[e]+t[e+1],16));return i}(e):function(e){let t=[];for(let i=0;i<e.length;i++)i=function(e,t,i){let r=e.charCodeAt(t);return r<128?(i.push(r),t):r<2048?(i.push(r>>6|192,63&r|128),t):(64512&e.charCodeAt(t))!=55296||t<0||t+1>=e.length||(64512&e.charCodeAt(t+1))!=56320?(i.push(r>>12|224,r>>6&63|128,63&r|128),t):(r=65536+((1023&r)<<10)+(1023&e.charCodeAt(t+1)),i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128),t+1)}(e,i,t);return t}(e);let i=[];for(let t=0;t<e.length;t++)i[t]=Math.trunc(e[t]);return i}function L(e){return ts(e)}function V(e,t){let i="";for(let r of e)"little"===t&&(r=ts(r)),i+=function(e){if(7===e.length)return"0"+e;if(6===e.length)return"00"+e;if(5===e.length)return"000"+e;if(4===e.length)return"0000"+e;if(3===e.length)return"00000"+e;else if(2===e.length)return"000000"+e;else if(1===e.length)return"0000000"+e;else return e}(r.toString(16));return i}let H="u"<typeof globalThis?void 0:globalThis.Buffer,M=null!=H&&"function"==typeof H.from,K="0123456789abcdef",q=Array(256);for(let e=0;e<q.length;e++)q[e]=K[e>>4&15]+K[15&e];let $=(()=>{let e="u"<typeof globalThis?void 0:globalThis.process,t=e?.getBuiltinModule;if("function"==typeof t)try{let i=t.call(e,"node:crypto");if(null!=i)return i}catch{}try{if("function"==typeof require)return require("node:crypto")}catch{}})();function z(e,t){return e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):Uint8Array.from(D(e,t))}function W(e){return"string"==typeof e?z(e,"hex"):z(e)}function j(e,t,i){null!=e?e.update(i):null!=t&&t.update(i)}function G(e,t){return null!=e?Array.from(e.digest()):null!=t?Array.from(t.digest()):[]}function X(e,t){if(null!=e)return e.digest("hex");if(null!=t){var i=t.digest();if(M)return H.from(i).toString("hex");let e=Array(i.length);for(let t=0;t<i.length;t++)e[t]=q[i[t]];return e.join("")}return""}function Y(e){let t=$?.createHash;if("function"==typeof t)try{return t(e)}catch{return}}function J(e,t){let i=$?.createHmac;if("function"==typeof i)try{return i(e,t)}catch{return}}function Z(e,t,i){let r=Y(e);if(null!=r)return r.update(z(t,i)),r.digest()}function Q(e,t,i,r){let n=J(e,W(t));if(null!=n)return n.update(z(i,r)),n.digest()}function ee(e,t){let i=Array(4*e.length);for(let r=0,n=0;r<e.length;r++,n+=4){let s=e[r];"big"===t?(i[n]=s>>>24,i[n+1]=s>>>16&255,i[n+2]=s>>>8&255,i[n+3]=255&s):(i[n+3]=s>>>24,i[n+2]=s>>>16&255,i[n+1]=s>>>8&255,i[n]=255&s)}return i}function et(e,t){return e>>>t|e<<32-t}function ei(e,t){return e<<t|e>>>32-t}function er(e,t){return e+t>>>0}let en=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],es=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],ea=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],eo=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11];function el(e,t,i,r){return e<=15?t^i^r:e<=31?t&i|~t&r:e<=47?(t|~i)^r:e<=63?t&r|i&~r:t^(i|~r)}class ec extends F{h;constructor(){super(512,160,192,64),this.endian="little",this.h=[0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0],this.endian="little"}_update(e,t){var i,r,n,s,a,o;let l,c=this.h[0],h=this.h[1],d=this.h[2],u=this.h[3],f=this.h[4],p=c,g=h,y=d,m=u,b=f;for(let w=0;w<80;w++){l=er(ei((i=c,r=el(w,h,d,u),i+r+e[en[w]+t]+((a=w)<=15?0:a<=31?0x5a827999:a<=47?0x6ed9eba1:a<=63?0x8f1bbcdc:0xa953fd4e)>>>0),ea[w]),f),c=f,f=u,u=ei(d,10),d=h,h=l,l=er(ei((n=p,s=el(79-w,g,y,m),n+s+e[es[w]+t]+((o=w)<=15?0x50a28be6:o<=31?0x5c4dd124:o<=47?0x6d703ef3:0x7a6d76e9*!!(o<=63))>>>0),eo[w]),b),p=b,b=m,m=ei(y,10),y=g,g=l}l=this.h[1]+d+m>>>0,this.h[1]=this.h[2]+u+b>>>0,this.h[2]=this.h[3]+f+p>>>0,this.h[3]=this.h[4]+c+g>>>0,this.h[4]=this.h[0]+h+y>>>0,this.h[0]=l}_digest(){return ee(this.h,"little")}_digestHex(){return V(this.h,"little")}}class eh{h;native;constructor(){this.native=Y("sha256"),null==this.native&&(this.h=new e2)}update(e,t){return j(this.native,this.h,z(e,t)),this}digest(){return G(this.native,this.h)}digestHex(){return X(this.native,this.h)}}class ed extends F{h;W;k;constructor(){super(512,160,80,64),this.k=[0x5a827999,0x6ed9eba1,0x8f1bbcdc,0xca62c1d6],this.h=[0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0],this.W=Array(80)}_update(e,t){let i,r=this.W;for(void 0===t&&(t=0),i=0;i<16;i++)r[i]=e[t+i];for(;i<r.length;i++)r[i]=ei(r[i-3]^r[i-8]^r[i-14]^r[i-16],1);let n=this.h[0],s=this.h[1],a=this.h[2],o=this.h[3],l=this.h[4];for(i=0;i<r.length;i++){var c,h,d,u,f,p,g,y,m;let e=Math.trunc(i/20),t=(u=ei(n,5),c=s,h=a,d=o,f=0===e?(p=c)&h^~p&d:1===e||3===e?c^h^d:2===e?(g=c)&(y=h)^g&(m=d)^y&m:0,u+f+l+r[i]+this.k[e]>>>0);l=o,o=a,a=ei(s,30),s=n,n=t}this.h[0]=er(this.h[0],n),this.h[1]=er(this.h[1],s),this.h[2]=er(this.h[2],a),this.h[3]=er(this.h[3],o),this.h[4]=er(this.h[4],l)}_digest(){return ee(this.h,"big")}_digestHex(){return V(this.h,"big")}}class eu{h;native;constructor(){this.native=Y("sha512"),null==this.native&&(this.h=new te)}update(e,t){return j(this.native,this.h,z(e,t)),this}digest(){return G(this.native,this.h)}digestHex(){return X(this.native,this.h)}}class ef{h;native;blockSize=64;outSize=32;constructor(e){const t=W(e);this.native=J("sha256",t),null==this.native&&(this.h=new ti(e8,t))}update(e,t){return j(this.native,this.h,z(e,t)),this}digest(){return G(this.native,this.h)}digestHex(){return X(this.native,this.h)}}class ep{inner;outer;blockSize=64;constructor(e){let t;for((e=D(e,"hex")).length>this.blockSize&&(e=new ed().update(e).digest()),t=e.length;t<this.blockSize;t++)e.push(0);for(t=0;t<e.length;t++)e[t]^=54;for(t=0,this.inner=new ed().update(e);t<e.length;t++)e[t]^=106;this.outer=new ed().update(e)}update(e,t){return this.inner.update(e,t),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}}class eg{h;native;blockSize=128;outSize=32;constructor(e){const t=W(e);this.native=J("sha512",t),null==this.native&&(this.h=new ti(tt,t))}update(e,t){return j(this.native,this.h,z(e,t)),this}digest(){return G(this.native,this.h)}digestHex(){return X(this.native,this.h)}}function ey(e,t){let i=Z("sha256",e,t);return null!=i?i:new e2().update(z(e,t)).digest()}function em(e,t){return Z("ripemd160",e,t)}let eb=(e,t)=>{let i=em(e,t);return null!=i?Array.from(i):new ec().update(e,t).digest()},ew=(e,t)=>new ed().update(e,t).digest(),ev=(e,t)=>Array.from(ey(e,t)),eI=(e,t)=>{let i;return Array.from(null!=(i=Z("sha512",e,t))?i:new te().update(z(e,t)).digest())},ek=(e,t)=>Array.from(ey(ey(e,t))),eS=(e,t)=>{let i=ey(e,t),r=em(i);return null!=r?Array.from(r):new ec().update(i).digest()},eE=(e,t,i)=>{let r=Q("sha256",e,t,i);return null!=r?Array.from(r):new ef(e).update(t,i).digest()},ex=(e,t,i)=>{let r=Q("sha512",e,t,i);return null!=r?Array.from(r):new eg(e).update(t,i).digest()};function eA(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`positive integer expected, got ${e}`)}function eT(e,...t){if(!(e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length)){let i=t.join(",");throw Error(`Uint8Array expected of length ${i}, got length=${e.length}`)}}function eO(e){if("function"!=typeof e||"function"!=typeof e.create)throw TypeError("Hash should be wrapped by utils.createHasher");eA(e.outputLen),eA(e.blockLen)}function eP(e,t=!0){if(!0===e.destroyed)throw Error("Hash instance has been destroyed");if(t&&!0===e.finished)throw Error("Hash#digest() has already been called")}function eN(...e){for(let t of e)t.fill(0)}function e_(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function eR(e){return"string"==typeof e&&(e=eC(e)),eT(e),e}function eC(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function eB(e){return"string"==typeof e&&(e=eC(e)),eT(e),e}class eU{}function eF(e){let t=t=>e().update(eR(t)).digest(),i=e();return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=()=>e(),t}let eD=BigInt(0x100000000-1),eL=BigInt(32),eV=(e,t,i)=>e>>>i,eH=(e,t,i)=>e<<32-i|t>>>i,eM=(e,t,i)=>e>>>i|t<<32-i,eK=(e,t,i)=>e<<32-i|t>>>i,eq=(e,t,i)=>e<<64-i|t>>>i-32,e$=(e,t,i)=>e>>>i-32|t<<64-i;function ez(e,t,i,r){let n=(t>>>0)+(r>>>0);return{h:e+i+(n/0x100000000|0)|0,l:0|n}}let eW=(e,t,i)=>(e>>>0)+(t>>>0)+(i>>>0),ej=(e,t,i,r)=>t+i+r+(e/0x100000000|0)|0,eG=(e,t,i,r)=>(e>>>0)+(t>>>0)+(i>>>0)+(r>>>0),eX=(e,t,i,r,n)=>t+i+r+n+(e/0x100000000|0)|0,eY=(e,t,i,r,n)=>(e>>>0)+(t>>>0)+(i>>>0)+(r>>>0)+(n>>>0),eJ=(e,t,i,r,n,s)=>t+i+r+n+s+(e/0x100000000|0)|0;class eZ extends eU{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,i,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=r,this.buffer=new Uint8Array(e),this.view=e_(this.buffer)}update(e){eP(this),eT(e=eR(e));let{view:t,buffer:i,blockLen:r}=this,n=e.length;for(let s=0;s<n;){let a=Math.min(r-this.pos,n-s);if(a===r){let t=e_(e);for(;r<=n-s;s+=r)this.process(t,s);continue}i.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){eP(this);eT(e);let t=this.outputLen;if(e.length<t)throw Error(`digestInto() expects output buffer of length at least ${t}`);this.finished=!0;let{buffer:i,view:r,blockLen:n,isLE:s}=this,{pos:a}=this;i[a++]=128,eN(this.buffer.subarray(a)),this.padOffset>n-a&&(this.process(r,0),a=0);for(let e=a;e<n;e++)i[e]=0;(function(e,t,i,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,i,r);let n=BigInt(32),s=BigInt(0xffffffff),a=Number(i>>n&s),o=Number(i&s),l=4*!!r,c=4*!r;e.setUint32(t+l,a,r),e.setUint32(t+c,o,r)})(r,n-8,BigInt(8*this.length),s),this.process(r,0);let o=e_(e),l=this.outputLen;if(l%4!=0)throw Error("_sha2: outputLen should be aligned to 32bit");let c=l/4,h=this.get();if(c>h.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,h[e],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){(e||=new this.constructor).set(...this.get());let{blockLen:t,buffer:i,length:r,finished:n,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=n,e.length=r,e.pos=a,r%t!=0&&e.buffer.set(i),e}clone(){return this._cloneInto()}}let eQ=Uint32Array.from([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),e0=Uint32Array.from([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0xfc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x6ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]),e1=new Uint32Array(64);class e2 extends eZ{A=0|eQ[0];B=0|eQ[1];C=0|eQ[2];D=0|eQ[3];E=0|eQ[4];F=0|eQ[5];G=0|eQ[6];H=0|eQ[7];constructor(e=32){super(64,e,8,!1)}get(){let{A:e,B:t,C:i,D:r,E:n,F:s,G:a,H:o}=this;return[e,t,i,r,n,s,a,o]}set(e,t,i,r,n,s,a,o){this.A=0|e,this.B=0|t,this.C=0|i,this.D=0|r,this.E=0|n,this.F=0|s,this.G=0|a,this.H=0|o}process(e,t){var i,r,n,s,a,o,l,c,h;for(let i=0;i<16;i++,t+=4)e1[i]=e.getUint32(t);for(let e=16;e<64;e++){let t=e1[e-15],i=e1[e-2],r=et(t,7)^et(t,18)^t>>>3,n=et(i,17)^et(i,19)^i>>>10;e1[e]=er(er(r,e1[e-7]),er(n,e1[e-16]))}let{A:d,B:u,C:f,D:p,E:g,F:y,G:m,H:b}=this;for(let e=0;e<64;e++){let t=(n=b,s=et(i=g,6)^et(i,11)^et(i,25),a=(r=g)&y^~r&m,n+s+a+e0[e]+e1[e]>>>0),w=er(et(o=d,2)^et(o,13)^et(o,22),(l=d)&(c=u)^l&(h=f)^c&h);b=m,m=y,y=g,g=er(p,t),p=f,f=u,u=d,d=er(t,w)}this.A=er(this.A,d),this.B=er(this.B,u),this.C=er(this.C,f),this.D=er(this.D,p),this.E=er(this.E,g),this.F=er(this.F,y),this.G=er(this.G,m),this.H=er(this.H,b)}roundClean(){eN(e1)}destroy(){eN(this.buffer),this.set(0,0,0,0,0,0,0,0)}}let e8=eF(()=>new e2),e3=Uint32Array.from([0x6a09e667,0xf3bcc908,0xbb67ae85,0x84caa73b,0x3c6ef372,0xfe94f82b,0xa54ff53a,0x5f1d36f1,0x510e527f,0xade682d1,0x9b05688c,0x2b3e6c1f,0x1f83d9ab,0xfb41bd6b,0x5be0cd19,0x137e2179]),e5=function(e,t=!1){let i=e.length,r=new Uint32Array(i),n=new Uint32Array(i);for(let s=0;s<i;s++){let{h:i,l:a}=function(e,t=!1){return t?{h:Number(e&eD),l:Number(e>>eL&eD)}:{h:0|Number(e>>eL&eD),l:0|Number(e&eD)}}(e[s],t);r[s]=i,n[s]=a}return[r,n]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(BigInt)),e6=e5[0],e4=e5[1],e9=new Uint32Array(80),e7=new Uint32Array(80);class te extends eZ{Ah=0|e3[0];Al=0|e3[1];Bh=0|e3[2];Bl=0|e3[3];Ch=0|e3[4];Cl=0|e3[5];Dh=0|e3[6];Dl=0|e3[7];Eh=0|e3[8];El=0|e3[9];Fh=0|e3[10];Fl=0|e3[11];Gh=0|e3[12];Gl=0|e3[13];Hh=0|e3[14];Hl=0|e3[15];constructor(e=64){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:i,Bl:r,Ch:n,Cl:s,Dh:a,Dl:o,Eh:l,El:c,Fh:h,Fl:d,Gh:u,Gl:f,Hh:p,Hl:g}=this;return[e,t,i,r,n,s,a,o,l,c,h,d,u,f,p,g]}set(e,t,i,r,n,s,a,o,l,c,h,d,u,f,p,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|i,this.Bl=0|r,this.Ch=0|n,this.Cl=0|s,this.Dh=0|a,this.Dl=0|o,this.Eh=0|l,this.El=0|c,this.Fh=0|h,this.Fl=0|d,this.Gh=0|u,this.Gl=0|f,this.Hh=0|p,this.Hl=0|g}process(e,t){for(let i=0;i<16;i++,t+=8)e9[i]=e.getUint32(t),e7[i]=e.getUint32(t+4);for(let e=16;e<80;e++){let t=0|e9[e-15],i=0|e7[e-15],r=eM(t,i,1)^eM(t,i,8)^eV(t,i,7),n=eK(t,i,1)^eK(t,i,8)^eH(t,i,7),s=0|e9[e-2],a=0|e7[e-2],o=eM(s,a,19)^eq(s,a,61)^eV(s,a,6),l=eG(n,eK(s,a,19)^e$(s,a,61)^eH(s,a,6),e7[e-7],e7[e-16]),c=eX(l,r,o,e9[e-7],e9[e-16]);e9[e]=0|c,e7[e]=0|l}let{Ah:i,Al:r,Bh:n,Bl:s,Ch:a,Cl:o,Dh:l,Dl:c,Eh:h,El:d,Fh:u,Fl:f,Gh:p,Gl:g,Hh:y,Hl:m}=this;for(let e=0;e<80;e++){let t=eM(h,d,14)^eM(h,d,18)^eq(h,d,41),b=eK(h,d,14)^eK(h,d,18)^e$(h,d,41),w=h&u^~h&p,v=eY(m,b,d&f^~d&g,e4[e],e7[e]),I=eJ(v,y,t,w,e6[e],e9[e]),k=0|v,S=eM(i,r,28)^eq(i,r,34)^eq(i,r,39),E=eK(i,r,28)^e$(i,r,34)^e$(i,r,39),x=i&n^i&a^n&a,A=r&s^r&o^s&o;y=0|p,m=0|g,p=0|u,g=0|f,u=0|h,f=0|d,({h:h,l:d}=ez(0|l,0|c,0|I,0|k)),l=0|a,c=0|o,a=0|n,o=0|s,n=0|i,s=0|r;let T=eW(E,A,k);i=ej(T,S,x,I),r=0|T}({h:i,l:r}=ez(i,r,this.Ah,this.Al)),({h:n,l:s}=ez(n,s,this.Bh,this.Bl)),({h:a,l:o}=ez(a,o,this.Ch,this.Cl)),({h:l,l:c}=ez(l,c,this.Dh,this.Dl)),({h:h,l:d}=ez(h,d,this.Eh,this.El)),({h:u,l:f}=ez(u,f,this.Fh,this.Fl)),({h:p,l:g}=ez(p,g,this.Gh,this.Gl)),({h:y,l:m}=ez(y,m,this.Hh,this.Hl)),this.set(i,r,n,s,a,o,l,c,h,d,u,f,p,g,y,m)}roundClean(){eN(e9,e7)}destroy(){eN(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}let tt=eF(()=>new te);class ti extends eU{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){super(),eO(e);const i=eR(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw TypeError("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,n=new Uint8Array(r);n.set(i.length>r?e.create().update(i).digest():i);for(let e=0;e<n.length;e++)n[e]^=54;this.iHash.update(n),this.oHash=e.create();for(let e=0;e<n.length;e++)n[e]^=106;this.oHash.update(n),eN(n)}update(e){return eP(this),this.iHash.update(e),this}digestInto(e){eP(this),eT(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:i,finished:r,destroyed:n,blockLen:s,outputLen:a}=this;return e.finished=r,e.destroyed=n,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash??void 0),e.iHash=i._cloneInto(e.iHash??void 0),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}let tr=(e,t,i)=>new ti(e,t).update(i).digest();function tn(e,t,i,r,n="sha512"){if("sha512"!==n)throw Error("Only sha512 is supported in this PBKDF2 implementation");let s=$?.pbkdf2Sync;return"function"==typeof s?Array.from(s(z(e),z(t),i,r,n)):Array.from(function(e,t,i,r){let n;eO(e);let{c:s,dkLen:a}=Object.assign({dkLen:32},r);if(eA(s),eA(a),s<1)throw Error("iterations (c) should be >= 1");let o=eB(t),l=eB(i),c=new Uint8Array(a),h=tr.create(e,o),d=h._cloneInto().update(l),u=new Uint8Array(4),f=e_(u),p=new Uint8Array(h.outputLen);for(let e=1,t=0;t<a;e++,t+=h.outputLen){let i=c.subarray(t,t+h.outputLen);f.setInt32(0,e,!1),(n=d._cloneInto(n)).update(u).digestInto(p),i.set(p.subarray(0,i.length));for(let e=1;e<s;e++){h._cloneInto(n).update(p).digestInto(p);for(let e=0;e<i.length;e++)i[e]^=p[e]}}return h.destroy(),d.destroy(),null!=n&&n.destroy(),eN(p),c}(tt,Uint8Array.from(e),Uint8Array.from(t),{c:i,dkLen:r}))}function ts(e){return(e>>>24|e>>>8&65280|e<<8&0xff0000|(255&e)<<24)>>>0}tr.create=(e,t)=>new ti(e,t);let ta=(i=new Uint32Array(t=new ArrayBuffer(4)),r=new Uint8Array(t),i[0]=0x1020304,4===r[0]);function to(e){return ta?ts(e):e>>>0}class tl{buffer;pos;capacity;constructor(e,t=256){if(null!=e&&e.length>0&&(t=Math.max(t,e.reduce((e,t)=>e+t.length,0))),this.buffer=new Uint8Array(t),this.pos=0,this.capacity=t,null!=e)for(const t of e)this.write(t)}getLength(){return this.pos}toUint8Array(){return this.buffer.slice(0,this.pos)}toArray(){return Array.from(this.toUint8Array())}toUint8ArrayZeroCopy(){return this.buffer.subarray(0,this.pos)}ensureCapacity(e){if(this.pos+e>this.capacity){let t=2*this.capacity;for(;this.pos+e>t;)t*=2;let i=new Uint8Array(t);i.set(this.buffer),this.buffer=i,this.capacity=t}}write(e){let t=e instanceof Uint8Array?e:new Uint8Array(e);return this.ensureCapacity(t.length),this.buffer.set(t,this.pos),this.pos+=t.length,this}writeReverse(e){let t=e instanceof Uint8Array?e:new Uint8Array(e);this.ensureCapacity(t.length);for(let e=t.length-1;e>=0;e--)this.buffer[this.pos]=t[e],this.pos+=1;return this}writeUInt8(e){return this.ensureCapacity(1),this.buffer[this.pos]=255&e,this.pos+=1,this}writeInt8(e){return this.writeUInt8(e),this}writeUInt16LE(e){return this.ensureCapacity(2),this.buffer[this.pos]=255&e,this.buffer[this.pos+1]=e>>8&255,this.pos+=2,this}writeUInt16BE(e){return this.ensureCapacity(2),this.buffer[this.pos]=e>>8&255,this.buffer[this.pos+1]=255&e,this.pos+=2,this}writeInt16LE(e){return this.writeUInt16LE(65535&e),this}writeInt16BE(e){return this.writeUInt16BE(65535&e),this}writeUInt32LE(e){return this.ensureCapacity(4),this.buffer[this.pos]=255&e,this.buffer[this.pos+1]=e>>8&255,this.buffer[this.pos+2]=e>>16&255,this.buffer[this.pos+3]=e>>24&255,this.pos+=4,this}writeUInt32BE(e){return this.ensureCapacity(4),this.buffer[this.pos]=e>>24&255,this.buffer[this.pos+1]=e>>16&255,this.buffer[this.pos+2]=e>>8&255,this.buffer[this.pos+3]=255&e,this.pos+=4,this}writeInt32LE(e){return this.writeUInt32LE(e>>>0),this}writeInt32BE(e){return this.writeUInt32BE(e>>>0),this}writeUInt64BEBn(e){let t=e.toArray("be",8);return this.write(t),this}writeUInt64LEBn(e){let t=e.toArray("be",8);return this.writeReverse(t),this}writeUInt64LE(e){let t=new A(e).toArray("be",8);return this.writeReverse(t),this}writeVarIntNum(e){let t=tP.varIntNum(e);return this.write(t),this}writeVarIntBn(e){let t=tP.varIntBn(e);return this.write(t),this}reset(){this.pos=0}}class tc{bin;pos;length;static makeReader(e,t=0){if(e instanceof Uint8Array)return new tc(e,t);if(Array.isArray(e))return new tN(e,t);throw Error("ReaderUint8Array.makeReader: bin must be Uint8Array or number[]")}constructor(e=new Uint8Array(0),t=0){if(e instanceof Uint8Array)this.bin=e;else if(Array.isArray(e))this.bin=new Uint8Array(e);else throw TypeError("ReaderUint8Array constructor: bin must be Uint8Array or number[]");this.pos=t,this.length=this.bin.length}eof(){return this.pos>=this.length}read(e=this.length){let t=this.pos,i=this.pos+e;return this.pos=i,this.bin.slice(t,i)}readReverse(e=this.length){let t=new Uint8Array(e);for(let i=0;i<e;i++)t[i]=this.bin[this.pos+e-1-i];return this.pos+=e,t}readUInt8(){let e=this.bin[this.pos];return this.pos+=1,e}readInt8(){let e=this.bin[this.pos];return this.pos+=1,(128&e)==0?e:e-256}readUInt16BE(){let e=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,e}readInt16BE(){let e=this.readUInt16BE();return(32768&e)==0?e:e-65536}readUInt16LE(){let e=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,e}readInt16LE(){let e=this.readUInt16LE();return(32768&e)==0?e:e-65536}readUInt32BE(){let e=0x1000000*this.bin[this.pos]+(this.bin[this.pos+1]<<16|this.bin[this.pos+2]<<8|this.bin[this.pos+3]);return this.pos+=4,e}readInt32BE(){let e=this.readUInt32BE();return(0x80000000&e)==0?e:e-0x100000000}readUInt32LE(){let e=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,e}readInt32LE(){let e=this.readUInt32LE();return(0x80000000&e)==0?e:e-0x100000000}readUInt64BEBn(){let e=new A(Array.from(this.bin.slice(this.pos,this.pos+8)));return this.pos=this.pos+8,e}readUInt64LEBn(){return new A(Array.from(this.readReverse(8)))}readInt64LEBn(){let e=new A(2).pow(new A(63)),t=new A(2).pow(new A(64)),i=new A(Array.from(this.readReverse(8)));return i.gte(e)&&(i=i.sub(t)),i}readVarIntNum(e=!0){let t,i=this.readUInt8();switch(i){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if((t=e?this.readInt64LEBn():this.readUInt64LEBn()).lte(new A(2).pow(new A(53))))return t.toNumber();throw Error("number too large to retain precision - use readVarIntBn");default:return i}}readVarInt(){switch(this.bin[this.pos]){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}}readVarIntBn(){let e=this.readUInt8();switch(e){case 253:return new A(this.readUInt16LE());case 254:return new A(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new A(e)}}}let th="u"<typeof globalThis?void 0:globalThis.Buffer,td=null!=th&&"function"==typeof th.from,tu=e=>e.length%2==1?"0"+e:e,tf="0123456789abcdef",tp=Array(256);for(let e=0;e<256;e++)tp[e]=tf[e>>4&15]+tf[15&e];let tg=e=>{if(td)return th.from(e).toString("hex");if(0===e.length)return"";let t=Array(e.length);for(let i=0;i<e.length;i++)t[i]=tp[255&e[i]];return t.join("")},ty=(e,t)=>e instanceof Uint8Array?e:new Uint8Array(tm(e,t)),tm=(e,t)=>{if(Array.isArray(e))return e.slice();if(void 0===e)return[];if("string"!=typeof e)return Array.from(e,e=>Math.trunc(e));switch(t){case"hex":return tw(e);case"base64":return tv(e);default:var i;return i=e,Array.from(new TextEncoder().encode(i))}},tb=new Int8Array(256).fill(-1);for(let e=0;e<10;e++)tb[48+e]=e;for(let e=0;e<6;e++)tb[65+e]=10+e,tb[97+e]=10+e;let tw=e=>{B(e);let t=e.length%2==0?e:"0"+e;if(td)return Array.from(th.from(t,"hex"));let i=Array(t.length/2),r=0;for(let e=0;e<t.length;e+=2){let n=tb[t.codePointAt(e)],s=tb[t.codePointAt(e+1)];i[r++]=n<<4|s}return i};function tv(e){if("string"!=typeof e)throw TypeError("msg must be a string");let t=e.trim().replaceAll(/[\r\n\t\f\v ]+/g,""),i=(t=t.replaceAll("-","+").replaceAll("_","/")).indexOf("=");if(-1!==i){let e=t.slice(i);if(!/^={1,2}$/.test(e)||t.slice(0,i).includes("="))throw Error("Invalid base64 padding");t=t.slice(0,i)}let r=[],n=0,s=0;for(let e=0;e<t.length;e++){let i=t.codePointAt(e),a=-1;if(i>=65&&i<=90)a=i-65;else if(i>=97&&i<=122)a=i-97+26;else if(i>=48&&i<=57)a=i-48+52;else if(43===i)a=62;else if(47===i)a=63;else throw Error(`Invalid base64 character at index ${e}`);for(n=n<<6|a,s+=6;s>=8;)s-=8,r.push(n>>s&255),n&=(1<<s)-1}return r}let tI=e=>new TextDecoder().decode(new Uint8Array(e)),tk=(e,t)=>{switch(t){case"hex":return tg(e);case"utf8":return tI(e);default:return e}};function tS(e){let t,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r="";for(t=0;t<e.length;t+=3){let n=e[t],s=t+1<e.length?e[t+1]:0,a=t+2<e.length?e[t+2]:0,o=n>>2,l=(3&n)<<4|s>>4,c=(15&s)<<2|a>>6,h=63&a;r+=i.charAt(o)+i.charAt(l),r+=t+1<e.length?i.charAt(c):"=",r+=t+2<e.length?i.charAt(h):"="}return r}let tE="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",tx=e=>{let t;if(""===e||"string"!=typeof e)throw Error(`Expected base58 string but got “${e}”`);let i=e.match(/[IOl0]/gmu);if(null!==i)throw Error(`Invalid base58 character “${i.join("")}”`);let r=e.match(/^1+/gmu),n=null===r?0:r[0].length,s=(e.length-n)*(Math.log(58)/Math.log(256))+1>>>0;return[...new Uint8Array([...new Uint8Array(n),...(e.match(/./gmu)??[]).map(e=>tE.indexOf(e)).reduce((e,t)=>e=e.map(e=>{let i=58*e+t;return t=i>>8,i}),new Uint8Array(s)).reverse().filter((t=!1,e=>t=t||e))])]},tA=e=>{let t=Array(256).fill(-1);for(let e=0;e<tE.length;++e)t[tE.codePointAt(e)]=e;let i=[];for(let r of e){let e=r;for(let r=0;r<i.length;++r){let n=(t[i[r]]<<8)+e;i[r]=tE.codePointAt(n%58),e=Math.trunc(n/58)}for(;0!==e;)i.push(tE.codePointAt(e%58)),e=Math.trunc(e/58)}for(let t of e)if(0===t)i.push(49);else break;return i.reverse(),String.fromCodePoint(...i)},tT=(e,t=[0])=>{let i=ek([...t,...e]);return tA(i=[...t,...e,...i.slice(0,4)])},tO=(e,t,i=1)=>{let r=tx(e),n=r.slice(0,i),s=r.slice(i,-4),a=[...n,...s];return a=ek(a),r.slice(-4).forEach((e,t)=>{if(e!==a[t])throw Error("Invalid checksum")}),"hex"===t&&(n=tg(n),s=tg(s)),{prefix:n,data:s}};class tP{bufs;length;constructor(e){for(const t of(this.bufs=e??[],this.length=0,this.bufs))this.length+=t.length}getLength(){return this.length}toUint8Array(){let e=new Uint8Array(this.length),t=0;for(let i of this.bufs)e.set(i,t),t+=i.length;return e}toArray(){let e=Array(this.length),t=0;for(let i of this.bufs)if(i instanceof Uint8Array)for(let r of i)e[t++]=r;else for(let r of i)e[t++]=r;return e}toHex(){return this.toArray().map(e=>e.toString(16).padStart(2,"0")).join("")}write(e){return this.bufs.push(e),this.length+=e.length,this}writeReverse(e){let t=Array(e.length);for(let i=0;i<t.length;i++)t[i]=e[e.length-1-i];return this.write(t)}writeUInt8(e){let t=[,];return t[0]=255&e,this.write(t),this}writeInt8(e){return this.writeUInt8(e)}writeUInt16BE(e){return this.write([e>>8&255,255&e])}writeInt16BE(e){return this.writeUInt16BE(65535&e)}writeUInt16LE(e){return this.write([255&e,e>>8&255])}writeInt16LE(e){return this.writeUInt16LE(65535&e)}writeUInt32BE(e){return this.write([e>>24&255,e>>16&255,e>>8&255,255&e])}writeInt32BE(e){return this.writeUInt32BE(e>>>0)}writeUInt32LE(e){return this.write([255&e,e>>8&255,e>>16&255,e>>24&255])}writeInt32LE(e){return this.writeUInt32LE(e>>>0)}writeUInt64BEBn(e){let t=e.toArray("be",8);return this.write(t),this}writeUInt64LEBn(e){let t=e.toArray("be",8);return this.writeReverse(t),this}writeUInt64LE(e){if(-1===e)this.write(Array(8).fill(255));else{let t=new A(e).toArray("be",8);this.writeReverse(t)}return this}writeVarIntNum(e){let t=tP.varIntNum(e);return this.write(t),this}writeVarIntBn(e){let t=tP.varIntBn(e);return this.write(t),this}static varIntNum(e){let t;if(e<0)return this.varIntBn(new A(e));if(e<253)t=[e];else if(e<65536)t=[253,255&e,e>>8&255];else if(e<0x100000000)t=[254,255&e,e>>8&255,e>>16&255,e>>24&255];else{let i=0|e,r=0|Math.floor(e/0x100000000);t=[255,255&i,i>>8&255,i>>16&255,i>>24&255,255&r,r>>8&255,r>>16&255,r>>24&255]}return t}static varIntBn(e){let t;if(e.isNeg()&&(e=e.add(tC)),e.ltn(253))t=[e.toNumber()];else if(e.ltn(65536)){let i=e.toNumber();t=[253,255&i,i>>8&255]}else if(e.lt(new A(0x100000000))){let i=e.toNumber();t=[254,255&i,i>>8&255,i>>16&255,i>>24&255]}else{let i=new tP;i.writeUInt8(255),i.writeUInt64LEBn(e),t=i.toArray()}return t}}class tN{bin;pos;length;constructor(e=[],t=0){this.bin=e,this.pos=t,this.length=e.length}eof(){return this.pos>=this.length}read(e=this.length){let t=this.pos,i=this.pos+e;return this.pos=i,this.bin.slice(t,i)}readReverse(e=this.length){let t=Array(e);for(let i=0;i<e;i++)t[i]=this.bin[this.pos+e-1-i];return this.pos+=e,t}readUInt8(){let e=this.bin[this.pos];return this.pos+=1,e}readInt8(){let e=this.bin[this.pos];return this.pos+=1,(128&e)==0?e:e-256}readUInt16BE(){let e=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,e}readInt16BE(){let e=this.readUInt16BE();return(32768&e)==0?e:e-65536}readUInt16LE(){let e=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,e}readInt16LE(){let e=this.readUInt16LE();return(32768&e)==0?e:e-65536}readUInt32BE(){let e=0x1000000*this.bin[this.pos]+(this.bin[this.pos+1]<<16|this.bin[this.pos+2]<<8|this.bin[this.pos+3]);return this.pos+=4,e}readInt32BE(){let e=this.readUInt32BE();return(0x80000000&e)==0?e:e-0x100000000}readUInt32LE(){let e=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,e}readInt32LE(){let e=this.readUInt32LE();return(0x80000000&e)==0?e:e-0x100000000}readUInt64BEBn(){let e=new A(this.bin.slice(this.pos,this.pos+8));return this.pos=this.pos+8,e}readUInt64LEBn(){return new A(this.readReverse(8))}readInt64LEBn(){let e=new A(this.readReverse(8));return e.gte(tR)&&(e=e.sub(tC)),e}readVarIntNum(e=!0){let t,i=this.readUInt8();switch(i){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if((t=e?this.readInt64LEBn():this.readUInt64LEBn()).lte(new A(2).pow(new A(53))))return t.toNumber();throw Error("number too large to retain precision - use readVarIntBn");default:return i}}readVarInt(){switch(this.bin[this.pos]){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}}readVarIntBn(){let e=this.readUInt8();switch(e){case 253:return new A(this.readUInt16LE());case 254:return new A(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new A(e)}}}let t_=e=>{if(0===e.length)return e;let t=e.at(-1);if((127&t)!=0)return e;if(1===e.length)return[];if((128&e.at(-2))!=0)return e;for(let i=e.length-1;i>0;i--)if(0!==e[i-1])if((128&e[i-1])==0)return e[i-1]|=t,e.slice(0,i);else return e[i]=t,e.slice(0,i+1);return[]},tR=new A(2).pow(new A(63)),tC=new A(2).pow(new A(64));function tB(e,t="Expected a valid value, but got undefined or null."){if(null==e)throw Error(t);return e}function tU(e,t){if(e.length!==t.length)return!1;let i=0;for(let r=0;r<e.length;r++)i|=e[r]^t[r];return 0===i}function tF(e,t,i){let r=-e,n=(t.X^i.X)&r,s=(t.Y^i.Y)&r,a=(t.Z^i.Z)&r;t.X^=n,i.X^=n,t.Y^=s,i.Y^=s,t.Z^=a,i.Z^=a}let tD=(1n<<256n)-1n;function tL(e){let t=e>>256n;return t=(e=(e&tD)+(t<<32n)+977n*t)>>256n,(e=(e&tD)+(t<<32n)+977n*t)>=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn&&(e-=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn),e}let tV=e=>tL((e%0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn+0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn)%0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn),tH=(e,t)=>e>=t?e-t:0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn-(t-e),tM=(e,t)=>tL(e*t),tK=e=>{let t=1n,i=0n,r=tV(e),n=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn;for(;r>1n;){let e=n/r;[t,i]=[i-t*e,t],[r,n]=[n-r*e,r]}return tV(t)},tq=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn+1n>>2n,t$=BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),tz=BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),tW=new Map,tj=e=>{let{X:t,Y:i,Z:r}=e;if(0n===i)return{X:0n,Y:1n,Z:0n};let n=tM(i,i),s=tM(4n,tM(t,n)),a=tM(3n,tM(t,t)),o=tH(tM(a,a),tM(2n,s)),l=tH(tM(a,tH(s,o)),tM(8n,tM(n,n)));return{X:o,Y:l,Z:tM(2n,tM(i,r))}},tG=(e,t)=>{if(0n===e.Z)return t;if(0n===t.Z)return e;let i=tM(e.Z,e.Z),r=tM(t.Z,t.Z),n=tM(e.X,r),s=tM(t.X,i),a=tM(e.Y,tM(r,t.Z)),o=tM(t.Y,tM(i,e.Z)),l=tH(s,n),c=tH(o,a);if(0n===l)return 0n===c?tj(e):{X:0n,Y:1n,Z:0n};let h=tM(l,l),d=tM(l,h),u=tM(n,h),f=tH(tH(tM(c,c),d),tM(2n,u)),p=tH(tM(c,tH(u,f)),tM(a,d));return{X:f,Y:p,Z:tM(l,tM(e.Z,t.Z))}},tX=e=>0n===e.Z?e:{X:e.X,Y:0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn-e.Y,Z:e.Z},tY=(e,t,i=5)=>{let r=`${i}:${t.x.toString(16)}:${t.y.toString(16)}`,n=tW.get(r);if(void 0===n){let e=1<<i-1;n=Array(e);let s={X:t.x,Y:t.y,Z:1n};n[0]=s;let a=tj(s);for(let t=1;t<e;t++)n[t]=tG(n[t-1],a);tW.set(r,n)}let s=[],a=1n<<BigInt(i),o=a>>1n,l=e;for(;l>0n;)if((1n&l)===0n)s.push(0),l>>=1n;else{let e=l&a-1n;e>o&&(e-=a),s.push(Number(e)),l-=e,l>>=1n}let c={X:0n,Y:1n,Z:0n};for(let e=s.length-1;e>=0;e--){c=tj(c);let t=s[e];if(0!==t){let e=Math.abs(t)>>1;c=tG(c,t>0?n[e]:tX(n[e]))}}return c},tJ=e=>{let t=e%0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;return t<0n&&(t+=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n),t},tZ=(e,t)=>tJ(e*t),tQ=e=>{let t=1n,i=0n,r=tJ(e),n=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;for(;r>1n;){let e=n/r;[t,i]=[i-t*e,t],[r,n]=[n-r*e,r]}return tJ(t)};class t0 extends _{x;y;inf;static _assertOnCurve(e){if(!e.validate())throw Error("Invalid point");return e}static fromDER(e){if((4===e[0]||6===e[0]||7===e[0])&&e.length-1==64){if(6===e[0]){if(e.at(-1)%2!=0)throw Error("Point string value is wrong length")}else if(7===e[0]&&e.at(-1)%2!=1)throw Error("Point string value is wrong length");let t=new t0(e.slice(1,33),e.slice(33,65));return t0._assertOnCurve(t)}if((2===e[0]||3===e[0])&&e.length-1==32)return t0._assertOnCurve(t0.fromX(e.slice(1,33),3===e[0]));throw Error("Unknown point format")}static fromString(e){let t=tm(e,"hex");return t0._assertOnCurve(t0.fromDER(t))}static fromX(e,t){var i;let r,n,s=A.isBN(e)?BigInt("0x"+e.toString(16)):"string"==typeof e?BigInt("0x"+e):Array.isArray(e)?BigInt("0x"+tg(e)):BigInt(e),a=(n=((e,t)=>{let i=1n;for(e=tV(e);t>0n;)(1n&t)!==0n&&(i=tM(i,e)),e=tM(e,e),t>>=1n;return i})(i=tL(tM(tM(r=s=tV(s),r),s)+7n),tq),tM(n,n)!==tV(i)?null:n);if(null===a)throw Error("Invalid point");let o=a;(1n&o)!==(t?1n:0n)&&(o=tH(0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,o));let l=new A(s.toString(16),16),c=new A(o.toString(16),16);return t0._assertOnCurve(new t0(l,c))}static fromJSON(e,t){"string"==typeof e&&(e=JSON.parse(e));let i=new t0(e[0],e[1],t);if(i=t0._assertOnCurve(i),"object"!=typeof e[2]||null===e[2])return i;let r=e[2],n=e=>{let i=new t0(e[0],e[1],t);return t0._assertOnCurve(i)};return i.precomputed={beta:null,doubles:"object"==typeof r.doubles&&null!==r.doubles?{step:r.doubles.step,points:[i].concat(r.doubles.points.map(n))}:void 0,naf:"object"==typeof r.naf&&null!==r.naf?{wnd:r.naf.wnd,points:[i].concat(r.naf.points.map(n))}:void 0},i}constructor(e,t,i=!0){super("affine"),this.precomputed=null,null===e&&null===t?(this.x=null,this.y=null,this.inf=!0):(A.isBN(e)||(e=new A(e,16)),this.x=e,A.isBN(t)||(t=new A(t,16)),this.y=t,i&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),null===this.x.red&&(this.x=this.x.toRed(this.curve.red)),null===this.y.red&&(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}validate(){if(this.inf||null==this.x||null==this.y)return!1;try{let e,t=BigInt("0x"+this.x.fromRed().toString(16)),i=BigInt("0x"+this.y.fromRed().toString(16)),r=tM(i,i),n=(e=tM(tM(t,t),t),tL(e+7n));return r===n}catch{return!1}}encode(e=!0,t){let i;if(this.inf)return"hex"===t?"00":[0];let r=this.curve.p.byteLength(),n=this.getX().toArray("be",r);return(i=e?[this.getY().isEven()?2:3].concat(n):[4].concat(n,this.getY().toArray("be",r)),"hex"===t)?tg(i):i}toString(){return this.encode(!0,"hex")}toJSON(){return null==this.precomputed?[this.x,this.y]:[this.x,this.y,"object"==typeof this.precomputed&&null!==this.precomputed?{doubles:null==this.precomputed.doubles?void 0:{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)},naf:null==this.precomputed.naf?void 0:{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}}:void 0]}inspect(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+(this.x?.fromRed()?.toString(16,2)??"undefined")+" y: "+(this.y?.fromRed()?.toString(16,2)??"undefined")+">"}isInfinity(){return this.inf}add(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e)||this.x?.cmp(e.x??new A(0))===0)return new t0(null,null);let t=tG({X:BigInt("0x"+this.x.fromRed().toString(16)),Y:BigInt("0x"+this.y.fromRed().toString(16)),Z:1n},{X:BigInt("0x"+e.x.fromRed().toString(16)),Y:BigInt("0x"+e.y.fromRed().toString(16)),Z:1n});if(0n===t.Z)return new t0(null,null);let i=tK(t.Z),r=tM(i,i),n=tM(t.X,r),s=tM(t.Y,tM(r,i));return new t0(n.toString(16),s.toString(16))}dbl(){if(this.inf)return this;if(null===this.x||null===this.y)throw Error("Point coordinates cannot be null");let e=BigInt("0x"+this.x.fromRed().toString(16)),t=BigInt("0x"+this.y.fromRed().toString(16));if(0n===t)return new t0(null,null);let i=tj({X:e,Y:t,Z:1n}),r=tK(i.Z),n=tM(r,r),s=tM(i.X,n),a=tM(i.Y,tM(n,r));return new t0(s.toString(16),a.toString(16))}getX(){return(this.x??new A(0)).fromRed()}getY(){return(this.y??new A(0)).fromRed()}mul(e){let t,i;if(A.isBN(e)||(e=new A(e,16)),this.inf)return this;let r=e.isNeg(),n=BigInt("0x"+(r?e.neg():e).toString(16));if(0n===(n=tV(n))||0n===n)return new t0(null,null);if(null===this.x||null===this.y)throw Error("Point coordinates cannot be null");this===this.curve.g?(t=t$,i=tz):(t=BigInt("0x"+this.x.fromRed().toString(16)),i=BigInt("0x"+this.y.fromRed().toString(16)));let s=tY(n,{x:t,y:i});if(0n===s.Z)return new t0(null,null);let a=tK(s.Z),o=tM(a,a),l=tM(s.X,o),c=tM(s.Y,tM(o,a)),h=new t0(new A(l.toString(16),16),new A(c.toString(16),16));return r?h.neg():h}mulCT(e){if(A.isBN(e)||(e=new A(e,16)),this.inf)return new t0(null,null);let t=e.isNeg(),i=BigInt("0x"+(t?e.neg():e).toString(16));if(0n===(i=tV(i)))return new t0(null,null);let r=this===this.curve.g?t$:BigInt("0x"+this.getX().toString(16)),n=this===this.curve.g?tz:BigInt("0x"+this.getY().toString(16)),s={X:0n,Y:1n,Z:0n},a={X:r,Y:n,Z:1n};for(let e of i.toString(2)){let t="1"===e?1n:0n;tF(t,s,a),a=tG(s,a),tF(t,s=tj(s),a)}if(0n===s.Z)return new t0(null,null);let o=tK(s.Z),l=tM(o,o),c=tM(s.X,l),h=tM(s.Y,tM(l,o)),d=new t0(c.toString(16),h.toString(16));return t?d.neg():d}mulAdd(e,t,i){return this._endoWnafMulAdd([this,t],[e,i])}jmulAdd(e,t,i){return this._endoWnafMulAdd([this,t],[e,i],!0)}eq(e){return this===e||this.inf===e.inf&&(this.inf||0===(this.x??new A(0)).cmp(e.x??new A(0))&&0===(this.y??new A(0)).cmp(e.y??new A(0)))}neg(e){if(this.inf)return this;let t=new t0(this.x,(this.y??new A(0)).redNeg());if(!0===e&&null!=this.precomputed){let e=this.precomputed;t.precomputed={naf:null==e.naf?void 0:{wnd:e.naf.wnd,points:e.naf.points.map(e=>e.neg())},doubles:null==e.doubles?void 0:{step:e.doubles.step,points:e.doubles.points.map(e=>e.neg())},beta:void 0}}return t}dblp(e){let t=this;for(let i=0;i<e;i++)t=t.dbl();return t}toJ(){return this.inf?new R(null,null,null):new R(this.x,this.y,this.curve.one)}_getBeta(){if("object"!=typeof this.curve.endo)return;let e=this.precomputed;if("object"==typeof e&&null!==e&&"object"==typeof e.beta&&null!==e.beta)return e.beta;let t=new t0((this.x??new A(0)).redMul(this.curve.endo.beta),this.y);if(null!=e){let i=this.curve,r=e=>{if(null===e.x)throw Error("p.x is null");if(void 0===i.endo||null===i.endo)throw Error("curve.endo is undefined");return new t0(e.x.redMul(i.endo.beta),e.y)};e.beta=t,t.precomputed={beta:null,naf:null==e.naf?void 0:{wnd:e.naf.wnd,points:e.naf.points.map(r)},doubles:null==e.doubles?void 0:{step:e.doubles.step,points:e.doubles.points.map(r)}}}return t}_fixedNafMul(e){if("object"!=typeof this.precomputed||null===this.precomputed)throw Error("_fixedNafMul requires precomputed values for the point");let t=this._getDoubles(),i=this.curve.getNAF(e,1,this.curve._bitLength),r=(1<<t.step+1)-(t.step%2==0?2:1);r/=3;let n=[];for(let e=0;e<i.length;e+=t.step){let r=0;for(let n=e+t.step-1;n>=e;n--)r=(r<<1)+i[n];n.push(r)}let s=new R(null,null,null),a=new R(null,null,null);for(let e=r;e>0;e--){for(let i=0;i<n.length;i++){let r=n[i];r===e?a=a.mixedAdd(t.points[i]):r===-e&&(a=a.mixedAdd(t.points[i].neg()))}s=s.add(a)}return s.toP()}_wnafMulAdd(e,t,i,r,n){let s=this.curve._wnafT1.map(e=>e.toNumber()),a=this.curve._wnafT2.map(()=>[]),o=this.curve._wnafT3.map(()=>[]),l=0;for(let i=0;i<r;i++){let r=t[i]._getNAFPoints(e);s[i]=r.wnd,a[i]=r.points}for(let e=r-1;e>=1;e-=2){let r=e-1,n=e;if(1!==s[r]||1!==s[n]){o[r]=this.curve.getNAF(i[r],s[r],this.curve._bitLength),o[n]=this.curve.getNAF(i[n],s[n],this.curve._bitLength),l=Math.max(o[r].length,l),l=Math.max(o[n].length,l);continue}let c=[t[r],null,null,t[n]];0===(t[r].y??new A(0)).cmp(t[n].y??new A(0))?(c[1]=t[r].add(t[n]),c[2]=t[r].toJ().mixedAdd(t[n].neg())):0===(t[r].y??new A(0)).cmp((t[n].y??new A(0)).redNeg())?(c[1]=t[r].toJ().mixedAdd(t[n]),c[2]=t[r].add(t[n].neg())):(c[1]=t[r].toJ().mixedAdd(t[n]),c[2]=t[r].toJ().mixedAdd(t[n].neg()));let h=[-3,-1,-5,-7,0,7,5,1,3],d=this.curve.getJSF(i[r],i[n]);l=Math.max(d[0].length,l),o[r]=Array(l),o[n]=Array(l);for(let e=0;e<l;e++){let t=Math.trunc(d[0][e]),i=Math.trunc(d[1][e]);o[r][e]=h[(t+1)*3+(i+1)],o[n][e]=0,a[r]=c}}let c=new R(null,null,null),h=this.curve._wnafT4;for(let e=l;e>=0;e--){let t=0;for(;e>=0;){let i=!0;for(let t=0;t<r;t++)h[t]=new A("number"==typeof o[t][e]?o[t][e]:0),h[t].isZero()||(i=!1);if(!i)break;t++,e--}if(e>=0&&t++,c=c.dblp(t),e<0)break;let i=new A(1),n=new A(2);for(let e=0;e<r;e++){let t,r=h[e];0!==r.cmpn(0)&&(c="affine"===(t=r.isNeg()?a[e][r.neg().sub(i).div(n).toNumber()].neg():a[e][r.sub(i).div(n).toNumber()]).type?c.mixedAdd(t):c.add(t))}}for(let e=0;e<r;e++)a[e]=[];return!0===n?c:c.toP()}_endoWnafMulAdd(e,t,i){let r,n=Array(2*e.length),s=Array(2*e.length);for(r=0;r<e.length;r++){let i=this.curve._endoSplit(t[r]),a=e[r],o=a._getBeta()??new t0(null,null);0!==i.k1.negative&&(i.k1.ineg(),a=a.neg(!0)),0!==i.k2.negative&&(i.k2.ineg(),o=o.neg(!0)),n[2*r]=a,n[2*r+1]=o,s[2*r]=i.k1,s[2*r+1]=i.k2}let a=this._wnafMulAdd(1,n,s,2*r,i);for(let e=0;e<2*r;e++)n[e]=null,s[e]=null;return a}_hasDoubles(e){if(null==this.precomputed)return!1;let t=this.precomputed.doubles;return"object"==typeof t&&t.points.length>=Math.ceil((e.bitLength()+1)/t.step)}_getDoubles(e,t){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.doubles&&null!==this.precomputed.doubles)return this.precomputed.doubles;let i=[this],r=this;for(let n=0;n<(t??0);n+=e??1){for(let t=0;t<(e??1);t++)r=r.dbl();i.push(r)}return{step:e??1,points:i}}_getNAFPoints(e){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.naf&&null!==this.precomputed.naf)return this.precomputed.naf;let t=[this],i=(1<<e)-1,r=1===i?null:this.dbl();for(let e=1;e<i;e++)null!==r&&(t[e]=t[e-1].add(r));return{wnd:e,points:t}}}class t1{p;red;redN;zero;one;two;g;n;a;b;tinv;zeroA;threeA;endo;_endoWnafT1;_endoWnafT2;_wnafT1;_wnafT2;_wnafT3;_wnafT4;_bitLength;static assert(e,t="Elliptic curve assertion failed"){if(!e)throw Error(t)}getNAF(e,t,i){let r=Array(Math.max(e.bitLength(),i)+1);r.fill(0);let n=1<<t+1,s=e.clone();for(let e=0;e<r.length;e++){let t,i=s.andln(n-1);s.isOdd()?(t=i>(n>>1)-1?(n>>1)-i:i,s.isubn(t)):t=0,r[e]=t,s.iushrn(1)}return r}getJSF(e,t){let i=[[],[]];e=e.clone(),t=t.clone();let r=0,n=0;for(;e.cmpn(-r)>0||t.cmpn(-n)>0;){let s,a,o=e.andln(3)+r&3,l=t.andln(3)+n&3;if(3===o&&(o=-1),3===l&&(l=-1),(1&o)==0)s=0;else{let t=e.andln(7)+r&7;s=(3===t||5===t)&&2===l?-o:o}if(i[0].push(s),(1&l)==0)a=0;else{let e=t.andln(7)+n&7;a=(3===e||5===e)&&2===o?-l:l}i[1].push(a),2*r===s+1&&(r=1-r),2*n===a+1&&(n=1-n),e.iushrn(1),t.iushrn(1)}return i}static cachedProperty(e,t,i){let r="_"+t;e.prototype[t]=function(){return void 0===this[r]&&(this[r]=i.call(this)),this[r]}}static parseBytes(e){return"string"==typeof e?tm(e,"hex"):e}static intFromLE(e){return new A(e,"hex","le")}constructor(){if(void 0!==e)return e;e=this;const t={prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",{doubles:{step:4,points:[["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a","f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"],["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508","11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"],["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739","d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"],["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640","4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"],["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c","4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"],["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda","96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"],["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa","5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"],["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0","cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"],["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d","9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"],["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d","e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"],["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1","9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"],["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0","5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"],["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047","10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"],["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862","283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"],["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7","7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"],["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd","56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"],["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83","7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"],["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a","53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"],["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8","bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"],["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d","4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"],["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725","7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"],["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754","4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"],["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c","17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"],["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6","6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"],["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39","c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"],["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891","893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"],["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b","febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"],["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03","2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"],["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d","eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"],["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070","7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"],["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4","e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"],["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da","662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"],["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11","1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"],["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e","efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"],["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41","2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"],["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef","67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"],["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8","db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"],["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d","648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"],["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96","35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"],["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd","ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"],["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5","9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"],["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266","40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"],["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71","34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"],["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac","c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"],["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751","1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"],["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e","493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"],["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241","c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"],["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3","be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"],["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f","4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"],["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19","aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"],["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be","b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"],["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9","6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"],["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2","8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"],["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13","7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"],["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c","ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"],["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba","2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"],["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151","e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"],["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073","d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"],["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458","38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"],["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b","69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"],["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366","d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"],["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa","40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"],["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0","620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"],["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787","7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"],["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e","ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]]},naf:{wnd:7,points:[["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"],["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4","d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"],["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"],["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe","cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"],["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"],["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8","ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"],["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e","581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"],["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34","4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"],["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c","85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"],["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5","321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"],["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f","2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"],["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714","73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"],["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729","a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"],["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db","2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"],["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4","e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"],["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5","b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"],["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479","2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"],["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d","80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"],["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f","1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"],["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb","d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"],["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9","eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"],["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963","758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"],["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74","958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"],["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530","e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"],["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b","5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"],["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247","cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"],["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1","cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"],["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120","4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"],["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435","91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"],["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18","673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"],["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8","59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"],["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb","3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"],["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f","55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"],["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143","efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"],["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba","e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"],["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45","f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"],["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a","744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"],["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e","c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"],["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8","e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"],["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c","30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"],["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519","e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"],["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab","100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"],["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca","ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"],["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf","8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"],["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610","68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"],["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4","f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"],["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c","d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"],["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940","edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"],["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980","a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"],["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3","66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"],["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf","9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"],["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63","4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"],["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448","fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"],["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf","5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"],["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5","8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"],["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6","8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"],["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5","5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"],["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99","f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"],["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51","f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"],["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5","42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"],["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5","204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"],["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997","4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"],["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881","73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"],["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5","39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"],["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66","d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"],["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726","ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"],["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede","6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"],["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94","60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"],["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31","3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"],["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51","b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"],["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252","ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"],["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5","cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"],["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b","6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"],["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4","322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"],["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f","6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"],["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889","2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"],["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246","b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"],["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984","998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"],["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a","b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"],["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030","bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"],["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197","6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"],["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593","c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"],["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef","21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"],["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38","60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"],["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a","49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"],["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111","5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"],["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502","7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"],["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea","be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"],["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26","8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"],["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986","39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"],["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e","62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"],["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4","25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"],["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda","ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"],["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859","cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"],["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f","f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"],["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c","6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"],["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942","fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"],["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a","1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"],["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80","5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"],["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d","438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"],["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1","cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"],["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63","c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"],["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352","6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"],["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193","ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"],["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00","9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"],["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58","ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"],["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7","d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"],["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8","c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"],["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e","67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"],["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d","cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"],["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b","299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"],["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f","f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"],["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6","462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"],["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297","62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"],["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a","7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"],["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c","ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"],["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52","4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"],["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb","bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"],["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065","bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"],["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917","603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"],["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9","cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"],["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3","553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"],["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57","712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"],["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66","ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"],["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8","9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"],["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721","9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"],["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180","4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]]}}]};this.p=new A(t.p,16),this.red=new P(t.prime),this.zero=new A(0).toRed(this.red),this.one=new A(1).toRed(this.red),this.two=new A(2).toRed(this.red),this.n=new A(t.n,16),this.g=t0.fromJSON(t.g,t.gRed),this._wnafT1=[,,,,],this._wnafT2=[,,,,],this._wnafT3=[,,,,],this._wnafT4=[,,,,],this._bitLength=this.n.bitLength(),this.redN=this.n.toRed(this.red),this.a=new A(t.a,16).toRed(this.red),this.b=new A(t.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(t),this._endoWnafT1=[,,,,],this._endoWnafT2=[,,,,]}_getEndomorphism(e){let t,i,r;if(this.zeroA&&1===this.p.modrn(3)){if(void 0===e.beta){let e=this._getEndoRoots(this.p);if(null===e)throw Error("Failed to get endomorphism roots for beta.");t=(t=0>e[0].cmp(e[1])?e[0]:e[1]).toRed(this.red)}else t=new A(e.beta,16).toRed(this.red);if(void 0===e.lambda){let e=this._getEndoRoots(this.n);if(null===e)throw Error("Failed to get endomorphism roots for lambda.");if(null==this.g)throw Error("Curve generator point (g) is not defined.");let r=this.g.mul(e[0])?.x,n=null==this.g.x?void 0:this.g.x.redMul(t);if(null!=r&&null!=n&&0===r.cmp(n))i=e[0];else{if(i=e[1],null==this.g)throw Error("Curve generator point (g) is not defined.");let r=this.g.mul(i)?.x,n=null==this.g.x?void 0:this.g.x.redMul(t);if(null==r||null==n)throw Error("Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.");t1.assert(0===r.cmp(n),"Lambda selection does not match computed beta.")}}else i=new A(e.lambda,16);return r="object"==typeof e.basis&&null!==e.basis?e.basis.map(function(e){return{a:new A(e.a,16),b:new A(e.b,16)}}):this._getEndoBasis(i),{beta:t,lambda:i,basis:r}}}_getEndoRoots(e){let t=e===this.p?this.red:new N(e),i=new A(2).toRed(t).redInvm(),r=i.redNeg(),n=new A(3).toRed(t).redNeg().redSqrt().redMul(i);return[r.redAdd(n).fromRed(),r.redSub(n).fromRed()]}_getEndoBasis(e){let t,i,r,n,s,a,o=this.n.ushrn(Math.floor(this.n.bitLength()/2)),l=e,c=this.n.clone(),h=new A(1),d=new A(0),u=new A(0),f=new A(1),p=new A(0),g=0,y=new A(0),m=new A(0);for(;0!==l.cmpn(0);){let e=c.div(l);y=c.sub(e.mul(l)),m=u.sub(e.mul(h));let s=f.sub(e.mul(d));if(void 0===r&&0>y.cmp(o))t=p.neg(),i=h,r=y.neg(),n=m;else if(void 0!==r&&2==++g)break;p=y,c=l,l=y,u=h,h=m,f=d,d=s}if(void 0===t||void 0===i||void 0===r||void 0===n)throw Error("Failed to compute Endo Basis values");s=y.neg(),a=m;let b=r.sqr().add(n.sqr());return s.sqr().add(a.sqr()).cmp(b)>=0&&(s=t,a=i),0!==r.negative&&(r=r.neg(),n=n.neg()),0!==s.negative&&(s=s.neg(),a=a.neg()),[{a:r,b:n},{a:s,b:a}]}_endoSplit(e){if(null==this.endo)throw Error("Endomorphism is not defined.");let t=this.endo.basis,i=t[0],r=t[1],n=r.b.mul(e).divRound(this.n),s=i.b.neg().mul(e).divRound(this.n),a=n.mul(i.a),o=s.mul(r.a),l=n.mul(i.b),c=s.mul(r.b);return{k1:e.sub(a).sub(o),k2:l.add(c).neg()}}validate(e){if(e.inf)return!0;let t=e.x,i=e.y;if(null===t||null===i)throw Error("Point coordinates cannot be null");let r=this.a.redMul(t),n=t.redSqr().redMul(t).redIAdd(r).redIAdd(this.b);return 0===i.redSqr().redISub(n).cmpn(0)}}class t2{r;s;static fromDER(e,t){let i=(e,t)=>{let i=e[t.place++];if((128&i)==0)return i;throw Error("Invalid DER entity length")};e=tm(e,t);let r=new class{place;constructor(){this.place=0}};if(48!==e[r.place++])throw Error("Signature DER must start with 0x30");if(i(e,r)+r.place!==e.length||2!==e[r.place++])throw Error("Signature DER invalid");let n=i(e,r),s=e.slice(r.place,n+r.place);if(r.place+=n,2!==e[r.place++])throw Error("Signature DER invalid");let a=i(e,r);if(e.length!==a+r.place)throw Error("Invalid R-length in signature DER");let o=e.slice(r.place,a+r.place);if(0===s[0])if((128&s[1])==0)throw Error("Invalid R-value in signature DER");else s=s.slice(1);if(0===o[0])if((128&o[1])==0)throw Error("Invalid S-value in signature DER");else o=o.slice(1);return new t2(new A(s),new A(o))}static fromCompact(e,t){if(65!==(e=tm(e,t)).length)throw Error("Invalid Compact Signature");let i=e[0];if(i<27||i>=35)throw Error("Invalid Compact Byte");return new t2(new A(e.slice(1,33)),new A(e.slice(33,65)))}constructor(e,t){this.r=e,this.s=t}verify(e,t,i){return it(new A(ev(e,i),16),this,t)}toString(e){return this.toDER(e)}toDER(e){let t=(e,t)=>{if(t<128)e.push(t);else throw Error("len must be < 0x80")},i=e=>{let t=0,i=e.length-1;for(;0===e[t]&&(128&e[t+1])==0&&t<i;)t++;return 0===t?e:e.slice(t)},r=this.r.toArray(),n=this.s.toArray();for((128&r[0])!=0&&(r=[0].concat(r)),(128&n[0])!=0&&(n=[0].concat(n)),r=i(r),n=i(n);0===n[0]&&(128&n[1])==0;)n=n.slice(1);let s=[2];t(s,r.length),(s=s.concat(r)).push(2),t(s,n.length);let a=s.concat(n),o=[48];return(t(o,a.length),o=o.concat(a),"hex"===e)?tg(o):"base64"===e?tS(o):o}toCompact(e,t,i){if(e<0||e>3)throw Error("Invalid recovery param");if("boolean"!=typeof t)throw TypeError("Invalid compressed param");let r=27+e;t&&(r+=4);let n=[r];return(n=(n=n.concat(this.r.toArray("be",32))).concat(this.s.toArray("be",32)),"hex"===i)?tg(n):"base64"===i?tS(n):n}RecoverPublicKey(e,t){let i=this.r,r=this.s,n=new t1,s=n.n,a=n.g,o=0==e>>1?i:i.add(s),l=t0.fromX(o,(1&e)!=0);if(!l.mul(s).isInfinity())throw Error("nR is not at infinity");let c=t.neg().umod(s),h=i.invm(s),d=h.mul(r).umod(s),u=h.mul(c).umod(s),f=new ii(a.mul(u).add(l.mul(d)));return f.validate(),f}CalculateRecoveryFactor(e,t){for(let i=0;i<4;i++){let r;try{r=this.RecoverPublicKey(i,t)}catch{continue}if(e.eq(r))return i}throw Error("Unable to find valid recovery factor")}}class t8{K;V;constructor(e,t){const i=tm(e,"hex"),r=tm(t,"hex");if(32!==i.length)throw Error("Entropy must be exactly 32 bytes (256 bits)");if(32!==r.length)throw Error("Nonce must be exactly 32 bytes (256 bits)");const n=i.concat(r);this.K=Array(32),this.V=Array(32);for(let e=0;e<32;e++)this.K[e]=0,this.V[e]=1;this.update(n)}hmac(){return new ef(this.K)}update(e){let t=this.hmac().update(this.V).update([0]);void 0!==e&&(t=t.update(e)),this.K=t.digest(),this.V=this.hmac().update(this.V).digest(),void 0!==e&&(this.K=this.hmac().update(this.V).update([1]).update(e).digest(),this.V=this.hmac().update(this.V).digest())}generate(e){let t=[];for(;t.length<e;)this.V=this.hmac().update(this.V).digest(),t=t.concat(this.V);let i=t.slice(0,e);return this.update(),tg(i)}}function t3(e,t,i=new t1){let r=8*e.byteLength()-i.n.bitLength();return(r>0&&e.iushrn(r),!0!==t&&e.cmp(i.n)>=0)?e.sub(i.n):e}function t5(e){let t=e.toArray("be"),i=0n;for(let e of t)i=i<<8n|BigInt(e);return i}let t6=new t1,t4=t6.n.byteLength(),t9=t6.n.subn(1),t7=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n>>1n,ie=(e,t,i=!1,r)=>{let n=t6.n.bitLength();if(e.bitLength()>n)throw Error(`ECDSA message is too large: expected <= ${n} bits. Callers must hash messages before signing.`);let s=t5(e=t3(e)),a=t5(t),o=new t8(t.toArray("be",t4),e.toArray("be",t4));for(let e=0;;e++){let t;if(null==(t="function"==typeof r?r(e):A.isBN(r)?r:new A(o.generate(t4),16)))throw Error("k is undefined");if(0>(t=t3(t,!0)).cmpn(1)||t.cmp(t9)>0){if(A.isBN(r))throw Error("Invalid fixed custom K value (must be >1 and <N-1)");continue}let n=t6.g.mulCT(t);if(n.isInfinity()){if(A.isBN(r))throw Error("Invalid fixed custom K value (k\xb7G at infinity)");continue}let l=tJ(BigInt("0x"+n.getX().toString(16)));if(0n===l){if(A.isBN(r))throw Error("Invalid fixed custom K value (r == 0)");continue}let c=tQ(BigInt("0x"+t.toString(16))),h=tJ(s+tZ(l,a)),d=tZ(c,h);if(0n===d){if(A.isBN(r))throw Error("Invalid fixed custom K value (s == 0)");continue}return i&&d>t7&&(d=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n-d),new t2(new A(l.toString(16),16),new A(d.toString(16),16))}},it=(e,t,i)=>{let r=t6.n.bitLength();if(e.bitLength()>r)return!1;let n=t5(e);if(null==i.x||null==i.y)throw Error("Invalid public key: missing coordinates.");let s={x:t5(i.x),y:t5(i.y)},{r:a,s:o}={r:t5(t.r),s:t5(t.s)};if(a<=0n||a>=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n||o<=0n||o>=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n)return!1;let l=tQ(o);if(0n===l)return!1;let c=tZ(n,l),h=tZ(a,l),d=tG(tY(c,{x:t$,y:tz}),tY(h,s));if(0n===d.Z)return!1;let u=tK(d.Z),f=tM(u,u);return tJ(tM(d.X,f))===a};class ii extends t0{static fromPrivateKey(e){let t=new t1().g.mul(e);return new ii(t.x,t.y)}static fromString(e){let t=t0.fromString(e);return new ii(t.x,t.y)}static fromDER(e){let t=t0.fromDER(e);return new ii(t.x,t.y)}constructor(e,t=null,i=!0){if(e instanceof t0)super(e.getX(),e.getY());else{if(null===t&&i&&"string"==typeof e&&(66===e.length||130===e.length))throw Error('You are using the "new PublicKey()" constructor with a DER hex string. You need to use "PublicKey.fromString()" instead.');super(e,t,i)}}deriveSharedSecret(e){if(!this.validate())throw Error("Public key not valid for ECDH secret derivation");return this.mulCT(e)}verify(e,t,i){return it(new A(ev(e,i),16),t,this)}toDER(e){return"hex"===e?this.encode(!0,e):this.encode(!0)}toHash(e){let t=eS(this.encode(!0));return"hex"===e?tg(t):t}toAddress(e=[0]){if("string"==typeof e)if("testnet"===e||"test"===e)e=[111];else if("mainnet"===e||"main"===e)e=[0];else throw Error(`Invalid prefix ${e}`);return tT(this.toHash(),e)}deriveChild(e,t,i,r){let n;if("function"==typeof r){let t=r(e,this);void 0===t?(n=this.deriveSharedSecret(e),"function"==typeof i&&i(e,this,n)):n=t}else n=this.deriveSharedSecret(e);let s=tm(t,"utf8"),a=eE(n.encode(!0),s),o=new t1().g.mul(new A(a)),l=this.add(o);return new ii(l.x,l.y)}static fromMsgHashAndCompactSignature(e,t,i){let r=tm(t,i);if(65!==r.length)throw Error("Invalid Compact Signature");let n=r[0];if(n<27||n>=35)throw Error("Invalid Compact Byte");let s=r[0]-27;return s>3&&(s-=4),new t2(new A(r.slice(1,33)),new A(r.slice(33,65))).RecoverPublicKey(s,e)}}class ir{_rand;getRandomValues(e,t){let i=new Uint8Array(t);return e.crypto.getRandomValues(i),Array.from(i)}constructor(){const e=()=>{throw Error("No secure random number generator is available in this environment.")};if(this._rand=e,"u">typeof globalThis&&"function"==typeof globalThis.crypto?.getRandomValues){this._rand=e=>this.getRandomValues(globalThis,e);return}if("u">typeof process&&process.release?.name==="node")try{const e=require("node:crypto");if("function"==typeof e.randomBytes){this._rand=t=>Array.from(e.randomBytes(t));return}}catch(e){}if(void 0!==globalThis.self&&"function"==typeof globalThis.self.crypto?.getRandomValues){this._rand=e=>this.getRandomValues(globalThis.self,e);return}if(void 0!==globalThis.window&&"function"==typeof globalThis.window.crypto?.getRandomValues){this._rand=e=>this.getRandomValues(globalThis.window,e);return}this._rand=e}generate(e){return this._rand(e)}}let is=null,ia=e=>(is??=new ir).generate(e);class io{x;y;constructor(e,t){const i=new t1().p;this.x=e.umod(i),this.y=t.umod(i)}toString(){return tA(this.x.toArray())+"."+tA(this.y.toArray())}static fromString(e){let[t,i]=e.split(".");return new io(new A(tx(t)),new A(tx(i)))}}class il{points;threshold;constructor(e,t){this.points=e,this.threshold=t??e.length}static fromPrivateKey(e,t){let i=new t1().p,r=[new io(new A(0),new A(e.toArray()))];for(let e=1;e<t;e++){let e=new A(ia(32)).umod(i),t=new A(ia(32)).umod(i);r.push(new io(e,t))}return new il(r)}valueAt(e){let t=new t1().p,i=new A(0);for(let r=0;r<this.threshold;r++){let n=this.points[r].y;for(let i=0;i<this.threshold;i++)if(r!==i){let s=this.points[i].x,a=this.points[r].x,o=e.sub(s).umod(t),l=a.sub(s).umod(t).invm(t),c=o.mul(l).umod(t);n=n.mul(c).umod(t)}i=i.add(n).umod(t)}return i}}class ic{points;threshold;integrity;constructor(e,t,i){this.points=e,this.threshold=t,this.integrity=i}static fromBackupFormat(e){let t=0,i="";return new ic(e.map((e,r)=>{let n=e.split(".");if(4!==n.length)throw Error("Invalid share format in share "+r.toString()+'. Expected format: "x.y.t.i" - received '+e);let[s,a,o,l]=n;if(void 0===o)throw Error("Threshold not found in share "+r.toString());if(void 0===l)throw Error("Integrity not found in share "+r.toString());let c=Number.parseInt(o,10);if(0!==r&&t!==c)throw Error("Threshold mismatch in share "+r.toString());if(0!==r&&i!==l)throw Error("Integrity mismatch in share "+r.toString());return t=c,i=l,io.fromString([s,a].join("."))}),t,i)}toBackupFormat(){return this.points.map(e=>e.toString()+"."+this.threshold.toString()+"."+this.integrity)}}class ih extends A{static fromRandom(){return new ih(ia(32))}static fromString(e,t="hex"){return new ih(super.fromString(e,t).toArray())}static fromHex(e){return new ih(super.fromHex(e,"big"))}static fromWif(e,t=1){let i=tO(e,void 0,t);if(33!==i.data.length)throw Error("Invalid WIF length");if(1!==i.data[32])throw Error("Invalid WIF padding");return new ih(i.data.slice(0,32))}constructor(e=0,t=10,i="be",r="apply"){if(e instanceof A?(super(),e.copy(this)):super(e,t,i),"nocheck"!==r){const e=this.checkInField();if(!e.inField){if("error"===r)throw Error("Input is out of field");A.move(this,e.modN)}}}checkInField(){let e=new t1,t=this.mod(e.n);return{inField:0===this.cmp(t),modN:t}}isValid(){return this.checkInField().inField}sign(e,t,i=!0,r){return ie(new A(ev(e,t),16),this,i,r)}verify(e,t,i){return it(new A(ev(e,i),16),t,this.toPublicKey())}toPublicKey(){let e=new t1().g.mulCT(this);return new ii(e.x,e.y)}toWif(e=[128]){if(!this.isValid())throw Error("Value is out of field");return tT([...this.toArray("be",32),1],e)}toAddress(e=[0]){return this.toPublicKey().toAddress(e)}toHex(){return super.toHex(32)}toString(e="hex",t=64){return super.toString(e,t)}deriveSharedSecret(e){if(!e.validate())throw Error("Public key not valid for ECDH secret derivation");return e.mulCT(this)}deriveChild(e,t,i,r){let n;if("function"==typeof r){let t=r(this,e);void 0===t?(n=this.deriveSharedSecret(e),"function"==typeof i&&i(this,e,n)):n=t}else n=this.deriveSharedSecret(e);let s=tm(t,"utf8"),a=eE(n.encode(!0),s),o=new t1;return new ih(this.add(new A(a)).mod(o.n).toArray())}toKeyShares(e,t){if("number"!=typeof e||"number"!=typeof t)throw TypeError("threshold and totalShares must be numbers");if(e<2)throw Error("threshold must be at least 2");if(t<2)throw Error("totalShares must be at least 2");if(e>t)throw Error("threshold should be less than or equal to totalShares");let i=il.fromPrivateKey(this,e),r=[],n=new Set,s=new t1,a=ia(64);for(let e=0;e<t;e++){let t,o=0;do if(t=new A(ex(a,[e,o,...ia(32)])).umod(s.p),++o>5)throw Error("Failed to generate unique x coordinate after 5 attempts");while(t.isZero()||n.has(t.toString()));n.add(t.toString());let l=i.valueAt(t);r.push(new io(t,l))}return new ic(r,e,this.toPublicKey().toHash("hex").slice(0,8))}toBackupShares(e,t){return this.toKeyShares(e,t).toBackupFormat()}static fromBackupShares(e){return ih.fromKeyShares(ic.fromBackupFormat(e))}static fromKeyShares(e){let{points:t,threshold:i,integrity:r}=e;if(i<2)throw Error("threshold must be at least 2");if(t.length<i)throw Error(`At least ${i} shares are required to reconstruct the private key`);for(let e=0;e<i;e++)for(let r=e+1;r<i;r++)if(t[e].x.eq(t[r].x))throw Error("Duplicate share detected, each must be unique.");let n=new ih(new il(t,i).valueAt(new A(0)).toArray());if(n.toPublicKey().toHash("hex").slice(0,8)!==r)throw Error("Integrity hash mismatch");return n}}let id=new Uint8Array([99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22]),iu=[[0,0,0,0],[1,0,0,0],[2,0,0,0],[4,0,0,0],[8,0,0,0],[16,0,0,0],[32,0,0,0],[64,0,0,0],[128,0,0,0],[27,0,0,0],[54,0,0,0]].map(e=>new Uint8Array(e)),ip=new Uint8Array(256),ig=new Uint8Array(256);for(let e=0;e<256;e++){let t=(e<<1^27*((128&e)!=0))&255;ip[e]=t,ig[e]=t^e}function iy(e,t,i){for(let r=0;r<4;r++){let n=t[i+r];for(let t=0;t<4;t++)e[t][r]^=n[t]}}function im(e){for(let t=0;t<4;t++)e[t]=id[e[t]]}function ib(e,t){let i,r,n,s,a=[[],[],[],[]],o=[],l=Array.from(t);if(16===l.length)s=11;else if(24===l.length)s=13;else if(32===l.length)s=15;else throw Error("Illegal key length: "+String(l.length));let c=function(e,t){let i=t.length/4,r=[];for(let e=0;e<t.length;e++)e%4==0&&r.push([]),r[e>>2].push(t[e]);for(let t=i;t<4*e;t++){r[t]=[];let e=r[t-1].slice();if(t%i==0){!function(e){let t=e[0];e[0]=e[1],e[1]=e[2],e[2]=e[3],e[3]=t}(e),im(e);let r=iu[t/i];for(let t=0;t<4;t++)e[t]^=r[t]}else i>6&&t%i==4&&im(e);for(let n=0;n<4;n++)r[t][n]=r[t-i][n]^e[n]}return r}(s,l);for(let t=0;t<4;t++)a[0][t]=e[4*t],a[1][t]=e[4*t+1],a[2][t]=e[4*t+2],a[3][t]=e[4*t+3];for(iy(a,c,0),n=1;n<s;n++){for(let e=0;e<4;e++)for(let t=0;t<4;t++)a[e][t]=id[a[e][t]];!function(e){let t=e[1][0];e[1][0]=e[1][1],e[1][1]=e[1][2],e[1][2]=e[1][3],e[1][3]=t,t=e[2][0];let i=e[2][1];e[2][0]=e[2][2],e[2][1]=e[2][3],e[2][2]=t,e[2][3]=i,t=e[3][3],e[3][3]=e[3][2],e[3][2]=e[3][1],e[3][1]=e[3][0],e[3][0]=t}(a),n+1<s&&function(e){for(let t=0;t<4;t++){let i=e[0][t],r=e[1][t],n=e[2][t],s=e[3][t];e[0][t]=ip[i]^ig[r]^n^s,e[1][t]=i^ip[r]^ig[n]^s,e[2][t]=i^r^ip[n]^ig[s],e[3][t]=ig[i]^r^n^ip[s]}}(a),iy(a,c,4*n)}for(i=0;i<4;i++)for(r=0;r<4;r++)o.push(a[r][i]);return o}let iw=function(e){if(e<0||e>Number.MAX_SAFE_INTEGER)throw Error("getBytes64: value out of range");let t=Math.floor(e/0x100000000),i=e>>>0;return[t>>>24&255,t>>>16&255,t>>>8&255,255&t,i>>>24&255,i>>>16&255,i>>>8&255,255&i]},iv=function(e){return new Uint8Array(e)},iI=((n=new Uint8Array(16))[0]=225,n),ik=(...e)=>{let t=0;for(let i of e)t+=i.length;let i=new Uint8Array(t),r=0;for(let t of e)i.set(t,r),r+=t.length;return i},iS=function(e){let t=0,i=0;for(let r=0;r<e.length;r++)i=t,t=1&e[r],e[r]=e[r]>>1,0!==i&&(e[r]=128|e[r]);return e},iE=function(e,t){let i=t.slice(),r=iv(16);for(let t=0;t<16;t++){let n=e[t];for(let e=7;e>=0;e--){let t=255&-(n>>e&1);for(let e=0;e<16;e++)r[e]^=i[e]&t;let s=255&-(1&i[15]);iS(i);for(let e=0;e<16;e++)i[e]^=iI[e]&s}}return r},ix=function(e){let t=e.slice();for(let e=15;e>11&&(t[e]=t[e]+1&255,0===t[e]);e--);return t};function iA(e,t){let i=iv(16),r=new Uint8Array(16);for(let n=0;n<e.length;n+=16){r.set(i);for(let t=0;t<16;t++)r[t]^=e[n+t]??0;i=iE(r,t)}return i}function iT(e,t,i){if(0===e.length)return new Uint8Array(0);let r=new Uint8Array(e.length),n=t.slice(),s=0,a=Math.ceil(e.length/16);for(let t=0;t<a;t++){let o=ib(n,i),l=Math.min(16,e.length-s);for(let t=0;t<l;t++)r[s]=e[s]^o[t],s++;t+1<a&&(n=ix(n))}return r}function iO(e){let t,i,r=8*e.length;t=0===e.length?16:e.length%16==0?0:16-e.length%16;let n=new Uint8Array(16+e.length+t+16);i=16,n.set(e,i),i+=e.length,i+=t;let s=iw(0);n.set(s,i),i+=8;let a=iw(r);return n.set(a,i),n}let iP=(()=>{let e="u"<typeof globalThis?void 0:globalThis.process,t=e?.getBuiltinModule;if("function"==typeof t)try{let i=t.call(e,"node:crypto");if(null!=i)return i}catch{}try{if("function"==typeof require)return require("node:crypto")}catch{}})(),iN=null!=iP&&"function"==typeof iP.createCipheriv&&"function"==typeof iP.createDecipheriv;class i_ extends A{static fromRandom(){return new i_(ia(32))}encrypt(e,t){let i=new Uint8Array(ia(32)),r=new Uint8Array(tm(e,t)),n=new Uint8Array(this.toArray("be",32));if(iN){let e=function(e,t,i){try{let r=iP.createCipheriv("aes-256-gcm",Buffer.from(i.buffer,i.byteOffset,i.byteLength),Buffer.from(t.buffer,t.byteOffset,t.byteLength)),n=Buffer.concat([r.update(Buffer.from(e.buffer,e.byteOffset,e.byteLength)),r.final()]),s=r.getAuthTag(),a=new Uint8Array(t.length+n.length+s.length),o=0;return a.set(t,o),o+=t.length,a.set(n,o),o+=n.length,a.set(s,o),a}catch{return null}}(r,i,n);if(null!==e)return tk(Array.from(e),t)}let{result:s,authenticationTag:a}=function(e,t,i){let r;if(0===t.length)throw Error("Initialization vector must not be empty");if(0===i.length)throw Error("Key must not be empty");let n=new Uint8Array(ib(iv(16),i));if(12===t.length)r=ik(t,iv(3),new Uint8Array([1]));else{let e=t;e.length%16!=0&&(e=ik(e,iv(16-e.length%16)));let i=iw(8*t.length);r=iA(ik(e,iv(8),new Uint8Array(i)),n)}let s=iT(e,ix(r),i),a=iT(iA(iO(s),n),r,i);return{result:s,authenticationTag:a}}(r,i,n),o=new Uint8Array(i.length+s.length+a.length),l=0;return o.set(i,l),l+=i.length,o.set(s,l),l+=s.length,o.set(a,l),tk(Array.from(o),t)}decrypt(e,t){let i=new Uint8Array(tm(e,t));if(i.length<48)throw Error("Ciphertext too short");let r=new Uint8Array(this.toArray("be",32));if(iN){let e=function(e,t){try{let i=e.slice(0,32),r=e.length-16,n=e.slice(32,r),s=e.slice(r),a=iP.createDecipheriv("aes-256-gcm",Buffer.from(t.buffer,t.byteOffset,t.byteLength),Buffer.from(i.buffer,i.byteOffset,i.byteLength));a.setAuthTag(Buffer.from(s.buffer,s.byteOffset,s.byteLength));let o=Buffer.concat([a.update(Buffer.from(n.buffer,n.byteOffset,n.byteLength)),a.final()]);return new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}catch{return null}}(i,r);if(void 0!==e){if(null===e)throw Error("Decryption failed!");return tk(Array.from(e),t)}}let n=i.slice(0,32),s=i.length-16,a=function(e,t,i,r){let n;if(0===e.length)throw Error("Cipher text must not be empty");if(0===t.length)throw Error("Initialization vector must not be empty");if(0===r.length)throw Error("Key must not be empty");let s=new Uint8Array(ib(iv(16),r));if(12===t.length)n=ik(t,iv(3),new Uint8Array([1]));else{let e=t;e.length%16!=0&&(e=ik(e,iv(16-e.length%16)));let i=iw(8*t.length);n=iA(ik(e,iv(8),new Uint8Array(i)),s)}let a=iT(e,ix(n),r),o=iT(iA(iO(e),s),n,r);if(o.length!==i.length)return null;let l=0;for(let e=0;e<o.length;e++)l|=o[e]^i[e];return 0!==l?null:a}(i.slice(32,s),n,i.slice(s),r);if(null===a)throw Error("Decryption failed!");return tk(Array.from(a),t)}}let iR={OP_0:0,OP_FALSE:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_1:81,OP_TRUE:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SPLIT:127,OP_NUM2BIN:128,OP_BIN2NUM:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP2:177,OP_CHECKSEQUENCEVERIFY:178,OP_NOP3:178,OP_SUBSTR:179,OP_NOP4:179,OP_LEFT:180,OP_NOP5:180,OP_RIGHT:181,OP_NOP6:181,OP_LSHIFTNUM:182,OP_NOP7:182,OP_RSHIFTNUM:183,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_NOP11:186,OP_NOP12:187,OP_NOP13:188,OP_NOP14:189,OP_NOP15:190,OP_NOP16:191,OP_NOP17:192,OP_NOP18:193,OP_NOP19:194,OP_NOP20:195,OP_NOP21:196,OP_NOP22:197,OP_NOP23:198,OP_NOP24:199,OP_NOP25:200,OP_NOP26:201,OP_NOP27:202,OP_NOP28:203,OP_NOP29:204,OP_NOP30:205,OP_NOP31:206,OP_NOP32:207,OP_NOP33:208,OP_NOP34:209,OP_NOP35:210,OP_NOP36:211,OP_NOP37:212,OP_NOP38:213,OP_NOP39:214,OP_NOP40:215,OP_NOP41:216,OP_NOP42:217,OP_NOP43:218,OP_NOP44:219,OP_NOP45:220,OP_NOP46:221,OP_NOP47:222,OP_NOP48:223,OP_NOP49:224,OP_NOP50:225,OP_NOP51:226,OP_NOP52:227,OP_NOP53:228,OP_NOP54:229,OP_NOP55:230,OP_NOP56:231,OP_NOP57:232,OP_NOP58:233,OP_NOP59:234,OP_NOP60:235,OP_NOP61:236,OP_NOP62:237,OP_NOP63:238,OP_NOP64:239,OP_NOP65:240,OP_NOP66:241,OP_NOP67:242,OP_NOP68:243,OP_NOP69:244,OP_NOP70:245,OP_NOP71:246,OP_NOP72:247,OP_NOP73:248,OP_NOP77:252,OP_SMALLDATA:249,OP_SMALLINTEGER:250,OP_PUBKEYS:251,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255};for(let e in iR)void 0===iR[iR[e]]&&(iR[iR[e]]=e);let iC=iR,iB="u"<typeof globalThis?void 0:globalThis.Buffer;class iU{_chunks;parsed;rawBytesCache;hexCache;static fromASM(e){let t=[],i=e.split(" "),r=0;for(;r<i.length;){let{chunk:e,advance:n}=iU.parseASMToken(i,r);t.push(e),r+=n}return new iU(t)}static pushdataOpCodeNum(e){return e>=0&&e<iC.OP_PUSHDATA1?e:e<256?iC.OP_PUSHDATA1:e<65536?iC.OP_PUSHDATA2:iC.OP_PUSHDATA4}static parseASMToken(e,t){let i=e[t];if("0"===i)return{chunk:{op:0},advance:1};if("-1"===i)return{chunk:{op:iC.OP_1NEGATE},advance:1};let r=i.startsWith("OP_")&&void 0!==iC[i],n=r?iC[i]:0;if(n===iC.OP_PUSHDATA1||n===iC.OP_PUSHDATA2||n===iC.OP_PUSHDATA4)return{chunk:{data:tm(e[t+2],"hex"),op:n},advance:3};if(!r){let e=i;e.length%2!=0&&(e="0"+e);let t=tm(e,"hex");if(tk(t,"hex")!==e)throw Error("invalid hex string in script");return{chunk:{data:t,op:iU.pushdataOpCodeNum(t.length)},advance:1}}return{chunk:{op:n},advance:1}}static fromHex(e){if(0===e.length)return iU.fromBinary([]);if(e.length%2!=0)throw Error("There is an uneven number of characters in the string which suggests it is not hex encoded.");if(!/^[0-9a-fA-F]+$/.test(e))throw Error("Some elements in this string are not hex encoded.");let t=tm(e,"hex");return new iU([],Uint8Array.from(t),e.toLowerCase(),!1)}static fromBinary(e){return new iU([],Uint8Array.from(e),void 0,!1)}constructor(e=[],t,i,r=!0){this._chunks=e,this.parsed=r,this.rawBytesCache=t,this.hexCache=i}get chunks(){return this.ensureParsed(),this._chunks}set chunks(e){this._chunks=e,this.parsed=!0,this.invalidateSerializationCaches()}ensureParsed(){this.parsed||(null!=this.rawBytesCache?this._chunks=iU.parseChunks(this.rawBytesCache):this._chunks=[],this.parsed=!0)}toASM(){let e="";for(let t of this.chunks)e+=this._chunkToString(t);return e.slice(1)}toHex(){if(null!=this.hexCache)return this.hexCache;this.rawBytesCache??=this.serializeChunksToBytes();let e=null==iB?tk(Array.from(this.rawBytesCache),"hex"):iB.from(this.rawBytesCache).toString("hex");return this.hexCache=e,e}toBinary(){return Array.from(this.toUint8Array())}toUint8Array(){return this.rawBytesCache??=this.serializeChunksToBytes(),this.rawBytesCache}writeScript(e){return this.invalidateSerializationCaches(),this.chunks=this.chunks.concat(e.chunks),this}writeOpCode(e){return this.invalidateSerializationCaches(),this.chunks.push({op:e}),this}setChunkOpCode(e,t){return this.invalidateSerializationCaches(),this.chunks[e]={op:t},this}writeBn(e){if(this.invalidateSerializationCaches(),e.cmpn(0)===iC.OP_0)this.chunks.push({op:iC.OP_0});else if(0===e.cmpn(-1))this.chunks.push({op:iC.OP_1NEGATE});else if(e.cmpn(1)>=0&&0>=e.cmpn(16))this.chunks.push({op:e.toNumber()+iC.OP_1-1});else{let t=e.toSm("little");this.writeBin(t)}return this}writeBin(e){let t;this.invalidateSerializationCaches();let i=e.length>0?e:void 0;if(e.length>0&&e.length<iC.OP_PUSHDATA1)t=e.length;else if(0===e.length)t=iC.OP_0;else if(e.length<256)t=iC.OP_PUSHDATA1;else if(e.length<65536)t=iC.OP_PUSHDATA2;else if(e.length<0x100000000)t=iC.OP_PUSHDATA4;else throw Error("You can't push that much data");return this.chunks.push({data:i,op:t}),this}writeNumber(e){return this.invalidateSerializationCaches(),this.writeBn(new A(e)),this}removeCodeseparators(){let e=this.toUint8Array();return this.rawBytesCache=Uint8Array.from(iU.removeOpcodeBytes(e,iC.OP_CODESEPARATOR)),this.hexCache=void 0,this._chunks=[],this.parsed=!1,this}findAndDelete(e){this.invalidateSerializationCaches();let t=e.toUint8Array(),i=t.length;if(0===i)return this;let r=t[0]??0,n=e=>{if(e.op!==r)return!1;let n=e.data??[],s=n.length;if(0===s)return 1===i;if(e.op===iC.OP_RETURN||e.op<iC.OP_PUSHDATA1){if(i!==1+s)return!1;for(let e=0;e<s;e++)if(t[1+e]!==n[e])return!1;return!0}if(e.op===iC.OP_PUSHDATA1){if(i!==2+s||t[1]!==(255&s))return!1;for(let e=0;e<s;e++)if(t[2+e]!==n[e])return!1;return!0}if(e.op===iC.OP_PUSHDATA2){if(i!==3+s||t[1]!==(255&s)||t[2]!==(s>>8&255))return!1;for(let e=0;e<s;e++)if(t[3+e]!==n[e])return!1;return!0}if(e.op===iC.OP_PUSHDATA4){if(i!==5+s)return!1;let e=s>>>0;if(t[1]!==(255&e)||t[2]!==(e>>8&255)||t[3]!==(e>>16&255)||t[4]!==(e>>24&255))return!1;for(let e=0;e<s;e++)if(t[5+e]!==n[e])return!1;return!0}return!1};for(let e=0;e<this.chunks.length;)n(this.chunks[e])?this.chunks.splice(e,1):e++;return this}isPushOnly(){for(let e of this.chunks)if(e.op>iC.OP_16)return!1;return!0}isLockingScript(){throw Error("Not implemented")}isUnlockingScript(){throw Error("Not implemented")}static computeSerializedLength(e){let t=0;for(let i of e){if(t+=1,null==i.data)continue;let e=i.data.length;if(i.op===iC.OP_RETURN){t+=e;break}i.op<iC.OP_PUSHDATA1?t+=e:i.op===iC.OP_PUSHDATA1?t+=1+e:i.op===iC.OP_PUSHDATA2?t+=2+e:i.op===iC.OP_PUSHDATA4&&(t+=4+e)}return t}serializeChunksToBytes(){let e=this.chunks,t=new Uint8Array(iU.computeSerializedLength(e)),i=0;for(let r of e)if(t[i++]=r.op,null!=r.data){if(r.op===iC.OP_RETURN){t.set(r.data,i);break}i=iU.writeChunkData(t,i,r.op,r.data)}return t}invalidateSerializationCaches(){this.rawBytesCache=void 0,this.hexCache=void 0}static writeChunkData(e,t,i,r){let n=r.length;if(i<iC.OP_PUSHDATA1)return e.set(r,t),t+n;if(i===iC.OP_PUSHDATA1)return e[t++]=255&n,e.set(r,t),t+n;if(i===iC.OP_PUSHDATA2)return e[t++]=255&n,e[t++]=n>>8&255,e.set(r,t),t+n;if(i===iC.OP_PUSHDATA4){let i=n>>>0;return e[t++]=255&i,e[t++]=i>>8&255,e[t++]=i>>16&255,e[t++]=i>>24&255,e.set(r,t),t+n}return t}static readPushdataLength(e,t,i,r){if(e>0&&e<iC.OP_PUSHDATA1)return{len:e,newPos:i,hasLength:!0};if(e===iC.OP_PUSHDATA1){let e=i<r;return{len:e?t[i++]??0:0,newPos:i,hasLength:e}}if(e===iC.OP_PUSHDATA2){let e=i+1<r;return{len:(t[i]??0)|(t[i+1]??0)<<8,newPos:Math.min(i+2,r),hasLength:e}}let n=i+3<r;return{len:((t[i]??0)|(t[i+1]??0)<<8|(t[i+2]??0)<<16|(t[i+3]??0)<<24)>>>0,newPos:Math.min(i+4,r),hasLength:n}}static parseChunks(e){let t=[],i=e.length,r=0,n=0;for(;r<i;){let s=e[r++]??0;if(s===iC.OP_RETURN&&0===n){t.push({op:s,data:iU.copyRange(e,r,i)});break}if(s===iC.OP_IF||s===iC.OP_NOTIF||s===iC.OP_VERIF||s===iC.OP_VERNOTIF?n++:s===iC.OP_ENDIF&&n--,s>0&&s<=iC.OP_PUSHDATA4){let{len:n,newPos:a,hasLength:o}=iU.readPushdataLength(s,e,r,i),l=Math.min((r=a)+n,i),c=!o||l-r!==n;t.push({data:iU.copyRange(e,r,l),op:s,invalidLength:c}),r=l}else t.push({op:s})}return t}static removeOpcodeBytes(e,t){let i=[],r=e.length,n=0;for(;n<r;){let s=n,a=e[n++]??0;if(a>0&&a<=iC.OP_PUSHDATA4){let{len:o,newPos:l}=iU.readPushdataLength(a,e,n,r),c=Math.min((n=l)+o,r);if(a!==t)for(let t=s;t<c;t++)i.push(e[t]??0);n=c}else a!==t&&i.push(a)}return i}static copyRange(e,t,i){let r=Math.max(i-t,0),n=Array(r);for(let i=0;i<r;i++)n[i]=e[t+i]??0;return n}_chunkToString(e){let t=e.op,i="";if(void 0===e.data){let e=iC[t];i=`${i} ${e}`}else i=`${i} ${tg(e.data)}`;return i}}let iF=new Uint8Array(0);class iD extends t2{static SIGHASH_ALL=1;static SIGHASH_NONE=2;static SIGHASH_SINGLE=3;static SIGHASH_CHRONICLE=32;static SIGHASH_FORKID=64;static SIGHASH_ANYONECANPAY=128;scope;static formatOTDA(e){let t=(e.scope&iD.SIGHASH_ANYONECANPAY)===iD.SIGHASH_ANYONECANPAY,i=(31&e.scope)===iD.SIGHASH_SINGLE,r=(31&e.scope)===iD.SIGHASH_NONE,n=(31&e.scope)===iD.SIGHASH_ALL||!i&&!r,s=iU.fromBinary(e.subscript.toBinary());s.removeCodeseparators();let a={sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,sequence:e.inputSequence,script:s.toBinary()},o=new tP;function l(e){for(let t of(o.writeVarIntNum(e.length),e))o.writeReverse(tm(t.sourceTXID,"hex")),o.writeUInt32LE(t.sourceOutputIndex),o.writeVarIntNum(t.script.length),o.write(t.script),o.writeUInt32LE(t.sequence)}function c(e){for(let t of(o.writeVarIntNum(e.length),e))o.writeUInt64LE(t.satoshis),o.writeVarIntNum(t.script.length),o.write(t.script)}o.writeInt32LE(e.transactionVersion);let h=new iU().toBinary();if(t)t&&l([a]);else{let t=e.otherInputs.map(e=>({sourceTXID:e.sourceTXID??e.sourceTransaction?.id("hex")??"",sourceOutputIndex:e.sourceOutputIndex,sequence:i||r?0:e.sequence??0xffffffff,script:h}));t.splice(e.inputIndex,0,a),l(t)}if(n)c(e.outputs.map(e=>({satoshis:e.satoshis??0,script:e.lockingScript.toBinary()})));else if(i){let t=[];for(let i=0;i<e.inputIndex;i++)t.push({satoshis:-1,script:h});let i=e.outputs[e.inputIndex];void 0!==i&&t.push({satoshis:i.satoshis??0,script:i.lockingScript.toBinary()}),c(t)}else r&&c([]);return o.writeUInt32LE(e.lockTime),o.writeUInt32LE(e.scope>>>0),o.toUint8Array()}static formatBip143(e){let t=e.cache,i={sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,sequence:e.inputSequence},r=[...e.otherInputs];function n(t){let i=new tP;if(void 0===t)for(let t of e.outputs){let e=t.satoshis??0;i.writeUInt64LE(e);let r=t.lockingScript?.toUint8Array()??iF;i.writeVarIntNum(r.length),i.write(r)}else{let r=e.outputs[t];if(void 0===r)throw Error(`Output at index ${t} does not exist`);let n=r.satoshis??0;i.writeUInt64LE(n);let s=r.lockingScript?.toUint8Array()??iF;i.writeVarIntNum(s.length),i.write(s)}return ek(i.toUint8Array())}r.splice(e.inputIndex,0,i);let s=Array(32).fill(0),a=Array(32).fill(0),o=Array(32).fill(0);if((e.scope&iD.SIGHASH_ANYONECANPAY)==0&&(t?.hashPrevouts==null?(s=(()=>{let e=new tP;for(let t of r){if(void 0===t.sourceTXID){if(null==t.sourceTransaction)throw Error("Missing sourceTransaction for input");e.write(t.sourceTransaction.hash())}else e.writeReverse(tm(t.sourceTXID,"hex"));e.writeUInt32LE(t.sourceOutputIndex)}return ek(e.toUint8Array())})(),null!=t&&(t.hashPrevouts=s)):s=t.hashPrevouts),(e.scope&iD.SIGHASH_ANYONECANPAY)==0&&(31&e.scope)!==iD.SIGHASH_SINGLE&&(31&e.scope)!==iD.SIGHASH_NONE&&(t?.hashSequence==null?(a=(()=>{let e=new tP;for(let t of r){let i=t.sequence??0xffffffff;e.writeUInt32LE(i)}return ek(e.toUint8Array())})(),null!=t&&(t.hashSequence=a)):a=t.hashSequence),(31&e.scope)!==iD.SIGHASH_SINGLE&&(31&e.scope)!==iD.SIGHASH_NONE)t?.hashOutputsAll==null?(o=n(),null!=t&&(t.hashOutputsAll=o)):o=t.hashOutputsAll;else if((31&e.scope)===iD.SIGHASH_SINGLE&&e.inputIndex<e.outputs.length){let i=e.inputIndex,r=t?.hashOutputsSingle?.get(i);null==r?(o=n(i),null!=t&&(t.hashOutputsSingle??=new Map,t.hashOutputsSingle.set(i,o))):o=r}let l=new tP;l.writeInt32LE(e.transactionVersion),l.write(s),l.write(a),l.writeReverse(tm(e.sourceTXID,"hex")),l.writeUInt32LE(e.sourceOutputIndex);let c=e.subscript.toUint8Array();l.writeVarIntNum(c.length),l.write(c),l.writeUInt64LE(e.sourceSatoshis);let h=i.sequence;return l.writeUInt32LE(h),l.write(o),l.writeUInt32LE(e.lockTime),l.writeUInt32LE(e.scope>>>0),l.toUint8Array()}static format(e){return Array.from(this.formatBytes(e))}static formatBytes(e){let t=(e.scope&iD.SIGHASH_FORKID)!=0,i=!0!==e.ignoreChronicle&&(e.scope&iD.SIGHASH_CHRONICLE)!=0;return t&&!i?iD.formatBip143(e):!t||t&&i?iD.formatOTDA(e):new Uint8Array(0)}static usesOtdaSingleBug(e){let t=(e.scope&iD.SIGHASH_FORKID)!=0,i=!0!==e.ignoreChronicle&&(e.scope&iD.SIGHASH_CHRONICLE)!=0;return(!t||t&&i)&&(31&e.scope)===iD.SIGHASH_SINGLE&&e.inputIndex>=e.outputs.length}static fromChecksigFormat(e){if(0===e.length)return new iD(new A(1),new A(1),1);let t=e.at(-1),i=e.slice(0,e.length-1),r=t2.fromDER(i);return new iD(r.r,r.s,t)}constructor(e,t,i){super(e,t),this.scope=i}hasLowS(){return!(this.s.ltn(1)||this.s.gt(new A("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex")))}toChecksigFormat(){return[...this.toDER(),this.scope]}}class iL{curve;constructor(){this.curve=new t1}generateProof(e,t,i,r){let n=ih.fromRandom(),s=n.toPublicKey(),a=i.mul(n),o=this.computeChallenge(t,i,r,a,s);return{R:s,SPrime:a,z:n.add(o.mul(e)).umod(this.curve.n)}}verifyProof(e,t,i,r){let{R:n,SPrime:s,z:a}=r,o=this.computeChallenge(e,t,i,s,n),l=this.curve.g.mul(a),c=n.add(e.mul(o));if(!l.eq(c))return!1;let h=t.mul(a),d=s.add(i.mul(o));return!!h.eq(d)}computeChallenge(e,t,i,r,n){return new A(ev([...e.encode(!0),...t.encode(!0),...i.encode(!0),...r.encode(!0),...n.encode(!0)])).umod(this.curve.n)}}let iV=/^[0-9a-fA-F]+$/,iH=BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),iM=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),iK=iH-3n,iq=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),i$={x:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),y:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},iz=iM>>1n;class iW{p=iH;n=iM;a=iK;b=iq;g=i$;mod(e,t=this.p){let i=e%t;return i>=0n?i:i+t}modInv(e,t){if(0n===e||t<=0n)throw Error("Invalid mod inverse input");let[i,r]=[this.mod(e,t),t],[n,s]=[1n,0n];for(;0n!==r;){let e=i/r;[i,r]=[r,i-e*r],[n,s]=[s,n-e*s]}if(1n!==i)throw Error("Inverse does not exist");return this.mod(n,t)}modPow(e,t,i){if(1n===i)return 0n;let r=1n,n=this.mod(e,i),s=t;for(;s>0n;)(1n&s)===1n&&(r=this.mod(r*n,i)),s>>=1n,n=this.mod(n*n,i);return r}isInfinity(e){return null===e}assertOnCurve(e){if(this.isInfinity(e))return;let{x:t,y:i}=e;if(this.mod(i*i)!==this.mod(this.mod(t*t*t+this.a*t)+this.b))throw Error("Point is not on secp256r1")}pointFromAffine(e,t){let i={x:this.mod(e),y:this.mod(t)};return this.assertOnCurve(i),i}pointFromHex(e){if(e.startsWith("04")){let t=BigInt("0x"+e.slice(2,66)),i=BigInt("0x"+e.slice(66));return this.pointFromAffine(t,i)}if(e.startsWith("02")||e.startsWith("03")){let t=BigInt("0x"+e.slice(2)),i=this.mod(this.mod(t*t*t+this.a*t)+this.b),r=this.modPow(i,this.p+1n>>2n,this.p),n=(1n&r)===1n===e.startsWith("03")?r:this.p-r;return this.pointFromAffine(t,n)}throw Error("Invalid point encoding")}pointToHex(e,t=!1){if(this.isInfinity(e))return"00";let i=this.to32BytesHex(e.x),r=this.to32BytesHex(e.y);return t?((1n&e.y)===0n?"02":"03")+i:"04"+i+r}addPoints(e,t){if(this.isInfinity(e))return t;if(this.isInfinity(t))return e;let{x:i,y:r}=e,{x:n,y:s}=t;if(i===n)return r===s?this.doublePoint(e):null;let a=this.mod((s-r)*this.modInv(n-i,this.p)),o=this.mod(a*a-i-n),l=this.mod(a*(i-o)-r);return{x:o,y:l}}doublePoint(e){if(this.isInfinity(e))return e;if(0n===e.y)return null;let t=this.mod((3n*e.x*e.x+this.a)*this.modInv(2n*e.y,this.p)),i=this.mod(t*t-2n*e.x),r=this.mod(t*(e.x-i)-e.y);return{x:i,y:r}}add(e,t){return this.addPoints(e,t)}multiply(e,t){if(0n===t||this.isInfinity(e))return null;let i=this.mod(t,this.n),r=null,n=e;for(;i>0n;)(1n&i)===1n&&(r=this.addPoints(r,n)),n=this.doublePoint(n),i>>=1n;return r}multiplyBase(e){return this.multiply(this.g,e)}isOnCurve(e){try{return this.assertOnCurve(e),!0}catch(e){return!1}}generatePrivateKeyHex(){return this.to32BytesHex(this.randomScalar())}randomScalar(){for(;;){let e=BigInt("0x"+tg(ia(32)));if(e>0n&&e<this.n)return e}}normalizePrivateKey(e){let t=this.mod(e,this.n);if(0n===t)throw Error("Invalid private key");return t}toScalar(e){if("bigint"==typeof e)return this.normalizePrivateKey(e);let t=e.startsWith("0x")?e.slice(2):e;if(!iV.test(t)||0===t.length||t.length>64)throw Error("Private key must be a hex string <= 32 bytes");let i=BigInt("0x"+t.padStart(64,"0"));return this.normalizePrivateKey(i)}publicKeyFromPrivate(e){let t=this.toScalar(e);return this.multiplyBase(t)}sign(e,t,i={}){let{prehashed:r=!1,nonce:n}=i,s=this.toScalar(t),a=this.normalizeMessage(e,r),o=this.bytesToScalar(a),l=n??this.deterministicNonce(s,a);for(;;){let e=this.multiplyBase(l);if(this.isInfinity(e)){l=n??this.deterministicNonce(s,a);continue}let t=this.mod(e.x,this.n);if(0n===t){l=n??this.deterministicNonce(s,a);continue}let i=this.modInv(l,this.n),r=this.mod(i*(o+t*s),this.n);if(0n===r){l=n??this.deterministicNonce(s,a);continue}return r>iz&&(r=this.n-r),{r:this.to32BytesHex(t),s:this.to32BytesHex(r)}}}verify(e,t,i,r={}){let n,{prehashed:s=!1}=r;try{n="string"==typeof i?this.pointFromHex(i):i}catch{return!1}if(null==n||!this.isOnCurve(n))return!1;let a="bigint"==typeof t.r?t.r:BigInt("0x"+t.r),o="bigint"==typeof t.s?t.s:BigInt("0x"+t.s);if(a<=0n||a>=this.n||o<=0n||o>=this.n)return!1;let l=this.bytesToScalar(this.normalizeMessage(e,s)),c=this.modInv(o,this.n),h=this.mod(l*c,this.n),d=this.mod(a*c,this.n),u=this.addPoints(this.multiplyBase(h),this.multiply(n,d));return!this.isInfinity(u)&&this.mod(u.x,this.n)===a}normalizeMessage(e,t){let i=this.toBytes(e);return t?i:new Uint8Array(ev(i))}bytesToScalar(e){return BigInt("0x"+tg(Array.from(e)))%this.n}deterministicNonce(e,t){let i=tm(this.to32BytesHex(e),"hex"),r=0;for(;r<1024;){let e=BigInt("0x"+tg(eE(i,0===r?Array.from(t):Array.from(t).concat([255&r]))))%this.n;if(e>0n)return e;r++}throw Error("Failed to derive deterministic nonce")}toBytes(e){if("string"==typeof e){let t=iV.test(e)&&e.length%2==0;return Uint8Array.from(tm(e,t?"hex":"utf8"))}if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error("Unsupported message format")}to32BytesHex(e){return e.toString(16).padStart(64,"0")}}class ij extends iU{isLockingScript(){return!0}isUnlockingScript(){return!1}}class iG extends iU{isLockingScript(){return!1}isUnlockingScript(){return!0}}class iX extends Error{txid;outputIndex;context;programCounter;stackState;altStackState;ifStackState;stackMem;altStackMem;constructor(e){const t=e.stackState.map(e=>null!=e&&void 0!==e.length?tg(e):null==e?"null/undef":"INVALID_STACK_ITEM").join(", "),i=e.altStackState.map(e=>null!=e&&void 0!==e.length?tg(e):null==e?"null/undef":"INVALID_STACK_ITEM").join(", "),r=`Context: ${e.context}, PC: ${e.programCounter}`,n=`Stack: [${t}] (len: ${e.stackState.length}, mem: ${e.stackMem})`,s=`AltStack: [${i}] (len: ${e.altStackState.length}, mem: ${e.altStackMem})`,a=`IfStack: [${e.ifStackState.join(", ")}]`;super(`Script evaluation error: ${e.message}
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.bsv=t():e.bsv=t()}(this,()=>(()=>{"use strict";let e,t,i,r,n;var s,a,o,l,c,h,d,u,f={};f.d=(e,t)=>{for(var i in t)f.o(t,i)&&!f.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},f.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),f.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var p={};f.r(p),f.d(p,{ARC:()=>rs,ATOMIC_BEEF:()=>ru,AuthFetch:()=>n6,BEEF_V1:()=>rh,BEEF_V2:()=>rd,BSM:()=>v,Beef:()=>rp,BeefParty:()=>rb,BeefTx:()=>rf,BigNumber:()=>A,BlockHeadersService:()=>rE,Brc29RemittanceModule:()=>sW,CachedKeyDeriver:()=>rj,Certificate:()=>r1,CompletedProtoWallet:()=>nY,Curve:()=>t1,DEFAULT_IDENTITY_CLIENT_OPTIONS:()=>sw,DEFAULT_REMITTANCE_MESSAGEBOX:()=>sL,DEFAULT_SLAP_TRACKERS:()=>si,DEFAULT_TESTNET_SLAP_TRACKERS:()=>sr,DEFAULT_UHRP_SERVERS:()=>sp,DefaultLockingScriptProvider:()=>sz,DefaultNonceProvider:()=>s$,ECDSA:()=>m,ECIES:()=>rK,EncryptedMessage:()=>w,FetchHttpClient:()=>ri,GlobalKVStore:()=>sU,HD:()=>rU,HTTPSOverlayBroadcastFacilitator:()=>sa,HTTPSOverlayLookupFacilitator:()=>sn,HTTPWalletJSON:()=>nt,HTTPWalletWire:()=>r5,Hash:()=>g,IdentityClient:()=>sA,InvoiceHandle:()=>sM,InvokableWalletBase:()=>rQ,KNOWN_IDENTITY_TYPES:()=>sv,KeyDeriver:()=>rW,KeyShares:()=>ic,LivePolicy:()=>i7,LocalKVStore:()=>sP,LockingScript:()=>ij,LookupResolver:()=>ss,MasterCertificate:()=>nG,MerklePath:()=>rc,Mnemonic:()=>rD,NodejsHttpClient:()=>rt,OP:()=>iC,OverlayAdminTokenTemplate:()=>n4,P2PKH:()=>i3,Peer:()=>n8,Point:()=>t0,PointInFiniteField:()=>io,Polynomial:()=>il,PrivateKey:()=>ih,ProtoWallet:()=>rX,PublicKey:()=>ii,PushDrop:()=>i4,REMITTANCE_STATE_TRANSITIONS:()=>sF,RPuzzle:()=>i5,Random:()=>ia,ReactNativeWebView:()=>ni,RegistryClient:()=>sT,RemittanceManager:()=>sV,RenewResiliencyError:()=>sg,SAT_UNIT:()=>sD,SHIPBroadcaster:()=>so,SHIPCast:()=>so,SatoshisPerKilobyte:()=>i9,Schnorr:()=>iL,Script:()=>iU,ScriptEvaluationError:()=>iX,Secp256r1:()=>iW,SecurityLevels:()=>h,SessionManager:()=>nJ,Signature:()=>t2,SignedMessage:()=>b,SimplifiedFetchTransport:()=>n5,Spend:()=>i0,StorageDownloader:()=>sm,StorageUploader:()=>sy,StorageUtils:()=>k,SymmetricKey:()=>i_,TOTP:()=>r$,TX_DATA_FORMAT:()=>c,Teranode:()=>rS,ThreadHandle:()=>sH,TopicBroadcaster:()=>so,Transaction:()=>rg,TransactionSignature:()=>iD,UnlockingScript:()=>iG,Utils:()=>y,Validation:()=>I,VerifiableCertificate:()=>nX,WERR_INSUFFICIENT_FUNDS:()=>ne,WERR_INVALID_PARAMETER:()=>r7,WERR_REVIEW_ACTIONS:()=>r4,WalletClient:()=>nW,WalletError:()=>rJ,WalletErrors:()=>rZ,WalletWireProcessor:()=>nj,WalletWireTransceiver:()=>r3,WhatsOnChain:()=>ro,WhatsOnChainBroadcaster:()=>rw,WindowCWISubstrate:()=>rY,XDM:()=>r0,binaryHttpClient:()=>rk,createNonce:()=>nQ,defaultBroadcaster:()=>ra,defaultChainTracker:()=>rl,defaultHttpClient:()=>rr,defaultIdentity:()=>sb,deserializeWalletProtocol:()=>sO,fromUtxo:()=>rq,getVerifiableCertificates:()=>n0,isBroadcastFailure:()=>rm,isBroadcastResponse:()=>ry,validateCertificates:()=>n1,verifyNonce:()=>nZ,walletErrors:()=>d,withDoubleSpendRetry:()=>sl});var g={};f.r(g),f.d(g,{RIPEMD160:()=>ec,SHA1:()=>ed,SHA1HMAC:()=>ep,SHA256:()=>eh,SHA256HMAC:()=>ef,SHA512:()=>eu,SHA512HMAC:()=>eg,hash160:()=>eS,hash256:()=>ek,htonl:()=>L,pbkdf2:()=>tn,realHtonl:()=>to,ripemd160:()=>eb,sha1:()=>ew,sha256:()=>ev,sha256hmac:()=>eE,sha512:()=>eI,sha512hmac:()=>ex,swapBytes32:()=>ts,toArray:()=>D});var y={};f.r(y),f.d(y,{Reader:()=>tN,ReaderUint8Array:()=>tc,Writer:()=>tP,WriterUint8Array:()=>tl,base64ToArray:()=>tv,constantTimeEquals:()=>tU,encode:()=>tk,fromBase58:()=>tx,fromBase58Check:()=>tO,minimallyEncode:()=>t_,toArray:()=>tm,toBase58:()=>tA,toBase58Check:()=>tT,toBase64:()=>tS,toHex:()=>tg,toUTF8:()=>tI,toUint8Array:()=>ty,verifyNotNull:()=>tB,zero2:()=>tu});var m={};f.r(m),f.d(m,{sign:()=>ie,verify:()=>it});var b={};f.r(b),f.d(b,{sign:()=>rA,verify:()=>rT});var w={};f.r(w),f.d(w,{decrypt:()=>rN,encrypt:()=>rP});var v={};f.r(v),f.d(v,{magicHash:()=>rR,sign:()=>rC,verify:()=>rB});var I={};f.r(I),f.d(I,{isHexString:()=>nw,parseWalletOutpoint:()=>nr,specOpThrowReviewActions:()=>nz,validateAbortActionArgs:()=>nA,validateAcquireDirectCertificateArgs:()=>nV,validateAcquireIssuanceCertificateArgs:()=>nL,validateBase64String:()=>ny,validateBasketInsertion:()=>nO,validateCreateActionArgs:()=>nS,validateCreateActionInput:()=>nv,validateCreateActionOptions:()=>nk,validateCreateActionOutput:()=>nI,validateDiscoverByAttributesArgs:()=>nK,validateDiscoverByIdentityKeyArgs:()=>nM,validateInteger:()=>nl,validateInternalizeActionArgs:()=>n_,validateInternalizeOutput:()=>nP,validateListActionsArgs:()=>n$,validateListCertificatesArgs:()=>nF,validateListOutputsArgs:()=>nq,validateOptionalInteger:()=>no,validateOptionalOutpointString:()=>nR,validateOriginator:()=>nN,validateOutpointString:()=>nC,validatePositiveIntegerOrZero:()=>nc,validateProveCertificateArgs:()=>nH,validateRelinquishCertificateArgs:()=>nU,validateRelinquishOutputArgs:()=>nB,validateSatoshis:()=>na,validateSignActionArgs:()=>nx,validateSignActionOptions:()=>nE,validateStringLength:()=>nh,validateWalletPayment:()=>nT});var k={};f.r(k),f.d(k,{getHashFromURL:()=>su,getURLForFile:()=>sd,getURLForHash:()=>sh,isValidURL:()=>sf,normalizeURL:()=>sc});let S="u"<typeof globalThis?void 0:globalThis.Buffer,E=null!=S&&"function"==typeof S.from,x=new Int8Array(256).fill(-1);for(let e=0;e<10;e++)x[48+e]=e;for(let e=0;e<6;e++)x[65+e]=10+e,x[97+e]=10+e;class A{static zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"];static groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5];static groupBases=[0,0,0x2000000,0x290d741,0x1000000,0x2e90edd,0x39aa400,0x267bf47,0x1000000,0x290d741,1e7,0x12959c3,0x222c000,0x3bd7765,7529536,0xadcea1,0x1000000,0x1704f61,0x206fc40,0x2cddcf9,64e6,4084101,5153632,6436343,7962624,9765625,0xb54ba0,0xdaf26b,0x1069c00,0x138f9ad,243e5,0x1b4d89f,0x2000000,0x25528a1,0x2b54a20,0x3216b93,0x39aa400];static wordSize=26;static WORD_SIZE_BIGINT=BigInt(A.wordSize);static WORD_MASK=(1n<<A.WORD_SIZE_BIGINT)-1n;static MAX_SAFE_INTEGER_BIGINT=BigInt(Number.MAX_SAFE_INTEGER);static MIN_SAFE_INTEGER_BIGINT=BigInt(Number.MIN_SAFE_INTEGER);static MAX_IMULN_ARG=0x3ffffff;static MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT=(1n<<53n)-1n;_magnitude=0n;_sign=0;_nominalWordLength=1;red;get negative(){return this._sign}set negative(e){this.assert(0===e||1===e,"Negative property must be 0 or 1"),0n===this._magnitude?this._sign=0:this._sign=+(1===e)}get _computedWordsArray(){if(0n===this._magnitude)return[0];let e=[],t=this._magnitude;for(;t>0n;)e.push(Number(t&A.WORD_MASK)),t>>=A.WORD_SIZE_BIGINT;return e.length>0?e:[0]}get words(){let e=this._computedWordsArray;if(this._nominalWordLength<=e.length)return e;let t=Array(this._nominalWordLength).fill(0);for(let i=0;i<e.length;i++)t[i]=e[i];return t}set words(e){let t=this._sign,i=0n,r=e.length>0?e.length:1;for(let t=r-1;t>=0;t--){let r=e[t]??0;i=i<<A.WORD_SIZE_BIGINT|BigInt(r&Number(A.WORD_MASK))}this._magnitude=i,this._sign=t,this._nominalWordLength=r,this.normSign()}get length(){return Math.max(1,this._nominalWordLength)}static isBN(e){return e instanceof A||null!==e&&"object"==typeof e&&e.constructor?.wordSize===A.wordSize&&Array.isArray(e.words)}static max(e,t){return e.cmp(t)>0?e:t}static min(e,t){return 0>e.cmp(t)?e:t}constructor(e=0,t=10,i="be"){if(this.red=null,null===(e??=0))return void this._initializeState(0n,0);if("bigint"==typeof e){this._initializeState(e<0n?-e:e,+(e<0n)),this.normSign();return}let r=t,n=i;if(("le"===t||"be"===t)&&(n=t,r=10),"number"==typeof e)return void this.initNumber(e,n);if(Array.isArray(e))return void this.initArray(e,n);if("string"==typeof e)return void this._initFromString(e,r,n);0!==e?this.assert(!1,"Unsupported input type for BigNumber constructor"):this._initializeState(0n,0)}_initFromString(e,t,i){"hex"===t&&(t=16),this.assert("number"==typeof t&&t===(0|t)&&t>=2&&t<=36,"Base must be an integer between 2 and 36");let r=e.toString().replace(/\s+/g,""),n=0,s=0;r.startsWith("-")?(n++,s=1):r.startsWith("+")&&n++;let a=r.substring(n);if(0===a.length){this._initializeState(0n,1===s&&r.startsWith("-")?1:0),this.normSign();return}16===t?this._initFromHexString(a,s,i):this._initFromNonHexString(a,t,s,i)}_initFromHexString(e,t,i){if("le"===i){let i=[],r=e;r.length%2!=0&&(r="0"+r);for(let e=0;e<r.length;e+=2){let t=Number.parseInt(r.substring(e,e+2),16);if(Number.isNaN(t))throw Error("Invalid character in "+r);i.push(t)}this.initArray(i,"le"),this._sign=t,this.normSign()}else{let i;try{i=BigInt("0x"+e)}catch(t){throw Error("Invalid character in "+e)}this._initializeState(i,t),this.normSign()}}_initFromNonHexString(e,t,i,r){try{if(this._parseBaseString(e,t),this._sign=i,this.normSign(),"le"===r){let e=this._sign;this.initArray(this.toArray("be"),"le"),this._sign=e,this.normSign()}}catch(e){if(e.message.includes("Invalid character in string")||e.message.includes("Invalid digit for base")||e.message.startsWith("Invalid character:"))throw Error("Invalid character");throw e}}_bigIntToStringInBase(e,t){if(0n===e)return"0";if(t<2||t>36)throw Error("Base must be between 2 and 36");let i="",r=e>0n?e:-e,n=BigInt(t);for(;r>0n;)i="0123456789abcdefghijklmnopqrstuvwxyz"[Number(r%n)]+i,r/=n;return i}_parseBaseString(e,t){if(0===e.length){this._magnitude=0n,this._finishInitialization();return}this._magnitude=0n;let i=BigInt(t),r=A.groupSizes[t],n=BigInt(A.groupBases[t]);(0===r||0n===n)&&(0===(r=Math.floor(Math.log(0x3ffffff)/Math.log(t)))&&(r=1),n=i**BigInt(r));let s=0,a=e.length,o=a%r;if(0===o&&a>0&&(o=r),o>0){let i=e.substring(s,s+o);this._magnitude=BigInt(this._parseBaseWord(i,t)),s+=o}for(;s<a;){let i=e.substring(s,s+r),a=BigInt(this._parseBaseWord(i,t));this._magnitude=this._magnitude*n+a,s+=r}this._finishInitialization()}_parseBaseWord(e,t){let i=0;for(let r=0;r<e.length;r++){let n,s=e.codePointAt(r);if(s>=48&&s<=57)n=s-48;else if(s>=65&&s<=90)n=s-65+10;else if(s>=97&&s<=122)n=s-97+10;else throw Error("Invalid character: "+e[r]);if(n>=t)throw Error("Invalid character");i=i*t+n}return i}_initializeState(e,t){this._magnitude=e,this._sign=0n===e?0:t,this._finishInitialization()}_finishInitialization(){if(0n===this._magnitude)this._nominalWordLength=1,this._sign=0;else{let e=this._magnitude.toString(2).length;this._nominalWordLength=Math.max(1,Math.ceil(e/A.wordSize))}}assert(e,t="Assertion failed"){if(!e)throw Error(t)}initNumber(e,t="be"){if(this.assert(BigInt(Math.abs(e))<=A.MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT,"The number is larger than 2 ^ 53 (unsafe)"),this.assert(e%1==0,"Number must be an integer for BigNumber conversion"),this._initializeState(BigInt(Math.abs(e)),+(e<0)),"le"===t){let e=this._sign,t=this.toArray("be");this.initArray(t,"le"),this._sign=e,this.normSign()}return this}initArray(e,t){if(0===e.length)return this._initializeState(0n,0),this;let i=0n;if("be"===t)for(let t of e)i=i<<8n|BigInt(255&t);else for(let t=e.length-1;t>=0;t--)i=i<<8n|BigInt(255&e[t]);return this._initializeState(i,0),this}copy(e){e._magnitude=this._magnitude,e._sign=this._sign,e._nominalWordLength=this._nominalWordLength,e.red=this.red}static move(e,t){e._magnitude=t._magnitude,e._sign=t._sign,e._nominalWordLength=t._nominalWordLength,e.red=t.red}clone(){let e=new A(0n);return this.copy(e),e}expand(e){return this.assert(e>=0,"Expand size must be non-negative"),this._nominalWordLength=Math.max(this._nominalWordLength,e,1),this}strip(){return this._finishInitialization(),this.normSign()}normSign(){return 0n===this._magnitude&&(this._sign=0),this}inspect(){return(null===this.red?"<BN: ":"<BN-R: ")+this.toString(16)+">"}_getMinimalHex(){return 0n===this._magnitude?"0":this._magnitude.toString(16)}toString(e=10,t=1){if(16===e||"hex"===e){let e=this._getMinimalHex();if(t>1)for("0"!==e&&e.length%2!=0&&(e="0"+e);e.length%t!=0;)e="0"+e;return(this.isNeg()?"-":"")+e}if("number"!=typeof e||e<2||e>36||e%1!=0)throw Error("Base should be an integer between 2 and 36");return this.toBaseString(e,t)}toBaseString(e,t){if(0n===this._magnitude){let e="0";if(t>1)for(;e.length<t;)e="0"+e;return e}let i=A.groupSizes[e],r=BigInt(A.groupBases[e]);(0===i||0n===r)&&(0===(i=Math.floor(Math.log(Number.MAX_SAFE_INTEGER)/Math.log(e)))&&(i=1),r=BigInt(e)**BigInt(i));let n="",s=this._magnitude;for(;s>0n;){let t=s%r;s/=r;let a=this._bigIntToStringInBase(t,e);n=(s>0n?this._zeroPaddedChunk(a,i):a)+n}if(t>0)for(;n.length<t;)n="0"+n;return(1===this._sign?"-":"")+n}_zeroPaddedChunk(e,t){let i=t-e.length;return i<=0?e:i<A.zeros.length?A.zeros[i]+e:"0".repeat(i)+e}toNumber(){let e=this._getSignedValue();if(e>A.MAX_SAFE_INTEGER_BIGINT||e<A.MIN_SAFE_INTEGER_BIGINT)throw Error("Number can only safely store up to 53 bits");return Number(e)}toBigInt(){return this._getSignedValue()}toJSON(){let e=this._getMinimalHex();return(this.isNeg()?"-":"")+e}toArrayLikeGeneric(e,t){let i=this._magnitude,r=t?0:e.length-1,n=t?1:-1;for(let t=0;t<e.length;++t){if(0n===i&&r>=0&&r<e.length)e[r]=0;else if(r>=0&&r<e.length)e[r]=Number(255n&i);else break;i>>=8n,r+=n}}toArray(e="be",t){this.strip();let i=this.byteLength(),r=t??Math.max(1,i);this.assert(i<=r,"byte array longer than desired length"),this.assert(r>0,"Requested array length <= 0");let n=Array(r).fill(0);return 0n===this._magnitude&&r>0?n:0n===this._magnitude&&0===r?[]:(this.toArrayLikeGeneric(n,"le"===e),n)}bitLength(){return 0n===this._magnitude?0:this._magnitude.toString(2).length}static toBitArray(e){let t=e.bitLength();if(0===t)return[];let i=Array(t),r=e._magnitude;for(let e=0;e<t;e++)i[e]=+((r>>BigInt(e)&1n)!==0n);return i}toBitArray(){return A.toBitArray(this)}zeroBits(){if(0n===this._magnitude)return 0;let e=0,t=this._magnitude;for(;(1n&t)===0n&&0n!==t;)e++,t>>=1n;return e}byteLength(){return 0n===this._magnitude?0:Math.ceil(this.bitLength()/8)}_getSignedValue(){return 1===this._sign?-this._magnitude:this._magnitude}_setValueFromSigned(e){e<0n?(this._magnitude=-e,this._sign=1):(this._magnitude=e,this._sign=0),this._finishInitialization(),this.normSign()}toTwos(e){this.assert(e>=0);let t=BigInt(e),i=this._getSignedValue();1===this._sign&&0n!==this._magnitude&&(i=(1n<<t)+i),i&=(1n<<t)-1n;let r=new A(0n);return r._initializeState(i,0),r}fromTwos(e){this.assert(e>=0);let t=BigInt(e),i=this._magnitude;if(e>0&&(i>>t-1n&1n)!==0n&&0===this._sign){let e=new A(0n);return e._setValueFromSigned(i-(1n<<t)),e}return this.clone()}isNeg(){return 1===this._sign&&0n!==this._magnitude}neg(){return this.clone().ineg()}ineg(){return 0n!==this._magnitude&&(this._sign=+(1!==this._sign)),this}_iuop(e,t,i=!1){let r=t(this._magnitude,e._magnitude),n=this._nominalWordLength;return i&&(n=Math.max(this.length,e.length)),this._magnitude=r,this._finishInitialization(),i&&(this._nominalWordLength=Math.max(this._nominalWordLength,n)),this.strip()}iuor(e){return this._iuop(e,(e,t)=>e|t)}iuand(e){return this._iuop(e,(e,t)=>e&t)}iuxor(e){return this._iuop(e,(e,t)=>e^t,!0)}_iop(e,t,i=!1){return this.assert(0===this._sign&&0===e._sign),this._iuop(e,t,i)}ior(e){return this._iop(e,(e,t)=>e|t)}iand(e){return this._iop(e,(e,t)=>e&t)}ixor(e){return this._iop(e,(e,t)=>e^t,!0)}_uop_new(e,t){return this.length>=e.length?this.clone()[t](e):e.clone()[t](this)}or(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuor")}uor(e){return this._uop_new(e,"iuor")}and(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuand")}uand(e){return this._uop_new(e,"iuand")}xor(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuxor")}uxor(e){return this._uop_new(e,"iuxor")}inotn(e){this.assert("number"==typeof e&&e>=0);let t=BigInt(e);this._magnitude=~this._magnitude&(1n<<t)-1n;let i=0===e?1:Math.ceil(e/A.wordSize);return this._nominalWordLength=Math.max(1,i),this.strip(),this._nominalWordLength=Math.max(this._nominalWordLength,Math.max(1,i)),this}notn(e){return this.clone().inotn(e)}setn(e,t){this.assert("number"==typeof e&&e>=0);let i=BigInt(e);1===t||!0===t?this._magnitude|=1n<<i:this._magnitude&=~(1n<<i);let r=Math.floor(e/A.wordSize)+1;return this._nominalWordLength=Math.max(this._nominalWordLength,r),this._finishInitialization(),this.strip()}iadd(e){return this._setValueFromSigned(this._getSignedValue()+e._getSignedValue()),this}add(e){let t=new A(0n);return t._setValueFromSigned(this._getSignedValue()+e._getSignedValue()),t}isub(e){return this._setValueFromSigned(this._getSignedValue()-e._getSignedValue()),this}sub(e){let t=new A(0n);return t._setValueFromSigned(this._getSignedValue()-e._getSignedValue()),t}mul(e){let t=new A(0n);return t._magnitude=this._magnitude*e._magnitude,t._sign=0n===t._magnitude?0:this._sign^e._sign,t._nominalWordLength=this.length+e.length,t.red=null,t.normSign()}imul(e){return this._magnitude*=e._magnitude,this._sign=0n===this._magnitude?0:this._sign^e._sign,this._nominalWordLength=this.length+e.length,this.red=null,this.normSign()}imuln(e){return this.assert("number"==typeof e,"Assertion failed"),this.assert(Math.abs(e)<=A.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()*BigInt(e)),this}muln(e){return this.clone().imuln(e)}sqr(){let e=new A(0n);return e._magnitude=this._magnitude*this._magnitude,e._sign=0,e._nominalWordLength=2*this.length,e.red=null,e}isqr(){return this._magnitude*=this._magnitude,this._sign=0,this._nominalWordLength=2*this.length,this.red=null,this}pow(e){if(this.assert(0===e._sign,"Exponent for pow must be non-negative"),e.isZero())return new A(1n);let t=new A(1n),i=this.clone(),r=e.clone(),n=i.isNeg(),s=r.isOdd();for(n&&i.ineg();!r.isZero();)r.isOdd()&&t.imul(i),i.isqr(),r.iushrn(1);return n&&s&&t.ineg(),t}static normalizeNonNegativeBigInt(e,t){if("number"==typeof e){if(!Number.isFinite(e)||!Number.isInteger(e)||e<0)throw Error(`${t} must be a non-negative integer`);return BigInt(e)}if(e<0n)throw Error(`${t} must be a non-negative integer`);return e}iushln(e){let t=A.normalizeNonNegativeBigInt(e,"Shift bits");return 0n===t?this:(this._magnitude<<=t,this._finishInitialization(),this.strip())}ishln(e){return this.assert(0===this._sign,"ishln requires positive number"),this.iushln(e)}iushrn(e,t,i){let r=A.normalizeNonNegativeBigInt(e,"Shift bits");if(0n===r)return null!=i&&i._initializeState(0n,0),this;if(null!=i){let e=this._magnitude&(1n<<r)-1n;i._initializeState(e,0)}return this._magnitude>>=r,this._finishInitialization(),this.strip()}ishrn(e,t,i){return this.assert(0===this._sign,"ishrn requires positive number"),this.iushrn(e,t,i)}shln(e){return this.clone().ishln(e)}ushln(e){return this.clone().iushln(e)}shrn(e){return this.clone().ishrn(e)}ushrn(e){return this.clone().iushrn(e)}testn(e){return this.assert("number"==typeof e&&e>=0),(this._magnitude>>BigInt(e)&1n)!==0n}imaskn(e){this.assert("number"==typeof e&&e>=0),this.assert(0===this._sign,"imaskn works only with positive numbers");let t=BigInt(e);this._magnitude&=0n===t?0n:(1n<<t)-1n;let i=0===e?1:Math.max(1,Math.ceil(e/A.wordSize));return this._nominalWordLength=i,this._finishInitialization(),this._nominalWordLength=Math.max(this._nominalWordLength,i),this.strip()}maskn(e){return this.clone().imaskn(e)}iaddn(e){return this.assert("number"==typeof e),this.assert(Math.abs(e)<=A.MAX_IMULN_ARG,"num is too large"),this._setValueFromSigned(this._getSignedValue()+BigInt(e)),this}_iaddn(e){return this.iaddn(e)}isubn(e){return this.assert("number"==typeof e),this.assert(Math.abs(e)<=A.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()-BigInt(e)),this}addn(e){return this.clone().iaddn(e)}subn(e){return this.clone().isubn(e)}iabs(){return this._sign=0,this}abs(){return this.clone().iabs()}divmod(e,t,i){if(this.assert(!e.isZero(),"Division by zero"),this.isZero()){let e=new A(0n);return{div:"mod"===t?null:e,mod:"div"===t?null:e}}let r=this._getSignedValue(),n=e._getSignedValue(),s="mod"!==t?r/n:null,a=this._computeMod(r,n,t,i);return{div:this._bigNumberFromSigned(s),mod:this._bigNumberFromSigned(a)}}_computeMod(e,t,i,r){if("div"===i)return null;let n=e%t;return!0===r&&n<0n&&(n+=t<0n?-t:t),n}_bigNumberFromSigned(e){if(null===e)return null;let t=new A(0n);return t._setValueFromSigned(e),t}div(e){return this.divmod(e,"div",!1).div}mod(e){return this.divmod(e,"mod",!1).mod}umod(e){return this.divmod(e,"mod",!0).mod}divRound(e){this.assert(!e.isZero());let t=this._getSignedValue(),i=e._getSignedValue(),r=t/i,n=t%i;if(0n===n){let e=new A(0n);return e._setValueFromSigned(r),e}2n*(n<0n?-n:n)>=(i<0n?-i:i)&&(t>0n&&i>0n||t<0n&&i<0n?r+=1n:r-=1n);let s=new A(0n);return s._setValueFromSigned(r),s}modrn(e){this.assert(0!==e,"Division by zero in modrn");let t=BigInt(Math.abs(e));if(0n===t)throw Error("Division by zero in modrn");let i=this._magnitude%t;return e<0?Number(-i):Number(i)}idivn(e){return this.assert(0!==e),this.assert(Math.abs(e)<=A.MAX_IMULN_ARG,"num is too large"),this._setValueFromSigned(this._getSignedValue()/BigInt(e)),this}divn(e){return this.clone().idivn(e)}egcd(e){this.assert(0===e._sign,"p must not be negative"),this.assert(!e.isZero(),"p must not be zero");let t=this._getSignedValue(),i=e._magnitude,r=1n,n=0n,s=0n,a=1n;for(;0n!==i;){let e=t/i,o=i;i=t%i,t=o,o=n,n=r-e*n,r=o,o=a,a=s-e*a,s=o}let o=new A(0n);o._setValueFromSigned(r);let l=new A(0n);l._setValueFromSigned(s);let c=new A(0n);return c._initializeState(t<0n?-t:t,0),{a:o,b:l,gcd:c}}gcd(e){let t=this._magnitude,i=e._magnitude;if(0n===t){let e=new A(0n);return e._setValueFromSigned(i),e.iabs()}if(0n===i){let e=new A(0n);return e._setValueFromSigned(t),e.iabs()}for(;0n!==i;){let e=t%i;t=i,i=e}let r=new A(0n);return r._initializeState(t,0),r}invm(e){this.assert(!e.isZero()&&0===e._sign,"Modulus for invm must be positive and non-zero");let t=this.egcd(e);if(!t.gcd.eqn(1))throw Error("Inverse does not exist (numbers are not coprime).");return t.a.umod(e)}isEven(){return this._magnitude%2n===0n}isOdd(){return this._magnitude%2n===1n}andln(e){return this.assert(e>=0),Number(this._magnitude&BigInt(e))}bincn(e){this.assert("number"==typeof e&&e>=0);let t=1n<<BigInt(e);return this._setValueFromSigned(this._getSignedValue()+t),this}isZero(){return 0n===this._magnitude}cmpn(e){this.assert(Math.abs(e)<=A.MAX_IMULN_ARG,"Number is too big");let t=this._getSignedValue(),i=BigInt(e);return t<i?-1:+(t>i)}cmp(e){let t=this._getSignedValue(),i=e._getSignedValue();return t<i?-1:+(t>i)}ucmp(e){return this._magnitude<e._magnitude?-1:+(this._magnitude>e._magnitude)}gtn(e){return 1===this.cmpn(e)}gt(e){return 1===this.cmp(e)}gten(e){return this.cmpn(e)>=0}gte(e){return this.cmp(e)>=0}ltn(e){return -1===this.cmpn(e)}lt(e){return -1===this.cmp(e)}lten(e){return 0>=this.cmpn(e)}lte(e){return 0>=this.cmp(e)}eqn(e){return 0===this.cmpn(e)}eq(e){return 0===this.cmp(e)}toRed(e){return this.assert(null==this.red,"Already a number in reduction context"),this.assert(0===this._sign,"toRed works only with positives"),e.convertTo(this).forceRed(e)}fromRed(){return this.assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)}forceRed(e){return this.red=e,this}redAdd(e){return this.assert(this.red,"redAdd works only with red numbers"),this.red.add(this,e)}redIAdd(e){return this.assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)}redSub(e){return this.assert(this.red,"redSub works only with red numbers"),this.red.sub(this,e)}redISub(e){return this.assert(this.red,"redISub works only with red numbers"),this.red.isub(this,e)}redShl(e){return this.assert(this.red,"redShl works only with red numbers"),this.red.shl(this,e)}redMul(e){return this.assert(this.red,"redMul works only with red numbers"),this.red.verify2(this,e),this.red.mul(this,e)}redIMul(e){return this.assert(this.red,"redIMul works only with red numbers"),this.red.verify2(this,e),this.red.imul(this,e)}redSqr(){return this.assert(this.red,"redSqr works only with red numbers"),this.red.verify1(this),this.red.sqr(this)}redISqr(){return this.assert(this.red,"redISqr works only with red numbers"),this.red.verify1(this),this.red.isqr(this)}redSqrt(){return this.assert(this.red,"redSqrt works only with red numbers"),this.red.verify1(this),this.red.sqrt(this)}redInvm(){return this.assert(this.red,"redInvm works only with red numbers"),this.red.verify1(this),this.red.invm(this)}redNeg(){return this.assert(this.red,"redNeg works only with red numbers"),this.red.verify1(this),this.red.neg(this)}redPow(e){return this.assert(null!=this.red&&null==e.red,"redPow(normalNum)"),this.red.verify1(this),this.red.pow(this,e)}static fromHex(e,t){let i="be";return("little"===t||"le"===t)&&(i="le"),new A(e,16,i)}toHex(e=0){if(this.isZero()&&0===e)return"";let t=this._getMinimalHex();"0"!==t&&t.length%2!=0&&(t="0"+t);let i=2*e;for(;t.length<i;)t="0"+t;return(this.isNeg()?"-":"")+t}static fromJSON(e){return new A(e,16)}static fromNumber(e){return new A(e)}static fromString(e,t){return new A(e,t)}static fromSm(e,t="big"){let i;if(0===e.length)return new A(0n);let r=e.slice();"little"===t&&r.reverse();let n=0;if(r.length>0&&(128&r[0])!=0&&(n=1,r[0]&=127),E)i=S.from(r).toString("hex");else for(let e of(i="",r))i+=e<16?"0"+e.toString(16):e.toString(16);let s=0===i.length?0n:BigInt("0x"+i),a=new A(0n);return a._initializeState(s,n),a}toSm(e="big"){let t;if(0n===this._magnitude)return 1===this._sign?[128]:[];let i=this._getMinimalHex();i.length%2!=0&&(i="0"+i);let r=Array(i.length/2);for(let e=0,t=0;e<i.length;e+=2){let n=x[i.codePointAt(e)],s=x[i.codePointAt(e+1)];r[t++]=(15&n)<<4|15&s}return 1===this._sign?(128&r[0])==0?(t=r.slice(),t[0]|=128):t=[128,...r]:t=(128&r[0])==0?r.slice():[0,...r],"little"===e?t.reverse():t}static fromBits(e,t=!1){let i=e>>>24,r=8388607&e,n=(8388608&e)!=0;if(t&&n)throw Error("negative bit set");if(0===i&&0===r){if(n&&t)throw Error("negative bit set for zero value");return new A(0n)}let s=new A(r);return i<=3?s.iushrn((3-i)*8):s.iushln((i-3)*8),n&&s.ineg(),s}toBits(){let e;if(this.strip(),this.isZero()&&!this.isNeg())return 0;let t=this.isNeg(),i=this.abs(),r=i.toArray("be"),n=0;for(;n<r.length-1&&0===r[n];)n++;let s=(r=r.slice(n)).length;if(0!==s||i.isZero()||(r=[0],s=1),i.isZero()&&(s=0,r=[]),0===s)e=0;else if(s<=3){e=0;for(let t=0;t<s;t++)e=e<<8|r[t]}else e=r[0]<<16|r[1]<<8|r[2];(8388608&e)!=0&&s<=255&&(e>>>=8,s++);let a=s<<24|e;return t&&(a|=8388608),a>>>0}static fromScriptNum(e,t=!1,i){if(void 0!==i&&e.length>i)throw Error("script number overflow");if(0===e.length)return new A(0n);if(t&&(127&e.at(-1))==0&&(e.length<=1||(128&e.at(-2))==0))throw Error("non-minimally encoded script number");return A.fromSm(e,"little")}toScriptNum(){return this.toSm("little")}_invmp(e){this.assert(0===e._sign,"p must not be negative for _invmp"),this.assert(!e.isZero(),"p must not be zero for _invmp");let t=this.umod(e),i=e.subn(2);if(null!==t.red)return t.redPow(i);let r=new A(1n),n=t.clone(),s=i.clone();for(;!s.isZero();)s.isOdd()&&(r=r.mul(n).umod(e)),n=n.sqr().umod(e),s.iushrn(1);return r}mulTo(e,t){return t._magnitude=this._magnitude*e._magnitude,t._sign=0n===t._magnitude?0:this._sign^e._sign,t._nominalWordLength=this.length+e.length,t.red=null,t.normSign(),t}}class T{name;p;k;n;tmp;constructor(e,t){this.name=e,this.p=new A(t,16),this.n=this.p.bitLength(),this.k=new A(BigInt(1)).iushln(this.n).isub(this.p),this.tmp=this._tmp()}_tmp(){let e=new A(BigInt(0)),t=Math.ceil(this.n/A.wordSize);return e.expand(Math.max(1,t)),e}ireduce(e){let t;do this.split(e,this.tmp),this.imulK(e),e.iadd(this.tmp),t=e.bitLength();while(t>this.n);let i=t<this.n?-1:e.ucmp(this.p);return 0===i?e.words=[0]:i>0&&e.isub(this.p),e.strip(),e}split(e,t){e.iushrn(this.n,0,t)}imulK(e){return e.imul(this.k)}}class O extends T{constructor(){super("k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}split(e,t){let i=e.words,r=e.length,n=Math.min(r,9),s=Array(n+ +(r>9)).fill(0);for(let e=0;e<n;e++)s[e]=i[e];let a=n;if(r<=9){let i=Array(a);for(let e=0;e<a;++e)i[e]=s[e];t.words=i,e.words=[0];return}let o=i[9];s[a++]=4194303&o;let l=Array(a);for(let e=0;e<a;++e)l[e]=s[e];t.words=l;let c=Array(Math.max(1,r-9)).fill(0),h=0;for(let e=10;e<r;e++){let t=Math.trunc(i[e]);h<c.length&&(c[h++]=(4194303&t)<<4|o>>>22),o=t}o>>>=22,h<c.length?c[h++]=o:0!==o&&c.length;let d=Array(h);for(let e=0;e<h;++e)d[e]=c[e];e.words=d}imulK(e){let t=e.words,i=e.length,r=i+2,n=Array(r).fill(0);for(let e=0;e<i;e++)n[e]=t[e];let s=0;for(let e=0;e<r;e++){let t=Math.trunc(n[e]);s+=977*t,n[e]=0x3ffffff&s,s=64*t+Math.trunc(s/0x4000000)}return e.words=n,e}}class P{prime;m;constructor(e){if("k256"===e){const e=new O;this.m=e.p,this.prime=e}else this.assert(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}assert(e,t="Assertion failed"){if(!e)throw Error(t)}verify1(e){this.assert(0===e.negative,"red works only with positives"),this.assert(e.red,"red works only with red numbers")}verify2(e,t){this.assert((e.negative|t.negative)==0,"red works only with positives"),this.assert(null!=e.red&&e.red===t.red,"red works only with red numbers")}imod(e){return null!=this.prime?this.prime.ireduce(e).forceRed(this):(A.move(e,e.umod(this.m).forceRed(this)),e)}neg(e){return e.isZero()?e.clone():this.m.sub(e).forceRed(this)}add(e,t){this.verify2(e,t);let i=e.clone();return i.iadd(t),i.isub(this.m),i.isNeg()&&i.iadd(this.m),i}iadd(e,t){return this.verify2(e,t),e.iadd(t),e.isub(this.m),e.isNeg()&&e.iadd(this.m),e}sub(e,t){this.verify2(e,t);let i=e.sub(t);return 0>i.cmpn(0)&&i.iadd(this.m),i.forceRed(this)}isub(e,t){this.verify2(e,t);let i=e.isub(t);return 0>i.cmpn(0)&&i.iadd(this.m),i}shl(e,t){return this.verify1(e),this.imod(e.ushln(t))}imul(e,t){return this.verify2(e,t),this.imod(e.imul(t))}mul(e,t){return this.verify2(e,t),this.imod(e.mul(t))}isqr(e){return this.imul(e,e.clone())}sqr(e){return this.mul(e,e)}sqrt(e){if(e.isZero())return e.clone();let t=this.m.andln(3);if(this.assert(t%2==1),3===t){let t=this.m.add(new A(1)).iushrn(2);return this.pow(e,t)}let i=this.m.subn(1),r=0;for(;!i.isZero()&&0===i.andln(1);)r++,i.iushrn(1);this.assert(!i.isZero());let n=new A(1).toRed(this),s=n.redNeg(),a=this.m.subn(1).iushrn(1),o=this.m.bitLength(),l=new A(2*o*o).toRed(this);for(;0!==this.pow(l,a).cmp(s);)l.redIAdd(s);let c=this.pow(l,i),h=this.pow(e,i.addn(1).iushrn(1)),d=this.pow(e,i),u=r;for(;0!==d.cmp(n);){let e=d,t=0;for(;0!==e.cmp(n);t++)e=e.redSqr();this.assert(t<u);let i=this.pow(c,new A(1).iushln(u-t-1));h=h.redMul(i),c=i.redSqr(),d=d.redMul(c),u=t}return h}invm(e){let t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)}pow(e,t){if(this.verify1(e),t.isZero())return new A(1).toRed(this);let i=new A(1).toRed(this),r=e.clone(),n=t.bitLength();for(let e=n-1;e>=0;e--)i=this.sqr(i),t.testn(e)&&(i=this.mul(i,r));return i}convertTo(e){let t=e.umod(this.m);return t===e?t.clone():t}convertFrom(e){let t=e.clone();return t.red=null,t}}class N extends P{shift;r;r2;rinv;minv;constructor(e){super(e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new A(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}convertTo(e){return this.imod(e.ushln(this.shift))}convertFrom(e){let t=this.imod(e.mul(this.rinv));return t.red=null,t}imul(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;let i=e.imul(t),r=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=i.isub(r).iushrn(this.shift),s=n;return n.cmp(this.m)>=0?s=n.isub(this.m):0>n.cmpn(0)&&(s=n.iadd(this.m)),s.forceRed(this)}mul(e,t){if(e.isZero()||t.isZero())return new A(0).forceRed(this);let i=e.mul(t),r=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=i.isub(r).iushrn(this.shift),s=n;return n.cmp(this.m)>=0?s=n.isub(this.m):0>n.cmpn(0)&&(s=n.iadd(this.m)),s.forceRed(this)}invm(e){return this.imod(e._invmp(this.m).mul(this.r2)).forceRed(this)}}class _{curve;type;precomputed;constructor(e){this.curve=new t1,this.type=e,this.precomputed=null}}class R extends _{x;y;z;zOne;constructor(e,t,i){super("jacobian"),null===e&&null===t&&null===i?(this.x=this.curve.one,this.y=this.curve.one,this.z=new A(0)):(A.isBN(e)||(e=new A(e,16)),this.x=e,A.isBN(t)||(t=new A(t,16)),this.y=t,A.isBN(i)||(i=new A(i,16)),this.z=i),null==this.x.red&&(this.x=this.x.toRed(this.curve.red)),null==this.y.red&&(this.y=this.y.toRed(this.curve.red)),null==this.z.red&&(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.isInfinity()&&(this.x=this.curve.one,this.y=this.curve.one,this.z=new A(0).toRed(this.curve.red),this.zOne=!1)}toP(){if(this.isInfinity())return new t0(null,null);let e=this.z.redInvm(),t=e.redSqr();return new t0(this.x.redMul(t),this.y.redMul(t).redMul(e))}neg(){return new R(this.x,this.y.redNeg(),this.z)}add(e){if(this.isInfinity())return e;if(e.isInfinity())return this;let t=e.z.redSqr(),i=this.z.redSqr(),r=this.x.redMul(t),n=e.x.redMul(i),s=this.y.redMul(t.redMul(e.z)),a=e.y.redMul(i.redMul(this.z)),o=r.redSub(n),l=s.redSub(a);if(0===o.cmpn(0))if(0===l.cmpn(0))return this.dbl();else return new R(null,null,null);let c=o.redSqr(),h=c.redMul(o),d=r.redMul(c),u=l.redSqr().redIAdd(h).redISub(d).redISub(d),f=l.redMul(d.redISub(u)).redISub(s.redMul(h));return new R(u,f,this.z.redMul(e.z).redMul(o))}mixedAdd(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;if(null===e.x||null===e.y)throw Error("Point coordinates cannot be null");let t=this.z.redSqr(),i=this.x,r=e.x.redMul(t),n=this.y,s=e.y.redMul(t).redMul(this.z),a=i.redSub(r),o=n.redSub(s);if(0===a.cmpn(0))if(0===o.cmpn(0))return this.dbl();else return new R(null,null,null);let l=a.redSqr(),c=l.redMul(a),h=i.redMul(l),d=o.redSqr().redIAdd(c).redISub(h).redISub(h),u=o.redMul(h.redISub(d)).redISub(n.redMul(c));return new R(d,u,this.z.redMul(a))}dblp(e){if(0===e||this.isInfinity())return this;if(void 0===e)return this.dbl();let t=this;for(let i=0;i<e;i++)t=t.dbl();return t}dbl(){let e,t,i;if(this.isInfinity())return this;if(this.zOne){let r=this.x.redSqr(),n=this.y.redSqr(),s=n.redSqr(),a=this.x.redAdd(n).redSqr().redISub(r).redISub(s);a=a.redIAdd(a);let o=r.redAdd(r).redIAdd(r),l=o.redSqr().redISub(a).redISub(a),c=s.redIAdd(s);c=(c=c.redIAdd(c)).redIAdd(c),e=l,t=o.redMul(a.redISub(l)).redISub(c),i=this.y.redAdd(this.y)}else{let r=this.x.redSqr(),n=this.y.redSqr(),s=n.redSqr(),a=this.x.redAdd(n).redSqr().redISub(r).redISub(s);a=a.redIAdd(a);let o=r.redAdd(r).redIAdd(r),l=o.redSqr(),c=s.redIAdd(s);c=(c=c.redIAdd(c)).redIAdd(c),e=l.redISub(a).redISub(a),t=o.redMul(a.redISub(e)).redISub(c),i=(i=this.y.redMul(this.z)).redIAdd(i)}return new R(e,t,i)}eq(e){if("affine"===e.type)return this.eq(e.toJ());if(this===e||this.isInfinity()&&e.isInfinity())return!0;if(this.isInfinity()!==e.isInfinity())return!1;let t=this.z.redSqr(),i=e.z.redSqr();if(0!==this.x.redMul(i).redISub(e.x.redMul(t)).cmpn(0))return!1;let r=t.redMul(this.z),n=i.redMul(e.z);return 0===this.y.redMul(n).redISub(e.y.redMul(r)).cmpn(0)}eqXToP(e){let t=this.z.redSqr(),i=e.toRed(this.curve?.red).redMul(t);if(0===this.x.cmp(i))return!0;let r=e.clone();if(this.curve?.redN==null)throw Error("Curve or redN is not initialized.");let n=this.curve.redN.redMul(t);for(;0>r.cmp(this.curve.p)&&(r.iadd(this.curve.n),!(r.cmp(this.curve.p)>=0));)if(i.redIAdd(n),0===this.x.cmp(i))return!0;return!1}inspect(){return this.isInfinity()?"<EC JPoint Infinity>":"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"}isInfinity(){return 0===this.z.cmpn(0)}}let C=/^[0-9a-fA-F]*$/;function B(e){if("string"!=typeof e)throw TypeError("Invalid hex string");if(0!==e.length&&!C.test(e))throw Error("Invalid hex string")}let U=(e,t="Hash assertion failed")=>{if(!e)throw Error(t)};class F{pending;pendingTotal;blockSize;outSize;endian;_delta8;_delta32;padLength;hmacStrength;constructor(e,t,i,r){this.pending=null,this.pendingTotal=0,this.blockSize=e,this.outSize=t,this.hmacStrength=i,this.padLength=r/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}_update(e,t){throw Error("Not implemented")}_digest(){throw Error("Not implemented")}_digestHex(){throw Error("Not implemented")}update(e,t){if(e=D(e,t),null==this.pending?this.pending=e:this.pending=this.pending.concat(e),this.pendingTotal+=e.length,this.pending.length>=this._delta8){let t=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-t,e.length),0===this.pending.length&&(this.pending=null),e=function(e,t,i){let r=t-0;U(r%4==0);let n=Array(r/4);for(let t=0,r=0;t<n.length;t++,r+=4){let s;s="big"===i?e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3]:e[r+3]<<24|e[r+2]<<16|e[r+1]<<8|e[r],n[t]=s>>>0}return n}(e,e.length-t,this.endian);for(let t=0;t<e.length;t+=this._delta32)this._update(e,t)}return this}digest(){return this.update(this._pad()),U(null===this.pending),this._digest()}digestHex(){return this.update(this._pad()),U(null===this.pending),this._digestHex()}_pad(){let e,t=this.pendingTotal;if(!Number.isSafeInteger(t)||t<0)throw Error("Message too long for this hash function");let i=this._delta8,r=i-(t+this.padLength)%i,n=Array(r+this.padLength);for(n[0]=128,e=1;e<r;e++)n[e]=0;let s=this.padLength,a=1n<<BigInt(8*s),o=8n*BigInt(t);if(o>=a)throw Error("Message too long for this hash function");if("big"===this.endian){let t=Array(s);for(let e=s-1;e>=0;e--)t[e]=Number(255n&o),o>>=8n;for(let i=0;i<s;i++)n[e++]=t[i]}else for(let t=0;t<s;t++)n[e++]=Number(255n&o),o>>=8n;return n}}function D(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];if("string"==typeof e)return"hex"===t?function(e){B(e);let t=function(e){if(B(e),0===e.length)return"";let t=e.toLowerCase();return t.length%2!=0&&(t="0"+t),t}(e),i=[];for(let e=0;e<t.length;e+=2)i.push(Number.parseInt(t[e]+t[e+1],16));return i}(e):function(e){let t=[];for(let i=0;i<e.length;i++)i=function(e,t,i){let r=e.charCodeAt(t);return r<128?(i.push(r),t):r<2048?(i.push(r>>6|192,63&r|128),t):(64512&e.charCodeAt(t))!=55296||t<0||t+1>=e.length||(64512&e.charCodeAt(t+1))!=56320?(i.push(r>>12|224,r>>6&63|128,63&r|128),t):(r=65536+((1023&r)<<10)+(1023&e.charCodeAt(t+1)),i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128),t+1)}(e,i,t);return t}(e);let i=[];for(let t=0;t<e.length;t++)i[t]=Math.trunc(e[t]);return i}function L(e){return ts(e)}function V(e,t){let i="";for(let r of e)"little"===t&&(r=ts(r)),i+=function(e){if(7===e.length)return"0"+e;if(6===e.length)return"00"+e;if(5===e.length)return"000"+e;if(4===e.length)return"0000"+e;if(3===e.length)return"00000"+e;else if(2===e.length)return"000000"+e;else if(1===e.length)return"0000000"+e;else return e}(r.toString(16));return i}let H="u"<typeof globalThis?void 0:globalThis.Buffer,M=null!=H&&"function"==typeof H.from,K="0123456789abcdef",q=Array(256);for(let e=0;e<q.length;e++)q[e]=K[e>>4&15]+K[15&e];let $=(()=>{let e="u"<typeof globalThis?void 0:globalThis.process,t=e?.getBuiltinModule;if("function"==typeof t)try{let i=t.call(e,"node:crypto");if(null!=i)return i}catch{}try{if("function"==typeof require)return require("node:crypto")}catch{}})();function z(e,t){return e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):Uint8Array.from(D(e,t))}function W(e){return"string"==typeof e?z(e,"hex"):z(e)}function j(e,t,i){null!=e?e.update(i):null!=t&&t.update(i)}function G(e,t){return null!=e?Array.from(e.digest()):null!=t?Array.from(t.digest()):[]}function X(e,t){if(null!=e)return e.digest("hex");if(null!=t){var i=t.digest();if(M)return H.from(i).toString("hex");let e=Array(i.length);for(let t=0;t<i.length;t++)e[t]=q[i[t]];return e.join("")}return""}function Y(e){let t=$?.createHash;if("function"==typeof t)try{return t(e)}catch{return}}function J(e,t){let i=$?.createHmac;if("function"==typeof i)try{return i(e,t)}catch{return}}function Z(e,t,i){let r=Y(e);if(null!=r)return r.update(z(t,i)),r.digest()}function Q(e,t,i,r){let n=J(e,W(t));if(null!=n)return n.update(z(i,r)),n.digest()}function ee(e,t){let i=Array(4*e.length);for(let r=0,n=0;r<e.length;r++,n+=4){let s=e[r];"big"===t?(i[n]=s>>>24,i[n+1]=s>>>16&255,i[n+2]=s>>>8&255,i[n+3]=255&s):(i[n+3]=s>>>24,i[n+2]=s>>>16&255,i[n+1]=s>>>8&255,i[n]=255&s)}return i}function et(e,t){return e>>>t|e<<32-t}function ei(e,t){return e<<t|e>>>32-t}function er(e,t){return e+t>>>0}let en=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],es=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],ea=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],eo=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11];function el(e,t,i,r){return e<=15?t^i^r:e<=31?t&i|~t&r:e<=47?(t|~i)^r:e<=63?t&r|i&~r:t^(i|~r)}class ec extends F{h;constructor(){super(512,160,192,64),this.endian="little",this.h=[0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0],this.endian="little"}_update(e,t){var i,r,n,s,a,o;let l,c=this.h[0],h=this.h[1],d=this.h[2],u=this.h[3],f=this.h[4],p=c,g=h,y=d,m=u,b=f;for(let w=0;w<80;w++){l=er(ei((i=c,r=el(w,h,d,u),i+r+e[en[w]+t]+((a=w)<=15?0:a<=31?0x5a827999:a<=47?0x6ed9eba1:a<=63?0x8f1bbcdc:0xa953fd4e)>>>0),ea[w]),f),c=f,f=u,u=ei(d,10),d=h,h=l,l=er(ei((n=p,s=el(79-w,g,y,m),n+s+e[es[w]+t]+((o=w)<=15?0x50a28be6:o<=31?0x5c4dd124:o<=47?0x6d703ef3:0x7a6d76e9*!!(o<=63))>>>0),eo[w]),b),p=b,b=m,m=ei(y,10),y=g,g=l}l=this.h[1]+d+m>>>0,this.h[1]=this.h[2]+u+b>>>0,this.h[2]=this.h[3]+f+p>>>0,this.h[3]=this.h[4]+c+g>>>0,this.h[4]=this.h[0]+h+y>>>0,this.h[0]=l}_digest(){return ee(this.h,"little")}_digestHex(){return V(this.h,"little")}}class eh{h;native;constructor(){this.native=Y("sha256"),null==this.native&&(this.h=new e2)}update(e,t){return j(this.native,this.h,z(e,t)),this}digest(){return G(this.native,this.h)}digestHex(){return X(this.native,this.h)}}class ed extends F{h;W;k;constructor(){super(512,160,80,64),this.k=[0x5a827999,0x6ed9eba1,0x8f1bbcdc,0xca62c1d6],this.h=[0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0],this.W=Array(80)}_update(e,t){let i,r=this.W;for(void 0===t&&(t=0),i=0;i<16;i++)r[i]=e[t+i];for(;i<r.length;i++)r[i]=ei(r[i-3]^r[i-8]^r[i-14]^r[i-16],1);let n=this.h[0],s=this.h[1],a=this.h[2],o=this.h[3],l=this.h[4];for(i=0;i<r.length;i++){var c,h,d,u,f,p,g,y,m;let e=Math.trunc(i/20),t=(u=ei(n,5),c=s,h=a,d=o,f=0===e?(p=c)&h^~p&d:1===e||3===e?c^h^d:2===e?(g=c)&(y=h)^g&(m=d)^y&m:0,u+f+l+r[i]+this.k[e]>>>0);l=o,o=a,a=ei(s,30),s=n,n=t}this.h[0]=er(this.h[0],n),this.h[1]=er(this.h[1],s),this.h[2]=er(this.h[2],a),this.h[3]=er(this.h[3],o),this.h[4]=er(this.h[4],l)}_digest(){return ee(this.h,"big")}_digestHex(){return V(this.h,"big")}}class eu{h;native;constructor(){this.native=Y("sha512"),null==this.native&&(this.h=new te)}update(e,t){return j(this.native,this.h,z(e,t)),this}digest(){return G(this.native,this.h)}digestHex(){return X(this.native,this.h)}}class ef{h;native;blockSize=64;outSize=32;constructor(e){const t=W(e);this.native=J("sha256",t),null==this.native&&(this.h=new ti(e8,t))}update(e,t){return j(this.native,this.h,z(e,t)),this}digest(){return G(this.native,this.h)}digestHex(){return X(this.native,this.h)}}class ep{inner;outer;blockSize=64;constructor(e){let t;for((e=D(e,"hex")).length>this.blockSize&&(e=new ed().update(e).digest()),t=e.length;t<this.blockSize;t++)e.push(0);for(t=0;t<e.length;t++)e[t]^=54;for(this.inner=new ed().update(e),t=0;t<e.length;t++)e[t]^=106;this.outer=new ed().update(e)}update(e,t){return this.inner.update(e,t),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}}class eg{h;native;blockSize=128;outSize=32;constructor(e){const t=W(e);this.native=J("sha512",t),null==this.native&&(this.h=new ti(tt,t))}update(e,t){return j(this.native,this.h,z(e,t)),this}digest(){return G(this.native,this.h)}digestHex(){return X(this.native,this.h)}}function ey(e,t){let i=Z("sha256",e,t);return null!=i?i:new e2().update(z(e,t)).digest()}function em(e,t){return Z("ripemd160",e,t)}let eb=(e,t)=>{let i=em(e,t);return null!=i?Array.from(i):new ec().update(e,t).digest()},ew=(e,t)=>new ed().update(e,t).digest(),ev=(e,t)=>Array.from(ey(e,t)),eI=(e,t)=>{let i;return Array.from(null!=(i=Z("sha512",e,t))?i:new te().update(z(e,t)).digest())},ek=(e,t)=>Array.from(ey(ey(e,t))),eS=(e,t)=>{let i=ey(e,t),r=em(i);return null!=r?Array.from(r):new ec().update(i).digest()},eE=(e,t,i)=>{let r=Q("sha256",e,t,i);return null!=r?Array.from(r):new ef(e).update(t,i).digest()},ex=(e,t,i)=>{let r=Q("sha512",e,t,i);return null!=r?Array.from(r):new eg(e).update(t,i).digest()};function eA(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`positive integer expected, got ${e}`)}function eT(e,...t){if(!(e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length)){let i=t.join(",");throw Error(`Uint8Array expected of length ${i}, got length=${e.length}`)}}function eO(e){if("function"!=typeof e||"function"!=typeof e.create)throw TypeError("Hash should be wrapped by utils.createHasher");eA(e.outputLen),eA(e.blockLen)}function eP(e,t=!0){if(!0===e.destroyed)throw Error("Hash instance has been destroyed");if(t&&!0===e.finished)throw Error("Hash#digest() has already been called")}function eN(...e){for(let t of e)t.fill(0)}function e_(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function eR(e){return"string"==typeof e&&(e=eC(e)),eT(e),e}function eC(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function eB(e){return"string"==typeof e&&(e=eC(e)),eT(e),e}class eU{}function eF(e){let t=t=>e().update(eR(t)).digest(),i=e();return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=()=>e(),t}let eD=BigInt(0x100000000-1),eL=BigInt(32),eV=(e,t,i)=>e>>>i,eH=(e,t,i)=>e<<32-i|t>>>i,eM=(e,t,i)=>e>>>i|t<<32-i,eK=(e,t,i)=>e<<32-i|t>>>i,eq=(e,t,i)=>e<<64-i|t>>>i-32,e$=(e,t,i)=>e>>>i-32|t<<64-i;function ez(e,t,i,r){let n=(t>>>0)+(r>>>0);return{h:e+i+(n/0x100000000|0)|0,l:0|n}}let eW=(e,t,i)=>(e>>>0)+(t>>>0)+(i>>>0),ej=(e,t,i,r)=>t+i+r+(e/0x100000000|0)|0,eG=(e,t,i,r)=>(e>>>0)+(t>>>0)+(i>>>0)+(r>>>0),eX=(e,t,i,r,n)=>t+i+r+n+(e/0x100000000|0)|0,eY=(e,t,i,r,n)=>(e>>>0)+(t>>>0)+(i>>>0)+(r>>>0)+(n>>>0),eJ=(e,t,i,r,n,s)=>t+i+r+n+s+(e/0x100000000|0)|0;class eZ extends eU{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,i,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=r,this.buffer=new Uint8Array(e),this.view=e_(this.buffer)}update(e){eP(this),eT(e=eR(e));let{view:t,buffer:i,blockLen:r}=this,n=e.length;for(let s=0;s<n;){let a=Math.min(r-this.pos,n-s);if(a===r){let t=e_(e);for(;r<=n-s;s+=r)this.process(t,s);continue}i.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){eP(this);eT(e);let t=this.outputLen;if(e.length<t)throw Error(`digestInto() expects output buffer of length at least ${t}`);this.finished=!0;let{buffer:i,view:r,blockLen:n,isLE:s}=this,{pos:a}=this;i[a++]=128,eN(this.buffer.subarray(a)),this.padOffset>n-a&&(this.process(r,0),a=0);for(let e=a;e<n;e++)i[e]=0;(function(e,t,i,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,i,r);let n=BigInt(32),s=BigInt(0xffffffff),a=Number(i>>n&s),o=Number(i&s),l=4*!!r,c=4*!r;e.setUint32(t+l,a,r),e.setUint32(t+c,o,r)})(r,n-8,BigInt(8*this.length),s),this.process(r,0);let o=e_(e),l=this.outputLen;if(l%4!=0)throw Error("_sha2: outputLen should be aligned to 32bit");let c=l/4,h=this.get();if(c>h.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,h[e],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){(e||=new this.constructor).set(...this.get());let{blockLen:t,buffer:i,length:r,finished:n,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=n,e.length=r,e.pos=a,r%t!=0&&e.buffer.set(i),e}clone(){return this._cloneInto()}}let eQ=Uint32Array.from([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),e0=Uint32Array.from([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0xfc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x6ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]),e1=new Uint32Array(64);class e2 extends eZ{A=0|eQ[0];B=0|eQ[1];C=0|eQ[2];D=0|eQ[3];E=0|eQ[4];F=0|eQ[5];G=0|eQ[6];H=0|eQ[7];constructor(e=32){super(64,e,8,!1)}get(){let{A:e,B:t,C:i,D:r,E:n,F:s,G:a,H:o}=this;return[e,t,i,r,n,s,a,o]}set(e,t,i,r,n,s,a,o){this.A=0|e,this.B=0|t,this.C=0|i,this.D=0|r,this.E=0|n,this.F=0|s,this.G=0|a,this.H=0|o}process(e,t){var i,r,n,s,a,o,l,c,h;for(let i=0;i<16;i++,t+=4)e1[i]=e.getUint32(t);for(let e=16;e<64;e++){let t=e1[e-15],i=e1[e-2],r=et(t,7)^et(t,18)^t>>>3,n=et(i,17)^et(i,19)^i>>>10;e1[e]=er(er(r,e1[e-7]),er(n,e1[e-16]))}let{A:d,B:u,C:f,D:p,E:g,F:y,G:m,H:b}=this;for(let e=0;e<64;e++){let t=(n=b,s=et(i=g,6)^et(i,11)^et(i,25),a=(r=g)&y^~r&m,n+s+a+e0[e]+e1[e]>>>0),w=er(et(o=d,2)^et(o,13)^et(o,22),(l=d)&(c=u)^l&(h=f)^c&h);b=m,m=y,y=g,g=er(p,t),p=f,f=u,u=d,d=er(t,w)}this.A=er(this.A,d),this.B=er(this.B,u),this.C=er(this.C,f),this.D=er(this.D,p),this.E=er(this.E,g),this.F=er(this.F,y),this.G=er(this.G,m),this.H=er(this.H,b)}roundClean(){eN(e1)}destroy(){eN(this.buffer),this.set(0,0,0,0,0,0,0,0)}}let e8=eF(()=>new e2),e3=Uint32Array.from([0x6a09e667,0xf3bcc908,0xbb67ae85,0x84caa73b,0x3c6ef372,0xfe94f82b,0xa54ff53a,0x5f1d36f1,0x510e527f,0xade682d1,0x9b05688c,0x2b3e6c1f,0x1f83d9ab,0xfb41bd6b,0x5be0cd19,0x137e2179]),e5=function(e,t=!1){let i=e.length,r=new Uint32Array(i),n=new Uint32Array(i);for(let s=0;s<i;s++){let{h:i,l:a}=function(e,t=!1){return t?{h:Number(e&eD),l:Number(e>>eL&eD)}:{h:0|Number(e>>eL&eD),l:0|Number(e&eD)}}(e[s],t);r[s]=i,n[s]=a}return[r,n]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(BigInt)),e6=e5[0],e4=e5[1],e9=new Uint32Array(80),e7=new Uint32Array(80);class te extends eZ{Ah=0|e3[0];Al=0|e3[1];Bh=0|e3[2];Bl=0|e3[3];Ch=0|e3[4];Cl=0|e3[5];Dh=0|e3[6];Dl=0|e3[7];Eh=0|e3[8];El=0|e3[9];Fh=0|e3[10];Fl=0|e3[11];Gh=0|e3[12];Gl=0|e3[13];Hh=0|e3[14];Hl=0|e3[15];constructor(e=64){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:i,Bl:r,Ch:n,Cl:s,Dh:a,Dl:o,Eh:l,El:c,Fh:h,Fl:d,Gh:u,Gl:f,Hh:p,Hl:g}=this;return[e,t,i,r,n,s,a,o,l,c,h,d,u,f,p,g]}set(e,t,i,r,n,s,a,o,l,c,h,d,u,f,p,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|i,this.Bl=0|r,this.Ch=0|n,this.Cl=0|s,this.Dh=0|a,this.Dl=0|o,this.Eh=0|l,this.El=0|c,this.Fh=0|h,this.Fl=0|d,this.Gh=0|u,this.Gl=0|f,this.Hh=0|p,this.Hl=0|g}process(e,t){for(let i=0;i<16;i++,t+=8)e9[i]=e.getUint32(t),e7[i]=e.getUint32(t+4);for(let e=16;e<80;e++){let t=0|e9[e-15],i=0|e7[e-15],r=eM(t,i,1)^eM(t,i,8)^eV(t,i,7),n=eK(t,i,1)^eK(t,i,8)^eH(t,i,7),s=0|e9[e-2],a=0|e7[e-2],o=eM(s,a,19)^eq(s,a,61)^eV(s,a,6),l=eG(n,eK(s,a,19)^e$(s,a,61)^eH(s,a,6),e7[e-7],e7[e-16]),c=eX(l,r,o,e9[e-7],e9[e-16]);e9[e]=0|c,e7[e]=0|l}let{Ah:i,Al:r,Bh:n,Bl:s,Ch:a,Cl:o,Dh:l,Dl:c,Eh:h,El:d,Fh:u,Fl:f,Gh:p,Gl:g,Hh:y,Hl:m}=this;for(let e=0;e<80;e++){let t=eM(h,d,14)^eM(h,d,18)^eq(h,d,41),b=eK(h,d,14)^eK(h,d,18)^e$(h,d,41),w=h&u^~h&p,v=eY(m,b,d&f^~d&g,e4[e],e7[e]),I=eJ(v,y,t,w,e6[e],e9[e]),k=0|v,S=eM(i,r,28)^eq(i,r,34)^eq(i,r,39),E=eK(i,r,28)^e$(i,r,34)^e$(i,r,39),x=i&n^i&a^n&a,A=r&s^r&o^s&o;y=0|p,m=0|g,p=0|u,g=0|f,u=0|h,f=0|d,({h:h,l:d}=ez(0|l,0|c,0|I,0|k)),l=0|a,c=0|o,a=0|n,o=0|s,n=0|i,s=0|r;let T=eW(E,A,k);i=ej(T,S,x,I),r=0|T}({h:i,l:r}=ez(i,r,this.Ah,this.Al)),({h:n,l:s}=ez(n,s,this.Bh,this.Bl)),({h:a,l:o}=ez(a,o,this.Ch,this.Cl)),({h:l,l:c}=ez(l,c,this.Dh,this.Dl)),({h:h,l:d}=ez(h,d,this.Eh,this.El)),({h:u,l:f}=ez(u,f,this.Fh,this.Fl)),({h:p,l:g}=ez(p,g,this.Gh,this.Gl)),({h:y,l:m}=ez(y,m,this.Hh,this.Hl)),this.set(i,r,n,s,a,o,l,c,h,d,u,f,p,g,y,m)}roundClean(){eN(e9,e7)}destroy(){eN(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}let tt=eF(()=>new te);class ti extends eU{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){super(),eO(e);const i=eR(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw TypeError("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,n=new Uint8Array(r);n.set(i.length>r?e.create().update(i).digest():i);for(let e=0;e<n.length;e++)n[e]^=54;this.iHash.update(n),this.oHash=e.create();for(let e=0;e<n.length;e++)n[e]^=106;this.oHash.update(n),eN(n)}update(e){return eP(this),this.iHash.update(e),this}digestInto(e){eP(this),eT(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:i,finished:r,destroyed:n,blockLen:s,outputLen:a}=this;return e.finished=r,e.destroyed=n,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash??void 0),e.iHash=i._cloneInto(e.iHash??void 0),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}let tr=(e,t,i)=>new ti(e,t).update(i).digest();function tn(e,t,i,r,n="sha512"){if("sha512"!==n)throw Error("Only sha512 is supported in this PBKDF2 implementation");let s=$?.pbkdf2Sync;return"function"==typeof s?Array.from(s(z(e),z(t),i,r,n)):Array.from(function(e,t,i,r){let n;eO(e);let{c:s,dkLen:a}=Object.assign({dkLen:32},r);if(eA(s),eA(a),s<1)throw Error("iterations (c) should be >= 1");let o=eB(t),l=eB(i),c=new Uint8Array(a),h=tr.create(e,o),d=h._cloneInto().update(l),u=new Uint8Array(4),f=e_(u),p=new Uint8Array(h.outputLen);for(let e=1,t=0;t<a;e++,t+=h.outputLen){let i=c.subarray(t,t+h.outputLen);f.setInt32(0,e,!1),(n=d._cloneInto(n)).update(u).digestInto(p),i.set(p.subarray(0,i.length));for(let e=1;e<s;e++){h._cloneInto(n).update(p).digestInto(p);for(let e=0;e<i.length;e++)i[e]^=p[e]}}return h.destroy(),d.destroy(),null!=n&&n.destroy(),eN(p),c}(tt,Uint8Array.from(e),Uint8Array.from(t),{c:i,dkLen:r}))}function ts(e){return(e>>>24|e>>>8&65280|e<<8&0xff0000|(255&e)<<24)>>>0}tr.create=(e,t)=>new ti(e,t);let ta=(i=new Uint32Array(t=new ArrayBuffer(4)),r=new Uint8Array(t),i[0]=0x1020304,4===r[0]);function to(e){return ta?ts(e):e>>>0}class tl{buffer;pos;capacity;constructor(e,t=256){if(null!=e&&e.length>0&&(t=Math.max(t,e.reduce((e,t)=>e+t.length,0))),this.buffer=new Uint8Array(t),this.pos=0,this.capacity=t,null!=e)for(const t of e)this.write(t)}getLength(){return this.pos}toUint8Array(){return this.buffer.slice(0,this.pos)}toArray(){return Array.from(this.toUint8Array())}toUint8ArrayZeroCopy(){return this.buffer.subarray(0,this.pos)}ensureCapacity(e){if(this.pos+e>this.capacity){let t=2*this.capacity;for(;this.pos+e>t;)t*=2;let i=new Uint8Array(t);i.set(this.buffer),this.buffer=i,this.capacity=t}}write(e){let t=e instanceof Uint8Array?e:new Uint8Array(e);return this.ensureCapacity(t.length),this.buffer.set(t,this.pos),this.pos+=t.length,this}writeReverse(e){let t=e instanceof Uint8Array?e:new Uint8Array(e);this.ensureCapacity(t.length);for(let e=t.length-1;e>=0;e--)this.buffer[this.pos]=t[e],this.pos+=1;return this}writeUInt8(e){return this.ensureCapacity(1),this.buffer[this.pos]=255&e,this.pos+=1,this}writeInt8(e){return this.writeUInt8(e),this}writeUInt16LE(e){return this.ensureCapacity(2),this.buffer[this.pos]=255&e,this.buffer[this.pos+1]=e>>8&255,this.pos+=2,this}writeUInt16BE(e){return this.ensureCapacity(2),this.buffer[this.pos]=e>>8&255,this.buffer[this.pos+1]=255&e,this.pos+=2,this}writeInt16LE(e){return this.writeUInt16LE(65535&e),this}writeInt16BE(e){return this.writeUInt16BE(65535&e),this}writeUInt32LE(e){return this.ensureCapacity(4),this.buffer[this.pos]=255&e,this.buffer[this.pos+1]=e>>8&255,this.buffer[this.pos+2]=e>>16&255,this.buffer[this.pos+3]=e>>24&255,this.pos+=4,this}writeUInt32BE(e){return this.ensureCapacity(4),this.buffer[this.pos]=e>>24&255,this.buffer[this.pos+1]=e>>16&255,this.buffer[this.pos+2]=e>>8&255,this.buffer[this.pos+3]=255&e,this.pos+=4,this}writeInt32LE(e){return this.writeUInt32LE(e>>>0),this}writeInt32BE(e){return this.writeUInt32BE(e>>>0),this}writeUInt64BEBn(e){let t=e.toArray("be",8);return this.write(t),this}writeUInt64LEBn(e){let t=e.toArray("be",8);return this.writeReverse(t),this}writeUInt64LE(e){let t=new A(e).toArray("be",8);return this.writeReverse(t),this}writeVarIntNum(e){let t=tP.varIntNum(e);return this.write(t),this}writeVarIntBn(e){let t=tP.varIntBn(e);return this.write(t),this}reset(){this.pos=0}}class tc{bin;pos;length;static makeReader(e,t=0){if(e instanceof Uint8Array)return new tc(e,t);if(Array.isArray(e))return new tN(e,t);throw Error("ReaderUint8Array.makeReader: bin must be Uint8Array or number[]")}constructor(e=new Uint8Array(0),t=0){if(e instanceof Uint8Array)this.bin=e;else if(Array.isArray(e))this.bin=new Uint8Array(e);else throw TypeError("ReaderUint8Array constructor: bin must be Uint8Array or number[]");this.pos=t,this.length=this.bin.length}eof(){return this.pos>=this.length}read(e=this.length){let t=this.pos,i=this.pos+e;return this.pos=i,this.bin.slice(t,i)}readReverse(e=this.length){let t=new Uint8Array(e);for(let i=0;i<e;i++)t[i]=this.bin[this.pos+e-1-i];return this.pos+=e,t}readUInt8(){let e=this.bin[this.pos];return this.pos+=1,e}readInt8(){let e=this.bin[this.pos];return this.pos+=1,(128&e)==0?e:e-256}readUInt16BE(){let e=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,e}readInt16BE(){let e=this.readUInt16BE();return(32768&e)==0?e:e-65536}readUInt16LE(){let e=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,e}readInt16LE(){let e=this.readUInt16LE();return(32768&e)==0?e:e-65536}readUInt32BE(){let e=0x1000000*this.bin[this.pos]+(this.bin[this.pos+1]<<16|this.bin[this.pos+2]<<8|this.bin[this.pos+3]);return this.pos+=4,e}readInt32BE(){let e=this.readUInt32BE();return(0x80000000&e)==0?e:e-0x100000000}readUInt32LE(){let e=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,e}readInt32LE(){let e=this.readUInt32LE();return(0x80000000&e)==0?e:e-0x100000000}readUInt64BEBn(){let e=new A(Array.from(this.bin.slice(this.pos,this.pos+8)));return this.pos=this.pos+8,e}readUInt64LEBn(){return new A(Array.from(this.readReverse(8)))}readInt64LEBn(){let e=new A(2).pow(new A(63)),t=new A(2).pow(new A(64)),i=new A(Array.from(this.readReverse(8)));return i.gte(e)&&(i=i.sub(t)),i}readVarIntNum(e=!0){let t,i=this.readUInt8();switch(i){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if((t=e?this.readInt64LEBn():this.readUInt64LEBn()).lte(new A(2).pow(new A(53))))return t.toNumber();throw Error("number too large to retain precision - use readVarIntBn");default:return i}}readVarInt(){switch(this.bin[this.pos]){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}}readVarIntBn(){let e=this.readUInt8();switch(e){case 253:return new A(this.readUInt16LE());case 254:return new A(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new A(e)}}}let th="u"<typeof globalThis?void 0:globalThis.Buffer,td=null!=th&&"function"==typeof th.from,tu=e=>e.length%2==1?"0"+e:e,tf="0123456789abcdef",tp=Array(256);for(let e=0;e<256;e++)tp[e]=tf[e>>4&15]+tf[15&e];let tg=e=>{if(td)return th.from(e).toString("hex");if(0===e.length)return"";let t=Array(e.length);for(let i=0;i<e.length;i++)t[i]=tp[255&e[i]];return t.join("")},ty=(e,t)=>e instanceof Uint8Array?e:new Uint8Array(tm(e,t)),tm=(e,t)=>{if(Array.isArray(e))return e.slice();if(void 0===e)return[];if("string"!=typeof e)return Array.from(e,e=>Math.trunc(e));switch(t){case"hex":return tw(e);case"base64":return tv(e);default:var i;return i=e,Array.from(new TextEncoder().encode(i))}},tb=new Int8Array(256).fill(-1);for(let e=0;e<10;e++)tb[48+e]=e;for(let e=0;e<6;e++)tb[65+e]=10+e,tb[97+e]=10+e;let tw=e=>{B(e);let t=e.length%2==0?e:"0"+e;if(td)return Array.from(th.from(t,"hex"));let i=Array(t.length/2),r=0;for(let e=0;e<t.length;e+=2){let n=tb[t.codePointAt(e)],s=tb[t.codePointAt(e+1)];i[r++]=n<<4|s}return i};function tv(e){if("string"!=typeof e)throw TypeError("msg must be a string");let t=e.trim().replaceAll(/[\r\n\t\f\v ]+/g,""),i=(t=t.replaceAll("-","+").replaceAll("_","/")).indexOf("=");if(-1!==i){let e=t.slice(i);if(!/^={1,2}$/.test(e)||t.slice(0,i).includes("="))throw Error("Invalid base64 padding");t=t.slice(0,i)}let r=[],n=0,s=0;for(let e=0;e<t.length;e++){let i=t.codePointAt(e),a=-1;if(i>=65&&i<=90)a=i-65;else if(i>=97&&i<=122)a=i-97+26;else if(i>=48&&i<=57)a=i-48+52;else if(43===i)a=62;else if(47===i)a=63;else throw Error(`Invalid base64 character at index ${e}`);for(n=n<<6|a,s+=6;s>=8;)s-=8,r.push(n>>s&255),n&=(1<<s)-1}return r}let tI=e=>new TextDecoder().decode(new Uint8Array(e)),tk=(e,t)=>{switch(t){case"hex":return tg(e);case"utf8":return tI(e);default:return e}};function tS(e){let t,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r="";for(t=0;t<e.length;t+=3){let n=e[t],s=t+1<e.length?e[t+1]:0,a=t+2<e.length?e[t+2]:0,o=n>>2,l=(3&n)<<4|s>>4,c=(15&s)<<2|a>>6,h=63&a;r+=i.charAt(o)+i.charAt(l),r+=t+1<e.length?i.charAt(c):"=",r+=t+2<e.length?i.charAt(h):"="}return r}let tE="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",tx=e=>{let t;if(""===e||"string"!=typeof e)throw Error(`Expected base58 string but got “${e}”`);let i=e.match(/[IOl0]/gmu);if(null!==i)throw Error(`Invalid base58 character “${i.join("")}”`);let r=e.match(/^1+/gmu),n=null===r?0:r[0].length,s=(e.length-n)*(Math.log(58)/Math.log(256))+1>>>0;return[...new Uint8Array([...new Uint8Array(n),...(e.match(/./gmu)??[]).map(e=>tE.indexOf(e)).reduce((e,t)=>e=e.map(e=>{let i=58*e+t;return t=i>>8,i}),new Uint8Array(s)).reverse().filter((t=!1,e=>t=t||e))])]},tA=e=>{let t=Array(256).fill(-1);for(let e=0;e<tE.length;++e)t[tE.codePointAt(e)]=e;let i=[];for(let r of e){let e=r;for(let r=0;r<i.length;++r){let n=(t[i[r]]<<8)+e;i[r]=tE.codePointAt(n%58),e=Math.trunc(n/58)}for(;0!==e;)i.push(tE.codePointAt(e%58)),e=Math.trunc(e/58)}for(let t of e)if(0===t)i.push(49);else break;return i.reverse(),String.fromCodePoint(...i)},tT=(e,t=[0])=>{let i=ek([...t,...e]);return tA(i=[...t,...e,...i.slice(0,4)])},tO=(e,t,i=1)=>{let r=tx(e),n=r.slice(0,i),s=r.slice(i,-4),a=[...n,...s];return a=ek(a),r.slice(-4).forEach((e,t)=>{if(e!==a[t])throw Error("Invalid checksum")}),"hex"===t&&(n=tg(n),s=tg(s)),{prefix:n,data:s}};class tP{bufs;length;constructor(e){for(const t of(this.bufs=e??[],this.length=0,this.bufs))this.length+=t.length}getLength(){return this.length}toUint8Array(){let e=new Uint8Array(this.length),t=0;for(let i of this.bufs)e.set(i,t),t+=i.length;return e}toArray(){let e=Array(this.length),t=0;for(let i of this.bufs)if(i instanceof Uint8Array)for(let r of i)e[t++]=r;else for(let r of i)e[t++]=r;return e}toHex(){return this.toArray().map(e=>e.toString(16).padStart(2,"0")).join("")}write(e){return this.bufs.push(e),this.length+=e.length,this}writeReverse(e){let t=Array(e.length);for(let i=0;i<t.length;i++)t[i]=e[e.length-1-i];return this.write(t)}writeUInt8(e){let t=[,];return t[0]=255&e,this.write(t),this}writeInt8(e){return this.writeUInt8(e)}writeUInt16BE(e){return this.write([e>>8&255,255&e])}writeInt16BE(e){return this.writeUInt16BE(65535&e)}writeUInt16LE(e){return this.write([255&e,e>>8&255])}writeInt16LE(e){return this.writeUInt16LE(65535&e)}writeUInt32BE(e){return this.write([e>>24&255,e>>16&255,e>>8&255,255&e])}writeInt32BE(e){return this.writeUInt32BE(e>>>0)}writeUInt32LE(e){return this.write([255&e,e>>8&255,e>>16&255,e>>24&255])}writeInt32LE(e){return this.writeUInt32LE(e>>>0)}writeUInt64BEBn(e){let t=e.toArray("be",8);return this.write(t),this}writeUInt64LEBn(e){let t=e.toArray("be",8);return this.writeReverse(t),this}writeUInt64LE(e){if(-1===e)this.write(Array(8).fill(255));else{let t=new A(e).toArray("be",8);this.writeReverse(t)}return this}writeVarIntNum(e){let t=tP.varIntNum(e);return this.write(t),this}writeVarIntBn(e){let t=tP.varIntBn(e);return this.write(t),this}static varIntNum(e){let t;if(e<0)return this.varIntBn(new A(e));if(e<253)t=[e];else if(e<65536)t=[253,255&e,e>>8&255];else if(e<0x100000000)t=[254,255&e,e>>8&255,e>>16&255,e>>24&255];else{let i=0|e,r=0|Math.floor(e/0x100000000);t=[255,255&i,i>>8&255,i>>16&255,i>>24&255,255&r,r>>8&255,r>>16&255,r>>24&255]}return t}static varIntBn(e){let t;if(e.isNeg()&&(e=e.add(tC)),e.ltn(253))t=[e.toNumber()];else if(e.ltn(65536)){let i=e.toNumber();t=[253,255&i,i>>8&255]}else if(e.lt(new A(0x100000000))){let i=e.toNumber();t=[254,255&i,i>>8&255,i>>16&255,i>>24&255]}else{let i=new tP;i.writeUInt8(255),i.writeUInt64LEBn(e),t=i.toArray()}return t}}class tN{bin;pos;length;constructor(e=[],t=0){this.bin=e,this.pos=t,this.length=e.length}eof(){return this.pos>=this.length}read(e=this.length){let t=this.pos,i=this.pos+e;return this.pos=i,this.bin.slice(t,i)}readReverse(e=this.length){let t=Array(e);for(let i=0;i<e;i++)t[i]=this.bin[this.pos+e-1-i];return this.pos+=e,t}readUInt8(){let e=this.bin[this.pos];return this.pos+=1,e}readInt8(){let e=this.bin[this.pos];return this.pos+=1,(128&e)==0?e:e-256}readUInt16BE(){let e=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,e}readInt16BE(){let e=this.readUInt16BE();return(32768&e)==0?e:e-65536}readUInt16LE(){let e=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,e}readInt16LE(){let e=this.readUInt16LE();return(32768&e)==0?e:e-65536}readUInt32BE(){let e=0x1000000*this.bin[this.pos]+(this.bin[this.pos+1]<<16|this.bin[this.pos+2]<<8|this.bin[this.pos+3]);return this.pos+=4,e}readInt32BE(){let e=this.readUInt32BE();return(0x80000000&e)==0?e:e-0x100000000}readUInt32LE(){let e=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,e}readInt32LE(){let e=this.readUInt32LE();return(0x80000000&e)==0?e:e-0x100000000}readUInt64BEBn(){let e=new A(this.bin.slice(this.pos,this.pos+8));return this.pos=this.pos+8,e}readUInt64LEBn(){return new A(this.readReverse(8))}readInt64LEBn(){let e=new A(this.readReverse(8));return e.gte(tR)&&(e=e.sub(tC)),e}readVarIntNum(e=!0){let t,i=this.readUInt8();switch(i){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if((t=e?this.readInt64LEBn():this.readUInt64LEBn()).lte(new A(2).pow(new A(53))))return t.toNumber();throw Error("number too large to retain precision - use readVarIntBn");default:return i}}readVarInt(){switch(this.bin[this.pos]){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}}readVarIntBn(){let e=this.readUInt8();switch(e){case 253:return new A(this.readUInt16LE());case 254:return new A(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new A(e)}}}let t_=e=>{if(0===e.length)return e;let t=e.at(-1);if((127&t)!=0)return e;if(1===e.length)return[];if((128&e.at(-2))!=0)return e;for(let i=e.length-1;i>0;i--)if(0!==e[i-1])if((128&e[i-1])==0)return e[i-1]|=t,e.slice(0,i);else return e[i]=t,e.slice(0,i+1);return[]},tR=new A(2).pow(new A(63)),tC=new A(2).pow(new A(64));function tB(e,t="Expected a valid value, but got undefined or null."){if(null==e)throw Error(t);return e}function tU(e,t){if(e.length!==t.length)return!1;let i=0;for(let r=0;r<e.length;r++)i|=e[r]^t[r];return 0===i}function tF(e,t,i){let r=-e,n=(t.X^i.X)&r,s=(t.Y^i.Y)&r,a=(t.Z^i.Z)&r;t.X^=n,i.X^=n,t.Y^=s,i.Y^=s,t.Z^=a,i.Z^=a}let tD=(1n<<256n)-1n;function tL(e){let t=e>>256n;return t=(e=(e&tD)+(t<<32n)+977n*t)>>256n,(e=(e&tD)+(t<<32n)+977n*t)>=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn&&(e-=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn),e}let tV=e=>tL((e%0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn+0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn)%0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn),tH=(e,t)=>e>=t?e-t:0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn-(t-e),tM=(e,t)=>tL(e*t),tK=e=>{let t=1n,i=0n,r=tV(e),n=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn;for(;r>1n;){let e=n/r;[t,i]=[i-t*e,t],[r,n]=[n-r*e,r]}return tV(t)},tq=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn+1n>>2n,t$=BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),tz=BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),tW=new Map,tj=e=>{let{X:t,Y:i,Z:r}=e;if(0n===i)return{X:0n,Y:1n,Z:0n};let n=tM(i,i),s=tM(4n,tM(t,n)),a=tM(3n,tM(t,t)),o=tH(tM(a,a),tM(2n,s)),l=tH(tM(a,tH(s,o)),tM(8n,tM(n,n)));return{X:o,Y:l,Z:tM(2n,tM(i,r))}},tG=(e,t)=>{if(0n===e.Z)return t;if(0n===t.Z)return e;let i=tM(e.Z,e.Z),r=tM(t.Z,t.Z),n=tM(e.X,r),s=tM(t.X,i),a=tM(e.Y,tM(r,t.Z)),o=tM(t.Y,tM(i,e.Z)),l=tH(s,n),c=tH(o,a);if(0n===l)return 0n===c?tj(e):{X:0n,Y:1n,Z:0n};let h=tM(l,l),d=tM(l,h),u=tM(n,h),f=tH(tH(tM(c,c),d),tM(2n,u)),p=tH(tM(c,tH(u,f)),tM(a,d));return{X:f,Y:p,Z:tM(l,tM(e.Z,t.Z))}},tX=e=>0n===e.Z?e:{X:e.X,Y:0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn-e.Y,Z:e.Z},tY=(e,t,i=5)=>{let r=`${i}:${t.x.toString(16)}:${t.y.toString(16)}`,n=tW.get(r);if(void 0===n){let e=1<<i-1;n=Array(e);let s={X:t.x,Y:t.y,Z:1n};n[0]=s;let a=tj(s);for(let t=1;t<e;t++)n[t]=tG(n[t-1],a);tW.set(r,n)}let s=[],a=1n<<BigInt(i),o=a>>1n,l=e;for(;l>0n;)if((1n&l)===0n)s.push(0),l>>=1n;else{let e=l&a-1n;e>o&&(e-=a),s.push(Number(e)),l-=e,l>>=1n}let c={X:0n,Y:1n,Z:0n};for(let e=s.length-1;e>=0;e--){c=tj(c);let t=s[e];if(0!==t){let e=Math.abs(t)>>1;c=tG(c,t>0?n[e]:tX(n[e]))}}return c},tJ=e=>{let t=e%0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;return t<0n&&(t+=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n),t},tZ=(e,t)=>tJ(e*t),tQ=e=>{let t=1n,i=0n,r=tJ(e),n=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;for(;r>1n;){let e=n/r;[t,i]=[i-t*e,t],[r,n]=[n-r*e,r]}return tJ(t)};class t0 extends _{x;y;inf;static _assertOnCurve(e){if(!e.validate())throw Error("Invalid point");return e}static fromDER(e){if((4===e[0]||6===e[0]||7===e[0])&&e.length-1==64){if(6===e[0]){if(e.at(-1)%2!=0)throw Error("Point string value is wrong length")}else if(7===e[0]&&e.at(-1)%2!=1)throw Error("Point string value is wrong length");let t=new t0(e.slice(1,33),e.slice(33,65));return t0._assertOnCurve(t)}if((2===e[0]||3===e[0])&&e.length-1==32)return t0._assertOnCurve(t0.fromX(e.slice(1,33),3===e[0]));throw Error("Unknown point format")}static fromString(e){let t=tm(e,"hex");return t0._assertOnCurve(t0.fromDER(t))}static fromX(e,t){var i;let r,n,s=A.isBN(e)?BigInt("0x"+e.toString(16)):"string"==typeof e?BigInt("0x"+e):Array.isArray(e)?BigInt("0x"+tg(e)):BigInt(e),a=(n=((e,t)=>{let i=1n;for(e=tV(e);t>0n;)(1n&t)!==0n&&(i=tM(i,e)),e=tM(e,e),t>>=1n;return i})(i=tL(tM(tM(r=s=tV(s),r),s)+7n),tq),tM(n,n)!==tV(i)?null:n);if(null===a)throw Error("Invalid point");let o=a;(1n&o)!==(t?1n:0n)&&(o=tH(0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,o));let l=new A(s.toString(16),16),c=new A(o.toString(16),16);return t0._assertOnCurve(new t0(l,c))}static fromJSON(e,t){"string"==typeof e&&(e=JSON.parse(e));let i=new t0(e[0],e[1],t);if(i=t0._assertOnCurve(i),"object"!=typeof e[2]||null===e[2])return i;let r=e[2],n=e=>{let i=new t0(e[0],e[1],t);return t0._assertOnCurve(i)};return i.precomputed={beta:null,doubles:"object"==typeof r.doubles&&null!==r.doubles?{step:r.doubles.step,points:[i].concat(r.doubles.points.map(n))}:void 0,naf:"object"==typeof r.naf&&null!==r.naf?{wnd:r.naf.wnd,points:[i].concat(r.naf.points.map(n))}:void 0},i}constructor(e,t,i=!0){super("affine"),this.precomputed=null,null===e&&null===t?(this.x=null,this.y=null,this.inf=!0):(A.isBN(e)||(e=new A(e,16)),this.x=e,A.isBN(t)||(t=new A(t,16)),this.y=t,i&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),null===this.x.red&&(this.x=this.x.toRed(this.curve.red)),null===this.y.red&&(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}validate(){if(this.inf||null==this.x||null==this.y)return!1;try{let e,t=BigInt("0x"+this.x.fromRed().toString(16)),i=BigInt("0x"+this.y.fromRed().toString(16)),r=tM(i,i),n=(e=tM(tM(t,t),t),tL(e+7n));return r===n}catch{return!1}}encode(e=!0,t){let i;if(this.inf)return"hex"===t?"00":[0];let r=this.curve.p.byteLength(),n=this.getX().toArray("be",r);return(i=e?[this.getY().isEven()?2:3].concat(n):[4].concat(n,this.getY().toArray("be",r)),"hex"===t)?tg(i):i}toString(){return this.encode(!0,"hex")}toJSON(){return null==this.precomputed?[this.x,this.y]:[this.x,this.y,"object"==typeof this.precomputed&&null!==this.precomputed?{doubles:null==this.precomputed.doubles?void 0:{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)},naf:null==this.precomputed.naf?void 0:{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}}:void 0]}inspect(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+(this.x?.fromRed()?.toString(16,2)??"undefined")+" y: "+(this.y?.fromRed()?.toString(16,2)??"undefined")+">"}isInfinity(){return this.inf}add(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e)||this.x?.cmp(e.x??new A(0))===0)return new t0(null,null);let t=tG({X:BigInt("0x"+this.x.fromRed().toString(16)),Y:BigInt("0x"+this.y.fromRed().toString(16)),Z:1n},{X:BigInt("0x"+e.x.fromRed().toString(16)),Y:BigInt("0x"+e.y.fromRed().toString(16)),Z:1n});if(0n===t.Z)return new t0(null,null);let i=tK(t.Z),r=tM(i,i),n=tM(t.X,r),s=tM(t.Y,tM(r,i));return new t0(n.toString(16),s.toString(16))}dbl(){if(this.inf)return this;if(null===this.x||null===this.y)throw Error("Point coordinates cannot be null");let e=BigInt("0x"+this.x.fromRed().toString(16)),t=BigInt("0x"+this.y.fromRed().toString(16));if(0n===t)return new t0(null,null);let i=tj({X:e,Y:t,Z:1n}),r=tK(i.Z),n=tM(r,r),s=tM(i.X,n),a=tM(i.Y,tM(n,r));return new t0(s.toString(16),a.toString(16))}getX(){return(this.x??new A(0)).fromRed()}getY(){return(this.y??new A(0)).fromRed()}mul(e){let t,i;if(A.isBN(e)||(e=new A(e,16)),this.inf)return this;let r=e.isNeg(),n=BigInt("0x"+(r?e.neg():e).toString(16));if(0n===(n=tV(n))||0n===n)return new t0(null,null);if(null===this.x||null===this.y)throw Error("Point coordinates cannot be null");this===this.curve.g?(t=t$,i=tz):(t=BigInt("0x"+this.x.fromRed().toString(16)),i=BigInt("0x"+this.y.fromRed().toString(16)));let s=tY(n,{x:t,y:i});if(0n===s.Z)return new t0(null,null);let a=tK(s.Z),o=tM(a,a),l=tM(s.X,o),c=tM(s.Y,tM(o,a)),h=new t0(new A(l.toString(16),16),new A(c.toString(16),16));return r?h.neg():h}mulCT(e){if(A.isBN(e)||(e=new A(e,16)),this.inf)return new t0(null,null);let t=e.isNeg(),i=BigInt("0x"+(t?e.neg():e).toString(16));if(0n===(i=tV(i)))return new t0(null,null);let r=this===this.curve.g?t$:BigInt("0x"+this.getX().toString(16)),n=this===this.curve.g?tz:BigInt("0x"+this.getY().toString(16)),s={X:0n,Y:1n,Z:0n},a={X:r,Y:n,Z:1n};for(let e of i.toString(2)){let t="1"===e?1n:0n;tF(t,s,a),a=tG(s,a),tF(t,s=tj(s),a)}if(0n===s.Z)return new t0(null,null);let o=tK(s.Z),l=tM(o,o),c=tM(s.X,l),h=tM(s.Y,tM(l,o)),d=new t0(c.toString(16),h.toString(16));return t?d.neg():d}mulAdd(e,t,i){return this._endoWnafMulAdd([this,t],[e,i])}jmulAdd(e,t,i){return this._endoWnafMulAdd([this,t],[e,i],!0)}eq(e){return this===e||this.inf===e.inf&&(this.inf||0===(this.x??new A(0)).cmp(e.x??new A(0))&&0===(this.y??new A(0)).cmp(e.y??new A(0)))}neg(e){if(this.inf)return this;let t=new t0(this.x,(this.y??new A(0)).redNeg());if(!0===e&&null!=this.precomputed){let e=this.precomputed;t.precomputed={naf:null==e.naf?void 0:{wnd:e.naf.wnd,points:e.naf.points.map(e=>e.neg())},doubles:null==e.doubles?void 0:{step:e.doubles.step,points:e.doubles.points.map(e=>e.neg())},beta:void 0}}return t}dblp(e){let t=this;for(let i=0;i<e;i++)t=t.dbl();return t}toJ(){return this.inf?new R(null,null,null):new R(this.x,this.y,this.curve.one)}_getBeta(){if("object"!=typeof this.curve.endo)return;let e=this.precomputed;if("object"==typeof e&&null!==e&&"object"==typeof e.beta&&null!==e.beta)return e.beta;let t=new t0((this.x??new A(0)).redMul(this.curve.endo.beta),this.y);if(null!=e){let i=this.curve,r=e=>{if(null===e.x)throw Error("p.x is null");if(void 0===i.endo||null===i.endo)throw Error("curve.endo is undefined");return new t0(e.x.redMul(i.endo.beta),e.y)};e.beta=t,t.precomputed={beta:null,naf:null==e.naf?void 0:{wnd:e.naf.wnd,points:e.naf.points.map(r)},doubles:null==e.doubles?void 0:{step:e.doubles.step,points:e.doubles.points.map(r)}}}return t}_fixedNafMul(e){if("object"!=typeof this.precomputed||null===this.precomputed)throw Error("_fixedNafMul requires precomputed values for the point");let t=this._getDoubles(),i=this.curve.getNAF(e,1,this.curve._bitLength),r=(1<<t.step+1)-(t.step%2==0?2:1);r/=3;let n=[];for(let e=0;e<i.length;e+=t.step){let r=0;for(let n=e+t.step-1;n>=e;n--)r=(r<<1)+i[n];n.push(r)}let s=new R(null,null,null),a=new R(null,null,null);for(let e=r;e>0;e--){for(let i=0;i<n.length;i++){let r=n[i];r===e?a=a.mixedAdd(t.points[i]):r===-e&&(a=a.mixedAdd(t.points[i].neg()))}s=s.add(a)}return s.toP()}_wnafMulAdd(e,t,i,r,n){let s=this.curve._wnafT1.map(e=>e.toNumber()),a=this.curve._wnafT2.map(()=>[]),o=this.curve._wnafT3.map(()=>[]),l=0;for(let i=0;i<r;i++){let r=t[i]._getNAFPoints(e);s[i]=r.wnd,a[i]=r.points}for(let e=r-1;e>=1;e-=2){let r=e-1,n=e;if(1!==s[r]||1!==s[n]){o[r]=this.curve.getNAF(i[r],s[r],this.curve._bitLength),o[n]=this.curve.getNAF(i[n],s[n],this.curve._bitLength),l=Math.max(o[r].length,l),l=Math.max(o[n].length,l);continue}let c=[t[r],null,null,t[n]];0===(t[r].y??new A(0)).cmp(t[n].y??new A(0))?(c[1]=t[r].add(t[n]),c[2]=t[r].toJ().mixedAdd(t[n].neg())):0===(t[r].y??new A(0)).cmp((t[n].y??new A(0)).redNeg())?(c[1]=t[r].toJ().mixedAdd(t[n]),c[2]=t[r].add(t[n].neg())):(c[1]=t[r].toJ().mixedAdd(t[n]),c[2]=t[r].toJ().mixedAdd(t[n].neg()));let h=[-3,-1,-5,-7,0,7,5,1,3],d=this.curve.getJSF(i[r],i[n]);l=Math.max(d[0].length,l),o[r]=Array(l),o[n]=Array(l);for(let e=0;e<l;e++){let t=Math.trunc(d[0][e]),i=Math.trunc(d[1][e]);o[r][e]=h[(t+1)*3+(i+1)],o[n][e]=0,a[r]=c}}let c=new R(null,null,null),h=this.curve._wnafT4;for(let e=l;e>=0;e--){let t=0;for(;e>=0;){let i=!0;for(let t=0;t<r;t++)h[t]=new A("number"==typeof o[t][e]?o[t][e]:0),h[t].isZero()||(i=!1);if(!i)break;t++,e--}if(e>=0&&t++,c=c.dblp(t),e<0)break;let i=new A(1),n=new A(2);for(let e=0;e<r;e++){let t,r=h[e];0!==r.cmpn(0)&&(c="affine"===(t=r.isNeg()?a[e][r.neg().sub(i).div(n).toNumber()].neg():a[e][r.sub(i).div(n).toNumber()]).type?c.mixedAdd(t):c.add(t))}}for(let e=0;e<r;e++)a[e]=[];return!0===n?c:c.toP()}_endoWnafMulAdd(e,t,i){let r,n=Array(2*e.length),s=Array(2*e.length);for(r=0;r<e.length;r++){let i=this.curve._endoSplit(t[r]),a=e[r],o=a._getBeta()??new t0(null,null);0!==i.k1.negative&&(i.k1.ineg(),a=a.neg(!0)),0!==i.k2.negative&&(i.k2.ineg(),o=o.neg(!0)),n[2*r]=a,n[2*r+1]=o,s[2*r]=i.k1,s[2*r+1]=i.k2}let a=this._wnafMulAdd(1,n,s,2*r,i);for(let e=0;e<2*r;e++)n[e]=null,s[e]=null;return a}_hasDoubles(e){if(null==this.precomputed)return!1;let t=this.precomputed.doubles;return"object"==typeof t&&t.points.length>=Math.ceil((e.bitLength()+1)/t.step)}_getDoubles(e,t){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.doubles&&null!==this.precomputed.doubles)return this.precomputed.doubles;let i=[this],r=this;for(let n=0;n<(t??0);n+=e??1){for(let t=0;t<(e??1);t++)r=r.dbl();i.push(r)}return{step:e??1,points:i}}_getNAFPoints(e){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.naf&&null!==this.precomputed.naf)return this.precomputed.naf;let t=[this],i=(1<<e)-1,r=1===i?null:this.dbl();for(let e=1;e<i;e++)null!==r&&(t[e]=t[e-1].add(r));return{wnd:e,points:t}}}class t1{p;red;redN;zero;one;two;g;n;a;b;tinv;zeroA;threeA;endo;_endoWnafT1;_endoWnafT2;_wnafT1;_wnafT2;_wnafT3;_wnafT4;_bitLength;static assert(e,t="Elliptic curve assertion failed"){if(!e)throw Error(t)}getNAF(e,t,i){let r=Array(Math.max(e.bitLength(),i)+1);r.fill(0);let n=1<<t+1,s=e.clone();for(let e=0;e<r.length;e++){let t,i=s.andln(n-1);s.isOdd()?(t=i>(n>>1)-1?(n>>1)-i:i,s.isubn(t)):t=0,r[e]=t,s.iushrn(1)}return r}getJSF(e,t){let i=[[],[]];e=e.clone(),t=t.clone();let r=0,n=0;for(;e.cmpn(-r)>0||t.cmpn(-n)>0;){let s,a,o=e.andln(3)+r&3,l=t.andln(3)+n&3;if(3===o&&(o=-1),3===l&&(l=-1),(1&o)==0)s=0;else{let t=e.andln(7)+r&7;s=(3===t||5===t)&&2===l?-o:o}if(i[0].push(s),(1&l)==0)a=0;else{let e=t.andln(7)+n&7;a=(3===e||5===e)&&2===o?-l:l}i[1].push(a),2*r===s+1&&(r=1-r),2*n===a+1&&(n=1-n),e.iushrn(1),t.iushrn(1)}return i}static cachedProperty(e,t,i){let r="_"+t;e.prototype[t]=function(){return void 0===this[r]&&(this[r]=i.call(this)),this[r]}}static parseBytes(e){return"string"==typeof e?tm(e,"hex"):e}static intFromLE(e){return new A(e,"hex","le")}constructor(){if(void 0!==e)return e;e=this;const t={prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",{doubles:{step:4,points:[["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a","f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"],["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508","11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"],["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739","d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"],["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640","4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"],["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c","4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"],["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda","96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"],["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa","5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"],["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0","cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"],["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d","9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"],["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d","e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"],["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1","9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"],["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0","5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"],["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047","10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"],["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862","283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"],["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7","7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"],["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd","56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"],["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83","7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"],["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a","53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"],["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8","bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"],["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d","4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"],["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725","7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"],["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754","4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"],["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c","17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"],["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6","6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"],["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39","c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"],["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891","893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"],["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b","febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"],["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03","2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"],["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d","eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"],["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070","7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"],["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4","e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"],["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da","662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"],["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11","1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"],["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e","efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"],["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41","2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"],["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef","67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"],["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8","db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"],["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d","648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"],["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96","35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"],["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd","ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"],["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5","9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"],["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266","40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"],["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71","34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"],["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac","c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"],["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751","1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"],["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e","493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"],["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241","c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"],["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3","be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"],["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f","4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"],["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19","aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"],["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be","b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"],["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9","6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"],["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2","8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"],["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13","7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"],["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c","ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"],["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba","2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"],["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151","e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"],["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073","d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"],["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458","38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"],["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b","69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"],["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366","d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"],["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa","40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"],["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0","620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"],["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787","7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"],["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e","ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]]},naf:{wnd:7,points:[["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"],["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4","d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"],["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"],["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe","cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"],["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"],["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8","ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"],["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e","581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"],["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34","4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"],["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c","85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"],["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5","321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"],["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f","2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"],["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714","73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"],["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729","a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"],["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db","2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"],["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4","e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"],["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5","b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"],["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479","2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"],["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d","80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"],["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f","1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"],["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb","d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"],["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9","eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"],["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963","758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"],["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74","958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"],["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530","e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"],["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b","5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"],["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247","cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"],["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1","cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"],["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120","4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"],["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435","91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"],["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18","673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"],["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8","59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"],["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb","3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"],["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f","55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"],["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143","efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"],["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba","e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"],["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45","f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"],["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a","744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"],["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e","c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"],["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8","e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"],["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c","30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"],["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519","e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"],["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab","100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"],["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca","ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"],["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf","8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"],["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610","68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"],["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4","f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"],["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c","d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"],["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940","edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"],["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980","a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"],["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3","66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"],["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf","9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"],["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63","4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"],["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448","fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"],["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf","5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"],["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5","8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"],["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6","8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"],["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5","5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"],["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99","f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"],["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51","f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"],["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5","42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"],["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5","204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"],["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997","4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"],["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881","73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"],["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5","39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"],["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66","d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"],["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726","ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"],["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede","6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"],["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94","60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"],["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31","3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"],["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51","b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"],["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252","ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"],["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5","cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"],["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b","6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"],["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4","322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"],["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f","6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"],["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889","2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"],["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246","b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"],["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984","998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"],["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a","b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"],["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030","bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"],["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197","6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"],["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593","c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"],["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef","21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"],["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38","60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"],["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a","49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"],["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111","5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"],["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502","7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"],["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea","be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"],["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26","8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"],["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986","39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"],["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e","62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"],["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4","25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"],["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda","ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"],["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859","cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"],["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f","f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"],["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c","6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"],["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942","fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"],["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a","1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"],["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80","5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"],["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d","438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"],["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1","cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"],["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63","c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"],["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352","6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"],["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193","ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"],["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00","9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"],["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58","ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"],["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7","d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"],["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8","c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"],["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e","67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"],["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d","cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"],["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b","299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"],["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f","f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"],["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6","462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"],["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297","62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"],["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a","7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"],["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c","ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"],["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52","4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"],["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb","bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"],["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065","bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"],["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917","603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"],["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9","cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"],["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3","553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"],["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57","712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"],["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66","ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"],["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8","9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"],["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721","9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"],["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180","4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]]}}]};this.p=new A(t.p,16),this.red=new P(t.prime),this.zero=new A(0).toRed(this.red),this.one=new A(1).toRed(this.red),this.two=new A(2).toRed(this.red),this.n=new A(t.n,16),this.g=t0.fromJSON(t.g,t.gRed),this._wnafT1=[,,,,],this._wnafT2=[,,,,],this._wnafT3=[,,,,],this._wnafT4=[,,,,],this._bitLength=this.n.bitLength(),this.redN=this.n.toRed(this.red),this.a=new A(t.a,16).toRed(this.red),this.b=new A(t.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(t),this._endoWnafT1=[,,,,],this._endoWnafT2=[,,,,]}_getEndomorphism(e){let t,i,r;if(this.zeroA&&1===this.p.modrn(3)){if(void 0===e.beta){let e=this._getEndoRoots(this.p);if(null===e)throw Error("Failed to get endomorphism roots for beta.");t=(t=0>e[0].cmp(e[1])?e[0]:e[1]).toRed(this.red)}else t=new A(e.beta,16).toRed(this.red);if(void 0===e.lambda){let e=this._getEndoRoots(this.n);if(null===e)throw Error("Failed to get endomorphism roots for lambda.");if(null==this.g)throw Error("Curve generator point (g) is not defined.");let r=this.g.mul(e[0])?.x,n=null==this.g.x?void 0:this.g.x.redMul(t);if(null!=r&&null!=n&&0===r.cmp(n))i=e[0];else{if(i=e[1],null==this.g)throw Error("Curve generator point (g) is not defined.");let r=this.g.mul(i)?.x,n=null==this.g.x?void 0:this.g.x.redMul(t);if(null==r||null==n)throw Error("Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.");t1.assert(0===r.cmp(n),"Lambda selection does not match computed beta.")}}else i=new A(e.lambda,16);return r="object"==typeof e.basis&&null!==e.basis?e.basis.map(function(e){return{a:new A(e.a,16),b:new A(e.b,16)}}):this._getEndoBasis(i),{beta:t,lambda:i,basis:r}}}_getEndoRoots(e){let t=e===this.p?this.red:new N(e),i=new A(2).toRed(t).redInvm(),r=i.redNeg(),n=new A(3).toRed(t).redNeg().redSqrt().redMul(i);return[r.redAdd(n).fromRed(),r.redSub(n).fromRed()]}_getEndoBasis(e){let t,i,r,n,s,a,o=this.n.ushrn(Math.floor(this.n.bitLength()/2)),l=e,c=this.n.clone(),h=new A(1),d=new A(0),u=new A(0),f=new A(1),p=new A(0),g=0,y=new A(0),m=new A(0);for(;0!==l.cmpn(0);){let e=c.div(l);y=c.sub(e.mul(l)),m=u.sub(e.mul(h));let s=f.sub(e.mul(d));if(void 0===r&&0>y.cmp(o))t=p.neg(),i=h,r=y.neg(),n=m;else if(void 0!==r&&2==++g)break;p=y,c=l,l=y,u=h,h=m,f=d,d=s}if(void 0===t||void 0===i||void 0===r||void 0===n)throw Error("Failed to compute Endo Basis values");s=y.neg(),a=m;let b=r.sqr().add(n.sqr());return s.sqr().add(a.sqr()).cmp(b)>=0&&(s=t,a=i),0!==r.negative&&(r=r.neg(),n=n.neg()),0!==s.negative&&(s=s.neg(),a=a.neg()),[{a:r,b:n},{a:s,b:a}]}_endoSplit(e){if(null==this.endo)throw Error("Endomorphism is not defined.");let t=this.endo.basis,i=t[0],r=t[1],n=r.b.mul(e).divRound(this.n),s=i.b.neg().mul(e).divRound(this.n),a=n.mul(i.a),o=s.mul(r.a),l=n.mul(i.b),c=s.mul(r.b);return{k1:e.sub(a).sub(o),k2:l.add(c).neg()}}validate(e){if(e.inf)return!0;let t=e.x,i=e.y;if(null===t||null===i)throw Error("Point coordinates cannot be null");let r=this.a.redMul(t),n=t.redSqr().redMul(t).redIAdd(r).redIAdd(this.b);return 0===i.redSqr().redISub(n).cmpn(0)}}class t2{r;s;static fromDER(e,t){let i=(e,t)=>{let i=e[t.place++];if((128&i)==0)return i;throw Error("Invalid DER entity length")};e=tm(e,t);let r=new class{place;constructor(){this.place=0}};if(48!==e[r.place++])throw Error("Signature DER must start with 0x30");if(i(e,r)+r.place!==e.length||2!==e[r.place++])throw Error("Signature DER invalid");let n=i(e,r),s=e.slice(r.place,n+r.place);if(r.place+=n,2!==e[r.place++])throw Error("Signature DER invalid");let a=i(e,r);if(e.length!==a+r.place)throw Error("Invalid R-length in signature DER");let o=e.slice(r.place,a+r.place);if(0===s[0])if((128&s[1])==0)throw Error("Invalid R-value in signature DER");else s=s.slice(1);if(0===o[0])if((128&o[1])==0)throw Error("Invalid S-value in signature DER");else o=o.slice(1);return new t2(new A(s),new A(o))}static fromCompact(e,t){if(65!==(e=tm(e,t)).length)throw Error("Invalid Compact Signature");let i=e[0];if(i<27||i>=35)throw Error("Invalid Compact Byte");return new t2(new A(e.slice(1,33)),new A(e.slice(33,65)))}constructor(e,t){this.r=e,this.s=t}verify(e,t,i){return it(new A(ev(e,i),16),this,t)}toString(e){return this.toDER(e)}toDER(e){let t=(e,t)=>{if(t<128)e.push(t);else throw Error("len must be < 0x80")},i=e=>{let t=0,i=e.length-1;for(;0===e[t]&&(128&e[t+1])==0&&t<i;)t++;return 0===t?e:e.slice(t)},r=this.r.toArray(),n=this.s.toArray();for((128&r[0])!=0&&(r=[0].concat(r)),(128&n[0])!=0&&(n=[0].concat(n)),r=i(r),n=i(n);0===n[0]&&(128&n[1])==0;)n=n.slice(1);let s=[2];t(s,r.length),(s=s.concat(r)).push(2),t(s,n.length);let a=s.concat(n),o=[48];return(t(o,a.length),o=o.concat(a),"hex"===e)?tg(o):"base64"===e?tS(o):o}toCompact(e,t,i){if(e<0||e>3)throw Error("Invalid recovery param");if("boolean"!=typeof t)throw TypeError("Invalid compressed param");let r=27+e;t&&(r+=4);let n=[r];return(n=(n=n.concat(this.r.toArray("be",32))).concat(this.s.toArray("be",32)),"hex"===i)?tg(n):"base64"===i?tS(n):n}RecoverPublicKey(e,t){let i=this.r,r=this.s,n=new t1,s=n.n,a=n.g,o=0==e>>1?i:i.add(s),l=t0.fromX(o,(1&e)!=0);if(!l.mul(s).isInfinity())throw Error("nR is not at infinity");let c=t.neg().umod(s),h=i.invm(s),d=h.mul(r).umod(s),u=h.mul(c).umod(s),f=new ii(a.mul(u).add(l.mul(d)));return f.validate(),f}CalculateRecoveryFactor(e,t){for(let i=0;i<4;i++){let r;try{r=this.RecoverPublicKey(i,t)}catch{continue}if(e.eq(r))return i}throw Error("Unable to find valid recovery factor")}}class t8{K;V;constructor(e,t){const i=tm(e,"hex"),r=tm(t,"hex");if(32!==i.length)throw Error("Entropy must be exactly 32 bytes (256 bits)");if(32!==r.length)throw Error("Nonce must be exactly 32 bytes (256 bits)");const n=i.concat(r);this.K=Array(32),this.V=Array(32);for(let e=0;e<32;e++)this.K[e]=0,this.V[e]=1;this.update(n)}hmac(){return new ef(this.K)}update(e){let t=this.hmac().update(this.V).update([0]);void 0!==e&&(t=t.update(e)),this.K=t.digest(),this.V=this.hmac().update(this.V).digest(),void 0!==e&&(this.K=this.hmac().update(this.V).update([1]).update(e).digest(),this.V=this.hmac().update(this.V).digest())}generate(e){let t=[];for(;t.length<e;)this.V=this.hmac().update(this.V).digest(),t=t.concat(this.V);let i=t.slice(0,e);return this.update(),tg(i)}}function t3(e,t,i=new t1){let r=8*e.byteLength()-i.n.bitLength();return(r>0&&e.iushrn(r),!0!==t&&e.cmp(i.n)>=0)?e.sub(i.n):e}function t5(e){let t=e.toArray("be"),i=0n;for(let e of t)i=i<<8n|BigInt(e);return i}let t6=new t1,t4=t6.n.byteLength(),t9=t6.n.subn(1),t7=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n>>1n,ie=(e,t,i=!1,r)=>{let n=t6.n.bitLength();if(e.bitLength()>n)throw Error(`ECDSA message is too large: expected <= ${n} bits. Callers must hash messages before signing.`);let s=t5(e=t3(e)),a=t5(t),o=new t8(t.toArray("be",t4),e.toArray("be",t4));for(let e=0;;e++){let t;if(null==(t="function"==typeof r?r(e):A.isBN(r)?r:new A(o.generate(t4),16)))throw Error("k is undefined");if(0>(t=t3(t,!0)).cmpn(1)||t.cmp(t9)>0){if(A.isBN(r))throw Error("Invalid fixed custom K value (must be >1 and <N-1)");continue}let n=t6.g.mulCT(t);if(n.isInfinity()){if(A.isBN(r))throw Error("Invalid fixed custom K value (k\xb7G at infinity)");continue}let l=tJ(BigInt("0x"+n.getX().toString(16)));if(0n===l){if(A.isBN(r))throw Error("Invalid fixed custom K value (r == 0)");continue}let c=tQ(BigInt("0x"+t.toString(16))),h=tJ(s+tZ(l,a)),d=tZ(c,h);if(0n===d){if(A.isBN(r))throw Error("Invalid fixed custom K value (s == 0)");continue}return i&&d>t7&&(d=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n-d),new t2(new A(l.toString(16),16),new A(d.toString(16),16))}},it=(e,t,i)=>{let r=t6.n.bitLength();if(e.bitLength()>r)return!1;let n=t5(e);if(null==i.x||null==i.y)throw Error("Invalid public key: missing coordinates.");let s={x:t5(i.x),y:t5(i.y)},{r:a,s:o}={r:t5(t.r),s:t5(t.s)};if(a<=0n||a>=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n||o<=0n||o>=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n)return!1;let l=tQ(o);if(0n===l)return!1;let c=tZ(n,l),h=tZ(a,l),d=tG(tY(c,{x:t$,y:tz}),tY(h,s));if(0n===d.Z)return!1;let u=tK(d.Z),f=tM(u,u);return tJ(tM(d.X,f))===a};class ii extends t0{static fromPrivateKey(e){let t=new t1().g.mul(e);return new ii(t.x,t.y)}static fromString(e){let t=t0.fromString(e);return new ii(t.x,t.y)}static fromDER(e){let t=t0.fromDER(e);return new ii(t.x,t.y)}constructor(e,t=null,i=!0){if(e instanceof t0)super(e.getX(),e.getY());else{if(null===t&&i&&"string"==typeof e&&(66===e.length||130===e.length))throw Error('You are using the "new PublicKey()" constructor with a DER hex string. You need to use "PublicKey.fromString()" instead.');super(e,t,i)}}deriveSharedSecret(e){if(!this.validate())throw Error("Public key not valid for ECDH secret derivation");return this.mulCT(e)}verify(e,t,i){return it(new A(ev(e,i),16),t,this)}toDER(e){return"hex"===e?this.encode(!0,e):this.encode(!0)}toHash(e){let t=eS(this.encode(!0));return"hex"===e?tg(t):t}toAddress(e=[0]){if("string"==typeof e)if("testnet"===e||"test"===e)e=[111];else if("mainnet"===e||"main"===e)e=[0];else throw Error(`Invalid prefix ${e}`);return tT(this.toHash(),e)}deriveChild(e,t,i,r){let n;if("function"==typeof r){let t=r(e,this);void 0===t?(n=this.deriveSharedSecret(e),"function"==typeof i&&i(e,this,n)):n=t}else n=this.deriveSharedSecret(e);let s=tm(t,"utf8"),a=eE(n.encode(!0),s),o=new t1().g.mul(new A(a)),l=this.add(o);return new ii(l.x,l.y)}static fromMsgHashAndCompactSignature(e,t,i){let r=tm(t,i);if(65!==r.length)throw Error("Invalid Compact Signature");let n=r[0];if(n<27||n>=35)throw Error("Invalid Compact Byte");let s=r[0]-27;return s>3&&(s-=4),new t2(new A(r.slice(1,33)),new A(r.slice(33,65))).RecoverPublicKey(s,e)}}class ir{_rand;getRandomValues(e,t){let i=new Uint8Array(t);return e.crypto.getRandomValues(i),Array.from(i)}constructor(){const e=()=>{throw Error("No secure random number generator is available in this environment.")};if(this._rand=e,"u">typeof globalThis&&"function"==typeof globalThis.crypto?.getRandomValues){this._rand=e=>this.getRandomValues(globalThis,e);return}if("u">typeof process&&process.release?.name==="node")try{const e=require("node:crypto");if("function"==typeof e.randomBytes){this._rand=t=>Array.from(e.randomBytes(t));return}}catch(e){}if(void 0!==globalThis.self&&"function"==typeof globalThis.self.crypto?.getRandomValues){this._rand=e=>this.getRandomValues(globalThis.self,e);return}if(void 0!==globalThis.window&&"function"==typeof globalThis.window.crypto?.getRandomValues){this._rand=e=>this.getRandomValues(globalThis.window,e);return}this._rand=e}generate(e){return this._rand(e)}}let is=null,ia=e=>(is??=new ir).generate(e);class io{x;y;constructor(e,t){const i=new t1().p;this.x=e.umod(i),this.y=t.umod(i)}toString(){return tA(this.x.toArray())+"."+tA(this.y.toArray())}static fromString(e){let[t,i]=e.split(".");return new io(new A(tx(t)),new A(tx(i)))}}class il{points;threshold;constructor(e,t){this.points=e,this.threshold=t??e.length}static fromPrivateKey(e,t){let i=new t1().p,r=[new io(new A(0),new A(e.toArray()))];for(let e=1;e<t;e++){let e=new A(ia(32)).umod(i),t=new A(ia(32)).umod(i);r.push(new io(e,t))}return new il(r)}valueAt(e){let t=new t1().p,i=new A(0);for(let r=0;r<this.threshold;r++){let n=this.points[r].y;for(let i=0;i<this.threshold;i++)if(r!==i){let s=this.points[i].x,a=this.points[r].x,o=e.sub(s).umod(t),l=a.sub(s).umod(t).invm(t),c=o.mul(l).umod(t);n=n.mul(c).umod(t)}i=i.add(n).umod(t)}return i}}class ic{points;threshold;integrity;constructor(e,t,i){this.points=e,this.threshold=t,this.integrity=i}static fromBackupFormat(e){let t=0,i="";return new ic(e.map((e,r)=>{let n=e.split(".");if(4!==n.length)throw Error("Invalid share format in share "+r.toString()+'. Expected format: "x.y.t.i" - received '+e);let[s,a,o,l]=n;if(void 0===o)throw Error("Threshold not found in share "+r.toString());if(void 0===l)throw Error("Integrity not found in share "+r.toString());let c=Number.parseInt(o,10);if(0!==r&&t!==c)throw Error("Threshold mismatch in share "+r.toString());if(0!==r&&i!==l)throw Error("Integrity mismatch in share "+r.toString());return t=c,i=l,io.fromString([s,a].join("."))}),t,i)}toBackupFormat(){return this.points.map(e=>e.toString()+"."+this.threshold.toString()+"."+this.integrity)}}class ih extends A{static fromRandom(){return new ih(ia(32))}static fromString(e,t="hex"){return new ih(super.fromString(e,t).toArray())}static fromHex(e){return new ih(super.fromHex(e,"big"))}static fromWif(e,t=1){let i=tO(e,void 0,t);if(33!==i.data.length)throw Error("Invalid WIF length");if(1!==i.data[32])throw Error("Invalid WIF padding");return new ih(i.data.slice(0,32))}constructor(e=0,t=10,i="be",r="apply"){if(e instanceof A?(super(),e.copy(this)):super(e,t,i),"nocheck"!==r){const e=this.checkInField();if(!e.inField){if("error"===r)throw Error("Input is out of field");A.move(this,e.modN)}}}checkInField(){let e=new t1,t=this.mod(e.n);return{inField:0===this.cmp(t),modN:t}}isValid(){return this.checkInField().inField}sign(e,t,i=!0,r){return ie(new A(ev(e,t),16),this,i,r)}verify(e,t,i){return it(new A(ev(e,i),16),t,this.toPublicKey())}toPublicKey(){let e=new t1().g.mulCT(this);return new ii(e.x,e.y)}toWif(e=[128]){if(!this.isValid())throw Error("Value is out of field");return tT([...this.toArray("be",32),1],e)}toAddress(e=[0]){return this.toPublicKey().toAddress(e)}toHex(){return super.toHex(32)}toString(e="hex",t=64){return super.toString(e,t)}deriveSharedSecret(e){if(!e.validate())throw Error("Public key not valid for ECDH secret derivation");return e.mulCT(this)}deriveChild(e,t,i,r){let n;if("function"==typeof r){let t=r(this,e);void 0===t?(n=this.deriveSharedSecret(e),"function"==typeof i&&i(this,e,n)):n=t}else n=this.deriveSharedSecret(e);let s=tm(t,"utf8"),a=eE(n.encode(!0),s),o=new t1;return new ih(this.add(new A(a)).mod(o.n).toArray())}toKeyShares(e,t){if("number"!=typeof e||"number"!=typeof t)throw TypeError("threshold and totalShares must be numbers");if(e<2)throw Error("threshold must be at least 2");if(t<2)throw Error("totalShares must be at least 2");if(e>t)throw Error("threshold should be less than or equal to totalShares");let i=il.fromPrivateKey(this,e),r=[],n=new Set,s=new t1,a=ia(64);for(let e=0;e<t;e++){let t,o=0;do if(t=new A(ex(a,[e,o,...ia(32)])).umod(s.p),++o>5)throw Error("Failed to generate unique x coordinate after 5 attempts");while(t.isZero()||n.has(t.toString()));n.add(t.toString());let l=i.valueAt(t);r.push(new io(t,l))}return new ic(r,e,this.toPublicKey().toHash("hex").slice(0,8))}toBackupShares(e,t){return this.toKeyShares(e,t).toBackupFormat()}static fromBackupShares(e){return ih.fromKeyShares(ic.fromBackupFormat(e))}static fromKeyShares(e){let{points:t,threshold:i,integrity:r}=e;if(i<2)throw Error("threshold must be at least 2");if(t.length<i)throw Error(`At least ${i} shares are required to reconstruct the private key`);for(let e=0;e<i;e++)for(let r=e+1;r<i;r++)if(t[e].x.eq(t[r].x))throw Error("Duplicate share detected, each must be unique.");let n=new ih(new il(t,i).valueAt(new A(0)).toArray());if(n.toPublicKey().toHash("hex").slice(0,8)!==r)throw Error("Integrity hash mismatch");return n}}let id=new Uint8Array([99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22]),iu=[[0,0,0,0],[1,0,0,0],[2,0,0,0],[4,0,0,0],[8,0,0,0],[16,0,0,0],[32,0,0,0],[64,0,0,0],[128,0,0,0],[27,0,0,0],[54,0,0,0]].map(e=>new Uint8Array(e)),ip=new Uint8Array(256),ig=new Uint8Array(256);for(let e=0;e<256;e++){let t=(e<<1^27*((128&e)!=0))&255;ip[e]=t,ig[e]=t^e}function iy(e,t,i){for(let r=0;r<4;r++){let n=t[i+r];for(let t=0;t<4;t++)e[t][r]^=n[t]}}function im(e){for(let t=0;t<4;t++)e[t]=id[e[t]]}function ib(e,t){let i,r,n,s,a=[[],[],[],[]],o=[],l=Array.from(t);if(16===l.length)s=11;else if(24===l.length)s=13;else if(32===l.length)s=15;else throw Error("Illegal key length: "+String(l.length));let c=function(e,t){let i=t.length/4,r=[];for(let e=0;e<t.length;e++)e%4==0&&r.push([]),r[e>>2].push(t[e]);for(let t=i;t<4*e;t++){r[t]=[];let e=r[t-1].slice();if(t%i==0){!function(e){let t=e[0];e[0]=e[1],e[1]=e[2],e[2]=e[3],e[3]=t}(e),im(e);let r=iu[t/i];for(let t=0;t<4;t++)e[t]^=r[t]}else i>6&&t%i==4&&im(e);for(let n=0;n<4;n++)r[t][n]=r[t-i][n]^e[n]}return r}(s,l);for(let t=0;t<4;t++)a[0][t]=e[4*t],a[1][t]=e[4*t+1],a[2][t]=e[4*t+2],a[3][t]=e[4*t+3];for(iy(a,c,0),n=1;n<s;n++){for(let e=0;e<4;e++)for(let t=0;t<4;t++)a[e][t]=id[a[e][t]];!function(e){let t=e[1][0];e[1][0]=e[1][1],e[1][1]=e[1][2],e[1][2]=e[1][3],e[1][3]=t,t=e[2][0];let i=e[2][1];e[2][0]=e[2][2],e[2][1]=e[2][3],e[2][2]=t,e[2][3]=i,t=e[3][3],e[3][3]=e[3][2],e[3][2]=e[3][1],e[3][1]=e[3][0],e[3][0]=t}(a),n+1<s&&function(e){for(let t=0;t<4;t++){let i=e[0][t],r=e[1][t],n=e[2][t],s=e[3][t];e[0][t]=ip[i]^ig[r]^n^s,e[1][t]=i^ip[r]^ig[n]^s,e[2][t]=i^r^ip[n]^ig[s],e[3][t]=ig[i]^r^n^ip[s]}}(a),iy(a,c,4*n)}for(i=0;i<4;i++)for(r=0;r<4;r++)o.push(a[r][i]);return o}let iw=function(e){if(e<0||e>Number.MAX_SAFE_INTEGER)throw Error("getBytes64: value out of range");let t=Math.floor(e/0x100000000),i=e>>>0;return[t>>>24&255,t>>>16&255,t>>>8&255,255&t,i>>>24&255,i>>>16&255,i>>>8&255,255&i]},iv=function(e){return new Uint8Array(e)},iI=((n=new Uint8Array(16))[0]=225,n),ik=(...e)=>{let t=0;for(let i of e)t+=i.length;let i=new Uint8Array(t),r=0;for(let t of e)i.set(t,r),r+=t.length;return i},iS=function(e){let t=0,i=0;for(let r=0;r<e.length;r++)i=t,t=1&e[r],e[r]=e[r]>>1,0!==i&&(e[r]=128|e[r]);return e},iE=function(e,t){let i=t.slice(),r=iv(16);for(let t=0;t<16;t++){let n=e[t];for(let e=7;e>=0;e--){let t=255&-(n>>e&1);for(let e=0;e<16;e++)r[e]^=i[e]&t;let s=255&-(1&i[15]);iS(i);for(let e=0;e<16;e++)i[e]^=iI[e]&s}}return r},ix=function(e){let t=e.slice();for(let e=15;e>11&&(t[e]=t[e]+1&255,0===t[e]);e--);return t};function iA(e,t){let i=iv(16),r=new Uint8Array(16);for(let n=0;n<e.length;n+=16){r.set(i);for(let t=0;t<16;t++)r[t]^=e[n+t]??0;i=iE(r,t)}return i}function iT(e,t,i){if(0===e.length)return new Uint8Array(0);let r=new Uint8Array(e.length),n=t.slice(),s=0,a=Math.ceil(e.length/16);for(let t=0;t<a;t++){let o=ib(n,i),l=Math.min(16,e.length-s);for(let t=0;t<l;t++)r[s]=e[s]^o[t],s++;t+1<a&&(n=ix(n))}return r}function iO(e){let t,i,r=8*e.length;t=0===e.length?16:e.length%16==0?0:16-e.length%16;let n=new Uint8Array(16+e.length+t+16);i=16,n.set(e,i),i+=e.length,i+=t;let s=iw(0);n.set(s,i),i+=8;let a=iw(r);return n.set(a,i),n}let iP=(()=>{let e="u"<typeof globalThis?void 0:globalThis.process,t=e?.getBuiltinModule;if("function"==typeof t)try{let i=t.call(e,"node:crypto");if(null!=i)return i}catch{}try{if("function"==typeof require)return require("node:crypto")}catch{}})(),iN=null!=iP&&"function"==typeof iP.createCipheriv&&"function"==typeof iP.createDecipheriv;class i_ extends A{static fromRandom(){return new i_(ia(32))}encrypt(e,t){let i=new Uint8Array(ia(32)),r=new Uint8Array(tm(e,t)),n=new Uint8Array(this.toArray("be",32));if(iN){let e=function(e,t,i){try{let r=iP.createCipheriv("aes-256-gcm",Buffer.from(i.buffer,i.byteOffset,i.byteLength),Buffer.from(t.buffer,t.byteOffset,t.byteLength)),n=Buffer.concat([r.update(Buffer.from(e.buffer,e.byteOffset,e.byteLength)),r.final()]),s=r.getAuthTag(),a=new Uint8Array(t.length+n.length+s.length),o=0;return a.set(t,o),o+=t.length,a.set(n,o),o+=n.length,a.set(s,o),a}catch{return null}}(r,i,n);if(null!==e)return tk(Array.from(e),t)}let{result:s,authenticationTag:a}=function(e,t,i){let r;if(0===t.length)throw Error("Initialization vector must not be empty");if(0===i.length)throw Error("Key must not be empty");let n=new Uint8Array(ib(iv(16),i));if(12===t.length)r=ik(t,iv(3),new Uint8Array([1]));else{let e=t;e.length%16!=0&&(e=ik(e,iv(16-e.length%16)));let i=iw(8*t.length);r=iA(ik(e,iv(8),new Uint8Array(i)),n)}let s=iT(e,ix(r),i),a=iT(iA(iO(s),n),r,i);return{result:s,authenticationTag:a}}(r,i,n),o=new Uint8Array(i.length+s.length+a.length),l=0;return o.set(i,l),l+=i.length,o.set(s,l),l+=s.length,o.set(a,l),tk(Array.from(o),t)}decrypt(e,t){let i=new Uint8Array(tm(e,t));if(i.length<48)throw Error("Ciphertext too short");let r=new Uint8Array(this.toArray("be",32));if(iN){let e=function(e,t){try{let i=e.slice(0,32),r=e.length-16,n=e.slice(32,r),s=e.slice(r),a=iP.createDecipheriv("aes-256-gcm",Buffer.from(t.buffer,t.byteOffset,t.byteLength),Buffer.from(i.buffer,i.byteOffset,i.byteLength));a.setAuthTag(Buffer.from(s.buffer,s.byteOffset,s.byteLength));let o=Buffer.concat([a.update(Buffer.from(n.buffer,n.byteOffset,n.byteLength)),a.final()]);return new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}catch{return null}}(i,r);if(void 0!==e){if(null===e)throw Error("Decryption failed!");return tk(Array.from(e),t)}}let n=i.slice(0,32),s=i.length-16,a=function(e,t,i,r){let n;if(0===e.length)throw Error("Cipher text must not be empty");if(0===t.length)throw Error("Initialization vector must not be empty");if(0===r.length)throw Error("Key must not be empty");let s=new Uint8Array(ib(iv(16),r));if(12===t.length)n=ik(t,iv(3),new Uint8Array([1]));else{let e=t;e.length%16!=0&&(e=ik(e,iv(16-e.length%16)));let i=iw(8*t.length);n=iA(ik(e,iv(8),new Uint8Array(i)),s)}let a=iT(e,ix(n),r),o=iT(iA(iO(e),s),n,r);if(o.length!==i.length)return null;let l=0;for(let e=0;e<o.length;e++)l|=o[e]^i[e];return 0!==l?null:a}(i.slice(32,s),n,i.slice(s),r);if(null===a)throw Error("Decryption failed!");return tk(Array.from(a),t)}}let iR={OP_0:0,OP_FALSE:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_1:81,OP_TRUE:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SPLIT:127,OP_NUM2BIN:128,OP_BIN2NUM:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP2:177,OP_CHECKSEQUENCEVERIFY:178,OP_NOP3:178,OP_SUBSTR:179,OP_NOP4:179,OP_LEFT:180,OP_NOP5:180,OP_RIGHT:181,OP_NOP6:181,OP_LSHIFTNUM:182,OP_NOP7:182,OP_RSHIFTNUM:183,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_NOP11:186,OP_NOP12:187,OP_NOP13:188,OP_NOP14:189,OP_NOP15:190,OP_NOP16:191,OP_NOP17:192,OP_NOP18:193,OP_NOP19:194,OP_NOP20:195,OP_NOP21:196,OP_NOP22:197,OP_NOP23:198,OP_NOP24:199,OP_NOP25:200,OP_NOP26:201,OP_NOP27:202,OP_NOP28:203,OP_NOP29:204,OP_NOP30:205,OP_NOP31:206,OP_NOP32:207,OP_NOP33:208,OP_NOP34:209,OP_NOP35:210,OP_NOP36:211,OP_NOP37:212,OP_NOP38:213,OP_NOP39:214,OP_NOP40:215,OP_NOP41:216,OP_NOP42:217,OP_NOP43:218,OP_NOP44:219,OP_NOP45:220,OP_NOP46:221,OP_NOP47:222,OP_NOP48:223,OP_NOP49:224,OP_NOP50:225,OP_NOP51:226,OP_NOP52:227,OP_NOP53:228,OP_NOP54:229,OP_NOP55:230,OP_NOP56:231,OP_NOP57:232,OP_NOP58:233,OP_NOP59:234,OP_NOP60:235,OP_NOP61:236,OP_NOP62:237,OP_NOP63:238,OP_NOP64:239,OP_NOP65:240,OP_NOP66:241,OP_NOP67:242,OP_NOP68:243,OP_NOP69:244,OP_NOP70:245,OP_NOP71:246,OP_NOP72:247,OP_NOP73:248,OP_NOP77:252,OP_SMALLDATA:249,OP_SMALLINTEGER:250,OP_PUBKEYS:251,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255};for(let e in iR)void 0===iR[iR[e]]&&(iR[iR[e]]=e);let iC=iR,iB="u"<typeof globalThis?void 0:globalThis.Buffer;class iU{_chunks;parsed;rawBytesCache;hexCache;static fromASM(e){let t=[],i=e.split(" "),r=0;for(;r<i.length;){let{chunk:e,advance:n}=iU.parseASMToken(i,r);t.push(e),r+=n}return new iU(t)}static pushdataOpCodeNum(e){return e>=0&&e<iC.OP_PUSHDATA1?e:e<256?iC.OP_PUSHDATA1:e<65536?iC.OP_PUSHDATA2:iC.OP_PUSHDATA4}static parseASMToken(e,t){let i=e[t];if("0"===i)return{chunk:{op:0},advance:1};if("-1"===i)return{chunk:{op:iC.OP_1NEGATE},advance:1};let r=i.startsWith("OP_")&&void 0!==iC[i],n=r?iC[i]:0;if(n===iC.OP_PUSHDATA1||n===iC.OP_PUSHDATA2||n===iC.OP_PUSHDATA4)return{chunk:{data:tm(e[t+2],"hex"),op:n},advance:3};if(!r){let e=i;e.length%2!=0&&(e="0"+e);let t=tm(e,"hex");if(tk(t,"hex")!==e)throw Error("invalid hex string in script");return{chunk:{data:t,op:iU.pushdataOpCodeNum(t.length)},advance:1}}return{chunk:{op:n},advance:1}}static fromHex(e){if(0===e.length)return iU.fromBinary([]);if(e.length%2!=0)throw Error("There is an uneven number of characters in the string which suggests it is not hex encoded.");if(!/^[0-9a-fA-F]+$/.test(e))throw Error("Some elements in this string are not hex encoded.");let t=tm(e,"hex");return new iU([],Uint8Array.from(t),e.toLowerCase(),!1)}static fromBinary(e){return new iU([],Uint8Array.from(e),void 0,!1)}constructor(e=[],t,i,r=!0){this._chunks=e,this.parsed=r,this.rawBytesCache=t,this.hexCache=i}get chunks(){return this.ensureParsed(),this._chunks}set chunks(e){this._chunks=e,this.parsed=!0,this.invalidateSerializationCaches()}ensureParsed(){this.parsed||(null!=this.rawBytesCache?this._chunks=iU.parseChunks(this.rawBytesCache):this._chunks=[],this.parsed=!0)}toASM(){let e="";for(let t of this.chunks)e+=this._chunkToString(t);return e.slice(1)}toHex(){if(null!=this.hexCache)return this.hexCache;this.rawBytesCache??=this.serializeChunksToBytes();let e=null==iB?tk(Array.from(this.rawBytesCache),"hex"):iB.from(this.rawBytesCache).toString("hex");return this.hexCache=e,e}toBinary(){return Array.from(this.toUint8Array())}toUint8Array(){return this.rawBytesCache??=this.serializeChunksToBytes(),this.rawBytesCache}writeScript(e){return this.invalidateSerializationCaches(),this.chunks=this.chunks.concat(e.chunks),this}writeOpCode(e){return this.invalidateSerializationCaches(),this.chunks.push({op:e}),this}setChunkOpCode(e,t){return this.invalidateSerializationCaches(),this.chunks[e]={op:t},this}writeBn(e){if(this.invalidateSerializationCaches(),e.cmpn(0)===iC.OP_0)this.chunks.push({op:iC.OP_0});else if(0===e.cmpn(-1))this.chunks.push({op:iC.OP_1NEGATE});else if(e.cmpn(1)>=0&&0>=e.cmpn(16))this.chunks.push({op:e.toNumber()+iC.OP_1-1});else{let t=e.toSm("little");this.writeBin(t)}return this}writeBin(e){let t;this.invalidateSerializationCaches();let i=e.length>0?e:void 0;if(e.length>0&&e.length<iC.OP_PUSHDATA1)t=e.length;else if(0===e.length)t=iC.OP_0;else if(e.length<256)t=iC.OP_PUSHDATA1;else if(e.length<65536)t=iC.OP_PUSHDATA2;else if(e.length<0x100000000)t=iC.OP_PUSHDATA4;else throw Error("You can't push that much data");return this.chunks.push({data:i,op:t}),this}writeNumber(e){return this.invalidateSerializationCaches(),this.writeBn(new A(e)),this}removeCodeseparators(){let e=this.toUint8Array();return this.rawBytesCache=Uint8Array.from(iU.removeOpcodeBytes(e,iC.OP_CODESEPARATOR)),this.hexCache=void 0,this._chunks=[],this.parsed=!1,this}findAndDelete(e){this.invalidateSerializationCaches();let t=e.toUint8Array(),i=t.length;if(0===i)return this;let r=t[0]??0,n=e=>{if(e.op!==r)return!1;let n=e.data??[],s=n.length;if(0===s)return 1===i;if(e.op===iC.OP_RETURN||e.op<iC.OP_PUSHDATA1){if(i!==1+s)return!1;for(let e=0;e<s;e++)if(t[1+e]!==n[e])return!1;return!0}if(e.op===iC.OP_PUSHDATA1){if(i!==2+s||t[1]!==(255&s))return!1;for(let e=0;e<s;e++)if(t[2+e]!==n[e])return!1;return!0}if(e.op===iC.OP_PUSHDATA2){if(i!==3+s||t[1]!==(255&s)||t[2]!==(s>>8&255))return!1;for(let e=0;e<s;e++)if(t[3+e]!==n[e])return!1;return!0}if(e.op===iC.OP_PUSHDATA4){if(i!==5+s)return!1;let e=s>>>0;if(t[1]!==(255&e)||t[2]!==(e>>8&255)||t[3]!==(e>>16&255)||t[4]!==(e>>24&255))return!1;for(let e=0;e<s;e++)if(t[5+e]!==n[e])return!1;return!0}return!1};for(let e=0;e<this.chunks.length;)n(this.chunks[e])?this.chunks.splice(e,1):e++;return this}isPushOnly(){for(let e of this.chunks)if(e.op>iC.OP_16)return!1;return!0}isLockingScript(){throw Error("Not implemented")}isUnlockingScript(){throw Error("Not implemented")}static computeSerializedLength(e){let t=0;for(let i of e){if(t+=1,null==i.data)continue;let e=i.data.length;if(i.op===iC.OP_RETURN){t+=e;break}i.op<iC.OP_PUSHDATA1?t+=e:i.op===iC.OP_PUSHDATA1?t+=1+e:i.op===iC.OP_PUSHDATA2?t+=2+e:i.op===iC.OP_PUSHDATA4&&(t+=4+e)}return t}serializeChunksToBytes(){let e=this.chunks,t=new Uint8Array(iU.computeSerializedLength(e)),i=0;for(let r of e)if(t[i++]=r.op,null!=r.data){if(r.op===iC.OP_RETURN){t.set(r.data,i);break}i=iU.writeChunkData(t,i,r.op,r.data)}return t}invalidateSerializationCaches(){this.rawBytesCache=void 0,this.hexCache=void 0}static writeChunkData(e,t,i,r){let n=r.length;if(i<iC.OP_PUSHDATA1)return e.set(r,t),t+n;if(i===iC.OP_PUSHDATA1)return e[t++]=255&n,e.set(r,t),t+n;if(i===iC.OP_PUSHDATA2)return e[t++]=255&n,e[t++]=n>>8&255,e.set(r,t),t+n;if(i===iC.OP_PUSHDATA4){let i=n>>>0;return e[t++]=255&i,e[t++]=i>>8&255,e[t++]=i>>16&255,e[t++]=i>>24&255,e.set(r,t),t+n}return t}static readPushdataLength(e,t,i,r){if(e>0&&e<iC.OP_PUSHDATA1)return{len:e,newPos:i,hasLength:!0};if(e===iC.OP_PUSHDATA1){let e=i<r;return{len:e?t[i++]??0:0,newPos:i,hasLength:e}}if(e===iC.OP_PUSHDATA2){let e=i+1<r;return{len:(t[i]??0)|(t[i+1]??0)<<8,newPos:Math.min(i+2,r),hasLength:e}}let n=i+3<r;return{len:((t[i]??0)|(t[i+1]??0)<<8|(t[i+2]??0)<<16|(t[i+3]??0)<<24)>>>0,newPos:Math.min(i+4,r),hasLength:n}}static parseChunks(e){let t=[],i=e.length,r=0,n=0;for(;r<i;){let s=e[r++]??0;if(s===iC.OP_RETURN&&0===n){t.push({op:s,data:iU.copyRange(e,r,i)});break}if(s===iC.OP_IF||s===iC.OP_NOTIF||s===iC.OP_VERIF||s===iC.OP_VERNOTIF?n++:s===iC.OP_ENDIF&&n--,s>0&&s<=iC.OP_PUSHDATA4){let{len:n,newPos:a,hasLength:o}=iU.readPushdataLength(s,e,r,i),l=Math.min((r=a)+n,i),c=!o||l-r!==n;t.push({data:iU.copyRange(e,r,l),op:s,invalidLength:c}),r=l}else t.push({op:s})}return t}static removeOpcodeBytes(e,t){let i=[],r=e.length,n=0;for(;n<r;){let s=n,a=e[n++]??0;if(a>0&&a<=iC.OP_PUSHDATA4){let{len:o,newPos:l}=iU.readPushdataLength(a,e,n,r),c=Math.min((n=l)+o,r);if(a!==t)for(let t=s;t<c;t++)i.push(e[t]??0);n=c}else a!==t&&i.push(a)}return i}static copyRange(e,t,i){let r=Math.max(i-t,0),n=Array(r);for(let i=0;i<r;i++)n[i]=e[t+i]??0;return n}_chunkToString(e){let t=e.op,i="";if(void 0===e.data){let e=iC[t];i=`${i} ${e}`}else i=`${i} ${tg(e.data)}`;return i}}let iF=new Uint8Array(0);class iD extends t2{static SIGHASH_ALL=1;static SIGHASH_NONE=2;static SIGHASH_SINGLE=3;static SIGHASH_CHRONICLE=32;static SIGHASH_FORKID=64;static SIGHASH_ANYONECANPAY=128;scope;static formatOTDA(e){let t=(e.scope&iD.SIGHASH_ANYONECANPAY)===iD.SIGHASH_ANYONECANPAY,i=(31&e.scope)===iD.SIGHASH_SINGLE,r=(31&e.scope)===iD.SIGHASH_NONE,n=(31&e.scope)===iD.SIGHASH_ALL||!i&&!r,s=iU.fromBinary(e.subscript.toBinary());s.removeCodeseparators();let a={sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,sequence:e.inputSequence,script:s.toBinary()},o=new tP;function l(e){for(let t of(o.writeVarIntNum(e.length),e))o.writeReverse(tm(t.sourceTXID,"hex")),o.writeUInt32LE(t.sourceOutputIndex),o.writeVarIntNum(t.script.length),o.write(t.script),o.writeUInt32LE(t.sequence)}function c(e){for(let t of(o.writeVarIntNum(e.length),e))o.writeUInt64LE(t.satoshis),o.writeVarIntNum(t.script.length),o.write(t.script)}o.writeInt32LE(e.transactionVersion);let h=new iU().toBinary();if(t)t&&l([a]);else{let t=e.otherInputs.map(e=>({sourceTXID:e.sourceTXID??e.sourceTransaction?.id("hex")??"",sourceOutputIndex:e.sourceOutputIndex,sequence:i||r?0:e.sequence??0xffffffff,script:h}));t.splice(e.inputIndex,0,a),l(t)}if(n)c(e.outputs.map(e=>({satoshis:e.satoshis??0,script:e.lockingScript.toBinary()})));else if(i){let t=[];for(let i=0;i<e.inputIndex;i++)t.push({satoshis:-1,script:h});let i=e.outputs[e.inputIndex];void 0!==i&&t.push({satoshis:i.satoshis??0,script:i.lockingScript.toBinary()}),c(t)}else r&&c([]);return o.writeUInt32LE(e.lockTime),o.writeUInt32LE(e.scope>>>0),o.toUint8Array()}static formatBip143(e){let t=e.cache,i={sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,sequence:e.inputSequence},r=[...e.otherInputs];function n(t){let i=new tP;if(void 0===t)for(let t of e.outputs){let e=t.satoshis??0;i.writeUInt64LE(e);let r=t.lockingScript?.toUint8Array()??iF;i.writeVarIntNum(r.length),i.write(r)}else{let r=e.outputs[t];if(void 0===r)throw Error(`Output at index ${t} does not exist`);let n=r.satoshis??0;i.writeUInt64LE(n);let s=r.lockingScript?.toUint8Array()??iF;i.writeVarIntNum(s.length),i.write(s)}return ek(i.toUint8Array())}r.splice(e.inputIndex,0,i);let s=Array(32).fill(0),a=Array(32).fill(0),o=Array(32).fill(0);if((e.scope&iD.SIGHASH_ANYONECANPAY)==0&&(t?.hashPrevouts==null?(s=(()=>{let e=new tP;for(let t of r){if(void 0===t.sourceTXID){if(null==t.sourceTransaction)throw Error("Missing sourceTransaction for input");e.write(t.sourceTransaction.hash())}else e.writeReverse(tm(t.sourceTXID,"hex"));e.writeUInt32LE(t.sourceOutputIndex)}return ek(e.toUint8Array())})(),null!=t&&(t.hashPrevouts=s)):s=t.hashPrevouts),(e.scope&iD.SIGHASH_ANYONECANPAY)==0&&(31&e.scope)!==iD.SIGHASH_SINGLE&&(31&e.scope)!==iD.SIGHASH_NONE&&(t?.hashSequence==null?(a=(()=>{let e=new tP;for(let t of r){let i=t.sequence??0xffffffff;e.writeUInt32LE(i)}return ek(e.toUint8Array())})(),null!=t&&(t.hashSequence=a)):a=t.hashSequence),(31&e.scope)!==iD.SIGHASH_SINGLE&&(31&e.scope)!==iD.SIGHASH_NONE)t?.hashOutputsAll==null?(o=n(),null!=t&&(t.hashOutputsAll=o)):o=t.hashOutputsAll;else if((31&e.scope)===iD.SIGHASH_SINGLE&&e.inputIndex<e.outputs.length){let i=e.inputIndex,r=t?.hashOutputsSingle?.get(i);null==r?(o=n(i),null!=t&&(t.hashOutputsSingle??=new Map,t.hashOutputsSingle.set(i,o))):o=r}let l=new tP;l.writeInt32LE(e.transactionVersion),l.write(s),l.write(a),l.writeReverse(tm(e.sourceTXID,"hex")),l.writeUInt32LE(e.sourceOutputIndex);let c=e.subscript.toUint8Array();l.writeVarIntNum(c.length),l.write(c),l.writeUInt64LE(e.sourceSatoshis);let h=i.sequence;return l.writeUInt32LE(h),l.write(o),l.writeUInt32LE(e.lockTime),l.writeUInt32LE(e.scope>>>0),l.toUint8Array()}static format(e){return Array.from(this.formatBytes(e))}static formatBytes(e){let t=(e.scope&iD.SIGHASH_FORKID)!=0,i=!0!==e.ignoreChronicle&&(e.scope&iD.SIGHASH_CHRONICLE)!=0;return t&&!i?iD.formatBip143(e):!t||t&&i?iD.formatOTDA(e):new Uint8Array(0)}static usesOtdaSingleBug(e){let t=(e.scope&iD.SIGHASH_FORKID)!=0,i=!0!==e.ignoreChronicle&&(e.scope&iD.SIGHASH_CHRONICLE)!=0;return(!t||t&&i)&&(31&e.scope)===iD.SIGHASH_SINGLE&&e.inputIndex>=e.outputs.length}static fromChecksigFormat(e){if(0===e.length)return new iD(new A(1),new A(1),1);let t=e.at(-1),i=e.slice(0,e.length-1),r=t2.fromDER(i);return new iD(r.r,r.s,t)}constructor(e,t,i){super(e,t),this.scope=i}hasLowS(){return!(this.s.ltn(1)||this.s.gt(new A("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex")))}toChecksigFormat(){return[...this.toDER(),this.scope]}}class iL{curve;constructor(){this.curve=new t1}generateProof(e,t,i,r){let n=ih.fromRandom(),s=n.toPublicKey(),a=i.mul(n),o=this.computeChallenge(t,i,r,a,s);return{R:s,SPrime:a,z:n.add(o.mul(e)).umod(this.curve.n)}}verifyProof(e,t,i,r){let{R:n,SPrime:s,z:a}=r,o=this.computeChallenge(e,t,i,s,n),l=this.curve.g.mul(a),c=n.add(e.mul(o));if(!l.eq(c))return!1;let h=t.mul(a),d=s.add(i.mul(o));return!!h.eq(d)}computeChallenge(e,t,i,r,n){return new A(ev([...e.encode(!0),...t.encode(!0),...i.encode(!0),...r.encode(!0),...n.encode(!0)])).umod(this.curve.n)}}let iV=/^[0-9a-fA-F]+$/,iH=BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),iM=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),iK=iH-3n,iq=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),i$={x:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),y:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},iz=iM>>1n;class iW{p=iH;n=iM;a=iK;b=iq;g=i$;mod(e,t=this.p){let i=e%t;return i>=0n?i:i+t}modInv(e,t){if(0n===e||t<=0n)throw Error("Invalid mod inverse input");let[i,r]=[this.mod(e,t),t],[n,s]=[1n,0n];for(;0n!==r;){let e=i/r;[i,r]=[r,i-e*r],[n,s]=[s,n-e*s]}if(1n!==i)throw Error("Inverse does not exist");return this.mod(n,t)}modPow(e,t,i){if(1n===i)return 0n;let r=1n,n=this.mod(e,i),s=t;for(;s>0n;)(1n&s)===1n&&(r=this.mod(r*n,i)),s>>=1n,n=this.mod(n*n,i);return r}isInfinity(e){return null===e}assertOnCurve(e){if(this.isInfinity(e))return;let{x:t,y:i}=e;if(this.mod(i*i)!==this.mod(this.mod(t*t*t+this.a*t)+this.b))throw Error("Point is not on secp256r1")}pointFromAffine(e,t){let i={x:this.mod(e),y:this.mod(t)};return this.assertOnCurve(i),i}pointFromHex(e){if(e.startsWith("04")){let t=BigInt("0x"+e.slice(2,66)),i=BigInt("0x"+e.slice(66));return this.pointFromAffine(t,i)}if(e.startsWith("02")||e.startsWith("03")){let t=BigInt("0x"+e.slice(2)),i=this.mod(this.mod(t*t*t+this.a*t)+this.b),r=this.modPow(i,this.p+1n>>2n,this.p),n=(1n&r)===1n===e.startsWith("03")?r:this.p-r;return this.pointFromAffine(t,n)}throw Error("Invalid point encoding")}pointToHex(e,t=!1){if(this.isInfinity(e))return"00";let i=this.to32BytesHex(e.x),r=this.to32BytesHex(e.y);return t?((1n&e.y)===0n?"02":"03")+i:"04"+i+r}addPoints(e,t){if(this.isInfinity(e))return t;if(this.isInfinity(t))return e;let{x:i,y:r}=e,{x:n,y:s}=t;if(i===n)return r===s?this.doublePoint(e):null;let a=this.mod((s-r)*this.modInv(n-i,this.p)),o=this.mod(a*a-i-n),l=this.mod(a*(i-o)-r);return{x:o,y:l}}doublePoint(e){if(this.isInfinity(e))return e;if(0n===e.y)return null;let t=this.mod((3n*e.x*e.x+this.a)*this.modInv(2n*e.y,this.p)),i=this.mod(t*t-2n*e.x),r=this.mod(t*(e.x-i)-e.y);return{x:i,y:r}}add(e,t){return this.addPoints(e,t)}multiply(e,t){if(0n===t||this.isInfinity(e))return null;let i=this.mod(t,this.n),r=null,n=e;for(;i>0n;)(1n&i)===1n&&(r=this.addPoints(r,n)),n=this.doublePoint(n),i>>=1n;return r}multiplyBase(e){return this.multiply(this.g,e)}isOnCurve(e){try{return this.assertOnCurve(e),!0}catch(e){return!1}}generatePrivateKeyHex(){return this.to32BytesHex(this.randomScalar())}randomScalar(){for(;;){let e=BigInt("0x"+tg(ia(32)));if(e>0n&&e<this.n)return e}}normalizePrivateKey(e){let t=this.mod(e,this.n);if(0n===t)throw Error("Invalid private key");return t}toScalar(e){if("bigint"==typeof e)return this.normalizePrivateKey(e);let t=e.startsWith("0x")?e.slice(2):e;if(!iV.test(t)||0===t.length||t.length>64)throw Error("Private key must be a hex string <= 32 bytes");let i=BigInt("0x"+t.padStart(64,"0"));return this.normalizePrivateKey(i)}publicKeyFromPrivate(e){let t=this.toScalar(e);return this.multiplyBase(t)}sign(e,t,i={}){let{prehashed:r=!1,nonce:n}=i,s=this.toScalar(t),a=this.normalizeMessage(e,r),o=this.bytesToScalar(a),l=n??this.deterministicNonce(s,a);for(;;){let e=this.multiplyBase(l);if(this.isInfinity(e)){l=n??this.deterministicNonce(s,a);continue}let t=this.mod(e.x,this.n);if(0n===t){l=n??this.deterministicNonce(s,a);continue}let i=this.modInv(l,this.n),r=this.mod(i*(o+t*s),this.n);if(0n===r){l=n??this.deterministicNonce(s,a);continue}return r>iz&&(r=this.n-r),{r:this.to32BytesHex(t),s:this.to32BytesHex(r)}}}verify(e,t,i,r={}){let n,{prehashed:s=!1}=r;try{n="string"==typeof i?this.pointFromHex(i):i}catch{return!1}if(null==n||!this.isOnCurve(n))return!1;let a="bigint"==typeof t.r?t.r:BigInt("0x"+t.r),o="bigint"==typeof t.s?t.s:BigInt("0x"+t.s);if(a<=0n||a>=this.n||o<=0n||o>=this.n)return!1;let l=this.bytesToScalar(this.normalizeMessage(e,s)),c=this.modInv(o,this.n),h=this.mod(l*c,this.n),d=this.mod(a*c,this.n),u=this.addPoints(this.multiplyBase(h),this.multiply(n,d));return!this.isInfinity(u)&&this.mod(u.x,this.n)===a}normalizeMessage(e,t){let i=this.toBytes(e);return t?i:new Uint8Array(ev(i))}bytesToScalar(e){return BigInt("0x"+tg(Array.from(e)))%this.n}deterministicNonce(e,t){let i=tm(this.to32BytesHex(e),"hex"),r=0;for(;r<1024;){let e=BigInt("0x"+tg(eE(i,0===r?Array.from(t):Array.from(t).concat([255&r]))))%this.n;if(e>0n)return e;r++}throw Error("Failed to derive deterministic nonce")}toBytes(e){if("string"==typeof e){let t=iV.test(e)&&e.length%2==0;return Uint8Array.from(tm(e,t?"hex":"utf8"))}if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error("Unsupported message format")}to32BytesHex(e){return e.toString(16).padStart(64,"0")}}class ij extends iU{isLockingScript(){return!0}isUnlockingScript(){return!1}}class iG extends iU{isLockingScript(){return!1}isUnlockingScript(){return!0}}class iX extends Error{txid;outputIndex;context;programCounter;stackState;altStackState;ifStackState;stackMem;altStackMem;constructor(e){const t=e.stackState.map(e=>null!=e&&void 0!==e.length?tg(e):null==e?"null/undef":"INVALID_STACK_ITEM").join(", "),i=e.altStackState.map(e=>null!=e&&void 0!==e.length?tg(e):null==e?"null/undef":"INVALID_STACK_ITEM").join(", "),r=`Context: ${e.context}, PC: ${e.programCounter}`,n=`Stack: [${t}] (len: ${e.stackState.length}, mem: ${e.stackMem})`,s=`AltStack: [${i}] (len: ${e.altStackState.length}, mem: ${e.altStackMem})`,a=`IfStack: [${e.ifStackState.join(", ")}]`;super(`Script evaluation error: ${e.message}
|
|
2
2
|
TXID: ${e.txid}, OutputIdx: ${e.outputIndex}
|
|
3
3
|
${r}
|
|
4
4
|
${n}
|
|
5
5
|
${s}
|
|
6
|
-
${a}`),this.name=this.constructor.name,this.txid=e.txid,this.outputIndex=e.outputIndex,this.context=e.context,this.programCounter=e.programCounter,this.stackState=e.stackState.map(e=>e.slice()),this.altStackState=e.altStackState.map(e=>e.slice()),this.ifStackState=e.ifStackState.slice(),this.stackMem=e.stackMem,this.altStackMem=e.altStackMem}}let iY=BigInt(0x7fffffff),iJ=Object.freeze(new A(-1).toScriptNum()),iZ=Object.freeze(Array.from({length:17},(e,t)=>Object.freeze(new A(t).toScriptNum())));function iQ(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}class i0{sourceTXID;sourceOutputIndex;sourceSatoshis;lockingScript;transactionVersion;otherInputs;outputs;inputIndex;unlockingScript;inputSequence;lockTime;context;programCounter;lastCodeSeparator;stack;altStack;ifStack;elseStack;memoryLimit;stackMem;altStackMem;isRelaxedOverride;verifyFlags;executedOpCount;returningFromConditional;sigHashCache;constructor(e){if(this.sourceTXID=e.sourceTXID,this.sourceOutputIndex=e.sourceOutputIndex,this.sourceSatoshis=e.sourceSatoshis,this.lockingScript=e.lockingScript,this.transactionVersion=e.transactionVersion,this.otherInputs=e.otherInputs,this.outputs=e.outputs,this.inputIndex=e.inputIndex,this.unlockingScript=e.unlockingScript,this.inputSequence=e.inputSequence,this.lockTime=e.lockTime,this.memoryLimit=e.memoryLimit??32e6,this.isRelaxedOverride=!0===e.isRelaxed,void 0===e.verifyFlags)this.verifyFlags=void 0;else{const t=Array.isArray(e.verifyFlags)?e.verifyFlags:e.verifyFlags.split(",");this.verifyFlags=new Set(t.map(e=>e.trim()).filter(e=>e.length>0))}this.stack=[],this.altStack=[],this.ifStack=[],this.elseStack=[],this.stackMem=0,this.altStackMem=0,this.executedOpCount=0,this.returningFromConditional=!1,this.sigHashCache={hashOutputsSingle:new Map},this.reset()}isRelaxed(){return this.isRelaxedOverride||this.transactionVersion>1}hasExplicitFlags(){return void 0!==this.verifyFlags}hasFlag(e){return this.verifyFlags?.has(e)===!0}isAfterGenesis(){return this.hasExplicitFlags()?this.hasFlag("GENESIS")||this.hasFlag("UTXO_AFTER_GENESIS")||this.hasFlag("UTXO_AFTER_CHRONICLE"):this.isRelaxed()}isAfterChronicle(){return this.hasExplicitFlags()?this.hasFlag("UTXO_AFTER_CHRONICLE"):this.isRelaxed()}shouldEnforceMinimalData(){return this.hasExplicitFlags()?this.hasFlag("MINIMALDATA"):!this.isRelaxed()}shouldEnforceLowS(){return this.hasExplicitFlags()?this.hasFlag("LOW_S"):!this.isRelaxed()}shouldEnforceNullDummy(){return this.hasExplicitFlags()?this.hasFlag("NULLDUMMY"):!this.isRelaxed()}shouldEnforceSigPushOnly(){return this.hasExplicitFlags()?this.hasFlag("SIGPUSHONLY"):!this.isRelaxed()}shouldEnforceCleanStack(){return this.hasExplicitFlags()?this.hasFlag("CLEANSTACK"):!this.isRelaxed()}shouldEnforceDerSignatures(){return!this.hasExplicitFlags()||this.hasFlag("DERSIG")||this.hasFlag("STRICTENC")||this.hasFlag("LOW_S")||this.hasFlag("SIGHASH_FORKID")}shouldEnforceStrictEncoding(){return!this.hasExplicitFlags()||this.hasFlag("STRICTENC")||this.hasFlag("SIGHASH_FORKID")}scriptNumMaxSize(){if(this.hasExplicitFlags()&&!this.isAfterGenesis())return 4}maxPushSize(){return this.hasExplicitFlags()&&!this.isAfterGenesis()?520:0x40000000}reset(){this.context="UnlockingScript",this.programCounter=0,this.lastCodeSeparator=null,this.stack=[],this.altStack=[],this.ifStack=[],this.elseStack=[],this.stackMem=0,this.altStackMem=0,this.executedOpCount=0,this.returningFromConditional=!1,this.sigHashCache={hashOutputsSingle:new Map}}ensureStackMem(e){this.stackMem+e>this.memoryLimit&&this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}ensureAltStackMem(e){this.altStackMem+e>this.memoryLimit&&this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}pushStack(e){this.ensureStackMem(e.length),this.stack.push(e),this.stackMem+=e.length}pushStackCopy(e){this.ensureStackMem(e.length);let t=e.slice();this.stack.push(t),this.stackMem+=t.length}popStack(){0===this.stack.length&&this.scriptEvaluationError("Attempted to pop from an empty stack.");let e=this.stack.pop();return void 0===e?(this.scriptEvaluationError("Attempted to pop from an empty stack."),[]):(this.stackMem-=e.length,e)}stackTop(e=-1){return(0===this.stack.length||this.stack.length<Math.abs(e)||e>=0&&e>=this.stack.length)&&this.scriptEvaluationError(`Stack underflow accessing element at index ${e}. Stack length is ${this.stack.length}.`),this.stack[this.stack.length+e]}setStack(e){this.stack=e.map(e=>e.slice()),this.stackMem=this.stack.reduce((e,t)=>e+t.length,0)}clearAltStack(){this.altStack=[],this.altStackMem=0}pushAltStack(e){this.ensureAltStackMem(e.length),this.altStack.push(e),this.altStackMem+=e.length}popAltStack(){0===this.altStack.length&&this.scriptEvaluationError("Attempted to pop from an empty alt stack.");let e=this.altStack.pop();return void 0===e?(this.scriptEvaluationError("Attempted to pop from an empty alt stack."),[]):(this.altStackMem-=e.length,e)}readScriptNumber(e){try{return A.fromScriptNum(e,this.shouldEnforceMinimalData(),this.scriptNumMaxSize())}catch(t){let e=t instanceof Error?t.message:String(t);this.scriptEvaluationError(e)}return new A(0)}isDefinedHashType(e){let t=31&e;return t>=iD.SIGHASH_ALL&&t<=iD.SIGHASH_SINGLE}checkSignatureEncoding(e){if(0===e.length)return!0;let t=this.shouldEnforceDerSignatures();if(t&&!function(e){if(e.length<9||e.length>73||48!==e[0]||e[1]!==e.length-3)return!1;let t=e[2],i=e[3];if(2!==t||0===i||5+i>=e.length)return!1;let r=4+i,n=e[r],s=e[r+1];if(2!==n||0===s||(128&e[4])!=0||i>1&&0===e[4]&&(128&e[5])==0)return!1;let a=r+2;return(128&e[a])==0&&(!(s>1)||0!==e[a]||(128&e[a+1])!=0)&&i+s+7===e.length}(e))return this.scriptEvaluationError("The signature format is invalid."),!1;try{let t=iD.fromChecksigFormat(e);if(this.shouldEnforceStrictEncoding()&&!this.isDefinedHashType(t.scope))return this.scriptEvaluationError("The signature hash type is invalid."),!1;if(this.shouldEnforceStrictEncoding()&&(t.scope&iD.SIGHASH_CHRONICLE)!=0&&!this.isAfterChronicle())return this.scriptEvaluationError("The signature hash type is invalid before Chronicle."),!1;let i=(t.scope&iD.SIGHASH_FORKID)!=0;if(this.hasExplicitFlags()){if(this.hasFlag("SIGHASH_FORKID")&&!i)return this.scriptEvaluationError("The signature must use SIGHASH_FORKID."),!1;if(!this.hasFlag("SIGHASH_FORKID")&&!this.isAfterGenesis()&&i)return this.scriptEvaluationError("The signature must not use SIGHASH_FORKID."),!1}if(this.shouldEnforceLowS()&&!t.hasLowS())return this.scriptEvaluationError("The signature must have a low S value."),!1}catch{if(t)return this.scriptEvaluationError("The signature format is invalid."),!1}return!0}parseChecksigSignature(e){try{return iD.fromChecksigFormat(e)}catch(t){if(this.shouldEnforceDerSignatures())throw t;return this.parseLaxChecksigSignature(e)}}readLaxDERLength(e,t){let i=e[t.value++];if(void 0===i)throw Error("Invalid DER length");if((128&i)==0)return i;let r=127&i;if(0===r||t.value+r>e.length)throw Error("Invalid DER length");let n=0;for(let i=0;i<r;i++)n=n<<8|(e[t.value++]??0);return n}parseLaxDERInteger(e,t,i){if(t.value>=i||2!==e[t.value++])throw Error("Invalid DER integer");let r=this.readLaxDERLength(e,t);if(t.value+r>i)throw Error("Invalid DER integer length");let n=e.slice(t.value,t.value+r);for(t.value+=r;n.length>1&&0===n[0];)n=n.slice(1);return 0===n.length&&(n=[0]),new A(n)}parseLaxChecksigSignature(e){if(0===e.length)return iD.fromChecksigFormat(e);let t=e.at(-1),i=e.slice(0,-1),r={value:0};if(48!==i[r.value++])throw Error("Signature DER must start with 0x30");let n=this.readLaxDERLength(i,r),s=Math.min(r.value+n,i.length);return new iD(this.parseLaxDERInteger(i,r,s),this.parseLaxDERInteger(i,r,s),t)}checkPublicKeyEncoding(e){if(!this.shouldEnforceStrictEncoding())return!0;if(0===e.length)return this.scriptEvaluationError("Public key is empty."),!1;if(e.length<33)return this.scriptEvaluationError("The public key is too short, it must be at least 33 bytes."),!1;if(4===e[0]){if(65!==e.length)return this.scriptEvaluationError("The non-compressed public key must be 65 bytes."),!1}else if(2!==e[0]&&3!==e[0])return this.scriptEvaluationError("The public key is in an unknown format."),!1;else if(33!==e.length)return this.scriptEvaluationError("The compressed public key must be 33 bytes."),!1;try{ii.fromDER(e)}catch{return this.scriptEvaluationError("The public key is in an unknown format."),!1}return!0}verifySignature(e,t,i){let r={sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,sourceSatoshis:this.sourceSatoshis,transactionVersion:this.transactionVersion,otherInputs:this.otherInputs,outputs:this.outputs,inputIndex:this.inputIndex,subscript:i,inputSequence:this.inputSequence,lockTime:this.lockTime,scope:e.scope,cache:this.sigHashCache};return it(new A(iD.usesOtdaSingleBug(r)?[1,...Array(31).fill(0)]:ek(iD.formatBytes(r))),e,t)}step(){if(this.stackMem>this.memoryLimit)return this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;if(this.altStackMem>this.memoryLimit)return this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;"UnlockingScript"===this.context&&this.programCounter>=this.unlockingScript.chunks.length&&(this.ifStack.length>0&&this.scriptEvaluationError("Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the unlocking script."),this.clearAltStack(),this.ifStack=[],this.elseStack=[],this.returningFromConditional=!1,this.lastCodeSeparator=null,this.context="LockingScript",this.programCounter=0);let e="UnlockingScript"===this.context?this.unlockingScript:this.lockingScript;if(this.programCounter>=e.chunks.length)return!1;let t=e.chunks[this.programCounter],i=t.op;void 0===i&&this.scriptEvaluationError(`Missing opcode in ${this.context} at pc=${this.programCounter}.`),!0===t.invalidLength&&this.scriptEvaluationError(`Malformed push data in ${this.context} at pc=${this.programCounter}.`),Array.isArray(t.data)&&t.data.length>this.maxPushSize()&&this.scriptEvaluationError(`Data push > ${this.maxPushSize()} bytes (pc=${this.programCounter}).`);let r=!this.returningFromConditional&&!this.ifStack.includes(!1);if(!this.hasExplicitFlags()||this.isAfterGenesis()||this.isAfterChronicle()||i!==iC.OP_2MUL&&i!==iC.OP_2DIV&&i!==iC.OP_VERIF&&i!==iC.OP_VERNOTIF||this.scriptEvaluationError(`${iC[i]} is disabled until Chronicle.`),r&&i>=0&&i<=iC.OP_PUSHDATA4){let e,i;this.shouldEnforceMinimalData()&&(e=t.data,i=t.op,Array.isArray(e)&&(0===e.length?i!==iC.OP_0:1===e.length&&e[0]>=1&&e[0]<=16?i!==iC.OP_1+(e[0]-1):1===e.length&&129===e[0]?i!==iC.OP_1NEGATE:e.length<=75?i!==e.length:e.length<=255?i!==iC.OP_PUSHDATA1:e.length<=65535&&i!==iC.OP_PUSHDATA2))&&this.scriptEvaluationError(`This data is not minimally-encoded. (PC: ${this.programCounter})`),this.pushStack(Array.isArray(t.data)?t.data:[])}else if(r||i>=iC.OP_IF&&i<=iC.OP_ENDIF){let e,t,n,s,a,o,l,c,h,d,u,f,p,g,y,m,b,w,v,I,k,S,E,x,T,O;if(r&&i>iC.OP_16&&(this.executedOpCount++,this.hasExplicitFlags()&&!this.isAfterGenesis()&&this.executedOpCount>500&&this.scriptEvaluationError("Script executed more than 500 opcodes.")),this.hasExplicitFlags()&&!this.isAfterChronicle()){if(r&&(i===iC.OP_SUBSTR||i===iC.OP_LEFT||i===iC.OP_RIGHT||i===iC.OP_LSHIFTNUM||i===iC.OP_RSHIFTNUM))return this.hasFlag("DISCOURAGE_UPGRADABLE_NOPS")&&this.scriptEvaluationError(`${iC[i]} is discouraged by verification flags.`),this.programCounter++,!0;if((r||!this.isAfterGenesis())&&(i===iC.OP_2MUL||i===iC.OP_2DIV)&&this.scriptEvaluationError(`${iC[i]} is disabled until Chronicle.`),(r||!this.isAfterGenesis())&&(i===iC.OP_VER||i===iC.OP_VERIF||i===iC.OP_VERNOTIF)&&this.scriptEvaluationError(`${iC[i]} is disabled until Chronicle.`),!r&&this.isAfterGenesis()&&(i===iC.OP_VERIF||i===iC.OP_VERNOTIF))return this.programCounter++,!0}switch(r&&this.hasFlag("DISCOURAGE_UPGRADABLE_NOPS")&&(i===iC.OP_NOP1||i===iC.OP_CHECKLOCKTIMEVERIFY||i===iC.OP_CHECKSEQUENCEVERIFY||i===iC.OP_NOP9||i===iC.OP_NOP10)&&this.scriptEvaluationError(`${iC[i]} is discouraged by verification flags.`),i){case iC.OP_VER:{let e=this.transactionVersion;this.pushStack([255&e,e>>>8&255,e>>>16&255,e>>>24&255]);break}case iC.OP_SUBSTR:{this.stack.length<3&&this.scriptEvaluationError("OP_SUBSTR requires at least three items to be on the stack.");let t=this.readScriptNumber(this.popStack()).toNumber(),i=this.readScriptNumber(this.popStack()).toNumber(),r=(e=this.popStack()).length;(i<0||i>=r||t<0||t>r-i)&&this.scriptEvaluationError(`OP_SUBSTR offset (${i}) must be in range [0, ${r}) and length (${t}) must be in range [0, ${r-i}]`),this.pushStack(e.slice(i,i+t));break}case iC.OP_LEFT:{this.stack.length<2&&this.scriptEvaluationError("OP_LEFT requires at least two items to be on the stack.");let t=this.readScriptNumber(this.popStack()).toNumber(),i=(e=this.popStack()).length;(t<0||t>i)&&this.scriptEvaluationError(`OP_LEFT length (${t}) must be in range [0, ${i}]`),this.pushStack(e.slice(0,t));break}case iC.OP_RIGHT:{this.stack.length<2&&this.scriptEvaluationError("OP_RIGHT requires at least two items to be on the stack.");let t=this.readScriptNumber(this.popStack()).toNumber(),i=(e=this.popStack()).length;(t<0||t>i)&&this.scriptEvaluationError(`OP_RIGHT length (${t}) must be in range [0, ${i}]`),this.pushStack(e.slice(i-t));break}case iC.OP_LSHIFTNUM:{this.stack.length<2&&this.scriptEvaluationError("OP_LSHIFTNUM requires at least two items to be on the stack.");let e=this.readScriptNumber(this.popStack()).toBigInt();e<0&&this.scriptEvaluationError("OP_LSHIFTNUM bits to shift must not be negative.");let t=new A(this.readScriptNumber(this.popStack()).toBigInt()<<e);this.pushStack(t.toScriptNum());break}case iC.OP_RSHIFTNUM:{let e;this.stack.length<2&&this.scriptEvaluationError("OP_RSHIFTNUM requires at least two items to be on the stack.");let t=this.readScriptNumber(this.popStack()).toBigInt();t<0&&this.scriptEvaluationError("OP_RSHIFTNUM bits to shift must not be negative.");let i=this.readScriptNumber(this.popStack()).toBigInt();e=new A(i<0?-(-i>>t):i>>t),this.pushStack(e.toScriptNum());break}case iC.OP_1NEGATE:this.pushStackCopy(iJ);break;case iC.OP_0:this.pushStackCopy(iZ[0]);break;case iC.OP_1:case iC.OP_2:case iC.OP_3:case iC.OP_4:case iC.OP_5:case iC.OP_6:case iC.OP_7:case iC.OP_8:case iC.OP_9:case iC.OP_10:case iC.OP_11:case iC.OP_12:case iC.OP_13:case iC.OP_14:case iC.OP_15:case iC.OP_16:f=i-(iC.OP_1-1),this.pushStackCopy(iZ[f]);break;case iC.OP_NOP:case iC.OP_NOP1:case iC.OP_CHECKLOCKTIMEVERIFY:break;case iC.OP_CHECKSEQUENCEVERIFY:if(this.hasFlag("CHECKSEQUENCEVERIFY")){this.stack.length<1&&this.scriptEvaluationError("OP_CHECKSEQUENCEVERIFY requires at least one item to be on the stack.");let e=0n;try{e=A.fromScriptNum(this.stackTop(),this.shouldEnforceMinimalData(),5).toBigInt()}catch{this.scriptEvaluationError("OP_CHECKSEQUENCEVERIFY requires a minimally-encoded numeric lock time.")}e<0n&&this.scriptEvaluationError("OP_CHECKSEQUENCEVERIFY requires a non-negative lock time."),0===Number(e&BigInt(0x80000000))&&this.transactionVersion<2&&this.scriptEvaluationError("OP_CHECKSEQUENCEVERIFY lock time is unsatisfied.")}break;case iC.OP_NOP9:case iC.OP_NOP10:break;case iC.OP_VERIF:case iC.OP_VERNOTIF:if(g=!1,r){if(this.stack.length<1&&this.scriptEvaluationError("OP_VERIF and OP_VERNOTIF require at least one item on the stack when they are used!"),4===(t=this.popStack()).length){let e=this.transactionVersion;g=iQ(t,n=[255&e,e>>>8&255,e>>>16&255,e>>>24&255])}i===iC.OP_VERNOTIF&&(g=!g)}this.ifStack.push(g),this.elseStack.push(!1);break;case iC.OP_IF:case iC.OP_NOTIF:g=!1,r&&(this.stack.length<1&&this.scriptEvaluationError("OP_IF and OP_NOTIF require at least one item on the stack when they are used!"),e=this.popStack(),this.hasFlag("MINIMALIF")&&e.length>0&&(1!==e.length||1!==e[0])&&this.scriptEvaluationError("OP_IF and OP_NOTIF require minimal truth values."),g=this.castToBool(e),i===iC.OP_NOTIF&&(g=!g)),this.ifStack.push(g),this.elseStack.push(!1);break;case iC.OP_ELSE:0===this.ifStack.length&&this.scriptEvaluationError("OP_ELSE requires a preceeding OP_IF."),this.hasExplicitFlags()&&this.isAfterGenesis()&&this.elseStack.at(-1)&&this.scriptEvaluationError("OP_ELSE may only be used once for each OP_IF or OP_NOTIF after Genesis."),this.elseStack[this.elseStack.length-1]=!0,this.ifStack[this.ifStack.length-1]=!this.ifStack.at(-1);break;case iC.OP_ENDIF:0===this.ifStack.length&&this.scriptEvaluationError("OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop(),this.elseStack.pop();break;case iC.OP_VERIFY:this.stack.length<1&&this.scriptEvaluationError("OP_VERIFY requires at least one item to be on the stack."),t=this.stackTop(),(g=this.castToBool(t))||this.scriptEvaluationError("OP_VERIFY requires the top stack value to be truthy."),this.popStack();break;case iC.OP_RETURN:this.hasExplicitFlags()&&!this.isAfterGenesis()&&this.scriptEvaluationError("OP_RETURN is invalid before Genesis."),this.ifStack.length>0?this.returningFromConditional=!0:("UnlockingScript"===this.context?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.programCounter--);break;case iC.OP_TOALTSTACK:this.stack.length<1&&this.scriptEvaluationError("OP_TOALTSTACK requires at oeast one item to be on the stack."),this.pushAltStack(this.popStack());break;case iC.OP_FROMALTSTACK:this.altStack.length<1&&this.scriptEvaluationError("OP_FROMALTSTACK requires at least one item to be on the stack."),this.pushStack(this.popAltStack());break;case iC.OP_2DROP:this.stack.length<2&&this.scriptEvaluationError("OP_2DROP requires at least two items to be on the stack."),this.popStack(),this.popStack();break;case iC.OP_2DUP:this.stack.length<2&&this.scriptEvaluationError("OP_2DUP requires at least two items to be on the stack."),t=this.stackTop(-2),n=this.stackTop(-1),this.pushStackCopy(t),this.pushStackCopy(n);break;case iC.OP_3DUP:this.stack.length<3&&this.scriptEvaluationError("OP_3DUP requires at least three items to be on the stack."),t=this.stackTop(-3),n=this.stackTop(-2),s=this.stackTop(-1),this.pushStackCopy(t),this.pushStackCopy(n),this.pushStackCopy(s);break;case iC.OP_2OVER:this.stack.length<4&&this.scriptEvaluationError("OP_2OVER requires at least four items to be on the stack."),t=this.stackTop(-4),n=this.stackTop(-3),this.pushStackCopy(t),this.pushStackCopy(n);break;case iC.OP_2ROT:{this.stack.length<6&&this.scriptEvaluationError("OP_2ROT requires at least six items to be on the stack.");let e=this.popStack(),t=this.popStack(),i=this.popStack(),r=this.popStack(),n=this.popStack(),s=this.popStack();this.pushStack(r),this.pushStack(i),this.pushStack(t),this.pushStack(e),this.pushStack(s),this.pushStack(n);break}case iC.OP_2SWAP:{this.stack.length<4&&this.scriptEvaluationError("OP_2SWAP requires at least four items to be on the stack.");let e=this.popStack(),t=this.popStack(),i=this.popStack(),r=this.popStack();this.pushStack(t),this.pushStack(e),this.pushStack(r),this.pushStack(i);break}case iC.OP_IFDUP:this.stack.length<1&&this.scriptEvaluationError("OP_IFDUP requires at least one item to be on the stack."),t=this.stackTop(),this.castToBool(t)&&this.pushStackCopy(t);break;case iC.OP_DEPTH:this.pushStack(new A(this.stack.length).toScriptNum());break;case iC.OP_DROP:this.stack.length<1&&this.scriptEvaluationError("OP_DROP requires at least one item to be on the stack."),this.popStack();break;case iC.OP_DUP:this.stack.length<1&&this.scriptEvaluationError("OP_DUP requires at least one item to be on the stack."),this.pushStackCopy(this.stackTop());break;case iC.OP_NIP:this.stack.length<2&&this.scriptEvaluationError("OP_NIP requires at least two items to be on the stack."),n=this.popStack(),this.popStack(),this.pushStack(n);break;case iC.OP_OVER:this.stack.length<2&&this.scriptEvaluationError("OP_OVER requires at least two items to be on the stack."),this.pushStackCopy(this.stackTop(-2));break;case iC.OP_PICK:case iC.OP_ROLL:{this.stack.length<2&&this.scriptEvaluationError(`${iC[i]} requires at least two items to be on the stack.`);let e=(c=this.readScriptNumber(this.popStack())).toBigInt();(e<0n||e>=BigInt(this.stack.length))&&this.scriptEvaluationError(`${iC[i]} requires the top stack element to be 0 or a positive number less than the current size of the stack.`);let t=Number(e),r=this.stack[this.stack.length-1-t];i===iC.OP_ROLL?(this.stack.splice(this.stack.length-1-t,1),this.stackMem-=r.length,this.pushStack(r)):this.pushStackCopy(r);break}case iC.OP_ROT:this.stack.length<3&&this.scriptEvaluationError("OP_ROT requires at least three items to be on the stack."),l=this.popStack(),o=this.popStack(),a=this.popStack(),this.pushStack(o),this.pushStack(l),this.pushStack(a);break;case iC.OP_SWAP:this.stack.length<2&&this.scriptEvaluationError("OP_SWAP requires at least two items to be on the stack."),o=this.popStack(),a=this.popStack(),this.pushStack(o),this.pushStack(a);break;case iC.OP_TUCK:this.stack.length<2&&this.scriptEvaluationError("OP_TUCK requires at least two items to be on the stack."),t=this.stackTop(-1),this.ensureStackMem(t.length),this.stack.splice(-2,0,t.slice()),this.stackMem+=t.length;break;case iC.OP_SIZE:this.stack.length<1&&this.scriptEvaluationError("OP_SIZE requires at least one item to be on the stack."),this.pushStack(new A(this.stackTop().length).toScriptNum());break;case iC.OP_AND:case iC.OP_OR:case iC.OP_XOR:{this.stack.length<2&&this.scriptEvaluationError(`${iC[i]} requires at least two items on the stack.`),n=this.popStack(),(t=this.popStack()).length!==n.length&&this.scriptEvaluationError(`${iC[i]} requires the top two stack items to be the same size.`);let e=Array(t.length);for(let r=0;r<t.length;r++)i===iC.OP_AND?e[r]=t[r]&n[r]:i===iC.OP_OR?e[r]=t[r]|n[r]:e[r]=t[r]^n[r];this.pushStack(e);break}case iC.OP_INVERT:{this.stack.length<1&&this.scriptEvaluationError("OP_INVERT requires at least one item to be on the stack.");let t=Array((e=this.popStack()).length);for(let i=0;i<e.length;i++)t[i]=255&~e[i];this.pushStack(t);break}case iC.OP_LSHIFT:case iC.OP_RSHIFT:{let e;this.stack.length<2&&this.scriptEvaluationError(`${iC[i]} requires at least two items to be on the stack.`),d=this.readScriptNumber(this.popStack()),t=this.popStack();let r=d.toBigInt();if(r<0n&&this.scriptEvaluationError(`${iC[i]} requires the top item on the stack not to be negative.`),0===t.length){this.pushStack([]);break}if(h=new A(t),i===iC.OP_LSHIFT){e=h.ushln(r);let i=new A(1).ushln(8*t.length).isubn(1);e=e.iand(i)}else e=h.ushrn(r);let n=e.toArray("be",t.length);this.pushStack(n);break}case iC.OP_EQUAL:case iC.OP_EQUALVERIFY:this.stack.length<2&&this.scriptEvaluationError(`${iC[i]} requires at least two items to be on the stack.`),n=this.popStack(),g=iQ(t=this.popStack(),n),this.pushStack(g?[1]:[]),i===iC.OP_EQUALVERIFY&&(g||this.scriptEvaluationError("OP_EQUALVERIFY requires the top two stack items to be equal."),this.popStack());break;case iC.OP_1ADD:case iC.OP_1SUB:case iC.OP_2MUL:case iC.OP_2DIV:case iC.OP_NEGATE:case iC.OP_ABS:case iC.OP_NOT:case iC.OP_0NOTEQUAL:switch(this.stack.length<1&&this.scriptEvaluationError(`${iC[i]} requires at least one item to be on the stack.`),c=this.readScriptNumber(this.popStack()),i){case iC.OP_1ADD:c=c.add(new A(1));break;case iC.OP_1SUB:c=c.sub(new A(1));break;case iC.OP_2MUL:c=c.mul(new A(2));break;case iC.OP_2DIV:c=c.div(new A(2));break;case iC.OP_NEGATE:c=c.neg();break;case iC.OP_ABS:c.isNeg()&&(c=c.neg());break;case iC.OP_NOT:c=new A(+(0===c.cmpn(0)));break;case iC.OP_0NOTEQUAL:c=new A(+(0!==c.cmpn(0)))}this.pushStack(c.toScriptNum());break;case iC.OP_ADD:case iC.OP_SUB:case iC.OP_MUL:case iC.OP_DIV:case iC.OP_MOD:case iC.OP_BOOLAND:case iC.OP_BOOLOR:case iC.OP_NUMEQUAL:case iC.OP_NUMEQUALVERIFY:case iC.OP_NUMNOTEQUAL:case iC.OP_LESSTHAN:case iC.OP_GREATERTHAN:case iC.OP_LESSTHANOREQUAL:case iC.OP_GREATERTHANOREQUAL:case iC.OP_MIN:case iC.OP_MAX:{this.stack.length<2&&this.scriptEvaluationError(`${iC[i]} requires at least two items to be on the stack.`),n=this.popStack(),t=this.popStack(),d=this.readScriptNumber(n),h=this.readScriptNumber(t);let e=0;switch(i){case iC.OP_MUL:e=h.byteLength()+d.byteLength();break;case iC.OP_ADD:case iC.OP_SUB:e=Math.max(h.byteLength(),d.byteLength())+1;break;default:e=Math.max(h.byteLength(),d.byteLength())}this.ensureStackMem(e);let r=new A(0);switch(i){case iC.OP_ADD:r=h.add(d);break;case iC.OP_SUB:r=h.sub(d);break;case iC.OP_MUL:r=h.mul(d);break;case iC.OP_DIV:0===d.cmpn(0)&&this.scriptEvaluationError("OP_DIV cannot divide by zero!"),r=h.div(d);break;case iC.OP_MOD:0===d.cmpn(0)&&this.scriptEvaluationError("OP_MOD cannot divide by zero!"),r=h.mod(d);break;case iC.OP_BOOLAND:r=new A(+(0!==h.cmpn(0)&&0!==d.cmpn(0)));break;case iC.OP_BOOLOR:r=new A(+(0!==h.cmpn(0)||0!==d.cmpn(0)));break;case iC.OP_NUMEQUAL:case iC.OP_NUMEQUALVERIFY:r=new A(+(0===h.cmp(d)));break;case iC.OP_NUMNOTEQUAL:r=new A(+(0!==h.cmp(d)));break;case iC.OP_LESSTHAN:r=new A(+(0>h.cmp(d)));break;case iC.OP_GREATERTHAN:r=new A(+(h.cmp(d)>0));break;case iC.OP_LESSTHANOREQUAL:r=new A(+(0>=h.cmp(d)));break;case iC.OP_GREATERTHANOREQUAL:r=new A(+(h.cmp(d)>=0));break;case iC.OP_MIN:r=0>h.cmp(d)?h:d;break;case iC.OP_MAX:r=h.cmp(d)>0?h:d}this.pushStack(r.toScriptNum()),i===iC.OP_NUMEQUALVERIFY&&(this.castToBool(this.stackTop())||this.scriptEvaluationError("OP_NUMEQUALVERIFY requires the top stack item to be truthy."),this.popStack());break}case iC.OP_WITHIN:this.stack.length<3&&this.scriptEvaluationError("OP_WITHIN requires at least three items to be on the stack."),u=this.readScriptNumber(this.popStack()),d=this.readScriptNumber(this.popStack()),g=(h=this.readScriptNumber(this.popStack())).cmp(d)>=0&&0>h.cmp(u),this.pushStack(g?[1]:[]);break;case iC.OP_RIPEMD160:case iC.OP_SHA1:case iC.OP_SHA256:case iC.OP_HASH160:case iC.OP_HASH256:{this.stack.length<1&&this.scriptEvaluationError(`${iC[i]} requires at least one item to be on the stack.`),e=this.popStack();let t=[];i===iC.OP_RIPEMD160?t=eb(e):i===iC.OP_SHA1?t=ew(e):i===iC.OP_SHA256?t=ev(e):i===iC.OP_HASH160?t=eS(e):i===iC.OP_HASH256&&(t=ek(e)),this.pushStack(t);break}case iC.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case iC.OP_CHECKSIG:case iC.OP_CHECKSIGVERIFY:if(this.stack.length<2&&this.scriptEvaluationError(`${iC[i]} requires at least two items to be on the stack.`),w=this.popStack(),b=this.popStack(),this.checkSignatureEncoding(b)&&this.checkPublicKeyEncoding(w)||this.scriptEvaluationError(`${iC[i]} requires correct encoding for the public key and signature.`),y=!1,b.length>0)try{v=this.parseChecksigSignature(b);let e=("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1);(m=new iU(e)).findAndDelete(new iU().writeBin(b)),I=ii.fromDER(w),y=this.verifySignature(v,I,m)}catch{y=!1}!y&&this.hasFlag("NULLFAIL")&&b.length>0&&this.scriptEvaluationError(`${iC[i]} requires failing signatures to be empty.`),this.pushStack(y?[1]:[]),i===iC.OP_CHECKSIGVERIFY&&(y||this.scriptEvaluationError("OP_CHECKSIGVERIFY requires that a valid signature is provided."),this.popStack());break;case iC.OP_CHECKMULTISIG:case iC.OP_CHECKMULTISIGVERIFY:{k=1,this.stack.length<k&&this.scriptEvaluationError(`${iC[i]} requires at least 1 item for nKeys.`);let e=this.readScriptNumber(this.stackTop(-k)).toBigInt(),t=this.hasExplicitFlags()&&!this.isAfterGenesis()?BigInt(20):iY;(e<0n||e>t)&&this.scriptEvaluationError(`${iC[i]} requires a key count between 0 and ${t.toString()}.`);let r=x=Number(e);S=++k,k+=x,this.stack.length<k&&this.scriptEvaluationError(`${iC[i]} stack too small for nKeys and keys. Need ${k}, have ${this.stack.length}.`);let n=this.readScriptNumber(this.stackTop(-k)).toBigInt();(n<0n||n>BigInt(x))&&this.scriptEvaluationError(`${iC[i]} requires the number of signatures to be no greater than the number of keys.`);let s=T=Number(n);E=++k,k+=T,this.stack.length<k&&this.scriptEvaluationError(`${iC[i]} stack too small for N, keys, M, sigs, and dummy. Need ${k}, have ${this.stack.length}.`),m=new iU(("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1));let a=!1;for(let e=0;e<T;e++)(b=this.stackTop(-E-e)).length>0&&(a=!0),m.findAndDelete(new iU().writeBin(b));for(y=!0;y&&T>0;){if(0===x){y=!1;break}if(b=this.stackTop(-E),w=this.stackTop(-S),this.checkSignatureEncoding(b)&&this.checkPublicKeyEncoding(w)||this.scriptEvaluationError(`${iC[i]} requires correct encoding for the public key and signature.`),O=!1,b.length>0)try{v=this.parseChecksigSignature(b),I=ii.fromDER(w),O=this.verifySignature(v,I,m)}catch{O=!1}O&&(E++,T--),S++,T>--x&&(y=!1)}!y&&this.hasFlag("NULLFAIL")&&a&&this.scriptEvaluationError(`${iC[i]} requires failing signatures to be empty.`);let o=1+r+1+s+1-1;for(;o>0;)this.popStack(),o--;this.stack.length<1&&this.scriptEvaluationError(`${iC[i]} requires an extra item (dummy) to be on the stack.`);let l=this.popStack();this.shouldEnforceNullDummy()&&l.length>0&&this.scriptEvaluationError(`${iC[i]} requires the extra stack item (dummy) to be empty.`),this.pushStack(y?[1]:[]),i===iC.OP_CHECKMULTISIGVERIFY&&(y||this.scriptEvaluationError("OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."),this.popStack());break}case iC.OP_CAT:{this.stack.length<2&&this.scriptEvaluationError("OP_CAT requires at least two items to be on the stack."),n=this.popStack();let e=(t=this.popStack()).concat(n);e.length>this.maxPushSize()&&this.scriptEvaluationError(`It's not currently possible to push data larger than ${this.maxPushSize()} bytes.`),this.pushStack(e);break}case iC.OP_SPLIT:{this.stack.length<2&&this.scriptEvaluationError("OP_SPLIT requires at least two items to be on the stack.");let e=this.popStack(),t=this.popStack(),i=this.readScriptNumber(e).toBigInt();(i<0n||i>BigInt(t.length))&&this.scriptEvaluationError("OP_SPLIT requires the first stack item to be a non-negative number less than or equal to the size of the second-from-top stack item.");let r=Number(i);this.pushStack(t.slice(0,r)),this.pushStack(t.slice(r));break}case iC.OP_NUM2BIN:{this.stack.length<2&&this.scriptEvaluationError("OP_NUM2BIN requires at least two items to be on the stack.");let e=this.readScriptNumber(this.popStack()).toBigInt();(e>BigInt(this.maxPushSize())||e<0n)&&this.scriptEvaluationError(`It's not currently possible to push data larger than ${this.maxPushSize()} bytes or negative size.`),p=Number(e);let t=this.popStack();if((t=t_(t)).length>p&&this.scriptEvaluationError("OP_NUM2BIN requires that the size expressed in the top stack item is large enough to hold the value expressed in the second-from-top stack item."),t.length===p){this.pushStack(t);break}let i=Array(p).fill(0),r=0;t.length>0&&(r=128&t.at(-1),t[t.length-1]&=127);for(let e=0;e<t.length;e++)i[e]=t[e];0!==r&&(i[p-1]|=128),this.pushStack(i);break}case iC.OP_BIN2NUM:{this.stack.length<1&&this.scriptEvaluationError("OP_BIN2NUM requires at least one item to be on the stack.");let e=t_(t=this.popStack());!function(e,t=Number.MAX_SAFE_INTEGER){return!(e.length>t)&&(!(e.length>0)||(127&e.at(-1))!=0||!(e.length<=1)&&(128&e.at(-2))!=0)}(e)&&this.scriptEvaluationError("OP_BIN2NUM requires that the resulting number is valid."),this.pushStack(e);break}default:this.scriptEvaluationError(`Invalid opcode ${i} (pc=${this.programCounter}).`)}}return this.returningFromConditional&&0===this.ifStack.length?this.programCounter=e.chunks.length:this.programCounter++,this.hasExplicitFlags()&&!this.isAfterGenesis()&&this.stack.length+this.altStack.length>1e3&&this.scriptEvaluationError("Stack item count has exceeded 1000."),!0}validate(){this.shouldEnforceSigPushOnly()&&!this.unlockingScript.isPushOnly()&&this.scriptEvaluationError("Unlocking scripts can only contain push operations, and no other opcodes.");let e=this.lockingScript,t=this.hasFlag("P2SH")&&!this.isAfterGenesis()&&this.isP2SHLockingScript(this.lockingScript);t&&!this.unlockingScript.isPushOnly()&&this.scriptEvaluationError("P2SH unlocking scripts can only contain push operations."),this.reset(),this.runScript("UnlockingScript");let i=this.stack.map(e=>e.slice());this.runScript("LockingScript"),this.requireTruthyTopStack();try{if(t){0===i.length&&this.scriptEvaluationError("P2SH evaluation requires a redeem script on the stack.");let e=i.pop();if(void 0===e)return this.scriptEvaluationError("P2SH evaluation requires a redeem script on the stack."),!1;this.setStack(i);let t=iU.fromBinary(e);this.lockingScript=new ij(t.chunks),this.runScript("LockingScript")}}finally{this.lockingScript=e}return this.shouldEnforceCleanStack()&&1!==this.stack.length&&this.scriptEvaluationError(`The clean stack rule requires exactly one item to be on the stack after script execution, found ${this.stack.length}.`),this.requireTruthyTopStack(),!0}runScript(e){this.context=e,this.programCounter=0,this.ifStack=[],this.elseStack=[],this.returningFromConditional=!1,this.clearAltStack(),this.lastCodeSeparator=null;let t="UnlockingScript"===e?this.unlockingScript:this.lockingScript;for(this.hasExplicitFlags()&&!this.isAfterGenesis()&&t.toUint8Array().length>1e4&&this.scriptEvaluationError("Script size exceeds 10000 bytes.");this.programCounter<t.chunks.length;)this.step();this.ifStack.length>0&&this.scriptEvaluationError("Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the script."),this.ifStack=[],this.elseStack=[],this.clearAltStack(),this.lastCodeSeparator=null}isP2SHLockingScript(e){let t=e.chunks;return 3===t.length&&t[0].op===iC.OP_HASH160&&20===t[1].op&&Array.isArray(t[1].data)&&20===t[1].data.length&&t[2].op===iC.OP_EQUAL}requireTruthyTopStack(){0===this.stack.length?this.scriptEvaluationError("The top stack element must be truthy after script evaluation (stack is empty)."):this.castToBool(this.stackTop())||this.scriptEvaluationError("The top stack element must be truthy after script evaluation.")}castToBool(e){if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(0!==e[t])return t!==e.length-1||128!==e[t];return!1}scriptEvaluationError(e){throw new iX({message:e,txid:this.sourceTXID,outputIndex:this.sourceOutputIndex,context:this.context,programCounter:this.programCounter,stackState:this.stack,altStackState:this.altStack,ifStackState:this.ifStack,stackMem:this.stackMem,altStackMem:this.altStackMem})}}function i1(e,t){let i=iD.SIGHASH_FORKID;return"all"===e&&(i|=iD.SIGHASH_ALL),"none"===e&&(i|=iD.SIGHASH_NONE),"single"===e&&(i|=iD.SIGHASH_SINGLE),t&&(i|=iD.SIGHASH_ANYONECANPAY),i}function i2(e,t,i,r){let n=e.inputs[t],s=e.inputs.filter((e,i)=>i!==t),a=n.sourceTXID??n.sourceTransaction?.id("hex");if(null==a||void 0===a||""===a)throw Error("The input sourceTXID or sourceTransaction is required for transaction signing.");let o=i??n.sourceTransaction?.outputs[n.sourceOutputIndex].satoshis;if(null==o||void 0===o)throw Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");let l=r??n.sourceTransaction?.outputs[n.sourceOutputIndex].lockingScript;if(null==l)throw Error("The lockingScript or input sourceTransaction is required for transaction signing.");return{sourceTXID:a,sourceSatoshis:o,lockingScript:l,otherInputs:s}}function i8(e){let{tx:t,inputIndex:i,signatureScope:r,sourceTXID:n,sourceSatoshis:s,lockingScript:a,otherInputs:o,inputSequence:l}=e,c=t.inputs[i];return iD.format({sourceTXID:n,sourceOutputIndex:tB(c.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:s,transactionVersion:t.version,otherInputs:o,inputIndex:i,outputs:t.outputs,inputSequence:l??tB(c.sequence,"input.sequence must have value"),subscript:a,lockTime:t.lockTime,scope:r})}class i3{lock(e){let t;if("string"==typeof e){let i=tO(e);if(0!==i.prefix[0]&&111!==i.prefix[0])throw Error("only P2PKH is supported");t=i.data}else t=e;if(20!==t.length)throw Error("P2PKH hash length must be 20 bytes");return new ij([{op:iC.OP_DUP},{op:iC.OP_HASH160},{op:t.length,data:t},{op:iC.OP_EQUALVERIFY},{op:iC.OP_CHECKSIG}])}unlock(e,t="all",i=!1,r,n){return{sign:async(s,a)=>{let o=i1(t,i),l=i2(s,a,r,n);r=l.sourceSatoshis,n=l.lockingScript;let c=i8({tx:s,inputIndex:a,signatureScope:o,sourceTXID:l.sourceTXID,sourceSatoshis:l.sourceSatoshis,lockingScript:l.lockingScript,otherInputs:l.otherInputs}),h=e.sign(ev(c)),d=new iD(h.r,h.s,o).toChecksigFormat(),u=e.toPublicKey().encode(!0);return new iG([{op:d.length,data:d},{op:u.length,data:u}])},estimateLength:async()=>108}}}class i5{type="raw";constructor(e="raw"){this.type=e}lock(e){let t=[{op:iC.OP_OVER},{op:iC.OP_3},{op:iC.OP_SPLIT},{op:iC.OP_NIP},{op:iC.OP_1},{op:iC.OP_SPLIT},{op:iC.OP_SWAP},{op:iC.OP_SPLIT},{op:iC.OP_DROP}];return"raw"!==this.type&&t.push({op:iC["OP_"+this.type]}),t.push({op:e.length,data:e}),t.push({op:iC.OP_EQUALVERIFY}),t.push({op:iC.OP_CHECKSIG}),new ij(t)}unlock(e,t,i="all",r=!1){return{sign:async(n,s)=>{t??=ih.fromRandom();let a=iD.SIGHASH_FORKID;"all"===i&&(a|=iD.SIGHASH_ALL),"none"===i&&(a|=iD.SIGHASH_NONE),"single"===i&&(a|=iD.SIGHASH_SINGLE),r&&(a|=iD.SIGHASH_ANYONECANPAY);let o=[...n.inputs],[l]=o.splice(s,1);if("object"!=typeof l.sourceTransaction)throw TypeError("The source transaction is needed for transaction signing.");let c=iD.format({sourceTXID:l.sourceTransaction?.id("hex")??"",sourceOutputIndex:l.sourceOutputIndex??0,sourceSatoshis:l.sourceTransaction?.outputs[l.sourceOutputIndex]?.satoshis??0,transactionVersion:n.version,otherInputs:o,inputIndex:s,outputs:n.outputs,inputSequence:l.sequence??0xffffffff,subscript:l.sourceTransaction?.outputs[l.sourceOutputIndex]?.lockingScript??new iU,lockTime:n.lockTime,scope:a}),h=t.sign(ev(c),void 0,!0,e),d=new iD(h.r,h.s,a).toChecksigFormat(),u=t.toPublicKey().encode(!0);return new iG([{op:d.length,data:d},{op:u.length,data:u}])},estimateLength:async()=>108}}}let i6=e=>0===e.length||1===e.length&&0===e[0]?{op:0}:1===e.length&&e[0]>0&&e[0]<=16?{op:80+e[0]}:1===e.length&&129===e[0]?{op:79}:e.length<=75?{op:e.length,data:e}:e.length<=255?{op:76,data:e}:e.length<=65535?{op:77,data:e}:{op:78,data:e};class i4{wallet;originator;static decode(e,t="before"){let i,r;if("before"===t)i=ii.fromString(tg(tB(e.chunks[0].data,"script.chunks[0].data must have value"))),r=2;else{let t=e.chunks.length-1;if(e.chunks[t].op!==iC.OP_CHECKSIG)throw Error("Expected OP_CHECKSIG at the end of the script");i=ii.fromString(tg(tB(e.chunks[t-1].data,"public key chunk data must have value"))),r=0}let n=[];for(let t=r;t<e.chunks.length;t++){let i=e.chunks[t+1]?.op,r=e.chunks[t].data??[];if(0===r.length&&(e.chunks[t].op>=80&&e.chunks[t].op<=95?r=[e.chunks[t].op-80]:0===e.chunks[t].op?r=[0]:79===e.chunks[t].op&&(r=[129])),n.push(r),i===iC.OP_DROP||i===iC.OP_2DROP)break}return{fields:n,lockingPublicKey:i}}constructor(e,t){this.wallet=e,this.originator=t}async lock(e,t,i,r,n=!1,s=!0,a="before"){let{publicKey:o}=await this.wallet.getPublicKey({protocolID:t,keyID:i,counterparty:r,forSelf:n},this.originator),l=[],c=[];if(l.push({op:o.length/2,data:tm(o,"hex")}),l.push({op:iC.OP_CHECKSIG}),s){let n=e.flat(),{signature:s}=await this.wallet.createSignature({data:n,protocolID:t,keyID:i,counterparty:r},this.originator);e.push(s)}for(let t of e)c.push(i6(t));let h=e.length;for(;h>1;)c.push({op:iC.OP_2DROP}),h-=2;return new ij((0!==h&&c.push({op:iC.OP_DROP}),"before"===a)?[...l,...c]:[...c,...l])}unlock(e,t,i,r="all",n=!1,s,a){return{sign:async(o,l)=>{let c=i1(r,n),h=i2(o,l,s,a);s=h.sourceSatoshis,a=h.lockingScript;let d=ev(i8({tx:o,inputIndex:l,signatureScope:c,sourceTXID:h.sourceTXID,sourceSatoshis:h.sourceSatoshis,lockingScript:h.lockingScript,otherInputs:h.otherInputs,inputSequence:o.inputs[l].sequence??0xffffffff})),{signature:u}=await this.wallet.createSignature({data:d,protocolID:e,keyID:t,counterparty:i},this.originator),f=t2.fromDER([...u]),p=new iD(f.r,f.s,c).toChecksigFormat();return new iG([{op:p.length,data:p}])},estimateLength:async()=>73}}}class i9{value;constructor(e){this.value=e}async computeFee(e){let t,i=e=>e>0x100000000?9:e>65536?5:e>253?3:1;t=4+i(e.inputs.length);for(let r=0;r<e.inputs.length;r++){let n,s=e.inputs[r];if(t+=40,"object"==typeof s.unlockingScript)n=s.unlockingScript.toBinary().length;else if("object"==typeof s.unlockingScriptTemplate)n=await s.unlockingScriptTemplate.estimateLength(e,r);else throw TypeError("All inputs must have an unlocking script or an unlocking script template for sat/kb fee computation.");t+=i(n),t+=n}for(let r of(t+=i(e.outputs.length),e.outputs)){t+=8;let e=r.lockingScript.toBinary().length;t+=i(e),t+=e}return Math.ceil((t+=4)/1e3*this.value)}}class i7 extends i9{static ARC_POLICY_URL="https://arc.gorillapool.io/v1/policy";static instance=null;cachedRate=null;cacheTimestamp=0;cacheValidityMs;constructor(e=3e5){super(100),this.cacheValidityMs=e}static getInstance(e=3e5){return i7.instance||(i7.instance=new i7(e)),i7.instance}async fetchFeeRate(){let e=Date.now();if(null!==this.cachedRate&&e-this.cacheTimestamp<this.cacheValidityMs)return this.cachedRate;try{let t=await fetch(i7.ARC_POLICY_URL);if(!t.ok)throw Error(`HTTP ${t.status}: ${t.statusText}`);let i=await t.json();if(!i.policy?.miningFee||"number"!=typeof i.policy.miningFee.satoshis||"number"!=typeof i.policy.miningFee.bytes)throw Error("Invalid policy response format");let r=i.policy.miningFee.satoshis/i.policy.miningFee.bytes*1e3;return this.cachedRate=r,this.cacheTimestamp=e,r}catch(e){if(null!==this.cachedRate)return console.warn("Failed to fetch live fee rate, using cached value:",e),this.cachedRate;return console.warn("Failed to fetch live fee rate, using default 100 sat/kb:",e),100}}async computeFee(e){let t=await this.fetchFeeRate();return this.value=t,super.computeFee(e)}}function re(e,t,i,r){return new Promise((n,s)=>{let a=e.request(t,i,e=>{let t="";e.on("data",e=>{t+=e}),e.on("end",()=>{let i=e.statusCode>=200&&e.statusCode<=299,r=e.headers["content-type"],s=""!==t&&"string"==typeof r&&r.startsWith("application/json")?JSON.parse(t):t;n({status:e.statusCode,statusText:e.statusMessage,ok:i,data:s})})});a.on("error",e=>{s(e)}),null!==i.data&&void 0!==i.data&&a.write(r(i.data)),a.end()})}class rt{https;constructor(e){this.https=e}async request(e,t){return await re(this.https,e,t,e=>JSON.stringify(e))}}class ri{fetch;constructor(e){this.fetch=e}async request(e,t){let i={method:t.method,headers:t.headers,body:JSON.stringify(t.data)},r=await this.fetch(e,i),n=r.headers.get("Content-Type"),s=n?.startsWith("application/json")?await r.json():await r.text();return{ok:r.ok,status:r.status,statusText:r.statusText,data:s}}}function rr(){let e={async request(){throw Error("No method available to perform HTTP request")}};if(void 0!==globalThis.window&&"function"==typeof globalThis.window.fetch)return new ri(globalThis.window.fetch.bind(globalThis.window));if("function"==typeof globalThis.fetch)return new ri(globalThis.fetch.bind(globalThis));if("u"<typeof require)return e;try{let e=require("node:https");return new rt(e)}catch(t){return e}}function rn(){return`ts-sdk-${tg(ia(16))}`}class rs{URL;apiKey;deploymentId;callbackUrl;callbackToken;headers;httpClient;constructor(e,t){if(this.URL=e,"string"==typeof t)this.apiKey=t,this.httpClient=rr(),this.deploymentId=rn(),this.callbackToken=void 0,this.callbackUrl=void 0;else{const{apiKey:e,deploymentId:i,httpClient:r,callbackToken:n,callbackUrl:s,headers:a}=t??{};this.apiKey=e,this.httpClient=r??rr(),this.deploymentId=i??rn(),this.callbackToken=n,this.callbackUrl=s,this.headers=a}}requestHeaders(){let e={"Content-Type":"application/json","XDeployment-ID":this.deploymentId};if(null!=this.apiKey&&""!==this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),null!=this.callbackUrl&&""!==this.callbackUrl&&(e["X-CallbackUrl"]=this.callbackUrl),null!=this.callbackToken&&""!==this.callbackToken&&(e["X-CallbackToken"]=this.callbackToken),null!=this.headers)for(let t in this.headers)e[t]=this.headers[t];return e}async broadcast(e){let t;try{t=e.toHexEF()}catch(i){if("All inputs must have source transactions when serializing to EF format"===i.message)t=e.toHex();else throw i}let i={method:"POST",headers:this.requestHeaders(),data:{rawTx:t}};try{let e=await this.httpClient.request(`${this.URL}/v1/tx`,i);if(e.ok){let{txid:t,extraInfo:i,txStatus:r,competingTxs:n}=e.data,s=i?.toUpperCase().includes("ORPHAN")||r?.toUpperCase().includes("ORPHAN");if(["DOUBLE_SPEND_ATTEMPTED","REJECTED","INVALID","MALFORMED","MINED_IN_STALE_BLOCK"].includes(r?.toUpperCase())||s){let e={status:"error",code:r??"UNKNOWN",txid:t,description:`${r??""} ${i??""}`.trim()};return null!=n&&(e.more={competingTxs:n}),e}let a={status:"success",txid:t,message:`${r} ${i}`};return null!=n&&(a.competingTxs=n),a}{let t=typeof e.status,i={status:"error",code:"number"===t||"string"===t?e.status.toString():"ERR_UNKNOWN",description:"Unknown error"},r=e.data;if("string"==typeof r)try{r=JSON.parse(e.data)}catch{}return"object"==typeof r&&(null!==r&&(i.more=r),null!=r&&"string"==typeof r.txid&&(i.txid=r.txid),null!=r&&"detail"in r&&"string"==typeof r.detail&&(i.description=r.detail)),i}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}async broadcastMany(e){let t=e.map(e=>{try{return{rawTx:e.toHexEF()}}catch(t){if("All inputs must have source transactions when serializing to EF format"===t.message)return{rawTx:e.toHex()};throw t}}),i={method:"POST",headers:this.requestHeaders(),data:t};try{return(await this.httpClient.request(`${this.URL}/v1/txs`,i)).data}catch(i){let t={status:"error",code:"500",description:"string"==typeof i.message?i.message:"Internal Server Error"};return e.map(()=>t)}}}function ra(e=!1,t={}){return new rs(e?"https://testnet.arc.gorillapool.io":"https://arc.gorillapool.io",t)}class ro{network;apiKey;URL;httpClient;constructor(e="main",t={}){const{apiKey:i,httpClient:r}=t;this.network=e,this.URL=`https://api.whatsonchain.com/v1/bsv/${e}`,this.httpClient=r??rr(),this.apiKey=i??""}async isValidRootForHeight(e,t){let i={method:"GET",headers:this.getHttpHeaders()},r=await this.httpClient.request(`${this.URL}/block/${t}/header`,i);if(r.ok){let{merkleroot:t}=r.data;return t===e}if(404===r.status)return!1;throw Error(`Failed to verify merkleroot for height ${t} because of an error: ${JSON.stringify(r.data)} `)}async currentHeight(){try{let e={method:"GET",headers:this.getHttpHeaders()},t=await this.httpClient.request(`${this.URL}/block/headers`,e);if(t.ok)return t.data[0].height;throw Error(`Failed to get current height because of an error: ${JSON.stringify(t.data)} `)}catch(e){throw Error(`Failed to get current height because of an error: ${e instanceof Error?e.message:String(e)}`)}}getHttpHeaders(){let e={Accept:"application/json"};return"string"==typeof this.apiKey&&""!==this.apiKey.trim()&&(e.Authorization=this.apiKey),e}}function rl(){return new ro}class rc{blockHeight;path;static fromHex(e){return rc.fromBinary(tm(e,"hex"))}static fromReader(e,t=!0){let i,r,n,s=e.readVarIntNum(),a=e.readUInt8(),o=Array(a).fill(null).map(()=>[]);for(let t=0;t<a;t++){for(n=e.readVarIntNum();n>0;){r=e.readVarIntNum(),i=e.readUInt8();let s={offset:r};(1&i)==1?s.duplicate=!0:((2&i)!=0&&(s.txid=!0),s.hash=tg(e.read(32).reverse())),Array.isArray(o[t])&&0!==o[t].length||(o[t]=[]),o[t].push(s),n--}o[t].sort((e,t)=>e.offset-t.offset)}return new rc(s,o,t)}static fromBinary(e){let t=new tc(e);return rc.fromReader(t)}static fromCoinbaseTxidAndHeight(e,t){return new rc(t,[[{offset:0,hash:e,txid:!0}]])}constructor(e,t,i=!0){let r;this.blockHeight=e,this.path=t;const n=Array(this.path.length).fill(0).map(()=>new Set);this.path.forEach((e,t)=>{if(0===e.length&&0===t)throw Error(`Empty level at height: ${t}`);let r=new Set;e.forEach(e=>{if(r.has(e.offset))throw Error(`Duplicate offset: ${e.offset}, at height: ${t}`);if(r.add(e.offset),0===t){if(!0!==e.duplicate)for(let t=1;t<this.path.length;t++)n[t].add(e.offset>>t^1)}else if(i&&!n[t].has(e.offset))throw Error(`Invalid offset: ${e.offset}, at height: ${t}, with legal offsets: ${Array.from(n[t]).join(", ")}`)})}),this.path[0].forEach((e,t)=>{if(0===t&&(r=this.computeRoot(e.hash)),r!==this.computeRoot(e.hash))throw Error("Mismatched roots")})}toWriter(e){e.writeVarIntNum(this.blockHeight);let t=this.path.length;e.writeUInt8(t);for(let i=0;i<t;i++){let t=Object.keys(this.path[i]).length;for(let r of(e.writeVarIntNum(t),this.path[i])){e.writeVarIntNum(r.offset);let t=0;r?.duplicate===!0&&(t|=1),r?.txid!==void 0&&null!==r.txid&&(t|=2),e.writeUInt8(t),(1&t)==0&&e.write(tm(r.hash,"hex").reverse())}}}toBinary(){let e=new tP;return this.toWriter(e),e.toArray()}toBinaryUint8Array(){let e=new tl;return this.toWriter(e),e.toUint8Array()}toHex(){return tg(this.toBinaryUint8Array())}indexOf(e){let t=this.path[0].find(t=>t.hash===e);if(null==t)throw Error(`Transaction ID ${e} not found in the Merkle Path`);return t.offset}computeRoot(e){if("string"!=typeof e){let t=this.path[0].find(e=>!!e?.hash);if(null==t)throw Error("No valid leaf found in the Merkle Path");e=t.hash}if("string"!=typeof e)throw TypeError("Transaction ID is undefined");let t=this.indexOf(e),i=e=>tg(ek(tm(e,"hex").reverse()).reverse()),r=e;if(1===this.path.length&&1===this.path[0].length)return r;let n=this.path[0].reduce((e,t)=>Math.max(e,t.offset),0),s=Math.max(this.path.length,32-Math.clz32(n));for(let e=0;e<s;e++){let s=t>>e^1,a=this.findOrComputeLeaf(e,s);if("object"!=typeof a){if(1===this.path.length&&t>>e==n>>e){r=i((r??"")+(r??""));continue}throw Error(`Missing hash for index ${t} at height ${e}`)}r=i(!0===a.duplicate?(r??"")+(r??""):s%2==1?(a.hash??"")+(r??""):(r??"")+(a.hash??""))}return r}findOrComputeLeaf(e,t){let i=e=>tg(ek(tm(e,"hex").reverse()).reverse()),r=e<this.path.length?this.path[e].find(e=>e.offset===t):void 0;if(null!=r)return r;if(0===e)return;let n=e-1,s=t<<1,a=this.findOrComputeLeaf(n,s);if(a?.hash==null||""===a.hash)return;let o=this.findOrComputeLeaf(n,s+1);if(o?.hash==null)return o?.duplicate===!0||1===this.path.length&&s===this.path[0].reduce((e,t)=>Math.max(e,t.offset),0)>>n?{offset:t,hash:i(a.hash+a.hash)}:void 0;return{offset:t,hash:i(!0===o.duplicate?a.hash+a.hash:(o.hash??"")+(a.hash??""))}}async verify(e,t){let i=this.computeRoot(e);if(0===this.indexOf(e)){let e=await t.currentHeight();if(this.blockHeight+100<e)return!1}return await t.isValidRootForHeight(i,this.blockHeight)}combine(e){if(this.blockHeight!==e.blockHeight)throw Error("You cannot combine paths which do not have the same block height.");if(this.computeRoot()!==e.computeRoot())throw Error("You cannot combine paths which do not have the same root.");let t=[];for(let i=0;i<this.path.length;i++){for(let e of(t.push([]),this.path[i]))t[i].push(e);for(let r of e.path[i]){let e=t[i].find(e=>e.offset===r.offset);void 0===e?t[i].push(r):r?.txid!==void 0&&r?.txid!==null&&(e.txid=!0)}}this.path=t,this.trim()}trim(){let e=(e,t)=>{(0===t.length||t.at(-1)!==e)&&t.push(e)},t=(e,t)=>{for(let i=e.length;i>=0;i--){let r=this.path[t].findIndex(t=>t.offset===e[i]);r>=0&&this.path[t].splice(r,1)}},i=t=>{let i=[];for(let r of t)e(r>>1,i);return i},r=[],n=[];for(let e of this.path)e.sort((e,t)=>e.offset-t.offset);for(let t=0;t<this.path[0].length;t++){let i=this.path[0][t];if(!0===i.txid)e(i.offset>>1,r);else{let r=i.offset%2==1,s=this.path[0][t+(r?-1:1)];void 0!==s.txid&&null!==s.txid&&s.txid||e(s.offset,n)}}t(n,0);for(let e=1;e<this.path.length;e++)n=r,r=i(r),t(n,e)}cachedFindLeaf(e,t,i,r,n){let s=`${e}:${t}`;if(r.has(s))return r.get(s);let a=e=>tg(ek(tm(e,"hex").reverse()).reverse()),o=e<i.length?i[e].get(t):void 0;if(null!=o)return r.set(s,o),o;if(0===e)return void r.set(s,void 0);let l=e-1,c=t<<1,h=this.cachedFindLeaf(l,c,i,r,n);if(h?.hash==null||""===h.hash)return void r.set(s,void 0);let d=this.cachedFindLeaf(l,c+1,i,r,n);return d?.hash==null?d?.duplicate===!0||1===this.path.length&&c===n>>l?(o={offset:t,hash:a(h.hash+h.hash)},r.set(s,o),o):void r.set(s,void 0):(o={offset:t,hash:a(!0===d.duplicate?h.hash+h.hash:(d.hash??"")+(h.hash??""))},r.set(s,o),o)}extract(e){if(0===e.length)throw Error("At least one txid must be provided to extract");let t=this.computeRoot(),i=this.path[0].reduce((e,t)=>Math.max(e,t.offset),0),r=Math.max(this.path.length,32-Math.clz32(i)),n=Array(this.path.length);for(let e=0;e<this.path.length;e++){let t=new Map;for(let i of this.path[e])t.set(i.offset,i);n[e]=t}let s=new Map,a=new Map;for(let e of this.path[0])null!=e.hash&&a.set(e.hash,e.offset);let o=Array(r);for(let e=0;e<r;e++)o[e]=new Map;for(let t of e){let e=a.get(t);if(void 0===e)throw Error(`Transaction ID ${t} not found in the Merkle Path`);o[0].set(e,{offset:e,txid:!0,hash:t});let l=1^e;if(!o[0].has(l)){let e=this.cachedFindLeaf(0,l,n,s,i);null!=e&&o[0].set(l,e)}for(let t=1;t<r;t++){let r=e>>t^1;if(o[t].has(r))continue;let a=this.cachedFindLeaf(t,r,n,s,i);null!=a?o[t].set(r,a):e>>t==i>>t&&o[t].set(r,{offset:r,duplicate:!0})}}let l=Array(r);for(let e=0;e<r;e++)l[e]=Array.from(o[e].values()).sort((e,t)=>e.offset-t.offset);let c=new rc(this.blockHeight,l);c.trim();let h=c.computeRoot();if(h!==t)throw Error(`Extracted path root ${h} does not match original root ${t}`);return c}}let rh=0xefbe0001,rd=0xefbe0002,ru=0x1010101;(s=c||(c={}))[s.RAWTX=0]="RAWTX",s[s.RAWTX_AND_BUMP_INDEX=1]="RAWTX_AND_BUMP_INDEX",s[s.TXID_ONLY=2]="TXID_ONLY";class rf{_bumpIndex;_tx;_rawTx;_txid;inputTxids=[];isValid=void 0;get bumpIndex(){return this._bumpIndex}set bumpIndex(e){this._bumpIndex=e,this.updateInputTxids()}get hasProof(){return void 0!==this._bumpIndex}get isTxidOnly(){return void 0!==this._txid&&null!==this._txid&&null==this._rawTx&&null==this._tx}get txid(){if(void 0!==this._txid&&null!==this._txid&&""!==this._txid)return this._txid;if(null!=this._tx)return this._txid=this._tx.id("hex"),this._txid;if(null!=this._rawTx)return this._txid=tg(ek(this._rawTx)),this._txid;throw Error("Internal")}get tx(){return null!=this._tx?this._tx:null!=this._rawTx?(this._tx=rg.fromBinary(this._rawTx),this._tx):void 0}get rawTx(){if(null!=this._rawTx)return Array.from(this._rawTx);if(null!=this._tx){let e=this._tx.toUint8Array();return this._rawTx=e,Array.from(e)}}get rawTxUint8Array(){return null!=this._rawTx?this._rawTx:null!=this._tx?(this._rawTx=this._tx.toUint8Array(),this._rawTx):void 0}constructor(e,t){if("string"==typeof e)this._txid=e;else if(e instanceof Uint8Array)this._rawTx=e;else if(Array.isArray(e))this._rawTx=new Uint8Array(e);else if(e instanceof rg)this._tx=e;else throw TypeError("Invalid transaction data type");this.bumpIndex=t,this.updateInputTxids()}static fromTx(e,t){return new rf(e,t)}static fromRawTx(e,t){return new rf(e,t)}static fromTxid(e,t){return new rf(e,t)}updateInputTxids(){if(this.hasProof||null==this.tx)this.inputTxids=[];else{let e=new Set;for(let t of this.tx.inputs)void 0!==t.sourceTXID&&null!==t.sourceTXID&&""!==t.sourceTXID&&e.add(t.sourceTXID);this.inputTxids=Array.from(e)}}toWriter(e,t){let i=t=>{e.writeUInt8(t)},r=()=>{if(null==this._txid)throw Error("Transaction ID (_txid) is undefined");e.writeReverse(tm(this._txid,"hex"))},n=()=>{let t=this.rawTxUint8Array;if(null==t)throw Error("a valid serialized Transaction is expected");e.write(t)},s=()=>{void 0===this.bumpIndex?i(c.RAWTX):(i(c.RAWTX_AND_BUMP_INDEX),e.writeVarIntNum(this.bumpIndex))};t===rd?this.isTxidOnly?(i(c.TXID_ONLY),r()):(void 0!==this.bumpIndex?(i(c.RAWTX_AND_BUMP_INDEX),e.writeVarIntNum(this.bumpIndex)):i(c.RAWTX),n()):(n(),s())}static fromReader(e,t){let i,r,n;if(t===rd){let t=e.readUInt8();t===c.TXID_ONLY?n=rf.fromTxid(tg(e.readReverse(32))):(t===c.RAWTX_AND_BUMP_INDEX&&(r=e.readVarIntNum()),i=rg.fromReader(e),n=rf.fromTx(i,r))}else i=rg.fromReader(e),r=0===e.readUInt8()?void 0:e.readVarIntNum(),n=rf.fromTx(i,r);return n}}class rp{bumps=[];txs=[];version=rd;atomicTxid=void 0;txidIndex=void 0;rawBytesCache;hexCache;needsSort=!0;constructor(e=rd){this.version=e}invalidateSerializationCaches(){this.rawBytesCache=void 0,this.hexCache=void 0}markMutated(e=!0){this.invalidateSerializationCaches(),e&&(this.needsSort=!0)}ensureSerializableState(){for(let e of this.txs)e.txid}ensureSortedForSerialization(){this.needsSort&&this.sortTxs()}getSerializedBytes(){if(this.ensureSerializableState(),null==this.rawBytesCache){this.ensureSortedForSerialization();let e=new tl;this.toWriter(e),this.rawBytesCache=e.toUint8Array()}return this.rawBytesCache}getBeefForAtomic(e){this.needsSort&&this.sortTxs();let t=this.findTxid(e);if(null==t)throw Error(`${e} does not exist in this Beef`);let i=this.txs.at(-1)===t?this:this.clone();if(i!==this){let t=this.txs.findIndex(t=>t.txid===e);i.txs.splice(t+1)}let r=new tl;return r.writeUInt32LE(ru),r.writeReverse(tm(e,"hex")),{beef:i,writer:r}}findTxid(e){return this.ensureTxidIndex().get(e)}ensureTxidIndex(){if(null==this.txidIndex)for(let e of(this.txidIndex=new Map,this.txs))this.txidIndex.set(e.txid,e);return this.txidIndex}deleteFromIndex(e){this.txidIndex?.delete(e)}addToIndex(e){this.txidIndex?.set(e.txid,e)}makeTxidOnly(e){let t=this.txs.findIndex(t=>t.txid===e);if(-1===t)return;let i=this.txs[t];return i.isTxidOnly?i:(this.deleteFromIndex(e),this.txs.splice(t,1),this.markMutated(!0),i=this.mergeTxidOnly(e))}findBump(e){return this.bumps.find(t=>t.path[0].some(t=>t.hash===e))}findTransactionForSigning(e){let t=this.findTxid(e);if(null!=t&&null!=t.tx){for(let e of t.tx.inputs)if(null==e.sourceTransaction){let t=this.findTxid(tB(e.sourceTXID,"sourceTXID must be valid"));null!=t&&(e.sourceTransaction=t.tx)}return t.tx}}findAtomicTransaction(e){let t=this.findTxid(e);if(null!=t&&null!=t.tx)return this.addInputProof(t.tx),t.tx}addInputProof(e){let t=this.findBump(e.id("hex"));if(null!=t){e.merklePath=t;return}for(let t of e.inputs)this.resolveInputSource(t),null!=t.sourceTransaction&&this.attachMerklePathOrRecurse(t.sourceTransaction)}resolveInputSource(e){if(null==e.sourceTransaction){let t=this.findTxid(tB(e.sourceTXID,"sourceTXID must be valid"));null!=t&&(e.sourceTransaction=t.tx)}}attachMerklePathOrRecurse(e){let t=this.findBump(e.id("hex"));null!=t?e.merklePath=t:this.addInputProof(e)}mergeBump(e){this.markMutated(!1);let t=this.findOrInsertBump(e),i=this.bumps[t];for(let e of this.txs)null==e.bumpIndex&&this.tryMarkTxProvenByBump(e,i,t);return t}findOrInsertBump(e){for(let t=0;t<this.bumps.length;t++){let i=this.bumps[t];if(i===e)return t;if(i.blockHeight===e.blockHeight&&i.computeRoot()===e.computeRoot())return i.combine(e),t}return this.bumps.push(e),this.bumps.length-1}tryMarkTxProvenByBump(e,t,i){let r=e.txid;for(let n of t.path[0])if(n.hash===r){e.bumpIndex=i,n.txid=!0;break}}mergeRawTx(e,t){this.markMutated(!0);let i=new rf(e,t);return this.removeExistingTxid(i.txid),this.txs.push(i),this.addToIndex(i),this.tryToValidateBumpIndex(i),i}mergeTransaction(e){let t;this.markMutated(!0);let i=e.id("hex");this.removeExistingTxid(i),null!=e.merklePath&&(t=this.mergeBump(e.merklePath));let r=new rf(e,t);if(this.txs.push(r),this.addToIndex(r),this.tryToValidateBumpIndex(r),void 0===(t=r.bumpIndex))for(let t of e.inputs)null!=t.sourceTransaction&&this.mergeTransaction(t.sourceTransaction);return r}removeExistingTxid(e){let t=this.txs.findIndex(t=>t.txid===e);t>=0&&(this.deleteFromIndex(e),this.txs.splice(t,1),this.markMutated(!0))}mergeTxidOnly(e){let t=this.findTxid(e);return null==t&&(t=new rf(e),this.txs.push(t),this.addToIndex(t),this.tryToValidateBumpIndex(t),this.markMutated(!0)),t}mergeBeefTx(e){let t=this.findTxid(e.txid);if(e.isTxidOnly&&null==t?t=this.mergeTxidOnly(e.txid):null!=e._tx&&(null==t||t.isTxidOnly)?t=this.mergeTransaction(e._tx):null!=e._rawTx&&(null==t||t.isTxidOnly)&&(t=this.mergeRawTx(e._rawTx)),null==t)throw Error(`Failed to merge BeefTx for txid: ${e.txid}`);return t}mergeBeef(e){let t=e instanceof rp?e:rp.fromBinary(e);for(let e of t.bumps)this.mergeBump(e);for(let e of t.txs)this.mergeBeefTx(e)}isValid(e){return this.verifyValid(e).valid}async verify(e,t){let i=this.verifyValid(t);if(!i.valid)return!1;for(let t of Object.keys(i.roots))if(!await e.isValidRootForHeight(i.roots[t],Number(t)))return!1;return!0}verifyValid(e){let t={valid:!1,roots:{}},i=this.sortTxs();if(i.missingInputs.length>0||i.notValid.length>0||i.txidOnly.length>0&&!0!==e||i.withMissingInputs.length>0)return t;let r={};return this.collectTxidOnlyTxids(r,e)&&this.collectBumpTxids(r,t)&&this.verifyBumpIndexLeaves()&&this.verifyInputDependencies(r)&&(t.valid=!0),t}collectTxidOnlyTxids(e,t){for(let i of this.txs)if(i.isTxidOnly){if(!0!==t)return!1;e[i.txid]=!0}return!0}collectBumpTxids(e,t){for(let i of this.bumps)for(let r of i.path[0])if(!0===r.txid&&"string"==typeof r.hash&&0!==r.hash.length&&(e[r.hash]=!0,!this.confirmComputedRoot(i,r.hash,t)))return!1;return!0}verifyBumpIndexLeaves(){for(let e of this.txs)if(void 0!==e.bumpIndex&&null==this.bumps[e.bumpIndex].path[0].find(t=>t.hash===e.txid))return!1;return!0}verifyInputDependencies(e){for(let t of this.txs){for(let i of t.inputTxids)if(!e[i])return!1;e[t.txid]=!0}return!0}confirmComputedRoot(e,t,i){let r=e.computeRoot(t);return(void 0===i.roots[e.blockHeight]||""===i.roots[e.blockHeight])&&(i.roots[e.blockHeight]=r),i.roots[e.blockHeight]===r}toWriter(e){for(let t of(e.writeUInt32LE(this.version),e.writeVarIntNum(this.bumps.length),this.bumps))e.write(t.toBinary());for(let t of(e.writeVarIntNum(this.txs.length),this.txs))t.toWriter(e,this.version)}toBinary(){return Array.from(this.getSerializedBytes())}toUint8Array(){return this.getSerializedBytes()}toBinaryAtomic(e){let{beef:t,writer:i}=this.getBeefForAtomic(e);return t.toWriter(i),i.toArray()}toUint8ArrayAtomic(e){let{beef:t,writer:i}=this.getBeefForAtomic(e),r=t.getSerializedBytes(),n=i.toUint8Array(),s=new Uint8Array(n.length+r.length);return s.set(n,0),s.set(r,n.length),s}toHex(){if(null!=this.hexCache)return this.hexCache;let e=tg(this.getSerializedBytes());return this.hexCache=e,e}static fromReader(e){let t,i=e.readUInt32LE();if(i===ru&&(t=tg(e.readReverse(32)),i=e.readUInt32LE()),i!==rh&&i!==rd)throw Error(`Serialized BEEF must start with ${rh} or ${rd} but starts with ${i}`);let r=new rp(i),n=e.readVarIntNum();for(let t=0;t<n;t++){let t=rc.fromReader(e,!1);r.bumps.push(t)}let s=e.readVarIntNum();for(let t=0;t<s;t++){let t=rf.fromReader(e,i);r.txs.push(t)}return r.atomicTxid=t,r}static fromBinary(e){let t=tc.makeReader(e);return rp.fromReader(t)}static fromString(e,t="hex"){let i=new tc(ty(e,t));return rp.fromReader(i)}tryToValidateBumpIndex(e){if(void 0!==e.bumpIndex)return!0;let t=e.txid;for(let i=0;i<this.bumps.length;i++){let r=this.bumps[i].path[0].findIndex(e=>e.hash===t);if(r>=0)return e.bumpIndex=i,this.bumps[i].path[0][r].txid=!0,!0}return!1}sortTxs(){let e={},t={},i=[],r=[],n=this.partitionTxs(t,e,i,r),{txsMissingInputs:s,missingInputs:a,remaining:o}=this.separateMissingInputs(n,t);n=o;let l=this.topoSort(n,e,i);return this.txs=s.concat(l).concat(r).concat(i),this.needsSort=!1,this.invalidateSerializationCaches(),{missingInputs:Object.keys(a),notValid:l.map(e=>e.txid),valid:Object.keys(e),withMissingInputs:s.map(e=>e.txid),txidOnly:r.map(e=>e.txid)}}partitionTxs(e,t,i,r){let n=[];for(let s of this.txs)e[s.txid]=s,s.isValid=s.hasProof,s.isValid?(t[s.txid]=!0,i.push(s)):s.isTxidOnly&&0===s.inputTxids.length?(t[s.txid]=!0,r.push(s)):n.push(s);return n}separateMissingInputs(e,t){let i={},r=[],n=[];for(let s of e){let e=!1;for(let r of s.inputTxids)void 0===t[r]&&(i[r]=!0,e=!0);e?r.push(s):n.push(s)}return{txsMissingInputs:r,missingInputs:i,remaining:n}}topoSort(e,t,i){for(;e.length>0;){let r=e;for(let n of(e=[],r))n.inputTxids.every(e=>t[e])?(t[n.txid]=!0,i.push(n)):e.push(n);if(r.length===e.length)break}return e}clone(){let e=new rp;return e.version=this.version,e.bumps=Array.from(this.bumps),e.txs=Array.from(this.txs),e.txidIndex=void 0,e.needsSort=this.needsSort,e.hexCache=this.hexCache,e.rawBytesCache=this.rawBytesCache,e}trimKnownTxids(e){let t=this.removeKnownTxidOnlyTxs(e);(t=this.reindexBumps()||t)&&this.markMutated(!0)}removeKnownTxidOnlyTxs(e){let t=!1;for(let i=0;i<this.txs.length;){let r=this.txs[i];r.isTxidOnly&&e.includes(r.txid)?(this.deleteFromIndex(r.txid),this.txs.splice(i,1),t=!0):i++}return t}reindexBumps(){let e=new Set;for(let t of this.txs)void 0!==t.bumpIndex&&e.add(t.bumpIndex);if(e.size>=this.bumps.length)return!1;let t=new Map,i=0;for(let r=0;r<this.bumps.length;r++)e.has(r)&&(t.set(r,i),i++);for(let i of(this.bumps=this.bumps.filter((t,i)=>e.has(i)),this.txs)){if(void 0===i.bumpIndex)continue;let e=t.get(i.bumpIndex);if(void 0===e)throw Error(`Internal error: bumpIndex ${i.bumpIndex} not found in indexMap`);i.bumpIndex=e}return!0}getValidTxids(){return this.sortTxs().valid}toLogString(){let e="";e+=`BEEF with ${this.bumps.length} BUMPS and ${this.txs.length} Transactions, isValid ${this.isValid().toString()}
|
|
6
|
+
${a}`),this.name=this.constructor.name,this.txid=e.txid,this.outputIndex=e.outputIndex,this.context=e.context,this.programCounter=e.programCounter,this.stackState=e.stackState.map(e=>e.slice()),this.altStackState=e.altStackState.map(e=>e.slice()),this.ifStackState=e.ifStackState.slice(),this.stackMem=e.stackMem,this.altStackMem=e.altStackMem}}let iY=BigInt(0x7fffffff),iJ=Object.freeze(new A(-1).toScriptNum()),iZ=Object.freeze(Array.from({length:17},(e,t)=>Object.freeze(new A(t).toScriptNum())));function iQ(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}class i0{sourceTXID;sourceOutputIndex;sourceSatoshis;lockingScript;transactionVersion;otherInputs;outputs;inputIndex;unlockingScript;inputSequence;lockTime;context;programCounter;lastCodeSeparator;stack;altStack;ifStack;elseStack;memoryLimit;stackMem;altStackMem;isRelaxedOverride;verifyFlags;executedOpCount;returningFromConditional;sigHashCache;constructor(e){if(this.sourceTXID=e.sourceTXID,this.sourceOutputIndex=e.sourceOutputIndex,this.sourceSatoshis=e.sourceSatoshis,this.lockingScript=e.lockingScript,this.transactionVersion=e.transactionVersion,this.otherInputs=e.otherInputs,this.outputs=e.outputs,this.inputIndex=e.inputIndex,this.unlockingScript=e.unlockingScript,this.inputSequence=e.inputSequence,this.lockTime=e.lockTime,this.memoryLimit=e.memoryLimit??32e6,this.isRelaxedOverride=!0===e.isRelaxed,void 0===e.verifyFlags)this.verifyFlags=void 0;else{const t=Array.isArray(e.verifyFlags)?e.verifyFlags:e.verifyFlags.split(",");this.verifyFlags=new Set(t.map(e=>e.trim()).filter(e=>e.length>0))}this.stack=[],this.altStack=[],this.ifStack=[],this.elseStack=[],this.stackMem=0,this.altStackMem=0,this.executedOpCount=0,this.returningFromConditional=!1,this.sigHashCache={hashOutputsSingle:new Map},this.reset()}isRelaxed(){return this.isRelaxedOverride||this.transactionVersion>1}hasExplicitFlags(){return void 0!==this.verifyFlags}hasFlag(e){return this.verifyFlags?.has(e)===!0}isAfterGenesis(){return this.hasExplicitFlags()?this.hasFlag("GENESIS")||this.hasFlag("UTXO_AFTER_GENESIS")||this.hasFlag("UTXO_AFTER_CHRONICLE"):this.isRelaxed()}isAfterChronicle(){return this.hasExplicitFlags()?this.hasFlag("UTXO_AFTER_CHRONICLE"):this.isRelaxed()}shouldEnforceMinimalData(){return this.hasExplicitFlags()?this.hasFlag("MINIMALDATA"):!this.isRelaxed()}shouldEnforceLowS(){return this.hasExplicitFlags()?this.hasFlag("LOW_S"):!this.isRelaxed()}shouldEnforceNullDummy(){return this.hasExplicitFlags()?this.hasFlag("NULLDUMMY"):!this.isRelaxed()}shouldEnforceSigPushOnly(){return this.hasExplicitFlags()?this.hasFlag("SIGPUSHONLY"):!this.isRelaxed()}shouldEnforceCleanStack(){return this.hasExplicitFlags()?this.hasFlag("CLEANSTACK"):!this.isRelaxed()}shouldEnforceDerSignatures(){return!this.hasExplicitFlags()||this.hasFlag("DERSIG")||this.hasFlag("STRICTENC")||this.hasFlag("LOW_S")||this.hasFlag("SIGHASH_FORKID")}shouldEnforceStrictEncoding(){return!this.hasExplicitFlags()||this.hasFlag("STRICTENC")||this.hasFlag("SIGHASH_FORKID")}scriptNumMaxSize(){if(this.hasExplicitFlags()&&!this.isAfterGenesis())return 4}maxPushSize(){return this.hasExplicitFlags()&&!this.isAfterGenesis()?520:0x40000000}reset(){this.context="UnlockingScript",this.programCounter=0,this.lastCodeSeparator=null,this.stack=[],this.altStack=[],this.ifStack=[],this.elseStack=[],this.stackMem=0,this.altStackMem=0,this.executedOpCount=0,this.returningFromConditional=!1,this.sigHashCache={hashOutputsSingle:new Map}}ensureStackMem(e){this.stackMem+e>this.memoryLimit&&this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}ensureAltStackMem(e){this.altStackMem+e>this.memoryLimit&&this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}pushStack(e){this.ensureStackMem(e.length),this.stack.push(e),this.stackMem+=e.length}pushStackCopy(e){this.ensureStackMem(e.length);let t=e.slice();this.stack.push(t),this.stackMem+=t.length}popStack(){0===this.stack.length&&this.scriptEvaluationError("Attempted to pop from an empty stack.");let e=this.stack.pop();return void 0===e?(this.scriptEvaluationError("Attempted to pop from an empty stack."),[]):(this.stackMem-=e.length,e)}stackTop(e=-1){return(0===this.stack.length||this.stack.length<Math.abs(e)||e>=0&&e>=this.stack.length)&&this.scriptEvaluationError(`Stack underflow accessing element at index ${e}. Stack length is ${this.stack.length}.`),this.stack[this.stack.length+e]}setStack(e){this.stack=e.map(e=>e.slice()),this.stackMem=this.stack.reduce((e,t)=>e+t.length,0)}clearAltStack(){this.altStack=[],this.altStackMem=0}pushAltStack(e){this.ensureAltStackMem(e.length),this.altStack.push(e),this.altStackMem+=e.length}popAltStack(){0===this.altStack.length&&this.scriptEvaluationError("Attempted to pop from an empty alt stack.");let e=this.altStack.pop();return void 0===e?(this.scriptEvaluationError("Attempted to pop from an empty alt stack."),[]):(this.altStackMem-=e.length,e)}readScriptNumber(e){try{return A.fromScriptNum(e,this.shouldEnforceMinimalData(),this.scriptNumMaxSize())}catch(t){let e=t instanceof Error?t.message:String(t);this.scriptEvaluationError(e)}return new A(0)}isDefinedHashType(e){let t=31&e;return t>=iD.SIGHASH_ALL&&t<=iD.SIGHASH_SINGLE}checkSignatureEncoding(e){if(0===e.length)return!0;let t=this.shouldEnforceDerSignatures();if(t&&!function(e){if(e.length<9||e.length>73||48!==e[0]||e[1]!==e.length-3)return!1;let t=e[2],i=e[3];if(2!==t||0===i||5+i>=e.length)return!1;let r=4+i,n=e[r],s=e[r+1];if(2!==n||0===s||(128&e[4])!=0||i>1&&0===e[4]&&(128&e[5])==0)return!1;let a=r+2;return(128&e[a])==0&&(!(s>1)||0!==e[a]||(128&e[a+1])!=0)&&i+s+7===e.length}(e))return this.scriptEvaluationError("The signature format is invalid."),!1;try{let t=iD.fromChecksigFormat(e);if(this.shouldEnforceStrictEncoding()&&!this.isDefinedHashType(t.scope))return this.scriptEvaluationError("The signature hash type is invalid."),!1;if(this.shouldEnforceStrictEncoding()&&(t.scope&iD.SIGHASH_CHRONICLE)!=0&&!this.isAfterChronicle())return this.scriptEvaluationError("The signature hash type is invalid before Chronicle."),!1;let i=(t.scope&iD.SIGHASH_FORKID)!=0;if(this.hasExplicitFlags()){if(this.hasFlag("SIGHASH_FORKID")&&!i)return this.scriptEvaluationError("The signature must use SIGHASH_FORKID."),!1;if(!this.hasFlag("SIGHASH_FORKID")&&!this.isAfterGenesis()&&i)return this.scriptEvaluationError("The signature must not use SIGHASH_FORKID."),!1}if(this.shouldEnforceLowS()&&!t.hasLowS())return this.scriptEvaluationError("The signature must have a low S value."),!1}catch{if(t)return this.scriptEvaluationError("The signature format is invalid."),!1}return!0}parseChecksigSignature(e){try{return iD.fromChecksigFormat(e)}catch(t){if(this.shouldEnforceDerSignatures())throw t;return this.parseLaxChecksigSignature(e)}}readLaxDERLength(e,t){let i=e[t.value++];if(void 0===i)throw Error("Invalid DER length");if((128&i)==0)return i;let r=127&i;if(0===r||t.value+r>e.length)throw Error("Invalid DER length");let n=0;for(let i=0;i<r;i++)n=n<<8|(e[t.value++]??0);return n}parseLaxDERInteger(e,t,i){if(t.value>=i||2!==e[t.value++])throw Error("Invalid DER integer");let r=this.readLaxDERLength(e,t);if(t.value+r>i)throw Error("Invalid DER integer length");let n=e.slice(t.value,t.value+r);for(t.value+=r;n.length>1&&0===n[0];)n=n.slice(1);return 0===n.length&&(n=[0]),new A(n)}parseLaxChecksigSignature(e){if(0===e.length)return iD.fromChecksigFormat(e);let t=e.at(-1),i=e.slice(0,-1),r={value:0};if(48!==i[r.value++])throw Error("Signature DER must start with 0x30");let n=this.readLaxDERLength(i,r),s=Math.min(r.value+n,i.length);return new iD(this.parseLaxDERInteger(i,r,s),this.parseLaxDERInteger(i,r,s),t)}checkPublicKeyEncoding(e){if(!this.shouldEnforceStrictEncoding())return!0;if(0===e.length)return this.scriptEvaluationError("Public key is empty."),!1;if(e.length<33)return this.scriptEvaluationError("The public key is too short, it must be at least 33 bytes."),!1;if(4===e[0]){if(65!==e.length)return this.scriptEvaluationError("The non-compressed public key must be 65 bytes."),!1}else if(2!==e[0]&&3!==e[0])return this.scriptEvaluationError("The public key is in an unknown format."),!1;else if(33!==e.length)return this.scriptEvaluationError("The compressed public key must be 33 bytes."),!1;try{ii.fromDER(e)}catch{return this.scriptEvaluationError("The public key is in an unknown format."),!1}return!0}verifySignature(e,t,i){let r={sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,sourceSatoshis:this.sourceSatoshis,transactionVersion:this.transactionVersion,otherInputs:this.otherInputs,outputs:this.outputs,inputIndex:this.inputIndex,subscript:i,inputSequence:this.inputSequence,lockTime:this.lockTime,scope:e.scope,cache:this.sigHashCache};return it(new A(iD.usesOtdaSingleBug(r)?[1,...Array(31).fill(0)]:ek(iD.formatBytes(r))),e,t)}step(){if(this.stackMem>this.memoryLimit)return this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;if(this.altStackMem>this.memoryLimit)return this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;"UnlockingScript"===this.context&&this.programCounter>=this.unlockingScript.chunks.length&&(this.ifStack.length>0&&this.scriptEvaluationError("Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the unlocking script."),this.clearAltStack(),this.ifStack=[],this.elseStack=[],this.returningFromConditional=!1,this.lastCodeSeparator=null,this.context="LockingScript",this.programCounter=0);let e="UnlockingScript"===this.context?this.unlockingScript:this.lockingScript;if(this.programCounter>=e.chunks.length)return!1;let t=e.chunks[this.programCounter],i=t.op;void 0===i&&this.scriptEvaluationError(`Missing opcode in ${this.context} at pc=${this.programCounter}.`),!0===t.invalidLength&&this.scriptEvaluationError(`Malformed push data in ${this.context} at pc=${this.programCounter}.`),Array.isArray(t.data)&&t.data.length>this.maxPushSize()&&this.scriptEvaluationError(`Data push > ${this.maxPushSize()} bytes (pc=${this.programCounter}).`);let r=!this.returningFromConditional&&!this.ifStack.includes(!1);if(!this.hasExplicitFlags()||this.isAfterGenesis()||this.isAfterChronicle()||i!==iC.OP_2MUL&&i!==iC.OP_2DIV&&i!==iC.OP_VERIF&&i!==iC.OP_VERNOTIF||this.scriptEvaluationError(`${iC[i]} is disabled until Chronicle.`),r&&i>=0&&i<=iC.OP_PUSHDATA4){let e,i;this.shouldEnforceMinimalData()&&(e=t.data,i=t.op,Array.isArray(e)&&(0===e.length?i!==iC.OP_0:1===e.length&&e[0]>=1&&e[0]<=16?i!==iC.OP_1+(e[0]-1):1===e.length&&129===e[0]?i!==iC.OP_1NEGATE:e.length<=75?i!==e.length:e.length<=255?i!==iC.OP_PUSHDATA1:e.length<=65535&&i!==iC.OP_PUSHDATA2))&&this.scriptEvaluationError(`This data is not minimally-encoded. (PC: ${this.programCounter})`),this.pushStack(Array.isArray(t.data)?t.data:[])}else if(r||i>=iC.OP_IF&&i<=iC.OP_ENDIF){let e,t,n,s,a,o,l,c,h,d,u,f,p,g,y,m,b,w,v,I,k,S,E,x,T,O;if(r&&i>iC.OP_16&&(this.executedOpCount++,this.hasExplicitFlags()&&!this.isAfterGenesis()&&this.executedOpCount>500&&this.scriptEvaluationError("Script executed more than 500 opcodes.")),this.hasExplicitFlags()&&!this.isAfterChronicle()){if(r&&(i===iC.OP_SUBSTR||i===iC.OP_LEFT||i===iC.OP_RIGHT||i===iC.OP_LSHIFTNUM||i===iC.OP_RSHIFTNUM))return this.hasFlag("DISCOURAGE_UPGRADABLE_NOPS")&&this.scriptEvaluationError(`${iC[i]} is discouraged by verification flags.`),this.programCounter++,!0;if((r||!this.isAfterGenesis())&&(i===iC.OP_2MUL||i===iC.OP_2DIV)&&this.scriptEvaluationError(`${iC[i]} is disabled until Chronicle.`),(r||!this.isAfterGenesis())&&(i===iC.OP_VER||i===iC.OP_VERIF||i===iC.OP_VERNOTIF)&&this.scriptEvaluationError(`${iC[i]} is disabled until Chronicle.`),!r&&this.isAfterGenesis()&&(i===iC.OP_VERIF||i===iC.OP_VERNOTIF))return this.programCounter++,!0}switch(r&&this.hasFlag("DISCOURAGE_UPGRADABLE_NOPS")&&(i===iC.OP_NOP1||i===iC.OP_CHECKLOCKTIMEVERIFY||i===iC.OP_CHECKSEQUENCEVERIFY||i===iC.OP_NOP9||i===iC.OP_NOP10)&&this.scriptEvaluationError(`${iC[i]} is discouraged by verification flags.`),i){case iC.OP_VER:{let e=this.transactionVersion;this.pushStack([255&e,e>>>8&255,e>>>16&255,e>>>24&255]);break}case iC.OP_SUBSTR:{this.stack.length<3&&this.scriptEvaluationError("OP_SUBSTR requires at least three items to be on the stack.");let t=this.readScriptNumber(this.popStack()).toNumber(),i=this.readScriptNumber(this.popStack()).toNumber(),r=(e=this.popStack()).length;(i<0||i>=r||t<0||t>r-i)&&this.scriptEvaluationError(`OP_SUBSTR offset (${i}) must be in range [0, ${r}) and length (${t}) must be in range [0, ${r-i}]`),this.pushStack(e.slice(i,i+t));break}case iC.OP_LEFT:{this.stack.length<2&&this.scriptEvaluationError("OP_LEFT requires at least two items to be on the stack.");let t=this.readScriptNumber(this.popStack()).toNumber(),i=(e=this.popStack()).length;(t<0||t>i)&&this.scriptEvaluationError(`OP_LEFT length (${t}) must be in range [0, ${i}]`),this.pushStack(e.slice(0,t));break}case iC.OP_RIGHT:{this.stack.length<2&&this.scriptEvaluationError("OP_RIGHT requires at least two items to be on the stack.");let t=this.readScriptNumber(this.popStack()).toNumber(),i=(e=this.popStack()).length;(t<0||t>i)&&this.scriptEvaluationError(`OP_RIGHT length (${t}) must be in range [0, ${i}]`),this.pushStack(e.slice(i-t));break}case iC.OP_LSHIFTNUM:{this.stack.length<2&&this.scriptEvaluationError("OP_LSHIFTNUM requires at least two items to be on the stack.");let e=this.readScriptNumber(this.popStack()).toBigInt();e<0&&this.scriptEvaluationError("OP_LSHIFTNUM bits to shift must not be negative.");let t=new A(this.readScriptNumber(this.popStack()).toBigInt()<<e);this.pushStack(t.toScriptNum());break}case iC.OP_RSHIFTNUM:{let e;this.stack.length<2&&this.scriptEvaluationError("OP_RSHIFTNUM requires at least two items to be on the stack.");let t=this.readScriptNumber(this.popStack()).toBigInt();t<0&&this.scriptEvaluationError("OP_RSHIFTNUM bits to shift must not be negative.");let i=this.readScriptNumber(this.popStack()).toBigInt();e=new A(i<0?-(-i>>t):i>>t),this.pushStack(e.toScriptNum());break}case iC.OP_1NEGATE:this.pushStackCopy(iJ);break;case iC.OP_0:this.pushStackCopy(iZ[0]);break;case iC.OP_1:case iC.OP_2:case iC.OP_3:case iC.OP_4:case iC.OP_5:case iC.OP_6:case iC.OP_7:case iC.OP_8:case iC.OP_9:case iC.OP_10:case iC.OP_11:case iC.OP_12:case iC.OP_13:case iC.OP_14:case iC.OP_15:case iC.OP_16:f=i-(iC.OP_1-1),this.pushStackCopy(iZ[f]);break;case iC.OP_NOP:case iC.OP_NOP1:case iC.OP_CHECKLOCKTIMEVERIFY:break;case iC.OP_CHECKSEQUENCEVERIFY:if(this.hasFlag("CHECKSEQUENCEVERIFY")){this.stack.length<1&&this.scriptEvaluationError("OP_CHECKSEQUENCEVERIFY requires at least one item to be on the stack.");let e=0n;try{e=A.fromScriptNum(this.stackTop(),this.shouldEnforceMinimalData(),5).toBigInt()}catch{this.scriptEvaluationError("OP_CHECKSEQUENCEVERIFY requires a minimally-encoded numeric lock time.")}e<0n&&this.scriptEvaluationError("OP_CHECKSEQUENCEVERIFY requires a non-negative lock time."),0===Number(e&BigInt(0x80000000))&&this.transactionVersion<2&&this.scriptEvaluationError("OP_CHECKSEQUENCEVERIFY lock time is unsatisfied.")}break;case iC.OP_NOP9:case iC.OP_NOP10:break;case iC.OP_VERIF:case iC.OP_VERNOTIF:if(g=!1,r){if(this.stack.length<1&&this.scriptEvaluationError("OP_VERIF and OP_VERNOTIF require at least one item on the stack when they are used!"),4===(t=this.popStack()).length){let e=this.transactionVersion;g=iQ(t,n=[255&e,e>>>8&255,e>>>16&255,e>>>24&255])}i===iC.OP_VERNOTIF&&(g=!g)}this.ifStack.push(g),this.elseStack.push(!1);break;case iC.OP_IF:case iC.OP_NOTIF:g=!1,r&&(this.stack.length<1&&this.scriptEvaluationError("OP_IF and OP_NOTIF require at least one item on the stack when they are used!"),e=this.popStack(),this.hasFlag("MINIMALIF")&&e.length>0&&(1!==e.length||1!==e[0])&&this.scriptEvaluationError("OP_IF and OP_NOTIF require minimal truth values."),g=this.castToBool(e),i===iC.OP_NOTIF&&(g=!g)),this.ifStack.push(g),this.elseStack.push(!1);break;case iC.OP_ELSE:0===this.ifStack.length&&this.scriptEvaluationError("OP_ELSE requires a preceeding OP_IF."),this.hasExplicitFlags()&&this.isAfterGenesis()&&this.elseStack.at(-1)&&this.scriptEvaluationError("OP_ELSE may only be used once for each OP_IF or OP_NOTIF after Genesis."),this.elseStack[this.elseStack.length-1]=!0,this.ifStack[this.ifStack.length-1]=!this.ifStack.at(-1);break;case iC.OP_ENDIF:0===this.ifStack.length&&this.scriptEvaluationError("OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop(),this.elseStack.pop();break;case iC.OP_VERIFY:this.stack.length<1&&this.scriptEvaluationError("OP_VERIFY requires at least one item to be on the stack."),t=this.stackTop(),(g=this.castToBool(t))||this.scriptEvaluationError("OP_VERIFY requires the top stack value to be truthy."),this.popStack();break;case iC.OP_RETURN:this.hasExplicitFlags()&&!this.isAfterGenesis()&&this.scriptEvaluationError("OP_RETURN is invalid before Genesis."),this.ifStack.length>0?this.returningFromConditional=!0:("UnlockingScript"===this.context?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.programCounter--);break;case iC.OP_TOALTSTACK:this.stack.length<1&&this.scriptEvaluationError("OP_TOALTSTACK requires at oeast one item to be on the stack."),this.pushAltStack(this.popStack());break;case iC.OP_FROMALTSTACK:this.altStack.length<1&&this.scriptEvaluationError("OP_FROMALTSTACK requires at least one item to be on the stack."),this.pushStack(this.popAltStack());break;case iC.OP_2DROP:this.stack.length<2&&this.scriptEvaluationError("OP_2DROP requires at least two items to be on the stack."),this.popStack(),this.popStack();break;case iC.OP_2DUP:this.stack.length<2&&this.scriptEvaluationError("OP_2DUP requires at least two items to be on the stack."),t=this.stackTop(-2),n=this.stackTop(-1),this.pushStackCopy(t),this.pushStackCopy(n);break;case iC.OP_3DUP:this.stack.length<3&&this.scriptEvaluationError("OP_3DUP requires at least three items to be on the stack."),t=this.stackTop(-3),n=this.stackTop(-2),s=this.stackTop(-1),this.pushStackCopy(t),this.pushStackCopy(n),this.pushStackCopy(s);break;case iC.OP_2OVER:this.stack.length<4&&this.scriptEvaluationError("OP_2OVER requires at least four items to be on the stack."),t=this.stackTop(-4),n=this.stackTop(-3),this.pushStackCopy(t),this.pushStackCopy(n);break;case iC.OP_2ROT:{this.stack.length<6&&this.scriptEvaluationError("OP_2ROT requires at least six items to be on the stack.");let e=this.popStack(),t=this.popStack(),i=this.popStack(),r=this.popStack(),n=this.popStack(),s=this.popStack();this.pushStack(r),this.pushStack(i),this.pushStack(t),this.pushStack(e),this.pushStack(s),this.pushStack(n);break}case iC.OP_2SWAP:{this.stack.length<4&&this.scriptEvaluationError("OP_2SWAP requires at least four items to be on the stack.");let e=this.popStack(),t=this.popStack(),i=this.popStack(),r=this.popStack();this.pushStack(t),this.pushStack(e),this.pushStack(r),this.pushStack(i);break}case iC.OP_IFDUP:this.stack.length<1&&this.scriptEvaluationError("OP_IFDUP requires at least one item to be on the stack."),t=this.stackTop(),this.castToBool(t)&&this.pushStackCopy(t);break;case iC.OP_DEPTH:this.pushStack(new A(this.stack.length).toScriptNum());break;case iC.OP_DROP:this.stack.length<1&&this.scriptEvaluationError("OP_DROP requires at least one item to be on the stack."),this.popStack();break;case iC.OP_DUP:this.stack.length<1&&this.scriptEvaluationError("OP_DUP requires at least one item to be on the stack."),this.pushStackCopy(this.stackTop());break;case iC.OP_NIP:this.stack.length<2&&this.scriptEvaluationError("OP_NIP requires at least two items to be on the stack."),n=this.popStack(),this.popStack(),this.pushStack(n);break;case iC.OP_OVER:this.stack.length<2&&this.scriptEvaluationError("OP_OVER requires at least two items to be on the stack."),this.pushStackCopy(this.stackTop(-2));break;case iC.OP_PICK:case iC.OP_ROLL:{this.stack.length<2&&this.scriptEvaluationError(`${iC[i]} requires at least two items to be on the stack.`);let e=(c=this.readScriptNumber(this.popStack())).toBigInt();(e<0n||e>=BigInt(this.stack.length))&&this.scriptEvaluationError(`${iC[i]} requires the top stack element to be 0 or a positive number less than the current size of the stack.`);let t=Number(e),r=this.stack[this.stack.length-1-t];i===iC.OP_ROLL?(this.stack.splice(this.stack.length-1-t,1),this.stackMem-=r.length,this.pushStack(r)):this.pushStackCopy(r);break}case iC.OP_ROT:this.stack.length<3&&this.scriptEvaluationError("OP_ROT requires at least three items to be on the stack."),l=this.popStack(),o=this.popStack(),a=this.popStack(),this.pushStack(o),this.pushStack(l),this.pushStack(a);break;case iC.OP_SWAP:this.stack.length<2&&this.scriptEvaluationError("OP_SWAP requires at least two items to be on the stack."),o=this.popStack(),a=this.popStack(),this.pushStack(o),this.pushStack(a);break;case iC.OP_TUCK:this.stack.length<2&&this.scriptEvaluationError("OP_TUCK requires at least two items to be on the stack."),t=this.stackTop(-1),this.ensureStackMem(t.length),this.stack.splice(-2,0,t.slice()),this.stackMem+=t.length;break;case iC.OP_SIZE:this.stack.length<1&&this.scriptEvaluationError("OP_SIZE requires at least one item to be on the stack."),this.pushStack(new A(this.stackTop().length).toScriptNum());break;case iC.OP_AND:case iC.OP_OR:case iC.OP_XOR:{this.stack.length<2&&this.scriptEvaluationError(`${iC[i]} requires at least two items on the stack.`),n=this.popStack(),(t=this.popStack()).length!==n.length&&this.scriptEvaluationError(`${iC[i]} requires the top two stack items to be the same size.`);let e=Array(t.length);for(let r=0;r<t.length;r++)i===iC.OP_AND?e[r]=t[r]&n[r]:i===iC.OP_OR?e[r]=t[r]|n[r]:e[r]=t[r]^n[r];this.pushStack(e);break}case iC.OP_INVERT:{this.stack.length<1&&this.scriptEvaluationError("OP_INVERT requires at least one item to be on the stack.");let t=Array((e=this.popStack()).length);for(let i=0;i<e.length;i++)t[i]=255&~e[i];this.pushStack(t);break}case iC.OP_LSHIFT:case iC.OP_RSHIFT:{let e;this.stack.length<2&&this.scriptEvaluationError(`${iC[i]} requires at least two items to be on the stack.`),d=this.readScriptNumber(this.popStack()),t=this.popStack();let r=d.toBigInt();if(r<0n&&this.scriptEvaluationError(`${iC[i]} requires the top item on the stack not to be negative.`),0===t.length){this.pushStack([]);break}if(h=new A(t),i===iC.OP_LSHIFT){e=h.ushln(r);let i=new A(1).ushln(8*t.length).isubn(1);e=e.iand(i)}else e=h.ushrn(r);let n=e.toArray("be",t.length);this.pushStack(n);break}case iC.OP_EQUAL:case iC.OP_EQUALVERIFY:this.stack.length<2&&this.scriptEvaluationError(`${iC[i]} requires at least two items to be on the stack.`),n=this.popStack(),g=iQ(t=this.popStack(),n),this.pushStack(g?[1]:[]),i===iC.OP_EQUALVERIFY&&(g||this.scriptEvaluationError("OP_EQUALVERIFY requires the top two stack items to be equal."),this.popStack());break;case iC.OP_1ADD:case iC.OP_1SUB:case iC.OP_2MUL:case iC.OP_2DIV:case iC.OP_NEGATE:case iC.OP_ABS:case iC.OP_NOT:case iC.OP_0NOTEQUAL:switch(this.stack.length<1&&this.scriptEvaluationError(`${iC[i]} requires at least one item to be on the stack.`),c=this.readScriptNumber(this.popStack()),i){case iC.OP_1ADD:c=c.add(new A(1));break;case iC.OP_1SUB:c=c.sub(new A(1));break;case iC.OP_2MUL:c=c.mul(new A(2));break;case iC.OP_2DIV:c=c.div(new A(2));break;case iC.OP_NEGATE:c=c.neg();break;case iC.OP_ABS:c.isNeg()&&(c=c.neg());break;case iC.OP_NOT:c=new A(+(0===c.cmpn(0)));break;case iC.OP_0NOTEQUAL:c=new A(+(0!==c.cmpn(0)))}this.pushStack(c.toScriptNum());break;case iC.OP_ADD:case iC.OP_SUB:case iC.OP_MUL:case iC.OP_DIV:case iC.OP_MOD:case iC.OP_BOOLAND:case iC.OP_BOOLOR:case iC.OP_NUMEQUAL:case iC.OP_NUMEQUALVERIFY:case iC.OP_NUMNOTEQUAL:case iC.OP_LESSTHAN:case iC.OP_GREATERTHAN:case iC.OP_LESSTHANOREQUAL:case iC.OP_GREATERTHANOREQUAL:case iC.OP_MIN:case iC.OP_MAX:{this.stack.length<2&&this.scriptEvaluationError(`${iC[i]} requires at least two items to be on the stack.`),n=this.popStack(),t=this.popStack(),d=this.readScriptNumber(n),h=this.readScriptNumber(t);let e=0;switch(i){case iC.OP_MUL:e=h.byteLength()+d.byteLength();break;case iC.OP_ADD:case iC.OP_SUB:e=Math.max(h.byteLength(),d.byteLength())+1;break;default:e=Math.max(h.byteLength(),d.byteLength())}this.ensureStackMem(e);let r=new A(0);switch(i){case iC.OP_ADD:r=h.add(d);break;case iC.OP_SUB:r=h.sub(d);break;case iC.OP_MUL:r=h.mul(d);break;case iC.OP_DIV:0===d.cmpn(0)&&this.scriptEvaluationError("OP_DIV cannot divide by zero!"),r=h.div(d);break;case iC.OP_MOD:0===d.cmpn(0)&&this.scriptEvaluationError("OP_MOD cannot divide by zero!"),r=h.mod(d);break;case iC.OP_BOOLAND:r=new A(+(0!==h.cmpn(0)&&0!==d.cmpn(0)));break;case iC.OP_BOOLOR:r=new A(+(0!==h.cmpn(0)||0!==d.cmpn(0)));break;case iC.OP_NUMEQUAL:case iC.OP_NUMEQUALVERIFY:r=new A(+(0===h.cmp(d)));break;case iC.OP_NUMNOTEQUAL:r=new A(+(0!==h.cmp(d)));break;case iC.OP_LESSTHAN:r=new A(+(0>h.cmp(d)));break;case iC.OP_GREATERTHAN:r=new A(+(h.cmp(d)>0));break;case iC.OP_LESSTHANOREQUAL:r=new A(+(0>=h.cmp(d)));break;case iC.OP_GREATERTHANOREQUAL:r=new A(+(h.cmp(d)>=0));break;case iC.OP_MIN:r=0>h.cmp(d)?h:d;break;case iC.OP_MAX:r=h.cmp(d)>0?h:d}this.pushStack(r.toScriptNum()),i===iC.OP_NUMEQUALVERIFY&&(this.castToBool(this.stackTop())||this.scriptEvaluationError("OP_NUMEQUALVERIFY requires the top stack item to be truthy."),this.popStack());break}case iC.OP_WITHIN:this.stack.length<3&&this.scriptEvaluationError("OP_WITHIN requires at least three items to be on the stack."),u=this.readScriptNumber(this.popStack()),d=this.readScriptNumber(this.popStack()),g=(h=this.readScriptNumber(this.popStack())).cmp(d)>=0&&0>h.cmp(u),this.pushStack(g?[1]:[]);break;case iC.OP_RIPEMD160:case iC.OP_SHA1:case iC.OP_SHA256:case iC.OP_HASH160:case iC.OP_HASH256:{this.stack.length<1&&this.scriptEvaluationError(`${iC[i]} requires at least one item to be on the stack.`),e=this.popStack();let t=[];i===iC.OP_RIPEMD160?t=eb(e):i===iC.OP_SHA1?t=ew(e):i===iC.OP_SHA256?t=ev(e):i===iC.OP_HASH160?t=eS(e):i===iC.OP_HASH256&&(t=ek(e)),this.pushStack(t);break}case iC.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case iC.OP_CHECKSIG:case iC.OP_CHECKSIGVERIFY:if(this.stack.length<2&&this.scriptEvaluationError(`${iC[i]} requires at least two items to be on the stack.`),w=this.popStack(),b=this.popStack(),this.checkSignatureEncoding(b)&&this.checkPublicKeyEncoding(w)||this.scriptEvaluationError(`${iC[i]} requires correct encoding for the public key and signature.`),y=!1,b.length>0)try{v=this.parseChecksigSignature(b);let e=("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1);(m=new iU(e)).findAndDelete(new iU().writeBin(b)),I=ii.fromDER(w),y=this.verifySignature(v,I,m)}catch{y=!1}!y&&this.hasFlag("NULLFAIL")&&b.length>0&&this.scriptEvaluationError(`${iC[i]} requires failing signatures to be empty.`),this.pushStack(y?[1]:[]),i===iC.OP_CHECKSIGVERIFY&&(y||this.scriptEvaluationError("OP_CHECKSIGVERIFY requires that a valid signature is provided."),this.popStack());break;case iC.OP_CHECKMULTISIG:case iC.OP_CHECKMULTISIGVERIFY:{k=1,this.stack.length<k&&this.scriptEvaluationError(`${iC[i]} requires at least 1 item for nKeys.`);let e=this.readScriptNumber(this.stackTop(-k)).toBigInt(),t=this.hasExplicitFlags()&&!this.isAfterGenesis()?BigInt(20):iY;(e<0n||e>t)&&this.scriptEvaluationError(`${iC[i]} requires a key count between 0 and ${t.toString()}.`);let r=x=Number(e);S=++k,k+=x,this.stack.length<k&&this.scriptEvaluationError(`${iC[i]} stack too small for nKeys and keys. Need ${k}, have ${this.stack.length}.`);let n=this.readScriptNumber(this.stackTop(-k)).toBigInt();(n<0n||n>BigInt(x))&&this.scriptEvaluationError(`${iC[i]} requires the number of signatures to be no greater than the number of keys.`);let s=T=Number(n);E=++k,k+=T,this.stack.length<k&&this.scriptEvaluationError(`${iC[i]} stack too small for N, keys, M, sigs, and dummy. Need ${k}, have ${this.stack.length}.`),m=new iU(("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1));let a=!1;for(let e=0;e<T;e++)(b=this.stackTop(-E-e)).length>0&&(a=!0),m.findAndDelete(new iU().writeBin(b));for(y=!0;y&&T>0;){if(0===x){y=!1;break}if(b=this.stackTop(-E),w=this.stackTop(-S),this.checkSignatureEncoding(b)&&this.checkPublicKeyEncoding(w)||this.scriptEvaluationError(`${iC[i]} requires correct encoding for the public key and signature.`),O=!1,b.length>0)try{v=this.parseChecksigSignature(b),I=ii.fromDER(w),O=this.verifySignature(v,I,m)}catch{O=!1}O&&(E++,T--),S++,T>--x&&(y=!1)}!y&&this.hasFlag("NULLFAIL")&&a&&this.scriptEvaluationError(`${iC[i]} requires failing signatures to be empty.`);let o=1+r+1+s+1-1;for(;o>0;)this.popStack(),o--;this.stack.length<1&&this.scriptEvaluationError(`${iC[i]} requires an extra item (dummy) to be on the stack.`);let l=this.popStack();this.shouldEnforceNullDummy()&&l.length>0&&this.scriptEvaluationError(`${iC[i]} requires the extra stack item (dummy) to be empty.`),this.pushStack(y?[1]:[]),i===iC.OP_CHECKMULTISIGVERIFY&&(y||this.scriptEvaluationError("OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."),this.popStack());break}case iC.OP_CAT:{this.stack.length<2&&this.scriptEvaluationError("OP_CAT requires at least two items to be on the stack."),n=this.popStack();let e=(t=this.popStack()).concat(n);e.length>this.maxPushSize()&&this.scriptEvaluationError(`It's not currently possible to push data larger than ${this.maxPushSize()} bytes.`),this.pushStack(e);break}case iC.OP_SPLIT:{this.stack.length<2&&this.scriptEvaluationError("OP_SPLIT requires at least two items to be on the stack.");let e=this.popStack(),t=this.popStack(),i=this.readScriptNumber(e).toBigInt();(i<0n||i>BigInt(t.length))&&this.scriptEvaluationError("OP_SPLIT requires the first stack item to be a non-negative number less than or equal to the size of the second-from-top stack item.");let r=Number(i);this.pushStack(t.slice(0,r)),this.pushStack(t.slice(r));break}case iC.OP_NUM2BIN:{this.stack.length<2&&this.scriptEvaluationError("OP_NUM2BIN requires at least two items to be on the stack.");let e=this.readScriptNumber(this.popStack()).toBigInt();(e>BigInt(this.maxPushSize())||e<0n)&&this.scriptEvaluationError(`It's not currently possible to push data larger than ${this.maxPushSize()} bytes or negative size.`),p=Number(e);let t=this.popStack();if((t=t_(t)).length>p&&this.scriptEvaluationError("OP_NUM2BIN requires that the size expressed in the top stack item is large enough to hold the value expressed in the second-from-top stack item."),t.length===p){this.pushStack(t);break}let i=Array(p).fill(0),r=0;t.length>0&&(r=128&t.at(-1),t[t.length-1]&=127);for(let e=0;e<t.length;e++)i[e]=t[e];0!==r&&(i[p-1]|=128),this.pushStack(i);break}case iC.OP_BIN2NUM:{this.stack.length<1&&this.scriptEvaluationError("OP_BIN2NUM requires at least one item to be on the stack.");let e=t_(t=this.popStack());!function(e,t=Number.MAX_SAFE_INTEGER){return!(e.length>t)&&(!(e.length>0)||(127&e.at(-1))!=0||!(e.length<=1)&&(128&e.at(-2))!=0)}(e)&&this.scriptEvaluationError("OP_BIN2NUM requires that the resulting number is valid."),this.pushStack(e);break}default:this.scriptEvaluationError(`Invalid opcode ${i} (pc=${this.programCounter}).`)}}return this.returningFromConditional&&0===this.ifStack.length?this.programCounter=e.chunks.length:this.programCounter++,this.hasExplicitFlags()&&!this.isAfterGenesis()&&this.stack.length+this.altStack.length>1e3&&this.scriptEvaluationError("Stack item count has exceeded 1000."),!0}validate(){this.shouldEnforceSigPushOnly()&&!this.unlockingScript.isPushOnly()&&this.scriptEvaluationError("Unlocking scripts can only contain push operations, and no other opcodes.");let e=this.lockingScript,t=this.hasFlag("P2SH")&&!this.isAfterGenesis()&&this.isP2SHLockingScript(this.lockingScript);t&&!this.unlockingScript.isPushOnly()&&this.scriptEvaluationError("P2SH unlocking scripts can only contain push operations."),this.reset(),this.runScript("UnlockingScript");let i=this.stack.map(e=>e.slice());this.runScript("LockingScript"),this.requireTruthyTopStack();try{if(t){0===i.length&&this.scriptEvaluationError("P2SH evaluation requires a redeem script on the stack.");let e=i.pop();if(void 0===e)return this.scriptEvaluationError("P2SH evaluation requires a redeem script on the stack."),!1;this.setStack(i);let t=iU.fromBinary(e);this.lockingScript=new ij(t.chunks),this.runScript("LockingScript")}}finally{this.lockingScript=e}return this.shouldEnforceCleanStack()&&1!==this.stack.length&&this.scriptEvaluationError(`The clean stack rule requires exactly one item to be on the stack after script execution, found ${this.stack.length}.`),this.requireTruthyTopStack(),!0}runScript(e){this.context=e,this.programCounter=0,this.ifStack=[],this.elseStack=[],this.returningFromConditional=!1,this.clearAltStack(),this.lastCodeSeparator=null;let t="UnlockingScript"===e?this.unlockingScript:this.lockingScript;for(this.hasExplicitFlags()&&!this.isAfterGenesis()&&t.toUint8Array().length>1e4&&this.scriptEvaluationError("Script size exceeds 10000 bytes.");this.programCounter<t.chunks.length;)this.step();this.ifStack.length>0&&this.scriptEvaluationError("Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the script."),this.ifStack=[],this.elseStack=[],this.clearAltStack(),this.lastCodeSeparator=null}isP2SHLockingScript(e){let t=e.chunks;return 3===t.length&&t[0].op===iC.OP_HASH160&&20===t[1].op&&Array.isArray(t[1].data)&&20===t[1].data.length&&t[2].op===iC.OP_EQUAL}requireTruthyTopStack(){0===this.stack.length?this.scriptEvaluationError("The top stack element must be truthy after script evaluation (stack is empty)."):this.castToBool(this.stackTop())||this.scriptEvaluationError("The top stack element must be truthy after script evaluation.")}castToBool(e){if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(0!==e[t])return t!==e.length-1||128!==e[t];return!1}scriptEvaluationError(e){throw new iX({message:e,txid:this.sourceTXID,outputIndex:this.sourceOutputIndex,context:this.context,programCounter:this.programCounter,stackState:this.stack,altStackState:this.altStack,ifStackState:this.ifStack,stackMem:this.stackMem,altStackMem:this.altStackMem})}}function i1(e,t){let i=iD.SIGHASH_FORKID;return"all"===e&&(i|=iD.SIGHASH_ALL),"none"===e&&(i|=iD.SIGHASH_NONE),"single"===e&&(i|=iD.SIGHASH_SINGLE),t&&(i|=iD.SIGHASH_ANYONECANPAY),i}function i2(e,t,i,r){let n=e.inputs[t],s=e.inputs.filter((e,i)=>i!==t),a=n.sourceTXID??n.sourceTransaction?.id("hex");if(null==a||void 0===a||""===a)throw Error("The input sourceTXID or sourceTransaction is required for transaction signing.");let o=i??n.sourceTransaction?.outputs[n.sourceOutputIndex].satoshis;if(null==o||void 0===o)throw Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");let l=r??n.sourceTransaction?.outputs[n.sourceOutputIndex].lockingScript;if(null==l)throw Error("The lockingScript or input sourceTransaction is required for transaction signing.");return{sourceTXID:a,sourceSatoshis:o,lockingScript:l,otherInputs:s}}function i8(e){let{tx:t,inputIndex:i,signatureScope:r,sourceTXID:n,sourceSatoshis:s,lockingScript:a,otherInputs:o,inputSequence:l}=e,c=t.inputs[i];return iD.format({sourceTXID:n,sourceOutputIndex:tB(c.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:s,transactionVersion:t.version,otherInputs:o,inputIndex:i,outputs:t.outputs,inputSequence:l??tB(c.sequence,"input.sequence must have value"),subscript:a,lockTime:t.lockTime,scope:r})}class i3{lock(e){let t;if("string"==typeof e){let i=tO(e);if(0!==i.prefix[0]&&111!==i.prefix[0])throw Error("only P2PKH is supported");t=i.data}else t=e;if(20!==t.length)throw Error("P2PKH hash length must be 20 bytes");return new ij([{op:iC.OP_DUP},{op:iC.OP_HASH160},{op:t.length,data:t},{op:iC.OP_EQUALVERIFY},{op:iC.OP_CHECKSIG}])}unlock(e,t="all",i=!1,r,n){return{sign:async(s,a)=>{let o=i1(t,i),l=i2(s,a,r,n);r=l.sourceSatoshis,n=l.lockingScript;let c=i8({tx:s,inputIndex:a,signatureScope:o,sourceTXID:l.sourceTXID,sourceSatoshis:l.sourceSatoshis,lockingScript:l.lockingScript,otherInputs:l.otherInputs}),h=e.sign(ev(c)),d=new iD(h.r,h.s,o).toChecksigFormat(),u=e.toPublicKey().encode(!0);return new iG([{op:d.length,data:d},{op:u.length,data:u}])},estimateLength:async()=>108}}}class i5{type="raw";constructor(e="raw"){this.type=e}lock(e){let t=[{op:iC.OP_OVER},{op:iC.OP_3},{op:iC.OP_SPLIT},{op:iC.OP_NIP},{op:iC.OP_1},{op:iC.OP_SPLIT},{op:iC.OP_SWAP},{op:iC.OP_SPLIT},{op:iC.OP_DROP}];return"raw"!==this.type&&t.push({op:iC["OP_"+this.type]}),t.push({op:e.length,data:e}),t.push({op:iC.OP_EQUALVERIFY}),t.push({op:iC.OP_CHECKSIG}),new ij(t)}unlock(e,t,i="all",r=!1){return{sign:async(n,s)=>{t??=ih.fromRandom();let a=iD.SIGHASH_FORKID;"all"===i&&(a|=iD.SIGHASH_ALL),"none"===i&&(a|=iD.SIGHASH_NONE),"single"===i&&(a|=iD.SIGHASH_SINGLE),r&&(a|=iD.SIGHASH_ANYONECANPAY);let o=[...n.inputs],[l]=o.splice(s,1);if("object"!=typeof l.sourceTransaction)throw TypeError("The source transaction is needed for transaction signing.");let c=iD.format({sourceTXID:l.sourceTransaction?.id("hex")??"",sourceOutputIndex:l.sourceOutputIndex??0,sourceSatoshis:l.sourceTransaction?.outputs[l.sourceOutputIndex]?.satoshis??0,transactionVersion:n.version,otherInputs:o,inputIndex:s,outputs:n.outputs,inputSequence:l.sequence??0xffffffff,subscript:l.sourceTransaction?.outputs[l.sourceOutputIndex]?.lockingScript??new iU,lockTime:n.lockTime,scope:a}),h=t.sign(ev(c),void 0,!0,e),d=new iD(h.r,h.s,a).toChecksigFormat(),u=t.toPublicKey().encode(!0);return new iG([{op:d.length,data:d},{op:u.length,data:u}])},estimateLength:async()=>108}}}let i6=e=>0===e.length||1===e.length&&0===e[0]?{op:0}:1===e.length&&e[0]>0&&e[0]<=16?{op:80+e[0]}:1===e.length&&129===e[0]?{op:79}:e.length<=75?{op:e.length,data:e}:e.length<=255?{op:76,data:e}:e.length<=65535?{op:77,data:e}:{op:78,data:e};class i4{wallet;originator;static decode(e,t="before"){let i,r;if("before"===t)i=ii.fromString(tg(tB(e.chunks[0].data,"script.chunks[0].data must have value"))),r=2;else{let t=e.chunks.length-1;if(e.chunks[t].op!==iC.OP_CHECKSIG)throw Error("Expected OP_CHECKSIG at the end of the script");i=ii.fromString(tg(tB(e.chunks[t-1].data,"public key chunk data must have value"))),r=0}let n=[];for(let t=r;t<e.chunks.length;t++){let i=e.chunks[t+1]?.op,r=e.chunks[t].data??[];if(0===r.length&&(e.chunks[t].op>=80&&e.chunks[t].op<=95?r=[e.chunks[t].op-80]:0===e.chunks[t].op?r=[0]:79===e.chunks[t].op&&(r=[129])),n.push(r),i===iC.OP_DROP||i===iC.OP_2DROP)break}return{fields:n,lockingPublicKey:i}}constructor(e,t){this.wallet=e,this.originator=t}async lock(e,t,i,r,n=!1,s=!0,a="before"){let{publicKey:o}=await this.wallet.getPublicKey({protocolID:t,keyID:i,counterparty:r,forSelf:n},this.originator),l=[],c=[];if(l.push({op:o.length/2,data:tm(o,"hex")}),l.push({op:iC.OP_CHECKSIG}),s){let n=e.flat(),{signature:s}=await this.wallet.createSignature({data:n,protocolID:t,keyID:i,counterparty:r},this.originator);e.push(s)}for(let t of e)c.push(i6(t));let h=e.length;for(;h>1;)c.push({op:iC.OP_2DROP}),h-=2;return new ij((0!==h&&c.push({op:iC.OP_DROP}),"before"===a)?[...l,...c]:[...c,...l])}unlock(e,t,i,r="all",n=!1,s,a){return{sign:async(o,l)=>{let c=i1(r,n),h=i2(o,l,s,a);s=h.sourceSatoshis,a=h.lockingScript;let d=ev(i8({tx:o,inputIndex:l,signatureScope:c,sourceTXID:h.sourceTXID,sourceSatoshis:h.sourceSatoshis,lockingScript:h.lockingScript,otherInputs:h.otherInputs,inputSequence:o.inputs[l].sequence??0xffffffff})),{signature:u}=await this.wallet.createSignature({data:d,protocolID:e,keyID:t,counterparty:i},this.originator),f=t2.fromDER([...u]),p=new iD(f.r,f.s,c).toChecksigFormat();return new iG([{op:p.length,data:p}])},estimateLength:async()=>73}}}class i9{value;constructor(e){this.value=e}async computeFee(e){let t,i=e=>e>0x100000000?9:e>65536?5:e>253?3:1;t=4+i(e.inputs.length);for(let r=0;r<e.inputs.length;r++){let n,s=e.inputs[r];if(t+=40,"object"==typeof s.unlockingScript)n=s.unlockingScript.toBinary().length;else if("object"==typeof s.unlockingScriptTemplate)n=await s.unlockingScriptTemplate.estimateLength(e,r);else throw TypeError("All inputs must have an unlocking script or an unlocking script template for sat/kb fee computation.");t+=i(n),t+=n}for(let r of(t+=i(e.outputs.length),e.outputs)){t+=8;let e=r.lockingScript.toBinary().length;t+=i(e),t+=e}return Math.ceil((t+=4)/1e3*this.value)}}class i7 extends i9{static ARC_POLICY_URL="https://arc.gorillapool.io/v1/policy";static instance=null;cachedRate=null;cacheTimestamp=0;cacheValidityMs;constructor(e=3e5){super(100),this.cacheValidityMs=e}static getInstance(e=3e5){return i7.instance||(i7.instance=new i7(e)),i7.instance}async fetchFeeRate(){let e=Date.now();if(null!==this.cachedRate&&e-this.cacheTimestamp<this.cacheValidityMs)return this.cachedRate;try{let t=await fetch(i7.ARC_POLICY_URL);if(!t.ok)throw Error(`HTTP ${t.status}: ${t.statusText}`);let i=await t.json();if(!i.policy?.miningFee||"number"!=typeof i.policy.miningFee.satoshis||"number"!=typeof i.policy.miningFee.bytes)throw Error("Invalid policy response format");let r=i.policy.miningFee.satoshis/i.policy.miningFee.bytes*1e3;return this.cachedRate=r,this.cacheTimestamp=e,r}catch(e){if(null!==this.cachedRate)return console.warn("Failed to fetch live fee rate, using cached value:",e),this.cachedRate;return console.warn("Failed to fetch live fee rate, using default 100 sat/kb:",e),100}}async computeFee(e){let t=await this.fetchFeeRate();return this.value=t,super.computeFee(e)}}function re(e,t,i,r){return new Promise((n,s)=>{let a=e.request(t,i,e=>{let t="";e.on("data",e=>{t+=e}),e.on("end",()=>{let i=e.statusCode>=200&&e.statusCode<=299,r=e.headers["content-type"],s=""!==t&&"string"==typeof r&&r.startsWith("application/json")?JSON.parse(t):t;n({status:e.statusCode,statusText:e.statusMessage,ok:i,data:s})})});a.on("error",e=>{s(e)}),null!==i.data&&void 0!==i.data&&a.write(r(i.data)),a.end()})}class rt{https;constructor(e){this.https=e}async request(e,t){return await re(this.https,e,t,e=>JSON.stringify(e))}}class ri{fetch;constructor(e){this.fetch=e}async request(e,t){let i={method:t.method,headers:t.headers,body:JSON.stringify(t.data)},r=await this.fetch(e,i),n=r.headers.get("Content-Type"),s=n?.startsWith("application/json")?await r.json():await r.text();return{ok:r.ok,status:r.status,statusText:r.statusText,data:s}}}function rr(){let e={async request(){throw Error("No method available to perform HTTP request")}};if(void 0!==globalThis.window&&"function"==typeof globalThis.window.fetch)return new ri(globalThis.window.fetch.bind(globalThis.window));if("function"==typeof globalThis.fetch)return new ri(globalThis.fetch.bind(globalThis));if("u"<typeof require)return e;try{let e=require("node:https");return new rt(e)}catch(t){return e}}function rn(){return`ts-sdk-${tg(ia(16))}`}class rs{URL;apiKey;deploymentId;callbackUrl;callbackToken;headers;httpClient;constructor(e,t){if(this.URL=e,"string"==typeof t)this.apiKey=t,this.httpClient=rr(),this.deploymentId=rn(),this.callbackToken=void 0,this.callbackUrl=void 0;else{const{apiKey:e,deploymentId:i,httpClient:r,callbackToken:n,callbackUrl:s,headers:a}=t??{};this.apiKey=e,this.httpClient=r??rr(),this.deploymentId=i??rn(),this.callbackToken=n,this.callbackUrl=s,this.headers=a}}requestHeaders(){let e={"Content-Type":"application/json","XDeployment-ID":this.deploymentId};if(null!=this.apiKey&&""!==this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),null!=this.callbackUrl&&""!==this.callbackUrl&&(e["X-CallbackUrl"]=this.callbackUrl),null!=this.callbackToken&&""!==this.callbackToken&&(e["X-CallbackToken"]=this.callbackToken),null!=this.headers)for(let t in this.headers)e[t]=this.headers[t];return e}async broadcast(e){let t;try{t=e.toHexEF()}catch(i){if("All inputs must have source transactions when serializing to EF format"===i.message)t=e.toHex();else throw i}let i={method:"POST",headers:this.requestHeaders(),data:{rawTx:t}};try{let e=await this.httpClient.request(`${this.URL}/v1/tx`,i);if(e.ok){let{txid:t,extraInfo:i,txStatus:r,competingTxs:n}=e.data,s=i?.toUpperCase().includes("ORPHAN")||r?.toUpperCase().includes("ORPHAN");if(["DOUBLE_SPEND_ATTEMPTED","REJECTED","INVALID","MALFORMED","MINED_IN_STALE_BLOCK"].includes(r?.toUpperCase())||s){let e={status:"error",code:r??"UNKNOWN",txid:t,description:`${r??""} ${i??""}`.trim()};return null!=n&&(e.more={competingTxs:n}),e}let a={status:"success",txid:t,message:`${r} ${i}`};return null!=n&&(a.competingTxs=n),a}{let t=typeof e.status,i={status:"error",code:"number"===t||"string"===t?e.status.toString():"ERR_UNKNOWN",description:"Unknown error"},r=e.data;if("string"==typeof r)try{r=JSON.parse(e.data)}catch{}return"object"==typeof r&&(null!==r&&(i.more=r),null!=r&&"string"==typeof r.txid&&(i.txid=r.txid),null!=r&&"detail"in r&&"string"==typeof r.detail&&(i.description=r.detail)),i}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}async broadcastMany(e){let t=e.map(e=>{try{return{rawTx:e.toHexEF()}}catch(t){if("All inputs must have source transactions when serializing to EF format"===t.message)return{rawTx:e.toHex()};throw t}}),i={method:"POST",headers:this.requestHeaders(),data:t};try{return(await this.httpClient.request(`${this.URL}/v1/txs`,i)).data}catch(i){let t={status:"error",code:"500",description:"string"==typeof i.message?i.message:"Internal Server Error"};return e.map(()=>t)}}}function ra(e=!1,t={}){return new rs(e?"https://testnet.arc.gorillapool.io":"https://arc.gorillapool.io",t)}class ro{network;apiKey;URL;httpClient;constructor(e="main",t={}){const{apiKey:i,httpClient:r}=t;this.network=e,this.URL=`https://api.whatsonchain.com/v1/bsv/${e}`,this.httpClient=r??rr(),this.apiKey=i??""}async isValidRootForHeight(e,t){let i={method:"GET",headers:this.getHttpHeaders()},r=await this.httpClient.request(`${this.URL}/block/${t}/header`,i);if(r.ok){let{merkleroot:t}=r.data;return t===e}if(404===r.status)return!1;throw Error(`Failed to verify merkleroot for height ${t} because of an error: ${JSON.stringify(r.data)} `)}async currentHeight(){try{let e={method:"GET",headers:this.getHttpHeaders()},t=await this.httpClient.request(`${this.URL}/block/headers`,e);if(t.ok)return t.data[0].height;throw Error(`Failed to get current height because of an error: ${JSON.stringify(t.data)} `)}catch(e){throw Error(`Failed to get current height because of an error: ${e instanceof Error?e.message:String(e)}`)}}getHttpHeaders(){let e={Accept:"application/json"};return"string"==typeof this.apiKey&&""!==this.apiKey.trim()&&(e.Authorization=this.apiKey),e}}function rl(){return new ro}class rc{blockHeight;path;static fromHex(e){return rc.fromBinary(tm(e,"hex"))}static fromReader(e,t=!0){let i,r,n,s=e.readVarIntNum(),a=e.readUInt8(),o=Array(a).fill(null).map(()=>[]);for(let t=0;t<a;t++){for(n=e.readVarIntNum();n>0;){r=e.readVarIntNum(),i=e.readUInt8();let s={offset:r};(1&i)==1?s.duplicate=!0:((2&i)!=0&&(s.txid=!0),s.hash=tg(e.read(32).reverse())),Array.isArray(o[t])&&0!==o[t].length||(o[t]=[]),o[t].push(s),n--}o[t].sort((e,t)=>e.offset-t.offset)}return new rc(s,o,t)}static fromBinary(e){let t=new tc(e);return rc.fromReader(t)}static fromCoinbaseTxidAndHeight(e,t){return new rc(t,[[{offset:0,hash:e,txid:!0}]])}constructor(e,t,i=!0){let r;this.blockHeight=e,this.path=t;const n=Array(this.path.length).fill(0).map(()=>new Set);this.path.forEach((e,t)=>{if(0===e.length&&0===t)throw Error(`Empty level at height: ${t}`);let r=new Set;e.forEach(e=>{if(r.has(e.offset))throw Error(`Duplicate offset: ${e.offset}, at height: ${t}`);if(r.add(e.offset),0===t){if(!0!==e.duplicate)for(let t=1;t<this.path.length;t++)n[t].add(e.offset>>t^1)}else if(i&&!n[t].has(e.offset))throw Error(`Invalid offset: ${e.offset}, at height: ${t}, with legal offsets: ${Array.from(n[t]).join(", ")}`)})}),this.path[0].forEach((e,t)=>{if(0===t&&(r=this.computeRoot(e.hash)),r!==this.computeRoot(e.hash))throw Error("Mismatched roots")})}toWriter(e){e.writeVarIntNum(this.blockHeight);let t=this.path.length;e.writeUInt8(t);for(let i=0;i<t;i++){let t=Object.keys(this.path[i]).length;for(let r of(e.writeVarIntNum(t),this.path[i])){e.writeVarIntNum(r.offset);let t=0;r?.duplicate===!0&&(t|=1),r?.txid!==void 0&&null!==r.txid&&(t|=2),e.writeUInt8(t),(1&t)==0&&e.write(tm(r.hash,"hex").reverse())}}}toBinary(){let e=new tP;return this.toWriter(e),e.toArray()}toBinaryUint8Array(){let e=new tl;return this.toWriter(e),e.toUint8Array()}toHex(){return tg(this.toBinaryUint8Array())}indexOf(e){let t=this.path[0].find(t=>t.hash===e);if(null==t)throw Error(`Transaction ID ${e} not found in the Merkle Path`);return t.offset}computeRoot(e){if("string"!=typeof e){let t=this.path[0].find(e=>!!e?.hash);if(null==t)throw Error("No valid leaf found in the Merkle Path");e=t.hash}if("string"!=typeof e)throw TypeError("Transaction ID is undefined");let t=this.indexOf(e),i=e=>tg(ek(tm(e,"hex").reverse()).reverse()),r=e;if(1===this.path.length&&1===this.path[0].length)return r;let n=this.path[0].reduce((e,t)=>Math.max(e,t.offset),0),s=Math.max(this.path.length,32-Math.clz32(n));for(let e=0;e<s;e++){let s=t>>e^1,a=this.findOrComputeLeaf(e,s);if("object"!=typeof a){if(1===this.path.length&&t>>e==n>>e){r=i((r??"")+(r??""));continue}throw Error(`Missing hash for index ${t} at height ${e}`)}r=i(!0===a.duplicate?(r??"")+(r??""):s%2==1?(a.hash??"")+(r??""):(r??"")+(a.hash??""))}return r}findOrComputeLeaf(e,t){let i=e=>tg(ek(tm(e,"hex").reverse()).reverse()),r=e<this.path.length?this.path[e].find(e=>e.offset===t):void 0;if(null!=r)return r;if(0===e)return;let n=e-1,s=t<<1,a=this.findOrComputeLeaf(n,s);if(a?.hash==null||""===a.hash)return;let o=this.findOrComputeLeaf(n,s+1);if(o?.hash==null)return o?.duplicate===!0||1===this.path.length&&s===this.path[0].reduce((e,t)=>Math.max(e,t.offset),0)>>n?{offset:t,hash:i(a.hash+a.hash)}:void 0;return{offset:t,hash:i(!0===o.duplicate?a.hash+a.hash:(o.hash??"")+(a.hash??""))}}async verify(e,t){let i=this.computeRoot(e);if(0===this.indexOf(e)){let e=await t.currentHeight();if(this.blockHeight+100>e)return!1}return await t.isValidRootForHeight(i,this.blockHeight)}combine(e){if(this.blockHeight!==e.blockHeight)throw Error("You cannot combine paths which do not have the same block height.");if(this.computeRoot()!==e.computeRoot())throw Error("You cannot combine paths which do not have the same root.");let t=[];for(let i=0;i<this.path.length;i++){for(let e of(t.push([]),this.path[i]))t[i].push(e);for(let r of e.path[i]){let e=t[i].find(e=>e.offset===r.offset);void 0===e?t[i].push(r):r?.txid!==void 0&&r?.txid!==null&&(e.txid=!0)}}this.path=t,this.trim()}trim(){let e=(e,t)=>{(0===t.length||t.at(-1)!==e)&&t.push(e)},t=(e,t)=>{for(let i=e.length;i>=0;i--){let r=this.path[t].findIndex(t=>t.offset===e[i]);r>=0&&this.path[t].splice(r,1)}},i=t=>{let i=[];for(let r of t)e(r>>1,i);return i},r=[],n=[];for(let e of this.path)e.sort((e,t)=>e.offset-t.offset);for(let t=0;t<this.path[0].length;t++){let i=this.path[0][t];if(!0===i.txid)e(i.offset>>1,r);else{let r=i.offset%2==1,s=this.path[0][t+(r?-1:1)];void 0!==s.txid&&null!==s.txid&&s.txid||e(s.offset,n)}}t(n,0);for(let e=1;e<this.path.length;e++)n=r,r=i(r),t(n,e)}cachedFindLeaf(e,t,i,r,n){let s=`${e}:${t}`;if(r.has(s))return r.get(s);let a=e=>tg(ek(tm(e,"hex").reverse()).reverse()),o=e<i.length?i[e].get(t):void 0;if(null!=o)return r.set(s,o),o;if(0===e)return void r.set(s,void 0);let l=e-1,c=t<<1,h=this.cachedFindLeaf(l,c,i,r,n);if(h?.hash==null||""===h.hash)return void r.set(s,void 0);let d=this.cachedFindLeaf(l,c+1,i,r,n);return d?.hash==null?d?.duplicate===!0||1===this.path.length&&c===n>>l?(o={offset:t,hash:a(h.hash+h.hash)},r.set(s,o),o):void r.set(s,void 0):(o={offset:t,hash:a(!0===d.duplicate?h.hash+h.hash:(d.hash??"")+(h.hash??""))},r.set(s,o),o)}extract(e){if(0===e.length)throw Error("At least one txid must be provided to extract");let t=this.computeRoot(),i=this.path[0].reduce((e,t)=>Math.max(e,t.offset),0),r=Math.max(this.path.length,32-Math.clz32(i)),n=Array(this.path.length);for(let e=0;e<this.path.length;e++){let t=new Map;for(let i of this.path[e])t.set(i.offset,i);n[e]=t}let s=new Map,a=new Map;for(let e of this.path[0])null!=e.hash&&a.set(e.hash,e.offset);let o=Array(r);for(let e=0;e<r;e++)o[e]=new Map;for(let t of e){let e=a.get(t);if(void 0===e)throw Error(`Transaction ID ${t} not found in the Merkle Path`);o[0].set(e,{offset:e,txid:!0,hash:t});let l=1^e;if(!o[0].has(l)){let e=this.cachedFindLeaf(0,l,n,s,i);null!=e&&o[0].set(l,e)}for(let t=1;t<r;t++){let r=e>>t^1;if(o[t].has(r))continue;let a=this.cachedFindLeaf(t,r,n,s,i);null!=a?o[t].set(r,a):e>>t==i>>t&&o[t].set(r,{offset:r,duplicate:!0})}}let l=Array(r);for(let e=0;e<r;e++)l[e]=Array.from(o[e].values()).sort((e,t)=>e.offset-t.offset);let c=new rc(this.blockHeight,l);c.trim();let h=c.computeRoot();if(h!==t)throw Error(`Extracted path root ${h} does not match original root ${t}`);return c}}let rh=0xefbe0001,rd=0xefbe0002,ru=0x1010101;(s=c||(c={}))[s.RAWTX=0]="RAWTX",s[s.RAWTX_AND_BUMP_INDEX=1]="RAWTX_AND_BUMP_INDEX",s[s.TXID_ONLY=2]="TXID_ONLY";class rf{_bumpIndex;_tx;_rawTx;_txid;inputTxids=[];isValid=void 0;get bumpIndex(){return this._bumpIndex}set bumpIndex(e){this._bumpIndex=e,this.updateInputTxids()}get hasProof(){return void 0!==this._bumpIndex}get isTxidOnly(){return void 0!==this._txid&&null!==this._txid&&null==this._rawTx&&null==this._tx}get txid(){if(void 0!==this._txid&&null!==this._txid&&""!==this._txid)return this._txid;if(null!=this._tx)return this._txid=this._tx.id("hex"),this._txid;if(null!=this._rawTx)return this._txid=tg(ek(this._rawTx)),this._txid;throw Error("Internal")}get tx(){return null!=this._tx?this._tx:null!=this._rawTx?(this._tx=rg.fromBinary(this._rawTx),this._tx):void 0}get rawTx(){if(null!=this._rawTx)return Array.from(this._rawTx);if(null!=this._tx){let e=this._tx.toUint8Array();return this._rawTx=e,Array.from(e)}}get rawTxUint8Array(){return null!=this._rawTx?this._rawTx:null!=this._tx?(this._rawTx=this._tx.toUint8Array(),this._rawTx):void 0}constructor(e,t){if("string"==typeof e)this._txid=e;else if(e instanceof Uint8Array)this._rawTx=e;else if(Array.isArray(e))this._rawTx=new Uint8Array(e);else if(e instanceof rg)this._tx=e;else throw TypeError("Invalid transaction data type");this.bumpIndex=t,this.updateInputTxids()}static fromTx(e,t){return new rf(e,t)}static fromRawTx(e,t){return new rf(e,t)}static fromTxid(e,t){return new rf(e,t)}updateInputTxids(){if(this.hasProof||null==this.tx)this.inputTxids=[];else{let e=new Set;for(let t of this.tx.inputs)void 0!==t.sourceTXID&&null!==t.sourceTXID&&""!==t.sourceTXID&&e.add(t.sourceTXID);this.inputTxids=Array.from(e)}}toWriter(e,t){let i=t=>{e.writeUInt8(t)},r=()=>{if(null==this._txid)throw Error("Transaction ID (_txid) is undefined");e.writeReverse(tm(this._txid,"hex"))},n=()=>{let t=this.rawTxUint8Array;if(null==t)throw Error("a valid serialized Transaction is expected");e.write(t)},s=()=>{void 0===this.bumpIndex?i(c.RAWTX):(i(c.RAWTX_AND_BUMP_INDEX),e.writeVarIntNum(this.bumpIndex))};t===rd?this.isTxidOnly?(i(c.TXID_ONLY),r()):(void 0!==this.bumpIndex?(i(c.RAWTX_AND_BUMP_INDEX),e.writeVarIntNum(this.bumpIndex)):i(c.RAWTX),n()):(n(),s())}static fromReader(e,t){let i,r,n;if(t===rd){let t=e.readUInt8();t===c.TXID_ONLY?n=rf.fromTxid(tg(e.readReverse(32))):(t===c.RAWTX_AND_BUMP_INDEX&&(r=e.readVarIntNum()),i=rg.fromReader(e),n=rf.fromTx(i,r))}else i=rg.fromReader(e),r=0===e.readUInt8()?void 0:e.readVarIntNum(),n=rf.fromTx(i,r);return n}}class rp{bumps=[];txs=[];version=rd;atomicTxid=void 0;txidIndex=void 0;rawBytesCache;hexCache;needsSort=!0;constructor(e=rd){this.version=e}invalidateSerializationCaches(){this.rawBytesCache=void 0,this.hexCache=void 0}markMutated(e=!0){this.invalidateSerializationCaches(),e&&(this.needsSort=!0)}ensureSerializableState(){for(let e of this.txs)e.txid}ensureSortedForSerialization(){this.needsSort&&this.sortTxs()}getSerializedBytes(){if(this.ensureSerializableState(),null==this.rawBytesCache){this.ensureSortedForSerialization();let e=new tl;this.toWriter(e),this.rawBytesCache=e.toUint8Array()}return this.rawBytesCache}getBeefForAtomic(e){this.needsSort&&this.sortTxs();let t=this.findTxid(e);if(null==t)throw Error(`${e} does not exist in this Beef`);let i=this.txs.at(-1)===t?this:this.clone();if(i!==this){let t=this.txs.findIndex(t=>t.txid===e);i.txs.splice(t+1)}let r=new tl;return r.writeUInt32LE(ru),r.writeReverse(tm(e,"hex")),{beef:i,writer:r}}findTxid(e){return this.ensureTxidIndex().get(e)}ensureTxidIndex(){if(null==this.txidIndex)for(let e of(this.txidIndex=new Map,this.txs))this.txidIndex.set(e.txid,e);return this.txidIndex}deleteFromIndex(e){this.txidIndex?.delete(e)}addToIndex(e){this.txidIndex?.set(e.txid,e)}makeTxidOnly(e){let t=this.txs.findIndex(t=>t.txid===e);if(-1===t)return;let i=this.txs[t];return i.isTxidOnly?i:(this.deleteFromIndex(e),this.txs.splice(t,1),this.markMutated(!0),i=this.mergeTxidOnly(e))}findBump(e){return this.bumps.find(t=>t.path[0].some(t=>t.hash===e))}findTransactionForSigning(e){let t=this.findTxid(e);if(null!=t&&null!=t.tx){for(let e of t.tx.inputs)if(null==e.sourceTransaction){let t=this.findTxid(tB(e.sourceTXID,"sourceTXID must be valid"));null!=t&&(e.sourceTransaction=t.tx)}return t.tx}}findAtomicTransaction(e){let t=this.findTxid(e);if(null!=t&&null!=t.tx)return this.addInputProof(t.tx),t.tx}addInputProof(e){let t=this.findBump(e.id("hex"));if(null!=t){e.merklePath=t;return}for(let t of e.inputs)this.resolveInputSource(t),null!=t.sourceTransaction&&this.attachMerklePathOrRecurse(t.sourceTransaction)}resolveInputSource(e){if(null==e.sourceTransaction){let t=this.findTxid(tB(e.sourceTXID,"sourceTXID must be valid"));null!=t&&(e.sourceTransaction=t.tx)}}attachMerklePathOrRecurse(e){let t=this.findBump(e.id("hex"));null!=t?e.merklePath=t:this.addInputProof(e)}mergeBump(e){this.markMutated(!1);let t=this.findOrInsertBump(e),i=this.bumps[t];for(let e of this.txs)null==e.bumpIndex&&this.tryMarkTxProvenByBump(e,i,t);return t}findOrInsertBump(e){for(let t=0;t<this.bumps.length;t++){let i=this.bumps[t];if(i===e)return t;if(i.blockHeight===e.blockHeight&&i.computeRoot()===e.computeRoot())return i.combine(e),t}return this.bumps.push(e),this.bumps.length-1}tryMarkTxProvenByBump(e,t,i){let r=e.txid;for(let n of t.path[0])if(n.hash===r){e.bumpIndex=i,n.txid=!0;break}}mergeRawTx(e,t){this.markMutated(!0);let i=new rf(e,t);return this.removeExistingTxid(i.txid),this.txs.push(i),this.addToIndex(i),this.tryToValidateBumpIndex(i),i}mergeTransaction(e){let t;this.markMutated(!0);let i=e.id("hex");this.removeExistingTxid(i),null!=e.merklePath&&(t=this.mergeBump(e.merklePath));let r=new rf(e,t);if(this.txs.push(r),this.addToIndex(r),this.tryToValidateBumpIndex(r),void 0===(t=r.bumpIndex))for(let t of e.inputs)null!=t.sourceTransaction&&this.mergeTransaction(t.sourceTransaction);return r}removeExistingTxid(e){let t=this.txs.findIndex(t=>t.txid===e);t>=0&&(this.deleteFromIndex(e),this.txs.splice(t,1),this.markMutated(!0))}mergeTxidOnly(e){let t=this.findTxid(e);return null==t&&(t=new rf(e),this.txs.push(t),this.addToIndex(t),this.tryToValidateBumpIndex(t),this.markMutated(!0)),t}mergeBeefTx(e){let t=this.findTxid(e.txid);if(e.isTxidOnly&&null==t?t=this.mergeTxidOnly(e.txid):null!=e._tx&&(null==t||t.isTxidOnly)?t=this.mergeTransaction(e._tx):null!=e._rawTx&&(null==t||t.isTxidOnly)&&(t=this.mergeRawTx(e._rawTx)),null==t)throw Error(`Failed to merge BeefTx for txid: ${e.txid}`);return t}mergeBeef(e){let t=e instanceof rp?e:rp.fromBinary(e);for(let e of t.bumps)this.mergeBump(e);for(let e of t.txs)this.mergeBeefTx(e)}isValid(e){return this.verifyValid(e).valid}async verify(e,t){let i=this.verifyValid(t);if(!i.valid)return!1;for(let t of Object.keys(i.roots))if(!await e.isValidRootForHeight(i.roots[t],Number(t)))return!1;return!0}verifyValid(e){let t={valid:!1,roots:{}},i=this.sortTxs();if(i.missingInputs.length>0||i.notValid.length>0||i.txidOnly.length>0&&!0!==e||i.withMissingInputs.length>0)return t;let r={};return this.collectTxidOnlyTxids(r,e)&&this.collectBumpTxids(r,t)&&this.verifyBumpIndexLeaves()&&this.verifyInputDependencies(r)&&(t.valid=!0),t}collectTxidOnlyTxids(e,t){for(let i of this.txs)if(i.isTxidOnly){if(!0!==t)return!1;e[i.txid]=!0}return!0}collectBumpTxids(e,t){for(let i of this.bumps)for(let r of i.path[0])if(!0===r.txid&&"string"==typeof r.hash&&0!==r.hash.length&&(e[r.hash]=!0,!this.confirmComputedRoot(i,r.hash,t)))return!1;return!0}verifyBumpIndexLeaves(){for(let e of this.txs)if(void 0!==e.bumpIndex&&null==this.bumps[e.bumpIndex].path[0].find(t=>t.hash===e.txid))return!1;return!0}verifyInputDependencies(e){for(let t of this.txs){for(let i of t.inputTxids)if(!e[i])return!1;e[t.txid]=!0}return!0}confirmComputedRoot(e,t,i){let r=e.computeRoot(t);return(void 0===i.roots[e.blockHeight]||""===i.roots[e.blockHeight])&&(i.roots[e.blockHeight]=r),i.roots[e.blockHeight]===r}toWriter(e){for(let t of(e.writeUInt32LE(this.version),e.writeVarIntNum(this.bumps.length),this.bumps))e.write(t.toBinary());for(let t of(e.writeVarIntNum(this.txs.length),this.txs))t.toWriter(e,this.version)}toBinary(){return Array.from(this.getSerializedBytes())}toUint8Array(){return this.getSerializedBytes()}toBinaryAtomic(e){let{beef:t,writer:i}=this.getBeefForAtomic(e);return t.toWriter(i),i.toArray()}toUint8ArrayAtomic(e){let{beef:t,writer:i}=this.getBeefForAtomic(e),r=t.getSerializedBytes(),n=i.toUint8Array(),s=new Uint8Array(n.length+r.length);return s.set(n,0),s.set(r,n.length),s}toHex(){if(null!=this.hexCache)return this.hexCache;let e=tg(this.getSerializedBytes());return this.hexCache=e,e}static fromReader(e){let t,i=e.readUInt32LE();if(i===ru&&(t=tg(e.readReverse(32)),i=e.readUInt32LE()),i!==rh&&i!==rd)throw Error(`Serialized BEEF must start with ${rh} or ${rd} but starts with ${i}`);let r=new rp(i),n=e.readVarIntNum();for(let t=0;t<n;t++){let t=rc.fromReader(e,!1);r.bumps.push(t)}let s=e.readVarIntNum();for(let t=0;t<s;t++){let t=rf.fromReader(e,i);r.txs.push(t)}return r.atomicTxid=t,r}static fromBinary(e){let t=tc.makeReader(e);return rp.fromReader(t)}static fromString(e,t="hex"){let i=new tc(ty(e,t));return rp.fromReader(i)}tryToValidateBumpIndex(e){if(void 0!==e.bumpIndex)return!0;let t=e.txid;for(let i=0;i<this.bumps.length;i++){let r=this.bumps[i].path[0].findIndex(e=>e.hash===t);if(r>=0)return e.bumpIndex=i,this.bumps[i].path[0][r].txid=!0,!0}return!1}sortTxs(){let e={},t={},i=[],r=[],n=this.partitionTxs(t,e,i,r),{txsMissingInputs:s,missingInputs:a,remaining:o}=this.separateMissingInputs(n,t);n=o;let l=this.topoSort(n,e,i);return this.txs=s.concat(l).concat(r).concat(i),this.needsSort=!1,this.invalidateSerializationCaches(),{missingInputs:Object.keys(a),notValid:l.map(e=>e.txid),valid:Object.keys(e),withMissingInputs:s.map(e=>e.txid),txidOnly:r.map(e=>e.txid)}}partitionTxs(e,t,i,r){let n=[];for(let s of this.txs)e[s.txid]=s,s.isValid=s.hasProof,s.isValid?(t[s.txid]=!0,i.push(s)):s.isTxidOnly&&0===s.inputTxids.length?(t[s.txid]=!0,r.push(s)):n.push(s);return n}separateMissingInputs(e,t){let i={},r=[],n=[];for(let s of e){let e=!1;for(let r of s.inputTxids)void 0===t[r]&&(i[r]=!0,e=!0);e?r.push(s):n.push(s)}return{txsMissingInputs:r,missingInputs:i,remaining:n}}topoSort(e,t,i){for(;e.length>0;){let r=e;for(let n of(e=[],r))n.inputTxids.every(e=>t[e])?(t[n.txid]=!0,i.push(n)):e.push(n);if(r.length===e.length)break}return e}clone(){let e=new rp;return e.version=this.version,e.bumps=Array.from(this.bumps),e.txs=Array.from(this.txs),e.txidIndex=void 0,e.needsSort=this.needsSort,e.hexCache=this.hexCache,e.rawBytesCache=this.rawBytesCache,e}trimKnownTxids(e){let t=this.removeKnownTxidOnlyTxs(e);(t=this.reindexBumps()||t)&&this.markMutated(!0)}removeKnownTxidOnlyTxs(e){let t=!1;for(let i=0;i<this.txs.length;){let r=this.txs[i];r.isTxidOnly&&e.includes(r.txid)?(this.deleteFromIndex(r.txid),this.txs.splice(i,1),t=!0):i++}return t}reindexBumps(){let e=new Set;for(let t of this.txs)void 0!==t.bumpIndex&&e.add(t.bumpIndex);if(e.size>=this.bumps.length)return!1;let t=new Map,i=0;for(let r=0;r<this.bumps.length;r++)e.has(r)&&(t.set(r,i),i++);for(let i of(this.bumps=this.bumps.filter((t,i)=>e.has(i)),this.txs)){if(void 0===i.bumpIndex)continue;let e=t.get(i.bumpIndex);if(void 0===e)throw Error(`Internal error: bumpIndex ${i.bumpIndex} not found in indexMap`);i.bumpIndex=e}return!0}getValidTxids(){return this.sortTxs().valid}toLogString(){let e="";e+=`BEEF with ${this.bumps.length} BUMPS and ${this.txs.length} Transactions, isValid ${this.isValid().toString()}
|
|
7
7
|
`;let t=-1;for(let i of this.bumps)t++,e+=` BUMP ${t}
|
|
8
8
|
block: ${i.blockHeight}
|
|
9
9
|
txids: [
|
|
@@ -16,4 +16,4 @@ ${i.path[0].filter(e=>!0===e.txid).map(e=>` '${e.hash??""}'`).join(",\n")}
|
|
|
16
16
|
`,i.inputTxids.length>0&&(e+=` inputs: [
|
|
17
17
|
${i.inputTxids.map(e=>` '${e}'`).join(",\n")}
|
|
18
18
|
]
|
|
19
|
-
`);return e}addComputedLeaves(){for(let e of this.bumps)for(let t=1;t<e.path.length;t++)this.addComputedLeavesForRow(e,t)}addComputedLeavesForRow(e,t){let i=e=>tg(ek(tm(e,"hex").reverse()).reverse());for(let r of e.path[t-1]){if("string"!=typeof r.hash||(1&r.offset)!=0)continue;let n=e.path[t-1].find(e=>e.offset===r.offset+1);if(void 0===n||"string"!=typeof n.hash)continue;let s=r.offset>>1;e.path[t].every(e=>e.offset!==s)&&e.path[t].push({offset:s,hash:i(n.hash+r.hash)})}}}class rg{version;inputs;outputs;lockTime;metadata;merklePath;cachedHash;rawBytesCache;hexCache;static addPathOrInputs(e,t,i){if("number"==typeof e.pathIndex){let t=i[e.pathIndex];if("object"!=typeof t)throw TypeError("Invalid merkle path index found in BEEF!");e.tx.merklePath=t}else for(let r of e.tx.inputs){if(void 0===r.sourceTXID)throw Error("Input sourceTXID is undefined");let e=t[r.sourceTXID];if("object"!=typeof e)throw TypeError(`Reference to unknown TXID in BEEF: ${r.sourceTXID??"undefined"}`);r.sourceTransaction=e.tx,this.addPathOrInputs(e,t,i)}}static fromBEEF(e,t){let{tx:i}=rg.fromAnyBeef(e,t);return i}static fromAtomicBEEF(e){let{tx:t,txid:i,beef:r}=rg.fromAnyBeef(e);if(i!==r.atomicTxid)if(null==r.atomicTxid)throw Error("beef must conform to BRC-95 and must contain the subject txid.");else throw Error(`Transaction with TXID ${r.atomicTxid} not found in BEEF data.`);return t}static fromAnyBeef(e,t){let i=rp.fromBinary(e);if(i.txs.length<1)throw Error("beef must include at least one transaction.");let r=i.txs.at(-1);if(null==r)throw Error("beef must include at least one transaction.");let n=t??i.atomicTxid??r.txid,s=i.findAtomicTransaction(n);if(null==s)if(null==t)throw Error("beef does not contain transaction for atomic txid.");else throw Error(`Transaction with TXID ${String(n)} not found in BEEF data.`);return{tx:s,beef:i,txid:n}}static fromEF(e){let t=tc.makeReader(e),i=t.readUInt32LE();if("0000000000ef"!==tg(t.read(6)))throw Error("Invalid EF marker");let r=t.readVarIntNum(),n=[];for(let e=0;e<r;e++){let e=tg(t.readReverse(32)),i=t.readUInt32LE(),r=t.readVarIntNum(),s=t.read(r),a=iG.fromBinary(s),o=t.readUInt32LE(),l=t.readUInt64LEBn().toNumber(),c=t.readVarIntNum(),h=t.read(c),d=ij.fromBinary(h),u=new rg(void 0,[],[],void 0);u.outputs=Array(i+1).fill(null),u.outputs[i]={satoshis:l,lockingScript:d},n.push({sourceTransaction:u,sourceTXID:e,sourceOutputIndex:i,unlockingScript:a,sequence:o})}let s=t.readVarIntNum(),a=[];for(let e=0;e<s;e++){let e=t.readUInt64LEBn().toNumber(),i=t.readVarIntNum(),r=t.read(i),n=ij.fromBinary(r);a.push({satoshis:e,lockingScript:n})}return new rg(i,n,a,t.readUInt32LE())}static parseScriptOffsets(e){let t=tc.makeReader(e),i=[],r=[];t.pos+=4;let n=t.readVarIntNum();for(let e=0;e<n;e++){t.pos+=36;let r=t.readVarIntNum();i.push({vin:e,offset:t.pos,length:r}),t.pos+=r+4}let s=t.readVarIntNum();for(let e=0;e<s;e++){t.pos+=8;let i=t.readVarIntNum();r.push({vout:e,offset:t.pos,length:i}),t.pos+=i}return{inputs:i,outputs:r}}static fromReader(e){let t=e.readUInt32LE(),i=e.readVarIntNum(),r=[];for(let t=0;t<i;t++){let t=tg(e.readReverse(32)),i=e.readUInt32LE(),n=e.readVarIntNum(),s=e.read(n),a=iG.fromBinary(s),o=e.readUInt32LE();r.push({sourceTXID:t,sourceOutputIndex:i,unlockingScript:a,sequence:o})}let n=e.readVarIntNum(),s=[];for(let t=0;t<n;t++){let t=e.readUInt64LEBn().toNumber(),i=e.readVarIntNum(),r=e.read(i),n=ij.fromBinary(r);s.push({satoshis:t,lockingScript:n})}return new rg(t,r,s,e.readUInt32LE())}static fromBinary(e){let t=e.slice(),i=Uint8Array.from(t),r=new tc(i),n=rg.fromReader(r);return n.rawBytesCache=i,n}static fromHex(e){let t=ty(e,"hex"),i=new tc(t),r=rg.fromReader(i);return r.rawBytesCache=t,r.hexCache=tg(t),r}static fromHexEF(e){return rg.fromEF(ty(e,"hex"))}static fromHexBEEF(e,t){return rg.fromBEEF(tm(e,"hex"),t)}constructor(e=1,t=[],i=[],r=0,n=new Map,s){this.version=e,this.inputs=t,this.outputs=i,this.lockTime=r,this.metadata=n,this.merklePath=s}invalidateSerializationCaches(){this.cachedHash=void 0,this.rawBytesCache=void 0,this.hexCache=void 0}addInput(e){if(void 0===e.sourceTXID&&void 0===e.sourceTransaction)throw TypeError("A reference to an an input transaction is required. If the input transaction itself cannot be referenced, its TXID must still be provided.");e.sequence??=0xffffffff,this.invalidateSerializationCaches(),this.inputs.push(e)}addOutput(e){if(this.cachedHash=void 0,!0!==e.change){if(void 0===e.satoshis)throw TypeError("either satoshis must be defined or change must be set to true");if(e.satoshis<0)throw Error("satoshis must be a positive integer or zero")}if(null==e.lockingScript)throw Error("lockingScript must be defined");this.outputs.push(e)}addP2PKHOutput(e,t){let i=new i3().lock(e);if(void 0===t)return this.addOutput({lockingScript:i,change:!0});this.addOutput({lockingScript:i,satoshis:t})}updateMetadata(e){this.metadata={...this.metadata,...e}}async fee(e=i7.getInstance(),t="equal"){if(this.invalidateSerializationCaches(),"number"==typeof e){let t=e;e={computeFee:async()=>t}}let i=await e.computeFee(this),r=this.calculateChange(i);if(r<=0){this.outputs=this.outputs.filter(e=>!0!==e.change);return}this.distributeChange(r,t)}calculateChange(e){let t=0;for(let e of this.inputs){if("object"!=typeof e.sourceTransaction)throw TypeError("Source transactions are required for all inputs during fee computation");t+=e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0}for(let i of(t-=e,this.outputs))!0!==i.change&&void 0!==i.satoshis&&(t-=i.satoshis);return t}distributeChange(e,t){let i=0,r=this.outputs.filter(e=>e.change);if("random"===t?i=this.distributeRandomChange(e,r):"equal"===t&&(i=this.distributeEqualChange(e,r)),i<e){let t=this.outputs.at(-1);void 0===t.satoshis?t.satoshis=e-i:t.satoshis+=e-i}}distributeRandomChange(e,t){let i=0,r=e,n=Array(t.length).fill(1);r-=t.length,i+=t.length;for(let e=0;e<t.length-1;e++){let t=this.benfordNumber(0,r);n[e]=n[e]+t,i+=t,r-=t}for(let e of this.outputs)!0===e.change&&(e.satoshis=n.shift());return i}distributeEqualChange(e,t){let i=0,r=Math.floor(e/t.length);for(let e of t)i+=r,e.satoshis=r;return i}benfordNumber(e,t){return Math.floor(e+(t-e)*Math.log10(1+1/(ia(1)[0]%9+1))/Math.log10(10))}getFee(){let e=0;for(let t of this.inputs){if("object"!=typeof t.sourceTransaction)throw TypeError("Source transactions or sourceSatoshis are required for all inputs to calculate fee");e+=t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0}let t=0;for(let e of this.outputs)t+=e.satoshis??0;return e-t}async sign(){for(let e of(this.invalidateSerializationCaches(),this.outputs))if(void 0===e.satoshis)if(!0===e.change)throw Error("There are still change outputs with uncomputed amounts. Use the fee() method to compute the change amounts and transaction fees prior to signing.");else throw Error("One or more transaction outputs is missing an amount. Ensure all output amounts are provided before signing.");let e=await Promise.all(this.inputs.map(async(e,t)=>"object"==typeof this.inputs[t].unlockingScriptTemplate?await this.inputs[t]?.unlockingScriptTemplate?.sign(this,t):await Promise.resolve(void 0)));for(let t=0,i=this.inputs.length;t<i;t++)"object"==typeof this.inputs[t].unlockingScriptTemplate&&(this.inputs[t].unlockingScript=e[t])}async broadcast(e=ra()){return await e.broadcast(this)}writeTransactionBody(e){for(let t of(e.writeUInt32LE(this.version),e.writeVarIntNum(this.inputs.length),this.inputs)){if(void 0===t.sourceTXID)if(null==t.sourceTransaction)throw Error("sourceTransaction is undefined");else e.write(t.sourceTransaction.hash());else e.writeReverse(tm(t.sourceTXID,"hex"));if(e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw Error("unlockingScript is undefined");let i=t.unlockingScript.toUint8Array();e.writeVarIntNum(i.length),e.write(i),e.writeUInt32LE(t.sequence??0xffffffff)}for(let t of(e.writeVarIntNum(this.outputs.length),this.outputs)){e.writeUInt64LE(t.satoshis??0);let i=t.lockingScript.toUint8Array();e.writeVarIntNum(i.length),e.write(i)}e.writeUInt32LE(this.lockTime)}buildSerializedBytes(){let e=new tl;return this.writeTransactionBody(e),e.toUint8Array()}getSerializedBytes(){return this.rawBytesCache??=this.buildSerializedBytes(),this.rawBytesCache}toBinary(){return Array.from(this.getSerializedBytes())}toUint8Array(){return this.getSerializedBytes()}writeEF(e){for(let t of(e.writeUInt32LE(this.version),e.write([0,0,0,0,0,239]),e.writeVarIntNum(this.inputs.length),this.inputs)){if(void 0===t.sourceTransaction)throw TypeError("All inputs must have source transactions when serializing to EF format");if(void 0===t.sourceTXID?e.write(t.sourceTransaction.hash()):e.write(tm(t.sourceTXID,"hex").reverse()),e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw Error("unlockingScript is undefined");let i=t.unlockingScript.toBinary();e.writeVarIntNum(i.length),e.write(i),e.writeUInt32LE(t.sequence??0xffffffff),e.writeUInt64LE(t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0);let r=t.sourceTransaction.outputs[t.sourceOutputIndex].lockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r)}for(let t of(e.writeVarIntNum(this.outputs.length),this.outputs)){e.writeUInt64LE(t.satoshis??0);let i=t.lockingScript.toBinary();e.writeVarIntNum(i.length),e.write(i)}e.writeUInt32LE(this.lockTime)}toEF(){let e=new tP;return this.writeEF(e),e.toArray()}toEFUint8Array(){let e=new tl;return this.writeEF(e),e.toUint8Array()}toHexEF(){return tg(this.toEFUint8Array())}toHex(){if(null!=this.hexCache)return this.hexCache;let e=tg(this.getSerializedBytes());return this.hexCache=e,e}toHexBEEF(){return tg(this.toBEEF())}toHexAtomicBEEF(){return tg(this.toAtomicBEEF())}hash(e){return(this.cachedHash??=ek(this.getSerializedBytes()),"hex"===e)?tg(this.cachedHash):this.cachedHash}id(e){let t=[...this.hash()];return(t.reverse(),"hex"===e)?tg(t):t}async verify(e=rl(),t,i){let r=new Set,n=[this];for(;n.length>0;){let s=n.shift(),a=s?.id("hex")??"";if(null!=a&&""!==a&&r.has(a))continue;if("object"==typeof s?.merklePath)if("scripts only"===e){null!=a&&r.add(a);continue}else{if(await s.merklePath.verify(a,e)){r.add(a);continue}throw Error(`Invalid merkle path for transaction ${a}`)}if(void 0!==t){if(void 0===s)throw Error("Transaction is undefined");let e=rg.fromEF(s.toEF());if(delete e.outputs[0].satoshis,e.outputs[0].change=!0,await e.fee(t),s.getFee()<e.getFee())throw Error(`Verification failed because the transaction ${a} has an insufficient fee and has not been mined.`)}let o=0;if(void 0===s)throw Error("Transaction is undefined");for(let e=0;e<s.inputs.length;e++){let t=s.inputs[e];if("object"!=typeof t.sourceTransaction)throw TypeError(`Verification failed because the input at index ${e} of transaction ${a} is missing an associated source transaction. This source transaction is required for transaction verification because there is no merkle proof for the transaction spending a UTXO it contains.`);if("object"!=typeof t.unlockingScript)throw TypeError(`Verification failed because the input at index ${e} of transaction ${a} is missing an associated unlocking script. This script is required for transaction verification because there is no merkle proof for the transaction spending the UTXO.`);let l=t.sourceTransaction.outputs[t.sourceOutputIndex];o+=l.satoshis??0;let c=t.sourceTransaction.id("hex");r.has(c)||n.push(t.sourceTransaction);let h=s.inputs.filter((t,i)=>i!==e);if(t.sourceTXID??=c,!new i0({sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,lockingScript:l.lockingScript,sourceSatoshis:l.satoshis??0,transactionVersion:s.version,otherInputs:h,unlockingScript:t.unlockingScript,inputSequence:t.sequence??0xffffffff,inputIndex:e,outputs:s.outputs,lockTime:s.lockTime,memoryLimit:i}).validate())return!1}let l=0;for(let e of s.outputs){if("number"!=typeof e.satoshis)throw TypeError("Every output must have a defined amount during transaction verification.");l+=e.satoshis}if(l>o)return!1;r.add(a)}return!0}writeSerializedBEEF(e,t){e.writeUInt32LE(rh);let i=[],r=new Map,n=new Map,s=[],a=new Set,o=e=>{let l=e.id("hex");if(a.has(l))return;let c={tx:e},h=e.merklePath,d="object"==typeof h;if(d&&null!=h&&(c.pathIndex=(e=>{let t=r.get(e);if(void 0!==t)return t;let s=`${e.blockHeight}:${e.computeRoot()}`,a=n.get(s);if(void 0!==a)return i[a].combine(e),r.set(e,a),a;let o=i.length;return i.push(e),r.set(e,o),n.set(s,o),o})(h)),!d)for(let i=e.inputs.length-1;i>=0;i--){let r=e.inputs[i];if("object"==typeof r.sourceTransaction)o(r.sourceTransaction);else if(!1===t)throw Error("A required source transaction is missing!")}a.add(l),s.push(c)};for(let t of(o(this),e.writeVarIntNum(i.length),i))e.write(t.toBinary());for(let t of(e.writeVarIntNum(s.length),s))e.write(t.tx.toBinary()),"number"==typeof t.pathIndex?(e.writeUInt8(1),e.writeVarIntNum(t.pathIndex)):e.writeUInt8(0);return e.toArray()}toBEEF(e){let t=new tP;return this.writeSerializedBEEF(t,e),t.toArray()}toBEEFUint8Array(e){let t=new tl;return this.writeSerializedBEEF(t,e),t.toArray()}toAtomicBEEF(e){return[1,1,1,1].concat(this.hash(),this.toBEEF(e))}toAtomicBEEFUint8Array(e){let t=new tl;t.write([1,1,1,1]);let i=this.hash();return t.write(i),this.writeSerializedBEEF(t,e),t.toUint8Array()}async completeWithWallet(e,t,i,r){let n,s=this.inputs.length,a=this.outputs.length,o={description:t??`Transaction with ${s} input(s) and ${a} output(s)`,inputs:[],outputs:[],lockTime:this.lockTime,version:this.version},l=this.inputs.some(e=>null!=e.unlockingScriptTemplate),c=new rp;for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];if(null==t.sourceTransaction)throw Error("All inputs must have a sourceTransaction when using completeWithWallet");let i=t.sourceTransaction.toBEEF();c.mergeBeef(i);let r=t.sourceTransaction.id("hex"),n={outpoint:`${r}.${t.sourceOutputIndex}`,inputDescription:"Input from source transaction",sequenceNumber:t.sequence};if(l)if(null!=t.unlockingScriptTemplate)n.unlockingScriptLength=await t.unlockingScriptTemplate.estimateLength(this,e);else if(null!=t.unlockingScript)n.unlockingScript=t.unlockingScript.toHex();else throw Error(`Input ${e} must have either an unlockingScript or unlockingScriptTemplate`);else{if(null==t.unlockingScript)throw Error("All inputs must have an unlockingScript when using completeWithWallet");n.unlockingScript=t.unlockingScript.toHex()}o.inputs.push(n)}for(let e of(this.inputs.length>0&&(o.inputBEEF=c.toBinary()),this.outputs))o.outputs.push({satoshis:e.satoshis,lockingScript:e.lockingScript.toHex(),outputDescription:"Output from source transaction"});if(this.metadata?.labels!=null&&Array.isArray(this.metadata.labels)&&(o.labels=this.metadata.labels),l){o.options={...r,signAndProcess:!1};let{signableTransaction:t}=await e.createAction(o,i);if(null==t)throw Error("Wallet createAction did not return signableTransaction");let s=rg.fromBEEF(t.tx),a={};for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];if(null!=t.unlockingScriptTemplate){let i=await t.unlockingScriptTemplate.sign(s,e);a[e]={unlockingScript:i.toHex()}}else null!=t.unlockingScript&&(a[e]={unlockingScript:t.unlockingScript.toHex()})}let l=null==r?void 0:{acceptDelayedBroadcast:r.acceptDelayedBroadcast,returnTXIDOnly:r.returnTXIDOnly,noSend:r.noSend,sendWith:r.sendWith},c=await e.signAction({reference:t.reference,spends:a,options:l},i);if(null==c.tx)throw Error("Wallet signAction did not return transaction data");n=c.tx}else{null!=r&&(o.options=r);let{tx:t}=await e.createAction(o,i);if(null==t)throw Error("Wallet createAction did not return transaction data");n=t}let h=rg.fromAtomicBEEF(n);this.version=h.version,this.inputs=h.inputs,this.outputs=h.outputs,this.lockTime=h.lockTime,this.merklePath=h.merklePath,this.cachedHash=h.cachedHash,this.metadata={...this.metadata,...h.metadata}}preimage(e,t,i){if(e??=0,t??=iD.SIGHASH_FORKID|iD.SIGHASH_ALL,e<0||e>=this.inputs.length)throw Error("Invalid input index");let r=240&t;if(224!==r&&192!==r&&64!==r)throw Error("FORKID must be set");let n=15&t;if(n<1||n>3)throw Error("Invalid signature coverage, must be all, none or single");let s=this.inputs[e];if(null==s.sourceTransaction)throw Error("Source transaction is required");let a=s.sourceTransaction.outputs[s.sourceOutputIndex];if(null==a)throw Error(`Source transaction's output at index ${s.sourceOutputIndex} is required`);let o=this.inputs.filter((t,i)=>i!==e);return iD.format({sourceTXID:s.sourceTXID??s.sourceTransaction.id("hex"),sourceOutputIndex:s.sourceOutputIndex,sourceSatoshis:a.satoshis,transactionVersion:this.version,otherInputs:o,inputIndex:e,outputs:this.outputs,inputSequence:s.sequence??0xffffffff,subscript:i??a.lockingScript,lockTime:this.lockTime,scope:t})}}function ry(e){return"success"===e.status}function rm(e){return"error"===e.status}let rb=class extends rp{knownTo={};constructor(e){if(super(),null!=e)for(const t of e)this.addParty(t)}isParty(e){return Object.keys(this.knownTo).includes(e)}addParty(e){if(this.isParty(e))throw Error(`Party ${e} already exists.`);this.knownTo[e]={}}getKnownTxidsForParty(e){let t=this.knownTo[e];if(void 0===t)throw Error(`Party ${e} is unknown.`);return Object.keys(t)}getTrimmedBeefForParty(e){let t=this.getKnownTxidsForParty(e),i=this.clone();return i.trimKnownTxids(t),i}addKnownTxidsForParty(e,t){this.isParty(e)||this.addParty(e);let i=this.knownTo[e];for(let e of t)i[e]=!0,this.mergeTxidOnly(e)}mergeBeefFromParty(e,t){let i=Array.isArray(t)?rp.fromBinary(t):t,r=i.getValidTxids();this.mergeBeef(i),this.addKnownTxidsForParty(e,r)}};class rw{network;URL;httpClient;constructor(e="main",t=rr()){this.network=e,this.URL=`https://api.whatsonchain.com/v1/bsv/${e}/tx/raw`,this.httpClient=t}async broadcast(e){let t=e.toHex();try{let e=await this.httpClient.request(this.URL,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/plain"},data:{txhex:t}});if(!e.ok)return{status:"error",code:e.status.toString()??"ERR_UNKNOWN",description:e.data??"Unknown error"};{let t=e.data;return{status:"success",txid:t,message:"broadcast successful"}}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class rv{https;constructor(e){this.https=e}async request(e,t){return await re(this.https,e,t,e=>Buffer.from(e))}}class rI{fetch;constructor(e){this.fetch=e}async request(e,t){let i={method:t.method,headers:t.headers,body:t.data},r=await this.fetch(e,i),n=await r.text();return{ok:r.ok,status:r.status,statusText:r.statusText,data:n}}}function rk(){let e={async request(){throw Error("No method available to perform HTTP request")}};if(void 0!==globalThis.window&&"function"==typeof globalThis.window.fetch)return new rI(globalThis.window.fetch.bind(globalThis.window));if("function"==typeof globalThis.fetch)return new rI(globalThis.fetch.bind(globalThis));if("u"<typeof require)return e;try{let e=require("node:https");return new rv(e)}catch(t){return e}}class rS{URL;httpClient;constructor(e,t=rk()){this.URL=e,this.httpClient=t}async broadcast(e){let t={method:"POST",headers:{"Content-Type":"application/octet-stream"},data:new Blob([new Uint8Array(e.toEF())])};try{let i=await this.httpClient.request(this.URL,t);if(!i.ok)return{status:"error",code:i.status.toString()??"ERR_UNKNOWN",description:i.data??"Unknown error"};{let t=e.id("hex");return{status:"success",txid:t,message:"broadcast successful"}}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class rE{baseUrl;httpClient;apiKey;constructor(e,t={}){const{httpClient:i,apiKey:r}=t;this.baseUrl=e,this.httpClient=i??rr(),this.apiKey=r??""}async isValidRootForHeight(e,t){let i={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.apiKey}`},data:[{blockHeight:t,merkleRoot:e}]};try{let e=await this.httpClient.request(`${this.baseUrl}/api/v1/chain/merkleroot/verify`,i);if(e.ok)return"CONFIRMED"===e.data.confirmationState;throw Error(`Failed to verify merkleroot for height ${t} because of an error: ${JSON.stringify(e.data)}`)}catch(e){throw Error(`Failed to verify merkleroot for height ${t} because of an error: ${e instanceof Error?e.message:String(e)}`)}}async currentHeight(){let e={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`}};try{let t=await this.httpClient.request(`${this.baseUrl}/api/v1/chain/tip/longest`,e);if(t.ok&&t.data&&"number"==typeof t.data.height)return t.data.height;throw Error(`Failed to get current height because of an error: ${JSON.stringify(t.data)}`)}catch(e){throw Error(`Failed to get current height because of an error: ${e instanceof Error?e.message:String(e)}`)}}}let rx="42423301",rA=(e,t,i)=>{let r="object"!=typeof i;if(r){let e=new t1,t=new ih(1),r=e.g.mul(t);i=new ii(r.x,r.y)}let n=ia(32),s=tS(n),a=`2-message signing-${s}`,o=t.deriveChild(i,a).sign(e).toDER(),l=t.toPublicKey().encode(!0);return[...tm(rx,"hex"),...l,...r?[0]:i.encode(!0),...n,...o]},rT=(e,t,i)=>{let r=new tN(t),n=tg(r.read(4));if(n!==rx)throw Error(`Message version mismatch: Expected ${rx}, received ${n}`);let s=ii.fromString(tg(r.read(33))),[a]=r.read(1);if(0===a)i=new ih(1);else{let e=tg([a,...r.read(32)]);if("object"!=typeof i)throw TypeError(`This signature can only be verified with knowledge of a specific private key. The associated public key is: ${e}`);let t=i.toPublicKey().encode(!0,"hex");if(e!==t)throw Error(`The recipient public key is ${t} but the signature requres the recipient to have public key ${e}`)}let o=tS(r.read(32)),l=tg(r.read(r.bin.length-r.pos)),c=t2.fromDER(l,"hex"),h=`2-message signing-${o}`;return s.deriveChild(i,h).verify(e,c)},rO="42421033",rP=(e,t,i)=>{let r=ia(32),n=tS(r),s=`2-message encryption-${n}`,a=t.deriveChild(i,s),o=i.deriveChild(t,s),l=new i_(a.deriveSharedSecret(o).encode(!0).slice(1)).encrypt(e),c=t.toPublicKey().encode(!0);return[...tm(rO,"hex"),...c,...i.encode(!0),...r,...l]},rN=(e,t)=>{let i=new tN(e),r=tg(i.read(4));if(r!==rO)throw Error(`Message version mismatch: Expected ${rO}, received ${r}`);let n=ii.fromString(tg(i.read(33))),s=tg(i.read(33)),a=t.toPublicKey().encode(!0,"hex");if(s!==a)throw Error(`The encrypted message expects a recipient public key of ${s}, but the provided key is ${a}`);let o=tS(i.read(32)),l=i.read(i.bin.length-i.pos),c=`2-message encryption-${o}`,h=n.deriveChild(t,c),d=t.deriveChild(n,c);return new i_(h.deriveSharedSecret(d).encode(!0).slice(1)).decrypt(l)},r_="Bitcoin Signed Message:\n",rR=e=>{let t=new tP;return t.writeVarIntNum(r_.length),t.write(tm(r_,"utf8")),t.writeVarIntNum(e.length),t.write(e),ek(t.toArray())},rC=(e,t,i="base64")=>{let r=rR(e),n=ie(new A(r),t,!0);if("raw"===i)return n;let s=new A(r),a=n.CalculateRecoveryFactor(t.toPublicKey(),s);return n.toCompact(a,!0,"base64")},rB=(e,t,i)=>it(new A(rR(e)),t,i);class rU{versionBytesNum;depth;parentFingerPrint;childIndex;chainCode;privKey;pubKey;constants={pubKey:0x488b21e,privKey:0x488ade4};constructor(e,t,i,r,n,s,a){this.versionBytesNum=e,this.depth=t,this.parentFingerPrint=i,this.childIndex=r,this.chainCode=n,this.privKey=s,this.pubKey=a}fromRandom(){return this.versionBytesNum=this.constants.privKey,this.depth=0,this.parentFingerPrint=[0,0,0,0],this.childIndex=0,this.chainCode=ia(32),this.privKey=ih.fromRandom(),this.pubKey=this.privKey.toPublicKey(),this}static fromRandom(){return new this().fromRandom()}static fromString(e){return new this().fromString(e)}fromString(e){let t=tO(e);return this.fromBinary([...t.prefix,...t.data])}static fromSeed(e){return new this().fromSeed(e)}fromSeed(e){if(e.length<16)throw Error("Need more than 128 bits of entropy");if(e.length>64)throw Error("More than 512 bits of entropy is nonstandard");let t=ex(tm("Bitcoin seed","utf8"),e);return this.depth=0,this.parentFingerPrint=[0,0,0,0],this.childIndex=0,this.chainCode=t.slice(32,64),this.versionBytesNum=this.constants.privKey,this.privKey=new ih(t.slice(0,32)),this.pubKey=this.privKey.toPublicKey(),this}static fromBinary(e){return new this().fromBinary(e)}fromBinary(e){if(78!==e.length)throw Error("incorrect bip32 data length");let t=new tN(e);this.versionBytesNum=t.readUInt32BE(),this.depth=t.readUInt8(),this.parentFingerPrint=t.read(4),this.childIndex=t.readUInt32BE(),this.chainCode=t.read(32);let i=t.read(33),r=this.versionBytesNum===this.constants.privKey,n=this.versionBytesNum===this.constants.pubKey;if(r&&0===i[0])this.privKey=new ih(i.slice(1,33)),this.pubKey=this.privKey.toPublicKey();else if(n&&(2===i[0]||3===i[0]))this.pubKey=ii.fromString(tg(i));else throw Error("Invalid key");return this}toString(){return tT(this.toBinary(),[])}derive(e){if("m"===e)return this;let t=e.split("/"),i=this;for(let[e,r]of t.entries()){if(0===e){if("m"!==r)throw Error("invalid path");continue}let t=/^(\d+)('?)$/.exec(r);if(null===t)throw Error("invalid path");let n=Number.parseInt(t[1],10);if(n>0x7fffffff)throw Error("invalid path");let s="'"===t[2],a=n;s&&(a+=0x80000000),i=i.deriveChild(a)}return i}deriveChild(e){if("number"!=typeof e)throw TypeError("i must be a number");let t=[];t.push(e>>24&255),t.push(e>>16&255),t.push(e>>8&255),t.push(255&e);let i=[...t],r=(0x80000000&e)!=0,n=this.versionBytesNum===this.constants.privKey;if(r&&(null===this.privKey||void 0===this.privKey||!n))throw Error("Cannot do private key derivation without private key");let s=null;if(null!==this.privKey&&void 0!==this.privKey){let e=null;e=r?[0,...this.privKey.toArray("be",32),...i]:[...this.pubKey.encode(!0),...i];let t=ex(this.chainCode,e),n=new A(t.slice(0,32)),a=t.slice(32,64),o=n.add(this.privKey).mod(new t1().n);(s=new rU).chainCode=a,s.privKey=new ih(o.toArray()),s.pubKey=s.privKey.toPublicKey()}else{let e=[...this.pubKey.encode(!0),...i],t=ex(this.chainCode,e),r=new A(t.slice(0,32)),n=t.slice(32,64),a=new t1().g.mul(r),o=this.pubKey,l=a.add(o),c=new ii(l.x,l.y);(s=new rU).chainCode=n,s.pubKey=c}s.childIndex=e;let a=eS(this.pubKey.encode(!0));return s.parentFingerPrint=a.slice(0,4),s.versionBytesNum=this.versionBytesNum,s.depth=this.depth+1,s}toPublic(){let e=new rU(this.versionBytesNum,this.depth,this.parentFingerPrint,this.childIndex,this.chainCode,this.privKey,this.pubKey);return e.versionBytesNum=this.constants.pubKey,e.privKey=void 0,e}toBinary(){let e=this.versionBytesNum===this.constants.privKey,t=this.versionBytesNum===this.constants.pubKey;if(e)return new tP().writeUInt32BE(this.versionBytesNum).writeUInt8(this.depth).write(this.parentFingerPrint).writeUInt32BE(this.childIndex).write(this.chainCode).writeUInt8(0).write(this.privKey.toArray("be",32)).toArray();if(t)return new tP().writeUInt32BE(this.versionBytesNum).writeUInt8(this.depth).write(this.parentFingerPrint).writeUInt32BE(this.childIndex).write(this.chainCode).write(this.pubKey.encode(!0)).toArray();throw Error("bip32: invalid versionBytesNum byte")}isPrivate(){return this.versionBytesNum===this.constants.privKey}}let rF={value:["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"],space:" "};class rD{mnemonic;seed;Wordlist;constructor(e,t,i=rF){this.mnemonic=e??"",this.seed=t??[],this.Wordlist=i}toBinary(){let e=new tP;if(""===this.mnemonic)e.writeVarIntNum(0);else{let t=tm(this.mnemonic,"utf8");e.writeVarIntNum(t.length),e.write(t)}return this.seed.length>0?(e.writeVarIntNum(this.seed.length),e.write(this.seed)):e.writeVarIntNum(0),e.toArray()}fromBinary(e){let t=new tN(e),i=t.readVarIntNum();i>0&&(this.mnemonic=tk(t.read(i),"utf8"));let r=t.readVarIntNum();return r>0&&(this.seed=t.read(r)),this}fromRandom(e){if((null==e||Number.isNaN(e)||0===e)&&(e=128),e%32!=0)throw Error("bits must be multiple of 32");if(e<128)throw Error("bits must be at least 128");let t=ia(e/8);return this.entropy2Mnemonic(t),this.mnemonic2Seed(),this}static fromRandom(e){return new this().fromRandom(e)}fromEntropy(e){return this.entropy2Mnemonic(e),this}static fromEntropy(e){return new this().fromEntropy(e)}fromString(e){return this.mnemonic=e,this}static fromString(e){return new this().fromString(e)}toString(){return this.mnemonic}toSeed(e){return this.mnemonic2Seed(e),this.seed}entropy2Mnemonic(e){if(e.length<16)throw Error("Entropy is less than 128 bits. It must be 128 bits or more.");let t=ev(e),i="",r=8*e.length;for(let t of e)i+=("00000000"+t.toString(2)).slice(-8);let n=t[0].toString(2);if((i+=n=("00000000"+n).slice(-8).slice(0,r/32)).length%11!=0)throw Error("internal error - entropy not an even multiple of 11 bits - "+i.length.toString());let s="";for(let e=0;e<i.length/11;e++){""!==s&&(s+=this.Wordlist.space);let t=Number.parseInt(i.slice(11*e,(e+1)*11),2);s+=this.Wordlist.value[t]}return this.mnemonic=s,this}check(){let e=this.mnemonic.split(this.Wordlist.space),t="";for(let i of e){let e=this.Wordlist.value.indexOf(i);if(e<0)return!1;t+=("00000000000"+e.toString(2)).slice(-11)}if(t.length%11!=0)throw Error("internal error - entropy not an even multiple of 11 bits - "+t.length.toString());let i=t.length/33,r=t.slice(-i),n=t.slice(0,t.length-i),s=[];for(let e=0;e<n.length/8;e++)s.push(Number.parseInt(t.slice(8*e,(e+1)*8),2));let a=ev(s.slice(0,n.length/8))[0].toString(2);return(a=("00000000"+a).slice(-8).slice(0,i))===r}mnemonic2Seed(e=""){let t=this.mnemonic;if(!this.check())throw Error("Mnemonic does not pass the check - was the mnemonic typed incorrectly? Are there extra spaces?");if("string"!=typeof e)throw TypeError("passphrase must be a string or undefined");t=t.normalize("NFKD"),e=e.normalize("NFKD");let i=tm(t,"utf8"),r=[...tm("mnemonic","utf8"),...tm(e,"utf8")];return this.seed=tn(i,r,2048,64,"sha512"),this}isValid(e=""){let t;try{this.mnemonic2Seed(e),t=!0}catch{t=!1}return t}static isValid(e,t=""){return new rD(e).isValid(t)}}function rL(e){let t,i;0===this._tables[0][0][0]&&this._precompute();let r=this._tables[0][4],n=this._tables[1],s=e.length,a=1;if(4!==s&&6!==s&&8!==s)throw Error("invalid aes key size");let o=e.slice(0),l=[];for(this._key=[o,l],i=s;i<4*s+28;i++)t=o[i-1],(i%s==0||8===s&&i%s==4)&&(t=r[t>>>24]<<24^r[t>>16&255]<<16^r[t>>8&255]<<8^r[255&t],i%s==0&&(t=t<<8^t>>>24^a<<24,a=a<<1^(a>>7)*283)),o[i]=o[i-s]^t;for(let e=0;i>0;e++,i--)t=o[(3&e)==0?i-4:i],i<=4||e<4?l[e]=t:l[e]=n[0][r[t>>>24]]^n[1][r[t>>16&255]]^n[2][r[t>>8&255]]^n[3][r[255&t]]}rL.prototype={encrypt:function(e){return this._crypt(e,0)},decrypt:function(e){return this._crypt(e,1)},_tables:[[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)]],_precompute:function(){let e,t,i,r,n,s,a,o,l=this._tables[0],c=this._tables[1],h=l[4],d=c[4],u=new Uint8Array(256),f=new Uint8Array(256);for(e=0;e<256;e++)u[e]=e<<1^(e>>7)*283,f[u[e]^e]=e;for(t=i=0;0===h[t];t^=0===r?1:r,i=0===f[i]?1:f[i])for(e=0,s=(s=i^i<<1^i<<2^i<<3^i<<4)>>8^255&s^99,h[t]=s,d[s]=t,r=u[t],n=u[r],o=0x1010101*u[n]^65537*n^257*r^0x1010100*t,a=257*u[s]^0x1010100*s;e<4;e++)l[e][t]=a=a<<24^a>>>8,c[e][s]=o=o<<24^o>>>8},_crypt:function(e,t){let i,r,n,s;if(4!==e.length)throw Error("invalid aes block size");let a=this._key[t],o=e[0]^a[0],l=e[1===t?3:1]^a[1],c=e[2]^a[2],h=e[1===t?1:3]^a[3],d=a.length/4-2,u=4,f=new Uint32Array(4),p=this._tables[t],g=p[0],y=p[1],m=p[2],b=p[3],w=p[4];for(s=0;s<d;s++)i=g[o>>>24]^y[l>>16&255]^m[c>>8&255]^b[255&h]^a[u],r=g[l>>>24]^y[c>>16&255]^m[h>>8&255]^b[255&o]^a[u+1],n=g[c>>>24]^y[h>>16&255]^m[o>>8&255]^b[255&l]^a[u+2],h=g[h>>>24]^y[o>>16&255]^m[l>>8&255]^b[255&c]^a[u+3],u+=4,o=i,l=r,c=n;for(s=0;s<4;s++)f[1===t?3&-s:s]=w[o>>>24]<<24^w[l>>16&255]<<16^w[c>>8&255]<<8^w[255&h]^a[u++],i=o,o=l,l=c,c=h,h=i;return f}};class rV{static encrypt(e,t){let i=rV.buf2Words(t),r=rV.buf2Words(e),n=new rL(i).encrypt(r);return rV.words2Buf(n)}static decrypt(e,t){let i=rV.buf2Words(e),r=new rL(rV.buf2Words(t)).decrypt(i);return rV.words2Buf(r)}static buf2Words(e){if(e.length%4!=0)throw Error("buf length must be a multiple of 4");let t=[];for(let i=0;i<e.length/4;i++){let r=0x1000000*e[4*i]+(e[4*i+1]<<16|e[4*i+2]<<8|e[4*i+3]);t.push(r)}return t}static words2Buf(e){let t=Array(4*e.length);for(let i=0;i<e.length;i++){let r=e[i];t[4*i]=r>>>24&255,t[4*i+1]=r>>>16&255,t[4*i+2]=r>>>8&255,t[4*i+3]=255&r}return t}}class rH{static buf2BlocksBuf(e,t){let i=t/8,r=[];for(let n=0;n<=e.length/i;n++){let s=e.slice(n*i,n*i+i);s.length<t&&(s=rH.pkcs7Pad(s,t)),r.push(s)}return r}static blockBufs2Buf(e){let t=e.at(-1);return t=rH.pkcs7Unpad(t),e[e.length-1]=t,e.flat()}static encrypt(e,t,i,r){let n=8*t.length,s=rH.buf2BlocksBuf(e,n);return rH.encryptBlocks(s,t,i,r).flat()}static decrypt(e,t,i,r){let n=t.length,s=[];for(let t=0;t<e.length/n;t++)s.push(e.slice(t*n,t*n+n));let a=rH.decryptBlocks(s,t,i,r);return rH.blockBufs2Buf(a)}static encryptBlock(e,t,i,r){let n=rH.xorBufs(e,t);return i.encrypt(n,r)}static decryptBlock(e,t,i,r){let n=i.decrypt(e,r);return rH.xorBufs(n,t)}static encryptBlocks(e,t,i,r){let n=[];for(let s of e){let e=rH.encryptBlock(s,t,i,r);n.push(e),t=e}return n}static decryptBlocks(e,t,i,r){let n=[];for(let s of e){let e=rH.decryptBlock(s,t,i,r);n.push(e),t=s}return n}static pkcs7Pad(e,t){let i=t/8-e.length,r=Array(i);return r.fill(i),[...e,...r]}static pkcs7Unpad(e){let t=e.at(-1),i=e.slice(e.length-t,e.length),r=Array(t);if(r.fill(t),tg(i)!==tg(r))throw Error("invalid padding");return e.slice(0,e.length-t)}static xorBufs(e,t){if(e.length!==t.length)throw Error("bufs must have the same length");let i=Array(e.length);for(let r=0;r<e.length;r++)i[r]=e[r]^t[r];return i}}class rM{static encrypt(e,t,i,r=!0){i=i??ia(16);let n=rH.encrypt(e,i,rV,t);return r?[...i,...n]:[...n]}static decrypt(e,t,i){if(null!=i)return rH.decrypt(e,i,rV,t);{i=e.slice(0,16);let r=e.slice(16);return rH.decrypt(r,i,rV,t)}}}class rK{static ivkEkM(e,t){let i=t.mul(e),r=eI(new ii(i.x,i.y).encode(!0));return{iv:r.slice(0,16),kE:r.slice(16,32),kM:r.slice(32,64)}}static electrumEncrypt(e,t,i,r=!1){let n,s=null;i??=ih.fromRandom(),r||(s=i.toPublicKey().encode(!0));let{iv:a,kE:o,kM:l}=rK.ivkEkM(i,t),c=rM.encrypt(e,o,a,!1),h=tm("BIE1","utf8"),d=eE(l,n=null!=s&&s.length>0?[...h,...s,...c]:[...h,...c]);return[...n,...d]}static electrumDecrypt(e,t,i){if("BIE1"!==tk(e.slice(0,4),"utf8"))throw Error("Invalid Magic");let r=4,n=null;if(e.length-r-32>=33){let t=e[r];2===t||3===t?(n=e.slice(r,r+33),r+=33):4===t&&(n=e.slice(r,r+65),r+=65)}if(null===n){if(null==i)throw Error("Sender public key is required")}else i??=ii.fromString(tg(n));let{iv:s,kE:a,kM:o}=rK.ivkEkM(t,i),l=e.slice(r,e.length-32),c=e.slice(e.length-32,e.length),h=eE(o,e.slice(0,e.length-32));if(tg(c)!==tg(h))throw Error("Invalid checksum");return rM.decrypt(l,a,s)}static bitcoreEncrypt(e,t,i,r){i??=ih.fromRandom(),r??=ia(16);let n=i,s=i.toPublicKey().encode(!0),a=eI(t.mul(n).getX().toArray("be",32)),o=a.slice(0,32),l=a.slice(32,64),c=rM.encrypt(e,o,r),h=eE(l,[...c]);return[...s,...c,...h]}static bitcoreDecrypt(e,t){let i=ii.fromString(tg(e.slice(0,33))).mul(t);if(i.eq(new t0(0,0)))throw Error("P equals 0");let r=eI(i.getX().toArray("be",32)),n=r.slice(0,32),s=r.slice(32,64),a=e.slice(33,-32),o=e.slice(-32),l=eE(s,a);if(tg(o)!==tg(l))throw Error("Invalid checksum");return[...rM.decrypt(a,n)]}}function rq(e,t){let i=new rg(0,[],[],0);return i.outputs=Array(e.vout+1).fill(null),i.outputs[e.vout]={satoshis:e.satoshis,lockingScript:ij.fromHex(e.script)},{sourceTransaction:i,sourceTXID:e.txid,sourceOutputIndex:e.vout,unlockingScriptTemplate:t,sequence:0xffffffff}}class r${static generate(e,t){let i=this.withDefaultOptions(t);return rz(e,this.getCounter(i.timestamp,i.period),i)}static validate(e,t,i){let r=this.withDefaultValidateOptions(i);if((t=t.trim()).length!==r.digits)return!1;let n=this.getCounter(r.timestamp,r.period),s=[n];for(let e=1;e<=r.skew;e++)s.push(n+e),s.push(n-e);for(let i of s){let n=rz(e,i,r);if(tU(tm(t,"utf8"),tm(n,"utf8")))return!0}return!1}static getCounter(e,t){return Math.floor(Math.floor(e/1e3)/t)}static withDefaultOptions(e){return{digits:2,algorithm:"SHA-1",period:30,timestamp:Date.now(),...e}}static withDefaultValidateOptions(e){return{skew:1,...this.withDefaultOptions(e)}}}function rz(e,t,i){let r=(function(e,t,i){switch(i){case"SHA-1":return new ep(e).update(t);case"SHA-256":return new ef(e).update(t);case"SHA-512":return new eg(e).update(t);default:throw Error("unsupported HMAC algorithm")}})(e,new A(t).toArray("be",8),i.algorithm).digest(),n=(r.at(-1)??0)&15;return(0x7fffffff&new A(r.slice(n,n+4)).toNumber()).toString().slice(-i.digits)}(a=h||(h={}))[a.Silent=0]="Silent",a[a.App=1]="App",a[a.Counterparty=2]="Counterparty";class rW{cacheSharedSecret;retrieveCachedSharedSecret;rootKey;identityKey;anyone;constructor(e,t,i){this.cacheSharedSecret=t,this.retrieveCachedSharedSecret=i,this.anyone=new ih(1).toPublicKey(),"anyone"===e?this.rootKey=new ih(1):this.rootKey=e,this.identityKey=this.rootKey.toPublicKey().toString()}derivePublicKey(e,t,i,r=!1){return(i=this.normalizeCounterparty(i),r)?this.rootKey.deriveChild(i,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret).toPublicKey():i.deriveChild(this.rootKey,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}derivePrivateKey(e,t,i){return i=this.normalizeCounterparty(i),this.rootKey.deriveChild(i,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}deriveSymmetricKey(e,t,i){i="anyone"===i?this.anyone:this.normalizeCounterparty(i);let r=this.derivePublicKey(e,t,i),n=this.derivePrivateKey(e,t,i);return new i_(n.deriveSharedSecret(r)?.x?.toArray()??[])}revealCounterpartySecret(e){if("self"===e)throw Error("Counterparty secrets cannot be revealed for counterparty=self.");e=this.normalizeCounterparty(e);let t=this.rootKey.toPublicKey();if(this.rootKey.deriveChild(t,"test").toHex()===this.rootKey.deriveChild(e,"test").toHex())throw Error("Counterparty secrets cannot be revealed for counterparty=self.");return this.rootKey.deriveSharedSecret(e).encode(!0)}revealSpecificSecret(e,t,i){e=this.normalizeCounterparty(e);let r=this.rootKey.deriveSharedSecret(e),n=tm(this.computeInvoiceNumber(t,i),"utf8");return eE(r.encode(!0),n)}normalizeCounterparty(e){if(null==e)throw Error("counterparty must be self, anyone or a public key!");return"self"===e?this.rootKey.toPublicKey():"anyone"===e?new ih(1).toPublicKey():"string"==typeof e?ii.fromString(e):e}computeInvoiceNumber(e,t){let i=e[0];if(!Number.isInteger(i)||i<0||i>2)throw Error("Protocol security level must be 0, 1, or 2");let r=e[1].toLowerCase().trim();if(t.length>800)throw Error("Key IDs must be 800 characters or less");if(t.length<1)throw Error("Key IDs must be 1 character or more");if(r.length>400)if(r.startsWith("specific linkage revelation ")){if(r.length>430)throw Error("Specific linkage revelation protocol names must be 430 characters or less")}else throw Error("Protocol names must be 400 characters or less");if(r.length<5)throw Error("Protocol names must be 5 characters or more");if(r.includes(" "))throw Error('Protocol names cannot contain multiple consecutive spaces (" ")');if(!/^[a-z0-9 ]+$/g.test(r))throw Error("Protocol names can only contain letters, numbers and spaces");if(r.endsWith(" protocol"))throw Error('No need to end your protocol name with " protocol"');return`${i}-${r}-${t}`}}class rj{keyDeriver;cache;maxCacheSize;rootKey;identityKey;constructor(e,t){"anyone"===e?this.rootKey=new ih(1):this.rootKey=e,this.keyDeriver=new rW(this.rootKey,(e,t,i)=>{this.cacheSet(`${e.toString()}-${t.toString()}`,i)},(e,t)=>this.cacheGet(`${e.toString()}-${t.toString()}`)),this.identityKey=this.rootKey.toPublicKey().toString(),this.cache=new Map;const i=t?.maxCacheSize;this.maxCacheSize=null!=i&&!Number.isNaN(i)&&i>0?i:1e3}derivePublicKey(e,t,i,r=!1){let n=this.generateCacheKey("derivePublicKey",e,t,i,r);if(this.cache.has(n)){let e=this.cacheGet(n);if(void 0===e)throw Error("Cached value is undefined");return e}{let s=this.keyDeriver.derivePublicKey(e,t,i,r);return this.cacheSet(n,s),s}}derivePrivateKey(e,t,i){let r=this.generateCacheKey("derivePrivateKey",e,t,i);if(this.cache.has(r)){let e=this.cacheGet(r);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.derivePrivateKey(e,t,i);return this.cacheSet(r,n),n}}deriveSymmetricKey(e,t,i){let r=this.generateCacheKey("deriveSymmetricKey",e,t,i);if(this.cache.has(r)){let e=this.cacheGet(r);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.deriveSymmetricKey(e,t,i);return this.cacheSet(r,n),n}}revealCounterpartySecret(e){let t=this.generateCacheKey("revealCounterpartySecret",e);if(this.cache.has(t)){let e=this.cacheGet(t);if(void 0===e)throw Error("Cached value is undefined");return e}{let i=this.keyDeriver.revealCounterpartySecret(e);return this.cacheSet(t,i),i}}revealSpecificSecret(e,t,i){let r=this.generateCacheKey("revealSpecificSecret",e,t,i);if(this.cache.has(r)){let e=this.cacheGet(r);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.revealSpecificSecret(e,t,i);return this.cacheSet(r,n),n}}generateCacheKey(e,...t){let i=t.map(e=>this.serializeArgument(e)).join("|");return`${e}|${i}`}serializeArgument(e){return e instanceof ii||e instanceof ih?e.toString():Array.isArray(e)?e.map(e=>this.serializeArgument(e)).join(","):"object"==typeof e&&null!==e?JSON.stringify(e):String(e)}cacheGet(e){let t=this.cache.get(e);return this.cache.delete(e),void 0!==t&&this.cache.set(e,t),t}cacheSet(e,t){if(this.cache.size>=this.maxCacheSize){let e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(e,t)}}class rG{keyDeriver;constructor(e){"string"!=typeof e.identityKey&&(e=new rj(e)),this.keyDeriver=e}async getPublicKey(e){if(e.identityKey){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==e.protocolID||null==e.keyID||""===e.keyID)throw Error("protocolID and keyID are required if identityKey is false or undefined.");return{publicKey:(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf).toString()}}async revealCounterpartyKeyLinkage(e){let{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let i=this.keyDeriver.revealCounterpartySecret(e.counterparty),r=new iL().generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),ii.fromString(e.counterparty),t0.fromDER(i)),n=[...r.R.encode(!0),...r.SPrime.encode(!0),...r.z.toArray()],s=new Date().toISOString(),{ciphertext:a}=await this.encrypt({plaintext:i,protocolID:[2,"counterparty linkage revelation"],keyID:s,counterparty:e.verifier}),{ciphertext:o}=await this.encrypt({plaintext:n,protocolID:[2,"counterparty linkage revelation"],keyID:s,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,revelationTime:s,encryptedLinkage:a,encryptedLinkageProof:o}}async revealSpecificKeyLinkage(e){let{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let i=this.keyDeriver.revealSpecificSecret(e.counterparty,e.protocolID,e.keyID),{ciphertext:r}=await this.encrypt({plaintext:i,protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier}),{ciphertext:n}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,protocolID:e.protocolID,keyID:e.keyID,encryptedLinkage:r,encryptedLinkageProof:n,proofType:0}}async encrypt(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{ciphertext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").encrypt(e.plaintext)}}async decrypt(e,t){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{plaintext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").decrypt(e.ciphertext)}}async createHmac(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{hmac:eE(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data)}}async verifyHmac(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let t=eE(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data),i=e.hmac,r=tU(tm(t),tm(i));if(!r){let e=Error("HMAC is not valid");throw e.code="ERR_INVALID_HMAC",e}return{valid:r}}async createSignature(e){if(null==e.hashToDirectlySign&&null==e.data)throw Error("args.data or args.hashToDirectlySign must be valid");let t=e.hashToDirectlySign??ev(e.data??[]),i=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePrivateKey(e.protocolID,e.keyID,e.counterparty??"anyone");return{signature:ie(new A(t),i,!0).toDER()}}async verifySignature(e){if(null==e.hashToDirectlyVerify&&null==e.data)throw Error("args.data or args.hashToDirectlyVerify must be valid");let t=e.hashToDirectlyVerify??ev(e.data??[]),i=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf),r=it(new A(t),t2.fromDER(e.signature),i);if(!r){let e=Error("Signature is not valid");throw e.code="ERR_INVALID_SIGNATURE",e}return{valid:r}}}let rX=rG;class rY{CWI;constructor(){if("object"!=typeof window)throw TypeError("The window.CWI substrate requires a global window object.");if("object"!=typeof window.CWI)throw TypeError("The window.CWI interface does not appear to be bound to the window object.");this.CWI=window.CWI}async createAction(e,t){return await this.CWI.createAction(e,t)}async signAction(e,t){return await this.CWI.signAction(e,t)}async abortAction(e,t){return await this.CWI.abortAction(e,t)}async listActions(e,t){return await this.CWI.listActions(e,t)}async internalizeAction(e,t){return await this.CWI.internalizeAction(e,t)}async listOutputs(e,t){return await this.CWI.listOutputs(e,t)}async relinquishOutput(e,t){return await this.CWI.relinquishOutput(e,t)}async getPublicKey(e,t){return await this.CWI.getPublicKey(e,t)}async revealCounterpartyKeyLinkage(e,t){return await this.CWI.revealCounterpartyKeyLinkage(e,t)}async revealSpecificKeyLinkage(e,t){return await this.CWI.revealSpecificKeyLinkage(e,t)}async encrypt(e,t){return await this.CWI.encrypt(e,t)}async decrypt(e,t){return await this.CWI.decrypt(e,t)}async createHmac(e,t){return await this.CWI.createHmac(e,t)}async verifyHmac(e,t){return await this.CWI.verifyHmac(e,t)}async createSignature(e,t){return await this.CWI.createSignature(e,t)}async verifySignature(e,t){return await this.CWI.verifySignature(e,t)}async acquireCertificate(e,t){return await this.CWI.acquireCertificate(e,t)}async listCertificates(e,t){return await this.CWI.listCertificates(e,t)}async proveCertificate(e,t){return await this.CWI.proveCertificate(e,t)}async relinquishCertificate(e,t){return await this.CWI.relinquishCertificate(e,t)}async discoverByIdentityKey(e,t){return await this.CWI.discoverByIdentityKey(e,t)}async discoverByAttributes(e,t){return await this.CWI.discoverByAttributes(e,t)}async isAuthenticated(e,t){return await this.CWI.isAuthenticated(e,t)}async waitForAuthentication(e,t){return await this.CWI.waitForAuthentication(e,t)}async getHeight(e,t){return await this.CWI.getHeight(e,t)}async getHeaderForHeight(e,t){return await this.CWI.getHeaderForHeight(e,t)}async getNetwork(e,t){return await this.CWI.getNetwork(e,t)}async getVersion(e,t){return await this.CWI.getVersion(e,t)}}class rJ extends Error{code;isError=!0;constructor(e,t=1,i){super(e),this.code=t,this.name=this.constructor.name,null!=i&&""!==i?this.stack=i:Error.captureStackTrace(this,this.constructor)}static unknownToJson(e){let t;return!0===e.isError&&String(e.name).startsWith("WERR_")?"WERR_REVIEW_ACTIONS"===(t={name:e.name,message:e.message,isError:!0}).name?(t.reviewActionResults=e.reviewActionResults,t.sendWithResults=e.sendWithResults,t.txid=e.txid,t.tx=e.tx,t.noSendChange=e.noSendChange,t.code=5):"WERR_INVALID_PARAMETER"===t.name?(t.parameter=e.parameter,t.code=6):"WERR_INSUFFICIENT_FUNDS"===t.name&&(t.totalSatoshisNeeded=e.totalSatoshisNeeded,t.moreSatoshisNeeded=e.moreSatoshisNeeded,t.code=7):t=e instanceof Error?{name:e.constructor.name,message:e.message,isError:!0}:{name:"WERR_UNKNOWN",message:String(e),isError:!0},JSON.stringify(t)}}(o=d||(d={}))[o.unknownError=1]="unknownError",o[o.unsupportedAction=2]="unsupportedAction",o[o.invalidHmac=3]="invalidHmac",o[o.invalidSignature=4]="invalidSignature",o[o.reviewActions=5]="reviewActions",o[o.invalidParameter=6]="invalidParameter",o[o.insufficientFunds=7]="insufficientFunds";let rZ=rJ;class rQ{async createAction(e){return await this.invoke("createAction",e)}async signAction(e){return await this.invoke("signAction",e)}async abortAction(e){return await this.invoke("abortAction",e)}async listActions(e){return await this.invoke("listActions",e)}async internalizeAction(e){return await this.invoke("internalizeAction",e)}async listOutputs(e){return await this.invoke("listOutputs",e)}async relinquishOutput(e){return await this.invoke("relinquishOutput",e)}async getPublicKey(e){return await this.invoke("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.invoke("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.invoke("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.invoke("encrypt",e)}async decrypt(e){return await this.invoke("decrypt",e)}async createHmac(e){return await this.invoke("createHmac",e)}async verifyHmac(e){return await this.invoke("verifyHmac",e)}async createSignature(e){return await this.invoke("createSignature",e)}async verifySignature(e){return await this.invoke("verifySignature",e)}async acquireCertificate(e){return await this.invoke("acquireCertificate",e)}async listCertificates(e){return await this.invoke("listCertificates",e)}async proveCertificate(e){return await this.invoke("proveCertificate",e)}async relinquishCertificate(e){return await this.invoke("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.invoke("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.invoke("discoverByAttributes",e)}async isAuthenticated(e){return await this.invoke("isAuthenticated",e)}async waitForAuthentication(e){return await this.invoke("waitForAuthentication",e)}async getHeight(e){return await this.invoke("getHeight",e)}async getHeaderForHeight(e){return await this.invoke("getHeaderForHeight",e)}async getNetwork(e){return await this.invoke("getNetwork",e)}async getVersion(e){return await this.invoke("getVersion",e)}}class r0 extends rQ{domain;constructor(e="*"){if(super(),"object"!=typeof globalThis.window)throw TypeError("The XDM substrate requires a global window object.");if("function"!=typeof globalThis.window.postMessage)throw TypeError("The window object does not seem to support postMessage calls.");this.domain=e}async invoke(e,t){return await new Promise((i,r)=>{let n=tS(ia(12)),s=e=>{"CWI"===e.data.type&&e.isTrusted&&e.data.id===n&&!0!==e.data.isInvocation&&("function"==typeof window.removeEventListener&&window.removeEventListener("message",s),"error"===e.data.status?r(new rJ(e.data.description,e.data.code)):i(e.data.result))};window.addEventListener("message",s),window.parent.postMessage({type:"CWI",isInvocation:!0,id:n,call:e,args:t},this.domain)})}}class r1{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(e,t,i,r,n,s,a){this.type=e,this.serialNumber=t,this.subject=i,this.certifier=r,this.revocationOutpoint=n,this.fields=s,this.signature=a}toBinary(e=!0){let t=new tP,i=tm(this.type,"base64");t.write(i);let r=tm(this.serialNumber,"base64");t.write(r);let n=tm(this.subject,"hex");t.write(n);let s=tm(this.certifier,"hex");t.write(s);let[a,o]=this.revocationOutpoint.split("."),l=tm(a,"hex");t.write(l),t.writeVarIntNum(Number(o));let c=Object.keys(this.fields).sort((e,t)=>e.localeCompare(t));for(let e of(t.writeVarIntNum(c.length),c)){let i=this.fields[e],r=tm(e,"utf8");t.writeVarIntNum(r.length),t.write(r);let n=tm(i,"utf8");t.writeVarIntNum(n.length),t.write(n)}if(e&&(this.signature??"").length>0){let e=tm(this.signature,"hex");t.write(e)}return t.toArray()}static fromBinary(e){let t,i=new tN(e),r=tS(i.read(32)),n=tS(i.read(32)),s=tg(i.read(33)),a=tg(i.read(33)),o=tg(i.read(32)),l=i.readVarIntNum(),c=`${o}.${l}`,h=i.readVarIntNum(),d={};for(let e=0;e<h;e++){let e=i.readVarIntNum(),t=tI(i.read(e)),r=i.readVarIntNum(),n=tI(i.read(r));d[t]=n}if(!i.eof()){let e=i.read();t=t2.fromDER(e).toString("hex")}return new r1(r,n,s,a,c,d,t)}async verify(){let e=new rX("anyone"),t=this.toBinary(!1),i=this.signature??"",{valid:r}=await e.verifySignature({signature:tm(i,"hex"),data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`,counterparty:this.certifier});return r}async sign(e){if(null!=this.signature&&this.signature.length>0)throw Error(`Certificate has already been signed! Signature present: ${this.signature}`);this.certifier=(await e.getPublicKey({identityKey:!0})).publicKey;let t=this.toBinary(!1),{signature:i}=await e.createSignature({data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`});this.signature=tg(i)}static getCertificateFieldEncryptionDetails(e,t){return{protocolID:[2,"certificate field encryption"],keyID:t?`${t} ${e}`:e}}static fromObject(e){return new r1(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature)}}(l=u||(u={}))[l.createAction=1]="createAction",l[l.signAction=2]="signAction",l[l.abortAction=3]="abortAction",l[l.listActions=4]="listActions",l[l.internalizeAction=5]="internalizeAction",l[l.listOutputs=6]="listOutputs",l[l.relinquishOutput=7]="relinquishOutput",l[l.getPublicKey=8]="getPublicKey",l[l.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",l[l.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",l[l.encrypt=11]="encrypt",l[l.decrypt=12]="decrypt",l[l.createHmac=13]="createHmac",l[l.verifyHmac=14]="verifyHmac",l[l.createSignature=15]="createSignature",l[l.verifySignature=16]="verifySignature",l[l.acquireCertificate=17]="acquireCertificate",l[l.listCertificates=18]="listCertificates",l[l.proveCertificate=19]="proveCertificate",l[l.relinquishCertificate=20]="relinquishCertificate",l[l.discoverByIdentityKey=21]="discoverByIdentityKey",l[l.discoverByAttributes=22]="discoverByAttributes",l[l.isAuthenticated=23]="isAuthenticated",l[l.waitForAuthentication=24]="waitForAuthentication",l[l.getHeight=25]="getHeight",l[l.getHeaderForHeight=26]="getHeaderForHeight",l[l.getNetwork=27]="getNetwork",l[l.getVersion=28]="getVersion";let r2=u,r8={1:"completed",2:"unprocessed",3:"sending",4:"unproven",5:"unsigned",6:"nosend",7:"nonfinal",8:"failed"};class r3{wire;constructor(e){this.wire=e}async transmit(e,t="",i=[]){let r=new tP;r.writeUInt8(r2[e]);let n=tm(t,"utf8");r.writeUInt8(n.length),r.write(n),i.length>0&&r.write(i);let s=r.toArray(),a=new tN(await this.wire.transmitToWallet(s)),o=a.readUInt8();if(0===o)return a.read();{let e=a.readVarIntNum(),t=tI(a.read(e)),i=a.readVarIntNum();throw new rJ(t,o,tI(a.read(i)))}}async createAction(e,t){let i=new tP;if(this.writeUTF8(i,e.description),null==e.inputBEEF?i.writeVarIntNum(-1):(i.writeVarIntNum(e.inputBEEF.length),i.write(e.inputBEEF)),null==e.inputs)i.writeVarIntNum(-1);else for(let t of(i.writeVarIntNum(e.inputs.length),e.inputs))this.serializeCreateActionInput(i,t);if(null==e.outputs)i.writeVarIntNum(-1);else for(let t of(i.writeVarIntNum(e.outputs.length),e.outputs))this.serializeCreateActionOutput(i,t);this.writeOptionalVarInt(i,e.lockTime),this.writeOptionalVarInt(i,e.version),this.writeUTF8Array(i,e.labels),this.serializeCreateActionOptions(i,e.options);let r=await this.transmit("createAction",t,i.toArray());return this.parseCreateActionResult(r)}parseCreateActionResult(e){let t=new tN(e),i={};1===t.readInt8()&&(i.txid=tg(t.read(32))),1===t.readInt8()&&(i.tx=t.read(t.readVarIntNum()));let r=t.readVarIntNum();if(r>=0){i.noSendChange=[];for(let e=0;e<r;e++)i.noSendChange.push(this.readOutpoint(t))}let n=this.readSendWithResults(t);return null!=n&&(i.sendWithResults=n),1===t.readInt8()&&(i.signableTransaction={tx:t.read(t.readVarIntNum()),reference:tS(t.read(t.readVarIntNum()))}),i}async signAction(e,t){let i=new tP,r=Object.keys(e.spends);for(let t of(i.writeVarIntNum(r.length),r)){i.writeVarIntNum(Number(t));let r=e.spends[Number(t)],n=tm(r.unlockingScript,"hex");i.writeVarIntNum(n.length),i.write(n),this.writeOptionalVarInt(i,r.sequenceNumber)}let n=tm(e.reference,"base64");i.writeVarIntNum(n.length),i.write(n),this.serializeSignActionOptions(i,e.options);let s=new tN(await this.transmit("signAction",t,i.toArray())),a={};1===s.readInt8()&&(a.txid=tg(s.read(32))),1===s.readInt8()&&(a.tx=s.read(s.readVarIntNum()));let o=this.readSendWithResults(s);return null!=o&&(a.sendWithResults=o),a}async abortAction(e,t){return await this.transmit("abortAction",t,tm(e.reference,"base64")),{aborted:!0}}async listActions(e,t){let i=new tP;for(let t of(i.writeVarIntNum(e.labels.length),e.labels))this.writeUTF8(i,t);for(let t of("any"===e.labelQueryMode?i.writeInt8(1):"all"===e.labelQueryMode?i.writeInt8(2):i.writeInt8(-1),[e.includeLabels,e.includeInputs,e.includeInputSourceLockingScripts,e.includeInputUnlockingScripts,e.includeOutputs,e.includeOutputLockingScripts]))this.writeOptionalBool(i,t);this.writeOptionalVarInt(i,e.limit),this.writeOptionalVarInt(i,e.offset),this.writeOptionalBool(i,e.seekPermission);let r=new tN(await this.transmit("listActions",t,i.toArray())),n=r.readVarIntNum(),s=[];for(let e=0;e<n;e++)s.push(this.parseAction(r));return{totalActions:n,actions:s}}parseActionStatus(e){let t=r8[e];if(null==t)throw Error(`Unknown status code: ${e}`);return t}parseAction(e){let t=tg(e.read(32)),i=e.readVarIntNum(),r=this.parseActionStatus(e.readInt8()),n={txid:t,satoshis:i,status:r,isOutgoing:1===e.readInt8(),description:tI(e.read(e.readVarIntNum())),version:0,lockTime:0},s=e.readVarIntNum();if(s>=0){n.labels=[];for(let t=0;t<s;t++)n.labels.push(tI(e.read(e.readVarIntNum())))}n.version=e.readVarIntNum(),n.lockTime=e.readVarIntNum();let a=e.readVarIntNum();if(a>=0){n.inputs=[];for(let t=0;t<a;t++)n.inputs.push(this.parseActionInput(e))}let o=e.readVarIntNum();if(o>=0){n.outputs=[];for(let t=0;t<o;t++)n.outputs.push(this.parseActionOutput(e))}return n}parseActionInput(e){let t=this.readOutpoint(e),i=e.readVarIntNum(),r=e.readVarIntNum(),n=r>=0?tg(e.read(r)):void 0,s=e.readVarIntNum(),a=s>=0?tg(e.read(s)):void 0;return{sourceOutpoint:t,sourceSatoshis:i,sourceLockingScript:n,unlockingScript:a,inputDescription:tI(e.read(e.readVarIntNum())),sequenceNumber:e.readVarIntNum()}}parseActionOutput(e){let t=e.readVarIntNum(),i=e.readVarIntNum(),r=e.readVarIntNum(),n=r>=0?tg(e.read(r)):void 0,s=1===e.readInt8(),a=tI(e.read(e.readVarIntNum())),o=e.readVarIntNum(),l=o>=0?tI(e.read(o)):void 0,c=e.readVarIntNum(),h=[];if(c>=0)for(let t=0;t<c;t++)h.push(tI(e.read(e.readVarIntNum())));let d=e.readVarIntNum();return{outputIndex:t,satoshis:i,lockingScript:n,spendable:s,outputDescription:a,basket:l,tags:h,customInstructions:d>=0?tI(e.read(d)):void 0}}async internalizeAction(e,t){let i=new tP;for(let t of(i.writeVarIntNum(e.tx.length),i.write(e.tx),i.writeVarIntNum(e.outputs.length),e.outputs))this.serializeInternalizeOutput(i,t);this.writeUTF8Array(i,"object"==typeof e.labels?e.labels:void 0);let r=tm(e.description);return i.writeVarIntNum(r.length),i.write(r),this.writeOptionalBool(i,e.seekPermission),await this.transmit("internalizeAction",t,i.toArray()),{accepted:!0}}serializeInternalizeOutput(e,t){if(e.writeVarIntNum(t.outputIndex),"wallet payment"===t.protocol){if(null==t.paymentRemittance)throw Error("Payment remittance is required for wallet payment");e.writeUInt8(1),e.write(tm(t.paymentRemittance.senderIdentityKey,"hex"));let i=tm(t.paymentRemittance.derivationPrefix,"base64");e.writeVarIntNum(i.length),e.write(i);let r=tm(t.paymentRemittance.derivationSuffix,"base64");e.writeVarIntNum(r.length),e.write(r)}else{e.writeUInt8(2);let i=tm(t.insertionRemittance?.basket,"utf8");e.writeVarIntNum(i.length),e.write(i),this.writeOptionalUTF8(e,t.insertionRemittance?.customInstructions);let r=t.insertionRemittance?.tags;if("object"==typeof r)for(let t of(e.writeVarIntNum(r.length),r)){let i=tm(t,"utf8");e.writeVarIntNum(i.length),e.write(i)}else e.writeVarIntNum(0)}}async listOutputs(e,t){let i=new tP;if(this.writeUTF8(i,e.basket),"object"==typeof e.tags)for(let t of(i.writeVarIntNum(e.tags.length),e.tags))this.writeUTF8(i,t);else i.writeVarIntNum(0);"all"===e.tagQueryMode?i.writeInt8(1):"any"===e.tagQueryMode?i.writeInt8(2):i.writeInt8(-1),"locking scripts"===e.include?i.writeInt8(1):"entire transactions"===e.include?i.writeInt8(2):i.writeInt8(-1),this.writeOptionalBool(i,e.includeCustomInstructions),this.writeOptionalBool(i,e.includeTags),this.writeOptionalBool(i,e.includeLabels),this.writeOptionalVarInt(i,e.limit),this.writeOptionalVarInt(i,e.offset),this.writeOptionalBool(i,e.seekPermission);let r=new tN(await this.transmit("listOutputs",t,i.toArray())),n=r.readVarIntNum(),s=r.readVarIntNum(),a=s>=0?r.read(s):void 0,o=[];for(let e=0;e<n;e++)o.push(this.parseListOutputEntry(r));return{totalOutputs:n,BEEF:a,outputs:o}}parseListOutputEntry(e){let t={spendable:!0,outpoint:this.readOutpoint(e),satoshis:e.readVarIntNum()},i=e.readVarIntNum();i>=0&&(t.lockingScript=tg(e.read(i)));let r=e.readVarIntNum();r>=0&&(t.customInstructions=tI(e.read(r)));let n=e.readVarIntNum();if(-1!==n){let i=[];for(let t=0;t<n;t++)i.push(tI(e.read(e.readVarIntNum())));t.tags=i}let s=e.readVarIntNum();if(-1!==s){let i=[];for(let t=0;t<s;t++)i.push(tI(e.read(e.readVarIntNum())));t.labels=i}return t}async relinquishOutput(e,t){let i=new tP,r=tm(e.basket,"utf8");return i.writeVarIntNum(r.length),i.write(r),i.write(this.encodeOutpoint(e.output)),await this.transmit("relinquishOutput",t,i.toArray()),{relinquished:!0}}encodeOutpoint(e){let t=new tP,[i,r]=e.split(".");return t.write(tm(i,"hex")),t.writeVarIntNum(Number(r)),t.toArray()}readOutpoint(e){let t=tg(e.read(32)),i=e.readVarIntNum();return`${t}.${i}`}async getPublicKey(e,t){let i=new tP;return i.writeUInt8(+!!e.identityKey),e.identityKey?i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)):(e.protocolID??=[h.Silent,"default"],e.keyID??="",i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?i.writeInt8(+!!e.forSelf):i.writeInt8(-1)),this.writeOptionalBool(i,e.seekPermission),{publicKey:tg(await this.transmit("getPublicKey",t,i.toArray()))}}async revealCounterpartyKeyLinkage(e,t){let i=new tP;i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),i.write(tm(e.counterparty,"hex")),i.write(tm(e.verifier,"hex"));let r=new tN(await this.transmit("revealCounterpartyKeyLinkage",t,i.toArray())),n=tg(r.read(33)),s=tg(r.read(33)),a=tg(r.read(33)),o=r.readVarIntNum(),l=tI(r.read(o)),c=r.readVarIntNum(),h=r.read(c),d=r.readVarIntNum();return{prover:n,verifier:s,counterparty:a,revelationTime:l,encryptedLinkage:h,encryptedLinkageProof:r.read(d)}}async revealSpecificKeyLinkage(e,t){let i=new tP;i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.write(tm(e.verifier,"hex"));let r=new tN(await this.transmit("revealSpecificKeyLinkage",t,i.toArray())),n=tg(r.read(33)),s=tg(r.read(33)),a=tg(r.read(33)),o=r.readUInt8(),l=r.readVarIntNum(),c=tI(r.read(l)),h=r.readVarIntNum(),d=tI(r.read(h)),u=r.readVarIntNum(),f=r.read(u),p=r.readVarIntNum();return{prover:n,verifier:s,counterparty:a,protocolID:[o,c],keyID:d,encryptedLinkage:f,encryptedLinkageProof:r.read(p),proofType:r.readUInt8()}}async encrypt(e,t){let i=new tP;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.writeVarIntNum(e.plaintext.length),i.write(e.plaintext),this.writeOptionalBool(i,e.seekPermission),{ciphertext:await this.transmit("encrypt",t,i.toArray())}}async decrypt(e,t){let i=new tP;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.writeVarIntNum(e.ciphertext.length),i.write(e.ciphertext),this.writeOptionalBool(i,e.seekPermission),{plaintext:await this.transmit("decrypt",t,i.toArray())}}async createHmac(e,t){let i=new tP;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.writeVarIntNum(e.data.length),i.write(e.data),this.writeOptionalBool(i,e.seekPermission),{hmac:await this.transmit("createHmac",t,i.toArray())}}async verifyHmac(e,t){let i=new tP;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.write(e.hmac),i.writeVarIntNum(e.data.length),i.write(e.data),this.writeOptionalBool(i,e.seekPermission),await this.transmit("verifyHmac",t,i.toArray()),{valid:!0}}async createSignature(e,t){let i=new tP;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"object"==typeof e.data?(i.writeUInt8(1),i.writeVarIntNum(e.data.length),i.write(e.data)):(e.hashToDirectlySign??=[],i.writeUInt8(2),i.write(e.hashToDirectlySign)),this.writeOptionalBool(i,e.seekPermission),{signature:await this.transmit("createSignature",t,i.toArray())}}async verifySignature(e,t){let i=new tP;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?i.writeInt8(+!!e.forSelf):i.writeInt8(-1),i.writeVarIntNum(e.signature.length),i.write(e.signature),"object"==typeof e.data?(i.writeUInt8(1),i.writeVarIntNum(e.data.length),i.write(e.data)):(i.writeUInt8(2),i.write(e.hashToDirectlyVerify??[])),this.writeOptionalBool(i,e.seekPermission),await this.transmit("verifySignature",t,i.toArray()),{valid:!0}}writeOptionalBool(e,t){"boolean"==typeof t?e.writeInt8(+!!t):e.writeInt8(-1)}writeOptionalVarInt(e,t){"number"==typeof t?e.writeVarIntNum(t):e.writeVarIntNum(-1)}writeUTF8(e,t){let i=tm(t??"","utf8");e.writeVarIntNum(i.length),e.write(i)}writeOptionalUTF8(e,t){if(null!=t&&""!==t){let i=tm(t,"utf8");e.writeVarIntNum(i.length),e.write(i)}else e.writeVarIntNum(-1)}writeUTF8Array(e,t){if(null==t)e.writeVarIntNum(-1);else for(let i of(e.writeVarIntNum(t.length),t)){let t=tm(i,"utf8");e.writeVarIntNum(t.length),e.write(t)}}writeTxidArray(e,t){if(null==t)e.writeVarIntNum(-1);else for(let i of(e.writeVarIntNum(t.length),t))e.write(tm(i,"hex"))}readSendWithResults(e){let t=e.readVarIntNum();if(t<0)return;let i=[];for(let r=0;r<t;r++){let t=tg(e.read(32)),r=e.readInt8(),n=2===r?"sending":3===r?"failed":"unproven";i.push({txid:t,status:n})}return i}serializeCreateActionInput(e,t){if(e.write(this.encodeOutpoint(t.outpoint)),null!=t.unlockingScript&&""!==t.unlockingScript){let i=tm(t.unlockingScript,"hex");e.writeVarIntNum(i.length),e.write(i)}else e.writeVarIntNum(-1),e.writeVarIntNum(t.unlockingScriptLength??0);this.writeUTF8(e,t.inputDescription),this.writeOptionalVarInt(e,t.sequenceNumber)}serializeCreateActionOutput(e,t){let i=tm(t.lockingScript,"hex");e.writeVarIntNum(i.length),e.write(i),e.writeVarIntNum(t.satoshis),this.writeUTF8(e,t.outputDescription),this.writeOptionalUTF8(e,t.basket),this.writeOptionalUTF8(e,t.customInstructions),this.writeUTF8Array(e,t.tags)}serializeCreateActionOptions(e,t){if(null==t)return void e.writeInt8(0);if(e.writeInt8(1),this.writeOptionalBool(e,t.signAndProcess),this.writeOptionalBool(e,t.acceptDelayedBroadcast),e.writeInt8("known"===t.trustSelf?1:-1),this.writeTxidArray(e,t.knownTxids),this.writeOptionalBool(e,t.returnTXIDOnly),this.writeOptionalBool(e,t.noSend),null==t.noSendChange)e.writeVarIntNum(-1);else for(let i of(e.writeVarIntNum(t.noSendChange.length),t.noSendChange))e.write(this.encodeOutpoint(i));this.writeTxidArray(e,t.sendWith),this.writeOptionalBool(e,t.randomizeOutputs)}serializeSignActionOptions(e,t){null==t?e.writeInt8(0):(e.writeInt8(1),this.writeOptionalBool(e,t.acceptDelayedBroadcast),this.writeOptionalBool(e,t.returnTXIDOnly),this.writeOptionalBool(e,t.noSend),this.writeTxidArray(e,t.sendWith))}encodeKeyRelatedParams(e,t,i,r,n){let s=new tP;s.writeUInt8(e[0]);let a=tm(e[1],"utf8");s.writeVarIntNum(a.length),s.write(a);let o=tm(t,"utf8");return s.writeVarIntNum(o.length),s.write(o),"string"!=typeof i?s.writeUInt8(0):"self"===i?s.writeUInt8(11):"anyone"===i?s.writeUInt8(12):s.write(tm(i,"hex")),s.write(this.encodePrivilegedParams(r,n)),s.toArray()}async acquireCertificate(e,t){let i=new tP;i.write(tm(e.type,"base64")),i.write(tm(e.certifier,"hex"));let r=Object.entries(e.fields);for(let[e,t]of(i.writeVarIntNum(r.length),r)){let r=tm(e,"utf8"),n=tm(t,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(n.length),i.write(n)}if(i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),i.writeUInt8("direct"===e.acquisitionProtocol?1:2),"direct"===e.acquisitionProtocol){i.write(tm(e.serialNumber,"base64")),i.write(this.encodeOutpoint(e.revocationOutpoint??""));let t=tm(e.signature,"hex");i.writeVarIntNum(t.length),i.write(t);let r="certifier"===e.keyringRevealer?[11]:tm(e.keyringRevealer,"hex");i.write(r);let n=Object.keys(e.keyringForSubject??{});for(let t of(i.writeVarIntNum(n.length),n)){let r=tm(t,"utf8");i.writeVarIntNum(r.length),i.write(r);let n=tm(e.keyringForSubject?.[t],"base64");i.writeVarIntNum(n.length),i.write(n)}}else{let t=tm(e.certifierUrl,"utf8");i.writeVarIntNum(t.length),i.write(t)}let n=await this.transmit("acquireCertificate",t,i.toArray()),s=r1.fromBinary(n);return{...s,signature:s.signature}}encodePrivilegedParams(e,t){let i=new tP;if("boolean"==typeof e?i.writeInt8(+!!e):i.writeInt8(-1),"string"==typeof t){let e=tm(t,"utf8");i.writeInt8(e.length),i.write(e)}else i.writeInt8(-1);return i.toArray()}async listCertificates(e,t){let i=new tP;for(let t of(i.writeVarIntNum(e.certifiers.length),e.certifiers))i.write(tm(t,"hex"));for(let t of(i.writeVarIntNum(e.types.length),e.types))i.write(tm(t,"base64"));"number"==typeof e.limit?i.writeVarIntNum(e.limit):i.writeVarIntNum(-1),"number"==typeof e.offset?i.writeVarIntNum(e.offset):i.writeVarIntNum(-1),i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let r=new tN(await this.transmit("listCertificates",t,i.toArray())),n=r.readVarIntNum(),s=[];for(let e=0;e<n;e++){let e,t=r.readVarIntNum(),i=r.read(t),n=r1.fromBinary(i),a={};if(1===r.readInt8()){let e=r.readVarIntNum();for(let t=0;t<e;t++){let e=r.readVarIntNum(),t=tI(r.read(e)),i=r.readVarIntNum();a[t]=tS(r.read(i))}}let o=r.readVarIntNum();o>0&&(e=tI(r.read(o))),s.push({...n,signature:n.signature,keyring:a,verifier:e})}return{totalCertificates:n,certificates:s}}async proveCertificate(e,t){let i=new tP,r=tm(e.certificate.type,"base64");i.write(r);let n=tm(e.certificate.subject,"hex");i.write(n);let s=tm(e.certificate.serialNumber,"base64");i.write(s);let a=tm(e.certificate.certifier,"hex");i.write(a);let o=this.encodeOutpoint(e.certificate.revocationOutpoint??"");i.write(o);let l=tm(e.certificate.signature,"hex");i.writeVarIntNum(l.length),i.write(l);let c=Object.entries(e.certificate.fields??{});for(let[e,t]of(i.writeVarIntNum(c.length),c)){let r=tm(e,"utf8"),n=tm(t,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(n.length),i.write(n)}for(let t of(i.writeVarIntNum(e.fieldsToReveal.length),e.fieldsToReveal)){let e=tm(t,"utf8");i.writeVarIntNum(e.length),i.write(e)}i.write(tm(e.verifier,"hex")),i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let h=new tN(await this.transmit("proveCertificate",t,i.toArray())),d=h.readVarIntNum(),u={};for(let e=0;e<d;e++){let e=h.readVarIntNum(),t=tI(h.read(e)),i=h.readVarIntNum();u[t]=tS(h.read(i))}return{keyringForVerifier:u}}async relinquishCertificate(e,t){let i=new tP,r=tm(e.type,"base64");i.write(r);let n=tm(e.serialNumber,"base64");i.write(n);let s=tm(e.certifier,"hex");return i.write(s),await this.transmit("relinquishCertificate",t,i.toArray()),{relinquished:!0}}parseDiscoveryResult(e){let t=new tN(e),i=t.readVarIntNum(),r=[];for(let e=0;e<i;e++){let e=t.readVarIntNum(),i=t.read(e),n=r1.fromBinary(i),s=t.readVarIntNum(),a=tI(t.read(s)),o=t.readVarIntNum(),l=tI(t.read(o)),c=t.readVarIntNum(),h=tI(t.read(c)),d=t.readUInt8(),u={},f=t.readVarIntNum();for(let e=0;e<f;e++){let e=t.readVarIntNum(),i=tI(t.read(e)),r=t.readVarIntNum();u[i]=t.read(r)}let p={},g=t.readVarIntNum();for(let e=0;e<g;e++){let e=t.readVarIntNum(),i=tI(t.read(e)),r=t.readVarIntNum();p[i]=tI(t.read(r))}r.push({...n,signature:n.signature,certifierInfo:{iconUrl:l,name:a,description:h,trust:d},publiclyRevealedKeyring:u,decryptedFields:p})}return{totalCertificates:i,certificates:r}}async discoverByIdentityKey(e,t){let i=new tP;i.write(tm(e.identityKey,"hex")),"number"==typeof e.limit?i.writeVarIntNum(e.limit):i.writeVarIntNum(-1),"number"==typeof e.offset?i.writeVarIntNum(e.offset):i.writeVarIntNum(-1),this.writeOptionalBool(i,e.seekPermission);let r=await this.transmit("discoverByIdentityKey",t,i.toArray());return this.parseDiscoveryResult(r)}async discoverByAttributes(e,t){let i=new tP,r=Object.keys(e.attributes);for(let t of(i.writeVarIntNum(r.length),r))i.writeVarIntNum(t.length),i.write(tm(t,"utf8")),i.writeVarIntNum(e.attributes[t].length),i.write(tm(e.attributes[t],"utf8"));"number"==typeof e.limit?i.writeVarIntNum(e.limit):i.writeVarIntNum(-1),"number"==typeof e.offset?i.writeVarIntNum(e.offset):i.writeVarIntNum(-1),this.writeOptionalBool(i,e.seekPermission);let n=await this.transmit("discoverByAttributes",t,i.toArray());return this.parseDiscoveryResult(n)}async isAuthenticated(e,t){return{authenticated:1===(await this.transmit("isAuthenticated",t))[0]}}async waitForAuthentication(e,t){return await this.transmit("waitForAuthentication",t),{authenticated:!0}}async getHeight(e,t){return{height:new tN(await this.transmit("getHeight",t)).readVarIntNum()}}async getHeaderForHeight(e,t){let i=new tP;return i.writeVarIntNum(e.height),{header:tg(await this.transmit("getHeaderForHeight",t,i.toArray()))}}async getNetwork(e,t){return{network:0===(await this.transmit("getNetwork",t))[0]?"mainnet":"testnet"}}async getVersion(e,t){return{version:tI(await this.transmit("getVersion",t))}}}class r5{baseUrl;httpClient;originator;constructor(e,t="http://localhost:3301",i=fetch){this.baseUrl=t,this.httpClient=i,this.originator=e}async transmitToWallet(e){let t,i=new tN(e),r=i.readUInt8(),n=r2[r];if(void 0===n||""===n)throw Error(`Invalid call code: ${r}`);let s=i.readUInt8();s>0&&(t=tI(i.read(s)));let a=i.read(),o=await fetch(`${this.baseUrl}/${n}`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Origin:t??""},body:new Uint8Array(a)});return Array.from(new Uint8Array(await o.arrayBuffer()))}}class r6 extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(e,t,i,r,n){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=e,this.sendWithResults=t,this.txid=i,this.tx=r,this.noSendChange=n,this.code=5,this.name=this.constructor.name}}let r4=r6;class r9 extends Error{parameter;code;isError=!0;constructor(e,t){super(`The ${e} parameter must be ${t??"valid."}`),this.parameter=e,this.code=6,this.name=this.constructor.name}}let r7=r9,ne=class extends Error{totalSatoshisNeeded;moreSatoshisNeeded;code;isError=!0;constructor(e,t){super(`Insufficient funds in the available inputs to cover the cost of the required outputs and the transaction fee (${t} more satoshis are needed, for a total of ${e}), plus whatever would be required in order to pay the fee to unlock and spend the outputs used to provide the additional satoshis.`),this.totalSatoshisNeeded=e,this.moreSatoshisNeeded=t,this.code=7,this.name=this.constructor.name}};class nt{baseUrl;httpClient;originator;api;constructor(e,t="http://localhost:3321",i=fetch){this.baseUrl=t,this.originator=e,this.httpClient=i;const r=void 0!==globalThis.window&&"u">typeof document&&globalThis.window?.origin!=="file://";this.api=async(e,t)=>{let n=!r&&this.originator?function(e,t="http"){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))try{return new URL(e).origin}catch{}try{return new URL(`${t}://${e}`).origin}catch{throw Error(`Invalid originator value: ${e}`)}}(this.originator,"http"):void 0;if(!r&&void 0===n)throw Error('HTTPWalletJSON: originator is required when using the HTTP substrate in Node.js. Pass an originator (e.g. "example.com") to the constructor.');let s=await i(`${this.baseUrl}/${e}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...n?{Origin:n}:{},...n?{Originator:n}:{}},body:JSON.stringify(t)}),a=await s.json();if(!s.ok){if(400===s.status&&a.isError){let e;switch(a.code){case 5:e=new r6(a.reviewActionResults,a.sendWithResults,a.txid,a.tx,a.noSendChange);break;case 6:(e=new r9(a.parameter)).message=a.message;break;case 7:e=new ne(a.totalSatoshisNeeded,a.moreSatoshisNeeded)}if(e)throw e}throw Error(JSON.stringify({call:e,args:t,message:a.message??`HTTP Client error ${s.status}`}))}return a}}async createAction(e){return await this.api("createAction",e)}async signAction(e){return await this.api("signAction",e)}async abortAction(e){return await this.api("abortAction",e)}async listActions(e){return await this.api("listActions",e)}async internalizeAction(e){return await this.api("internalizeAction",e)}async listOutputs(e){return await this.api("listOutputs",e)}async relinquishOutput(e){return await this.api("relinquishOutput",e)}async getPublicKey(e){return await this.api("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.api("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.api("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.api("encrypt",e)}async decrypt(e){return await this.api("decrypt",e)}async createHmac(e){return await this.api("createHmac",e)}async verifyHmac(e){return await this.api("verifyHmac",e)}async createSignature(e){return await this.api("createSignature",e)}async verifySignature(e){return await this.api("verifySignature",e)}async acquireCertificate(e){return await this.api("acquireCertificate",e)}async listCertificates(e){return await this.api("listCertificates",e)}async proveCertificate(e){return await this.api("proveCertificate",e)}async relinquishCertificate(e){return await this.api("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.api("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.api("discoverByAttributes",e)}async isAuthenticated(e){return await this.api("isAuthenticated",e)}async waitForAuthentication(e){return await this.api("waitForAuthentication",e)}async getHeight(e){return await this.api("getHeight",e)}async getHeaderForHeight(e){return await this.api("getHeaderForHeight",e)}async getNetwork(e){return await this.api("getNetwork",e)}async getVersion(e){return await this.api("getVersion",e)}}class ni extends rQ{domain;constructor(e="*"){if(super(),"object"!=typeof globalThis.window)throw TypeError("The XDM substrate requires a global window object.");if(!globalThis.window.hasOwnProperty("ReactNativeWebView"))throw Error("The window object does not have a ReactNativeWebView property.");if("function"!=typeof globalThis.window.ReactNativeWebView.postMessage)throw TypeError("The window.ReactNativeWebView property does not seem to support postMessage calls.");this.domain=e}async invoke(e,t){return await new Promise((i,r)=>{let n=tS(ia(12)),s=e=>{let t=JSON.parse(e.data);"CWI"===t.type&&t.id===n&&!0!==t.isInvocation&&("function"==typeof globalThis.window.removeEventListener&&globalThis.window.removeEventListener("message",s),"error"===t.status?r(new rJ(t.description,t.code)):i(t.result))};globalThis.window.addEventListener("message",s),globalThis.window.ReactNativeWebView.postMessage(JSON.stringify({type:"CWI",isInvocation:!0,id:n,call:e,args:t}))})}}function nr(e){let[t,i]=e.split(".");return{txid:t,vout:Number(i)}}function nn(e){return e??!1}function ns(e,t,i,r){if(void 0!==e)return nh(e,t,i,r)}function na(e,t,i){if(void 0===e||!Number.isInteger(e)||e<0||e>21e14)throw new r7(t,"a valid number of satoshis");if(void 0!==i&&e<i)throw new r7(t,`at least ${i} satoshis.`);return e}function no(e,t,i,r){if(void 0!==e)return nl(e,t,void 0,i,r)}function nl(e,t,i,r,n){if(void 0===e){if(void 0!==i)return i;throw new r7(t,"a valid integer")}if(!Number.isInteger(e))throw new r7(t,"an integer");if(e=Number(e),void 0!==r&&e<r)throw new r7(t,`at least ${r} length.`);if(void 0!==n&&e>n)throw new r7(t,`no more than ${n} length.`);return e}function nc(e,t){return nl(e,t,0,0)}function nh(e,t,i,r){let n=tm(e,"utf8").length;if(void 0!==i&&n<i)throw new r7(t,`at least ${i} length.`);if(void 0!==r&&n>r)throw new r7(t,`no more than ${r} length.`);return e}function nd(e){return np(e,"basket",1,300)}function nu(e){return np(e,"label",1,300)}function nf(e){return np(e,"tag",1,300)}function np(e,t,i,r){let n=tm(e=e.trim().toLowerCase(),"utf8").length;if(void 0!==i&&n<i)throw new r7(t,`at least ${i} length.`);if(void 0!==r&&n>r)throw new r7(t,`no more than ${r} length.`);return e}function ng(e,t,i,r){if(void 0!==e)return ny(e,t,i,r)}function ny(e,t,i,r){if(0===(e=e.trim()).length)throw new r7(t,"valid base64 string");let n=0;for(let i=0;i<e.length;i++){let r=e.codePointAt(i)??0;if((!(r>=65)||!(r<=90))&&(!(r>=97)||!(r<=122))&&(!(r>=48)||!(r<=57))&&43!==r&&47!==r){if(61===r){if(i<e.length-2)throw new r7(t,"valid base64 string");n++;continue}throw new r7(t,"valid base64 string")}}if(n>2||n>0&&e.length%4!=0)throw new r7(t,"valid base64 string");let s=e.length%4;if(0!==s&&s!==4-n)throw new r7(t,"valid base64 string");let a=Math.floor(3*(e.length-n)/4);if(void 0!==i&&a<i)throw new r7(t,`at least ${i} bytes`);if(void 0!==r&&a>r)throw new r7(t,`no more than ${r} bytes`);return e}function nm(e,t,i,r){if(void 0!==e)return nb(e,t,i,r)}function nb(e,t,i,r){if((e=e.trim().toLowerCase()).length%2==1)throw new r7(t,`even length, not ${e.length}.`);if(!/^[0-9A-Fa-f]+$/.test(e))throw new r7(t,"hexadecimal string.");if(void 0!==i&&e.length<i)throw new r7(t,`at least ${i} length.`);if(void 0!==r&&e.length>r)throw new r7(t,`no more than ${r} length.`);return e}function nw(e){return(e=e.trim()).length%2!=1&&!!/^[0-9A-Fa-f]+$/.test(e)}function nv(e){if(void 0===e.unlockingScript&&void 0===e.unlockingScriptLength)throw new r7("unlockingScript, unlockingScriptLength","at least one valid value.");let t=nm(e.unlockingScript,"unlockingScript"),i=e.unlockingScriptLength??(null==t?0:t.length/2);if(t&&i!==t.length/2)throw new r7("unlockingScriptLength","length unlockingScript if both valid.");return{outpoint:nr(e.outpoint),inputDescription:nh(e.inputDescription,"inputDescription",5,2e3),unlockingScript:t,unlockingScriptLength:i,sequenceNumber:e.sequenceNumber??0xffffffff}}function nI(e){return{lockingScript:nb(e.lockingScript,"lockingScript"),satoshis:na(e.satoshis,"satoshis"),outputDescription:nh(e.outputDescription,"outputDescription",5,2e3),basket:function(e){if(void 0!==e)return nd(e)}(e.basket),customInstructions:e.customInstructions,tags:(e.tags??[]).map(e=>nf(e))}}function nk(e){let t=e??{};return{signAndProcess:t.signAndProcess??!0,acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,knownTxids:t.knownTxids??[],returnTXIDOnly:nn(t.returnTXIDOnly),noSend:nn(t.noSend),noSendChange:(t.noSendChange??[]).map(e=>nr(e)),sendWith:t.sendWith??[],randomizeOutputs:t.randomizeOutputs??!0}}function nS(e,t){let i={description:nh(e.description,"description",5,2e3),inputBEEF:e.inputBEEF,inputs:(e.inputs??[]).map(e=>nv(e)),outputs:(e.outputs??[]).map(e=>nI(e)),lockTime:e.lockTime??0,version:e.version??1,labels:e.labels?.map(e=>nu(e))??[],options:nk(e.options),logger:t,isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!1,isRemixChange:!1,isSignAction:!1,randomVals:void 0,includeAllSourceTransactions:!1,isTestWerrReviewActions:!1};return i.isTestWerrReviewActions=i.labels.includes(nz),i.isSendWith=i.options.sendWith.length>0,i.isRemixChange=!i.isSendWith&&0===i.inputs.length&&0===i.outputs.length,i.isNewTx=i.isRemixChange||i.inputs.length>0||i.outputs.length>0,i.isSignAction=i.isNewTx&&(!i.options.signAndProcess||i.inputs.some(e=>void 0===e.unlockingScript)),i.isDelayed=i.options.acceptDelayedBroadcast,i.isNoSend=i.options.noSend,i}function nE(e){let t=e??{};return{acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,returnTXIDOnly:nn(t.returnTXIDOnly),noSend:nn(t.noSend),sendWith:t.sendWith??[]}}function nx(e){let t={spends:e.spends,reference:e.reference,options:nE(e.options),isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!0,isRemixChange:!1,isTestWerrReviewActions:!1};return t.isSendWith=t.options.sendWith.length>0,t.isDelayed=t.options.acceptDelayedBroadcast,t.isNoSend=t.options.noSend,t}function nA(e){return{reference:ny(e.reference,"reference")}}function nT(e){if(void 0!==e)return{derivationPrefix:ny(e.derivationPrefix,"derivationPrefix"),derivationSuffix:ny(e.derivationSuffix,"derivationSuffix"),senderIdentityKey:nb(e.senderIdentityKey,"senderIdentityKey")}}function nO(e){if(void 0!==e)return{basket:nd(e.basket),customInstructions:ns(e.customInstructions,"customInstructions",0,1e3),tags:(e.tags??[]).map(e=>nf(e))}}function nP(e){if("basket insertion"!==e.protocol&&"wallet payment"!==e.protocol)throw new r7("protocol","'basket insertion' or 'wallet payment'");return{outputIndex:nc(e.outputIndex,"outputIndex"),protocol:e.protocol,paymentRemittance:nT(e.paymentRemittance),insertionRemittance:nO(e.insertionRemittance)}}function nN(e){if(void 0!==e){for(let t of(nh(e=e.trim().toLowerCase(),"originator",1,250),e.split(".")))nh(t,"originator part",1,63);return e}}function n_(e){let t={tx:e.tx,outputs:e.outputs.map(e=>nP(e)),description:nh(e.description,"description",5,2e3),labels:(e.labels??[]).map(e=>nu(e)),seekPermission:e.seekPermission??!0};try{if(rp.fromBinary(t.tx).txs.length<1)throw new r7("tx","at least one transaction to internalize an output from")}catch{throw new r7("tx","valid with at least one transaction to internalize an output from")}if(t.outputs.length<1)throw new r7("outputs","at least one output to internalize from the transaction");return t}function nR(e,t){if(void 0!==e)return nC(e,t)}function nC(e,t){let i=e.split(".");if(2!==i.length||!Number.isInteger(Number(i[1])))throw new r7(t,"txid as hex string and numeric output index joined with '.'");let r=nb(i[0],`${t} txid`,void 0,64),n=nc(Number(i[1]),`${t} vout`);return`${r}.${n}`}function nB(e){return{basket:nd(e.basket),output:nC(e.output,"output")}}function nU(e){return{type:ny(e.type,"type"),serialNumber:ny(e.serialNumber,"serialNumber"),certifier:nb(e.certifier,"certifier")}}function nF(e){return{certifiers:e.certifiers.map(e=>nb(e.trim(),"certifiers"))??[],types:e.types.map(e=>ny(e.trim(),"types"))??[],limit:nl(e.limit,"limit",10,1,1e4),offset:nc(e.offset??0,"offset"),privileged:nn(e.privileged),privilegedReason:ns(e.privilegedReason,"privilegedReason",5,50),partial:void 0}}function nD(e){for(let t of Object.keys(e))nh(t,"field name",1,50);return e}function nL(e){if("issuance"!==e.acquisitionProtocol)throw Error("Only acquire certificate via issuance requests allowed here.");if(e.serialNumber)throw new r7("serialNumber",'valid when acquisitionProtocol is "direct"');if(e.signature)throw new r7("signature",'valid when acquisitionProtocol is "direct"');if(e.revocationOutpoint)throw new r7("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(e.keyringRevealer)throw new r7("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null!=e.keyringForSubject)throw new r7("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(!e.certifierUrl)throw new r7("certifierUrl",'valid when acquisitionProtocol is "issuance"');if(e.privileged&&!e.privilegedReason)throw new r7("privilegedReason","valid when 'privileged' is true ");return{type:ny(e.type,"type"),certifier:nb(e.certifier,"certifier"),certifierUrl:e.certifierUrl,fields:nD(e.fields),privileged:nn(e.privileged),privilegedReason:ns(e.privilegedReason,"privilegedReason",5,50),subject:""}}function nV(e){var t;if("direct"!==e.acquisitionProtocol)throw Error("Only acquire direct certificate requests allowed here.");if(!e.serialNumber)throw new r7("serialNumber",'valid when acquisitionProtocol is "direct"');if(!e.signature)throw new r7("signature",'valid when acquisitionProtocol is "direct"');if(!e.revocationOutpoint)throw new r7("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(!e.keyringRevealer)throw new r7("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null==e.keyringForSubject)throw new r7("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(e.privileged&&!e.privilegedReason)throw new r7("privilegedReason","valid when 'privileged' is true ");return{type:ny(e.type,"type"),serialNumber:ny(e.serialNumber,"serialNumber"),certifier:nb(e.certifier,"certifier"),revocationOutpoint:nC(e.revocationOutpoint,"revocationOutpoint"),fields:nD(e.fields),signature:nb(e.signature,"signature"),keyringRevealer:(t=e.keyringRevealer,"certifier"===t?t:nb(t,"keyringRevealer")),keyringForSubject:function(e,t){for(let i of Object.keys(e))nh(i,`${t} field name`,1,50),ny(e[i],`${t} field value`);return e}(e.keyringForSubject,"keyringForSubject"),privileged:nn(e.privileged),privilegedReason:ns(e.privilegedReason,"privilegedReason",5,50),subject:""}}function nH(e){if(e.privileged&&!e.privilegedReason)throw new r7("privilegedReason","valid when 'privileged' is true ");return{type:ng(e.certificate.type,"certificate.type"),serialNumber:ng(e.certificate.serialNumber,"certificate.serialNumber"),certifier:nm(e.certificate.certifier,"certificate.certifier"),subject:nm(e.certificate.subject,"certificate.subject"),revocationOutpoint:nR(e.certificate.revocationOutpoint,"certificate.revocationOutpoint"),signature:nm(e.certificate.signature,"certificate.signature"),fieldsToReveal:(e.fieldsToReveal??[]).map(e=>nh(e,`fieldsToReveal ${e}`,1,50)),verifier:nb(e.verifier,"verifier"),privileged:nn(e.privileged),privilegedReason:ns(e.privilegedReason,"privilegedReason",5,50)}}function nM(e){return{identityKey:nb(e.identityKey,"identityKey",66,66),limit:nl(e.limit,"limit",10,1,1e4),offset:nc(e.offset??0,"offset"),seekPermission:nn(e.seekPermission)}}function nK(e){return{attributes:function(e){for(let t of Object.keys(e))nh(t,`field name ${t}`,1,50);return e}(e.attributes),limit:nl(e.limit,"limit",10,1,1e4),offset:nc(e.offset??0,"offset"),seekPermission:nn(e.seekPermission)}}function nq(e){let t;if(void 0===e.tagQueryMode||"any"===e.tagQueryMode)t="any";else if("all"===e.tagQueryMode)t="all";else throw new r7("tagQueryMode","undefined, 'any', or 'all'");return{basket:nd(e.basket),tags:(e.tags??[]).map(e=>nf(e)),tagQueryMode:t,includeLockingScripts:"locking scripts"===e.include,includeTransactions:"entire transactions"===e.include,includeCustomInstructions:nn(e.includeCustomInstructions),includeTags:nn(e.includeTags),includeLabels:nn(e.includeLabels),limit:nl(e.limit,"limit",10,1,1e4),offset:nl(e.offset,"offset",0),seekPermission:e.seekPermission??!0,knownTxids:[]}}function n$(e){let t;if(void 0===e.labelQueryMode||"any"===e.labelQueryMode)t="any";else if("all"===e.labelQueryMode)t="all";else throw new r7("labelQueryMode","undefined, 'any', or 'all'");return{labels:(e.labels??[]).map(e=>nu(e)),labelQueryMode:t,includeLabels:nn(e.includeLabels),includeInputs:nn(e.includeInputs),includeInputSourceLockingScripts:nn(e.includeInputSourceLockingScripts),includeInputUnlockingScripts:nn(e.includeInputUnlockingScripts),includeOutputs:nn(e.includeOutputs),includeOutputLockingScripts:nn(e.includeOutputLockingScripts),limit:nl(e.limit,"limit",10,1,1e4),offset:nl(e.offset,"offset",0,0),seekPermission:e.seekPermission??!0}}let nz="a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a";class nW{substrate;originator;constructor(e="auto",t){"Cicada"===e&&(e=new r3(new r5(t))),"window.CWI"===e&&(e=new rY),"XDM"===e&&(e=new r0),"json-api"===e&&(e=new nt(t)),"react-native"===e&&(e=new ni(t)),"secure-json-api"===e&&(e=new nt(t,"https://localhost:2121")),this.substrate=e,this.originator=t}async connectToSubstrate(){if("object"==typeof this.substrate)return;let e=async(e,t)=>{try{let i,r=e();if(i="number"==typeof t?await Promise.race([r.getVersion({}),new Promise((e,i)=>setTimeout(()=>i(Error("Timed out.")),t))]):await r.getVersion({}),"object"!=typeof i||"string"!=typeof i.version)return{success:!1};return{success:!0,sub:r}}catch{return{success:!1}}},t=[e(()=>new rY),e(()=>new r3(new r5(this.originator))),e(()=>new nt(this.originator,"https://localhost:2121")),e(()=>new nt(this.originator)),e(()=>new ni(this.originator))],i=(await Promise.allSettled(t)).filter(e=>"fulfilled"===e.status&&e.value.success&&void 0!==e.value.sub).map(e=>e.value.sub);if(i.length>0){this.substrate=i[0];return}let r=await e(()=>new r0,200);if(r.success&&void 0!==r.sub)this.substrate=r.sub;else throw Error("No wallet available over any communication substrate. Install a BSV wallet today!")}async createAction(e){return nS(e),await this.connectToSubstrate(),await this.substrate.createAction(e,this.originator)}async signAction(e){return nx(e),await this.connectToSubstrate(),await this.substrate.signAction(e,this.originator)}async abortAction(e){return nA(e),await this.connectToSubstrate(),await this.substrate.abortAction(e,this.originator)}async listActions(e){return n$(e),await this.connectToSubstrate(),await this.substrate.listActions(e,this.originator)}async internalizeAction(e){return n_(e),await this.connectToSubstrate(),await this.substrate.internalizeAction(e,this.originator)}async listOutputs(e){return nq(e),await this.connectToSubstrate(),await this.substrate.listOutputs(e,this.originator)}async relinquishOutput(e){return nB(e),await this.connectToSubstrate(),await this.substrate.relinquishOutput(e,this.originator)}async getPublicKey(e){return await this.connectToSubstrate(),await this.substrate.getPublicKey(e,this.originator)}async revealCounterpartyKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealCounterpartyKeyLinkage(e,this.originator)}async revealSpecificKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealSpecificKeyLinkage(e,this.originator)}async encrypt(e){return await this.connectToSubstrate(),await this.substrate.encrypt(e,this.originator)}async decrypt(e){return await this.connectToSubstrate(),await this.substrate.decrypt(e,this.originator)}async createHmac(e){return await this.connectToSubstrate(),await this.substrate.createHmac(e,this.originator)}async verifyHmac(e){return await this.connectToSubstrate(),await this.substrate.verifyHmac(e,this.originator)}async createSignature(e){return await this.connectToSubstrate(),await this.substrate.createSignature(e,this.originator)}async verifySignature(e){return await this.connectToSubstrate(),await this.substrate.verifySignature(e,this.originator)}async acquireCertificate(e){if("direct"===e.acquisitionProtocol)nV(e);else if("issuance"===e.acquisitionProtocol)nL(e);else throw new r9("acquisitionProtocol",`valid. ${String(e.acquisitionProtocol)} is unrecognized.`);return await this.connectToSubstrate(),await this.substrate.acquireCertificate(e,this.originator)}async listCertificates(e){return nF(e),await this.connectToSubstrate(),await this.substrate.listCertificates(e,this.originator)}async proveCertificate(e){return nH(e),await this.connectToSubstrate(),await this.substrate.proveCertificate(e,this.originator)}async relinquishCertificate(e){return nU(e),await this.connectToSubstrate(),await this.substrate.relinquishCertificate(e,this.originator)}async discoverByIdentityKey(e){return nM(e),await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(e,this.originator)}async discoverByAttributes(e){return nK(e),await this.connectToSubstrate(),await this.substrate.discoverByAttributes(e,this.originator)}async isAuthenticated(e={}){return await this.connectToSubstrate(),await this.substrate.isAuthenticated(e,this.originator)}async waitForAuthentication(e={}){return await this.connectToSubstrate(),await this.substrate.waitForAuthentication(e,this.originator)}async getHeight(e={}){return await this.connectToSubstrate(),await this.substrate.getHeight(e,this.originator)}async getHeaderForHeight(e){return await this.connectToSubstrate(),await this.substrate.getHeaderForHeight(e,this.originator)}async getNetwork(e={}){return await this.connectToSubstrate(),await this.substrate.getNetwork(e,this.originator)}async getVersion(e={}){return await this.connectToSubstrate(),await this.substrate.getVersion(e,this.originator)}}class nj{wallet;constructor(e){this.wallet=e}decodeOutpoint(e){let t=tg(e.read(32)),i=e.readVarIntNum();return`${t}.${i}`}encodeOutpoint(e){let t=new tP,[i,r]=e.split(".");return t.write(tm(i,"hex")),t.writeVarIntNum(Number(r)),t.toArray()}async transmitToWallet(e){let t=new tN(e);try{let e=t.readUInt8(),i=r2[e];if(void 0===i||""===i)throw Error(`Invalid call code: ${e}`);let r=t.readUInt8(),n=t.read(r),s=tI(n);switch(i){case"createAction":{let e={},i=t.readVarIntNum(),r=t.read(i);e.description=tI(r);let n=t.readVarIntNum();n>=0?e.inputBEEF=t.read(n):e.inputBEEF=void 0;let a=t.readVarIntNum();if(a>=0){e.inputs=[];for(let i=0;i<a;i++){let i={};i.outpoint=this.decodeOutpoint(t);let r=t.readVarIntNum();if(r>=0){let e=t.read(r);i.unlockingScript=tg(e)}else i.unlockingScript=void 0,i.unlockingScriptLength=t.readVarIntNum();let n=t.readVarIntNum(),s=t.read(n);i.inputDescription=tI(s);let a=t.readVarIntNum();a>=0?i.sequenceNumber=a:i.sequenceNumber=void 0,e.inputs.push(i)}}else e.inputs=void 0;let o=t.readVarIntNum();if(o>=0){e.outputs=[];for(let i=0;i<o;i++){let i={},r=t.readVarIntNum(),n=t.read(r);i.lockingScript=tg(n),i.satoshis=t.readVarIntNum();let s=t.readVarIntNum(),a=t.read(s);i.outputDescription=tI(a);let o=t.readVarIntNum();if(o>=0){let e=t.read(o);i.basket=tI(e)}else i.basket=void 0;let l=t.readVarIntNum();if(l>=0){let e=t.read(l);i.customInstructions=tI(e)}else i.customInstructions=void 0;let c=t.readVarIntNum();if(c>=0){i.tags=[];for(let e=0;e<c;e++){let e=t.readVarIntNum(),r=t.read(e),n=tI(r);i.tags.push(n)}}else i.tags=void 0;e.outputs.push(i)}}else e.outputs=void 0;let l=t.readVarIntNum();l>=0?e.lockTime=l:e.lockTime=void 0;let c=t.readVarIntNum();c>=0?e.version=c:e.version=void 0;let h=t.readVarIntNum();if(h>=0){e.labels=[];for(let i=0;i<h;i++){let i=t.readVarIntNum(),r=t.read(i),n=tI(r);e.labels.push(n)}}else e.labels=void 0;let d=t.readInt8();if(1===d){e.options={};let i=t.readInt8();-1===i?e.options.signAndProcess=void 0:e.options.signAndProcess=1===i;let r=t.readInt8();-1===r?e.options.acceptDelayedBroadcast=void 0:e.options.acceptDelayedBroadcast=1===r;let n=t.readInt8();-1===n?e.options.trustSelf=void 0:1===n&&(e.options.trustSelf="known");let s=t.readVarIntNum();if(s>=0){e.options.knownTxids=[];for(let i=0;i<s;i++){let i=t.read(32),r=tg(i);e.options.knownTxids.push(r)}}else e.options.knownTxids=void 0;let a=t.readInt8();-1===a?e.options.returnTXIDOnly=void 0:e.options.returnTXIDOnly=1===a;let o=t.readInt8();-1===o?e.options.noSend=void 0:e.options.noSend=1===o;let l=t.readVarIntNum();if(l>=0){e.options.noSendChange=[];for(let i=0;i<l;i++){let i=this.decodeOutpoint(t);e.options.noSendChange.push(i)}}else e.options.noSendChange=void 0;let c=t.readVarIntNum();if(c>=0){e.options.sendWith=[];for(let i=0;i<c;i++){let i=t.read(32),r=tg(i);e.options.sendWith.push(r)}}else e.options.sendWith=void 0;let h=t.readInt8();-1===h?e.options.randomizeOutputs=void 0:e.options.randomizeOutputs=1===h}else e.options=void 0;let u=await this.wallet.createAction(e,s),f=new tP;if(null!=u.txid&&""!==u.txid?(f.writeInt8(1),f.write(tm(u.txid,"hex"))):f.writeInt8(0),null==u.tx?f.writeInt8(0):(f.writeInt8(1),f.writeVarIntNum(u.tx.length),f.write(u.tx)),null==u.noSendChange)f.writeVarIntNum(-1);else for(let e of(f.writeVarIntNum(u.noSendChange.length),u.noSendChange))f.write(this.encodeOutpoint(e));if(null==u.sendWithResults)f.writeVarIntNum(-1);else for(let e of(f.writeVarIntNum(u.sendWithResults.length),u.sendWithResults)){let t;f.write(tm(e.txid,"hex")),"unproven"===e.status?t=1:"sending"===e.status?t=2:"failed"===e.status&&(t=3),f.writeInt8(t)}if(null==u.signableTransaction)f.writeInt8(0);else{f.writeInt8(1),f.writeVarIntNum(u.signableTransaction.tx.length),f.write(u.signableTransaction.tx);let e=tm(u.signableTransaction.reference,"base64");f.writeVarIntNum(e.length),f.write(e)}let p=new tP;return p.writeUInt8(0),p.write(f.toArray()),p.toArray()}case"signAction":{let e={},i=t.readVarIntNum();e.spends={};for(let r=0;r<i;r++){let i=t.readVarIntNum(),r={},n=t.readVarIntNum(),s=t.read(n);r.unlockingScript=tg(s);let a=t.readVarIntNum();a>=0?r.sequenceNumber=a:r.sequenceNumber=void 0,e.spends[i]=r}let r=t.readVarIntNum(),n=t.read(r);e.reference=tS(n);let a=t.readInt8();if(1===a){e.options={};let i=t.readInt8();-1===i?e.options.acceptDelayedBroadcast=void 0:e.options.acceptDelayedBroadcast=1===i;let r=t.readInt8();-1===r?e.options.returnTXIDOnly=void 0:e.options.returnTXIDOnly=1===r;let n=t.readInt8();-1===n?e.options.noSend=void 0:e.options.noSend=1===n;let s=t.readVarIntNum();if(s>=0){e.options.sendWith=[];for(let i=0;i<s;i++){let i=t.read(32),r=tg(i);e.options.sendWith.push(r)}}else e.options.sendWith=void 0}else e.options=void 0;let o=await this.wallet.signAction(e,s),l=new tP;if(null!=o.txid&&""!==o.txid?(l.writeInt8(1),l.write(tm(o.txid,"hex"))):l.writeInt8(0),null==o.tx?l.writeInt8(0):(l.writeInt8(1),l.writeVarIntNum(o.tx.length),l.write(o.tx)),null==o.sendWithResults)l.writeVarIntNum(-1);else for(let e of(l.writeVarIntNum(o.sendWithResults.length),o.sendWithResults)){let t;l.write(tm(e.txid,"hex")),"unproven"===e.status?t=1:"sending"===e.status?t=2:"failed"===e.status&&(t=3),l.writeInt8(t)}let c=new tP;return c.writeUInt8(0),c.write(l.toArray()),c.toArray()}case"abortAction":{let e=t.read(),i=tS(e);await this.wallet.abortAction({reference:i},s);let r=new tP;return r.writeUInt8(0),r.toArray()}case"listActions":{let e={},i=t.readVarIntNum();e.labels=[];for(let r=0;r<i;r++){let i=t.readVarIntNum(),r=t.read(i);e.labels.push(tI(r))}let r=t.readInt8();for(let i of(-1===r?e.labelQueryMode=void 0:1===r?e.labelQueryMode="any":2===r&&(e.labelQueryMode="all"),["includeLabels","includeInputs","includeInputSourceLockingScripts","includeInputUnlockingScripts","includeOutputs","includeOutputLockingScripts"])){let r=t.readInt8();-1===r?e[i]=void 0:e[i]=1===r}let n=t.readVarIntNum();n>=0?e.limit=n:e.limit=void 0;let a=t.readVarIntNum();a>=0?e.offset=a:e.offset=void 0;let o=t.readInt8();o>=0?e.seekPermission=1===o:e.seekPermission=void 0;let l=await this.wallet.listActions(e,s),c=new tP;for(let e of(c.writeVarIntNum(l.totalActions),l.actions)){let t;switch(c.write(tm(e.txid,"hex")),c.writeVarIntNum(e.satoshis),e.status){case"completed":t=1;break;case"unprocessed":t=2;break;case"sending":t=3;break;case"unproven":t=4;break;case"unsigned":t=5;break;case"nosend":t=6;break;case"nonfinal":t=7;break;case"failed":t=8;break;default:t=-1}c.writeInt8(t),c.writeInt8(+!!e.isOutgoing);let i=tm(e.description,"utf8");if(c.writeVarIntNum(i.length),c.write(i),void 0===e.labels)c.writeVarIntNum(-1);else for(let t of(c.writeVarIntNum(e.labels.length),e.labels)){let e=tm(t,"utf8");c.writeVarIntNum(e.length),c.write(e)}if(c.writeVarIntNum(e.version),c.writeVarIntNum(e.lockTime),void 0===e.inputs)c.writeVarIntNum(-1);else for(let t of(c.writeVarIntNum(e.inputs.length),e.inputs)){if(c.write(this.encodeOutpoint(t.sourceOutpoint)),c.writeVarIntNum(t.sourceSatoshis),void 0===t.sourceLockingScript)c.writeVarIntNum(-1);else{let e=tm(t.sourceLockingScript,"hex");c.writeVarIntNum(e.length),c.write(e)}if(void 0===t.unlockingScript)c.writeVarIntNum(-1);else{let e=tm(t.unlockingScript,"hex");c.writeVarIntNum(e.length),c.write(e)}let e=tm(t.inputDescription,"utf8");c.writeVarIntNum(e.length),c.write(e),c.writeVarIntNum(t.sequenceNumber)}if(void 0===e.outputs)c.writeVarIntNum(-1);else for(let t of(c.writeVarIntNum(e.outputs.length),e.outputs)){if(c.writeVarIntNum(t.outputIndex),c.writeVarIntNum(t.satoshis),void 0===t.lockingScript)c.writeVarIntNum(-1);else{let e=tm(t.lockingScript,"hex");c.writeVarIntNum(e.length),c.write(e)}c.writeInt8(+!!t.spendable);let e=tm(t.outputDescription,"utf8");if(c.writeVarIntNum(e.length),c.write(e),void 0===t.basket)c.writeVarIntNum(-1);else{let e=tm(t.basket,"utf8");c.writeVarIntNum(e.length),c.write(e)}if(void 0===t.tags)c.writeVarIntNum(-1);else for(let e of(c.writeVarIntNum(t.tags.length),t.tags)){let t=tm(e,"utf8");c.writeVarIntNum(t.length),c.write(t)}if(void 0===t.customInstructions)c.writeVarIntNum(-1);else{let e=tm(t.customInstructions,"utf8");c.writeVarIntNum(e.length),c.write(e)}}}let h=new tP;return h.writeUInt8(0),h.write(c.toArray()),h.toArray()}case"internalizeAction":{let e={},i=t.readVarIntNum();e.tx=t.read(i);let r=t.readVarIntNum();e.outputs=[];for(let i=0;i<r;i++){let i={};i.outputIndex=t.readVarIntNum();let r=t.readUInt8();if(1===r){i.protocol="wallet payment",i.paymentRemittance={};let e=t.read(33);i.paymentRemittance.senderIdentityKey=tg(e);let r=t.readVarIntNum(),n=t.read(r);i.paymentRemittance.derivationPrefix=tS(n);let s=t.readVarIntNum(),a=t.read(s);i.paymentRemittance.derivationSuffix=tS(a)}else if(2===r){i.protocol="basket insertion",i.insertionRemittance={};let e=t.readVarIntNum(),r=t.read(e);i.insertionRemittance.basket=tI(r);let n=t.readVarIntNum();if(n>=0){let e=t.read(n);i.insertionRemittance.customInstructions=tI(e)}let s=t.readVarIntNum();if(s>0){i.insertionRemittance.tags=[];for(let e=0;e<s;e++){let e=t.readVarIntNum(),r=t.read(e);i.insertionRemittance.tags.push(tI(r))}}else i.insertionRemittance.tags=[]}e.outputs.push(i)}let n=t.readVarIntNum();if(n>=0){e.labels=[];for(let i=0;i<n;i++){let i=t.readVarIntNum();e.labels.push(tI(t.read(i)))}}let a=t.readVarIntNum();e.description=tI(t.read(a));let o=t.readInt8();o>=0?e.seekPermission=1===o:e.seekPermission=void 0,await this.wallet.internalizeAction(e,s);let l=new tP;return l.writeUInt8(0),l.toArray()}case"listOutputs":{let e={},i=t.readVarIntNum(),r=t.read(i);e.basket=tI(r);let n=t.readVarIntNum();if(n>0){e.tags=[];for(let i=0;i<n;i++){let i=t.readVarIntNum(),r=t.read(i);e.tags.push(tI(r))}}else e.tags=void 0;let a=t.readInt8();1===a?e.tagQueryMode="all":2===a?e.tagQueryMode="any":e.tagQueryMode=void 0;let o=t.readInt8();1===o?e.include="locking scripts":2===o?e.include="entire transactions":e.include=void 0;let l=t.readInt8();-1===l?e.includeCustomInstructions=void 0:e.includeCustomInstructions=1===l;let c=t.readInt8();-1===c?e.includeTags=void 0:e.includeTags=1===c;let h=t.readInt8();-1===h?e.includeLabels=void 0:e.includeLabels=1===h;let d=t.readVarIntNum();d>=0?e.limit=d:e.limit=void 0;let u=t.readVarIntNum();u>=0?e.offset=u:e.offset=void 0;let f=t.readInt8();f>=0?e.seekPermission=1===f:e.seekPermission=void 0;let p=await this.wallet.listOutputs(e,s),g=new tP;for(let e of(g.writeVarIntNum(p.totalOutputs),null==p.BEEF?g.writeVarIntNum(-1):(g.writeVarIntNum(p.BEEF.length),g.write(p.BEEF)),p.outputs)){if(g.write(this.encodeOutpoint(e.outpoint)),g.writeVarIntNum(e.satoshis),void 0===e.lockingScript)g.writeVarIntNum(-1);else{let t=tm(e.lockingScript,"hex");g.writeVarIntNum(t.length),g.write(t)}if(void 0===e.customInstructions)g.writeVarIntNum(-1);else{let t=tm(e.customInstructions,"utf8");g.writeVarIntNum(t.length),g.write(t)}if(void 0===e.tags)g.writeVarIntNum(-1);else for(let t of(g.writeVarIntNum(e.tags.length),e.tags)){let e=tm(t,"utf8");g.writeVarIntNum(e.length),g.write(e)}if(void 0===e.labels)g.writeVarIntNum(-1);else for(let t of(g.writeVarIntNum(e.labels.length),e.labels)){let e=tm(t,"utf8");g.writeVarIntNum(e.length),g.write(e)}}let y=new tP;return y.writeUInt8(0),y.write(g.toArray()),y.toArray()}case"relinquishOutput":{let e={},i=t.readVarIntNum(),r=t.read(i);e.basket=tI(r),e.output=this.decodeOutpoint(t),await this.wallet.relinquishOutput(e,s);let n=new tP;return n.writeUInt8(0),n.toArray()}case"getPublicKey":{let e={},i=t.readUInt8();if(e.identityKey=1===i,!0===e.identityKey){let i=t.readInt8();-1===i?e.privileged=void 0:e.privileged=1===i;let r=t.readInt8();if(-1===r)e.privilegedReason=void 0;else{let i=t.read(r);e.privilegedReason=tI(i)}}else{e.protocolID=this.decodeProtocolID(t),e.keyID=this.decodeString(t),e.counterparty=this.decodeCounterparty(t);let i=t.readInt8();-1===i?e.privileged=void 0:e.privileged=1===i;let r=t.readInt8();if(-1===r)e.privilegedReason=void 0;else{let i=t.read(r);e.privilegedReason=tI(i)}let n=t.readInt8();-1===n?e.forSelf=void 0:e.forSelf=1===n}let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.getPublicKey(e,s),a=new tP;a.writeUInt8(0);let o=tm(n.publicKey,"hex");return a.write(o),a.toArray()}case"encrypt":{let e=this.decodeKeyRelatedParams(t),i=t.readVarIntNum();e.plaintext=t.read(i);let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.encrypt(e,s),a=new tP;return a.writeUInt8(0),a.write(n.ciphertext),a.toArray()}case"decrypt":{let e=this.decodeKeyRelatedParams(t),i=t.readVarIntNum();e.ciphertext=t.read(i);let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.decrypt(e,s),a=new tP;return a.writeUInt8(0),a.write(n.plaintext),a.toArray()}case"createHmac":{let e=this.decodeKeyRelatedParams(t),i=t.readVarIntNum();e.data=t.read(i);let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.createHmac(e,s),a=new tP;return a.writeUInt8(0),a.write(n.hmac),a.toArray()}case"verifyHmac":{let e=this.decodeKeyRelatedParams(t);e.hmac=t.read(32);let i=t.readVarIntNum();e.data=t.read(i);let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0,await this.wallet.verifyHmac(e,s);let n=new tP;return n.writeUInt8(0),n.toArray()}case"createSignature":{let e=this.decodeKeyRelatedParams(t),i=t.readUInt8();if(1===i){let i=t.readVarIntNum();e.data=t.read(i)}else 2===i&&(e.hashToDirectlySign=t.read(32));let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.createSignature(e,s),a=new tP;return a.writeUInt8(0),a.write(n.signature),a.toArray()}case"verifySignature":{let e=this.decodeKeyRelatedParams(t),i=t.readInt8();-1===i?e.forSelf=void 0:e.forSelf=1===i;let r=t.readVarIntNum();e.signature=t.read(r);let n=t.readUInt8();if(1===n){let i=t.readVarIntNum();e.data=t.read(i)}else 2===n&&(e.hashToDirectlyVerify=t.read(32));let a=t.readInt8();a>=0?e.seekPermission=1===a:e.seekPermission=void 0,await this.wallet.verifySignature(e,s);let o=new tP;return o.writeUInt8(0),o.toArray()}case"isAuthenticated":{let e=await this.wallet.isAuthenticated({},s),t=new tP;return t.writeUInt8(0),t.writeUInt8(+!!e.authenticated),t.toArray()}case"waitForAuthentication":{await this.wallet.waitForAuthentication({},s);let e=new tP;return e.writeUInt8(0),e.toArray()}case"getHeight":{let e=await this.wallet.getHeight({},s),t=new tP;return t.writeUInt8(0),t.writeVarIntNum(e.height),t.toArray()}case"getHeaderForHeight":{let e={};e.height=t.readVarIntNum();let i=await this.wallet.getHeaderForHeight(e,s),r=new tP;r.writeUInt8(0);let n=tm(i.header,"hex");return r.write(n),r.toArray()}case"getNetwork":{let e=await this.wallet.getNetwork({},s),t=new tP;return t.writeUInt8(0),t.writeUInt8(+("mainnet"!==e.network)),t.toArray()}case"getVersion":{let e=await this.wallet.getVersion({},s),t=new tP;t.writeUInt8(0);let i=tm(e.version,"utf8");return t.write(i),t.toArray()}case"revealCounterpartyKeyLinkage":{let e={},i=t.readInt8();-1===i?e.privileged=void 0:e.privileged=1===i;let r=t.readInt8();if(-1===r)e.privilegedReason=void 0;else{let i=t.read(r);e.privilegedReason=tI(i)}let n=t.read(33);e.counterparty=tg(n);let a=t.read(33);e.verifier=tg(a);let o=await this.wallet.revealCounterpartyKeyLinkage(e,s),l=new tP;l.write(tm(o.prover,"hex")),l.write(tm(o.verifier,"hex")),l.write(tm(o.counterparty,"hex"));let c=tm(o.revelationTime,"utf8");l.writeVarIntNum(c.length),l.write(c),l.writeVarIntNum(o.encryptedLinkage.length),l.write(o.encryptedLinkage),l.writeVarIntNum(o.encryptedLinkageProof.length),l.write(o.encryptedLinkageProof);let h=new tP;return h.writeUInt8(0),h.write(l.toArray()),h.toArray()}case"revealSpecificKeyLinkage":{let e=this.decodeKeyRelatedParams(t),i=t.read(33);e.verifier=tg(i);let r=await this.wallet.revealSpecificKeyLinkage(e,s),n=new tP;n.write(tm(r.prover,"hex")),n.write(tm(r.verifier,"hex")),n.write(tm(r.counterparty,"hex")),n.writeUInt8(r.protocolID[0]);let a=tm(r.protocolID[1],"utf8");n.writeVarIntNum(a.length),n.write(a);let o=tm(r.keyID,"utf8");n.writeVarIntNum(o.length),n.write(o),n.writeVarIntNum(r.encryptedLinkage.length),n.write(r.encryptedLinkage),n.writeVarIntNum(r.encryptedLinkageProof.length),n.write(r.encryptedLinkageProof),n.writeUInt8(r.proofType);let l=new tP;return l.writeUInt8(0),l.write(n.toArray()),l.toArray()}case"acquireCertificate":{let e={},i=t.read(32);e.type=tS(i);let r=t.read(33);e.certifier=tg(r);let n=t.readVarIntNum();e.fields={};for(let i=0;i<n;i++){let i=t.readVarIntNum(),r=t.read(i),n=tI(r),s=t.readVarIntNum(),a=t.read(s),o=tI(a);e.fields[n]=o}let a=t.readInt8();-1===a?e.privileged=void 0:e.privileged=1===a;let o=t.readInt8();if(-1===o)e.privilegedReason=void 0;else{let i=t.read(o);e.privilegedReason=tI(i)}let l=t.readUInt8();if(e.acquisitionProtocol=1===l?"direct":"issuance","direct"===e.acquisitionProtocol){let i=t.read(32);e.serialNumber=tS(i),e.revocationOutpoint=this.decodeOutpoint(t);let r=t.readVarIntNum(),n=t.read(r);e.signature=tg(n);let s=t.readUInt8();if(11===s)e.keyringRevealer="certifier";else{let i=[s].concat(t.read(32));e.keyringRevealer=tg(i)}let a=t.readVarIntNum();e.keyringForSubject={};for(let i=0;i<a;i++){let i=t.readVarIntNum(),r=t.read(i),n=tI(r),s=t.readVarIntNum(),a=t.read(s),o=tS(a);e.keyringForSubject[n]=o}}else{let i=t.readVarIntNum(),r=t.read(i);e.certifierUrl=tI(r)}let c=await this.wallet.acquireCertificate(e,s),h=new r1(c.type,c.serialNumber,c.subject,c.certifier,c.revocationOutpoint,c.fields,c.signature).toBinary(),d=new tP;return d.writeUInt8(0),d.write(h),d.toArray()}case"listCertificates":{let e={},i=t.readVarIntNum();e.certifiers=[];for(let r=0;r<i;r++){let i=t.read(33);e.certifiers.push(tg(i))}let r=t.readVarIntNum();e.types=[];for(let i=0;i<r;i++){let i=t.read(32);e.types.push(tS(i))}let n=t.readVarIntNum();n>=0?e.limit=n:e.limit=void 0;let a=t.readVarIntNum();a>=0?e.offset=a:e.offset=void 0;let o=t.readInt8();-1===o?e.privileged=void 0:e.privileged=1===o;let l=t.readInt8();if(-1===l)e.privilegedReason=void 0;else{let i=t.read(l);e.privilegedReason=tI(i)}let c=await this.wallet.listCertificates(e,s),h=new tP;for(let e of(h.writeVarIntNum(c.totalCertificates),c.certificates)){let t=new r1(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature).toBinary();if(h.writeVarIntNum(t.length),h.write(t),e.keyring&&Object.keys(e.keyring).length>0){h.writeInt8(1);let t=Object.entries(e.keyring);for(let[e,i]of(h.writeVarIntNum(t.length),t)){let t=tm(e,"utf8");h.writeVarIntNum(t.length),h.write(t);let r=tm(i,"base64");h.writeVarIntNum(r.length),h.write(r)}}else h.writeInt8(0);let i=tm(e.verifier,"hex");h.writeVarIntNum(i.length),h.write(i)}let d=new tP;return d.writeUInt8(0),d.write(h.toArray()),d.toArray()}case"proveCertificate":{let e={},i={},r=t.read(32);i.type=tS(r);let n=t.read(33);i.subject=tg(n);let a=t.read(32);i.serialNumber=tS(a);let o=t.read(33);i.certifier=tg(o),i.revocationOutpoint=this.decodeOutpoint(t);let l=t.readVarIntNum(),c=t.read(l);i.signature=tg(c);let h=t.readVarIntNum();i.fields={};for(let e=0;e<h;e++){let e=t.readVarIntNum(),r=t.read(e),n=tI(r),s=t.readVarIntNum(),a=t.read(s),o=tI(a);i.fields[n]=o}e.certificate=i;let d=t.readVarIntNum();e.fieldsToReveal=[];for(let i=0;i<d;i++){let i=t.readVarIntNum(),r=t.read(i),n=tI(r);e.fieldsToReveal.push(n)}let u=t.read(33);e.verifier=tg(u);let f=t.readInt8();-1===f?e.privileged=void 0:e.privileged=1===f;let p=t.readInt8();if(-1===p)e.privilegedReason=void 0;else{let i=t.read(p);e.privilegedReason=tI(i)}let g=await this.wallet.proveCertificate(e,s),y=new tP,m=Object.entries(g.keyringForVerifier);for(let[e,t]of(y.writeVarIntNum(m.length),m)){let i=tm(e,"utf8");y.writeVarIntNum(i.length),y.write(i);let r=tm(t,"base64");y.writeVarIntNum(r.length),y.write(r)}let b=new tP;return b.writeUInt8(0),b.write(y.toArray()),b.toArray()}case"relinquishCertificate":{let e={},i=t.read(32);e.type=tS(i);let r=t.read(32);e.serialNumber=tS(r);let n=t.read(33);e.certifier=tg(n),await this.wallet.relinquishCertificate(e,s);let a=new tP;return a.writeUInt8(0),a.toArray()}case"discoverByIdentityKey":{let e={},i=t.read(33);e.identityKey=tg(i);let r=t.readVarIntNum();r>=0?e.limit=r:e.limit=void 0;let n=t.readVarIntNum();n>=0?e.offset=n:e.offset=void 0;let a=t.readInt8();a>=0?e.seekPermission=1===a:e.seekPermission=void 0;let o=await this.wallet.discoverByIdentityKey(e,s),l=this.serializeDiscoveryResult(o),c=new tP;return c.writeUInt8(0),c.write(l),c.toArray()}case"discoverByAttributes":{let e={},i=t.readVarIntNum();e.attributes={};for(let r=0;r<i;r++){let i=t.readVarIntNum(),r=t.read(i),n=tI(r),s=t.readVarIntNum(),a=t.read(s),o=tI(a);e.attributes[n]=o}let r=t.readVarIntNum();r>=0?e.limit=r:e.limit=void 0;let n=t.readVarIntNum();n>=0?e.offset=n:e.offset=void 0;let a=t.readInt8();a>=0?e.seekPermission=1===a:e.seekPermission=void 0;let o=await this.wallet.discoverByAttributes(e,s),l=this.serializeDiscoveryResult(o),c=new tP;return c.writeUInt8(0),c.write(l),c.toArray()}default:throw Error(`Method ${i} not implemented`)}}catch(r){let e=new tP;e.writeUInt8("number"==typeof r.code?r.code:1);let t=tm("string"==typeof r.message?r.message:"Unknown error","utf8");e.writeVarIntNum(t.length),e.write(t);let i=tm("string"==typeof r.stack?r.stack:"","utf8");return e.writeVarIntNum(i.length),e.write(i),e.toArray()}}decodeProtocolID(e){let t=e.readUInt8(),i=e.readVarIntNum();return[t,tI(e.read(i))]}decodeString(e){let t=e.readVarIntNum();return tI(e.read(t))}decodeCounterparty(e){let t=e.readUInt8();return 11===t?"self":12===t?"anyone":0!==t?tg([t,...e.read(32)]):void 0}serializeDiscoveryResult(e){let t=new tP;for(let i of(t.writeVarIntNum(e.totalCertificates),e.certificates)){let e=new r1(i.type,i.serialNumber,i.subject,i.certifier,i.revocationOutpoint,i.fields,i.signature).toBinary();t.writeVarIntNum(e.length),t.write(e);let r=tm(i.certifierInfo.name,"utf8");t.writeVarIntNum(r.length),t.write(r);let n=tm(i.certifierInfo.iconUrl,"utf8");t.writeVarIntNum(n.length),t.write(n);let s=tm(i.certifierInfo.description,"utf8");t.writeVarIntNum(s.length),t.write(s),t.writeUInt8(i.certifierInfo.trust);let a=Object.entries(i.publiclyRevealedKeyring);for(let[e,i]of(t.writeVarIntNum(a.length),a)){let r=tm(e,"utf8");t.writeVarIntNum(r.length),t.write(r);let n=tm(i,"base64");t.writeVarIntNum(n.length),t.write(n)}let o=Object.entries(i.decryptedFields);for(let[e,i]of(t.writeVarIntNum(o.length),o)){let r=tm(e,"utf8");t.writeVarIntNum(r.length),t.write(r);let n=tm(i,"utf8");t.writeVarIntNum(n.length),t.write(n)}}return t.toArray()}decodeKeyRelatedParams(e){let t={};t.protocolID=this.decodeProtocolID(e);let i=e.readVarIntNum();t.keyID=tI(e.read(i)),t.counterparty=this.decodeCounterparty(e);let r=e.readInt8();-1===r?t.privileged=void 0:t.privileged=1===r;let n=e.readInt8();return -1===n?t.privilegedReason=void 0:t.privilegedReason=tI(e.read(n)),t}}class nG extends r1{masterKeyring;constructor(e,t,i,r,n,s,a,o){for(const l of(super(e,t,i,r,n,s,o),Object.keys(s)))if(void 0===a[l]||""===a[l])throw Error(`Master keyring must contain a value for every field. Missing or empty key for field: "${l}".`);this.masterKeyring=a}static async createCertificateFields(e,t,i,r,n){let s={},a={};for(let[o,l]of Object.entries(i)){let i=i_.fromRandom(),c=i.encrypt(tm(l,"utf8"));s[o]=tS(c);let{ciphertext:h}=await e.encrypt({plaintext:i.toArray(),...r1.getCertificateFieldEncryptionDetails(o),counterparty:t,privileged:r,privilegedReason:n});a[o]=tS(h)}return{certificateFields:s,masterKeyring:a}}static async createKeyringForVerifier(e,t,i,r,n,s,a,o,l){if(!Array.isArray(n))throw TypeError("fieldsToReveal must be an array of strings");let c={};for(let h of n){if(void 0===r[h]||null===r[h]||""===r[h])throw Error(`Fields to reveal must be a subset of the certificate fields. Missing the "${h}" field.`);let n=(await this.decryptField(e,s,h,r[h],t,o,l)).fieldRevelationKey,{ciphertext:d}=await e.encrypt({plaintext:n,...r1.getCertificateFieldEncryptionDetails(h,a),counterparty:i,privileged:o,privilegedReason:l});c[h]=tS(d)}return c}static async issueCertificateForSubject(e,t,i,r,n=async e=>"00".repeat(32),s){let a=s??tS(ia(32)),{certificateFields:o,masterKeyring:l}=await this.createCertificateFields(e,t,i),c=await n(a),h=new nG(r,a,"self"===t?(await e.getPublicKey({identityKey:!0})).publicKey:t,(await e.getPublicKey({identityKey:!0})).publicKey,c,o,l);return await h.sign(e),h}static async decryptFields(e,t,i,r,n,s){if(null==t||0===Object.keys(t).length)throw Error("A MasterCertificate must have a valid masterKeyring!");try{let a={};for(let o of Object.keys(i))a[o]=(await this.decryptField(e,t,o,i[o],r,n,s)).decryptedFieldValue;return a}catch{throw Error("Failed to decrypt all master certificate fields.")}}static async decryptField(e,t,i,r,n,s,a){if(null==t||0===Object.keys(t).length)throw Error("A MasterCertificate must have a valid masterKeyring!");try{let{plaintext:o}=await e.decrypt({ciphertext:tm(t[i],"base64"),...r1.getCertificateFieldEncryptionDetails(i),counterparty:n,privileged:s,privilegedReason:a}),l=new i_(o).decrypt(tm(r,"base64"));return{fieldRevelationKey:o,decryptedFieldValue:tI(l)}}catch{throw Error("Failed to decrypt certificate field!")}}}class nX extends r1{keyring;decryptedFields;constructor(e,t,i,r,n,s,a,o,l){super(e,t,i,r,n,s,o),this.keyring=a,this.decryptedFields=l}static fromCertificate(e,t){return new nX(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,t,e.signature)}async decryptFields(e,t,i,r){if(null==this.keyring||0===Object.keys(this.keyring).length)throw Error("A keyring is required to decrypt certificate fields for the verifier.");try{let n={};for(let s in this.keyring){let{plaintext:a}=await e.decrypt({ciphertext:tm(this.keyring[s],"base64"),...r1.getCertificateFieldEncryptionDetails(s,this.serialNumber),counterparty:this.subject,privileged:t,privilegedReason:i},r),o=new i_(a).decrypt(tm(this.fields[s],"base64"));n[s]=tI(o)}return n}catch(e){throw Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(e instanceof Error?e.message:e)}`)}}}class nY extends rX{keyDeriver;constructor(e){if(super(e),e instanceof rW)this.keyDeriver=e;else if("string"==typeof e||e instanceof ih)this.keyDeriver=new rj(e);else throw TypeError("Invalid key deriver provided")}async isAuthenticated(){throw Error("not implemented")}async waitForAuthentication(){throw Error("not implemented")}async getNetwork(){throw Error("not implemented")}async getVersion(){throw Error("not implemented")}async getPublicKey(e){if(!0===e.privileged)throw Error("no privilege support");if(!0===e.identityKey){if(null===this.keyDeriver||void 0===this.keyDeriver)throw Error("keyDeriver is not initialized");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==e.protocolID||"string"!=typeof e.keyID||""===e.keyID.trim())throw Error("protocolID and keyID are required if identityKey is false or undefined.");if(null===this.keyDeriver||void 0===this.keyDeriver)throw Error("keyDeriver is not initialized");return{publicKey:this.keyDeriver.derivePublicKey(e.protocolID,e.keyID,"string"==typeof e.counterparty&&""!==e.counterparty.trim()?e.counterparty:"self",!!e.forSelf).toString()}}async createAction(){throw Error("not implemented")}async signAction(){throw Error("not implemented")}async abortAction(){throw Error("not implemented")}async listActions(){throw Error("not implemented")}async internalizeAction(){throw Error("not implemented")}async listOutputs(){throw Error("not implemented")}async relinquishOutput(){throw Error("not implemented")}async acquireCertificate(){throw Error("not implemented")}async listCertificates(){throw Error("not implemented")}async proveCertificate(){throw Error("not implemented")}async relinquishCertificate(){throw Error("not implemented")}async discoverByIdentityKey(){throw Error("not implemented")}async discoverByAttributes(){throw Error("not implemented")}async getHeight(){throw Error("not implemented")}async getHeaderForHeight(){throw Error("not implemented")}}class nJ{sessionNonceToSession;identityKeyToNonces;constructor(){this.sessionNonceToSession=new Map,this.identityKeyToNonces=new Map}addSession(e){if("string"!=typeof e.sessionNonce)throw TypeError("Invalid session: sessionNonce is required to add a session.");if(this.sessionNonceToSession.set(e.sessionNonce,e),"string"==typeof e.peerIdentityKey){let t=this.identityKeyToNonces.get(e.peerIdentityKey);null==t&&(t=new Set,this.identityKeyToNonces.set(e.peerIdentityKey,t)),t.add(e.sessionNonce)}}updateSession(e){this.removeSession(e),this.addSession(e)}getSession(e){let t,i=this.sessionNonceToSession.get(e);if(null!=i)return i;let r=this.identityKeyToNonces.get(e);if(null!=r&&0!==r.size){for(let e of r){let i=this.sessionNonceToSession.get(e);null!=i&&(null==t?t=i:(i.lastUpdate??0)>(t.lastUpdate??0)&&(t=i))}return t}}removeSession(e){if("string"==typeof e.sessionNonce&&this.sessionNonceToSession.delete(e.sessionNonce),"string"==typeof e.peerIdentityKey){let t=this.identityKeyToNonces.get(e.peerIdentityKey);null!=t&&(t.delete(e.sessionNonce??""),0===t.size&&this.identityKeyToNonces.delete(e.peerIdentityKey))}}hasSession(e){if(this.sessionNonceToSession.has(e))return!0;let t=this.identityKeyToNonces.get(e);return null!=t&&t.size>0}}async function nZ(e,t,i="self",r){let n=tm(e,"base64"),s=n.slice(0,16),a=n.slice(16),{valid:o}=await t.verifyHmac({data:s,hmac:a,protocolID:[2,"server hmac"],keyID:tI(s),counterparty:i},r);return o}async function nQ(e,t="self",i){let r=ia(16),{hmac:n}=await e.createHmac({protocolID:[2,"server hmac"],keyID:tI(r),data:r,counterparty:t},i);return tS([...r,...n])}let n0=async(e,t,i,r)=>{let n=await e.listCertificates({certifiers:t.certifiers,types:Object.keys(t.types)},r);return await Promise.all(n.certificates.map(async n=>{let{keyringForVerifier:s}=await e.proveCertificate({certificate:n,fieldsToReveal:t.types[n.type],verifier:i},r);return new nX(n.type,n.serialNumber,n.subject,n.certifier,n.revocationOutpoint,n.fields,s,n.signature)}))},n1=async(e,t,i,r)=>{if(null==t.certificates||0===t.certificates.length)throw Error("No certificates were provided in the AuthMessage.");await Promise.all(t.certificates.map(async n=>{if(n.subject!==t.identityKey)throw Error(`The subject of one of your certificates ("${n.subject}") is not the same as the request sender ("${t.identityKey}").`);let s=new nX(n.type,n.serialNumber,n.subject,n.certifier,n.revocationOutpoint,n.fields,n.keyring,n.signature);if(!await s.verify())throw Error(`The signature for the certificate with serial number ${s.serialNumber} is invalid!`);if(null!=i){let{certifiers:e,types:t}=i;if(!e.includes(s.certifier))throw Error(`Certificate with serial number ${s.serialNumber} has an unrequested certifier: ${s.certifier}`);if(null==t[s.type])throw Error(`Certificate with type ${s.type} was not requested`)}await s.decryptFields(e,void 0,void 0,r)}))},n2="u"<typeof globalThis?void 0:globalThis.Buffer;class n8{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;certificateValidationPromises=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;originator;identityPublicKey;ready;constructor(e,t,i,r,n,s){this.wallet=e,this.originator=s,this.transport=t,this.certificatesToRequest=i??{certifiers:[],types:{}},this.ready=this.transport.onData(this.handleIncomingMessage.bind(this)),this.sessionManager=r??new nJ,!1===n?this.autoPersistLastSession=!1:this.autoPersistLastSession=!0}async toPeer(e,t){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);let i=await this.getAuthenticatedSession(t);if(null==i.peerIdentityKey)throw Error("Peer identity is not established");if(!0===i.certificatesRequired&&!0!==i.certificatesValidated)throw Error("Cannot send general message before certificate validation is complete");let r=tS(ia(32)),{signature:n}=await this.wallet.createSignature({data:e,protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),s={version:"0.1",messageType:"general",identityKey:await this.getIdentityPublicKey(),nonce:r,yourNonce:i.peerNonce,payload:e,signature:n};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}async requestCertificates(e,t){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);let i=await this.getAuthenticatedSession(t),r=tS(ia(32)),{signature:n}=await this.wallet.createSignature({data:n8.utf8ToBytes(JSON.stringify(e)),protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),s={version:"0.1",messageType:"certificateRequest",identityKey:await this.getIdentityPublicKey(),nonce:r,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,requestedCertificates:e,signature:n};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}async getAuthenticatedSession(e){let t;if(void 0===this.transport)throw Error("Peer transport is not connected!");if("string"==typeof e&&(t=this.sessionManager.getSession(e)),t?.isAuthenticated!==!0){let i=await this.initiateHandshake(e);if(t=this.sessionManager.getSession(i),t?.isAuthenticated!==!0)throw Error("Unable to establish mutual authentication with peer!")}return t}listenForGeneralMessages(e){let t=this.callbackIdCounter++;return this.onGeneralMessageReceivedCallbacks.set(t,e),t}stopListeningForGeneralMessages(e){this.onGeneralMessageReceivedCallbacks.delete(e)}listenForCertificatesReceived(e){let t=this.callbackIdCounter++;return this.onCertificatesReceivedCallbacks.set(t,e),t}stopListeningForCertificatesReceived(e){this.onCertificatesReceivedCallbacks.delete(e)}listenForCertificatesRequested(e){let t=this.callbackIdCounter++;return this.onCertificateRequestReceivedCallbacks.set(t,e),t}stopListeningForCertificatesRequested(e){this.onCertificateRequestReceivedCallbacks.delete(e)}async initiateHandshake(e){let t=await nQ(this.wallet,void 0,this.originator),i=Date.now(),r=this.certificatesToRequest.certifiers.length>0;this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:t,peerIdentityKey:e,lastUpdate:i,certificatesRequired:r,certificatesValidated:!r});let n={version:"0.1",messageType:"initialRequest",identityKey:await this.getIdentityPublicKey(),initialNonce:t,requestedCertificates:this.certificatesToRequest};return await this.transport.send(n),await this.waitForInitialResponse(t)}async waitForInitialResponse(e){return await new Promise(t=>{let i=this.listenForInitialResponse(e,e=>{this.stopListeningForInitialResponses(i),t(e)})})}listenForInitialResponse(e,t){let i=this.callbackIdCounter++;return this.onInitialResponseReceivedCallbacks.set(i,{callback:t,sessionNonce:e}),i}stopListeningForInitialResponses(e){this.onInitialResponseReceivedCallbacks.delete(e)}propagateTransportError(e,t){if(t instanceof Error){if(null!=e){let i=t.details;null!=i&&"object"==typeof i?i.peerIdentityKey??=e:t.details={peerIdentityKey:e}}throw t}throw Error(`Failed to send message to peer ${e??"unknown"}: ${String(t)}`)}async handleIncomingMessage(e){if("string"!=typeof e.version||"0.1"!==e.version)throw Error(`Invalid or unsupported message auth version! Received: ${e.version}, expected: 0.1`);switch(e.messageType){case"initialRequest":await this.processInitialRequest(e);break;case"initialResponse":await this.processInitialResponse(e);break;case"certificateRequest":await this.processCertificateRequest(e);break;case"certificateResponse":await this.processCertificateResponse(e);break;case"general":await this.processGeneralMessage(e);break;default:throw Error(`Unknown message type of ${String(e.messageType)} from ${String(e.identityKey)}`)}}async processInitialRequest(e){let t;if("string"!=typeof e.identityKey||"string"!=typeof e.initialNonce||""===e.initialNonce)throw Error("Missing required fields in initialRequest message.");let i=await nQ(this.wallet,void 0,this.originator),r=Date.now(),n=Array.isArray(this.certificatesToRequest?.certifiers)&&this.certificatesToRequest.certifiers.length>0;this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:i,peerNonce:e.initialNonce,peerIdentityKey:e.identityKey,lastUpdate:r,certificatesRequired:n,certificatesValidated:!n}),Array.isArray(e.requestedCertificates?.certifiers)&&e.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)}):t=await n0(this.wallet,e.requestedCertificates,e.identityKey,this.originator));let{signature:s}=await this.wallet.createSignature({data:[...n8.base64ToBytes(e.initialNonce),...n8.base64ToBytes(i)],protocolID:[2,"auth message signature"],keyID:`${e.initialNonce} ${i}`,counterparty:e.identityKey},this.originator),a={version:"0.1",messageType:"initialResponse",identityKey:await this.getIdentityPublicKey(),initialNonce:i,yourNonce:e.initialNonce,certificates:t,requestedCertificates:this.certificatesToRequest,signature:s};this.lastInteractedWithPeer??=e.identityKey,await this.transport.send(a)}async processInitialResponse(e){if(!await nZ(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Initial response nonce verification failed from peer: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Peer session not found for peer: ${e.identityKey}`);let i=n8.base64ToBytes((t.sessionNonce??"")+(e.initialNonce??"")),{valid:r}=await this.wallet.verifySignature({data:i,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${t.sessionNonce??""} ${e.initialNonce??""}`,counterparty:e.identityKey},this.originator);if(!r)throw Error(`Unable to verify initial response signature for peer: ${e.identityKey}`);if(t.peerNonce=e.initialNonce,t.peerIdentityKey=e.identityKey,t.isAuthenticated=!0,t.certificatesRequired=Array.isArray(this.certificatesToRequest?.certifiers)&&this.certificatesToRequest.certifiers.length>0,t.certificatesValidated=!t.certificatesRequired,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),t.certificatesRequired&&Array.isArray(e.certificates)&&e.certificates.length>0&&(await n1(this.wallet,e,this.certificatesToRequest,this.originator),t.certificatesValidated=!0,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),null!=t.sessionNonce&&this.resolveCertificateValidation(t.sessionNonce),this.onCertificatesReceivedCallbacks.forEach(t=>t(e.identityKey,e.certificates))),this.lastInteractedWithPeer=e.identityKey,this.onInitialResponseReceivedCallbacks.forEach(e=>{e.sessionNonce===t.sessionNonce&&e.callback(t.sessionNonce)}),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)});else{let t=await n0(this.wallet,e.requestedCertificates,e.identityKey,this.originator);t.length>0&&await this.sendCertificateResponse(e.identityKey,t)}}async processCertificateRequest(e){if(!await nZ(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for certificate request message from: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let{valid:i}=await this.wallet.verifySignature({data:n8.utf8ToBytes(JSON.stringify(e.requestedCertificates)),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!i)throw Error(`Invalid signature in certificate request message from ${t.peerIdentityKey}`);if(t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)});else{let t=await n0(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async sendCertificateResponse(e,t){let i=await this.getAuthenticatedSession(e),r=tS(ia(32)),{signature:n}=await this.wallet.createSignature({data:n8.utf8ToBytes(JSON.stringify(t)),protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),s={version:"0.1",messageType:"certificateResponse",identityKey:await this.getIdentityPublicKey(),nonce:r,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,certificates:t,signature:n};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}async processCertificateResponse(e){if(!await nZ(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for certificate response from: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let{valid:i}=await this.wallet.verifySignature({data:n8.utf8ToBytes(JSON.stringify(e.certificates)),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:e.identityKey},this.originator);if(!i)throw Error(`Unable to verify certificate response signature for peer: ${e.identityKey}`);Array.isArray(e.certificates)&&e.certificates.length>0&&(await n1(this.wallet,e,e.requestedCertificates,this.originator),t.certificatesValidated=!0,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),null!=t.sessionNonce&&this.resolveCertificateValidation(t.sessionNonce)),this.onCertificatesReceivedCallbacks.forEach(t=>{t(e.identityKey,e.certificates??[])})}async processGeneralMessage(e){if(!await nZ(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for general message from: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let i=!0===t.certificatesRequired,r=!0===t.certificatesValidated;if(i&&!r){let e=t.sessionNonce;if(null==e)throw Error("Session nonce is required for certificate validation");await new Promise((i,r)=>{let n=setTimeout(()=>{null!=this.certificateValidationPromises.get(e)&&(this.certificateValidationPromises.delete(e),r(Error(`Timeout waiting for certificate validation from peer ${t.peerIdentityKey??"unknown"}`)))},3e4);"object"==typeof n&&"unref"in n&&n.unref(),this.certificateValidationPromises.set(e,{resolve:()=>{clearTimeout(n),i()},reject:e=>{clearTimeout(n),r(e)}})})}let{valid:n}=await this.wallet.verifySignature({data:e.payload,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!n)throw Error(`Invalid signature in generalMessage from ${t.peerIdentityKey}`);t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.lastInteractedWithPeer=e.identityKey,this.onGeneralMessageReceivedCallbacks.forEach(t=>{t(e.identityKey,e.payload??[])})}resolveCertificateValidation(e){let t=this.certificateValidationPromises.get(e);null!=t&&(t.resolve(),this.certificateValidationPromises.delete(e))}async getIdentityPublicKey(){if(null!=this.identityPublicKey)return this.identityPublicKey;let{publicKey:e}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return this.identityPublicKey=e,e}static utf8ToBytes(e){return null!=n2?Array.from(n2.from(e,"utf8")):"u">typeof TextEncoder?Array.from(new TextEncoder().encode(e)):tm(e,"utf8")}static base64ToBytes(e){return null!=n2?Array.from(n2.from(e,"base64")):tm(e,"base64")}}let n3="u">typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch;class n5{onDataCallback;fetchClient;baseUrl;constructor(e,t=n3){if("function"!=typeof t)throw TypeError("SimplifiedFetchTransport requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=t,this.baseUrl=e}async send(e){if(null==this.onDataCallback)throw Error("Listen before you start speaking. God gave you two ears and one mouth for a reason.");if("general"!==e.messageType)return await new Promise((t,i)=>{(async()=>{try{let i=`${this.baseUrl}/.well-known/auth`,r=(async()=>{try{return await this.fetchClient(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(e){throw this.createNetworkError(i,e)}})();"initialRequest"!==e.messageType&&t();let n=await r;if(!n.ok){let e=Array.from(new Uint8Array(await n.arrayBuffer()));throw this.createUnauthenticatedResponseError(i,n,e)}if(null!=this.onDataCallback){let e=await n.json();this.onDataCallback(e)}"initialRequest"===e.messageType&&t()}catch(e){i(e)}})()});{let t,i,r=this.deserializeRequestPayload(e.payload),n=`${this.baseUrl}${r.urlPostfix}`;if("object"!=typeof r.headers&&(r.headers={}),r.headers["x-bsv-auth-version"]=e.version,r.headers["x-bsv-auth-identity-key"]=e.identityKey,r.headers["x-bsv-auth-nonce"]=e.nonce,r.headers["x-bsv-auth-your-nonce"]=e.yourNonce,r.headers["x-bsv-auth-signature"]=tg(e.signature),r.headers["x-bsv-auth-request-id"]=r.requestId,null!=r.body){let e=r.headers;if(null==e["content-type"])throw Error("Content-Type header is required for requests with a body.");let t=String(e["content-type"]??"");t.includes("application/json")||t.includes("application/x-www-form-urlencoded")||t.includes("text/plain")?r.body=tI(r.body):r.body=new Uint8Array(r.body)}try{t=await this.fetchClient(n,{method:r.method,headers:r.headers,body:r.body})}catch(e){throw this.createNetworkError(n,e)}let s=Array.from(new Uint8Array(await t.arrayBuffer())),a=["x-bsv-auth-version","x-bsv-auth-identity-key","x-bsv-auth-signature"].filter(e=>{let i=t.headers.get(e);return null==i||0===i.trim().length});if(a.length>0)throw this.createUnauthenticatedResponseError(n,t,s,a);let o=t.headers.get("x-bsv-auth-requested-certificates");if(null!=o)try{i=JSON.parse(o)}catch(e){throw this.createMalformedHeaderError(n,"x-bsv-auth-requested-certificates",o,e)}let l=new tP;null!=t.headers.get("x-bsv-auth-request-id")&&l.write(tm(t.headers.get("x-bsv-auth-request-id"),"base64")),l.writeVarIntNum(t.status);let c=[];for(let[e,i]of(t.headers.forEach((e,t)=>{let i=t.toLowerCase();(i.startsWith("x-bsv-")||"authorization"===i)&&!i.startsWith("x-bsv-auth")&&c.push([i,e])}),c.sort(([e],[t])=>e.localeCompare(t)),l.writeVarIntNum(c.length),c)){let t=tm(e,"utf8");l.writeVarIntNum(t.length),l.write(t);let r=tm(i,"utf8");l.writeVarIntNum(r.length),l.write(r)}l.writeVarIntNum(s.length),s.length>0&&l.write(s);let h={version:t.headers.get("x-bsv-auth-version"),messageType:"certificateRequest"===t.headers.get("x-bsv-auth-message-type")?"certificateRequest":"general",identityKey:t.headers.get("x-bsv-auth-identity-key"),nonce:t.headers.get("x-bsv-auth-nonce")??void 0,yourNonce:t.headers.get("x-bsv-auth-your-nonce")??void 0,requestedCertificates:i,payload:l.toArray(),signature:tm(t.headers.get("x-bsv-auth-signature"),"hex")};if(null==h.version)throw this.createUnauthenticatedResponseError(n,t,s);this.onDataCallback(h)}}async onData(e){this.onDataCallback=t=>{e(t).catch(()=>{})}}createNetworkError(e,t){let i=`Network error while sending authenticated request to ${e}`;if(t instanceof Error){let e=Error(`${i}: ${t.message}`);return e.stack=t.stack,e.cause=t,e}return Error(`${i}: ${String(t)}`)}createUnauthenticatedResponseError(e,t,i,r=[]){let n=(t.statusText??"").trim(),s=n.length>0?`${t.status} ${n}`:`${t.status}`,a=r.length>0?`missing headers: ${r.join(", ")}`:"response lacked required BSV auth headers",o=this.getBodyPreview(i,t.headers.get("content-type")),l=[`Received HTTP ${s} from ${e} without valid BSV authentication (${a})`];null!=o&&l.push(`body preview: ${o}`);let c=Error(l.join(" - "));return c.details={url:e,status:t.status,statusText:t.statusText,missingHeaders:r,bodyPreview:o},c}createMalformedHeaderError(e,t,i,r){let n=`Failed to parse ${t} returned by ${e}: ${i}`;if(r instanceof Error){let e=Error(`${n}. ${r.message}`);return e.stack=r.stack,e.cause=r,e}return Error(`${n}. ${String(r)}`)}getBodyPreview(e,t){let i;if(0===e.length)return;let r=e.length>1024,n=r?e.slice(0,1024):e;if(this.isTextualContent(t,n))try{i=tI(n)}catch{i=this.formatBinaryPreview(n,r)}else i=this.formatBinaryPreview(n,r);return i.length>512&&(i=`${i.slice(0,512)}…`),r&&(i=`${i} (truncated)`),i}isTextualContent(e,t){if(0===t.length)return!1;if(null!=e){let t=e.toLowerCase();if(["application/json","application/problem+json","application/xml","application/xhtml+xml","application/javascript","application/ecmascript","application/x-www-form-urlencoded","text/"].some(e=>t.includes(e))||t.includes("charset="))return!0}return t.reduce((e,t)=>9===t||10===t||13===t||t>=32&&t<=126?e+1:e,0)/t.length>.8}formatBinaryPreview(e,t){let i=e.map(e=>e.toString(16).padStart(2,"0")).join("");return`0x${i}${t?"…":""}`}deserializeRequestPayload(e){let t,i=new tN(e),r=tS(i.read(32)),n=i.readVarIntNum(),s="GET";n>0&&(s=tI(i.read(n)));let a=i.readVarIntNum(),o="";a>0&&(o=tI(i.read(a)));let l=i.readVarIntNum(),c="";l>0&&(c=tI(i.read(l)));let h={},d=i.readVarIntNum();if(d>0)for(let e=0;e<d;e++){let e=i.readVarIntNum(),t=tI(i.read(e)),r=i.readVarIntNum(),n=tI(i.read(r));h[t]=n}let u=i.readVarIntNum();return u>0&&(t=i.read(u)),{urlPostfix:o+c,method:s,headers:h,body:t,requestId:r}}}class n6{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;originator;peers={};constructor(e,t,i,r){this.wallet=e,this.requestedCertificates=t,this.sessionManager=i??new nJ,this.originator=r}async fetch(e,t={}){if("number"==typeof t.retryCounter){if(t.retryCounter<=0)throw Error("Request failed after maximum number of retries.");t.retryCounter--}let i=await new Promise(async(i,r)=>{try{let n,{method:s="GET",headers:a={},body:o}=t,l=new URL(e),c=l.origin;if(void 0===this.peers[c]){let e=new n5(c),t=new n8(this.wallet,e,this.requestedCertificates,this.sessionManager,void 0,this.originator);await t.ready,n={peer:t,pendingCertificateRequests:[]},this.peers[c]=n,this.peers[c].peer.listenForCertificatesReceived((e,t)=>{this.certificatesReceived.push(...t)}),this.peers[c].peer.listenForCertificatesRequested(async(e,t)=>{try{this.peers[c].pendingCertificateRequests.push(!0);let i=await n0(this.wallet,t,e,this.originator);i.length>0&&await this.peers[c].peer.sendCertificateResponse(e,i)}finally{await new Promise(e=>setTimeout(e,500)),this.peers[c].pendingCertificateRequests.shift()}})}else{if(!1===this.peers[c].supportsMutualAuth){try{let r=await this.handleFetchAndValidate(e,t,this.peers[c]);i(r)}catch(e){r(e)}return}n=this.peers[c]}let h=ia(32),d=tS(h),u=await this.serializeRequest(s,a,o,l,h);this.callbacks[d]={resolve:i,reject:r};let f=n.peer.listenForGeneralMessages((e,t)=>{let i,r=new tN(t);if(tS(r.read(32))!==d)return;n.peer.stopListeningForGeneralMessages(f),this.peers[c].identityKey=e,this.peers[c].supportsMutualAuth=!0;let s=r.readVarIntNum(),a={},o=r.readVarIntNum();if(o>0)for(let e=0;e<o;e++){let e=r.readVarIntNum(),t=r.read(e),i=tI(t),n=r.readVarIntNum(),s=r.read(n),o=tI(s);a[i]=o}a["x-bsv-auth-identity-key"]=e;let l=r.readVarIntNum();l>0&&(i=r.read(l));let h=new Response(i?new Uint8Array(i):null,{status:s,statusText:`${s}`,headers:new Headers(a)});this.callbacks[d].resolve(h),delete this.callbacks[d]});n.pendingCertificateRequests.length>0&&await new Promise((e,t)=>{let i=Date.now(),r=()=>{0===n.pendingCertificateRequests.length?e():Date.now()-i>3e4?t(Error("Timeout waiting for certificate request to complete")):setTimeout(r,100)};r()}),await n.peer.toPeer(u.toArray(),n.identityKey).catch(async s=>{if(s.message.includes("Session not found for nonce")||s.message.includes("without valid BSV authentication")&&null!=n.identityKey&&s.details?.status===401){delete this.peers[c],t.retryCounter??=3;let r=await this.fetch(e,t);i(r);return}if(s.message.includes("HTTP server failed to authenticate"))try{let r=await this.handleFetchAndValidate(e,t,n);i(r);return}catch(e){r(e)}else r(s)})}catch(e){r(e)}});return 402===i.status?await this.handlePaymentAndRetry(e,t,i):i}async sendCertificateRequest(e,t){let i,r=new URL(e).origin;if(void 0===this.peers[r]){let e=new n5(r),t=new n8(this.wallet,e,this.requestedCertificates,this.sessionManager,this.originator);await t.ready,i={peer:t},this.peers[r]=i}else i={peer:this.peers[r].peer};return await new Promise(async(e,n)=>{let s=!1,a=()=>{s=!0,clearTimeout(l),i.peer.stopListeningForCertificatesReceived(o)},o=i.peer.listenForCertificatesReceived((t,i)=>{s||(a(),this.certificatesReceived.push(...i),e(i))}),l=setTimeout(()=>{s||(a(),n(Error(`sendCertificateRequest timed out after 30000ms waiting for certificate response from ${r}`)))},3e4);try{await i.peer.requestCertificates(t,i.identityKey)}catch(e){s||(a(),n(e))}})}consumeReceivedCertificates(){return this.certificatesReceived.splice(0)}async serializeRequest(e,t,i,r,n){let s=new tP;if(s.write(n),s.writeVarIntNum(e.length),s.write(tm(e)),r.pathname.length>0){let e=tm(r.pathname);s.writeVarIntNum(e.length),s.write(e)}else s.writeVarIntNum(-1);if(r.search.length>0){let e=tm(r.search);s.writeVarIntNum(e.length),s.write(e)}else s.writeVarIntNum(-1);let a=[];for(let[e,i]of Object.entries(t))if((e=e.toLowerCase()).startsWith("x-bsv-")||"authorization"===e){if(e.startsWith("x-bsv-auth"))throw Error("No BSV auth headers allowed here!");a.push([e,i])}else if(e.startsWith("content-type"))i=i.split(";")[0].trim(),a.push([e,i]);else throw Error("Unsupported header in the simplified fetch implementation. Only content-type, authorization, and x-bsv-* headers are supported.");for(let[e,t]of(a.sort(([e],[t])=>e.localeCompare(t)),s.writeVarIntNum(a.length),a)){let i=tm(e,"utf8");s.writeVarIntNum(i.length),s.write(i);let r=tm(t,"utf8");s.writeVarIntNum(r.length),s.write(r)}if(["POST","PUT","PATCH","DELETE"].includes(e.toUpperCase())&&void 0===i){let e=a.find(([e])=>"content-type"===e);i=e?.[1].includes("application/json")===!0?"{}":""}if(i){let e=await this.normalizeBodyToNumberArray(i);s.writeVarIntNum(e.length),s.write(e)}else s.writeVarIntNum(-1);return s}async handleFetchAndValidate(e,t,i){let r=await fetch(e,t);if(r.headers.forEach(e=>{if(e.toLocaleLowerCase().startsWith("x-bsv"))throw Error("The server is trying to claim it has been authenticated when it has not!")}),r.ok)return i.supportsMutualAuth=!1,r;throw Error(`Request failed with status: ${r.status}`)}async handlePaymentAndRetry(e,t={},i){let r=i.headers.get("x-bsv-payment-version");if(!r||"1.0"!==r)throw Error(`Unsupported x-bsv-payment-version response header. Client version: 1.0, Server version: ${r}`);let n=i.headers.get("x-bsv-payment-satoshis-required");if(!n)throw Error("Missing x-bsv-payment-satoshis-required response header.");let s=Number.parseInt(n);if(Number.isNaN(s)||s<=0)throw Error("Invalid x-bsv-payment-satoshis-required response header value.");let a=i.headers.get("x-bsv-auth-identity-key");if("string"!=typeof a)throw TypeError("Missing x-bsv-auth-identity-key response header.");let o=i.headers.get("x-bsv-payment-derivation-prefix");if("string"!=typeof o||o.length<1)throw Error("Missing x-bsv-payment-derivation-prefix response header.");let l=t.paymentContext;if(null==l?l=await this.createPaymentContext(e,t,s,a,o):this.isPaymentContextCompatible(l,s,a,o)||(this.logPaymentAttempt("warn","Server adjusted payment requirements; regenerating transaction",this.composePaymentLogDetails(e,l)),l=await this.createPaymentContext(e,t,s,a,o)),l.attempts>=l.maxAttempts)throw this.buildPaymentFailureError(e,l,Error("Maximum payment attempts exceeded before retrying"));let c={...t.headers};c["x-bsv-payment"]=JSON.stringify({derivationPrefix:l.derivationPrefix,derivationSuffix:l.derivationSuffix,transaction:l.transactionBase64});let h={...t,headers:c,paymentContext:l};"number"!=typeof h.retryCounter&&(h.retryCounter=3);let d=l.attempts+1,u=l.maxAttempts;l.attempts=d;let f=this.composePaymentLogDetails(e,l);this.logPaymentAttempt("warn",`Attempting paid request (${d}/${u})`,f);try{let t=await this.fetch(e,h);return this.logPaymentAttempt("info",`Paid request attempt ${d} succeeded`,f),t}catch(n){let t=this.createPaymentErrorEntry(l.attempts,n);if(l.errors.push(t),this.logPaymentAttempt("error",`Paid request attempt ${d} failed`,{...f,error:{message:t.message,stack:t.stack}}),l.attempts>=l.maxAttempts)throw this.buildPaymentFailureError(e,l,n);let r=this.getPaymentRetryDelay(l.attempts);return await this.wait(r),this.handlePaymentAndRetry(e,h,i)}}isPaymentContextCompatible(e,t,i,r){return e.satoshisRequired===t&&e.serverIdentityKey===i&&e.derivationPrefix===r}async createPaymentContext(e,t,i,r,n){let s=await nQ(this.wallet,void 0,this.originator),{publicKey:a}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${n} ${s}`,counterparty:r},this.originator),o=new i3().lock(ii.fromString(a).toAddress()).toHex(),{tx:l}=await this.wallet.createAction({description:`Payment for request to ${new URL(e).origin}`,outputs:[{satoshis:i,lockingScript:o,customInstructions:JSON.stringify({derivationPrefix:n,derivationSuffix:s,payee:r}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}},this.originator),{publicKey:c}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return{satoshisRequired:i,transactionBase64:tS(l),derivationPrefix:n,derivationSuffix:s,serverIdentityKey:r,clientIdentityKey:c,attempts:0,maxAttempts:this.getMaxPaymentAttempts(t),errors:[],requestSummary:this.buildPaymentRequestSummary(e,t)}}getMaxPaymentAttempts(e){let t="number"==typeof e.paymentRetryAttempts?e.paymentRetryAttempts:void 0;return"number"==typeof t&&t>0?Math.floor(t):3}buildPaymentRequestSummary(e,t){let i={...t.headers},r="string"==typeof t.method?t.method.toUpperCase():"GET",n=this.describeRequestBodyForLogging(t.body);return{url:e,method:r,headers:i,bodyType:n.type,bodyByteLength:n.byteLength}}describeRequestBodyForLogging(e){if(null==e)return{type:"none",byteLength:0};if("string"==typeof e)return{type:"string",byteLength:tm(e,"utf8").length};if(Array.isArray(e))return e.every(e=>"number"==typeof e)?{type:"number[]",byteLength:e.length}:{type:"array",byteLength:e.length};if("u">typeof ArrayBuffer&&e instanceof ArrayBuffer)return{type:"ArrayBuffer",byteLength:e.byteLength};if("u">typeof ArrayBuffer&&ArrayBuffer.isView(e))return{type:null==e.constructor?"TypedArray":e.constructor.name,byteLength:e.byteLength};if("u">typeof Blob&&e instanceof Blob)return{type:"Blob",byteLength:e.size};if("u">typeof FormData&&e instanceof FormData)return{type:"FormData",byteLength:0};if("u">typeof URLSearchParams&&e instanceof URLSearchParams)return{type:"URLSearchParams",byteLength:tm(e.toString(),"utf8").length};if("u">typeof ReadableStream&&e instanceof ReadableStream)return{type:"ReadableStream",byteLength:0};try{let t=JSON.stringify(e);if("string"==typeof t)return{type:"object",byteLength:tm(t,"utf8").length}}catch(e){}return{type:typeof e,byteLength:0}}composePaymentLogDetails(e,t){return{url:e,request:t.requestSummary,payment:{satoshis:t.satoshisRequired,transactionBase64:t.transactionBase64,derivationPrefix:t.derivationPrefix,derivationSuffix:t.derivationSuffix,serverIdentityKey:t.serverIdentityKey,clientIdentityKey:t.clientIdentityKey},attempts:{used:t.attempts,max:t.maxAttempts},errors:t.errors}}logPaymentAttempt(e,t,i){let r="[AuthFetch][Payment]";"error"===e?console.error(`${r} ${t}`,i):"warn"===e?console.warn(`${r} ${t}`,i):"function"==typeof console.info?console.info(`${r} ${t}`,i):console.log(`${r} ${t}`,i)}createPaymentErrorEntry(e,t){let i={attempt:e,timestamp:new Date().toISOString(),message:"",stack:void 0};return t instanceof Error?(i.message=t.message,i.stack=t.stack??void 0):i.message=String(t),i}getPaymentRetryDelay(e){return 250*Math.min(e,5)}async wait(e){e<=0||await new Promise(t=>setTimeout(t,e))}buildPaymentFailureError(e,t,i){let r=Error(`Paid request to ${e} failed after ${t.attempts}/${t.maxAttempts} attempts. Sent ${t.satoshisRequired} satoshis to ${t.serverIdentityKey}.`);return r.details={request:t.requestSummary,payment:{satoshis:t.satoshisRequired,transactionBase64:t.transactionBase64,derivationPrefix:t.derivationPrefix,derivationSuffix:t.derivationSuffix,serverIdentityKey:t.serverIdentityKey,clientIdentityKey:t.clientIdentityKey},attempts:{used:t.attempts,max:t.maxAttempts},errors:t.errors},i instanceof Error&&(r.cause=i),r}async normalizeBodyToNumberArray(e){if(null==e)return[];if("object"==typeof e)return tm(JSON.stringify(e,"utf8"));if(Array.isArray(e)&&e.every(e=>"number"==typeof e))return e;if("string"==typeof e)return tm(e,"utf8");if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Array.from(new Uint8Array(e instanceof ArrayBuffer?e:e.buffer));if(e instanceof Blob)return Array.from(new Uint8Array(await e.arrayBuffer()));if(e instanceof FormData){let t=[];return e.forEach((e,i)=>{t.push([i,e.toString()])}),tm(new URLSearchParams(t).toString(),"utf8")}if(e instanceof URLSearchParams)return tm(e.toString(),"utf8");if(e instanceof ReadableStream)throw TypeError("ReadableStream cannot be directly converted to number[].");throw Error("Unsupported body type in this SimplifiedFetch implementation.")}}class n4{pushDrop;static decode(e){let t=i4.decode(e);if(t.fields.length<4)throw Error("Invalid SHIP/SLAP advertisement!");let i=tI(t.fields[0]);if("SHIP"!==i&&"SLAP"!==i)throw Error("Invalid protocol type!");let r=tg(t.fields[1]);return{protocol:i,identityKey:r,domain:tI(t.fields[2]),topicOrService:tI(t.fields[3])}}constructor(e,t){this.pushDrop=new i4(e,t)}async lock(e,t,i){let{publicKey:r}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([tm(e,"utf8"),tm(r,"hex"),tm(t,"utf8"),tm(i,"utf8")],[2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}unlock(e){return this.pushDrop.unlock([2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}}let n9="bsvsdk_overlay_host_reputation_v1";class n7{stats;store;constructor(e){this.stats=new Map,this.store=e??this.getLocalStorageAdapter(),this.loadFromStorage()}reset(){this.stats.clear()}recordSuccess(e,t){let i=this.getOrCreate(e),r=Date.now(),n=Number.isFinite(t)&&t>=0?t:1500;null===i.avgLatencyMs?i.avgLatencyMs=n:i.avgLatencyMs=.75*i.avgLatencyMs+.25*n,i.lastLatencyMs=n,i.totalSuccesses+=1,i.consecutiveFailures=0,i.backoffUntil=0,i.lastUpdatedAt=r,i.lastError=void 0,this.saveToStorage()}recordFailure(e,t){let i,r=this.getOrCreate(e),n=Date.now();r.totalFailures+=1,r.consecutiveFailures+=1,"string"==typeof(i="string"==typeof t?t:t instanceof Error?t.message:void 0)&&(i.includes("ERR_NAME_NOT_RESOLVED")||i.includes("ENOTFOUND")||i.includes("getaddrinfo")||i.includes("Failed to fetch"))&&r.consecutiveFailures<3&&(r.consecutiveFailures=3);let s=Math.max(r.consecutiveFailures-2,0);0===s?r.backoffUntil=0:r.backoffUntil=n+Math.min(6e4,1e3*Math.pow(2,s-1)),r.lastUpdatedAt=n,"string"==typeof t?r.lastError=t:t instanceof Error?r.lastError=t.message:r.lastError=void 0,this.saveToStorage()}rankHosts(e,t=Date.now()){let i=new Map;e.forEach((e,t)=>{"string"==typeof e&&0!==e.length&&(i.has(e)||i.set(e,t))});let r=Array.from(i.keys()).map(e=>{let r=this.getOrCreate(e);return{...r,score:this.computeScore(r,t),originalOrder:i.get(e)??0}});return r.sort((e,i)=>{let r=e.backoffUntil>t;return r!==i.backoffUntil>t?r?1:-1:e.score!==i.score?e.score-i.score:e.totalSuccesses!==i.totalSuccesses?i.totalSuccesses-e.totalSuccesses:e.originalOrder-i.originalOrder}),r.map(({originalOrder:e,...t})=>t)}snapshot(e){let t=this.stats.get(e);return null==t?void 0:{...t}}getStorage(){try{let e="object"==typeof globalThis?globalThis:void 0;if(e?.localStorage==null)return;return e.localStorage}catch{return}}getLocalStorageAdapter(){let e=this.getStorage();if(null!=e)return{get:t=>{try{return e.getItem(t)}catch{return null}},set:(t,i)=>{try{e.setItem(t,i)}catch{}}}}loadFromStorage(){let e=this.store;if(null!=e)try{let t=e.get(n9);if("string"!=typeof t||0===t.length)return;let i=JSON.parse(t);if("object"!=typeof i||null===i)return;for(let e of(this.stats.clear(),Object.keys(i))){let t=i[e];if(null!=t&&"object"==typeof t){let i={host:String(t.host??e),totalSuccesses:Number(t.totalSuccesses??0),totalFailures:Number(t.totalFailures??0),consecutiveFailures:Number(t.consecutiveFailures??0),avgLatencyMs:null==t.avgLatencyMs?null:Number(t.avgLatencyMs),lastLatencyMs:null==t.lastLatencyMs?null:Number(t.lastLatencyMs),backoffUntil:Number(t.backoffUntil??0),lastUpdatedAt:Number(t.lastUpdatedAt??0),lastError:"string"==typeof t.lastError?t.lastError:void 0};this.stats.set(i.host,i)}}}catch{}}saveToStorage(){let e=this.store;if(null!=e)try{let t={};for(let[e,i]of this.stats.entries())t[e]=i;e.set(n9,JSON.stringify(t))}catch{}}computeScore(e,t){let i=e.avgLatencyMs??1500,r=400*e.consecutiveFailures,n=Math.min(30*e.totalSuccesses,i/2);return i+r+(e.backoffUntil>t?e.backoffUntil-t:0)-n}getOrCreate(e){let t=this.stats.get(e);return null==t&&(t={host:e,totalSuccesses:0,totalFailures:0,consecutiveFailures:0,avgLatencyMs:null,lastLatencyMs:null,backoffUntil:0,lastUpdatedAt:0},this.stats.set(e,t)),t}}let se=new n7,st="u">typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch,si=["https://overlay-us-1.bsvb.tech","https://overlay-eu-1.bsvb.tech","https://overlay-ap-1.bsvb.tech","https://users.bapp.dev"],sr=["https://testnet-users.bapp.dev"];class sn{fetchClient;allowHTTP;constructor(e=st,t=!1){if("function"!=typeof e)throw TypeError("HTTPSOverlayLookupFacilitator requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=e,this.allowHTTP=t}async lookup(e,t,i=2e3){if(!e.startsWith("https:")&&!this.allowHTTP)throw Error('HTTPS facilitator can only use URLs that start with "https:"');let r="u"<typeof AbortController?void 0:new AbortController,n=setTimeout(()=>{try{r?.abort()}catch{}},i);try{let i={method:"POST",headers:{"Content-Type":"application/json","X-Aggregation":"yes"},body:JSON.stringify({service:t.service,query:t.query}),signal:r?.signal},n=await this.fetchClient(`${e}/lookup`,i);if(!n.ok)throw Error(`Failed to facilitate lookup (HTTP ${n.status})`);if("application/octet-stream"===n.headers.get("content-type"))return await this.parseOctetStreamLookup(n);return await n.json()}catch(e){if(e?.name==="AbortError")throw Error("Request timed out");throw e}finally{clearTimeout(n)}}async parseOctetStreamLookup(e){let t=new tN([...new Uint8Array(await e.arrayBuffer())]),i=t.readVarIntNum(),r=[];for(let e=0;e<i;e++){let e=tg(t.read(32)),i=t.readVarIntNum(),n=t.readVarIntNum(),s=n>0?t.read(n):void 0;r.push({txid:e,outputIndex:i,context:s})}let n=t.read(),s=rp.fromBinary(n);return{type:"output-list",outputs:await this.extractAtomicOutputs(r,s)}}async extractAtomicOutputs(e,t){let i=new Map,r=Array(e.length);for(let n=0;n<e.length;n++){let s=e[n],a=i.get(s.txid);void 0===a&&(a=t.toBinaryAtomic(s.txid),i.set(s.txid,a)),r[n]={outputIndex:s.outputIndex,context:s.context,beef:a,txid:s.txid},n>0&&n<e.length-1&&await new Promise(e=>setTimeout(e,0))}return r}}class ss{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;hostReputation;hostsCache;hostsInFlight;hostsTtlMs;hostsMaxEntries;txMemo;txMemoTtlMs;constructor(e={}){this.networkPreset=e.networkPreset??"mainnet",this.facilitator=e.facilitator??new sn(void 0,"local"===this.networkPreset),this.slapTrackers=e.slapTrackers??("mainnet"===this.networkPreset?si:sr);const t=e.hostOverrides??{};this.assertValidOverrideServices(t),this.hostOverrides=t,this.additionalHosts=e.additionalHosts??{};const i=e.reputationStorage;"localStorage"===i?this.hostReputation=new n7:"object"==typeof i&&null!==i&&"function"==typeof i.get&&"function"==typeof i.set?this.hostReputation=new n7(i):this.hostReputation=se,this.hostsTtlMs=e.cache?.hostsTtlMs??3e5,this.hostsMaxEntries=e.cache?.hostsMaxEntries??128,this.txMemoTtlMs=e.cache?.txMemoTtlMs??6e5,this.hostsCache=new Map,this.hostsInFlight=new Map,this.txMemo=new Map}async query(e,t,i){let r=this.query$(e,t,i)[Symbol.asyncIterator](),n=null;try{let{value:e,done:t}=await r.next();!0!==t&&null!=e&&(n=e)}finally{await r.return?.(void 0)}return{type:"output-list",outputs:n?.outputs??[]}}async *query$(e,t,i){let r=[];if(r="ls_slap"===e.service?"local"===this.networkPreset?["http://localhost:8080"]:this.slapTrackers:null!=this.hostOverrides[e.service]?this.hostOverrides[e.service]:"local"===this.networkPreset?["http://localhost:8080"]:await this.getCompetentHostsCached(e.service),this.additionalHosts[e.service]?.length>0){let t=this.additionalHosts[e.service],i=new Set(r);for(let e of t)i.has(e)||r.push(e)}if(r.length<1)throw Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${e.service}`);let n=this.prepareHostsForQuery(r,`lookup service ${e.service}`);if(n.length<1)throw Error(`All competent hosts for ${e.service} are temporarily unavailable due to backoff.`);let s=i?.graceMs??80,a=i?.softTimeoutMs,o=n.length,l=new Map,c=[],h=0,d=null,u=[],f=null,p=e=>{if(u.push(e),null!==f){let e=f;f=null,e()}};for(let i of n)this.lookupHostWithTracking(i,e,t).then(e=>{e?.type==="output-list"&&Array.isArray(e.outputs)&&e.outputs.length>0&&p({kind:"answer",answer:e})}).catch(()=>{}).finally(()=>{h++,p({kind:"done"})});let g=null;"number"==typeof a&&a>=0&&(g=setTimeout(()=>p({kind:"soft"}),a));let y=null,m=!1,b=!1,w=e=>{let t=!1,i=Date.now();for(let r of e.outputs){let e=this.resolveTxIdForOutput(r,i);if(null===e)continue;let n=`${e}.${r.outputIndex}`;l.has(n)||(l.set(n,r),c.push(e),t=!0)}return t},v=e=>({type:"output-list",outputs:Array.from(l.values()),txIds:c.slice(),isFinal:e,hostCount:o,completedHosts:h});try{for(;h<o;){0===u.length&&await new Promise(e=>{f=e});let e=u.shift();if("answer"===e.kind){let t=w(e.answer);null===d&&(d=Date.now(),!m&&s>0?y=setTimeout(()=>{m=!0,p({kind:"soft"})},s):m=!0),m&&t&&(b=!0,yield v(!1))}else if("soft"===e.kind){if(b||(m=!0,b=!0,yield v(!1)),"number"==typeof a&&null!==d)break}else e.kind}yield v(!0)}finally{null!==y&&clearTimeout(y),null!==g&&clearTimeout(g)}}async getCompetentHostsCached(e){let t=Date.now(),i=this.hostsCache.get(e);if("object"==typeof i&&i.expiresAt>t)return i.hosts.slice();if("object"==typeof i&&i.expiresAt<=t)return this.hostsInFlight.has(e)||this.hostsInFlight.set(e,this.refreshHosts(e).finally(()=>{this.hostsInFlight.delete(e)})),i.hosts.slice();if(this.hostsInFlight.has(e))try{let t=await this.hostsInFlight.get(e);if("object"!=typeof t)throw TypeError("Hosts is not defined.");return t.slice()}catch{}let r=this.refreshHosts(e).finally(()=>{this.hostsInFlight.delete(e)});return this.hostsInFlight.set(e,r),(await r).slice()}async refreshHosts(e){let t=await this.findCompetentHosts(e),i=Date.now()+this.hostsTtlMs;if(!this.hostsCache.has(e)&&this.hostsCache.size>=this.hostsMaxEntries){let e=this.hostsCache.keys().next().value;void 0!==e&&this.hostsCache.delete(e)}return this.hostsCache.set(e,{hosts:t,expiresAt:i}),t}extractHostsFromAnswer(e,t){let i=[];if("output-list"!==e.type)return i;for(let r of e.outputs)try{let e=rg.fromBEEF(r.beef),n=e.outputs[r.outputIndex]?.lockingScript;if("object"!=typeof n||null===n)continue;let s=n4.decode(n);if(s.topicOrService!==t||"SLAP"!==s.protocol)continue;"string"==typeof s.domain&&s.domain.length>0&&i.push(s.domain)}catch{continue}return i}async findCompetentHosts(e){let t={service:"ls_slap",query:{service:e}},i=this.prepareHostsForQuery(this.slapTrackers,"SLAP trackers");return 0===i.length?[]:await new Promise(r=>{let n=new Set,s=!1,a=i.length;for(let o of i)this.lookupHostWithTracking(o,t,5e3).then(t=>{for(let i of this.extractHostsFromAnswer(t,e))n.add(i);!s&&n.size>0&&(s=!0,r([...n]))}).catch(()=>{}).finally(()=>{0!=--a||s||(s=!0,r([...n]))})})}resolveTxIdForOutput(e,t){if("string"==typeof e.txid&&e.txid.length>0)return e.txid;let i=Array.isArray(e.beef)?e.beef.join(","):"",r=this.txMemo.get(i);if("object"==typeof r&&null!==r&&r.expiresAt>t)return r.txId;try{let r=rg.fromBEEF(e.beef).id("hex");return this.txMemo.size>4096&&this.evictOldest(this.txMemo),this.txMemo.set(i,{txId:r,expiresAt:t+this.txMemoTtlMs}),r}catch{return null}}evictOldest(e){let t=e.keys().next().value;void 0!==t&&e.delete(t)}assertValidOverrideServices(e){for(let t of Object.keys(e))if(!t.startsWith("ls_"))throw Error(`Host override service names must start with "ls_": ${t}`)}prepareHostsForQuery(e,t){if(0===e.length)return[];let i=Date.now(),r=this.hostReputation.rankHosts(e,i),n=r.filter(e=>e.backoffUntil<=i).map(e=>e.host);if(n.length>0)return n;let s=Math.max(Math.min(...r.map(e=>e.backoffUntil))-i,0);throw Error(`All ${t} hosts are backing off for approximately ${s}ms due to repeated failures.`)}async lookupHostWithTracking(e,t,i){let r=Date.now();try{let n=await this.facilitator.lookup(e,t,i),s=Date.now()-r;return"object"==typeof n&&null!==n&&"output-list"===n.type&&Array.isArray(n.outputs)?this.hostReputation.recordSuccess(e,s):this.hostReputation.recordFailure(e,"Invalid lookup response"),n}catch(t){throw this.hostReputation.recordFailure(e,t),t}}}class sa{httpClient;allowHTTP;constructor(e=fetch,t=!1){this.httpClient=e,this.allowHTTP=t}async send(e,t){let i;if(!e.startsWith("https:")&&!this.allowHTTP)throw Error('HTTPS facilitator can only use URLs that start with "https:"');let r={"Content-Type":"application/octet-stream","X-Topics":JSON.stringify(t.topics)};if(Array.isArray(t.offChainValues)){r["x-includes-off-chain-values"]="true";let e=new tP;e.writeVarIntNum(t.beef.length),e.write(t.beef),e.write(t.offChainValues),i=new Uint8Array(e.toArray())}else i=new Uint8Array(t.beef);let n=await fetch(`${e}/submit`,{method:"POST",headers:r,body:i});if(n.ok)return await n.json();throw Error("Failed to facilitate broadcast")}}class so{topics;facilitator;resolver;requireAcknowledgmentFromAllHostsForTopics;requireAcknowledgmentFromAnyHostForTopics;requireAcknowledgmentFromSpecificHostsForTopics;networkPreset;interestedHostsCache=null;interestedHostsInFlight=null;interestedHostsTtlMs;constructor(e,t={}){if(0===e.length)throw Error("At least one topic is required for broadcast.");if(e.some(e=>!e.startsWith("tm_")))throw Error('Every topic must start with "tm_".');this.topics=e,this.networkPreset=t.networkPreset??"mainnet",this.facilitator=t.facilitator??new sa(void 0,"local"===this.networkPreset),this.resolver=t.resolver??new ss({networkPreset:this.networkPreset}),this.requireAcknowledgmentFromAllHostsForTopics=t.requireAcknowledgmentFromAllHostsForTopics??[],this.requireAcknowledgmentFromAnyHostForTopics=t.requireAcknowledgmentFromAnyHostForTopics??"all",this.requireAcknowledgmentFromSpecificHostsForTopics=t.requireAcknowledgmentFromSpecificHostsForTopics??{},this.interestedHostsTtlMs=3e5}async broadcast(e){let t,i=e.metadata.get("OffChainValues");try{t=e.toBEEF()}catch(e){throw Error("Transactions sent via SHIP to Overlay Services must be serializable to BEEF format.")}let r=await this.findInterestedHosts();if(0===Object.keys(r).length)return{status:"error",code:"ERR_NO_HOSTS_INTERESTED",description:`No ${this.networkPreset} hosts are interested in receiving this transaction.`};let n=Object.entries(r).map(async([e,r])=>{try{let n=await this.facilitator.send(e,{beef:t,offChainValues:i,topics:[...r]});if(null==n||0===Object.keys(n).length)throw Error("Steak has no topics.");return{host:e,success:!0,steak:n}}catch(t){return console.error(t),{host:e,success:!1,error:t}}}),s=(await Promise.all(n)).filter(e=>e.success);if(0===s.length)return{status:"error",code:"ERR_ALL_HOSTS_REJECTED",description:`All ${this.networkPreset} topical hosts have rejected the transaction.`};let a={};for(let e of s){let t=e.host,i=e.steak,r=new Set;for(let[e,t]of Object.entries(i)){let i=t.outputsToAdmit,n=t.coinsToRetain,s=t.coinsRemoved;(i?.length>0||n?.length>0||s?.length>0)&&r.add(e)}a[t]=r}let o=this.checkAllHostsRequirement(a);if(null!=o)return o;let l=this.checkAnyHostRequirement(a);if(null!=l)return l;let c=this.checkSpecificHostsRequirement(a);return null!=c?c:{status:"success",txid:e.id("hex"),message:`Sent to ${s.length} Overlay Services ${1===s.length?"host":"hosts"}.`}}resolveAllHostsRequirement(){let e=this.requireAcknowledgmentFromAllHostsForTopics;return"any"===e?{requiredTopics:this.topics,require:"any"}:Array.isArray(e)?{requiredTopics:e,require:"all"}:{requiredTopics:this.topics,require:"all"}}checkAllHostsRequirement(e){let{requiredTopics:t,require:i}=this.resolveAllHostsRequirement();return 0===t.length||this.checkAcknowledgmentFromAllHosts(e,t,i)?null:{status:"error",code:"ERR_REQUIRE_ACK_FROM_ALL_HOSTS_FAILED",description:"Not all hosts acknowledged the required topics."}}resolveAnyHostRequirement(){let e=this.requireAcknowledgmentFromAnyHostForTopics;return"all"===e?{requiredTopics:this.topics,require:"all"}:"any"===e?{requiredTopics:this.topics,require:"any"}:Array.isArray(e)?{requiredTopics:e,require:"all"}:{requiredTopics:[],require:"all"}}checkAnyHostRequirement(e){let{requiredTopics:t,require:i}=this.resolveAnyHostRequirement();return 0===t.length||this.checkAcknowledgmentFromAnyHost(e,t,i)?null:{status:"error",code:"ERR_REQUIRE_ACK_FROM_ANY_HOST_FAILED",description:"No host acknowledged the required topics."}}checkSpecificHostsRequirement(e){return 0===Object.keys(this.requireAcknowledgmentFromSpecificHostsForTopics).length||this.checkAcknowledgmentFromSpecificHosts(e,this.requireAcknowledgmentFromSpecificHostsForTopics)?null:{status:"error",code:"ERR_REQUIRE_ACK_FROM_SPECIFIC_HOSTS_FAILED",description:"Specific hosts did not acknowledge the required topics."}}topicsMatchRequirement(e,t,i){return"all"===i?t.every(t=>e.has(t)):t.some(t=>e.has(t))}checkAcknowledgmentFromAllHosts(e,t,i){return Object.values(e).every(e=>this.topicsMatchRequirement(e,t,i))}checkAcknowledgmentFromAnyHost(e,t,i){return Object.values(e).some(e=>this.topicsMatchRequirement(e,t,i))}checkAcknowledgmentFromSpecificHosts(e,t){for(let[i,r]of Object.entries(t)){let t,n,s=e[i];if(null==s)return!1;if("all"===r||"any"===r)n=r,t=this.topics;else{if(!Array.isArray(r))continue;t=r,n="all"}if(!this.topicsMatchRequirement(s,t,n))return!1}return!0}async findInterestedHosts(){if("local"===this.networkPreset){let e=new Set;for(let t of this.topics)e.add(t);return{"http://localhost:8080":e}}let e=Date.now();if(null!=this.interestedHostsCache&&this.interestedHostsCache.expiresAt>e)return this.interestedHostsCache.hosts;if(null!=this.interestedHostsInFlight)return await this.interestedHostsInFlight;this.interestedHostsInFlight=this.fetchInterestedHosts();try{let e=await this.interestedHostsInFlight;return this.interestedHostsCache={hosts:e,expiresAt:Date.now()+this.interestedHostsTtlMs},e}finally{this.interestedHostsInFlight=null}}async fetchInterestedHosts(){let e={},t=await this.resolver.query({service:"ls_ship",query:{topics:this.topics}},5e3);if("output-list"!==t.type)throw Error("SHIP answer is not an output list.");for(let i of t.outputs)try{let t=rg.fromBEEF(i.beef).outputs[i.outputIndex].lockingScript,r=n4.decode(t);if(!this.topics.includes(r.topicOrService)||"SHIP"!==r.protocol)continue;e[r.domain]??=new Set,e[r.domain].add(r.topicOrService)}catch(e){continue}return e}}async function sl(e,t,i=5){let r=0;for(;r<i;){r++;try{return await e()}catch(e){if(r<i&&"WERR_REVIEW_ACTIONS"===e.name){let n=e.reviewActionResults.find(e=>"doubleSpend"===e.status);if(n?.competingBeef!=null&&n?.competingTxs!=null&&n?.competingTxs.length>0){let e=rg.fromBEEF(n.competingBeef,n.competingTxs[0]);await sl(async()=>await t.broadcast(e),t,i-r);continue}}throw e}}throw Error("Unexpected end of retry loop")}let sc=e=>(e.toLowerCase().startsWith("uhrp:")&&(e=e.slice(5)),e.startsWith("//")&&(e=e.slice(2)),e),sh=e=>{if(32!==e.length)throw Error("Hash length must be 32 bytes (sha256)");return tT(e,tm("ce00","hex"))},sd=e=>{let t=e instanceof Uint8Array?e:Uint8Array.from(e),i=new eh;for(let e=0;e<t.length;e+=1048576){let r=t.subarray(e,e+1048576);i.update(Array.from(r))}return sh(i.digest())},su=e=>{let{data:t,prefix:i}=tO(e=sc(e),void 0,2);if(32!==t.length)throw Error("Invalid length!");if("ce00"!==tg(i))throw Error("Bad prefix");return t},sf=e=>{try{return su(e),!0}catch{return!1}},sp=["https://nanostore.babbage.systems","https://bsv-storage-cloudflare.dev-a3e.workers.dev"];class sg extends Error{results;requiredSuccesses;successCount;constructor(e,t,i,r){super(e),this.name="RenewResiliencyError",this.results=t,this.requiredSuccesses=i,this.successCount=r}}class sy{authFetch;hosts;resilienceLevel;baseURL;constructor(e){let t;const i=void 0===e.storageURLs&&"string"==typeof e.storageURL;if(void 0!==e.storageURLs){if(0===e.storageURLs.length)throw Error("StorageUploader requires at least one storage provider.");t=[...e.storageURLs]}else t="string"==typeof e.storageURL?[e.storageURL]:[...sp];const r=e.resilienceLevel??1;if(!Number.isInteger(r)||r<1)throw Error("resilienceLevel must be a positive integer.");this.resilienceLevel=i?1:r,this.hosts=t,this.baseURL=t[0],this.authFetch=new n6(e.wallet)}async getQuote(e,t,i){try{let r=await fetch(`${e}/quote`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileSize:t,retentionPeriod:i})});if(!r.ok)return null;let n=await r.json();if("error"===n.status||"number"!=typeof n.quote)return null;return{host:e,amount:n.quote}}catch{return null}}async getUploadURL(e,t,i){let r=await this.authFetch.fetch(`${e}/upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileSize:t,retentionPeriod:i})});if(!r.ok)throw Error(`Upload info request failed: HTTP ${r.status}`);let n=await r.json();if("error"===n.status)throw Error("Upload route returned an error.");return{uploadURL:n.uploadURL,requiredHeaders:n.requiredHeaders,amount:n.amount}}async putFile(e,t,i,r){let n=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":i,...r}});if(!n.ok)throw Error(`File upload failed: HTTP ${n.status}`)}async collectQuotes(e,t,i){let r=[],n=0;for(;n<this.hosts.length&&r.length<i;){let s=i-r.length,a=this.hosts.slice(n,n+s);for(let s of(n+=a.length,await Promise.all(a.map(async i=>await this.getQuote(i,e,t)))))null!==s&&r.length<i&&r.push(s)}return r}async estimateCost(e){let{fileSize:t,retentionPeriod:i}=e,r=await this.collectQuotes(t,i,2*this.resilienceLevel);r.sort((e,t)=>e.amount-t.amount);let n=r.length>=this.resilienceLevel,s=(n?r.slice(0,this.resilienceLevel):r).reduce((e,t)=>e+t.amount,0);return{quotes:r.map(e=>({host:e.host,amount:e.amount})),resilienceLevel:this.resilienceLevel,totalForResilience:s,meetsResilienceThreshold:n}}async publishFile(e){let{file:t,retentionPeriod:i}=e,r=t.data instanceof Uint8Array?t.data:Uint8Array.from(t.data),n=r.byteLength,s=await this.estimateCost({fileSize:n,retentionPeriod:i});if(!s.meetsResilienceThreshold)throw Error(`Resiliency threshold of ${this.resilienceLevel} could not be met: only ${s.quotes.length} of ${this.hosts.length} provider(s) responded with quotes.`);let a=sd(r),o=[],l=[];for(let e of s.quotes){if(o.length>=this.resilienceLevel)break;try{let{uploadURL:s,requiredHeaders:a}=await this.getUploadURL(e.host,n,i);await this.putFile(s,r,t.type,a),o.push(e.host)}catch(t){l.push({host:e.host,error:t.message})}}if(o.length<this.resilienceLevel){let e=l.map(e=>`${e.host}: ${e.error}`).join("; ");throw Error(`Resiliency threshold of ${this.resilienceLevel} could not be met: only ${o.length} upload(s) succeeded. Failures — ${e}`)}return{published:!0,uhrpURL:a,hostedBy:o}}async findFileAtHost(e,t){let i=new URL(`${e}/find`);i.searchParams.set("uhrpUrl",t);let r=await this.authFetch.fetch(i.toString(),{method:"GET"});if(!r.ok)throw Error(`findFile request failed: HTTP ${r.status}`);let n=await r.json();if("error"===n.status){let e=n.code??"unknown-code",t=n.description??"no-description";throw Error(`findFile returned an error: ${e} - ${t}`)}return n.data}async renewFileAtHost(e,t,i){let r=await this.authFetch.fetch(`${e}/renew`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({uhrpUrl:t,additionalMinutes:i})});if(!r.ok)throw Error(`renewFile request failed: HTTP ${r.status}`);let n=await r.json();if("error"===n.status){let e=n.code??"unknown-code",t=n.description??"no-description";throw Error(`renewFile returned an error: ${e} - ${t}`)}return{status:n.status,prevExpiryTime:n.prevExpiryTime,newExpiryTime:n.newExpiryTime,amount:n.amount}}resolveTargets(e){if(void 0===e)return this.hosts;let t=new Set(this.hosts),i=e.filter(e=>t.has(e));if(0===i.length)throw Error("hostedBy did not intersect any configured provider. Provide hosts that were also passed to the StorageUploader constructor.");return i}async findFile(e,t={}){let i=this.resolveTargets(t.hostedBy),r=await Promise.all(i.map(async t=>{try{return{ok:!0,host:t,data:await this.findFileAtHost(t,e)}}catch(e){return{ok:!1,host:t,error:e}}})),n=r.flatMap(e=>e.ok?[e]:[]);if(0===n.length){let e=r.flatMap(e=>e.ok?[]:[e]);if(1===i.length)throw e[0].error;let t=e.map(e=>`${e.host}: ${e.error.message}`).join("; ");throw Error(`findFile: no configured host reported this UHRP URL — ${t}`)}n.sort((e,t)=>t.data.expiryTime-e.data.expiryTime);let s=n[0];return 1===i.length?s.data:{...s.data,hostedBy:n.map(e=>e.host)}}async listUploads(e={}){let t=this.resolveTargets(e.hostedBy),i=await Promise.all(t.map(async e=>{try{return{ok:!0,host:e,data:await this.listUploadsAtHost(e)}}catch(t){return{ok:!1,host:e,error:t}}})),r=i.flatMap(e=>e.ok?[e]:[]);if(0===r.length){let e=i.flatMap(e=>e.ok?[]:[e]);if(1===t.length)throw e[0].error;let r=e.map(e=>`${e.host}: ${e.error.message}`).join("; ");throw Error(`listUploads: no configured host returned a listing — ${r}`)}if(1===t.length)return r[0].data;let n=new Map;for(let{host:e,data:t}of r)if(Array.isArray(t))for(let i of t){let t=i?.uhrpUrl;if("string"!=typeof t)continue;let r=Number(i.expiryTime),s=Number.isFinite(r)?r:0,a=n.get(t);void 0===a?n.set(t,{uhrpUrl:t,expiryTime:s,hostedBy:[e]}):(a.expiryTime=Math.max(a.expiryTime,s),a.hostedBy.includes(e)||a.hostedBy.push(e))}return Array.from(n.values())}async listUploadsAtHost(e){let t=await this.authFetch.fetch(`${e}/list`,{method:"GET"});if(!t.ok)throw Error(`listUploads request failed: HTTP ${t.status}`);let i=await t.json();if("error"===i.status){let e=i.code??"unknown-code",t=i.description??"no-description";throw Error(`listUploads returned an error: ${e} - ${t}`)}return i.uploads}async renewFile(e,t,i={}){let r=this.resolveTargets(i.hostedBy);if(1===r.length){let i=await this.renewFileAtHost(r[0],e,t);return{status:i.status,prevExpiryTime:i.prevExpiryTime,newExpiryTime:i.newExpiryTime,amount:i.amount}}let n=(await Promise.all(r.map(async i=>{try{let r=await this.renewFileAtHost(i,e,t);return{result:{host:i,status:"success",prevExpiryTime:r.prevExpiryTime,newExpiryTime:r.newExpiryTime,amount:r.amount}}}catch(e){return{result:{host:i,status:"error",error:e.message},raw:e}}}))).map(e=>e.result),s=n.filter(e=>"success"===e.status),a=Math.min(r.length,this.resilienceLevel);if(s.length<a){let e=n.map(e=>`${e.host}: ${"success"===e.status?"renewed":e.error??"unknown"}`).join("; ");throw new sg(`renewFile: only ${s.length} of ${a} required hosts renewed — ${e}`,n,a,s.length)}s.sort((e,t)=>(t.newExpiryTime??0)-(e.newExpiryTime??0));let o=s[0],l=s.reduce((e,t)=>e+(t.amount??0),0);return{status:"success",prevExpiryTime:o.prevExpiryTime,newExpiryTime:o.newExpiryTime,amount:l,results:n}}}class sm{networkPreset="mainnet";lookupResolver;constructor(e){this.networkPreset=e?.networkPreset??"mainnet",this.lookupResolver=new ss({networkPreset:this.networkPreset})}async resolve(e){let t=await this.lookupResolver.query({service:"ls_uhrp",query:{uhrpUrl:e}});if("output-list"!==t.type)throw Error("Lookup answer must be an output list");let i=[],r=Math.floor(Date.now()/1e3);for(let e of t.outputs){let t=rg.fromBEEF(e.beef),{fields:n}=i4.decode(t.outputs[e.outputIndex].lockingScript);new tN(n[3]).readVarIntNum()<r||i.push(tI(n[2]))}return i}async download(e){if(!sf(e))throw Error("Invalid parameter UHRP url");let t=tg(su(e)),i=await this.resolve(e);if(!Array.isArray(i)||0===i.length)throw Error("No one currently hosts this file!");for(let e of i)try{let i=await fetch(e,{method:"GET"});if(!i.ok||i.status>=400||null==i.body)continue;let r=i.body.getReader(),n=new eh,s=[],a=0;for(;;){let{done:e,value:t}=await r.read();if(e)break;n.update(Array.from(t)),s.push(t),a+=t.length}if(tg(n.digest())!==t)throw Error("Data integrity error: value of content does not match hash of the url given");let o=new Uint8Array(a),l=0;for(let e of s)o.set(e,l),l+=e.length;return{data:o,mimeType:i.headers.get("Content-Type")}}catch{continue}throw Error(`Unable to download content from ${e}`)}}let sb={name:"Unknown Identity",avatarURL:"XUUB8bbn9fEthk15Ge3zTQXypUShfC94vFjp65v7u5CQ8qkpxzst",identityKey:"",abbreviatedKey:"",badgeIconURL:"XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",badgeLabel:"Not verified by anyone you trust.",badgeClickURL:"https://bsv-blockchain.github.io/ts-sdk/reference/identity/"},sw={protocolID:[1,"identity"],keyID:"1",tokenAmount:1,outputIndex:0},sv={identiCert:"z40BOInXkI8m7f/wBrv4MJ09bZfzZbTj2fJqCtONqCY=",discordCert:"2TgqRC35B1zehGmB21xveZNc7i5iqHc0uxMb+1NMPW4=",phoneCert:"mffUklUzxbHr65xLohn0hRL0Tq2GjW1GYF/OPfzqJ6A=",xCert:"vdDWvftf1H+5+ZprUw123kjHlywH+v20aPQTuXgMpNc=",registrant:"YoPsbfR6YQczjzPdHCoGC7nJsOdPQR50+SYqcWpJ0y0=",emailCert:"exOl3KM0dIJ04EW5pZgbZmPag6MdJXd3/a1enmUU/BA=",anyone:"mfkOMfLDQmrr3SBxBQ5WeE+6Hy3VJRFq6w4A5Ljtlis=",self:"Hkge6X5JRxt1cWXtHLCrSTg6dCVTxjQJJ48iOYd7n3g=",coolCert:"AGfk/WrT1eBDXpz3mcw386Zww2HmqcIn3uY6x4Af1eo="},sI=[2,"contact"];class sk{cache=new Map;getItem(e){return this.cache.get(e)??null}setItem(e,t){this.cache.set(e,t)}removeItem(e){this.cache.delete(e)}clear(){this.cache.clear()}}class sS{wallet;cache=new sk;CONTACTS_CACHE_KEY="metanet-contacts";originator;inFlightLoad=null;knownEmpty=!1;constructor(e,t){this.wallet=e??new nW,this.originator=t}async getContacts(e,t=!1,i=1e3){if(t&&this.invalidate(),this.knownEmpty)return[];if(!t){let t=this.loadCachedContacts(e);if(null!==t)return t}this.inFlightLoad??=this.loadContactsFromWallet(i).finally(()=>{this.inFlightLoad=null});let r=await this.inFlightLoad;return null==e?r:r.filter(t=>t.identityKey===e)}invalidate(){this.cache.removeItem(this.CONTACTS_CACHE_KEY),this.knownEmpty=!1,this.inFlightLoad=null}async loadContactsFromWallet(e){let t=await this.wallet.listOutputs({basket:"contacts",include:"locking scripts",includeCustomInstructions:!0,tags:[],limit:e},this.originator);if(null==t.outputs||0===t.outputs.length)return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify([])),this.knownEmpty=!0,[];let i=await this.decryptContactOutputs(t.outputs);return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(i)),i}loadCachedContacts(e){let t=this.cache.getItem(this.CONTACTS_CACHE_KEY);if(null==t||""===t)return null;try{let i=JSON.parse(t);return null!=e?i.filter(t=>t.identityKey===e):i}catch(e){return console.warn("Invalid cached contacts JSON; will reload from chain",e),null}}async buildIdentityKeyTags(e){if(null==e)return[];let{hmac:t}=await this.wallet.createHmac({protocolID:sI,keyID:e,counterparty:"self",data:tm(e,"utf8")},this.originator);return[`identityKey ${tg(t)}`]}async decryptContactOutputs(e){let t=[];for(let i of e)try{if(null==i.lockingScript||null==i.customInstructions)continue;let e=i4.decode(ij.fromHex(i.lockingScript)),r=JSON.parse(i.customInstructions).keyID;t.push({keyID:r,ciphertext:e.fields[0]})}catch(e){console.warn("ContactsManager: Failed to decode contact output:",e)}let i=await Promise.allSettled(t.map(async e=>await this.wallet.decrypt({ciphertext:e.ciphertext,protocolID:sI,keyID:e.keyID,counterparty:"self"},this.originator))),r=[];for(let e of i)if("fulfilled"===e.status)try{r.push(JSON.parse(tI(e.value.plaintext)))}catch(e){console.warn("ContactsManager: Failed to parse contact data:",e)}else console.warn("ContactsManager: Failed to decrypt contact output:",e.reason);return r}async saveContact(e,t){let i=this.cache.getItem(this.CONTACTS_CACHE_KEY),r=null!=i&&""!==i?JSON.parse(i):await this.getContacts(),n={...e,metadata:t},s=r.findIndex(t=>t.identityKey===e.identityKey);s>=0?r[s]=n:r.push(n);let a=await this.hashIdentityKey(e.identityKey),o=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:[`identityKey ${tg(a)}`],limit:100},this.originator),{existingOutput:l,keyID:c}=await this.findExistingOutput(o,e.identityKey),h=await this.encryptAndLock(n,c);null!=l?await this.updateContactOutput(o,l,h,c,a,e):await this.createContactOutput(h,c,a,e),this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(r)),this.knownEmpty=!1,this.inFlightLoad=null}async hashIdentityKey(e){let{hmac:t}=await this.wallet.createHmac({protocolID:sI,keyID:e,counterparty:"self",data:tm(e,"utf8")},this.originator);return t}async findExistingOutput(e,t){let i=null,r=tS(ia(32));if(null==e.outputs)return{existingOutput:i,keyID:r};for(let n of e.outputs)try{let[s,a]=n.outpoint.split("."),o=rg.fromBEEF(e.BEEF,s),l=i4.decode(o.outputs[Number(a)].lockingScript);if(null==n.customInstructions)continue;r=JSON.parse(n.customInstructions).keyID;let{plaintext:c}=await this.wallet.decrypt({ciphertext:l.fields[0],protocolID:sI,keyID:r,counterparty:"self"},this.originator);if(JSON.parse(tI(c)).identityKey===t){i=n;break}}catch(e){}return{existingOutput:i,keyID:r}}async encryptAndLock(e,t){let{ciphertext:i}=await this.wallet.encrypt({plaintext:tm(JSON.stringify(e),"utf8"),protocolID:sI,keyID:t,counterparty:"self"},this.originator);return await new i4(this.wallet,this.originator).lock([i],sI,t,"self")}async updateContactOutput(e,t,i,r,n,s){let[a,o]=String(t.outpoint).split("."),l=`${a}.${o}`,c=new i4(this.wallet,this.originator),{signableTransaction:h}=await this.wallet.createAction({description:"Update Contact",inputBEEF:e.BEEF,inputs:[{outpoint:l,unlockingScriptLength:74,inputDescription:"Spend previous contact output"}],outputs:[{basket:"contacts",satoshis:1,lockingScript:i.toHex(),outputDescription:`Updated Contact: ${s.name??s.identityKey.slice(0,10)}`,tags:[`identityKey ${tg(n)}`],customInstructions:JSON.stringify({keyID:r})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==h)throw Error("Unable to update contact");let d=await c.unlock(sI,r,"self").sign(rg.fromBEEF(h.tx),0),{tx:u}=await this.wallet.signAction({reference:h.reference,spends:{0:{unlockingScript:d.toHex()}}},this.originator);if(null==u)throw Error("Failed to update contact output")}async createContactOutput(e,t,i,r){let{tx:n}=await this.wallet.createAction({description:"Add Contact",outputs:[{basket:"contacts",satoshis:1,lockingScript:e.toHex(),outputDescription:`Contact: ${r.name??r.identityKey.slice(0,10)}`,tags:[`identityKey ${tg(i)}`],customInstructions:JSON.stringify({keyID:t})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==n)throw Error("Failed to create contact output")}async removeContact(e){let t=this.cache.getItem(this.CONTACTS_CACHE_KEY);if(null!=t&&""!==t)try{let i=JSON.parse(t).filter(t=>t.identityKey!==e);this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(i)),this.knownEmpty=0===i.length}catch(e){console.warn("Failed to update cache after contact removal:",e)}this.inFlightLoad=null;let i=await this.buildIdentityKeyTags(e),r=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:i,limit:100},this.originator);if(null!=r.outputs)for(let t of r.outputs)try{if(await this.trySpendContactOutput(t,r,e))return}catch(e){}}async trySpendContactOutput(e,t,i){let[r,n]=String(e.outpoint).split("."),s=rg.fromBEEF(t.BEEF,r),a=i4.decode(s.outputs[Number(n)].lockingScript);if(null==e.customInstructions)return!1;let o=JSON.parse(e.customInstructions).keyID,{plaintext:l}=await this.wallet.decrypt({ciphertext:a.fields[0],protocolID:sI,keyID:o,counterparty:"self"},this.originator);if(JSON.parse(tI(l)).identityKey!==i)return!1;let c=`${r}.${n}`,h=new i4(this.wallet,this.originator),{signableTransaction:d}=await this.wallet.createAction({description:"Delete Contact",inputBEEF:t.BEEF,inputs:[{outpoint:c,unlockingScriptLength:74,inputDescription:"Spend contact output to delete"}],outputs:[],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==d)throw Error("Unable to delete contact");let u=await h.unlock(sI,o,"self").sign(rg.fromBEEF(d.tx),0),{tx:f}=await this.wallet.signAction({reference:d.reference,spends:{0:{unlockingScript:u.toHex()}}},this.originator);if(null==f)throw Error("Failed to delete contact output");return!0}}async function sE(){let e=globalThis.scheduler;return null!=e&&"function"==typeof e.yield?await e.yield():await new Promise(e=>setTimeout(e,0))}function sx(e){return void 0===e?{useContacts:!1,parallel:!1}:"boolean"==typeof e?{useContacts:e,parallel:!1}:{useContacts:e.overrideWithContacts??e.useContacts??!1,parallel:!0===e.parallel}}class sA{options;originator;wallet;contactsManager;constructor(e,t=sw,i){this.options=t,this.originator=i,this.originator=i,this.wallet=e??new nW,this.contactsManager=new sS(this.wallet,this.originator)}async publiclyRevealAttributes(e,t){if(0===Object.keys(e.fields).length)throw Error("Public reveal failed: Certificate has no fields to reveal!");if(0===t.length)throw Error("Public reveal failed: You must reveal at least one field!");try{let t=new r1(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature);await t.verify()}catch(e){throw Error("Public reveal failed: Certificate verification failed!")}let{keyringForVerifier:i}=await this.wallet.proveCertificate({certificate:e,fieldsToReveal:t,verifier:new ih(1).toPublicKey().toString()},this.originator),r=await new i4(this.wallet,this.originator).lock([tm(JSON.stringify({...e,keyring:i}))],this.options.protocolID,this.options.keyID,"anyone",!0,!0),{tx:n}=await this.wallet.createAction({description:"Create a new Identity Token",outputs:[{satoshis:this.options.tokenAmount,lockingScript:r.toHex(),outputDescription:"Identity Token"}],options:{randomizeOutputs:!1}},this.originator);if(void 0!==n){let e=new so(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network});return await e.broadcast(rg.fromAtomicBEEF(n))}throw Error("Public reveal failed: failed to create action!")}async resolveByIdentityKey(e,t=!1){let{useContacts:i,parallel:r}=sx(t);if(!i){let t=await this.wallet.discoverByIdentityKey(e,this.originator),i=t?.certificates??[];return await sA.parseIdentities(i)}if(!r){let t=await this.contactsManager.getContacts(e.identityKey);if(t.length>0)return t;let i=await this.wallet.discoverByIdentityKey(e,this.originator),r=i?.certificates??[];return await sA.parseIdentities(r)}let[n,s]=await Promise.all([this.contactsManager.getContacts(e.identityKey),this.wallet.discoverByIdentityKey(e,this.originator)]);if(n.length>0)return n;let a=s?.certificates??[];return await sA.parseIdentities(a)}async resolveByAttributes(e,t=!1){let{useContacts:i,parallel:r}=sx(t);if(!i){let t=await this.wallet.discoverByAttributes(e,this.originator),i=t?.certificates??[];return await sA.parseIdentities(i)}if(!r){let t=await this.contactsManager.getContacts(),i=this.matchContactsByAttributes(t,e);if(i.length>0)return i;let r=await this.wallet.discoverByAttributes(e,this.originator),n=r?.certificates??[];if(0===t.length)return await sA.parseIdentities(n);let s=new Map(t.map(e=>[e.identityKey,e]));return await sA.parseIdentitiesWithOverrides(n,s)}let[n,s]=await Promise.all([this.contactsManager.getContacts(),this.wallet.discoverByAttributes(e,this.originator)]),a=s?.certificates??[];if(0===n.length)return await sA.parseIdentities(a);let o=new Map(n.map(e=>[e.identityKey,e]));return await sA.parseIdentitiesWithOverrides(a,o)}matchContactsByAttributes(e,t){let i=t.attributes;if(null==i||"object"!=typeof i||Array.isArray(i))return[];let r=Object.entries(i).filter(([,e])=>"string"==typeof e&&e.length>0);return 0===r.length?[]:e.filter(e=>{let t={name:e.name,identityKey:e.identityKey};return r.every(([e,i])=>"string"==typeof t[e]&&t[e].toLowerCase()===i.toLowerCase())})}async revokeCertificateRevelation(e){let t=new ss({networkPreset:(await this.wallet.getNetwork({})).network}),i=await t.query({service:"ls_identity",query:{serialNumber:e}});if("output-list"!==i.type)throw Error("Failed to get lookup result");let r=new so(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network,requireAcknowledgmentFromAllHostsForTopics:[],requireAcknowledgmentFromAnyHostForTopics:[],requireAcknowledgmentFromSpecificHostsForTopics:{tm_identity:[]}});await sl(async()=>{let e=rg.fromBEEF(i.outputs[0].beef),t=`${e.id("hex")}.${this.options.outputIndex}`;if(void 0===e.outputs[this.options.outputIndex].lockingScript||void 0===t)throw Error("Failed to get locking script for revelation output!");let{signableTransaction:n}=await this.wallet.createAction({description:"Spend certificate revelation token",inputBEEF:i.outputs[0].beef,inputs:[{inputDescription:"Revelation token",outpoint:t,unlockingScriptLength:74}],options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1,noSend:!0}},this.originator);if(void 0===n)throw Error("Failed to create signable transaction");let s=rg.fromBEEF(n.tx),a=new i4(this.wallet,this.originator).unlock(this.options.protocolID,this.options.keyID,"anyone"),o=await a.sign(s,this.options.outputIndex),{tx:l}=await this.wallet.signAction({reference:n.reference,spends:{[this.options.outputIndex]:{unlockingScript:o.toHex()}},options:{acceptDelayedBroadcast:!1,noSend:!0}},this.originator);if(void 0===l)throw Error("Failed to sign transaction");await r.broadcast(rg.fromAtomicBEEF(l))},r)}async getContacts(e,t=!1,i=1e3){return await this.contactsManager.getContacts(e,t,i)}async saveContact(e,t){return await this.contactsManager.saveContact(e,t)}async removeContact(e){return await this.contactsManager.removeContact(e)}static async parseIdentities(e){let t=e.length;if(t<=32)return e.map(e=>sA.parseIdentity(e));let i=Array(t);for(let r=0;r<t;r++)i[r]=sA.parseIdentity(e[r]),(r+1)%32==0&&await sE();return i}static async parseIdentitiesWithOverrides(e,t){let i=e.length;if(i<=32)return e.map(e=>t.get(e.subject)??sA.parseIdentity(e));let r=Array(i);for(let n=0;n<i;n++){let i=e[n];r[n]=t.get(i.subject)??sA.parseIdentity(i),(n+1)%32==0&&await sE()}return r}static parseIdentity(e){let t,i,r,n,s,{type:a,decryptedFields:o,certifierInfo:l}=e;switch(a){case sv.xCert:t=o.userName,i=o.profilePhoto,r=`X account certified by ${l.name}`,n=l.iconUrl,s="https://socialcert.net";break;case sv.discordCert:t=o.userName,i=o.profilePhoto,r=`Discord account certified by ${l.name}`,n=l.iconUrl,s="https://socialcert.net";break;case sv.emailCert:t=o.email,i="XUTZxep7BBghAJbSBwTjNfmcsDdRFs5EaGEgkESGSgjJVYgMEizu",r=`Email certified by ${l.name}`,n=l.iconUrl,s="https://socialcert.net";break;case sv.phoneCert:t=o.phoneNumber,i="XUTLxtX3ELNUwRhLwL7kWNGbdnFM8WG2eSLv84J7654oH8HaJWrU",r=`Phone certified by ${l.name}`,n=l.iconUrl,s="https://socialcert.net";break;case sv.identiCert:t=`${o.firstName} ${o.lastName}`,i=o.profilePhoto,r=`Government ID certified by ${l.name}`,n=l.iconUrl,s="https://identicert.me";break;case sv.registrant:t=o.name,i=o.icon,r=`Entity certified by ${l.name}`,n=l.iconUrl,s="https://bsv-blockchain.github.io/ts-sdk/reference/identity/";break;case sv.coolCert:t="true"===o.cool?"Cool Person!":"Not cool!";break;case sv.anyone:t="Anyone",i="XUT4bpQ6cpBaXi1oMzZsXfpkWGbtp2JTUYAoN7PzhStFJ6wLfoeR",r="Represents the ability for anyone to access this information.",n="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",s="https://bsv-blockchain.github.io/ts-sdk/reference/identity/";break;case sv.self:t="You",i="XUT9jHGk2qace148jeCX5rDsMftkSGYKmigLwU2PLLBc7Hm63VYR",r="Represents your ability to access this information.",n="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",s="https://bsv-blockchain.github.io/ts-sdk/reference/identity/";break;default:{let e=sA.tryToParseGenericIdentity(a,o,l);t=e.name,i=e.avatarURL,r=e.badgeLabel,n=e.badgeIconURL,s=e.badgeClickURL}}return{name:t,avatarURL:i,abbreviatedKey:e.subject.length>0?`${e.subject.substring(0,10)}...`:"",identityKey:e.subject,badgeIconURL:n,badgeLabel:r,badgeClickURL:s}}static hasValue(e){return null!=e&&""!==e}static tryToParseGenericIdentity(e,t,i){let r,n,s,a=t.firstName,o=t.lastName;sA.hasValue(a)&&sA.hasValue(o)?r=`${a} ${o}`:sA.hasValue(a)?r=a:sA.hasValue(o)&&(r=o),n=sA.hasValue(t.name)?t.name:sA.hasValue(t.userName)?t.userName:void 0!==r?r:sA.hasValue(t.email)?t.email:sb.name,s=sA.hasValue(t.profilePhoto)?t.profilePhoto:sA.hasValue(t.avatar)?t.avatar:sA.hasValue(t.icon)?t.icon:sA.hasValue(t.photo)?t.photo:sb.avatarURL;let l=sA.hasValue(i?.name)?`${e} certified by ${String(i.name)}`:sb.badgeLabel;return{name:n,avatarURL:s,badgeLabel:l,badgeIconURL:sA.hasValue(i?.iconUrl)?i.iconUrl:sb.badgeIconURL,badgeClickURL:sb.badgeClickURL}}}class sT{wallet;originator;network;resolver;cachedIdentityKey;acceptDelayedBroadcast;constructor(e=new nW,t={},i){this.wallet=e,this.originator=i,this.acceptDelayedBroadcast=t.acceptDelayedBroadcast??!1,this.resolver=t.resolver??new ss}async getIdentityKey(){return this.cachedIdentityKey??=(await this.wallet.getPublicKey({identityKey:!0})).publicKey,this.cachedIdentityKey}async getNetwork(){return this.network??=(await this.wallet.getNetwork({})).network,this.network}async registerDefinition(e){let t=await this.getIdentityKey(),i=new i4(this.wallet,this.originator),r=this.buildPushDropFields(e,t),n=this.mapDefinitionTypeToWalletProtocol(e.definitionType),s=await i.lock(r,n,"1","anyone",!0),{tx:a}=await this.wallet.createAction({description:`Register a new ${e.definitionType} item`,outputs:[{satoshis:1,lockingScript:s.toHex(),outputDescription:`New ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===a)throw Error(`Failed to create ${e.definitionType} registration transaction!`);let o=new so([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await o.broadcast(rg.fromAtomicBEEF(a))}async resolve(e,t){let i=this.mapDefinitionTypeToServiceName(e),r=await this.resolver.query({service:i,query:t});if("output-list"!==r.type)return[];let n=[];for(let t of r.outputs)try{let i=rg.fromBEEF(t.beef).outputs[t.outputIndex].lockingScript,r=await this.parseLockingScript(e,i);n.push(r)}catch{}return n}async listOwnRegistryEntries(e){let t=this.mapDefinitionTypeToBasketName(e),{outputs:i,BEEF:r}=await this.wallet.listOutputs({basket:t,include:"entire transactions"}),n=[];for(let t of i)if(t.spendable)try{let[i,s]=t.outpoint.split("."),a=rg.fromBEEF(r,i).outputs[Number(s)].lockingScript,o=await this.parseLockingScript(e,a);n.push({...o,txid:i,outputIndex:Number(s),satoshis:t.satoshis,lockingScript:a.toHex(),beef:r})}catch{}return n}async removeDefinition(e){let t;if(void 0===e.txid||void 0===e.outputIndex||void 0===e.lockingScript)throw Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");let i=await this.getIdentityKey();if(e.registryOperator!==i)throw Error("This registry token does not belong to the current wallet.");t="basket"===e.definitionType?e.basketID:"protocol"===e.definitionType?e.name:"certificate"===e.definitionType?e.name??e.type:"unknown";let r=`${e.txid}.${e.outputIndex}`,{signableTransaction:n}=await this.wallet.createAction({description:`Remove ${e.definitionType} item: ${t}`,inputBEEF:e.beef,inputs:[{outpoint:r,unlockingScriptLength:74,inputDescription:`Removing ${e.definitionType} token`}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===n)throw Error("Failed to create signable transaction.");let s=rg.fromAtomicBEEF(n.tx),a=new i4(this.wallet,this.originator).unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone"),o=await a.sign(s,0),{tx:l}=await this.wallet.signAction({reference:n.reference,spends:{0:{unlockingScript:o.toHex()}},options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if(void 0===l)throw Error("Failed to finalize the transaction signature.");let c=new so([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await c.broadcast(rg.fromAtomicBEEF(l))}async updateDefinition(e,t){let i;if(void 0===e.txid||void 0===e.outputIndex||void 0===e.lockingScript)throw Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");if(e.definitionType!==t.definitionType)throw Error(`Cannot change definition type from ${e.definitionType} to ${t.definitionType}`);let r=await this.getIdentityKey();if(e.registryOperator!==r)throw Error("This registry token does not belong to the current wallet.");i="basket"===e.definitionType?e.basketID:"protocol"===e.definitionType?e.name:"certificate"===e.definitionType?e.name??e.type:"unknown";let n=new i4(this.wallet,this.originator),s=this.buildPushDropFields(t,r),a=this.mapDefinitionTypeToWalletProtocol(t.definitionType),o=await n.lock(s,a,"1","anyone",!0),l=`${e.txid}.${e.outputIndex}`,{signableTransaction:c}=await this.wallet.createAction({description:`Update ${e.definitionType} item: ${i}`,inputBEEF:e.beef,inputs:[{outpoint:l,unlockingScriptLength:74,inputDescription:`Updating ${e.definitionType} token`}],outputs:[{satoshis:1,lockingScript:o.toHex(),outputDescription:`Updated ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===c)throw Error("Failed to create signable transaction.");let h=rg.fromAtomicBEEF(c.tx),d=n.unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone"),u=await d.sign(h,0),{tx:f}=await this.wallet.signAction({reference:c.reference,spends:{0:{unlockingScript:u.toHex()}},options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if(void 0===f)throw Error("Failed to finalize the transaction signature.");let p=new so([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await p.broadcast(rg.fromAtomicBEEF(f))}buildPushDropFields(e,t){let i;switch(e.definitionType){case"basket":i=[e.basketID,e.name,e.iconURL,e.description,e.documentationURL];break;case"protocol":i=[JSON.stringify(e.protocolID),e.name,e.iconURL,e.description,e.documentationURL];break;case"certificate":i=[e.type,e.name,e.iconURL,e.description,e.documentationURL,JSON.stringify(e.fields)];break;default:throw Error("Unsupported definition type")}return i.push(t),i.map(e=>tm(e))}async parseLockingScript(e,t){let i,r,n=i4.decode(t);if(0===n.fields.length)throw Error("Not a valid registry pushdrop script.");switch(e){case"basket":{if(7!==n.fields.length)throw Error("Unexpected field count for basket type.");let[e,t,s,a,o,l]=n.fields;i=tI(l),r={definitionType:"basket",basketID:tI(e),name:tI(t),iconURL:tI(s),description:tI(a),documentationURL:tI(o)};break}case"protocol":{if(7!==n.fields.length)throw Error("Unexpected field count for protocol type.");let[e,t,s,a,o,l]=n.fields;i=tI(l),r={definitionType:"protocol",protocolID:sO(tI(e)),name:tI(t),iconURL:tI(s),description:tI(a),documentationURL:tI(o)};break}case"certificate":{if(8!==n.fields.length)throw Error("Unexpected field count for certificate type.");let[e,t,s,a,o,l,c]=n.fields;i=tI(c);let h={};try{h=JSON.parse(tI(l))}catch{}r={definitionType:"certificate",type:tI(e),name:tI(t),iconURL:tI(s),description:tI(a),documentationURL:tI(o),fields:h};break}default:throw Error(`Unsupported definition type: ${e}`)}return{...r,registryOperator:i}}mapDefinitionTypeToWalletProtocol(e){switch(e){case"basket":return[1,"basketmap"];case"protocol":return[1,"protomap"];case"certificate":return[1,"certmap"];default:throw Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToBasketName(e){switch(e){case"basket":return"basketmap";case"protocol":return"protomap";case"certificate":return"certmap";default:throw Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToTopic(e){switch(e){case"basket":return"tm_basketmap";case"protocol":return"tm_protomap";case"certificate":return"tm_certmap";default:throw Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToServiceName(e){switch(e){case"basket":return"ls_basketmap";case"protocol":return"ls_protomap";case"certificate":return"ls_certmap";default:throw Error(`Unknown definition type: ${e}`)}}}function sO(e){let t=JSON.parse(e);if(!Array.isArray(t)||2!==t.length)throw Error("Invalid wallet protocol format.");let[i,r]=t;if(![0,1,2].includes(i))throw Error("Invalid security level.");if("string"!=typeof r)throw TypeError("Invalid protocolID");return[i,r]}class sP{wallet;context;encrypt;originator;acceptDelayedBroadcast=!1;keyLocks=new Map;constructor(e=new nW,t="kvstore default",i=!0,r,n=!1){if("string"!=typeof t||t.length<1)throw Error("A context in which to operate is required.");this.wallet=e,this.context=t,this.encrypt=i,this.originator=r,this.acceptDelayedBroadcast=n}async queueOperationOnKey(e){let t=this.keyLocks.get(e);null==t&&(t=[],this.keyLocks.set(e,t));let i=()=>{},r=new Promise(e=>{i=e,null!=t&&t.push(e)});return 1===t.length&&i(),await r,t}finishOperationOnKey(e,t){t.shift(),t.length>0&&t[0]()}getProtocol(e){return{protocolID:[2,this.context],keyID:e}}async getOutputs(e,t){return await this.wallet.listOutputs({basket:this.context,tags:[e],tagQueryMode:"all",include:"entire transactions",limit:t},this.originator)}async get(e,t){let i=await this.queueOperationOnKey(e);try{return(await this.lookupValue(e,t,5)).value}finally{this.finishOperationOnKey(e,i)}}getLockingScript(e,t){let[i,r]=e.outpoint.split("."),n=t.findTxid(i)?.tx;if(null==n)throw Error(`beef must contain txid ${i}`);return n.outputs[Number(r)].lockingScript}async lookupValue(e,t,i){let r,n=await this.getOutputs(e,i),s={value:t,outpoint:void 0,lor:n},{outputs:a}=n;if(0===a.length)return s;let o=a.at(-1);s.outpoint=o.outpoint;try{if(void 0===n.BEEF)throw Error("entire transactions listOutputs option must return valid BEEF");let e=this.getLockingScript(o,rp.fromBinary(n.BEEF)),t=i4.decode(e);if(t.fields.length<1||t.fields.length>2)throw Error("Invalid token.");r=t.fields[0]}catch(e){throw Error(`Invalid value found. You need to call set to collapse the corrupted state (or relinquish the corrupted ${a[0].outpoint} output from the ${this.context} basket) before you can get this value again. Original error: ${e instanceof Error?e.message:String(e)}`)}if(this.encrypt){let{plaintext:t}=await this.wallet.decrypt({...this.getProtocol(e),ciphertext:r},this.originator);s.value=tI(t)}else s.value=tI(r);return s}getInputs(e){let t=[];for(let i of e)t.push({outpoint:i.outpoint,unlockingScriptLength:74,inputDescription:"Previous key-value token"});return t}async getSpends(e,t,i,r){let n=this.getProtocol(e),s=rg.fromAtomicBEEF(r),a={};for(let[e]of t.entries()){let t=i.unlock(n.protocolID,n.keyID,"self"),r=await t.sign(s,e);a[e]={unlockingScript:r.toHex()}}return a}async set(e,t){let i=await this.queueOperationOnKey(e);try{let i,r=await this.lookupValue(e,void 0,10);if(r.value===t){if(void 0===r.outpoint)throw Error("outpoint must be valid when value is valid and unchanged");return r.outpoint}let n=this.getProtocol(e),s=tm(t,"utf8");if(this.encrypt){let{ciphertext:e}=await this.wallet.encrypt({...n,plaintext:s},this.originator);s=e}let a=new i4(this.wallet,this.originator),o=await a.lock([s],n.protocolID,n.keyID,"self"),{outputs:l,BEEF:c}=r.lor;try{let t=this.getInputs(l),{txid:r,signableTransaction:n}=await this.wallet.createAction({description:`Update ${e} in ${this.context}`,inputBEEF:c,inputs:t,outputs:[{basket:this.context,tags:[e],lockingScript:o.toHex(),satoshis:1,outputDescription:"Key-value token"}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(l.length>0&&"object"!=typeof n)throw Error("Wallet did not return a signable transaction when expected.");if(null==n)i=`${r}.0`;else{let t=await this.getSpends(e,l,a,n.tx),{txid:r}=await this.wallet.signAction({reference:n.reference,spends:t},this.originator);i=`${r}.0`}}catch(t){throw Error(`There are ${l.length} outputs with tag ${e} that cannot be unlocked. Original error: ${t instanceof Error?t.message:String(t)}`)}return i}finally{this.finishOperationOnKey(e,i)}}async remove(e){let t=await this.queueOperationOnKey(e);try{let t=[];for(;;){let{outputs:i,BEEF:r,totalOutputs:n}=await this.getOutputs(e);if(i.length>0){let s=new i4(this.wallet,this.originator);try{let n=this.getInputs(i),{signableTransaction:a}=await this.wallet.createAction({description:`Remove ${e} in ${this.context}`,inputBEEF:r,inputs:n,options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if("object"!=typeof a)throw TypeError("Wallet did not return a signable transaction when expected.");let o=await this.getSpends(e,i,s,a.tx),{txid:l}=await this.wallet.signAction({reference:a.reference,spends:o},this.originator);if(void 0===l)throw Error("signAction must return a valid txid");t.push(l)}catch(t){throw Error(`There are ${n} outputs with tag ${e} that cannot be unlocked. Original error: ${t instanceof Error?t.message:String(t)}`)}}if(i.length===n)break}return t}finally{this.finishOperationOnKey(e,t)}}}class sN{interpreter;debug;historyCache;interpreterVersion;ctxKeyFn;constructor(e,t){this.interpreter=e,this.debug=t?.debug??!1,this.historyCache=t?.historyCache,this.interpreterVersion=t?.interpreterVersion??"v1",this.ctxKeyFn=t?.ctxKeyFn??(e=>{try{return JSON.stringify(e??null)}catch{return""}})}historyKey(e,t){let i=e.id("hex"),r=this.ctxKeyFn(t);return`${this.interpreterVersion}|${i}|${r}`}async buildHistory(e,t){if(null!=this.historyCache){let i=this.historyKey(e,t);if(this.historyCache.has(i)){let e=this.historyCache.get(i);if(null!=e)return this.debug&&console.log("[Historian] History cache hit:",i),e.slice()}}let i=[],r=new Set,n=async e=>{let s=e.id("hex");if(r.has(s)){this.debug&&console.log(`[Historian] Skipping already visited transaction: ${s}`);return}r.add(s),this.debug&&console.log(`[Historian] Processing transaction: ${s}`);for(let r=0;r<e.outputs.length;r++)try{let n=await Promise.resolve(this.interpreter(e,r,t));void 0!==n&&(i.push(n),this.debug&&console.log("[Historian] Added value to history:",n))}catch(e){this.debug&&console.log(`[Historian] Failed to interpret output ${r}:`,e)}for(let t of e.inputs)null!=t.sourceTransaction?await n(t.sourceTransaction):this.debug&&console.log("[Historian] Input missing sourceTransaction, skipping")};await n(e);let s=i.toReversed();if(null!=this.historyCache){let i=this.historyKey(e,t);this.historyCache.set(i,Object.freeze(s.slice())),this.debug&&console.log("[Historian] History cached:",i)}return s}}let s_={protocolID:0,key:1,value:2,controller:3,tags:4,signature:5},sR=async(e,t,i)=>{try{let r=e.outputs[t];if(r?.lockingScript==null||i?.key==null)return;let n=i4.decode(r.lockingScript),s=Object.keys(s_).length,a=n.fields.length===s;if(n.fields.length!==s-1&&!a)return;let o=tI(n.fields[s_.key]),l=tI(n.fields[s_.protocolID]);if(o!==i.key||l!==JSON.stringify(i.protocolID))return;try{return tI(n.fields[s_.value])}catch{return}}catch{return}},sC={protocolID:[1,"kvstore"],serviceName:"ls_kvstore",tokenAmount:1,topics:["tm_kvstore"],networkPreset:"mainnet",acceptDelayedBroadcast:!1,overlayBroadcast:!1,tokenSetDescription:"",tokenUpdateDescription:"",tokenRemovalDescription:""};class sB{wallet;config;historian;lookupResolver;topicBroadcaster;keyLocks=new Map;cachedIdentityKey=null;constructor(e={}){this.config={...sC,...e},this.wallet=e.wallet??new nW,this.historian=new sN(sR),this.lookupResolver=new ss({networkPreset:this.config.networkPreset}),this.topicBroadcaster=new so(this.config.topics,{networkPreset:this.config.networkPreset})}async get(e,t={}){if(this.validateQuerySelectors(e),null!=e.key&&null!=e.controller){let i=await this.queryOverlay(e,t);return i.length>0?i[0]:void 0}return await this.queryOverlay(e,t)}validateQuerySelectors(e){if(!("string"==typeof e.key&&e.key.length>0||"string"==typeof e.controller&&e.controller.length>0||Array.isArray(e.protocolID)&&2===e.protocolID.length||Array.isArray(e.tags)&&e.tags.length>0))throw Error("Must specify at least one selector: key, controller, protocolID, or tags")}async set(e,t,i={}){if("string"!=typeof e||0===e.length)throw Error("Key must be a non-empty string.");if("string"!=typeof t)throw TypeError("Value must be a string.");let r=await this.getIdentityKey(),n=await this.queueOperationOnKey(e),s=i.protocolID??this.config.protocolID,a=null!=i.tokenSetDescription&&""!==i.tokenSetDescription?i.tokenSetDescription:`Create KVStore value for ${e}`,o=null!=i.tokenUpdateDescription&&""!==i.tokenUpdateDescription?i.tokenUpdateDescription:`Update KVStore value for ${e}`,l=i.tokenAmount??this.config.tokenAmount,c=i.tags??[];try{let i=new i4(this.wallet,this.config.originator),n=[tm(JSON.stringify(s),"utf8"),tm(e,"utf8"),tm(t,"utf8"),tm(r,"hex")];c.length>0&&n.push(tm(JSON.stringify(c),"utf8"));let h=await i.lock(n,s??this.config.protocolID,tI(tm(e,"utf8")),"anyone",!0);return await sl(async()=>{let t=await this.queryOverlay({key:e,controller:r},{includeToken:!0}),n=t.length>0?t[0].token:void 0;if(null==n){let{tx:e}=await this.wallet.createAction({description:a,outputs:[{satoshis:l??this.config.tokenAmount,lockingScript:h.toHex(),outputDescription:"KVStore token"}],options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast,randomizeOutputs:!1}},this.config.originator);if(null==e)throw Error("Failed to create transaction");let t=rg.fromAtomicBEEF(e);return await this.submitToOverlay(t),`${t.id("hex")}.0`}{let t=[{outpoint:`${n.txid}.${n.outputIndex}`,unlockingScriptLength:74,inputDescription:"Previous KVStore token"}],r=n.beef,{signableTransaction:s}=await this.wallet.createAction({description:o,inputBEEF:r.toBinary(),inputs:t,outputs:[{satoshis:l??this.config.tokenAmount,lockingScript:h.toHex(),outputDescription:"KVStore token"}],options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast,randomizeOutputs:!1}},this.config.originator);if(null==s)throw Error("Unable to create update transaction");let a=rg.fromAtomicBEEF(s.tx),c=i.unlock(this.config.protocolID,e,"anyone"),d=await c.sign(a,0),{tx:u}=await this.wallet.signAction({reference:s.reference,spends:{0:{unlockingScript:d.toHex()}},options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==u)throw Error("Unable to finalize update transaction");let f=rg.fromAtomicBEEF(u);return await this.submitToOverlay(f),`${f.id("hex")}.0`}},this.topicBroadcaster)}finally{n.length>0&&this.finishOperationOnKey(e,n)}}async remove(e,t,i={}){if("string"!=typeof e||0===e.length)throw Error("Key must be a non-empty string.");let r=await this.getIdentityKey(),n=await this.queueOperationOnKey(e),s=i.protocolID??this.config.protocolID,a=null!=i.tokenRemovalDescription&&""!==i.tokenRemovalDescription?i.tokenRemovalDescription:`Remove KVStore value for ${e}`;try{let i=new i4(this.wallet,this.config.originator);return await sl(async()=>{let n=await this.queryOverlay({key:e,controller:r},{includeToken:!0});if(0===n.length||null==n[0].token)throw Error("The item did not exist, no item was deleted.");let o=n[0].token,l=[{outpoint:`${o.txid}.${o.outputIndex}`,unlockingScriptLength:74,inputDescription:"KVStore token to remove"}],{signableTransaction:c}=await this.wallet.createAction({description:a,inputBEEF:o.beef.toBinary(),inputs:l,outputs:t,options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,randomizeOutputs:!1,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==c)throw Error("Unable to create removal transaction");let h=rg.fromAtomicBEEF(c.tx),d=i.unlock(s??this.config.protocolID,e,"anyone"),u=await d.sign(h,0),{tx:f}=await this.wallet.signAction({reference:c.reference,spends:{0:{unlockingScript:u.toHex()}},options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==f)throw Error("Unable to finalize removal transaction");let p=rg.fromAtomicBEEF(f);return await this.submitToOverlay(p),p.id("hex")},this.topicBroadcaster)}finally{n.length>0&&this.finishOperationOnKey(e,n)}}async queueOperationOnKey(e){let t=this.keyLocks.get(e);null==t&&(t=[],this.keyLocks.set(e,t));let i=()=>{},r=new Promise(e=>{i=e,null!=t&&t.push(e)});return 1===t.length&&i(),await r,t}finishOperationOnKey(e,t){t.shift(),t.length>0?t[0]():this.keyLocks.delete(e)}async getIdentityKey(){return this.cachedIdentityKey??=(await this.wallet.getPublicKey({identityKey:!0},this.config.originator)).publicKey,this.cachedIdentityKey}async queryOverlay(e,t={}){let i=await this.lookupResolver.query({service:t.serviceName??this.config.serviceName,query:e});if("output-list"!==i.type||0===i.outputs.length)return[];let r=[];for(let e of i.outputs)try{let i,n=rg.fromBEEF(e.beef),s=n.outputs[e.outputIndex],a=i4.decode(s.lockingScript),o=Object.keys(s_).length,l=a.fields.length===o;if(a.fields.length!==o-1&&!l)continue;let c=new rG("anyone"),h=a.fields.pop();try{await c.verifySignature({data:a.fields.flat(),signature:h,counterparty:tg(a.fields[s_.controller]),protocolID:JSON.parse(tI(a.fields[s_.protocolID])),keyID:tI(a.fields[s_.key])})}catch(e){continue}if(l&&null!=a.fields[s_.tags])try{i=JSON.parse(tI(a.fields[s_.tags]))}catch(e){i=void 0}let d={key:tI(a.fields[s_.key]),value:tI(a.fields[s_.value]),controller:tg(a.fields[s_.controller]),protocolID:JSON.parse(tI(a.fields[s_.protocolID])),tags:i};!0===t.includeToken&&(d.token={txid:n.id("hex"),outputIndex:e.outputIndex,beef:rp.fromBinary(e.beef),satoshis:s.satoshis??1}),!0===t.history&&(d.history=await this.historian.buildHistory(n,{key:d.key,protocolID:d.protocolID})),r.push(d)}catch(e){continue}return r}async submitToOverlay(e){return await this.topicBroadcaster.broadcast(e)}}let sU=sB,sF={new:["identityRequested","invoiced","settled","terminated","errored"],identityRequested:["identityResponded","identityAcknowledged","invoiced","settled","terminated","errored"],identityResponded:["identityAcknowledged","invoiced","settled","terminated","errored"],identityAcknowledged:["invoiced","settled","terminated","errored"],invoiced:["identityRequested","identityResponded","identityAcknowledged","settled","terminated","errored"],settled:["receipted","terminated","errored"],receipted:["terminated","errored"],terminated:["errored"],errored:[]},sD={namespace:"bsv",code:"sat",decimals:0},sL="remittance_inbox";class sV{wallet;comms;cfg;messageBox;now;threadIdFactory;moduleRegistry;runtime;eventListeners;stateWaiters;eventHandlers;defaultPaymentOptionId;threads;myIdentityKey;constructor(e,t,i,r=[]){this.cfg=e,this.wallet=t,this.comms=i,this.messageBox=e.messageBox??sL,this.now=e.now??(()=>Date.now()),this.threadIdFactory=e.threadIdFactory??sK,this.moduleRegistry=new Map(e.remittanceModules.map(e=>[e.id,e])),this.eventListeners=new Set,this.stateWaiters=new Map,this.eventHandlers=e.events,"function"==typeof e.onEvent&&this.eventListeners.add(e.onEvent),this.runtime={identityOptions:e.options?.identityOptions??{makerRequestIdentity:"never",takerRequestIdentity:"never"},receiptProvided:e.options?.receiptProvided??!0,autoIssueReceipt:e.options?.autoIssueReceipt??!0,invoiceExpirySeconds:e.options?.invoiceExpirySeconds??3600,identityTimeoutMs:e.options?.identityTimeoutMs??3e4,identityPollIntervalMs:e.options?.identityPollIntervalMs??500},this.threads=r.map(e=>this.ensureThreadState(e))}async init(){if("function"!=typeof this.cfg.stateLoader)return;let e=await this.cfg.stateLoader();"object"==typeof e&&(this.loadState(e),"string"==typeof e.defaultPaymentOptionId&&(this.defaultPaymentOptionId=e.defaultPaymentOptionId),await this.refreshMyIdentityKey())}onEvent(e){return this.eventListeners.add(e),()=>{this.eventListeners.delete(e)}}preselectPaymentOption(e){this.defaultPaymentOptionId=e}saveState(){return{v:1,threads:JSON.parse(JSON.stringify(this.threads)),defaultPaymentOptionId:this.defaultPaymentOptionId}}loadState(e){if(1!==e.v)throw Error("Unsupported RemittanceManagerState version");this.threads=(e.threads??[]).map(e=>this.ensureThreadState(e)),this.defaultPaymentOptionId=e.defaultPaymentOptionId}async persistState(){null!=this.cfg.stateSaver&&await this.cfg.stateSaver(this.saveState())}async syncThreads(e){for(let t of(await this.refreshMyIdentityKey(),await this.comms.listMessages({messageBox:this.messageBox,host:e})))await this.handleInboundMessage(t)}async startListening(e){if("function"!=typeof this.comms.listenForLiveMessages)throw TypeError("CommsLayer does not support live message listening");await this.comms.listenForLiveMessages({messageBox:this.messageBox,overrideHost:e,onMessage:e=>{this.handleInboundMessage(e)}})}async sendInvoice(e,t,i){await this.refreshMyIdentityKey();let r=this.threadIdFactory(),n=this.now(),s=this.requireMyIdentityKey("sendInvoice requires the wallet to provide an identity key"),a={threadId:r,counterparty:e,myRole:"maker",theirRole:"taker",createdAt:n,updatedAt:n,state:"new",stateLog:[],processedMessageIds:[],protocolLog:[],identity:{certsSent:[],certsReceived:[],requestSent:!1,responseSent:!1,acknowledgmentSent:!1,acknowledgmentReceived:!1},flags:{hasIdentified:!1,hasInvoiced:!1,hasPaid:!1,hasReceipted:!1,error:!1}};this.threads.push(a),this.emitEvent({type:"threadCreated",threadId:a.threadId,thread:a}),a.identity.responseSent&&!a.flags.hasIdentified&&await this.waitForIdentityAcknowledgment(r,{timeoutMs:this.runtime.identityTimeoutMs,pollIntervalMs:this.runtime.identityPollIntervalMs}),this.shouldRequestIdentity(a,"beforeInvoicing")&&await this.ensureIdentityExchange(a,i);let o=await this.composeInvoice(r,s,e,t);for(let e of(a.invoice=o,a.flags.hasInvoiced=!0,this.transitionThreadState(a,"invoiced","invoice created"),this.moduleRegistry.values())){if("function"!=typeof e.createOption)continue;let t=await e.createOption({threadId:r,invoice:o},this.moduleContext());o.options[e.id]=t}let l=this.makeEnvelope("invoice",r,o),c=await this.sendEnvelope(e,l,i);return a.protocolLog.push({direction:"out",envelope:l,transportMessageId:c}),this.emitEvent({type:"invoiceSent",threadId:a.threadId,invoice:o}),a.updatedAt=this.now(),await this.persistState(),new sM(this,r)}async sendInvoiceForThread(e,t,i){await this.refreshMyIdentityKey();let r=this.getThreadOrThrow(e);if(r.flags.error)throw Error("Thread is in error state");if("maker"!==r.myRole)throw Error("Only makers can send invoices");if(null!=r.invoice)throw Error("Thread already has an invoice");r.identity.responseSent&&!r.flags.hasIdentified&&await this.waitForIdentityAcknowledgment(e,{timeoutMs:this.runtime.identityTimeoutMs,pollIntervalMs:this.runtime.identityPollIntervalMs}),this.shouldRequestIdentity(r,"beforeInvoicing")&&await this.ensureIdentityExchange(r,i);let n=this.requireMyIdentityKey("sendInvoice requires the wallet to provide an identity key"),s=await this.composeInvoice(e,n,r.counterparty,t);for(let t of(r.invoice=s,r.flags.hasInvoiced=!0,this.transitionThreadState(r,"invoiced","invoice created"),this.moduleRegistry.values())){if("function"!=typeof t.createOption)continue;let i=await t.createOption({threadId:e,invoice:s},this.moduleContext());s.options[t.id]=i}let a=this.makeEnvelope("invoice",e,s),o=await this.sendEnvelope(r.counterparty,a,i);return r.protocolLog.push({direction:"out",envelope:a,transportMessageId:o}),this.emitEvent({type:"invoiceSent",threadId:r.threadId,invoice:s}),r.updatedAt=this.now(),await this.persistState(),new sM(this,e)}findInvoicesPayable(e){let t="string"==typeof e&&e.length>0;return this.threads.filter(e=>"taker"===e.myRole&&null!=e.invoice&&null==e.settlement&&!e.flags.error).filter(i=>!t||i.counterparty===e).map(e=>new sM(this,e.threadId))}findReceivableInvoices(e){let t="string"==typeof e&&e.length>0;return this.threads.filter(e=>"maker"===e.myRole&&null!=e.invoice&&null==e.settlement&&!e.flags.error).filter(i=>!t||i.counterparty===e).map(e=>new sM(this,e.threadId))}async pay(e,t,i){await this.refreshMyIdentityKey();let r=this.getThreadOrThrow(e);if(null==r.invoice)throw Error("Thread has no invoice to pay");if(r.flags.error)throw Error("Thread is in error state");if(null!=r.settlement)throw Error("Invoice already paid (settlement exists)");r.identity.responseSent&&!r.flags.hasIdentified&&await this.waitForIdentityAcknowledgment(e,{timeoutMs:this.runtime.identityTimeoutMs,pollIntervalMs:this.runtime.identityPollIntervalMs}),this.shouldRequestIdentity(r,"beforeSettlement")&&await this.ensureIdentityExchange(r,i);let n=r.invoice.expiresAt;if("number"==typeof n&&this.now()>n)throw Error("Invoice is expired");let s=t??this.defaultPaymentOptionId??Object.keys(r.invoice.options)[0];if(null==s||""===s)throw Error("No remittance options available on invoice");let a=this.moduleRegistry.get(s);if(null==a)throw Error(`No configured remittance module for option: ${s}`);let o=r.invoice.options[s],l=this.requireMyIdentityKey("pay() requires the wallet to provide an identity key"),c=await a.buildSettlement({threadId:e,invoice:r.invoice,option:o,note:r.invoice.note},this.moduleContext());if("terminate"===c.action){let e=c.termination;return await this.sendTermination(r,r.counterparty,e.message,e.details,e.code),await this.persistState(),e}let h={kind:"settlement",threadId:e,moduleId:a.id,optionId:s,sender:l,createdAt:this.now(),artifact:c.artifact,note:r.invoice.note},d=this.makeEnvelope("settlement",e,h),u=await this.sendEnvelope(r.invoice.payee,d,i);if(r.protocolLog.push({direction:"out",envelope:d,transportMessageId:u}),this.emitEvent({type:"settlementSent",threadId:r.threadId,settlement:h}),r.settlement=h,r.flags.hasPaid=!0,this.transitionThreadState(r,"settled","settlement sent"),r.updatedAt=this.now(),await this.persistState(),this.runtime.receiptProvided)return await this.waitForReceipt(e)}async waitForReceipt(e,t={}){let i=t.timeoutMs??3e4,r=t.pollIntervalMs??500,n=this.now();for(;this.now()-n<i;){let t=this.getThreadOrThrow(e);if("object"==typeof t.receipt)return t.receipt;if("object"==typeof t.termination)return t.termination;await this.syncThreads(),await sq(r)}throw Error("Timed out waiting for receipt")}async waitForState(e,t,i={}){let r,n,s=i.timeoutMs??3e4,a=i.pollIntervalMs??500,o=this.now(),l=this.getThreadOrThrow(e);if(l.state===t)return l;if("terminated"===l.state||"errored"===l.state)throw Error(`Thread entered terminal state: ${l.state}`);let c=!1,h=!1,d={state:t,resolve:()=>{c||h||(c=!0,r())},reject:e=>{c||h||(c=!0,n(e))}},u=new Promise((t,i)=>{r=t,n=i;let s=this.stateWaiters.get(e)??[];s.push(d),this.stateWaiters.set(e,s)}),f=()=>{let t=this.stateWaiters.get(e);if(null==t)return;let i=t.filter(e=>e!==d);0===i.length?this.stateWaiters.delete(e):this.stateWaiters.set(e,i)},p=(async()=>{for(;this.now()-o<s;){if(c)return;let i=this.getThreadOrThrow(e);if(i.state===t)return void this.resolveStateWaiters(e,t);if("terminated"===i.state||"errored"===i.state)throw Error(`Thread entered terminal state: ${i.state}`);await this.syncThreads(),await sq(a)}})();if(await Promise.race([u,p]).catch(e=>{throw f(),e}),this.now()-o>=s&&!c)throw h=!0,f(),Error(`Timed out waiting for state: ${t}`);return f(),this.getThreadOrThrow(e)}async waitForIdentity(e,t){return await this.waitForState(e,"identityAcknowledged",t)}async waitForSettlement(e,t={}){let i=t.timeoutMs??3e4,r=t.pollIntervalMs??500,n=this.now();for(;this.now()-n<i;){let t=this.getThreadOrThrow(e);if("object"==typeof t.settlement)return t.settlement;if("object"==typeof t.termination)return t.termination;await this.syncThreads(),await sq(r)}throw Error("Timed out waiting for settlement")}async sendUnsolicitedSettlement(e,t,i){await this.refreshMyIdentityKey();let r=this.moduleRegistry.get(t.moduleId);if(null==r)throw Error(`No configured remittance module for option: ${t.moduleId}`);if(!r.allowUnsolicitedSettlements)throw Error(`Remittance module ${t.moduleId} does not allow unsolicited settlements`);let n=this.threadIdFactory(),s=this.now(),a=this.requireMyIdentityKey("sendUnsolicitedSettlement requires the wallet to provide an identity key"),o={threadId:n,counterparty:e,myRole:"taker",theirRole:"maker",createdAt:s,updatedAt:s,state:"new",stateLog:[],processedMessageIds:[],protocolLog:[],identity:{certsSent:[],certsReceived:[],requestSent:!1,responseSent:!1,acknowledgmentSent:!1,acknowledgmentReceived:!1},flags:{hasIdentified:!1,hasInvoiced:!1,hasPaid:!1,hasReceipted:!1,error:!1}};this.threads.push(o),this.emitEvent({type:"threadCreated",threadId:o.threadId,thread:o}),this.shouldRequestIdentity(o,"beforeSettlement")&&await this.ensureIdentityExchange(o,i);let l=await r.buildSettlement({threadId:n,option:t.option,note:t.note},this.moduleContext());if("terminate"===l.action)return await this.sendTermination(o,e,l.termination.message,l.termination.details,l.termination.code),await this.persistState(),new sH(this,n);let c={kind:"settlement",threadId:n,moduleId:r.id,optionId:t.optionId??r.id,sender:a,createdAt:this.now(),artifact:l.artifact,note:t.note},h=this.makeEnvelope("settlement",n,c),d=await this.sendEnvelope(e,h,i);return o.protocolLog.push({direction:"out",envelope:h,transportMessageId:d}),this.emitEvent({type:"settlementSent",threadId:o.threadId,settlement:c}),o.settlement=c,o.flags.hasPaid=!0,this.transitionThreadState(o,"settled","settlement sent"),o.updatedAt=this.now(),await this.persistState(),new sH(this,n)}getThread(e){return this.threads.find(t=>t.threadId===e)}getThreadHandle(e){return this.getThreadOrThrow(e),new sH(this,e)}getThreadOrThrow(e){let t=this.getThread(e);if("object"!=typeof t)throw Error(`Unknown thread: ${e}`);return this.ensureThreadState(t)}moduleContext(){return{wallet:this.wallet,originator:this.cfg.originator,now:this.now,logger:this.cfg.logger}}makeEnvelope(e,t,i){return{v:1,id:this.threadIdFactory(),kind:e,threadId:t,createdAt:this.now(),payload:i}}async sendEnvelope(e,t,i){let r=JSON.stringify(t);if("function"==typeof this.comms.sendLiveMessage)try{let n=await this.comms.sendLiveMessage({recipient:e,messageBox:this.messageBox,body:r},i);return this.emitEvent({type:"envelopeSent",threadId:t.threadId,envelope:t,transportMessageId:n}),n}catch(e){this.cfg.logger?.warn?.("[RemittanceManager] sendLiveMessage failed, falling back to non-live",e)}let n=await this.comms.sendMessage({recipient:e,messageBox:this.messageBox,body:r},i);return this.emitEvent({type:"envelopeSent",threadId:t.threadId,envelope:t,transportMessageId:n}),n}getOrCreateThreadFromInboundEnvelope(e,t){let i=this.getThread(e.threadId);if("object"==typeof i)return i;let r=this.now(),n=(()=>{if("invoice"===e.kind)return"taker";if("settlement"===e.kind)return"maker";if("receipt"===e.kind||"termination"===e.kind)return"taker";if("identityVerificationRequest"===e.kind||"identityVerificationResponse"===e.kind||"identityVerificationAcknowledgment"===e.kind){let t,i=this.runtime.identityOptions?.makerRequestIdentity??"never",r=this.runtime.identityOptions?.takerRequestIdentity??"never",n="never"!==i,s="never"!==r;return(n&&!s?t="maker":s&&!n?t="taker":n&&s&&i!==r&&(t="beforeInvoicing"===i&&"beforeSettlement"===r?"maker":"beforeSettlement"===i&&"beforeInvoicing"===r?"taker":void 0),"string"!=typeof t)?"taker":"identityVerificationResponse"===e.kind?t:"maker"===t?"taker":"maker"}return"taker"})(),s={threadId:e.threadId,counterparty:t.sender,myRole:n,theirRole:"maker"===n?"taker":"maker",createdAt:r,updatedAt:r,state:"new",stateLog:[],processedMessageIds:[],protocolLog:[],identity:{certsSent:[],certsReceived:[],requestSent:!1,responseSent:!1,acknowledgmentSent:!1,acknowledgmentReceived:!1},flags:{hasIdentified:!1,hasInvoiced:!1,hasPaid:!1,hasReceipted:!1,error:!1}};return this.threads.push(s),this.emitEvent({type:"threadCreated",threadId:s.threadId,thread:s}),s}async handleInboundMessage(e){let t=function(e){try{let t=JSON.parse(e);if("object"!=typeof t||1!==t.v||"string"!=typeof t.kind||"string"!=typeof t.threadId||"string"!=typeof t.id)return;return t}catch{return}}(e.body);if(null==t)return;let i=this.getOrCreateThreadFromInboundEnvelope(t,e);if(i.processedMessageIds.includes(e.messageId))return void await this.safeAck([e.messageId]);try{await this.applyInboundEnvelope(i,t,e),i.processedMessageIds.push(e.messageId),i.updatedAt=this.now(),await this.persistState(),await this.safeAck([e.messageId])}catch(e){this.markThreadError(i,e),await this.persistState()}}async applyInboundEnvelope(e,t,i){switch(e.protocolLog.push({direction:"in",envelope:t,transportMessageId:i.messageId}),this.emitEvent({type:"envelopeReceived",threadId:e.threadId,envelope:t,transportMessageId:i.messageId}),t.kind){case"identityVerificationRequest":{let r=t.payload;if("object"!=typeof r)throw TypeError("Identity verification request payload missing data");if(null==this.cfg.identityLayer)return void await this.sendTermination(e,i.sender,"Identity verification requested but no identity layer is configured");this.transitionThreadState(e,"identityRequested","identity request received"),this.emitEvent({type:"identityRequested",threadId:e.threadId,direction:"in",request:r});let n=await this.cfg.identityLayer.respondToRequest({counterparty:i.sender,threadId:e.threadId,request:r},this.moduleContext());if("terminate"===n.action)return void await this.sendTermination(e,i.sender,n.termination.message,n.termination.details,n.termination.code);let s=this.makeEnvelope("identityVerificationResponse",e.threadId,n.response),a=await this.sendEnvelope(i.sender,s);e.protocolLog.push({direction:"out",envelope:s,transportMessageId:a}),e.identity.certsSent=n.response.certificates,e.identity.responseSent=!0,this.transitionThreadState(e,"identityResponded","identity response sent"),this.emitEvent({type:"identityResponded",threadId:e.threadId,direction:"out",response:n.response});return}case"identityVerificationResponse":{let r=t.payload;if("object"!=typeof r)throw TypeError("Identity verification response payload missing data");if(null==this.cfg.identityLayer)return void await this.sendTermination(e,i.sender,"Identity verification response received but no identity layer is configured");e.identity.certsReceived=r.certificates,this.transitionThreadState(e,"identityResponded","identity response received"),this.emitEvent({type:"identityResponded",threadId:e.threadId,direction:"in",response:r});let n=await this.cfg.identityLayer.assessReceivedCertificateSufficiency(i.sender,r,e.threadId);if("message"in n)return void await this.sendTermination(e,i.sender,n.message,n.details,n.code);if("identityVerificationAcknowledgment"===n.kind){let t=this.makeEnvelope("identityVerificationAcknowledgment",e.threadId,n),r=await this.sendEnvelope(i.sender,t);e.protocolLog.push({direction:"out",envelope:t,transportMessageId:r}),e.identity.acknowledgmentSent=!0,e.flags.hasIdentified=!0,this.transitionThreadState(e,"identityAcknowledged","identity acknowledgment sent"),this.emitEvent({type:"identityAcknowledged",threadId:e.threadId,direction:"out",acknowledgment:n});return}throw Error("Unknown identity verification decision")}case"identityVerificationAcknowledgment":{let i=t.payload;if("object"!=typeof i)throw TypeError("Identity verification acknowledgment payload missing data");e.identity.acknowledgmentReceived=!0,e.flags.hasIdentified=!0,this.transitionThreadState(e,"identityAcknowledged","identity acknowledgment received"),this.emitEvent({type:"identityAcknowledged",threadId:e.threadId,direction:"in",acknowledgment:i});return}case"invoice":{let i=t.payload;if("object"!=typeof i)throw TypeError("Invoice payload missing invoice data");e.invoice=i,e.flags.hasInvoiced=!0,this.transitionThreadState(e,"invoiced","invoice received"),this.emitEvent({type:"invoiceReceived",threadId:e.threadId,invoice:i});return}case"settlement":{let r=t.payload;if("object"!=typeof r)throw TypeError("Settlement payload missing settlement data");if(this.shouldRequireIdentityBeforeSettlement(e)&&!e.flags.hasIdentified)return void await this.sendTermination(e,i.sender,"Identity verification is required before settlement");e.settlement=r,e.flags.hasPaid=!0,this.transitionThreadState(e,"settled","settlement received"),this.emitEvent({type:"settlementReceived",threadId:e.threadId,settlement:r});let n=this.moduleRegistry.get(r.moduleId);if("object"!=typeof n)return void await this.maybeSendTermination(e,r,i.sender,`Unsupported module: ${r.moduleId}`);if(null==e.invoice&&!n.allowUnsolicitedSettlements)return void await this.maybeSendTermination(e,r,i.sender,"Unsolicited settlement not supported");let s=await n.acceptSettlement({threadId:e.threadId,invoice:e.invoice,settlement:r.artifact,sender:i.sender},this.moduleContext()).catch(async t=>{let n=t instanceof Error?t.message:String(t);throw await this.maybeSendTermination(e,r,i.sender,`Settlement processing failed: ${n}`),t});if("accept"===s.action){let t=this.requireMyIdentityKey("Receiving settlement requires identity key"),n=i.sender,a={kind:"receipt",threadId:e.threadId,moduleId:r.moduleId,optionId:r.optionId,payee:t,payer:n,createdAt:this.now(),receiptData:s.receiptData};if(e.receipt=a,e.flags.hasReceipted=!0,this.transitionThreadState(e,"receipted","receipt issued"),this.runtime.receiptProvided&&this.runtime.autoIssueReceipt){let t=this.makeEnvelope("receipt",e.threadId,a),r=await this.sendEnvelope(i.sender,t);e.protocolLog.push({direction:"out",envelope:t,transportMessageId:r}),this.emitEvent({type:"receiptSent",threadId:e.threadId,receipt:a})}}else if("terminate"===s.action)await this.maybeSendTermination(e,r,i.sender,s.termination.message,s.termination.details);else throw Error("Unknown settlement acceptance action");return}case"receipt":{let r=t.payload;if("object"!=typeof r)throw TypeError("Receipt payload missing receipt data");e.receipt=r,e.flags.hasReceipted=!0,this.transitionThreadState(e,"receipted","receipt received"),this.emitEvent({type:"receiptReceived",threadId:e.threadId,receipt:r});let n=this.moduleRegistry.get(r.moduleId);n?.processReceipt!=null&&await n.processReceipt({threadId:e.threadId,invoice:e.invoice,receiptData:r.receiptData,sender:i.sender},this.moduleContext());return}case"termination":{let r=t.payload;if("object"!=typeof r)throw TypeError("Termination payload missing data");if(e.termination=r,e.lastError={message:r.message,at:this.now()},e.flags.error=!0,this.transitionThreadState(e,"terminated","termination received"),this.emitEvent({type:"terminationReceived",threadId:e.threadId,termination:r}),null!=e.settlement){let t=this.moduleRegistry.get(e.settlement.moduleId);t?.processTermination!=null&&await t.processTermination({threadId:e.threadId,invoice:e.invoice,settlement:e.settlement,termination:r,sender:i.sender},this.moduleContext())}return}default:{let e=t.kind;throw Error(`Unknown envelope kind: ${String(e)}`)}}}async maybeSendTermination(e,t,i,r,n){let s={code:"error",message:r,details:n},a=this.makeEnvelope("termination",e.threadId,s),o=await this.sendEnvelope(i,a);e.protocolLog.push({direction:"out",envelope:a,transportMessageId:o}),this.emitEvent({type:"terminationSent",threadId:e.threadId,termination:s}),e.termination=s,e.lastError={message:`Sent termination: ${r}`,at:this.now()},e.flags.error=!0,this.transitionThreadState(e,"terminated","termination sent")}async sendTermination(e,t,i,r,n="error"){let s={code:n,message:i,details:r},a=this.makeEnvelope("termination",e.threadId,s),o=await this.sendEnvelope(t,a);e.protocolLog.push({direction:"out",envelope:a,transportMessageId:o}),this.emitEvent({type:"terminationSent",threadId:e.threadId,termination:s}),e.termination=s,e.lastError={message:`Sent termination: ${i}`,at:this.now()},e.flags.error=!0,this.transitionThreadState(e,"terminated","termination sent")}shouldRequestIdentity(e,t){let{makerRequestIdentity:i="never",takerRequestIdentity:r="never"}=this.runtime.identityOptions??{};if(!("maker"===e.myRole?i===t:r===t))return!1;if(null==this.cfg.identityLayer)throw Error("Identity layer is required by runtime options but is not configured");return!0}shouldRequireIdentityBeforeSettlement(e){return"maker"===e.myRole&&(this.runtime.identityOptions?.makerRequestIdentity??"never")==="beforeSettlement"}async ensureIdentityExchange(e,t){if(null!=this.cfg.identityLayer&&!e.flags.hasIdentified){if(!e.identity.requestSent){let i=await this.cfg.identityLayer.determineCertificatesToRequest({counterparty:e.counterparty,threadId:e.threadId},this.moduleContext()),r=this.makeEnvelope("identityVerificationRequest",e.threadId,i),n=await this.sendEnvelope(e.counterparty,r,t);e.protocolLog.push({direction:"out",envelope:r,transportMessageId:n}),e.identity.requestSent=!0,this.transitionThreadState(e,"identityRequested","identity request sent"),this.emitEvent({type:"identityRequested",threadId:e.threadId,direction:"out",request:i}),e.updatedAt=this.now(),await this.persistState()}await this.waitForIdentityAcknowledgment(e.threadId,{timeoutMs:this.runtime.identityTimeoutMs,pollIntervalMs:this.runtime.identityPollIntervalMs})}}async waitForIdentityAcknowledgment(e,t={}){await this.waitForState(e,"identityAcknowledged",t)}async safeAck(e){try{await this.comms.acknowledgeMessage({messageIds:e})}catch(e){this.cfg.logger?.warn?.("[RemittanceManager] Failed to acknowledge message(s)",e)}}markThreadError(e,t){e.flags.error=!0,this.transitionThreadState(e,"errored","thread error"),e.lastError={message:String(t?.message??t),at:this.now()},this.cfg.logger?.error?.("[RemittanceManager] Thread error",e.threadId,t),this.emitEvent({type:"error",threadId:e.threadId,error:String(t?.message??t)})}ensureThreadState(e){return e.identity=e.identity??{certsSent:[],certsReceived:[],requestSent:!1,responseSent:!1,acknowledgmentSent:!1,acknowledgmentReceived:!1},e.identity.certsSent??=[],e.identity.certsReceived??=[],e.identity.requestSent??=!1,e.identity.responseSent??=!1,e.identity.acknowledgmentSent??=!1,e.identity.acknowledgmentReceived??=!1,e.flags=e.flags??{hasIdentified:!1,hasInvoiced:!1,hasPaid:!1,hasReceipted:!1,error:!1},e.processedMessageIds??=[],e.protocolLog??=[],e.stateLog??=[],e.state??=this.deriveThreadState(e),e}deriveThreadState(e){return e.flags.error?"errored":null!=e.termination?"terminated":null!=e.receipt?"receipted":null!=e.settlement?"settled":null!=e.invoice?"invoiced":e.identity.acknowledgmentReceived||e.identity.acknowledgmentSent||e.flags.hasIdentified?"identityAcknowledged":e.identity.responseSent||e.identity.certsSent.length>0?"identityResponded":e.identity.requestSent||e.identity.certsReceived.length>0?"identityRequested":"new"}transitionThreadState(e,t,i){let r=e.state;if(r!==t){if(!(sF[r]??[]).includes(t))throw Error(`Invalid remittance state transition: ${r} -> ${t}`);e.state=t,e.updatedAt=this.now(),e.stateLog.push({at:this.now(),from:r,to:t,reason:i}),this.emitEvent({type:"stateChanged",threadId:e.threadId,previous:r,next:t,reason:i}),this.resolveStateWaiters(e.threadId,t),("terminated"===t||"errored"===t)&&this.rejectStateWaiters(e.threadId,Error(`Thread entered terminal state: ${t}`))}}resolveStateWaiters(e,t){let i=this.stateWaiters.get(e);if(null==i)return;let r=[];for(let e of i)e.state===t?e.resolve():r.push(e);0===r.length?this.stateWaiters.delete(e):this.stateWaiters.set(e,r)}rejectStateWaiters(e,t){let i=this.stateWaiters.get(e);if(null!=i){for(let e of i)e.reject(t);this.stateWaiters.delete(e)}}emitEvent(e){let t=this.eventHandlers;if(null!=t)try{switch(e.type){case"threadCreated":t.onThreadCreated?.(e);break;case"stateChanged":t.onStateChanged?.(e);break;case"envelopeSent":t.onEnvelopeSent?.(e);break;case"envelopeReceived":t.onEnvelopeReceived?.(e);break;case"identityRequested":t.onIdentityRequested?.(e);break;case"identityResponded":t.onIdentityResponded?.(e);break;case"identityAcknowledged":t.onIdentityAcknowledged?.(e);break;case"invoiceSent":t.onInvoiceSent?.(e);break;case"invoiceReceived":t.onInvoiceReceived?.(e);break;case"settlementSent":t.onSettlementSent?.(e);break;case"settlementReceived":t.onSettlementReceived?.(e);break;case"receiptSent":t.onReceiptSent?.(e);break;case"receiptReceived":t.onReceiptReceived?.(e);break;case"terminationSent":t.onTerminationSent?.(e);break;case"terminationReceived":t.onTerminationReceived?.(e);break;case"error":t.onError?.(e)}}catch(e){this.cfg.logger?.warn?.("[RemittanceManager] Event handler error",e)}for(let t of this.eventListeners)try{t(e)}catch(e){this.cfg.logger?.warn?.("[RemittanceManager] Event listener error",e)}}async refreshMyIdentityKey(){if("string"==typeof this.myIdentityKey||"object"!=typeof this.wallet)return;let{publicKey:e}=await this.wallet.getPublicKey({identityKey:!0},this.cfg.originator);"string"==typeof e&&""!==e.trim()&&(this.myIdentityKey=e)}requireMyIdentityKey(e){if("string"!=typeof this.myIdentityKey)throw TypeError(e);return this.myIdentityKey}async composeInvoice(e,t,i,r){let n=this.now(),s=this.runtime.invoiceExpirySeconds>=0?n+1e3*this.runtime.invoiceExpirySeconds:void 0;return{kind:"invoice",threadId:e,payee:t,payer:i,note:r.note,lineItems:r.lineItems,total:r.total,invoiceNumber:r.invoiceNumber??e,createdAt:n,expiresAt:s,arbitrary:r.arbitrary,options:{}}}}class sH{manager;threadId;constructor(e,t){this.manager=e,this.threadId=t}get thread(){return this.manager.getThreadOrThrow(this.threadId)}async waitForState(e,t){return await this.manager.waitForState(this.threadId,e,t)}async waitForIdentity(e){return await this.manager.waitForIdentity(this.threadId,e)}async waitForSettlement(e){return await this.manager.waitForSettlement(this.threadId,e)}async waitForReceipt(e){return await this.manager.waitForReceipt(this.threadId,e)}}class sM extends sH{get invoice(){let e=this.thread.invoice;if("object"!=typeof e)throw Error("Thread has no invoice");return e}async pay(e){return await this.manager.pay(this.threadId,e)}}function sK(){return tS(ia(32))}async function sq(e){return await new Promise(t=>setTimeout(t,e))}let s$={createNonce:async(e,t,i)=>await nQ(e,t,i)},sz={async pubKeyToP2PKHLockingScript(e){let t=ii.fromString(e).toAddress();return new i3().lock(t).toHex()}};class sW{id="brc29.p2pkh";name="BSV (BRC-29 derived P2PKH)";allowUnsolicitedSettlements=!0;protocolID;labels;description;outputDescription;refundFeeSatoshis;minRefundSatoshis;internalizeProtocol;nonceProvider;lockingScriptProvider;constructor(e={}){this.protocolID=e.protocolID??[2,"3241645161d8"],this.labels=e.labels??["brc29"],this.description=e.description??"BRC-29 payment",this.outputDescription=e.outputDescription??"Payment for remittance invoice",this.refundFeeSatoshis=e.refundFeeSatoshis??1e3,this.minRefundSatoshis=e.minRefundSatoshis??1e3,this.internalizeProtocol=e.internalizeProtocol??"wallet payment",this.nonceProvider=e.nonceProvider??s$,this.lockingScriptProvider=e.lockingScriptProvider??sz}async buildSettlement(e,t){let i,{wallet:r,originator:n}=t;try{i=function(e){if(null==e||"object"!=typeof e)throw Error("BRC-29 option terms are required");let t=e.amountSatoshis;if(!Number.isInteger(t)||t<=0)throw Error("BRC-29 option amount must be a positive integer");let i=e.outputIndex;if(null!=i&&(!Number.isInteger(i)||i<0))throw Error("BRC-29 option outputIndex must be a non-negative integer");let r=e.protocolID;if(null!=r){if(!Array.isArray(r)||2!==r.length)throw Error("BRC-29 option protocolID must be a tuple [number, string]");let[e,t]=r;if(!Number.isInteger(e)||e<0||!sX(t))throw Error("BRC-29 option protocolID must be a tuple [number, string]")}let n=e.labels;if(null!=n&&(!Array.isArray(n)||n.some(e=>!sX(e))))throw Error("BRC-29 option labels must be a list of non-empty strings");let s=e.description;if(null!=s&&!sX(s))throw Error("BRC-29 option description must be a non-empty string");return e}(e.option)}catch(e){return sj("brc29.invalid_option",e instanceof Error?e.message:String(e))}let s=i.amountSatoshis;try{let t=await this.nonceProvider.createNonce(r,"self",n),a=await this.nonceProvider.createNonce(r,"self",n),o=i.protocolID??this.protocolID,l=`${t} ${a}`,{publicKey:c}=await r.getPublicKey({protocolID:o,keyID:l,counterparty:i.payee},n);if("string"!=typeof c||""===c.trim())return sj("brc29.public_key_missing","Failed to derive payee public key for BRC-29 settlement.");let h=await this.lockingScriptProvider.pubKeyToP2PKHLockingScript(c);if("string"!=typeof h||""===h.trim())return sj("brc29.locking_script_missing","Failed to produce P2PKH locking script.");let d=await r.createAction({description:i.description??this.description,labels:i.labels??this.labels,outputs:[{satoshis:s,lockingScript:h,customInstructions:JSON.stringify({derivationPrefix:t,derivationSuffix:a,payee:i.payee,threadId:e.threadId,note:e.note}),outputDescription:this.outputDescription}],options:{randomizeOutputs:!1}},n),u=d.tx??d.signableTransaction?.tx;if(null==u)return sj("brc29.missing_tx","wallet.createAction did not return a transaction.");if(!sG(u))return sj("brc29.invalid_tx","wallet.createAction returned an invalid transaction payload.");return{action:"settle",artifact:{customInstructions:{derivationPrefix:t,derivationSuffix:a},transaction:u,amountSatoshis:i.amountSatoshis,outputIndex:i.outputIndex??0}}}catch(t){let e=t instanceof Error?t.message:String(t);return sj("brc29.build_failed",`BRC-29 settlement failed: ${e}`)}}async acceptSettlement(e,t){let{wallet:i,originator:r}=t;console.log("acceptSettlement",e);try{let t=function(e){if(null==e||"object"!=typeof e)throw Error("BRC-29 settlement artifact is required");let t=e.customInstructions;if(null==t||"object"!=typeof t)throw Error("BRC-29 settlement requires customInstructions");if(!sX(t.derivationPrefix)||!sX(t.derivationSuffix))throw Error("BRC-29 settlement derivation values are required");let i=e.amountSatoshis;if(!Number.isInteger(i)||i<=0)throw Error("BRC-29 settlement amount must be a positive integer");let r=e.outputIndex;if(null!=r&&(!Number.isInteger(r)||r<0))throw Error("BRC-29 settlement outputIndex must be a non-negative integer");if(!sG(e.transaction))throw Error("BRC-29 settlement transaction must be a non-empty byte array");return e}(e.settlement),n=t.outputIndex??0,s=await i.internalizeAction({tx:t.transaction,outputs:[{paymentRemittance:{derivationPrefix:t.customInstructions.derivationPrefix,derivationSuffix:t.customInstructions.derivationSuffix,senderIdentityKey:e.sender},outputIndex:n,protocol:this.internalizeProtocol}],labels:this.labels,description:"BRC-29 payment received"},r);return{action:"accept",receiptData:{internalizeResult:s}}}catch(t){let e=t instanceof Error?t.message:String(t);return sj("brc29.internalize_failed",`Failed to internalize BRC-29 settlement: ${e}`)}}}function sj(e,t,i){return{action:"terminate",termination:{code:e,message:t,details:i}}}function sG(e){return!!Array.isArray(e)&&0!==e.length&&e.every(e=>Number.isInteger(e)&&e>=0&&e<=255)}function sX(e){return"string"==typeof e&&e.trim().length>0}return p})());
|
|
19
|
+
`);return e}addComputedLeaves(){for(let e of this.bumps)for(let t=1;t<e.path.length;t++)this.addComputedLeavesForRow(e,t)}addComputedLeavesForRow(e,t){let i=e=>tg(ek(tm(e,"hex").reverse()).reverse());for(let r of e.path[t-1]){if("string"!=typeof r.hash||(1&r.offset)!=0)continue;let n=e.path[t-1].find(e=>e.offset===r.offset+1);if(void 0===n||"string"!=typeof n.hash)continue;let s=r.offset>>1;e.path[t].every(e=>e.offset!==s)&&e.path[t].push({offset:s,hash:i(n.hash+r.hash)})}}}class rg{version;inputs;outputs;lockTime;metadata;merklePath;cachedHash;rawBytesCache;hexCache;static addPathOrInputs(e,t,i){if("number"==typeof e.pathIndex){let t=i[e.pathIndex];if("object"!=typeof t)throw TypeError("Invalid merkle path index found in BEEF!");e.tx.merklePath=t}else for(let r of e.tx.inputs){if(void 0===r.sourceTXID)throw Error("Input sourceTXID is undefined");let e=t[r.sourceTXID];if("object"!=typeof e)throw TypeError(`Reference to unknown TXID in BEEF: ${r.sourceTXID??"undefined"}`);r.sourceTransaction=e.tx,this.addPathOrInputs(e,t,i)}}static fromBEEF(e,t){let{tx:i}=rg.fromAnyBeef(e,t);return i}static fromAtomicBEEF(e){let{tx:t,txid:i,beef:r}=rg.fromAnyBeef(e);if(i!==r.atomicTxid)if(null==r.atomicTxid)throw Error("beef must conform to BRC-95 and must contain the subject txid.");else throw Error(`Transaction with TXID ${r.atomicTxid} not found in BEEF data.`);return t}static fromAnyBeef(e,t){let i=rp.fromBinary(e);if(i.txs.length<1)throw Error("beef must include at least one transaction.");let r=i.txs.at(-1);if(null==r)throw Error("beef must include at least one transaction.");let n=t??i.atomicTxid??r.txid,s=i.findAtomicTransaction(n);if(null==s)if(null==t)throw Error("beef does not contain transaction for atomic txid.");else throw Error(`Transaction with TXID ${String(n)} not found in BEEF data.`);return{tx:s,beef:i,txid:n}}static fromEF(e){let t=tc.makeReader(e),i=t.readUInt32LE();if("0000000000ef"!==tg(t.read(6)))throw Error("Invalid EF marker");let r=t.readVarIntNum(),n=[];for(let e=0;e<r;e++){let e=tg(t.readReverse(32)),i=t.readUInt32LE(),r=t.readVarIntNum(),s=t.read(r),a=iG.fromBinary(s),o=t.readUInt32LE(),l=t.readUInt64LEBn().toNumber(),c=t.readVarIntNum(),h=t.read(c),d=ij.fromBinary(h),u=new rg(void 0,[],[],void 0);u.outputs=Array(i+1).fill(null),u.outputs[i]={satoshis:l,lockingScript:d},n.push({sourceTransaction:u,sourceTXID:e,sourceOutputIndex:i,unlockingScript:a,sequence:o})}let s=t.readVarIntNum(),a=[];for(let e=0;e<s;e++){let e=t.readUInt64LEBn().toNumber(),i=t.readVarIntNum(),r=t.read(i),n=ij.fromBinary(r);a.push({satoshis:e,lockingScript:n})}return new rg(i,n,a,t.readUInt32LE())}static parseScriptOffsets(e){let t=tc.makeReader(e),i=[],r=[];t.pos+=4;let n=t.readVarIntNum();for(let e=0;e<n;e++){t.pos+=36;let r=t.readVarIntNum();i.push({vin:e,offset:t.pos,length:r}),t.pos+=r+4}let s=t.readVarIntNum();for(let e=0;e<s;e++){t.pos+=8;let i=t.readVarIntNum();r.push({vout:e,offset:t.pos,length:i}),t.pos+=i}return{inputs:i,outputs:r}}static fromReader(e){let t=e.readUInt32LE(),i=e.readVarIntNum(),r=[];for(let t=0;t<i;t++){let t=tg(e.readReverse(32)),i=e.readUInt32LE(),n=e.readVarIntNum(),s=e.read(n),a=iG.fromBinary(s),o=e.readUInt32LE();r.push({sourceTXID:t,sourceOutputIndex:i,unlockingScript:a,sequence:o})}let n=e.readVarIntNum(),s=[];for(let t=0;t<n;t++){let t=e.readUInt64LEBn().toNumber(),i=e.readVarIntNum(),r=e.read(i),n=ij.fromBinary(r);s.push({satoshis:t,lockingScript:n})}return new rg(t,r,s,e.readUInt32LE())}static fromBinary(e){let t=e.slice(),i=Uint8Array.from(t),r=new tc(i),n=rg.fromReader(r);return n.rawBytesCache=i,n}static fromHex(e){let t=ty(e,"hex"),i=new tc(t),r=rg.fromReader(i);return r.rawBytesCache=t,r.hexCache=tg(t),r}static fromHexEF(e){return rg.fromEF(ty(e,"hex"))}static fromHexBEEF(e,t){return rg.fromBEEF(tm(e,"hex"),t)}constructor(e=1,t=[],i=[],r=0,n=new Map,s){this.version=e,this.inputs=t,this.outputs=i,this.lockTime=r,this.metadata=n,this.merklePath=s}invalidateSerializationCaches(){this.cachedHash=void 0,this.rawBytesCache=void 0,this.hexCache=void 0}addInput(e){if(void 0===e.sourceTXID&&void 0===e.sourceTransaction)throw TypeError("A reference to an an input transaction is required. If the input transaction itself cannot be referenced, its TXID must still be provided.");e.sequence??=0xffffffff,this.invalidateSerializationCaches(),this.inputs.push(e)}addOutput(e){if(this.cachedHash=void 0,!0!==e.change){if(void 0===e.satoshis)throw TypeError("either satoshis must be defined or change must be set to true");if(e.satoshis<0)throw Error("satoshis must be a positive integer or zero")}if(null==e.lockingScript)throw Error("lockingScript must be defined");this.outputs.push(e)}addP2PKHOutput(e,t){let i=new i3().lock(e);if(void 0===t)return this.addOutput({lockingScript:i,change:!0});this.addOutput({lockingScript:i,satoshis:t})}updateMetadata(e){this.metadata={...this.metadata,...e}}async fee(e=i7.getInstance(),t="equal"){if(this.invalidateSerializationCaches(),"number"==typeof e){let t=e;e={computeFee:async()=>t}}let i=await e.computeFee(this),r=this.calculateChange(i);if(r<=0){this.outputs=this.outputs.filter(e=>!0!==e.change);return}this.distributeChange(r,t)}calculateChange(e){let t=0;for(let e of this.inputs){if("object"!=typeof e.sourceTransaction)throw TypeError("Source transactions are required for all inputs during fee computation");t+=e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0}for(let i of(t-=e,this.outputs))!0!==i.change&&void 0!==i.satoshis&&(t-=i.satoshis);return t}distributeChange(e,t){let i=0,r=this.outputs.filter(e=>e.change);if("random"===t?i=this.distributeRandomChange(e,r):"equal"===t&&(i=this.distributeEqualChange(e,r)),i<e){let t=this.outputs.at(-1);void 0===t.satoshis?t.satoshis=e-i:t.satoshis+=e-i}}distributeRandomChange(e,t){let i=0,r=e,n=Array(t.length).fill(1);r-=t.length,i+=t.length;for(let e=0;e<t.length-1;e++){let t=this.benfordNumber(0,r);n[e]=n[e]+t,i+=t,r-=t}for(let e of this.outputs)!0===e.change&&(e.satoshis=n.shift());return i}distributeEqualChange(e,t){let i=0,r=Math.floor(e/t.length);for(let e of t)i+=r,e.satoshis=r;return i}benfordNumber(e,t){return Math.floor(e+(t-e)*Math.log10(1+1/(ia(1)[0]%9+1))/Math.log10(10))}getFee(){let e=0;for(let t of this.inputs){if("object"!=typeof t.sourceTransaction)throw TypeError("Source transactions or sourceSatoshis are required for all inputs to calculate fee");e+=t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0}let t=0;for(let e of this.outputs)t+=e.satoshis??0;return e-t}async sign(){for(let e of(this.invalidateSerializationCaches(),this.outputs))if(void 0===e.satoshis)if(!0===e.change)throw Error("There are still change outputs with uncomputed amounts. Use the fee() method to compute the change amounts and transaction fees prior to signing.");else throw Error("One or more transaction outputs is missing an amount. Ensure all output amounts are provided before signing.");let e=await Promise.all(this.inputs.map(async(e,t)=>"object"==typeof this.inputs[t].unlockingScriptTemplate?await this.inputs[t]?.unlockingScriptTemplate?.sign(this,t):await Promise.resolve(void 0)));for(let t=0,i=this.inputs.length;t<i;t++)"object"==typeof this.inputs[t].unlockingScriptTemplate&&(this.inputs[t].unlockingScript=e[t])}async broadcast(e=ra()){return await e.broadcast(this)}writeTransactionBody(e){for(let t of(e.writeUInt32LE(this.version),e.writeVarIntNum(this.inputs.length),this.inputs)){if(void 0===t.sourceTXID)if(null==t.sourceTransaction)throw Error("sourceTransaction is undefined");else e.write(t.sourceTransaction.hash());else e.writeReverse(tm(t.sourceTXID,"hex"));if(e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw Error("unlockingScript is undefined");let i=t.unlockingScript.toUint8Array();e.writeVarIntNum(i.length),e.write(i),e.writeUInt32LE(t.sequence??0xffffffff)}for(let t of(e.writeVarIntNum(this.outputs.length),this.outputs)){e.writeUInt64LE(t.satoshis??0);let i=t.lockingScript.toUint8Array();e.writeVarIntNum(i.length),e.write(i)}e.writeUInt32LE(this.lockTime)}buildSerializedBytes(){let e=new tl;return this.writeTransactionBody(e),e.toUint8Array()}getSerializedBytes(){return this.rawBytesCache??=this.buildSerializedBytes(),this.rawBytesCache}toBinary(){return Array.from(this.getSerializedBytes())}toUint8Array(){return this.getSerializedBytes()}writeEF(e){for(let t of(e.writeUInt32LE(this.version),e.write([0,0,0,0,0,239]),e.writeVarIntNum(this.inputs.length),this.inputs)){if(void 0===t.sourceTransaction)throw TypeError("All inputs must have source transactions when serializing to EF format");if(void 0===t.sourceTXID?e.write(t.sourceTransaction.hash()):e.write(tm(t.sourceTXID,"hex").reverse()),e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw Error("unlockingScript is undefined");let i=t.unlockingScript.toBinary();e.writeVarIntNum(i.length),e.write(i),e.writeUInt32LE(t.sequence??0xffffffff),e.writeUInt64LE(t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0);let r=t.sourceTransaction.outputs[t.sourceOutputIndex].lockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r)}for(let t of(e.writeVarIntNum(this.outputs.length),this.outputs)){e.writeUInt64LE(t.satoshis??0);let i=t.lockingScript.toBinary();e.writeVarIntNum(i.length),e.write(i)}e.writeUInt32LE(this.lockTime)}toEF(){let e=new tP;return this.writeEF(e),e.toArray()}toEFUint8Array(){let e=new tl;return this.writeEF(e),e.toUint8Array()}toHexEF(){return tg(this.toEFUint8Array())}toHex(){if(null!=this.hexCache)return this.hexCache;let e=tg(this.getSerializedBytes());return this.hexCache=e,e}toHexBEEF(){return tg(this.toBEEF())}toHexAtomicBEEF(){return tg(this.toAtomicBEEF())}hash(e){return(this.cachedHash??=ek(this.getSerializedBytes()),"hex"===e)?tg(this.cachedHash):this.cachedHash}id(e){let t=[...this.hash()];return(t.reverse(),"hex"===e)?tg(t):t}async verify(e=rl(),t,i){let r=new Set,n=[this];for(;n.length>0;){let s=n.shift(),a=s?.id("hex")??"";if(null!=a&&""!==a&&r.has(a))continue;if("object"==typeof s?.merklePath)if("scripts only"===e){null!=a&&r.add(a);continue}else{if(await s.merklePath.verify(a,e)){r.add(a);continue}throw Error(`Invalid merkle path for transaction ${a}`)}if(void 0!==t){if(void 0===s)throw Error("Transaction is undefined");let e=rg.fromEF(s.toEF());if(delete e.outputs[0].satoshis,e.outputs[0].change=!0,await e.fee(t),s.getFee()<e.getFee())throw Error(`Verification failed because the transaction ${a} has an insufficient fee and has not been mined.`)}let o=0;if(void 0===s)throw Error("Transaction is undefined");for(let e=0;e<s.inputs.length;e++){let t=s.inputs[e];if("object"!=typeof t.sourceTransaction)throw TypeError(`Verification failed because the input at index ${e} of transaction ${a} is missing an associated source transaction. This source transaction is required for transaction verification because there is no merkle proof for the transaction spending a UTXO it contains.`);if("object"!=typeof t.unlockingScript)throw TypeError(`Verification failed because the input at index ${e} of transaction ${a} is missing an associated unlocking script. This script is required for transaction verification because there is no merkle proof for the transaction spending the UTXO.`);let l=t.sourceTransaction.outputs[t.sourceOutputIndex];o+=l.satoshis??0;let c=t.sourceTransaction.id("hex");r.has(c)||n.push(t.sourceTransaction);let h=s.inputs.filter((t,i)=>i!==e);if(t.sourceTXID??=c,!new i0({sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,lockingScript:l.lockingScript,sourceSatoshis:l.satoshis??0,transactionVersion:s.version,otherInputs:h,unlockingScript:t.unlockingScript,inputSequence:t.sequence??0xffffffff,inputIndex:e,outputs:s.outputs,lockTime:s.lockTime,memoryLimit:i}).validate())return!1}let l=0;for(let e of s.outputs){if("number"!=typeof e.satoshis)throw TypeError("Every output must have a defined amount during transaction verification.");l+=e.satoshis}if(l>o)return!1;r.add(a)}return!0}writeSerializedBEEF(e,t){e.writeUInt32LE(rh);let i=[],r=new Map,n=new Map,s=[],a=new Set,o=e=>{let l=e.id("hex");if(a.has(l))return;let c={tx:e},h=e.merklePath,d="object"==typeof h;if(d&&null!=h&&(c.pathIndex=(e=>{let t=r.get(e);if(void 0!==t)return t;let s=`${e.blockHeight}:${e.computeRoot()}`,a=n.get(s);if(void 0!==a)return i[a].combine(e),r.set(e,a),a;let o=i.length;return i.push(e),r.set(e,o),n.set(s,o),o})(h)),!d)for(let i=e.inputs.length-1;i>=0;i--){let r=e.inputs[i];if("object"==typeof r.sourceTransaction)o(r.sourceTransaction);else if(!1===t)throw Error("A required source transaction is missing!")}a.add(l),s.push(c)};for(let t of(o(this),e.writeVarIntNum(i.length),i))e.write(t.toBinary());for(let t of(e.writeVarIntNum(s.length),s))e.write(t.tx.toBinary()),"number"==typeof t.pathIndex?(e.writeUInt8(1),e.writeVarIntNum(t.pathIndex)):e.writeUInt8(0);return e.toArray()}toBEEF(e){let t=new tP;return this.writeSerializedBEEF(t,e),t.toArray()}toBEEFUint8Array(e){let t=new tl;return this.writeSerializedBEEF(t,e),t.toArray()}toAtomicBEEF(e){return[1,1,1,1].concat(this.hash(),this.toBEEF(e))}toAtomicBEEFUint8Array(e){let t=new tl;t.write([1,1,1,1]);let i=this.hash();return t.write(i),this.writeSerializedBEEF(t,e),t.toUint8Array()}async completeWithWallet(e,t,i,r){let n,s=this.inputs.length,a=this.outputs.length,o={description:t??`Transaction with ${s} input(s) and ${a} output(s)`,inputs:[],outputs:[],lockTime:this.lockTime,version:this.version},l=this.inputs.some(e=>null!=e.unlockingScriptTemplate),c=new rp;for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];if(null==t.sourceTransaction)throw Error("All inputs must have a sourceTransaction when using completeWithWallet");let i=t.sourceTransaction.toBEEF();c.mergeBeef(i);let r=t.sourceTransaction.id("hex"),n={outpoint:`${r}.${t.sourceOutputIndex}`,inputDescription:"Input from source transaction",sequenceNumber:t.sequence};if(l)if(null!=t.unlockingScriptTemplate)n.unlockingScriptLength=await t.unlockingScriptTemplate.estimateLength(this,e);else if(null!=t.unlockingScript)n.unlockingScript=t.unlockingScript.toHex();else throw Error(`Input ${e} must have either an unlockingScript or unlockingScriptTemplate`);else{if(null==t.unlockingScript)throw Error("All inputs must have an unlockingScript when using completeWithWallet");n.unlockingScript=t.unlockingScript.toHex()}o.inputs.push(n)}for(let e of(this.inputs.length>0&&(o.inputBEEF=c.toBinary()),this.outputs))o.outputs.push({satoshis:e.satoshis,lockingScript:e.lockingScript.toHex(),outputDescription:"Output from source transaction"});if(this.metadata?.labels!=null&&Array.isArray(this.metadata.labels)&&(o.labels=this.metadata.labels),l){o.options={...r,signAndProcess:!1};let{signableTransaction:t}=await e.createAction(o,i);if(null==t)throw Error("Wallet createAction did not return signableTransaction");let s=rg.fromBEEF(t.tx),a={};for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];if(null!=t.unlockingScriptTemplate){let i=await t.unlockingScriptTemplate.sign(s,e);a[e]={unlockingScript:i.toHex()}}else null!=t.unlockingScript&&(a[e]={unlockingScript:t.unlockingScript.toHex()})}let l=null==r?void 0:{acceptDelayedBroadcast:r.acceptDelayedBroadcast,returnTXIDOnly:r.returnTXIDOnly,noSend:r.noSend,sendWith:r.sendWith},c=await e.signAction({reference:t.reference,spends:a,options:l},i);if(null==c.tx)throw Error("Wallet signAction did not return transaction data");n=c.tx}else{null!=r&&(o.options=r);let{tx:t}=await e.createAction(o,i);if(null==t)throw Error("Wallet createAction did not return transaction data");n=t}let h=rg.fromAtomicBEEF(n);this.version=h.version,this.inputs=h.inputs,this.outputs=h.outputs,this.lockTime=h.lockTime,this.merklePath=h.merklePath,this.cachedHash=h.cachedHash,this.metadata={...this.metadata,...h.metadata}}preimage(e,t,i){if(e??=0,t??=iD.SIGHASH_FORKID|iD.SIGHASH_ALL,e<0||e>=this.inputs.length)throw Error("Invalid input index");let r=240&t;if(224!==r&&192!==r&&64!==r)throw Error("FORKID must be set");let n=15&t;if(n<1||n>3)throw Error("Invalid signature coverage, must be all, none or single");let s=this.inputs[e];if(null==s.sourceTransaction)throw Error("Source transaction is required");let a=s.sourceTransaction.outputs[s.sourceOutputIndex];if(null==a)throw Error(`Source transaction's output at index ${s.sourceOutputIndex} is required`);let o=this.inputs.filter((t,i)=>i!==e);return iD.format({sourceTXID:s.sourceTXID??s.sourceTransaction.id("hex"),sourceOutputIndex:s.sourceOutputIndex,sourceSatoshis:a.satoshis,transactionVersion:this.version,otherInputs:o,inputIndex:e,outputs:this.outputs,inputSequence:s.sequence??0xffffffff,subscript:i??a.lockingScript,lockTime:this.lockTime,scope:t})}}function ry(e){return"success"===e.status}function rm(e){return"error"===e.status}let rb=class extends rp{knownTo={};constructor(e){if(super(),null!=e)for(const t of e)this.addParty(t)}isParty(e){return Object.keys(this.knownTo).includes(e)}addParty(e){if(this.isParty(e))throw Error(`Party ${e} already exists.`);this.knownTo[e]={}}getKnownTxidsForParty(e){let t=this.knownTo[e];if(void 0===t)throw Error(`Party ${e} is unknown.`);return Object.keys(t)}getTrimmedBeefForParty(e){let t=this.getKnownTxidsForParty(e),i=this.clone();return i.trimKnownTxids(t),i}addKnownTxidsForParty(e,t){this.isParty(e)||this.addParty(e);let i=this.knownTo[e];for(let e of t)i[e]=!0,this.mergeTxidOnly(e)}mergeBeefFromParty(e,t){let i=Array.isArray(t)?rp.fromBinary(t):t,r=i.getValidTxids();this.mergeBeef(i),this.addKnownTxidsForParty(e,r)}};class rw{network;URL;httpClient;constructor(e="main",t=rr()){this.network=e,this.URL=`https://api.whatsonchain.com/v1/bsv/${e}/tx/raw`,this.httpClient=t}async broadcast(e){let t=e.toHex();try{let e=await this.httpClient.request(this.URL,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/plain"},data:{txhex:t}});if(!e.ok)return{status:"error",code:e.status.toString()??"ERR_UNKNOWN",description:e.data??"Unknown error"};{let t=e.data;return{status:"success",txid:t,message:"broadcast successful"}}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class rv{https;constructor(e){this.https=e}async request(e,t){return await re(this.https,e,t,e=>Buffer.from(e))}}class rI{fetch;constructor(e){this.fetch=e}async request(e,t){let i={method:t.method,headers:t.headers,body:t.data},r=await this.fetch(e,i),n=await r.text();return{ok:r.ok,status:r.status,statusText:r.statusText,data:n}}}function rk(){let e={async request(){throw Error("No method available to perform HTTP request")}};if(void 0!==globalThis.window&&"function"==typeof globalThis.window.fetch)return new rI(globalThis.window.fetch.bind(globalThis.window));if("function"==typeof globalThis.fetch)return new rI(globalThis.fetch.bind(globalThis));if("u"<typeof require)return e;try{let e=require("node:https");return new rv(e)}catch(t){return e}}class rS{URL;httpClient;constructor(e,t=rk()){this.URL=e,this.httpClient=t}async broadcast(e){let t={method:"POST",headers:{"Content-Type":"application/octet-stream"},data:new Blob([new Uint8Array(e.toEF())])};try{let i=await this.httpClient.request(this.URL,t);if(!i.ok)return{status:"error",code:i.status.toString()??"ERR_UNKNOWN",description:i.data??"Unknown error"};{let t=e.id("hex");return{status:"success",txid:t,message:"broadcast successful"}}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class rE{baseUrl;httpClient;apiKey;constructor(e,t={}){const{httpClient:i,apiKey:r}=t;this.baseUrl=e,this.httpClient=i??rr(),this.apiKey=r??""}async isValidRootForHeight(e,t){let i={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.apiKey}`},data:[{blockHeight:t,merkleRoot:e}]};try{let e=await this.httpClient.request(`${this.baseUrl}/api/v1/chain/merkleroot/verify`,i);if(e.ok)return"CONFIRMED"===e.data.confirmationState;throw Error(`Failed to verify merkleroot for height ${t} because of an error: ${JSON.stringify(e.data)}`)}catch(e){throw Error(`Failed to verify merkleroot for height ${t} because of an error: ${e instanceof Error?e.message:String(e)}`)}}async currentHeight(){let e={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`}};try{let t=await this.httpClient.request(`${this.baseUrl}/api/v1/chain/tip/longest`,e);if(t.ok&&t.data&&"number"==typeof t.data.height)return t.data.height;throw Error(`Failed to get current height because of an error: ${JSON.stringify(t.data)}`)}catch(e){throw Error(`Failed to get current height because of an error: ${e instanceof Error?e.message:String(e)}`)}}}let rx="42423301",rA=(e,t,i)=>{let r="object"!=typeof i;if(r){let e=new t1,t=new ih(1),r=e.g.mul(t);i=new ii(r.x,r.y)}let n=ia(32),s=tS(n),a=`2-message signing-${s}`,o=t.deriveChild(i,a).sign(e).toDER(),l=t.toPublicKey().encode(!0);return[...tm(rx,"hex"),...l,...r?[0]:i.encode(!0),...n,...o]},rT=(e,t,i)=>{let r=new tN(t),n=tg(r.read(4));if(n!==rx)throw Error(`Message version mismatch: Expected ${rx}, received ${n}`);let s=ii.fromString(tg(r.read(33))),[a]=r.read(1);if(0===a)i=new ih(1);else{let e=tg([a,...r.read(32)]);if("object"!=typeof i)throw TypeError(`This signature can only be verified with knowledge of a specific private key. The associated public key is: ${e}`);let t=i.toPublicKey().encode(!0,"hex");if(e!==t)throw Error(`The recipient public key is ${t} but the signature requres the recipient to have public key ${e}`)}let o=tS(r.read(32)),l=tg(r.read(r.bin.length-r.pos)),c=t2.fromDER(l,"hex"),h=`2-message signing-${o}`;return s.deriveChild(i,h).verify(e,c)},rO="42421033",rP=(e,t,i)=>{let r=ia(32),n=tS(r),s=`2-message encryption-${n}`,a=t.deriveChild(i,s),o=i.deriveChild(t,s),l=new i_(a.deriveSharedSecret(o).encode(!0).slice(1)).encrypt(e),c=t.toPublicKey().encode(!0);return[...tm(rO,"hex"),...c,...i.encode(!0),...r,...l]},rN=(e,t)=>{let i=new tN(e),r=tg(i.read(4));if(r!==rO)throw Error(`Message version mismatch: Expected ${rO}, received ${r}`);let n=ii.fromString(tg(i.read(33))),s=tg(i.read(33)),a=t.toPublicKey().encode(!0,"hex");if(s!==a)throw Error(`The encrypted message expects a recipient public key of ${s}, but the provided key is ${a}`);let o=tS(i.read(32)),l=i.read(i.bin.length-i.pos),c=`2-message encryption-${o}`,h=n.deriveChild(t,c),d=t.deriveChild(n,c);return new i_(h.deriveSharedSecret(d).encode(!0).slice(1)).decrypt(l)},r_="Bitcoin Signed Message:\n",rR=e=>{let t=new tP;return t.writeVarIntNum(r_.length),t.write(tm(r_,"utf8")),t.writeVarIntNum(e.length),t.write(e),ek(t.toArray())},rC=(e,t,i="base64")=>{let r=rR(e),n=ie(new A(r),t,!0);if("raw"===i)return n;let s=new A(r),a=n.CalculateRecoveryFactor(t.toPublicKey(),s);return n.toCompact(a,!0,"base64")},rB=(e,t,i)=>it(new A(rR(e)),t,i);class rU{versionBytesNum;depth;parentFingerPrint;childIndex;chainCode;privKey;pubKey;constants={pubKey:0x488b21e,privKey:0x488ade4};constructor(e,t,i,r,n,s,a){this.versionBytesNum=e,this.depth=t,this.parentFingerPrint=i,this.childIndex=r,this.chainCode=n,this.privKey=s,this.pubKey=a}fromRandom(){return this.versionBytesNum=this.constants.privKey,this.depth=0,this.parentFingerPrint=[0,0,0,0],this.childIndex=0,this.chainCode=ia(32),this.privKey=ih.fromRandom(),this.pubKey=this.privKey.toPublicKey(),this}static fromRandom(){return new this().fromRandom()}static fromString(e){return new this().fromString(e)}fromString(e){let t=tO(e);return this.fromBinary([...t.prefix,...t.data])}static fromSeed(e){return new this().fromSeed(e)}fromSeed(e){if(e.length<16)throw Error("Need more than 128 bits of entropy");if(e.length>64)throw Error("More than 512 bits of entropy is nonstandard");let t=ex(tm("Bitcoin seed","utf8"),e);return this.depth=0,this.parentFingerPrint=[0,0,0,0],this.childIndex=0,this.chainCode=t.slice(32,64),this.versionBytesNum=this.constants.privKey,this.privKey=new ih(t.slice(0,32)),this.pubKey=this.privKey.toPublicKey(),this}static fromBinary(e){return new this().fromBinary(e)}fromBinary(e){if(78!==e.length)throw Error("incorrect bip32 data length");let t=new tN(e);this.versionBytesNum=t.readUInt32BE(),this.depth=t.readUInt8(),this.parentFingerPrint=t.read(4),this.childIndex=t.readUInt32BE(),this.chainCode=t.read(32);let i=t.read(33),r=this.versionBytesNum===this.constants.privKey,n=this.versionBytesNum===this.constants.pubKey;if(r&&0===i[0])this.privKey=new ih(i.slice(1,33)),this.pubKey=this.privKey.toPublicKey();else if(n&&(2===i[0]||3===i[0]))this.pubKey=ii.fromString(tg(i));else throw Error("Invalid key");return this}toString(){return tT(this.toBinary(),[])}derive(e){if("m"===e)return this;let t=e.split("/"),i=this;for(let[e,r]of t.entries()){if(0===e){if("m"!==r)throw Error("invalid path");continue}let t=/^(\d+)('?)$/.exec(r);if(null===t)throw Error("invalid path");let n=Number.parseInt(t[1],10);if(n>0x7fffffff)throw Error("invalid path");let s="'"===t[2],a=n;s&&(a+=0x80000000),i=i.deriveChild(a)}return i}deriveChild(e){if("number"!=typeof e)throw TypeError("i must be a number");let t=[];t.push(e>>24&255),t.push(e>>16&255),t.push(e>>8&255),t.push(255&e);let i=[...t],r=(0x80000000&e)!=0,n=this.versionBytesNum===this.constants.privKey;if(r&&(null===this.privKey||void 0===this.privKey||!n))throw Error("Cannot do private key derivation without private key");let s=null;if(null!==this.privKey&&void 0!==this.privKey){let e=null;e=r?[0,...this.privKey.toArray("be",32),...i]:[...this.pubKey.encode(!0),...i];let t=ex(this.chainCode,e),n=new A(t.slice(0,32)),a=t.slice(32,64),o=n.add(this.privKey).mod(new t1().n);(s=new rU).chainCode=a,s.privKey=new ih(o.toArray()),s.pubKey=s.privKey.toPublicKey()}else{let e=[...this.pubKey.encode(!0),...i],t=ex(this.chainCode,e),r=new A(t.slice(0,32)),n=t.slice(32,64),a=new t1().g.mul(r),o=this.pubKey,l=a.add(o),c=new ii(l.x,l.y);(s=new rU).chainCode=n,s.pubKey=c}s.childIndex=e;let a=eS(this.pubKey.encode(!0));return s.parentFingerPrint=a.slice(0,4),s.versionBytesNum=this.versionBytesNum,s.depth=this.depth+1,s}toPublic(){let e=new rU(this.versionBytesNum,this.depth,this.parentFingerPrint,this.childIndex,this.chainCode,this.privKey,this.pubKey);return e.versionBytesNum=this.constants.pubKey,e.privKey=void 0,e}toBinary(){let e=this.versionBytesNum===this.constants.privKey,t=this.versionBytesNum===this.constants.pubKey;if(e)return new tP().writeUInt32BE(this.versionBytesNum).writeUInt8(this.depth).write(this.parentFingerPrint).writeUInt32BE(this.childIndex).write(this.chainCode).writeUInt8(0).write(this.privKey.toArray("be",32)).toArray();if(t)return new tP().writeUInt32BE(this.versionBytesNum).writeUInt8(this.depth).write(this.parentFingerPrint).writeUInt32BE(this.childIndex).write(this.chainCode).write(this.pubKey.encode(!0)).toArray();throw Error("bip32: invalid versionBytesNum byte")}isPrivate(){return this.versionBytesNum===this.constants.privKey}}let rF={value:["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"],space:" "};class rD{mnemonic;seed;Wordlist;constructor(e,t,i=rF){this.mnemonic=e??"",this.seed=t??[],this.Wordlist=i}toBinary(){let e=new tP;if(""===this.mnemonic)e.writeVarIntNum(0);else{let t=tm(this.mnemonic,"utf8");e.writeVarIntNum(t.length),e.write(t)}return this.seed.length>0?(e.writeVarIntNum(this.seed.length),e.write(this.seed)):e.writeVarIntNum(0),e.toArray()}fromBinary(e){let t=new tN(e),i=t.readVarIntNum();i>0&&(this.mnemonic=tk(t.read(i),"utf8"));let r=t.readVarIntNum();return r>0&&(this.seed=t.read(r)),this}fromRandom(e){if((null==e||Number.isNaN(e)||0===e)&&(e=128),e%32!=0)throw Error("bits must be multiple of 32");if(e<128)throw Error("bits must be at least 128");let t=ia(e/8);return this.entropy2Mnemonic(t),this.mnemonic2Seed(),this}static fromRandom(e){return new this().fromRandom(e)}fromEntropy(e){return this.entropy2Mnemonic(e),this}static fromEntropy(e){return new this().fromEntropy(e)}fromString(e){this.mnemonic=e;let t=!1;try{t=this.check()}catch{t=!1}if(!t)throw Error("Mnemonic does not pass the check - was the mnemonic typed incorrectly? Are there extra spaces?");return this}static fromString(e){return new this().fromString(e)}toString(){return this.mnemonic}toSeed(e){return this.mnemonic2Seed(e),this.seed}entropy2Mnemonic(e){if(e.length<16)throw Error("Entropy is less than 128 bits. It must be 128 bits or more.");let t=ev(e),i="",r=8*e.length;for(let t of e)i+=("00000000"+t.toString(2)).slice(-8);let n=t[0].toString(2);if((i+=n=("00000000"+n).slice(-8).slice(0,r/32)).length%11!=0)throw Error("internal error - entropy not an even multiple of 11 bits - "+i.length.toString());let s="";for(let e=0;e<i.length/11;e++){""!==s&&(s+=this.Wordlist.space);let t=Number.parseInt(i.slice(11*e,(e+1)*11),2);s+=this.Wordlist.value[t]}return this.mnemonic=s,this}check(){let e=this.mnemonic.split(this.Wordlist.space),t="";for(let i of e){let e=this.Wordlist.value.indexOf(i);if(e<0)return!1;t+=("00000000000"+e.toString(2)).slice(-11)}if(t.length%11!=0)throw Error("internal error - entropy not an even multiple of 11 bits - "+t.length.toString());let i=t.length/33,r=t.slice(-i),n=t.slice(0,t.length-i),s=[];for(let e=0;e<n.length/8;e++)s.push(Number.parseInt(t.slice(8*e,(e+1)*8),2));let a=ev(s.slice(0,n.length/8))[0].toString(2);return(a=("00000000"+a).slice(-8).slice(0,i))===r}mnemonic2Seed(e=""){let t=this.mnemonic;if(!this.check())throw Error("Mnemonic does not pass the check - was the mnemonic typed incorrectly? Are there extra spaces?");if("string"!=typeof e)throw TypeError("passphrase must be a string or undefined");t=t.normalize("NFKD"),e=e.normalize("NFKD");let i=tm(t,"utf8"),r=[...tm("mnemonic","utf8"),...tm(e,"utf8")];return this.seed=tn(i,r,2048,64,"sha512"),this}isValid(e=""){let t;try{this.mnemonic2Seed(e),t=!0}catch{t=!1}return t}static isValid(e,t=""){return new rD(e).isValid(t)}}function rL(e){let t,i;0===this._tables[0][0][0]&&this._precompute();let r=this._tables[0][4],n=this._tables[1],s=e.length,a=1;if(4!==s&&6!==s&&8!==s)throw Error("invalid aes key size");let o=e.slice(0),l=[];for(this._key=[o,l],i=s;i<4*s+28;i++)t=o[i-1],(i%s==0||8===s&&i%s==4)&&(t=r[t>>>24]<<24^r[t>>16&255]<<16^r[t>>8&255]<<8^r[255&t],i%s==0&&(t=t<<8^t>>>24^a<<24,a=a<<1^(a>>7)*283)),o[i]=o[i-s]^t;for(let e=0;i>0;e++,i--)t=o[(3&e)==0?i-4:i],i<=4||e<4?l[e]=t:l[e]=n[0][r[t>>>24]]^n[1][r[t>>16&255]]^n[2][r[t>>8&255]]^n[3][r[255&t]]}rL.prototype={encrypt:function(e){return this._crypt(e,0)},decrypt:function(e){return this._crypt(e,1)},_tables:[[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)]],_precompute:function(){let e,t,i,r,n,s,a,o,l=this._tables[0],c=this._tables[1],h=l[4],d=c[4],u=new Uint8Array(256),f=new Uint8Array(256);for(e=0;e<256;e++)u[e]=e<<1^(e>>7)*283,f[u[e]^e]=e;for(t=i=0;0===h[t];t^=0===r?1:r,i=0===f[i]?1:f[i])for(s=(s=i^i<<1^i<<2^i<<3^i<<4)>>8^255&s^99,h[t]=s,d[s]=t,r=u[t],n=u[r],o=0x1010101*u[n]^65537*n^257*r^0x1010100*t,a=257*u[s]^0x1010100*s,e=0;e<4;e++)l[e][t]=a=a<<24^a>>>8,c[e][s]=o=o<<24^o>>>8},_crypt:function(e,t){let i,r,n,s;if(4!==e.length)throw Error("invalid aes block size");let a=this._key[t],o=e[0]^a[0],l=e[1===t?3:1]^a[1],c=e[2]^a[2],h=e[1===t?1:3]^a[3],d=a.length/4-2,u=4,f=new Uint32Array(4),p=this._tables[t],g=p[0],y=p[1],m=p[2],b=p[3],w=p[4];for(s=0;s<d;s++)i=g[o>>>24]^y[l>>16&255]^m[c>>8&255]^b[255&h]^a[u],r=g[l>>>24]^y[c>>16&255]^m[h>>8&255]^b[255&o]^a[u+1],n=g[c>>>24]^y[h>>16&255]^m[o>>8&255]^b[255&l]^a[u+2],h=g[h>>>24]^y[o>>16&255]^m[l>>8&255]^b[255&c]^a[u+3],u+=4,o=i,l=r,c=n;for(s=0;s<4;s++)f[1===t?3&-s:s]=w[o>>>24]<<24^w[l>>16&255]<<16^w[c>>8&255]<<8^w[255&h]^a[u++],i=o,o=l,l=c,c=h,h=i;return f}};class rV{static encrypt(e,t){let i=rV.buf2Words(t),r=rV.buf2Words(e),n=new rL(i).encrypt(r);return rV.words2Buf(n)}static decrypt(e,t){let i=rV.buf2Words(e),r=new rL(rV.buf2Words(t)).decrypt(i);return rV.words2Buf(r)}static buf2Words(e){if(e.length%4!=0)throw Error("buf length must be a multiple of 4");let t=[];for(let i=0;i<e.length/4;i++){let r=0x1000000*e[4*i]+(e[4*i+1]<<16|e[4*i+2]<<8|e[4*i+3]);t.push(r)}return t}static words2Buf(e){let t=Array(4*e.length);for(let i=0;i<e.length;i++){let r=e[i];t[4*i]=r>>>24&255,t[4*i+1]=r>>>16&255,t[4*i+2]=r>>>8&255,t[4*i+3]=255&r}return t}}class rH{static buf2BlocksBuf(e,t){let i=t/8,r=[];for(let n=0;n<=e.length/i;n++){let s=e.slice(n*i,n*i+i);s.length<t&&(s=rH.pkcs7Pad(s,t)),r.push(s)}return r}static blockBufs2Buf(e){let t=e.at(-1);return t=rH.pkcs7Unpad(t),e[e.length-1]=t,e.flat()}static encrypt(e,t,i,r){let n=8*t.length,s=rH.buf2BlocksBuf(e,n);return rH.encryptBlocks(s,t,i,r).flat()}static decrypt(e,t,i,r){let n=t.length,s=[];for(let t=0;t<e.length/n;t++)s.push(e.slice(t*n,t*n+n));let a=rH.decryptBlocks(s,t,i,r);return rH.blockBufs2Buf(a)}static encryptBlock(e,t,i,r){let n=rH.xorBufs(e,t);return i.encrypt(n,r)}static decryptBlock(e,t,i,r){let n=i.decrypt(e,r);return rH.xorBufs(n,t)}static encryptBlocks(e,t,i,r){let n=[];for(let s of e){let e=rH.encryptBlock(s,t,i,r);n.push(e),t=e}return n}static decryptBlocks(e,t,i,r){let n=[];for(let s of e){let e=rH.decryptBlock(s,t,i,r);n.push(e),t=s}return n}static pkcs7Pad(e,t){let i=t/8-e.length,r=Array(i);return r.fill(i),[...e,...r]}static pkcs7Unpad(e){let t=e.at(-1),i=e.slice(e.length-t,e.length),r=Array(t);if(r.fill(t),tg(i)!==tg(r))throw Error("invalid padding");return e.slice(0,e.length-t)}static xorBufs(e,t){if(e.length!==t.length)throw Error("bufs must have the same length");let i=Array(e.length);for(let r=0;r<e.length;r++)i[r]=e[r]^t[r];return i}}class rM{static encrypt(e,t,i,r=!0){i=i??ia(16);let n=rH.encrypt(e,i,rV,t);return r?[...i,...n]:[...n]}static decrypt(e,t,i){if(null!=i)return rH.decrypt(e,i,rV,t);{i=e.slice(0,16);let r=e.slice(16);return rH.decrypt(r,i,rV,t)}}}class rK{static ivkEkM(e,t){let i=t.mul(e),r=eI(new ii(i.x,i.y).encode(!0));return{iv:r.slice(0,16),kE:r.slice(16,32),kM:r.slice(32,64)}}static electrumEncrypt(e,t,i,r=!1){let n,s=null;i??=ih.fromRandom(),r||(s=i.toPublicKey().encode(!0));let{iv:a,kE:o,kM:l}=rK.ivkEkM(i,t),c=rM.encrypt(e,o,a,!1),h=tm("BIE1","utf8"),d=eE(l,n=null!=s&&s.length>0?[...h,...s,...c]:[...h,...c]);return[...n,...d]}static electrumDecrypt(e,t,i){if("BIE1"!==tk(e.slice(0,4),"utf8"))throw Error("Invalid Magic");let r=4,n=null;if(e.length-r-32>=33){let t=e[r];2===t||3===t?(n=e.slice(r,r+33),r+=33):4===t&&(n=e.slice(r,r+65),r+=65)}if(null===n){if(null==i)throw Error("Sender public key is required")}else i??=ii.fromString(tg(n));let{iv:s,kE:a,kM:o}=rK.ivkEkM(t,i),l=e.slice(r,e.length-32),c=e.slice(e.length-32,e.length),h=eE(o,e.slice(0,e.length-32));if(tg(c)!==tg(h))throw Error("Invalid checksum");return rM.decrypt(l,a,s)}static bitcoreEncrypt(e,t,i,r){i??=ih.fromRandom(),r??=ia(16);let n=i,s=i.toPublicKey().encode(!0),a=eI(t.mul(n).getX().toArray("be",32)),o=a.slice(0,32),l=a.slice(32,64),c=rM.encrypt(e,o,r),h=eE(l,[...c]);return[...s,...c,...h]}static bitcoreDecrypt(e,t){let i=ii.fromString(tg(e.slice(0,33))).mul(t);if(i.eq(new t0(0,0)))throw Error("P equals 0");let r=eI(i.getX().toArray("be",32)),n=r.slice(0,32),s=r.slice(32,64),a=e.slice(33,-32),o=e.slice(-32),l=eE(s,a);if(tg(o)!==tg(l))throw Error("Invalid checksum");return[...rM.decrypt(a,n)]}}function rq(e,t){let i=new rg(0,[],[],0);return i.outputs=Array(e.vout+1).fill(null),i.outputs[e.vout]={satoshis:e.satoshis,lockingScript:ij.fromHex(e.script)},{sourceTransaction:i,sourceTXID:e.txid,sourceOutputIndex:e.vout,unlockingScriptTemplate:t,sequence:0xffffffff}}class r${static generate(e,t){let i=this.withDefaultOptions(t);return rz(e,this.getCounter(i.timestamp,i.period),i)}static validate(e,t,i){let r=this.withDefaultValidateOptions(i);if((t=t.trim()).length!==r.digits)return!1;let n=this.getCounter(r.timestamp,r.period),s=[n];for(let e=1;e<=r.skew;e++)s.push(n+e),s.push(n-e);for(let i of s){let n=rz(e,i,r);if(tU(tm(t,"utf8"),tm(n,"utf8")))return!0}return!1}static getCounter(e,t){return Math.floor(Math.floor(e/1e3)/t)}static withDefaultOptions(e){return{digits:2,algorithm:"SHA-1",period:30,timestamp:Date.now(),...e}}static withDefaultValidateOptions(e){return{skew:1,...this.withDefaultOptions(e)}}}function rz(e,t,i){let r=(function(e,t,i){switch(i){case"SHA-1":return new ep(e).update(t);case"SHA-256":return new ef(e).update(t);case"SHA-512":return new eg(e).update(t);default:throw Error("unsupported HMAC algorithm")}})(e,new A(t).toArray("be",8),i.algorithm).digest(),n=(r.at(-1)??0)&15;return(0x7fffffff&new A(r.slice(n,n+4)).toNumber()).toString().slice(-i.digits)}(a=h||(h={}))[a.Silent=0]="Silent",a[a.App=1]="App",a[a.Counterparty=2]="Counterparty";class rW{cacheSharedSecret;retrieveCachedSharedSecret;rootKey;identityKey;anyone;constructor(e,t,i){this.cacheSharedSecret=t,this.retrieveCachedSharedSecret=i,this.anyone=new ih(1).toPublicKey(),"anyone"===e?this.rootKey=new ih(1):this.rootKey=e,this.identityKey=this.rootKey.toPublicKey().toString()}derivePublicKey(e,t,i,r=!1){return(i=this.normalizeCounterparty(i),r)?this.rootKey.deriveChild(i,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret).toPublicKey():i.deriveChild(this.rootKey,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}derivePrivateKey(e,t,i){return i=this.normalizeCounterparty(i),this.rootKey.deriveChild(i,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}deriveSymmetricKey(e,t,i){i="anyone"===i?this.anyone:this.normalizeCounterparty(i);let r=this.derivePublicKey(e,t,i),n=this.derivePrivateKey(e,t,i);return new i_(n.deriveSharedSecret(r)?.x?.toArray()??[])}revealCounterpartySecret(e){if("self"===e)throw Error("Counterparty secrets cannot be revealed for counterparty=self.");e=this.normalizeCounterparty(e);let t=this.rootKey.toPublicKey();if(this.rootKey.deriveChild(t,"test").toHex()===this.rootKey.deriveChild(e,"test").toHex())throw Error("Counterparty secrets cannot be revealed for counterparty=self.");return this.rootKey.deriveSharedSecret(e).encode(!0)}revealSpecificSecret(e,t,i){e=this.normalizeCounterparty(e);let r=this.rootKey.deriveSharedSecret(e),n=tm(this.computeInvoiceNumber(t,i),"utf8");return eE(r.encode(!0),n)}normalizeCounterparty(e){if(null==e)throw Error("counterparty must be self, anyone or a public key!");return"self"===e?this.rootKey.toPublicKey():"anyone"===e?new ih(1).toPublicKey():"string"==typeof e?ii.fromString(e):e}computeInvoiceNumber(e,t){let i=e[0];if(!Number.isInteger(i)||i<0||i>2)throw Error("Protocol security level must be 0, 1, or 2");let r=e[1].toLowerCase().trim();if(t.length>800)throw Error("Key IDs must be 800 characters or less");if(t.length<1)throw Error("Key IDs must be 1 character or more");if(r.length>400)if(r.startsWith("specific linkage revelation ")){if(r.length>430)throw Error("Specific linkage revelation protocol names must be 430 characters or less")}else throw Error("Protocol names must be 400 characters or less");if(r.length<5)throw Error("Protocol names must be 5 characters or more");if(r.includes(" "))throw Error('Protocol names cannot contain multiple consecutive spaces (" ")');if(!/^[a-z0-9 ]+$/g.test(r))throw Error("Protocol names can only contain letters, numbers and spaces");if(r.endsWith(" protocol"))throw Error('No need to end your protocol name with " protocol"');return`${i}-${r}-${t}`}}class rj{keyDeriver;cache;maxCacheSize;rootKey;identityKey;constructor(e,t){"anyone"===e?this.rootKey=new ih(1):this.rootKey=e,this.keyDeriver=new rW(this.rootKey,(e,t,i)=>{this.cacheSet(`${e.toString()}-${t.toString()}`,i)},(e,t)=>this.cacheGet(`${e.toString()}-${t.toString()}`)),this.identityKey=this.rootKey.toPublicKey().toString(),this.cache=new Map;const i=t?.maxCacheSize;this.maxCacheSize=null!=i&&!Number.isNaN(i)&&i>0?i:1e3}derivePublicKey(e,t,i,r=!1){let n=this.generateCacheKey("derivePublicKey",e,t,i,r);if(this.cache.has(n)){let e=this.cacheGet(n);if(void 0===e)throw Error("Cached value is undefined");return e}{let s=this.keyDeriver.derivePublicKey(e,t,i,r);return this.cacheSet(n,s),s}}derivePrivateKey(e,t,i){let r=this.generateCacheKey("derivePrivateKey",e,t,i);if(this.cache.has(r)){let e=this.cacheGet(r);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.derivePrivateKey(e,t,i);return this.cacheSet(r,n),n}}deriveSymmetricKey(e,t,i){let r=this.generateCacheKey("deriveSymmetricKey",e,t,i);if(this.cache.has(r)){let e=this.cacheGet(r);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.deriveSymmetricKey(e,t,i);return this.cacheSet(r,n),n}}revealCounterpartySecret(e){let t=this.generateCacheKey("revealCounterpartySecret",e);if(this.cache.has(t)){let e=this.cacheGet(t);if(void 0===e)throw Error("Cached value is undefined");return e}{let i=this.keyDeriver.revealCounterpartySecret(e);return this.cacheSet(t,i),i}}revealSpecificSecret(e,t,i){let r=this.generateCacheKey("revealSpecificSecret",e,t,i);if(this.cache.has(r)){let e=this.cacheGet(r);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.revealSpecificSecret(e,t,i);return this.cacheSet(r,n),n}}generateCacheKey(e,...t){let i=t.map(e=>this.serializeArgument(e)).join("|");return`${e}|${i}`}serializeArgument(e){return e instanceof ii||e instanceof ih?e.toString():Array.isArray(e)?e.map(e=>this.serializeArgument(e)).join(","):"object"==typeof e&&null!==e?JSON.stringify(e):String(e)}cacheGet(e){let t=this.cache.get(e);return this.cache.delete(e),void 0!==t&&this.cache.set(e,t),t}cacheSet(e,t){if(this.cache.size>=this.maxCacheSize){let e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(e,t)}}class rG{keyDeriver;constructor(e){"string"!=typeof e.identityKey&&(e=new rj(e)),this.keyDeriver=e}async getPublicKey(e){if(e.identityKey){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==e.protocolID||null==e.keyID||""===e.keyID)throw Error("protocolID and keyID are required if identityKey is false or undefined.");return{publicKey:(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf).toString()}}async revealCounterpartyKeyLinkage(e){let{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let i=this.keyDeriver.revealCounterpartySecret(e.counterparty),r=new iL().generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),ii.fromString(e.counterparty),t0.fromDER(i)),n=[...r.R.encode(!0),...r.SPrime.encode(!0),...r.z.toArray()],s=new Date().toISOString(),{ciphertext:a}=await this.encrypt({plaintext:i,protocolID:[2,"counterparty linkage revelation"],keyID:s,counterparty:e.verifier}),{ciphertext:o}=await this.encrypt({plaintext:n,protocolID:[2,"counterparty linkage revelation"],keyID:s,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,revelationTime:s,encryptedLinkage:a,encryptedLinkageProof:o}}async revealSpecificKeyLinkage(e){let{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let i=this.keyDeriver.revealSpecificSecret(e.counterparty,e.protocolID,e.keyID),{ciphertext:r}=await this.encrypt({plaintext:i,protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier}),{ciphertext:n}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,protocolID:e.protocolID,keyID:e.keyID,encryptedLinkage:r,encryptedLinkageProof:n,proofType:0}}async encrypt(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{ciphertext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").encrypt(e.plaintext)}}async decrypt(e,t){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{plaintext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").decrypt(e.ciphertext)}}async createHmac(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{hmac:eE(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data)}}async verifyHmac(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let t=eE(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data),i=e.hmac,r=tU(tm(t),tm(i));if(!r){let e=Error("HMAC is not valid");throw e.code="ERR_INVALID_HMAC",e}return{valid:r}}async createSignature(e){if(null==e.hashToDirectlySign&&null==e.data)throw Error("args.data or args.hashToDirectlySign must be valid");let t=e.hashToDirectlySign??ev(e.data??[]),i=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePrivateKey(e.protocolID,e.keyID,e.counterparty??"anyone");return{signature:ie(new A(t),i,!0).toDER()}}async verifySignature(e){if(null==e.hashToDirectlyVerify&&null==e.data)throw Error("args.data or args.hashToDirectlyVerify must be valid");let t=e.hashToDirectlyVerify??ev(e.data??[]),i=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf),r=it(new A(t),t2.fromDER(e.signature),i);if(!r){let e=Error("Signature is not valid");throw e.code="ERR_INVALID_SIGNATURE",e}return{valid:r}}}let rX=rG;class rY{CWI;constructor(){if("object"!=typeof window)throw TypeError("The window.CWI substrate requires a global window object.");if("object"!=typeof window.CWI)throw TypeError("The window.CWI interface does not appear to be bound to the window object.");this.CWI=window.CWI}async createAction(e,t){return await this.CWI.createAction(e,t)}async signAction(e,t){return await this.CWI.signAction(e,t)}async abortAction(e,t){return await this.CWI.abortAction(e,t)}async listActions(e,t){return await this.CWI.listActions(e,t)}async internalizeAction(e,t){return await this.CWI.internalizeAction(e,t)}async listOutputs(e,t){return await this.CWI.listOutputs(e,t)}async relinquishOutput(e,t){return await this.CWI.relinquishOutput(e,t)}async getPublicKey(e,t){return await this.CWI.getPublicKey(e,t)}async revealCounterpartyKeyLinkage(e,t){return await this.CWI.revealCounterpartyKeyLinkage(e,t)}async revealSpecificKeyLinkage(e,t){return await this.CWI.revealSpecificKeyLinkage(e,t)}async encrypt(e,t){return await this.CWI.encrypt(e,t)}async decrypt(e,t){return await this.CWI.decrypt(e,t)}async createHmac(e,t){return await this.CWI.createHmac(e,t)}async verifyHmac(e,t){return await this.CWI.verifyHmac(e,t)}async createSignature(e,t){return await this.CWI.createSignature(e,t)}async verifySignature(e,t){return await this.CWI.verifySignature(e,t)}async acquireCertificate(e,t){return await this.CWI.acquireCertificate(e,t)}async listCertificates(e,t){return await this.CWI.listCertificates(e,t)}async proveCertificate(e,t){return await this.CWI.proveCertificate(e,t)}async relinquishCertificate(e,t){return await this.CWI.relinquishCertificate(e,t)}async discoverByIdentityKey(e,t){return await this.CWI.discoverByIdentityKey(e,t)}async discoverByAttributes(e,t){return await this.CWI.discoverByAttributes(e,t)}async isAuthenticated(e,t){return await this.CWI.isAuthenticated(e,t)}async waitForAuthentication(e,t){return await this.CWI.waitForAuthentication(e,t)}async getHeight(e,t){return await this.CWI.getHeight(e,t)}async getHeaderForHeight(e,t){return await this.CWI.getHeaderForHeight(e,t)}async getNetwork(e,t){return await this.CWI.getNetwork(e,t)}async getVersion(e,t){return await this.CWI.getVersion(e,t)}}class rJ extends Error{code;isError=!0;constructor(e,t=1,i){super(e),this.code=t,this.name=this.constructor.name,null!=i&&""!==i?this.stack=i:Error.captureStackTrace(this,this.constructor)}static unknownToJson(e){let t;return!0===e.isError&&String(e.name).startsWith("WERR_")?"WERR_REVIEW_ACTIONS"===(t={name:e.name,message:e.message,isError:!0}).name?(t.reviewActionResults=e.reviewActionResults,t.sendWithResults=e.sendWithResults,t.txid=e.txid,t.tx=e.tx,t.noSendChange=e.noSendChange,t.code=5):"WERR_INVALID_PARAMETER"===t.name?(t.parameter=e.parameter,t.code=6):"WERR_INSUFFICIENT_FUNDS"===t.name&&(t.totalSatoshisNeeded=e.totalSatoshisNeeded,t.moreSatoshisNeeded=e.moreSatoshisNeeded,t.code=7):t=e instanceof Error?{name:e.constructor.name,message:e.message,isError:!0}:{name:"WERR_UNKNOWN",message:String(e),isError:!0},JSON.stringify(t)}}(o=d||(d={}))[o.unknownError=1]="unknownError",o[o.unsupportedAction=2]="unsupportedAction",o[o.invalidHmac=3]="invalidHmac",o[o.invalidSignature=4]="invalidSignature",o[o.reviewActions=5]="reviewActions",o[o.invalidParameter=6]="invalidParameter",o[o.insufficientFunds=7]="insufficientFunds";let rZ=rJ;class rQ{async createAction(e){return await this.invoke("createAction",e)}async signAction(e){return await this.invoke("signAction",e)}async abortAction(e){return await this.invoke("abortAction",e)}async listActions(e){return await this.invoke("listActions",e)}async internalizeAction(e){return await this.invoke("internalizeAction",e)}async listOutputs(e){return await this.invoke("listOutputs",e)}async relinquishOutput(e){return await this.invoke("relinquishOutput",e)}async getPublicKey(e){return await this.invoke("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.invoke("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.invoke("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.invoke("encrypt",e)}async decrypt(e){return await this.invoke("decrypt",e)}async createHmac(e){return await this.invoke("createHmac",e)}async verifyHmac(e){return await this.invoke("verifyHmac",e)}async createSignature(e){return await this.invoke("createSignature",e)}async verifySignature(e){return await this.invoke("verifySignature",e)}async acquireCertificate(e){return await this.invoke("acquireCertificate",e)}async listCertificates(e){return await this.invoke("listCertificates",e)}async proveCertificate(e){return await this.invoke("proveCertificate",e)}async relinquishCertificate(e){return await this.invoke("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.invoke("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.invoke("discoverByAttributes",e)}async isAuthenticated(e){return await this.invoke("isAuthenticated",e)}async waitForAuthentication(e){return await this.invoke("waitForAuthentication",e)}async getHeight(e){return await this.invoke("getHeight",e)}async getHeaderForHeight(e){return await this.invoke("getHeaderForHeight",e)}async getNetwork(e){return await this.invoke("getNetwork",e)}async getVersion(e){return await this.invoke("getVersion",e)}}class r0 extends rQ{domain;constructor(e="*"){if(super(),"object"!=typeof globalThis.window)throw TypeError("The XDM substrate requires a global window object.");if("function"!=typeof globalThis.window.postMessage)throw TypeError("The window object does not seem to support postMessage calls.");this.domain=e}async invoke(e,t){return await new Promise((i,r)=>{let n=tS(ia(12)),s=e=>{"CWI"===e.data.type&&e.isTrusted&&e.data.id===n&&!0!==e.data.isInvocation&&("function"==typeof window.removeEventListener&&window.removeEventListener("message",s),"error"===e.data.status?r(new rJ(e.data.description,e.data.code)):i(e.data.result))};window.addEventListener("message",s),window.parent.postMessage({type:"CWI",isInvocation:!0,id:n,call:e,args:t},this.domain)})}}class r1{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(e,t,i,r,n,s,a){this.type=e,this.serialNumber=t,this.subject=i,this.certifier=r,this.revocationOutpoint=n,this.fields=s,this.signature=a}toBinary(e=!0){let t=new tP,i=tm(this.type,"base64");t.write(i);let r=tm(this.serialNumber,"base64");t.write(r);let n=tm(this.subject,"hex");t.write(n);let s=tm(this.certifier,"hex");t.write(s);let[a,o]=this.revocationOutpoint.split("."),l=tm(a,"hex");t.write(l),t.writeVarIntNum(Number(o));let c=Object.keys(this.fields).sort((e,t)=>e.localeCompare(t));for(let e of(t.writeVarIntNum(c.length),c)){let i=this.fields[e],r=tm(e,"utf8");t.writeVarIntNum(r.length),t.write(r);let n=tm(i,"utf8");t.writeVarIntNum(n.length),t.write(n)}if(e&&(this.signature??"").length>0){let e=tm(this.signature,"hex");t.write(e)}return t.toArray()}static fromBinary(e){let t,i=new tN(e),r=tS(i.read(32)),n=tS(i.read(32)),s=tg(i.read(33)),a=tg(i.read(33)),o=tg(i.read(32)),l=i.readVarIntNum(),c=`${o}.${l}`,h=i.readVarIntNum(),d={};for(let e=0;e<h;e++){let e=i.readVarIntNum(),t=tI(i.read(e)),r=i.readVarIntNum(),n=tI(i.read(r));d[t]=n}if(!i.eof()){let e=i.read();t=t2.fromDER(e).toString("hex")}return new r1(r,n,s,a,c,d,t)}async verify(){let e=new rX("anyone"),t=this.toBinary(!1),i=this.signature??"",{valid:r}=await e.verifySignature({signature:tm(i,"hex"),data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`,counterparty:this.certifier});return r}async sign(e){if(null!=this.signature&&this.signature.length>0)throw Error(`Certificate has already been signed! Signature present: ${this.signature}`);this.certifier=(await e.getPublicKey({identityKey:!0})).publicKey;let t=this.toBinary(!1),{signature:i}=await e.createSignature({data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`});this.signature=tg(i)}static getCertificateFieldEncryptionDetails(e,t){return{protocolID:[2,"certificate field encryption"],keyID:t?`${t} ${e}`:e}}static fromObject(e){return new r1(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature)}}(l=u||(u={}))[l.createAction=1]="createAction",l[l.signAction=2]="signAction",l[l.abortAction=3]="abortAction",l[l.listActions=4]="listActions",l[l.internalizeAction=5]="internalizeAction",l[l.listOutputs=6]="listOutputs",l[l.relinquishOutput=7]="relinquishOutput",l[l.getPublicKey=8]="getPublicKey",l[l.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",l[l.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",l[l.encrypt=11]="encrypt",l[l.decrypt=12]="decrypt",l[l.createHmac=13]="createHmac",l[l.verifyHmac=14]="verifyHmac",l[l.createSignature=15]="createSignature",l[l.verifySignature=16]="verifySignature",l[l.acquireCertificate=17]="acquireCertificate",l[l.listCertificates=18]="listCertificates",l[l.proveCertificate=19]="proveCertificate",l[l.relinquishCertificate=20]="relinquishCertificate",l[l.discoverByIdentityKey=21]="discoverByIdentityKey",l[l.discoverByAttributes=22]="discoverByAttributes",l[l.isAuthenticated=23]="isAuthenticated",l[l.waitForAuthentication=24]="waitForAuthentication",l[l.getHeight=25]="getHeight",l[l.getHeaderForHeight=26]="getHeaderForHeight",l[l.getNetwork=27]="getNetwork",l[l.getVersion=28]="getVersion";let r2=u,r8={1:"completed",2:"unprocessed",3:"sending",4:"unproven",5:"unsigned",6:"nosend",7:"nonfinal",8:"failed"};class r3{wire;constructor(e){this.wire=e}async transmit(e,t="",i=[]){let r=new tP;r.writeUInt8(r2[e]);let n=tm(t,"utf8");r.writeUInt8(n.length),r.write(n),i.length>0&&r.write(i);let s=r.toArray(),a=new tN(await this.wire.transmitToWallet(s)),o=a.readUInt8();if(0===o)return a.read();{let e=a.readVarIntNum(),t=tI(a.read(e)),i=a.readVarIntNum();throw new rJ(t,o,tI(a.read(i)))}}async createAction(e,t){let i=new tP;if(this.writeUTF8(i,e.description),null==e.inputBEEF?i.writeVarIntNum(-1):(i.writeVarIntNum(e.inputBEEF.length),i.write(e.inputBEEF)),null==e.inputs)i.writeVarIntNum(-1);else for(let t of(i.writeVarIntNum(e.inputs.length),e.inputs))this.serializeCreateActionInput(i,t);if(null==e.outputs)i.writeVarIntNum(-1);else for(let t of(i.writeVarIntNum(e.outputs.length),e.outputs))this.serializeCreateActionOutput(i,t);this.writeOptionalVarInt(i,e.lockTime),this.writeOptionalVarInt(i,e.version),this.writeUTF8Array(i,e.labels),this.serializeCreateActionOptions(i,e.options);let r=await this.transmit("createAction",t,i.toArray());return this.parseCreateActionResult(r)}parseCreateActionResult(e){let t=new tN(e),i={};1===t.readInt8()&&(i.txid=tg(t.read(32))),1===t.readInt8()&&(i.tx=t.read(t.readVarIntNum()));let r=t.readVarIntNum();if(r>=0){i.noSendChange=[];for(let e=0;e<r;e++)i.noSendChange.push(this.readOutpoint(t))}let n=this.readSendWithResults(t);return null!=n&&(i.sendWithResults=n),1===t.readInt8()&&(i.signableTransaction={tx:t.read(t.readVarIntNum()),reference:tS(t.read(t.readVarIntNum()))}),i}async signAction(e,t){let i=new tP,r=Object.keys(e.spends);for(let t of(i.writeVarIntNum(r.length),r)){i.writeVarIntNum(Number(t));let r=e.spends[Number(t)],n=tm(r.unlockingScript,"hex");i.writeVarIntNum(n.length),i.write(n),this.writeOptionalVarInt(i,r.sequenceNumber)}let n=tm(e.reference,"base64");i.writeVarIntNum(n.length),i.write(n),this.serializeSignActionOptions(i,e.options);let s=new tN(await this.transmit("signAction",t,i.toArray())),a={};1===s.readInt8()&&(a.txid=tg(s.read(32))),1===s.readInt8()&&(a.tx=s.read(s.readVarIntNum()));let o=this.readSendWithResults(s);return null!=o&&(a.sendWithResults=o),a}async abortAction(e,t){return await this.transmit("abortAction",t,tm(e.reference,"base64")),{aborted:!0}}async listActions(e,t){let i=new tP;for(let t of(i.writeVarIntNum(e.labels.length),e.labels))this.writeUTF8(i,t);for(let t of("any"===e.labelQueryMode?i.writeInt8(1):"all"===e.labelQueryMode?i.writeInt8(2):i.writeInt8(-1),[e.includeLabels,e.includeInputs,e.includeInputSourceLockingScripts,e.includeInputUnlockingScripts,e.includeOutputs,e.includeOutputLockingScripts]))this.writeOptionalBool(i,t);this.writeOptionalVarInt(i,e.limit),this.writeOptionalVarInt(i,e.offset),this.writeOptionalBool(i,e.seekPermission);let r=new tN(await this.transmit("listActions",t,i.toArray())),n=r.readVarIntNum(),s=[];for(let e=0;e<n;e++)s.push(this.parseAction(r));return{totalActions:n,actions:s}}parseActionStatus(e){let t=r8[e];if(null==t)throw Error(`Unknown status code: ${e}`);return t}parseAction(e){let t=tg(e.read(32)),i=e.readVarIntNum(),r=this.parseActionStatus(e.readInt8()),n={txid:t,satoshis:i,status:r,isOutgoing:1===e.readInt8(),description:tI(e.read(e.readVarIntNum())),version:0,lockTime:0},s=e.readVarIntNum();if(s>=0){n.labels=[];for(let t=0;t<s;t++)n.labels.push(tI(e.read(e.readVarIntNum())))}n.version=e.readVarIntNum(),n.lockTime=e.readVarIntNum();let a=e.readVarIntNum();if(a>=0){n.inputs=[];for(let t=0;t<a;t++)n.inputs.push(this.parseActionInput(e))}let o=e.readVarIntNum();if(o>=0){n.outputs=[];for(let t=0;t<o;t++)n.outputs.push(this.parseActionOutput(e))}return n}parseActionInput(e){let t=this.readOutpoint(e),i=e.readVarIntNum(),r=e.readVarIntNum(),n=r>=0?tg(e.read(r)):void 0,s=e.readVarIntNum(),a=s>=0?tg(e.read(s)):void 0;return{sourceOutpoint:t,sourceSatoshis:i,sourceLockingScript:n,unlockingScript:a,inputDescription:tI(e.read(e.readVarIntNum())),sequenceNumber:e.readVarIntNum()}}parseActionOutput(e){let t=e.readVarIntNum(),i=e.readVarIntNum(),r=e.readVarIntNum(),n=r>=0?tg(e.read(r)):void 0,s=1===e.readInt8(),a=tI(e.read(e.readVarIntNum())),o=e.readVarIntNum(),l=o>=0?tI(e.read(o)):void 0,c=e.readVarIntNum(),h=[];if(c>=0)for(let t=0;t<c;t++)h.push(tI(e.read(e.readVarIntNum())));let d=e.readVarIntNum();return{outputIndex:t,satoshis:i,lockingScript:n,spendable:s,outputDescription:a,basket:l,tags:h,customInstructions:d>=0?tI(e.read(d)):void 0}}async internalizeAction(e,t){let i=new tP;for(let t of(i.writeVarIntNum(e.tx.length),i.write(e.tx),i.writeVarIntNum(e.outputs.length),e.outputs))this.serializeInternalizeOutput(i,t);this.writeUTF8Array(i,"object"==typeof e.labels?e.labels:void 0);let r=tm(e.description);return i.writeVarIntNum(r.length),i.write(r),this.writeOptionalBool(i,e.seekPermission),await this.transmit("internalizeAction",t,i.toArray()),{accepted:!0}}serializeInternalizeOutput(e,t){if(e.writeVarIntNum(t.outputIndex),"wallet payment"===t.protocol){if(null==t.paymentRemittance)throw Error("Payment remittance is required for wallet payment");e.writeUInt8(1),e.write(tm(t.paymentRemittance.senderIdentityKey,"hex"));let i=tm(t.paymentRemittance.derivationPrefix,"base64");e.writeVarIntNum(i.length),e.write(i);let r=tm(t.paymentRemittance.derivationSuffix,"base64");e.writeVarIntNum(r.length),e.write(r)}else{e.writeUInt8(2);let i=tm(t.insertionRemittance?.basket,"utf8");e.writeVarIntNum(i.length),e.write(i),this.writeOptionalUTF8(e,t.insertionRemittance?.customInstructions);let r=t.insertionRemittance?.tags;if("object"==typeof r)for(let t of(e.writeVarIntNum(r.length),r)){let i=tm(t,"utf8");e.writeVarIntNum(i.length),e.write(i)}else e.writeVarIntNum(0)}}async listOutputs(e,t){let i=new tP;if(this.writeUTF8(i,e.basket),"object"==typeof e.tags)for(let t of(i.writeVarIntNum(e.tags.length),e.tags))this.writeUTF8(i,t);else i.writeVarIntNum(0);"all"===e.tagQueryMode?i.writeInt8(1):"any"===e.tagQueryMode?i.writeInt8(2):i.writeInt8(-1),"locking scripts"===e.include?i.writeInt8(1):"entire transactions"===e.include?i.writeInt8(2):i.writeInt8(-1),this.writeOptionalBool(i,e.includeCustomInstructions),this.writeOptionalBool(i,e.includeTags),this.writeOptionalBool(i,e.includeLabels),this.writeOptionalVarInt(i,e.limit),this.writeOptionalVarInt(i,e.offset),this.writeOptionalBool(i,e.seekPermission);let r=new tN(await this.transmit("listOutputs",t,i.toArray())),n=r.readVarIntNum(),s=r.readVarIntNum(),a=s>=0?r.read(s):void 0,o=[];for(let e=0;e<n;e++)o.push(this.parseListOutputEntry(r));return{totalOutputs:n,BEEF:a,outputs:o}}parseListOutputEntry(e){let t={spendable:!0,outpoint:this.readOutpoint(e),satoshis:e.readVarIntNum()},i=e.readVarIntNum();i>=0&&(t.lockingScript=tg(e.read(i)));let r=e.readVarIntNum();r>=0&&(t.customInstructions=tI(e.read(r)));let n=e.readVarIntNum();if(-1!==n){let i=[];for(let t=0;t<n;t++)i.push(tI(e.read(e.readVarIntNum())));t.tags=i}let s=e.readVarIntNum();if(-1!==s){let i=[];for(let t=0;t<s;t++)i.push(tI(e.read(e.readVarIntNum())));t.labels=i}return t}async relinquishOutput(e,t){let i=new tP,r=tm(e.basket,"utf8");return i.writeVarIntNum(r.length),i.write(r),i.write(this.encodeOutpoint(e.output)),await this.transmit("relinquishOutput",t,i.toArray()),{relinquished:!0}}encodeOutpoint(e){let t=new tP,[i,r]=e.split(".");return t.write(tm(i,"hex")),t.writeVarIntNum(Number(r)),t.toArray()}readOutpoint(e){let t=tg(e.read(32)),i=e.readVarIntNum();return`${t}.${i}`}async getPublicKey(e,t){let i=new tP;return i.writeUInt8(+!!e.identityKey),e.identityKey?i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)):(e.protocolID??=[h.Silent,"default"],e.keyID??="",i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?i.writeInt8(+!!e.forSelf):i.writeInt8(-1)),this.writeOptionalBool(i,e.seekPermission),{publicKey:tg(await this.transmit("getPublicKey",t,i.toArray()))}}async revealCounterpartyKeyLinkage(e,t){let i=new tP;i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),i.write(tm(e.counterparty,"hex")),i.write(tm(e.verifier,"hex"));let r=new tN(await this.transmit("revealCounterpartyKeyLinkage",t,i.toArray())),n=tg(r.read(33)),s=tg(r.read(33)),a=tg(r.read(33)),o=r.readVarIntNum(),l=tI(r.read(o)),c=r.readVarIntNum(),h=r.read(c),d=r.readVarIntNum();return{prover:n,verifier:s,counterparty:a,revelationTime:l,encryptedLinkage:h,encryptedLinkageProof:r.read(d)}}async revealSpecificKeyLinkage(e,t){let i=new tP;i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.write(tm(e.verifier,"hex"));let r=new tN(await this.transmit("revealSpecificKeyLinkage",t,i.toArray())),n=tg(r.read(33)),s=tg(r.read(33)),a=tg(r.read(33)),o=r.readUInt8(),l=r.readVarIntNum(),c=tI(r.read(l)),h=r.readVarIntNum(),d=tI(r.read(h)),u=r.readVarIntNum(),f=r.read(u),p=r.readVarIntNum();return{prover:n,verifier:s,counterparty:a,protocolID:[o,c],keyID:d,encryptedLinkage:f,encryptedLinkageProof:r.read(p),proofType:r.readUInt8()}}async encrypt(e,t){let i=new tP;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.writeVarIntNum(e.plaintext.length),i.write(e.plaintext),this.writeOptionalBool(i,e.seekPermission),{ciphertext:await this.transmit("encrypt",t,i.toArray())}}async decrypt(e,t){let i=new tP;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.writeVarIntNum(e.ciphertext.length),i.write(e.ciphertext),this.writeOptionalBool(i,e.seekPermission),{plaintext:await this.transmit("decrypt",t,i.toArray())}}async createHmac(e,t){let i=new tP;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.writeVarIntNum(e.data.length),i.write(e.data),this.writeOptionalBool(i,e.seekPermission),{hmac:await this.transmit("createHmac",t,i.toArray())}}async verifyHmac(e,t){let i=new tP;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.write(e.hmac),i.writeVarIntNum(e.data.length),i.write(e.data),this.writeOptionalBool(i,e.seekPermission),await this.transmit("verifyHmac",t,i.toArray()),{valid:!0}}async createSignature(e,t){let i=new tP;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"object"==typeof e.data?(i.writeUInt8(1),i.writeVarIntNum(e.data.length),i.write(e.data)):(e.hashToDirectlySign??=[],i.writeUInt8(2),i.write(e.hashToDirectlySign)),this.writeOptionalBool(i,e.seekPermission),{signature:await this.transmit("createSignature",t,i.toArray())}}async verifySignature(e,t){let i=new tP;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?i.writeInt8(+!!e.forSelf):i.writeInt8(-1),i.writeVarIntNum(e.signature.length),i.write(e.signature),"object"==typeof e.data?(i.writeUInt8(1),i.writeVarIntNum(e.data.length),i.write(e.data)):(i.writeUInt8(2),i.write(e.hashToDirectlyVerify??[])),this.writeOptionalBool(i,e.seekPermission),await this.transmit("verifySignature",t,i.toArray()),{valid:!0}}writeOptionalBool(e,t){"boolean"==typeof t?e.writeInt8(+!!t):e.writeInt8(-1)}writeOptionalVarInt(e,t){"number"==typeof t?e.writeVarIntNum(t):e.writeVarIntNum(-1)}writeUTF8(e,t){let i=tm(t??"","utf8");e.writeVarIntNum(i.length),e.write(i)}writeOptionalUTF8(e,t){if(null!=t&&""!==t){let i=tm(t,"utf8");e.writeVarIntNum(i.length),e.write(i)}else e.writeVarIntNum(-1)}writeUTF8Array(e,t){if(null==t)e.writeVarIntNum(-1);else for(let i of(e.writeVarIntNum(t.length),t)){let t=tm(i,"utf8");e.writeVarIntNum(t.length),e.write(t)}}writeTxidArray(e,t){if(null==t)e.writeVarIntNum(-1);else for(let i of(e.writeVarIntNum(t.length),t))e.write(tm(i,"hex"))}readSendWithResults(e){let t=e.readVarIntNum();if(t<0)return;let i=[];for(let r=0;r<t;r++){let t=tg(e.read(32)),r=e.readInt8(),n=2===r?"sending":3===r?"failed":"unproven";i.push({txid:t,status:n})}return i}serializeCreateActionInput(e,t){if(e.write(this.encodeOutpoint(t.outpoint)),null!=t.unlockingScript&&""!==t.unlockingScript){let i=tm(t.unlockingScript,"hex");e.writeVarIntNum(i.length),e.write(i)}else e.writeVarIntNum(-1),e.writeVarIntNum(t.unlockingScriptLength??0);this.writeUTF8(e,t.inputDescription),this.writeOptionalVarInt(e,t.sequenceNumber)}serializeCreateActionOutput(e,t){let i=tm(t.lockingScript,"hex");e.writeVarIntNum(i.length),e.write(i),e.writeVarIntNum(t.satoshis),this.writeUTF8(e,t.outputDescription),this.writeOptionalUTF8(e,t.basket),this.writeOptionalUTF8(e,t.customInstructions),this.writeUTF8Array(e,t.tags)}serializeCreateActionOptions(e,t){if(null==t)return void e.writeInt8(0);if(e.writeInt8(1),this.writeOptionalBool(e,t.signAndProcess),this.writeOptionalBool(e,t.acceptDelayedBroadcast),e.writeInt8("known"===t.trustSelf?1:-1),this.writeTxidArray(e,t.knownTxids),this.writeOptionalBool(e,t.returnTXIDOnly),this.writeOptionalBool(e,t.noSend),null==t.noSendChange)e.writeVarIntNum(-1);else for(let i of(e.writeVarIntNum(t.noSendChange.length),t.noSendChange))e.write(this.encodeOutpoint(i));this.writeTxidArray(e,t.sendWith),this.writeOptionalBool(e,t.randomizeOutputs)}serializeSignActionOptions(e,t){null==t?e.writeInt8(0):(e.writeInt8(1),this.writeOptionalBool(e,t.acceptDelayedBroadcast),this.writeOptionalBool(e,t.returnTXIDOnly),this.writeOptionalBool(e,t.noSend),this.writeTxidArray(e,t.sendWith))}encodeKeyRelatedParams(e,t,i,r,n){let s=new tP;s.writeUInt8(e[0]);let a=tm(e[1],"utf8");s.writeVarIntNum(a.length),s.write(a);let o=tm(t,"utf8");return s.writeVarIntNum(o.length),s.write(o),"string"!=typeof i?s.writeUInt8(0):"self"===i?s.writeUInt8(11):"anyone"===i?s.writeUInt8(12):s.write(tm(i,"hex")),s.write(this.encodePrivilegedParams(r,n)),s.toArray()}async acquireCertificate(e,t){let i=new tP;i.write(tm(e.type,"base64")),i.write(tm(e.certifier,"hex"));let r=Object.entries(e.fields);for(let[e,t]of(i.writeVarIntNum(r.length),r)){let r=tm(e,"utf8"),n=tm(t,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(n.length),i.write(n)}if(i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),i.writeUInt8("direct"===e.acquisitionProtocol?1:2),"direct"===e.acquisitionProtocol){i.write(tm(e.serialNumber,"base64")),i.write(this.encodeOutpoint(e.revocationOutpoint??""));let t=tm(e.signature,"hex");i.writeVarIntNum(t.length),i.write(t);let r="certifier"===e.keyringRevealer?[11]:tm(e.keyringRevealer,"hex");i.write(r);let n=Object.keys(e.keyringForSubject??{});for(let t of(i.writeVarIntNum(n.length),n)){let r=tm(t,"utf8");i.writeVarIntNum(r.length),i.write(r);let n=tm(e.keyringForSubject?.[t],"base64");i.writeVarIntNum(n.length),i.write(n)}}else{let t=tm(e.certifierUrl,"utf8");i.writeVarIntNum(t.length),i.write(t)}let n=await this.transmit("acquireCertificate",t,i.toArray()),s=r1.fromBinary(n);return{...s,signature:s.signature}}encodePrivilegedParams(e,t){let i=new tP;if("boolean"==typeof e?i.writeInt8(+!!e):i.writeInt8(-1),"string"==typeof t){let e=tm(t,"utf8");i.writeInt8(e.length),i.write(e)}else i.writeInt8(-1);return i.toArray()}async listCertificates(e,t){let i=new tP;for(let t of(i.writeVarIntNum(e.certifiers.length),e.certifiers))i.write(tm(t,"hex"));for(let t of(i.writeVarIntNum(e.types.length),e.types))i.write(tm(t,"base64"));"number"==typeof e.limit?i.writeVarIntNum(e.limit):i.writeVarIntNum(-1),"number"==typeof e.offset?i.writeVarIntNum(e.offset):i.writeVarIntNum(-1),i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let r=new tN(await this.transmit("listCertificates",t,i.toArray())),n=r.readVarIntNum(),s=[];for(let e=0;e<n;e++){let e,t=r.readVarIntNum(),i=r.read(t),n=r1.fromBinary(i),a={};if(1===r.readInt8()){let e=r.readVarIntNum();for(let t=0;t<e;t++){let e=r.readVarIntNum(),t=tI(r.read(e)),i=r.readVarIntNum();a[t]=tS(r.read(i))}}let o=r.readVarIntNum();o>0&&(e=tI(r.read(o))),s.push({...n,signature:n.signature,keyring:a,verifier:e})}return{totalCertificates:n,certificates:s}}async proveCertificate(e,t){let i=new tP,r=tm(e.certificate.type,"base64");i.write(r);let n=tm(e.certificate.subject,"hex");i.write(n);let s=tm(e.certificate.serialNumber,"base64");i.write(s);let a=tm(e.certificate.certifier,"hex");i.write(a);let o=this.encodeOutpoint(e.certificate.revocationOutpoint??"");i.write(o);let l=tm(e.certificate.signature,"hex");i.writeVarIntNum(l.length),i.write(l);let c=Object.entries(e.certificate.fields??{});for(let[e,t]of(i.writeVarIntNum(c.length),c)){let r=tm(e,"utf8"),n=tm(t,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(n.length),i.write(n)}for(let t of(i.writeVarIntNum(e.fieldsToReveal.length),e.fieldsToReveal)){let e=tm(t,"utf8");i.writeVarIntNum(e.length),i.write(e)}i.write(tm(e.verifier,"hex")),i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let h=new tN(await this.transmit("proveCertificate",t,i.toArray())),d=h.readVarIntNum(),u={};for(let e=0;e<d;e++){let e=h.readVarIntNum(),t=tI(h.read(e)),i=h.readVarIntNum();u[t]=tS(h.read(i))}return{keyringForVerifier:u}}async relinquishCertificate(e,t){let i=new tP,r=tm(e.type,"base64");i.write(r);let n=tm(e.serialNumber,"base64");i.write(n);let s=tm(e.certifier,"hex");return i.write(s),await this.transmit("relinquishCertificate",t,i.toArray()),{relinquished:!0}}parseDiscoveryResult(e){let t=new tN(e),i=t.readVarIntNum(),r=[];for(let e=0;e<i;e++){let e=t.readVarIntNum(),i=t.read(e),n=r1.fromBinary(i),s=t.readVarIntNum(),a=tI(t.read(s)),o=t.readVarIntNum(),l=tI(t.read(o)),c=t.readVarIntNum(),h=tI(t.read(c)),d=t.readUInt8(),u={},f=t.readVarIntNum();for(let e=0;e<f;e++){let e=t.readVarIntNum(),i=tI(t.read(e)),r=t.readVarIntNum();u[i]=t.read(r)}let p={},g=t.readVarIntNum();for(let e=0;e<g;e++){let e=t.readVarIntNum(),i=tI(t.read(e)),r=t.readVarIntNum();p[i]=tI(t.read(r))}r.push({...n,signature:n.signature,certifierInfo:{iconUrl:l,name:a,description:h,trust:d},publiclyRevealedKeyring:u,decryptedFields:p})}return{totalCertificates:i,certificates:r}}async discoverByIdentityKey(e,t){let i=new tP;i.write(tm(e.identityKey,"hex")),"number"==typeof e.limit?i.writeVarIntNum(e.limit):i.writeVarIntNum(-1),"number"==typeof e.offset?i.writeVarIntNum(e.offset):i.writeVarIntNum(-1),this.writeOptionalBool(i,e.seekPermission);let r=await this.transmit("discoverByIdentityKey",t,i.toArray());return this.parseDiscoveryResult(r)}async discoverByAttributes(e,t){let i=new tP,r=Object.keys(e.attributes);for(let t of(i.writeVarIntNum(r.length),r))i.writeVarIntNum(t.length),i.write(tm(t,"utf8")),i.writeVarIntNum(e.attributes[t].length),i.write(tm(e.attributes[t],"utf8"));"number"==typeof e.limit?i.writeVarIntNum(e.limit):i.writeVarIntNum(-1),"number"==typeof e.offset?i.writeVarIntNum(e.offset):i.writeVarIntNum(-1),this.writeOptionalBool(i,e.seekPermission);let n=await this.transmit("discoverByAttributes",t,i.toArray());return this.parseDiscoveryResult(n)}async isAuthenticated(e,t){return{authenticated:1===(await this.transmit("isAuthenticated",t))[0]}}async waitForAuthentication(e,t){return await this.transmit("waitForAuthentication",t),{authenticated:!0}}async getHeight(e,t){return{height:new tN(await this.transmit("getHeight",t)).readVarIntNum()}}async getHeaderForHeight(e,t){let i=new tP;return i.writeVarIntNum(e.height),{header:tg(await this.transmit("getHeaderForHeight",t,i.toArray()))}}async getNetwork(e,t){return{network:0===(await this.transmit("getNetwork",t))[0]?"mainnet":"testnet"}}async getVersion(e,t){return{version:tI(await this.transmit("getVersion",t))}}}class r5{baseUrl;httpClient;originator;constructor(e,t="http://localhost:3301",i=fetch){this.baseUrl=t,this.httpClient=i,this.originator=e}async transmitToWallet(e){let t,i=new tN(e),r=i.readUInt8(),n=r2[r];if(void 0===n||""===n)throw Error(`Invalid call code: ${r}`);let s=i.readUInt8();s>0&&(t=tI(i.read(s)));let a=i.read(),o=await fetch(`${this.baseUrl}/${n}`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Origin:t??""},body:new Uint8Array(a)});return Array.from(new Uint8Array(await o.arrayBuffer()))}}class r6 extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(e,t,i,r,n){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=e,this.sendWithResults=t,this.txid=i,this.tx=r,this.noSendChange=n,this.code=5,this.name=this.constructor.name}}let r4=r6;class r9 extends Error{parameter;code;isError=!0;constructor(e,t){super(`The ${e} parameter must be ${t??"valid."}`),this.parameter=e,this.code=6,this.name=this.constructor.name}}let r7=r9,ne=class extends Error{totalSatoshisNeeded;moreSatoshisNeeded;code;isError=!0;constructor(e,t){super(`Insufficient funds in the available inputs to cover the cost of the required outputs and the transaction fee (${t} more satoshis are needed, for a total of ${e}), plus whatever would be required in order to pay the fee to unlock and spend the outputs used to provide the additional satoshis.`),this.totalSatoshisNeeded=e,this.moreSatoshisNeeded=t,this.code=7,this.name=this.constructor.name}};class nt{baseUrl;httpClient;originator;api;constructor(e,t="http://localhost:3321",i=fetch){this.baseUrl=t,this.originator=e,this.httpClient=i;const r=void 0!==globalThis.window&&"u">typeof document&&globalThis.window?.origin!=="file://";this.api=async(e,t)=>{let n=!r&&this.originator?function(e,t="http"){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))try{return new URL(e).origin}catch{}try{return new URL(`${t}://${e}`).origin}catch{throw Error(`Invalid originator value: ${e}`)}}(this.originator,"http"):void 0;if(!r&&void 0===n)throw Error('HTTPWalletJSON: originator is required when using the HTTP substrate in Node.js. Pass an originator (e.g. "example.com") to the constructor.');let s=await i(`${this.baseUrl}/${e}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...n?{Origin:n}:{},...n?{Originator:n}:{}},body:JSON.stringify(t)}),a=await s.json();if(!s.ok){if(400===s.status&&a.isError){let e;switch(a.code){case 5:e=new r6(a.reviewActionResults,a.sendWithResults,a.txid,a.tx,a.noSendChange);break;case 6:(e=new r9(a.parameter)).message=a.message;break;case 7:e=new ne(a.totalSatoshisNeeded,a.moreSatoshisNeeded)}if(e)throw e}throw Error(JSON.stringify({call:e,args:t,message:a.message??`HTTP Client error ${s.status}`}))}return a}}async createAction(e){return await this.api("createAction",e)}async signAction(e){return await this.api("signAction",e)}async abortAction(e){return await this.api("abortAction",e)}async listActions(e){return await this.api("listActions",e)}async internalizeAction(e){return await this.api("internalizeAction",e)}async listOutputs(e){return await this.api("listOutputs",e)}async relinquishOutput(e){return await this.api("relinquishOutput",e)}async getPublicKey(e){return await this.api("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.api("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.api("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.api("encrypt",e)}async decrypt(e){return await this.api("decrypt",e)}async createHmac(e){return await this.api("createHmac",e)}async verifyHmac(e){return await this.api("verifyHmac",e)}async createSignature(e){return await this.api("createSignature",e)}async verifySignature(e){return await this.api("verifySignature",e)}async acquireCertificate(e){return await this.api("acquireCertificate",e)}async listCertificates(e){return await this.api("listCertificates",e)}async proveCertificate(e){return await this.api("proveCertificate",e)}async relinquishCertificate(e){return await this.api("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.api("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.api("discoverByAttributes",e)}async isAuthenticated(e){return await this.api("isAuthenticated",e)}async waitForAuthentication(e){return await this.api("waitForAuthentication",e)}async getHeight(e){return await this.api("getHeight",e)}async getHeaderForHeight(e){return await this.api("getHeaderForHeight",e)}async getNetwork(e){return await this.api("getNetwork",e)}async getVersion(e){return await this.api("getVersion",e)}}class ni extends rQ{domain;constructor(e="*"){if(super(),"object"!=typeof globalThis.window)throw TypeError("The XDM substrate requires a global window object.");if(!globalThis.window.hasOwnProperty("ReactNativeWebView"))throw Error("The window object does not have a ReactNativeWebView property.");if("function"!=typeof globalThis.window.ReactNativeWebView.postMessage)throw TypeError("The window.ReactNativeWebView property does not seem to support postMessage calls.");this.domain=e}async invoke(e,t){return await new Promise((i,r)=>{let n=tS(ia(12)),s=e=>{let t=JSON.parse(e.data);"CWI"===t.type&&t.id===n&&!0!==t.isInvocation&&("function"==typeof globalThis.window.removeEventListener&&globalThis.window.removeEventListener("message",s),"error"===t.status?r(new rJ(t.description,t.code)):i(t.result))};globalThis.window.addEventListener("message",s),globalThis.window.ReactNativeWebView.postMessage(JSON.stringify({type:"CWI",isInvocation:!0,id:n,call:e,args:t}))})}}function nr(e){let[t,i]=e.split(".");return{txid:t,vout:Number(i)}}function nn(e){return e??!1}function ns(e,t,i,r){if(void 0!==e)return nh(e,t,i,r)}function na(e,t,i){if(void 0===e||!Number.isInteger(e)||e<0||e>21e14)throw new r7(t,"a valid number of satoshis");if(void 0!==i&&e<i)throw new r7(t,`at least ${i} satoshis.`);return e}function no(e,t,i,r){if(void 0!==e)return nl(e,t,void 0,i,r)}function nl(e,t,i,r,n){if(void 0===e){if(void 0!==i)return i;throw new r7(t,"a valid integer")}if(!Number.isInteger(e))throw new r7(t,"an integer");if(e=Number(e),void 0!==r&&e<r)throw new r7(t,`at least ${r} length.`);if(void 0!==n&&e>n)throw new r7(t,`no more than ${n} length.`);return e}function nc(e,t){return nl(e,t,0,0)}function nh(e,t,i,r){let n=tm(e,"utf8").length;if(void 0!==i&&n<i)throw new r7(t,`at least ${i} length.`);if(void 0!==r&&n>r)throw new r7(t,`no more than ${r} length.`);return e}function nd(e){return np(e,"basket",1,300)}function nu(e){return np(e,"label",1,300)}function nf(e){return np(e,"tag",1,300)}function np(e,t,i,r){let n=tm(e=e.trim().toLowerCase(),"utf8").length;if(void 0!==i&&n<i)throw new r7(t,`at least ${i} length.`);if(void 0!==r&&n>r)throw new r7(t,`no more than ${r} length.`);return e}function ng(e,t,i,r){if(void 0!==e)return ny(e,t,i,r)}function ny(e,t,i,r){if(0===(e=e.trim()).length)throw new r7(t,"valid base64 string");let n=0;for(let i=0;i<e.length;i++){let r=e.codePointAt(i)??0;if((!(r>=65)||!(r<=90))&&(!(r>=97)||!(r<=122))&&(!(r>=48)||!(r<=57))&&43!==r&&47!==r){if(61===r){if(i<e.length-2)throw new r7(t,"valid base64 string");n++;continue}throw new r7(t,"valid base64 string")}}if(n>2||n>0&&e.length%4!=0)throw new r7(t,"valid base64 string");let s=e.length%4;if(0!==s&&s!==4-n)throw new r7(t,"valid base64 string");let a=Math.floor(3*(e.length-n)/4);if(void 0!==i&&a<i)throw new r7(t,`at least ${i} bytes`);if(void 0!==r&&a>r)throw new r7(t,`no more than ${r} bytes`);return e}function nm(e,t,i,r){if(void 0!==e)return nb(e,t,i,r)}function nb(e,t,i,r){if((e=e.trim().toLowerCase()).length%2==1)throw new r7(t,`even length, not ${e.length}.`);if(!/^[0-9A-Fa-f]+$/.test(e))throw new r7(t,"hexadecimal string.");if(void 0!==i&&e.length<i)throw new r7(t,`at least ${i} length.`);if(void 0!==r&&e.length>r)throw new r7(t,`no more than ${r} length.`);return e}function nw(e){return(e=e.trim()).length%2!=1&&!!/^[0-9A-Fa-f]+$/.test(e)}function nv(e){if(void 0===e.unlockingScript&&void 0===e.unlockingScriptLength)throw new r7("unlockingScript, unlockingScriptLength","at least one valid value.");let t=nm(e.unlockingScript,"unlockingScript"),i=e.unlockingScriptLength??(null==t?0:t.length/2);if(t&&i!==t.length/2)throw new r7("unlockingScriptLength","length unlockingScript if both valid.");return{outpoint:nr(e.outpoint),inputDescription:nh(e.inputDescription,"inputDescription",5,2e3),unlockingScript:t,unlockingScriptLength:i,sequenceNumber:e.sequenceNumber??0xffffffff}}function nI(e){return{lockingScript:nb(e.lockingScript,"lockingScript"),satoshis:na(e.satoshis,"satoshis"),outputDescription:nh(e.outputDescription,"outputDescription",5,2e3),basket:function(e){if(void 0!==e)return nd(e)}(e.basket),customInstructions:e.customInstructions,tags:(e.tags??[]).map(e=>nf(e))}}function nk(e){let t=e??{};return{signAndProcess:t.signAndProcess??!0,acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,knownTxids:t.knownTxids??[],returnTXIDOnly:nn(t.returnTXIDOnly),noSend:nn(t.noSend),noSendChange:(t.noSendChange??[]).map(e=>nr(e)),sendWith:t.sendWith??[],randomizeOutputs:t.randomizeOutputs??!0}}function nS(e,t){let i={description:nh(e.description,"description",5,2e3),inputBEEF:e.inputBEEF,inputs:(e.inputs??[]).map(e=>nv(e)),outputs:(e.outputs??[]).map(e=>nI(e)),lockTime:e.lockTime??0,version:e.version??1,labels:e.labels?.map(e=>nu(e))??[],options:nk(e.options),logger:t,isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!1,isRemixChange:!1,isSignAction:!1,randomVals:void 0,includeAllSourceTransactions:!1,isTestWerrReviewActions:!1};return i.isTestWerrReviewActions=i.labels.includes(nz),i.isSendWith=i.options.sendWith.length>0,i.isRemixChange=!i.isSendWith&&0===i.inputs.length&&0===i.outputs.length,i.isNewTx=i.isRemixChange||i.inputs.length>0||i.outputs.length>0,i.isSignAction=i.isNewTx&&(!i.options.signAndProcess||i.inputs.some(e=>void 0===e.unlockingScript)),i.isDelayed=i.options.acceptDelayedBroadcast,i.isNoSend=i.options.noSend,i}function nE(e){let t=e??{};return{acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,returnTXIDOnly:nn(t.returnTXIDOnly),noSend:nn(t.noSend),sendWith:t.sendWith??[]}}function nx(e){let t={spends:e.spends,reference:e.reference,options:nE(e.options),isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!0,isRemixChange:!1,isTestWerrReviewActions:!1};return t.isSendWith=t.options.sendWith.length>0,t.isDelayed=t.options.acceptDelayedBroadcast,t.isNoSend=t.options.noSend,t}function nA(e){return{reference:ny(e.reference,"reference")}}function nT(e){if(void 0!==e)return{derivationPrefix:ny(e.derivationPrefix,"derivationPrefix"),derivationSuffix:ny(e.derivationSuffix,"derivationSuffix"),senderIdentityKey:nb(e.senderIdentityKey,"senderIdentityKey")}}function nO(e){if(void 0!==e)return{basket:nd(e.basket),customInstructions:ns(e.customInstructions,"customInstructions",0,1e3),tags:(e.tags??[]).map(e=>nf(e))}}function nP(e){if("basket insertion"!==e.protocol&&"wallet payment"!==e.protocol)throw new r7("protocol","'basket insertion' or 'wallet payment'");return{outputIndex:nc(e.outputIndex,"outputIndex"),protocol:e.protocol,paymentRemittance:nT(e.paymentRemittance),insertionRemittance:nO(e.insertionRemittance)}}function nN(e){if(void 0!==e){for(let t of(nh(e=e.trim().toLowerCase(),"originator",1,250),e.split(".")))nh(t,"originator part",1,63);return e}}function n_(e){let t={tx:e.tx,outputs:e.outputs.map(e=>nP(e)),description:nh(e.description,"description",5,2e3),labels:(e.labels??[]).map(e=>nu(e)),seekPermission:e.seekPermission??!0};try{if(rp.fromBinary(t.tx).txs.length<1)throw new r7("tx","at least one transaction to internalize an output from")}catch{throw new r7("tx","valid with at least one transaction to internalize an output from")}if(t.outputs.length<1)throw new r7("outputs","at least one output to internalize from the transaction");return t}function nR(e,t){if(void 0!==e)return nC(e,t)}function nC(e,t){let i=e.split(".");if(2!==i.length||!Number.isInteger(Number(i[1])))throw new r7(t,"txid as hex string and numeric output index joined with '.'");let r=nb(i[0],`${t} txid`,void 0,64),n=nc(Number(i[1]),`${t} vout`);return`${r}.${n}`}function nB(e){return{basket:nd(e.basket),output:nC(e.output,"output")}}function nU(e){return{type:ny(e.type,"type"),serialNumber:ny(e.serialNumber,"serialNumber"),certifier:nb(e.certifier,"certifier")}}function nF(e){return{certifiers:e.certifiers.map(e=>nb(e.trim(),"certifiers"))??[],types:e.types.map(e=>ny(e.trim(),"types"))??[],limit:nl(e.limit,"limit",10,1,1e4),offset:nc(e.offset??0,"offset"),privileged:nn(e.privileged),privilegedReason:ns(e.privilegedReason,"privilegedReason",5,50),partial:void 0}}function nD(e){for(let t of Object.keys(e))nh(t,"field name",1,50);return e}function nL(e){if("issuance"!==e.acquisitionProtocol)throw Error("Only acquire certificate via issuance requests allowed here.");if(e.serialNumber)throw new r7("serialNumber",'valid when acquisitionProtocol is "direct"');if(e.signature)throw new r7("signature",'valid when acquisitionProtocol is "direct"');if(e.revocationOutpoint)throw new r7("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(e.keyringRevealer)throw new r7("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null!=e.keyringForSubject)throw new r7("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(!e.certifierUrl)throw new r7("certifierUrl",'valid when acquisitionProtocol is "issuance"');if(e.privileged&&!e.privilegedReason)throw new r7("privilegedReason","valid when 'privileged' is true ");return{type:ny(e.type,"type"),certifier:nb(e.certifier,"certifier"),certifierUrl:e.certifierUrl,fields:nD(e.fields),privileged:nn(e.privileged),privilegedReason:ns(e.privilegedReason,"privilegedReason",5,50),subject:""}}function nV(e){var t;if("direct"!==e.acquisitionProtocol)throw Error("Only acquire direct certificate requests allowed here.");if(!e.serialNumber)throw new r7("serialNumber",'valid when acquisitionProtocol is "direct"');if(!e.signature)throw new r7("signature",'valid when acquisitionProtocol is "direct"');if(!e.revocationOutpoint)throw new r7("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(!e.keyringRevealer)throw new r7("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null==e.keyringForSubject)throw new r7("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(e.privileged&&!e.privilegedReason)throw new r7("privilegedReason","valid when 'privileged' is true ");return{type:ny(e.type,"type"),serialNumber:ny(e.serialNumber,"serialNumber"),certifier:nb(e.certifier,"certifier"),revocationOutpoint:nC(e.revocationOutpoint,"revocationOutpoint"),fields:nD(e.fields),signature:nb(e.signature,"signature"),keyringRevealer:(t=e.keyringRevealer,"certifier"===t?t:nb(t,"keyringRevealer")),keyringForSubject:function(e,t){for(let i of Object.keys(e))nh(i,`${t} field name`,1,50),ny(e[i],`${t} field value`);return e}(e.keyringForSubject,"keyringForSubject"),privileged:nn(e.privileged),privilegedReason:ns(e.privilegedReason,"privilegedReason",5,50),subject:""}}function nH(e){if(e.privileged&&!e.privilegedReason)throw new r7("privilegedReason","valid when 'privileged' is true ");return{type:ng(e.certificate.type,"certificate.type"),serialNumber:ng(e.certificate.serialNumber,"certificate.serialNumber"),certifier:nm(e.certificate.certifier,"certificate.certifier"),subject:nm(e.certificate.subject,"certificate.subject"),revocationOutpoint:nR(e.certificate.revocationOutpoint,"certificate.revocationOutpoint"),signature:nm(e.certificate.signature,"certificate.signature"),fieldsToReveal:(e.fieldsToReveal??[]).map(e=>nh(e,`fieldsToReveal ${e}`,1,50)),verifier:nb(e.verifier,"verifier"),privileged:nn(e.privileged),privilegedReason:ns(e.privilegedReason,"privilegedReason",5,50)}}function nM(e){return{identityKey:nb(e.identityKey,"identityKey",66,66),limit:nl(e.limit,"limit",10,1,1e4),offset:nc(e.offset??0,"offset"),seekPermission:nn(e.seekPermission)}}function nK(e){return{attributes:function(e){for(let t of Object.keys(e))nh(t,`field name ${t}`,1,50);return e}(e.attributes),limit:nl(e.limit,"limit",10,1,1e4),offset:nc(e.offset??0,"offset"),seekPermission:nn(e.seekPermission)}}function nq(e){let t;if(void 0===e.tagQueryMode||"any"===e.tagQueryMode)t="any";else if("all"===e.tagQueryMode)t="all";else throw new r7("tagQueryMode","undefined, 'any', or 'all'");return{basket:nd(e.basket),tags:(e.tags??[]).map(e=>nf(e)),tagQueryMode:t,includeLockingScripts:"locking scripts"===e.include,includeTransactions:"entire transactions"===e.include,includeCustomInstructions:nn(e.includeCustomInstructions),includeTags:nn(e.includeTags),includeLabels:nn(e.includeLabels),limit:nl(e.limit,"limit",10,1,1e4),offset:nl(e.offset,"offset",0),seekPermission:e.seekPermission??!0,knownTxids:[]}}function n$(e){let t;if(void 0===e.labelQueryMode||"any"===e.labelQueryMode)t="any";else if("all"===e.labelQueryMode)t="all";else throw new r7("labelQueryMode","undefined, 'any', or 'all'");return{labels:(e.labels??[]).map(e=>nu(e)),labelQueryMode:t,includeLabels:nn(e.includeLabels),includeInputs:nn(e.includeInputs),includeInputSourceLockingScripts:nn(e.includeInputSourceLockingScripts),includeInputUnlockingScripts:nn(e.includeInputUnlockingScripts),includeOutputs:nn(e.includeOutputs),includeOutputLockingScripts:nn(e.includeOutputLockingScripts),limit:nl(e.limit,"limit",10,1,1e4),offset:nl(e.offset,"offset",0,0),seekPermission:e.seekPermission??!0}}let nz="a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a";class nW{substrate;originator;constructor(e="auto",t){"Cicada"===e&&(e=new r3(new r5(t))),"window.CWI"===e&&(e=new rY),"XDM"===e&&(e=new r0),"json-api"===e&&(e=new nt(t)),"react-native"===e&&(e=new ni(t)),"secure-json-api"===e&&(e=new nt(t,"https://localhost:2121")),this.substrate=e,this.originator=t}async connectToSubstrate(){if("object"==typeof this.substrate)return;let e=async(e,t)=>{try{let i,r=e();if(i="number"==typeof t?await Promise.race([r.getVersion({}),new Promise((e,i)=>setTimeout(()=>i(Error("Timed out.")),t))]):await r.getVersion({}),"object"!=typeof i||"string"!=typeof i.version)return{success:!1};return{success:!0,sub:r}}catch{return{success:!1}}},t=[e(()=>new rY),e(()=>new r3(new r5(this.originator))),e(()=>new nt(this.originator,"https://localhost:2121")),e(()=>new nt(this.originator)),e(()=>new ni(this.originator))],i=(await Promise.allSettled(t)).filter(e=>"fulfilled"===e.status&&e.value.success&&void 0!==e.value.sub).map(e=>e.value.sub);if(i.length>0){this.substrate=i[0];return}let r=await e(()=>new r0,200);if(r.success&&void 0!==r.sub)this.substrate=r.sub;else throw Error("No wallet available over any communication substrate. Install a BSV wallet today!")}async createAction(e){return nS(e),await this.connectToSubstrate(),await this.substrate.createAction(e,this.originator)}async signAction(e){return nx(e),await this.connectToSubstrate(),await this.substrate.signAction(e,this.originator)}async abortAction(e){return nA(e),await this.connectToSubstrate(),await this.substrate.abortAction(e,this.originator)}async listActions(e){return n$(e),await this.connectToSubstrate(),await this.substrate.listActions(e,this.originator)}async internalizeAction(e){return n_(e),await this.connectToSubstrate(),await this.substrate.internalizeAction(e,this.originator)}async listOutputs(e){return nq(e),await this.connectToSubstrate(),await this.substrate.listOutputs(e,this.originator)}async relinquishOutput(e){return nB(e),await this.connectToSubstrate(),await this.substrate.relinquishOutput(e,this.originator)}async getPublicKey(e){return await this.connectToSubstrate(),await this.substrate.getPublicKey(e,this.originator)}async revealCounterpartyKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealCounterpartyKeyLinkage(e,this.originator)}async revealSpecificKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealSpecificKeyLinkage(e,this.originator)}async encrypt(e){return await this.connectToSubstrate(),await this.substrate.encrypt(e,this.originator)}async decrypt(e){return await this.connectToSubstrate(),await this.substrate.decrypt(e,this.originator)}async createHmac(e){return await this.connectToSubstrate(),await this.substrate.createHmac(e,this.originator)}async verifyHmac(e){return await this.connectToSubstrate(),await this.substrate.verifyHmac(e,this.originator)}async createSignature(e){return await this.connectToSubstrate(),await this.substrate.createSignature(e,this.originator)}async verifySignature(e){return await this.connectToSubstrate(),await this.substrate.verifySignature(e,this.originator)}async acquireCertificate(e){if("direct"===e.acquisitionProtocol)nV(e);else if("issuance"===e.acquisitionProtocol)nL(e);else throw new r9("acquisitionProtocol",`valid. ${String(e.acquisitionProtocol)} is unrecognized.`);return await this.connectToSubstrate(),await this.substrate.acquireCertificate(e,this.originator)}async listCertificates(e){return nF(e),await this.connectToSubstrate(),await this.substrate.listCertificates(e,this.originator)}async proveCertificate(e){return nH(e),await this.connectToSubstrate(),await this.substrate.proveCertificate(e,this.originator)}async relinquishCertificate(e){return nU(e),await this.connectToSubstrate(),await this.substrate.relinquishCertificate(e,this.originator)}async discoverByIdentityKey(e){return nM(e),await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(e,this.originator)}async discoverByAttributes(e){return nK(e),await this.connectToSubstrate(),await this.substrate.discoverByAttributes(e,this.originator)}async isAuthenticated(e={}){return await this.connectToSubstrate(),await this.substrate.isAuthenticated(e,this.originator)}async waitForAuthentication(e={}){return await this.connectToSubstrate(),await this.substrate.waitForAuthentication(e,this.originator)}async getHeight(e={}){return await this.connectToSubstrate(),await this.substrate.getHeight(e,this.originator)}async getHeaderForHeight(e){return await this.connectToSubstrate(),await this.substrate.getHeaderForHeight(e,this.originator)}async getNetwork(e={}){return await this.connectToSubstrate(),await this.substrate.getNetwork(e,this.originator)}async getVersion(e={}){return await this.connectToSubstrate(),await this.substrate.getVersion(e,this.originator)}}class nj{wallet;constructor(e){this.wallet=e}decodeOutpoint(e){let t=tg(e.read(32)),i=e.readVarIntNum();return`${t}.${i}`}encodeOutpoint(e){let t=new tP,[i,r]=e.split(".");return t.write(tm(i,"hex")),t.writeVarIntNum(Number(r)),t.toArray()}async transmitToWallet(e){let t=new tN(e);try{let e=t.readUInt8(),i=r2[e];if(void 0===i||""===i)throw Error(`Invalid call code: ${e}`);let r=t.readUInt8(),n=t.read(r),s=tI(n);switch(i){case"createAction":{let e={},i=t.readVarIntNum(),r=t.read(i);e.description=tI(r);let n=t.readVarIntNum();n>=0?e.inputBEEF=t.read(n):e.inputBEEF=void 0;let a=t.readVarIntNum();if(a>=0){e.inputs=[];for(let i=0;i<a;i++){let i={};i.outpoint=this.decodeOutpoint(t);let r=t.readVarIntNum();if(r>=0){let e=t.read(r);i.unlockingScript=tg(e)}else i.unlockingScript=void 0,i.unlockingScriptLength=t.readVarIntNum();let n=t.readVarIntNum(),s=t.read(n);i.inputDescription=tI(s);let a=t.readVarIntNum();a>=0?i.sequenceNumber=a:i.sequenceNumber=void 0,e.inputs.push(i)}}else e.inputs=void 0;let o=t.readVarIntNum();if(o>=0){e.outputs=[];for(let i=0;i<o;i++){let i={},r=t.readVarIntNum(),n=t.read(r);i.lockingScript=tg(n),i.satoshis=t.readVarIntNum();let s=t.readVarIntNum(),a=t.read(s);i.outputDescription=tI(a);let o=t.readVarIntNum();if(o>=0){let e=t.read(o);i.basket=tI(e)}else i.basket=void 0;let l=t.readVarIntNum();if(l>=0){let e=t.read(l);i.customInstructions=tI(e)}else i.customInstructions=void 0;let c=t.readVarIntNum();if(c>=0){i.tags=[];for(let e=0;e<c;e++){let e=t.readVarIntNum(),r=t.read(e),n=tI(r);i.tags.push(n)}}else i.tags=void 0;e.outputs.push(i)}}else e.outputs=void 0;let l=t.readVarIntNum();l>=0?e.lockTime=l:e.lockTime=void 0;let c=t.readVarIntNum();c>=0?e.version=c:e.version=void 0;let h=t.readVarIntNum();if(h>=0){e.labels=[];for(let i=0;i<h;i++){let i=t.readVarIntNum(),r=t.read(i),n=tI(r);e.labels.push(n)}}else e.labels=void 0;let d=t.readInt8();if(1===d){e.options={};let i=t.readInt8();-1===i?e.options.signAndProcess=void 0:e.options.signAndProcess=1===i;let r=t.readInt8();-1===r?e.options.acceptDelayedBroadcast=void 0:e.options.acceptDelayedBroadcast=1===r;let n=t.readInt8();-1===n?e.options.trustSelf=void 0:1===n&&(e.options.trustSelf="known");let s=t.readVarIntNum();if(s>=0){e.options.knownTxids=[];for(let i=0;i<s;i++){let i=t.read(32),r=tg(i);e.options.knownTxids.push(r)}}else e.options.knownTxids=void 0;let a=t.readInt8();-1===a?e.options.returnTXIDOnly=void 0:e.options.returnTXIDOnly=1===a;let o=t.readInt8();-1===o?e.options.noSend=void 0:e.options.noSend=1===o;let l=t.readVarIntNum();if(l>=0){e.options.noSendChange=[];for(let i=0;i<l;i++){let i=this.decodeOutpoint(t);e.options.noSendChange.push(i)}}else e.options.noSendChange=void 0;let c=t.readVarIntNum();if(c>=0){e.options.sendWith=[];for(let i=0;i<c;i++){let i=t.read(32),r=tg(i);e.options.sendWith.push(r)}}else e.options.sendWith=void 0;let h=t.readInt8();-1===h?e.options.randomizeOutputs=void 0:e.options.randomizeOutputs=1===h}else e.options=void 0;let u=await this.wallet.createAction(e,s),f=new tP;if(null!=u.txid&&""!==u.txid?(f.writeInt8(1),f.write(tm(u.txid,"hex"))):f.writeInt8(0),null==u.tx?f.writeInt8(0):(f.writeInt8(1),f.writeVarIntNum(u.tx.length),f.write(u.tx)),null==u.noSendChange)f.writeVarIntNum(-1);else for(let e of(f.writeVarIntNum(u.noSendChange.length),u.noSendChange))f.write(this.encodeOutpoint(e));if(null==u.sendWithResults)f.writeVarIntNum(-1);else for(let e of(f.writeVarIntNum(u.sendWithResults.length),u.sendWithResults)){let t;f.write(tm(e.txid,"hex")),"unproven"===e.status?t=1:"sending"===e.status?t=2:"failed"===e.status&&(t=3),f.writeInt8(t)}if(null==u.signableTransaction)f.writeInt8(0);else{f.writeInt8(1),f.writeVarIntNum(u.signableTransaction.tx.length),f.write(u.signableTransaction.tx);let e=tm(u.signableTransaction.reference,"base64");f.writeVarIntNum(e.length),f.write(e)}let p=new tP;return p.writeUInt8(0),p.write(f.toArray()),p.toArray()}case"signAction":{let e={},i=t.readVarIntNum();e.spends={};for(let r=0;r<i;r++){let i=t.readVarIntNum(),r={},n=t.readVarIntNum(),s=t.read(n);r.unlockingScript=tg(s);let a=t.readVarIntNum();a>=0?r.sequenceNumber=a:r.sequenceNumber=void 0,e.spends[i]=r}let r=t.readVarIntNum(),n=t.read(r);e.reference=tS(n);let a=t.readInt8();if(1===a){e.options={};let i=t.readInt8();-1===i?e.options.acceptDelayedBroadcast=void 0:e.options.acceptDelayedBroadcast=1===i;let r=t.readInt8();-1===r?e.options.returnTXIDOnly=void 0:e.options.returnTXIDOnly=1===r;let n=t.readInt8();-1===n?e.options.noSend=void 0:e.options.noSend=1===n;let s=t.readVarIntNum();if(s>=0){e.options.sendWith=[];for(let i=0;i<s;i++){let i=t.read(32),r=tg(i);e.options.sendWith.push(r)}}else e.options.sendWith=void 0}else e.options=void 0;let o=await this.wallet.signAction(e,s),l=new tP;if(null!=o.txid&&""!==o.txid?(l.writeInt8(1),l.write(tm(o.txid,"hex"))):l.writeInt8(0),null==o.tx?l.writeInt8(0):(l.writeInt8(1),l.writeVarIntNum(o.tx.length),l.write(o.tx)),null==o.sendWithResults)l.writeVarIntNum(-1);else for(let e of(l.writeVarIntNum(o.sendWithResults.length),o.sendWithResults)){let t;l.write(tm(e.txid,"hex")),"unproven"===e.status?t=1:"sending"===e.status?t=2:"failed"===e.status&&(t=3),l.writeInt8(t)}let c=new tP;return c.writeUInt8(0),c.write(l.toArray()),c.toArray()}case"abortAction":{let e=t.read(),i=tS(e);await this.wallet.abortAction({reference:i},s);let r=new tP;return r.writeUInt8(0),r.toArray()}case"listActions":{let e={},i=t.readVarIntNum();e.labels=[];for(let r=0;r<i;r++){let i=t.readVarIntNum(),r=t.read(i);e.labels.push(tI(r))}let r=t.readInt8();for(let i of(-1===r?e.labelQueryMode=void 0:1===r?e.labelQueryMode="any":2===r&&(e.labelQueryMode="all"),["includeLabels","includeInputs","includeInputSourceLockingScripts","includeInputUnlockingScripts","includeOutputs","includeOutputLockingScripts"])){let r=t.readInt8();-1===r?e[i]=void 0:e[i]=1===r}let n=t.readVarIntNum();n>=0?e.limit=n:e.limit=void 0;let a=t.readVarIntNum();a>=0?e.offset=a:e.offset=void 0;let o=t.readInt8();o>=0?e.seekPermission=1===o:e.seekPermission=void 0;let l=await this.wallet.listActions(e,s),c=new tP;for(let e of(c.writeVarIntNum(l.totalActions),l.actions)){let t;switch(c.write(tm(e.txid,"hex")),c.writeVarIntNum(e.satoshis),e.status){case"completed":t=1;break;case"unprocessed":t=2;break;case"sending":t=3;break;case"unproven":t=4;break;case"unsigned":t=5;break;case"nosend":t=6;break;case"nonfinal":t=7;break;case"failed":t=8;break;default:t=-1}c.writeInt8(t),c.writeInt8(+!!e.isOutgoing);let i=tm(e.description,"utf8");if(c.writeVarIntNum(i.length),c.write(i),void 0===e.labels)c.writeVarIntNum(-1);else for(let t of(c.writeVarIntNum(e.labels.length),e.labels)){let e=tm(t,"utf8");c.writeVarIntNum(e.length),c.write(e)}if(c.writeVarIntNum(e.version),c.writeVarIntNum(e.lockTime),void 0===e.inputs)c.writeVarIntNum(-1);else for(let t of(c.writeVarIntNum(e.inputs.length),e.inputs)){if(c.write(this.encodeOutpoint(t.sourceOutpoint)),c.writeVarIntNum(t.sourceSatoshis),void 0===t.sourceLockingScript)c.writeVarIntNum(-1);else{let e=tm(t.sourceLockingScript,"hex");c.writeVarIntNum(e.length),c.write(e)}if(void 0===t.unlockingScript)c.writeVarIntNum(-1);else{let e=tm(t.unlockingScript,"hex");c.writeVarIntNum(e.length),c.write(e)}let e=tm(t.inputDescription,"utf8");c.writeVarIntNum(e.length),c.write(e),c.writeVarIntNum(t.sequenceNumber)}if(void 0===e.outputs)c.writeVarIntNum(-1);else for(let t of(c.writeVarIntNum(e.outputs.length),e.outputs)){if(c.writeVarIntNum(t.outputIndex),c.writeVarIntNum(t.satoshis),void 0===t.lockingScript)c.writeVarIntNum(-1);else{let e=tm(t.lockingScript,"hex");c.writeVarIntNum(e.length),c.write(e)}c.writeInt8(+!!t.spendable);let e=tm(t.outputDescription,"utf8");if(c.writeVarIntNum(e.length),c.write(e),void 0===t.basket)c.writeVarIntNum(-1);else{let e=tm(t.basket,"utf8");c.writeVarIntNum(e.length),c.write(e)}if(void 0===t.tags)c.writeVarIntNum(-1);else for(let e of(c.writeVarIntNum(t.tags.length),t.tags)){let t=tm(e,"utf8");c.writeVarIntNum(t.length),c.write(t)}if(void 0===t.customInstructions)c.writeVarIntNum(-1);else{let e=tm(t.customInstructions,"utf8");c.writeVarIntNum(e.length),c.write(e)}}}let h=new tP;return h.writeUInt8(0),h.write(c.toArray()),h.toArray()}case"internalizeAction":{let e={},i=t.readVarIntNum();e.tx=t.read(i);let r=t.readVarIntNum();e.outputs=[];for(let i=0;i<r;i++){let i={};i.outputIndex=t.readVarIntNum();let r=t.readUInt8();if(1===r){i.protocol="wallet payment",i.paymentRemittance={};let e=t.read(33);i.paymentRemittance.senderIdentityKey=tg(e);let r=t.readVarIntNum(),n=t.read(r);i.paymentRemittance.derivationPrefix=tS(n);let s=t.readVarIntNum(),a=t.read(s);i.paymentRemittance.derivationSuffix=tS(a)}else if(2===r){i.protocol="basket insertion",i.insertionRemittance={};let e=t.readVarIntNum(),r=t.read(e);i.insertionRemittance.basket=tI(r);let n=t.readVarIntNum();if(n>=0){let e=t.read(n);i.insertionRemittance.customInstructions=tI(e)}let s=t.readVarIntNum();if(s>0){i.insertionRemittance.tags=[];for(let e=0;e<s;e++){let e=t.readVarIntNum(),r=t.read(e);i.insertionRemittance.tags.push(tI(r))}}else i.insertionRemittance.tags=[]}e.outputs.push(i)}let n=t.readVarIntNum();if(n>=0){e.labels=[];for(let i=0;i<n;i++){let i=t.readVarIntNum();e.labels.push(tI(t.read(i)))}}let a=t.readVarIntNum();e.description=tI(t.read(a));let o=t.readInt8();o>=0?e.seekPermission=1===o:e.seekPermission=void 0,await this.wallet.internalizeAction(e,s);let l=new tP;return l.writeUInt8(0),l.toArray()}case"listOutputs":{let e={},i=t.readVarIntNum(),r=t.read(i);e.basket=tI(r);let n=t.readVarIntNum();if(n>0){e.tags=[];for(let i=0;i<n;i++){let i=t.readVarIntNum(),r=t.read(i);e.tags.push(tI(r))}}else e.tags=void 0;let a=t.readInt8();1===a?e.tagQueryMode="all":2===a?e.tagQueryMode="any":e.tagQueryMode=void 0;let o=t.readInt8();1===o?e.include="locking scripts":2===o?e.include="entire transactions":e.include=void 0;let l=t.readInt8();-1===l?e.includeCustomInstructions=void 0:e.includeCustomInstructions=1===l;let c=t.readInt8();-1===c?e.includeTags=void 0:e.includeTags=1===c;let h=t.readInt8();-1===h?e.includeLabels=void 0:e.includeLabels=1===h;let d=t.readVarIntNum();d>=0?e.limit=d:e.limit=void 0;let u=t.readVarIntNum();u>=0?e.offset=u:e.offset=void 0;let f=t.readInt8();f>=0?e.seekPermission=1===f:e.seekPermission=void 0;let p=await this.wallet.listOutputs(e,s),g=new tP;for(let e of(g.writeVarIntNum(p.totalOutputs),null==p.BEEF?g.writeVarIntNum(-1):(g.writeVarIntNum(p.BEEF.length),g.write(p.BEEF)),p.outputs)){if(g.write(this.encodeOutpoint(e.outpoint)),g.writeVarIntNum(e.satoshis),void 0===e.lockingScript)g.writeVarIntNum(-1);else{let t=tm(e.lockingScript,"hex");g.writeVarIntNum(t.length),g.write(t)}if(void 0===e.customInstructions)g.writeVarIntNum(-1);else{let t=tm(e.customInstructions,"utf8");g.writeVarIntNum(t.length),g.write(t)}if(void 0===e.tags)g.writeVarIntNum(-1);else for(let t of(g.writeVarIntNum(e.tags.length),e.tags)){let e=tm(t,"utf8");g.writeVarIntNum(e.length),g.write(e)}if(void 0===e.labels)g.writeVarIntNum(-1);else for(let t of(g.writeVarIntNum(e.labels.length),e.labels)){let e=tm(t,"utf8");g.writeVarIntNum(e.length),g.write(e)}}let y=new tP;return y.writeUInt8(0),y.write(g.toArray()),y.toArray()}case"relinquishOutput":{let e={},i=t.readVarIntNum(),r=t.read(i);e.basket=tI(r),e.output=this.decodeOutpoint(t),await this.wallet.relinquishOutput(e,s);let n=new tP;return n.writeUInt8(0),n.toArray()}case"getPublicKey":{let e={},i=t.readUInt8();if(e.identityKey=1===i,!0===e.identityKey){let i=t.readInt8();-1===i?e.privileged=void 0:e.privileged=1===i;let r=t.readInt8();if(-1===r)e.privilegedReason=void 0;else{let i=t.read(r);e.privilegedReason=tI(i)}}else{e.protocolID=this.decodeProtocolID(t),e.keyID=this.decodeString(t),e.counterparty=this.decodeCounterparty(t);let i=t.readInt8();-1===i?e.privileged=void 0:e.privileged=1===i;let r=t.readInt8();if(-1===r)e.privilegedReason=void 0;else{let i=t.read(r);e.privilegedReason=tI(i)}let n=t.readInt8();-1===n?e.forSelf=void 0:e.forSelf=1===n}let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.getPublicKey(e,s),a=new tP;a.writeUInt8(0);let o=tm(n.publicKey,"hex");return a.write(o),a.toArray()}case"encrypt":{let e=this.decodeKeyRelatedParams(t),i=t.readVarIntNum();e.plaintext=t.read(i);let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.encrypt(e,s),a=new tP;return a.writeUInt8(0),a.write(n.ciphertext),a.toArray()}case"decrypt":{let e=this.decodeKeyRelatedParams(t),i=t.readVarIntNum();e.ciphertext=t.read(i);let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.decrypt(e,s),a=new tP;return a.writeUInt8(0),a.write(n.plaintext),a.toArray()}case"createHmac":{let e=this.decodeKeyRelatedParams(t),i=t.readVarIntNum();e.data=t.read(i);let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.createHmac(e,s),a=new tP;return a.writeUInt8(0),a.write(n.hmac),a.toArray()}case"verifyHmac":{let e=this.decodeKeyRelatedParams(t);e.hmac=t.read(32);let i=t.readVarIntNum();e.data=t.read(i);let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0,await this.wallet.verifyHmac(e,s);let n=new tP;return n.writeUInt8(0),n.toArray()}case"createSignature":{let e=this.decodeKeyRelatedParams(t),i=t.readUInt8();if(1===i){let i=t.readVarIntNum();e.data=t.read(i)}else 2===i&&(e.hashToDirectlySign=t.read(32));let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.createSignature(e,s),a=new tP;return a.writeUInt8(0),a.write(n.signature),a.toArray()}case"verifySignature":{let e=this.decodeKeyRelatedParams(t),i=t.readInt8();-1===i?e.forSelf=void 0:e.forSelf=1===i;let r=t.readVarIntNum();e.signature=t.read(r);let n=t.readUInt8();if(1===n){let i=t.readVarIntNum();e.data=t.read(i)}else 2===n&&(e.hashToDirectlyVerify=t.read(32));let a=t.readInt8();a>=0?e.seekPermission=1===a:e.seekPermission=void 0,await this.wallet.verifySignature(e,s);let o=new tP;return o.writeUInt8(0),o.toArray()}case"isAuthenticated":{let e=await this.wallet.isAuthenticated({},s),t=new tP;return t.writeUInt8(0),t.writeUInt8(+!!e.authenticated),t.toArray()}case"waitForAuthentication":{await this.wallet.waitForAuthentication({},s);let e=new tP;return e.writeUInt8(0),e.toArray()}case"getHeight":{let e=await this.wallet.getHeight({},s),t=new tP;return t.writeUInt8(0),t.writeVarIntNum(e.height),t.toArray()}case"getHeaderForHeight":{let e={};e.height=t.readVarIntNum();let i=await this.wallet.getHeaderForHeight(e,s),r=new tP;r.writeUInt8(0);let n=tm(i.header,"hex");return r.write(n),r.toArray()}case"getNetwork":{let e=await this.wallet.getNetwork({},s),t=new tP;return t.writeUInt8(0),t.writeUInt8(+("mainnet"!==e.network)),t.toArray()}case"getVersion":{let e=await this.wallet.getVersion({},s),t=new tP;t.writeUInt8(0);let i=tm(e.version,"utf8");return t.write(i),t.toArray()}case"revealCounterpartyKeyLinkage":{let e={},i=t.readInt8();-1===i?e.privileged=void 0:e.privileged=1===i;let r=t.readInt8();if(-1===r)e.privilegedReason=void 0;else{let i=t.read(r);e.privilegedReason=tI(i)}let n=t.read(33);e.counterparty=tg(n);let a=t.read(33);e.verifier=tg(a);let o=await this.wallet.revealCounterpartyKeyLinkage(e,s),l=new tP;l.write(tm(o.prover,"hex")),l.write(tm(o.verifier,"hex")),l.write(tm(o.counterparty,"hex"));let c=tm(o.revelationTime,"utf8");l.writeVarIntNum(c.length),l.write(c),l.writeVarIntNum(o.encryptedLinkage.length),l.write(o.encryptedLinkage),l.writeVarIntNum(o.encryptedLinkageProof.length),l.write(o.encryptedLinkageProof);let h=new tP;return h.writeUInt8(0),h.write(l.toArray()),h.toArray()}case"revealSpecificKeyLinkage":{let e=this.decodeKeyRelatedParams(t),i=t.read(33);e.verifier=tg(i);let r=await this.wallet.revealSpecificKeyLinkage(e,s),n=new tP;n.write(tm(r.prover,"hex")),n.write(tm(r.verifier,"hex")),n.write(tm(r.counterparty,"hex")),n.writeUInt8(r.protocolID[0]);let a=tm(r.protocolID[1],"utf8");n.writeVarIntNum(a.length),n.write(a);let o=tm(r.keyID,"utf8");n.writeVarIntNum(o.length),n.write(o),n.writeVarIntNum(r.encryptedLinkage.length),n.write(r.encryptedLinkage),n.writeVarIntNum(r.encryptedLinkageProof.length),n.write(r.encryptedLinkageProof),n.writeUInt8(r.proofType);let l=new tP;return l.writeUInt8(0),l.write(n.toArray()),l.toArray()}case"acquireCertificate":{let e={},i=t.read(32);e.type=tS(i);let r=t.read(33);e.certifier=tg(r);let n=t.readVarIntNum();e.fields={};for(let i=0;i<n;i++){let i=t.readVarIntNum(),r=t.read(i),n=tI(r),s=t.readVarIntNum(),a=t.read(s),o=tI(a);e.fields[n]=o}let a=t.readInt8();-1===a?e.privileged=void 0:e.privileged=1===a;let o=t.readInt8();if(-1===o)e.privilegedReason=void 0;else{let i=t.read(o);e.privilegedReason=tI(i)}let l=t.readUInt8();if(e.acquisitionProtocol=1===l?"direct":"issuance","direct"===e.acquisitionProtocol){let i=t.read(32);e.serialNumber=tS(i),e.revocationOutpoint=this.decodeOutpoint(t);let r=t.readVarIntNum(),n=t.read(r);e.signature=tg(n);let s=t.readUInt8();if(11===s)e.keyringRevealer="certifier";else{let i=[s].concat(t.read(32));e.keyringRevealer=tg(i)}let a=t.readVarIntNum();e.keyringForSubject={};for(let i=0;i<a;i++){let i=t.readVarIntNum(),r=t.read(i),n=tI(r),s=t.readVarIntNum(),a=t.read(s),o=tS(a);e.keyringForSubject[n]=o}}else{let i=t.readVarIntNum(),r=t.read(i);e.certifierUrl=tI(r)}let c=await this.wallet.acquireCertificate(e,s),h=new r1(c.type,c.serialNumber,c.subject,c.certifier,c.revocationOutpoint,c.fields,c.signature).toBinary(),d=new tP;return d.writeUInt8(0),d.write(h),d.toArray()}case"listCertificates":{let e={},i=t.readVarIntNum();e.certifiers=[];for(let r=0;r<i;r++){let i=t.read(33);e.certifiers.push(tg(i))}let r=t.readVarIntNum();e.types=[];for(let i=0;i<r;i++){let i=t.read(32);e.types.push(tS(i))}let n=t.readVarIntNum();n>=0?e.limit=n:e.limit=void 0;let a=t.readVarIntNum();a>=0?e.offset=a:e.offset=void 0;let o=t.readInt8();-1===o?e.privileged=void 0:e.privileged=1===o;let l=t.readInt8();if(-1===l)e.privilegedReason=void 0;else{let i=t.read(l);e.privilegedReason=tI(i)}let c=await this.wallet.listCertificates(e,s),h=new tP;for(let e of(h.writeVarIntNum(c.totalCertificates),c.certificates)){let t=new r1(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature).toBinary();if(h.writeVarIntNum(t.length),h.write(t),e.keyring&&Object.keys(e.keyring).length>0){h.writeInt8(1);let t=Object.entries(e.keyring);for(let[e,i]of(h.writeVarIntNum(t.length),t)){let t=tm(e,"utf8");h.writeVarIntNum(t.length),h.write(t);let r=tm(i,"base64");h.writeVarIntNum(r.length),h.write(r)}}else h.writeInt8(0);let i=tm(e.verifier,"hex");h.writeVarIntNum(i.length),h.write(i)}let d=new tP;return d.writeUInt8(0),d.write(h.toArray()),d.toArray()}case"proveCertificate":{let e={},i={},r=t.read(32);i.type=tS(r);let n=t.read(33);i.subject=tg(n);let a=t.read(32);i.serialNumber=tS(a);let o=t.read(33);i.certifier=tg(o),i.revocationOutpoint=this.decodeOutpoint(t);let l=t.readVarIntNum(),c=t.read(l);i.signature=tg(c);let h=t.readVarIntNum();i.fields={};for(let e=0;e<h;e++){let e=t.readVarIntNum(),r=t.read(e),n=tI(r),s=t.readVarIntNum(),a=t.read(s),o=tI(a);i.fields[n]=o}e.certificate=i;let d=t.readVarIntNum();e.fieldsToReveal=[];for(let i=0;i<d;i++){let i=t.readVarIntNum(),r=t.read(i),n=tI(r);e.fieldsToReveal.push(n)}let u=t.read(33);e.verifier=tg(u);let f=t.readInt8();-1===f?e.privileged=void 0:e.privileged=1===f;let p=t.readInt8();if(-1===p)e.privilegedReason=void 0;else{let i=t.read(p);e.privilegedReason=tI(i)}let g=await this.wallet.proveCertificate(e,s),y=new tP,m=Object.entries(g.keyringForVerifier);for(let[e,t]of(y.writeVarIntNum(m.length),m)){let i=tm(e,"utf8");y.writeVarIntNum(i.length),y.write(i);let r=tm(t,"base64");y.writeVarIntNum(r.length),y.write(r)}let b=new tP;return b.writeUInt8(0),b.write(y.toArray()),b.toArray()}case"relinquishCertificate":{let e={},i=t.read(32);e.type=tS(i);let r=t.read(32);e.serialNumber=tS(r);let n=t.read(33);e.certifier=tg(n),await this.wallet.relinquishCertificate(e,s);let a=new tP;return a.writeUInt8(0),a.toArray()}case"discoverByIdentityKey":{let e={},i=t.read(33);e.identityKey=tg(i);let r=t.readVarIntNum();r>=0?e.limit=r:e.limit=void 0;let n=t.readVarIntNum();n>=0?e.offset=n:e.offset=void 0;let a=t.readInt8();a>=0?e.seekPermission=1===a:e.seekPermission=void 0;let o=await this.wallet.discoverByIdentityKey(e,s),l=this.serializeDiscoveryResult(o),c=new tP;return c.writeUInt8(0),c.write(l),c.toArray()}case"discoverByAttributes":{let e={},i=t.readVarIntNum();e.attributes={};for(let r=0;r<i;r++){let i=t.readVarIntNum(),r=t.read(i),n=tI(r),s=t.readVarIntNum(),a=t.read(s),o=tI(a);e.attributes[n]=o}let r=t.readVarIntNum();r>=0?e.limit=r:e.limit=void 0;let n=t.readVarIntNum();n>=0?e.offset=n:e.offset=void 0;let a=t.readInt8();a>=0?e.seekPermission=1===a:e.seekPermission=void 0;let o=await this.wallet.discoverByAttributes(e,s),l=this.serializeDiscoveryResult(o),c=new tP;return c.writeUInt8(0),c.write(l),c.toArray()}default:throw Error(`Method ${i} not implemented`)}}catch(r){let e=new tP;e.writeUInt8("number"==typeof r.code?r.code:1);let t=tm("string"==typeof r.message?r.message:"Unknown error","utf8");e.writeVarIntNum(t.length),e.write(t);let i=tm("string"==typeof r.stack?r.stack:"","utf8");return e.writeVarIntNum(i.length),e.write(i),e.toArray()}}decodeProtocolID(e){let t=e.readUInt8(),i=e.readVarIntNum();return[t,tI(e.read(i))]}decodeString(e){let t=e.readVarIntNum();return tI(e.read(t))}decodeCounterparty(e){let t=e.readUInt8();return 11===t?"self":12===t?"anyone":0!==t?tg([t,...e.read(32)]):void 0}serializeDiscoveryResult(e){let t=new tP;for(let i of(t.writeVarIntNum(e.totalCertificates),e.certificates)){let e=new r1(i.type,i.serialNumber,i.subject,i.certifier,i.revocationOutpoint,i.fields,i.signature).toBinary();t.writeVarIntNum(e.length),t.write(e);let r=tm(i.certifierInfo.name,"utf8");t.writeVarIntNum(r.length),t.write(r);let n=tm(i.certifierInfo.iconUrl,"utf8");t.writeVarIntNum(n.length),t.write(n);let s=tm(i.certifierInfo.description,"utf8");t.writeVarIntNum(s.length),t.write(s),t.writeUInt8(i.certifierInfo.trust);let a=Object.entries(i.publiclyRevealedKeyring);for(let[e,i]of(t.writeVarIntNum(a.length),a)){let r=tm(e,"utf8");t.writeVarIntNum(r.length),t.write(r);let n=tm(i,"base64");t.writeVarIntNum(n.length),t.write(n)}let o=Object.entries(i.decryptedFields);for(let[e,i]of(t.writeVarIntNum(o.length),o)){let r=tm(e,"utf8");t.writeVarIntNum(r.length),t.write(r);let n=tm(i,"utf8");t.writeVarIntNum(n.length),t.write(n)}}return t.toArray()}decodeKeyRelatedParams(e){let t={};t.protocolID=this.decodeProtocolID(e);let i=e.readVarIntNum();t.keyID=tI(e.read(i)),t.counterparty=this.decodeCounterparty(e);let r=e.readInt8();-1===r?t.privileged=void 0:t.privileged=1===r;let n=e.readInt8();return -1===n?t.privilegedReason=void 0:t.privilegedReason=tI(e.read(n)),t}}class nG extends r1{masterKeyring;constructor(e,t,i,r,n,s,a,o){for(const l of(super(e,t,i,r,n,s,o),Object.keys(s)))if(void 0===a[l]||""===a[l])throw Error(`Master keyring must contain a value for every field. Missing or empty key for field: "${l}".`);this.masterKeyring=a}static async createCertificateFields(e,t,i,r,n){let s={},a={};for(let[o,l]of Object.entries(i)){let i=i_.fromRandom(),c=i.encrypt(tm(l,"utf8"));s[o]=tS(c);let{ciphertext:h}=await e.encrypt({plaintext:i.toArray(),...r1.getCertificateFieldEncryptionDetails(o),counterparty:t,privileged:r,privilegedReason:n});a[o]=tS(h)}return{certificateFields:s,masterKeyring:a}}static async createKeyringForVerifier(e,t,i,r,n,s,a,o,l){if(!Array.isArray(n))throw TypeError("fieldsToReveal must be an array of strings");let c={};for(let h of n){if(void 0===r[h]||null===r[h]||""===r[h])throw Error(`Fields to reveal must be a subset of the certificate fields. Missing the "${h}" field.`);let n=(await this.decryptField(e,s,h,r[h],t,o,l)).fieldRevelationKey,{ciphertext:d}=await e.encrypt({plaintext:n,...r1.getCertificateFieldEncryptionDetails(h,a),counterparty:i,privileged:o,privilegedReason:l});c[h]=tS(d)}return c}static async issueCertificateForSubject(e,t,i,r,n=async e=>"00".repeat(32),s){let a=s??tS(ia(32)),{certificateFields:o,masterKeyring:l}=await this.createCertificateFields(e,t,i),c=await n(a),h=new nG(r,a,"self"===t?(await e.getPublicKey({identityKey:!0})).publicKey:t,(await e.getPublicKey({identityKey:!0})).publicKey,c,o,l);return await h.sign(e),h}static async decryptFields(e,t,i,r,n,s){if(null==t||0===Object.keys(t).length)throw Error("A MasterCertificate must have a valid masterKeyring!");try{let a={};for(let o of Object.keys(i))a[o]=(await this.decryptField(e,t,o,i[o],r,n,s)).decryptedFieldValue;return a}catch{throw Error("Failed to decrypt all master certificate fields.")}}static async decryptField(e,t,i,r,n,s,a){if(null==t||0===Object.keys(t).length)throw Error("A MasterCertificate must have a valid masterKeyring!");try{let{plaintext:o}=await e.decrypt({ciphertext:tm(t[i],"base64"),...r1.getCertificateFieldEncryptionDetails(i),counterparty:n,privileged:s,privilegedReason:a}),l=new i_(o).decrypt(tm(r,"base64"));return{fieldRevelationKey:o,decryptedFieldValue:tI(l)}}catch{throw Error("Failed to decrypt certificate field!")}}}class nX extends r1{keyring;decryptedFields;constructor(e,t,i,r,n,s,a,o,l){super(e,t,i,r,n,s,o),this.keyring=a,this.decryptedFields=l}static fromCertificate(e,t){return new nX(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,t,e.signature)}async decryptFields(e,t,i,r){if(null==this.keyring||0===Object.keys(this.keyring).length)throw Error("A keyring is required to decrypt certificate fields for the verifier.");try{let n={};for(let s in this.keyring){let{plaintext:a}=await e.decrypt({ciphertext:tm(this.keyring[s],"base64"),...r1.getCertificateFieldEncryptionDetails(s,this.serialNumber),counterparty:this.subject,privileged:t,privilegedReason:i},r),o=new i_(a).decrypt(tm(this.fields[s],"base64"));n[s]=tI(o)}return n}catch(e){throw Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(e instanceof Error?e.message:e)}`)}}}class nY extends rX{keyDeriver;constructor(e){if(super(e),e instanceof rW)this.keyDeriver=e;else if("string"==typeof e||e instanceof ih)this.keyDeriver=new rj(e);else throw TypeError("Invalid key deriver provided")}async isAuthenticated(){throw Error("not implemented")}async waitForAuthentication(){throw Error("not implemented")}async getNetwork(){throw Error("not implemented")}async getVersion(){throw Error("not implemented")}async getPublicKey(e){if(!0===e.privileged)throw Error("no privilege support");if(!0===e.identityKey){if(null===this.keyDeriver||void 0===this.keyDeriver)throw Error("keyDeriver is not initialized");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==e.protocolID||"string"!=typeof e.keyID||""===e.keyID.trim())throw Error("protocolID and keyID are required if identityKey is false or undefined.");if(null===this.keyDeriver||void 0===this.keyDeriver)throw Error("keyDeriver is not initialized");return{publicKey:this.keyDeriver.derivePublicKey(e.protocolID,e.keyID,"string"==typeof e.counterparty&&""!==e.counterparty.trim()?e.counterparty:"self",!!e.forSelf).toString()}}async createAction(){throw Error("not implemented")}async signAction(){throw Error("not implemented")}async abortAction(){throw Error("not implemented")}async listActions(){throw Error("not implemented")}async internalizeAction(){throw Error("not implemented")}async listOutputs(){throw Error("not implemented")}async relinquishOutput(){throw Error("not implemented")}async acquireCertificate(){throw Error("not implemented")}async listCertificates(){throw Error("not implemented")}async proveCertificate(){throw Error("not implemented")}async relinquishCertificate(){throw Error("not implemented")}async discoverByIdentityKey(){throw Error("not implemented")}async discoverByAttributes(){throw Error("not implemented")}async getHeight(){throw Error("not implemented")}async getHeaderForHeight(){throw Error("not implemented")}}class nJ{sessionNonceToSession;identityKeyToNonces;constructor(){this.sessionNonceToSession=new Map,this.identityKeyToNonces=new Map}addSession(e){if("string"!=typeof e.sessionNonce)throw TypeError("Invalid session: sessionNonce is required to add a session.");if(this.sessionNonceToSession.set(e.sessionNonce,e),"string"==typeof e.peerIdentityKey){let t=this.identityKeyToNonces.get(e.peerIdentityKey);null==t&&(t=new Set,this.identityKeyToNonces.set(e.peerIdentityKey,t)),t.add(e.sessionNonce)}}updateSession(e){this.removeSession(e),this.addSession(e)}getSession(e){let t,i=this.sessionNonceToSession.get(e);if(null!=i)return i;let r=this.identityKeyToNonces.get(e);if(null!=r&&0!==r.size){for(let e of r){let i=this.sessionNonceToSession.get(e);null!=i&&(null==t?t=i:(i.lastUpdate??0)>(t.lastUpdate??0)&&(t=i))}return t}}removeSession(e){if("string"==typeof e.sessionNonce&&this.sessionNonceToSession.delete(e.sessionNonce),"string"==typeof e.peerIdentityKey){let t=this.identityKeyToNonces.get(e.peerIdentityKey);null!=t&&(t.delete(e.sessionNonce??""),0===t.size&&this.identityKeyToNonces.delete(e.peerIdentityKey))}}hasSession(e){if(this.sessionNonceToSession.has(e))return!0;let t=this.identityKeyToNonces.get(e);return null!=t&&t.size>0}}async function nZ(e,t,i="self",r){let n=tm(e,"base64"),s=n.slice(0,16),a=n.slice(16),{valid:o}=await t.verifyHmac({data:s,hmac:a,protocolID:[2,"server hmac"],keyID:tI(s),counterparty:i},r);return o}async function nQ(e,t="self",i){let r=ia(16),{hmac:n}=await e.createHmac({protocolID:[2,"server hmac"],keyID:tI(r),data:r,counterparty:t},i);return tS([...r,...n])}let n0=async(e,t,i,r)=>{let n=await e.listCertificates({certifiers:t.certifiers,types:Object.keys(t.types)},r);return await Promise.all(n.certificates.map(async n=>{let{keyringForVerifier:s}=await e.proveCertificate({certificate:n,fieldsToReveal:t.types[n.type],verifier:i},r);return new nX(n.type,n.serialNumber,n.subject,n.certifier,n.revocationOutpoint,n.fields,s,n.signature)}))},n1=async(e,t,i,r)=>{if(null==t.certificates||0===t.certificates.length)throw Error("No certificates were provided in the AuthMessage.");await Promise.all(t.certificates.map(async n=>{if(n.subject!==t.identityKey)throw Error(`The subject of one of your certificates ("${n.subject}") is not the same as the request sender ("${t.identityKey}").`);let s=new nX(n.type,n.serialNumber,n.subject,n.certifier,n.revocationOutpoint,n.fields,n.keyring,n.signature);if(!await s.verify())throw Error(`The signature for the certificate with serial number ${s.serialNumber} is invalid!`);if(null!=i){let{certifiers:e,types:t}=i;if(!e.includes(s.certifier))throw Error(`Certificate with serial number ${s.serialNumber} has an unrequested certifier: ${s.certifier}`);if(null==t[s.type])throw Error(`Certificate with type ${s.type} was not requested`)}await s.decryptFields(e,void 0,void 0,r)}))},n2="u"<typeof globalThis?void 0:globalThis.Buffer;class n8{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;certificateValidationPromises=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;originator;identityPublicKey;ready;constructor(e,t,i,r,n,s){this.wallet=e,this.originator=s,this.transport=t,this.certificatesToRequest=i??{certifiers:[],types:{}},this.ready=this.transport.onData(this.handleIncomingMessage.bind(this)),this.sessionManager=r??new nJ,!1===n?this.autoPersistLastSession=!1:this.autoPersistLastSession=!0}async toPeer(e,t){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);let i=await this.getAuthenticatedSession(t);if(null==i.peerIdentityKey)throw Error("Peer identity is not established");if(!0===i.certificatesRequired&&!0!==i.certificatesValidated)throw Error("Cannot send general message before certificate validation is complete");let r=tS(ia(32)),{signature:n}=await this.wallet.createSignature({data:e,protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),s={version:"0.1",messageType:"general",identityKey:await this.getIdentityPublicKey(),nonce:r,yourNonce:i.peerNonce,payload:e,signature:n};i.lastUpdate=Date.now(),await this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}async requestCertificates(e,t){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);let i=await this.getAuthenticatedSession(t),r=tS(ia(32)),{signature:n}=await this.wallet.createSignature({data:n8.utf8ToBytes(JSON.stringify(e)),protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),s={version:"0.1",messageType:"certificateRequest",identityKey:await this.getIdentityPublicKey(),nonce:r,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,requestedCertificates:e,signature:n};i.lastUpdate=Date.now(),await this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}async getAuthenticatedSession(e){let t;if(void 0===this.transport)throw Error("Peer transport is not connected!");if("string"==typeof e&&(t=await this.sessionManager.getSession(e)),t?.isAuthenticated!==!0){let i=await this.initiateHandshake(e);if(t=await this.sessionManager.getSession(i),t?.isAuthenticated!==!0)throw Error("Unable to establish mutual authentication with peer!")}return t}listenForGeneralMessages(e){let t=this.callbackIdCounter++;return this.onGeneralMessageReceivedCallbacks.set(t,e),t}stopListeningForGeneralMessages(e){this.onGeneralMessageReceivedCallbacks.delete(e)}listenForCertificatesReceived(e){let t=this.callbackIdCounter++;return this.onCertificatesReceivedCallbacks.set(t,e),t}stopListeningForCertificatesReceived(e){this.onCertificatesReceivedCallbacks.delete(e)}listenForCertificatesRequested(e){let t=this.callbackIdCounter++;return this.onCertificateRequestReceivedCallbacks.set(t,e),t}stopListeningForCertificatesRequested(e){this.onCertificateRequestReceivedCallbacks.delete(e)}async initiateHandshake(e){let t=await nQ(this.wallet,void 0,this.originator),i=Date.now(),r=this.certificatesToRequest.certifiers.length>0;await this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:t,peerIdentityKey:e,lastUpdate:i,certificatesRequired:r,certificatesValidated:!r});let n={version:"0.1",messageType:"initialRequest",identityKey:await this.getIdentityPublicKey(),initialNonce:t,requestedCertificates:this.certificatesToRequest};return await this.transport.send(n),await this.waitForInitialResponse(t)}async waitForInitialResponse(e){return await new Promise(t=>{let i=this.listenForInitialResponse(e,e=>{this.stopListeningForInitialResponses(i),t(e)})})}listenForInitialResponse(e,t){let i=this.callbackIdCounter++;return this.onInitialResponseReceivedCallbacks.set(i,{callback:t,sessionNonce:e}),i}stopListeningForInitialResponses(e){this.onInitialResponseReceivedCallbacks.delete(e)}propagateTransportError(e,t){if(t instanceof Error){if(null!=e){let i=t.details;null!=i&&"object"==typeof i?i.peerIdentityKey??=e:t.details={peerIdentityKey:e}}throw t}throw Error(`Failed to send message to peer ${e??"unknown"}: ${String(t)}`)}async handleIncomingMessage(e){if("string"!=typeof e.version||"0.1"!==e.version)throw Error(`Invalid or unsupported message auth version! Received: ${e.version}, expected: 0.1`);switch(e.messageType){case"initialRequest":await this.processInitialRequest(e);break;case"initialResponse":await this.processInitialResponse(e);break;case"certificateRequest":await this.processCertificateRequest(e);break;case"certificateResponse":await this.processCertificateResponse(e);break;case"general":await this.processGeneralMessage(e);break;default:throw Error(`Unknown message type of ${String(e.messageType)} from ${String(e.identityKey)}`)}}async processInitialRequest(e){let t;if("string"!=typeof e.identityKey||"string"!=typeof e.initialNonce||""===e.initialNonce)throw Error("Missing required fields in initialRequest message.");let i=await nQ(this.wallet,void 0,this.originator),r=Date.now(),n=Array.isArray(this.certificatesToRequest?.certifiers)&&this.certificatesToRequest.certifiers.length>0;await this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:i,peerNonce:e.initialNonce,peerIdentityKey:e.identityKey,lastUpdate:r,certificatesRequired:n,certificatesValidated:!n}),Array.isArray(e.requestedCertificates?.certifiers)&&e.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)}):t=await n0(this.wallet,e.requestedCertificates,e.identityKey,this.originator));let{signature:s}=await this.wallet.createSignature({data:[...n8.base64ToBytes(e.initialNonce),...n8.base64ToBytes(i)],protocolID:[2,"auth message signature"],keyID:`${e.initialNonce} ${i}`,counterparty:e.identityKey},this.originator),a={version:"0.1",messageType:"initialResponse",identityKey:await this.getIdentityPublicKey(),initialNonce:i,yourNonce:e.initialNonce,certificates:t,requestedCertificates:this.certificatesToRequest,signature:s};this.lastInteractedWithPeer??=e.identityKey,await this.transport.send(a)}async processInitialResponse(e){if(!await nZ(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Initial response nonce verification failed from peer: ${e.identityKey}`);let t=await this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Peer session not found for peer: ${e.identityKey}`);let i=n8.base64ToBytes((t.sessionNonce??"")+(e.initialNonce??"")),{valid:r}=await this.wallet.verifySignature({data:i,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${t.sessionNonce??""} ${e.initialNonce??""}`,counterparty:e.identityKey},this.originator);if(!r)throw Error(`Unable to verify initial response signature for peer: ${e.identityKey}`);if(t.peerNonce=e.initialNonce,t.peerIdentityKey=e.identityKey,t.isAuthenticated=!0,t.certificatesRequired=Array.isArray(this.certificatesToRequest?.certifiers)&&this.certificatesToRequest.certifiers.length>0,t.certificatesValidated=!t.certificatesRequired,t.lastUpdate=Date.now(),await this.sessionManager.updateSession(t),t.certificatesRequired&&Array.isArray(e.certificates)&&e.certificates.length>0&&(await n1(this.wallet,e,this.certificatesToRequest,this.originator),t.certificatesValidated=!0,t.lastUpdate=Date.now(),await this.sessionManager.updateSession(t),null!=t.sessionNonce&&this.resolveCertificateValidation(t.sessionNonce),this.onCertificatesReceivedCallbacks.forEach(t=>t(e.identityKey,e.certificates))),this.lastInteractedWithPeer=e.identityKey,this.onInitialResponseReceivedCallbacks.forEach(e=>{e.sessionNonce===t.sessionNonce&&e.callback(t.sessionNonce)}),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)});else{let t=await n0(this.wallet,e.requestedCertificates,e.identityKey,this.originator);t.length>0&&await this.sendCertificateResponse(e.identityKey,t)}}async processCertificateRequest(e){if(!await nZ(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for certificate request message from: ${e.identityKey}`);let t=await this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let{valid:i}=await this.wallet.verifySignature({data:n8.utf8ToBytes(JSON.stringify(e.requestedCertificates)),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!i)throw Error(`Invalid signature in certificate request message from ${t.peerIdentityKey}`);if(t.lastUpdate=Date.now(),await this.sessionManager.updateSession(t),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)});else{let t=await n0(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async sendCertificateResponse(e,t){let i=await this.getAuthenticatedSession(e),r=tS(ia(32)),{signature:n}=await this.wallet.createSignature({data:n8.utf8ToBytes(JSON.stringify(t)),protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),s={version:"0.1",messageType:"certificateResponse",identityKey:await this.getIdentityPublicKey(),nonce:r,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,certificates:t,signature:n};i.lastUpdate=Date.now(),await this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}async processCertificateResponse(e){if(!await nZ(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for certificate response from: ${e.identityKey}`);let t=await this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let{valid:i}=await this.wallet.verifySignature({data:n8.utf8ToBytes(JSON.stringify(e.certificates)),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:e.identityKey},this.originator);if(!i)throw Error(`Unable to verify certificate response signature for peer: ${e.identityKey}`);Array.isArray(e.certificates)&&e.certificates.length>0&&(await n1(this.wallet,e,e.requestedCertificates,this.originator),t.certificatesValidated=!0,t.lastUpdate=Date.now(),await this.sessionManager.updateSession(t),null!=t.sessionNonce&&this.resolveCertificateValidation(t.sessionNonce)),this.onCertificatesReceivedCallbacks.forEach(t=>{t(e.identityKey,e.certificates??[])})}async processGeneralMessage(e){if(!await nZ(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for general message from: ${e.identityKey}`);let t=await this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let i=!0===t.certificatesRequired,r=!0===t.certificatesValidated;if(i&&!r){let e=t.sessionNonce;if(null==e)throw Error("Session nonce is required for certificate validation");await new Promise((i,r)=>{let n=setTimeout(()=>{null!=this.certificateValidationPromises.get(e)&&(this.certificateValidationPromises.delete(e),r(Error(`Timeout waiting for certificate validation from peer ${t.peerIdentityKey??"unknown"}`)))},3e4);"object"==typeof n&&"unref"in n&&n.unref(),this.certificateValidationPromises.set(e,{resolve:()=>{clearTimeout(n),i()},reject:e=>{clearTimeout(n),r(e)}})})}let{valid:n}=await this.wallet.verifySignature({data:e.payload,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!n)throw Error(`Invalid signature in generalMessage from ${t.peerIdentityKey}`);t.lastUpdate=Date.now(),await this.sessionManager.updateSession(t),this.lastInteractedWithPeer=e.identityKey,this.onGeneralMessageReceivedCallbacks.forEach(t=>{t(e.identityKey,e.payload??[])})}resolveCertificateValidation(e){let t=this.certificateValidationPromises.get(e);null!=t&&(t.resolve(),this.certificateValidationPromises.delete(e))}async getIdentityPublicKey(){if(null!=this.identityPublicKey)return this.identityPublicKey;let{publicKey:e}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return this.identityPublicKey=e,e}static utf8ToBytes(e){return null!=n2?Array.from(n2.from(e,"utf8")):"u">typeof TextEncoder?Array.from(new TextEncoder().encode(e)):tm(e,"utf8")}static base64ToBytes(e){return null!=n2?Array.from(n2.from(e,"base64")):tm(e,"base64")}}let n3="u">typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch;class n5{onDataCallback;fetchClient;baseUrl;constructor(e,t=n3){if("function"!=typeof t)throw TypeError("SimplifiedFetchTransport requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=t,this.baseUrl=e}async send(e){if(null==this.onDataCallback)throw Error("Listen before you start speaking. God gave you two ears and one mouth for a reason.");if("general"!==e.messageType)return await new Promise((t,i)=>{(async()=>{try{let i=`${this.baseUrl}/.well-known/auth`,r=(async()=>{try{return await this.fetchClient(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(e){throw this.createNetworkError(i,e)}})();"initialRequest"!==e.messageType&&t();let n=await r;if(!n.ok){let e=Array.from(new Uint8Array(await n.arrayBuffer()));throw this.createUnauthenticatedResponseError(i,n,e)}if(null!=this.onDataCallback){let e=await n.json();this.onDataCallback(e)}"initialRequest"===e.messageType&&t()}catch(e){i(e)}})()});{let t,i,r=this.deserializeRequestPayload(e.payload),n=`${this.baseUrl}${r.urlPostfix}`;if("object"!=typeof r.headers&&(r.headers={}),r.headers["x-bsv-auth-version"]=e.version,r.headers["x-bsv-auth-identity-key"]=e.identityKey,r.headers["x-bsv-auth-nonce"]=e.nonce,r.headers["x-bsv-auth-your-nonce"]=e.yourNonce,r.headers["x-bsv-auth-signature"]=tg(e.signature),r.headers["x-bsv-auth-request-id"]=r.requestId,null!=r.body){let e=r.headers;if(null==e["content-type"])throw Error("Content-Type header is required for requests with a body.");let t=String(e["content-type"]??"");t.includes("application/json")||t.includes("application/x-www-form-urlencoded")||t.includes("text/plain")?r.body=tI(r.body):r.body=new Uint8Array(r.body)}try{t=await this.fetchClient(n,{method:r.method,headers:r.headers,body:r.body})}catch(e){throw this.createNetworkError(n,e)}let s=Array.from(new Uint8Array(await t.arrayBuffer())),a=["x-bsv-auth-version","x-bsv-auth-identity-key","x-bsv-auth-signature"].filter(e=>{let i=t.headers.get(e);return null==i||0===i.trim().length});if(a.length>0)throw this.createUnauthenticatedResponseError(n,t,s,a);let o=t.headers.get("x-bsv-auth-requested-certificates");if(null!=o)try{i=JSON.parse(o)}catch(e){throw this.createMalformedHeaderError(n,"x-bsv-auth-requested-certificates",o,e)}let l=new tP;null!=t.headers.get("x-bsv-auth-request-id")&&l.write(tm(t.headers.get("x-bsv-auth-request-id"),"base64")),l.writeVarIntNum(t.status);let c=[];for(let[e,i]of(t.headers.forEach((e,t)=>{let i=t.toLowerCase();(i.startsWith("x-bsv-")||"authorization"===i)&&!i.startsWith("x-bsv-auth")&&c.push([i,e])}),c.sort(([e],[t])=>e.localeCompare(t)),l.writeVarIntNum(c.length),c)){let t=tm(e,"utf8");l.writeVarIntNum(t.length),l.write(t);let r=tm(i,"utf8");l.writeVarIntNum(r.length),l.write(r)}l.writeVarIntNum(s.length),s.length>0&&l.write(s);let h={version:t.headers.get("x-bsv-auth-version"),messageType:"certificateRequest"===t.headers.get("x-bsv-auth-message-type")?"certificateRequest":"general",identityKey:t.headers.get("x-bsv-auth-identity-key"),nonce:t.headers.get("x-bsv-auth-nonce")??void 0,yourNonce:t.headers.get("x-bsv-auth-your-nonce")??void 0,requestedCertificates:i,payload:l.toArray(),signature:tm(t.headers.get("x-bsv-auth-signature"),"hex")};if(null==h.version)throw this.createUnauthenticatedResponseError(n,t,s);this.onDataCallback(h)}}async onData(e){this.onDataCallback=t=>{e(t).catch(()=>{})}}createNetworkError(e,t){let i=`Network error while sending authenticated request to ${e}`;if(t instanceof Error){let e=Error(`${i}: ${t.message}`);return e.stack=t.stack,e.cause=t,e}return Error(`${i}: ${String(t)}`)}createUnauthenticatedResponseError(e,t,i,r=[]){let n=(t.statusText??"").trim(),s=n.length>0?`${t.status} ${n}`:`${t.status}`,a=r.length>0?`missing headers: ${r.join(", ")}`:"response lacked required BSV auth headers",o=this.getBodyPreview(i,t.headers.get("content-type")),l=[`Received HTTP ${s} from ${e} without valid BSV authentication (${a})`];null!=o&&l.push(`body preview: ${o}`);let c=Error(l.join(" - "));return c.details={url:e,status:t.status,statusText:t.statusText,missingHeaders:r,bodyPreview:o},c}createMalformedHeaderError(e,t,i,r){let n=`Failed to parse ${t} returned by ${e}: ${i}`;if(r instanceof Error){let e=Error(`${n}. ${r.message}`);return e.stack=r.stack,e.cause=r,e}return Error(`${n}. ${String(r)}`)}getBodyPreview(e,t){let i;if(0===e.length)return;let r=e.length>1024,n=r?e.slice(0,1024):e;if(this.isTextualContent(t,n))try{i=tI(n)}catch{i=this.formatBinaryPreview(n,r)}else i=this.formatBinaryPreview(n,r);return i.length>512&&(i=`${i.slice(0,512)}…`),r&&(i=`${i} (truncated)`),i}isTextualContent(e,t){if(0===t.length)return!1;if(null!=e){let t=e.toLowerCase();if(["application/json","application/problem+json","application/xml","application/xhtml+xml","application/javascript","application/ecmascript","application/x-www-form-urlencoded","text/"].some(e=>t.includes(e))||t.includes("charset="))return!0}return t.reduce((e,t)=>9===t||10===t||13===t||t>=32&&t<=126?e+1:e,0)/t.length>.8}formatBinaryPreview(e,t){let i=e.map(e=>e.toString(16).padStart(2,"0")).join("");return`0x${i}${t?"…":""}`}deserializeRequestPayload(e){let t,i=new tN(e),r=tS(i.read(32)),n=i.readVarIntNum(),s="GET";n>0&&(s=tI(i.read(n)));let a=i.readVarIntNum(),o="";a>0&&(o=tI(i.read(a)));let l=i.readVarIntNum(),c="";l>0&&(c=tI(i.read(l)));let h={},d=i.readVarIntNum();if(d>0)for(let e=0;e<d;e++){let e=i.readVarIntNum(),t=tI(i.read(e)),r=i.readVarIntNum(),n=tI(i.read(r));h[t]=n}let u=i.readVarIntNum();return u>0&&(t=i.read(u)),{urlPostfix:o+c,method:s,headers:h,body:t,requestId:r}}}class n6{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;originator;peers={};constructor(e,t,i,r){this.wallet=e,this.requestedCertificates=t,this.sessionManager=i??new nJ,this.originator=r}async fetch(e,t={}){if("number"==typeof t.retryCounter){if(t.retryCounter<=0)throw Error("Request failed after maximum number of retries.");t.retryCounter--}let i=await new Promise(async(i,r)=>{try{let n,{method:s="GET",headers:a={},body:o}=t,l=new URL(e),c=l.origin;if(void 0===this.peers[c]){let e=new n5(c),t=new n8(this.wallet,e,this.requestedCertificates,this.sessionManager,void 0,this.originator);await t.ready,n={peer:t,pendingCertificateRequests:[]},this.peers[c]=n,this.peers[c].peer.listenForCertificatesReceived((e,t)=>{this.certificatesReceived.push(...t)}),this.peers[c].peer.listenForCertificatesRequested(async(e,t)=>{try{this.peers[c].pendingCertificateRequests.push(!0);let i=await n0(this.wallet,t,e,this.originator);i.length>0&&await this.peers[c].peer.sendCertificateResponse(e,i)}finally{await new Promise(e=>setTimeout(e,500)),this.peers[c].pendingCertificateRequests.shift()}})}else{if(!1===this.peers[c].supportsMutualAuth){try{let r=await this.handleFetchAndValidate(e,t,this.peers[c]);i(r)}catch(e){r(e)}return}n=this.peers[c]}let h=ia(32),d=tS(h),u=await this.serializeRequest(s,a,o,l,h);this.callbacks[d]={resolve:i,reject:r};let f=n.peer.listenForGeneralMessages((e,t)=>{let i,r=new tN(t);if(tS(r.read(32))!==d)return;n.peer.stopListeningForGeneralMessages(f),this.peers[c].identityKey=e,this.peers[c].supportsMutualAuth=!0;let s=r.readVarIntNum(),a={},o=r.readVarIntNum();if(o>0)for(let e=0;e<o;e++){let e=r.readVarIntNum(),t=r.read(e),i=tI(t),n=r.readVarIntNum(),s=r.read(n),o=tI(s);a[i]=o}a["x-bsv-auth-identity-key"]=e;let l=r.readVarIntNum();l>0&&(i=r.read(l));let h=new Response(i?new Uint8Array(i):null,{status:s,statusText:`${s}`,headers:new Headers(a)});this.callbacks[d].resolve(h),delete this.callbacks[d]});n.pendingCertificateRequests.length>0&&await new Promise((e,t)=>{let i=Date.now(),r=()=>{0===n.pendingCertificateRequests.length?e():Date.now()-i>3e4?t(Error("Timeout waiting for certificate request to complete")):setTimeout(r,100)};r()}),await n.peer.toPeer(u.toArray(),n.identityKey).catch(async s=>{if(s.message.includes("Session not found for nonce")||s.message.includes("without valid BSV authentication")&&null!=n.identityKey&&s.details?.status===401){delete this.peers[c],t.retryCounter??=3;let r=await this.fetch(e,t);i(r);return}if(s.message.includes("HTTP server failed to authenticate"))try{let r=await this.handleFetchAndValidate(e,t,n);i(r);return}catch(e){r(e)}else r(s)})}catch(e){r(e)}});return 402===i.status?await this.handlePaymentAndRetry(e,t,i):i}async sendCertificateRequest(e,t){let i,r=new URL(e).origin;if(void 0===this.peers[r]){let e=new n5(r),t=new n8(this.wallet,e,this.requestedCertificates,this.sessionManager,this.originator);await t.ready,i={peer:t},this.peers[r]=i}else i={peer:this.peers[r].peer};return await new Promise(async(e,n)=>{let s=!1,a=()=>{s=!0,clearTimeout(l),i.peer.stopListeningForCertificatesReceived(o)},o=i.peer.listenForCertificatesReceived((t,i)=>{s||(a(),this.certificatesReceived.push(...i),e(i))}),l=setTimeout(()=>{s||(a(),n(Error(`sendCertificateRequest timed out after 30000ms waiting for certificate response from ${r}`)))},3e4);try{await i.peer.requestCertificates(t,i.identityKey)}catch(e){s||(a(),n(e))}})}consumeReceivedCertificates(){return this.certificatesReceived.splice(0)}async serializeRequest(e,t,i,r,n){let s=new tP;if(s.write(n),s.writeVarIntNum(e.length),s.write(tm(e)),r.pathname.length>0){let e=tm(r.pathname);s.writeVarIntNum(e.length),s.write(e)}else s.writeVarIntNum(-1);if(r.search.length>0){let e=tm(r.search);s.writeVarIntNum(e.length),s.write(e)}else s.writeVarIntNum(-1);let a=[];for(let[e,i]of Object.entries(t))if((e=e.toLowerCase()).startsWith("x-bsv-")||"authorization"===e){if(e.startsWith("x-bsv-auth"))throw Error("No BSV auth headers allowed here!");a.push([e,i])}else if(e.startsWith("content-type"))i=i.split(";")[0].trim(),a.push([e,i]);else throw Error("Unsupported header in the simplified fetch implementation. Only content-type, authorization, and x-bsv-* headers are supported.");for(let[e,t]of(a.sort(([e],[t])=>e.localeCompare(t)),s.writeVarIntNum(a.length),a)){let i=tm(e,"utf8");s.writeVarIntNum(i.length),s.write(i);let r=tm(t,"utf8");s.writeVarIntNum(r.length),s.write(r)}if(["POST","PUT","PATCH","DELETE"].includes(e.toUpperCase())&&void 0===i){let e=a.find(([e])=>"content-type"===e);i=e?.[1].includes("application/json")===!0?"{}":""}if(i){let e=await this.normalizeBodyToNumberArray(i);s.writeVarIntNum(e.length),s.write(e)}else s.writeVarIntNum(-1);return s}async handleFetchAndValidate(e,t,i){let r=await fetch(e,t);if(r.headers.forEach(e=>{if(e.toLocaleLowerCase().startsWith("x-bsv"))throw Error("The server is trying to claim it has been authenticated when it has not!")}),r.ok)return i.supportsMutualAuth=!1,r;throw Error(`Request failed with status: ${r.status}`)}async handlePaymentAndRetry(e,t={},i){let r=i.headers.get("x-bsv-payment-version");if(!r||"1.0"!==r)throw Error(`Unsupported x-bsv-payment-version response header. Client version: 1.0, Server version: ${r}`);let n=i.headers.get("x-bsv-payment-satoshis-required");if(!n)throw Error("Missing x-bsv-payment-satoshis-required response header.");let s=Number.parseInt(n);if(Number.isNaN(s)||s<=0)throw Error("Invalid x-bsv-payment-satoshis-required response header value.");let a=i.headers.get("x-bsv-auth-identity-key");if("string"!=typeof a)throw TypeError("Missing x-bsv-auth-identity-key response header.");let o=i.headers.get("x-bsv-payment-derivation-prefix");if("string"!=typeof o||o.length<1)throw Error("Missing x-bsv-payment-derivation-prefix response header.");let l=t.paymentContext;if(null==l?l=await this.createPaymentContext(e,t,s,a,o):this.isPaymentContextCompatible(l,s,a,o)||(this.logPaymentAttempt("warn","Server adjusted payment requirements; regenerating transaction",this.composePaymentLogDetails(e,l)),l=await this.createPaymentContext(e,t,s,a,o)),l.attempts>=l.maxAttempts)throw this.buildPaymentFailureError(e,l,Error("Maximum payment attempts exceeded before retrying"));let c={...t.headers};c["x-bsv-payment"]=JSON.stringify({derivationPrefix:l.derivationPrefix,derivationSuffix:l.derivationSuffix,transaction:l.transactionBase64});let h={...t,headers:c,paymentContext:l};"number"!=typeof h.retryCounter&&(h.retryCounter=3);let d=l.attempts+1,u=l.maxAttempts;l.attempts=d;let f=this.composePaymentLogDetails(e,l);this.logPaymentAttempt("warn",`Attempting paid request (${d}/${u})`,f);try{let t=await this.fetch(e,h);return this.logPaymentAttempt("info",`Paid request attempt ${d} succeeded`,f),t}catch(n){let t=this.createPaymentErrorEntry(l.attempts,n);if(l.errors.push(t),this.logPaymentAttempt("error",`Paid request attempt ${d} failed`,{...f,error:{message:t.message,stack:t.stack}}),l.attempts>=l.maxAttempts)throw this.buildPaymentFailureError(e,l,n);let r=this.getPaymentRetryDelay(l.attempts);return await this.wait(r),this.handlePaymentAndRetry(e,h,i)}}isPaymentContextCompatible(e,t,i,r){return e.satoshisRequired===t&&e.serverIdentityKey===i&&e.derivationPrefix===r}async createPaymentContext(e,t,i,r,n){let s=await nQ(this.wallet,void 0,this.originator),{publicKey:a}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${n} ${s}`,counterparty:r},this.originator),o=new i3().lock(ii.fromString(a).toAddress()).toHex(),{tx:l}=await this.wallet.createAction({description:`Payment for request to ${new URL(e).origin}`,outputs:[{satoshis:i,lockingScript:o,customInstructions:JSON.stringify({derivationPrefix:n,derivationSuffix:s,payee:r}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}},this.originator),{publicKey:c}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return{satoshisRequired:i,transactionBase64:tS(l),derivationPrefix:n,derivationSuffix:s,serverIdentityKey:r,clientIdentityKey:c,attempts:0,maxAttempts:this.getMaxPaymentAttempts(t),errors:[],requestSummary:this.buildPaymentRequestSummary(e,t)}}getMaxPaymentAttempts(e){let t="number"==typeof e.paymentRetryAttempts?e.paymentRetryAttempts:void 0;return"number"==typeof t&&t>0?Math.floor(t):3}buildPaymentRequestSummary(e,t){let i={...t.headers},r="string"==typeof t.method?t.method.toUpperCase():"GET",n=this.describeRequestBodyForLogging(t.body);return{url:e,method:r,headers:i,bodyType:n.type,bodyByteLength:n.byteLength}}describeRequestBodyForLogging(e){if(null==e)return{type:"none",byteLength:0};if("string"==typeof e)return{type:"string",byteLength:tm(e,"utf8").length};if(Array.isArray(e))return e.every(e=>"number"==typeof e)?{type:"number[]",byteLength:e.length}:{type:"array",byteLength:e.length};if("u">typeof ArrayBuffer&&e instanceof ArrayBuffer)return{type:"ArrayBuffer",byteLength:e.byteLength};if("u">typeof ArrayBuffer&&ArrayBuffer.isView(e))return{type:null==e.constructor?"TypedArray":e.constructor.name,byteLength:e.byteLength};if("u">typeof Blob&&e instanceof Blob)return{type:"Blob",byteLength:e.size};if("u">typeof FormData&&e instanceof FormData)return{type:"FormData",byteLength:0};if("u">typeof URLSearchParams&&e instanceof URLSearchParams)return{type:"URLSearchParams",byteLength:tm(e.toString(),"utf8").length};if("u">typeof ReadableStream&&e instanceof ReadableStream)return{type:"ReadableStream",byteLength:0};try{let t=JSON.stringify(e);if("string"==typeof t)return{type:"object",byteLength:tm(t,"utf8").length}}catch(e){}return{type:typeof e,byteLength:0}}composePaymentLogDetails(e,t){return{url:e,request:t.requestSummary,payment:{satoshis:t.satoshisRequired,transactionBase64:t.transactionBase64,derivationPrefix:t.derivationPrefix,derivationSuffix:t.derivationSuffix,serverIdentityKey:t.serverIdentityKey,clientIdentityKey:t.clientIdentityKey},attempts:{used:t.attempts,max:t.maxAttempts},errors:t.errors}}logPaymentAttempt(e,t,i){let r="[AuthFetch][Payment]";"error"===e?console.error(`${r} ${t}`,i):"warn"===e?console.warn(`${r} ${t}`,i):"function"==typeof console.info?console.info(`${r} ${t}`,i):console.log(`${r} ${t}`,i)}createPaymentErrorEntry(e,t){let i={attempt:e,timestamp:new Date().toISOString(),message:"",stack:void 0};return t instanceof Error?(i.message=t.message,i.stack=t.stack??void 0):i.message=String(t),i}getPaymentRetryDelay(e){return 250*Math.min(e,5)}async wait(e){e<=0||await new Promise(t=>setTimeout(t,e))}buildPaymentFailureError(e,t,i){let r=Error(`Paid request to ${e} failed after ${t.attempts}/${t.maxAttempts} attempts. Sent ${t.satoshisRequired} satoshis to ${t.serverIdentityKey}.`);return r.details={request:t.requestSummary,payment:{satoshis:t.satoshisRequired,transactionBase64:t.transactionBase64,derivationPrefix:t.derivationPrefix,derivationSuffix:t.derivationSuffix,serverIdentityKey:t.serverIdentityKey,clientIdentityKey:t.clientIdentityKey},attempts:{used:t.attempts,max:t.maxAttempts},errors:t.errors},i instanceof Error&&(r.cause=i),r}async normalizeBodyToNumberArray(e){if(null==e)return[];if("object"==typeof e)return tm(JSON.stringify(e,"utf8"));if(Array.isArray(e)&&e.every(e=>"number"==typeof e))return e;if("string"==typeof e)return tm(e,"utf8");if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Array.from(new Uint8Array(e instanceof ArrayBuffer?e:e.buffer));if(e instanceof Blob)return Array.from(new Uint8Array(await e.arrayBuffer()));if(e instanceof FormData){let t=[];return e.forEach((e,i)=>{t.push([i,e.toString()])}),tm(new URLSearchParams(t).toString(),"utf8")}if(e instanceof URLSearchParams)return tm(e.toString(),"utf8");if(e instanceof ReadableStream)throw TypeError("ReadableStream cannot be directly converted to number[].");throw Error("Unsupported body type in this SimplifiedFetch implementation.")}}class n4{pushDrop;static decode(e){let t=i4.decode(e);if(t.fields.length<4)throw Error("Invalid SHIP/SLAP advertisement!");let i=tI(t.fields[0]);if("SHIP"!==i&&"SLAP"!==i)throw Error("Invalid protocol type!");let r=tg(t.fields[1]);return{protocol:i,identityKey:r,domain:tI(t.fields[2]),topicOrService:tI(t.fields[3])}}constructor(e,t){this.pushDrop=new i4(e,t)}async lock(e,t,i){let{publicKey:r}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([tm(e,"utf8"),tm(r,"hex"),tm(t,"utf8"),tm(i,"utf8")],[2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}unlock(e){return this.pushDrop.unlock([2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}}let n9="bsvsdk_overlay_host_reputation_v1";class n7{stats;store;constructor(e){this.stats=new Map,this.store=e??this.getLocalStorageAdapter(),this.loadFromStorage()}reset(){this.stats.clear()}recordSuccess(e,t){let i=this.getOrCreate(e),r=Date.now(),n=Number.isFinite(t)&&t>=0?t:1500;null===i.avgLatencyMs?i.avgLatencyMs=n:i.avgLatencyMs=.75*i.avgLatencyMs+.25*n,i.lastLatencyMs=n,i.totalSuccesses+=1,i.consecutiveFailures=0,i.backoffUntil=0,i.lastUpdatedAt=r,i.lastError=void 0,this.saveToStorage()}recordFailure(e,t){let i,r=this.getOrCreate(e),n=Date.now();r.totalFailures+=1,r.consecutiveFailures+=1,"string"==typeof(i="string"==typeof t?t:t instanceof Error?t.message:void 0)&&(i.includes("ERR_NAME_NOT_RESOLVED")||i.includes("ENOTFOUND")||i.includes("getaddrinfo")||i.includes("Failed to fetch"))&&r.consecutiveFailures<3&&(r.consecutiveFailures=3);let s=Math.max(r.consecutiveFailures-2,0);0===s?r.backoffUntil=0:r.backoffUntil=n+Math.min(6e4,1e3*Math.pow(2,s-1)),r.lastUpdatedAt=n,"string"==typeof t?r.lastError=t:t instanceof Error?r.lastError=t.message:r.lastError=void 0,this.saveToStorage()}rankHosts(e,t=Date.now()){let i=new Map;e.forEach((e,t)=>{"string"==typeof e&&0!==e.length&&(i.has(e)||i.set(e,t))});let r=Array.from(i.keys()).map(e=>{let r=this.getOrCreate(e);return{...r,score:this.computeScore(r,t),originalOrder:i.get(e)??0}});return r.sort((e,i)=>{let r=e.backoffUntil>t;return r!==i.backoffUntil>t?r?1:-1:e.score!==i.score?e.score-i.score:e.totalSuccesses!==i.totalSuccesses?i.totalSuccesses-e.totalSuccesses:e.originalOrder-i.originalOrder}),r.map(({originalOrder:e,...t})=>t)}snapshot(e){let t=this.stats.get(e);return null==t?void 0:{...t}}getStorage(){try{let e="object"==typeof globalThis?globalThis:void 0;if(e?.localStorage==null)return;return e.localStorage}catch{return}}getLocalStorageAdapter(){let e=this.getStorage();if(null!=e)return{get:t=>{try{return e.getItem(t)}catch{return null}},set:(t,i)=>{try{e.setItem(t,i)}catch{}}}}loadFromStorage(){let e=this.store;if(null!=e)try{let t=e.get(n9);if("string"!=typeof t||0===t.length)return;let i=JSON.parse(t);if("object"!=typeof i||null===i)return;for(let e of(this.stats.clear(),Object.keys(i))){let t=i[e];if(null!=t&&"object"==typeof t){let i={host:String(t.host??e),totalSuccesses:Number(t.totalSuccesses??0),totalFailures:Number(t.totalFailures??0),consecutiveFailures:Number(t.consecutiveFailures??0),avgLatencyMs:null==t.avgLatencyMs?null:Number(t.avgLatencyMs),lastLatencyMs:null==t.lastLatencyMs?null:Number(t.lastLatencyMs),backoffUntil:Number(t.backoffUntil??0),lastUpdatedAt:Number(t.lastUpdatedAt??0),lastError:"string"==typeof t.lastError?t.lastError:void 0};this.stats.set(i.host,i)}}}catch{}}saveToStorage(){let e=this.store;if(null!=e)try{let t={};for(let[e,i]of this.stats.entries())t[e]=i;e.set(n9,JSON.stringify(t))}catch{}}computeScore(e,t){let i=e.avgLatencyMs??1500,r=400*e.consecutiveFailures,n=Math.min(30*e.totalSuccesses,i/2);return i+r+(e.backoffUntil>t?e.backoffUntil-t:0)-n}getOrCreate(e){let t=this.stats.get(e);return null==t&&(t={host:e,totalSuccesses:0,totalFailures:0,consecutiveFailures:0,avgLatencyMs:null,lastLatencyMs:null,backoffUntil:0,lastUpdatedAt:0},this.stats.set(e,t)),t}}let se=new n7,st="u">typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch,si=["https://overlay-us-1.bsvb.tech","https://overlay-eu-1.bsvb.tech","https://overlay-ap-1.bsvb.tech","https://users.bapp.dev"],sr=["https://testnet-users.bapp.dev"];class sn{fetchClient;allowHTTP;constructor(e=st,t=!1){if("function"!=typeof e)throw TypeError("HTTPSOverlayLookupFacilitator requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=e,this.allowHTTP=t}async lookup(e,t,i=2e3){let r,n;if(!e.startsWith("https:")&&!this.allowHTTP)throw Error('HTTPS facilitator can only use URLs that start with "https:"');let s="u"<typeof AbortController?void 0:new AbortController,a=(r=!1,n=null,{promise:new Promise((e,t)=>{n=setTimeout(()=>{r=!0;try{s?.abort()}catch{}t(Error("Request timed out"))},i)}),cancel:()=>{null!==n&&clearTimeout(n)},didTimeOut:()=>r}),o=this.performLookupRequest(e,t,s?.signal);o.catch(()=>{});try{return await Promise.race([o,a.promise])}catch(e){throw a.didTimeOut()||e?.name==="AbortError"?Error("Request timed out"):e instanceof Error?e:Error(function(e){if(null===e)return"null";if(void 0===e)return"undefined";if("string"==typeof e)return e;if("number"==typeof e)return e.toString();if("boolean"==typeof e)return e?"true":"false";if("bigint"==typeof e)return e.toString();let t=e.message;if("string"==typeof t&&t.length>0)return t;try{return JSON.stringify(e)??"Unknown error"}catch{return"Unknown error"}}(e))}finally{a.cancel()}}async performLookupRequest(e,t,i){var r;let n={method:"POST",headers:{"Content-Type":"application/json","X-Aggregation":"yes"},body:JSON.stringify({service:t.service,query:t.query}),signal:i},s=await this.fetchClient(`${e}/lookup`,n);if(!s.ok)throw Error(`Failed to facilitate lookup (HTTP ${s.status})`);return"string"==typeof(r=s.headers.get("content-type"))&&"application/octet-stream"===r.split(";",1)[0].trim().toLowerCase()?await this.parseOctetStreamLookup(s):await s.json()}async parseOctetStreamLookup(e){let t=new tN([...new Uint8Array(await e.arrayBuffer())]),i=t.readVarIntNum(),r=[];for(let e=0;e<i;e++){let e=tg(t.read(32)),i=t.readVarIntNum(),n=t.readVarIntNum(),s=n>0?t.read(n):void 0;r.push({txid:e,outputIndex:i,context:s})}let n=t.read(),s=rp.fromBinary(n);return{type:"output-list",outputs:await this.extractAtomicOutputs(r,s)}}async extractAtomicOutputs(e,t){let i=new Map,r=Array(e.length);for(let n=0;n<e.length;n++){let s=e[n],a=i.get(s.txid);void 0===a&&(a=t.toBinaryAtomic(s.txid),i.set(s.txid,a)),r[n]={outputIndex:s.outputIndex,context:s.context,beef:a,txid:s.txid},n>0&&n<e.length-1&&await new Promise(e=>setTimeout(e,0))}return r}}class ss{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;hostReputation;hostsCache;hostsInFlight;hostsTtlMs;hostsMaxEntries;txMemo;txMemoTtlMs;constructor(e={}){this.networkPreset=e.networkPreset??"mainnet",this.facilitator=e.facilitator??new sn(void 0,"local"===this.networkPreset),this.slapTrackers=e.slapTrackers??("mainnet"===this.networkPreset?si:sr);const t=e.hostOverrides??{};this.assertValidOverrideServices(t),this.hostOverrides=t,this.additionalHosts=e.additionalHosts??{};const i=e.reputationStorage;"localStorage"===i?this.hostReputation=new n7:"object"==typeof i&&null!==i&&"function"==typeof i.get&&"function"==typeof i.set?this.hostReputation=new n7(i):this.hostReputation=se,this.hostsTtlMs=e.cache?.hostsTtlMs??3e5,this.hostsMaxEntries=e.cache?.hostsMaxEntries??128,this.txMemoTtlMs=e.cache?.txMemoTtlMs??6e5,this.hostsCache=new Map,this.hostsInFlight=new Map,this.txMemo=new Map}async query(e,t,i){let r=this.query$(e,t,i)[Symbol.asyncIterator](),n=null;try{let{value:e,done:t}=await r.next();!0!==t&&null!=e&&(n=e)}finally{await r.return?.(void 0)}return{type:"output-list",outputs:n?.outputs??[]}}async *query$(e,t,i){let r=[];if(r="ls_slap"===e.service?"local"===this.networkPreset?["http://localhost:8080"]:this.slapTrackers:null!=this.hostOverrides[e.service]?this.hostOverrides[e.service]:"local"===this.networkPreset?["http://localhost:8080"]:await this.getCompetentHostsCached(e.service),this.additionalHosts[e.service]?.length>0){let t=this.additionalHosts[e.service],i=new Set(r);for(let e of t)i.has(e)||r.push(e)}if(r.length<1)throw Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${e.service}`);let n=this.prepareHostsForQuery(r,`lookup service ${e.service}`);if(n.length<1)throw Error(`All competent hosts for ${e.service} are temporarily unavailable due to backoff.`);let s=i?.graceMs??80,a=i?.softTimeoutMs,o=n.length,l=new Map,c=[],h=0,d=null,u=[],f=null,p=e=>{if(u.push(e),null!==f){let e=f;f=null,e()}};for(let i of n)this.lookupHostWithTracking(i,e,t).then(e=>{e?.type==="output-list"&&Array.isArray(e.outputs)&&e.outputs.length>0&&p({kind:"answer",answer:e})}).catch(()=>{}).finally(()=>{h++,p({kind:"done"})});let g=null;"number"==typeof a&&a>=0&&(g=setTimeout(()=>p({kind:"soft"}),a));let y=null,m=!1,b=!1,w=e=>{let t=!1,i=Date.now();for(let r of e.outputs){let e=this.resolveTxIdForOutput(r,i);if(null===e)continue;let n=`${e}.${r.outputIndex}`;l.has(n)||(l.set(n,r),c.push(e),t=!0)}return t},v=e=>({type:"output-list",outputs:Array.from(l.values()),txIds:c.slice(),isFinal:e,hostCount:o,completedHosts:h});try{for(;h<o;){0===u.length&&await new Promise(e=>{f=e});let e=u.shift();if("answer"===e.kind){let t=w(e.answer);null===d&&(d=Date.now(),!m&&s>0?y=setTimeout(()=>{m=!0,p({kind:"soft"})},s):m=!0),m&&t&&(b=!0,yield v(!1))}else if("soft"===e.kind){if(b||(m=!0,b=!0,yield v(!1)),"number"==typeof a&&null!==d)break}else e.kind}yield v(!0)}finally{null!==y&&clearTimeout(y),null!==g&&clearTimeout(g)}}async getCompetentHostsCached(e){let t=Date.now(),i=this.hostsCache.get(e);if("object"==typeof i&&i.expiresAt>t)return i.hosts.slice();if("object"==typeof i&&i.expiresAt<=t)return this.hostsInFlight.has(e)||this.hostsInFlight.set(e,this.refreshHosts(e).finally(()=>{this.hostsInFlight.delete(e)})),i.hosts.slice();if(this.hostsInFlight.has(e))try{let t=await this.hostsInFlight.get(e);if("object"!=typeof t)throw TypeError("Hosts is not defined.");return t.slice()}catch{}let r=this.refreshHosts(e).finally(()=>{this.hostsInFlight.delete(e)});return this.hostsInFlight.set(e,r),(await r).slice()}async refreshHosts(e){let t=await this.findCompetentHosts(e),i=Date.now()+this.hostsTtlMs;if(!this.hostsCache.has(e)&&this.hostsCache.size>=this.hostsMaxEntries){let e=this.hostsCache.keys().next().value;void 0!==e&&this.hostsCache.delete(e)}return this.hostsCache.set(e,{hosts:t,expiresAt:i}),t}extractHostsFromAnswer(e,t){let i=[];if("output-list"!==e.type)return i;for(let r of e.outputs)try{let e=rg.fromBEEF(r.beef),n=e.outputs[r.outputIndex]?.lockingScript;if("object"!=typeof n||null===n)continue;let s=n4.decode(n);if(s.topicOrService!==t||"SLAP"!==s.protocol)continue;"string"==typeof s.domain&&s.domain.length>0&&i.push(s.domain)}catch{continue}return i}async findCompetentHosts(e){let t={service:"ls_slap",query:{service:e}},i=this.prepareHostsForQuery(this.slapTrackers,"SLAP trackers");return 0===i.length?[]:await new Promise(r=>{let n=new Set,s=!1,a=i.length;for(let o of i)this.lookupHostWithTracking(o,t,5e3).then(t=>{for(let i of this.extractHostsFromAnswer(t,e))n.add(i);!s&&n.size>0&&(s=!0,r([...n]))}).catch(()=>{}).finally(()=>{0!=--a||s||(s=!0,r([...n]))})})}resolveTxIdForOutput(e,t){if("string"==typeof e.txid&&e.txid.length>0)return e.txid;let i=Array.isArray(e.beef)?e.beef.join(","):"",r=this.txMemo.get(i);if("object"==typeof r&&null!==r&&r.expiresAt>t)return r.txId;try{let r=rg.fromBEEF(e.beef).id("hex");return this.txMemo.size>4096&&this.evictOldest(this.txMemo),this.txMemo.set(i,{txId:r,expiresAt:t+this.txMemoTtlMs}),r}catch{return null}}evictOldest(e){let t=e.keys().next().value;void 0!==t&&e.delete(t)}assertValidOverrideServices(e){for(let t of Object.keys(e))if(!t.startsWith("ls_"))throw Error(`Host override service names must start with "ls_": ${t}`)}prepareHostsForQuery(e,t){if(0===e.length)return[];let i=Date.now(),r=this.hostReputation.rankHosts(e,i),n=r.filter(e=>e.backoffUntil<=i).map(e=>e.host);if(n.length>0)return n;let s=Math.max(Math.min(...r.map(e=>e.backoffUntil))-i,0);throw Error(`All ${t} hosts are backing off for approximately ${s}ms due to repeated failures.`)}async lookupHostWithTracking(e,t,i){let r=Date.now();try{let n=await this.facilitator.lookup(e,t,i),s=Date.now()-r;return"object"==typeof n&&null!==n&&"output-list"===n.type&&Array.isArray(n.outputs)?this.hostReputation.recordSuccess(e,s):this.hostReputation.recordFailure(e,"Invalid lookup response"),n}catch(t){throw this.hostReputation.recordFailure(e,t),t}}}class sa{httpClient;allowHTTP;constructor(e=fetch,t=!1){this.httpClient=e,this.allowHTTP=t}async send(e,t){let i;if(!e.startsWith("https:")&&!this.allowHTTP)throw Error('HTTPS facilitator can only use URLs that start with "https:"');let r={"Content-Type":"application/octet-stream","X-Topics":JSON.stringify(t.topics)};if(Array.isArray(t.offChainValues)){r["x-includes-off-chain-values"]="true";let e=new tP;e.writeVarIntNum(t.beef.length),e.write(t.beef),e.write(t.offChainValues),i=new Uint8Array(e.toArray())}else i=new Uint8Array(t.beef);let n=await fetch(`${e}/submit`,{method:"POST",headers:r,body:i});if(n.ok)return await n.json();throw Error("Failed to facilitate broadcast")}}class so{topics;facilitator;resolver;requireAcknowledgmentFromAllHostsForTopics;requireAcknowledgmentFromAnyHostForTopics;requireAcknowledgmentFromSpecificHostsForTopics;networkPreset;interestedHostsCache=null;interestedHostsInFlight=null;interestedHostsTtlMs;constructor(e,t={}){if(0===e.length)throw Error("At least one topic is required for broadcast.");if(e.some(e=>!e.startsWith("tm_")))throw Error('Every topic must start with "tm_".');this.topics=e,this.networkPreset=t.networkPreset??"mainnet",this.facilitator=t.facilitator??new sa(void 0,"local"===this.networkPreset),this.resolver=t.resolver??new ss({networkPreset:this.networkPreset}),this.requireAcknowledgmentFromAllHostsForTopics=t.requireAcknowledgmentFromAllHostsForTopics??[],this.requireAcknowledgmentFromAnyHostForTopics=t.requireAcknowledgmentFromAnyHostForTopics??"all",this.requireAcknowledgmentFromSpecificHostsForTopics=t.requireAcknowledgmentFromSpecificHostsForTopics??{},this.interestedHostsTtlMs=3e5}async broadcast(e){let t,i=e.metadata.get("OffChainValues");try{t=e.toBEEF()}catch(e){throw Error("Transactions sent via SHIP to Overlay Services must be serializable to BEEF format.")}let r=await this.findInterestedHosts();if(0===Object.keys(r).length)return{status:"error",code:"ERR_NO_HOSTS_INTERESTED",description:`No ${this.networkPreset} hosts are interested in receiving this transaction.`};let n=Object.entries(r).map(async([e,r])=>{try{let n=await this.facilitator.send(e,{beef:t,offChainValues:i,topics:[...r]});if(null==n||0===Object.keys(n).length)throw Error("Steak has no topics.");return{host:e,success:!0,steak:n}}catch(t){return console.error(t),{host:e,success:!1,error:t}}}),s=(await Promise.all(n)).filter(e=>e.success);if(0===s.length)return{status:"error",code:"ERR_ALL_HOSTS_REJECTED",description:`All ${this.networkPreset} topical hosts have rejected the transaction.`};let a={};for(let e of s){let t=e.host,i=e.steak,r=new Set;for(let[e,t]of Object.entries(i)){let i=t.outputsToAdmit,n=t.coinsToRetain,s=t.coinsRemoved;(i?.length>0||n?.length>0||s?.length>0)&&r.add(e)}a[t]=r}let o=this.checkAllHostsRequirement(a);if(null!=o)return o;let l=this.checkAnyHostRequirement(a);if(null!=l)return l;let c=this.checkSpecificHostsRequirement(a);return null!=c?c:{status:"success",txid:e.id("hex"),message:`Sent to ${s.length} Overlay Services ${1===s.length?"host":"hosts"}.`}}resolveAllHostsRequirement(){let e=this.requireAcknowledgmentFromAllHostsForTopics;return"any"===e?{requiredTopics:this.topics,require:"any"}:Array.isArray(e)?{requiredTopics:e,require:"all"}:{requiredTopics:this.topics,require:"all"}}checkAllHostsRequirement(e){let{requiredTopics:t,require:i}=this.resolveAllHostsRequirement();return 0===t.length||this.checkAcknowledgmentFromAllHosts(e,t,i)?null:{status:"error",code:"ERR_REQUIRE_ACK_FROM_ALL_HOSTS_FAILED",description:"Not all hosts acknowledged the required topics."}}resolveAnyHostRequirement(){let e=this.requireAcknowledgmentFromAnyHostForTopics;return"all"===e?{requiredTopics:this.topics,require:"all"}:"any"===e?{requiredTopics:this.topics,require:"any"}:Array.isArray(e)?{requiredTopics:e,require:"all"}:{requiredTopics:[],require:"all"}}checkAnyHostRequirement(e){let{requiredTopics:t,require:i}=this.resolveAnyHostRequirement();return 0===t.length||this.checkAcknowledgmentFromAnyHost(e,t,i)?null:{status:"error",code:"ERR_REQUIRE_ACK_FROM_ANY_HOST_FAILED",description:"No host acknowledged the required topics."}}checkSpecificHostsRequirement(e){return 0===Object.keys(this.requireAcknowledgmentFromSpecificHostsForTopics).length||this.checkAcknowledgmentFromSpecificHosts(e,this.requireAcknowledgmentFromSpecificHostsForTopics)?null:{status:"error",code:"ERR_REQUIRE_ACK_FROM_SPECIFIC_HOSTS_FAILED",description:"Specific hosts did not acknowledge the required topics."}}topicsMatchRequirement(e,t,i){return"all"===i?t.every(t=>e.has(t)):t.some(t=>e.has(t))}checkAcknowledgmentFromAllHosts(e,t,i){return Object.values(e).every(e=>this.topicsMatchRequirement(e,t,i))}checkAcknowledgmentFromAnyHost(e,t,i){return Object.values(e).some(e=>this.topicsMatchRequirement(e,t,i))}checkAcknowledgmentFromSpecificHosts(e,t){for(let[i,r]of Object.entries(t)){let t,n,s=e[i];if(null==s)return!1;if("all"===r||"any"===r)n=r,t=this.topics;else{if(!Array.isArray(r))continue;t=r,n="all"}if(!this.topicsMatchRequirement(s,t,n))return!1}return!0}async findInterestedHosts(){if("local"===this.networkPreset){let e=new Set;for(let t of this.topics)e.add(t);return{"http://localhost:8080":e}}let e=Date.now();if(null!=this.interestedHostsCache&&this.interestedHostsCache.expiresAt>e)return this.interestedHostsCache.hosts;if(null!=this.interestedHostsInFlight)return await this.interestedHostsInFlight;this.interestedHostsInFlight=this.fetchInterestedHosts();try{let e=await this.interestedHostsInFlight;return this.interestedHostsCache={hosts:e,expiresAt:Date.now()+this.interestedHostsTtlMs},e}finally{this.interestedHostsInFlight=null}}async fetchInterestedHosts(){let e={},t=await this.resolver.query({service:"ls_ship",query:{topics:this.topics}},5e3);if("output-list"!==t.type)throw Error("SHIP answer is not an output list.");for(let i of t.outputs)try{let t=rg.fromBEEF(i.beef).outputs[i.outputIndex].lockingScript,r=n4.decode(t);if(!this.topics.includes(r.topicOrService)||"SHIP"!==r.protocol)continue;e[r.domain]??=new Set,e[r.domain].add(r.topicOrService)}catch(e){continue}return e}}async function sl(e,t,i=5){let r=0;for(;r<i;){r++;try{return await e()}catch(e){if(r<i&&"WERR_REVIEW_ACTIONS"===e.name){let n=e.reviewActionResults.find(e=>"doubleSpend"===e.status);if(n?.competingBeef!=null&&n?.competingTxs!=null&&n?.competingTxs.length>0){let e=rg.fromBEEF(n.competingBeef,n.competingTxs[0]);await sl(async()=>await t.broadcast(e),t,i-r);continue}}throw e}}throw Error("Unexpected end of retry loop")}let sc=e=>(e.toLowerCase().startsWith("uhrp:")&&(e=e.slice(5)),e.startsWith("//")&&(e=e.slice(2)),e),sh=e=>{if(32!==e.length)throw Error("Hash length must be 32 bytes (sha256)");return tT(e,tm("ce00","hex"))},sd=e=>{let t=e instanceof Uint8Array?e:Uint8Array.from(e),i=new eh;for(let e=0;e<t.length;e+=1048576){let r=t.subarray(e,e+1048576);i.update(Array.from(r))}return sh(i.digest())},su=e=>{let{data:t,prefix:i}=tO(e=sc(e),void 0,2);if(32!==t.length)throw Error("Invalid length!");if("ce00"!==tg(i))throw Error("Bad prefix");return t},sf=e=>{try{return su(e),!0}catch{return!1}},sp=["https://nanostore.babbage.systems","https://bsv-storage-cloudflare.dev-a3e.workers.dev"];class sg extends Error{results;requiredSuccesses;successCount;constructor(e,t,i,r){super(e),this.name="RenewResiliencyError",this.results=t,this.requiredSuccesses=i,this.successCount=r}}class sy{authFetch;hosts;resilienceLevel;baseURL;constructor(e){let t;const i=void 0===e.storageURLs&&"string"==typeof e.storageURL;if(void 0!==e.storageURLs){if(0===e.storageURLs.length)throw Error("StorageUploader requires at least one storage provider.");t=[...e.storageURLs]}else t="string"==typeof e.storageURL?[e.storageURL]:[...sp];const r=e.resilienceLevel??1;if(!Number.isInteger(r)||r<1)throw Error("resilienceLevel must be a positive integer.");this.resilienceLevel=i?1:r,this.hosts=t,this.baseURL=t[0],this.authFetch=new n6(e.wallet)}async getQuote(e,t,i){try{let r=await fetch(`${e}/quote`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileSize:t,retentionPeriod:i})});if(!r.ok)return null;let n=await r.json();if("error"===n.status||"number"!=typeof n.quote)return null;return{host:e,amount:n.quote}}catch{return null}}async getUploadURL(e,t,i){let r=await this.authFetch.fetch(`${e}/upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileSize:t,retentionPeriod:i})});if(!r.ok)throw Error(`Upload info request failed: HTTP ${r.status}`);let n=await r.json();if("error"===n.status)throw Error("Upload route returned an error.");return{uploadURL:n.uploadURL,requiredHeaders:n.requiredHeaders,amount:n.amount}}async putFile(e,t,i,r){let n=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":i,...r}});if(!n.ok)throw Error(`File upload failed: HTTP ${n.status}`)}async collectQuotes(e,t,i){let r=[],n=0;for(;n<this.hosts.length&&r.length<i;){let s=i-r.length,a=this.hosts.slice(n,n+s);for(let s of(n+=a.length,await Promise.all(a.map(async i=>await this.getQuote(i,e,t)))))null!==s&&r.length<i&&r.push(s)}return r}async estimateCost(e){let{fileSize:t,retentionPeriod:i}=e,r=await this.collectQuotes(t,i,2*this.resilienceLevel);r.sort((e,t)=>e.amount-t.amount);let n=r.length>=this.resilienceLevel,s=(n?r.slice(0,this.resilienceLevel):r).reduce((e,t)=>e+t.amount,0);return{quotes:r.map(e=>({host:e.host,amount:e.amount})),resilienceLevel:this.resilienceLevel,totalForResilience:s,meetsResilienceThreshold:n}}async publishFile(e){let{file:t,retentionPeriod:i}=e,r=t.data instanceof Uint8Array?t.data:Uint8Array.from(t.data),n=r.byteLength,s=await this.estimateCost({fileSize:n,retentionPeriod:i});if(!s.meetsResilienceThreshold)throw Error(`Resiliency threshold of ${this.resilienceLevel} could not be met: only ${s.quotes.length} of ${this.hosts.length} provider(s) responded with quotes.`);let a=sd(r),o=[],l=[];for(let e of s.quotes){if(o.length>=this.resilienceLevel)break;try{let{uploadURL:s,requiredHeaders:a}=await this.getUploadURL(e.host,n,i);await this.putFile(s,r,t.type,a),o.push(e.host)}catch(t){l.push({host:e.host,error:t.message})}}if(o.length<this.resilienceLevel){let e=l.map(e=>`${e.host}: ${e.error}`).join("; ");throw Error(`Resiliency threshold of ${this.resilienceLevel} could not be met: only ${o.length} upload(s) succeeded. Failures — ${e}`)}return{published:!0,uhrpURL:a,hostedBy:o}}async findFileAtHost(e,t){let i=new URL(`${e}/find`);i.searchParams.set("uhrpUrl",t);let r=await this.authFetch.fetch(i.toString(),{method:"GET"});if(!r.ok)throw Error(`findFile request failed: HTTP ${r.status}`);let n=await r.json();if("error"===n.status){let e=n.code??"unknown-code",t=n.description??"no-description";throw Error(`findFile returned an error: ${e} - ${t}`)}return n.data}async renewFileAtHost(e,t,i){let r=await this.authFetch.fetch(`${e}/renew`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({uhrpUrl:t,additionalMinutes:i})});if(!r.ok)throw Error(`renewFile request failed: HTTP ${r.status}`);let n=await r.json();if("error"===n.status){let e=n.code??"unknown-code",t=n.description??"no-description";throw Error(`renewFile returned an error: ${e} - ${t}`)}return{status:n.status,prevExpiryTime:n.prevExpiryTime,newExpiryTime:n.newExpiryTime,amount:n.amount}}resolveTargets(e){if(void 0===e)return this.hosts;let t=new Set(this.hosts),i=e.filter(e=>t.has(e));if(0===i.length)throw Error("hostedBy did not intersect any configured provider. Provide hosts that were also passed to the StorageUploader constructor.");return i}async findFile(e,t={}){let i=this.resolveTargets(t.hostedBy),r=await Promise.all(i.map(async t=>{try{return{ok:!0,host:t,data:await this.findFileAtHost(t,e)}}catch(e){return{ok:!1,host:t,error:e}}})),n=r.flatMap(e=>e.ok?[e]:[]);if(0===n.length){let e=r.flatMap(e=>e.ok?[]:[e]);if(1===i.length)throw e[0].error;let t=e.map(e=>`${e.host}: ${e.error.message}`).join("; ");throw Error(`findFile: no configured host reported this UHRP URL — ${t}`)}n.sort((e,t)=>t.data.expiryTime-e.data.expiryTime);let s=n[0];return 1===i.length?s.data:{...s.data,hostedBy:n.map(e=>e.host)}}async listUploads(e={}){let t=this.resolveTargets(e.hostedBy),i=await Promise.all(t.map(async e=>{try{return{ok:!0,host:e,data:await this.listUploadsAtHost(e)}}catch(t){return{ok:!1,host:e,error:t}}})),r=i.flatMap(e=>e.ok?[e]:[]);if(0===r.length){let e=i.flatMap(e=>e.ok?[]:[e]);if(1===t.length)throw e[0].error;let r=e.map(e=>`${e.host}: ${e.error.message}`).join("; ");throw Error(`listUploads: no configured host returned a listing — ${r}`)}if(1===t.length)return r[0].data;let n=new Map;for(let{host:e,data:t}of r)if(Array.isArray(t))for(let i of t){let t=i?.uhrpUrl;if("string"!=typeof t)continue;let r=Number(i.expiryTime),s=Number.isFinite(r)?r:0,a=n.get(t);void 0===a?n.set(t,{uhrpUrl:t,expiryTime:s,hostedBy:[e]}):(a.expiryTime=Math.max(a.expiryTime,s),a.hostedBy.includes(e)||a.hostedBy.push(e))}return Array.from(n.values())}async listUploadsAtHost(e){let t=await this.authFetch.fetch(`${e}/list`,{method:"GET"});if(!t.ok)throw Error(`listUploads request failed: HTTP ${t.status}`);let i=await t.json();if("error"===i.status){let e=i.code??"unknown-code",t=i.description??"no-description";throw Error(`listUploads returned an error: ${e} - ${t}`)}return i.uploads}async renewFile(e,t,i={}){let r=this.resolveTargets(i.hostedBy);if(1===r.length){let i=await this.renewFileAtHost(r[0],e,t);return{status:i.status,prevExpiryTime:i.prevExpiryTime,newExpiryTime:i.newExpiryTime,amount:i.amount}}let n=(await Promise.all(r.map(async i=>{try{let r=await this.renewFileAtHost(i,e,t);return{result:{host:i,status:"success",prevExpiryTime:r.prevExpiryTime,newExpiryTime:r.newExpiryTime,amount:r.amount}}}catch(e){return{result:{host:i,status:"error",error:e.message},raw:e}}}))).map(e=>e.result),s=n.filter(e=>"success"===e.status),a=Math.min(r.length,this.resilienceLevel);if(s.length<a){let e=n.map(e=>`${e.host}: ${"success"===e.status?"renewed":e.error??"unknown"}`).join("; ");throw new sg(`renewFile: only ${s.length} of ${a} required hosts renewed — ${e}`,n,a,s.length)}s.sort((e,t)=>(t.newExpiryTime??0)-(e.newExpiryTime??0));let o=s[0],l=s.reduce((e,t)=>e+(t.amount??0),0);return{status:"success",prevExpiryTime:o.prevExpiryTime,newExpiryTime:o.newExpiryTime,amount:l,results:n}}}class sm{networkPreset="mainnet";lookupResolver;constructor(e){this.networkPreset=e?.networkPreset??"mainnet",this.lookupResolver=new ss({networkPreset:this.networkPreset})}async resolve(e){let t=await this.lookupResolver.query({service:"ls_uhrp",query:{uhrpUrl:e}});if("output-list"!==t.type)throw Error("Lookup answer must be an output list");let i=[],r=Math.floor(Date.now()/1e3);for(let e of t.outputs){let t=rg.fromBEEF(e.beef),{fields:n}=i4.decode(t.outputs[e.outputIndex].lockingScript);new tN(n[3]).readVarIntNum()<r||i.push(tI(n[2]))}return i}async download(e){if(!sf(e))throw Error("Invalid parameter UHRP url");let t=tg(su(e)),i=await this.resolve(e);if(!Array.isArray(i)||0===i.length)throw Error("No one currently hosts this file!");for(let e of i)try{let i=await fetch(e,{method:"GET"});if(!i.ok||i.status>=400||null==i.body)continue;let r=i.body.getReader(),n=new eh,s=[],a=0;for(;;){let{done:e,value:t}=await r.read();if(e)break;n.update(Array.from(t)),s.push(t),a+=t.length}if(tg(n.digest())!==t)throw Error("Data integrity error: value of content does not match hash of the url given");let o=new Uint8Array(a),l=0;for(let e of s)o.set(e,l),l+=e.length;return{data:o,mimeType:i.headers.get("Content-Type")}}catch{continue}throw Error(`Unable to download content from ${e}`)}}let sb={name:"Unknown Identity",avatarURL:"XUUB8bbn9fEthk15Ge3zTQXypUShfC94vFjp65v7u5CQ8qkpxzst",identityKey:"",abbreviatedKey:"",badgeIconURL:"XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",badgeLabel:"Not verified by anyone you trust.",badgeClickURL:"https://bsv-blockchain.github.io/ts-sdk/reference/identity/"},sw={protocolID:[1,"identity"],keyID:"1",tokenAmount:1,outputIndex:0},sv={identiCert:"z40BOInXkI8m7f/wBrv4MJ09bZfzZbTj2fJqCtONqCY=",discordCert:"2TgqRC35B1zehGmB21xveZNc7i5iqHc0uxMb+1NMPW4=",phoneCert:"mffUklUzxbHr65xLohn0hRL0Tq2GjW1GYF/OPfzqJ6A=",xCert:"vdDWvftf1H+5+ZprUw123kjHlywH+v20aPQTuXgMpNc=",registrant:"YoPsbfR6YQczjzPdHCoGC7nJsOdPQR50+SYqcWpJ0y0=",emailCert:"exOl3KM0dIJ04EW5pZgbZmPag6MdJXd3/a1enmUU/BA=",anyone:"mfkOMfLDQmrr3SBxBQ5WeE+6Hy3VJRFq6w4A5Ljtlis=",self:"Hkge6X5JRxt1cWXtHLCrSTg6dCVTxjQJJ48iOYd7n3g=",coolCert:"AGfk/WrT1eBDXpz3mcw386Zww2HmqcIn3uY6x4Af1eo="},sI=[2,"contact"];class sk{cache=new Map;getItem(e){return this.cache.get(e)??null}setItem(e,t){this.cache.set(e,t)}removeItem(e){this.cache.delete(e)}clear(){this.cache.clear()}}class sS{wallet;cache=new sk;CONTACTS_CACHE_KEY="metanet-contacts";originator;inFlightLoad=null;knownEmpty=!1;constructor(e,t){this.wallet=e??new nW,this.originator=t}async getContacts(e,t=!1,i=1e3){if(t&&this.invalidate(),this.knownEmpty)return[];if(!t){let t=this.loadCachedContacts(e);if(null!==t)return t}this.inFlightLoad??=this.loadContactsFromWallet(i).finally(()=>{this.inFlightLoad=null});let r=await this.inFlightLoad;return null==e?r:r.filter(t=>t.identityKey===e)}invalidate(){this.cache.removeItem(this.CONTACTS_CACHE_KEY),this.knownEmpty=!1,this.inFlightLoad=null}async loadContactsFromWallet(e){let t=await this.wallet.listOutputs({basket:"contacts",include:"locking scripts",includeCustomInstructions:!0,tags:[],limit:e},this.originator);if(null==t.outputs||0===t.outputs.length)return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify([])),this.knownEmpty=!0,[];let i=await this.decryptContactOutputs(t.outputs);return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(i)),i}loadCachedContacts(e){let t=this.cache.getItem(this.CONTACTS_CACHE_KEY);if(null==t||""===t)return null;try{let i=JSON.parse(t);return null!=e?i.filter(t=>t.identityKey===e):i}catch(e){return console.warn("Invalid cached contacts JSON; will reload from chain",e),null}}async buildIdentityKeyTags(e){if(null==e)return[];let{hmac:t}=await this.wallet.createHmac({protocolID:sI,keyID:e,counterparty:"self",data:tm(e,"utf8")},this.originator);return[`identityKey ${tg(t)}`]}async decryptContactOutputs(e){let t=[];for(let i of e)try{if(null==i.lockingScript||null==i.customInstructions)continue;let e=i4.decode(ij.fromHex(i.lockingScript)),r=JSON.parse(i.customInstructions).keyID;t.push({keyID:r,ciphertext:e.fields[0]})}catch(e){console.warn("ContactsManager: Failed to decode contact output:",e)}let i=await Promise.allSettled(t.map(async e=>await this.wallet.decrypt({ciphertext:e.ciphertext,protocolID:sI,keyID:e.keyID,counterparty:"self"},this.originator))),r=[];for(let e of i)if("fulfilled"===e.status)try{r.push(JSON.parse(tI(e.value.plaintext)))}catch(e){console.warn("ContactsManager: Failed to parse contact data:",e)}else console.warn("ContactsManager: Failed to decrypt contact output:",e.reason);return r}async saveContact(e,t){let i=this.cache.getItem(this.CONTACTS_CACHE_KEY),r=null!=i&&""!==i?JSON.parse(i):await this.getContacts(),n={...e,metadata:t},s=r.findIndex(t=>t.identityKey===e.identityKey);s>=0?r[s]=n:r.push(n);let a=await this.hashIdentityKey(e.identityKey),o=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:[`identityKey ${tg(a)}`],limit:100},this.originator),{existingOutput:l,keyID:c}=await this.findExistingOutput(o,e.identityKey),h=await this.encryptAndLock(n,c);null!=l?await this.updateContactOutput(o,l,h,c,a,e):await this.createContactOutput(h,c,a,e),this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(r)),this.knownEmpty=!1,this.inFlightLoad=null}async hashIdentityKey(e){let{hmac:t}=await this.wallet.createHmac({protocolID:sI,keyID:e,counterparty:"self",data:tm(e,"utf8")},this.originator);return t}async findExistingOutput(e,t){let i=null,r=tS(ia(32));if(null==e.outputs)return{existingOutput:i,keyID:r};for(let n of e.outputs)try{let[s,a]=n.outpoint.split("."),o=rg.fromBEEF(e.BEEF,s),l=i4.decode(o.outputs[Number(a)].lockingScript);if(null==n.customInstructions)continue;r=JSON.parse(n.customInstructions).keyID;let{plaintext:c}=await this.wallet.decrypt({ciphertext:l.fields[0],protocolID:sI,keyID:r,counterparty:"self"},this.originator);if(JSON.parse(tI(c)).identityKey===t){i=n;break}}catch(e){}return{existingOutput:i,keyID:r}}async encryptAndLock(e,t){let{ciphertext:i}=await this.wallet.encrypt({plaintext:tm(JSON.stringify(e),"utf8"),protocolID:sI,keyID:t,counterparty:"self"},this.originator);return await new i4(this.wallet,this.originator).lock([i],sI,t,"self")}async updateContactOutput(e,t,i,r,n,s){let[a,o]=String(t.outpoint).split("."),l=`${a}.${o}`,c=new i4(this.wallet,this.originator),{signableTransaction:h}=await this.wallet.createAction({description:"Update Contact",inputBEEF:e.BEEF,inputs:[{outpoint:l,unlockingScriptLength:74,inputDescription:"Spend previous contact output"}],outputs:[{basket:"contacts",satoshis:1,lockingScript:i.toHex(),outputDescription:`Updated Contact: ${s.name??s.identityKey.slice(0,10)}`,tags:[`identityKey ${tg(n)}`],customInstructions:JSON.stringify({keyID:r})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==h)throw Error("Unable to update contact");let d=await c.unlock(sI,r,"self").sign(rg.fromBEEF(h.tx),0),{tx:u}=await this.wallet.signAction({reference:h.reference,spends:{0:{unlockingScript:d.toHex()}}},this.originator);if(null==u)throw Error("Failed to update contact output")}async createContactOutput(e,t,i,r){let{tx:n}=await this.wallet.createAction({description:"Add Contact",outputs:[{basket:"contacts",satoshis:1,lockingScript:e.toHex(),outputDescription:`Contact: ${r.name??r.identityKey.slice(0,10)}`,tags:[`identityKey ${tg(i)}`],customInstructions:JSON.stringify({keyID:t})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==n)throw Error("Failed to create contact output")}async removeContact(e){let t=this.cache.getItem(this.CONTACTS_CACHE_KEY);if(null!=t&&""!==t)try{let i=JSON.parse(t).filter(t=>t.identityKey!==e);this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(i)),this.knownEmpty=0===i.length}catch(e){console.warn("Failed to update cache after contact removal:",e)}this.inFlightLoad=null;let i=await this.buildIdentityKeyTags(e),r=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:i,limit:100},this.originator);if(null!=r.outputs)for(let t of r.outputs)try{if(await this.trySpendContactOutput(t,r,e))return}catch(e){}}async trySpendContactOutput(e,t,i){let[r,n]=String(e.outpoint).split("."),s=rg.fromBEEF(t.BEEF,r),a=i4.decode(s.outputs[Number(n)].lockingScript);if(null==e.customInstructions)return!1;let o=JSON.parse(e.customInstructions).keyID,{plaintext:l}=await this.wallet.decrypt({ciphertext:a.fields[0],protocolID:sI,keyID:o,counterparty:"self"},this.originator);if(JSON.parse(tI(l)).identityKey!==i)return!1;let c=`${r}.${n}`,h=new i4(this.wallet,this.originator),{signableTransaction:d}=await this.wallet.createAction({description:"Delete Contact",inputBEEF:t.BEEF,inputs:[{outpoint:c,unlockingScriptLength:74,inputDescription:"Spend contact output to delete"}],outputs:[],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==d)throw Error("Unable to delete contact");let u=await h.unlock(sI,o,"self").sign(rg.fromBEEF(d.tx),0),{tx:f}=await this.wallet.signAction({reference:d.reference,spends:{0:{unlockingScript:u.toHex()}}},this.originator);if(null==f)throw Error("Failed to delete contact output");return!0}}async function sE(){let e=globalThis.scheduler;return null!=e&&"function"==typeof e.yield?await e.yield():await new Promise(e=>setTimeout(e,0))}function sx(e){return void 0===e?{useContacts:!1,parallel:!1}:"boolean"==typeof e?{useContacts:e,parallel:!1}:{useContacts:e.overrideWithContacts??e.useContacts??!1,parallel:!0===e.parallel}}class sA{options;originator;wallet;contactsManager;constructor(e,t=sw,i){this.options=t,this.originator=i,this.originator=i,this.wallet=e??new nW,this.contactsManager=new sS(this.wallet,this.originator)}async publiclyRevealAttributes(e,t){if(0===Object.keys(e.fields).length)throw Error("Public reveal failed: Certificate has no fields to reveal!");if(0===t.length)throw Error("Public reveal failed: You must reveal at least one field!");try{let t=new r1(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature);await t.verify()}catch(e){throw Error("Public reveal failed: Certificate verification failed!")}let{keyringForVerifier:i}=await this.wallet.proveCertificate({certificate:e,fieldsToReveal:t,verifier:new ih(1).toPublicKey().toString()},this.originator),r=await new i4(this.wallet,this.originator).lock([tm(JSON.stringify({...e,keyring:i}))],this.options.protocolID,this.options.keyID,"anyone",!0,!0),{tx:n}=await this.wallet.createAction({description:"Create a new Identity Token",outputs:[{satoshis:this.options.tokenAmount,lockingScript:r.toHex(),outputDescription:"Identity Token"}],options:{randomizeOutputs:!1}},this.originator);if(void 0!==n){let e=new so(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network});return await e.broadcast(rg.fromAtomicBEEF(n))}throw Error("Public reveal failed: failed to create action!")}async resolveByIdentityKey(e,t=!1){let{useContacts:i,parallel:r}=sx(t);if(!i){let t=await this.wallet.discoverByIdentityKey(e,this.originator),i=t?.certificates??[];return await sA.parseIdentities(i)}if(!r){let t=await this.contactsManager.getContacts(e.identityKey);if(t.length>0)return t;let i=await this.wallet.discoverByIdentityKey(e,this.originator),r=i?.certificates??[];return await sA.parseIdentities(r)}let[n,s]=await Promise.all([this.contactsManager.getContacts(e.identityKey),this.wallet.discoverByIdentityKey(e,this.originator)]);if(n.length>0)return n;let a=s?.certificates??[];return await sA.parseIdentities(a)}async resolveByAttributes(e,t=!1){let{useContacts:i,parallel:r}=sx(t);if(!i){let t=await this.wallet.discoverByAttributes(e,this.originator),i=t?.certificates??[];return await sA.parseIdentities(i)}if(!r){let t=await this.contactsManager.getContacts(),i=this.matchContactsByAttributes(t,e);if(i.length>0)return i;let r=await this.wallet.discoverByAttributes(e,this.originator),n=r?.certificates??[];if(0===t.length)return await sA.parseIdentities(n);let s=new Map(t.map(e=>[e.identityKey,e]));return await sA.parseIdentitiesWithOverrides(n,s)}let[n,s]=await Promise.all([this.contactsManager.getContacts(),this.wallet.discoverByAttributes(e,this.originator)]),a=s?.certificates??[];if(0===n.length)return await sA.parseIdentities(a);let o=new Map(n.map(e=>[e.identityKey,e]));return await sA.parseIdentitiesWithOverrides(a,o)}matchContactsByAttributes(e,t){let i=t.attributes;if(null==i||"object"!=typeof i||Array.isArray(i))return[];let r=Object.entries(i).filter(([,e])=>"string"==typeof e&&e.length>0);return 0===r.length?[]:e.filter(e=>{let t={name:e.name,identityKey:e.identityKey};return r.every(([e,i])=>"string"==typeof t[e]&&t[e].toLowerCase()===i.toLowerCase())})}async revokeCertificateRevelation(e){let t=new ss({networkPreset:(await this.wallet.getNetwork({})).network}),i=await t.query({service:"ls_identity",query:{serialNumber:e}});if("output-list"!==i.type)throw Error("Failed to get lookup result");let r=new so(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network,requireAcknowledgmentFromAllHostsForTopics:[],requireAcknowledgmentFromAnyHostForTopics:[],requireAcknowledgmentFromSpecificHostsForTopics:{tm_identity:[]}});await sl(async()=>{let e=rg.fromBEEF(i.outputs[0].beef),t=`${e.id("hex")}.${this.options.outputIndex}`;if(void 0===e.outputs[this.options.outputIndex].lockingScript||void 0===t)throw Error("Failed to get locking script for revelation output!");let{signableTransaction:n}=await this.wallet.createAction({description:"Spend certificate revelation token",inputBEEF:i.outputs[0].beef,inputs:[{inputDescription:"Revelation token",outpoint:t,unlockingScriptLength:74}],options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1,noSend:!0}},this.originator);if(void 0===n)throw Error("Failed to create signable transaction");let s=rg.fromBEEF(n.tx),a=new i4(this.wallet,this.originator).unlock(this.options.protocolID,this.options.keyID,"anyone"),o=await a.sign(s,this.options.outputIndex),{tx:l}=await this.wallet.signAction({reference:n.reference,spends:{[this.options.outputIndex]:{unlockingScript:o.toHex()}},options:{acceptDelayedBroadcast:!1,noSend:!0}},this.originator);if(void 0===l)throw Error("Failed to sign transaction");await r.broadcast(rg.fromAtomicBEEF(l))},r)}async getContacts(e,t=!1,i=1e3){return await this.contactsManager.getContacts(e,t,i)}async saveContact(e,t){return await this.contactsManager.saveContact(e,t)}async removeContact(e){return await this.contactsManager.removeContact(e)}static async parseIdentities(e){let t=e.length;if(t<=32)return e.map(e=>sA.parseIdentity(e));let i=Array(t);for(let r=0;r<t;r++)i[r]=sA.parseIdentity(e[r]),(r+1)%32==0&&await sE();return i}static async parseIdentitiesWithOverrides(e,t){let i=e.length;if(i<=32)return e.map(e=>t.get(e.subject)??sA.parseIdentity(e));let r=Array(i);for(let n=0;n<i;n++){let i=e[n];r[n]=t.get(i.subject)??sA.parseIdentity(i),(n+1)%32==0&&await sE()}return r}static parseIdentity(e){let t,i,r,n,s,{type:a,decryptedFields:o,certifierInfo:l}=e;switch(a){case sv.xCert:t=o.userName,i=o.profilePhoto,r=`X account certified by ${l.name}`,n=l.iconUrl,s="https://socialcert.net";break;case sv.discordCert:t=o.userName,i=o.profilePhoto,r=`Discord account certified by ${l.name}`,n=l.iconUrl,s="https://socialcert.net";break;case sv.emailCert:t=o.email,i="XUTZxep7BBghAJbSBwTjNfmcsDdRFs5EaGEgkESGSgjJVYgMEizu",r=`Email certified by ${l.name}`,n=l.iconUrl,s="https://socialcert.net";break;case sv.phoneCert:t=o.phoneNumber,i="XUTLxtX3ELNUwRhLwL7kWNGbdnFM8WG2eSLv84J7654oH8HaJWrU",r=`Phone certified by ${l.name}`,n=l.iconUrl,s="https://socialcert.net";break;case sv.identiCert:t=`${o.firstName} ${o.lastName}`,i=o.profilePhoto,r=`Government ID certified by ${l.name}`,n=l.iconUrl,s="https://identicert.me";break;case sv.registrant:t=o.name,i=o.icon,r=`Entity certified by ${l.name}`,n=l.iconUrl,s="https://bsv-blockchain.github.io/ts-sdk/reference/identity/";break;case sv.coolCert:t="true"===o.cool?"Cool Person!":"Not cool!";break;case sv.anyone:t="Anyone",i="XUT4bpQ6cpBaXi1oMzZsXfpkWGbtp2JTUYAoN7PzhStFJ6wLfoeR",r="Represents the ability for anyone to access this information.",n="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",s="https://bsv-blockchain.github.io/ts-sdk/reference/identity/";break;case sv.self:t="You",i="XUT9jHGk2qace148jeCX5rDsMftkSGYKmigLwU2PLLBc7Hm63VYR",r="Represents your ability to access this information.",n="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",s="https://bsv-blockchain.github.io/ts-sdk/reference/identity/";break;default:{let e=sA.tryToParseGenericIdentity(a,o,l);t=e.name,i=e.avatarURL,r=e.badgeLabel,n=e.badgeIconURL,s=e.badgeClickURL}}return{name:t,avatarURL:i,abbreviatedKey:e.subject.length>0?`${e.subject.substring(0,10)}...`:"",identityKey:e.subject,badgeIconURL:n,badgeLabel:r,badgeClickURL:s}}static hasValue(e){return null!=e&&""!==e}static tryToParseGenericIdentity(e,t,i){let r,n,s,a=t.firstName,o=t.lastName;sA.hasValue(a)&&sA.hasValue(o)?r=`${a} ${o}`:sA.hasValue(a)?r=a:sA.hasValue(o)&&(r=o),n=sA.hasValue(t.name)?t.name:sA.hasValue(t.userName)?t.userName:void 0!==r?r:sA.hasValue(t.email)?t.email:sb.name,s=sA.hasValue(t.profilePhoto)?t.profilePhoto:sA.hasValue(t.avatar)?t.avatar:sA.hasValue(t.icon)?t.icon:sA.hasValue(t.photo)?t.photo:sb.avatarURL;let l=sA.hasValue(i?.name)?`${e} certified by ${String(i.name)}`:sb.badgeLabel;return{name:n,avatarURL:s,badgeLabel:l,badgeIconURL:sA.hasValue(i?.iconUrl)?i.iconUrl:sb.badgeIconURL,badgeClickURL:sb.badgeClickURL}}}class sT{wallet;originator;network;resolver;cachedIdentityKey;acceptDelayedBroadcast;constructor(e=new nW,t={},i){this.wallet=e,this.originator=i,this.acceptDelayedBroadcast=t.acceptDelayedBroadcast??!1,this.resolver=t.resolver??new ss}async getIdentityKey(){return this.cachedIdentityKey??=(await this.wallet.getPublicKey({identityKey:!0})).publicKey,this.cachedIdentityKey}async getNetwork(){return this.network??=(await this.wallet.getNetwork({})).network,this.network}async registerDefinition(e){let t=await this.getIdentityKey(),i=new i4(this.wallet,this.originator),r=this.buildPushDropFields(e,t),n=this.mapDefinitionTypeToWalletProtocol(e.definitionType),s=await i.lock(r,n,"1","anyone",!0),{tx:a}=await this.wallet.createAction({description:`Register a new ${e.definitionType} item`,outputs:[{satoshis:1,lockingScript:s.toHex(),outputDescription:`New ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===a)throw Error(`Failed to create ${e.definitionType} registration transaction!`);let o=new so([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await o.broadcast(rg.fromAtomicBEEF(a))}async resolve(e,t){let i=this.mapDefinitionTypeToServiceName(e),r=await this.resolver.query({service:i,query:t});if("output-list"!==r.type)return[];let n=[];for(let t of r.outputs)try{let i=rg.fromBEEF(t.beef).outputs[t.outputIndex].lockingScript,r=await this.parseLockingScript(e,i);n.push(r)}catch{}return n}async listOwnRegistryEntries(e){let t=this.mapDefinitionTypeToBasketName(e),{outputs:i,BEEF:r}=await this.wallet.listOutputs({basket:t,include:"entire transactions"}),n=[];for(let t of i)if(t.spendable)try{let[i,s]=t.outpoint.split("."),a=rg.fromBEEF(r,i).outputs[Number(s)].lockingScript,o=await this.parseLockingScript(e,a);n.push({...o,txid:i,outputIndex:Number(s),satoshis:t.satoshis,lockingScript:a.toHex(),beef:r})}catch{}return n}async removeDefinition(e){let t;if(void 0===e.txid||void 0===e.outputIndex||void 0===e.lockingScript)throw Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");let i=await this.getIdentityKey();if(e.registryOperator!==i)throw Error("This registry token does not belong to the current wallet.");t="basket"===e.definitionType?e.basketID:"protocol"===e.definitionType?e.name:"certificate"===e.definitionType?e.name??e.type:"unknown";let r=`${e.txid}.${e.outputIndex}`,{signableTransaction:n}=await this.wallet.createAction({description:`Remove ${e.definitionType} item: ${t}`,inputBEEF:e.beef,inputs:[{outpoint:r,unlockingScriptLength:74,inputDescription:`Removing ${e.definitionType} token`}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===n)throw Error("Failed to create signable transaction.");let s=rg.fromAtomicBEEF(n.tx),a=new i4(this.wallet,this.originator).unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone"),o=await a.sign(s,0),{tx:l}=await this.wallet.signAction({reference:n.reference,spends:{0:{unlockingScript:o.toHex()}},options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if(void 0===l)throw Error("Failed to finalize the transaction signature.");let c=new so([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await c.broadcast(rg.fromAtomicBEEF(l))}async updateDefinition(e,t){let i;if(void 0===e.txid||void 0===e.outputIndex||void 0===e.lockingScript)throw Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");if(e.definitionType!==t.definitionType)throw Error(`Cannot change definition type from ${e.definitionType} to ${t.definitionType}`);let r=await this.getIdentityKey();if(e.registryOperator!==r)throw Error("This registry token does not belong to the current wallet.");i="basket"===e.definitionType?e.basketID:"protocol"===e.definitionType?e.name:"certificate"===e.definitionType?e.name??e.type:"unknown";let n=new i4(this.wallet,this.originator),s=this.buildPushDropFields(t,r),a=this.mapDefinitionTypeToWalletProtocol(t.definitionType),o=await n.lock(s,a,"1","anyone",!0),l=`${e.txid}.${e.outputIndex}`,{signableTransaction:c}=await this.wallet.createAction({description:`Update ${e.definitionType} item: ${i}`,inputBEEF:e.beef,inputs:[{outpoint:l,unlockingScriptLength:74,inputDescription:`Updating ${e.definitionType} token`}],outputs:[{satoshis:1,lockingScript:o.toHex(),outputDescription:`Updated ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===c)throw Error("Failed to create signable transaction.");let h=rg.fromAtomicBEEF(c.tx),d=n.unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone"),u=await d.sign(h,0),{tx:f}=await this.wallet.signAction({reference:c.reference,spends:{0:{unlockingScript:u.toHex()}},options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if(void 0===f)throw Error("Failed to finalize the transaction signature.");let p=new so([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await p.broadcast(rg.fromAtomicBEEF(f))}buildPushDropFields(e,t){let i;switch(e.definitionType){case"basket":i=[e.basketID,e.name,e.iconURL,e.description,e.documentationURL];break;case"protocol":i=[JSON.stringify(e.protocolID),e.name,e.iconURL,e.description,e.documentationURL];break;case"certificate":i=[e.type,e.name,e.iconURL,e.description,e.documentationURL,JSON.stringify(e.fields)];break;default:throw Error("Unsupported definition type")}return i.push(t),i.map(e=>tm(e))}async parseLockingScript(e,t){let i,r,n=i4.decode(t);if(0===n.fields.length)throw Error("Not a valid registry pushdrop script.");switch(e){case"basket":{if(7!==n.fields.length)throw Error("Unexpected field count for basket type.");let[e,t,s,a,o,l]=n.fields;i=tI(l),r={definitionType:"basket",basketID:tI(e),name:tI(t),iconURL:tI(s),description:tI(a),documentationURL:tI(o)};break}case"protocol":{if(7!==n.fields.length)throw Error("Unexpected field count for protocol type.");let[e,t,s,a,o,l]=n.fields;i=tI(l),r={definitionType:"protocol",protocolID:sO(tI(e)),name:tI(t),iconURL:tI(s),description:tI(a),documentationURL:tI(o)};break}case"certificate":{if(8!==n.fields.length)throw Error("Unexpected field count for certificate type.");let[e,t,s,a,o,l,c]=n.fields;i=tI(c);let h={};try{h=JSON.parse(tI(l))}catch{}r={definitionType:"certificate",type:tI(e),name:tI(t),iconURL:tI(s),description:tI(a),documentationURL:tI(o),fields:h};break}default:throw Error(`Unsupported definition type: ${e}`)}return{...r,registryOperator:i}}mapDefinitionTypeToWalletProtocol(e){switch(e){case"basket":return[1,"basketmap"];case"protocol":return[1,"protomap"];case"certificate":return[1,"certmap"];default:throw Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToBasketName(e){switch(e){case"basket":return"basketmap";case"protocol":return"protomap";case"certificate":return"certmap";default:throw Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToTopic(e){switch(e){case"basket":return"tm_basketmap";case"protocol":return"tm_protomap";case"certificate":return"tm_certmap";default:throw Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToServiceName(e){switch(e){case"basket":return"ls_basketmap";case"protocol":return"ls_protomap";case"certificate":return"ls_certmap";default:throw Error(`Unknown definition type: ${e}`)}}}function sO(e){let t=JSON.parse(e);if(!Array.isArray(t)||2!==t.length)throw Error("Invalid wallet protocol format.");let[i,r]=t;if(![0,1,2].includes(i))throw Error("Invalid security level.");if("string"!=typeof r)throw TypeError("Invalid protocolID");return[i,r]}class sP{wallet;context;encrypt;originator;acceptDelayedBroadcast=!1;keyLocks=new Map;constructor(e=new nW,t="kvstore default",i=!0,r,n=!1){if("string"!=typeof t||t.length<1)throw Error("A context in which to operate is required.");this.wallet=e,this.context=t,this.encrypt=i,this.originator=r,this.acceptDelayedBroadcast=n}async queueOperationOnKey(e){let t=this.keyLocks.get(e);null==t&&(t=[],this.keyLocks.set(e,t));let i=()=>{},r=new Promise(e=>{i=e,null!=t&&t.push(e)});return 1===t.length&&i(),await r,t}finishOperationOnKey(e,t){t.shift(),t.length>0&&t[0]()}getProtocol(e){return{protocolID:[2,this.context],keyID:e}}async getOutputs(e,t){return await this.wallet.listOutputs({basket:this.context,tags:[e],tagQueryMode:"all",include:"entire transactions",limit:t},this.originator)}async get(e,t){let i=await this.queueOperationOnKey(e);try{return(await this.lookupValue(e,t,5)).value}finally{this.finishOperationOnKey(e,i)}}getLockingScript(e,t){let[i,r]=e.outpoint.split("."),n=t.findTxid(i)?.tx;if(null==n)throw Error(`beef must contain txid ${i}`);return n.outputs[Number(r)].lockingScript}async lookupValue(e,t,i){let r,n=await this.getOutputs(e,i),s={value:t,outpoint:void 0,lor:n},{outputs:a}=n;if(0===a.length)return s;let o=a.at(-1);s.outpoint=o.outpoint;try{if(void 0===n.BEEF)throw Error("entire transactions listOutputs option must return valid BEEF");let e=this.getLockingScript(o,rp.fromBinary(n.BEEF)),t=i4.decode(e);if(t.fields.length<1||t.fields.length>2)throw Error("Invalid token.");r=t.fields[0]}catch(e){throw Error(`Invalid value found. You need to call set to collapse the corrupted state (or relinquish the corrupted ${a[0].outpoint} output from the ${this.context} basket) before you can get this value again. Original error: ${e instanceof Error?e.message:String(e)}`)}if(this.encrypt){let{plaintext:t}=await this.wallet.decrypt({...this.getProtocol(e),ciphertext:r},this.originator);s.value=tI(t)}else s.value=tI(r);return s}getInputs(e){let t=[];for(let i of e)t.push({outpoint:i.outpoint,unlockingScriptLength:74,inputDescription:"Previous key-value token"});return t}async getSpends(e,t,i,r){let n=this.getProtocol(e),s=rg.fromAtomicBEEF(r),a={};for(let[e]of t.entries()){let t=i.unlock(n.protocolID,n.keyID,"self"),r=await t.sign(s,e);a[e]={unlockingScript:r.toHex()}}return a}async set(e,t){let i=await this.queueOperationOnKey(e);try{let i,r=await this.lookupValue(e,void 0,10);if(r.value===t){if(void 0===r.outpoint)throw Error("outpoint must be valid when value is valid and unchanged");return r.outpoint}let n=this.getProtocol(e),s=tm(t,"utf8");if(this.encrypt){let{ciphertext:e}=await this.wallet.encrypt({...n,plaintext:s},this.originator);s=e}let a=new i4(this.wallet,this.originator),o=await a.lock([s],n.protocolID,n.keyID,"self"),{outputs:l,BEEF:c}=r.lor;try{let t=this.getInputs(l),{txid:r,signableTransaction:n}=await this.wallet.createAction({description:`Update ${e} in ${this.context}`,inputBEEF:c,inputs:t,outputs:[{basket:this.context,tags:[e],lockingScript:o.toHex(),satoshis:1,outputDescription:"Key-value token"}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(l.length>0&&"object"!=typeof n)throw Error("Wallet did not return a signable transaction when expected.");if(null==n)i=`${r}.0`;else{let t=await this.getSpends(e,l,a,n.tx),{txid:r}=await this.wallet.signAction({reference:n.reference,spends:t},this.originator);i=`${r}.0`}}catch(t){throw Error(`There are ${l.length} outputs with tag ${e} that cannot be unlocked. Original error: ${t instanceof Error?t.message:String(t)}`)}return i}finally{this.finishOperationOnKey(e,i)}}async remove(e){let t=await this.queueOperationOnKey(e);try{let t=[];for(;;){let{outputs:i,BEEF:r,totalOutputs:n}=await this.getOutputs(e);if(i.length>0){let s=new i4(this.wallet,this.originator);try{let n=this.getInputs(i),{signableTransaction:a}=await this.wallet.createAction({description:`Remove ${e} in ${this.context}`,inputBEEF:r,inputs:n,options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if("object"!=typeof a)throw TypeError("Wallet did not return a signable transaction when expected.");let o=await this.getSpends(e,i,s,a.tx),{txid:l}=await this.wallet.signAction({reference:a.reference,spends:o},this.originator);if(void 0===l)throw Error("signAction must return a valid txid");t.push(l)}catch(t){throw Error(`There are ${n} outputs with tag ${e} that cannot be unlocked. Original error: ${t instanceof Error?t.message:String(t)}`)}}if(i.length===n)break}return t}finally{this.finishOperationOnKey(e,t)}}}class sN{interpreter;debug;historyCache;interpreterVersion;ctxKeyFn;constructor(e,t){this.interpreter=e,this.debug=t?.debug??!1,this.historyCache=t?.historyCache,this.interpreterVersion=t?.interpreterVersion??"v1",this.ctxKeyFn=t?.ctxKeyFn??(e=>{try{return JSON.stringify(e??null)}catch{return""}})}historyKey(e,t){let i=e.id("hex"),r=this.ctxKeyFn(t);return`${this.interpreterVersion}|${i}|${r}`}async buildHistory(e,t){if(null!=this.historyCache){let i=this.historyKey(e,t);if(this.historyCache.has(i)){let e=this.historyCache.get(i);if(null!=e)return this.debug&&console.log("[Historian] History cache hit:",i),e.slice()}}let i=[],r=new Set,n=async e=>{let s=e.id("hex");if(r.has(s)){this.debug&&console.log(`[Historian] Skipping already visited transaction: ${s}`);return}r.add(s),this.debug&&console.log(`[Historian] Processing transaction: ${s}`);for(let r=0;r<e.outputs.length;r++)try{let n=await Promise.resolve(this.interpreter(e,r,t));void 0!==n&&(i.push(n),this.debug&&console.log("[Historian] Added value to history:",n))}catch(e){this.debug&&console.log(`[Historian] Failed to interpret output ${r}:`,e)}for(let t of e.inputs)null!=t.sourceTransaction?await n(t.sourceTransaction):this.debug&&console.log("[Historian] Input missing sourceTransaction, skipping")};await n(e);let s=i.toReversed();if(null!=this.historyCache){let i=this.historyKey(e,t);this.historyCache.set(i,Object.freeze(s.slice())),this.debug&&console.log("[Historian] History cached:",i)}return s}}let s_={protocolID:0,key:1,value:2,controller:3,tags:4,signature:5},sR=async(e,t,i)=>{try{let r=e.outputs[t];if(r?.lockingScript==null||i?.key==null)return;let n=i4.decode(r.lockingScript),s=Object.keys(s_).length,a=n.fields.length===s;if(n.fields.length!==s-1&&!a)return;let o=tI(n.fields[s_.key]),l=tI(n.fields[s_.protocolID]);if(o!==i.key||l!==JSON.stringify(i.protocolID))return;try{return tI(n.fields[s_.value])}catch{return}}catch{return}},sC={protocolID:[1,"kvstore"],serviceName:"ls_kvstore",tokenAmount:1,topics:["tm_kvstore"],networkPreset:"mainnet",acceptDelayedBroadcast:!1,overlayBroadcast:!1,tokenSetDescription:"",tokenUpdateDescription:"",tokenRemovalDescription:""};class sB{wallet;config;historian;lookupResolver;topicBroadcaster;keyLocks=new Map;cachedIdentityKey=null;constructor(e={}){this.config={...sC,...e},this.wallet=e.wallet??new nW,this.historian=new sN(sR),this.lookupResolver=new ss({networkPreset:this.config.networkPreset}),this.topicBroadcaster=new so(this.config.topics,{networkPreset:this.config.networkPreset})}async get(e,t={}){if(this.validateQuerySelectors(e),null!=e.key&&null!=e.controller){let i=await this.queryOverlay(e,t);return i.length>0?i[0]:void 0}return await this.queryOverlay(e,t)}validateQuerySelectors(e){if(!("string"==typeof e.key&&e.key.length>0||"string"==typeof e.controller&&e.controller.length>0||Array.isArray(e.protocolID)&&2===e.protocolID.length||Array.isArray(e.tags)&&e.tags.length>0))throw Error("Must specify at least one selector: key, controller, protocolID, or tags")}async set(e,t,i={}){if("string"!=typeof e||0===e.length)throw Error("Key must be a non-empty string.");if("string"!=typeof t)throw TypeError("Value must be a string.");let r=await this.getIdentityKey(),n=await this.queueOperationOnKey(e),s=i.protocolID??this.config.protocolID,a=null!=i.tokenSetDescription&&""!==i.tokenSetDescription?i.tokenSetDescription:`Create KVStore value for ${e}`,o=null!=i.tokenUpdateDescription&&""!==i.tokenUpdateDescription?i.tokenUpdateDescription:`Update KVStore value for ${e}`,l=i.tokenAmount??this.config.tokenAmount,c=i.tags??[];try{let i=new i4(this.wallet,this.config.originator),n=[tm(JSON.stringify(s),"utf8"),tm(e,"utf8"),tm(t,"utf8"),tm(r,"hex")];c.length>0&&n.push(tm(JSON.stringify(c),"utf8"));let h=await i.lock(n,s??this.config.protocolID,tI(tm(e,"utf8")),"anyone",!0);return await sl(async()=>{let t=await this.queryOverlay({key:e,controller:r},{includeToken:!0}),n=t.length>0?t[0].token:void 0;if(null==n){let{tx:e}=await this.wallet.createAction({description:a,outputs:[{satoshis:l??this.config.tokenAmount,lockingScript:h.toHex(),outputDescription:"KVStore token"}],options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast,randomizeOutputs:!1}},this.config.originator);if(null==e)throw Error("Failed to create transaction");let t=rg.fromAtomicBEEF(e);return await this.submitToOverlay(t),`${t.id("hex")}.0`}{let t=[{outpoint:`${n.txid}.${n.outputIndex}`,unlockingScriptLength:74,inputDescription:"Previous KVStore token"}],r=n.beef,{signableTransaction:s}=await this.wallet.createAction({description:o,inputBEEF:r.toBinary(),inputs:t,outputs:[{satoshis:l??this.config.tokenAmount,lockingScript:h.toHex(),outputDescription:"KVStore token"}],options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast,randomizeOutputs:!1}},this.config.originator);if(null==s)throw Error("Unable to create update transaction");let a=rg.fromAtomicBEEF(s.tx),c=i.unlock(this.config.protocolID,e,"anyone"),d=await c.sign(a,0),{tx:u}=await this.wallet.signAction({reference:s.reference,spends:{0:{unlockingScript:d.toHex()}},options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==u)throw Error("Unable to finalize update transaction");let f=rg.fromAtomicBEEF(u);return await this.submitToOverlay(f),`${f.id("hex")}.0`}},this.topicBroadcaster)}finally{n.length>0&&this.finishOperationOnKey(e,n)}}async remove(e,t,i={}){if("string"!=typeof e||0===e.length)throw Error("Key must be a non-empty string.");let r=await this.getIdentityKey(),n=await this.queueOperationOnKey(e),s=i.protocolID??this.config.protocolID,a=null!=i.tokenRemovalDescription&&""!==i.tokenRemovalDescription?i.tokenRemovalDescription:`Remove KVStore value for ${e}`;try{let i=new i4(this.wallet,this.config.originator);return await sl(async()=>{let n=await this.queryOverlay({key:e,controller:r},{includeToken:!0});if(0===n.length||null==n[0].token)throw Error("The item did not exist, no item was deleted.");let o=n[0].token,l=[{outpoint:`${o.txid}.${o.outputIndex}`,unlockingScriptLength:74,inputDescription:"KVStore token to remove"}],{signableTransaction:c}=await this.wallet.createAction({description:a,inputBEEF:o.beef.toBinary(),inputs:l,outputs:t,options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,randomizeOutputs:!1,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==c)throw Error("Unable to create removal transaction");let h=rg.fromAtomicBEEF(c.tx),d=i.unlock(s??this.config.protocolID,e,"anyone"),u=await d.sign(h,0),{tx:f}=await this.wallet.signAction({reference:c.reference,spends:{0:{unlockingScript:u.toHex()}},options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==f)throw Error("Unable to finalize removal transaction");let p=rg.fromAtomicBEEF(f);return await this.submitToOverlay(p),p.id("hex")},this.topicBroadcaster)}finally{n.length>0&&this.finishOperationOnKey(e,n)}}async queueOperationOnKey(e){let t=this.keyLocks.get(e);null==t&&(t=[],this.keyLocks.set(e,t));let i=()=>{},r=new Promise(e=>{i=e,null!=t&&t.push(e)});return 1===t.length&&i(),await r,t}finishOperationOnKey(e,t){t.shift(),t.length>0?t[0]():this.keyLocks.delete(e)}async getIdentityKey(){return this.cachedIdentityKey??=(await this.wallet.getPublicKey({identityKey:!0},this.config.originator)).publicKey,this.cachedIdentityKey}async queryOverlay(e,t={}){let i=await this.lookupResolver.query({service:t.serviceName??this.config.serviceName,query:e});if("output-list"!==i.type||0===i.outputs.length)return[];let r=[];for(let e of i.outputs)try{let i,n=rg.fromBEEF(e.beef),s=n.outputs[e.outputIndex],a=i4.decode(s.lockingScript),o=Object.keys(s_).length,l=a.fields.length===o;if(a.fields.length!==o-1&&!l)continue;let c=new rG("anyone"),h=a.fields.pop();try{await c.verifySignature({data:a.fields.flat(),signature:h,counterparty:tg(a.fields[s_.controller]),protocolID:JSON.parse(tI(a.fields[s_.protocolID])),keyID:tI(a.fields[s_.key])})}catch(e){continue}if(l&&null!=a.fields[s_.tags])try{i=JSON.parse(tI(a.fields[s_.tags]))}catch(e){i=void 0}let d={key:tI(a.fields[s_.key]),value:tI(a.fields[s_.value]),controller:tg(a.fields[s_.controller]),protocolID:JSON.parse(tI(a.fields[s_.protocolID])),tags:i};!0===t.includeToken&&(d.token={txid:n.id("hex"),outputIndex:e.outputIndex,beef:rp.fromBinary(e.beef),satoshis:s.satoshis??1}),!0===t.history&&(d.history=await this.historian.buildHistory(n,{key:d.key,protocolID:d.protocolID})),r.push(d)}catch(e){continue}return r}async submitToOverlay(e){return await this.topicBroadcaster.broadcast(e)}}let sU=sB,sF={new:["identityRequested","invoiced","settled","terminated","errored"],identityRequested:["identityResponded","identityAcknowledged","invoiced","settled","terminated","errored"],identityResponded:["identityAcknowledged","invoiced","settled","terminated","errored"],identityAcknowledged:["invoiced","settled","terminated","errored"],invoiced:["identityRequested","identityResponded","identityAcknowledged","settled","terminated","errored"],settled:["receipted","terminated","errored"],receipted:["terminated","errored"],terminated:["errored"],errored:[]},sD={namespace:"bsv",code:"sat",decimals:0},sL="remittance_inbox";class sV{wallet;comms;cfg;messageBox;now;threadIdFactory;moduleRegistry;runtime;eventListeners;stateWaiters;eventHandlers;defaultPaymentOptionId;threads;myIdentityKey;constructor(e,t,i,r=[]){this.cfg=e,this.wallet=t,this.comms=i,this.messageBox=e.messageBox??sL,this.now=e.now??(()=>Date.now()),this.threadIdFactory=e.threadIdFactory??sK,this.moduleRegistry=new Map(e.remittanceModules.map(e=>[e.id,e])),this.eventListeners=new Set,this.stateWaiters=new Map,this.eventHandlers=e.events,"function"==typeof e.onEvent&&this.eventListeners.add(e.onEvent),this.runtime={identityOptions:e.options?.identityOptions??{makerRequestIdentity:"never",takerRequestIdentity:"never"},receiptProvided:e.options?.receiptProvided??!0,autoIssueReceipt:e.options?.autoIssueReceipt??!0,invoiceExpirySeconds:e.options?.invoiceExpirySeconds??3600,identityTimeoutMs:e.options?.identityTimeoutMs??3e4,identityPollIntervalMs:e.options?.identityPollIntervalMs??500},this.threads=r.map(e=>this.ensureThreadState(e))}async init(){if("function"!=typeof this.cfg.stateLoader)return;let e=await this.cfg.stateLoader();"object"==typeof e&&(this.loadState(e),"string"==typeof e.defaultPaymentOptionId&&(this.defaultPaymentOptionId=e.defaultPaymentOptionId),await this.refreshMyIdentityKey())}onEvent(e){return this.eventListeners.add(e),()=>{this.eventListeners.delete(e)}}preselectPaymentOption(e){this.defaultPaymentOptionId=e}saveState(){return{v:1,threads:JSON.parse(JSON.stringify(this.threads)),defaultPaymentOptionId:this.defaultPaymentOptionId}}loadState(e){if(1!==e.v)throw Error("Unsupported RemittanceManagerState version");this.threads=(e.threads??[]).map(e=>this.ensureThreadState(e)),this.defaultPaymentOptionId=e.defaultPaymentOptionId}async persistState(){null!=this.cfg.stateSaver&&await this.cfg.stateSaver(this.saveState())}async syncThreads(e){for(let t of(await this.refreshMyIdentityKey(),await this.comms.listMessages({messageBox:this.messageBox,host:e})))await this.handleInboundMessage(t)}async startListening(e){if("function"!=typeof this.comms.listenForLiveMessages)throw TypeError("CommsLayer does not support live message listening");await this.comms.listenForLiveMessages({messageBox:this.messageBox,overrideHost:e,onMessage:e=>{this.handleInboundMessage(e)}})}async sendInvoice(e,t,i){await this.refreshMyIdentityKey();let r=this.threadIdFactory(),n=this.now(),s=this.requireMyIdentityKey("sendInvoice requires the wallet to provide an identity key"),a={threadId:r,counterparty:e,myRole:"maker",theirRole:"taker",createdAt:n,updatedAt:n,state:"new",stateLog:[],processedMessageIds:[],protocolLog:[],identity:{certsSent:[],certsReceived:[],requestSent:!1,responseSent:!1,acknowledgmentSent:!1,acknowledgmentReceived:!1},flags:{hasIdentified:!1,hasInvoiced:!1,hasPaid:!1,hasReceipted:!1,error:!1}};this.threads.push(a),this.emitEvent({type:"threadCreated",threadId:a.threadId,thread:a}),a.identity.responseSent&&!a.flags.hasIdentified&&await this.waitForIdentityAcknowledgment(r,{timeoutMs:this.runtime.identityTimeoutMs,pollIntervalMs:this.runtime.identityPollIntervalMs}),this.shouldRequestIdentity(a,"beforeInvoicing")&&await this.ensureIdentityExchange(a,i);let o=await this.composeInvoice(r,s,e,t);for(let e of(a.invoice=o,a.flags.hasInvoiced=!0,this.transitionThreadState(a,"invoiced","invoice created"),this.moduleRegistry.values())){if("function"!=typeof e.createOption)continue;let t=await e.createOption({threadId:r,invoice:o},this.moduleContext());o.options[e.id]=t}let l=this.makeEnvelope("invoice",r,o),c=await this.sendEnvelope(e,l,i);return a.protocolLog.push({direction:"out",envelope:l,transportMessageId:c}),this.emitEvent({type:"invoiceSent",threadId:a.threadId,invoice:o}),a.updatedAt=this.now(),await this.persistState(),new sM(this,r)}async sendInvoiceForThread(e,t,i){await this.refreshMyIdentityKey();let r=this.getThreadOrThrow(e);if(r.flags.error)throw Error("Thread is in error state");if("maker"!==r.myRole)throw Error("Only makers can send invoices");if(null!=r.invoice)throw Error("Thread already has an invoice");r.identity.responseSent&&!r.flags.hasIdentified&&await this.waitForIdentityAcknowledgment(e,{timeoutMs:this.runtime.identityTimeoutMs,pollIntervalMs:this.runtime.identityPollIntervalMs}),this.shouldRequestIdentity(r,"beforeInvoicing")&&await this.ensureIdentityExchange(r,i);let n=this.requireMyIdentityKey("sendInvoice requires the wallet to provide an identity key"),s=await this.composeInvoice(e,n,r.counterparty,t);for(let t of(r.invoice=s,r.flags.hasInvoiced=!0,this.transitionThreadState(r,"invoiced","invoice created"),this.moduleRegistry.values())){if("function"!=typeof t.createOption)continue;let i=await t.createOption({threadId:e,invoice:s},this.moduleContext());s.options[t.id]=i}let a=this.makeEnvelope("invoice",e,s),o=await this.sendEnvelope(r.counterparty,a,i);return r.protocolLog.push({direction:"out",envelope:a,transportMessageId:o}),this.emitEvent({type:"invoiceSent",threadId:r.threadId,invoice:s}),r.updatedAt=this.now(),await this.persistState(),new sM(this,e)}findInvoicesPayable(e){let t="string"==typeof e&&e.length>0;return this.threads.filter(e=>"taker"===e.myRole&&null!=e.invoice&&null==e.settlement&&!e.flags.error).filter(i=>!t||i.counterparty===e).map(e=>new sM(this,e.threadId))}findReceivableInvoices(e){let t="string"==typeof e&&e.length>0;return this.threads.filter(e=>"maker"===e.myRole&&null!=e.invoice&&null==e.settlement&&!e.flags.error).filter(i=>!t||i.counterparty===e).map(e=>new sM(this,e.threadId))}async pay(e,t,i){await this.refreshMyIdentityKey();let r=this.getThreadOrThrow(e);if(null==r.invoice)throw Error("Thread has no invoice to pay");if(r.flags.error)throw Error("Thread is in error state");if(null!=r.settlement)throw Error("Invoice already paid (settlement exists)");r.identity.responseSent&&!r.flags.hasIdentified&&await this.waitForIdentityAcknowledgment(e,{timeoutMs:this.runtime.identityTimeoutMs,pollIntervalMs:this.runtime.identityPollIntervalMs}),this.shouldRequestIdentity(r,"beforeSettlement")&&await this.ensureIdentityExchange(r,i);let n=r.invoice.expiresAt;if("number"==typeof n&&this.now()>n)throw Error("Invoice is expired");let s=t??this.defaultPaymentOptionId??Object.keys(r.invoice.options)[0];if(null==s||""===s)throw Error("No remittance options available on invoice");let a=this.moduleRegistry.get(s);if(null==a)throw Error(`No configured remittance module for option: ${s}`);let o=r.invoice.options[s],l=this.requireMyIdentityKey("pay() requires the wallet to provide an identity key"),c=await a.buildSettlement({threadId:e,invoice:r.invoice,option:o,note:r.invoice.note},this.moduleContext());if("terminate"===c.action){let e=c.termination;return await this.sendTermination(r,r.counterparty,e.message,e.details,e.code),await this.persistState(),e}let h={kind:"settlement",threadId:e,moduleId:a.id,optionId:s,sender:l,createdAt:this.now(),artifact:c.artifact,note:r.invoice.note},d=this.makeEnvelope("settlement",e,h),u=await this.sendEnvelope(r.invoice.payee,d,i);if(r.protocolLog.push({direction:"out",envelope:d,transportMessageId:u}),this.emitEvent({type:"settlementSent",threadId:r.threadId,settlement:h}),r.settlement=h,r.flags.hasPaid=!0,this.transitionThreadState(r,"settled","settlement sent"),r.updatedAt=this.now(),await this.persistState(),this.runtime.receiptProvided)return await this.waitForReceipt(e)}async waitForReceipt(e,t={}){let i=t.timeoutMs??3e4,r=t.pollIntervalMs??500,n=this.now();for(;this.now()-n<i;){let t=this.getThreadOrThrow(e);if("object"==typeof t.receipt)return t.receipt;if("object"==typeof t.termination)return t.termination;await this.syncThreads(),await sq(r)}throw Error("Timed out waiting for receipt")}async waitForState(e,t,i={}){let r,n,s=i.timeoutMs??3e4,a=i.pollIntervalMs??500,o=this.now(),l=this.getThreadOrThrow(e);if(l.state===t)return l;if("terminated"===l.state||"errored"===l.state)throw Error(`Thread entered terminal state: ${l.state}`);let c=!1,h=!1,d={state:t,resolve:()=>{c||h||(c=!0,r())},reject:e=>{c||h||(c=!0,n(e))}},u=new Promise((t,i)=>{r=t,n=i;let s=this.stateWaiters.get(e)??[];s.push(d),this.stateWaiters.set(e,s)}),f=()=>{let t=this.stateWaiters.get(e);if(null==t)return;let i=t.filter(e=>e!==d);0===i.length?this.stateWaiters.delete(e):this.stateWaiters.set(e,i)},p=(async()=>{for(;this.now()-o<s;){if(c)return;let i=this.getThreadOrThrow(e);if(i.state===t)return void this.resolveStateWaiters(e,t);if("terminated"===i.state||"errored"===i.state)throw Error(`Thread entered terminal state: ${i.state}`);await this.syncThreads(),await sq(a)}})();if(await Promise.race([u,p]).catch(e=>{throw f(),e}),this.now()-o>=s&&!c)throw h=!0,f(),Error(`Timed out waiting for state: ${t}`);return f(),this.getThreadOrThrow(e)}async waitForIdentity(e,t){return await this.waitForState(e,"identityAcknowledged",t)}async waitForSettlement(e,t={}){let i=t.timeoutMs??3e4,r=t.pollIntervalMs??500,n=this.now();for(;this.now()-n<i;){let t=this.getThreadOrThrow(e);if("object"==typeof t.settlement)return t.settlement;if("object"==typeof t.termination)return t.termination;await this.syncThreads(),await sq(r)}throw Error("Timed out waiting for settlement")}async sendUnsolicitedSettlement(e,t,i){await this.refreshMyIdentityKey();let r=this.moduleRegistry.get(t.moduleId);if(null==r)throw Error(`No configured remittance module for option: ${t.moduleId}`);if(!r.allowUnsolicitedSettlements)throw Error(`Remittance module ${t.moduleId} does not allow unsolicited settlements`);let n=this.threadIdFactory(),s=this.now(),a=this.requireMyIdentityKey("sendUnsolicitedSettlement requires the wallet to provide an identity key"),o={threadId:n,counterparty:e,myRole:"taker",theirRole:"maker",createdAt:s,updatedAt:s,state:"new",stateLog:[],processedMessageIds:[],protocolLog:[],identity:{certsSent:[],certsReceived:[],requestSent:!1,responseSent:!1,acknowledgmentSent:!1,acknowledgmentReceived:!1},flags:{hasIdentified:!1,hasInvoiced:!1,hasPaid:!1,hasReceipted:!1,error:!1}};this.threads.push(o),this.emitEvent({type:"threadCreated",threadId:o.threadId,thread:o}),this.shouldRequestIdentity(o,"beforeSettlement")&&await this.ensureIdentityExchange(o,i);let l=await r.buildSettlement({threadId:n,option:t.option,note:t.note},this.moduleContext());if("terminate"===l.action)return await this.sendTermination(o,e,l.termination.message,l.termination.details,l.termination.code),await this.persistState(),new sH(this,n);let c={kind:"settlement",threadId:n,moduleId:r.id,optionId:t.optionId??r.id,sender:a,createdAt:this.now(),artifact:l.artifact,note:t.note},h=this.makeEnvelope("settlement",n,c),d=await this.sendEnvelope(e,h,i);return o.protocolLog.push({direction:"out",envelope:h,transportMessageId:d}),this.emitEvent({type:"settlementSent",threadId:o.threadId,settlement:c}),o.settlement=c,o.flags.hasPaid=!0,this.transitionThreadState(o,"settled","settlement sent"),o.updatedAt=this.now(),await this.persistState(),new sH(this,n)}getThread(e){return this.threads.find(t=>t.threadId===e)}getThreadHandle(e){return this.getThreadOrThrow(e),new sH(this,e)}getThreadOrThrow(e){let t=this.getThread(e);if("object"!=typeof t)throw Error(`Unknown thread: ${e}`);return this.ensureThreadState(t)}moduleContext(){return{wallet:this.wallet,originator:this.cfg.originator,now:this.now,logger:this.cfg.logger}}makeEnvelope(e,t,i){return{v:1,id:this.threadIdFactory(),kind:e,threadId:t,createdAt:this.now(),payload:i}}async sendEnvelope(e,t,i){let r=JSON.stringify(t);if("function"==typeof this.comms.sendLiveMessage)try{let n=await this.comms.sendLiveMessage({recipient:e,messageBox:this.messageBox,body:r},i);return this.emitEvent({type:"envelopeSent",threadId:t.threadId,envelope:t,transportMessageId:n}),n}catch(e){this.cfg.logger?.warn?.("[RemittanceManager] sendLiveMessage failed, falling back to non-live",e)}let n=await this.comms.sendMessage({recipient:e,messageBox:this.messageBox,body:r},i);return this.emitEvent({type:"envelopeSent",threadId:t.threadId,envelope:t,transportMessageId:n}),n}getOrCreateThreadFromInboundEnvelope(e,t){let i=this.getThread(e.threadId);if("object"==typeof i)return i;let r=this.now(),n=(()=>{if("invoice"===e.kind)return"taker";if("settlement"===e.kind)return"maker";if("receipt"===e.kind||"termination"===e.kind)return"taker";if("identityVerificationRequest"===e.kind||"identityVerificationResponse"===e.kind||"identityVerificationAcknowledgment"===e.kind){let t,i=this.runtime.identityOptions?.makerRequestIdentity??"never",r=this.runtime.identityOptions?.takerRequestIdentity??"never",n="never"!==i,s="never"!==r;return(n&&!s?t="maker":s&&!n?t="taker":n&&s&&i!==r&&(t="beforeInvoicing"===i&&"beforeSettlement"===r?"maker":"beforeSettlement"===i&&"beforeInvoicing"===r?"taker":void 0),"string"!=typeof t)?"taker":"identityVerificationResponse"===e.kind?t:"maker"===t?"taker":"maker"}return"taker"})(),s={threadId:e.threadId,counterparty:t.sender,myRole:n,theirRole:"maker"===n?"taker":"maker",createdAt:r,updatedAt:r,state:"new",stateLog:[],processedMessageIds:[],protocolLog:[],identity:{certsSent:[],certsReceived:[],requestSent:!1,responseSent:!1,acknowledgmentSent:!1,acknowledgmentReceived:!1},flags:{hasIdentified:!1,hasInvoiced:!1,hasPaid:!1,hasReceipted:!1,error:!1}};return this.threads.push(s),this.emitEvent({type:"threadCreated",threadId:s.threadId,thread:s}),s}async handleInboundMessage(e){let t=function(e){try{let t=JSON.parse(e);if("object"!=typeof t||1!==t.v||"string"!=typeof t.kind||"string"!=typeof t.threadId||"string"!=typeof t.id)return;return t}catch{return}}(e.body);if(null==t)return;let i=this.getOrCreateThreadFromInboundEnvelope(t,e);if(i.processedMessageIds.includes(e.messageId))return void await this.safeAck([e.messageId]);try{await this.applyInboundEnvelope(i,t,e),i.processedMessageIds.push(e.messageId),i.updatedAt=this.now(),await this.persistState(),await this.safeAck([e.messageId])}catch(e){this.markThreadError(i,e),await this.persistState()}}async applyInboundEnvelope(e,t,i){switch(e.protocolLog.push({direction:"in",envelope:t,transportMessageId:i.messageId}),this.emitEvent({type:"envelopeReceived",threadId:e.threadId,envelope:t,transportMessageId:i.messageId}),t.kind){case"identityVerificationRequest":{let r=t.payload;if("object"!=typeof r)throw TypeError("Identity verification request payload missing data");if(null==this.cfg.identityLayer)return void await this.sendTermination(e,i.sender,"Identity verification requested but no identity layer is configured");this.transitionThreadState(e,"identityRequested","identity request received"),this.emitEvent({type:"identityRequested",threadId:e.threadId,direction:"in",request:r});let n=await this.cfg.identityLayer.respondToRequest({counterparty:i.sender,threadId:e.threadId,request:r},this.moduleContext());if("terminate"===n.action)return void await this.sendTermination(e,i.sender,n.termination.message,n.termination.details,n.termination.code);let s=this.makeEnvelope("identityVerificationResponse",e.threadId,n.response),a=await this.sendEnvelope(i.sender,s);e.protocolLog.push({direction:"out",envelope:s,transportMessageId:a}),e.identity.certsSent=n.response.certificates,e.identity.responseSent=!0,this.transitionThreadState(e,"identityResponded","identity response sent"),this.emitEvent({type:"identityResponded",threadId:e.threadId,direction:"out",response:n.response});return}case"identityVerificationResponse":{let r=t.payload;if("object"!=typeof r)throw TypeError("Identity verification response payload missing data");if(null==this.cfg.identityLayer)return void await this.sendTermination(e,i.sender,"Identity verification response received but no identity layer is configured");e.identity.certsReceived=r.certificates,this.transitionThreadState(e,"identityResponded","identity response received"),this.emitEvent({type:"identityResponded",threadId:e.threadId,direction:"in",response:r});let n=await this.cfg.identityLayer.assessReceivedCertificateSufficiency(i.sender,r,e.threadId);if("message"in n)return void await this.sendTermination(e,i.sender,n.message,n.details,n.code);if("identityVerificationAcknowledgment"===n.kind){let t=this.makeEnvelope("identityVerificationAcknowledgment",e.threadId,n),r=await this.sendEnvelope(i.sender,t);e.protocolLog.push({direction:"out",envelope:t,transportMessageId:r}),e.identity.acknowledgmentSent=!0,e.flags.hasIdentified=!0,this.transitionThreadState(e,"identityAcknowledged","identity acknowledgment sent"),this.emitEvent({type:"identityAcknowledged",threadId:e.threadId,direction:"out",acknowledgment:n});return}throw Error("Unknown identity verification decision")}case"identityVerificationAcknowledgment":{let i=t.payload;if("object"!=typeof i)throw TypeError("Identity verification acknowledgment payload missing data");e.identity.acknowledgmentReceived=!0,e.flags.hasIdentified=!0,this.transitionThreadState(e,"identityAcknowledged","identity acknowledgment received"),this.emitEvent({type:"identityAcknowledged",threadId:e.threadId,direction:"in",acknowledgment:i});return}case"invoice":{let i=t.payload;if("object"!=typeof i)throw TypeError("Invoice payload missing invoice data");e.invoice=i,e.flags.hasInvoiced=!0,this.transitionThreadState(e,"invoiced","invoice received"),this.emitEvent({type:"invoiceReceived",threadId:e.threadId,invoice:i});return}case"settlement":{let r=t.payload;if("object"!=typeof r)throw TypeError("Settlement payload missing settlement data");if(this.shouldRequireIdentityBeforeSettlement(e)&&!e.flags.hasIdentified)return void await this.sendTermination(e,i.sender,"Identity verification is required before settlement");e.settlement=r,e.flags.hasPaid=!0,this.transitionThreadState(e,"settled","settlement received"),this.emitEvent({type:"settlementReceived",threadId:e.threadId,settlement:r});let n=this.moduleRegistry.get(r.moduleId);if("object"!=typeof n)return void await this.maybeSendTermination(e,r,i.sender,`Unsupported module: ${r.moduleId}`);if(null==e.invoice&&!n.allowUnsolicitedSettlements)return void await this.maybeSendTermination(e,r,i.sender,"Unsolicited settlement not supported");let s=await n.acceptSettlement({threadId:e.threadId,invoice:e.invoice,settlement:r.artifact,sender:i.sender},this.moduleContext()).catch(async t=>{let n=t instanceof Error?t.message:String(t);throw await this.maybeSendTermination(e,r,i.sender,`Settlement processing failed: ${n}`),t});if("accept"===s.action){let t=this.requireMyIdentityKey("Receiving settlement requires identity key"),n=i.sender,a={kind:"receipt",threadId:e.threadId,moduleId:r.moduleId,optionId:r.optionId,payee:t,payer:n,createdAt:this.now(),receiptData:s.receiptData};if(e.receipt=a,e.flags.hasReceipted=!0,this.transitionThreadState(e,"receipted","receipt issued"),this.runtime.receiptProvided&&this.runtime.autoIssueReceipt){let t=this.makeEnvelope("receipt",e.threadId,a),r=await this.sendEnvelope(i.sender,t);e.protocolLog.push({direction:"out",envelope:t,transportMessageId:r}),this.emitEvent({type:"receiptSent",threadId:e.threadId,receipt:a})}}else if("terminate"===s.action)await this.maybeSendTermination(e,r,i.sender,s.termination.message,s.termination.details);else throw Error("Unknown settlement acceptance action");return}case"receipt":{let r=t.payload;if("object"!=typeof r)throw TypeError("Receipt payload missing receipt data");e.receipt=r,e.flags.hasReceipted=!0,this.transitionThreadState(e,"receipted","receipt received"),this.emitEvent({type:"receiptReceived",threadId:e.threadId,receipt:r});let n=this.moduleRegistry.get(r.moduleId);n?.processReceipt!=null&&await n.processReceipt({threadId:e.threadId,invoice:e.invoice,receiptData:r.receiptData,sender:i.sender},this.moduleContext());return}case"termination":{let r=t.payload;if("object"!=typeof r)throw TypeError("Termination payload missing data");if(e.termination=r,e.lastError={message:r.message,at:this.now()},e.flags.error=!0,this.transitionThreadState(e,"terminated","termination received"),this.emitEvent({type:"terminationReceived",threadId:e.threadId,termination:r}),null!=e.settlement){let t=this.moduleRegistry.get(e.settlement.moduleId);t?.processTermination!=null&&await t.processTermination({threadId:e.threadId,invoice:e.invoice,settlement:e.settlement,termination:r,sender:i.sender},this.moduleContext())}return}default:{let e=t.kind;throw Error(`Unknown envelope kind: ${String(e)}`)}}}async maybeSendTermination(e,t,i,r,n){let s={code:"error",message:r,details:n},a=this.makeEnvelope("termination",e.threadId,s),o=await this.sendEnvelope(i,a);e.protocolLog.push({direction:"out",envelope:a,transportMessageId:o}),this.emitEvent({type:"terminationSent",threadId:e.threadId,termination:s}),e.termination=s,e.lastError={message:`Sent termination: ${r}`,at:this.now()},e.flags.error=!0,this.transitionThreadState(e,"terminated","termination sent")}async sendTermination(e,t,i,r,n="error"){let s={code:n,message:i,details:r},a=this.makeEnvelope("termination",e.threadId,s),o=await this.sendEnvelope(t,a);e.protocolLog.push({direction:"out",envelope:a,transportMessageId:o}),this.emitEvent({type:"terminationSent",threadId:e.threadId,termination:s}),e.termination=s,e.lastError={message:`Sent termination: ${i}`,at:this.now()},e.flags.error=!0,this.transitionThreadState(e,"terminated","termination sent")}shouldRequestIdentity(e,t){let{makerRequestIdentity:i="never",takerRequestIdentity:r="never"}=this.runtime.identityOptions??{};if(!("maker"===e.myRole?i===t:r===t))return!1;if(null==this.cfg.identityLayer)throw Error("Identity layer is required by runtime options but is not configured");return!0}shouldRequireIdentityBeforeSettlement(e){return"maker"===e.myRole&&(this.runtime.identityOptions?.makerRequestIdentity??"never")==="beforeSettlement"}async ensureIdentityExchange(e,t){if(null!=this.cfg.identityLayer&&!e.flags.hasIdentified){if(!e.identity.requestSent){let i=await this.cfg.identityLayer.determineCertificatesToRequest({counterparty:e.counterparty,threadId:e.threadId},this.moduleContext()),r=this.makeEnvelope("identityVerificationRequest",e.threadId,i),n=await this.sendEnvelope(e.counterparty,r,t);e.protocolLog.push({direction:"out",envelope:r,transportMessageId:n}),e.identity.requestSent=!0,this.transitionThreadState(e,"identityRequested","identity request sent"),this.emitEvent({type:"identityRequested",threadId:e.threadId,direction:"out",request:i}),e.updatedAt=this.now(),await this.persistState()}await this.waitForIdentityAcknowledgment(e.threadId,{timeoutMs:this.runtime.identityTimeoutMs,pollIntervalMs:this.runtime.identityPollIntervalMs})}}async waitForIdentityAcknowledgment(e,t={}){await this.waitForState(e,"identityAcknowledged",t)}async safeAck(e){try{await this.comms.acknowledgeMessage({messageIds:e})}catch(e){this.cfg.logger?.warn?.("[RemittanceManager] Failed to acknowledge message(s)",e)}}markThreadError(e,t){e.flags.error=!0,this.transitionThreadState(e,"errored","thread error"),e.lastError={message:String(t?.message??t),at:this.now()},this.cfg.logger?.error?.("[RemittanceManager] Thread error",e.threadId,t),this.emitEvent({type:"error",threadId:e.threadId,error:String(t?.message??t)})}ensureThreadState(e){return e.identity=e.identity??{certsSent:[],certsReceived:[],requestSent:!1,responseSent:!1,acknowledgmentSent:!1,acknowledgmentReceived:!1},e.identity.certsSent??=[],e.identity.certsReceived??=[],e.identity.requestSent??=!1,e.identity.responseSent??=!1,e.identity.acknowledgmentSent??=!1,e.identity.acknowledgmentReceived??=!1,e.flags=e.flags??{hasIdentified:!1,hasInvoiced:!1,hasPaid:!1,hasReceipted:!1,error:!1},e.processedMessageIds??=[],e.protocolLog??=[],e.stateLog??=[],e.state??=this.deriveThreadState(e),e}deriveThreadState(e){return e.flags.error?"errored":null!=e.termination?"terminated":null!=e.receipt?"receipted":null!=e.settlement?"settled":null!=e.invoice?"invoiced":e.identity.acknowledgmentReceived||e.identity.acknowledgmentSent||e.flags.hasIdentified?"identityAcknowledged":e.identity.responseSent||e.identity.certsSent.length>0?"identityResponded":e.identity.requestSent||e.identity.certsReceived.length>0?"identityRequested":"new"}transitionThreadState(e,t,i){let r=e.state;if(r!==t){if(!(sF[r]??[]).includes(t))throw Error(`Invalid remittance state transition: ${r} -> ${t}`);e.state=t,e.updatedAt=this.now(),e.stateLog.push({at:this.now(),from:r,to:t,reason:i}),this.emitEvent({type:"stateChanged",threadId:e.threadId,previous:r,next:t,reason:i}),this.resolveStateWaiters(e.threadId,t),("terminated"===t||"errored"===t)&&this.rejectStateWaiters(e.threadId,Error(`Thread entered terminal state: ${t}`))}}resolveStateWaiters(e,t){let i=this.stateWaiters.get(e);if(null==i)return;let r=[];for(let e of i)e.state===t?e.resolve():r.push(e);0===r.length?this.stateWaiters.delete(e):this.stateWaiters.set(e,r)}rejectStateWaiters(e,t){let i=this.stateWaiters.get(e);if(null!=i){for(let e of i)e.reject(t);this.stateWaiters.delete(e)}}emitEvent(e){let t=this.eventHandlers;if(null!=t)try{switch(e.type){case"threadCreated":t.onThreadCreated?.(e);break;case"stateChanged":t.onStateChanged?.(e);break;case"envelopeSent":t.onEnvelopeSent?.(e);break;case"envelopeReceived":t.onEnvelopeReceived?.(e);break;case"identityRequested":t.onIdentityRequested?.(e);break;case"identityResponded":t.onIdentityResponded?.(e);break;case"identityAcknowledged":t.onIdentityAcknowledged?.(e);break;case"invoiceSent":t.onInvoiceSent?.(e);break;case"invoiceReceived":t.onInvoiceReceived?.(e);break;case"settlementSent":t.onSettlementSent?.(e);break;case"settlementReceived":t.onSettlementReceived?.(e);break;case"receiptSent":t.onReceiptSent?.(e);break;case"receiptReceived":t.onReceiptReceived?.(e);break;case"terminationSent":t.onTerminationSent?.(e);break;case"terminationReceived":t.onTerminationReceived?.(e);break;case"error":t.onError?.(e)}}catch(e){this.cfg.logger?.warn?.("[RemittanceManager] Event handler error",e)}for(let t of this.eventListeners)try{t(e)}catch(e){this.cfg.logger?.warn?.("[RemittanceManager] Event listener error",e)}}async refreshMyIdentityKey(){if("string"==typeof this.myIdentityKey||"object"!=typeof this.wallet)return;let{publicKey:e}=await this.wallet.getPublicKey({identityKey:!0},this.cfg.originator);"string"==typeof e&&""!==e.trim()&&(this.myIdentityKey=e)}requireMyIdentityKey(e){if("string"!=typeof this.myIdentityKey)throw TypeError(e);return this.myIdentityKey}async composeInvoice(e,t,i,r){let n=this.now(),s=this.runtime.invoiceExpirySeconds>=0?n+1e3*this.runtime.invoiceExpirySeconds:void 0;return{kind:"invoice",threadId:e,payee:t,payer:i,note:r.note,lineItems:r.lineItems,total:r.total,invoiceNumber:r.invoiceNumber??e,createdAt:n,expiresAt:s,arbitrary:r.arbitrary,options:{}}}}class sH{manager;threadId;constructor(e,t){this.manager=e,this.threadId=t}get thread(){return this.manager.getThreadOrThrow(this.threadId)}async waitForState(e,t){return await this.manager.waitForState(this.threadId,e,t)}async waitForIdentity(e){return await this.manager.waitForIdentity(this.threadId,e)}async waitForSettlement(e){return await this.manager.waitForSettlement(this.threadId,e)}async waitForReceipt(e){return await this.manager.waitForReceipt(this.threadId,e)}}class sM extends sH{get invoice(){let e=this.thread.invoice;if("object"!=typeof e)throw Error("Thread has no invoice");return e}async pay(e){return await this.manager.pay(this.threadId,e)}}function sK(){return tS(ia(32))}async function sq(e){return await new Promise(t=>setTimeout(t,e))}let s$={createNonce:async(e,t,i)=>await nQ(e,t,i)},sz={async pubKeyToP2PKHLockingScript(e){let t=ii.fromString(e).toAddress();return new i3().lock(t).toHex()}};class sW{id="brc29.p2pkh";name="BSV (BRC-29 derived P2PKH)";allowUnsolicitedSettlements=!0;protocolID;labels;description;outputDescription;refundFeeSatoshis;minRefundSatoshis;internalizeProtocol;nonceProvider;lockingScriptProvider;constructor(e={}){this.protocolID=e.protocolID??[2,"3241645161d8"],this.labels=e.labels??["brc29"],this.description=e.description??"BRC-29 payment",this.outputDescription=e.outputDescription??"Payment for remittance invoice",this.refundFeeSatoshis=e.refundFeeSatoshis??1e3,this.minRefundSatoshis=e.minRefundSatoshis??1e3,this.internalizeProtocol=e.internalizeProtocol??"wallet payment",this.nonceProvider=e.nonceProvider??s$,this.lockingScriptProvider=e.lockingScriptProvider??sz}async buildSettlement(e,t){let i,{wallet:r,originator:n}=t;try{i=function(e){if(null==e||"object"!=typeof e)throw Error("BRC-29 option terms are required");let t=e.amountSatoshis;if(!Number.isInteger(t)||t<=0)throw Error("BRC-29 option amount must be a positive integer");let i=e.outputIndex;if(null!=i&&(!Number.isInteger(i)||i<0))throw Error("BRC-29 option outputIndex must be a non-negative integer");let r=e.protocolID;if(null!=r){if(!Array.isArray(r)||2!==r.length)throw Error("BRC-29 option protocolID must be a tuple [number, string]");let[e,t]=r;if(!Number.isInteger(e)||e<0||!sX(t))throw Error("BRC-29 option protocolID must be a tuple [number, string]")}let n=e.labels;if(null!=n&&(!Array.isArray(n)||n.some(e=>!sX(e))))throw Error("BRC-29 option labels must be a list of non-empty strings");let s=e.description;if(null!=s&&!sX(s))throw Error("BRC-29 option description must be a non-empty string");return e}(e.option)}catch(e){return sj("brc29.invalid_option",e instanceof Error?e.message:String(e))}let s=i.amountSatoshis;try{let t=await this.nonceProvider.createNonce(r,"self",n),a=await this.nonceProvider.createNonce(r,"self",n),o=i.protocolID??this.protocolID,l=`${t} ${a}`,{publicKey:c}=await r.getPublicKey({protocolID:o,keyID:l,counterparty:i.payee},n);if("string"!=typeof c||""===c.trim())return sj("brc29.public_key_missing","Failed to derive payee public key for BRC-29 settlement.");let h=await this.lockingScriptProvider.pubKeyToP2PKHLockingScript(c);if("string"!=typeof h||""===h.trim())return sj("brc29.locking_script_missing","Failed to produce P2PKH locking script.");let d=await r.createAction({description:i.description??this.description,labels:i.labels??this.labels,outputs:[{satoshis:s,lockingScript:h,customInstructions:JSON.stringify({derivationPrefix:t,derivationSuffix:a,payee:i.payee,threadId:e.threadId,note:e.note}),outputDescription:this.outputDescription}],options:{randomizeOutputs:!1}},n),u=d.tx??d.signableTransaction?.tx;if(null==u)return sj("brc29.missing_tx","wallet.createAction did not return a transaction.");if(!sG(u))return sj("brc29.invalid_tx","wallet.createAction returned an invalid transaction payload.");return{action:"settle",artifact:{customInstructions:{derivationPrefix:t,derivationSuffix:a},transaction:u,amountSatoshis:i.amountSatoshis,outputIndex:i.outputIndex??0}}}catch(t){let e=t instanceof Error?t.message:String(t);return sj("brc29.build_failed",`BRC-29 settlement failed: ${e}`)}}async acceptSettlement(e,t){let{wallet:i,originator:r}=t;console.log("acceptSettlement",e);try{let t=function(e){if(null==e||"object"!=typeof e)throw Error("BRC-29 settlement artifact is required");let t=e.customInstructions;if(null==t||"object"!=typeof t)throw Error("BRC-29 settlement requires customInstructions");if(!sX(t.derivationPrefix)||!sX(t.derivationSuffix))throw Error("BRC-29 settlement derivation values are required");let i=e.amountSatoshis;if(!Number.isInteger(i)||i<=0)throw Error("BRC-29 settlement amount must be a positive integer");let r=e.outputIndex;if(null!=r&&(!Number.isInteger(r)||r<0))throw Error("BRC-29 settlement outputIndex must be a non-negative integer");if(!sG(e.transaction))throw Error("BRC-29 settlement transaction must be a non-empty byte array");return e}(e.settlement),n=t.outputIndex??0,s=await i.internalizeAction({tx:t.transaction,outputs:[{paymentRemittance:{derivationPrefix:t.customInstructions.derivationPrefix,derivationSuffix:t.customInstructions.derivationSuffix,senderIdentityKey:e.sender},outputIndex:n,protocol:this.internalizeProtocol}],labels:this.labels,description:"BRC-29 payment received"},r);return{action:"accept",receiptData:{internalizeResult:s}}}catch(t){let e=t instanceof Error?t.message:String(t);return sj("brc29.internalize_failed",`Failed to internalize BRC-29 settlement: ${e}`)}}}function sj(e,t,i){return{action:"terminate",termination:{code:e,message:t,details:i}}}function sG(e){return!!Array.isArray(e)&&0!==e.length&&e.every(e=>Number.isInteger(e)&&e>=0&&e<=255)}function sX(e){return"string"==typeof e&&e.trim().length>0}return p})());
|