@bsv/sdk 1.4.22 → 1.4.24
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 +1 -1
- package/dist/cjs/src/auth/certificates/VerifiableCertificate.js +10 -0
- package/dist/cjs/src/auth/certificates/VerifiableCertificate.js.map +1 -1
- package/dist/cjs/src/auth/clients/AuthFetch.js.map +1 -1
- package/dist/cjs/src/transaction/broadcasters/Teranode.js +64 -0
- package/dist/cjs/src/transaction/broadcasters/Teranode.js.map +1 -0
- package/dist/cjs/src/transaction/broadcasters/index.js +3 -1
- package/dist/cjs/src/transaction/broadcasters/index.js.map +1 -1
- package/dist/cjs/src/transaction/http/BinaryFetchClient.js +94 -0
- package/dist/cjs/src/transaction/http/BinaryFetchClient.js.map +1 -0
- package/dist/cjs/src/transaction/http/NodejsHttpClient.js.map +1 -1
- package/dist/cjs/src/transaction/http/index.js +3 -1
- package/dist/cjs/src/transaction/http/index.js.map +1 -1
- package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
- package/dist/esm/src/auth/certificates/VerifiableCertificate.js +10 -0
- package/dist/esm/src/auth/certificates/VerifiableCertificate.js.map +1 -1
- package/dist/esm/src/auth/clients/AuthFetch.js.map +1 -1
- package/dist/esm/src/transaction/broadcasters/Teranode.js +62 -0
- package/dist/esm/src/transaction/broadcasters/Teranode.js.map +1 -0
- package/dist/esm/src/transaction/broadcasters/index.js +1 -0
- package/dist/esm/src/transaction/broadcasters/index.js.map +1 -1
- package/dist/esm/src/transaction/http/BinaryFetchClient.js +90 -0
- package/dist/esm/src/transaction/http/BinaryFetchClient.js.map +1 -0
- package/dist/esm/src/transaction/http/NodejsHttpClient.js.map +1 -1
- package/dist/esm/src/transaction/http/index.js +1 -0
- package/dist/esm/src/transaction/http/index.js.map +1 -1
- package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
- package/dist/types/src/auth/certificates/VerifiableCertificate.d.ts +9 -1
- package/dist/types/src/auth/certificates/VerifiableCertificate.d.ts.map +1 -1
- package/dist/types/src/auth/clients/AuthFetch.d.ts.map +1 -1
- package/dist/types/src/transaction/broadcasters/Teranode.d.ts +25 -0
- package/dist/types/src/transaction/broadcasters/Teranode.d.ts.map +1 -0
- package/dist/types/src/transaction/broadcasters/index.d.ts +1 -0
- package/dist/types/src/transaction/broadcasters/index.d.ts.map +1 -1
- package/dist/types/src/transaction/http/BinaryFetchClient.d.ts +50 -0
- package/dist/types/src/transaction/http/BinaryFetchClient.d.ts.map +1 -0
- package/dist/types/src/transaction/http/index.d.ts +1 -0
- package/dist/types/src/transaction/http/index.d.ts.map +1 -1
- package/dist/types/tsconfig.types.tsbuildinfo +1 -1
- package/dist/umd/bundle.js +1 -1
- package/docs/auth.md +120 -46
- package/docs/compat.md +48 -24
- package/docs/identity.md +14 -8
- package/docs/kvstore.md +9 -3
- package/docs/messages.md +4 -4
- package/docs/overlay-tools.md +69 -21
- package/docs/primitives.md +379 -235
- package/docs/registry.md +20 -14
- package/docs/script.md +87 -33
- package/docs/storage.md +17 -11
- package/docs/totp.md +11 -5
- package/docs/transaction.md +145 -67
- package/docs/wallet.md +169 -133
- package/package.json +1 -1
- package/src/auth/certificates/VerifiableCertificate.ts +24 -0
- package/src/auth/certificates/__tests/VerifiableCertificate.test.ts +28 -1
- package/src/auth/clients/AuthFetch.ts +2 -0
- package/src/transaction/broadcasters/Teranode.ts +77 -0
- package/src/transaction/broadcasters/index.ts +1 -0
- package/src/transaction/http/BinaryFetchClient.ts +141 -0
- package/src/transaction/http/NodejsHttpClient.ts +1 -1
- package/src/transaction/http/index.ts +1 -0
package/dist/umd/bundle.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.bsv=e():t.bsv=e()}(this,(()=>(()=>{"use strict";var t={d:(e,r)=>{for(var i in r)t.o(r,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:r[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{ARC:()=>ze,ATOMIC_BEEF:()=>tr,AuthFetch:()=>si,BEEF_V1:()=>Ze,BEEF_V2:()=>Qe,BSM:()=>o,Beef:()=>rr,BeefParty:()=>ar,BeefTx:()=>Ye,BigNumber:()=>h,CachedKeyDeriver:()=>Tr,Certificate:()=>Dr,CompletedProtoWallet:()=>Gr,Curve:()=>Lt,DEFAULT_IDENTITY_CLIENT_OPTIONS:()=>Ii,DEFAULT_SLAP_TRACKERS:()=>oi,DEFAULT_TESTNET_SLAP_TRACKERS:()=>ci,DRBG:()=>zt,ECDSA:()=>n,ECIES:()=>Er,EncryptedMessage:()=>a,FetchHttpClient:()=>qe,HD:()=>br,HTTPSOverlayBroadcastFacilitator:()=>li,HTTPSOverlayLookupFacilitator:()=>hi,HTTPWalletJSON:()=>$r,HTTPWalletWire:()=>Kr,Hash:()=>r,IdentityClient:()=>Pi,KNOWN_IDENTITY_TYPES:()=>ki,KeyDeriver:()=>Ar,KeyShares:()=>ee,LocalKVStore:()=>Ni,LockingScript:()=>Ae,LookupResolver:()=>ui,MasterCertificate:()=>Wr,MerklePath:()=>Ge,Mnemonic:()=>yr,NodejsHttpClient:()=>Ke,OP:()=>Oe,OverlayAdminTokenTemplate:()=>ai,P2PKH:()=>Ve,Peer:()=>ri,Point:()=>Kt,PointInFiniteField:()=>Qt,Polynomial:()=>te,PrivateKey:()=>re,ProtoWallet:()=>Mr,PublicKey:()=>Gt,PushDrop:()=>Ue,RPuzzle:()=>De,Random:()=>Zt,RegistryClient:()=>Ei,SHIPBroadcaster:()=>di,SHIPCast:()=>di,SatoshisPerKilobyte:()=>He,Schnorr:()=>Se,Script:()=>xe,SecurityLevels:()=>xr,SessionManager:()=>Yr,Signature:()=>$t,SignedMessage:()=>s,SimplifiedFetchTransport:()=>ni,Spend:()=>Re,StorageDownloader:()=>yi,StorageUploader:()=>gi,StorageUtils:()=>c,SymmetricKey:()=>Pe,TOTP:()=>Nr,TX_DATA_FORMAT:()=>er,TopicBroadcaster:()=>di,Transaction:()=>ir,TransactionSignature:()=>Ee,UnlockingScript:()=>Te,Utils:()=>i,VerifiableCertificate:()=>Xr,WERR_REVIEW_ACTIONS:()=>Lr,WalletClient:()=>zr,WalletError:()=>Fr,WalletErrors:()=>Cr,WalletWireProcessor:()=>jr,WalletWireTransceiver:()=>Hr,WhatsOnChain:()=>We,WhatsOnChainBroadcaster:()=>or,WindowCWISubstrate:()=>_r,XDM:()=>Vr,createNonce:()=>Zr,defaultBroadcaster:()=>je,defaultChainTracker:()=>Xe,defaultHttpClient:()=>Le,defaultIdentity:()=>vi,deserializeWalletProtocol:()=>Si,fromUtxo:()=>Sr,getVerifiableCertificates:()=>Qr,isBroadcastFailure:()=>sr,isBroadcastResponse:()=>nr,validateCertificates:()=>ti,verifyNonce:()=>Jr,walletErrors:()=>Rr});var r={};t.r(r),t.d(r,{RIPEMD160:()=>J,SHA1:()=>Q,SHA1HMAC:()=>pt,SHA256:()=>Z,SHA256HMAC:()=>ft,SHA512:()=>tt,SHA512HMAC:()=>mt,hash160:()=>It,hash256:()=>vt,pbkdf2:()=>Et,ripemd160:()=>wt,sha1:()=>bt,sha256:()=>gt,sha256hmac:()=>kt,sha512:()=>yt,sha512hmac:()=>Pt,toArray:()=>y});var i={};t.r(i),t.d(i,{Reader:()=>Ut,Writer:()=>Bt,encode:()=>Mt,fromBase58:()=>Rt,fromBase58Check:()=>Dt,minimallyEncode:()=>Ht,toArray:()=>Ot,toBase58:()=>Ct,toBase58Check:()=>Vt,toBase64:()=>_t,toHex:()=>Nt,toUTF8:()=>Tt,zero2:()=>St});var n={};t.r(n),t.d(n,{sign:()=>Wt,verify:()=>Xt});var s={};t.r(s),t.d(s,{sign:()=>hr,verify:()=>ur});var a={};t.r(a),t.d(a,{decrypt:()=>fr,encrypt:()=>dr});var o={};t.r(o),t.d(o,{magicHash:()=>pr,sign:()=>mr,verify:()=>wr});var c={};t.r(c),t.d(c,{getHashFromURL:()=>wi,getURLForFile:()=>mi,getURLForHash:()=>pi,isValidURL:()=>bi,normalizeURL:()=>fi});class h{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,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];static wordSize=26;negative;words;length;red;static isBN(t){return t instanceof h||null!==t&&"object"==typeof t&&t.constructor.wordSize===h.wordSize&&Array.isArray(t.words)}static max(t,e){return t.cmp(e)>0?t:e}static min(t,e){return t.cmp(e)<0?t:e}constructor(t=0,e=10,r="be"){if(this.negative=0,this.words=[],this.length=0,this.red=null,null!==t){if("le"!==e&&"be"!==e||(r=e,e=10),"number"==typeof t)return void this.initNumber(t,e,r);if("object"==typeof t)return void this.initArray(t,r);"hex"===e&&(e=16),this.assert(e===(0|e)&&e>=2&&e<=36);let i=0;(t=t.toString().replace(/\s+/g,"")).startsWith("-")&&(i++,this.negative=1),i<t.length&&(16===e?this.parseHex(t,i,r):(this.parseBase(t,e,i),"le"===r&&this.initArray(this.toArray(),r)))}}assert(t,e="Assertion failed"){if(!t)throw new Error(e)}initNumber(t,e,r){return t<0&&(this.negative=1,t=-t),t<67108864?(this.words=[67108863&t],this.length=1):t<4503599627370496?(this.words=[67108863&t,t/67108864&67108863],this.length=2):(this.assert(t<=9007199254740991,"The number is larger than 2 ^ 53 (unsafe)"),this.words=[67108863&t,t/67108864&67108863,1],this.length=3),"le"!==r||this.initArray(this.toArray(),r),this}initArray(t,e){if(this.assert("number"==typeof t.length,"The number must have a length"),t.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(t.length/3),this.words=new Array(this.length);let r,i,n=0;for(;n<this.length;n++)this.words[n]=0;let s=0;if("be"===e)for(n=t.length-1,r=0;n>=0;n-=3)i=t[n]|t[n-1]<<8|t[n-2]<<16,this.words[r]|=i<<s&67108863,this.words[r+1]=i>>>26-s&67108863,s+=24,s>=26&&(s-=26,r++);else if("le"===e)for(n=0,r=0;n<t.length;n+=3)i=t[n]|t[n+1]<<8|t[n+2]<<16,this.words[r]|=i<<s&67108863,this.words[r+1]=i>>>26-s&67108863,s+=24,s>=26&&(s-=26,r++);return this.strip()}parseHex4Bits(t,e){const r=t.charCodeAt(e);if(r>=48&&r<=57)return r-48;if(r>=65&&r<=70)return r-55;if(r>=97&&r<=102)return r-87;throw new Error("Invalid character in "+t)}parseHexByte(t,e,r){let i=this.parseHex4Bits(t,r);return r-1>=e&&(i|=this.parseHex4Bits(t,r-1)<<4),i}parseHex(t,e,r){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length).fill(0);let i=0,n=0;const s=r=>{const s=this.parseHexByte(t,e,r)<<i;this.words[n]|=67108863&s,i>=18?(i-=18,n+=1,this.words[n]|=s>>>26):i+=8};if("be"===r)for(let r=t.length-1;r>=e;r-=2)s(r);else for(let r=(t.length-e)%2==0?e+1:e;r<t.length;r+=2)s(r);return this.strip()}parseBaseWord(t,e,r,i){let n=0,s=0;const a=Math.min(t.length,r);for(let r=e;r<a;r++){const e=t.charCodeAt(r)-48;n*=i,s=e>=49?e-49+10:e>=17?e-17+10:e,this.assert(e>=0&&s<i,"Invalid character"),n+=s}return n}parseBase(t,e,r){this.words=[0],this.length=1;let i=0,n=1;for(;n<=67108863;n*=e)i++;i--,n=n/e|0;const s=t.length-r,a=s%i,o=Math.min(s,s-a)+r;let c=0,h=r;for(;h<o;h+=i)c=this.parseBaseWord(t,h,h+i,e),this.imuln(n),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c);if(0!==a){let r=1;for(c=this.parseBaseWord(t,h,t.length,e),h=0;h<a;h++)r*=e;this.imuln(r),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c)}return this.strip()}copy(t){t.words=new Array(this.length);for(let e=0;e<this.length;e++)t.words[e]=this.words[e];t.length=this.length,t.negative=this.negative,t.red=this.red}static move(t,e){t.words=e.words,t.length=e.length,t.negative=e.negative,t.red=e.red}clone(){const t=new h;return this.copy(t),t}expand(t){for(;this.length<t;)this.words[this.length++]=0;return this}strip(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this.normSign()}normSign(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this}inspect(){return(null!==this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}toString(t=10,e=1){if(16===t||"hex"===t)return this.toHexString(e);if(t===(0|t)&&t>=2&&t<=36)return this.toBaseString(t,e);throw new Error("Base should be between 2 and 36")}toHexString(t){let e="",r=0,i=0;for(let t=0;t<this.length;t++){const n=this.words[t],s=(16777215&(n<<r|i)).toString(16);i=n>>>24-r&16777215,r+=2,r>=26&&(r-=26,t--),e=0!==i||t!==this.length-1?h.zeros[6-s.length]+s+e:s+e}if(0!==i&&(e=i.toString(16)+e),0===t&&"0"===e)return"";for(;e.length%t!=0&&0!==t;)e="0"+e;return 0!==this.negative&&(e="-"+e),e}toBaseString(t,e){const r=h.groupSizes[t],i=h.groupBases[t];let n="",s=this.clone();for(s.negative=0;!s.isZero();){const e=s.modrn(i).toString(t);s=s.idivn(i),n=s.isZero()?e+n:h.zeros[r-e.length]+e+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}toNumber(){let t=this.words[0];if(2===this.length)t+=67108864*this.words[1];else if(3===this.length&&1===this.words[2])t+=4503599627370496+67108864*this.words[1];else if(this.length>2)throw new Error("Number can only safely store up to 53 bits");return 0!==this.negative?-t:t}toJSON(){return this.toString(16)}toArrayLikeLE(t,e){let r=0,i=0;for(let e=0,n=0;e<this.length;e++){const s=this.words[e]<<n|i;t[r++]=255&s,r<t.length&&(t[r++]=s>>8&255),r<t.length&&(t[r++]=s>>16&255),6===n?(r<t.length&&(t[r++]=s>>24&255),i=0,n=0):(i=s>>>24,n+=2)}if(r<t.length)for(t[r++]=i;r<t.length;)t[r++]=0}toArrayLikeBE(t,e){let r=t.length-1,i=0;for(let e=0,n=0;e<this.length;e++){const s=this.words[e]<<n|i;t[r--]=255&s,r>=0&&(t[r--]=s>>8&255),r>=0&&(t[r--]=s>>16&255),6===n?(r>=0&&(t[r--]=s>>24&255),i=0,n=0):(i=s>>>24,n+=2)}if(r>=0)for(t[r--]=i;r>=0;)t[r--]=0}toArray(t="be",e){this.strip();const r=this.byteLength(),i=e??Math.max(1,r);this.assert(r<=i,"byte array longer than desired length"),this.assert(i>0,"Requested array length <= 0");const n=new Array(i);return"le"===t?this.toArrayLikeLE(n,r):this.toArrayLikeBE(n,r),n}countWordBits(t){if("function"==typeof Math.clz32)return 32-Math.clz32(t);let e=t,r=0;return e>=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e}zeroWordBits(t){if(0===t)return 26;let e=t,r=0;return 8191&e||(r+=13,e>>>=13),127&e||(r+=7,e>>>=7),15&e||(r+=4,e>>>=4),3&e||(r+=2,e>>>=2),1&e||r++,r}bitLength(){const t=this.words[this.length-1],e=this.countWordBits(t);return 26*(this.length-1)+e}static toBitArray(t){const e=new Array(t.bitLength());for(let r=0;r<e.length;r++){const i=r/26|0,n=r%26;e[r]=t.words[i]>>>n&1}return e}toBitArray(){return h.toBitArray(this)}zeroBits(){if(this.isZero())return 0;let t=0;for(let e=0;e<this.length;e++){const r=this.zeroWordBits(this.words[e]);if(t+=r,26!==r)break}return t}byteLength(){return Math.ceil(this.bitLength()/8)}toTwos(t){return 0!==this.negative?this.abs().inotn(t).iaddn(1):this.clone()}fromTwos(t){return this.testn(t-1)?this.notn(t).iaddn(1).ineg():this.clone()}isNeg(){return 0!==this.negative}neg(){return this.clone().ineg()}ineg(){return this.isZero()||(this.negative^=1),this}iuor(t){for(;this.length<t.length;)this.words[this.length++]=0;for(let e=0;e<t.length;e++)this.words[e]=this.words[e]|t.words[e];return this.strip()}ior(t){return this.assert(!(this.negative|t.negative)),this.iuor(t)}or(t){return this.length>t.length?this.clone().ior(t):t.clone().ior(this)}uor(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)}iuand(t){const e=Math.min(this.length,t.length);for(let r=0;r<e;r++)this.words[r]=this.words[r]&t.words[r];return this.length=e,this.strip()}iand(t){return this.assert(!(this.negative|t.negative)),this.iuand(t)}and(t){return this.length>t.length?this.clone().iand(t):t.clone().iand(this)}uand(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)}iuxor(t){if(this.length>t.length)for(let e=0;e<t.length;e++)this.words[e]=this.words[e]^t.words[e];else{for(let e=0;e<this.length;e++)this.words[e]=this.words[e]^t.words[e];for(let e=this.length;e<t.length;e++)this.words[e]=t.words[e];this.length=t.length}return this.strip()}ixor(t){return this.assert(!(this.negative|t.negative),"Neither number can be negative"),this.iuxor(t)}xor(t){return this.length>t.length?this.clone().ixor(t):t.clone().ixor(this)}uxor(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)}inotn(t){this.assert("number"==typeof t&&t>=0,"The width needs to be a number greater than zero");let e=0|Math.ceil(t/26);const r=t%26;this.expand(e),r>0&&e--;let i=0;for(;i<e;i++)this.words[i]=67108863&~this.words[i];return r>0&&(this.words[i]=~this.words[i]&67108863>>26-r),this.strip()}notn(t){return this.clone().inotn(t)}setn(t,e){this.assert("number"==typeof t&&t>=0);const r=t/26|0,i=t%26;return this.expand(r+1),this.words[r]=1===e||!0===e?this.words[r]|1<<i:this.words[r]&~(1<<i),this.strip()}iadd(t){let e,r,i;if(0!==this.negative&&0===t.negative)return this.negative=0,e=this.isub(t),this.negative^=1,this.normSign();if(0===this.negative&&0!==t.negative)return t.negative=0,e=this.isub(t),t.negative=1,e.normSign();this.length>t.length?(r=this,i=t):(r=t,i=this);let n=0,s=0;for(;s<i.length;s++)e=(0|r.words[s])+(0|i.words[s])+n,this.words[s]=67108863&e,n=e>>>26;for(;0!==n&&s<r.length;s++)e=(0|r.words[s])+n,this.words[s]=67108863&e,n=e>>>26;if(this.length=r.length,0!==n)this.words[this.length]=n,this.length++;else if(r!==this)for(;s<r.length;s++)this.words[s]=r.words[s];return this}add(t){let e;return 0!==t.negative&&0===this.negative?(t.negative=0,e=this.sub(t),t.negative^=1,e):0===t.negative&&0!==this.negative?(this.negative=0,e=t.sub(this),this.negative=1,e):this.length>t.length?this.clone().iadd(t):t.clone().iadd(this)}isub(t){let e;if(0!==t.negative)return t.negative=0,e=this.iadd(t),t.negative=1,e.normSign();if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this.normSign();const r=this.cmp(t);if(0===r)return this.negative=0,this.length=1,this.words[0]=0,this;let i,n;r>0?(i=this,n=t):(i=t,n=this);let s=0,a=0;for(;a<n.length;a++)e=(0|i.words[a])-(0|n.words[a])+s,s=e>>26,this.words[a]=67108863&e;for(;0!==s&&a<i.length;a++)e=(0|i.words[a])+s,s=e>>26,this.words[a]=67108863&e;if(0===s&&a<i.length&&i!==this)for(;a<i.length;a++)this.words[a]=i.words[a];return this.length=Math.max(this.length,a),i!==this&&(this.negative=1),this.strip()}sub(t){return this.clone().isub(t)}smallMulTo(t,e,r){r.negative=e.negative^t.negative;let i=t.length+e.length|0;r.length=i,i=i-1|0;let n=0|t.words[0],s=0|e.words[0],a=n*s;const o=67108863&a;let c=a/67108864|0;r.words[0]=o;let h=1;for(;h<i;h++){let i=c>>>26,o=67108863&c;const u=Math.min(h,e.length-1);for(let r=Math.max(0,h-t.length+1);r<=u;r++){const c=h-r|0;n=0|t.words[c],s=0|e.words[r],a=n*s+o,i+=a/67108864|0,o=67108863&a}r.words[h]=0|o,c=0|i}return 0!==c?r.words[h]=0|c:r.length--,r.strip()}comb10MulTo(t,e,r){const i=t.words,n=e.words,s=r.words;let a,o,c,h=0;const u=0|i[0],l=8191&u,d=u>>>13,f=0|i[1],p=8191&f,m=f>>>13,w=0|i[2],b=8191&w,g=w>>>13,y=0|i[3],v=8191&y,I=y>>>13,k=0|i[4],P=8191&k,E=k>>>13,S=0|i[5],N=8191&S,O=S>>>13,x=0|i[6],A=8191&x,T=x>>>13,M=0|i[7],_=8191&M,F=M>>>13,R=0|i[8],C=8191&R,V=R>>>13,D=0|i[9],B=8191&D,U=D>>>13,H=0|n[0],K=8191&H,q=H>>>13,L=0|n[1],$=8191&L,z=L>>>13,j=0|n[2],W=8191&j,X=j>>>13,G=0|n[3],Y=8191&G,J=G>>>13,Z=0|n[4],Q=8191&Z,tt=Z>>>13,et=0|n[5],rt=8191&et,it=et>>>13,nt=0|n[6],st=8191&nt,at=nt>>>13,ot=0|n[7],ct=8191&ot,ht=ot>>>13,ut=0|n[8],lt=8191&ut,dt=ut>>>13,ft=0|n[9],pt=8191&ft,mt=ft>>>13;r.negative=t.negative^e.negative,r.length=19,a=Math.imul(l,K),o=Math.imul(l,q),o=o+Math.imul(d,K)|0,c=Math.imul(d,q);let wt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(wt>>>26)|0,wt&=67108863,a=Math.imul(p,K),o=Math.imul(p,q),o=o+Math.imul(m,K)|0,c=Math.imul(m,q),a=a+Math.imul(l,$)|0,o=o+Math.imul(l,z)|0,o=o+Math.imul(d,$)|0,c=c+Math.imul(d,z)|0;let bt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(bt>>>26)|0,bt&=67108863,a=Math.imul(b,K),o=Math.imul(b,q),o=o+Math.imul(g,K)|0,c=Math.imul(g,q),a=a+Math.imul(p,$)|0,o=o+Math.imul(p,z)|0,o=o+Math.imul(m,$)|0,c=c+Math.imul(m,z)|0,a=a+Math.imul(l,W)|0,o=o+Math.imul(l,X)|0,o=o+Math.imul(d,W)|0,c=c+Math.imul(d,X)|0;let gt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(gt>>>26)|0,gt&=67108863,a=Math.imul(v,K),o=Math.imul(v,q),o=o+Math.imul(I,K)|0,c=Math.imul(I,q),a=a+Math.imul(b,$)|0,o=o+Math.imul(b,z)|0,o=o+Math.imul(g,$)|0,c=c+Math.imul(g,z)|0,a=a+Math.imul(p,W)|0,o=o+Math.imul(p,X)|0,o=o+Math.imul(m,W)|0,c=c+Math.imul(m,X)|0,a=a+Math.imul(l,Y)|0,o=o+Math.imul(l,J)|0,o=o+Math.imul(d,Y)|0,c=c+Math.imul(d,J)|0;let yt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(yt>>>26)|0,yt&=67108863,a=Math.imul(P,K),o=Math.imul(P,q),o=o+Math.imul(E,K)|0,c=Math.imul(E,q),a=a+Math.imul(v,$)|0,o=o+Math.imul(v,z)|0,o=o+Math.imul(I,$)|0,c=c+Math.imul(I,z)|0,a=a+Math.imul(b,W)|0,o=o+Math.imul(b,X)|0,o=o+Math.imul(g,W)|0,c=c+Math.imul(g,X)|0,a=a+Math.imul(p,Y)|0,o=o+Math.imul(p,J)|0,o=o+Math.imul(m,Y)|0,c=c+Math.imul(m,J)|0,a=a+Math.imul(l,Q)|0,o=o+Math.imul(l,tt)|0,o=o+Math.imul(d,Q)|0,c=c+Math.imul(d,tt)|0;let vt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(vt>>>26)|0,vt&=67108863,a=Math.imul(N,K),o=Math.imul(N,q),o=o+Math.imul(O,K)|0,c=Math.imul(O,q),a=a+Math.imul(P,$)|0,o=o+Math.imul(P,z)|0,o=o+Math.imul(E,$)|0,c=c+Math.imul(E,z)|0,a=a+Math.imul(v,W)|0,o=o+Math.imul(v,X)|0,o=o+Math.imul(I,W)|0,c=c+Math.imul(I,X)|0,a=a+Math.imul(b,Y)|0,o=o+Math.imul(b,J)|0,o=o+Math.imul(g,Y)|0,c=c+Math.imul(g,J)|0,a=a+Math.imul(p,Q)|0,o=o+Math.imul(p,tt)|0,o=o+Math.imul(m,Q)|0,c=c+Math.imul(m,tt)|0,a=a+Math.imul(l,rt)|0,o=o+Math.imul(l,it)|0,o=o+Math.imul(d,rt)|0,c=c+Math.imul(d,it)|0;let It=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(It>>>26)|0,It&=67108863,a=Math.imul(A,K),o=Math.imul(A,q),o=o+Math.imul(T,K)|0,c=Math.imul(T,q),a=a+Math.imul(N,$)|0,o=o+Math.imul(N,z)|0,o=o+Math.imul(O,$)|0,c=c+Math.imul(O,z)|0,a=a+Math.imul(P,W)|0,o=o+Math.imul(P,X)|0,o=o+Math.imul(E,W)|0,c=c+Math.imul(E,X)|0,a=a+Math.imul(v,Y)|0,o=o+Math.imul(v,J)|0,o=o+Math.imul(I,Y)|0,c=c+Math.imul(I,J)|0,a=a+Math.imul(b,Q)|0,o=o+Math.imul(b,tt)|0,o=o+Math.imul(g,Q)|0,c=c+Math.imul(g,tt)|0,a=a+Math.imul(p,rt)|0,o=o+Math.imul(p,it)|0,o=o+Math.imul(m,rt)|0,c=c+Math.imul(m,it)|0,a=a+Math.imul(l,st)|0,o=o+Math.imul(l,at)|0,o=o+Math.imul(d,st)|0,c=c+Math.imul(d,at)|0;let kt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(kt>>>26)|0,kt&=67108863,a=Math.imul(_,K),o=Math.imul(_,q),o=o+Math.imul(F,K)|0,c=Math.imul(F,q),a=a+Math.imul(A,$)|0,o=o+Math.imul(A,z)|0,o=o+Math.imul(T,$)|0,c=c+Math.imul(T,z)|0,a=a+Math.imul(N,W)|0,o=o+Math.imul(N,X)|0,o=o+Math.imul(O,W)|0,c=c+Math.imul(O,X)|0,a=a+Math.imul(P,Y)|0,o=o+Math.imul(P,J)|0,o=o+Math.imul(E,Y)|0,c=c+Math.imul(E,J)|0,a=a+Math.imul(v,Q)|0,o=o+Math.imul(v,tt)|0,o=o+Math.imul(I,Q)|0,c=c+Math.imul(I,tt)|0,a=a+Math.imul(b,rt)|0,o=o+Math.imul(b,it)|0,o=o+Math.imul(g,rt)|0,c=c+Math.imul(g,it)|0,a=a+Math.imul(p,st)|0,o=o+Math.imul(p,at)|0,o=o+Math.imul(m,st)|0,c=c+Math.imul(m,at)|0,a=a+Math.imul(l,ct)|0,o=o+Math.imul(l,ht)|0,o=o+Math.imul(d,ct)|0,c=c+Math.imul(d,ht)|0;let Pt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,a=Math.imul(C,K),o=Math.imul(C,q),o=o+Math.imul(V,K)|0,c=Math.imul(V,q),a=a+Math.imul(_,$)|0,o=o+Math.imul(_,z)|0,o=o+Math.imul(F,$)|0,c=c+Math.imul(F,z)|0,a=a+Math.imul(A,W)|0,o=o+Math.imul(A,X)|0,o=o+Math.imul(T,W)|0,c=c+Math.imul(T,X)|0,a=a+Math.imul(N,Y)|0,o=o+Math.imul(N,J)|0,o=o+Math.imul(O,Y)|0,c=c+Math.imul(O,J)|0,a=a+Math.imul(P,Q)|0,o=o+Math.imul(P,tt)|0,o=o+Math.imul(E,Q)|0,c=c+Math.imul(E,tt)|0,a=a+Math.imul(v,rt)|0,o=o+Math.imul(v,it)|0,o=o+Math.imul(I,rt)|0,c=c+Math.imul(I,it)|0,a=a+Math.imul(b,st)|0,o=o+Math.imul(b,at)|0,o=o+Math.imul(g,st)|0,c=c+Math.imul(g,at)|0,a=a+Math.imul(p,ct)|0,o=o+Math.imul(p,ht)|0,o=o+Math.imul(m,ct)|0,c=c+Math.imul(m,ht)|0,a=a+Math.imul(l,lt)|0,o=o+Math.imul(l,dt)|0,o=o+Math.imul(d,lt)|0,c=c+Math.imul(d,dt)|0;let Et=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(Et>>>26)|0,Et&=67108863,a=Math.imul(B,K),o=Math.imul(B,q),o=o+Math.imul(U,K)|0,c=Math.imul(U,q),a=a+Math.imul(C,$)|0,o=o+Math.imul(C,z)|0,o=o+Math.imul(V,$)|0,c=c+Math.imul(V,z)|0,a=a+Math.imul(_,W)|0,o=o+Math.imul(_,X)|0,o=o+Math.imul(F,W)|0,c=c+Math.imul(F,X)|0,a=a+Math.imul(A,Y)|0,o=o+Math.imul(A,J)|0,o=o+Math.imul(T,Y)|0,c=c+Math.imul(T,J)|0,a=a+Math.imul(N,Q)|0,o=o+Math.imul(N,tt)|0,o=o+Math.imul(O,Q)|0,c=c+Math.imul(O,tt)|0,a=a+Math.imul(P,rt)|0,o=o+Math.imul(P,it)|0,o=o+Math.imul(E,rt)|0,c=c+Math.imul(E,it)|0,a=a+Math.imul(v,st)|0,o=o+Math.imul(v,at)|0,o=o+Math.imul(I,st)|0,c=c+Math.imul(I,at)|0,a=a+Math.imul(b,ct)|0,o=o+Math.imul(b,ht)|0,o=o+Math.imul(g,ct)|0,c=c+Math.imul(g,ht)|0,a=a+Math.imul(p,lt)|0,o=o+Math.imul(p,dt)|0,o=o+Math.imul(m,lt)|0,c=c+Math.imul(m,dt)|0,a=a+Math.imul(l,pt)|0,o=o+Math.imul(l,mt)|0,o=o+Math.imul(d,pt)|0,c=c+Math.imul(d,mt)|0;let St=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(St>>>26)|0,St&=67108863,a=Math.imul(B,$),o=Math.imul(B,z),o=o+Math.imul(U,$)|0,c=Math.imul(U,z),a=a+Math.imul(C,W)|0,o=o+Math.imul(C,X)|0,o=o+Math.imul(V,W)|0,c=c+Math.imul(V,X)|0,a=a+Math.imul(_,Y)|0,o=o+Math.imul(_,J)|0,o=o+Math.imul(F,Y)|0,c=c+Math.imul(F,J)|0,a=a+Math.imul(A,Q)|0,o=o+Math.imul(A,tt)|0,o=o+Math.imul(T,Q)|0,c=c+Math.imul(T,tt)|0,a=a+Math.imul(N,rt)|0,o=o+Math.imul(N,it)|0,o=o+Math.imul(O,rt)|0,c=c+Math.imul(O,it)|0,a=a+Math.imul(P,st)|0,o=o+Math.imul(P,at)|0,o=o+Math.imul(E,st)|0,c=c+Math.imul(E,at)|0,a=a+Math.imul(v,ct)|0,o=o+Math.imul(v,ht)|0,o=o+Math.imul(I,ct)|0,c=c+Math.imul(I,ht)|0,a=a+Math.imul(b,lt)|0,o=o+Math.imul(b,dt)|0,o=o+Math.imul(g,lt)|0,c=c+Math.imul(g,dt)|0,a=a+Math.imul(p,pt)|0,o=o+Math.imul(p,mt)|0,o=o+Math.imul(m,pt)|0,c=c+Math.imul(m,mt)|0;let Nt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(Nt>>>26)|0,Nt&=67108863,a=Math.imul(B,W),o=Math.imul(B,X),o=o+Math.imul(U,W)|0,c=Math.imul(U,X),a=a+Math.imul(C,Y)|0,o=o+Math.imul(C,J)|0,o=o+Math.imul(V,Y)|0,c=c+Math.imul(V,J)|0,a=a+Math.imul(_,Q)|0,o=o+Math.imul(_,tt)|0,o=o+Math.imul(F,Q)|0,c=c+Math.imul(F,tt)|0,a=a+Math.imul(A,rt)|0,o=o+Math.imul(A,it)|0,o=o+Math.imul(T,rt)|0,c=c+Math.imul(T,it)|0,a=a+Math.imul(N,st)|0,o=o+Math.imul(N,at)|0,o=o+Math.imul(O,st)|0,c=c+Math.imul(O,at)|0,a=a+Math.imul(P,ct)|0,o=o+Math.imul(P,ht)|0,o=o+Math.imul(E,ct)|0,c=c+Math.imul(E,ht)|0,a=a+Math.imul(v,lt)|0,o=o+Math.imul(v,dt)|0,o=o+Math.imul(I,lt)|0,c=c+Math.imul(I,dt)|0,a=a+Math.imul(b,pt)|0,o=o+Math.imul(b,mt)|0,o=o+Math.imul(g,pt)|0,c=c+Math.imul(g,mt)|0;let Ot=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,a=Math.imul(B,Y),o=Math.imul(B,J),o=o+Math.imul(U,Y)|0,c=Math.imul(U,J),a=a+Math.imul(C,Q)|0,o=o+Math.imul(C,tt)|0,o=o+Math.imul(V,Q)|0,c=c+Math.imul(V,tt)|0,a=a+Math.imul(_,rt)|0,o=o+Math.imul(_,it)|0,o=o+Math.imul(F,rt)|0,c=c+Math.imul(F,it)|0,a=a+Math.imul(A,st)|0,o=o+Math.imul(A,at)|0,o=o+Math.imul(T,st)|0,c=c+Math.imul(T,at)|0,a=a+Math.imul(N,ct)|0,o=o+Math.imul(N,ht)|0,o=o+Math.imul(O,ct)|0,c=c+Math.imul(O,ht)|0,a=a+Math.imul(P,lt)|0,o=o+Math.imul(P,dt)|0,o=o+Math.imul(E,lt)|0,c=c+Math.imul(E,dt)|0,a=a+Math.imul(v,pt)|0,o=o+Math.imul(v,mt)|0,o=o+Math.imul(I,pt)|0,c=c+Math.imul(I,mt)|0;let xt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(xt>>>26)|0,xt&=67108863,a=Math.imul(B,Q),o=Math.imul(B,tt),o=o+Math.imul(U,Q)|0,c=Math.imul(U,tt),a=a+Math.imul(C,rt)|0,o=o+Math.imul(C,it)|0,o=o+Math.imul(V,rt)|0,c=c+Math.imul(V,it)|0,a=a+Math.imul(_,st)|0,o=o+Math.imul(_,at)|0,o=o+Math.imul(F,st)|0,c=c+Math.imul(F,at)|0,a=a+Math.imul(A,ct)|0,o=o+Math.imul(A,ht)|0,o=o+Math.imul(T,ct)|0,c=c+Math.imul(T,ht)|0,a=a+Math.imul(N,lt)|0,o=o+Math.imul(N,dt)|0,o=o+Math.imul(O,lt)|0,c=c+Math.imul(O,dt)|0,a=a+Math.imul(P,pt)|0,o=o+Math.imul(P,mt)|0,o=o+Math.imul(E,pt)|0,c=c+Math.imul(E,mt)|0;let At=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(At>>>26)|0,At&=67108863,a=Math.imul(B,rt),o=Math.imul(B,it),o=o+Math.imul(U,rt)|0,c=Math.imul(U,it),a=a+Math.imul(C,st)|0,o=o+Math.imul(C,at)|0,o=o+Math.imul(V,st)|0,c=c+Math.imul(V,at)|0,a=a+Math.imul(_,ct)|0,o=o+Math.imul(_,ht)|0,o=o+Math.imul(F,ct)|0,c=c+Math.imul(F,ht)|0,a=a+Math.imul(A,lt)|0,o=o+Math.imul(A,dt)|0,o=o+Math.imul(T,lt)|0,c=c+Math.imul(T,dt)|0,a=a+Math.imul(N,pt)|0,o=o+Math.imul(N,mt)|0,o=o+Math.imul(O,pt)|0,c=c+Math.imul(O,mt)|0;let Tt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,a=Math.imul(B,st),o=Math.imul(B,at),o=o+Math.imul(U,st)|0,c=Math.imul(U,at),a=a+Math.imul(C,ct)|0,o=o+Math.imul(C,ht)|0,o=o+Math.imul(V,ct)|0,c=c+Math.imul(V,ht)|0,a=a+Math.imul(_,lt)|0,o=o+Math.imul(_,dt)|0,o=o+Math.imul(F,lt)|0,c=c+Math.imul(F,dt)|0,a=a+Math.imul(A,pt)|0,o=o+Math.imul(A,mt)|0,o=o+Math.imul(T,pt)|0,c=c+Math.imul(T,mt)|0;let Mt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,a=Math.imul(B,ct),o=Math.imul(B,ht),o=o+Math.imul(U,ct)|0,c=Math.imul(U,ht),a=a+Math.imul(C,lt)|0,o=o+Math.imul(C,dt)|0,o=o+Math.imul(V,lt)|0,c=c+Math.imul(V,dt)|0,a=a+Math.imul(_,pt)|0,o=o+Math.imul(_,mt)|0,o=o+Math.imul(F,pt)|0,c=c+Math.imul(F,mt)|0;let _t=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(_t>>>26)|0,_t&=67108863,a=Math.imul(B,lt),o=Math.imul(B,dt),o=o+Math.imul(U,lt)|0,c=Math.imul(U,dt),a=a+Math.imul(C,pt)|0,o=o+Math.imul(C,mt)|0,o=o+Math.imul(V,pt)|0,c=c+Math.imul(V,mt)|0;let Ft=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(Ft>>>26)|0,Ft&=67108863,a=Math.imul(B,pt),o=Math.imul(B,mt),o=o+Math.imul(U,pt)|0,c=Math.imul(U,mt);let Rt=(h+a|0)+((8191&o)<<13)|0;return h=(c+(o>>>13)|0)+(Rt>>>26)|0,Rt&=67108863,s[0]=wt,s[1]=bt,s[2]=gt,s[3]=yt,s[4]=vt,s[5]=It,s[6]=kt,s[7]=Pt,s[8]=Et,s[9]=St,s[10]=Nt,s[11]=Ot,s[12]=xt,s[13]=At,s[14]=Tt,s[15]=Mt,s[16]=_t,s[17]=Ft,s[18]=Rt,0!==h&&(s[19]=h,r.length++),r}bigMulTo(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;let i=0,n=0,s=0;for(;s<r.length-1;s++){let a=n;n=0;let o=67108863&i;const c=Math.min(s,e.length-1);for(let r=Math.max(0,s-t.length+1);r<=c;r++){const i=s-r,c=(0|t.words[i])*(0|e.words[r]);let h=67108863&c;a=a+(c/67108864|0)|0,h=h+o|0,o=67108863&h,a=a+(h>>>26)|0,n+=a>>>26,a&=67108863}r.words[s]=o,i=a,a=n}return 0!==i?r.words[s]=i:r.length--,r.strip()}mulTo(t,e){let r;const i=this.length+t.length;return r=10===this.length&&10===t.length?this.comb10MulTo(this,t,e):i<63?this.smallMulTo(this,t,e):this.bigMulTo(this,t,e),r}mul(t){const e=new h;return e.words=new Array(this.length+t.length),this.mulTo(t,e)}imul(t){return this.clone().mulTo(t,this)}imuln(t){const e=t<0;e&&(t=-t),this.assert("number"==typeof t),this.assert(t<67108864);let r=0,i=0;for(;i<this.length;i++){const e=(0|this.words[i])*t,n=(67108863&e)+(67108863&r);r>>=26,r+=e/67108864|0,r+=n>>>26,this.words[i]=67108863&n}return 0!==r&&(this.words[i]=r,this.length++),e?this.ineg():this}muln(t){return this.clone().imuln(t)}sqr(){return this.mul(this)}isqr(){return this.imul(this.clone())}pow(t){const e=h.toBitArray(t);if(0===e.length)return new h(1);let r=this,i=0;for(;i<e.length&&0===e[i];i++,r=r.sqr());if(++i<e.length)for(let t=r.sqr();i<e.length;i++,t=t.sqr())0!==e[i]&&(r=r.mul(t));return r}iushln(t){this.assert("number"==typeof t&&t>=0);const e=t%26,r=(t-e)/26,i=67108863>>>26-e<<26-e;let n;if(0!==e){let t=0;for(n=0;n<this.length;n++){const r=this.words[n]&i,s=(0|this.words[n])-r<<e;this.words[n]=s|t,t=r>>>26-e}0!==t&&(this.words[n]=t,this.length++)}if(0!==r){for(n=this.length-1;n>=0;n--)this.words[n+r]=this.words[n];for(n=0;n<r;n++)this.words[n]=0;this.length+=r}return this.strip()}ishln(t){return this.assert(0===this.negative),this.iushln(t)}iushrn(t,e,r){let i;this.assert("number"==typeof t&&t>=0),i="number"==typeof e&&0!==e?(e-e%26)/26:0;const n=t%26,s=Math.min((t-n)/26,this.length),a=67108863^67108863>>>n<<n,o=r;i-=s,i=Math.max(0,i);let c=0;if(void 0!==o){for(;c<s;c++)o.words[c]=this.words[c];o.length=s}if(0===s);else if(this.length>s)for(this.length-=s,c=0;c<this.length;c++)this.words[c]=this.words[c+s];else this.words[0]=0,this.length=1;let h=0;for(c=this.length-1;c>=0&&(0!==h||c>=i);c--){const t=0|this.words[c];this.words[c]=h<<26-n|t>>>n,h=t&a}return null!=o&&0!==h&&(o.words[o.length++]=h),0===this.length&&(this.words[0]=0,this.length=1),this.strip()}ishrn(t,e,r){return this.assert(0===this.negative),this.iushrn(t,e,r)}shln(t){return this.clone().ishln(t)}ushln(t){return this.clone().iushln(t)}shrn(t){return this.clone().ishrn(t)}ushrn(t){return this.clone().iushrn(t)}testn(t){this.assert("number"==typeof t&&t>=0);const e=t%26,r=(t-e)/26,i=1<<e;if(this.length<=r)return!1;const n=this.words[r];return Boolean(n&i)}imaskn(t){this.assert("number"==typeof t&&t>=0);const e=t%26;let r=(t-e)/26;if(this.assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==e&&r++,this.length=Math.min(r,this.length),0!==e){const t=67108863^67108863>>>e<<e;this.words[this.length-1]&=t}return this.strip()}maskn(t){return this.clone().imaskn(t)}iaddn(t){return this.assert("number"==typeof t),this.assert(t<67108864,"num is too large"),t<0?this.isubn(-t):0!==this.negative?1===this.length&&(0|this.words[0])<=t?(this.words[0]=t-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(t),this.negative=1,this):this._iaddn(t)}_iaddn(t){this.words[0]+=t;let e=0;for(;e<this.length&&this.words[e]>=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this}isubn(t){if(this.assert("number"==typeof t),this.assert(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(let t=0;t<this.length&&this.words[t]<0;t++)this.words[t]+=67108864,this.words[t+1]-=1;return this.strip()}addn(t){return this.clone().iaddn(t)}subn(t){return this.clone().isubn(t)}iabs(){return this.negative=0,this}abs(){return this.clone().iabs()}_ishlnsubmul(t,e,r){const i=t.length+r;let n,s;this.expand(i);let a=0;for(n=0;n<t.length;n++){s=(0|this.words[n+r])+a;const i=(0|t.words[n])*e;s-=67108863&i,a=(s>>26)-(i/67108864|0),this.words[n+r]=67108863&s}for(;n<this.length-r;n++)s=(0|this.words[n+r])+a,a=s>>26,this.words[n+r]=67108863&s;if(0===a)return this.strip();for(this.assert(-1===a,"carry must be -1"),a=0,n=0;n<this.length;n++)s=-(0|this.words[n])+a,a=s>>26,this.words[n]=67108863&s;return this.negative=1,this.strip()}wordDiv(t,e){let r=this.length-t.length,i=this.clone(),n=t,s=0|n.words[n.length-1];r=26-this.countWordBits(s),0!==r&&(n=n.ushln(r),i.iushln(r),s=0|n.words[n.length-1]);const a=i.length-n.length;let o;if("mod"!==e){o=new h,o.length=a+1,o.words=new Array(o.length);for(let t=0;t<o.length;t++)o.words[t]=0}const c=i.clone()._ishlnsubmul(n,1,a);0===c.negative&&(i=c,void 0!==o&&(o.words[a]=1));for(let t=a-1;t>=0;t--){let e=67108864*(0|i.words[n.length+t])+(0|i.words[n.length+t-1]);for(e=Math.min(e/s|0,67108863),i._ishlnsubmul(n,e,t);0!==i.negative;)e--,i.negative=0,i._ishlnsubmul(n,1,t),i.isZero()||(i.negative^=1);void 0!==o&&(o.words[t]=e)}return void 0!==o&&o.strip(),i.strip(),"div"!==e&&0!==r&&i.iushrn(r),{div:o??null,mod:i}}divmod(t,e,r){if(this.assert(!t.isZero()),this.isZero())return{div:new h(0),mod:new h(0)};let i,n,s;return 0!==this.negative&&0===t.negative?(s=this.neg().divmod(t,e),"mod"!==e&&(i=s.div.neg()),"div"!==e&&(n=s.mod.neg(),!0===r&&0!==n.negative&&n.iadd(t)),{div:i,mod:n}):0===this.negative&&0!==t.negative?(s=this.divmod(t.neg(),e),"mod"!==e&&(i=s.div.neg()),{div:i,mod:s.mod}):this.negative&t.negative?(s=this.neg().divmod(t.neg(),e),"div"!==e&&(n=s.mod.neg(),!0===r&&0!==n.negative&&n.isub(t)),{div:s.div,mod:n}):t.length>this.length||this.cmp(t)<0?{div:new h(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new h(this.modrn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new h(this.modrn(t.words[0]))}:this.wordDiv(t,e)}div(t){return this.divmod(t,"div",!1).div}mod(t){return this.divmod(t,"mod",!1).mod}umod(t){return this.divmod(t,"mod",!0).mod}divRound(t){const e=this.divmod(t);if(e.mod.isZero())return e.div;const r=0!==e.div.negative?e.mod.isub(t):e.mod,i=t.ushrn(1),n=t.andln(1),s=r.cmp(i);return s<0||1===n&&0===s?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)}modrn(t){const e=t<0;e&&(t=-t),this.assert(t<=67108863);const r=(1<<26)%t;let i=0;for(let e=this.length-1;e>=0;e--)i=(r*i+(0|this.words[e]))%t;return e?-i:i}idivn(t){const e=t<0;e&&(t=-t),this.assert(t<=67108863);let r=0;for(let e=this.length-1;e>=0;e--){const i=(0|this.words[e])+67108864*r;this.words[e]=i/t|0,r=i%t}return this.strip(),e?this.ineg():this}divn(t){return this.clone().idivn(t)}egcd(t){this.assert(0===t.negative,"p must not be negative"),this.assert(!t.isZero(),"p must not be zero");let e=this;const r=t.clone();e=0!==e.negative?e.umod(t):e.clone();const i=new h(1),n=new h(0),s=new h(0),a=new h(1);let o=0;for(;e.isEven()&&r.isEven();)e.iushrn(1),r.iushrn(1),++o;const c=r.clone(),u=e.clone();for(;!e.isZero();){let t=0,o=1;for(;!(e.words[0]&o)&&t<26;++t,o<<=1);if(t>0)for(e.iushrn(t);t-- >0;)(i.isOdd()||n.isOdd())&&(i.iadd(c),n.isub(u)),i.iushrn(1),n.iushrn(1);let h=0,l=1;for(;!(r.words[0]&l)&&h<26;++h,l<<=1);if(h>0)for(r.iushrn(h);h-- >0;)(s.isOdd()||a.isOdd())&&(s.iadd(c),a.isub(u)),s.iushrn(1),a.iushrn(1);e.cmp(r)>=0?(e.isub(r),i.isub(s),n.isub(a)):(r.isub(e),s.isub(i),a.isub(n))}return{a:s,b:a,gcd:r.iushln(o)}}_invmp(t){this.assert(0===t.negative,"p must not be negative"),this.assert(!t.isZero(),"p must not be zero");let e=this;const r=t.clone();e=0!==e.negative?e.umod(t):e.clone();const i=new h(1),n=new h(0),s=r.clone();for(;e.cmpn(1)>0&&r.cmpn(1)>0;){let t=0,a=1;for(;!(e.words[0]&a)&&t<26;++t,a<<=1);if(t>0)for(e.iushrn(t);t-- >0;)i.isOdd()&&i.iadd(s),i.iushrn(1);let o=0,c=1;for(;!(r.words[0]&c)&&o<26;++o,c<<=1);if(o>0)for(r.iushrn(o);o-- >0;)n.isOdd()&&n.iadd(s),n.iushrn(1);e.cmp(r)>=0?(e.isub(r),i.isub(n)):(r.isub(e),n.isub(i))}let a;return a=0===e.cmpn(1)?i:n,a.cmpn(0)<0&&a.iadd(t),a}gcd(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();let e=this.clone(),r=t.clone();e.negative=0,r.negative=0;let i=0;for(;e.isEven()&&r.isEven();i++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);const t=e.cmp(r);if(t<0){const t=e;e=r,r=t}else if(0===t||0===r.cmpn(1))break;e.isub(r)}return r.iushln(i)}invm(t){return this.egcd(t).a.umod(t)}isEven(){return!(1&this.words[0])}isOdd(){return!(1&~this.words[0])}andln(t){return this.words[0]&t}bincn(t){this.assert("number"==typeof t);const e=t%26,r=(t-e)/26,i=1<<e;if(this.length<=r)return this.expand(r+1),this.words[r]|=i,this;let n=i,s=r;for(;0!==n&&s<this.length;s++){let t=0|this.words[s];t+=n,n=t>>>26,t&=67108863,this.words[s]=t}return 0!==n&&(this.words[s]=n,this.length++),this}isZero(){return 1===this.length&&0===this.words[0]}cmpn(t){const e=t<0;if(0!==this.negative&&!e)return-1;if(0===this.negative&&e)return 1;let r;if(this.strip(),this.length>1)r=1;else{e&&(t=-t),this.assert(t<=67108863,"Number is too big");const i=0|this.words[0];r=i===t?0:i<t?-1:1}return 0!==this.negative?0|-r:r}cmp(t){if(0!==this.negative&&0===t.negative)return-1;if(0===this.negative&&0!==t.negative)return 1;const e=this.ucmp(t);return 0!==this.negative?0|-e:e}ucmp(t){if(this.length>t.length)return 1;if(this.length<t.length)return-1;let e=0;for(let r=this.length-1;r>=0;r--){const i=0|this.words[r],n=0|t.words[r];if(i!==n){i<n?e=-1:i>n&&(e=1);break}}return e}gtn(t){return 1===this.cmpn(t)}gt(t){return 1===this.cmp(t)}gten(t){return this.cmpn(t)>=0}gte(t){return this.cmp(t)>=0}ltn(t){return-1===this.cmpn(t)}lt(t){return-1===this.cmp(t)}lten(t){return this.cmpn(t)<=0}lte(t){return this.cmp(t)<=0}eqn(t){return 0===this.cmpn(t)}eq(t){return 0===this.cmp(t)}toRed(t){return this.assert(null==this.red,"Already a number in reduction context"),this.assert(0===this.negative,"red works only with positives"),t.convertTo(this).forceRed(t)}fromRed(){return this.assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)}forceRed(t){return this.red=t,this}redAdd(t){return this.assert(this.red,"redAdd works only with red numbers"),this.red.add(this,t)}redIAdd(t){return this.assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)}redSub(t){return this.assert(this.red,"redSub works only with red numbers"),this.red.sub(this,t)}redISub(t){return this.assert(this.red,"redISub works only with red numbers"),this.red.isub(this,t)}redShl(t){return this.assert(this.red,"redShl works only with red numbers"),this.red.shl(this,t)}redMul(t){return this.assert(this.red,"redMul works only with red numbers"),this.red.verify2(this,t),this.red.mul(this,t)}redIMul(t){return this.assert(this.red,"redMul works only with red numbers"),this.red.verify2(this,t),this.red.imul(this,t)}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(t){return this.assert(null!=this.red&&null==t.red,"redPow(normalNum)"),this.red.verify1(this),this.red.pow(this,t)}static fromHex(t,e){return"big"===e?new h(t,16):new h(t,16,"le")}toHex(t=0){return this.toString("hex",2*t)}static fromJSON(t){return new h(t)}static fromNumber(t){return new h(t)}static fromString(t,e){return new h(t,e)}static fromSm(t,e="big"){let r=t;return 0===t.length?new h(0):("little"===e&&(r=[...r],r=r.reverse()),128&r[0]?(r=[...r],r[0]=127&r[0],new h(r).neg()):new h(r))}toSm(t="big"){let e;return-1===this.cmpn(0)?(e=this.neg().toArray(),128&e[0]?e=[128,...e]:e[0]=128|e[0]):(e=this.toArray(),128&e[0]&&(e=[0,...e])),1===e.length&&0===e[0]&&(e=[]),"little"===t&&(e=e.reverse()),e}static fromBits(t,e=!1){if(t=2147483648&t?t-4294967296:t,e&&8388608&t)throw new Error("negative bit set");const r=t>>24,i=8388607&t;let n=[i>>24&255,i>>16&255,i>>8&255,255&i];if(r<=3)n=n.slice(1,1+r);else for(let t=0;t<r-3;t++)n.push(0);return 8388608&t?new h(n).neg():new h(n)}toBits(){let t;for(t=this.ltn(0)?this.neg().toArray("be"):this.toArray("be");t.length<4;)t.unshift(0);if(t.every((t=>0===t)))return 0;for(;0===t[0];)t.shift();let e=t.length,r=t.slice(0,3).reduce(((t,e)=>256*t+e),0);8388608&r&&(t.unshift(0),e+=1,r>>>=8);let i=e<<24|r;return this.ltn(0)&&(i|=8388608),i>>>0}static fromScriptNum(t,e,r){if(void 0===r&&(r=Number.MAX_SAFE_INTEGER),t.length>r)throw new Error("script number overflow");if(!0===e&&t.length>0&&!(127&t[t.length-1]||!(t.length<=1)&&128&t[t.length-2]))throw new Error("non-minimally encoded script number");return h.fromSm(t,"little")}toScriptNum(){return this.toSm("little")}}class u{name;p;k;n;tmp;constructor(t,e){this.name=t,this.p=new h(e,16),this.n=this.p.bitLength(),this.k=new h(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}_tmp(){const t=new h;return t.words=new Array(Math.ceil(this.n/13)),t}ireduce(t){let e,r=t;do{this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),e=r.bitLength()}while(e>this.n);const i=e<this.n?-1:r.ucmp(this.p);return 0===i?(r.words[0]=0,r.length=1):i>0?r.isub(this.p):(r.strip,r.strip()),r}split(t,e){t.iushrn(this.n,0,e)}imulK(t){return t.imul(this.k)}}class l extends u{constructor(){super("k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}split(t,e){const r=4194303,i=Math.min(t.length,9);let n=0;for(;n<i;n++)e.words[n]=t.words[n];if(e.length=i,t.length<=9)return t.words[0]=0,void(t.length=1);let s=t.words[9];for(e.words[e.length++]=s&r,n=10;n<t.length;n++){const e=0|t.words[n];t.words[n-10]=(e&r)<<4|s>>>22,s=e}s>>>=22,t.words[n-10]=s,0===s&&t.length>10?t.length-=10:t.length-=9}imulK(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;let e=0;for(let r=0;r<t.length;r++){const i=0|t.words[r];e+=977*i,t.words[r]=67108863&e,e=64*i+(e/67108864|0)}return 0===t.words[t.length-1]&&(t.length--,0===t.words[t.length-1]&&t.length--),t}}class d{prime;m;constructor(t){if("k256"===t){const t=new l;this.m=t.p,this.prime=t}else this.assert(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}assert(t,e="Assertion failed"){if(!t)throw new Error(e)}verify1(t){this.assert(0===t.negative,"red works only with positives"),this.assert(t.red,"red works only with red numbers")}verify2(t,e){this.assert(!(t.negative|e.negative),"red works only with positives"),this.assert(null!=t.red&&t.red===e.red,"red works only with red numbers")}imod(t){return null!=this.prime?this.prime.ireduce(t).forceRed(this):(h.move(t,t.umod(this.m).forceRed(this)),t)}neg(t){return t.isZero()?t.clone():this.m.sub(t).forceRed(this)}add(t,e){this.verify2(t,e);const r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r.forceRed(this)}iadd(t,e){this.verify2(t,e);const r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r}sub(t,e){this.verify2(t,e);const r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r.forceRed(this)}isub(t,e){this.verify2(t,e);const r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r}shl(t,e){return this.verify1(t),this.imod(t.ushln(e))}imul(t,e){return this.verify2(t,e),this.imod(t.imul(e))}mul(t,e){return this.verify2(t,e),this.imod(t.mul(e))}isqr(t){return this.imul(t,t.clone())}sqr(t){return this.mul(t,t)}sqrt(t){if(t.isZero())return t.clone();const e=this.m.andln(3);if(this.assert(e%2==1),3===e){const e=this.m.add(new h(1)).iushrn(2);return this.pow(t,e)}const r=this.m.subn(1);let i=0;for(;!r.isZero()&&0===r.andln(1);)i++,r.iushrn(1);this.assert(!r.isZero());const n=new h(1).toRed(this),s=n.redNeg(),a=this.m.subn(1).iushrn(1),o=this.m.bitLength(),c=new h(2*o*o).toRed(this);for(;0!==this.pow(c,a).cmp(s);)c.redIAdd(s);let u=this.pow(c,r),l=this.pow(t,r.addn(1).iushrn(1)),d=this.pow(t,r),f=i;for(;0!==d.cmp(n);){let t=d,e=0;for(;0!==t.cmp(n);e++)t=t.redSqr();this.assert(e<f);const r=this.pow(u,new h(1).iushln(f-e-1));l=l.redMul(r),u=r.redSqr(),d=d.redMul(u),f=e}return l}invm(t){const e=t._invmp(this.m);return 0!==e.negative?(e.negative=0,this.imod(e).redNeg()):this.imod(e)}pow(t,e){if(e.isZero())return new h(1).toRed(this);if(0===e.cmpn(1))return t.clone();const r=new Array(16);r[0]=new h(1).toRed(this),r[1]=t;let i=2;for(;i<r.length;i++)r[i]=this.mul(r[i-1],t);let n=r[0],s=0,a=0,o=e.bitLength()%26;for(0===o&&(o=26),i=e.length-1;i>=0;i--){const t=e.words[i];for(let e=o-1;e>=0;e--){const o=t>>e&1;n!==r[0]&&(n=this.sqr(n)),0!==o||0!==s?(s<<=1,s|=o,a++,(4===a||0===i&&0===e)&&(n=this.mul(n,r[s]),a=0,s=0)):a=0}o=26}return n}convertTo(t){const e=t.umod(this.m);return e===t?e.clone():e}convertFrom(t){const e=t.clone();return e.red=null,e}}class f extends d{shift;r;r2;rinv;minv;constructor(t){super(t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new h(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(t){return this.imod(t.ushln(this.shift))}convertFrom(t){const e=this.imod(t.mul(this.rinv));return e.red=null,e}imul(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;const r=t.imul(e),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=r.isub(i).iushrn(this.shift);let s=n;return n.cmp(this.m)>=0?s=n.isub(this.m):n.cmpn(0)<0&&(s=n.iadd(this.m)),s.forceRed(this)}mul(t,e){if(t.isZero()||e.isZero())return new h(0).forceRed(this);const r=t.mul(e),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=r.isub(i).iushrn(this.shift);let s=n;return n.cmp(this.m)>=0?s=n.isub(this.m):n.cmpn(0)<0&&(s=n.iadd(this.m)),s.forceRed(this)}invm(t){return this.imod(t._invmp(this.m).mul(this.r2)).forceRed(this)}}class p{curve;type;precomputed;constructor(t){this.curve=new Lt,this.type=t,this.precomputed=null}}class m extends p{x;y;z;zOne;constructor(t,e,r){super("jacobian"),null===t&&null===e&&null===r?(this.x=this.curve.one,this.y=this.curve.one,this.z=new h(0)):(h.isBN(t)||(t=new h(t,16)),this.x=t,h.isBN(e)||(e=new h(e,16)),this.y=e,h.isBN(r)||(r=new h(r,16)),this.z=r),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}toP(){if(this.isInfinity())return new Kt(null,null);const t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),i=this.y.redMul(e).redMul(t);return new Kt(r,i)}neg(){return new m(this.x,this.y.redNeg(),this.z)}add(t){if(this.isInfinity())return t;if(t.isInfinity())return this;const e=t.z.redSqr(),r=this.z.redSqr(),i=this.x.redMul(e),n=t.x.redMul(r),s=this.y.redMul(e.redMul(t.z)),a=t.y.redMul(r.redMul(this.z)),o=i.redSub(n),c=s.redSub(a);if(0===o.cmpn(0))return 0!==c.cmpn(0)?new m(null,null,null):this.dbl();const h=o.redSqr(),u=h.redMul(o),l=i.redMul(h),d=c.redSqr().redIAdd(u).redISub(l).redISub(l),f=c.redMul(l.redISub(d)).redISub(s.redMul(u)),p=this.z.redMul(t.z).redMul(o);return new m(d,f,p)}mixedAdd(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;if(null===t.x||null===t.y)throw new Error("Point coordinates cannot be null");const e=this.z.redSqr(),r=this.x,i=t.x.redMul(e),n=this.y,s=t.y.redMul(e).redMul(this.z),a=r.redSub(i),o=n.redSub(s);if(0===a.cmpn(0))return 0!==o.cmpn(0)?new m(null,null,null):this.dbl();const c=a.redSqr(),h=c.redMul(a),u=r.redMul(c),l=o.redSqr().redIAdd(h).redISub(u).redISub(u),d=o.redMul(u.redISub(l)).redISub(n.redMul(h)),f=this.z.redMul(a);return new m(l,d,f)}dblp(t){if(0===t)return this;if(this.isInfinity())return this;if(void 0===t)return this.dbl();let e=this;for(let r=0;r<t;r++)e=e.dbl();return e}dbl(){if(this.isInfinity())return this;let t,e,r;if(this.zOne){const i=this.x.redSqr(),n=this.y.redSqr(),s=n.redSqr();let a=this.x.redAdd(n).redSqr().redISub(i).redISub(s);a=a.redIAdd(a);const o=i.redAdd(i).redIAdd(i),c=o.redSqr().redISub(a).redISub(a);let h=s.redIAdd(s);h=h.redIAdd(h),h=h.redIAdd(h),t=c,e=o.redMul(a.redISub(c)).redISub(h),r=this.y.redAdd(this.y)}else{const i=this.x.redSqr(),n=this.y.redSqr(),s=n.redSqr();let a=this.x.redAdd(n).redSqr().redISub(i).redISub(s);a=a.redIAdd(a);const o=i.redAdd(i).redIAdd(i),c=o.redSqr();let h=s.redIAdd(s);h=h.redIAdd(h),h=h.redIAdd(h),t=c.redISub(a).redISub(a),e=o.redMul(a.redISub(t)).redISub(h),r=this.y.redMul(this.z),r=r.redIAdd(r)}return new m(t,e,r)}eq(t){if("affine"===t.type)return this.eq(t.toJ());if(this===t)return!0;const e=this.z.redSqr(),r=t.z.redSqr();if(0!==this.x.redMul(r).redISub(t.x.redMul(e)).cmpn(0))return!1;const i=e.redMul(this.z),n=r.redMul(t.z);return 0===this.y.redMul(n).redISub(t.y.redMul(i)).cmpn(0)}eqXToP(t){const e=this.z.redSqr(),r=t.toRed(this.curve?.red).redMul(e);if(0===this.x.cmp(r))return!0;const i=t.clone();if(null===this.curve||null==this.curve.redN)throw new Error("Curve or redN is not initialized.");const n=this.curve.redN.redMul(e);for(;i.cmp(this.curve.p)<0;){if(i.iadd(this.curve.n),i.cmp(this.curve.p)>=0)return!1;if(r.redIAdd(n),0===this.x.cmp(r))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)}}const w=(t,e="Hash assertion failed")=>{if(!t)throw new Error(e)};class b{pending;pendingTotal;blockSize;outSize;endian;_delta8;_delta32;padLength;hmacStrength;constructor(t,e,r,i){this.pending=null,this.pendingTotal=0,this.blockSize=t,this.outSize=e,this.hmacStrength=r,this.padLength=i/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}_update(t,e){throw new Error("Not implemented")}_digest(){throw new Error("Not implemented")}_digestHex(){throw new Error("Not implemented")}update(t,e){if(t=y(t,e),null==this.pending?this.pending=t:this.pending=this.pending.concat(t),this.pendingTotal+=t.length,this.pending.length>=this._delta8){const e=(t=this.pending).length%this._delta8;this.pending=t.slice(t.length-e,t.length),0===this.pending.length&&(this.pending=null),t=function(t,e,r,i){const n=r-0;w(n%4==0);const s=new Array(n/4);for(let e=0,r=0;e<s.length;e++,r+=4){let n;n="big"===i?t[r]<<24|t[r+1]<<16|t[r+2]<<8|t[r+3]:t[r+3]<<24|t[r+2]<<16|t[r+1]<<8|t[r],s[e]=n>>>0}return s}(t,0,t.length-e,this.endian);for(let e=0;e<t.length;e+=this._delta32)this._update(t,e)}return this}digest(){return this.update(this._pad()),w(null===this.pending),this._digest()}digestHex(){return this.update(this._pad()),w(null===this.pending),this._digestHex()}_pad(){let t=this.pendingTotal;const e=this._delta8,r=e-(t+this.padLength)%e,i=new Array(r+this.padLength);let n,s;for(i[0]=128,n=1;n<r;n++)i[n]=0;if(t<<=3,"big"===this.endian){for(s=8;s<this.padLength;s++)i[n++]=0;i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=t>>>24&255,i[n++]=t>>>16&255,i[n++]=t>>>8&255,i[n++]=255&t}else for(i[n++]=255&t,i[n++]=t>>>8&255,i[n++]=t>>>16&255,i[n++]=t>>>24&255,i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=0,s=8;s<this.padLength;s++)i[n++]=0;return i}}function g(t,e){return 55296==(64512&t.charCodeAt(e))&&!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1))}function y(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];const r=[];if("string"==typeof t)if("hex"!==e){let e=0;for(let i=0;i<t.length;i++){let n=t.charCodeAt(i);n<128?r[e++]=n:n<2048?(r[e++]=n>>6|192,r[e++]=63&n|128):g(t,i)?(n=65536+((1023&n)<<10)+(1023&t.charCodeAt(++i)),r[e++]=n>>18|240,r[e++]=n>>12&63|128,r[e++]=n>>6&63|128,r[e++]=63&n|128):(r[e++]=n>>12|224,r[e++]=n>>6&63|128,r[e++]=63&n|128)}}else{(t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t);for(let e=0;e<t.length;e+=2)r.push(parseInt(t[e]+t[e+1],16))}else for(let e=0;e<t.length;e++)r[e]=0|t[e];return r}function v(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}function I(t,e){let r="";for(let n=0;n<t.length;n++){let s=t[n];"little"===e&&(s=v(s)),r+=7===(i=s.toString(16)).length?"0"+i:6===i.length?"00"+i:5===i.length?"000"+i:4===i.length?"0000"+i:3===i.length?"00000"+i:2===i.length?"000000"+i:1===i.length?"0000000"+i:i}var i;return r}function k(t,e){const r=new Array(4*t.length);for(let i=0,n=0;i<t.length;i++,n+=4){const s=t[i];"big"===e?(r[n]=s>>>24,r[n+1]=s>>>16&255,r[n+2]=s>>>8&255,r[n+3]=255&s):(r[n+3]=s>>>24,r[n+2]=s>>>16&255,r[n+1]=s>>>8&255,r[n]=255&s)}return r}function P(t,e){return t>>>e|t<<32-e}function E(t,e){return t<<e|t>>>32-e}function S(t,e){return t+e>>>0}function N(t,e,r){return t+e+r>>>0}function O(t,e,r,i){return t+e+r+i>>>0}function x(t,e,r,i,n){return t+e+r+i+n>>>0}function A(t,e,r,i){return 0===t?T(e,r,i):1===t||3===t?function(t,e,r){return t^e^r}(e,r,i):2===t?M(e,r,i):void 0}function T(t,e,r){return t&e^~t&r}function M(t,e,r){return t&e^t&r^e&r}function _(t){return P(t,2)^P(t,13)^P(t,22)}function F(t){return P(t,6)^P(t,11)^P(t,25)}function R(t){return P(t,7)^P(t,18)^t>>>3}const C=[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],V=[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],D=[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],B=[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 U(t,e,r,i){return t<=15?e^r^i:t<=31?e&r|~e&i:t<=47?(e|~r)^i:t<=63?e&i|r&~i:e^(r|~i)}function H(t){return t<=15?0:t<=31?1518500249:t<=47?1859775393:t<=63?2400959708:2840853838}function K(t){return t<=15?1352829926:t<=31?1548603684:t<=47?1836072691:t<=63?2053994217:0}function q(t,e,r,i){const n=t[e],s=i+t[e+1]>>>0,a=(s<i?1:0)+r+n;t[e]=a>>>0,t[e+1]=s}function L(t,e,r,i){return(e+i>>>0<e?1:0)+t+r>>>0}function $(t,e,r,i){return e+i>>>0}function z(t,e,r,i,n,s,a,o){let c=0,h=e;return h=h+i>>>0,c+=h<e?1:0,h=h+s>>>0,c+=h<s?1:0,h=h+o>>>0,c+=h<o?1:0,t+r+n+a+c>>>0}function j(t,e,r,i,n,s,a,o,c,h){let u=0,l=e;return l=l+i>>>0,u+=l<e?1:0,l=l+s>>>0,u+=l<s?1:0,l=l+o>>>0,u+=l<o?1:0,l=l+h>>>0,u+=l<h?1:0,t+r+n+a+c+u>>>0}function W(t,e,r){return(e<<32-r|t>>>r)>>>0}function X(t,e,r){return(t<<32-r|e>>>r)>>>0}function G(t,e,r){return t>>>r}function Y(t,e,r){return(t<<32-r|e>>>r)>>>0}class J extends b{h;constructor(){super(512,160,192,64),this.endian="little",this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}_update(t,e){let r,i=this.h[0],n=this.h[1],s=this.h[2],a=this.h[3],o=this.h[4],c=i,h=n,u=s,l=a,d=o;for(let f=0;f<80;f++)r=S(E(O(i,U(f,n,s,a),t[C[f]+e],H(f)),D[f]),o),i=o,o=a,a=E(s,10),s=n,n=r,r=S(E(O(c,U(79-f,h,u,l),t[V[f]+e],K(f)),B[f]),d),c=d,d=l,l=E(u,10),u=h,h=r;r=N(this.h[1],s,l),this.h[1]=N(this.h[2],a,d),this.h[2]=N(this.h[3],o,c),this.h[3]=N(this.h[4],i,h),this.h[4]=N(this.h[0],n,u),this.h[0]=r}_digest(){return k(this.h,"little")}_digestHex(){return I(this.h,"little")}}class Z extends b{h;W;k;constructor(){super(512,256,192,64),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],this.W=new Array(64)}_update(t,e){const r=this.W;let i;for(void 0===e&&(e=0),i=0;i<16;i++)r[i]=t[e+i];for(;i<r.length;i++)r[i]=O(P(n=r[i-2],17)^P(n,19)^n>>>10,r[i-7],R(r[i-15]),r[i-16]);var n;let s=this.h[0],a=this.h[1],o=this.h[2],c=this.h[3],h=this.h[4],u=this.h[5],l=this.h[6],d=this.h[7];for(w(this.k.length===r.length),i=0;i<r.length;i++){const t=x(d,F(h),T(h,u,l),this.k[i],r[i]),e=S(_(s),M(s,a,o));d=l,l=u,u=h,h=S(c,t),c=o,o=a,a=s,s=S(t,e)}this.h[0]=S(this.h[0],s),this.h[1]=S(this.h[1],a),this.h[2]=S(this.h[2],o),this.h[3]=S(this.h[3],c),this.h[4]=S(this.h[4],h),this.h[5]=S(this.h[5],u),this.h[6]=S(this.h[6],l),this.h[7]=S(this.h[7],d)}_digest(){return k(this.h,"big")}_digestHex(){return I(this.h,"big")}}class Q extends b{h;W;k;constructor(){super(512,160,80,64),this.k=[1518500249,1859775393,2400959708,3395469782],this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}_update(t,e){const r=this.W;let i;for(void 0===e&&(e=0),i=0;i<16;i++)r[i]=t[e+i];for(;i<r.length;i++)r[i]=E(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],c=this.h[4];for(i=0;i<r.length;i++){const t=~~(i/20),e=x(E(n,5),A(t,s,a,o),c,r[i],this.k[t]);c=o,o=a,a=E(s,30),s=n,n=e}this.h[0]=S(this.h[0],n),this.h[1]=S(this.h[1],s),this.h[2]=S(this.h[2],a),this.h[3]=S(this.h[3],o),this.h[4]=S(this.h[4],c)}_digest(){return k(this.h,"big")}_digestHex(){return I(this.h,"big")}}class tt extends b{h;W;k;constructor(){super(1024,512,192,128),this.h=[1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209],this.k=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],this.W=new Array(160)}_prepareBlock(t,e){const r=this.W;let i;for(i=0;i<32;i++)r[i]=t[e+i];for(;i<r.length;i+=2){const t=lt(r[i-4],r[i-3]),e=dt(r[i-4],r[i-3]),n=r[i-14],s=r[i-13],a=ht(r[i-30],r[i-29]),o=ut(r[i-30],r[i-29]),c=r[i-32],h=r[i-31];r[i]=z(t,e,n,s,a,o,c,h),r[i+1]=e+s+o+h>>>0}}_update(t,e){this._prepareBlock(t,e);const r=this.W;let i=this.h[0],n=this.h[1],s=this.h[2],a=this.h[3],o=this.h[4],c=this.h[5],h=this.h[6],u=this.h[7],l=this.h[8],d=this.h[9],f=this.h[10],p=this.h[11],m=this.h[12],b=this.h[13],g=this.h[14],y=this.h[15];w(this.k.length===r.length);for(let t=0;t<r.length;t+=2){let e=g,w=y,v=ot(l,d),I=ct(l,d);const k=et(l,0,f,0,m),P=rt(0,d,0,p,0,b),E=this.k[t],S=this.k[t+1],N=r[t],O=r[t+1],x=j(e,w,v,I,k,P,E,S,N,O),A=w+I+P+S+O>>>0;e=st(i,n),w=at(i,n),v=it(i,0,s,0,o),I=nt(0,n,0,a,0,c);const T=L(e,w,v,I),M=$(0,w,0,I);g=m,y=b,m=f,b=p,f=l,p=d,l=L(h,u,x,A),d=$(0,u,0,A),h=o,u=c,o=s,c=a,s=i,a=n,i=L(x,A,T,M),n=$(0,A,0,M)}q(this.h,0,i,n),q(this.h,2,s,a),q(this.h,4,o,c),q(this.h,6,h,u),q(this.h,8,l,d),q(this.h,10,f,p),q(this.h,12,m,b),q(this.h,14,g,y)}_digest(){return k(this.h,"big")}_digestHex(){return I(this.h,"big")}}function et(t,e,r,i,n,s){let a=t&r^~t&n;return a<0&&(a+=4294967296),a}function rt(t,e,r,i,n,s){let a=e&i^~e&s;return a<0&&(a+=4294967296),a}function it(t,e,r,i,n,s){let a=t&r^t&n^r&n;return a<0&&(a+=4294967296),a}function nt(t,e,r,i,n,s){let a=e&i^e&s^i&s;return a<0&&(a+=4294967296),a}function st(t,e){let r=W(t,e,28)^W(e,t,2)^W(e,t,7);return r<0&&(r+=4294967296),r}function at(t,e){let r=X(t,e,28)^X(e,t,2)^X(e,t,7);return r<0&&(r+=4294967296),r}function ot(t,e){let r=W(t,e,14)^W(t,e,18)^W(e,t,9);return r<0&&(r+=4294967296),r}function ct(t,e){let r=X(t,e,14)^X(t,e,18)^X(e,t,9);return r<0&&(r+=4294967296),r}function ht(t,e){let r=W(t,e,1)^W(t,e,8)^G(t,0,7);return r<0&&(r+=4294967296),r}function ut(t,e){let r=X(t,e,1)^X(t,e,8)^Y(t,e,7);return r<0&&(r+=4294967296),r}function lt(t,e){let r=W(t,e,19)^W(e,t,29)^G(t,0,6);return r<0&&(r+=4294967296),r}function dt(t,e){let r=X(t,e,19)^X(e,t,29)^Y(t,e,6);return r<0&&(r+=4294967296),r}class ft{inner;outer;blockSize=64;outSize=32;constructor(t){let e;for((t=y(t,"hex")).length>this.blockSize&&(t=(new Z).update(t).digest()),w(t.length<=this.blockSize),e=t.length;e<this.blockSize;e++)t.push(0);for(e=0;e<t.length;e++)t[e]^=54;for(this.inner=(new Z).update(t),e=0;e<t.length;e++)t[e]^=106;this.outer=(new Z).update(t)}update(t,e){return this.inner.update(t,e),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}}class pt{inner;outer;blockSize=64;constructor(t){let e;for((t=y(t,"hex")).length>this.blockSize&&(t=(new Q).update(t).digest()),e=t.length;e<this.blockSize;e++)t.push(0);for(e=0;e<t.length;e++)t[e]^=54;for(this.inner=(new Q).update(t),e=0;e<t.length;e++)t[e]^=106;this.outer=(new Q).update(t)}update(t,e){return this.inner.update(t,e),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}}class mt{inner;outer;blockSize=128;outSize=32;constructor(t){let e;for((t=y(t,"hex")).length>this.blockSize&&(t=(new tt).update(t).digest()),w(t.length<=this.blockSize),e=t.length;e<this.blockSize;e++)t.push(0);for(e=0;e<t.length;e++)t[e]^=54;for(this.inner=(new tt).update(t),e=0;e<t.length;e++)t[e]^=106;this.outer=(new tt).update(t)}update(t,e){return this.inner.update(t,e),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}}const wt=(t,e)=>(new J).update(t,e).digest(),bt=(t,e)=>(new Q).update(t,e).digest(),gt=(t,e)=>(new Z).update(t,e).digest(),yt=(t,e)=>(new tt).update(t,e).digest(),vt=(t,e)=>{const r=(new Z).update(t,e).digest();return(new Z).update(r).digest()},It=(t,e)=>{const r=(new Z).update(t,e).digest();return(new J).update(r).digest()},kt=(t,e,r)=>new ft(t).update(e,r).digest(),Pt=(t,e,r)=>new mt(t).update(e,r).digest();function Et(t,e,r,i,n="sha512"){if("sha512"!==n)throw new Error("Only sha512 is supported in this PBKDF2 implementation");const s=new Array(i),a=[...e,0,0,0,0];let o=0;const c=Math.ceil(i/64);for(let i=1;i<=c;i++){a[e.length]=i>>24&255,a[e.length+1]=i>>16&255,a[e.length+2]=i>>8&255,a[e.length+3]=255&i;const n=Pt(t,a);let c=n;for(let e=1;e<r;e++){c=Pt(t,c);for(let t=0;t<64;t++)n[t]^=c[t]}for(let t=0;t<n.length;t++)s[o+t]=n[t];o+=64}return s.slice(0,i)}const St=t=>t.length%2==1?"0"+t:t,Nt=t=>{let e="";for(const r of t)e+=St(r.toString(16));return e},Ot=(t,e)=>{if(Array.isArray(t))return t.slice();if(void 0===t)return[];if("string"!=typeof t)return Array.from(t,(t=>0|t));switch(e){case"hex":return xt(t);case"base64":return At(t);default:return function(t){const e=[];for(let r=0;r<t.length;r++){const i=t.codePointAt(r);if(void 0===i)throw new Error(`Index out of range: ${r}`);let n=i;n>65535?r++:n>=55296&&n<=57343&&(n=65533),n<=127?e.push(n):n<=2047?e.push(192|n>>6,128|63&n):n<=65535?e.push(224|n>>12,128|n>>6&63,128|63&n):e.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}return e}(t)}},xt=t=>{(t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t);const e=[];for(let r=0;r<t.length;r+=2)e.push(parseInt(t[r]+t[r+1],16));return e},At=t=>{const e=[];let r=0,i=0;for(const n of t.replace(/=+$/,""))r=r<<6|"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(n),i+=6,i>=8&&(i-=8,e.push(r>>i&255),r&=(1<<i)-1);return e},Tt=t=>{let e="",r=0;for(let i=0;i<t.length;i++){const n=t[i];if(r>0)r--;else if(n<=127)e+=String.fromCharCode(n);else if(n>=192&&n<=223){r=1;const s=(31&n)<<6|63&t[i+1];e+=String.fromCharCode(s)}else if(n>=224&&n<=239){r=2;const s=(15&n)<<12|(63&t[i+1])<<6|63&t[i+2];e+=String.fromCharCode(s)}else if(n>=240&&n<=247){r=3;const s=(7&n)<<18|(63&t[i+1])<<12|(63&t[i+2])<<6|63&t[i+3],a=55296+(s-65536>>10),o=56320+(s-65536&1023);e+=String.fromCharCode(a,o)}}return e},Mt=(t,e)=>{switch(e){case"hex":return Nt(t);case"utf8":return Tt(t);default:return t}};function _t(t){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r,i="";for(r=0;r<t.length;r+=3){const n=t[r],s=r+1<t.length?t[r+1]:0,a=r+2<t.length?t[r+2]:0,o=(3&n)<<4|s>>4,c=(15&s)<<2|a>>6,h=63&a;i+=e.charAt(n>>2)+e.charAt(o),i+=r+1<t.length?e.charAt(c):"=",i+=r+2<t.length?e.charAt(h):"="}return i}const Ft="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Rt=t=>{if(""===t||"string"!=typeof t)throw new Error(`Expected base58 string but got “${t}”`);const e=t.match(/[IOl0]/gmu);if(null!==e)throw new Error(`Invalid base58 character “${e.join("")}”`);const r=t.match(/^1+/gmu),i=null!==r?r[0].length:0,n=(t.length-i)*(Math.log(58)/Math.log(256))+1>>>0;var s;return[...new Uint8Array([...new Uint8Array(i),...(t.match(/./gmu)??[]).map((t=>Ft.indexOf(t))).reduce(((t,e)=>t.map((t=>{const r=58*t+e;return e=r>>8,r}))),new Uint8Array(n)).reverse().filter((s=!1,t=>s=s||t))])]},Ct=t=>{const e=Array(256).fill(-1);for(let t=0;t<58;++t)e[Ft.charCodeAt(t)]=t;const r=[];for(const i of t){let t=i;for(let i=0;i<r.length;++i){const n=(e[r[i]]<<8)+t;r[i]=Ft.charCodeAt(n%58),t=n/58|0}for(;0!==t;)r.push(Ft.charCodeAt(t%58)),t=t/58|0}for(const e of t){if(0!==e)break;r.push("1".charCodeAt(0))}return r.reverse(),String.fromCharCode(...r)},Vt=(t,e=[0])=>{let r=vt([...e,...t]);return r=[...e,...t,...r.slice(0,4)],Ct(r)},Dt=(t,e,r=1)=>{const i=Rt(t);let n=i.slice(0,r),s=i.slice(r,-4),a=[...n,...s];return a=vt(a),i.slice(-4).forEach(((t,e)=>{if(t!==a[e])throw new Error("Invalid checksum")})),"hex"===e&&(n=Nt(n),s=Nt(s)),{prefix:n,data:s}};class Bt{bufs;constructor(t){this.bufs=void 0!==t?t:[]}getLength(){let t=0;for(const e of this.bufs)t+=e.length;return t}toArray(){const t=this.getLength(),e=new Array(t);let r=0;for(const t of this.bufs)for(const i of t)e[r++]=i;return e}write(t){return this.bufs.push(t),this}writeReverse(t){const e=new Array(t.length);for(let r=0;r<e.length;r++)e[r]=t[t.length-1-r];return this.bufs.push(e),this}writeUInt8(t){const e=new Array(1);return e[0]=t,this.write(e),this}writeInt8(t){const e=new Array(1);return e[0]=255&t,this.write(e),this}writeUInt16BE(t){return this.bufs.push([t>>8&255,255&t]),this}writeInt16BE(t){return this.writeUInt16BE(65535&t)}writeUInt16LE(t){return this.bufs.push([255&t,t>>8&255]),this}writeInt16LE(t){return this.writeUInt16LE(65535&t)}writeUInt32BE(t){return this.bufs.push([t>>24&255,t>>16&255,t>>8&255,255&t]),this}writeInt32BE(t){return this.writeUInt32BE(t>>>0)}writeUInt32LE(t){return this.bufs.push([255&t,t>>8&255,t>>16&255,t>>24&255]),this}writeInt32LE(t){return this.writeUInt32LE(t>>>0)}writeUInt64BEBn(t){const e=t.toArray("be",8);return this.write(e),this}writeUInt64LEBn(t){const e=t.toArray("be",8);return this.writeReverse(e),this}writeUInt64LE(t){const e=new h(t).toArray("be",8);return this.writeReverse(e),this}writeVarIntNum(t){const e=Bt.varIntNum(t);return this.write(e),this}writeVarIntBn(t){const e=Bt.varIntBn(t);return this.write(e),this}static varIntNum(t){let e;if(t<253)e=[t];else if(t<65536)e=[253,255&t,t>>8&255];else if(t<4294967296)e=[254,255&t,t>>8&255,t>>16&255,t>>24&255];else{const r=4294967295&t,i=4294967295&Math.floor(t/4294967296);e=[255,255&r,r>>8&255,r>>16&255,r>>24&255,255&i,i>>8&255,i>>16&255,i>>24&255]}return e}static varIntBn(t){let e;if(t.ltn(253))e=[t.toNumber()];else if(t.ltn(65536)){const r=t.toNumber();e=[253,255&r,r>>8&255]}else if(t.lt(new h(4294967296))){const r=t.toNumber();e=[254,255&r,r>>8&255,r>>16&255,r>>24&255]}else{const r=new Bt;r.writeUInt8(255),r.writeUInt64LEBn(t),e=r.toArray()}return e}}class Ut{bin;pos;constructor(t=[],e=0){this.bin=t,this.pos=e}eof(){return this.pos>=this.bin.length}read(t=this.bin.length){const e=this.pos,r=this.pos+t;return this.pos=r,this.bin.slice(e,r)}readReverse(t=this.bin.length){const e=new Array(t);for(let r=0;r<t;r++)e[r]=this.bin[this.pos+t-1-r];return this.pos+=t,e}readUInt8(){const t=this.bin[this.pos];return this.pos+=1,t}readInt8(){const t=this.bin[this.pos];return this.pos+=1,128&t?t-256:t}readUInt16BE(){const t=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,t}readInt16BE(){const t=this.readUInt16BE();return 32768&t?t-65536:t}readUInt16LE(){const t=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,t}readInt16LE(){const t=this.readUInt16LE();return 32768&t?t-65536:t}readUInt32BE(){const t=16777216*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,t}readInt32BE(){const t=this.readUInt32BE();return 2147483648&t?t-4294967296:t}readUInt32LE(){const t=(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,t}readInt32LE(){const t=this.readUInt32LE();return 2147483648&t?t-4294967296:t}readUInt64BEBn(){const t=this.bin.slice(this.pos,this.pos+8),e=new h(t);return this.pos=this.pos+8,e}readUInt64LEBn(){const t=this.readReverse(8);return new h(t)}readVarIntNum(){const t=this.readUInt8();let e;switch(t){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if(e=this.readUInt64LEBn(),e.lte(new h(2).pow(new h(53))))return e.toNumber();throw new Error("number too large to retain precision - use readVarIntBn");default:return t}}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(){const t=this.readUInt8();switch(t){case 253:return new h(this.readUInt16LE());case 254:return new h(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new h(t)}}}const Ht=t=>{if(0===t.length)return t;const e=t[t.length-1];if(127&e)return t;if(1===t.length)return[];if(128&t[t.length-2])return t;for(let r=t.length-1;r>0;r--)if(0!==t[r-1])return 128&t[r-1]?(t[r]=e,t.slice(0,r+1)):(t[r-1]|=e,t.slice(0,r));return[]};class Kt extends p{static red=new d("k256");static a=new h(0).toRed(Kt.red);static b=new h(7).toRed(Kt.red);static zero=new h(0).toRed(Kt.red);x;y;inf;static fromDER(t){if((4===t[0]||6===t[0]||7===t[0])&&t.length-1==64){if(6===t[0]){if(t[t.length-1]%2!=0)throw new Error("Point string value is wrong length")}else if(7===t[0]&&t[t.length-1]%2!=1)throw new Error("Point string value is wrong length");return new Kt(t.slice(1,33),t.slice(33,65))}if((2===t[0]||3===t[0])&&t.length-1==32)return Kt.fromX(t.slice(1,33),3===t[0]);throw new Error("Unknown point format")}static fromString(t){const e=Ot(t,"hex");return Kt.fromDER(e)}static redSqrtOptimized(t){const e=Kt.red.m.addn(1).iushrn(2);return t.redPow(e)}static fromX(t,e){if("function"==typeof BigInt){function r(t,e){return(t%e+e)%e}function i(t,e,i){let n=BigInt(1);for(t=r(t,i);e>BigInt(0);)(e&BigInt(1))===BigInt(1)&&(n=r(n*t,i)),e>>=BigInt(1),t=r(t*t,i);return n}function n(t,e){const n=i(t,e+BigInt(1)>>BigInt(2),e);return r(n*n,e)===r(t,e)?n:null}const s=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),a=BigInt(7);let o;if(t instanceof h)o=BigInt("0x"+t.toString(16));else if("string"==typeof t)o=BigInt("0x"+t);else if(Array.isArray(t))o=BigInt("0x"+Nt(t).padStart(64,"0"));else{if("number"!=typeof t)throw new Error("Invalid x-coordinate type");o=BigInt(t)}o=r(o,s);let c=n(r(i(o,BigInt(3),s)+a,s),s);if(null===c)throw new Error("Invalid point");const u=c%BigInt(2)===BigInt(1);(e&&!u||!e&&u)&&(c=s-c);const l=new h(o.toString(16),16),f=new h(c.toString(16),16);return new Kt(l,f)}{const p=new d("k256"),m=new h(0).toRed(p),w=new h(7).toRed(p),b=new h(0).toRed(p);h.isBN(t)||(t=new h(t,16)),null==t.red&&(t=t.toRed(p));const g=t.redSqr().redMul(t).redIAdd(t.redMul(m)).redIAdd(w);let y=g.redSqrt();if(0!==y.redSqr().redSub(g).cmp(b))throw new Error("invalid point");const v=y.fromRed().isOdd();return(e&&!v||!e&&v)&&(y=y.redNeg()),new Kt(t,y)}}static fromJSON(t,e){"string"==typeof t&&(t=JSON.parse(t));const r=new Kt(t[0],t[1],e);if("object"!=typeof t[2])return r;const i=t=>new Kt(t[0],t[1],e),n=t[2];return r.precomputed={beta:null,doubles:"object"==typeof n.doubles&&null!==n.doubles?{step:n.doubles.step,points:[r].concat(n.doubles.points.map(i))}:void 0,naf:"object"==typeof n.naf&&null!==n.naf?{wnd:n.naf.wnd,points:[r].concat(n.naf.points.map(i))}:void 0},r}constructor(t,e,r=!0){super("affine"),this.precomputed=null,null===t&&null===e?(this.x=null,this.y=null,this.inf=!0):(h.isBN(t)||(t=new h(t,16)),this.x=t,h.isBN(e)||(e=new h(e,16)),this.y=e,r&&(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(){return this.curve.validate(this)}encode(t=!0,e){const r=this.curve.p.byteLength(),i=this.getX().toArray("be",r);let n;return n=t?[this.getY().isEven()?2:3].concat(i):[4].concat(i,this.getY().toArray("be",r)),"hex"!==e?n:Nt(n)}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?{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)}:void 0,naf:null!=this.precomputed.naf?{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}:void 0}: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(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return new Kt(new h(0),new h(0));if(0===this.x?.cmp(t.x??new h(0)))return new Kt(new h(0),new h(0));let e=this.y?.redSub(t.y??new h(0))??new h(0);0!==e.cmpn(0)&&(e=e.redMul(this.x?.redSub(t.x??new h(0)).redInvm()??new h(1)));const r=e?.redSqr().redISub(this.x??new h(0)).redISub(t.x??new h(0)),i=(e??new h(1)).redMul((this.x??new h(0)).redSub(r??new h(0))).redISub(this.y??new h(0));return new Kt(r??new h(0),i??new h(0))}dbl(){if(this.inf)return this;const t=(this.y??new h(0)).redAdd(this.y??new h(0));if(0===t.cmpn(0))return new Kt(new h(0),new h(0));const e=this.curve.a,r=(this.x??new h(0)).redSqr(),i=t.redInvm(),n=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(i),s=n.redSqr().redISub((this.x??new h(0)).redAdd(this.x??new h(0))),a=n.redMul((this.x??new h(0)).redSub(s)).redISub(this.y??new h(0));return new Kt(s,a)}getX(){return(this.x??new h(0)).fromRed()}getY(){return(this.y??new h(0)).fromRed()}mul(t){return h.isBN(t)||(t=new h(t,16)),this.isInfinity()?this:this._hasDoubles(t)?this._fixedNafMul(t):this._endoWnafMulAdd([this],[t])}mulAdd(t,e,r){const i=[this,e],n=[t,r];return this._endoWnafMulAdd(i,n)}jmulAdd(t,e,r){const i=[this,e],n=[t,r];return this._endoWnafMulAdd(i,n,!0)}eq(t){return this===t||this.inf===t.inf&&(this.inf||0===(this.x??new h(0)).cmp(t.x??new h(0))&&0===(this.y??new h(0)).cmp(t.y??new h(0)))}neg(t){if(this.inf)return this;const e=new Kt(this.x,(this.y??new h(0)).redNeg());if(!0===t&&null!=this.precomputed){const t=this.precomputed,r=t=>t.neg();e.precomputed={naf:null!=t.naf?{wnd:t.naf.wnd,points:t.naf.points.map(r)}:void 0,doubles:null!=t.doubles?{step:t.doubles.step,points:t.doubles.points.map((t=>t.neg()))}:void 0,beta:void 0}}return e}dblp(t){let e=this;for(let r=0;r<t;r++)e=e.dbl();return e}toJ(){return this.inf?new m(null,null,null):new m(this.x,this.y,this.curve.one)}_getBeta(){if("object"!=typeof this.curve.endo)return;const t=this.precomputed;if("object"==typeof t&&null!==t&&"object"==typeof t.beta&&null!==t.beta)return t.beta;const e=new Kt((this.x??new h(0)).redMul(this.curve.endo.beta),this.y);if(null!=t){const r=this.curve,i=t=>{if(null===t.x)throw new Error("p.x is null");if(void 0===r.endo||null===r.endo)throw new Error("curve.endo is undefined");return new Kt(t.x.redMul(r.endo.beta),t.y)};t.beta=e,e.precomputed={beta:null,naf:null!=t.naf?{wnd:t.naf.wnd,points:t.naf.points.map(i)}:void 0,doubles:null!=t.doubles?{step:t.doubles.step,points:t.doubles.points.map(i)}:void 0}}return e}_fixedNafMul(t){if("object"!=typeof this.precomputed||null===this.precomputed)throw new Error("_fixedNafMul requires precomputed values for the point");const e=this._getDoubles(),r=this.curve.getNAF(t,1,this.curve._bitLength);let i=(1<<e.step+1)-(e.step%2==0?2:1);i/=3;const n=[];for(let t=0;t<r.length;t+=e.step){let i=0;for(let n=t+e.step-1;n>=t;n--)i=(i<<1)+r[n];n.push(i)}let s=new m(null,null,null),a=new m(null,null,null);for(let t=i;t>0;t--){for(let r=0;r<n.length;r++){const i=n[r];i===t?a=a.mixedAdd(e.points[r]):i===-t&&(a=a.mixedAdd(e.points[r].neg()))}s=s.add(a)}return s.toP()}_wnafMulAdd(t,e,r,i,n){const s=this.curve._wnafT1.map((t=>t.toNumber())),a=this.curve._wnafT2.map((()=>[])),o=this.curve._wnafT3.map((()=>[]));let c=0;for(let r=0;r<i;r++){const i=e[r]._getNAFPoints(t);s[r]=i.wnd,a[r]=i.points}for(let t=i-1;t>=1;t-=2){const i=t-1,n=t;if(1!==s[i]||1!==s[n]){o[i]=this.curve.getNAF(r[i],s[i],this.curve._bitLength),o[n]=this.curve.getNAF(r[n],s[n],this.curve._bitLength),c=Math.max(o[i].length,c),c=Math.max(o[n].length,c);continue}const u=[e[i],null,null,e[n]];0===(e[i].y??new h(0)).cmp(e[n].y??new h(0))?(u[1]=e[i].add(e[n]),u[2]=e[i].toJ().mixedAdd(e[n].neg())):0===(e[i].y??new h(0)).cmp((e[n].y??new h(0)).redNeg())?(u[1]=e[i].toJ().mixedAdd(e[n]),u[2]=e[i].add(e[n].neg())):(u[1]=e[i].toJ().mixedAdd(e[n]),u[2]=e[i].toJ().mixedAdd(e[n].neg()));const l=[-3,-1,-5,-7,0,7,5,1,3],d=this.curve.getJSF(r[i],r[n]);c=Math.max(d[0].length,c),o[i]=new Array(c),o[n]=new Array(c);for(let t=0;t<c;t++){const e=0|d[0][t],r=0|d[1][t];o[i][t]=l[3*(e+1)+(r+1)],o[n][t]=0,a[i]=u}}let u=new m(null,null,null);const l=this.curve._wnafT4;for(let t=c;t>=0;t--){let e=0;for(;t>=0;){let r=!0;for(let e=0;e<i;e++)l[e]=new h("number"==typeof o[e][t]?o[e][t]:0),l[e].isZero()||(r=!1);if(!r)break;e++,t--}if(t>=0&&e++,u=u.dblp(e),t<0)break;const r=new h(1),n=new h(2);for(let t=0;t<i;t++){const e=l[t];let i;0!==e.cmpn(0)&&(i=e.isNeg()?a[t][e.neg().sub(r).div(n).toNumber()].neg():a[t][e.sub(r).div(n).toNumber()],u="affine"===i.type?u.mixedAdd(i):u.add(i))}}for(let t=0;t<i;t++)a[t]=[];return!0===n?u:u.toP()}_endoWnafMulAdd(t,e,r){const i=new Array(2*t.length),n=new Array(2*t.length);let s;for(s=0;s<t.length;s++){const r=this.curve._endoSplit(e[s]);let a=t[s],o=a._getBeta()??new Kt(new h(0),new h(0));0!==r.k1.negative&&(r.k1.ineg(),a=a.neg(!0)),0!==r.k2.negative&&(r.k2.ineg(),o=o.neg(!0)),i[2*s]=a,i[2*s+1]=o,n[2*s]=r.k1,n[2*s+1]=r.k2}const a=this._wnafMulAdd(1,i,n,2*s,r);for(let t=0;t<2*s;t++)i[t]=null,n[t]=null;return a}_hasDoubles(t){if(null==this.precomputed)return!1;const e=this.precomputed.doubles;return"object"==typeof e&&e.points.length>=Math.ceil((t.bitLength()+1)/e.step)}_getDoubles(t,e){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.doubles&&null!==this.precomputed.doubles)return this.precomputed.doubles;const r=[this];let i=this;for(let n=0;n<(e??0);n+=t??1){for(let e=0;e<(t??1);e++)i=i.dbl();r.push(i)}return{step:t??1,points:r}}_getNAFPoints(t){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.naf&&null!==this.precomputed.naf)return this.precomputed.naf;const e=[this],r=(1<<t)-1,i=1===r?null:this.dbl();for(let t=1;t<r;t++)null!==i&&(e[t]=e[t-1].add(i));return{wnd:t,points:e}}}let qt;class Lt{p;red;redN;zero;one;two;g;n;a;b;tinv;zeroA;threeA;endo;_endoWnafT1;_endoWnafT2;_wnafT1;_wnafT2;_wnafT3;_wnafT4;_bitLength;static assert(t,e="Elliptic curve assertion failed"){if(!t)throw new Error(e)}getNAF(t,e,r){const i=new Array(Math.max(t.bitLength(),r)+1);i.fill(0);const n=1<<e+1,s=t.clone();for(let t=0;t<i.length;t++){let e;const r=s.andln(n-1);s.isOdd()?(e=r>(n>>1)-1?(n>>1)-r:r,s.isubn(e)):e=0,i[t]=e,s.iushrn(1)}return i}getJSF(t,e){const r=[[],[]];t=t.clone(),e=e.clone();let i=0,n=0;for(;t.cmpn(-i)>0||e.cmpn(-n)>0;){let s,a,o=t.andln(3)+i&3,c=e.andln(3)+n&3;if(3===o&&(o=-1),3===c&&(c=-1),1&o){const e=t.andln(7)+i&7;s=3!==e&&5!==e||2!==c?o:-o}else s=0;if(r[0].push(s),1&c){const t=e.andln(7)+n&7;a=3!==t&&5!==t||2!==o?c:-c}else a=0;r[1].push(a),2*i===s+1&&(i=1-i),2*n===a+1&&(n=1-n),t.iushrn(1),e.iushrn(1)}return r}static cachedProperty(t,e,r){const i="_"+e;t.prototype[e]=function(){return void 0!==this[i]?this[i]:this[i]=r.call(this)}}static parseBytes(t){return"string"==typeof t?Ot(t,"hex"):t}static intFromLE(t){return new h(t,"hex","le")}constructor(){if(void 0!==qt)return qt;qt=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 h(t.p,16),this.red=new d(t.prime),this.zero=new h(0).toRed(this.red),this.one=new h(1).toRed(this.red),this.two=new h(2).toRed(this.red),this.n=new h(t.n,16),this.g=Kt.fromJSON(t.g,t.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n.bitLength(),this.redN=this.n.toRed(this.red),this.a=new h(t.a,16).toRed(this.red),this.b=new h(t.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(t),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}_getEndomorphism(t){if(!this.zeroA||1!==this.p.modrn(3))return;let e,r,i;if(void 0!==t.beta)e=new h(t.beta,16).toRed(this.red);else{const t=this._getEndoRoots(this.p);if(null===t)throw new Error("Failed to get endomorphism roots for beta.");e=t[0].cmp(t[1])<0?t[0]:t[1],e=e.toRed(this.red)}if(void 0!==t.lambda)r=new h(t.lambda,16);else{const t=this._getEndoRoots(this.n);if(null===t)throw new Error("Failed to get endomorphism roots for lambda.");if(null==this.g)throw new Error("Curve generator point (g) is not defined.");const i=this.g.mul(t[0])?.x,n=null!=this.g.x?this.g.x.redMul(e):void 0;if(null!=i&&null!=n&&0===i.cmp(n))r=t[0];else{if(r=t[1],null==this.g)throw new Error("Curve generator point (g) is not defined.");const i=this.g.mul(r)?.x,n=null!=this.g.x?this.g.x.redMul(e):void 0;if(null==i||null==n)throw new Error("Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.");Lt.assert(0===i.cmp(n),"Lambda selection does not match computed beta.")}}return i="object"==typeof t.basis&&null!==t.basis?t.basis.map((function(t){return{a:new h(t.a,16),b:new h(t.b,16)}})):this._getEndoBasis(r),{beta:e,lambda:r,basis:i}}_getEndoRoots(t){const e=t===this.p?this.red:new f(t),r=new h(2).toRed(e).redInvm(),i=r.redNeg(),n=new h(3).toRed(e).redNeg().redSqrt().redMul(r);return[i.redAdd(n).fromRed(),i.redSub(n).fromRed()]}_getEndoBasis(t){const e=this.n.ushrn(Math.floor(this.n.bitLength()/2));let r,i,n,s,a,o,c=t,u=this.n.clone(),l=new h(1),d=new h(0),f=new h(0),p=new h(1),m=new h(0),w=0,b=new h(0),g=new h(0);for(;0!==c.cmpn(0);){const t=u.div(c);b=u.sub(t.mul(c)),g=f.sub(t.mul(l));const a=p.sub(t.mul(d));if(void 0===n&&b.cmp(e)<0)r=m.neg(),i=l,n=b.neg(),s=g;else if(void 0!==n&&2==++w)break;m=b,u=c,c=b,f=l,l=g,p=d,d=a}if(void 0===r||void 0===i||void 0===n||void 0===s)throw new Error("Failed to compute Endo Basis values");a=b.neg(),o=g;const y=n.sqr().add(s.sqr());return a.sqr().add(o.sqr()).cmp(y)>=0&&(a=r,o=i),0!==n.negative&&(n=n.neg(),s=s.neg()),0!==a.negative&&(a=a.neg(),o=o.neg()),[{a:n,b:s},{a,b:o}]}_endoSplit(t){if(null==this.endo)throw new Error("Endomorphism is not defined.");const e=this.endo.basis,r=e[0],i=e[1],n=i.b.mul(t).divRound(this.n),s=r.b.neg().mul(t).divRound(this.n),a=n.mul(r.a),o=s.mul(i.a),c=n.mul(r.b),h=s.mul(i.b);return{k1:t.sub(a).sub(o),k2:c.add(h).neg()}}validate(t){if(t.inf)return!0;const e=t.x,r=t.y;if(null===e||null===r)throw new Error("Point coordinates cannot be null");const i=this.a.redMul(e),n=e.redSqr().redMul(e).redIAdd(i).redIAdd(this.b);return 0===r.redSqr().redISub(n).cmpn(0)}}class $t{r;s;static fromDER(t,e){const r=(t,e)=>{const r=t[e.place++];if(128&r)throw new Error("Invalid DER entity length");return r};t=Ot(t,e);const i=new class{place;constructor(){this.place=0}};if(48!==t[i.place++])throw new Error("Signature DER must start with 0x30");if(r(t,i)+i.place!==t.length)throw new Error("Signature DER invalid");if(2!==t[i.place++])throw new Error("Signature DER invalid");const n=r(t,i);let s=t.slice(i.place,n+i.place);if(i.place+=n,2!==t[i.place++])throw new Error("Signature DER invalid");const a=r(t,i);if(t.length!==a+i.place)throw new Error("Invalid R-length in signature DER");let o=t.slice(i.place,a+i.place);if(0===s[0]){if(!(128&s[1]))throw new Error("Invalid R-value in signature DER");s=s.slice(1)}if(0===o[0]){if(!(128&o[1]))throw new Error("Invalid S-value in signature DER");o=o.slice(1)}return new $t(new h(s),new h(o))}static fromCompact(t,e){if(65!==(t=Ot(t,e)).length)throw new Error("Invalid Compact Signature");const r=t[0];if(r<27||r>=35)throw new Error("Invalid Compact Byte");return new $t(new h(t.slice(1,33)),new h(t.slice(33,65)))}constructor(t,e){this.r=t,this.s=e}verify(t,e,r){const i=new h(gt(t,r),16);return Xt(i,this,e)}toString(t){return this.toDER(t)}toDER(t){const e=(t,e)=>{if(!(e<128))throw new Error("len must be < 0x80");t.push(e)},r=t=>{let e=0;const r=t.length-1;for(;0===t[e]&&!(128&t[e+1])&&e<r;)e++;return 0===e?t:t.slice(e)};let i=this.r.toArray(),n=this.s.toArray();for(128&i[0]&&(i=[0].concat(i)),128&n[0]&&(n=[0].concat(n)),i=r(i),n=r(n);0===n[0]&&!(128&n[1]);)n=n.slice(1);let s=[2];e(s,i.length),s=s.concat(i),s.push(2),e(s,n.length);const a=s.concat(n);let o=[48];return e(o,a.length),o=o.concat(a),"hex"===t?Nt(o):"base64"===t?_t(o):o}toCompact(t,e,r){if(t<0||t>3)throw new Error("Invalid recovery param");if("boolean"!=typeof e)throw new Error("Invalid compressed param");let i=27+t;e&&(i+=4);let n=[i];return n=n.concat(this.r.toArray("be",32)),n=n.concat(this.s.toArray("be",32)),"hex"===r?Nt(n):"base64"===r?_t(n):n}RecoverPublicKey(t,e){const r=this.r,i=this.s,n=!!(1&t),s=t>>1,a=new Lt,o=a.n,c=a.g,h=0!==s?r.add(o):r,u=Kt.fromX(h,n);if(!u.mul(o).isInfinity())throw new Error("nR is not at infinity");const l=e.neg().umod(o),d=r.invm(o),f=d.mul(i).umod(o),p=d.mul(l).umod(o),m=c.mul(p).add(u.mul(f)),w=new Gt(m);return w.validate(),w}CalculateRecoveryFactor(t,e){for(let r=0;r<4;r++){let i;try{i=this.RecoverPublicKey(r,e)}catch{continue}if(t.eq(i))return r}throw new Error("Unable to find valid recovery factor")}}class zt{K;V;constructor(t,e){if(t=Ot(t,"hex"),e=Ot(e,"hex"),t.length<32)throw new Error("Not enough entropy. Minimum is 256 bits");const r=t.concat(e);this.K=new Array(32),this.V=new Array(32);for(let t=0;t<32;t++)this.K[t]=0,this.V[t]=1;this.update(r)}hmac(){return new ft(this.K)}update(t){let e=this.hmac().update(this.V).update([0]);void 0!==t&&(e=e.update(t)),this.K=e.digest(),this.V=this.hmac().update(this.V).digest(),void 0!==t&&(this.K=this.hmac().update(this.V).update([1]).update(t).digest(),this.V=this.hmac().update(this.V).digest())}generate(t){let e=[];for(;e.length<t;)this.V=this.hmac().update(this.V).digest(),e=e.concat(this.V);const r=e.slice(0,t);return this.update(),Nt(r)}}function jt(t,e,r=new Lt){const i=8*t.byteLength()-r.n.bitLength();return i>0&&t.iushrn(i),null===e&&t.cmp(r.n)>=0?t.sub(r.n):t}const Wt=(t,e,r=!1,i)=>{if("function"==typeof BigInt){const n=BigInt(0),s=BigInt(1),a=BigInt(2),o=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),c=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),u={x:BigInt("0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"),y:BigInt("0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8")},l=BigInt("0x"+t.toString(16)),d=BigInt("0x"+e.toString(16));if(d<=n||d>=o)throw new Error("Invalid private key");function f(t,e){const r=t.toString(16).padStart(2*e,"0"),i=new Uint8Array(e);for(let t=0;t<e;t++)i[t]=parseInt(r.substr(2*t,2),16);return i}const p=32,m=f(d,p),w=f(l,p),b=new zt(Array.from(m),Array.from(w)),g=o-s;let y=0;function v(t,e,r=!0){const i=t.toString(2).length-e.toString(2).length;return i>0&&(t>>=BigInt(i)),!r&&t>=e?t-e:t}function I(t){if("function"==typeof t){const e=t(y).toString(16);return BigInt("0x"+e)}if(null!=t&&h.isBN(t)){const e=t.toString(16);return BigInt("0x"+e)}{const t=b.generate(p);return BigInt("0x"+t)}}function k(t,e){return(t%e+e)%e}function P(t,e){let r=s,i=n,a=k(t,e),o=e;for(;a>s;){const t=o/a,e=i-r*t,n=o-a*t;i=r,r=e,o=a,a=n}return k(r,e)}function E(t,e){if(null===t)return e;if(null===e)return t;if(t.x===e.x&&t.y===k(-e.y,c))return null;let r;if(t.x===e.x&&t.y===e.y){if(t.y===n)return null;const e=k(BigInt(3)*t.x*t.x,c);r=k(e*P(a*t.y,c),c)}else{const i=k(e.y-t.y,c);r=k(i*P(e.x-t.x,c),c)}const i=k(r*r-t.x-e.x,c);return{x:i,y:k(r*(t.x-i)-t.y,c)}}function S(t,e){let r=e,i=null;for(;t>BigInt(0);)t%BigInt(2)===BigInt(1)&&(i=null===i?r:E(i,r)??i),r=E(r,r)??r,t>>=BigInt(1);if(null===i)throw new Error("Scalar multiplication resulted in an invalid point.");return i}let N=!1;for(;!N;){y+=1,N=!0,y+=1;let O=I(i);if(O=v(O,o,!0),O<=s||O>=g){if(i instanceof h)throw new Error("Invalid fixed custom K value (must be more than 1 and less than N-1)");continue}const x=S(O,u);if(null===x){if(i instanceof h)throw new Error("Invalid fixed custom K value (must not create a point at infinity when multiplied by the generator point)");continue}const A=k(x.x,o);if(A===n){if(i instanceof h)throw new Error("Invalid fixed custom K value (when multiplied by G, the resulting x coordinate mod N must not be zero)");continue}const T=P(O,o),M=k(A*d,o);let _=k(T*(l+M),o);if(_===n){if(i instanceof h)throw new Error("Invalid fixed custom K value (when used with the key, it cannot create a zero value for S)");continue}r&&_>o/a&&(_=o-_);const F=new h(A.toString(16),16),R=new h(_.toString(16),16);return new $t(F,R)}}else{const C=new Lt;t=jt(t);const V=C.n.byteLength(),D=e.toArray("be",V),B=t.toArray("be",V),U=new zt(D,B),H=C.n.subn(1);for(let K=0;;K++){let q="function"==typeof i?i(K):h.isBN(i)?i:new h(U.generate(V),16);if(null==q)throw new Error("k is undefined");if(q=jt(q,!0),q.cmpn(1)<=0||q.cmp(H)>=0){if(h.isBN(i))throw new Error("Invalid fixed custom K value (must be more than 1 and less than N-1)");continue}const L=C.g.mul(q);if(L.isInfinity()){if(h.isBN(i))throw new Error("Invalid fixed custom K value (must not create a point at infinity when multiplied by the generator point)");continue}const $=L.getX().umod(C.n);if(0===$.cmpn(0)){if(h.isBN(i))throw new Error("Invalid fixed custom K value (when multiplied by G, the resulting x coordinate mod N must not be zero)");continue}let z=q.invm(C.n).mul($.mul(e).iadd(t));if(z=z.umod(C.n),0!==z.cmpn(0))return r&&z.cmp(C.n.ushrn(1))>0&&(z=C.n.sub(z)),new $t($,z);if(h.isBN(i))throw new Error("Invalid fixed custom K value (when used with the key, it cannot create a zero value for S)")}}throw new Error("Failed to generate a valid signature")},Xt=(t,e,r)=>{if("function"==typeof BigInt){const i=BigInt(0),n=BigInt(1),s=BigInt(2),a=BigInt(3),o=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),c=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),h={x:BigInt("0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"),y:BigInt("0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8")},u=(t,e)=>(t%e+e)%e,l=(t,e)=>{let[r,s]=[t,e],[a,o]=[BigInt(1),BigInt(0)];for(;s!==i;){const t=r/s;[r,s]=[s,r-t*s],[a,o]=[o,a-t*o]}return r>n?i:u(a,e)},d=(t,e,r)=>u(t*e,r),f=(t,e,r)=>u(t-e,r),p=BigInt(4),m=BigInt(8),w=t=>{const{X:e,Y:r,Z:c}=t;if(r===i)return{X:i,Y:n,Z:i};const h=d(r,r,o),u=d(p,d(e,h,o),o),l=d(a,d(e,e,o),o),w=f(d(l,l,o),d(s,u,o),o);return{X:w,Y:f(d(l,f(u,w,o),o),d(m,d(h,h,o),o),o),Z:d(s,d(r,c,o),o)}},b=(t,e)=>{if(t.Z===i)return e;if(e.Z===i)return t;const r=d(t.Z,t.Z,o),a=d(e.Z,e.Z,o),c=d(t.X,a,o),h=d(e.X,r,o),u=d(t.Y,d(a,e.Z,o),o),l=d(e.Y,d(r,t.Z,o),o),p=f(h,c,o),m=f(l,u,o);if(p===i)return m===i?w(t):{X:i,Y:n,Z:i};const b=d(p,p,o),g=d(p,b,o),y=d(c,b,o),v=f(f(d(m,m,o),g,o),d(s,y,o),o);return{X:v,Y:f(d(m,f(y,v,o),o),d(u,g,o),o),Z:d(p,d(t.Z,e.Z,o),o)}},g=(t,e)=>{const r={X:e.x,Y:e.y,Z:n};let s={X:i,Y:n,Z:i};const a=t.toString(2);for(let t=0;t<a.length;t++)s=w(s),"1"===a[t]&&(s=b(s,r));return s},y=(t,e,r)=>{const{r:n,s}=r,a=t;if(n<=i||n>=c||s<=i||s>=c)return!1;const f=l(s,c);if(f===i)return!1;const p=d(a,f,c),m=d(n,f,c),w=g(p,h),y=g(m,e),v=b(w,y);if(v.Z===i)return!1;const I=l(v.Z,o);if(I===i)return!1;const k=d(I,I,o),P=d(v.X,k,o);return u(P,c)===n},v=BigInt("0x"+t.toString(16));if(null==r.x||null==r.y)throw new Error("Invalid public key: missing coordinates.");return y(v,{x:BigInt("0x"+r.x.toString(16)),y:BigInt("0x"+r.y.toString(16))},{r:BigInt("0x"+e.r.toString(16)),s:BigInt("0x"+e.s.toString(16))})}{const i=new Lt;t=jt(t);const n=e.r,s=e.s;if(n.cmpn(1)<0||n.cmp(i.n)>=0)return!1;if(s.cmpn(1)<0||s.cmp(i.n)>=0)return!1;const a=s.invm(i.n),o=a.mul(t).umod(i.n),c=a.mul(n).umod(i.n),h=i.g.jmulAdd(o,r,c);return!h.isInfinity()&&h.eqXToP(n)}};class Gt extends Kt{static fromPrivateKey(t){const e=(new Lt).g.mul(t);return new Gt(e.x,e.y)}static fromString(t){const e=Kt.fromString(t);return new Gt(e.x,e.y)}static fromDER(t){const e=Kt.fromDER(t);return new Gt(e.x,e.y)}constructor(t,e=null,r=!0){if(t instanceof Kt)super(t.getX(),t.getY());else{if(null===e&&r&&"string"==typeof t&&(66===t.length||130===t.length))throw new Error('You are using the "new PublicKey()" constructor with a DER hex string. You need to use "PublicKey.fromString()" instead.');super(t,e,r)}}deriveSharedSecret(t){if(!this.validate())throw new Error("Public key not valid for ECDH secret derivation");return this.mul(t)}verify(t,e,r){const i=new h(gt(t,r),16);return Xt(i,e,this)}toDER(t){return"hex"===t?this.encode(!0,t):this.encode(!0)}toHash(t){const e=It(this.encode(!0));return"hex"===t?Nt(e):e}toAddress(t=[0]){if("string"==typeof t)if("testnet"===t||"test"===t)t=[111];else{if("mainnet"!==t&&"main"!==t)throw new Error(`Invalid prefix ${t}`);t=[0]}return Vt(this.toHash(),t)}deriveChild(t,e){const r=this.deriveSharedSecret(t),i=Ot(e,"utf8"),n=kt(r.encode(!0),i),s=(new Lt).g.mul(new h(n)),a=this.add(s);return new Gt(a.x,a.y)}static fromMsgHashAndCompactSignature(t,e,r){const i=Ot(e,r);if(65!==i.length)throw new Error("Invalid Compact Signature");const n=i[0];if(n<27||n>=35)throw new Error("Invalid Compact Byte");let s=i[0]-27;return s>3&&(s-=4),new $t(new h(i.slice(1,33)),new h(i.slice(33,65))).RecoverPublicKey(s,t)}}class Yt{_rand;constructor(){const t=()=>{throw new Error("No secure random number generator is available in this environment.")};if(this._rand=t,"object"==typeof self)self.crypto?.getRandomValues?this._rand=t=>{const e=new Uint8Array(t);return self.crypto.getRandomValues(e),[...e]}:this._rand=t;else try{const t=require("crypto");"function"==typeof t.randomBytes&&(this._rand=e=>[...t.randomBytes(e)])}catch{this._rand=t}}generate(t){return this._rand(t)}}let Jt=null;const Zt=t=>(null==Jt&&(Jt=new Yt),Jt.generate(t));class Qt{x;y;constructor(t,e){const r=(new Lt).p;this.x=t.umod(r),this.y=e.umod(r)}toString(){return Ct(this.x.toArray())+"."+Ct(this.y.toArray())}static fromString(t){const[e,r]=t.split(".");return new Qt(new h(Rt(e)),new h(Rt(r)))}}class te{points;threshold;constructor(t,e){this.points=t,this.threshold=e??t.length}static fromPrivateKey(t,e){const r=(new Lt).p,i=[new Qt(new h(0),new h(t.toArray()))];for(let t=1;t<e;t++){const t=new h(Zt(32)).umod(r),e=new h(Zt(32)).umod(r);i.push(new Qt(t,e))}return new te(i)}valueAt(t){const e=(new Lt).p;let r=new h(0);for(let i=0;i<this.threshold;i++){let n=this.points[i].y;for(let r=0;r<this.threshold;r++)if(i!==r){const s=this.points[r].x,a=this.points[i].x,o=t.sub(s).umod(e),c=a.sub(s).umod(e).invm(e),h=o.mul(c).umod(e);n=n.mul(h).umod(e)}r=r.add(n).umod(e)}return r}}class ee{points;threshold;integrity;constructor(t,e,r){this.points=t,this.threshold=e,this.integrity=r}static fromBackupFormat(t){let e=0,r="";const i=t.map(((t,i)=>{const n=t.split(".");if(4!==n.length)throw new Error("Invalid share format in share "+i.toString()+'. Expected format: "x.y.t.i" - received '+t);const[s,a,o,c]=n;if(void 0===o)throw new Error("Threshold not found in share "+i.toString());if(void 0===c)throw new Error("Integrity not found in share "+i.toString());const h=parseInt(o);if(0!==i&&e!==h)throw new Error("Threshold mismatch in share "+i.toString());if(0!==i&&r!==c)throw new Error("Integrity mismatch in share "+i.toString());return e=h,r=c,Qt.fromString([s,a].join("."))}));return new ee(i,e,r)}toBackupFormat(){return this.points.map((t=>t.toString()+"."+this.threshold.toString()+"."+this.integrity))}}class re extends h{static fromRandom(){return new re(Zt(32))}static fromString(t,e="hex"){return new re(super.fromString(t,e).toArray())}static fromHex(t){return new re(super.fromHex(t,"big"))}static fromWif(t,e=1){const r=Dt(t,void 0,e);if(33!==r.data.length)throw new Error("Invalid WIF length");if(1!==r.data[32])throw new Error("Invalid WIF padding");return new re(r.data.slice(0,32))}constructor(t=0,e=10,r="be",i="apply"){if(t instanceof h?(super(),t.copy(this)):super(t,e,r),"nocheck"!==i){const t=this.checkInField();if(!t.inField){if("error"===i)throw new Error("Input is out of field");h.move(this,t.modN)}}}checkInField(){const t=new Lt,e=this.mod(t.n);return{inField:0===this.cmp(e),modN:e}}isValid(){return this.checkInField().inField}sign(t,e,r=!0,i){const n=new h(gt(t,e),16);return Wt(n,this,r,i)}verify(t,e,r){const i=new h(gt(t,r),16);return Xt(i,e,this.toPublicKey())}toPublicKey(){const t=(new Lt).g.mul(this);return new Gt(t.x,t.y)}toWif(t=[128]){if(!this.isValid())throw new Error("Value is out of field");return Vt([...this.toArray("be",32),1],t)}toAddress(t=[0]){return this.toPublicKey().toAddress(t)}toHex(){return super.toHex(32)}toString(t="hex",e=64){return super.toString(t,e)}deriveSharedSecret(t){if(!t.validate())throw new Error("Public key not valid for ECDH secret derivation");return t.mul(this)}deriveChild(t,e){const r=this.deriveSharedSecret(t),i=Ot(e,"utf8"),n=kt(r.encode(!0),i),s=new Lt;return new re(this.add(new h(n)).mod(s.n).toArray())}toKeyShares(t,e){if("number"!=typeof t||"number"!=typeof e)throw new Error("threshold and totalShares must be numbers");if(t<2)throw new Error("threshold must be at least 2");if(e<2)throw new Error("totalShares must be at least 2");if(t>e)throw new Error("threshold should be less than or equal to totalShares");const r=te.fromPrivateKey(this,t),i=[];for(let t=0;t<e;t++){const t=new h(re.fromRandom().toArray()),e=r.valueAt(t);i.push(new Qt(t,e))}const n=this.toPublicKey().toHash("hex").slice(0,8);return new ee(i,t,n)}toBackupShares(t,e){return this.toKeyShares(t,e).toBackupFormat()}static fromBackupShares(t){return re.fromKeyShares(ee.fromBackupFormat(t))}static fromKeyShares(t){const{points:e,threshold:r,integrity:i}=t;if(r<2)throw new Error("threshold must be at least 2");if(e.length<r)throw new Error(`At least ${r} shares are required to reconstruct the private key`);for(let t=0;t<r;t++)for(let i=t+1;i<r;i++)if(e[t].x.eq(e[i].x))throw new Error("Duplicate share detected, each must be unique.");const n=new te(e,r),s=new re(n.valueAt(new h(0)).toArray());if(s.toPublicKey().toHash("hex").slice(0,8)!==i)throw new Error("Integrity hash mismatch");return s}}const ie=[[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]],ne=[[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]];function se(t,e,r){let i,n;for(i=0;i<4;i++)for(n=0;n<4;n++)t[i][n]=t[i][n]^e[r+n][i]}function ae(t){let e,r;for(e=0;e<4;e++)for(r=0;r<4;r++)t[e][r]=ie[(240&t[e][r])>>4][15&t[e][r]]}function oe(t){let e;for(e=0;e<4;e++)t[e]=ie[(240&t[e])>>4][15&t[e]]}function ce(t){const e=t[0];t[0]=t[1],t[1]=t[2],t[2]=t[3],t[3]=e}function he(t){let e,r,i,n,s;for(e=1;e<4;e++)for(r=0;r<(e-1)%2+1;r++){for(s=t[e][r],i=r;n=i+e,n>=4&&(n-=4),n!==r;)t[e][i]=t[e][n],i=n;t[e][i]=s}}function ue(t,e){let r,i=0;for(r=0;r<8;r++)1&e&&(i^=t),128&t?(t<<=1,t^=283):t<<=1,e>>=1;return i}function le(t){let e,r;const i=[[],[],[],[]];for(e=0;e<4;e++)i[0][e]=ue(2,t[0][e])^ue(3,t[1][e])^t[2][e]^t[3][e],i[1][e]=t[0][e]^ue(2,t[1][e])^ue(3,t[2][e])^t[3][e],i[2][e]=t[0][e]^t[1][e]^ue(2,t[2][e])^ue(3,t[3][e]),i[3][e]=ue(3,t[0][e])^t[1][e]^t[2][e]^ue(2,t[3][e]);for(e=0;e<4;e++)for(r=0;r<4;r++)t[e][r]=i[e][r]}function de(t,e){let r,i,n,s;const a=[[],[],[],[]],o=[],c=Array.from(e);if(c.length<=16){for(;c.length<16;)c.unshift(0);s=11}else if(c.length<=24){for(;c.length<24;)c.unshift(0);s=13}else{if(!(e.length<=32))throw new Error("Illegal key length: "+String(e.length));for(;c.length<32;)c.unshift(0);s=15}const h=function(t,e){let r,i;const n=parseInt(String(e.length/4)),s=[];for(r=0;r<e.length;r++)r%4==0&&s.push([]),s[parseInt(String(r/4))].push(e[r]);for(r=n;r<4*t;r++){s[r]=[];const t=s[r-1].slice();if(r%n==0)for(ce(t),oe(t),i=0;i<4;i++)t[i]=t[i]^ne[parseInt(String(r/n))][i];else n>6&&r%n==4&&oe(t);for(i=0;i<4;i++)s[r][i]=s[r-n][i]^t[i]}return s}(s,c);for(r=0;r<15;r++)a[parseInt(String(r/4))].push(t[4*r%15]);for(a[3].push(t[15]),se(a,h,0),n=1;n<s;n++)ae(a),he(a),n+1<s&&le(a),se(a,h,4*n);for(r=0;r<4;r++)for(i=0;i<4;i++)o.push(a[i][r]);return o}const fe=function(t,e,r){return t[e]&1<<r?1:0},pe=function(t){return[(4278190080&t)>>>24,(16711680&t)>>16,(65280&t)>>8,255&t]},me=function(t){let e;const r=[];for(e=0;e<t;e++)r.push(0);return r},we=[225].concat(me(15)),be=function(t,e){let r;const i=[];for(r=0;r<t.length;r++)i[r]=t[r]^e[r];return i},ge=function(t){let e,r=0,i=0;for(e=0;e<t.length;e++)i=r,r=1&t[e],t[e]=t[e]>>1,0!==i&&(t[e]=128|t[e]);return t},ye=function(t,e){let r,i,n=e.slice(),s=me(16);for(r=0;r<16;r++)for(i=7;-1!==i;i--)0!==fe(t,r,i)&&(s=be(s,n)),n=0!==fe(n,15,0)?be(ge(n),we):ge(n);return s},ve=function(t){let e;const r=t.slice();for(e=15;11!==e&&(r[e]=r[e]+1,256===r[e]);e--)r[e]=0;return r};function Ie(t,e){let r,i=me(16);for(r=0;r<t.length;r+=16)i=ye(be(i,t.slice(r,Math.min(r+16,t.length))),e);return i}function ke(t,e,r){let i,n,s,a=e;const o=[];if(0===t.length)return t;const c=Math.ceil(t.length/16);for(i=0;i<c;i++){for(s=be(t.slice(16*i,Math.min(16*(i+1),t.length)),de(a,r)),n=0;n<s.length;n++)o.push(s[n]);i+1<c&&(a=ve(a))}return o}class Pe extends h{static fromRandom(){return new Pe(Zt(32))}encrypt(t,e){const r=Zt(32);t=Ot(t,e);const{result:i,authenticationTag:n}=function(t,e,r,i){let n,s;const a=de(me(16),i);n=[...r],12===r.length?n=n.concat(me(3)).concat([1]):(r.length%16!=0&&(n=n.concat(me(16-r.length%16))),n=n.concat(me(8)),n=Ie(n.concat(me(4)).concat(pe(8*r.length)),a));const o=ke(t,ve(n),i);return s=e.slice(),0===e.length?s=s.concat(me(16)):e.length%16!=0&&(s=s.concat(me(16-e.length%16))),s=s.concat(o),0===o.length?s=s.concat(me(16)):o.length%16!=0&&(s=s.concat(me(16-o.length%16))),s=s.concat(me(4)).concat(pe(8*e.length)).concat(me(4)).concat(pe(8*o.length)),{result:o,authenticationTag:ke(Ie(s,a),n,i)}}(t,[],r,this.toArray("be",32));return Mt([...r,...i,...n],e)}decrypt(t,e){const r=(t=Ot(t,e)).slice(0,32),i=t.slice(32),n=i.slice(-16),s=function(t,e,r,i,n){let s,a;const o=de(me(16),n);s=[...r],12===r.length?s=s.concat(me(3)).concat([1]):(r.length%16!=0&&(s=s.concat(me(16-r.length%16))),s=s.concat(me(8)),s=Ie(s.concat(me(4)).concat(pe(8*r.length)),o));const c=ke(t,ve(s),n);return a=e.slice(),0===e.length?a=a.concat(me(16)):e.length%16!=0&&(a=a.concat(me(16-e.length%16))),a=a.concat(t),0===t.length?a=a.concat(me(16)):t.length%16!=0&&(a=a.concat(me(16-t.length%16))),a=a.concat(me(4)).concat(pe(8*e.length)).concat(me(4)).concat(pe(8*t.length)),ke(Ie(a,o),s,n).join()!==i.join()?null:c}(i.slice(0,-16),[],r,n,this.toArray());if(null===s)throw new Error("Decryption failed!");return Mt(s,e)}}class Ee extends $t{static SIGHASH_ALL=1;static SIGHASH_NONE=2;static SIGHASH_SINGLE=3;static SIGHASH_FORKID=64;static SIGHASH_ANYONECANPAY=128;scope;static format(t){const e={sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,sequence:t.inputSequence},r=[...t.otherInputs];function i(e){const r=new Bt;if(void 0===e)for(const e of t.outputs){const t=e.satoshis??0;r.writeUInt64LE(t);const i=e.lockingScript?.toBinary()??[];r.writeVarIntNum(i.length),r.write(i)}else{const i=t.outputs[e];if(void 0===i)throw new Error(`Output at index ${e} does not exist`);const n=i.satoshis??0;r.writeUInt64LE(n);const s=i.lockingScript?.toBinary()??[];r.writeVarIntNum(s.length),r.write(s)}const i=r.toArray();return vt(i)}r.splice(t.inputIndex,0,e);let n=new Array(32).fill(0),s=new Array(32).fill(0),a=new Array(32).fill(0);t.scope&Ee.SIGHASH_ANYONECANPAY||(n=(()=>{const t=new Bt;for(const e of r){if(void 0===e.sourceTXID){if(null==e.sourceTransaction)throw new Error("Missing sourceTransaction for input");t.write(e.sourceTransaction.hash())}else t.writeReverse(Ot(e.sourceTXID,"hex"));t.writeUInt32LE(e.sourceOutputIndex)}const e=t.toArray();return vt(e)})()),t.scope&Ee.SIGHASH_ANYONECANPAY||(31&t.scope)===Ee.SIGHASH_SINGLE||(31&t.scope)===Ee.SIGHASH_NONE||(s=(()=>{const t=new Bt;for(const e of r){const r=e.sequence??4294967295;t.writeUInt32LE(r)}const e=t.toArray();return vt(e)})()),(31&t.scope)!==Ee.SIGHASH_SINGLE&&(31&t.scope)!==Ee.SIGHASH_NONE?a=i():(31&t.scope)===Ee.SIGHASH_SINGLE&&t.inputIndex<t.outputs.length&&(a=i(t.inputIndex));const o=new Bt;o.writeInt32LE(t.transactionVersion),o.write(n),o.write(s),o.writeReverse(Ot(t.sourceTXID,"hex")),o.writeUInt32LE(t.sourceOutputIndex);const c=t.subscript.toBinary();o.writeVarIntNum(c.length),o.write(c),o.writeUInt64LE(t.sourceSatoshis);const h=e.sequence;return o.writeUInt32LE(h),o.write(a),o.writeUInt32LE(t.lockTime),o.writeUInt32LE(t.scope>>>0),o.toArray()}static fromChecksigFormat(t){if(0===t.length){const t=new h(1),e=new h(1);return new Ee(t,e,1)}const e=t[t.length-1],r=t.slice(0,t.length-1),i=$t.fromDER(r);return new Ee(i.r,i.s,e)}constructor(t,e,r){super(t,e),this.scope=r}hasLowS(){return!this.s.ltn(1)&&!this.s.gt(new h("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex"))}toChecksigFormat(){return[...this.toDER(),this.scope]}}class Se{curve;constructor(){this.curve=new Lt}generateProof(t,e,r,i){const n=re.fromRandom(),s=n.toPublicKey(),a=r.mul(n),o=this.computeChallenge(e,r,i,a,s);return{R:s,SPrime:a,z:n.add(o.mul(t)).umod(this.curve.n)}}verifyProof(t,e,r,i){const{R:n,SPrime:s,z:a}=i,o=this.computeChallenge(t,e,r,s,n),c=this.curve.g.mul(a),h=n.add(t.mul(o));if(!c.eq(h))return!1;const u=e.mul(a),l=s.add(r.mul(o));return!!u.eq(l)}computeChallenge(t,e,r,i,n){const s=[...t.encode(!0),...e.encode(!0),...r.encode(!0),...i.encode(!0),...n.encode(!0)],a=gt(s);return new h(a).umod(this.curve.n)}}const Ne={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_SPLIT:127,OP_LEFT:128,OP_NUM2BIN:128,OP_RIGHT:129,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_NOP2:177,OP_NOP3:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_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(const t in Ne)Ne[Ne[t]]=t;const Oe=Ne;class xe{chunks;static fromASM(t){const e=[],r=t.split(" ");let i=0;for(;i<r.length;){const t=r[i];let n,s=0;if(t.startsWith("OP_")&&void 0!==Oe[t]&&(n=t,s=Oe[t]),"0"===t)s=0,e.push({op:s}),i+=1;else if("-1"===t)s=Oe.OP_1NEGATE,e.push({op:s}),i+=1;else if(void 0===n){let t=r[i];t.length%2!=0&&(t="0"+t);const n=Ot(t,"hex");if(Mt(n,"hex")!==t)throw new Error("invalid hex string in script");const a=n.length;a>=0&&a<Oe.OP_PUSHDATA1?s=a:a<Math.pow(2,8)?s=Oe.OP_PUSHDATA1:a<Math.pow(2,16)?s=Oe.OP_PUSHDATA2:a<Math.pow(2,32)&&(s=Oe.OP_PUSHDATA4),e.push({data:n,op:s}),i+=1}else s===Oe.OP_PUSHDATA1||s===Oe.OP_PUSHDATA2||s===Oe.OP_PUSHDATA4?(e.push({data:Ot(r[i+2],"hex"),op:s}),i+=3):(e.push({op:s}),i+=1)}return new xe(e)}static fromHex(t){if(0===t.length)return xe.fromBinary([]);if(t.length%2!=0)throw new Error("There is an uneven number of characters in the string which suggests it is not hex encoded.");if(!/^[0-9a-fA-F]+$/.test(t))throw new Error("Some elements in this string are not hex encoded.");return xe.fromBinary(Ot(t,"hex"))}static fromBinary(t){t=[...t];const e=[],r=new Ut(t);for(;!r.eof();){const t=r.readUInt8();let i=0,n=[];if(t>0&&t<Oe.OP_PUSHDATA1)i=t,e.push({data:r.read(i),op:t});else if(t===Oe.OP_PUSHDATA1){try{i=r.readUInt8(),n=r.read(i)}catch{r.read()}e.push({data:n,op:t})}else if(t===Oe.OP_PUSHDATA2){try{i=r.readUInt16LE(),n=r.read(i)}catch{r.read()}e.push({data:n,op:t})}else if(t===Oe.OP_PUSHDATA4){try{i=r.readUInt32LE(),n=r.read(i)}catch{r.read()}e.push({data:n,op:t})}else e.push({op:t})}return new xe(e)}constructor(t=[]){this.chunks=t}toASM(){let t="";for(let e=0;e<this.chunks.length;e++){const r=this.chunks[e];t+=this._chunkToString(r)}return t.slice(1)}toHex(){return Mt(this.toBinary(),"hex")}toBinary(){const t=new Bt;for(let e=0;e<this.chunks.length;e++){const r=this.chunks[e],i=r.op;t.writeUInt8(i),null!=r.data&&(i<Oe.OP_PUSHDATA1?t.write(r.data):i===Oe.OP_PUSHDATA1?(t.writeUInt8(r.data.length),t.write(r.data)):i===Oe.OP_PUSHDATA2?(t.writeUInt16LE(r.data.length),t.write(r.data)):i===Oe.OP_PUSHDATA4&&(t.writeUInt32LE(r.data.length),t.write(r.data)))}return t.toArray()}writeScript(t){return this.chunks=this.chunks.concat(t.chunks),this}writeOpCode(t){return this.chunks.push({op:t}),this}setChunkOpCode(t,e){return this.chunks[t]={op:e},this}writeBn(t){if(t.cmpn(0)===Oe.OP_0)this.chunks.push({op:Oe.OP_0});else if(0===t.cmpn(-1))this.chunks.push({op:Oe.OP_1NEGATE});else if(t.cmpn(1)>=0&&t.cmpn(16)<=0)this.chunks.push({op:t.toNumber()+Oe.OP_1-1});else{const e=t.toSm("little");this.writeBin(e)}return this}writeBin(t){let e;if(t.length>0&&t.length<Oe.OP_PUSHDATA1)e=t.length;else if(0===t.length)e=Oe.OP_0;else if(t.length<Math.pow(2,8))e=Oe.OP_PUSHDATA1;else if(t.length<Math.pow(2,16))e=Oe.OP_PUSHDATA2;else{if(!(t.length<Math.pow(2,32)))throw new Error("You can't push that much data");e=Oe.OP_PUSHDATA4}return this.chunks.push({data:t,op:e}),this}writeNumber(t){return this.writeBn(new h(t)),this}removeCodeseparators(){const t=[];for(let e=0;e<this.chunks.length;e++)this.chunks[e].op!==Oe.OP_CODESEPARATOR&&t.push(this.chunks[e]);return this.chunks=t,this}findAndDelete(t){const e=t.toHex();for(let t=0;t<this.chunks.length;t++)e===new xe([this.chunks[t]]).toHex()&&this.chunks.splice(t,1);return this}isPushOnly(){for(let t=0;t<this.chunks.length;t++)if(this.chunks[t].op>Oe.OP_16)return!1;return!0}isLockingScript(){throw new Error("Not implemented")}isUnlockingScript(){throw new Error("Not implemented")}_chunkToString(t){const e=t.op;let r="";return r=void 0===t.data?`${r} ${Oe[e]}`:`${r} ${Nt(t.data)}`,r}}class Ae extends xe{isLockingScript(){return!0}isUnlockingScript(){return!1}}class Te extends xe{isLockingScript(){return!1}isUnlockingScript(){return!0}}const Me=1073741824,_e=Math.pow(2,31)-1,Fe=!0;class Re{sourceTXID;sourceOutputIndex;sourceSatoshis;lockingScript;transactionVersion;otherInputs;outputs;inputIndex;unlockingScript;inputSequence;lockTime;context;programCounter;lastCodeSeparator;stack;altStack;ifStack;memoryLimit;stackMem;altStackMem;constructor(t){this.sourceTXID=t.sourceTXID,this.sourceOutputIndex=t.sourceOutputIndex,this.sourceSatoshis=t.sourceSatoshis,this.lockingScript=t.lockingScript,this.transactionVersion=t.transactionVersion,this.otherInputs=t.otherInputs,this.outputs=t.outputs,this.inputIndex=t.inputIndex,this.unlockingScript=t.unlockingScript,this.inputSequence=t.inputSequence,this.lockTime=t.lockTime,this.memoryLimit=t.memoryLimit??1e5,this.stackMem=0,this.altStackMem=0,this.reset()}reset(){this.context="UnlockingScript",this.programCounter=0,this.lastCodeSeparator=null,this.stack=[],this.altStack=[],this.ifStack=[],this.stackMem=0,this.altStackMem=0}step(){let t;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;const e=()=>{t=void 0};let r;"UnlockingScript"===this.context&&this.programCounter>=this.unlockingScript.chunks.length&&(this.context="LockingScript",this.programCounter=0),r="UnlockingScript"===this.context?this.unlockingScript.chunks[this.programCounter]:this.lockingScript.chunks[this.programCounter];const i=t=>{if(0===t.length)return!0;(t=>{if(t.length<9)return!1;if(t.length>73)return!1;if(48!==t[0])return!1;if(t[1]!==t.length-3)return!1;const e=t[3];if(5+e>=t.length)return!1;const r=t[5+e];if(e+r+7!==t.length)return!1;const i=t.slice(4);if(2!==t[2])return!1;if(t[3]!==e)return!1;if(0===e)return!1;if(128&i[0])return!1;if(e>1&&0===i[0]&&!(128&i[1]))return!1;const n=t.slice(6+e);return!(2!==t[6+e-2]||t[6+e-1]!==r||0===r||128&n[0]||r>1&&0===n[0]&&!(128&n[1]))})(t)||this.scriptEvaluationError("The signature format is invalid.");const e=Ee.fromChecksigFormat(t);return e.hasLowS()||this.scriptEvaluationError("The signature must have a low S value."),!!(e.scope&Ee.SIGHASH_FORKID)||(this.scriptEvaluationError("The signature must use SIGHASH_FORKID."),!1)},n=t=>(t.length<33&&this.scriptEvaluationError("The public key is too short, it must be at least 33 bytes."),4===t[0]?65!==t.length&&this.scriptEvaluationError("The non-compressed public key must be 65 bytes."):2===t[0]||3===t[0]?33!==t.length&&this.scriptEvaluationError("The compressed public key must be 33 bytes."):this.scriptEvaluationError("The public key is in an unknown format."),!0),s=(t,e,r)=>{const i=Ee.format({sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,sourceSatoshis:this.sourceSatoshis,transactionVersion:this.transactionVersion,otherInputs:this.otherInputs,outputs:this.outputs,inputIndex:this.inputIndex,subscript:r,inputSequence:this.inputSequence,lockTime:this.lockTime,scope:t.scope}),n=new h(vt(i));return Xt(n,t,e)},a=!this.ifStack.includes(!1);let o,c,u,l,d,f,p,m,w,b,g,y,v,I,k,P,E,S,N,O,x,A,T,M,_,F,R,C,V,D,B,U;const H=r.op;var K;if(void 0===H&&this.scriptEvaluationError(`An opcode is missing in this chunk of the ${this.context}!`),Array.isArray(r.data)&&r.data.length>Me&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes."),a&&((K=H)===Oe.OP_2MUL||K===Oe.OP_2DIV||K===Oe.OP_VERIF||K===Oe.OP_VERNOTIF||K===Oe.OP_VER)&&this.scriptEvaluationError("This opcode is currently disabled."),a&&H>=0&&H<=Oe.OP_PUSHDATA4)(t=>{const e=t.data,r=t.op;return!(Array.isArray(e)&&(0===e.length?r!==Oe.OP_0:1===e.length&&e[0]>=1&&e[0]<=16?r!==Oe.OP_1+(e[0]-1):1===e.length&&129===e[0]?r!==Oe.OP_1NEGATE:e.length<=75?r!==e.length:e.length<=255?r!==Oe.OP_PUSHDATA1:e.length<=65535&&r!==Oe.OP_PUSHDATA2))})(r)||this.scriptEvaluationError("This data is not minimally-encoded."),Array.isArray(r.data)?(this.stack.push(r.data),this.stackMem+=r.data.length):(this.stack.push([]),this.stackMem+=0);else if(a||Oe.OP_IF<=H&&H<=Oe.OP_ENDIF)switch(H){case Oe.OP_1NEGATE:case Oe.OP_1:case Oe.OP_2:case Oe.OP_3:case Oe.OP_4:case Oe.OP_5:case Oe.OP_6:case Oe.OP_7:case Oe.OP_8:case Oe.OP_9:case Oe.OP_10:case Oe.OP_11:case Oe.OP_12:case Oe.OP_13:case Oe.OP_14:case Oe.OP_15:case Oe.OP_16:f=H-(Oe.OP_1-1),o=new h(f).toScriptNum(),this.stack.push(o),this.stackMem+=o.length;break;case Oe.OP_NOP:case Oe.OP_NOP2:case Oe.OP_NOP3:case Oe.OP_NOP1:case Oe.OP_NOP4:case Oe.OP_NOP5:case Oe.OP_NOP6:case Oe.OP_NOP7:case Oe.OP_NOP8:case Oe.OP_NOP9:case Oe.OP_NOP10:case Oe.OP_NOP11:case Oe.OP_NOP12:case Oe.OP_NOP13:case Oe.OP_NOP14:case Oe.OP_NOP15:case Oe.OP_NOP16:case Oe.OP_NOP17:case Oe.OP_NOP18:case Oe.OP_NOP19:case Oe.OP_NOP20:case Oe.OP_NOP21:case Oe.OP_NOP22:case Oe.OP_NOP23:case Oe.OP_NOP24:case Oe.OP_NOP25:case Oe.OP_NOP26:case Oe.OP_NOP27:case Oe.OP_NOP28:case Oe.OP_NOP29:case Oe.OP_NOP30:case Oe.OP_NOP31:case Oe.OP_NOP32:case Oe.OP_NOP33:case Oe.OP_NOP34:case Oe.OP_NOP35:case Oe.OP_NOP36:case Oe.OP_NOP37:case Oe.OP_NOP38:case Oe.OP_NOP39:case Oe.OP_NOP40:case Oe.OP_NOP41:case Oe.OP_NOP42:case Oe.OP_NOP43:case Oe.OP_NOP44:case Oe.OP_NOP45:case Oe.OP_NOP46:case Oe.OP_NOP47:case Oe.OP_NOP48:case Oe.OP_NOP49:case Oe.OP_NOP50:case Oe.OP_NOP51:case Oe.OP_NOP52:case Oe.OP_NOP53:case Oe.OP_NOP54:case Oe.OP_NOP55:case Oe.OP_NOP56:case Oe.OP_NOP57:case Oe.OP_NOP58:case Oe.OP_NOP59:case Oe.OP_NOP60:case Oe.OP_NOP61:case Oe.OP_NOP62:case Oe.OP_NOP63:case Oe.OP_NOP64:case Oe.OP_NOP65:case Oe.OP_NOP66:case Oe.OP_NOP67:case Oe.OP_NOP68:case Oe.OP_NOP69:case Oe.OP_NOP70:case Oe.OP_NOP71:case Oe.OP_NOP72:case Oe.OP_NOP73:case Oe.OP_NOP77:break;case Oe.OP_IF:case Oe.OP_NOTIF:D=!1,a&&(this.stack.length<1&&this.scriptEvaluationError("OP_IF and OP_NOTIF require at least one item on the stack when they are used!"),o=this.stacktop(-1),D=this.castToBool(o),H===Oe.OP_NOTIF&&(D=!D),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e()),this.ifStack.push(D);break;case Oe.OP_ELSE:0===this.ifStack.length&&this.scriptEvaluationError("OP_ELSE requires a preceeding OP_IF."),this.ifStack[this.ifStack.length-1]=!this.ifStack[this.ifStack.length-1];break;case Oe.OP_ENDIF:0===this.ifStack.length&&this.scriptEvaluationError("OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop();break;case Oe.OP_VERIFY:this.stack.length<1&&this.scriptEvaluationError("OP_VERIFY requires at least one item to be on the stack."),o=this.stacktop(-1),D=this.castToBool(o),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),D||this.scriptEvaluationError("OP_VERIFY requires the top stack value to be truthy.");break;case Oe.OP_RETURN:"UnlockingScript"===this.context?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.ifStack=[];break;case Oe.OP_TOALTSTACK:this.stack.length<1&&this.scriptEvaluationError("OP_TOALTSTACK requires at oeast one item to be on the stack."),t=this.stack.pop(),null!=t&&(this.altStack.push(t),this.altStackMem+=t.length,this.stackMem-=t.length),e();break;case Oe.OP_FROMALTSTACK:this.altStack.length<1&&this.scriptEvaluationError("OP_FROMALTSTACK requires at least one item to be on the stack."),t=this.altStack.pop(),null!=t&&(this.stack.push(t),this.stackMem+=t.length,this.altStackMem-=t.length),e();break;case Oe.OP_2DROP:this.stack.length<2&&this.scriptEvaluationError("OP_2DROP requires at least two items to be on the stack."),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e();break;case Oe.OP_2DUP:this.stack.length<2&&this.scriptEvaluationError("OP_2DUP requires at least two items to be on the stack."),c=this.stacktop(-2),u=this.stacktop(-1),this.stack.push([...c]),this.stackMem+=c.length,this.stack.push([...u]),this.stackMem+=u.length;break;case Oe.OP_3DUP:this.stack.length<3&&this.scriptEvaluationError("OP_3DUP requires at least three items to be on the stack."),c=this.stacktop(-3),u=this.stacktop(-2),l=this.stacktop(-1),this.stack.push([...c]),this.stackMem+=c.length,this.stack.push([...u]),this.stackMem+=u.length,this.stack.push([...l]),this.stackMem+=l.length;break;case Oe.OP_2OVER:this.stack.length<4&&this.scriptEvaluationError("OP_2OVER requires at least four items to be on the stack."),c=this.stacktop(-4),u=this.stacktop(-3),this.stack.push([...c]),this.stackMem+=c.length,this.stack.push([...u]),this.stackMem+=u.length;break;case Oe.OP_2ROT:this.stack.length<6&&this.scriptEvaluationError("OP_2ROT requires at least six items to be on the stack."),d=this.stack.splice(this.stack.length-6,2),this.stack.push(d[0]),this.stackMem+=d[0].length,this.stack.push(d[1]),this.stackMem+=d[1].length;break;case Oe.OP_2SWAP:this.stack.length<4&&this.scriptEvaluationError("OP_2SWAP requires at least four items to be on the stack."),d=this.stack.splice(this.stack.length-4,2),this.stack.push(d[0]),this.stackMem+=d[0].length,this.stack.push(d[1]),this.stackMem+=d[1].length;break;case Oe.OP_IFDUP:this.stack.length<1&&this.scriptEvaluationError("OP_IFDUP requires at least one item to be on the stack."),o=this.stacktop(-1),D=this.castToBool(o),D&&(this.stack.push([...o]),this.stackMem+=o.length);break;case Oe.OP_DEPTH:o=new h(this.stack.length).toScriptNum(),this.stack.push(o),this.stackMem+=o.length;break;case Oe.OP_DROP:this.stack.length<1&&this.scriptEvaluationError("OP_DROP requires at least one item to be on the stack."),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e();break;case Oe.OP_DUP:this.stack.length<1&&this.scriptEvaluationError("OP_DUP requires at least one item to be on the stack."),this.stack.push([...this.stacktop(-1)]),this.stackMem+=this.stacktop(-1).length;break;case Oe.OP_NIP:this.stack.length<2&&this.scriptEvaluationError("OP_NIP requires at least two items to be on the stack."),this.stack.splice(this.stack.length-2,1),this.stackMem-=this.stacktop(-1).length;break;case Oe.OP_OVER:this.stack.length<2&&this.scriptEvaluationError("OP_OVER requires at least two items to be on the stack."),this.stack.push([...this.stacktop(-2)]),this.stackMem+=this.stacktop(-2).length;break;case Oe.OP_PICK:case Oe.OP_ROLL:this.stack.length<2&&this.scriptEvaluationError(`${Oe[H]} requires at least two items to be on the stack.`),o=this.stacktop(-1),I=h.fromScriptNum(o,Fe),f=I.toNumber(),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),(f<0||f>=this.stack.length)&&this.scriptEvaluationError(`${Oe[H]} requires the top stack element to be 0 or a positive number less than the current size of the stack.`),o=this.stacktop(-f-1),H===Oe.OP_ROLL&&(this.stack.splice(this.stack.length-f-1,1),this.stackMem-=o.length),this.stack.push([...o]),this.stackMem+=o.length;break;case Oe.OP_ROT:this.stack.length<3&&this.scriptEvaluationError("OP_ROT requires at least three items to be on the stack."),g=this.stacktop(-3),y=this.stacktop(-2),v=this.stacktop(-1),this.stack[this.stack.length-3]=y,this.stack[this.stack.length-2]=v,this.stack[this.stack.length-1]=g;break;case Oe.OP_SWAP:this.stack.length<2&&this.scriptEvaluationError("OP_SWAP requires at least two items to be on the stack."),g=this.stacktop(-2),y=this.stacktop(-1),this.stack[this.stack.length-2]=y,this.stack[this.stack.length-1]=g;break;case Oe.OP_TUCK:this.stack.length<2&&this.scriptEvaluationError("OP_TUCK requires at least two items to be on the stack."),this.stack.splice(this.stack.length-2,0,[...this.stacktop(-1)]),this.stackMem+=this.stacktop(-1).length;break;case Oe.OP_SIZE:this.stack.length<1&&this.scriptEvaluationError("OP_SIZE requires at least one item to be on the stack."),I=new h(this.stacktop(-1).length),this.stack.push(I.toScriptNum()),this.stackMem+=I.toScriptNum().length;break;case Oe.OP_AND:case Oe.OP_OR:case Oe.OP_XOR:switch(this.stack.length<2&&this.scriptEvaluationError(`${Oe[H]} requires at least one item to be on the stack.`),c=this.stacktop(-2),u=this.stacktop(-1),c.length!==u.length&&this.scriptEvaluationError(`${Oe[H]} requires the top two stack items to be the same size.`),H){case Oe.OP_AND:for(let t=0;t<c.length;t++)c[t]&=u[t];break;case Oe.OP_OR:for(let t=0;t<c.length;t++)c[t]|=u[t];break;case Oe.OP_XOR:for(let t=0;t<c.length;t++)c[t]^=u[t]}t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e();break;case Oe.OP_INVERT:this.stack.length<1&&this.scriptEvaluationError("OP_INVERT requires at least one item to be on the stack."),o=this.stacktop(-1);for(let t=0;t<o.length;t++)o[t]=~o[t];break;case Oe.OP_LSHIFT:case Oe.OP_RSHIFT:if(this.stack.length<2&&this.scriptEvaluationError(`${Oe[H]} requires at least two items to be on the stack.`),c=this.stacktop(-2),0===c.length)t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e();else{let r;k=new h(c),P=h.fromScriptNum(this.stacktop(-1),Fe),f=P.toNumber(),f<0&&this.scriptEvaluationError(`${Oe[H]} requires the top item on the stack not to be negative.`),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),H===Oe.OP_LSHIFT&&(r=k.ushln(f)),H===Oe.OP_RSHIFT&&(r=k.ushrn(f));const i=((t,e)=>{const r=t;for(;r.length<e;)r.unshift(0);return r})(r.toArray().slice(-1*c.length),c.length);this.stack.push(i),this.stackMem+=i.length}break;case Oe.OP_EQUAL:case Oe.OP_EQUALVERIFY:this.stack.length<2&&this.scriptEvaluationError(`${Oe[H]} requires at least two items to be on the stack.`),c=this.stacktop(-2),u=this.stacktop(-1),B=Nt(c)===Nt(u),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),this.stack.push(B?[1]:[]),this.stackMem+=B?1:0,H===Oe.OP_EQUALVERIFY&&(this.castToBool(this.stacktop(-1))?(t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e()):this.scriptEvaluationError("OP_EQUALVERIFY requires the top two stack items to be equal."));break;case Oe.OP_1ADD:case Oe.OP_1SUB:case Oe.OP_NEGATE:case Oe.OP_ABS:case Oe.OP_NOT:case Oe.OP_0NOTEQUAL:switch(this.stack.length<1&&this.scriptEvaluationError(`${Oe[H]} requires at least one items to be on the stack.`),o=this.stacktop(-1),I=h.fromScriptNum(o,Fe),H){case Oe.OP_1ADD:I=I.addn(1);break;case Oe.OP_1SUB:I=I.subn(1);break;case Oe.OP_NEGATE:I=I.neg();break;case Oe.OP_ABS:I.cmpn(0)<0&&(I=I.neg());break;case Oe.OP_NOT:I=new h(0===I.cmpn(0)?1:0);break;case Oe.OP_0NOTEQUAL:I=new h(0!==I.cmpn(0)?1:0)}t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),this.stack.push(I.toScriptNum()),this.stackMem+=I.toScriptNum().length;break;case Oe.OP_ADD:case Oe.OP_SUB:case Oe.OP_MUL:case Oe.OP_MOD:case Oe.OP_DIV:case Oe.OP_BOOLAND:case Oe.OP_BOOLOR:case Oe.OP_NUMEQUAL:case Oe.OP_NUMEQUALVERIFY:case Oe.OP_NUMNOTEQUAL:case Oe.OP_LESSTHAN:case Oe.OP_GREATERTHAN:case Oe.OP_LESSTHANOREQUAL:case Oe.OP_GREATERTHANOREQUAL:case Oe.OP_MIN:case Oe.OP_MAX:switch(this.stack.length<2&&this.scriptEvaluationError(`${Oe[H]} requires at least two items to be on the stack.`),k=h.fromScriptNum(this.stacktop(-2),Fe),P=h.fromScriptNum(this.stacktop(-1),Fe),I=new h(0),H){case Oe.OP_ADD:I=k.add(P);break;case Oe.OP_SUB:I=k.sub(P);break;case Oe.OP_MUL:I=k.mul(P);break;case Oe.OP_DIV:0===P.cmpn(0)&&this.scriptEvaluationError("OP_DIV cannot divide by zero!"),I=k.div(P);break;case Oe.OP_MOD:0===P.cmpn(0)&&this.scriptEvaluationError("OP_MOD cannot divide by zero!"),I=k.mod(P);break;case Oe.OP_BOOLAND:I=new h(0!==k.cmpn(0)&&0!==P.cmpn(0)?1:0);break;case Oe.OP_BOOLOR:I=new h(0!==k.cmpn(0)||0!==P.cmpn(0)?1:0);break;case Oe.OP_NUMEQUAL:case Oe.OP_NUMEQUALVERIFY:I=new h(0===k.cmp(P)?1:0);break;case Oe.OP_NUMNOTEQUAL:I=new h(0!==k.cmp(P)?1:0);break;case Oe.OP_LESSTHAN:I=new h(k.cmp(P)<0?1:0);break;case Oe.OP_GREATERTHAN:I=new h(k.cmp(P)>0?1:0);break;case Oe.OP_LESSTHANOREQUAL:I=new h(k.cmp(P)<=0?1:0);break;case Oe.OP_GREATERTHANOREQUAL:I=new h(k.cmp(P)>=0?1:0);break;case Oe.OP_MIN:I=k.cmp(P)<0?k:P;break;case Oe.OP_MAX:I=k.cmp(P)>0?k:P}t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),this.stack.push(I.toScriptNum()),this.stackMem+=I.toScriptNum().length,H===Oe.OP_NUMEQUALVERIFY&&(this.castToBool(this.stacktop(-1))?(t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e()):this.scriptEvaluationError("OP_NUMEQUALVERIFY requires the top stack item to be truthy."));break;case Oe.OP_WITHIN:this.stack.length<3&&this.scriptEvaluationError("OP_WITHIN requires at least three items to be on the stack."),k=h.fromScriptNum(this.stacktop(-3),Fe),P=h.fromScriptNum(this.stacktop(-2),Fe),E=h.fromScriptNum(this.stacktop(-1),Fe),D=P.cmp(k)<=0&&k.cmp(E)<0,t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),this.stack.push(D?[1]:[]),this.stackMem+=D?1:0;break;case Oe.OP_RIPEMD160:case Oe.OP_SHA1:case Oe.OP_SHA256:case Oe.OP_HASH160:case Oe.OP_HASH256:{this.stack.length<1&&this.scriptEvaluationError(`${Oe[H]} requires at least one item to be on the stack.`);let r=[];o=this.stacktop(-1),H===Oe.OP_RIPEMD160?r=wt(o):H===Oe.OP_SHA1?r=bt(o):H===Oe.OP_SHA256?r=gt(o):H===Oe.OP_HASH160?r=It(o):H===Oe.OP_HASH256&&(r=vt(o)),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),this.stack.push(r),this.stackMem+=r.length;break}case Oe.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case Oe.OP_CHECKSIG:case Oe.OP_CHECKSIGVERIFY:this.stack.length<2&&this.scriptEvaluationError(`${Oe[H]} requires at least two items to be on the stack.`),S=this.stacktop(-2),N=this.stacktop(-1),i(S)&&n(N)||this.scriptEvaluationError(`${Oe[H]} requires correct encoding for the public key and signature.`),O="UnlockingScript"===this.context?new xe(this.unlockingScript.chunks.slice(this.lastCodeSeparator??0)):new xe(this.lockingScript.chunks.slice(this.lastCodeSeparator??0)),O.findAndDelete((new xe).writeBin(S));try{x=Ee.fromChecksigFormat(S),A=Gt.fromDER(N),U=s(x,A,O)}catch(t){U=!1}!U&&S.length>0&&this.scriptEvaluationError(`${Oe[H]} failed to verify the signature, and requires an empty signature when verification fails.`),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),this.stack.push(U?[1]:[]),this.stackMem+=U?1:0,H===Oe.OP_CHECKSIGVERIFY&&(U?(t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e()):this.scriptEvaluationError("OP_CHECKSIGVERIFY requires that a valid signature is provided."));break;case Oe.OP_CHECKMULTISIG:case Oe.OP_CHECKMULTISIGVERIFY:T=1,this.stack.length<T&&this.scriptEvaluationError(`${Oe[H]} requires at least 1 item to be on the stack.`),_=h.fromScriptNum(this.stacktop(-T),Fe).toNumber(),(_<0||_>_e)&&this.scriptEvaluationError(`${Oe[H]} requires a key count between 0 and ${_e}.`),F=++T,T+=_,R=_+2,this.stack.length<T&&this.scriptEvaluationError(`${Oe[H]} requires the number of stack items not to be less than the number of keys used.`),C=h.fromScriptNum(this.stacktop(-T),Fe).toNumber(),(C<0||C>_)&&this.scriptEvaluationError(`${Oe[H]} requires the number of signatures to be no greater than the number of keys.`),V=++T,T+=C,this.stack.length<T&&this.scriptEvaluationError(`${Oe[H]} requires the number of stack items not to be less than the number of signatures provided.`),O="UnlockingScript"===this.context?new xe(this.unlockingScript.chunks.slice(this.lastCodeSeparator??0)):new xe(this.lockingScript.chunks.slice(this.lastCodeSeparator??0));for(let t=0;t<C;t++)S=this.stacktop(-V-t),O.findAndDelete((new xe).writeBin(S));for(U=!0;U&&C>0;){S=this.stacktop(-V),N=this.stacktop(-F),i(S)&&n(N)||this.scriptEvaluationError(`${Oe[H]} requires correct encoding for the public key and signature.`);try{x=Ee.fromChecksigFormat(S),A=Gt.fromString(Nt(N)),M=s(x,A,O)}catch(t){M=!1}M&&(V++,C--),F++,_--,C>_&&(U=!1)}for(;T-- >1;)!U&&0===R&&this.stacktop(-1).length>0&&this.scriptEvaluationError(`${Oe[H]} failed to verify a signature, and requires an empty signature when verification fails.`),R>0&&R--,t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e();this.stack.length<1&&this.scriptEvaluationError(`${Oe[H]} requires an extra item to be on the stack.`),this.stacktop(-1).length>0&&this.scriptEvaluationError(`${Oe[H]} requires the extra stack item to be empty.`),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),this.stack.push(U?[1]:[]),this.stackMem+=U?1:0,H===Oe.OP_CHECKMULTISIGVERIFY&&(U?(t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e()):this.scriptEvaluationError("OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."));break;case Oe.OP_CAT:this.stack.length<2&&this.scriptEvaluationError("OP_CAT requires at least two items to be on the stack."),c=this.stacktop(-2),u=this.stacktop(-1),c.length+u.length>Me&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes."),this.stack[this.stack.length-2]=[...c,...u],this.stackMem-=c.length,this.stackMem-=u.length,this.stackMem+=c.length+u.length,t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e();break;case Oe.OP_SPLIT:this.stack.length<2&&this.scriptEvaluationError("OP_SPLIT requires at least two items to be on the stack."),c=this.stacktop(-2),f=h.fromScriptNum(this.stacktop(-1),Fe).toNumber(),(f<0||f>c.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."),u=[...c],this.stack[this.stack.length-2]=u.slice(0,f),this.stackMem-=c.length,this.stackMem+=f,this.stack[this.stack.length-1]=u.slice(f),this.stackMem+=c.length-f;break;case Oe.OP_NUM2BIN:if(this.stack.length<2&&this.scriptEvaluationError("OP_NUM2BIN requires at least two items to be on the stack."),p=h.fromScriptNum(this.stacktop(-1),Fe).toNumber(),p>Me&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes."),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),m=this.stacktop(-1),m=Ht(m),m.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."),m.length===p){this.stack[this.stack.length-1]=m;break}for(b=0,m.length>0&&(b=128&m[m.length-1],m[m.length-1]&=127),w=new Array(p),w.fill(0),f=0;f<p;f++)w[f]=m[f];for(f=m.length-1;f++<p-2;)w[f]=0;w[f]=b,this.stack[this.stack.length-1]=w,this.stackMem-=m.length,this.stackMem+=p;break;case Oe.OP_BIN2NUM:this.stack.length<1&&this.scriptEvaluationError("OP_BIN2NUM requires at least one item to be on the stack."),c=this.stacktop(-1),u=Ht(c),this.stack[this.stack.length-1]=u,this.stackMem-=c.length,this.stackMem+=u.length,((t,e=Number.MAX_SAFE_INTEGER)=>!(t.length>e||t.length>0&&!(127&t[t.length-1]||!(t.length<=1)&&128&t[t.length-2])))(u)||this.scriptEvaluationError("OP_BIN2NUM requires that the resulting number is valid.");break;default:this.scriptEvaluationError("Invalid opcode!")}return this.programCounter++,!0}validate(){for(this.unlockingScript.isPushOnly()||this.scriptEvaluationError("Unlocking scripts can only contain push operations, and no other opcodes.");this.step()&&!("LockingScript"===this.context&&this.programCounter>=this.lockingScript.chunks.length););return this.ifStack.length>0&&this.scriptEvaluationError("Every OP_IF must be terminated prior to the end of the script."),1!==this.stack.length&&this.scriptEvaluationError("The clean stack rule requires exactly one item to be on the stack after script execution."),this.castToBool(this.stacktop(-1))||this.scriptEvaluationError("The top stack element must be truthy after script evaluation."),!0}stacktop(t){return this.stack[this.stack.length+t]}castToBool(t){for(let e=0;e<t.length;e++)if(0!==t[e])return e!==t.length-1||128!==t[e];return!1}scriptEvaluationError(t){throw new Error(`Script evaluation error: ${t}\n\nSource TXID: ${this.sourceTXID}\nSource output index: ${this.sourceOutputIndex}\nContext: ${this.context}\nProgram counter: ${this.programCounter}\nStack size: ${this.stack.length}\nAlt stack size: ${this.altStack.length}`)}}function Ce(t){if(null==t)throw new Error("must have value");return t}class Ve{lock(t){let e;if("string"==typeof t){const r=Dt(t);if(0!==r.prefix[0]&&111!==r.prefix[0])throw new Error("only P2PKH is supported");e=r.data}else e=t;if(20!==e.length)throw new Error("P2PKH hash length must be 20 bytes");return new Ae([{op:Oe.OP_DUP},{op:Oe.OP_HASH160},{op:e.length,data:e},{op:Oe.OP_EQUALVERIFY},{op:Oe.OP_CHECKSIG}])}unlock(t,e="all",r=!1,i,n){return{sign:async(s,a)=>{let o=Ee.SIGHASH_FORKID;"all"===e&&(o|=Ee.SIGHASH_ALL),"none"===e&&(o|=Ee.SIGHASH_NONE),"single"===e&&(o|=Ee.SIGHASH_SINGLE),r&&(o|=Ee.SIGHASH_ANYONECANPAY);const c=s.inputs[a],h=s.inputs.filter(((t,e)=>e!==a)),u=c.sourceTXID??c.sourceTransaction?.id("hex");if(null==u||void 0===u)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(""===u)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(i||=c.sourceTransaction?.outputs[c.sourceOutputIndex].satoshis,null==i||void 0===i)throw new Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(n||=c.sourceTransaction?.outputs[c.sourceOutputIndex].lockingScript,null==n)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");const l=Ee.format({sourceTXID:u,sourceOutputIndex:Ce(c.sourceOutputIndex),sourceSatoshis:i,transactionVersion:s.version,otherInputs:h,inputIndex:a,outputs:s.outputs,inputSequence:Ce(c.sequence),subscript:n,lockTime:s.lockTime,scope:o}),d=t.sign(gt(l)),f=new Ee(d.r,d.s,o).toChecksigFormat(),p=t.toPublicKey().encode(!0);return new Te([{op:f.length,data:f},{op:p.length,data:p}])},estimateLength:async()=>108}}}class De{type="raw";constructor(t="raw"){this.type=t}lock(t){const e=[{op:Oe.OP_OVER},{op:Oe.OP_3},{op:Oe.OP_SPLIT},{op:Oe.OP_NIP},{op:Oe.OP_1},{op:Oe.OP_SPLIT},{op:Oe.OP_SWAP},{op:Oe.OP_SPLIT},{op:Oe.OP_DROP}];return"raw"!==this.type&&e.push({op:Oe["OP_"+this.type]}),e.push({op:t.length,data:t}),e.push({op:Oe.OP_EQUALVERIFY}),e.push({op:Oe.OP_CHECKSIG}),new Ae(e)}unlock(t,e,r="all",i=!1){return{sign:async(n,s)=>{void 0===e&&(e=re.fromRandom());let a=Ee.SIGHASH_FORKID;"all"===r&&(a|=Ee.SIGHASH_ALL),"none"===r&&(a|=Ee.SIGHASH_NONE),"single"===r&&(a|=Ee.SIGHASH_SINGLE),i&&(a|=Ee.SIGHASH_ANYONECANPAY);const o=[...n.inputs],[c]=o.splice(s,1);if("object"!=typeof c.sourceTransaction)throw new Error("The source transaction is needed for transaction signing.");const h=Ee.format({sourceTXID:c.sourceTransaction?.id("hex")??"",sourceOutputIndex:c.sourceOutputIndex??0,sourceSatoshis:c.sourceTransaction?.outputs[c.sourceOutputIndex]?.satoshis??0,transactionVersion:n.version,otherInputs:o,inputIndex:s,outputs:n.outputs,inputSequence:c.sequence??4294967295,subscript:c.sourceTransaction?.outputs[c.sourceOutputIndex]?.lockingScript??new xe,lockTime:n.lockTime,scope:a}),u=e.sign(gt(h),void 0,!0,t),l=new Ee(u.r,u.s,a).toChecksigFormat(),d=e.toPublicKey().encode(!0);return new Te([{op:l.length,data:l},{op:d.length,data:d}])},estimateLength:async()=>108}}}function Be(t){if(null==t)throw new Error("must have value");return t}class Ue{wallet;originator;static decode(t){const e=Gt.fromString(Nt(Be(t.chunks[0].data))),r=[];for(let e=2;e<t.chunks.length;e++){const i=t.chunks[e+1]?.op;let n=t.chunks[e].data??[];if(0===n.length&&(t.chunks[e].op>=80&&t.chunks[e].op<=95?n=[t.chunks[e].op-80]:0===t.chunks[e].op?n=[0]:79===t.chunks[e].op&&(n=[129])),r.push(n),i===Oe.OP_DROP||i===Oe.OP_2DROP)break}return{fields:r,lockingPublicKey:e}}constructor(t,e){this.wallet=t,this.originator=e}async lock(t,e,r,i,n=!1,s=!0,a="before"){const{publicKey:o}=await this.wallet.getPublicKey({protocolID:e,keyID:r,counterparty:i,forSelf:n},this.originator),c=[],h=[];if(c.push({op:o.length/2,data:Ot(o,"hex")}),c.push({op:Oe.OP_CHECKSIG}),s){const n=t.reduce(((t,e)=>[...t,...e]),[]),{signature:s}=await this.wallet.createSignature({data:n,protocolID:e,keyID:r,counterparty:i},this.originator);t.push(s)}for(const e of t)h.push(0===(u=e).length||1===u.length&&0===u[0]?{op:0}:1===u.length&&u[0]>0&&u[0]<=16?{op:80+u[0]}:1===u.length&&129===u[0]?{op:79}:u.length<=75?{op:u.length,data:u}:u.length<=255?{op:76,data:u}:u.length<=65535?{op:77,data:u}:{op:78,data:u});var u;let l=t.length;for(;l>1;)h.push({op:Oe.OP_2DROP}),l-=2;return 0!==l&&h.push({op:Oe.OP_DROP}),new Ae("before"===a?[...c,...h]:[...h,...c])}unlock(t,e,r,i="all",n=!1,s,a){return{sign:async(o,c)=>{let h=Ee.SIGHASH_FORKID;"all"===i&&(h|=Ee.SIGHASH_ALL),"none"===i&&(h|=Ee.SIGHASH_NONE),"single"===i&&(h|=Ee.SIGHASH_SINGLE),n&&(h|=Ee.SIGHASH_ANYONECANPAY);const u=o.inputs[c],l=o.inputs.filter(((t,e)=>e!==c)),d=u.sourceTXID??u.sourceTransaction?.id("hex");if(null==d||void 0===d)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(s||=u.sourceTransaction?.outputs[u.sourceOutputIndex].satoshis,null==s||void 0===s)throw new Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(a||=u.sourceTransaction?.outputs[u.sourceOutputIndex].lockingScript,null==a)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");const f=Ee.format({sourceTXID:d,sourceOutputIndex:Be(u.sourceOutputIndex),sourceSatoshis:s,transactionVersion:o.version,otherInputs:l,inputIndex:c,outputs:o.outputs,inputSequence:u.sequence??4294967295,subscript:a,lockTime:o.lockTime,scope:h}),p=gt(f),{signature:m}=await this.wallet.createSignature({data:p,protocolID:t,keyID:e,counterparty:r},this.originator),w=$t.fromDER([...m]),b=new Ee(w.r,w.s,h).toChecksigFormat();return new Te([{op:b.length,data:b}])},estimateLength:async()=>73}}}class He{value;constructor(t){this.value=t}async computeFee(t){const e=t=>t>2**32?9:t>65536?5:t>253?3:1;let r=4;r+=e(t.inputs.length);for(let i=0;i<t.inputs.length;i++){const n=t.inputs[i];let s;if(r+=40,"object"==typeof n.unlockingScript)s=n.unlockingScript.toBinary().length;else{if("object"!=typeof n.unlockingScriptTemplate)throw new Error("All inputs must have an unlocking script or an unlocking script template for sat/kb fee computation.");s=await n.unlockingScriptTemplate.estimateLength(t,i)}r+=e(s),r+=s}r+=e(t.outputs.length);for(const i of t.outputs){r+=8;const t=i.lockingScript.toBinary().length;r+=e(t),r+=t}return r+=4,Math.ceil(r/1e3*this.value)}}class Ke{https;constructor(t){this.https=t}async request(t,e){return await new Promise(((r,i)=>{const n=this.https.request(t,e,(t=>{let e="";t.on("data",(t=>{e+=t})),t.on("end",(()=>{const i=t.statusCode>=200&&t.statusCode<=299,n=t.headers["content-type"],s=""!==e&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(e):e;r({status:t.statusCode,statusText:t.statusMessage,ok:i,data:s})}))}));n.on("error",(t=>{i(t)})),null!==e.data&&void 0!==e.data&&n.write(JSON.stringify(e.data)),n.end()}))}}class qe{fetch;constructor(t){this.fetch=t}async request(t,e){const r={method:e.method,headers:e.headers,body:JSON.stringify(e.data)},i=await this.fetch(t,r),n=i.headers.get("Content-Type"),s=n?.startsWith("application/json")?await i.json():await i.text();return{ok:i.ok,status:i.status,statusText:i.statusText,data:s}}}function Le(){const t={async request(...t){throw new Error("No method available to perform HTTP request")}};if("undefined"!=typeof window&&"function"==typeof window.fetch)return new qe(window.fetch.bind(window));if("undefined"==typeof require)return t;try{const t=require("https");return new Ke(t)}catch(e){return t}}function $e(){return`ts-sdk-${Nt(Zt(16))}`}class ze{URL;apiKey;deploymentId;callbackUrl;callbackToken;headers;httpClient;constructor(t,e){if(this.URL=t,"string"==typeof e)this.apiKey=e,this.httpClient=Le(),this.deploymentId=$e(),this.callbackToken=void 0,this.callbackUrl=void 0;else{const t=e??{},{apiKey:r,deploymentId:i,httpClient:n,callbackToken:s,callbackUrl:a,headers:o}=t;this.apiKey=r,this.httpClient=n??Le(),this.deploymentId=i??$e(),this.callbackToken=s,this.callbackUrl=a,this.headers=o}}requestHeaders(){const t={"Content-Type":"application/json","XDeployment-ID":this.deploymentId};if(null!=this.apiKey&&""!==this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),null!=this.callbackUrl&&""!==this.callbackUrl&&(t["X-CallbackUrl"]=this.callbackUrl),null!=this.callbackToken&&""!==this.callbackToken&&(t["X-CallbackToken"]=this.callbackToken),null!=this.headers)for(const e in this.headers)t[e]=this.headers[e];return t}async broadcast(t){let e;try{e=t.toHexEF()}catch(r){if("All inputs must have source transactions when serializing to EF format"!==r.message)throw r;e=t.toHex()}const r={method:"POST",headers:this.requestHeaders(),data:{rawTx:e}};try{const t=await this.httpClient.request(`${this.URL}/v1/tx`,r);if(t.ok){const{txid:e,extraInfo:r,txStatus:i,competingTxs:n}=t.data,s={status:"success",txid:e,message:`${i} ${r}`};return null!=n&&(s.competingTxs=n),s}{const e=typeof t.status,r={status:"error",code:"number"===e||"string"===e?t.status.toString():"ERR_UNKNOWN",description:"Unknown error"};let i=t.data;if("string"==typeof i)try{i=JSON.parse(t.data)}catch{}return"object"==typeof i&&(null!==i&&(r.more=i),null!=i&&"string"==typeof i.txid&&(r.txid=i.txid),null!=i&&"detail"in i&&"string"==typeof i.detail&&(r.description=i.detail)),r}}catch(t){return{status:"error",code:"500",description:"string"==typeof t.message?t.message:"Internal Server Error"}}}async broadcastMany(t){const e=t.map((t=>{try{return{rawTx:t.toHexEF()}}catch(e){if("All inputs must have source transactions when serializing to EF format"===e.message)return{rawTx:t.toHex()};throw e}})),r={method:"POST",headers:this.requestHeaders(),data:e};try{return(await this.httpClient.request(`${this.URL}/v1/txs`,r)).data}catch(e){const r={status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"};return t.map((()=>r))}}}function je(t=!1,e={}){return new ze(t?"https://arc-test.taal.com":"https://arc.taal.com",e)}class We{network;apiKey;URL;httpClient;constructor(t="main",e={}){const{apiKey:r,httpClient:i}=e;this.network=t,this.URL=`https://api.whatsonchain.com/v1/bsv/${t}`,this.httpClient=i??Le(),this.apiKey=r??""}async isValidRootForHeight(t,e){const r={method:"GET",headers:this.getHttpHeaders()},i=await this.httpClient.request(`${this.URL}/block/${e}/header`,r);if(i.ok){const{merkleroot:e}=i.data;return e===t}if(404===i.status)return!1;throw new Error(`Failed to verify merkleroot for height ${e} because of an error: ${JSON.stringify(i.data)} `)}async currentHeight(){try{const t={method:"GET",headers:this.getHttpHeaders()},e=await this.httpClient.request(`${this.URL}/block/headers`,t);if(e.ok)return e.data[0].height;throw new Error(`Failed to get current height because of an error: ${JSON.stringify(e.data)} `)}catch(t){throw new Error(`Failed to get current height because of an error: ${t instanceof Error?t.message:String(t)}`)}}getHttpHeaders(){const t={Accept:"application/json"};return"string"==typeof this.apiKey&&""!==this.apiKey.trim()&&(t.Authorization=this.apiKey),t}}function Xe(){return new We}class Ge{blockHeight;path;static fromHex(t){return Ge.fromBinary(Ot(t,"hex"))}static fromReader(t,e=!0){const r=t.readVarIntNum(),i=t.readUInt8(),n=Array(i).fill(null).map((()=>[]));let s,a,o;for(let e=0;e<i;e++){for(o=t.readVarIntNum();o>0;){a=t.readVarIntNum(),s=t.readUInt8();const r={offset:a};1&s?r.duplicate=!0:(2&s&&(r.txid=!0),r.hash=Nt(t.read(32).reverse())),Array.isArray(n[e])&&0!==n[e].length||(n[e]=[]),n[e].push(r),o--}n[e].sort(((t,e)=>t.offset-e.offset))}return new Ge(r,n,e)}static fromBinary(t){const e=new Ut(t);return Ge.fromReader(e)}static fromCoinbaseTxidAndHeight(t,e){return new Ge(e,[[{offset:0,hash:t,txid:!0}]])}constructor(t,e,r=!0){this.blockHeight=t,this.path=e;const i=Array(this.path.length).fill(0).map((()=>new Set));let n;this.path.forEach(((t,e)=>{if(0===t.length&&0===e)throw new Error(`Empty level at height: ${e}`);const n=new Set;t.forEach((t=>{if(n.has(t.offset))throw new Error(`Duplicate offset: ${t.offset}, at height: ${e}`);if(n.add(t.offset),0===e){if(!0!==t.duplicate)for(let e=1;e<this.path.length;e++)i[e].add(t.offset>>e^1)}else if(r&&!i[e].has(t.offset))throw new Error(`Invalid offset: ${t.offset}, at height: ${e}, with legal offsets: ${Array.from(i[e]).join(", ")}`)}))})),this.path[0].forEach(((t,e)=>{if(0===e&&(n=this.computeRoot(t.hash)),n!==this.computeRoot(t.hash))throw new Error("Mismatched roots")}))}toBinary(){const t=new Bt;t.writeVarIntNum(this.blockHeight);const e=this.path.length;t.writeUInt8(e);for(let r=0;r<e;r++){const e=Object.keys(this.path[r]).length;t.writeVarIntNum(e);for(const e of this.path[r]){t.writeVarIntNum(e.offset);let r=0;!0===e?.duplicate&&(r|=1),void 0!==e?.txid&&null!==e.txid&&(r|=2),t.writeUInt8(r),1&r||t.write(Ot(e.hash,"hex").reverse())}}return t.toArray()}toHex(){return Nt(this.toBinary())}indexOf(t){const e=this.path[0].find((e=>e.hash===t));if(null==e)throw new Error(`Transaction ID ${t} not found in the Merkle Path`);return e.offset}computeRoot(t){if("string"!=typeof t){const e=this.path[0].find((t=>Boolean(t?.hash)));if(null==e)throw new Error("No valid leaf found in the Merkle Path");t=e.hash}if("string"!=typeof t)throw new Error("Transaction ID is undefined");const e=this.indexOf(t);if("number"!=typeof e)throw new Error(`This proof does not contain the txid: ${t??"undefined"}`);const r=t=>Nt(vt(Ot(t,"hex").reverse()).reverse());let i=t;if(1===this.path.length&&1===this.path[0].length)return i;for(let t=0;t<this.path.length;t++){this.path[t];const n=e>>t^1,s=this.findOrComputeLeaf(t,n);if("object"!=typeof s)throw new Error(`Missing hash for index ${e} at height ${t}`);i=!0===s.duplicate?r((i??"")+(i??"")):r(n%2!=0?(s.hash??"")+(i??""):(i??"")+(s.hash??""))}return i}findOrComputeLeaf(t,e){const r=t=>Nt(vt(Ot(t,"hex").reverse()).reverse());let i=this.path[t].find((t=>t.offset===e));if(null!=i)return i;if(0===t)return;const n=t-1,s=e<<1,a=this.findOrComputeLeaf(n,s);if(null==a||null==a.hash||""===a.hash)return;const o=this.findOrComputeLeaf(n,s+1);if(null==o)return;let c;return c=!0===o.duplicate?r(a.hash+a.hash):r((o.hash??"")+(a.hash??"")),i={offset:e,hash:c},i}async verify(t,e){const r=this.computeRoot(t);if(0===this.indexOf(t)){const t=await e.currentHeight();if(this.blockHeight+100<t)return!1}return await e.isValidRootForHeight(r,this.blockHeight)}combine(t){if(this.blockHeight!==t.blockHeight)throw new Error("You cannot combine paths which do not have the same block height.");if(this.computeRoot()!==t.computeRoot())throw new Error("You cannot combine paths which do not have the same root.");const e=[];for(let r=0;r<this.path.length;r++){e.push([]);for(let t=0;t<this.path[r].length;t++)e[r].push(this.path[r][t]);for(let i=0;i<t.path[r].length;i++)if(void 0===e[r].find((e=>e.offset===t.path[r][i].offset)))e[r].push(t.path[r][i]);else if(void 0!==t.path[r][i]?.txid&&null!==t.path[r][i]?.txid){const n=e[r].find((e=>e.offset===t.path[r][i].offset));null!=n&&(n.txid=!0)}}this.path=e,this.trim()}trim(){const t=(t,e)=>{0!==e.length&&e.slice(-1)[0]===t||e.push(t)},e=(t,e)=>{for(let r=t.length;r>=0;r--){const i=this.path[e].findIndex((e=>e.offset===t[r]));i>=0&&this.path[e].splice(i,1)}},r=e=>{const r=[];for(const i of e)t(i>>1,r);return r};let i=[],n=[];for(let t=0;t<this.path.length;t++)this.path[t].sort(((t,e)=>t.offset-e.offset));for(let e=0;e<this.path[0].length;e++){const r=this.path[0][e];if(!0===r.txid)t(r.offset>>1,i);else{const i=r.offset%2==1,s=this.path[0][e+(i?-1:1)];void 0!==s.txid&&null!==s.txid&&s.txid||t(s.offset,n)}}e(n,0);for(let t=1;t<this.path.length;t++)n=i,i=r(i),e(n,t)}}class Ye{_bumpIndex;_tx;_rawTx;_txid;inputTxids=[];isValid=void 0;get bumpIndex(){return this._bumpIndex}set bumpIndex(t){this._bumpIndex=t,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=Nt(vt(this._rawTx)),this._txid;throw new Error("Internal")}get tx(){return null!=this._tx?this._tx:null!=this._rawTx?(this._tx=ir.fromBinary(this._rawTx),this._tx):void 0}get rawTx(){return null!=this._rawTx?this._rawTx:null!=this._tx?(this._rawTx=this._tx.toBinary(),this._rawTx):void 0}constructor(t,e){"string"==typeof t?this._txid=t:Array.isArray(t)?this._rawTx=t:this._tx=t,this.bumpIndex=e,this.updateInputTxids()}static fromTx(t,e){return new Ye(t,e)}static fromRawTx(t,e){return new Ye(t,e)}static fromTxid(t,e){return new Ye(t,e)}updateInputTxids(){if(this.hasProof||null==this.tx)this.inputTxids=[];else{const t={};for(const e of this.tx.inputs)void 0!==e.sourceTXID&&null!==e.sourceTXID&&""!==e.sourceTXID&&(t[e.sourceTXID]=!0);this.inputTxids=Object.keys(t)}}toWriter(t,e){const r=e=>{t.writeUInt8(e)},i=()=>{if(null!=this._rawTx)t.write(this._rawTx);else{if(null==this._tx)throw new Error("a valid serialized Transaction is expected");t.write(this._tx.toBinary())}};e===Qe?this.isTxidOnly?(r(er.TXID_ONLY),(()=>{if(null==this._txid)throw new Error("Transaction ID (_txid) is undefined");t.writeReverse(Ot(this._txid,"hex"))})()):void 0!==this.bumpIndex?(r(er.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex),i()):(r(er.RAWTX),i()):(i(),(()=>{void 0===this.bumpIndex?r(er.RAWTX):(r(er.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex))})())}static fromReader(t,e){let r,i,n;if(e===Qe){const e=t.readUInt8();e===er.TXID_ONLY?n=Ye.fromTxid(Nt(t.readReverse(32))):(e===er.RAWTX_AND_BUMP_INDEX&&(i=t.readVarIntNum()),r=ir.fromReader(t),n=Ye.fromTx(r,i))}else r=ir.fromReader(t),i=0!==t.readUInt8()?t.readVarIntNum():void 0,n=Ye.fromTx(r,i);return n}}function Je(t){if(null==t)throw new Error("Expected a valid value, but got undefined.");return t}const Ze=4022206465,Qe=4022206466,tr=16843009;var er;!function(t){t[t.RAWTX=0]="RAWTX",t[t.RAWTX_AND_BUMP_INDEX=1]="RAWTX_AND_BUMP_INDEX",t[t.TXID_ONLY=2]="TXID_ONLY"}(er||(er={}));class rr{bumps=[];txs=[];version=Qe;atomicTxid=void 0;constructor(t=Qe){this.version=t}findTxid(t){return this.txs.find((e=>e.txid===t))}makeTxidOnly(t){const e=this.txs.findIndex((e=>e.txid===t));if(-1===e)return;let r=this.txs[e];return r.isTxidOnly||(this.txs.splice(e,1),r=this.mergeTxidOnly(t)),r}findBump(t){return this.bumps.find((e=>e.path[0].some((e=>e.hash===t))))}findTransactionForSigning(t){const e=this.findTxid(t);if(null!=e&&null!=e.tx){for(const t of e.tx.inputs)if(null==t.sourceTransaction){const e=this.findTxid(Je(t.sourceTXID));null!=e&&(t.sourceTransaction=e.tx)}return e.tx}}findAtomicTransaction(t){const e=this.findTxid(t);if(null==e||null==e.tx)return;const r=(t,e)=>{const i=t.findBump(e.id("hex"));if(null!=i)e.merklePath=i;else for(const i of e.inputs){if(null==i.sourceTransaction){const e=t.findTxid(Je(i.sourceTXID));null!=e&&(i.sourceTransaction=e.tx)}if(null!=i.sourceTransaction){const e=t.findBump(i.sourceTransaction.id("hex"));null!=e?i.sourceTransaction.merklePath=e:r(t,i.sourceTransaction)}}};return r(this,e.tx),e.tx}mergeBump(t){let e;for(let r=0;r<this.bumps.length;r++){const i=this.bumps[r];if(i===t)return r;if(i.blockHeight===t.blockHeight&&i.computeRoot()===t.computeRoot()){i.combine(t),e=r;break}}void 0===e&&(e=this.bumps.length,this.bumps.push(t));const r=this.bumps[e];for(const t of this.txs){const i=t.txid;if(null==t.bumpIndex)for(const n of r.path[0])if(n.hash===i){t.bumpIndex=e,n.txid=!0;break}}return e}mergeRawTx(t,e){const r=new Ye(t,e);return this.removeExistingTxid(r.txid),this.txs.push(r),this.tryToValidateBumpIndex(r),r}mergeTransaction(t){const e=t.id("hex");let r;this.removeExistingTxid(e),null!=t.merklePath&&(r=this.mergeBump(t.merklePath));const i=new Ye(t,r);if(this.txs.push(i),this.tryToValidateBumpIndex(i),r=i.bumpIndex,void 0===r)for(const e of t.inputs)null!=e.sourceTransaction&&this.mergeTransaction(e.sourceTransaction);return i}removeExistingTxid(t){const e=this.txs.findIndex((e=>e.txid===t));e>=0&&this.txs.splice(e,1)}mergeTxidOnly(t){let e=this.txs.find((e=>e.txid===t));return null==e&&(e=new Ye(t),this.txs.push(e),this.tryToValidateBumpIndex(e)),e}mergeBeefTx(t){let e=this.findTxid(t.txid);if(t.isTxidOnly&&null==e?e=this.mergeTxidOnly(t.txid):null==t._tx||null!=e&&!e.isTxidOnly?null==t._rawTx||null!=e&&!e.isTxidOnly||(e=this.mergeRawTx(t._rawTx)):e=this.mergeTransaction(t._tx),null==e)throw new Error(`Failed to merge BeefTx for txid: ${t.txid}`);return e}mergeBeef(t){const e=Array.isArray(t)?rr.fromBinary(t):t;for(const t of e.bumps)this.mergeBump(t);for(const t of e.txs)this.mergeBeefTx(t)}isValid(t){return this.verifyValid(t).valid}async verify(t,e){const r=this.verifyValid(e);if(!r.valid)return!1;for(const e of Object.keys(r.roots))if(!await t.isValidRootForHeight(r.roots[e],Number(e)))return!1;return!0}verifyValid(t){const e={valid:!1,roots:{}},r=this.sortTxs();if(r.missingInputs.length>0||r.notValid.length>0||r.txidOnly.length>0&&!0!==t||r.withMissingInputs.length>0)return e;const i={};for(const r of this.txs)if(r.isTxidOnly){if(!0!==t)return e;i[r.txid]=!0}const n=(t,r)=>{const i=t.computeRoot(r);return void 0!==e.roots[t.blockHeight]&&""!==e.roots[t.blockHeight]||(e.roots[t.blockHeight]=i),e.roots[t.blockHeight]===i};for(const t of this.bumps)for(const r of t.path[0])if(!0===r.txid&&"string"==typeof r.hash&&r.hash.length>0&&(i[r.hash]=!0,!n(t,r.hash)))return e;for(const t of this.txs)if(void 0!==t.bumpIndex&&null==this.bumps[t.bumpIndex].path[0].find((e=>e.hash===t.txid)))return e;for(const t of this.txs){for(const r of t.inputTxids)if(!i[r])return e;i[t.txid]=!0}return e.valid=!0,e}toWriter(t){t.writeUInt32LE(this.version),t.writeVarIntNum(this.bumps.length);for(const e of this.bumps)t.write(e.toBinary());t.writeVarIntNum(this.txs.length);for(const e of this.txs)e.toWriter(t,this.version)}toBinary(){this.sortTxs();const t=new Bt;return this.toWriter(t),t.toArray()}toBinaryAtomic(t){this.sortTxs();const e=this.findTxid(t);if(null==e)throw new Error(`${t} does not exist in this Beef`);const r=this.txs[this.txs.length-1]===e?this:this.clone();if(r!==this){const e=this.txs.findIndex((e=>e.txid===t));r.txs.splice(e+1)}const i=new Bt;return i.writeUInt32LE(tr),i.writeReverse(Ot(t,"hex")),r.toWriter(i),i.toArray()}toHex(){return Nt(this.toBinary())}static fromReader(t){let e,r=t.readUInt32LE();if(r===tr&&(e=Nt(t.readReverse(32)),r=t.readUInt32LE()),r!==Ze&&r!==Qe)throw new Error(`Serialized BEEF must start with ${Ze} or ${Qe} but starts with ${r}`);const i=new rr(r),n=t.readVarIntNum();for(let e=0;e<n;e++){const e=Ge.fromReader(t,!1);i.bumps.push(e)}const s=t.readVarIntNum();for(let e=0;e<s;e++){const e=Ye.fromReader(t,r);i.txs.push(e)}return i.atomicTxid=e,i}static fromBinary(t){const e=new Ut(t);return rr.fromReader(e)}static fromString(t,e="hex"){const r=Ot(t,e),i=new Ut(r);return rr.fromReader(i)}tryToValidateBumpIndex(t){if(void 0!==t.bumpIndex)return!0;const e=t.txid;for(let r=0;r<this.bumps.length;r++){const i=this.bumps[r].path[0].findIndex((t=>t.hash===e));if(i>=0)return t.bumpIndex=r,this.bumps[r].path[0][i].txid=!0,!0}return!1}sortTxs(){const t={},e={};let r=[];const i=[],n=[];for(const 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,n.push(s)):r.push(s);const s={},a=[],o=r;r=[];for(const t of o){let i=!1;for(const r of t.inputTxids)void 0===e[r]&&(s[r]=!0,i=!0);i?a.push(t):r.push(t)}for(;r.length>0;){const e=r;r=[];for(const n of e)n.inputTxids.every((e=>t[e]))?(t[n.txid]=!0,i.push(n)):r.push(n);if(e.length===r.length)break}const c=r;return this.txs=a.concat(c).concat(n).concat(i),{missingInputs:Object.keys(s),notValid:c.map((t=>t.txid)),valid:Object.keys(t),withMissingInputs:a.map((t=>t.txid)),txidOnly:n.map((t=>t.txid))}}clone(){const t=new rr;return t.version=this.version,t.bumps=Array.from(this.bumps),t.txs=Array.from(this.txs),t}trimKnownTxids(t){for(let e=0;e<this.txs.length;){const r=this.txs[e];r.isTxidOnly&&t.includes(r.txid)?this.txs.splice(e,1):e++}}getValidTxids(){return this.sortTxs().valid}toLogString(){let t="";t+=`BEEF with ${this.bumps.length} BUMPS and ${this.txs.length} Transactions, isValid ${this.isValid().toString()}\n`;let e=-1;for(const r of this.bumps)e++,t+=` BUMP ${e}\n block: ${r.blockHeight}\n txids: [\n${r.path[0].filter((t=>!0===t.txid)).map((t=>` '${t.hash??""}'`)).join(",\n")}\n ]\n`;e=-1;for(const r of this.txs)e++,t+=` TX ${e}\n txid: ${r.txid}\n`,void 0!==r.bumpIndex&&(t+=` bumpIndex: ${r.bumpIndex}\n`),r.isTxidOnly?t+=" txidOnly\n":t+=` rawTx length=${r.rawTx?.length??0}\n`,r.inputTxids.length>0&&(t+=` inputs: [\n${r.inputTxids.map((t=>` '${t}'`)).join(",\n")}\n ]\n`);return t}addComputedLeaves(){for(const e of this.bumps)for(let r=1;r<e.path.length;r++)for(const i of e.path[r-1])if("string"==typeof i.hash&&!(1&i.offset)){const n=e.path[r-1].find((t=>t.offset===i.offset+1)),s=i.offset>>1;void 0!==n&&"string"==typeof n.hash&&e.path[r].every((t=>t.offset!==s))&&e.path[r].push({offset:s,hash:(t=n.hash+i.hash,Nt(vt(Ot(t,"hex").reverse()).reverse()))})}var t}}class ir{version;inputs;outputs;lockTime;metadata;merklePath;cachedHash;static addPathOrInputs(t,e,r){if("number"==typeof t.pathIndex){const e=r[t.pathIndex];if("object"!=typeof e)throw new Error("Invalid merkle path index found in BEEF!");t.tx.merklePath=e}else for(const i of t.tx.inputs){if(void 0===i.sourceTXID)throw new Error("Input sourceTXID is undefined");const t=e[i.sourceTXID];if("object"!=typeof t)throw new Error(`Reference to unknown TXID in BEEF: ${i.sourceTXID??"undefined"}`);i.sourceTransaction=t.tx,this.addPathOrInputs(t,e,r)}}static fromBEEF(t,e){const{tx:r}=ir.fromAnyBeef(t,e);return r}static fromAtomicBEEF(t){const{tx:e,txid:r,beef:i}=ir.fromAnyBeef(t);if(r!==i.atomicTxid)throw i.atomicTxid?new Error(`Transaction with TXID ${i.atomicTxid} not found in BEEF data.`):new Error("beef must conform to BRC-95 and must contain the subject txid.");return e}static fromAnyBeef(t,e){const r=rr.fromBinary(t);if(r.txs.length<1)throw new Error("beef must include at least one transaction.");const i=e||r.atomicTxid||r.txs.slice(-1)[0].txid,n=r.findAtomicTransaction(i);if(null==n)throw e?new Error(`Transaction with TXID ${i} not found in BEEF data.`):new Error("beef does not contain transaction for atomic txid.");return{tx:n,beef:r,txid:i}}static fromEF(t){const e=new Ut(t),r=e.readUInt32LE();if("0000000000ef"!==Nt(e.read(6)))throw new Error("Invalid EF marker");const i=e.readVarIntNum(),n=[];for(let t=0;t<i;t++){const t=Nt(e.readReverse(32)),r=e.readUInt32LE(),i=e.readVarIntNum(),s=e.read(i),a=Te.fromBinary(s),o=e.readUInt32LE(),c=e.readUInt64LEBn().toNumber(),h=e.readVarIntNum(),u=e.read(h),l=Ae.fromBinary(u),d=new ir(void 0,[],[],void 0);d.outputs=Array(r+1).fill(null),d.outputs[r]={satoshis:c,lockingScript:l},n.push({sourceTransaction:d,sourceTXID:t,sourceOutputIndex:r,unlockingScript:a,sequence:o})}const s=e.readVarIntNum(),a=[];for(let t=0;t<s;t++){const t=e.readUInt64LEBn().toNumber(),r=e.readVarIntNum(),i=e.read(r),n=Ae.fromBinary(i);a.push({satoshis:t,lockingScript:n})}const o=e.readUInt32LE();return new ir(r,n,a,o)}static parseScriptOffsets(t){const e=new Ut(t),r=[],i=[];e.pos+=4;const n=e.readVarIntNum();for(let t=0;t<n;t++){e.pos+=36;const i=e.readVarIntNum();r.push({vin:t,offset:e.pos,length:i}),e.pos+=i+4}const s=e.readVarIntNum();for(let t=0;t<s;t++){e.pos+=8;const r=e.readVarIntNum();i.push({vout:t,offset:e.pos,length:r}),e.pos+=r}return{inputs:r,outputs:i}}static fromReader(t){const e=t.readUInt32LE(),r=t.readVarIntNum(),i=[];for(let e=0;e<r;e++){const e=Nt(t.readReverse(32)),r=t.readUInt32LE(),n=t.readVarIntNum(),s=t.read(n),a=Te.fromBinary(s),o=t.readUInt32LE();i.push({sourceTXID:e,sourceOutputIndex:r,unlockingScript:a,sequence:o})}const n=t.readVarIntNum(),s=[];for(let e=0;e<n;e++){const e=t.readUInt64LEBn().toNumber(),r=t.readVarIntNum(),i=t.read(r),n=Ae.fromBinary(i);s.push({satoshis:e,lockingScript:n})}const a=t.readUInt32LE();return new ir(e,i,s,a)}static fromBinary(t){const e=new Ut(t);return ir.fromReader(e)}static fromHex(t){return ir.fromBinary(Ot(t,"hex"))}static fromHexEF(t){return ir.fromEF(Ot(t,"hex"))}static fromHexBEEF(t,e){return ir.fromBEEF(Ot(t,"hex"),e)}constructor(t=1,e=[],r=[],i=0,n={},s){this.version=t,this.inputs=e,this.outputs=r,this.lockTime=i,this.metadata=n,this.merklePath=s}addInput(t){if(void 0===t.sourceTXID&&void 0===t.sourceTransaction)throw new Error("A reference to an an input transaction is required. If the input transaction itself cannot be referenced, its TXID must still be provided.");void 0===t.sequence&&(t.sequence=4294967295),this.cachedHash=void 0,this.inputs.push(t)}addOutput(t){if(this.cachedHash=void 0,!0!==t.change){if(void 0===t.satoshis)throw new Error("either satoshis must be defined or change must be set to true");if(t.satoshis<0)throw new Error("satoshis must be a positive integer or zero")}if(null==t.lockingScript)throw new Error("lockingScript must be defined");this.outputs.push(t)}addP2PKHOutput(t,e){const r=(new Ve).lock(t);if(void 0===e)return this.addOutput({lockingScript:r,change:!0});this.addOutput({lockingScript:r,satoshis:e})}updateMetadata(t){this.metadata={...this.metadata,...t}}async fee(t=new He(1),e="equal"){if(this.cachedHash=void 0,"number"==typeof t){const e=t;t={computeFee:async()=>e}}const r=await t.computeFee(this),i=this.calculateChange(r);i<=0?this.outputs=this.outputs.filter((t=>!0!==t.change)):this.distributeChange(i,e)}calculateChange(t){let e=0;for(const t of this.inputs){if("object"!=typeof t.sourceTransaction)throw new Error("Source transactions are required for all inputs during fee computation");e+=t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0}e-=t;for(const t of this.outputs)!0!==t.change&&void 0!==t.satoshis&&(e-=t.satoshis);return e}distributeChange(t,e){let r=0;const i=this.outputs.filter((t=>t.change));if("random"===e?r=this.distributeRandomChange(t,i):"equal"===e&&(r=this.distributeEqualChange(t,i)),r<t){const e=this.outputs[this.outputs.length-1];void 0!==e.satoshis?e.satoshis+=t-r:e.satoshis=t-r}}distributeRandomChange(t,e){let r=0,i=t;const n=Array(e.length).fill(1);i-=e.length,r+=e.length;for(let t=0;t<e.length-1;t++){const e=this.benfordNumber(0,i);n[t]=n[t]+e,r+=e,i-=e}for(const t of this.outputs)!0===t.change&&(t.satoshis=n.shift());return r}distributeEqualChange(t,e){let r=0;const i=Math.floor(t/e.length);for(const t of e)r+=i,t.satoshis=i;return r}benfordNumber(t,e){const r=Math.floor(9*Math.random())+1;return Math.floor(t+(e-t)*Math.log10(1+1/r)/Math.log10(10))}getFee(){let t=0;for(const e of this.inputs){if("object"!=typeof e.sourceTransaction)throw new Error("Source transactions or sourceSatoshis are required for all inputs to calculate fee");t+=e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0}let e=0;for(const t of this.outputs)e+=t.satoshis??0;return t-e}async sign(){this.cachedHash=void 0;for(const t of this.outputs)if(void 0===t.satoshis)throw!0===t.change?new Error("There are still change outputs with uncomputed amounts. Use the fee() method to compute the change amounts and transaction fees prior to signing."):new Error("One or more transaction outputs is missing an amount. Ensure all output amounts are provided before signing.");const t=await Promise.all(this.inputs.map((async(t,e)=>"object"==typeof this.inputs[e].unlockingScriptTemplate?await(this.inputs[e]?.unlockingScriptTemplate?.sign(this,e)):await Promise.resolve(void 0))));for(let e=0,r=this.inputs.length;e<r;e++)"object"==typeof this.inputs[e].unlockingScriptTemplate&&(this.inputs[e].unlockingScript=t[e])}async broadcast(t=je()){return await t.broadcast(this)}toBinary(){const t=new Bt;t.writeUInt32LE(this.version),t.writeVarIntNum(this.inputs.length);for(const e of this.inputs){if(void 0===e.sourceTXID){if(null==e.sourceTransaction)throw new Error("sourceTransaction is undefined");t.write(e.sourceTransaction.hash())}else t.writeReverse(Ot(e.sourceTXID,"hex"));if(t.writeUInt32LE(e.sourceOutputIndex),null==e.unlockingScript)throw new Error("unlockingScript is undefined");const r=e.unlockingScript.toBinary();t.writeVarIntNum(r.length),t.write(r),t.writeUInt32LE(e.sequence??0)}t.writeVarIntNum(this.outputs.length);for(const e of this.outputs){t.writeUInt64LE(e.satoshis??0);const r=e.lockingScript.toBinary();t.writeVarIntNum(r.length),t.write(r)}return t.writeUInt32LE(this.lockTime),t.toArray()}toEF(){const t=new Bt;t.writeUInt32LE(this.version),t.write([0,0,0,0,0,239]),t.writeVarIntNum(this.inputs.length);for(const e of this.inputs){if(void 0===e.sourceTransaction)throw new Error("All inputs must have source transactions when serializing to EF format");if(void 0===e.sourceTXID?t.write(e.sourceTransaction.hash()):t.write(Ot(e.sourceTXID,"hex").reverse()),t.writeUInt32LE(e.sourceOutputIndex),null==e.unlockingScript)throw new Error("unlockingScript is undefined");const r=e.unlockingScript.toBinary();t.writeVarIntNum(r.length),t.write(r),t.writeUInt32LE(e.sequence??0),t.writeUInt64LE(e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0);const i=e.sourceTransaction.outputs[e.sourceOutputIndex].lockingScript.toBinary();t.writeVarIntNum(i.length),t.write(i)}t.writeVarIntNum(this.outputs.length);for(const e of this.outputs){t.writeUInt64LE(e.satoshis??0);const r=e.lockingScript.toBinary();t.writeVarIntNum(r.length),t.write(r)}return t.writeUInt32LE(this.lockTime),t.toArray()}toHexEF(){return Nt(this.toEF())}toHex(){return Nt(this.toBinary())}toHexBEEF(){return Nt(this.toBEEF())}toHexAtomicBEEF(){return Nt(this.toAtomicBEEF())}hash(t){let e;return null!=this.cachedHash?e=this.cachedHash:(e=vt(this.toBinary()),this.cachedHash=e),"hex"===t?Nt(e):e}id(t){const e=[...this.hash()];return e.reverse(),"hex"===t?Nt(e):e}async verify(t=Xe(),e,r){const i=new Set,n=[this];for(;n.length>0;){const s=n.shift(),a=s?.id("hex")??"";if(null!=a&&""!==a&&i.has(a))continue;if("object"==typeof s?.merklePath){if("scripts only"===t){null!=a&&i.add(a);continue}if(await s.merklePath.verify(a,t)){i.add(a);continue}}if(void 0!==e){if(void 0===s)throw new Error("Transaction is undefined");const t=ir.fromEF(s.toEF());if(delete t.outputs[0].satoshis,t.outputs[0].change=!0,await t.fee(e),s.getFee()<t.getFee())throw new Error(`Verification failed because the transaction ${a} has an insufficient fee and has not been mined.`)}let o=0;if(void 0===s)throw new Error("Transaction is undefined");for(let t=0;t<s.inputs.length;t++){const e=s.inputs[t];if("object"!=typeof e.sourceTransaction)throw new Error(`Verification failed because the input at index ${t} 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 e.unlockingScript)throw new Error(`Verification failed because the input at index ${t} 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.`);const c=e.sourceTransaction.outputs[e.sourceOutputIndex];o+=c.satoshis??0;const h=e.sourceTransaction.id("hex");i.has(h)||n.push(e.sourceTransaction);const u=s.inputs.filter(((e,r)=>r!==t));if(void 0===e.sourceTXID&&(e.sourceTXID=h),!new Re({sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,lockingScript:c.lockingScript,sourceSatoshis:c.satoshis??0,transactionVersion:s.version,otherInputs:u,unlockingScript:e.unlockingScript,inputSequence:e.sequence??0,inputIndex:t,outputs:s.outputs,lockTime:s.lockTime,memoryLimit:r}).validate())return!1}let c=0;for(const t of s.outputs){if("number"!=typeof t.satoshis)throw new Error("Every output must have a defined amount during transaction verification.");c+=t.satoshis}if(c>o)return!1;i.add(a)}return!0}toBEEF(t){const e=new Bt;e.writeUInt32LE(Ze);const r=[],i=[],n=e=>{const s={tx:e},a="object"==typeof e.merklePath;if(a){let t=!1;for(let i=0;i<r.length;i++){if(r[i]===e.merklePath){s.pathIndex=i,t=!0;break}if(null!==e.merklePath&&void 0!==e.merklePath&&r[i].blockHeight===e.merklePath.blockHeight&&r[i].computeRoot()===e.merklePath.computeRoot()){r[i].combine(e.merklePath),s.pathIndex=i,t=!0;break}}t||(s.pathIndex=r.length,null!==e.merklePath&&void 0!==e.merklePath&&r.push(e.merklePath))}if(i.some((t=>t.tx.id("hex")===e.id("hex")))||i.unshift(s),!a)for(let r=0;r<e.inputs.length;r++){const i=e.inputs[r];if("object"==typeof i.sourceTransaction)n(i.sourceTransaction);else if(!1===t)throw new Error("A required source transaction is missing!")}};n(this),e.writeVarIntNum(r.length);for(const t of r)e.write(t.toBinary());e.writeVarIntNum(i.length);for(const t of i)e.write(t.tx.toBinary()),"number"==typeof t.pathIndex?(e.writeUInt8(1),e.writeVarIntNum(t.pathIndex)):e.writeUInt8(0);return e.toArray()}toAtomicBEEF(t){const e=new Bt;e.writeUInt32LE(16843009),e.write(this.hash());const r=this.toBEEF(t);return e.write(r),e.toArray()}}function nr(t){return"success"===t.status}function sr(t){return"error"===t.status}const ar=class extends rr{knownTo={};constructor(t){if(super(),null!=t)for(const e of t)this.addParty(e)}isParty(t){return Object.keys(this.knownTo).includes(t)}addParty(t){if(this.isParty(t))throw new Error(`Party ${t} already exists.`);this.knownTo[t]={}}getKnownTxidsForParty(t){const e=this.knownTo[t];if(void 0===e)throw new Error(`Party ${t} is unknown.`);return Object.keys(e)}getTrimmedBeefForParty(t){const e=this.getKnownTxidsForParty(t),r=this.clone();return r.trimKnownTxids(e),r}addKnownTxidsForParty(t,e){this.isParty(t)||this.addParty(t);const r=this.knownTo[t];for(const t of e)r[t]=!0,this.mergeTxidOnly(t)}mergeBeefFromParty(t,e){const r=Array.isArray(e)?rr.fromBinary(e):e,i=r.getValidTxids();this.mergeBeef(r),this.addKnownTxidsForParty(t,i)}};class or{network;URL;httpClient;constructor(t="main",e=Le()){this.network=t,this.URL=`https://api.whatsonchain.com/v1/bsv/${t}/tx/raw`,this.httpClient=e}async broadcast(t){const e={method:"POST",headers:{"Content-Type":"application/json",Accept:"text/plain"},data:{txhex:t.toHex()}};try{const t=await this.httpClient.request(this.URL,e);return t.ok?{status:"success",txid:t.data,message:"broadcast successful"}:{status:"error",code:t.status.toString()??"ERR_UNKNOWN",description:t.data??"Unknown error"}}catch(t){return{status:"error",code:"500",description:"string"==typeof t.message?t.message:"Internal Server Error"}}}}const cr="42423301",hr=(t,e,r)=>{const i="object"!=typeof r;if(i){const t=new Lt,e=new re(1),i=t.g.mul(e);r=new Gt(i.x,i.y)}const n=Zt(32),s=`2-message signing-${_t(n)}`,a=e.deriveChild(r,s).sign(t).toDER(),o=e.toPublicKey().encode(!0);return[...Ot(cr,"hex"),...o,...i?[0]:r.encode(!0),...n,...a]},ur=(t,e,r)=>{const i=new Ut(e),n=Nt(i.read(4));if(n!==cr)throw new Error(`Message version mismatch: Expected ${cr}, received ${n}`);const s=Gt.fromString(Nt(i.read(33))),[a]=i.read(1);if(0===a)r=new re(1);else{const t=i.read(32),e=Nt([a,...t]);if("object"!=typeof r)throw new Error(`This signature can only be verified with knowledge of a specific private key. The associated public key is: ${e}`);const n=r.toPublicKey().encode(!0,"hex");if(e!==n)throw new Error(`The recipient public key is ${n} but the signature requres the recipient to have public key ${e}`)}const o=_t(i.read(32)),c=Nt(i.read(i.bin.length-i.pos)),h=$t.fromDER(c,"hex"),u=`2-message signing-${o}`;return s.deriveChild(r,u).verify(t,h)},lr="42421033",dr=(t,e,r)=>{const i=Zt(32),n=`2-message encryption-${_t(i)}`,s=e.deriveChild(r,n),a=r.deriveChild(e,n),o=s.deriveSharedSecret(a),c=new Pe(o.encode(!0).slice(1)).encrypt(t),h=e.toPublicKey().encode(!0);return[...Ot(lr,"hex"),...h,...r.encode(!0),...i,...c]},fr=(t,e)=>{const r=new Ut(t),i=Nt(r.read(4));if(i!==lr)throw new Error(`Message version mismatch: Expected ${lr}, received ${i}`);const n=Gt.fromString(Nt(r.read(33))),s=Nt(r.read(33)),a=e.toPublicKey().encode(!0,"hex");if(s!==a)throw new Error(`The encrypted message expects a recipient public key of ${s}, but the provided key is ${a}`);const o=_t(r.read(32)),c=r.read(r.bin.length-r.pos),h=`2-message encryption-${o}`,u=n.deriveChild(e,h),l=e.deriveChild(n,h),d=u.deriveSharedSecret(l);return new Pe(d.encode(!0).slice(1)).decrypt(c)},pr=t=>{const e=new Bt;e.writeVarIntNum(24),e.write(Ot("Bitcoin Signed Message:\n","utf8")),e.writeVarIntNum(t.length),e.write(t);const r=e.toArray();return vt(r)},mr=(t,e,r="base64")=>{const i=pr(t),n=Wt(new h(i),e,!0);if("raw"===r)return n;const s=new h(i),a=n.CalculateRecoveryFactor(e.toPublicKey(),s);return n.toCompact(a,!0,"base64")},wr=(t,e,r)=>{const i=pr(t);return Xt(new h(i),e,r)};class br{versionBytesNum;depth;parentFingerPrint;childIndex;chainCode;privKey;pubKey;constants={pubKey:76067358,privKey:76066276};constructor(t,e,r,i,n,s,a){this.versionBytesNum=t,this.depth=e,this.parentFingerPrint=r,this.childIndex=i,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=Zt(32),this.privKey=re.fromRandom(),this.pubKey=this.privKey.toPublicKey(),this}static fromRandom(){return(new this).fromRandom()}static fromString(t){return(new this).fromString(t)}fromString(t){const e=Dt(t);return this.fromBinary([...e.prefix,...e.data])}static fromSeed(t){return(new this).fromSeed(t)}fromSeed(t){if(t.length<16)throw new Error("Need more than 128 bits of entropy");if(t.length>64)throw new Error("More than 512 bits of entropy is nonstandard");const e=Pt(Ot("Bitcoin seed","utf8"),t);return this.depth=0,this.parentFingerPrint=[0,0,0,0],this.childIndex=0,this.chainCode=e.slice(32,64),this.versionBytesNum=this.constants.privKey,this.privKey=new re(e.slice(0,32)),this.pubKey=this.privKey.toPublicKey(),this}static fromBinary(t){return(new this).fromBinary(t)}fromBinary(t){if(78!==t.length)throw new Error("incorrect bip32 data length");const e=new Ut(t);this.versionBytesNum=e.readUInt32BE(),this.depth=e.readUInt8(),this.parentFingerPrint=e.read(4),this.childIndex=e.readUInt32BE(),this.chainCode=e.read(32);const r=e.read(33),i=this.versionBytesNum===this.constants.privKey,n=this.versionBytesNum===this.constants.pubKey;if(i&&0===r[0])this.privKey=new re(r.slice(1,33)),this.pubKey=this.privKey.toPublicKey();else{if(!n||2!==r[0]&&3!==r[0])throw new Error("Invalid key");this.pubKey=Gt.fromString(Nt(r))}return this}toString(){const t=this.toBinary();return Vt(t,[])}derive(t){if("m"===t)return this;const e=t.split("/");let r=this;for(const[t,i]of e.entries()){if(0===t){if("m"!==i)throw new Error("invalid path");continue}if(parseInt(i.replace("'",""),10).toString()!==i.replace("'",""))throw new Error("invalid path");const e=i.length>1&&"'"===i[i.length-1];let n=2147483647&parseInt(e?i.slice(0,i.length-1):i,10);e&&(n+=2147483648),r=r.deriveChild(n)}return r}deriveChild(t){if("number"!=typeof t)throw new Error("i must be a number");const e=[];e.push(t>>24&255),e.push(t>>16&255),e.push(t>>8&255),e.push(255&t);const r=[...e],i=!!(2147483648&t),n=this.versionBytesNum===this.constants.privKey;if(i&&(null===this.privKey||void 0===this.privKey||!n))throw new Error("Cannot do private key derivation without private key");let s=null;if(null!==this.privKey&&void 0!==this.privKey){let t=null;t=i?[0,...this.privKey.toArray("be",32),...r]:[...this.pubKey.encode(!0),...r];const e=Pt(this.chainCode,t),n=new h(e.slice(0,32)),a=e.slice(32,64),o=n.add(this.privKey).mod((new Lt).n);s=new br,s.chainCode=a,s.privKey=new re(o.toArray()),s.pubKey=s.privKey.toPublicKey()}else{const t=[...this.pubKey.encode(!0),...r],e=Pt(this.chainCode,t),i=new h(e.slice(0,32)),n=e.slice(32,64),a=(new Lt).g.mul(i),o=this.pubKey,c=a.add(o),u=new Gt(c.x,c.y);s=new br,s.chainCode=n,s.pubKey=u}s.childIndex=t;const a=It(this.pubKey.encode(!0));return s.parentFingerPrint=a.slice(0,4),s.versionBytesNum=this.versionBytesNum,s.depth=this.depth+1,s}toPublic(){const t=new br(this.versionBytesNum,this.depth,this.parentFingerPrint,this.childIndex,this.chainCode,this.privKey,this.pubKey);return t.versionBytesNum=this.constants.pubKey,t.privKey=void 0,t}toBinary(){const t=this.versionBytesNum===this.constants.privKey,e=this.versionBytesNum===this.constants.pubKey;if(t)return(new Bt).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(e)return(new Bt).writeUInt32BE(this.versionBytesNum).writeUInt8(this.depth).write(this.parentFingerPrint).writeUInt32BE(this.childIndex).write(this.chainCode).write(this.pubKey.encode(!0)).toArray();throw new Error("bip32: invalid versionBytesNum byte")}isPrivate(){return this.versionBytesNum===this.constants.privKey}}const gr={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 yr{mnemonic;seed;Wordlist;constructor(t,e,r=gr){this.mnemonic=t??"",this.seed=e??[],this.Wordlist=r}toBinary(){const t=new Bt;if(""!==this.mnemonic){const e=Ot(this.mnemonic,"utf8");t.writeVarIntNum(e.length),t.write(e)}else t.writeVarIntNum(0);return this.seed.length>0?(t.writeVarIntNum(this.seed.length),t.write(this.seed)):t.writeVarIntNum(0),t.toArray()}fromBinary(t){const e=new Ut(t),r=e.readVarIntNum();r>0&&(this.mnemonic=Mt(e.read(r),"utf8"));const i=e.readVarIntNum();return i>0&&(this.seed=e.read(i)),this}fromRandom(t){if((null==t||isNaN(t)||0===t)&&(t=128),t%32!=0)throw new Error("bits must be multiple of 32");if(t<128)throw new Error("bits must be at least 128");const e=Zt(t/8);return this.entropy2Mnemonic(e),this.mnemonic2Seed(),this}static fromRandom(t){return(new this).fromRandom(t)}fromEntropy(t){return this.entropy2Mnemonic(t),this}static fromEntropy(t){return(new this).fromEntropy(t)}fromString(t){return this.mnemonic=t,this}static fromString(t){return(new this).fromString(t)}toString(){return this.mnemonic}toSeed(t){return this.mnemonic2Seed(t),this.seed}entropy2Mnemonic(t){if(t.length<16)throw new Error("Entropy is less than 128 bits. It must be 128 bits or more.");const e=gt(t);let r="";const i=8*t.length;for(let e=0;e<t.length;e++)r+=("00000000"+t[e].toString(2)).slice(-8);let n=e[0].toString(2);if(n=("00000000"+n).slice(-8).slice(0,i/32),r+=n,r.length%11!=0)throw new Error("internal error - entropy not an even multiple of 11 bits - "+r.length.toString());let s="";for(let t=0;t<r.length/11;t++){""!==s&&(s+=this.Wordlist.space);const e=parseInt(r.slice(11*t,11*(t+1)),2);s+=this.Wordlist.value[e]}return this.mnemonic=s,this}check(){const t=this.mnemonic.split(this.Wordlist.space);let e="";for(let r=0;r<t.length;r++){const i=this.Wordlist.value.indexOf(t[r]);if(i<0)return!1;e+=("00000000000"+i.toString(2)).slice(-11)}if(e.length%11!=0)throw new Error("internal error - entropy not an even multiple of 11 bits - "+e.length.toString());const r=e.length/33,i=e.slice(-r),n=e.slice(0,e.length-r),s=[];for(let t=0;t<n.length/8;t++)s.push(parseInt(e.slice(8*t,8*(t+1)),2));let a=gt(s.slice(0,n.length/8))[0].toString(2);return a=("00000000"+a).slice(-8).slice(0,r),a===i}mnemonic2Seed(t=""){let e=this.mnemonic;if(!this.check())throw new Error("Mnemonic does not pass the check - was the mnemonic typed incorrectly? Are there extra spaces?");if("string"!=typeof t)throw new Error("passphrase must be a string or undefined");e=e.normalize("NFKD"),t=t.normalize("NFKD");const r=Ot(e,"utf8"),i=[...Ot("mnemonic","utf8"),...Ot(t,"utf8")];return this.seed=Et(r,i,2048,64,"sha512"),this}isValid(t=""){let e;try{this.mnemonic2Seed(t),e=!0}catch{e=!1}return e}static isValid(t,e=""){return new yr(t).isValid(e)}}function vr(t){let e,r,i;0===this._tables[0][0][0]&&this._precompute();const n=this._tables[0][4],s=this._tables[1],a=t.length;let o,c=1;if(4!==a&&6!==a&&8!==a)throw new Error("invalid aes key size");for(this._key=[r=t.slice(0),i=[]],o=a;o<4*a+28;o++)e=r[o-1],(o%a==0||8===a&&o%a==4)&&(e=n[e>>>24]<<24^n[e>>16&255]<<16^n[e>>8&255]<<8^n[255&e],o%a==0&&(e=e<<8^e>>>24^c<<24,c=c<<1^283*(c>>7))),r[o]=r[o-a]^e;for(let t=0;o>0;t++,o--)e=r[3&t?o:o-4],i[t]=o<=4||t<4?e:s[0][n[e>>>24]]^s[1][n[e>>16&255]]^s[2][n[e>>8&255]]^s[3][n[255&e]]}vr.prototype={encrypt:function(t){return this._crypt(t,0)},decrypt:function(t){return this._crypt(t,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(){const t=this._tables[0],e=this._tables[1],r=t[4],i=e[4];let n,s,a;const o=new Uint8Array(256),c=new Uint8Array(256);let h,u,l,d,f,p;for(n=0;n<256;n++)c[(o[n]=n<<1^283*(n>>7))^n]=n;for(s=a=0;0===r[s];s^=0!==h?h:1,a=0!==c[a]?c[a]:1)for(d=a^a<<1^a<<2^a<<3^a<<4,d=d>>8^255&d^99,r[s]=d,i[d]=s,l=o[u=o[h=o[s]]],p=16843009*l^65537*u^257*h^16843008*s,f=257*o[d]^16843008*d,n=0;n<4;n++)t[n][s]=f=f<<24^f>>>8,e[n][d]=p=p<<24^p>>>8},_crypt:function(t,e){if(4!==t.length)throw new Error("invalid aes block size");const r=this._key[e];let i,n,s,a=t[0]^r[0],o=t[1===e?3:1]^r[1],c=t[2]^r[2],h=t[1===e?1:3]^r[3];const u=r.length/4-2;let l,d=4;const f=new Uint32Array(4),p=this._tables[e],m=p[0],w=p[1],b=p[2],g=p[3],y=p[4];for(l=0;l<u;l++)i=m[a>>>24]^w[o>>16&255]^b[c>>8&255]^g[255&h]^r[d],n=m[o>>>24]^w[c>>16&255]^b[h>>8&255]^g[255&a]^r[d+1],s=m[c>>>24]^w[h>>16&255]^b[a>>8&255]^g[255&o]^r[d+2],h=m[h>>>24]^w[a>>16&255]^b[o>>8&255]^g[255&c]^r[d+3],d+=4,a=i,o=n,c=s;for(l=0;l<4;l++)f[1===e?3&-l:l]=y[a>>>24]<<24^y[o>>16&255]<<16^y[c>>8&255]<<8^y[255&h]^r[d++],i=a,a=o,o=c,c=h,h=i;return f}};class Ir{static encrypt(t,e){const r=Ir.buf2Words(e),i=Ir.buf2Words(t),n=new vr(r).encrypt(i);return Ir.words2Buf(n)}static decrypt(t,e){const r=Ir.buf2Words(t),i=new vr(Ir.buf2Words(e)).decrypt(r);return Ir.words2Buf(i)}static buf2Words(t){if(t.length%4!=0)throw new Error("buf length must be a multiple of 4");const e=[];for(let r=0;r<t.length/4;r++){const i=16777216*t[4*r]+(t[4*r+1]<<16|t[4*r+2]<<8|t[4*r+3]);e.push(i)}return e}static words2Buf(t){const e=new Array(4*t.length);for(let r=0;r<t.length;r++){const i=t[r];e[4*r]=i>>>24&255,e[4*r+1]=i>>>16&255,e[4*r+2]=i>>>8&255,e[4*r+3]=255&i}return e}}class kr{static buf2BlocksBuf(t,e){const r=e/8,i=[];for(let n=0;n<=t.length/r;n++){let s=t.slice(n*r,n*r+r);s.length<e&&(s=kr.pkcs7Pad(s,e)),i.push(s)}return i}static blockBufs2Buf(t){let e=t[t.length-1];return e=kr.pkcs7Unpad(e),t[t.length-1]=e,t.flat()}static encrypt(t,e,r,i){const n=8*e.length,s=kr.buf2BlocksBuf(t,n);return kr.encryptBlocks(s,e,r,i).flat()}static decrypt(t,e,r,i){const n=e.length,s=[];for(let e=0;e<t.length/n;e++)s.push(t.slice(e*n,e*n+n));const a=kr.decryptBlocks(s,e,r,i);return kr.blockBufs2Buf(a)}static encryptBlock(t,e,r,i){const n=kr.xorBufs(t,e);return r.encrypt(n,i)}static decryptBlock(t,e,r,i){const n=r.decrypt(t,i);return kr.xorBufs(n,e)}static encryptBlocks(t,e,r,i){const n=[];for(let s=0;s<t.length;s++){const a=t[s],o=kr.encryptBlock(a,e,r,i);n.push(o),e=o}return n}static decryptBlocks(t,e,r,i){const n=[];for(let s=0;s<t.length;s++){const a=t[s],o=kr.decryptBlock(a,e,r,i);n.push(o),e=a}return n}static pkcs7Pad(t,e){const r=e/8-t.length,i=new Array(r);return i.fill(r),[...t,...i]}static pkcs7Unpad(t){const e=t[t.length-1],r=t.slice(t.length-e,t.length),i=new Array(e);if(i.fill(e),Nt(r)!==Nt(i))throw new Error("invalid padding");return t.slice(0,t.length-e)}static xorBufs(t,e){if(t.length!==e.length)throw new Error("bufs must have the same length");const r=new Array(t.length);for(let i=0;i<t.length;i++)r[i]=t[i]^e[i];return r}}class Pr{static encrypt(t,e,r,i=!0){r=r??Zt(16);const n=kr.encrypt(t,r,Ir,e);return i?[...r,...n]:[...n]}static decrypt(t,e,r){if(null==r){r=t.slice(0,16);const i=t.slice(16);return kr.decrypt(i,r,Ir,e)}{const i=t;return kr.decrypt(i,r,Ir,e)}}}class Er{static ivkEkM(t,e){const r=t,i=e.mul(r),n=new Gt(i.x,i.y).encode(!0),s=yt(n);return{iv:s.slice(0,16),kE:s.slice(16,32),kM:s.slice(32,64)}}static electrumEncrypt(t,e,r,i=!1){let n=null;null==r&&(r=re.fromRandom()),i||(n=r.toPublicKey().encode(!0));const{iv:s,kE:a,kM:o}=Er.ivkEkM(r,e),c=Pr.encrypt(t,a,s,!1),h=Ot("BIE1","utf8");let u;u=null!=n&&n.length>0?[...h,...n,...c]:[...h,...c];const l=kt(o,u);return[...u,...l]}static electrumDecrypt(t,e,r){const i=t.slice(0,4);if("BIE1"!==Mt(i,"utf8"))throw new Error("Invalid Magic");let n=4,s=null;if(t.length-n-32>=33){const e=t[n];2===e||3===e?(s=t.slice(n,n+33),n+=33):4===e&&(s=t.slice(n,n+65),n+=65)}if(null!==s)null==r&&(r=Gt.fromString(Nt(s)));else if(null==r)throw new Error("Sender public key is required");const{iv:a,kE:o,kM:c}=Er.ivkEkM(e,r),h=t.slice(n,t.length-32),u=t.slice(t.length-32,t.length),l=kt(c,t.slice(0,t.length-32));if(Nt(u)!==Nt(l))throw new Error("Invalid checksum");return Pr.decrypt(h,o,a)}static bitcoreEncrypt(t,e,r,i){null==r&&(r=re.fromRandom()),null==i&&(i=Zt(16));const n=r,s=r.toPublicKey().encode(!0),a=e.mul(n).getX().toArray("be",32),o=yt(a),c=o.slice(0,32),h=o.slice(32,64),u=Pr.encrypt(t,c,i),l=kt(h,[...u]);return[...s,...u,...l]}static bitcoreDecrypt(t,e){const r=e,i=Gt.fromString(Nt(t.slice(0,33))).mul(r);if(i.eq(new Kt(0,0)))throw new Error("P equals 0");const n=i.getX().toArray("be",32),s=yt(n),a=s.slice(0,32),o=s.slice(32,64),c=t.slice(33,t.length-32),h=t.slice(t.length-32,t.length),u=kt(o,c);if(Nt(h)!==Nt(u))throw new Error("Invalid checksum");return[...Pr.decrypt(c,a)]}}function Sr(t,e){const r=new ir(0,[],[],0);return r.outputs=Array(t.vout+1).fill(null),r.outputs[t.vout]={satoshis:t.satoshis,lockingScript:Ae.fromHex(t.script)},{sourceTransaction:r,sourceTXID:t.txid,sourceOutputIndex:t.vout,unlockingScriptTemplate:e,sequence:4294967295}}class Nr{static generate(t,e){const r=this.withDefaultOptions(e);return Or(t,this.getCounter(r.timestamp,r.period),r)}static validate(t,e,r){const i=this.withDefaultValidateOptions(r);if((e=e.trim()).length!==i.digits)return!1;const n=this.getCounter(i.timestamp,i.period),s=[n];for(let t=1;t<=i.skew;t++)s.push(n+t),s.push(n-t);for(const r of s)if(e===Or(t,r,i))return!0;return!1}static getCounter(t,e){const r=Math.floor(t/1e3);return Math.floor(r/e)}static withDefaultOptions(t){return{digits:2,algorithm:"SHA-1",period:30,timestamp:Date.now(),...t}}static withDefaultValidateOptions(t){return{skew:1,...this.withDefaultOptions(t)}}}function Or(t,e,r){const i=function(t,e,r){switch(r){case"SHA-1":return new pt(t).update(e);case"SHA-256":return new ft(t).update(e);case"SHA-512":return new mt(t).update(e);default:throw new Error("unsupported HMAC algorithm")}}(t,new h(e).toArray("be",8),r.algorithm),n=i.digest(),s=15&n[n.length-1],a=n.slice(s,s+4);return(2147483647&new h(a).toNumber()).toString().slice(-r.digits)}var xr;!function(t){t[t.Silent=0]="Silent",t[t.App=1]="App",t[t.Counterparty=2]="Counterparty"}(xr||(xr={}));class Ar{rootKey;identityKey;constructor(t){this.rootKey="anyone"===t?new re(1):t,this.identityKey=this.rootKey.toPublicKey().toString()}derivePublicKey(t,e,r,i=!1){return r=this.normalizeCounterparty(r),i?this.rootKey.deriveChild(r,this.computeInvoiceNumber(t,e)).toPublicKey():r.deriveChild(this.rootKey,this.computeInvoiceNumber(t,e))}derivePrivateKey(t,e,r){return r=this.normalizeCounterparty(r),this.rootKey.deriveChild(r,this.computeInvoiceNumber(t,e))}deriveSymmetricKey(t,e,r){"anyone"===r&&(r=new re(1).toPublicKey()),r=this.normalizeCounterparty(r);const i=this.derivePublicKey(t,e,r),n=this.derivePrivateKey(t,e,r);return new Pe(n.deriveSharedSecret(i)?.x?.toArray()??[])}revealCounterpartySecret(t){if("self"===t)throw new Error("Counterparty secrets cannot be revealed for counterparty=self.");t=this.normalizeCounterparty(t);const e=this.rootKey.toPublicKey();if(this.rootKey.deriveChild(e,"test").toHex()===this.rootKey.deriveChild(t,"test").toHex())throw new Error("Counterparty secrets cannot be revealed for counterparty=self.");return this.rootKey.deriveSharedSecret(t).encode(!0)}revealSpecificSecret(t,e,r){t=this.normalizeCounterparty(t);const i=this.rootKey.deriveSharedSecret(t),n=Ot(this.computeInvoiceNumber(e,r),"utf8");return kt(i.encode(!0),n)}normalizeCounterparty(t){if(null==t)throw new Error("counterparty must be self, anyone or a public key!");return"self"===t?this.rootKey.toPublicKey():"anyone"===t?new re(1).toPublicKey():"string"==typeof t?Gt.fromString(t):t}computeInvoiceNumber(t,e){const r=t[0];if(!Number.isInteger(r)||r<0||r>2)throw new Error("Protocol security level must be 0, 1, or 2");const i=t[1].toLowerCase().trim();if(e.length>800)throw new Error("Key IDs must be 800 characters or less");if(e.length<1)throw new Error("Key IDs must be 1 character or more");if(i.length>400){if(!i.startsWith("specific linkage revelation "))throw new Error("Protocol names must be 400 characters or less");if(i.length>430)throw new Error("Specific linkage revelation protocol names must be 430 characters or less")}if(i.length<5)throw new Error("Protocol names must be 5 characters or more");if(i.includes(" "))throw new Error('Protocol names cannot contain multiple consecutive spaces (" ")');if(!/^[a-z0-9 ]+$/g.test(i))throw new Error("Protocol names can only contain letters, numbers and spaces");if(i.endsWith(" protocol"))throw new Error('No need to end your protocol name with " protocol"');return`${r}-${i}-${e}`}}class Tr{keyDeriver;cache;maxCacheSize;constructor(t,e){this.keyDeriver=new Ar(t),this.cache=new Map;const r=e?.maxCacheSize;this.maxCacheSize=null!=r&&!isNaN(r)&&r>0?r:1e3}derivePublicKey(t,e,r,i=!1){const n=this.generateCacheKey("derivePublicKey",t,e,r,i);if(this.cache.has(n)){const t=this.cacheGet(n);if(void 0===t)throw new Error("Cached value is undefined");return t}{const s=this.keyDeriver.derivePublicKey(t,e,r,i);return this.cacheSet(n,s),s}}derivePrivateKey(t,e,r){const i=this.generateCacheKey("derivePrivateKey",t,e,r);if(this.cache.has(i)){const t=this.cacheGet(i);if(void 0===t)throw new Error("Cached value is undefined");return t}{const n=this.keyDeriver.derivePrivateKey(t,e,r);return this.cacheSet(i,n),n}}deriveSymmetricKey(t,e,r){const i=this.generateCacheKey("deriveSymmetricKey",t,e,r);if(this.cache.has(i)){const t=this.cacheGet(i);if(void 0===t)throw new Error("Cached value is undefined");return t}{const n=this.keyDeriver.deriveSymmetricKey(t,e,r);return this.cacheSet(i,n),n}}revealCounterpartySecret(t){const e=this.generateCacheKey("revealCounterpartySecret",t);if(this.cache.has(e)){const t=this.cacheGet(e);if(void 0===t)throw new Error("Cached value is undefined");return t}{const r=this.keyDeriver.revealCounterpartySecret(t);return this.cacheSet(e,r),r}}revealSpecificSecret(t,e,r){const i=this.generateCacheKey("revealSpecificSecret",t,e,r);if(this.cache.has(i)){const t=this.cacheGet(i);if(void 0===t)throw new Error("Cached value is undefined");return t}{const n=this.keyDeriver.revealSpecificSecret(t,e,r);return this.cacheSet(i,n),n}}generateCacheKey(t,...e){return`${t}|${e.map((t=>this.serializeArgument(t))).join("|")}`}serializeArgument(t){return t instanceof Gt||t instanceof re?t.toString():Array.isArray(t)?t.map((t=>this.serializeArgument(t))).join(","):"object"==typeof t&&null!==t?JSON.stringify(t):String(t)}cacheGet(t){const e=this.cache.get(t);return this.cache.delete(t),void 0!==e&&this.cache.set(t,e),e}cacheSet(t,e){if(this.cache.size>=this.maxCacheSize){const t=this.cache.keys().next().value;this.cache.delete(t)}this.cache.set(t,e)}}const Mr=class{keyDeriver;constructor(t){"string"!=typeof t.identityKey&&(t=new Ar(t)),this.keyDeriver=t}async getPublicKey(t){if(t.identityKey){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==t.protocolID||null==t.keyID||""===t.keyID)throw new Error("protocolID and keyID are required if identityKey is false or undefined.");return{publicKey:(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePublicKey(t.protocolID,t.keyID,t.counterparty??"self",t.forSelf).toString()}}async revealCounterpartyKeyLinkage(t){const{publicKey:e}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const r=this.keyDeriver.revealCounterpartySecret(t.counterparty),i=(new Se).generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),Gt.fromString(t.counterparty),Kt.fromDER(r)),n=[...i.R.encode(!0),...i.SPrime.encode(!0),...i.z.toArray()],s=(new Date).toISOString(),{ciphertext:a}=await this.encrypt({plaintext:r,protocolID:[2,"counterparty linkage revelation"],keyID:s,counterparty:t.verifier}),{ciphertext:o}=await this.encrypt({plaintext:n,protocolID:[2,"counterparty linkage revelation"],keyID:s,counterparty:t.verifier});return{prover:e,verifier:t.verifier,counterparty:t.counterparty,revelationTime:s,encryptedLinkage:a,encryptedLinkageProof:o}}async revealSpecificKeyLinkage(t){const{publicKey:e}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const r=this.keyDeriver.revealSpecificSecret(t.counterparty,t.protocolID,t.keyID),{ciphertext:i}=await this.encrypt({plaintext:r,protocolID:[2,`specific linkage revelation ${t.protocolID[0]} ${t.protocolID[1]}`],keyID:t.keyID,counterparty:t.verifier}),{ciphertext:n}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${t.protocolID[0]} ${t.protocolID[1]}`],keyID:t.keyID,counterparty:t.verifier});return{prover:e,verifier:t.verifier,counterparty:t.counterparty,protocolID:t.protocolID,keyID:t.keyID,encryptedLinkage:i,encryptedLinkageProof:n,proofType:0}}async encrypt(t){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{ciphertext:this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self").encrypt(t.plaintext)}}async decrypt(t){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{plaintext:this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self").decrypt(t.ciphertext)}}async createHmac(t){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const e=this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self");return{hmac:kt(e.toArray(),t.data)}}async verifyHmac(t){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const e=this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self"),r=kt(e.toArray(),t.data).toString()===t.hmac.toString();if(!r){const t=new Error("HMAC is not valid");throw t.code="ERR_INVALID_HMAC",t}return{valid:r}}async createSignature(t){if(null==t.hashToDirectlySign&&null==t.data)throw new Error("args.data or args.hashToDirectlySign must be valid");const e=t.hashToDirectlySign??gt(t.data??[]),r=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePrivateKey(t.protocolID,t.keyID,t.counterparty??"anyone");return{signature:Wt(new h(e),r,!0).toDER()}}async verifySignature(t){if(null==t.hashToDirectlyVerify&&null==t.data)throw new Error("args.data or args.hashToDirectlyVerify must be valid");const e=t.hashToDirectlyVerify??gt(t.data??[]),r=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePublicKey(t.protocolID,t.keyID,t.counterparty??"self",t.forSelf),i=Xt(new h(e),$t.fromDER(t.signature),r);if(!i){const t=new Error("Signature is not valid");throw t.code="ERR_INVALID_SIGNATURE",t}return{valid:i}}};class _r{CWI;constructor(){if("object"!=typeof window)throw new Error("The window.CWI substrate requires a global window object.");if("object"!=typeof window.CWI)throw new Error("The window.CWI interface does not appear to be bound to the window object.");this.CWI=window.CWI}async createAction(t,e){return await this.CWI.createAction(t,e)}async signAction(t,e){return await this.CWI.signAction(t,e)}async abortAction(t,e){return await this.CWI.abortAction(t,e)}async listActions(t,e){return await this.CWI.listActions(t,e)}async internalizeAction(t,e){return await this.CWI.internalizeAction(t,e)}async listOutputs(t,e){return await this.CWI.listOutputs(t,e)}async relinquishOutput(t,e){return await this.CWI.relinquishOutput(t,e)}async getPublicKey(t,e){return await this.CWI.getPublicKey(t,e)}async revealCounterpartyKeyLinkage(t,e){return await this.CWI.revealCounterpartyKeyLinkage(t,e)}async revealSpecificKeyLinkage(t,e){return await this.CWI.revealSpecificKeyLinkage(t,e)}async encrypt(t,e){return await this.CWI.encrypt(t,e)}async decrypt(t,e){return await this.CWI.decrypt(t,e)}async createHmac(t,e){return await this.CWI.createHmac(t,e)}async verifyHmac(t,e){return await this.CWI.verifyHmac(t,e)}async createSignature(t,e){return await this.CWI.createSignature(t,e)}async verifySignature(t,e){return await this.CWI.verifySignature(t,e)}async acquireCertificate(t,e){return await this.CWI.acquireCertificate(t,e)}async listCertificates(t,e){return await this.CWI.listCertificates(t,e)}async proveCertificate(t,e){return await this.CWI.proveCertificate(t,e)}async relinquishCertificate(t,e){return await this.CWI.relinquishCertificate(t,e)}async discoverByIdentityKey(t,e){return await this.CWI.discoverByIdentityKey(t,e)}async discoverByAttributes(t,e){return await this.CWI.discoverByAttributes(t,e)}async isAuthenticated(t,e){return await this.CWI.isAuthenticated(t,e)}async waitForAuthentication(t,e){return await this.CWI.waitForAuthentication(t,e)}async getHeight(t,e){return await this.CWI.getHeight(t,e)}async getHeaderForHeight(t,e){return await this.CWI.getHeaderForHeight(t,e)}async getNetwork(t,e){return await this.CWI.getNetwork(t,e)}async getVersion(t,e){return await this.CWI.getVersion(t,e)}}class Fr extends Error{code;isError=!0;constructor(t,e=1,r){super(t),this.code=e,this.name=this.constructor.name,null!=r&&""!==r?this.stack=r:Error.captureStackTrace(this,this.constructor)}}var Rr;!function(t){t[t.unknownError=1]="unknownError",t[t.unsupportedAction=2]="unsupportedAction",t[t.invalidHmac=3]="invalidHmac",t[t.invalidSignature=4]="invalidSignature",t[t.reviewActions=5]="reviewActions"}(Rr||(Rr={}));const Cr=Fr;class Vr{domain;constructor(t="*"){if("object"!=typeof window)throw new Error("The XDM substrate requires a global window object.");if("function"!=typeof window.postMessage)throw new Error("The window object does not seem to support postMessage calls.");this.domain=t}async invoke(t,e){return await new Promise(((r,i)=>{const n=_t(Zt(12)),s=t=>{if("CWI"===t.data.type&&t.isTrusted&&t.data.id===n&&!0!==t.data.isInvocation)if("function"==typeof window.removeEventListener&&window.removeEventListener("message",s),"error"===t.data.status){const e=new Fr(t.data.description,t.data.code);i(e)}else r(t.data.result)};window.addEventListener("message",s),window.parent.postMessage({type:"CWI",isInvocation:!0,id:n,call:t,args:e},this.domain)}))}async createAction(t){return await this.invoke("createAction",t)}async signAction(t){return await this.invoke("signAction",t)}async abortAction(t){return await this.invoke("abortAction",t)}async listActions(t){return await this.invoke("listActions",t)}async internalizeAction(t){return await this.invoke("internalizeAction",t)}async listOutputs(t){return await this.invoke("listOutputs",t)}async relinquishOutput(t){return await this.invoke("relinquishOutput",t)}async getPublicKey(t){return await this.invoke("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.invoke("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.invoke("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.invoke("encrypt",t)}async decrypt(t){return await this.invoke("decrypt",t)}async createHmac(t){return await this.invoke("createHmac",t)}async verifyHmac(t){return await this.invoke("verifyHmac",t)}async createSignature(t){return await this.invoke("createSignature",t)}async verifySignature(t){return await this.invoke("verifySignature",t)}async acquireCertificate(t){return await this.invoke("acquireCertificate",t)}async listCertificates(t){return await this.invoke("listCertificates",t)}async proveCertificate(t){return await this.invoke("proveCertificate",t)}async relinquishCertificate(t){return await this.invoke("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.invoke("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.invoke("discoverByAttributes",t)}async isAuthenticated(t){return await this.invoke("isAuthenticated",t)}async waitForAuthentication(t){return await this.invoke("waitForAuthentication",t)}async getHeight(t){return await this.invoke("getHeight",t)}async getHeaderForHeight(t){return await this.invoke("getHeaderForHeight",t)}async getNetwork(t){return await this.invoke("getNetwork",t)}async getVersion(t){return await this.invoke("getVersion",t)}}class Dr{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(t,e,r,i,n,s,a){this.type=t,this.serialNumber=e,this.subject=r,this.certifier=i,this.revocationOutpoint=n,this.fields=s,this.signature=a}toBinary(t=!0){const e=new Bt,r=Ot(this.type,"base64");e.write(r);const i=Ot(this.serialNumber,"base64");e.write(i);const n=Ot(this.subject,"hex");e.write(n);const s=Ot(this.certifier,"hex");e.write(s);const[a,o]=this.revocationOutpoint.split("."),c=Ot(a,"hex");e.write(c),e.writeVarIntNum(Number(o));const h=Object.keys(this.fields).sort();e.writeVarIntNum(h.length);for(const t of h){const r=this.fields[t],i=Ot(t,"utf8");e.writeVarIntNum(i.length),e.write(i);const n=Ot(r,"utf8");e.writeVarIntNum(n.length),e.write(n)}if(t&&(this.signature??"").length>0){const t=Ot(this.signature,"hex");e.write(t)}return e.toArray()}static fromBinary(t){const e=new Ut(t),r=_t(e.read(32)),i=_t(e.read(32)),n=e.read(33),s=Nt(n),a=e.read(33),o=Nt(a),c=e.read(32),h=`${Nt(c)}.${e.readVarIntNum()}`,u=e.readVarIntNum(),l={};for(let t=0;t<u;t++){const t=e.readVarIntNum(),r=e.read(t),i=Tt(r),n=e.readVarIntNum(),s=e.read(n),a=Tt(s);l[i]=a}let d;if(!e.eof()){const t=e.read();d=$t.fromDER(t).toString("hex")}return new Dr(r,i,s,o,h,l,d)}async verify(){const t=new Mr("anyone"),e=this.toBinary(!1),r=this.signature??"",{valid:i}=await t.verifySignature({signature:Ot(r,"hex"),data:e,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`,counterparty:this.certifier});return i}async sign(t){if(null!=this.signature&&this.signature.length>0)throw new Error(`Certificate has already been signed! Signature present: ${this.signature}`);this.certifier=(await t.getPublicKey({identityKey:!0})).publicKey;const e=this.toBinary(!1),{signature:r}=await t.createSignature({data:e,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`});this.signature=Nt(r)}static getCertificateFieldEncryptionDetails(t,e){return{protocolID:[2,"certificate field encryption"],keyID:e?`${e} ${t}`:t}}}var Br;!function(t){t[t.createAction=1]="createAction",t[t.signAction=2]="signAction",t[t.abortAction=3]="abortAction",t[t.listActions=4]="listActions",t[t.internalizeAction=5]="internalizeAction",t[t.listOutputs=6]="listOutputs",t[t.relinquishOutput=7]="relinquishOutput",t[t.getPublicKey=8]="getPublicKey",t[t.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",t[t.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",t[t.encrypt=11]="encrypt",t[t.decrypt=12]="decrypt",t[t.createHmac=13]="createHmac",t[t.verifyHmac=14]="verifyHmac",t[t.createSignature=15]="createSignature",t[t.verifySignature=16]="verifySignature",t[t.acquireCertificate=17]="acquireCertificate",t[t.listCertificates=18]="listCertificates",t[t.proveCertificate=19]="proveCertificate",t[t.relinquishCertificate=20]="relinquishCertificate",t[t.discoverByIdentityKey=21]="discoverByIdentityKey",t[t.discoverByAttributes=22]="discoverByAttributes",t[t.isAuthenticated=23]="isAuthenticated",t[t.waitForAuthentication=24]="waitForAuthentication",t[t.getHeight=25]="getHeight",t[t.getHeaderForHeight=26]="getHeaderForHeight",t[t.getNetwork=27]="getNetwork",t[t.getVersion=28]="getVersion"}(Br||(Br={}));const Ur=Br;class Hr{wire;constructor(t){this.wire=t}async transmit(t,e="",r=[]){const i=new Bt;i.writeUInt8(Ur[t]);const n=Ot(e,"utf8");i.writeUInt8(n.length),i.write(n),r.length>0&&i.write(r);const s=i.toArray(),a=await this.wire.transmitToWallet(s),o=new Ut(a),c=o.readUInt8();if(0===c)return o.read();{const t=o.readVarIntNum(),e=o.read(t),r=Tt(e),i=o.readVarIntNum(),n=o.read(i),s=Tt(n);throw new Fr(r,c,s)}}async createAction(t,e){const r=new Bt,i=Ot(t.description,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=t.inputBEEF?(r.writeVarIntNum(t.inputBEEF.length),r.write(t.inputBEEF)):r.writeVarIntNum(-1),null!=t.inputs){r.writeVarIntNum(t.inputs.length);for(const e of t.inputs){if(r.write(this.encodeOutpoint(e.outpoint)),null!=e.unlockingScript&&""!==e.unlockingScript){const t=Ot(e.unlockingScript,"hex");r.writeVarIntNum(t.length),r.write(t)}else r.writeVarIntNum(-1),r.writeVarIntNum(e.unlockingScriptLength??0);const t=Ot(e.inputDescription,"utf8");r.writeVarIntNum(t.length),r.write(t),"number"==typeof e.sequenceNumber?r.writeVarIntNum(e.sequenceNumber):r.writeVarIntNum(-1)}}else r.writeVarIntNum(-1);if(null!=t.outputs){r.writeVarIntNum(t.outputs.length);for(const e of t.outputs){const t=Ot(e.lockingScript,"hex");r.writeVarIntNum(t.length),r.write(t),r.writeVarIntNum(e.satoshis);const i=Ot(e.outputDescription,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=e.basket&&""!==e.basket){const t=Ot(e.basket,"utf8");r.writeVarIntNum(t.length),r.write(t)}else r.writeVarIntNum(-1);if(null!=e.customInstructions&&""!==e.customInstructions){const t=Ot(e.customInstructions,"utf8");r.writeVarIntNum(t.length),r.write(t)}else r.writeVarIntNum(-1);if(null!=e.tags){r.writeVarIntNum(e.tags.length);for(const t of e.tags){const e=Ot(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}}else r.writeVarIntNum(-1)}}else r.writeVarIntNum(-1);if("number"==typeof t.lockTime?r.writeVarIntNum(t.lockTime):r.writeVarIntNum(-1),"number"==typeof t.version?r.writeVarIntNum(t.version):r.writeVarIntNum(-1),null!=t.labels){r.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=Ot(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}}else r.writeVarIntNum(-1);if(null!=t.options){if(r.writeInt8(1),"boolean"==typeof t.options.signAndProcess?r.writeInt8(t.options.signAndProcess?1:0):r.writeInt8(-1),"boolean"==typeof t.options.acceptDelayedBroadcast?r.writeInt8(t.options.acceptDelayedBroadcast?1:0):r.writeInt8(-1),"known"===t.options.trustSelf?r.writeInt8(1):r.writeInt8(-1),null!=t.options.knownTxids){r.writeVarIntNum(t.options.knownTxids.length);for(const e of t.options.knownTxids){const t=Ot(e,"hex");r.write(t)}}else r.writeVarIntNum(-1);if("boolean"==typeof t.options.returnTXIDOnly?r.writeInt8(t.options.returnTXIDOnly?1:0):r.writeInt8(-1),"boolean"==typeof t.options.noSend?r.writeInt8(t.options.noSend?1:0):r.writeInt8(-1),null!=t.options.noSendChange){r.writeVarIntNum(t.options.noSendChange.length);for(const e of t.options.noSendChange)r.write(this.encodeOutpoint(e))}else r.writeVarIntNum(-1);if(null!=t.options.sendWith){r.writeVarIntNum(t.options.sendWith.length);for(const e of t.options.sendWith){const t=Ot(e,"hex");r.write(t)}}else r.writeVarIntNum(-1);"boolean"==typeof t.options.randomizeOutputs?r.writeInt8(t.options.randomizeOutputs?1:0):r.writeInt8(-1)}else r.writeInt8(0);const n=await this.transmit("createAction",e,r.toArray()),s=new Ut(n),a={};if(1===s.readInt8()){const t=s.read(32);a.txid=Nt(t)}if(1===s.readInt8()){const t=s.readVarIntNum();a.tx=s.read(t)}const o=s.readVarIntNum();if(o>=0){a.noSendChange=[];for(let t=0;t<o;t++){const t=this.readOutpoint(s);a.noSendChange.push(t)}}const c=s.readVarIntNum();if(c>=0){a.sendWithResults=[];for(let t=0;t<c;t++){const t=s.read(32),e=Nt(t),r=s.readInt8();let i="unproven";1===r?i="unproven":2===r?i="sending":3===r&&(i="failed"),a.sendWithResults.push({txid:e,status:i})}}if(1===s.readInt8()){const t=s.readVarIntNum(),e=s.read(t),r=s.readVarIntNum(),i=s.read(r);a.signableTransaction={tx:e,reference:_t(i)}}return a}async signAction(t,e){const r=new Bt,i=Object.keys(t.spends);r.writeVarIntNum(i.length);for(const e of i){r.writeVarIntNum(Number(e));const i=t.spends[Number(e)],n=Ot(i.unlockingScript,"hex");r.writeVarIntNum(n.length),r.write(n),"number"==typeof i.sequenceNumber?r.writeVarIntNum(i.sequenceNumber):r.writeVarIntNum(-1)}const n=Ot(t.reference,"base64");if(r.writeVarIntNum(n.length),r.write(n),null!=t.options)if(r.writeInt8(1),"boolean"==typeof t.options.acceptDelayedBroadcast?r.writeInt8(t.options.acceptDelayedBroadcast?1:0):r.writeInt8(-1),"boolean"==typeof t.options.returnTXIDOnly?r.writeInt8(t.options.returnTXIDOnly?1:0):r.writeInt8(-1),"boolean"==typeof t.options.noSend?r.writeInt8(t.options.noSend?1:0):r.writeInt8(-1),null!=t.options.sendWith){r.writeVarIntNum(t.options.sendWith.length);for(const e of t.options.sendWith){const t=Ot(e,"hex");r.write(t)}}else r.writeVarIntNum(-1);else r.writeInt8(0);const s=await this.transmit("signAction",e,r.toArray()),a=new Ut(s),o={};if(1===a.readInt8()){const t=a.read(32);o.txid=Nt(t)}if(1===a.readInt8()){const t=a.readVarIntNum();o.tx=a.read(t)}const c=a.readVarIntNum();if(c>=0){o.sendWithResults=[];for(let t=0;t<c;t++){const t=a.read(32),e=Nt(t),r=a.readInt8();let i="unproven";1===r?i="unproven":2===r?i="sending":3===r&&(i="failed"),o.sendWithResults.push({txid:e,status:i})}}return o}async abortAction(t,e){return await this.transmit("abortAction",e,Ot(t.reference,"base64")),{aborted:!0}}async listActions(t,e){const r=new Bt;r.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=Ot(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}"any"===t.labelQueryMode?r.writeInt8(1):"all"===t.labelQueryMode?r.writeInt8(2):r.writeInt8(-1);const i=[t.includeLabels,t.includeInputs,t.includeInputSourceLockingScripts,t.includeInputUnlockingScripts,t.includeOutputs,t.includeOutputLockingScripts];for(const t of i)"boolean"==typeof t?r.writeInt8(t?1:0):r.writeInt8(-1);"number"==typeof t.limit?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),"number"==typeof t.offset?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const n=await this.transmit("listActions",e,r.toArray()),s=new Ut(n),a=s.readVarIntNum(),o=[];for(let t=0;t<a;t++){const t=s.read(32),e=Nt(t),r=s.readVarIntNum(),i=s.readInt8();let n;switch(i){case 1:n="completed";break;case 2:n="unprocessed";break;case 3:n="sending";break;case 4:n="unproven";break;case 5:n="unsigned";break;case 6:n="nosend";break;case 7:n="nonfinal";break;case 8:n="failed";break;default:throw new Error(`Unknown status code: ${i}`)}const a=1===s.readInt8(),c=s.readVarIntNum(),h=s.read(c),u={txid:e,satoshis:r,status:n,isOutgoing:a,description:Tt(h),version:0,lockTime:0},l=s.readVarIntNum();if(l>=0){u.labels=[];for(let t=0;t<l;t++){const t=s.readVarIntNum(),e=s.read(t);u.labels.push(Tt(e))}}u.version=s.readVarIntNum(),u.lockTime=s.readVarIntNum();const d=s.readVarIntNum();if(d>=0){u.inputs=[];for(let t=0;t<d;t++){const t=this.readOutpoint(s),e=s.readVarIntNum(),r=s.readVarIntNum();let i;if(r>=0){const t=s.read(r);i=Nt(t)}const n=s.readVarIntNum();let a;if(n>=0){const t=s.read(n);a=Nt(t)}const o=s.readVarIntNum(),c=s.read(o),h=Tt(c),l=s.readVarIntNum();u.inputs.push({sourceOutpoint:t,sourceSatoshis:e,sourceLockingScript:i,unlockingScript:a,inputDescription:h,sequenceNumber:l})}}const f=s.readVarIntNum();if(f>=0){u.outputs=[];for(let t=0;t<f;t++){const t=s.readVarIntNum(),e=s.readVarIntNum(),r=s.readVarIntNum();let i;if(r>=0){const t=s.read(r);i=Nt(t)}const n=1===s.readInt8(),a=s.readVarIntNum(),o=s.read(a),c=Tt(o),h=s.readVarIntNum();let l;if(h>=0){const t=s.read(h);l=Tt(t)}const d=s.readVarIntNum(),f=[];if(d>=0)for(let t=0;t<d;t++){const t=s.readVarIntNum(),e=s.read(t);f.push(Tt(e))}const p=s.readVarIntNum();let m;if(p>=0){const t=s.read(p);m=Tt(t)}u.outputs.push({outputIndex:t,satoshis:e,lockingScript:i,spendable:n,outputDescription:c,basket:l,tags:f,customInstructions:m})}}o.push(u)}return{totalActions:a,actions:o}}async internalizeAction(t,e){const r=new Bt;r.writeVarIntNum(t.tx.length),r.write(t.tx),r.writeVarIntNum(t.outputs.length);for(const e of t.outputs)if(r.writeVarIntNum(e.outputIndex),"wallet payment"===e.protocol){if(null==e.paymentRemittance)throw new Error("Payment remittance is required for wallet payment");r.writeUInt8(1),r.write(Ot(e.paymentRemittance.senderIdentityKey,"hex"));const t=Ot(e.paymentRemittance.derivationPrefix,"base64");r.writeVarIntNum(t.length),r.write(t);const i=Ot(e.paymentRemittance.derivationSuffix,"base64");r.writeVarIntNum(i.length),r.write(i)}else{r.writeUInt8(2);const t=Ot(e.insertionRemittance?.basket,"utf8");if(r.writeVarIntNum(t.length),r.write(t),"string"==typeof e.insertionRemittance?.customInstructions&&""!==e.insertionRemittance.customInstructions){const t=Ot(e.insertionRemittance.customInstructions,"utf8");r.writeVarIntNum(t.length),r.write(t)}else r.writeVarIntNum(-1);if("object"==typeof e.insertionRemittance?.tags){r.writeVarIntNum(e.insertionRemittance.tags.length);for(const t of e.insertionRemittance.tags){const e=Ot(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}}else r.writeVarIntNum(0)}if("object"==typeof t.labels){r.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=Ot(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}}else r.writeVarIntNum(-1);const i=Ot(t.description);return r.writeVarIntNum(i.length),r.write(i),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),await this.transmit("internalizeAction",e,r.toArray()),{accepted:!0}}async listOutputs(t,e){const r=new Bt,i=Ot(t.basket,"utf8");if(r.writeVarIntNum(i.length),r.write(i),"object"==typeof t.tags){r.writeVarIntNum(t.tags.length);for(const e of t.tags){const t=Ot(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}}else r.writeVarIntNum(0);"all"===t.tagQueryMode?r.writeInt8(1):"any"===t.tagQueryMode?r.writeInt8(2):r.writeInt8(-1),"locking scripts"===t.include?r.writeInt8(1):"entire transactions"===t.include?r.writeInt8(2):r.writeInt8(-1),"boolean"==typeof t.includeCustomInstructions?r.writeInt8(t.includeCustomInstructions?1:0):r.writeInt8(-1),"boolean"==typeof t.includeTags?r.writeInt8(t.includeTags?1:0):r.writeInt8(-1),"boolean"==typeof t.includeLabels?r.writeInt8(t.includeLabels?1:0):r.writeInt8(-1),"number"==typeof t.limit?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),"number"==typeof t.offset?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const n=await this.transmit("listOutputs",e,r.toArray()),s=new Ut(n),a=s.readVarIntNum(),o=s.readVarIntNum();let c;o>=0&&(c=s.read(o));const h=[];for(let t=0;t<a;t++){const t={spendable:!0,outpoint:this.readOutpoint(s),satoshis:s.readVarIntNum()},e=s.readVarIntNum();e>=0&&(t.lockingScript=Nt(s.read(e)));const r=s.readVarIntNum();r>=0&&(t.customInstructions=Tt(s.read(r)));const i=s.readVarIntNum();if(-1!==i){const e=[];for(let t=0;t<i;t++){const t=s.readVarIntNum();e.push(Tt(s.read(t)))}t.tags=e}const n=s.readVarIntNum();if(-1!==n){const e=[];for(let t=0;t<n;t++){const t=s.readVarIntNum();e.push(Tt(s.read(t)))}t.labels=e}h.push(t)}return{totalOutputs:a,BEEF:c,outputs:h}}async relinquishOutput(t,e){const r=new Bt,i=Ot(t.basket,"utf8");return r.writeVarIntNum(i.length),r.write(i),r.write(this.encodeOutpoint(t.output)),await this.transmit("relinquishOutput",e,r.toArray()),{relinquished:!0}}encodeOutpoint(t){const e=new Bt,[r,i]=t.split(".");return e.write(Ot(r,"hex")),e.writeVarIntNum(Number(i)),e.toArray()}readOutpoint(t){return`${Nt(t.read(32))}.${t.readVarIntNum()}`}async getPublicKey(t,e){const r=new Bt;r.writeUInt8(t.identityKey?1:0),t.identityKey?r.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)):(r.write(this.encodeKeyRelatedParams(t.protocolID??=[xr.Silent,"default"],t.keyID??="",t.counterparty,t.privileged,t.privilegedReason)),"boolean"==typeof t.forSelf?r.writeInt8(t.forSelf?1:0):r.writeInt8(-1)),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const i=await this.transmit("getPublicKey",e,r.toArray());return{publicKey:Nt(i)}}async revealCounterpartyKeyLinkage(t,e){const r=new Bt;r.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)),r.write(Ot(t.counterparty,"hex")),r.write(Ot(t.verifier,"hex"));const i=await this.transmit("revealCounterpartyKeyLinkage",e,r.toArray()),n=new Ut(i),s=Nt(n.read(33)),a=Nt(n.read(33)),o=Nt(n.read(33)),c=n.readVarIntNum(),h=Tt(n.read(c)),u=n.readVarIntNum(),l=n.read(u),d=n.readVarIntNum();return{prover:s,verifier:a,counterparty:o,revelationTime:h,encryptedLinkage:l,encryptedLinkageProof:n.read(d)}}async revealSpecificKeyLinkage(t,e){const r=new Bt;r.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),r.write(Ot(t.verifier,"hex"));const i=await this.transmit("revealSpecificKeyLinkage",e,r.toArray()),n=new Ut(i),s=Nt(n.read(33)),a=Nt(n.read(33)),o=Nt(n.read(33)),c=n.readUInt8(),h=n.readVarIntNum(),u=Tt(n.read(h)),l=n.readVarIntNum(),d=Tt(n.read(l)),f=n.readVarIntNum(),p=n.read(f),m=n.readVarIntNum();return{prover:s,verifier:a,counterparty:o,protocolID:[c,u],keyID:d,encryptedLinkage:p,encryptedLinkageProof:n.read(m),proofType:n.readUInt8()}}async encrypt(t,e){const r=new Bt;return r.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),r.writeVarIntNum(t.plaintext.length),r.write(t.plaintext),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),{ciphertext:await this.transmit("encrypt",e,r.toArray())}}async decrypt(t,e){const r=new Bt;return r.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),r.writeVarIntNum(t.ciphertext.length),r.write(t.ciphertext),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),{plaintext:await this.transmit("decrypt",e,r.toArray())}}async createHmac(t,e){const r=new Bt;return r.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),r.writeVarIntNum(t.data.length),r.write(t.data),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),{hmac:await this.transmit("createHmac",e,r.toArray())}}async verifyHmac(t,e){const r=new Bt;return r.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),r.write(t.hmac),r.writeVarIntNum(t.data.length),r.write(t.data),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),await this.transmit("verifyHmac",e,r.toArray()),{valid:!0}}async createSignature(t,e){const r=new Bt;return r.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),"object"==typeof t.data?(r.writeUInt8(1),r.writeVarIntNum(t.data.length),r.write(t.data)):(r.writeUInt8(2),r.write(t.hashToDirectlySign??=[])),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),{signature:await this.transmit("createSignature",e,r.toArray())}}async verifySignature(t,e){const r=new Bt;return r.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),"boolean"==typeof t.forSelf?r.writeInt8(t.forSelf?1:0):r.writeInt8(-1),r.writeVarIntNum(t.signature.length),r.write(t.signature),"object"==typeof t.data?(r.writeUInt8(1),r.writeVarIntNum(t.data.length),r.write(t.data)):(r.writeUInt8(2),r.write(t.hashToDirectlyVerify??[])),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),await this.transmit("verifySignature",e,r.toArray()),{valid:!0}}encodeKeyRelatedParams(t,e,r,i,n){const s=new Bt;s.writeUInt8(t[0]);const a=Ot(t[1],"utf8");s.writeVarIntNum(a.length),s.write(a);const o=Ot(e,"utf8");return s.writeVarIntNum(o.length),s.write(o),"string"!=typeof r?s.writeUInt8(0):"self"===r?s.writeUInt8(11):"anyone"===r?s.writeUInt8(12):s.write(Ot(r,"hex")),s.write(this.encodePrivilegedParams(i,n)),s.toArray()}async acquireCertificate(t,e){const r=new Bt;r.write(Ot(t.type,"base64")),r.write(Ot(t.certifier,"hex"));const i=Object.entries(t.fields);r.writeVarIntNum(i.length);for(const[t,e]of i){const i=Ot(t,"utf8"),n=Ot(e,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(n.length),r.write(n)}if(r.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)),r.writeUInt8("direct"===t.acquisitionProtocol?1:2),"direct"===t.acquisitionProtocol){r.write(Ot(t.serialNumber,"base64")),r.write(this.encodeOutpoint(t.revocationOutpoint??""));const e=Ot(t.signature,"hex");r.writeVarIntNum(e.length),r.write(e);const i="certifier"!==t.keyringRevealer?Ot(t.keyringRevealer,"hex"):[11];r.write(i);const n=Object.keys(t.keyringForSubject??{});r.writeVarIntNum(n.length);for(let e=0;e<n.length;e++){const i=Ot(n[e],"utf8");r.writeVarIntNum(i.length),r.write(i);const s=Ot(t.keyringForSubject?.[n[e]],"base64");r.writeVarIntNum(s.length),r.write(s)}}else{const e=Ot(t.certifierUrl,"utf8");r.writeVarIntNum(e.length),r.write(e)}const n=await this.transmit("acquireCertificate",e,r.toArray()),s=Dr.fromBinary(n);return{...s,signature:s.signature}}encodePrivilegedParams(t,e){const r=new Bt;if("boolean"==typeof t?r.writeInt8(t?1:0):r.writeInt8(-1),"string"==typeof e){const t=Ot(e,"utf8");r.writeInt8(t.length),r.write(t)}else r.writeInt8(-1);return r.toArray()}async listCertificates(t,e){const r=new Bt;r.writeVarIntNum(t.certifiers.length);for(let e=0;e<t.certifiers.length;e++)r.write(Ot(t.certifiers[e],"hex"));r.writeVarIntNum(t.types.length);for(let e=0;e<t.types.length;e++)r.write(Ot(t.types[e],"base64"));"number"==typeof t.limit?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),"number"==typeof t.offset?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),r.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason));const i=await this.transmit("listCertificates",e,r.toArray()),n=new Ut(i),s=n.readVarIntNum(),a=[];for(let t=0;t<s;t++){const t=n.readVarIntNum(),e=n.read(t),r=Dr.fromBinary(e);a.push({...r,signature:r.signature})}return{totalCertificates:s,certificates:a}}async proveCertificate(t,e){const r=new Bt,i=Ot(t.certificate.type,"base64");r.write(i);const n=Ot(t.certificate.subject,"hex");r.write(n);const s=Ot(t.certificate.serialNumber,"base64");r.write(s);const a=Ot(t.certificate.certifier,"hex");r.write(a);const o=this.encodeOutpoint(t.certificate.revocationOutpoint??"");r.write(o);const c=Ot(t.certificate.signature,"hex");r.writeVarIntNum(c.length),r.write(c);const h=Object.entries(t.certificate.fields??{});r.writeVarIntNum(h.length);for(const[t,e]of h){const i=Ot(t,"utf8"),n=Ot(e,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(n.length),r.write(n)}r.writeVarIntNum(t.fieldsToReveal.length);for(const e of t.fieldsToReveal){const t=Ot(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}r.write(Ot(t.verifier,"hex")),r.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason));const u=await this.transmit("proveCertificate",e,r.toArray()),l=new Ut(u),d=l.readVarIntNum(),f={};for(let t=0;t<d;t++){const t=l.readVarIntNum(),e=Tt(l.read(t)),r=l.readVarIntNum();f[e]=_t(l.read(r))}return{keyringForVerifier:f}}async relinquishCertificate(t,e){const r=new Bt,i=Ot(t.type,"base64");r.write(i);const n=Ot(t.serialNumber,"base64");r.write(n);const s=Ot(t.certifier,"hex");return r.write(s),await this.transmit("relinquishCertificate",e,r.toArray()),{relinquished:!0}}parseDiscoveryResult(t){const e=new Ut(t),r=e.readVarIntNum(),i=[];for(let t=0;t<r;t++){const t=e.readVarIntNum(),r=e.read(t),n=Dr.fromBinary(r),s=e.readVarIntNum(),a=Tt(e.read(s)),o=e.readVarIntNum(),c=Tt(e.read(o)),h=e.readVarIntNum(),u=Tt(e.read(h)),l=e.readUInt8(),d={},f=e.readVarIntNum();for(let t=0;t<f;t++){const t=e.readVarIntNum(),r=Tt(e.read(t)),i=e.readVarIntNum();d[r]=e.read(i)}const p={},m=e.readVarIntNum();for(let t=0;t<m;t++){const t=e.readVarIntNum(),r=Tt(e.read(t)),i=e.readVarIntNum();p[r]=Tt(e.read(i))}i.push({...n,signature:n.signature,certifierInfo:{iconUrl:c,name:a,description:u,trust:l},publiclyRevealedKeyring:d,decryptedFields:p})}return{totalCertificates:r,certificates:i}}async discoverByIdentityKey(t,e){const r=new Bt;r.write(Ot(t.identityKey,"hex")),"number"==typeof t.limit?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),"number"==typeof t.offset?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const i=await this.transmit("discoverByIdentityKey",e,r.toArray());return this.parseDiscoveryResult(i)}async discoverByAttributes(t,e){const r=new Bt,i=Object.keys(t.attributes);r.writeVarIntNum(i.length);for(let e=0;e<i.length;e++)r.writeVarIntNum(i[e].length),r.write(Ot(i[e],"utf8")),r.writeVarIntNum(t.attributes[i[e]].length),r.write(Ot(t.attributes[i[e]],"utf8"));"number"==typeof t.limit?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),"number"==typeof t.offset?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const n=await this.transmit("discoverByAttributes",e,r.toArray());return this.parseDiscoveryResult(n)}async isAuthenticated(t,e){return{authenticated:1===(await this.transmit("isAuthenticated",e))[0]}}async waitForAuthentication(t,e){return await this.transmit("waitForAuthentication",e),{authenticated:!0}}async getHeight(t,e){const r=await this.transmit("getHeight",e);return{height:new Ut(r).readVarIntNum()}}async getHeaderForHeight(t,e){const r=new Bt;r.writeVarIntNum(t.height);const i=await this.transmit("getHeaderForHeight",e,r.toArray());return{header:Nt(i)}}async getNetwork(t,e){return{network:0===(await this.transmit("getNetwork",e))[0]?"mainnet":"testnet"}}async getVersion(t,e){const r=await this.transmit("getVersion",e);return{version:Tt(r)}}}class Kr{baseUrl;httpClient;originator;constructor(t,e="http://localhost:3301",r=fetch){this.baseUrl=e,this.httpClient=r,this.originator=t}async transmitToWallet(t){const e=new Ut(t),r=e.readUInt8(),i=Ur[r];if(void 0===i||""===i)throw new Error(`Invalid call code: ${r}`);const n=e.readUInt8();let s;if(n>0){const t=e.read(n);s=Tt(t)}const a=e.read(),o=await fetch(`${this.baseUrl}/${i}`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Origin:s??""},body:new Uint8Array(a)}),c=await o.arrayBuffer();return Array.from(new Uint8Array(c))}}class qr extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(t,e,r,i,n){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=t,this.sendWithResults=e,this.txid=r,this.tx=i,this.noSendChange=n,this.code=5,this.name=this.constructor.name}}const Lr=qr;class $r{baseUrl;httpClient;originator;api;constructor(t,e="http://localhost:3321",r=fetch){this.baseUrl=e,this.originator=t,this.httpClient=r,this.api=async(t,e)=>{const i=await await r(`${this.baseUrl}/${t}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Originator:this.originator??""},body:JSON.stringify(e)}),n=await i.json();if(!i.ok){if(400===i.status&&n.isError&&5===n.code)throw new qr(n.reviewActionResults,n.sendWithResults,n.txid,n.tx,n.noSendChange);{const r={call:t,args:e,message:n.message??`HTTP Client error ${i.status}`};throw new Error(JSON.stringify(r))}}return n}}async createAction(t){return await this.api("createAction",t)}async signAction(t){return await this.api("signAction",t)}async abortAction(t){return await this.api("abortAction",t)}async listActions(t){return await this.api("listActions",t)}async internalizeAction(t){return await this.api("internalizeAction",t)}async listOutputs(t){return await this.api("listOutputs",t)}async relinquishOutput(t){return await this.api("relinquishOutput",t)}async getPublicKey(t){return await this.api("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.api("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.api("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.api("encrypt",t)}async decrypt(t){return await this.api("decrypt",t)}async createHmac(t){return await this.api("createHmac",t)}async verifyHmac(t){return await this.api("verifyHmac",t)}async createSignature(t){return await this.api("createSignature",t)}async verifySignature(t){return await this.api("verifySignature",t)}async acquireCertificate(t){return await this.api("acquireCertificate",t)}async listCertificates(t){return await this.api("listCertificates",t)}async proveCertificate(t){return await this.api("proveCertificate",t)}async relinquishCertificate(t){return await this.api("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.api("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.api("discoverByAttributes",t)}async isAuthenticated(t){return await this.api("isAuthenticated",t)}async waitForAuthentication(t){return await this.api("waitForAuthentication",t)}async getHeight(t){return await this.api("getHeight",t)}async getHeaderForHeight(t){return await this.api("getHeaderForHeight",t)}async getNetwork(t){return await this.api("getNetwork",t)}async getVersion(t){return await this.api("getVersion",t)}}class zr{substrate;originator;constructor(t="auto",e){"Cicada"===t&&(t=new Hr(new Kr(e))),"window.CWI"===t&&(t=new _r),"XDM"===t&&(t=new Vr),"json-api"===t&&(t=new $r(e)),this.substrate=t,this.originator=e}async connectToSubstrate(){if("object"==typeof this.substrate)return;let t;const e=async e=>{let r;if(r="number"==typeof e?await Promise.race([t.getVersion({}),new Promise(((t,r)=>setTimeout((()=>r(new Error("Timed out."))),e)))]):await t.getVersion({}),"object"!=typeof r||"string"!=typeof r.version)throw new Error("Failed to use substrate.")};try{t=new _r,await e(),this.substrate=t}catch(r){try{t=new Vr,await e(200),this.substrate=t}catch(r){try{t=new Hr(new Kr(this.originator)),await e(),this.substrate=t}catch(r){try{t=new $r(this.originator),await e(),this.substrate=t}catch(t){throw new Error("No wallet available over any communication substrate. Install a BSV wallet today!")}}}}}async createAction(t){return await this.connectToSubstrate(),await this.substrate.createAction(t,this.originator)}async signAction(t){return await this.connectToSubstrate(),await this.substrate.signAction(t,this.originator)}async abortAction(t){return await this.connectToSubstrate(),await this.substrate.abortAction(t,this.originator)}async listActions(t){return await this.connectToSubstrate(),await this.substrate.listActions(t,this.originator)}async internalizeAction(t){return await this.connectToSubstrate(),await this.substrate.internalizeAction(t,this.originator)}async listOutputs(t){return await this.connectToSubstrate(),await this.substrate.listOutputs(t,this.originator)}async relinquishOutput(t){return await this.connectToSubstrate(),await this.substrate.relinquishOutput(t,this.originator)}async getPublicKey(t){return await this.connectToSubstrate(),await this.substrate.getPublicKey(t,this.originator)}async revealCounterpartyKeyLinkage(t){return await this.connectToSubstrate(),await this.substrate.revealCounterpartyKeyLinkage(t,this.originator)}async revealSpecificKeyLinkage(t){return await this.connectToSubstrate(),await this.substrate.revealSpecificKeyLinkage(t,this.originator)}async encrypt(t){return await this.connectToSubstrate(),await this.substrate.encrypt(t,this.originator)}async decrypt(t){return await this.substrate.decrypt(t,this.originator)}async createHmac(t){return await this.connectToSubstrate(),await this.substrate.createHmac(t,this.originator)}async verifyHmac(t){return await this.connectToSubstrate(),await this.substrate.verifyHmac(t,this.originator)}async createSignature(t){return await this.connectToSubstrate(),await this.substrate.createSignature(t,this.originator)}async verifySignature(t){return await this.connectToSubstrate(),await this.substrate.verifySignature(t,this.originator)}async acquireCertificate(t){return await this.connectToSubstrate(),await this.substrate.acquireCertificate(t,this.originator)}async listCertificates(t){return await this.connectToSubstrate(),await this.substrate.listCertificates(t,this.originator)}async proveCertificate(t){return await this.connectToSubstrate(),await this.substrate.proveCertificate(t,this.originator)}async relinquishCertificate(t){return await this.connectToSubstrate(),await this.substrate.relinquishCertificate(t,this.originator)}async discoverByIdentityKey(t){return await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(t,this.originator)}async discoverByAttributes(t){return await this.connectToSubstrate(),await this.substrate.discoverByAttributes(t,this.originator)}async isAuthenticated(t={}){return await this.connectToSubstrate(),await this.substrate.isAuthenticated(t,this.originator)}async waitForAuthentication(t={}){return await this.connectToSubstrate(),await this.substrate.waitForAuthentication(t,this.originator)}async getHeight(t={}){return await this.connectToSubstrate(),await this.substrate.getHeight(t,this.originator)}async getHeaderForHeight(t){return await this.connectToSubstrate(),await this.substrate.getHeaderForHeight(t,this.originator)}async getNetwork(t={}){return await this.connectToSubstrate(),await this.substrate.getNetwork(t,this.originator)}async getVersion(t={}){return await this.connectToSubstrate(),await this.substrate.getVersion(t,this.originator)}}class jr{wallet;constructor(t){this.wallet=t}decodeOutpoint(t){const e=t.read(32);return`${Nt(e)}.${t.readVarIntNum()}`}encodeOutpoint(t){const e=new Bt,[r,i]=t.split(".");return e.write(Ot(r,"hex")),e.writeVarIntNum(Number(i)),e.toArray()}async transmitToWallet(t){const e=new Ut(t);try{const t=e.readUInt8(),r=Ur[t];if(void 0===r||""===r)throw new Error(`Invalid call code: ${t}`);const i=e.readUInt8(),n=e.read(i),s=Tt(n),a=e;switch(r){case"createAction":{const t={},e=a.readVarIntNum(),r=a.read(e);t.description=Tt(r);const i=a.readVarIntNum();t.inputBEEF=i>=0?a.read(i):void 0;const n=a.readVarIntNum();if(n>=0){t.inputs=[];for(let e=0;e<n;e++){const e={};e.outpoint=this.decodeOutpoint(a);const r=a.readVarIntNum();if(r>=0){const t=a.read(r);e.unlockingScript=Nt(t)}else{e.unlockingScript=void 0;const t=a.readVarIntNum();e.unlockingScriptLength=t}const i=a.readVarIntNum(),n=a.read(i);e.inputDescription=Tt(n);const s=a.readVarIntNum();e.sequenceNumber=s>=0?s:void 0,t.inputs.push(e)}}else t.inputs=void 0;const o=a.readVarIntNum();if(o>=0){t.outputs=[];for(let e=0;e<o;e++){const e={},r=a.readVarIntNum(),i=a.read(r);e.lockingScript=Nt(i),e.satoshis=a.readVarIntNum();const n=a.readVarIntNum(),s=a.read(n);e.outputDescription=Tt(s);const o=a.readVarIntNum();if(o>=0){const t=a.read(o);e.basket=Tt(t)}else e.basket=void 0;const c=a.readVarIntNum();if(c>=0){const t=a.read(c);e.customInstructions=Tt(t)}else e.customInstructions=void 0;const h=a.readVarIntNum();if(h>=0){e.tags=[];for(let t=0;t<h;t++){const t=a.readVarIntNum(),r=a.read(t),i=Tt(r);e.tags.push(i)}}else e.tags=void 0;t.outputs.push(e)}}else t.outputs=void 0;const c=a.readVarIntNum();t.lockTime=c>=0?c:void 0;const h=a.readVarIntNum();t.version=h>=0?h:void 0;const u=a.readVarIntNum();if(u>=0){t.labels=[];for(let e=0;e<u;e++){const e=a.readVarIntNum(),r=a.read(e),i=Tt(r);t.labels.push(i)}}else t.labels=void 0;if(1===a.readInt8()){t.options={};const e=a.readInt8();t.options.signAndProcess=-1===e?void 0:1===e;const r=a.readInt8();t.options.acceptDelayedBroadcast=-1===r?void 0:1===r;const i=a.readInt8();-1===i?t.options.trustSelf=void 0:1===i&&(t.options.trustSelf="known");const n=a.readVarIntNum();if(n>=0){t.options.knownTxids=[];for(let e=0;e<n;e++){const e=a.read(32),r=Nt(e);t.options.knownTxids.push(r)}}else t.options.knownTxids=void 0;const s=a.readInt8();t.options.returnTXIDOnly=-1===s?void 0:1===s;const o=a.readInt8();t.options.noSend=-1===o?void 0:1===o;const c=a.readVarIntNum();if(c>=0){t.options.noSendChange=[];for(let e=0;e<c;e++){const e=this.decodeOutpoint(a);t.options.noSendChange.push(e)}}else t.options.noSendChange=void 0;const h=a.readVarIntNum();if(h>=0){t.options.sendWith=[];for(let e=0;e<h;e++){const e=a.read(32),r=Nt(e);t.options.sendWith.push(r)}}else t.options.sendWith=void 0;const u=a.readInt8();t.options.randomizeOutputs=-1===u?void 0:1===u}else t.options=void 0;const l=await this.wallet.createAction(t,s),d=new Bt;if(null!=l.txid&&""!==l.txid?(d.writeInt8(1),d.write(Ot(l.txid,"hex"))):d.writeInt8(0),null!=l.tx?(d.writeInt8(1),d.writeVarIntNum(l.tx.length),d.write(l.tx)):d.writeInt8(0),null!=l.noSendChange){d.writeVarIntNum(l.noSendChange.length);for(const t of l.noSendChange)d.write(this.encodeOutpoint(t))}else d.writeVarIntNum(-1);if(null!=l.sendWithResults){d.writeVarIntNum(l.sendWithResults.length);for(const t of l.sendWithResults){let e;d.write(Ot(t.txid,"hex")),"unproven"===t.status?e=1:"sending"===t.status?e=2:"failed"===t.status&&(e=3),d.writeInt8(e)}}else d.writeVarIntNum(-1);if(null!=l.signableTransaction){d.writeInt8(1),d.writeVarIntNum(l.signableTransaction.tx.length),d.write(l.signableTransaction.tx);const t=Ot(l.signableTransaction.reference,"base64");d.writeVarIntNum(t.length),d.write(t)}else d.writeInt8(0);const f=new Bt;return f.writeUInt8(0),f.write(d.toArray()),f.toArray()}case"signAction":{const t={},e=a.readVarIntNum();t.spends={};for(let r=0;r<e;r++){const e=a.readVarIntNum(),r={},i=a.readVarIntNum(),n=a.read(i);r.unlockingScript=Nt(n);const s=a.readVarIntNum();r.sequenceNumber=s>=0?s:void 0,t.spends[e]=r}const r=a.readVarIntNum(),i=a.read(r);if(t.reference=_t(i),1===a.readInt8()){t.options={};const e=a.readInt8();t.options.acceptDelayedBroadcast=-1===e?void 0:1===e;const r=a.readInt8();t.options.returnTXIDOnly=-1===r?void 0:1===r;const i=a.readInt8();t.options.noSend=-1===i?void 0:1===i;const n=a.readVarIntNum();if(n>=0){t.options.sendWith=[];for(let e=0;e<n;e++){const e=a.read(32),r=Nt(e);t.options.sendWith.push(r)}}else t.options.sendWith=void 0}else t.options=void 0;const n=await this.wallet.signAction(t,s),o=new Bt;if(null!=n.txid&&""!==n.txid?(o.writeInt8(1),o.write(Ot(n.txid,"hex"))):o.writeInt8(0),null!=n.tx?(o.writeInt8(1),o.writeVarIntNum(n.tx.length),o.write(n.tx)):o.writeInt8(0),null!=n.sendWithResults){o.writeVarIntNum(n.sendWithResults.length);for(const t of n.sendWithResults){let e;o.write(Ot(t.txid,"hex")),"unproven"===t.status?e=1:"sending"===t.status?e=2:"failed"===t.status&&(e=3),o.writeInt8(e)}}else o.writeVarIntNum(-1);const c=new Bt;return c.writeUInt8(0),c.write(o.toArray()),c.toArray()}case"abortAction":{const t=_t(a.read());await this.wallet.abortAction({reference:t},s);const e=new Bt;return e.writeUInt8(0),e.toArray()}case"listActions":{const t={},e=a.readVarIntNum();t.labels=[];for(let r=0;r<e;r++){const e=a.readVarIntNum(),r=a.read(e);t.labels.push(Tt(r))}const r=a.readInt8();-1===r?t.labelQueryMode=void 0:1===r?t.labelQueryMode="any":2===r&&(t.labelQueryMode="all");const i=["includeLabels","includeInputs","includeInputSourceLockingScripts","includeInputUnlockingScripts","includeOutputs","includeOutputLockingScripts"];for(const e of i){const r=a.readInt8();t[e]=-1===r?void 0:1===r}const n=a.readVarIntNum();t.limit=n>=0?n:void 0;const o=a.readVarIntNum();t.offset=o>=0?o:void 0;const c=a.readInt8();t.seekPermission=c>=0?1===c:void 0;const h=await this.wallet.listActions(t,s),u=new Bt;u.writeVarIntNum(h.totalActions);for(const t of h.actions){let e;switch(u.write(Ot(t.txid,"hex")),u.writeVarIntNum(t.satoshis),t.status){case"completed":e=1;break;case"unprocessed":e=2;break;case"sending":e=3;break;case"unproven":e=4;break;case"unsigned":e=5;break;case"nosend":e=6;break;case"nonfinal":e=7;break;case"failed":e=8;break;default:e=-1}u.writeInt8(e),u.writeInt8(t.isOutgoing?1:0);const r=Ot(t.description,"utf8");if(u.writeVarIntNum(r.length),u.write(r),void 0!==t.labels){u.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=Ot(e,"utf8");u.writeVarIntNum(t.length),u.write(t)}}else u.writeVarIntNum(-1);if(u.writeVarIntNum(t.version),u.writeVarIntNum(t.lockTime),void 0!==t.inputs){u.writeVarIntNum(t.inputs.length);for(const e of t.inputs){if(u.write(this.encodeOutpoint(e.sourceOutpoint)),u.writeVarIntNum(e.sourceSatoshis),void 0!==e.sourceLockingScript){const t=Ot(e.sourceLockingScript,"hex");u.writeVarIntNum(t.length),u.write(t)}else u.writeVarIntNum(-1);if(void 0!==e.unlockingScript){const t=Ot(e.unlockingScript,"hex");u.writeVarIntNum(t.length),u.write(t)}else u.writeVarIntNum(-1);const t=Ot(e.inputDescription,"utf8");u.writeVarIntNum(t.length),u.write(t),u.writeVarIntNum(e.sequenceNumber)}}else u.writeVarIntNum(-1);if(void 0!==t.outputs){u.writeVarIntNum(t.outputs.length);for(const e of t.outputs){if(u.writeVarIntNum(e.outputIndex),u.writeVarIntNum(e.satoshis),void 0!==e.lockingScript){const t=Ot(e.lockingScript,"hex");u.writeVarIntNum(t.length),u.write(t)}else u.writeVarIntNum(-1);u.writeInt8(e.spendable?1:0);const t=Ot(e.outputDescription,"utf8");if(u.writeVarIntNum(t.length),u.write(t),void 0!==e.basket){const t=Ot(e.basket,"utf8");u.writeVarIntNum(t.length),u.write(t)}else u.writeVarIntNum(-1);if(void 0!==e.tags){u.writeVarIntNum(e.tags.length);for(const t of e.tags){const e=Ot(t,"utf8");u.writeVarIntNum(e.length),u.write(e)}}else u.writeVarIntNum(-1);if(void 0!==e.customInstructions){const t=Ot(e.customInstructions,"utf8");u.writeVarIntNum(t.length),u.write(t)}else u.writeVarIntNum(-1)}}else u.writeVarIntNum(-1)}const l=new Bt;return l.writeUInt8(0),l.write(u.toArray()),l.toArray()}case"internalizeAction":{const t={},e=a.readVarIntNum();t.tx=a.read(e);const r=a.readVarIntNum();t.outputs=[];for(let e=0;e<r;e++){const e={};e.outputIndex=a.readVarIntNum();const r=a.readUInt8();if(1===r){e.protocol="wallet payment",e.paymentRemittance={};const t=a.read(33);e.paymentRemittance.senderIdentityKey=Nt(t);const r=a.readVarIntNum(),i=a.read(r);e.paymentRemittance.derivationPrefix=_t(i);const n=a.readVarIntNum(),s=a.read(n);e.paymentRemittance.derivationSuffix=_t(s)}else if(2===r){e.protocol="basket insertion",e.insertionRemittance={};const t=a.readVarIntNum(),r=a.read(t);e.insertionRemittance.basket=Tt(r);const i=a.readVarIntNum();if(i>=0){const t=a.read(i);e.insertionRemittance.customInstructions=Tt(t)}const n=a.readVarIntNum();if(n>0){e.insertionRemittance.tags=[];for(let t=0;t<n;t++){const t=a.readVarIntNum(),r=a.read(t);e.insertionRemittance.tags.push(Tt(r))}}else e.insertionRemittance.tags=[]}t.outputs.push(e)}const i=a.readVarIntNum();if(i>=0){t.labels=[];for(let e=0;e<i;e++){const e=a.readVarIntNum();t.labels.push(Tt(a.read(e)))}}const n=a.readVarIntNum();t.description=Tt(a.read(n));const o=a.readInt8();t.seekPermission=o>=0?1===o:void 0,await this.wallet.internalizeAction(t,s);const c=new Bt;return c.writeUInt8(0),c.toArray()}case"listOutputs":{const t={},e=a.readVarIntNum(),r=a.read(e);t.basket=Tt(r);const i=a.readVarIntNum();if(i>0){t.tags=[];for(let e=0;e<i;e++){const e=a.readVarIntNum(),r=a.read(e);t.tags.push(Tt(r))}}else t.tags=void 0;const n=a.readInt8();t.tagQueryMode=1===n?"all":2===n?"any":void 0;const o=a.readInt8();t.include=1===o?"locking scripts":2===o?"entire transactions":void 0;const c=a.readInt8();t.includeCustomInstructions=-1===c?void 0:1===c;const h=a.readInt8();t.includeTags=-1===h?void 0:1===h;const u=a.readInt8();t.includeLabels=-1===u?void 0:1===u;const l=a.readVarIntNum();t.limit=l>=0?l:void 0;const d=a.readVarIntNum();t.offset=d>=0?d:void 0;const f=a.readInt8();t.seekPermission=f>=0?1===f:void 0;const p=await this.wallet.listOutputs(t,s),m=new Bt;m.writeVarIntNum(p.totalOutputs),null!=p.BEEF?(m.writeVarIntNum(p.BEEF.length),m.write(p.BEEF)):m.writeVarIntNum(-1);for(const t of p.outputs){if(m.write(this.encodeOutpoint(t.outpoint)),m.writeVarIntNum(t.satoshis),void 0!==t.lockingScript){const e=Ot(t.lockingScript,"hex");m.writeVarIntNum(e.length),m.write(e)}else m.writeVarIntNum(-1);if(void 0!==t.customInstructions){const e=Ot(t.customInstructions,"utf8");m.writeVarIntNum(e.length),m.write(e)}else m.writeVarIntNum(-1);if(void 0!==t.tags){m.writeVarIntNum(t.tags.length);for(const e of t.tags){const t=Ot(e,"utf8");m.writeVarIntNum(t.length),m.write(t)}}else m.writeVarIntNum(-1);if(void 0!==t.labels){m.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=Ot(e,"utf8");m.writeVarIntNum(t.length),m.write(t)}}else m.writeVarIntNum(-1)}const w=new Bt;return w.writeUInt8(0),w.write(m.toArray()),w.toArray()}case"relinquishOutput":{const t={},e=a.readVarIntNum(),r=a.read(e);t.basket=Tt(r),t.output=this.decodeOutpoint(a),await this.wallet.relinquishOutput(t,s);const i=new Bt;return i.writeUInt8(0),i.toArray()}case"getPublicKey":{const t={},e=a.readUInt8();if(t.identityKey=1===e,!0!==t.identityKey){t.protocolID=this.decodeProtocolID(a),t.keyID=this.decodeString(a),t.counterparty=this.decodeCounterparty(a);const e=a.readInt8();t.privileged=-1===e?void 0:1===e;const r=a.readInt8();if(-1!==r){const e=a.read(r);t.privilegedReason=Tt(e)}else t.privilegedReason=void 0;const i=a.readInt8();t.forSelf=-1===i?void 0:1===i}else{const e=a.readInt8();t.privileged=-1===e?void 0:1===e;const r=a.readInt8();if(-1!==r){const e=a.read(r);t.privilegedReason=Tt(e)}else t.privilegedReason=void 0}const r=a.readInt8();t.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.getPublicKey(t,s),n=new Bt;n.writeUInt8(0);const o=Ot(i.publicKey,"hex");return n.write(o),n.toArray()}case"encrypt":{const t=this.decodeKeyRelatedParams(a),e=a.readVarIntNum();t.plaintext=a.read(e);const r=a.readInt8();t.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.encrypt(t,s),n=new Bt;return n.writeUInt8(0),n.write(i.ciphertext),n.toArray()}case"decrypt":{const t=this.decodeKeyRelatedParams(a),e=a.readVarIntNum();t.ciphertext=a.read(e);const r=a.readInt8();t.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.decrypt(t,s),n=new Bt;return n.writeUInt8(0),n.write(i.plaintext),n.toArray()}case"createHmac":{const t=this.decodeKeyRelatedParams(a),e=a.readVarIntNum();t.data=a.read(e);const r=a.readInt8();t.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.createHmac(t,s),n=new Bt;return n.writeUInt8(0),n.write(i.hmac),n.toArray()}case"verifyHmac":{const t=this.decodeKeyRelatedParams(a);t.hmac=a.read(32);const e=a.readVarIntNum();t.data=a.read(e);const r=a.readInt8();t.seekPermission=r>=0?1===r:void 0,await this.wallet.verifyHmac(t,s);const i=new Bt;return i.writeUInt8(0),i.toArray()}case"createSignature":{const t=this.decodeKeyRelatedParams(a),e=a.readUInt8();if(1===e){const e=a.readVarIntNum();t.data=a.read(e)}else 2===e&&(t.hashToDirectlySign=a.read(32));const r=a.readInt8();t.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.createSignature(t,s),n=new Bt;return n.writeUInt8(0),n.write(i.signature),n.toArray()}case"verifySignature":{const t=this.decodeKeyRelatedParams(a),e=a.readInt8();t.forSelf=-1===e?void 0:1===e;const r=a.readVarIntNum();t.signature=a.read(r);const i=a.readUInt8();if(1===i){const e=a.readVarIntNum();t.data=a.read(e)}else 2===i&&(t.hashToDirectlyVerify=a.read(32));const n=a.readInt8();t.seekPermission=n>=0?1===n:void 0,await this.wallet.verifySignature(t,s);const o=new Bt;return o.writeUInt8(0),o.toArray()}case"isAuthenticated":{const t=await this.wallet.isAuthenticated({},s),e=new Bt;return e.writeUInt8(0),e.writeUInt8(t.authenticated?1:0),e.toArray()}case"waitForAuthentication":{await this.wallet.waitForAuthentication({},s);const t=new Bt;return t.writeUInt8(0),t.toArray()}case"getHeight":{const t=await this.wallet.getHeight({},s),e=new Bt;return e.writeUInt8(0),e.writeVarIntNum(t.height),e.toArray()}case"getHeaderForHeight":{const t={};t.height=a.readVarIntNum();const e=await this.wallet.getHeaderForHeight(t,s),r=new Bt;r.writeUInt8(0);const i=Ot(e.header,"hex");return r.write(i),r.toArray()}case"getNetwork":{const t=await this.wallet.getNetwork({},s),e=new Bt;return e.writeUInt8(0),e.writeUInt8("mainnet"===t.network?0:1),e.toArray()}case"getVersion":{const t=await this.wallet.getVersion({},s),e=new Bt;e.writeUInt8(0);const r=Ot(t.version,"utf8");return e.write(r),e.toArray()}case"revealCounterpartyKeyLinkage":{const t={},e=a.readInt8();t.privileged=-1===e?void 0:1===e;const r=a.readInt8();if(-1===r)t.privilegedReason=void 0;else{const e=a.read(r);t.privilegedReason=Tt(e)}const i=a.read(33);t.counterparty=Nt(i);const n=a.read(33);t.verifier=Nt(n);const o=await this.wallet.revealCounterpartyKeyLinkage(t,s),c=new Bt;c.write(Ot(o.prover,"hex")),c.write(Ot(o.verifier,"hex")),c.write(Ot(o.counterparty,"hex"));const h=Ot(o.revelationTime,"utf8");c.writeVarIntNum(h.length),c.write(h),c.writeVarIntNum(o.encryptedLinkage.length),c.write(o.encryptedLinkage),c.writeVarIntNum(o.encryptedLinkageProof.length),c.write(o.encryptedLinkageProof);const u=new Bt;return u.writeUInt8(0),u.write(c.toArray()),u.toArray()}case"revealSpecificKeyLinkage":{const t=this.decodeKeyRelatedParams(a),e=a.read(33);t.verifier=Nt(e);const r=await this.wallet.revealSpecificKeyLinkage(t,s),i=new Bt;i.write(Ot(r.prover,"hex")),i.write(Ot(r.verifier,"hex")),i.write(Ot(r.counterparty,"hex")),i.writeUInt8(r.protocolID[0]);const n=Ot(r.protocolID[1],"utf8");i.writeVarIntNum(n.length),i.write(n);const o=Ot(r.keyID,"utf8");i.writeVarIntNum(o.length),i.write(o),i.writeVarIntNum(r.encryptedLinkage.length),i.write(r.encryptedLinkage),i.writeVarIntNum(r.encryptedLinkageProof.length),i.write(r.encryptedLinkageProof),i.writeUInt8(r.proofType);const c=new Bt;return c.writeUInt8(0),c.write(i.toArray()),c.toArray()}case"acquireCertificate":{const t={},e=a.read(32);t.type=_t(e);const r=a.read(33);t.certifier=Nt(r);const i=a.readVarIntNum();t.fields={};for(let e=0;e<i;e++){const e=a.readVarIntNum(),r=a.read(e),i=Tt(r),n=a.readVarIntNum(),s=a.read(n),o=Tt(s);t.fields[i]=o}const n=a.readInt8();t.privileged=-1===n?void 0:1===n;const o=a.readInt8();if(-1===o)t.privilegedReason=void 0;else{const e=a.read(o);t.privilegedReason=Tt(e)}const c=a.readUInt8();if(t.acquisitionProtocol=1===c?"direct":"issuance","direct"===t.acquisitionProtocol){const e=a.read(32);t.serialNumber=_t(e),t.revocationOutpoint=this.decodeOutpoint(a);const r=a.readVarIntNum(),i=a.read(r);t.signature=Nt(i);const n=a.readUInt8();if(11===n)t.keyringRevealer="certifier";else{const e=[n].concat(a.read(32));t.keyringRevealer=Nt(e)}const s=a.readVarIntNum();t.keyringForSubject={};for(let e=0;e<s;e++){const e=a.readVarIntNum(),r=a.read(e),i=Tt(r),n=a.readVarIntNum(),s=_t(a.read(n));t.keyringForSubject[i]=s}}else{const e=a.readVarIntNum(),r=a.read(e);t.certifierUrl=Tt(r)}const h=await this.wallet.acquireCertificate(t,s),u=new Dr(h.type,h.serialNumber,h.subject,h.certifier,h.revocationOutpoint,h.fields,h.signature).toBinary(),l=new Bt;return l.writeUInt8(0),l.write(u),l.toArray()}case"listCertificates":{const t={},e=a.readVarIntNum();t.certifiers=[];for(let r=0;r<e;r++){const e=a.read(33);t.certifiers.push(Nt(e))}const r=a.readVarIntNum();t.types=[];for(let e=0;e<r;e++){const e=a.read(32);t.types.push(_t(e))}const i=a.readVarIntNum();t.limit=i>=0?i:void 0;const n=a.readVarIntNum();t.offset=n>=0?n:void 0;const o=a.readInt8();t.privileged=-1===o?void 0:1===o;const c=a.readInt8();if(-1===c)t.privilegedReason=void 0;else{const e=a.read(c);t.privilegedReason=Tt(e)}const h=await this.wallet.listCertificates(t,s),u=new Bt;u.writeVarIntNum(h.totalCertificates);for(const t of h.certificates){const e=new Dr(t.type,t.serialNumber,t.subject,t.certifier,t.revocationOutpoint,t.fields,t.signature).toBinary();u.writeVarIntNum(e.length),u.write(e)}const l=new Bt;return l.writeUInt8(0),l.write(u.toArray()),l.toArray()}case"proveCertificate":{const t={},e={},r=a.read(32);e.type=_t(r);const i=a.read(33);e.subject=Nt(i);const n=a.read(32);e.serialNumber=_t(n);const o=a.read(33);e.certifier=Nt(o),e.revocationOutpoint=this.decodeOutpoint(a);const c=a.readVarIntNum(),h=a.read(c);e.signature=Nt(h);const u=a.readVarIntNum();e.fields={};for(let t=0;t<u;t++){const t=a.readVarIntNum(),r=a.read(t),i=Tt(r),n=a.readVarIntNum(),s=a.read(n),o=Tt(s);e.fields[i]=o}t.certificate=e;const l=a.readVarIntNum();t.fieldsToReveal=[];for(let e=0;e<l;e++){const e=a.readVarIntNum(),r=a.read(e),i=Tt(r);t.fieldsToReveal.push(i)}const d=a.read(33);t.verifier=Nt(d);const f=a.readInt8();t.privileged=-1===f?void 0:1===f;const p=a.readInt8();if(-1===p)t.privilegedReason=void 0;else{const e=a.read(p);t.privilegedReason=Tt(e)}const m=await this.wallet.proveCertificate(t,s),w=new Bt,b=Object.entries(m.keyringForVerifier);w.writeVarIntNum(b.length);for(const[t,e]of b){const r=Ot(t,"utf8");w.writeVarIntNum(r.length),w.write(r);const i=Ot(e,"base64");w.writeVarIntNum(i.length),w.write(i)}const g=new Bt;return g.writeUInt8(0),g.write(w.toArray()),g.toArray()}case"relinquishCertificate":{const t={},e=a.read(32);t.type=_t(e);const r=a.read(32);t.serialNumber=_t(r);const i=a.read(33);t.certifier=Nt(i),await this.wallet.relinquishCertificate(t,s);const n=new Bt;return n.writeUInt8(0),n.toArray()}case"discoverByIdentityKey":{const t={},e=a.read(33);t.identityKey=Nt(e);const r=a.readVarIntNum();t.limit=r>=0?r:void 0;const i=a.readVarIntNum();t.offset=i>=0?i:void 0;const n=a.readInt8();t.seekPermission=n>=0?1===n:void 0;const o=await this.wallet.discoverByIdentityKey(t,s),c=this.serializeDiscoveryResult(o),h=new Bt;return h.writeUInt8(0),h.write(c),h.toArray()}case"discoverByAttributes":{const t={},e=a.readVarIntNum();t.attributes={};for(let r=0;r<e;r++){const e=a.readVarIntNum(),r=a.read(e),i=Tt(r),n=a.readVarIntNum(),s=a.read(n),o=Tt(s);t.attributes[i]=o}const r=a.readVarIntNum();t.limit=r>=0?r:void 0;const i=a.readVarIntNum();t.offset=i>=0?i:void 0;const n=a.readInt8();t.seekPermission=n>=0?1===n:void 0;const o=await this.wallet.discoverByAttributes(t,s),c=this.serializeDiscoveryResult(o),h=new Bt;return h.writeUInt8(0),h.write(c),h.toArray()}default:throw new Error(`Method ${r} not implemented`)}}catch(t){const e=new Bt;e.writeUInt8("number"==typeof t.code?t.code:1);const r="string"==typeof t.message?t.message:"Unknown error",i=Ot(r,"utf8");e.writeVarIntNum(i.length),e.write(i);const n="string"==typeof t.stack?t.stack:"",s=Ot(n,"utf8");return e.writeVarIntNum(s.length),e.write(s),e.toArray()}}decodeProtocolID(t){const e=t.readUInt8(),r=t.readVarIntNum(),i=t.read(r);return[e,Tt(i)]}decodeString(t){const e=t.readVarIntNum(),r=t.read(e);return Tt(r)}decodeCounterparty(t){const e=t.readUInt8();if(11===e)return"self";if(12===e)return"anyone";if(0!==e){const r=t.read(32);return Nt([e,...r])}}serializeDiscoveryResult(t){const e=new Bt;e.writeVarIntNum(t.totalCertificates);for(const r of t.certificates){const t=new Dr(r.type,r.serialNumber,r.subject,r.certifier,r.revocationOutpoint,r.fields,r.signaturre).toBinary();e.writeVarIntNum(t.length),e.write(t);const i=Ot(r.certifierInfo.name,"utf8");e.writeVarIntNum(i.length),e.write(i);const n=Ot(r.certifierInfo.iconUrl,"utf8");e.writeVarIntNum(n.length),e.write(n);const s=Ot(r.certifierInfo.description,"utf8");e.writeVarIntNum(s.length),e.write(s),e.writeUInt8(r.certifierInfo.trust);const a=Object.entries(r.publiclyRevealedKeyring);e.writeVarIntNum(a.length);for(const[t,r]of a){const i=Ot(t,"utf8");e.writeVarIntNum(i.length),e.write(i);const n=Ot(r,"base64");e.writeVarIntNum(n.length),e.write(n)}const o=Object.entries(r.decryptedFields);e.writeVarIntNum(o.length);for(const[t,r]of o){const i=Ot(t,"utf8");e.writeVarIntNum(i.length),e.write(i);const n=Ot(r,"utf8");e.writeVarIntNum(n.length),e.write(n)}}return e.toArray()}decodeKeyRelatedParams(t){const e={};e.protocolID=this.decodeProtocolID(t);const r=t.readVarIntNum(),i=t.read(r);e.keyID=Tt(i),e.counterparty=this.decodeCounterparty(t);const n=t.readInt8();e.privileged=-1===n?void 0:1===n;const s=t.readInt8();if(-1===s)e.privilegedReason=void 0;else{const r=t.read(s);e.privilegedReason=Tt(r)}return e}}class Wr extends Dr{masterKeyring;constructor(t,e,r,i,n,s,a,o){super(t,e,r,i,n,s,o);for(const t of Object.keys(s))if(void 0===a[t]||""===a[t])throw new Error(`Master keyring must contain a value for every field. Missing or empty key for field: "${t}".`);this.masterKeyring=a}static async createCertificateFields(t,e,r,i,n){const s={},a={};for(const[o,c]of Object.entries(r)){const r=Pe.fromRandom(),h=r.encrypt(Ot(c,"utf8"));s[o]=_t(h);const{ciphertext:u}=await t.encrypt({plaintext:r.toArray(),...Dr.getCertificateFieldEncryptionDetails(o),counterparty:e,privileged:i,privilegedReason:n});a[o]=_t(u)}return{certificateFields:s,masterKeyring:a}}static async createKeyringForVerifier(t,e,r,i,n,s,a,o,c){if(!Array.isArray(n))throw new Error("fieldsToReveal must be an array of strings");const h={};for(const u of n){if(void 0===i[u]||null===i[u]||""===i[u])throw new Error(`Fields to reveal must be a subset of the certificate fields. Missing the "${u}" field.`);const n=(await this.decryptField(t,s,u,i[u],e,o,c)).fieldRevelationKey,{ciphertext:l}=await t.encrypt({plaintext:n,...Dr.getCertificateFieldEncryptionDetails(u,a),counterparty:r,privileged:o,privilegedReason:c});h[u]=_t(l)}return h}static async issueCertificateForSubject(t,e,r,i,n=async t=>"Certificate revocation not tracked.",s){const a=s??_t(Zt(32)),{certificateFields:o,masterKeyring:c}=await this.createCertificateFields(t,e,r),h=await n(a),u=new Wr(i,a,e,(await t.getPublicKey({identityKey:!0})).publicKey,h,o,c);return await u.sign(t),u}static async decryptFields(t,e,r,i,n,s){if(null==e||0===Object.keys(e).length)throw new Error("A MasterCertificate must have a valid masterKeyring!");try{const a={};for(const o of Object.keys(r))a[o]=(await this.decryptField(t,e,o,r[o],i,n,s)).decryptedFieldValue;return a}catch{throw new Error("Failed to decrypt all master certificate fields.")}}static async decryptField(t,e,r,i,n,s,a){if(null==e||0===Object.keys(e).length)throw new Error("A MasterCertificate must have a valid masterKeyring!");try{const{plaintext:o}=await t.decrypt({ciphertext:Ot(e[r],"base64"),...Dr.getCertificateFieldEncryptionDetails(r),counterparty:n,privileged:s,privilegedReason:a}),c=new Pe(o).decrypt(Ot(i,"base64"));return{fieldRevelationKey:o,decryptedFieldValue:Tt(c)}}catch{throw new Error("Failed to decrypt certificate field!")}}}class Xr extends Dr{keyring;decryptedFields;constructor(t,e,r,i,n,s,a,o,c){super(t,e,r,i,n,s,o),this.keyring=a,this.decryptedFields=c}async decryptFields(t,e,r){if(null==this.keyring||0===Object.keys(this.keyring).length)throw new Error("A keyring is required to decrypt certificate fields for the verifier.");try{const i={};for(const n in this.keyring){const{plaintext:s}=await t.decrypt({ciphertext:Ot(this.keyring[n],"base64"),...Dr.getCertificateFieldEncryptionDetails(n,this.serialNumber),counterparty:this.subject,privileged:e,privilegedReason:r}),a=new Pe(s).decrypt(Ot(this.fields[n],"base64"));i[n]=Tt(a)}return i}catch(t){throw new Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(t instanceof Error?t.message:t)}`)}}}class Gr extends Mr{keyDeriver;constructor(t){if(super(t),t instanceof Ar)this.keyDeriver=t;else{if(!("string"==typeof t||t instanceof re))throw new Error("Invalid key deriver provided");this.keyDeriver=new Ar(t)}}async isAuthenticated(){throw new Error("not implemented")}async waitForAuthentication(){throw new Error("not implemented")}async getNetwork(){throw new Error("not implemented")}async getVersion(){throw new Error("not implemented")}async getPublicKey(t){if(!0===t.privileged)throw new Error("no privilege support");if(!0===t.identityKey){if(null===this.keyDeriver||void 0===this.keyDeriver)throw new Error("keyDeriver is not initialized");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==t.protocolID||"string"!=typeof t.keyID||""===t.keyID.trim())throw new Error("protocolID and keyID are required if identityKey is false or undefined.");if(null===this.keyDeriver||void 0===this.keyDeriver)throw new Error("keyDeriver is not initialized");return{publicKey:this.keyDeriver.derivePublicKey(t.protocolID,t.keyID,"string"==typeof t.counterparty&&""!==t.counterparty.trim()?t.counterparty:"self",Boolean(t.forSelf)).toString()}}async createAction(){throw new Error("not implemented")}async signAction(){throw new Error("not implemented")}async abortAction(){throw new Error("not implemented")}async listActions(){throw new Error("not implemented")}async internalizeAction(){throw new Error("not implemented")}async listOutputs(){throw new Error("not implemented")}async relinquishOutput(){throw new Error("not implemented")}async acquireCertificate(){throw new Error("not implemented")}async listCertificates(){throw new Error("not implemented")}async proveCertificate(){throw new Error("not implemented")}async relinquishCertificate(){throw new Error("not implemented")}async discoverByIdentityKey(){throw new Error("not implemented")}async discoverByAttributes(){throw new Error("not implemented")}async getHeight(){throw new Error("not implemented")}async getHeaderForHeight(){throw new Error("not implemented")}}class Yr{sessionNonceToSession;identityKeyToNonces;constructor(){this.sessionNonceToSession=new Map,this.identityKeyToNonces=new Map}addSession(t){if("string"!=typeof t.sessionNonce)throw new Error("Invalid session: sessionNonce is required to add a session.");if(this.sessionNonceToSession.set(t.sessionNonce,t),"string"==typeof t.peerIdentityKey){let e=this.identityKeyToNonces.get(t.peerIdentityKey);null==e&&(e=new Set,this.identityKeyToNonces.set(t.peerIdentityKey,e)),e.add(t.sessionNonce)}}updateSession(t){this.removeSession(t),this.addSession(t)}getSession(t){const e=this.sessionNonceToSession.get(t);if(null!=e)return e;const r=this.identityKeyToNonces.get(t);if(null==r||0===r.size)return;let i;for(const t of r){const e=this.sessionNonceToSession.get(t);null!=e&&(null==i||(e.lastUpdate??0)>(i.lastUpdate??0))&&(i=e)}return i}removeSession(t){if("string"==typeof t.sessionNonce&&this.sessionNonceToSession.delete(t.sessionNonce),"string"==typeof t.peerIdentityKey){const e=this.identityKeyToNonces.get(t.peerIdentityKey);null!=e&&(e.delete(t.sessionNonce??""),0===e.size&&this.identityKeyToNonces.delete(t.peerIdentityKey))}}hasSession(t){if(this.sessionNonceToSession.has(t))return!0;const e=this.identityKeyToNonces.get(t);return!(null==e)&&e.size>0}}async function Jr(t,e,r="self"){const i=Ot(t,"base64"),n=i.slice(0,16),s=i.slice(16),{valid:a}=await e.verifyHmac({data:n,hmac:s,protocolID:[2,"server hmac"],keyID:Tt(n),counterparty:r});return a}async function Zr(t,e="self"){const r=Zt(16),{hmac:i}=await t.createHmac({protocolID:[2,"server hmac"],keyID:Tt(r),data:r,counterparty:e});return _t([...r,...i])}const Qr=async(t,e,r)=>{const i=await t.listCertificates({certifiers:e.certifiers,types:Object.keys(e.types)});return await Promise.all(i.certificates.map((async i=>{const{keyringForVerifier:n}=await t.proveCertificate({certificate:i,fieldsToReveal:e.types[i.type],verifier:r});return new Xr(i.type,i.serialNumber,i.subject,i.certifier,i.revocationOutpoint,i.fields,n,i.signature)})))},ti=async(t,e,r)=>{if(null==e.certificates||0===e.certificates.length)throw new Error("No certificates were provided in the AuthMessage.");await Promise.all(e.certificates.map((async i=>{if(i.subject!==e.identityKey)throw new Error(`The subject of one of your certificates ("${i.subject}") is not the same as the request sender ("${e.identityKey}").`);const n=new Xr(i.type,i.serialNumber,i.subject,i.certifier,i.revocationOutpoint,i.fields,i.keyring,i.signature);if(!await n.verify())throw new Error(`The signature for the certificate with serial number ${n.serialNumber} is invalid!`);if(null!=r){const{certifiers:t,types:e}=r;if(!t.includes(n.certifier))throw new Error(`Certificate with serial number ${n.serialNumber} has an unrequested certifier: ${n.certifier}`);if(null==e[n.type])throw new Error(`Certificate with type ${n.type} was not requested`)}await n.decryptFields(t)})))},ei="0.1";class ri{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;constructor(t,e,r,i,n){this.wallet=t,this.transport=e,this.certificatesToRequest=r??{certifiers:[],types:{}},this.transport.onData(this.handleIncomingMessage.bind(this)).catch((t=>{throw t})),this.sessionManager=null!=i?i:new Yr,this.autoPersistLastSession=!1!==n}async toPeer(t,e,r){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof e&&(e=this.lastInteractedWithPeer);const i=await this.getAuthenticatedSession(e,r),n=_t(Zt(32)),{signature:s}=await this.wallet.createSignature({data:t,protocolID:[2,"auth message signature"],keyID:`${n} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey}),a={version:ei,messageType:"general",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,nonce:n,yourNonce:i.peerNonce,payload:t,signature:s};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(a)}catch(t){const e=new Error(`Failed to send message to peer ${i.peerIdentityKey??"unknown"}: ${String(t.message)}`);throw e.stack=t.stack,e}}async requestCertificates(t,e,r=1e4){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof e&&(e=this.lastInteractedWithPeer);const i=await this.getAuthenticatedSession(e,r),n=_t(Zt(32)),{signature:s}=await this.wallet.createSignature({data:Ot(JSON.stringify(t),"utf8"),protocolID:[2,"auth message signature"],keyID:`${n} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey}),a={version:ei,messageType:"certificateRequest",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,nonce:n,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,requestedCertificates:t,signature:s};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(a)}catch(t){throw new Error(`Failed to send certificate request message to peer ${i.peerIdentityKey??"unknown"}: ${String(t.message)}`)}}async getAuthenticatedSession(t,e){if(void 0===this.transport)throw new Error("Peer transport is not connected!");let r;if("string"==typeof t&&(r=this.sessionManager.getSession(t)),null==r||!r.isAuthenticated){const i=await this.initiateHandshake(t,e);if(r=this.sessionManager.getSession(i),null==r||!r.isAuthenticated)throw new Error("Unable to establish mutual authentication with peer!")}return r}listenForGeneralMessages(t){const e=this.callbackIdCounter++;return this.onGeneralMessageReceivedCallbacks.set(e,t),e}stopListeningForGeneralMessages(t){this.onGeneralMessageReceivedCallbacks.delete(t)}listenForCertificatesReceived(t){const e=this.callbackIdCounter++;return this.onCertificatesReceivedCallbacks.set(e,t),e}stopListeningForCertificatesReceived(t){this.onCertificatesReceivedCallbacks.delete(t)}listenForCertificatesRequested(t){const e=this.callbackIdCounter++;return this.onCertificateRequestReceivedCallbacks.set(e,t),e}stopListeningForCertificatesRequested(t){this.onCertificateRequestReceivedCallbacks.delete(t)}async initiateHandshake(t,e=1e4){const r=await Zr(this.wallet),i=Date.now();this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:r,peerIdentityKey:t,lastUpdate:i});const n={version:ei,messageType:"initialRequest",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,initialNonce:r,requestedCertificates:this.certificatesToRequest};return await this.transport.send(n),await this.waitForInitialResponse(r,e)}async waitForInitialResponse(t,e=1e4){return await new Promise(((r,i)=>{const n=this.listenForInitialResponse(t,(t=>{clearTimeout(s),this.stopListeningForInitialResponses(n),r(t)})),s=setTimeout((()=>{this.stopListeningForInitialResponses(n),i(new Error("Initial response timed out."))}),e)}))}listenForInitialResponse(t,e){const r=this.callbackIdCounter++;return this.onInitialResponseReceivedCallbacks.set(r,{callback:e,sessionNonce:t}),r}stopListeningForInitialResponses(t){this.onInitialResponseReceivedCallbacks.delete(t)}async handleIncomingMessage(t){if("string"!=typeof t.version||t.version!==ei)throw new Error(`Invalid or unsupported message auth version! Received: ${t.version}, expected: ${ei}`);switch(t.messageType){case"initialRequest":await this.processInitialRequest(t);break;case"initialResponse":await this.processInitialResponse(t);break;case"certificateRequest":await this.processCertificateRequest(t);break;case"certificateResponse":await this.processCertificateResponse(t);break;case"general":await this.processGeneralMessage(t);break;default:throw new Error(`Unknown message type of ${String(t.messageType)} from ${String(t.identityKey)}`)}}async processInitialRequest(t){if("string"!=typeof t.identityKey||"string"!=typeof t.initialNonce||""===t.initialNonce)throw new Error("Missing required fields in initialRequest message.");const e=await Zr(this.wallet),r=Date.now();let i;this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:e,peerNonce:t.initialNonce,peerIdentityKey:t.identityKey,lastUpdate:r}),null!=t.requestedCertificates&&Array.isArray(t.requestedCertificates.certifiers)&&t.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach((e=>{e(t.identityKey,t.requestedCertificates)})):i=await Qr(this.wallet,t.requestedCertificates,t.identityKey));const{signature:n}=await this.wallet.createSignature({data:Ot(t.initialNonce+e,"base64"),protocolID:[2,"auth message signature"],keyID:`${t.initialNonce} ${e}`,counterparty:t.identityKey}),s={version:ei,messageType:"initialResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,initialNonce:e,yourNonce:t.initialNonce,certificates:i,requestedCertificates:this.certificatesToRequest,signature:n};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=t.identityKey),await this.transport.send(s)}async processInitialResponse(t){if(!await Jr(t.yourNonce,this.wallet))throw new Error(`Initial response nonce verification failed from peer: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Peer session not found for peer: ${t.identityKey}`);const r=Ot((e.sessionNonce??"")+(t.initialNonce??""),"base64"),{valid:i}=await this.wallet.verifySignature({data:r,signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${e.sessionNonce??""} ${t.initialNonce??""}`,counterparty:t.identityKey});if(!i)throw new Error(`Unable to verify initial response signature for peer: ${t.identityKey}`);if(e.peerNonce=t.initialNonce,e.peerIdentityKey=t.identityKey,e.isAuthenticated=!0,e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),this.certificatesToRequest?.certifiers?.length>0&&t.certificates?.length>0&&(await ti(this.wallet,t,this.certificatesToRequest),this.onCertificatesReceivedCallbacks.forEach((e=>e(t.identityKey,t.certificates)))),this.lastInteractedWithPeer=t.identityKey,this.onInitialResponseReceivedCallbacks.forEach((t=>{t.sessionNonce===e.sessionNonce&&t.callback(e.sessionNonce)})),null!=t.requestedCertificates&&Array.isArray(t.requestedCertificates.certifiers)&&t.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach((e=>{e(t.identityKey,t.requestedCertificates)}));else{const e=await Qr(this.wallet,t.requestedCertificates,t.identityKey);await this.sendCertificateResponse(t.identityKey,e)}}async processCertificateRequest(t){if(!await Jr(t.yourNonce,this.wallet))throw new Error(`Unable to verify nonce for certificate request message from: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Session not found for nonce: ${t.yourNonce}`);const{valid:r}=await this.wallet.verifySignature({data:Ot(JSON.stringify(t.requestedCertificates),"utf8"),signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:e.peerIdentityKey});if(!r)throw new Error(`Invalid signature in certificate request message from ${e.peerIdentityKey}`);if(e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),null!=t.requestedCertificates&&Array.isArray(t.requestedCertificates.certifiers)&&t.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach((e=>{e(t.identityKey,t.requestedCertificates)}));else{const e=await Qr(this.wallet,t.requestedCertificates,t.identityKey);await this.sendCertificateResponse(t.identityKey,e)}}async sendCertificateResponse(t,e){const r=await this.getAuthenticatedSession(t),i=_t(Zt(32)),{signature:n}=await this.wallet.createSignature({data:Ot(JSON.stringify(e),"utf8"),protocolID:[2,"auth message signature"],keyID:`${i} ${r.peerNonce??""}`,counterparty:r.peerIdentityKey}),s={version:ei,messageType:"certificateResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,nonce:i,initialNonce:r.sessionNonce,yourNonce:r.peerNonce,certificates:e,signature:n};r.lastUpdate=Date.now(),this.sessionManager.updateSession(r);try{await this.transport.send(s)}catch(t){const e=t instanceof Error?t.message:String(t);throw new Error(`Failed to send certificate response message to peer ${r.peerIdentityKey??"unknown"}: ${e}`)}}async processCertificateResponse(t){if(!await Jr(t.yourNonce,this.wallet))throw new Error(`Unable to verify nonce for certificate response from: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Session not found for nonce: ${t.yourNonce}`);const{valid:r}=await this.wallet.verifySignature({data:Ot(JSON.stringify(t.certificates),"utf8"),signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:t.identityKey});if(!r)throw new Error(`Unable to verify certificate response signature for peer: ${t.identityKey}`);await ti(this.wallet,t,t.requestedCertificates),this.onCertificatesReceivedCallbacks.forEach((e=>{e(t.identityKey,t.certificates??[])})),e.lastUpdate=Date.now(),this.sessionManager.updateSession(e)}async processGeneralMessage(t){if(!await Jr(t.yourNonce,this.wallet))throw new Error(`Unable to verify nonce for general message from: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Session not found for nonce: ${t.yourNonce}`);const{valid:r}=await this.wallet.verifySignature({data:t.payload,signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:e.peerIdentityKey});if(!r)throw new Error(`Invalid signature in generalMessage from ${e.peerIdentityKey}`);e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),this.lastInteractedWithPeer=t.identityKey,this.onGeneralMessageReceivedCallbacks.forEach((e=>{e(t.identityKey,t.payload??[])}))}}const ii="undefined"!=typeof window?fetch.bind(window):fetch;class ni{onDataCallback;fetchClient;baseUrl;constructor(t,e=ii){this.fetchClient=e,this.baseUrl=t}async send(t){if(!this.onDataCallback)throw new Error("Listen before you start speaking. God gave you two ears and one mouth for a reason.");if("general"!==t.messageType)return new Promise((async(e,r)=>{try{const r=this.fetchClient(`${this.baseUrl}/.well-known/auth`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});"initialRequest"!==t.messageType&&e();const i=await r;if(!i.ok||!this.onDataCallback)throw new Error("HTTP server failed to authenticate");{const t=await i.json();this.onDataCallback(t)}"initialRequest"===t.messageType&&e()}catch(t){return void r(t)}}));{const e=this.deserializeRequestPayload(t.payload),r=`${this.baseUrl}${e.urlPostfix}`;let i=e;if("object"!=typeof e.headers&&(i.headers={}),i.headers["x-bsv-auth-version"]=t.version,i.headers["x-bsv-auth-identity-key"]=t.identityKey,i.headers["x-bsv-auth-nonce"]=t.nonce,i.headers["x-bsv-auth-your-nonce"]=t.yourNonce,i.headers["x-bsv-auth-signature"]=Nt(t.signature),i.headers["x-bsv-auth-request-id"]=e.requestId,i.body){const t=i.headers;if(!t["content-type"])throw new Error("Content-Type header is required for requests with a body.");const e=t["content-type"];e.includes("application/json")||e.includes("application/x-www-form-urlencoded")||e.includes("text/plain")?i.body=Tt(i.body):i.body=new Uint8Array(i.body)}const n=await this.fetchClient(r,{method:i.method,headers:i.headers,body:i.body});if(500===n.status&&!n.headers.get("x-bsv-auth-request-id")){const t=await n.json();throw new Error(`HTTP ${n.status} - ${JSON.stringify(t)}`)}const s=await n.arrayBuffer(),a=new Bt;a.write(Ot(n.headers.get("x-bsv-auth-request-id"),"base64")),a.writeVarIntNum(n.status);const o=[];n.headers.forEach(((t,e)=>{const r=e.toLowerCase();!r.startsWith("x-bsv-")&&"authorization"!==r||r.startsWith("x-bsv-auth")||o.push([r,t])})),o.sort((([t],[e])=>t.localeCompare(e))),a.writeVarIntNum(o.length);for(let t=0;t<o.length;t++){const e=Ot(o[t][0],"utf8");a.writeVarIntNum(e.length),a.write(e);const r=Ot(o[t][1],"utf8");a.writeVarIntNum(r.length),a.write(r)}if(s){const t=Array.from(new Uint8Array(s));a.writeVarIntNum(t.length),a.write(t)}else a.writeVarIntNum(-1);const c={version:n.headers.get("x-bsv-auth-version"),messageType:"certificateRequest"===n.headers.get("x-bsv-auth-message-type")?"certificateRequest":"general",identityKey:n.headers.get("x-bsv-auth-identity-key"),nonce:n.headers.get("x-bsv-auth-nonce"),yourNonce:n.headers.get("x-bsv-auth-your-nonce"),requestedCertificates:JSON.parse(n.headers.get("x-bsv-auth-requested-certificates")),payload:a.toArray(),signature:Ot(n.headers.get("x-bsv-auth-signature"),"hex")};if(!c.version)throw new Error("HTTP server failed to authenticate");this.onDataCallback(c)}}async onData(t){this.onDataCallback=e=>{t(e)}}deserializeRequestPayload(t){const e=new Ut(t),r=_t(e.read(32)),i=e.readVarIntNum();let n="GET";i>0&&(n=Tt(e.read(i)));const s=e.readVarIntNum();let a="";s>0&&(a=Tt(e.read(s)));const o=e.readVarIntNum();let c="";o>0&&(c=Tt(e.read(o)));const h={},u=e.readVarIntNum();if(u>0)for(let t=0;t<u;t++){const t=e.readVarIntNum(),r=e.read(t),i=Tt(r),n=e.readVarIntNum(),s=e.read(n),a=Tt(s);h[i]=a}let l;const d=e.readVarIntNum();return d>0&&(l=e.read(d)),{urlPostfix:a+c,method:n,headers:h,body:l,requestId:r}}}class si{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;peers={};constructor(t,e,r){this.wallet=t,this.requestedCertificates=e,this.sessionManager=r||new Yr}async fetch(t,e={}){if("number"==typeof e.retryCounter){if(e.retryCounter<=0)throw new Error("Request failed after maximum number of retries.");e.retryCounter--}const r=await new Promise((async(r,i)=>{try{const{method:n="GET",headers:s={},body:a}=e,o=new URL(t),c=o.origin;let h;if(void 0===this.peers[c]){const t=new ni(c);h={peer:new ri(this.wallet,t,this.requestedCertificates,this.sessionManager),pendingCertificateRequests:[]},this.peers[c]=h,this.peers[c].peer.listenForCertificatesReceived(((t,e)=>{this.certificatesReceived.push(...e)})),this.peers[c].peer.listenForCertificatesRequested((async(t,e)=>{try{this.peers[c].pendingCertificateRequests.push(!0);const r=await Qr(this.wallet,e,t);await this.peers[c].peer.sendCertificateResponse(t,r)}finally{await new Promise((t=>setTimeout(t,500))),this.peers[c].pendingCertificateRequests.shift()}}))}else{if(!1===this.peers[c].supportsMutualAuth){try{const i=await this.handleFetchAndValidate(t,e,this.peers[c]);r(i)}catch(t){i(t)}return}h=this.peers[c]}const u=Zt(32),l=_t(u),d=await this.serializeRequest(n,s,a,o,u);this.callbacks[l]={resolve:r,reject:i};const f=h.peer.listenForGeneralMessages(((t,e)=>{const r=new Ut(e);if(_t(r.read(32))!==l)return;h.peer.stopListeningForGeneralMessages(f),this.peers[c].identityKey=t,this.peers[c].supportsMutualAuth=!0;const i=r.readVarIntNum(),n={},s=r.readVarIntNum();if(s>0)for(let t=0;t<s;t++){const t=r.readVarIntNum(),e=r.read(t),i=Tt(e),s=r.readVarIntNum(),a=r.read(s),o=Tt(a);n[i]=o}let a;n["x-bsv-auth-identity-key"]=t;const o=r.readVarIntNum();o>0&&(a=r.read(o));const u=new Response(a?new Uint8Array(a):null,{status:i,statusText:`${i}`,headers:new Headers(n)});this.callbacks[l].resolve(u),delete this.callbacks[l]}));h.pendingCertificateRequests.length>0&&await new Promise((t=>{setInterval((()=>{0===h.pendingCertificateRequests.length&&t()}),100)})),await h.peer.toPeer(d.toArray(),h.identityKey).catch((async n=>{if(n.message.includes("Session not found for nonce")){delete this.peers[c],e.retryCounter??=3;const i=await this.fetch(t,e);r(i)}else if(n.message.includes("HTTP server failed to authenticate"))try{const i=await this.handleFetchAndValidate(t,e,h);return void r(i)}catch(t){i(t)}else i(n)}))}catch(t){i(t)}}));return 402===r.status?await this.handlePaymentAndRetry(t,e,r):r}async sendCertificateRequest(t,e){const r=new URL(t).origin;let i;if(void 0!==this.peers[r])i={peer:this.peers[r].peer};else{const t=new ni(r);i={peer:new ri(this.wallet,t,this.requestedCertificates,this.sessionManager)},this.peers[r]=i}return await new Promise((async(t,r)=>{const n=i.peer.listenForCertificatesReceived(((e,r)=>{i.peer.stopListeningForCertificatesReceived(n),this.certificatesReceived.push(...r),t(r)}));try{await i.peer.requestCertificates(e,i.identityKey)}catch(t){i.peer.stopListeningForCertificatesReceived(n),r(t)}}))}consumeReceivedCertificates(){return this.certificatesReceived.splice(0)}async serializeRequest(t,e,r,i,n){const s=new Bt;if(s.write(n),s.writeVarIntNum(t.length),s.write(Ot(t)),i.pathname.length>0){const t=Ot(i.pathname);s.writeVarIntNum(t.length),s.write(t)}else s.writeVarIntNum(-1);if(i.search.length>0){const t=Ot(i.search);s.writeVarIntNum(t.length),s.write(t)}else s.writeVarIntNum(-1);const a=[];for(let[t,r]of Object.entries(e))if(t=t.toLowerCase(),t.startsWith("x-bsv-")||"authorization"===t){if(t.startsWith("x-bsv-auth"))throw new Error("No BSV auth headers allowed here!");a.push([t,r])}else{if(!t.startsWith("content-type"))throw new Error("Unsupported header in the simplified fetch implementation. Only content-type, authorization, and x-bsv-* headers are supported.");r=r.split(";")[0].trim(),a.push([t,r])}a.sort((([t],[e])=>t.localeCompare(e))),s.writeVarIntNum(a.length);for(let t=0;t<a.length;t++){const e=Ot(a[t][0],"utf8");s.writeVarIntNum(e.length),s.write(e);const r=Ot(a[t][1],"utf8");s.writeVarIntNum(r.length),s.write(r)}if(["POST","PUT","PATCH","DELETE"].includes(t.toUpperCase())&&void 0===r){const t=a.find((([t])=>"content-type"===t));r=t&&t[1].includes("application/json")?"{}":""}if(r){const t=await this.normalizeBodyToNumberArray(r);s.writeVarIntNum(t.length),s.write(t)}else s.writeVarIntNum(-1);return s}async handleFetchAndValidate(t,e,r){const i=await fetch(t,e);if(i.headers.forEach((t=>{if(t.toLocaleLowerCase().startsWith("x-bsv"))throw new Error("The server is trying to claim it has been authenticated when it has not!")})),i.ok)return r.supportsMutualAuth=!1,i;throw new Error(`Request failed with status: ${i.status}`)}async handlePaymentAndRetry(t,e={},r){const i=r.headers.get("x-bsv-payment-version");if(!i||"1.0"!==i)throw new Error(`Unsupported x-bsv-payment-version response header. Client version: 1.0, Server version: ${i}`);const n=r.headers.get("x-bsv-payment-satoshis-required");if(!n)throw new Error("Missing x-bsv-payment-satoshis-required response header.");const s=parseInt(n);if(isNaN(s)||s<=0)throw new Error("Invalid x-bsv-payment-satoshis-required response header value.");const a=r.headers.get("x-bsv-auth-identity-key");if(!a)throw new Error("Missing x-bsv-auth-identity-key response header.");const o=r.headers.get("x-bsv-payment-derivation-prefix");if("string"!=typeof o||o.length<1)throw new Error("Missing x-bsv-payment-derivation-prefix response header.");const c=await Zr(this.wallet),{publicKey:h}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${o} ${c}`,counterparty:a}),u=(new Ve).lock(Gt.fromString(h).toAddress()).toHex(),{tx:l}=await this.wallet.createAction({description:`Payment for request to ${new URL(t).origin}`,outputs:[{satoshis:s,lockingScript:u,customInstructions:JSON.stringify({derivationPrefix:o,derivationSuffix:c,payee:a}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}});return e.headers=e.headers||{},e.headers["x-bsv-payment"]=JSON.stringify({derivationPrefix:o,derivationSuffix:c,transaction:_t(l)}),e.retryCounter??=3,this.fetch(t,e)}async normalizeBodyToNumberArray(t){if(null==t)return[];if("object"==typeof t)return Ot(JSON.stringify(t,"utf8"));if(Array.isArray(t)&&t.every((t=>"number"==typeof t)))return t;if("string"==typeof t)return Ot(t,"utf8");if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)){const e=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer);return Array.from(e)}if(t instanceof Blob){const e=await t.arrayBuffer();return Array.from(new Uint8Array(e))}if(t instanceof FormData){const e=[];t.forEach(((t,r)=>{e.push([r,t.toString()])}));const r=new URLSearchParams(e).toString();return Ot(r,"utf8")}if(t instanceof URLSearchParams)return Ot(t.toString(),"utf8");if(t instanceof ReadableStream)throw new Error("ReadableStream cannot be directly converted to number[].");throw new Error("Unsupported body type in this SimplifiedFetch implementation.")}}class ai{pushDrop;static decode(t){const e=Ue.decode(t);if(e.fields.length<4)throw new Error("Invalid SHIP/SLAP advertisement!");const r=Tt(e.fields[0]);if("SHIP"!==r&&"SLAP"!==r)throw new Error("Invalid protocol type!");return{protocol:r,identityKey:Nt(e.fields[1]),domain:Tt(e.fields[2]),topicOrService:Tt(e.fields[3])}}constructor(t){this.pushDrop=new Ue(t)}async lock(t,e,r){const{publicKey:i}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([Ot(t,"utf8"),Ot(i,"hex"),Ot(e,"utf8"),Ot(r,"utf8")],[2,"SHIP"===t?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}unlock(t){return this.pushDrop.unlock([2,"SHIP"===t?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}}const oi=["https://users.bapp.dev"],ci=["https://testnet-users.bapp.dev"];class hi{fetchClient;allowHTTP;constructor(t=fetch,e=!1){this.fetchClient=t,this.allowHTTP=e}async lookup(t,e,r=5e3){if(!t.startsWith("https:")&&!this.allowHTTP)throw new Error('HTTPS facilitator can only use URLs that start with "https:"');const i=new Promise(((t,e)=>setTimeout((()=>e(new Error("Request timed out"))),r))),n=fetch(`${t}/lookup`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:e.service,query:e.query})}),s=await Promise.race([n,i]);if(s.ok)return await s.json();throw new Error("Failed to facilitate lookup")}}class ui{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;constructor(t={}){this.networkPreset=t.networkPreset??"mainnet",this.facilitator=t.facilitator??new hi(void 0,"local"===this.networkPreset),this.slapTrackers=t.slapTrackers??("mainnet"===this.networkPreset?oi:ci),this.hostOverrides=t.hostOverrides??{},this.additionalHosts=t.additionalHosts??{}}async query(t,e){let r=[];if(r="ls_slap"===t.service?"local"===this.networkPreset?["http://localhost:8080"]:this.slapTrackers:null!=this.hostOverrides[t.service]?this.hostOverrides[t.service]:"local"===this.networkPreset?["http://localhost:8080"]:await this.findCompetentHosts(t.service),this.additionalHosts[t.service]?.length>0&&(r=[...r,...this.additionalHosts[t.service]]),r.length<1)throw new Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${t.service}`);const i=(await Promise.allSettled(r.map((async r=>await this.facilitator.lookup(r,t,e))))).filter((t=>"fulfilled"===t.status)).map((t=>t.value));if(0===i.length)throw new Error("No successful responses from any hosts");if("freeform"===i[0].type)return i[0];const n=new Map;for(const t of i)if("output-list"===t.type)try{for(const e of t.outputs)try{const t=String(ir.fromBEEF(e.beef).id("hex"));if(""!==t){const r=`${String(t)}.${String(e.outputIndex)}`;n.set(r,e)}else console.warn("Invalid transaction ID:",t)}catch{continue}}catch(t){}return{type:"output-list",outputs:Array.from(n.values())}}async findCompetentHosts(t){const e={service:"ls_slap",query:{service:t}},r=await Promise.allSettled(this.slapTrackers.map((async t=>await this.facilitator.lookup(t,e,5e3)))),i=new Set;for(const e of r)if("fulfilled"===e.status){const r=e.value;if("output-list"!==r.type)continue;for(const e of r.outputs)try{const r=ir.fromBEEF(e.beef).outputs[e.outputIndex].lockingScript,n=ai.decode(r);if(n.topicOrService!==t||"SLAP"!==n.protocol)continue;i.add(n.domain)}catch{continue}}return[...i]}}class li{httpClient;allowHTTP;constructor(t=fetch,e=!1){this.httpClient=t,this.allowHTTP=e}async send(t,e){if(console.log(t),!t.startsWith("https:")&&!this.allowHTTP)throw new Error('HTTPS facilitator can only use URLs that start with "https:"');const r=await fetch(`${t}/submit`,{method:"POST",headers:{"Content-Type":"application/octet-stream","X-Topics":JSON.stringify(e.topics)},body:new Uint8Array(e.beef)});if(r.ok)return await r.json();throw new Error("Failed to facilitate broadcast")}}class di{topics;facilitator;resolver;requireAcknowledgmentFromAllHostsForTopics;requireAcknowledgmentFromAnyHostForTopics;requireAcknowledgmentFromSpecificHostsForTopics;networkPreset;constructor(t,e={}){if(0===t.length)throw new Error("At least one topic is required for broadcast.");if(t.some((t=>!t.startsWith("tm_"))))throw new Error('Every topic must start with "tm_".');this.topics=t,this.networkPreset=e.networkPreset??"mainnet",this.facilitator=e.facilitator??new li(void 0,"local"===this.networkPreset),this.resolver=e.resolver??new ui({networkPreset:this.networkPreset}),this.requireAcknowledgmentFromAllHostsForTopics=e.requireAcknowledgmentFromAllHostsForTopics??[],this.requireAcknowledgmentFromAnyHostForTopics=e.requireAcknowledgmentFromAnyHostForTopics??"all",this.requireAcknowledgmentFromSpecificHostsForTopics=e.requireAcknowledgmentFromSpecificHostsForTopics??{}}async broadcast(t){let e;console.log(t);try{e=t.toBEEF()}catch(t){throw new Error("Transactions sent via SHIP to Overlay Services must be serializable to BEEF format.")}const r=await this.findInterestedHosts();if(console.log(r),0===Object.keys(r).length)return{status:"error",code:"ERR_NO_HOSTS_INTERESTED",description:`No ${this.networkPreset} hosts are interested in receiving this transaction.`};const i=Object.entries(r).map((async([t,r])=>{try{const i=await this.facilitator.send(t,{beef:e,topics:[...r]});if(null==i||0===Object.keys(i).length)throw new Error("Steak has no topics.");return{host:t,success:!0,steak:i}}catch(e){return console.error(e),{host:t,success:!1,error:e}}})),n=(await Promise.all(i)).filter((t=>t.success));if(0===n.length)return{status:"error",code:"ERR_ALL_HOSTS_REJECTED",description:`All ${this.networkPreset} topical hosts have rejected the transaction.`};const s={};for(const t of n){const e=t.host,r=t.steak,i=new Set;for(const[t,e]of Object.entries(r)){const r=e.outputsToAdmit,n=e.coinsToRetain,s=e.coinsRemoved;(r?.length>0||n?.length>0||s?.length>0)&&i.add(t)}s[e]=i}let a,o,c,h;return"all"===this.requireAcknowledgmentFromAllHostsForTopics?(a=this.topics,o="all"):"any"===this.requireAcknowledgmentFromAllHostsForTopics?(a=this.topics,o="any"):Array.isArray(this.requireAcknowledgmentFromAllHostsForTopics)?(a=this.requireAcknowledgmentFromAllHostsForTopics,o="all"):(a=this.topics,o="all"),a.length>0&&!this.checkAcknowledgmentFromAllHosts(s,a,o)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ALL_HOSTS_FAILED",description:"Not all hosts acknowledged the required topics."}:("all"===this.requireAcknowledgmentFromAnyHostForTopics?(c=this.topics,h="all"):"any"===this.requireAcknowledgmentFromAnyHostForTopics?(c=this.topics,h="any"):Array.isArray(this.requireAcknowledgmentFromAnyHostForTopics)?(c=this.requireAcknowledgmentFromAnyHostForTopics,h="all"):(c=[],h="all"),c.length>0&&!this.checkAcknowledgmentFromAnyHost(s,c,h)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ANY_HOST_FAILED",description:"No host acknowledged the required topics."}:Object.keys(this.requireAcknowledgmentFromSpecificHostsForTopics).length>0&&!this.checkAcknowledgmentFromSpecificHosts(s,this.requireAcknowledgmentFromSpecificHostsForTopics)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_SPECIFIC_HOSTS_FAILED",description:"Specific hosts did not acknowledge the required topics."}:{status:"success",txid:t.id("hex"),message:`Sent to ${n.length} Overlay Services ${1===n.length?"host":"hosts"}.`})}checkAcknowledgmentFromAllHosts(t,e,r){for(const i of Object.values(t))if("all"===r){for(const t of e)if(!i.has(t))return!1}else if("any"===r){let t=!1;for(const r of e)if(i.has(r)){t=!0;break}if(!t)return!1}return!0}checkAcknowledgmentFromAnyHost(t,e,r){if("all"===r){for(const r of Object.values(t)){let t=!0;for(const i of e)if(!r.has(i)){t=!1;break}if(t)return!0}return!1}for(const r of Object.values(t))for(const t of e)if(r.has(t))return!0;return!1}checkAcknowledgmentFromSpecificHosts(t,e){for(const[r,i]of Object.entries(e)){const e=t[r];if(null==e)return!1;let n,s;if("all"===i||"any"===i)s=i,n=this.topics;else{if(!Array.isArray(i))continue;n=i,s="all"}if("all"===s){for(const t of n)if(!e.has(t))return!1}else if("any"===s){let t=!1;for(const r of n)if(e.has(r)){t=!0;break}if(!t)return!1}}return!0}async findInterestedHosts(){if("local"===this.networkPreset){const t=new Set;for(let e=0;e<this.topics.length;e++)t.add(this.topics[e]);return{"http://localhost:8080":t}}const t={},e=await this.resolver.query({service:"ls_ship",query:{topics:this.topics}},5e3);if("output-list"!==e.type)throw new Error("SHIP answer is not an output list.");for(const r of e.outputs)try{const e=ir.fromBEEF(r.beef).outputs[r.outputIndex].lockingScript,i=ai.decode(e);if(!this.topics.includes(i.topicOrService)||"SHIP"!==i.protocol)continue;void 0===t[i.domain]&&(t[i.domain]=new Set),t[i.domain].add(i.topicOrService)}catch(t){continue}return t}}const fi=t=>(t.toLowerCase().startsWith("uhrp:")&&(t=t.slice(5)),t.startsWith("//")&&(t=t.slice(2)),t),pi=t=>{if(32!==t.length)throw new Error("Hash length must be 32 bytes (sha256)");return Vt(t,Ot("ce00","hex"))},mi=t=>{const e=gt(t);return pi(e)},wi=t=>{t=fi(t);const{data:e,prefix:r}=Dt(t,void 0,2);if(32!==e.length)throw new Error("Invalid length!");if("ce00"!==Nt(r))throw new Error("Bad prefix");return e},bi=t=>{try{return wi(t),!0}catch(t){return!1}};class gi{authFetch;baseURL;constructor(t){this.baseURL=t.storageURL,this.authFetch=new si(t.wallet)}async getUploadInfo(t,e){const r=`${this.baseURL}/upload`,i={fileSize:t,retentionPeriod:e},n=await this.authFetch.fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!n.ok)throw new Error(`Upload info request failed: HTTP ${n.status}`);const s=await n.json();if("error"===s.status)throw new Error("Upload route returned an error.");return{uploadURL:s.uploadURL,requiredHeaders:s.requiredHeaders,amount:s.amount}}async uploadFile(t,e,r){const i=Uint8Array.from(e.data),n=await fetch(t,{method:"PUT",body:i,headers:{"Content-Type":e.type,...r}});if(!n.ok)throw new Error(`File upload failed: HTTP ${n.status}`);return{published:!0,uhrpURL:await mi(e.data)}}async publishFile(t){const{file:e,retentionPeriod:r}=t,i=e.data.length,{uploadURL:n,requiredHeaders:s}=await this.getUploadInfo(i,r);return await this.uploadFile(n,e,s)}async findFile(t){const e=new URL(`${this.baseURL}/find`);e.searchParams.set("uhrpUrl",t);const r=await this.authFetch.fetch(e.toString(),{method:"GET"});if(!r.ok)throw new Error(`findFile request failed: HTTP ${r.status}`);const i=await r.json();if("error"===i.status){const t=i.code??"unknown-code",e=i.description??"no-description";throw new Error(`findFile returned an error: ${t} - ${e}`)}return i.data}async listUploads(){const t=`${this.baseURL}/list`,e=await this.authFetch.fetch(t,{method:"GET"});if(!e.ok)throw new Error(`listUploads request failed: HTTP ${e.status}`);const r=await e.json();if("error"===r.status){const t=r.code??"unknown-code",e=r.description??"no-description";throw new Error(`listUploads returned an error: ${t} - ${e}`)}return r.uploads}async renewFile(t,e){const r=`${this.baseURL}/renew`,i={uhrpUrl:t,additionalMinutes:e},n=await this.authFetch.fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!n.ok)throw new Error(`renewFile request failed: HTTP ${n.status}`);const s=await n.json();if("error"===s.status){const t=s.code??"unknown-code",e=s.description??"no-description";throw new Error(`renewFile returned an error: ${t} - ${e}`)}return{status:s.status,prevExpiryTime:s.prevExpiryTime,newExpiryTime:s.newExpiryTime,amount:s.amount}}}class yi{networkPreset="mainnet";constructor(t){this.networkPreset=t?.networkPreset}async resolve(t){const e=new ui({networkPreset:this.networkPreset}),r=await e.query({service:"ls_uhrp",query:{uhrpUrl:t}});if("output-list"!==r.type)throw new Error("Lookup answer must be an output list");const i=[],n=Math.floor(Date.now()/1e3);for(let t=0;t<r.outputs.length;t++){const e=ir.fromBEEF(r.outputs[t].beef),{fields:s}=Ue.decode(e.outputs[r.outputs[t].outputIndex].lockingScript);new Ut(s[3]).readVarIntNum()<n||i.push(Tt(s[2]))}return i}async download(t){if(!bi(t))throw new Error("Invalid parameter UHRP url");const e=wi(t),r=await this.resolve(t);if(!Array.isArray(r)||0===r.length)throw new Error("No one currently hosts this file!");for(let t=0;t<r.length;t++)try{const i=await fetch(r[t],{method:"GET"});if(!i.ok||i.status>=400)continue;const n=await i.arrayBuffer(),s=[...new Uint8Array(n)],a=gt(s);for(let t=0;t<a.length;++t)if(a[t]!==e[t])throw new Error("Value of content does not match hash of the url given");return{data:s,mimeType:i.headers.get("Content-Type")}}catch(t){continue}throw new Error(`Unable to download content from ${t}`)}}const vi={name:"Unknown Identity",avatarURL:"XUUB8bbn9fEthk15Ge3zTQXypUShfC94vFjp65v7u5CQ8qkpxzst",identityKey:"",abbreviatedKey:"",badgeIconURL:"XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",badgeLabel:"Not verified by anyone you trust.",badgeClickURL:"https://projectbabbage.com/docs/unknown-identity"},Ii={protocolID:[1,"identity"],keyID:"1",tokenAmount:1,outputIndex:0},ki={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="};class Pi{options;originator;authClient;wallet;constructor(t,e=Ii,r){this.options=e,this.originator=r,this.wallet=t??new zr,this.authClient=new si(this.wallet)}async publiclyRevealAttributes(t,e){if(0===Object.keys(t.fields).length)throw new Error("Public reveal failed: Certificate has no fields to reveal!");if(0===e.length)throw new Error("Public reveal failed: You must reveal at least one field!");try{const e=new Dr(t.type,t.serialNumber,t.subject,t.certifier,t.revocationOutpoint,t.fields,t.signature);await e.verify()}catch(t){throw new Error("Public reveal failed: Certificate verification failed!")}const{keyringForVerifier:r}=await this.wallet.proveCertificate({certificate:t,fieldsToReveal:e,verifier:new re(1).toPublicKey().toString()}),i=await new Ue(this.wallet).lock([Ot(JSON.stringify({...t,keyring:r}))],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:i.toHex(),outputDescription:"Identity Token"}],options:{randomizeOutputs:!1}});if(void 0!==n){const t=new di(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network});return await t.broadcast(ir.fromAtomicBEEF(n))}throw new Error("Public reveal failed: failed to create action!")}async resolveByIdentityKey(t){const{certificates:e}=await this.wallet.discoverByIdentityKey(t,this.originator);return e.map((t=>Pi.parseIdentity(t)))}async resolveByAttributes(t){const{certificates:e}=await this.wallet.discoverByAttributes(t,this.originator);return e.map((t=>Pi.parseIdentity(t)))}static parseIdentity(t){const{type:e,decryptedFields:r,certifierInfo:i}=t;let n,s,a,o,c;switch(e){case ki.xCert:n=r.userName,s=r.profilePhoto,a=`X account certified by ${i.name}`,o=i.iconUrl,c="https://socialcert.net";break;case ki.discordCert:n=r.userName,s=r.profilePhoto,a=`Discord account certified by ${i.name}`,o=i.iconUrl,c="https://socialcert.net";break;case ki.emailCert:n=r.email,s="XUTZxep7BBghAJbSBwTjNfmcsDdRFs5EaGEgkESGSgjJVYgMEizu",a=`Email certified by ${i.name}`,o=i.iconUrl,c="https://socialcert.net";break;case ki.phoneCert:n=r.phoneNumber,s="XUTLxtX3ELNUwRhLwL7kWNGbdnFM8WG2eSLv84J7654oH8HaJWrU",a=`Phone certified by ${i.name}`,o=i.iconUrl,c="https://socialcert.net";break;case ki.identiCert:n=`${r.firstName} ${r.lastName}`,s=r.profilePhoto,a=`Government ID certified by ${i.name}`,o=i.iconUrl,c="https://identicert.me";break;case ki.registrant:n=r.name,s=r.icon,a=`Entity certified by ${i.name}`,o=i.iconUrl,c="https://projectbabbage.com/docs/registrant";break;case ki.coolCert:n="true"===r.cool?"Cool Person!":"Not cool!";break;case ki.anyone:n="Anyone",s="XUT4bpQ6cpBaXi1oMzZsXfpkWGbtp2JTUYAoN7PzhStFJ6wLfoeR",a="Represents the ability for anyone to access this information.",o="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",c="https://projectbabbage.com/docs/anyone-identity";break;case ki.self:n="You",s="XUT9jHGk2qace148jeCX5rDsMftkSGYKmigLwU2PLLBc7Hm63VYR",a="Represents your ability to access this information.",o="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",c="https://projectbabbage.com/docs/self-identity";break;default:n=vi.name,s=r.profilePhoto,a=vi.badgeLabel,o=vi.badgeIconURL,c=vi.badgeClickURL}return{name:n,avatarURL:s,abbreviatedKey:t.subject.length>0?`${t.subject.substring(0,10)}...`:"",identityKey:t.subject,badgeIconURL:o,badgeLabel:a,badgeClickURL:c}}}class Ei{wallet;network;constructor(t=new zr){this.wallet=t}async registerDefinition(t){const e=(await this.wallet.getPublicKey({identityKey:!0})).publicKey,r=new Ue(this.wallet),i=this.buildPushDropFields(t,e),n=this.mapDefinitionTypeToWalletProtocol(t.definitionType),s=await r.lock(i,n,"1","anyone",!0),{tx:a}=await this.wallet.createAction({description:`Register a new ${t.definitionType} item`,outputs:[{satoshis:1,lockingScript:s.toHex(),outputDescription:`New ${t.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(t.definitionType)}],options:{randomizeOutputs:!1}});if(void 0===a)throw new Error(`Failed to create ${t.definitionType} registration transaction!`);const o=new di([this.mapDefinitionTypeToTopic(t.definitionType)],{networkPreset:this.network??=(await this.wallet.getNetwork({})).network});return await o.broadcast(ir.fromAtomicBEEF(a))}async resolve(t,e){const r=new ui,i=this.mapDefinitionTypeToServiceName(t),n=await r.query({service:i,query:e});if("output-list"!==n.type)return[];const s=[];for(const e of n.outputs)try{const r=ir.fromBEEF(e.beef).outputs[e.outputIndex].lockingScript,i=await this.parseLockingScript(t,r);s.push(i)}catch{}return s}async listOwnRegistryEntries(t){const e=this.mapDefinitionTypeToBasketName(t),{outputs:r,BEEF:i}=await this.wallet.listOutputs({basket:e,include:"entire transactions"}),n=[];for(const e of r)if(e.spendable)try{const[r,s]=e.outpoint.split("."),a=ir.fromBEEF(i).outputs[s].lockingScript,o=await this.parseLockingScript(t,a);n.push({...o,txid:r,outputIndex:Number(s),satoshis:e.satoshis,lockingScript:a.toHex(),beef:i})}catch{}return n}async revokeOwnRegistryEntry(t){if(void 0===t.txid||void 0===t.outputIndex||void 0===t.lockingScript)throw new Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");const e=(await this.wallet.getPublicKey({identityKey:!0})).publicKey;if(t.registryOperator!==e)throw new Error("This registry token does not belong to the current wallet.");const r="basket"===t.definitionType?t.basketID:"protocol"===t.definitionType?t.name:"certificate"===t.definitionType?void 0!==t.name?t.name:t.type:"unknown",i=`${t.txid}.${t.outputIndex}`,{signableTransaction:n}=await this.wallet.createAction({description:`Revoke ${t.definitionType} item: ${r}`,inputBEEF:t.beef,inputs:[{outpoint:i,unlockingScriptLength:73,inputDescription:`Revoking ${t.definitionType} token`}]});if(void 0===n)throw new Error("Failed to create signable transaction.");const s=ir.fromBEEF(n.tx),a=new Ue(this.wallet),o=await a.unlock(this.mapDefinitionTypeToWalletProtocol(t.definitionType),"1","anyone","all",!1,t.satoshis,Ae.fromHex(t.lockingScript)),c=await o.sign(s,t.outputIndex),{tx:h}=await this.wallet.signAction({reference:n.reference,spends:{[t.outputIndex]:{unlockingScript:c.toHex()}},options:{acceptDelayedBroadcast:!1}});if(void 0===h)throw new Error("Failed to finalize the transaction signature.");const u=new di([this.mapDefinitionTypeToTopic(t.definitionType)],{networkPreset:this.network??=(await this.wallet.getNetwork({})).network});return await u.broadcast(ir.fromAtomicBEEF(h))}buildPushDropFields(t,e){let r;switch(t.definitionType){case"basket":r=[t.basketID,t.name,t.iconURL,t.description,t.documentationURL];break;case"protocol":r=[JSON.stringify(t.protocolID),t.name,t.iconURL,t.description,t.documentationURL];break;case"certificate":r=[t.type,t.name,t.iconURL,t.description,t.documentationURL,JSON.stringify(t.fields)];break;default:throw new Error("Unsupported definition type")}return r.push(e),r.map((t=>Ot(t)))}async parseLockingScript(t,e){const r=Ue.decode(e);if(0===r.fields.length)throw new Error("Not a valid registry pushdrop script.");let i,n;switch(t){case"basket":{if(7!==r.fields.length)throw new Error("Unexpected field count for basket type.");const[t,e,s,a,o,c]=r.fields;i=Tt(c),n={definitionType:"basket",basketID:Tt(t),name:Tt(e),iconURL:Tt(s),description:Tt(a),documentationURL:Tt(o)};break}case"protocol":{if(7!==r.fields.length)throw new Error("Unexpected field count for protocol type.");const[t,e,s,a,o,c]=r.fields;i=Tt(c),n={definitionType:"protocol",protocolID:Si(Tt(t)),name:Tt(e),iconURL:Tt(s),description:Tt(a),documentationURL:Tt(o)};break}case"certificate":{if(8!==r.fields.length)throw new Error("Unexpected field count for certificate type.");const[t,e,s,a,o,c,h]=r.fields;i=Tt(h);let u={};try{u=JSON.parse(Tt(c))}catch{}n={definitionType:"certificate",type:Tt(t),name:Tt(e),iconURL:Tt(s),description:Tt(a),documentationURL:Tt(o),fields:u};break}default:throw new Error(`Unsupported definition type: ${t}`)}return{...n,registryOperator:i}}mapDefinitionTypeToWalletProtocol(t){switch(t){case"basket":return[1,"basketmap"];case"protocol":return[1,"protomap"];case"certificate":return[1,"certmap"];default:throw new Error(`Unknown definition type: ${t}`)}}mapDefinitionTypeToBasketName(t){switch(t){case"basket":return"basketmap";case"protocol":return"protomap";case"certificate":return"certmap";default:throw new Error(`Unknown definition type: ${t}`)}}mapDefinitionTypeToTopic(t){switch(t){case"basket":return"tm_basketmap";case"protocol":return"tm_protomap";case"certificate":return"tm_certmap";default:throw new Error(`Unknown definition type: ${t}`)}}mapDefinitionTypeToServiceName(t){switch(t){case"basket":return"ls_basketmap";case"protocol":return"ls_protomap";case"certificate":return"ls_certmap";default:throw new Error(`Unknown definition type: ${t}`)}}}function Si(t){const e=JSON.parse(t);if(!Array.isArray(e)||2!==e.length)throw new Error("Invalid wallet protocol format.");const[r,i]=e;if(![0,1,2].includes(r))throw new Error("Invalid security level.");if("string"!=typeof i)throw new Error("Invalid protocolID");return[r,i]}class Ni{wallet;context;encrypt;originator;constructor(t=new zr,e="kvstore default",r=!0,i){if("string"!=typeof e||e.length<1)throw new Error("A context in which to operate is required.");this.wallet=t,this.context=e,this.encrypt=r,this.originator=i}getProtocol(t){return{protocolID:[2,this.context],keyID:t}}async getOutputs(t,e){return await this.wallet.listOutputs({basket:this.context,tags:[t],tagQueryMode:"all",include:"entire transactions",limit:e})}async get(t,e=void 0){return(await this.lookupValue(t,e,5)).value}getLockingScript(t,e){const[r,i]=t.outpoint.split("."),n=e.findTxid(r)?.tx;if(null==n)throw new Error(`beef must contain txid ${r}`);return n.outputs[Number(i)].lockingScript}async lookupValue(t,e,r){const i=await this.getOutputs(t,r),n={value:e,outpoint:void 0,lor:i},{outputs:s}=i;if(0===s.length)return n;const a=s.slice(-1)[0];let o;n.outpoint=a.outpoint;try{if(void 0===i.BEEF)throw new Error("entire transactions listOutputs option must return valid BEEF");const t=this.getLockingScript(a,rr.fromBinary(i.BEEF)),e=Ue.decode(t);if(e.fields.length<1||e.fields.length>2)throw new Error("Invalid token.");o=e.fields[0]}catch(t){throw new Error(`Invalid value found. You need to call set to collapse the corrupted state (or relinquish the corrupted ${s[0].outpoint} output from the ${this.context} basket) before you can get this value again.`)}if(this.encrypt){const{plaintext:e}=await this.wallet.decrypt({...this.getProtocol(t),ciphertext:o});n.value=Tt(e)}else n.value=Tt(o);return n}getInputs(t){const e=[];for(let r=0;r<t.length;r++)e.push({outpoint:t[r].outpoint,unlockingScriptLength:74,inputDescription:"Previous key-value token"});return e}async getSpends(t,e,r,i){const n=this.getProtocol(t),s=ir.fromAtomicBEEF(i),a={};for(let t=0;t<e.length;t++){const e=r.unlock(n.protocolID,n.keyID,"self"),i=await e.sign(s,t);a[t]={unlockingScript:i.toHex()}}return a}async set(t,e){const r=await this.lookupValue(t,void 0,10);if(r.value===e){if(void 0===r.outpoint)throw new Error("outpoint must be valid when value is valid and unchanged");return r.outpoint}const i=this.getProtocol(t);let n=Ot(e,"utf8");if(this.encrypt){const{ciphertext:t}=await this.wallet.encrypt({...i,plaintext:n});n=t}const s=new Ue(this.wallet,this.originator),a=await s.lock([n],i.protocolID,i.keyID,"self"),{outputs:o,BEEF:c}=r.lor;let h;try{const e=this.getInputs(o),{txid:r,signableTransaction:i}=await this.wallet.createAction({description:`Update ${t} in ${this.context}`,inputBEEF:c,inputs:e,outputs:[{basket:this.context,tags:[t],lockingScript:a.toHex(),satoshis:1,outputDescription:"Key-value token"}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}});if(o.length>0&&"object"!=typeof i)throw new Error("Wallet did not return a signable transaction when expected.");if(null==i)h=`${r}.0`;else{const e=await this.getSpends(t,o,s,i.tx),{txid:r}=await this.wallet.signAction({reference:i.reference,spends:e});h=`${r}.0`}}catch(e){throw new Error(`There are ${o.length} outputs with tag ${t} that cannot be unlocked.`)}return h}async remove(t){const e=[];for(;;){const{outputs:r,BEEF:i,totalOutputs:n}=await this.getOutputs(t);if(r.length>0){const s=new Ue(this.wallet,this.originator);try{const n=this.getInputs(r),{signableTransaction:a}=await this.wallet.createAction({description:`Remove ${t} in ${this.context}`,inputBEEF:i,inputs:n,options:{acceptDelayedBroadcast:!1}});if("object"!=typeof a)throw new Error("Wallet did not return a signable transaction when expected.");const o=await this.getSpends(t,r,s,a.tx),{txid:c}=await this.wallet.signAction({reference:a.reference,spends:o});if(void 0===c)throw new Error("signAction must return a valid txid");e.push(c)}catch(e){throw new Error(`There are ${n} outputs with tag ${t} that cannot be unlocked.`)}}if(r.length===n)break}return e}}return e})()));
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.bsv=e():t.bsv=e()}(this,(()=>(()=>{"use strict";var t={d:(e,r)=>{for(var i in r)t.o(r,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:r[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{ARC:()=>ze,ATOMIC_BEEF:()=>tr,AuthFetch:()=>hi,BEEF_V1:()=>Ze,BEEF_V2:()=>Qe,BSM:()=>o,Beef:()=>rr,BeefParty:()=>ar,BeefTx:()=>Ye,BigNumber:()=>h,CachedKeyDeriver:()=>Rr,Certificate:()=>Kr,CompletedProtoWallet:()=>Qr,Curve:()=>Lt,DEFAULT_IDENTITY_CLIENT_OPTIONS:()=>Si,DEFAULT_SLAP_TRACKERS:()=>li,DEFAULT_TESTNET_SLAP_TRACKERS:()=>di,DRBG:()=>zt,ECDSA:()=>n,ECIES:()=>xr,EncryptedMessage:()=>a,FetchHttpClient:()=>qe,HD:()=>Ir,HTTPSOverlayBroadcastFacilitator:()=>mi,HTTPSOverlayLookupFacilitator:()=>fi,HTTPWalletJSON:()=>Xr,HTTPWalletWire:()=>zr,Hash:()=>r,IdentityClient:()=>Oi,KNOWN_IDENTITY_TYPES:()=>Ni,KeyDeriver:()=>Fr,KeyShares:()=>ee,LocalKVStore:()=>Ti,LockingScript:()=>Ae,LookupResolver:()=>pi,MasterCertificate:()=>Jr,MerklePath:()=>Ge,Mnemonic:()=>Pr,NodejsHttpClient:()=>Ke,OP:()=>Oe,OverlayAdminTokenTemplate:()=>ui,P2PKH:()=>Ve,Peer:()=>ai,Point:()=>Kt,PointInFiniteField:()=>Qt,Polynomial:()=>te,PrivateKey:()=>re,ProtoWallet:()=>Cr,PublicKey:()=>Gt,PushDrop:()=>Ue,RPuzzle:()=>De,Random:()=>Zt,RegistryClient:()=>xi,SHIPBroadcaster:()=>wi,SHIPCast:()=>wi,SatoshisPerKilobyte:()=>He,Schnorr:()=>Se,Script:()=>xe,SecurityLevels:()=>_r,SessionManager:()=>ti,Signature:()=>$t,SignedMessage:()=>s,SimplifiedFetchTransport:()=>ci,Spend:()=>Re,StorageDownloader:()=>Pi,StorageUploader:()=>ki,StorageUtils:()=>c,SymmetricKey:()=>Pe,TOTP:()=>Tr,TX_DATA_FORMAT:()=>er,Teranode:()=>lr,TopicBroadcaster:()=>wi,Transaction:()=>ir,TransactionSignature:()=>Ee,UnlockingScript:()=>Te,Utils:()=>i,VerifiableCertificate:()=>Zr,WERR_REVIEW_ACTIONS:()=>Wr,WalletClient:()=>Gr,WalletError:()=>Dr,WalletErrors:()=>Ur,WalletWireProcessor:()=>Yr,WalletWireTransceiver:()=>$r,WhatsOnChain:()=>We,WhatsOnChainBroadcaster:()=>or,WindowCWISubstrate:()=>Vr,XDM:()=>Hr,binaryHttpClient:()=>ur,createNonce:()=>ri,defaultBroadcaster:()=>je,defaultChainTracker:()=>Xe,defaultHttpClient:()=>Le,defaultIdentity:()=>Ei,deserializeWalletProtocol:()=>Ai,fromUtxo:()=>Ar,getVerifiableCertificates:()=>ii,isBroadcastFailure:()=>sr,isBroadcastResponse:()=>nr,validateCertificates:()=>ni,verifyNonce:()=>ei,walletErrors:()=>Br});var r={};t.r(r),t.d(r,{RIPEMD160:()=>J,SHA1:()=>Q,SHA1HMAC:()=>pt,SHA256:()=>Z,SHA256HMAC:()=>ft,SHA512:()=>tt,SHA512HMAC:()=>mt,hash160:()=>It,hash256:()=>vt,pbkdf2:()=>Et,ripemd160:()=>wt,sha1:()=>bt,sha256:()=>gt,sha256hmac:()=>kt,sha512:()=>yt,sha512hmac:()=>Pt,toArray:()=>y});var i={};t.r(i),t.d(i,{Reader:()=>Ut,Writer:()=>Bt,encode:()=>Mt,fromBase58:()=>Rt,fromBase58Check:()=>Dt,minimallyEncode:()=>Ht,toArray:()=>Ot,toBase58:()=>Ct,toBase58Check:()=>Vt,toBase64:()=>_t,toHex:()=>Nt,toUTF8:()=>Tt,zero2:()=>St});var n={};t.r(n),t.d(n,{sign:()=>Wt,verify:()=>Xt});var s={};t.r(s),t.d(s,{sign:()=>fr,verify:()=>pr});var a={};t.r(a),t.d(a,{decrypt:()=>br,encrypt:()=>wr});var o={};t.r(o),t.d(o,{magicHash:()=>gr,sign:()=>yr,verify:()=>vr});var c={};t.r(c),t.d(c,{getHashFromURL:()=>vi,getURLForFile:()=>yi,getURLForHash:()=>gi,isValidURL:()=>Ii,normalizeURL:()=>bi});class h{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,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];static wordSize=26;negative;words;length;red;static isBN(t){return t instanceof h||null!==t&&"object"==typeof t&&t.constructor.wordSize===h.wordSize&&Array.isArray(t.words)}static max(t,e){return t.cmp(e)>0?t:e}static min(t,e){return t.cmp(e)<0?t:e}constructor(t=0,e=10,r="be"){if(this.negative=0,this.words=[],this.length=0,this.red=null,null!==t){if("le"!==e&&"be"!==e||(r=e,e=10),"number"==typeof t)return void this.initNumber(t,e,r);if("object"==typeof t)return void this.initArray(t,r);"hex"===e&&(e=16),this.assert(e===(0|e)&&e>=2&&e<=36);let i=0;(t=t.toString().replace(/\s+/g,"")).startsWith("-")&&(i++,this.negative=1),i<t.length&&(16===e?this.parseHex(t,i,r):(this.parseBase(t,e,i),"le"===r&&this.initArray(this.toArray(),r)))}}assert(t,e="Assertion failed"){if(!t)throw new Error(e)}initNumber(t,e,r){return t<0&&(this.negative=1,t=-t),t<67108864?(this.words=[67108863&t],this.length=1):t<4503599627370496?(this.words=[67108863&t,t/67108864&67108863],this.length=2):(this.assert(t<=9007199254740991,"The number is larger than 2 ^ 53 (unsafe)"),this.words=[67108863&t,t/67108864&67108863,1],this.length=3),"le"!==r||this.initArray(this.toArray(),r),this}initArray(t,e){if(this.assert("number"==typeof t.length,"The number must have a length"),t.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(t.length/3),this.words=new Array(this.length);let r,i,n=0;for(;n<this.length;n++)this.words[n]=0;let s=0;if("be"===e)for(n=t.length-1,r=0;n>=0;n-=3)i=t[n]|t[n-1]<<8|t[n-2]<<16,this.words[r]|=i<<s&67108863,this.words[r+1]=i>>>26-s&67108863,s+=24,s>=26&&(s-=26,r++);else if("le"===e)for(n=0,r=0;n<t.length;n+=3)i=t[n]|t[n+1]<<8|t[n+2]<<16,this.words[r]|=i<<s&67108863,this.words[r+1]=i>>>26-s&67108863,s+=24,s>=26&&(s-=26,r++);return this.strip()}parseHex4Bits(t,e){const r=t.charCodeAt(e);if(r>=48&&r<=57)return r-48;if(r>=65&&r<=70)return r-55;if(r>=97&&r<=102)return r-87;throw new Error("Invalid character in "+t)}parseHexByte(t,e,r){let i=this.parseHex4Bits(t,r);return r-1>=e&&(i|=this.parseHex4Bits(t,r-1)<<4),i}parseHex(t,e,r){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length).fill(0);let i=0,n=0;const s=r=>{const s=this.parseHexByte(t,e,r)<<i;this.words[n]|=67108863&s,i>=18?(i-=18,n+=1,this.words[n]|=s>>>26):i+=8};if("be"===r)for(let r=t.length-1;r>=e;r-=2)s(r);else for(let r=(t.length-e)%2==0?e+1:e;r<t.length;r+=2)s(r);return this.strip()}parseBaseWord(t,e,r,i){let n=0,s=0;const a=Math.min(t.length,r);for(let r=e;r<a;r++){const e=t.charCodeAt(r)-48;n*=i,s=e>=49?e-49+10:e>=17?e-17+10:e,this.assert(e>=0&&s<i,"Invalid character"),n+=s}return n}parseBase(t,e,r){this.words=[0],this.length=1;let i=0,n=1;for(;n<=67108863;n*=e)i++;i--,n=n/e|0;const s=t.length-r,a=s%i,o=Math.min(s,s-a)+r;let c=0,h=r;for(;h<o;h+=i)c=this.parseBaseWord(t,h,h+i,e),this.imuln(n),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c);if(0!==a){let r=1;for(c=this.parseBaseWord(t,h,t.length,e),h=0;h<a;h++)r*=e;this.imuln(r),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c)}return this.strip()}copy(t){t.words=new Array(this.length);for(let e=0;e<this.length;e++)t.words[e]=this.words[e];t.length=this.length,t.negative=this.negative,t.red=this.red}static move(t,e){t.words=e.words,t.length=e.length,t.negative=e.negative,t.red=e.red}clone(){const t=new h;return this.copy(t),t}expand(t){for(;this.length<t;)this.words[this.length++]=0;return this}strip(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this.normSign()}normSign(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this}inspect(){return(null!==this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}toString(t=10,e=1){if(16===t||"hex"===t)return this.toHexString(e);if(t===(0|t)&&t>=2&&t<=36)return this.toBaseString(t,e);throw new Error("Base should be between 2 and 36")}toHexString(t){let e="",r=0,i=0;for(let t=0;t<this.length;t++){const n=this.words[t],s=(16777215&(n<<r|i)).toString(16);i=n>>>24-r&16777215,r+=2,r>=26&&(r-=26,t--),e=0!==i||t!==this.length-1?h.zeros[6-s.length]+s+e:s+e}if(0!==i&&(e=i.toString(16)+e),0===t&&"0"===e)return"";for(;e.length%t!=0&&0!==t;)e="0"+e;return 0!==this.negative&&(e="-"+e),e}toBaseString(t,e){const r=h.groupSizes[t],i=h.groupBases[t];let n="",s=this.clone();for(s.negative=0;!s.isZero();){const e=s.modrn(i).toString(t);s=s.idivn(i),n=s.isZero()?e+n:h.zeros[r-e.length]+e+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}toNumber(){let t=this.words[0];if(2===this.length)t+=67108864*this.words[1];else if(3===this.length&&1===this.words[2])t+=4503599627370496+67108864*this.words[1];else if(this.length>2)throw new Error("Number can only safely store up to 53 bits");return 0!==this.negative?-t:t}toJSON(){return this.toString(16)}toArrayLikeLE(t,e){let r=0,i=0;for(let e=0,n=0;e<this.length;e++){const s=this.words[e]<<n|i;t[r++]=255&s,r<t.length&&(t[r++]=s>>8&255),r<t.length&&(t[r++]=s>>16&255),6===n?(r<t.length&&(t[r++]=s>>24&255),i=0,n=0):(i=s>>>24,n+=2)}if(r<t.length)for(t[r++]=i;r<t.length;)t[r++]=0}toArrayLikeBE(t,e){let r=t.length-1,i=0;for(let e=0,n=0;e<this.length;e++){const s=this.words[e]<<n|i;t[r--]=255&s,r>=0&&(t[r--]=s>>8&255),r>=0&&(t[r--]=s>>16&255),6===n?(r>=0&&(t[r--]=s>>24&255),i=0,n=0):(i=s>>>24,n+=2)}if(r>=0)for(t[r--]=i;r>=0;)t[r--]=0}toArray(t="be",e){this.strip();const r=this.byteLength(),i=e??Math.max(1,r);this.assert(r<=i,"byte array longer than desired length"),this.assert(i>0,"Requested array length <= 0");const n=new Array(i);return"le"===t?this.toArrayLikeLE(n,r):this.toArrayLikeBE(n,r),n}countWordBits(t){if("function"==typeof Math.clz32)return 32-Math.clz32(t);let e=t,r=0;return e>=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e}zeroWordBits(t){if(0===t)return 26;let e=t,r=0;return 8191&e||(r+=13,e>>>=13),127&e||(r+=7,e>>>=7),15&e||(r+=4,e>>>=4),3&e||(r+=2,e>>>=2),1&e||r++,r}bitLength(){const t=this.words[this.length-1],e=this.countWordBits(t);return 26*(this.length-1)+e}static toBitArray(t){const e=new Array(t.bitLength());for(let r=0;r<e.length;r++){const i=r/26|0,n=r%26;e[r]=t.words[i]>>>n&1}return e}toBitArray(){return h.toBitArray(this)}zeroBits(){if(this.isZero())return 0;let t=0;for(let e=0;e<this.length;e++){const r=this.zeroWordBits(this.words[e]);if(t+=r,26!==r)break}return t}byteLength(){return Math.ceil(this.bitLength()/8)}toTwos(t){return 0!==this.negative?this.abs().inotn(t).iaddn(1):this.clone()}fromTwos(t){return this.testn(t-1)?this.notn(t).iaddn(1).ineg():this.clone()}isNeg(){return 0!==this.negative}neg(){return this.clone().ineg()}ineg(){return this.isZero()||(this.negative^=1),this}iuor(t){for(;this.length<t.length;)this.words[this.length++]=0;for(let e=0;e<t.length;e++)this.words[e]=this.words[e]|t.words[e];return this.strip()}ior(t){return this.assert(!(this.negative|t.negative)),this.iuor(t)}or(t){return this.length>t.length?this.clone().ior(t):t.clone().ior(this)}uor(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)}iuand(t){const e=Math.min(this.length,t.length);for(let r=0;r<e;r++)this.words[r]=this.words[r]&t.words[r];return this.length=e,this.strip()}iand(t){return this.assert(!(this.negative|t.negative)),this.iuand(t)}and(t){return this.length>t.length?this.clone().iand(t):t.clone().iand(this)}uand(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)}iuxor(t){if(this.length>t.length)for(let e=0;e<t.length;e++)this.words[e]=this.words[e]^t.words[e];else{for(let e=0;e<this.length;e++)this.words[e]=this.words[e]^t.words[e];for(let e=this.length;e<t.length;e++)this.words[e]=t.words[e];this.length=t.length}return this.strip()}ixor(t){return this.assert(!(this.negative|t.negative),"Neither number can be negative"),this.iuxor(t)}xor(t){return this.length>t.length?this.clone().ixor(t):t.clone().ixor(this)}uxor(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)}inotn(t){this.assert("number"==typeof t&&t>=0,"The width needs to be a number greater than zero");let e=0|Math.ceil(t/26);const r=t%26;this.expand(e),r>0&&e--;let i=0;for(;i<e;i++)this.words[i]=67108863&~this.words[i];return r>0&&(this.words[i]=~this.words[i]&67108863>>26-r),this.strip()}notn(t){return this.clone().inotn(t)}setn(t,e){this.assert("number"==typeof t&&t>=0);const r=t/26|0,i=t%26;return this.expand(r+1),this.words[r]=1===e||!0===e?this.words[r]|1<<i:this.words[r]&~(1<<i),this.strip()}iadd(t){let e,r,i;if(0!==this.negative&&0===t.negative)return this.negative=0,e=this.isub(t),this.negative^=1,this.normSign();if(0===this.negative&&0!==t.negative)return t.negative=0,e=this.isub(t),t.negative=1,e.normSign();this.length>t.length?(r=this,i=t):(r=t,i=this);let n=0,s=0;for(;s<i.length;s++)e=(0|r.words[s])+(0|i.words[s])+n,this.words[s]=67108863&e,n=e>>>26;for(;0!==n&&s<r.length;s++)e=(0|r.words[s])+n,this.words[s]=67108863&e,n=e>>>26;if(this.length=r.length,0!==n)this.words[this.length]=n,this.length++;else if(r!==this)for(;s<r.length;s++)this.words[s]=r.words[s];return this}add(t){let e;return 0!==t.negative&&0===this.negative?(t.negative=0,e=this.sub(t),t.negative^=1,e):0===t.negative&&0!==this.negative?(this.negative=0,e=t.sub(this),this.negative=1,e):this.length>t.length?this.clone().iadd(t):t.clone().iadd(this)}isub(t){let e;if(0!==t.negative)return t.negative=0,e=this.iadd(t),t.negative=1,e.normSign();if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this.normSign();const r=this.cmp(t);if(0===r)return this.negative=0,this.length=1,this.words[0]=0,this;let i,n;r>0?(i=this,n=t):(i=t,n=this);let s=0,a=0;for(;a<n.length;a++)e=(0|i.words[a])-(0|n.words[a])+s,s=e>>26,this.words[a]=67108863&e;for(;0!==s&&a<i.length;a++)e=(0|i.words[a])+s,s=e>>26,this.words[a]=67108863&e;if(0===s&&a<i.length&&i!==this)for(;a<i.length;a++)this.words[a]=i.words[a];return this.length=Math.max(this.length,a),i!==this&&(this.negative=1),this.strip()}sub(t){return this.clone().isub(t)}smallMulTo(t,e,r){r.negative=e.negative^t.negative;let i=t.length+e.length|0;r.length=i,i=i-1|0;let n=0|t.words[0],s=0|e.words[0],a=n*s;const o=67108863&a;let c=a/67108864|0;r.words[0]=o;let h=1;for(;h<i;h++){let i=c>>>26,o=67108863&c;const u=Math.min(h,e.length-1);for(let r=Math.max(0,h-t.length+1);r<=u;r++){const c=h-r|0;n=0|t.words[c],s=0|e.words[r],a=n*s+o,i+=a/67108864|0,o=67108863&a}r.words[h]=0|o,c=0|i}return 0!==c?r.words[h]=0|c:r.length--,r.strip()}comb10MulTo(t,e,r){const i=t.words,n=e.words,s=r.words;let a,o,c,h=0;const u=0|i[0],l=8191&u,d=u>>>13,f=0|i[1],p=8191&f,m=f>>>13,w=0|i[2],b=8191&w,g=w>>>13,y=0|i[3],v=8191&y,I=y>>>13,k=0|i[4],P=8191&k,E=k>>>13,S=0|i[5],N=8191&S,O=S>>>13,x=0|i[6],A=8191&x,T=x>>>13,M=0|i[7],_=8191&M,F=M>>>13,R=0|i[8],C=8191&R,V=R>>>13,D=0|i[9],B=8191&D,U=D>>>13,H=0|n[0],K=8191&H,q=H>>>13,L=0|n[1],$=8191&L,z=L>>>13,j=0|n[2],W=8191&j,X=j>>>13,G=0|n[3],Y=8191&G,J=G>>>13,Z=0|n[4],Q=8191&Z,tt=Z>>>13,et=0|n[5],rt=8191&et,it=et>>>13,nt=0|n[6],st=8191&nt,at=nt>>>13,ot=0|n[7],ct=8191&ot,ht=ot>>>13,ut=0|n[8],lt=8191&ut,dt=ut>>>13,ft=0|n[9],pt=8191&ft,mt=ft>>>13;r.negative=t.negative^e.negative,r.length=19,a=Math.imul(l,K),o=Math.imul(l,q),o=o+Math.imul(d,K)|0,c=Math.imul(d,q);let wt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(wt>>>26)|0,wt&=67108863,a=Math.imul(p,K),o=Math.imul(p,q),o=o+Math.imul(m,K)|0,c=Math.imul(m,q),a=a+Math.imul(l,$)|0,o=o+Math.imul(l,z)|0,o=o+Math.imul(d,$)|0,c=c+Math.imul(d,z)|0;let bt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(bt>>>26)|0,bt&=67108863,a=Math.imul(b,K),o=Math.imul(b,q),o=o+Math.imul(g,K)|0,c=Math.imul(g,q),a=a+Math.imul(p,$)|0,o=o+Math.imul(p,z)|0,o=o+Math.imul(m,$)|0,c=c+Math.imul(m,z)|0,a=a+Math.imul(l,W)|0,o=o+Math.imul(l,X)|0,o=o+Math.imul(d,W)|0,c=c+Math.imul(d,X)|0;let gt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(gt>>>26)|0,gt&=67108863,a=Math.imul(v,K),o=Math.imul(v,q),o=o+Math.imul(I,K)|0,c=Math.imul(I,q),a=a+Math.imul(b,$)|0,o=o+Math.imul(b,z)|0,o=o+Math.imul(g,$)|0,c=c+Math.imul(g,z)|0,a=a+Math.imul(p,W)|0,o=o+Math.imul(p,X)|0,o=o+Math.imul(m,W)|0,c=c+Math.imul(m,X)|0,a=a+Math.imul(l,Y)|0,o=o+Math.imul(l,J)|0,o=o+Math.imul(d,Y)|0,c=c+Math.imul(d,J)|0;let yt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(yt>>>26)|0,yt&=67108863,a=Math.imul(P,K),o=Math.imul(P,q),o=o+Math.imul(E,K)|0,c=Math.imul(E,q),a=a+Math.imul(v,$)|0,o=o+Math.imul(v,z)|0,o=o+Math.imul(I,$)|0,c=c+Math.imul(I,z)|0,a=a+Math.imul(b,W)|0,o=o+Math.imul(b,X)|0,o=o+Math.imul(g,W)|0,c=c+Math.imul(g,X)|0,a=a+Math.imul(p,Y)|0,o=o+Math.imul(p,J)|0,o=o+Math.imul(m,Y)|0,c=c+Math.imul(m,J)|0,a=a+Math.imul(l,Q)|0,o=o+Math.imul(l,tt)|0,o=o+Math.imul(d,Q)|0,c=c+Math.imul(d,tt)|0;let vt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(vt>>>26)|0,vt&=67108863,a=Math.imul(N,K),o=Math.imul(N,q),o=o+Math.imul(O,K)|0,c=Math.imul(O,q),a=a+Math.imul(P,$)|0,o=o+Math.imul(P,z)|0,o=o+Math.imul(E,$)|0,c=c+Math.imul(E,z)|0,a=a+Math.imul(v,W)|0,o=o+Math.imul(v,X)|0,o=o+Math.imul(I,W)|0,c=c+Math.imul(I,X)|0,a=a+Math.imul(b,Y)|0,o=o+Math.imul(b,J)|0,o=o+Math.imul(g,Y)|0,c=c+Math.imul(g,J)|0,a=a+Math.imul(p,Q)|0,o=o+Math.imul(p,tt)|0,o=o+Math.imul(m,Q)|0,c=c+Math.imul(m,tt)|0,a=a+Math.imul(l,rt)|0,o=o+Math.imul(l,it)|0,o=o+Math.imul(d,rt)|0,c=c+Math.imul(d,it)|0;let It=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(It>>>26)|0,It&=67108863,a=Math.imul(A,K),o=Math.imul(A,q),o=o+Math.imul(T,K)|0,c=Math.imul(T,q),a=a+Math.imul(N,$)|0,o=o+Math.imul(N,z)|0,o=o+Math.imul(O,$)|0,c=c+Math.imul(O,z)|0,a=a+Math.imul(P,W)|0,o=o+Math.imul(P,X)|0,o=o+Math.imul(E,W)|0,c=c+Math.imul(E,X)|0,a=a+Math.imul(v,Y)|0,o=o+Math.imul(v,J)|0,o=o+Math.imul(I,Y)|0,c=c+Math.imul(I,J)|0,a=a+Math.imul(b,Q)|0,o=o+Math.imul(b,tt)|0,o=o+Math.imul(g,Q)|0,c=c+Math.imul(g,tt)|0,a=a+Math.imul(p,rt)|0,o=o+Math.imul(p,it)|0,o=o+Math.imul(m,rt)|0,c=c+Math.imul(m,it)|0,a=a+Math.imul(l,st)|0,o=o+Math.imul(l,at)|0,o=o+Math.imul(d,st)|0,c=c+Math.imul(d,at)|0;let kt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(kt>>>26)|0,kt&=67108863,a=Math.imul(_,K),o=Math.imul(_,q),o=o+Math.imul(F,K)|0,c=Math.imul(F,q),a=a+Math.imul(A,$)|0,o=o+Math.imul(A,z)|0,o=o+Math.imul(T,$)|0,c=c+Math.imul(T,z)|0,a=a+Math.imul(N,W)|0,o=o+Math.imul(N,X)|0,o=o+Math.imul(O,W)|0,c=c+Math.imul(O,X)|0,a=a+Math.imul(P,Y)|0,o=o+Math.imul(P,J)|0,o=o+Math.imul(E,Y)|0,c=c+Math.imul(E,J)|0,a=a+Math.imul(v,Q)|0,o=o+Math.imul(v,tt)|0,o=o+Math.imul(I,Q)|0,c=c+Math.imul(I,tt)|0,a=a+Math.imul(b,rt)|0,o=o+Math.imul(b,it)|0,o=o+Math.imul(g,rt)|0,c=c+Math.imul(g,it)|0,a=a+Math.imul(p,st)|0,o=o+Math.imul(p,at)|0,o=o+Math.imul(m,st)|0,c=c+Math.imul(m,at)|0,a=a+Math.imul(l,ct)|0,o=o+Math.imul(l,ht)|0,o=o+Math.imul(d,ct)|0,c=c+Math.imul(d,ht)|0;let Pt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,a=Math.imul(C,K),o=Math.imul(C,q),o=o+Math.imul(V,K)|0,c=Math.imul(V,q),a=a+Math.imul(_,$)|0,o=o+Math.imul(_,z)|0,o=o+Math.imul(F,$)|0,c=c+Math.imul(F,z)|0,a=a+Math.imul(A,W)|0,o=o+Math.imul(A,X)|0,o=o+Math.imul(T,W)|0,c=c+Math.imul(T,X)|0,a=a+Math.imul(N,Y)|0,o=o+Math.imul(N,J)|0,o=o+Math.imul(O,Y)|0,c=c+Math.imul(O,J)|0,a=a+Math.imul(P,Q)|0,o=o+Math.imul(P,tt)|0,o=o+Math.imul(E,Q)|0,c=c+Math.imul(E,tt)|0,a=a+Math.imul(v,rt)|0,o=o+Math.imul(v,it)|0,o=o+Math.imul(I,rt)|0,c=c+Math.imul(I,it)|0,a=a+Math.imul(b,st)|0,o=o+Math.imul(b,at)|0,o=o+Math.imul(g,st)|0,c=c+Math.imul(g,at)|0,a=a+Math.imul(p,ct)|0,o=o+Math.imul(p,ht)|0,o=o+Math.imul(m,ct)|0,c=c+Math.imul(m,ht)|0,a=a+Math.imul(l,lt)|0,o=o+Math.imul(l,dt)|0,o=o+Math.imul(d,lt)|0,c=c+Math.imul(d,dt)|0;let Et=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(Et>>>26)|0,Et&=67108863,a=Math.imul(B,K),o=Math.imul(B,q),o=o+Math.imul(U,K)|0,c=Math.imul(U,q),a=a+Math.imul(C,$)|0,o=o+Math.imul(C,z)|0,o=o+Math.imul(V,$)|0,c=c+Math.imul(V,z)|0,a=a+Math.imul(_,W)|0,o=o+Math.imul(_,X)|0,o=o+Math.imul(F,W)|0,c=c+Math.imul(F,X)|0,a=a+Math.imul(A,Y)|0,o=o+Math.imul(A,J)|0,o=o+Math.imul(T,Y)|0,c=c+Math.imul(T,J)|0,a=a+Math.imul(N,Q)|0,o=o+Math.imul(N,tt)|0,o=o+Math.imul(O,Q)|0,c=c+Math.imul(O,tt)|0,a=a+Math.imul(P,rt)|0,o=o+Math.imul(P,it)|0,o=o+Math.imul(E,rt)|0,c=c+Math.imul(E,it)|0,a=a+Math.imul(v,st)|0,o=o+Math.imul(v,at)|0,o=o+Math.imul(I,st)|0,c=c+Math.imul(I,at)|0,a=a+Math.imul(b,ct)|0,o=o+Math.imul(b,ht)|0,o=o+Math.imul(g,ct)|0,c=c+Math.imul(g,ht)|0,a=a+Math.imul(p,lt)|0,o=o+Math.imul(p,dt)|0,o=o+Math.imul(m,lt)|0,c=c+Math.imul(m,dt)|0,a=a+Math.imul(l,pt)|0,o=o+Math.imul(l,mt)|0,o=o+Math.imul(d,pt)|0,c=c+Math.imul(d,mt)|0;let St=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(St>>>26)|0,St&=67108863,a=Math.imul(B,$),o=Math.imul(B,z),o=o+Math.imul(U,$)|0,c=Math.imul(U,z),a=a+Math.imul(C,W)|0,o=o+Math.imul(C,X)|0,o=o+Math.imul(V,W)|0,c=c+Math.imul(V,X)|0,a=a+Math.imul(_,Y)|0,o=o+Math.imul(_,J)|0,o=o+Math.imul(F,Y)|0,c=c+Math.imul(F,J)|0,a=a+Math.imul(A,Q)|0,o=o+Math.imul(A,tt)|0,o=o+Math.imul(T,Q)|0,c=c+Math.imul(T,tt)|0,a=a+Math.imul(N,rt)|0,o=o+Math.imul(N,it)|0,o=o+Math.imul(O,rt)|0,c=c+Math.imul(O,it)|0,a=a+Math.imul(P,st)|0,o=o+Math.imul(P,at)|0,o=o+Math.imul(E,st)|0,c=c+Math.imul(E,at)|0,a=a+Math.imul(v,ct)|0,o=o+Math.imul(v,ht)|0,o=o+Math.imul(I,ct)|0,c=c+Math.imul(I,ht)|0,a=a+Math.imul(b,lt)|0,o=o+Math.imul(b,dt)|0,o=o+Math.imul(g,lt)|0,c=c+Math.imul(g,dt)|0,a=a+Math.imul(p,pt)|0,o=o+Math.imul(p,mt)|0,o=o+Math.imul(m,pt)|0,c=c+Math.imul(m,mt)|0;let Nt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(Nt>>>26)|0,Nt&=67108863,a=Math.imul(B,W),o=Math.imul(B,X),o=o+Math.imul(U,W)|0,c=Math.imul(U,X),a=a+Math.imul(C,Y)|0,o=o+Math.imul(C,J)|0,o=o+Math.imul(V,Y)|0,c=c+Math.imul(V,J)|0,a=a+Math.imul(_,Q)|0,o=o+Math.imul(_,tt)|0,o=o+Math.imul(F,Q)|0,c=c+Math.imul(F,tt)|0,a=a+Math.imul(A,rt)|0,o=o+Math.imul(A,it)|0,o=o+Math.imul(T,rt)|0,c=c+Math.imul(T,it)|0,a=a+Math.imul(N,st)|0,o=o+Math.imul(N,at)|0,o=o+Math.imul(O,st)|0,c=c+Math.imul(O,at)|0,a=a+Math.imul(P,ct)|0,o=o+Math.imul(P,ht)|0,o=o+Math.imul(E,ct)|0,c=c+Math.imul(E,ht)|0,a=a+Math.imul(v,lt)|0,o=o+Math.imul(v,dt)|0,o=o+Math.imul(I,lt)|0,c=c+Math.imul(I,dt)|0,a=a+Math.imul(b,pt)|0,o=o+Math.imul(b,mt)|0,o=o+Math.imul(g,pt)|0,c=c+Math.imul(g,mt)|0;let Ot=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,a=Math.imul(B,Y),o=Math.imul(B,J),o=o+Math.imul(U,Y)|0,c=Math.imul(U,J),a=a+Math.imul(C,Q)|0,o=o+Math.imul(C,tt)|0,o=o+Math.imul(V,Q)|0,c=c+Math.imul(V,tt)|0,a=a+Math.imul(_,rt)|0,o=o+Math.imul(_,it)|0,o=o+Math.imul(F,rt)|0,c=c+Math.imul(F,it)|0,a=a+Math.imul(A,st)|0,o=o+Math.imul(A,at)|0,o=o+Math.imul(T,st)|0,c=c+Math.imul(T,at)|0,a=a+Math.imul(N,ct)|0,o=o+Math.imul(N,ht)|0,o=o+Math.imul(O,ct)|0,c=c+Math.imul(O,ht)|0,a=a+Math.imul(P,lt)|0,o=o+Math.imul(P,dt)|0,o=o+Math.imul(E,lt)|0,c=c+Math.imul(E,dt)|0,a=a+Math.imul(v,pt)|0,o=o+Math.imul(v,mt)|0,o=o+Math.imul(I,pt)|0,c=c+Math.imul(I,mt)|0;let xt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(xt>>>26)|0,xt&=67108863,a=Math.imul(B,Q),o=Math.imul(B,tt),o=o+Math.imul(U,Q)|0,c=Math.imul(U,tt),a=a+Math.imul(C,rt)|0,o=o+Math.imul(C,it)|0,o=o+Math.imul(V,rt)|0,c=c+Math.imul(V,it)|0,a=a+Math.imul(_,st)|0,o=o+Math.imul(_,at)|0,o=o+Math.imul(F,st)|0,c=c+Math.imul(F,at)|0,a=a+Math.imul(A,ct)|0,o=o+Math.imul(A,ht)|0,o=o+Math.imul(T,ct)|0,c=c+Math.imul(T,ht)|0,a=a+Math.imul(N,lt)|0,o=o+Math.imul(N,dt)|0,o=o+Math.imul(O,lt)|0,c=c+Math.imul(O,dt)|0,a=a+Math.imul(P,pt)|0,o=o+Math.imul(P,mt)|0,o=o+Math.imul(E,pt)|0,c=c+Math.imul(E,mt)|0;let At=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(At>>>26)|0,At&=67108863,a=Math.imul(B,rt),o=Math.imul(B,it),o=o+Math.imul(U,rt)|0,c=Math.imul(U,it),a=a+Math.imul(C,st)|0,o=o+Math.imul(C,at)|0,o=o+Math.imul(V,st)|0,c=c+Math.imul(V,at)|0,a=a+Math.imul(_,ct)|0,o=o+Math.imul(_,ht)|0,o=o+Math.imul(F,ct)|0,c=c+Math.imul(F,ht)|0,a=a+Math.imul(A,lt)|0,o=o+Math.imul(A,dt)|0,o=o+Math.imul(T,lt)|0,c=c+Math.imul(T,dt)|0,a=a+Math.imul(N,pt)|0,o=o+Math.imul(N,mt)|0,o=o+Math.imul(O,pt)|0,c=c+Math.imul(O,mt)|0;let Tt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,a=Math.imul(B,st),o=Math.imul(B,at),o=o+Math.imul(U,st)|0,c=Math.imul(U,at),a=a+Math.imul(C,ct)|0,o=o+Math.imul(C,ht)|0,o=o+Math.imul(V,ct)|0,c=c+Math.imul(V,ht)|0,a=a+Math.imul(_,lt)|0,o=o+Math.imul(_,dt)|0,o=o+Math.imul(F,lt)|0,c=c+Math.imul(F,dt)|0,a=a+Math.imul(A,pt)|0,o=o+Math.imul(A,mt)|0,o=o+Math.imul(T,pt)|0,c=c+Math.imul(T,mt)|0;let Mt=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,a=Math.imul(B,ct),o=Math.imul(B,ht),o=o+Math.imul(U,ct)|0,c=Math.imul(U,ht),a=a+Math.imul(C,lt)|0,o=o+Math.imul(C,dt)|0,o=o+Math.imul(V,lt)|0,c=c+Math.imul(V,dt)|0,a=a+Math.imul(_,pt)|0,o=o+Math.imul(_,mt)|0,o=o+Math.imul(F,pt)|0,c=c+Math.imul(F,mt)|0;let _t=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(_t>>>26)|0,_t&=67108863,a=Math.imul(B,lt),o=Math.imul(B,dt),o=o+Math.imul(U,lt)|0,c=Math.imul(U,dt),a=a+Math.imul(C,pt)|0,o=o+Math.imul(C,mt)|0,o=o+Math.imul(V,pt)|0,c=c+Math.imul(V,mt)|0;let Ft=(h+a|0)+((8191&o)<<13)|0;h=(c+(o>>>13)|0)+(Ft>>>26)|0,Ft&=67108863,a=Math.imul(B,pt),o=Math.imul(B,mt),o=o+Math.imul(U,pt)|0,c=Math.imul(U,mt);let Rt=(h+a|0)+((8191&o)<<13)|0;return h=(c+(o>>>13)|0)+(Rt>>>26)|0,Rt&=67108863,s[0]=wt,s[1]=bt,s[2]=gt,s[3]=yt,s[4]=vt,s[5]=It,s[6]=kt,s[7]=Pt,s[8]=Et,s[9]=St,s[10]=Nt,s[11]=Ot,s[12]=xt,s[13]=At,s[14]=Tt,s[15]=Mt,s[16]=_t,s[17]=Ft,s[18]=Rt,0!==h&&(s[19]=h,r.length++),r}bigMulTo(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;let i=0,n=0,s=0;for(;s<r.length-1;s++){let a=n;n=0;let o=67108863&i;const c=Math.min(s,e.length-1);for(let r=Math.max(0,s-t.length+1);r<=c;r++){const i=s-r,c=(0|t.words[i])*(0|e.words[r]);let h=67108863&c;a=a+(c/67108864|0)|0,h=h+o|0,o=67108863&h,a=a+(h>>>26)|0,n+=a>>>26,a&=67108863}r.words[s]=o,i=a,a=n}return 0!==i?r.words[s]=i:r.length--,r.strip()}mulTo(t,e){let r;const i=this.length+t.length;return r=10===this.length&&10===t.length?this.comb10MulTo(this,t,e):i<63?this.smallMulTo(this,t,e):this.bigMulTo(this,t,e),r}mul(t){const e=new h;return e.words=new Array(this.length+t.length),this.mulTo(t,e)}imul(t){return this.clone().mulTo(t,this)}imuln(t){const e=t<0;e&&(t=-t),this.assert("number"==typeof t),this.assert(t<67108864);let r=0,i=0;for(;i<this.length;i++){const e=(0|this.words[i])*t,n=(67108863&e)+(67108863&r);r>>=26,r+=e/67108864|0,r+=n>>>26,this.words[i]=67108863&n}return 0!==r&&(this.words[i]=r,this.length++),e?this.ineg():this}muln(t){return this.clone().imuln(t)}sqr(){return this.mul(this)}isqr(){return this.imul(this.clone())}pow(t){const e=h.toBitArray(t);if(0===e.length)return new h(1);let r=this,i=0;for(;i<e.length&&0===e[i];i++,r=r.sqr());if(++i<e.length)for(let t=r.sqr();i<e.length;i++,t=t.sqr())0!==e[i]&&(r=r.mul(t));return r}iushln(t){this.assert("number"==typeof t&&t>=0);const e=t%26,r=(t-e)/26,i=67108863>>>26-e<<26-e;let n;if(0!==e){let t=0;for(n=0;n<this.length;n++){const r=this.words[n]&i,s=(0|this.words[n])-r<<e;this.words[n]=s|t,t=r>>>26-e}0!==t&&(this.words[n]=t,this.length++)}if(0!==r){for(n=this.length-1;n>=0;n--)this.words[n+r]=this.words[n];for(n=0;n<r;n++)this.words[n]=0;this.length+=r}return this.strip()}ishln(t){return this.assert(0===this.negative),this.iushln(t)}iushrn(t,e,r){let i;this.assert("number"==typeof t&&t>=0),i="number"==typeof e&&0!==e?(e-e%26)/26:0;const n=t%26,s=Math.min((t-n)/26,this.length),a=67108863^67108863>>>n<<n,o=r;i-=s,i=Math.max(0,i);let c=0;if(void 0!==o){for(;c<s;c++)o.words[c]=this.words[c];o.length=s}if(0===s);else if(this.length>s)for(this.length-=s,c=0;c<this.length;c++)this.words[c]=this.words[c+s];else this.words[0]=0,this.length=1;let h=0;for(c=this.length-1;c>=0&&(0!==h||c>=i);c--){const t=0|this.words[c];this.words[c]=h<<26-n|t>>>n,h=t&a}return null!=o&&0!==h&&(o.words[o.length++]=h),0===this.length&&(this.words[0]=0,this.length=1),this.strip()}ishrn(t,e,r){return this.assert(0===this.negative),this.iushrn(t,e,r)}shln(t){return this.clone().ishln(t)}ushln(t){return this.clone().iushln(t)}shrn(t){return this.clone().ishrn(t)}ushrn(t){return this.clone().iushrn(t)}testn(t){this.assert("number"==typeof t&&t>=0);const e=t%26,r=(t-e)/26,i=1<<e;if(this.length<=r)return!1;const n=this.words[r];return Boolean(n&i)}imaskn(t){this.assert("number"==typeof t&&t>=0);const e=t%26;let r=(t-e)/26;if(this.assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==e&&r++,this.length=Math.min(r,this.length),0!==e){const t=67108863^67108863>>>e<<e;this.words[this.length-1]&=t}return this.strip()}maskn(t){return this.clone().imaskn(t)}iaddn(t){return this.assert("number"==typeof t),this.assert(t<67108864,"num is too large"),t<0?this.isubn(-t):0!==this.negative?1===this.length&&(0|this.words[0])<=t?(this.words[0]=t-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(t),this.negative=1,this):this._iaddn(t)}_iaddn(t){this.words[0]+=t;let e=0;for(;e<this.length&&this.words[e]>=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this}isubn(t){if(this.assert("number"==typeof t),this.assert(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(let t=0;t<this.length&&this.words[t]<0;t++)this.words[t]+=67108864,this.words[t+1]-=1;return this.strip()}addn(t){return this.clone().iaddn(t)}subn(t){return this.clone().isubn(t)}iabs(){return this.negative=0,this}abs(){return this.clone().iabs()}_ishlnsubmul(t,e,r){const i=t.length+r;let n,s;this.expand(i);let a=0;for(n=0;n<t.length;n++){s=(0|this.words[n+r])+a;const i=(0|t.words[n])*e;s-=67108863&i,a=(s>>26)-(i/67108864|0),this.words[n+r]=67108863&s}for(;n<this.length-r;n++)s=(0|this.words[n+r])+a,a=s>>26,this.words[n+r]=67108863&s;if(0===a)return this.strip();for(this.assert(-1===a,"carry must be -1"),a=0,n=0;n<this.length;n++)s=-(0|this.words[n])+a,a=s>>26,this.words[n]=67108863&s;return this.negative=1,this.strip()}wordDiv(t,e){let r=this.length-t.length,i=this.clone(),n=t,s=0|n.words[n.length-1];r=26-this.countWordBits(s),0!==r&&(n=n.ushln(r),i.iushln(r),s=0|n.words[n.length-1]);const a=i.length-n.length;let o;if("mod"!==e){o=new h,o.length=a+1,o.words=new Array(o.length);for(let t=0;t<o.length;t++)o.words[t]=0}const c=i.clone()._ishlnsubmul(n,1,a);0===c.negative&&(i=c,void 0!==o&&(o.words[a]=1));for(let t=a-1;t>=0;t--){let e=67108864*(0|i.words[n.length+t])+(0|i.words[n.length+t-1]);for(e=Math.min(e/s|0,67108863),i._ishlnsubmul(n,e,t);0!==i.negative;)e--,i.negative=0,i._ishlnsubmul(n,1,t),i.isZero()||(i.negative^=1);void 0!==o&&(o.words[t]=e)}return void 0!==o&&o.strip(),i.strip(),"div"!==e&&0!==r&&i.iushrn(r),{div:o??null,mod:i}}divmod(t,e,r){if(this.assert(!t.isZero()),this.isZero())return{div:new h(0),mod:new h(0)};let i,n,s;return 0!==this.negative&&0===t.negative?(s=this.neg().divmod(t,e),"mod"!==e&&(i=s.div.neg()),"div"!==e&&(n=s.mod.neg(),!0===r&&0!==n.negative&&n.iadd(t)),{div:i,mod:n}):0===this.negative&&0!==t.negative?(s=this.divmod(t.neg(),e),"mod"!==e&&(i=s.div.neg()),{div:i,mod:s.mod}):this.negative&t.negative?(s=this.neg().divmod(t.neg(),e),"div"!==e&&(n=s.mod.neg(),!0===r&&0!==n.negative&&n.isub(t)),{div:s.div,mod:n}):t.length>this.length||this.cmp(t)<0?{div:new h(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new h(this.modrn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new h(this.modrn(t.words[0]))}:this.wordDiv(t,e)}div(t){return this.divmod(t,"div",!1).div}mod(t){return this.divmod(t,"mod",!1).mod}umod(t){return this.divmod(t,"mod",!0).mod}divRound(t){const e=this.divmod(t);if(e.mod.isZero())return e.div;const r=0!==e.div.negative?e.mod.isub(t):e.mod,i=t.ushrn(1),n=t.andln(1),s=r.cmp(i);return s<0||1===n&&0===s?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)}modrn(t){const e=t<0;e&&(t=-t),this.assert(t<=67108863);const r=(1<<26)%t;let i=0;for(let e=this.length-1;e>=0;e--)i=(r*i+(0|this.words[e]))%t;return e?-i:i}idivn(t){const e=t<0;e&&(t=-t),this.assert(t<=67108863);let r=0;for(let e=this.length-1;e>=0;e--){const i=(0|this.words[e])+67108864*r;this.words[e]=i/t|0,r=i%t}return this.strip(),e?this.ineg():this}divn(t){return this.clone().idivn(t)}egcd(t){this.assert(0===t.negative,"p must not be negative"),this.assert(!t.isZero(),"p must not be zero");let e=this;const r=t.clone();e=0!==e.negative?e.umod(t):e.clone();const i=new h(1),n=new h(0),s=new h(0),a=new h(1);let o=0;for(;e.isEven()&&r.isEven();)e.iushrn(1),r.iushrn(1),++o;const c=r.clone(),u=e.clone();for(;!e.isZero();){let t=0,o=1;for(;!(e.words[0]&o)&&t<26;++t,o<<=1);if(t>0)for(e.iushrn(t);t-- >0;)(i.isOdd()||n.isOdd())&&(i.iadd(c),n.isub(u)),i.iushrn(1),n.iushrn(1);let h=0,l=1;for(;!(r.words[0]&l)&&h<26;++h,l<<=1);if(h>0)for(r.iushrn(h);h-- >0;)(s.isOdd()||a.isOdd())&&(s.iadd(c),a.isub(u)),s.iushrn(1),a.iushrn(1);e.cmp(r)>=0?(e.isub(r),i.isub(s),n.isub(a)):(r.isub(e),s.isub(i),a.isub(n))}return{a:s,b:a,gcd:r.iushln(o)}}_invmp(t){this.assert(0===t.negative,"p must not be negative"),this.assert(!t.isZero(),"p must not be zero");let e=this;const r=t.clone();e=0!==e.negative?e.umod(t):e.clone();const i=new h(1),n=new h(0),s=r.clone();for(;e.cmpn(1)>0&&r.cmpn(1)>0;){let t=0,a=1;for(;!(e.words[0]&a)&&t<26;++t,a<<=1);if(t>0)for(e.iushrn(t);t-- >0;)i.isOdd()&&i.iadd(s),i.iushrn(1);let o=0,c=1;for(;!(r.words[0]&c)&&o<26;++o,c<<=1);if(o>0)for(r.iushrn(o);o-- >0;)n.isOdd()&&n.iadd(s),n.iushrn(1);e.cmp(r)>=0?(e.isub(r),i.isub(n)):(r.isub(e),n.isub(i))}let a;return a=0===e.cmpn(1)?i:n,a.cmpn(0)<0&&a.iadd(t),a}gcd(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();let e=this.clone(),r=t.clone();e.negative=0,r.negative=0;let i=0;for(;e.isEven()&&r.isEven();i++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);const t=e.cmp(r);if(t<0){const t=e;e=r,r=t}else if(0===t||0===r.cmpn(1))break;e.isub(r)}return r.iushln(i)}invm(t){return this.egcd(t).a.umod(t)}isEven(){return!(1&this.words[0])}isOdd(){return!(1&~this.words[0])}andln(t){return this.words[0]&t}bincn(t){this.assert("number"==typeof t);const e=t%26,r=(t-e)/26,i=1<<e;if(this.length<=r)return this.expand(r+1),this.words[r]|=i,this;let n=i,s=r;for(;0!==n&&s<this.length;s++){let t=0|this.words[s];t+=n,n=t>>>26,t&=67108863,this.words[s]=t}return 0!==n&&(this.words[s]=n,this.length++),this}isZero(){return 1===this.length&&0===this.words[0]}cmpn(t){const e=t<0;if(0!==this.negative&&!e)return-1;if(0===this.negative&&e)return 1;let r;if(this.strip(),this.length>1)r=1;else{e&&(t=-t),this.assert(t<=67108863,"Number is too big");const i=0|this.words[0];r=i===t?0:i<t?-1:1}return 0!==this.negative?0|-r:r}cmp(t){if(0!==this.negative&&0===t.negative)return-1;if(0===this.negative&&0!==t.negative)return 1;const e=this.ucmp(t);return 0!==this.negative?0|-e:e}ucmp(t){if(this.length>t.length)return 1;if(this.length<t.length)return-1;let e=0;for(let r=this.length-1;r>=0;r--){const i=0|this.words[r],n=0|t.words[r];if(i!==n){i<n?e=-1:i>n&&(e=1);break}}return e}gtn(t){return 1===this.cmpn(t)}gt(t){return 1===this.cmp(t)}gten(t){return this.cmpn(t)>=0}gte(t){return this.cmp(t)>=0}ltn(t){return-1===this.cmpn(t)}lt(t){return-1===this.cmp(t)}lten(t){return this.cmpn(t)<=0}lte(t){return this.cmp(t)<=0}eqn(t){return 0===this.cmpn(t)}eq(t){return 0===this.cmp(t)}toRed(t){return this.assert(null==this.red,"Already a number in reduction context"),this.assert(0===this.negative,"red works only with positives"),t.convertTo(this).forceRed(t)}fromRed(){return this.assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)}forceRed(t){return this.red=t,this}redAdd(t){return this.assert(this.red,"redAdd works only with red numbers"),this.red.add(this,t)}redIAdd(t){return this.assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)}redSub(t){return this.assert(this.red,"redSub works only with red numbers"),this.red.sub(this,t)}redISub(t){return this.assert(this.red,"redISub works only with red numbers"),this.red.isub(this,t)}redShl(t){return this.assert(this.red,"redShl works only with red numbers"),this.red.shl(this,t)}redMul(t){return this.assert(this.red,"redMul works only with red numbers"),this.red.verify2(this,t),this.red.mul(this,t)}redIMul(t){return this.assert(this.red,"redMul works only with red numbers"),this.red.verify2(this,t),this.red.imul(this,t)}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(t){return this.assert(null!=this.red&&null==t.red,"redPow(normalNum)"),this.red.verify1(this),this.red.pow(this,t)}static fromHex(t,e){return"big"===e?new h(t,16):new h(t,16,"le")}toHex(t=0){return this.toString("hex",2*t)}static fromJSON(t){return new h(t)}static fromNumber(t){return new h(t)}static fromString(t,e){return new h(t,e)}static fromSm(t,e="big"){let r=t;return 0===t.length?new h(0):("little"===e&&(r=[...r],r=r.reverse()),128&r[0]?(r=[...r],r[0]=127&r[0],new h(r).neg()):new h(r))}toSm(t="big"){let e;return-1===this.cmpn(0)?(e=this.neg().toArray(),128&e[0]?e=[128,...e]:e[0]=128|e[0]):(e=this.toArray(),128&e[0]&&(e=[0,...e])),1===e.length&&0===e[0]&&(e=[]),"little"===t&&(e=e.reverse()),e}static fromBits(t,e=!1){if(t=2147483648&t?t-4294967296:t,e&&8388608&t)throw new Error("negative bit set");const r=t>>24,i=8388607&t;let n=[i>>24&255,i>>16&255,i>>8&255,255&i];if(r<=3)n=n.slice(1,1+r);else for(let t=0;t<r-3;t++)n.push(0);return 8388608&t?new h(n).neg():new h(n)}toBits(){let t;for(t=this.ltn(0)?this.neg().toArray("be"):this.toArray("be");t.length<4;)t.unshift(0);if(t.every((t=>0===t)))return 0;for(;0===t[0];)t.shift();let e=t.length,r=t.slice(0,3).reduce(((t,e)=>256*t+e),0);8388608&r&&(t.unshift(0),e+=1,r>>>=8);let i=e<<24|r;return this.ltn(0)&&(i|=8388608),i>>>0}static fromScriptNum(t,e,r){if(void 0===r&&(r=Number.MAX_SAFE_INTEGER),t.length>r)throw new Error("script number overflow");if(!0===e&&t.length>0&&!(127&t[t.length-1]||!(t.length<=1)&&128&t[t.length-2]))throw new Error("non-minimally encoded script number");return h.fromSm(t,"little")}toScriptNum(){return this.toSm("little")}}class u{name;p;k;n;tmp;constructor(t,e){this.name=t,this.p=new h(e,16),this.n=this.p.bitLength(),this.k=new h(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}_tmp(){const t=new h;return t.words=new Array(Math.ceil(this.n/13)),t}ireduce(t){let e,r=t;do{this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),e=r.bitLength()}while(e>this.n);const i=e<this.n?-1:r.ucmp(this.p);return 0===i?(r.words[0]=0,r.length=1):i>0?r.isub(this.p):(r.strip,r.strip()),r}split(t,e){t.iushrn(this.n,0,e)}imulK(t){return t.imul(this.k)}}class l extends u{constructor(){super("k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}split(t,e){const r=4194303,i=Math.min(t.length,9);let n=0;for(;n<i;n++)e.words[n]=t.words[n];if(e.length=i,t.length<=9)return t.words[0]=0,void(t.length=1);let s=t.words[9];for(e.words[e.length++]=s&r,n=10;n<t.length;n++){const e=0|t.words[n];t.words[n-10]=(e&r)<<4|s>>>22,s=e}s>>>=22,t.words[n-10]=s,0===s&&t.length>10?t.length-=10:t.length-=9}imulK(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;let e=0;for(let r=0;r<t.length;r++){const i=0|t.words[r];e+=977*i,t.words[r]=67108863&e,e=64*i+(e/67108864|0)}return 0===t.words[t.length-1]&&(t.length--,0===t.words[t.length-1]&&t.length--),t}}class d{prime;m;constructor(t){if("k256"===t){const t=new l;this.m=t.p,this.prime=t}else this.assert(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}assert(t,e="Assertion failed"){if(!t)throw new Error(e)}verify1(t){this.assert(0===t.negative,"red works only with positives"),this.assert(t.red,"red works only with red numbers")}verify2(t,e){this.assert(!(t.negative|e.negative),"red works only with positives"),this.assert(null!=t.red&&t.red===e.red,"red works only with red numbers")}imod(t){return null!=this.prime?this.prime.ireduce(t).forceRed(this):(h.move(t,t.umod(this.m).forceRed(this)),t)}neg(t){return t.isZero()?t.clone():this.m.sub(t).forceRed(this)}add(t,e){this.verify2(t,e);const r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r.forceRed(this)}iadd(t,e){this.verify2(t,e);const r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r}sub(t,e){this.verify2(t,e);const r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r.forceRed(this)}isub(t,e){this.verify2(t,e);const r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r}shl(t,e){return this.verify1(t),this.imod(t.ushln(e))}imul(t,e){return this.verify2(t,e),this.imod(t.imul(e))}mul(t,e){return this.verify2(t,e),this.imod(t.mul(e))}isqr(t){return this.imul(t,t.clone())}sqr(t){return this.mul(t,t)}sqrt(t){if(t.isZero())return t.clone();const e=this.m.andln(3);if(this.assert(e%2==1),3===e){const e=this.m.add(new h(1)).iushrn(2);return this.pow(t,e)}const r=this.m.subn(1);let i=0;for(;!r.isZero()&&0===r.andln(1);)i++,r.iushrn(1);this.assert(!r.isZero());const n=new h(1).toRed(this),s=n.redNeg(),a=this.m.subn(1).iushrn(1),o=this.m.bitLength(),c=new h(2*o*o).toRed(this);for(;0!==this.pow(c,a).cmp(s);)c.redIAdd(s);let u=this.pow(c,r),l=this.pow(t,r.addn(1).iushrn(1)),d=this.pow(t,r),f=i;for(;0!==d.cmp(n);){let t=d,e=0;for(;0!==t.cmp(n);e++)t=t.redSqr();this.assert(e<f);const r=this.pow(u,new h(1).iushln(f-e-1));l=l.redMul(r),u=r.redSqr(),d=d.redMul(u),f=e}return l}invm(t){const e=t._invmp(this.m);return 0!==e.negative?(e.negative=0,this.imod(e).redNeg()):this.imod(e)}pow(t,e){if(e.isZero())return new h(1).toRed(this);if(0===e.cmpn(1))return t.clone();const r=new Array(16);r[0]=new h(1).toRed(this),r[1]=t;let i=2;for(;i<r.length;i++)r[i]=this.mul(r[i-1],t);let n=r[0],s=0,a=0,o=e.bitLength()%26;for(0===o&&(o=26),i=e.length-1;i>=0;i--){const t=e.words[i];for(let e=o-1;e>=0;e--){const o=t>>e&1;n!==r[0]&&(n=this.sqr(n)),0!==o||0!==s?(s<<=1,s|=o,a++,(4===a||0===i&&0===e)&&(n=this.mul(n,r[s]),a=0,s=0)):a=0}o=26}return n}convertTo(t){const e=t.umod(this.m);return e===t?e.clone():e}convertFrom(t){const e=t.clone();return e.red=null,e}}class f extends d{shift;r;r2;rinv;minv;constructor(t){super(t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new h(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(t){return this.imod(t.ushln(this.shift))}convertFrom(t){const e=this.imod(t.mul(this.rinv));return e.red=null,e}imul(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;const r=t.imul(e),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=r.isub(i).iushrn(this.shift);let s=n;return n.cmp(this.m)>=0?s=n.isub(this.m):n.cmpn(0)<0&&(s=n.iadd(this.m)),s.forceRed(this)}mul(t,e){if(t.isZero()||e.isZero())return new h(0).forceRed(this);const r=t.mul(e),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=r.isub(i).iushrn(this.shift);let s=n;return n.cmp(this.m)>=0?s=n.isub(this.m):n.cmpn(0)<0&&(s=n.iadd(this.m)),s.forceRed(this)}invm(t){return this.imod(t._invmp(this.m).mul(this.r2)).forceRed(this)}}class p{curve;type;precomputed;constructor(t){this.curve=new Lt,this.type=t,this.precomputed=null}}class m extends p{x;y;z;zOne;constructor(t,e,r){super("jacobian"),null===t&&null===e&&null===r?(this.x=this.curve.one,this.y=this.curve.one,this.z=new h(0)):(h.isBN(t)||(t=new h(t,16)),this.x=t,h.isBN(e)||(e=new h(e,16)),this.y=e,h.isBN(r)||(r=new h(r,16)),this.z=r),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}toP(){if(this.isInfinity())return new Kt(null,null);const t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),i=this.y.redMul(e).redMul(t);return new Kt(r,i)}neg(){return new m(this.x,this.y.redNeg(),this.z)}add(t){if(this.isInfinity())return t;if(t.isInfinity())return this;const e=t.z.redSqr(),r=this.z.redSqr(),i=this.x.redMul(e),n=t.x.redMul(r),s=this.y.redMul(e.redMul(t.z)),a=t.y.redMul(r.redMul(this.z)),o=i.redSub(n),c=s.redSub(a);if(0===o.cmpn(0))return 0!==c.cmpn(0)?new m(null,null,null):this.dbl();const h=o.redSqr(),u=h.redMul(o),l=i.redMul(h),d=c.redSqr().redIAdd(u).redISub(l).redISub(l),f=c.redMul(l.redISub(d)).redISub(s.redMul(u)),p=this.z.redMul(t.z).redMul(o);return new m(d,f,p)}mixedAdd(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;if(null===t.x||null===t.y)throw new Error("Point coordinates cannot be null");const e=this.z.redSqr(),r=this.x,i=t.x.redMul(e),n=this.y,s=t.y.redMul(e).redMul(this.z),a=r.redSub(i),o=n.redSub(s);if(0===a.cmpn(0))return 0!==o.cmpn(0)?new m(null,null,null):this.dbl();const c=a.redSqr(),h=c.redMul(a),u=r.redMul(c),l=o.redSqr().redIAdd(h).redISub(u).redISub(u),d=o.redMul(u.redISub(l)).redISub(n.redMul(h)),f=this.z.redMul(a);return new m(l,d,f)}dblp(t){if(0===t)return this;if(this.isInfinity())return this;if(void 0===t)return this.dbl();let e=this;for(let r=0;r<t;r++)e=e.dbl();return e}dbl(){if(this.isInfinity())return this;let t,e,r;if(this.zOne){const i=this.x.redSqr(),n=this.y.redSqr(),s=n.redSqr();let a=this.x.redAdd(n).redSqr().redISub(i).redISub(s);a=a.redIAdd(a);const o=i.redAdd(i).redIAdd(i),c=o.redSqr().redISub(a).redISub(a);let h=s.redIAdd(s);h=h.redIAdd(h),h=h.redIAdd(h),t=c,e=o.redMul(a.redISub(c)).redISub(h),r=this.y.redAdd(this.y)}else{const i=this.x.redSqr(),n=this.y.redSqr(),s=n.redSqr();let a=this.x.redAdd(n).redSqr().redISub(i).redISub(s);a=a.redIAdd(a);const o=i.redAdd(i).redIAdd(i),c=o.redSqr();let h=s.redIAdd(s);h=h.redIAdd(h),h=h.redIAdd(h),t=c.redISub(a).redISub(a),e=o.redMul(a.redISub(t)).redISub(h),r=this.y.redMul(this.z),r=r.redIAdd(r)}return new m(t,e,r)}eq(t){if("affine"===t.type)return this.eq(t.toJ());if(this===t)return!0;const e=this.z.redSqr(),r=t.z.redSqr();if(0!==this.x.redMul(r).redISub(t.x.redMul(e)).cmpn(0))return!1;const i=e.redMul(this.z),n=r.redMul(t.z);return 0===this.y.redMul(n).redISub(t.y.redMul(i)).cmpn(0)}eqXToP(t){const e=this.z.redSqr(),r=t.toRed(this.curve?.red).redMul(e);if(0===this.x.cmp(r))return!0;const i=t.clone();if(null===this.curve||null==this.curve.redN)throw new Error("Curve or redN is not initialized.");const n=this.curve.redN.redMul(e);for(;i.cmp(this.curve.p)<0;){if(i.iadd(this.curve.n),i.cmp(this.curve.p)>=0)return!1;if(r.redIAdd(n),0===this.x.cmp(r))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)}}const w=(t,e="Hash assertion failed")=>{if(!t)throw new Error(e)};class b{pending;pendingTotal;blockSize;outSize;endian;_delta8;_delta32;padLength;hmacStrength;constructor(t,e,r,i){this.pending=null,this.pendingTotal=0,this.blockSize=t,this.outSize=e,this.hmacStrength=r,this.padLength=i/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}_update(t,e){throw new Error("Not implemented")}_digest(){throw new Error("Not implemented")}_digestHex(){throw new Error("Not implemented")}update(t,e){if(t=y(t,e),null==this.pending?this.pending=t:this.pending=this.pending.concat(t),this.pendingTotal+=t.length,this.pending.length>=this._delta8){const e=(t=this.pending).length%this._delta8;this.pending=t.slice(t.length-e,t.length),0===this.pending.length&&(this.pending=null),t=function(t,e,r,i){const n=r-0;w(n%4==0);const s=new Array(n/4);for(let e=0,r=0;e<s.length;e++,r+=4){let n;n="big"===i?t[r]<<24|t[r+1]<<16|t[r+2]<<8|t[r+3]:t[r+3]<<24|t[r+2]<<16|t[r+1]<<8|t[r],s[e]=n>>>0}return s}(t,0,t.length-e,this.endian);for(let e=0;e<t.length;e+=this._delta32)this._update(t,e)}return this}digest(){return this.update(this._pad()),w(null===this.pending),this._digest()}digestHex(){return this.update(this._pad()),w(null===this.pending),this._digestHex()}_pad(){let t=this.pendingTotal;const e=this._delta8,r=e-(t+this.padLength)%e,i=new Array(r+this.padLength);let n,s;for(i[0]=128,n=1;n<r;n++)i[n]=0;if(t<<=3,"big"===this.endian){for(s=8;s<this.padLength;s++)i[n++]=0;i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=t>>>24&255,i[n++]=t>>>16&255,i[n++]=t>>>8&255,i[n++]=255&t}else for(i[n++]=255&t,i[n++]=t>>>8&255,i[n++]=t>>>16&255,i[n++]=t>>>24&255,i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=0,s=8;s<this.padLength;s++)i[n++]=0;return i}}function g(t,e){return 55296==(64512&t.charCodeAt(e))&&!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1))}function y(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];const r=[];if("string"==typeof t)if("hex"!==e){let e=0;for(let i=0;i<t.length;i++){let n=t.charCodeAt(i);n<128?r[e++]=n:n<2048?(r[e++]=n>>6|192,r[e++]=63&n|128):g(t,i)?(n=65536+((1023&n)<<10)+(1023&t.charCodeAt(++i)),r[e++]=n>>18|240,r[e++]=n>>12&63|128,r[e++]=n>>6&63|128,r[e++]=63&n|128):(r[e++]=n>>12|224,r[e++]=n>>6&63|128,r[e++]=63&n|128)}}else{(t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t);for(let e=0;e<t.length;e+=2)r.push(parseInt(t[e]+t[e+1],16))}else for(let e=0;e<t.length;e++)r[e]=0|t[e];return r}function v(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}function I(t,e){let r="";for(let n=0;n<t.length;n++){let s=t[n];"little"===e&&(s=v(s)),r+=7===(i=s.toString(16)).length?"0"+i:6===i.length?"00"+i:5===i.length?"000"+i:4===i.length?"0000"+i:3===i.length?"00000"+i:2===i.length?"000000"+i:1===i.length?"0000000"+i:i}var i;return r}function k(t,e){const r=new Array(4*t.length);for(let i=0,n=0;i<t.length;i++,n+=4){const s=t[i];"big"===e?(r[n]=s>>>24,r[n+1]=s>>>16&255,r[n+2]=s>>>8&255,r[n+3]=255&s):(r[n+3]=s>>>24,r[n+2]=s>>>16&255,r[n+1]=s>>>8&255,r[n]=255&s)}return r}function P(t,e){return t>>>e|t<<32-e}function E(t,e){return t<<e|t>>>32-e}function S(t,e){return t+e>>>0}function N(t,e,r){return t+e+r>>>0}function O(t,e,r,i){return t+e+r+i>>>0}function x(t,e,r,i,n){return t+e+r+i+n>>>0}function A(t,e,r,i){return 0===t?T(e,r,i):1===t||3===t?function(t,e,r){return t^e^r}(e,r,i):2===t?M(e,r,i):void 0}function T(t,e,r){return t&e^~t&r}function M(t,e,r){return t&e^t&r^e&r}function _(t){return P(t,2)^P(t,13)^P(t,22)}function F(t){return P(t,6)^P(t,11)^P(t,25)}function R(t){return P(t,7)^P(t,18)^t>>>3}const C=[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],V=[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],D=[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],B=[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 U(t,e,r,i){return t<=15?e^r^i:t<=31?e&r|~e&i:t<=47?(e|~r)^i:t<=63?e&i|r&~i:e^(r|~i)}function H(t){return t<=15?0:t<=31?1518500249:t<=47?1859775393:t<=63?2400959708:2840853838}function K(t){return t<=15?1352829926:t<=31?1548603684:t<=47?1836072691:t<=63?2053994217:0}function q(t,e,r,i){const n=t[e],s=i+t[e+1]>>>0,a=(s<i?1:0)+r+n;t[e]=a>>>0,t[e+1]=s}function L(t,e,r,i){return(e+i>>>0<e?1:0)+t+r>>>0}function $(t,e,r,i){return e+i>>>0}function z(t,e,r,i,n,s,a,o){let c=0,h=e;return h=h+i>>>0,c+=h<e?1:0,h=h+s>>>0,c+=h<s?1:0,h=h+o>>>0,c+=h<o?1:0,t+r+n+a+c>>>0}function j(t,e,r,i,n,s,a,o,c,h){let u=0,l=e;return l=l+i>>>0,u+=l<e?1:0,l=l+s>>>0,u+=l<s?1:0,l=l+o>>>0,u+=l<o?1:0,l=l+h>>>0,u+=l<h?1:0,t+r+n+a+c+u>>>0}function W(t,e,r){return(e<<32-r|t>>>r)>>>0}function X(t,e,r){return(t<<32-r|e>>>r)>>>0}function G(t,e,r){return t>>>r}function Y(t,e,r){return(t<<32-r|e>>>r)>>>0}class J extends b{h;constructor(){super(512,160,192,64),this.endian="little",this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}_update(t,e){let r,i=this.h[0],n=this.h[1],s=this.h[2],a=this.h[3],o=this.h[4],c=i,h=n,u=s,l=a,d=o;for(let f=0;f<80;f++)r=S(E(O(i,U(f,n,s,a),t[C[f]+e],H(f)),D[f]),o),i=o,o=a,a=E(s,10),s=n,n=r,r=S(E(O(c,U(79-f,h,u,l),t[V[f]+e],K(f)),B[f]),d),c=d,d=l,l=E(u,10),u=h,h=r;r=N(this.h[1],s,l),this.h[1]=N(this.h[2],a,d),this.h[2]=N(this.h[3],o,c),this.h[3]=N(this.h[4],i,h),this.h[4]=N(this.h[0],n,u),this.h[0]=r}_digest(){return k(this.h,"little")}_digestHex(){return I(this.h,"little")}}class Z extends b{h;W;k;constructor(){super(512,256,192,64),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],this.W=new Array(64)}_update(t,e){const r=this.W;let i;for(void 0===e&&(e=0),i=0;i<16;i++)r[i]=t[e+i];for(;i<r.length;i++)r[i]=O(P(n=r[i-2],17)^P(n,19)^n>>>10,r[i-7],R(r[i-15]),r[i-16]);var n;let s=this.h[0],a=this.h[1],o=this.h[2],c=this.h[3],h=this.h[4],u=this.h[5],l=this.h[6],d=this.h[7];for(w(this.k.length===r.length),i=0;i<r.length;i++){const t=x(d,F(h),T(h,u,l),this.k[i],r[i]),e=S(_(s),M(s,a,o));d=l,l=u,u=h,h=S(c,t),c=o,o=a,a=s,s=S(t,e)}this.h[0]=S(this.h[0],s),this.h[1]=S(this.h[1],a),this.h[2]=S(this.h[2],o),this.h[3]=S(this.h[3],c),this.h[4]=S(this.h[4],h),this.h[5]=S(this.h[5],u),this.h[6]=S(this.h[6],l),this.h[7]=S(this.h[7],d)}_digest(){return k(this.h,"big")}_digestHex(){return I(this.h,"big")}}class Q extends b{h;W;k;constructor(){super(512,160,80,64),this.k=[1518500249,1859775393,2400959708,3395469782],this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}_update(t,e){const r=this.W;let i;for(void 0===e&&(e=0),i=0;i<16;i++)r[i]=t[e+i];for(;i<r.length;i++)r[i]=E(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],c=this.h[4];for(i=0;i<r.length;i++){const t=~~(i/20),e=x(E(n,5),A(t,s,a,o),c,r[i],this.k[t]);c=o,o=a,a=E(s,30),s=n,n=e}this.h[0]=S(this.h[0],n),this.h[1]=S(this.h[1],s),this.h[2]=S(this.h[2],a),this.h[3]=S(this.h[3],o),this.h[4]=S(this.h[4],c)}_digest(){return k(this.h,"big")}_digestHex(){return I(this.h,"big")}}class tt extends b{h;W;k;constructor(){super(1024,512,192,128),this.h=[1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209],this.k=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],this.W=new Array(160)}_prepareBlock(t,e){const r=this.W;let i;for(i=0;i<32;i++)r[i]=t[e+i];for(;i<r.length;i+=2){const t=lt(r[i-4],r[i-3]),e=dt(r[i-4],r[i-3]),n=r[i-14],s=r[i-13],a=ht(r[i-30],r[i-29]),o=ut(r[i-30],r[i-29]),c=r[i-32],h=r[i-31];r[i]=z(t,e,n,s,a,o,c,h),r[i+1]=e+s+o+h>>>0}}_update(t,e){this._prepareBlock(t,e);const r=this.W;let i=this.h[0],n=this.h[1],s=this.h[2],a=this.h[3],o=this.h[4],c=this.h[5],h=this.h[6],u=this.h[7],l=this.h[8],d=this.h[9],f=this.h[10],p=this.h[11],m=this.h[12],b=this.h[13],g=this.h[14],y=this.h[15];w(this.k.length===r.length);for(let t=0;t<r.length;t+=2){let e=g,w=y,v=ot(l,d),I=ct(l,d);const k=et(l,0,f,0,m),P=rt(0,d,0,p,0,b),E=this.k[t],S=this.k[t+1],N=r[t],O=r[t+1],x=j(e,w,v,I,k,P,E,S,N,O),A=w+I+P+S+O>>>0;e=st(i,n),w=at(i,n),v=it(i,0,s,0,o),I=nt(0,n,0,a,0,c);const T=L(e,w,v,I),M=$(0,w,0,I);g=m,y=b,m=f,b=p,f=l,p=d,l=L(h,u,x,A),d=$(0,u,0,A),h=o,u=c,o=s,c=a,s=i,a=n,i=L(x,A,T,M),n=$(0,A,0,M)}q(this.h,0,i,n),q(this.h,2,s,a),q(this.h,4,o,c),q(this.h,6,h,u),q(this.h,8,l,d),q(this.h,10,f,p),q(this.h,12,m,b),q(this.h,14,g,y)}_digest(){return k(this.h,"big")}_digestHex(){return I(this.h,"big")}}function et(t,e,r,i,n,s){let a=t&r^~t&n;return a<0&&(a+=4294967296),a}function rt(t,e,r,i,n,s){let a=e&i^~e&s;return a<0&&(a+=4294967296),a}function it(t,e,r,i,n,s){let a=t&r^t&n^r&n;return a<0&&(a+=4294967296),a}function nt(t,e,r,i,n,s){let a=e&i^e&s^i&s;return a<0&&(a+=4294967296),a}function st(t,e){let r=W(t,e,28)^W(e,t,2)^W(e,t,7);return r<0&&(r+=4294967296),r}function at(t,e){let r=X(t,e,28)^X(e,t,2)^X(e,t,7);return r<0&&(r+=4294967296),r}function ot(t,e){let r=W(t,e,14)^W(t,e,18)^W(e,t,9);return r<0&&(r+=4294967296),r}function ct(t,e){let r=X(t,e,14)^X(t,e,18)^X(e,t,9);return r<0&&(r+=4294967296),r}function ht(t,e){let r=W(t,e,1)^W(t,e,8)^G(t,0,7);return r<0&&(r+=4294967296),r}function ut(t,e){let r=X(t,e,1)^X(t,e,8)^Y(t,e,7);return r<0&&(r+=4294967296),r}function lt(t,e){let r=W(t,e,19)^W(e,t,29)^G(t,0,6);return r<0&&(r+=4294967296),r}function dt(t,e){let r=X(t,e,19)^X(e,t,29)^Y(t,e,6);return r<0&&(r+=4294967296),r}class ft{inner;outer;blockSize=64;outSize=32;constructor(t){let e;for((t=y(t,"hex")).length>this.blockSize&&(t=(new Z).update(t).digest()),w(t.length<=this.blockSize),e=t.length;e<this.blockSize;e++)t.push(0);for(e=0;e<t.length;e++)t[e]^=54;for(this.inner=(new Z).update(t),e=0;e<t.length;e++)t[e]^=106;this.outer=(new Z).update(t)}update(t,e){return this.inner.update(t,e),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}}class pt{inner;outer;blockSize=64;constructor(t){let e;for((t=y(t,"hex")).length>this.blockSize&&(t=(new Q).update(t).digest()),e=t.length;e<this.blockSize;e++)t.push(0);for(e=0;e<t.length;e++)t[e]^=54;for(this.inner=(new Q).update(t),e=0;e<t.length;e++)t[e]^=106;this.outer=(new Q).update(t)}update(t,e){return this.inner.update(t,e),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}}class mt{inner;outer;blockSize=128;outSize=32;constructor(t){let e;for((t=y(t,"hex")).length>this.blockSize&&(t=(new tt).update(t).digest()),w(t.length<=this.blockSize),e=t.length;e<this.blockSize;e++)t.push(0);for(e=0;e<t.length;e++)t[e]^=54;for(this.inner=(new tt).update(t),e=0;e<t.length;e++)t[e]^=106;this.outer=(new tt).update(t)}update(t,e){return this.inner.update(t,e),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}}const wt=(t,e)=>(new J).update(t,e).digest(),bt=(t,e)=>(new Q).update(t,e).digest(),gt=(t,e)=>(new Z).update(t,e).digest(),yt=(t,e)=>(new tt).update(t,e).digest(),vt=(t,e)=>{const r=(new Z).update(t,e).digest();return(new Z).update(r).digest()},It=(t,e)=>{const r=(new Z).update(t,e).digest();return(new J).update(r).digest()},kt=(t,e,r)=>new ft(t).update(e,r).digest(),Pt=(t,e,r)=>new mt(t).update(e,r).digest();function Et(t,e,r,i,n="sha512"){if("sha512"!==n)throw new Error("Only sha512 is supported in this PBKDF2 implementation");const s=new Array(i),a=[...e,0,0,0,0];let o=0;const c=Math.ceil(i/64);for(let i=1;i<=c;i++){a[e.length]=i>>24&255,a[e.length+1]=i>>16&255,a[e.length+2]=i>>8&255,a[e.length+3]=255&i;const n=Pt(t,a);let c=n;for(let e=1;e<r;e++){c=Pt(t,c);for(let t=0;t<64;t++)n[t]^=c[t]}for(let t=0;t<n.length;t++)s[o+t]=n[t];o+=64}return s.slice(0,i)}const St=t=>t.length%2==1?"0"+t:t,Nt=t=>{let e="";for(const r of t)e+=St(r.toString(16));return e},Ot=(t,e)=>{if(Array.isArray(t))return t.slice();if(void 0===t)return[];if("string"!=typeof t)return Array.from(t,(t=>0|t));switch(e){case"hex":return xt(t);case"base64":return At(t);default:return function(t){const e=[];for(let r=0;r<t.length;r++){const i=t.codePointAt(r);if(void 0===i)throw new Error(`Index out of range: ${r}`);let n=i;n>65535?r++:n>=55296&&n<=57343&&(n=65533),n<=127?e.push(n):n<=2047?e.push(192|n>>6,128|63&n):n<=65535?e.push(224|n>>12,128|n>>6&63,128|63&n):e.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}return e}(t)}},xt=t=>{(t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t);const e=[];for(let r=0;r<t.length;r+=2)e.push(parseInt(t[r]+t[r+1],16));return e},At=t=>{const e=[];let r=0,i=0;for(const n of t.replace(/=+$/,""))r=r<<6|"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(n),i+=6,i>=8&&(i-=8,e.push(r>>i&255),r&=(1<<i)-1);return e},Tt=t=>{let e="",r=0;for(let i=0;i<t.length;i++){const n=t[i];if(r>0)r--;else if(n<=127)e+=String.fromCharCode(n);else if(n>=192&&n<=223){r=1;const s=(31&n)<<6|63&t[i+1];e+=String.fromCharCode(s)}else if(n>=224&&n<=239){r=2;const s=(15&n)<<12|(63&t[i+1])<<6|63&t[i+2];e+=String.fromCharCode(s)}else if(n>=240&&n<=247){r=3;const s=(7&n)<<18|(63&t[i+1])<<12|(63&t[i+2])<<6|63&t[i+3],a=55296+(s-65536>>10),o=56320+(s-65536&1023);e+=String.fromCharCode(a,o)}}return e},Mt=(t,e)=>{switch(e){case"hex":return Nt(t);case"utf8":return Tt(t);default:return t}};function _t(t){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r,i="";for(r=0;r<t.length;r+=3){const n=t[r],s=r+1<t.length?t[r+1]:0,a=r+2<t.length?t[r+2]:0,o=(3&n)<<4|s>>4,c=(15&s)<<2|a>>6,h=63&a;i+=e.charAt(n>>2)+e.charAt(o),i+=r+1<t.length?e.charAt(c):"=",i+=r+2<t.length?e.charAt(h):"="}return i}const Ft="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Rt=t=>{if(""===t||"string"!=typeof t)throw new Error(`Expected base58 string but got “${t}”`);const e=t.match(/[IOl0]/gmu);if(null!==e)throw new Error(`Invalid base58 character “${e.join("")}”`);const r=t.match(/^1+/gmu),i=null!==r?r[0].length:0,n=(t.length-i)*(Math.log(58)/Math.log(256))+1>>>0;var s;return[...new Uint8Array([...new Uint8Array(i),...(t.match(/./gmu)??[]).map((t=>Ft.indexOf(t))).reduce(((t,e)=>t.map((t=>{const r=58*t+e;return e=r>>8,r}))),new Uint8Array(n)).reverse().filter((s=!1,t=>s=s||t))])]},Ct=t=>{const e=Array(256).fill(-1);for(let t=0;t<58;++t)e[Ft.charCodeAt(t)]=t;const r=[];for(const i of t){let t=i;for(let i=0;i<r.length;++i){const n=(e[r[i]]<<8)+t;r[i]=Ft.charCodeAt(n%58),t=n/58|0}for(;0!==t;)r.push(Ft.charCodeAt(t%58)),t=t/58|0}for(const e of t){if(0!==e)break;r.push("1".charCodeAt(0))}return r.reverse(),String.fromCharCode(...r)},Vt=(t,e=[0])=>{let r=vt([...e,...t]);return r=[...e,...t,...r.slice(0,4)],Ct(r)},Dt=(t,e,r=1)=>{const i=Rt(t);let n=i.slice(0,r),s=i.slice(r,-4),a=[...n,...s];return a=vt(a),i.slice(-4).forEach(((t,e)=>{if(t!==a[e])throw new Error("Invalid checksum")})),"hex"===e&&(n=Nt(n),s=Nt(s)),{prefix:n,data:s}};class Bt{bufs;constructor(t){this.bufs=void 0!==t?t:[]}getLength(){let t=0;for(const e of this.bufs)t+=e.length;return t}toArray(){const t=this.getLength(),e=new Array(t);let r=0;for(const t of this.bufs)for(const i of t)e[r++]=i;return e}write(t){return this.bufs.push(t),this}writeReverse(t){const e=new Array(t.length);for(let r=0;r<e.length;r++)e[r]=t[t.length-1-r];return this.bufs.push(e),this}writeUInt8(t){const e=new Array(1);return e[0]=t,this.write(e),this}writeInt8(t){const e=new Array(1);return e[0]=255&t,this.write(e),this}writeUInt16BE(t){return this.bufs.push([t>>8&255,255&t]),this}writeInt16BE(t){return this.writeUInt16BE(65535&t)}writeUInt16LE(t){return this.bufs.push([255&t,t>>8&255]),this}writeInt16LE(t){return this.writeUInt16LE(65535&t)}writeUInt32BE(t){return this.bufs.push([t>>24&255,t>>16&255,t>>8&255,255&t]),this}writeInt32BE(t){return this.writeUInt32BE(t>>>0)}writeUInt32LE(t){return this.bufs.push([255&t,t>>8&255,t>>16&255,t>>24&255]),this}writeInt32LE(t){return this.writeUInt32LE(t>>>0)}writeUInt64BEBn(t){const e=t.toArray("be",8);return this.write(e),this}writeUInt64LEBn(t){const e=t.toArray("be",8);return this.writeReverse(e),this}writeUInt64LE(t){const e=new h(t).toArray("be",8);return this.writeReverse(e),this}writeVarIntNum(t){const e=Bt.varIntNum(t);return this.write(e),this}writeVarIntBn(t){const e=Bt.varIntBn(t);return this.write(e),this}static varIntNum(t){let e;if(t<253)e=[t];else if(t<65536)e=[253,255&t,t>>8&255];else if(t<4294967296)e=[254,255&t,t>>8&255,t>>16&255,t>>24&255];else{const r=4294967295&t,i=4294967295&Math.floor(t/4294967296);e=[255,255&r,r>>8&255,r>>16&255,r>>24&255,255&i,i>>8&255,i>>16&255,i>>24&255]}return e}static varIntBn(t){let e;if(t.ltn(253))e=[t.toNumber()];else if(t.ltn(65536)){const r=t.toNumber();e=[253,255&r,r>>8&255]}else if(t.lt(new h(4294967296))){const r=t.toNumber();e=[254,255&r,r>>8&255,r>>16&255,r>>24&255]}else{const r=new Bt;r.writeUInt8(255),r.writeUInt64LEBn(t),e=r.toArray()}return e}}class Ut{bin;pos;constructor(t=[],e=0){this.bin=t,this.pos=e}eof(){return this.pos>=this.bin.length}read(t=this.bin.length){const e=this.pos,r=this.pos+t;return this.pos=r,this.bin.slice(e,r)}readReverse(t=this.bin.length){const e=new Array(t);for(let r=0;r<t;r++)e[r]=this.bin[this.pos+t-1-r];return this.pos+=t,e}readUInt8(){const t=this.bin[this.pos];return this.pos+=1,t}readInt8(){const t=this.bin[this.pos];return this.pos+=1,128&t?t-256:t}readUInt16BE(){const t=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,t}readInt16BE(){const t=this.readUInt16BE();return 32768&t?t-65536:t}readUInt16LE(){const t=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,t}readInt16LE(){const t=this.readUInt16LE();return 32768&t?t-65536:t}readUInt32BE(){const t=16777216*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,t}readInt32BE(){const t=this.readUInt32BE();return 2147483648&t?t-4294967296:t}readUInt32LE(){const t=(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,t}readInt32LE(){const t=this.readUInt32LE();return 2147483648&t?t-4294967296:t}readUInt64BEBn(){const t=this.bin.slice(this.pos,this.pos+8),e=new h(t);return this.pos=this.pos+8,e}readUInt64LEBn(){const t=this.readReverse(8);return new h(t)}readVarIntNum(){const t=this.readUInt8();let e;switch(t){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if(e=this.readUInt64LEBn(),e.lte(new h(2).pow(new h(53))))return e.toNumber();throw new Error("number too large to retain precision - use readVarIntBn");default:return t}}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(){const t=this.readUInt8();switch(t){case 253:return new h(this.readUInt16LE());case 254:return new h(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new h(t)}}}const Ht=t=>{if(0===t.length)return t;const e=t[t.length-1];if(127&e)return t;if(1===t.length)return[];if(128&t[t.length-2])return t;for(let r=t.length-1;r>0;r--)if(0!==t[r-1])return 128&t[r-1]?(t[r]=e,t.slice(0,r+1)):(t[r-1]|=e,t.slice(0,r));return[]};class Kt extends p{static red=new d("k256");static a=new h(0).toRed(Kt.red);static b=new h(7).toRed(Kt.red);static zero=new h(0).toRed(Kt.red);x;y;inf;static fromDER(t){if((4===t[0]||6===t[0]||7===t[0])&&t.length-1==64){if(6===t[0]){if(t[t.length-1]%2!=0)throw new Error("Point string value is wrong length")}else if(7===t[0]&&t[t.length-1]%2!=1)throw new Error("Point string value is wrong length");return new Kt(t.slice(1,33),t.slice(33,65))}if((2===t[0]||3===t[0])&&t.length-1==32)return Kt.fromX(t.slice(1,33),3===t[0]);throw new Error("Unknown point format")}static fromString(t){const e=Ot(t,"hex");return Kt.fromDER(e)}static redSqrtOptimized(t){const e=Kt.red.m.addn(1).iushrn(2);return t.redPow(e)}static fromX(t,e){if("function"==typeof BigInt){function r(t,e){return(t%e+e)%e}function i(t,e,i){let n=BigInt(1);for(t=r(t,i);e>BigInt(0);)(e&BigInt(1))===BigInt(1)&&(n=r(n*t,i)),e>>=BigInt(1),t=r(t*t,i);return n}function n(t,e){const n=i(t,e+BigInt(1)>>BigInt(2),e);return r(n*n,e)===r(t,e)?n:null}const s=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),a=BigInt(7);let o;if(t instanceof h)o=BigInt("0x"+t.toString(16));else if("string"==typeof t)o=BigInt("0x"+t);else if(Array.isArray(t))o=BigInt("0x"+Nt(t).padStart(64,"0"));else{if("number"!=typeof t)throw new Error("Invalid x-coordinate type");o=BigInt(t)}o=r(o,s);let c=n(r(i(o,BigInt(3),s)+a,s),s);if(null===c)throw new Error("Invalid point");const u=c%BigInt(2)===BigInt(1);(e&&!u||!e&&u)&&(c=s-c);const l=new h(o.toString(16),16),f=new h(c.toString(16),16);return new Kt(l,f)}{const p=new d("k256"),m=new h(0).toRed(p),w=new h(7).toRed(p),b=new h(0).toRed(p);h.isBN(t)||(t=new h(t,16)),null==t.red&&(t=t.toRed(p));const g=t.redSqr().redMul(t).redIAdd(t.redMul(m)).redIAdd(w);let y=g.redSqrt();if(0!==y.redSqr().redSub(g).cmp(b))throw new Error("invalid point");const v=y.fromRed().isOdd();return(e&&!v||!e&&v)&&(y=y.redNeg()),new Kt(t,y)}}static fromJSON(t,e){"string"==typeof t&&(t=JSON.parse(t));const r=new Kt(t[0],t[1],e);if("object"!=typeof t[2])return r;const i=t=>new Kt(t[0],t[1],e),n=t[2];return r.precomputed={beta:null,doubles:"object"==typeof n.doubles&&null!==n.doubles?{step:n.doubles.step,points:[r].concat(n.doubles.points.map(i))}:void 0,naf:"object"==typeof n.naf&&null!==n.naf?{wnd:n.naf.wnd,points:[r].concat(n.naf.points.map(i))}:void 0},r}constructor(t,e,r=!0){super("affine"),this.precomputed=null,null===t&&null===e?(this.x=null,this.y=null,this.inf=!0):(h.isBN(t)||(t=new h(t,16)),this.x=t,h.isBN(e)||(e=new h(e,16)),this.y=e,r&&(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(){return this.curve.validate(this)}encode(t=!0,e){const r=this.curve.p.byteLength(),i=this.getX().toArray("be",r);let n;return n=t?[this.getY().isEven()?2:3].concat(i):[4].concat(i,this.getY().toArray("be",r)),"hex"!==e?n:Nt(n)}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?{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)}:void 0,naf:null!=this.precomputed.naf?{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}:void 0}: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(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return new Kt(new h(0),new h(0));if(0===this.x?.cmp(t.x??new h(0)))return new Kt(new h(0),new h(0));let e=this.y?.redSub(t.y??new h(0))??new h(0);0!==e.cmpn(0)&&(e=e.redMul(this.x?.redSub(t.x??new h(0)).redInvm()??new h(1)));const r=e?.redSqr().redISub(this.x??new h(0)).redISub(t.x??new h(0)),i=(e??new h(1)).redMul((this.x??new h(0)).redSub(r??new h(0))).redISub(this.y??new h(0));return new Kt(r??new h(0),i??new h(0))}dbl(){if(this.inf)return this;const t=(this.y??new h(0)).redAdd(this.y??new h(0));if(0===t.cmpn(0))return new Kt(new h(0),new h(0));const e=this.curve.a,r=(this.x??new h(0)).redSqr(),i=t.redInvm(),n=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(i),s=n.redSqr().redISub((this.x??new h(0)).redAdd(this.x??new h(0))),a=n.redMul((this.x??new h(0)).redSub(s)).redISub(this.y??new h(0));return new Kt(s,a)}getX(){return(this.x??new h(0)).fromRed()}getY(){return(this.y??new h(0)).fromRed()}mul(t){return h.isBN(t)||(t=new h(t,16)),this.isInfinity()?this:this._hasDoubles(t)?this._fixedNafMul(t):this._endoWnafMulAdd([this],[t])}mulAdd(t,e,r){const i=[this,e],n=[t,r];return this._endoWnafMulAdd(i,n)}jmulAdd(t,e,r){const i=[this,e],n=[t,r];return this._endoWnafMulAdd(i,n,!0)}eq(t){return this===t||this.inf===t.inf&&(this.inf||0===(this.x??new h(0)).cmp(t.x??new h(0))&&0===(this.y??new h(0)).cmp(t.y??new h(0)))}neg(t){if(this.inf)return this;const e=new Kt(this.x,(this.y??new h(0)).redNeg());if(!0===t&&null!=this.precomputed){const t=this.precomputed,r=t=>t.neg();e.precomputed={naf:null!=t.naf?{wnd:t.naf.wnd,points:t.naf.points.map(r)}:void 0,doubles:null!=t.doubles?{step:t.doubles.step,points:t.doubles.points.map((t=>t.neg()))}:void 0,beta:void 0}}return e}dblp(t){let e=this;for(let r=0;r<t;r++)e=e.dbl();return e}toJ(){return this.inf?new m(null,null,null):new m(this.x,this.y,this.curve.one)}_getBeta(){if("object"!=typeof this.curve.endo)return;const t=this.precomputed;if("object"==typeof t&&null!==t&&"object"==typeof t.beta&&null!==t.beta)return t.beta;const e=new Kt((this.x??new h(0)).redMul(this.curve.endo.beta),this.y);if(null!=t){const r=this.curve,i=t=>{if(null===t.x)throw new Error("p.x is null");if(void 0===r.endo||null===r.endo)throw new Error("curve.endo is undefined");return new Kt(t.x.redMul(r.endo.beta),t.y)};t.beta=e,e.precomputed={beta:null,naf:null!=t.naf?{wnd:t.naf.wnd,points:t.naf.points.map(i)}:void 0,doubles:null!=t.doubles?{step:t.doubles.step,points:t.doubles.points.map(i)}:void 0}}return e}_fixedNafMul(t){if("object"!=typeof this.precomputed||null===this.precomputed)throw new Error("_fixedNafMul requires precomputed values for the point");const e=this._getDoubles(),r=this.curve.getNAF(t,1,this.curve._bitLength);let i=(1<<e.step+1)-(e.step%2==0?2:1);i/=3;const n=[];for(let t=0;t<r.length;t+=e.step){let i=0;for(let n=t+e.step-1;n>=t;n--)i=(i<<1)+r[n];n.push(i)}let s=new m(null,null,null),a=new m(null,null,null);for(let t=i;t>0;t--){for(let r=0;r<n.length;r++){const i=n[r];i===t?a=a.mixedAdd(e.points[r]):i===-t&&(a=a.mixedAdd(e.points[r].neg()))}s=s.add(a)}return s.toP()}_wnafMulAdd(t,e,r,i,n){const s=this.curve._wnafT1.map((t=>t.toNumber())),a=this.curve._wnafT2.map((()=>[])),o=this.curve._wnafT3.map((()=>[]));let c=0;for(let r=0;r<i;r++){const i=e[r]._getNAFPoints(t);s[r]=i.wnd,a[r]=i.points}for(let t=i-1;t>=1;t-=2){const i=t-1,n=t;if(1!==s[i]||1!==s[n]){o[i]=this.curve.getNAF(r[i],s[i],this.curve._bitLength),o[n]=this.curve.getNAF(r[n],s[n],this.curve._bitLength),c=Math.max(o[i].length,c),c=Math.max(o[n].length,c);continue}const u=[e[i],null,null,e[n]];0===(e[i].y??new h(0)).cmp(e[n].y??new h(0))?(u[1]=e[i].add(e[n]),u[2]=e[i].toJ().mixedAdd(e[n].neg())):0===(e[i].y??new h(0)).cmp((e[n].y??new h(0)).redNeg())?(u[1]=e[i].toJ().mixedAdd(e[n]),u[2]=e[i].add(e[n].neg())):(u[1]=e[i].toJ().mixedAdd(e[n]),u[2]=e[i].toJ().mixedAdd(e[n].neg()));const l=[-3,-1,-5,-7,0,7,5,1,3],d=this.curve.getJSF(r[i],r[n]);c=Math.max(d[0].length,c),o[i]=new Array(c),o[n]=new Array(c);for(let t=0;t<c;t++){const e=0|d[0][t],r=0|d[1][t];o[i][t]=l[3*(e+1)+(r+1)],o[n][t]=0,a[i]=u}}let u=new m(null,null,null);const l=this.curve._wnafT4;for(let t=c;t>=0;t--){let e=0;for(;t>=0;){let r=!0;for(let e=0;e<i;e++)l[e]=new h("number"==typeof o[e][t]?o[e][t]:0),l[e].isZero()||(r=!1);if(!r)break;e++,t--}if(t>=0&&e++,u=u.dblp(e),t<0)break;const r=new h(1),n=new h(2);for(let t=0;t<i;t++){const e=l[t];let i;0!==e.cmpn(0)&&(i=e.isNeg()?a[t][e.neg().sub(r).div(n).toNumber()].neg():a[t][e.sub(r).div(n).toNumber()],u="affine"===i.type?u.mixedAdd(i):u.add(i))}}for(let t=0;t<i;t++)a[t]=[];return!0===n?u:u.toP()}_endoWnafMulAdd(t,e,r){const i=new Array(2*t.length),n=new Array(2*t.length);let s;for(s=0;s<t.length;s++){const r=this.curve._endoSplit(e[s]);let a=t[s],o=a._getBeta()??new Kt(new h(0),new h(0));0!==r.k1.negative&&(r.k1.ineg(),a=a.neg(!0)),0!==r.k2.negative&&(r.k2.ineg(),o=o.neg(!0)),i[2*s]=a,i[2*s+1]=o,n[2*s]=r.k1,n[2*s+1]=r.k2}const a=this._wnafMulAdd(1,i,n,2*s,r);for(let t=0;t<2*s;t++)i[t]=null,n[t]=null;return a}_hasDoubles(t){if(null==this.precomputed)return!1;const e=this.precomputed.doubles;return"object"==typeof e&&e.points.length>=Math.ceil((t.bitLength()+1)/e.step)}_getDoubles(t,e){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.doubles&&null!==this.precomputed.doubles)return this.precomputed.doubles;const r=[this];let i=this;for(let n=0;n<(e??0);n+=t??1){for(let e=0;e<(t??1);e++)i=i.dbl();r.push(i)}return{step:t??1,points:r}}_getNAFPoints(t){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.naf&&null!==this.precomputed.naf)return this.precomputed.naf;const e=[this],r=(1<<t)-1,i=1===r?null:this.dbl();for(let t=1;t<r;t++)null!==i&&(e[t]=e[t-1].add(i));return{wnd:t,points:e}}}let qt;class Lt{p;red;redN;zero;one;two;g;n;a;b;tinv;zeroA;threeA;endo;_endoWnafT1;_endoWnafT2;_wnafT1;_wnafT2;_wnafT3;_wnafT4;_bitLength;static assert(t,e="Elliptic curve assertion failed"){if(!t)throw new Error(e)}getNAF(t,e,r){const i=new Array(Math.max(t.bitLength(),r)+1);i.fill(0);const n=1<<e+1,s=t.clone();for(let t=0;t<i.length;t++){let e;const r=s.andln(n-1);s.isOdd()?(e=r>(n>>1)-1?(n>>1)-r:r,s.isubn(e)):e=0,i[t]=e,s.iushrn(1)}return i}getJSF(t,e){const r=[[],[]];t=t.clone(),e=e.clone();let i=0,n=0;for(;t.cmpn(-i)>0||e.cmpn(-n)>0;){let s,a,o=t.andln(3)+i&3,c=e.andln(3)+n&3;if(3===o&&(o=-1),3===c&&(c=-1),1&o){const e=t.andln(7)+i&7;s=3!==e&&5!==e||2!==c?o:-o}else s=0;if(r[0].push(s),1&c){const t=e.andln(7)+n&7;a=3!==t&&5!==t||2!==o?c:-c}else a=0;r[1].push(a),2*i===s+1&&(i=1-i),2*n===a+1&&(n=1-n),t.iushrn(1),e.iushrn(1)}return r}static cachedProperty(t,e,r){const i="_"+e;t.prototype[e]=function(){return void 0!==this[i]?this[i]:this[i]=r.call(this)}}static parseBytes(t){return"string"==typeof t?Ot(t,"hex"):t}static intFromLE(t){return new h(t,"hex","le")}constructor(){if(void 0!==qt)return qt;qt=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 h(t.p,16),this.red=new d(t.prime),this.zero=new h(0).toRed(this.red),this.one=new h(1).toRed(this.red),this.two=new h(2).toRed(this.red),this.n=new h(t.n,16),this.g=Kt.fromJSON(t.g,t.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n.bitLength(),this.redN=this.n.toRed(this.red),this.a=new h(t.a,16).toRed(this.red),this.b=new h(t.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(t),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}_getEndomorphism(t){if(!this.zeroA||1!==this.p.modrn(3))return;let e,r,i;if(void 0!==t.beta)e=new h(t.beta,16).toRed(this.red);else{const t=this._getEndoRoots(this.p);if(null===t)throw new Error("Failed to get endomorphism roots for beta.");e=t[0].cmp(t[1])<0?t[0]:t[1],e=e.toRed(this.red)}if(void 0!==t.lambda)r=new h(t.lambda,16);else{const t=this._getEndoRoots(this.n);if(null===t)throw new Error("Failed to get endomorphism roots for lambda.");if(null==this.g)throw new Error("Curve generator point (g) is not defined.");const i=this.g.mul(t[0])?.x,n=null!=this.g.x?this.g.x.redMul(e):void 0;if(null!=i&&null!=n&&0===i.cmp(n))r=t[0];else{if(r=t[1],null==this.g)throw new Error("Curve generator point (g) is not defined.");const i=this.g.mul(r)?.x,n=null!=this.g.x?this.g.x.redMul(e):void 0;if(null==i||null==n)throw new Error("Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.");Lt.assert(0===i.cmp(n),"Lambda selection does not match computed beta.")}}return i="object"==typeof t.basis&&null!==t.basis?t.basis.map((function(t){return{a:new h(t.a,16),b:new h(t.b,16)}})):this._getEndoBasis(r),{beta:e,lambda:r,basis:i}}_getEndoRoots(t){const e=t===this.p?this.red:new f(t),r=new h(2).toRed(e).redInvm(),i=r.redNeg(),n=new h(3).toRed(e).redNeg().redSqrt().redMul(r);return[i.redAdd(n).fromRed(),i.redSub(n).fromRed()]}_getEndoBasis(t){const e=this.n.ushrn(Math.floor(this.n.bitLength()/2));let r,i,n,s,a,o,c=t,u=this.n.clone(),l=new h(1),d=new h(0),f=new h(0),p=new h(1),m=new h(0),w=0,b=new h(0),g=new h(0);for(;0!==c.cmpn(0);){const t=u.div(c);b=u.sub(t.mul(c)),g=f.sub(t.mul(l));const a=p.sub(t.mul(d));if(void 0===n&&b.cmp(e)<0)r=m.neg(),i=l,n=b.neg(),s=g;else if(void 0!==n&&2==++w)break;m=b,u=c,c=b,f=l,l=g,p=d,d=a}if(void 0===r||void 0===i||void 0===n||void 0===s)throw new Error("Failed to compute Endo Basis values");a=b.neg(),o=g;const y=n.sqr().add(s.sqr());return a.sqr().add(o.sqr()).cmp(y)>=0&&(a=r,o=i),0!==n.negative&&(n=n.neg(),s=s.neg()),0!==a.negative&&(a=a.neg(),o=o.neg()),[{a:n,b:s},{a,b:o}]}_endoSplit(t){if(null==this.endo)throw new Error("Endomorphism is not defined.");const e=this.endo.basis,r=e[0],i=e[1],n=i.b.mul(t).divRound(this.n),s=r.b.neg().mul(t).divRound(this.n),a=n.mul(r.a),o=s.mul(i.a),c=n.mul(r.b),h=s.mul(i.b);return{k1:t.sub(a).sub(o),k2:c.add(h).neg()}}validate(t){if(t.inf)return!0;const e=t.x,r=t.y;if(null===e||null===r)throw new Error("Point coordinates cannot be null");const i=this.a.redMul(e),n=e.redSqr().redMul(e).redIAdd(i).redIAdd(this.b);return 0===r.redSqr().redISub(n).cmpn(0)}}class $t{r;s;static fromDER(t,e){const r=(t,e)=>{const r=t[e.place++];if(128&r)throw new Error("Invalid DER entity length");return r};t=Ot(t,e);const i=new class{place;constructor(){this.place=0}};if(48!==t[i.place++])throw new Error("Signature DER must start with 0x30");if(r(t,i)+i.place!==t.length)throw new Error("Signature DER invalid");if(2!==t[i.place++])throw new Error("Signature DER invalid");const n=r(t,i);let s=t.slice(i.place,n+i.place);if(i.place+=n,2!==t[i.place++])throw new Error("Signature DER invalid");const a=r(t,i);if(t.length!==a+i.place)throw new Error("Invalid R-length in signature DER");let o=t.slice(i.place,a+i.place);if(0===s[0]){if(!(128&s[1]))throw new Error("Invalid R-value in signature DER");s=s.slice(1)}if(0===o[0]){if(!(128&o[1]))throw new Error("Invalid S-value in signature DER");o=o.slice(1)}return new $t(new h(s),new h(o))}static fromCompact(t,e){if(65!==(t=Ot(t,e)).length)throw new Error("Invalid Compact Signature");const r=t[0];if(r<27||r>=35)throw new Error("Invalid Compact Byte");return new $t(new h(t.slice(1,33)),new h(t.slice(33,65)))}constructor(t,e){this.r=t,this.s=e}verify(t,e,r){const i=new h(gt(t,r),16);return Xt(i,this,e)}toString(t){return this.toDER(t)}toDER(t){const e=(t,e)=>{if(!(e<128))throw new Error("len must be < 0x80");t.push(e)},r=t=>{let e=0;const r=t.length-1;for(;0===t[e]&&!(128&t[e+1])&&e<r;)e++;return 0===e?t:t.slice(e)};let i=this.r.toArray(),n=this.s.toArray();for(128&i[0]&&(i=[0].concat(i)),128&n[0]&&(n=[0].concat(n)),i=r(i),n=r(n);0===n[0]&&!(128&n[1]);)n=n.slice(1);let s=[2];e(s,i.length),s=s.concat(i),s.push(2),e(s,n.length);const a=s.concat(n);let o=[48];return e(o,a.length),o=o.concat(a),"hex"===t?Nt(o):"base64"===t?_t(o):o}toCompact(t,e,r){if(t<0||t>3)throw new Error("Invalid recovery param");if("boolean"!=typeof e)throw new Error("Invalid compressed param");let i=27+t;e&&(i+=4);let n=[i];return n=n.concat(this.r.toArray("be",32)),n=n.concat(this.s.toArray("be",32)),"hex"===r?Nt(n):"base64"===r?_t(n):n}RecoverPublicKey(t,e){const r=this.r,i=this.s,n=!!(1&t),s=t>>1,a=new Lt,o=a.n,c=a.g,h=0!==s?r.add(o):r,u=Kt.fromX(h,n);if(!u.mul(o).isInfinity())throw new Error("nR is not at infinity");const l=e.neg().umod(o),d=r.invm(o),f=d.mul(i).umod(o),p=d.mul(l).umod(o),m=c.mul(p).add(u.mul(f)),w=new Gt(m);return w.validate(),w}CalculateRecoveryFactor(t,e){for(let r=0;r<4;r++){let i;try{i=this.RecoverPublicKey(r,e)}catch{continue}if(t.eq(i))return r}throw new Error("Unable to find valid recovery factor")}}class zt{K;V;constructor(t,e){if(t=Ot(t,"hex"),e=Ot(e,"hex"),t.length<32)throw new Error("Not enough entropy. Minimum is 256 bits");const r=t.concat(e);this.K=new Array(32),this.V=new Array(32);for(let t=0;t<32;t++)this.K[t]=0,this.V[t]=1;this.update(r)}hmac(){return new ft(this.K)}update(t){let e=this.hmac().update(this.V).update([0]);void 0!==t&&(e=e.update(t)),this.K=e.digest(),this.V=this.hmac().update(this.V).digest(),void 0!==t&&(this.K=this.hmac().update(this.V).update([1]).update(t).digest(),this.V=this.hmac().update(this.V).digest())}generate(t){let e=[];for(;e.length<t;)this.V=this.hmac().update(this.V).digest(),e=e.concat(this.V);const r=e.slice(0,t);return this.update(),Nt(r)}}function jt(t,e,r=new Lt){const i=8*t.byteLength()-r.n.bitLength();return i>0&&t.iushrn(i),null===e&&t.cmp(r.n)>=0?t.sub(r.n):t}const Wt=(t,e,r=!1,i)=>{if("function"==typeof BigInt){const n=BigInt(0),s=BigInt(1),a=BigInt(2),o=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),c=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),u={x:BigInt("0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"),y:BigInt("0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8")},l=BigInt("0x"+t.toString(16)),d=BigInt("0x"+e.toString(16));if(d<=n||d>=o)throw new Error("Invalid private key");function f(t,e){const r=t.toString(16).padStart(2*e,"0"),i=new Uint8Array(e);for(let t=0;t<e;t++)i[t]=parseInt(r.substr(2*t,2),16);return i}const p=32,m=f(d,p),w=f(l,p),b=new zt(Array.from(m),Array.from(w)),g=o-s;let y=0;function v(t,e,r=!0){const i=t.toString(2).length-e.toString(2).length;return i>0&&(t>>=BigInt(i)),!r&&t>=e?t-e:t}function I(t){if("function"==typeof t){const e=t(y).toString(16);return BigInt("0x"+e)}if(null!=t&&h.isBN(t)){const e=t.toString(16);return BigInt("0x"+e)}{const t=b.generate(p);return BigInt("0x"+t)}}function k(t,e){return(t%e+e)%e}function P(t,e){let r=s,i=n,a=k(t,e),o=e;for(;a>s;){const t=o/a,e=i-r*t,n=o-a*t;i=r,r=e,o=a,a=n}return k(r,e)}function E(t,e){if(null===t)return e;if(null===e)return t;if(t.x===e.x&&t.y===k(-e.y,c))return null;let r;if(t.x===e.x&&t.y===e.y){if(t.y===n)return null;const e=k(BigInt(3)*t.x*t.x,c);r=k(e*P(a*t.y,c),c)}else{const i=k(e.y-t.y,c);r=k(i*P(e.x-t.x,c),c)}const i=k(r*r-t.x-e.x,c);return{x:i,y:k(r*(t.x-i)-t.y,c)}}function S(t,e){let r=e,i=null;for(;t>BigInt(0);)t%BigInt(2)===BigInt(1)&&(i=null===i?r:E(i,r)??i),r=E(r,r)??r,t>>=BigInt(1);if(null===i)throw new Error("Scalar multiplication resulted in an invalid point.");return i}let N=!1;for(;!N;){y+=1,N=!0,y+=1;let O=I(i);if(O=v(O,o,!0),O<=s||O>=g){if(i instanceof h)throw new Error("Invalid fixed custom K value (must be more than 1 and less than N-1)");continue}const x=S(O,u);if(null===x){if(i instanceof h)throw new Error("Invalid fixed custom K value (must not create a point at infinity when multiplied by the generator point)");continue}const A=k(x.x,o);if(A===n){if(i instanceof h)throw new Error("Invalid fixed custom K value (when multiplied by G, the resulting x coordinate mod N must not be zero)");continue}const T=P(O,o),M=k(A*d,o);let _=k(T*(l+M),o);if(_===n){if(i instanceof h)throw new Error("Invalid fixed custom K value (when used with the key, it cannot create a zero value for S)");continue}r&&_>o/a&&(_=o-_);const F=new h(A.toString(16),16),R=new h(_.toString(16),16);return new $t(F,R)}}else{const C=new Lt;t=jt(t);const V=C.n.byteLength(),D=e.toArray("be",V),B=t.toArray("be",V),U=new zt(D,B),H=C.n.subn(1);for(let K=0;;K++){let q="function"==typeof i?i(K):h.isBN(i)?i:new h(U.generate(V),16);if(null==q)throw new Error("k is undefined");if(q=jt(q,!0),q.cmpn(1)<=0||q.cmp(H)>=0){if(h.isBN(i))throw new Error("Invalid fixed custom K value (must be more than 1 and less than N-1)");continue}const L=C.g.mul(q);if(L.isInfinity()){if(h.isBN(i))throw new Error("Invalid fixed custom K value (must not create a point at infinity when multiplied by the generator point)");continue}const $=L.getX().umod(C.n);if(0===$.cmpn(0)){if(h.isBN(i))throw new Error("Invalid fixed custom K value (when multiplied by G, the resulting x coordinate mod N must not be zero)");continue}let z=q.invm(C.n).mul($.mul(e).iadd(t));if(z=z.umod(C.n),0!==z.cmpn(0))return r&&z.cmp(C.n.ushrn(1))>0&&(z=C.n.sub(z)),new $t($,z);if(h.isBN(i))throw new Error("Invalid fixed custom K value (when used with the key, it cannot create a zero value for S)")}}throw new Error("Failed to generate a valid signature")},Xt=(t,e,r)=>{if("function"==typeof BigInt){const i=BigInt(0),n=BigInt(1),s=BigInt(2),a=BigInt(3),o=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),c=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),h={x:BigInt("0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"),y:BigInt("0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8")},u=(t,e)=>(t%e+e)%e,l=(t,e)=>{let[r,s]=[t,e],[a,o]=[BigInt(1),BigInt(0)];for(;s!==i;){const t=r/s;[r,s]=[s,r-t*s],[a,o]=[o,a-t*o]}return r>n?i:u(a,e)},d=(t,e,r)=>u(t*e,r),f=(t,e,r)=>u(t-e,r),p=BigInt(4),m=BigInt(8),w=t=>{const{X:e,Y:r,Z:c}=t;if(r===i)return{X:i,Y:n,Z:i};const h=d(r,r,o),u=d(p,d(e,h,o),o),l=d(a,d(e,e,o),o),w=f(d(l,l,o),d(s,u,o),o);return{X:w,Y:f(d(l,f(u,w,o),o),d(m,d(h,h,o),o),o),Z:d(s,d(r,c,o),o)}},b=(t,e)=>{if(t.Z===i)return e;if(e.Z===i)return t;const r=d(t.Z,t.Z,o),a=d(e.Z,e.Z,o),c=d(t.X,a,o),h=d(e.X,r,o),u=d(t.Y,d(a,e.Z,o),o),l=d(e.Y,d(r,t.Z,o),o),p=f(h,c,o),m=f(l,u,o);if(p===i)return m===i?w(t):{X:i,Y:n,Z:i};const b=d(p,p,o),g=d(p,b,o),y=d(c,b,o),v=f(f(d(m,m,o),g,o),d(s,y,o),o);return{X:v,Y:f(d(m,f(y,v,o),o),d(u,g,o),o),Z:d(p,d(t.Z,e.Z,o),o)}},g=(t,e)=>{const r={X:e.x,Y:e.y,Z:n};let s={X:i,Y:n,Z:i};const a=t.toString(2);for(let t=0;t<a.length;t++)s=w(s),"1"===a[t]&&(s=b(s,r));return s},y=(t,e,r)=>{const{r:n,s}=r,a=t;if(n<=i||n>=c||s<=i||s>=c)return!1;const f=l(s,c);if(f===i)return!1;const p=d(a,f,c),m=d(n,f,c),w=g(p,h),y=g(m,e),v=b(w,y);if(v.Z===i)return!1;const I=l(v.Z,o);if(I===i)return!1;const k=d(I,I,o),P=d(v.X,k,o);return u(P,c)===n},v=BigInt("0x"+t.toString(16));if(null==r.x||null==r.y)throw new Error("Invalid public key: missing coordinates.");return y(v,{x:BigInt("0x"+r.x.toString(16)),y:BigInt("0x"+r.y.toString(16))},{r:BigInt("0x"+e.r.toString(16)),s:BigInt("0x"+e.s.toString(16))})}{const i=new Lt;t=jt(t);const n=e.r,s=e.s;if(n.cmpn(1)<0||n.cmp(i.n)>=0)return!1;if(s.cmpn(1)<0||s.cmp(i.n)>=0)return!1;const a=s.invm(i.n),o=a.mul(t).umod(i.n),c=a.mul(n).umod(i.n),h=i.g.jmulAdd(o,r,c);return!h.isInfinity()&&h.eqXToP(n)}};class Gt extends Kt{static fromPrivateKey(t){const e=(new Lt).g.mul(t);return new Gt(e.x,e.y)}static fromString(t){const e=Kt.fromString(t);return new Gt(e.x,e.y)}static fromDER(t){const e=Kt.fromDER(t);return new Gt(e.x,e.y)}constructor(t,e=null,r=!0){if(t instanceof Kt)super(t.getX(),t.getY());else{if(null===e&&r&&"string"==typeof t&&(66===t.length||130===t.length))throw new Error('You are using the "new PublicKey()" constructor with a DER hex string. You need to use "PublicKey.fromString()" instead.');super(t,e,r)}}deriveSharedSecret(t){if(!this.validate())throw new Error("Public key not valid for ECDH secret derivation");return this.mul(t)}verify(t,e,r){const i=new h(gt(t,r),16);return Xt(i,e,this)}toDER(t){return"hex"===t?this.encode(!0,t):this.encode(!0)}toHash(t){const e=It(this.encode(!0));return"hex"===t?Nt(e):e}toAddress(t=[0]){if("string"==typeof t)if("testnet"===t||"test"===t)t=[111];else{if("mainnet"!==t&&"main"!==t)throw new Error(`Invalid prefix ${t}`);t=[0]}return Vt(this.toHash(),t)}deriveChild(t,e){const r=this.deriveSharedSecret(t),i=Ot(e,"utf8"),n=kt(r.encode(!0),i),s=(new Lt).g.mul(new h(n)),a=this.add(s);return new Gt(a.x,a.y)}static fromMsgHashAndCompactSignature(t,e,r){const i=Ot(e,r);if(65!==i.length)throw new Error("Invalid Compact Signature");const n=i[0];if(n<27||n>=35)throw new Error("Invalid Compact Byte");let s=i[0]-27;return s>3&&(s-=4),new $t(new h(i.slice(1,33)),new h(i.slice(33,65))).RecoverPublicKey(s,t)}}class Yt{_rand;constructor(){const t=()=>{throw new Error("No secure random number generator is available in this environment.")};if(this._rand=t,"object"==typeof self)self.crypto?.getRandomValues?this._rand=t=>{const e=new Uint8Array(t);return self.crypto.getRandomValues(e),[...e]}:this._rand=t;else try{const t=require("crypto");"function"==typeof t.randomBytes&&(this._rand=e=>[...t.randomBytes(e)])}catch{this._rand=t}}generate(t){return this._rand(t)}}let Jt=null;const Zt=t=>(null==Jt&&(Jt=new Yt),Jt.generate(t));class Qt{x;y;constructor(t,e){const r=(new Lt).p;this.x=t.umod(r),this.y=e.umod(r)}toString(){return Ct(this.x.toArray())+"."+Ct(this.y.toArray())}static fromString(t){const[e,r]=t.split(".");return new Qt(new h(Rt(e)),new h(Rt(r)))}}class te{points;threshold;constructor(t,e){this.points=t,this.threshold=e??t.length}static fromPrivateKey(t,e){const r=(new Lt).p,i=[new Qt(new h(0),new h(t.toArray()))];for(let t=1;t<e;t++){const t=new h(Zt(32)).umod(r),e=new h(Zt(32)).umod(r);i.push(new Qt(t,e))}return new te(i)}valueAt(t){const e=(new Lt).p;let r=new h(0);for(let i=0;i<this.threshold;i++){let n=this.points[i].y;for(let r=0;r<this.threshold;r++)if(i!==r){const s=this.points[r].x,a=this.points[i].x,o=t.sub(s).umod(e),c=a.sub(s).umod(e).invm(e),h=o.mul(c).umod(e);n=n.mul(h).umod(e)}r=r.add(n).umod(e)}return r}}class ee{points;threshold;integrity;constructor(t,e,r){this.points=t,this.threshold=e,this.integrity=r}static fromBackupFormat(t){let e=0,r="";const i=t.map(((t,i)=>{const n=t.split(".");if(4!==n.length)throw new Error("Invalid share format in share "+i.toString()+'. Expected format: "x.y.t.i" - received '+t);const[s,a,o,c]=n;if(void 0===o)throw new Error("Threshold not found in share "+i.toString());if(void 0===c)throw new Error("Integrity not found in share "+i.toString());const h=parseInt(o);if(0!==i&&e!==h)throw new Error("Threshold mismatch in share "+i.toString());if(0!==i&&r!==c)throw new Error("Integrity mismatch in share "+i.toString());return e=h,r=c,Qt.fromString([s,a].join("."))}));return new ee(i,e,r)}toBackupFormat(){return this.points.map((t=>t.toString()+"."+this.threshold.toString()+"."+this.integrity))}}class re extends h{static fromRandom(){return new re(Zt(32))}static fromString(t,e="hex"){return new re(super.fromString(t,e).toArray())}static fromHex(t){return new re(super.fromHex(t,"big"))}static fromWif(t,e=1){const r=Dt(t,void 0,e);if(33!==r.data.length)throw new Error("Invalid WIF length");if(1!==r.data[32])throw new Error("Invalid WIF padding");return new re(r.data.slice(0,32))}constructor(t=0,e=10,r="be",i="apply"){if(t instanceof h?(super(),t.copy(this)):super(t,e,r),"nocheck"!==i){const t=this.checkInField();if(!t.inField){if("error"===i)throw new Error("Input is out of field");h.move(this,t.modN)}}}checkInField(){const t=new Lt,e=this.mod(t.n);return{inField:0===this.cmp(e),modN:e}}isValid(){return this.checkInField().inField}sign(t,e,r=!0,i){const n=new h(gt(t,e),16);return Wt(n,this,r,i)}verify(t,e,r){const i=new h(gt(t,r),16);return Xt(i,e,this.toPublicKey())}toPublicKey(){const t=(new Lt).g.mul(this);return new Gt(t.x,t.y)}toWif(t=[128]){if(!this.isValid())throw new Error("Value is out of field");return Vt([...this.toArray("be",32),1],t)}toAddress(t=[0]){return this.toPublicKey().toAddress(t)}toHex(){return super.toHex(32)}toString(t="hex",e=64){return super.toString(t,e)}deriveSharedSecret(t){if(!t.validate())throw new Error("Public key not valid for ECDH secret derivation");return t.mul(this)}deriveChild(t,e){const r=this.deriveSharedSecret(t),i=Ot(e,"utf8"),n=kt(r.encode(!0),i),s=new Lt;return new re(this.add(new h(n)).mod(s.n).toArray())}toKeyShares(t,e){if("number"!=typeof t||"number"!=typeof e)throw new Error("threshold and totalShares must be numbers");if(t<2)throw new Error("threshold must be at least 2");if(e<2)throw new Error("totalShares must be at least 2");if(t>e)throw new Error("threshold should be less than or equal to totalShares");const r=te.fromPrivateKey(this,t),i=[];for(let t=0;t<e;t++){const t=new h(re.fromRandom().toArray()),e=r.valueAt(t);i.push(new Qt(t,e))}const n=this.toPublicKey().toHash("hex").slice(0,8);return new ee(i,t,n)}toBackupShares(t,e){return this.toKeyShares(t,e).toBackupFormat()}static fromBackupShares(t){return re.fromKeyShares(ee.fromBackupFormat(t))}static fromKeyShares(t){const{points:e,threshold:r,integrity:i}=t;if(r<2)throw new Error("threshold must be at least 2");if(e.length<r)throw new Error(`At least ${r} shares are required to reconstruct the private key`);for(let t=0;t<r;t++)for(let i=t+1;i<r;i++)if(e[t].x.eq(e[i].x))throw new Error("Duplicate share detected, each must be unique.");const n=new te(e,r),s=new re(n.valueAt(new h(0)).toArray());if(s.toPublicKey().toHash("hex").slice(0,8)!==i)throw new Error("Integrity hash mismatch");return s}}const ie=[[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]],ne=[[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]];function se(t,e,r){let i,n;for(i=0;i<4;i++)for(n=0;n<4;n++)t[i][n]=t[i][n]^e[r+n][i]}function ae(t){let e,r;for(e=0;e<4;e++)for(r=0;r<4;r++)t[e][r]=ie[(240&t[e][r])>>4][15&t[e][r]]}function oe(t){let e;for(e=0;e<4;e++)t[e]=ie[(240&t[e])>>4][15&t[e]]}function ce(t){const e=t[0];t[0]=t[1],t[1]=t[2],t[2]=t[3],t[3]=e}function he(t){let e,r,i,n,s;for(e=1;e<4;e++)for(r=0;r<(e-1)%2+1;r++){for(s=t[e][r],i=r;n=i+e,n>=4&&(n-=4),n!==r;)t[e][i]=t[e][n],i=n;t[e][i]=s}}function ue(t,e){let r,i=0;for(r=0;r<8;r++)1&e&&(i^=t),128&t?(t<<=1,t^=283):t<<=1,e>>=1;return i}function le(t){let e,r;const i=[[],[],[],[]];for(e=0;e<4;e++)i[0][e]=ue(2,t[0][e])^ue(3,t[1][e])^t[2][e]^t[3][e],i[1][e]=t[0][e]^ue(2,t[1][e])^ue(3,t[2][e])^t[3][e],i[2][e]=t[0][e]^t[1][e]^ue(2,t[2][e])^ue(3,t[3][e]),i[3][e]=ue(3,t[0][e])^t[1][e]^t[2][e]^ue(2,t[3][e]);for(e=0;e<4;e++)for(r=0;r<4;r++)t[e][r]=i[e][r]}function de(t,e){let r,i,n,s;const a=[[],[],[],[]],o=[],c=Array.from(e);if(c.length<=16){for(;c.length<16;)c.unshift(0);s=11}else if(c.length<=24){for(;c.length<24;)c.unshift(0);s=13}else{if(!(e.length<=32))throw new Error("Illegal key length: "+String(e.length));for(;c.length<32;)c.unshift(0);s=15}const h=function(t,e){let r,i;const n=parseInt(String(e.length/4)),s=[];for(r=0;r<e.length;r++)r%4==0&&s.push([]),s[parseInt(String(r/4))].push(e[r]);for(r=n;r<4*t;r++){s[r]=[];const t=s[r-1].slice();if(r%n==0)for(ce(t),oe(t),i=0;i<4;i++)t[i]=t[i]^ne[parseInt(String(r/n))][i];else n>6&&r%n==4&&oe(t);for(i=0;i<4;i++)s[r][i]=s[r-n][i]^t[i]}return s}(s,c);for(r=0;r<15;r++)a[parseInt(String(r/4))].push(t[4*r%15]);for(a[3].push(t[15]),se(a,h,0),n=1;n<s;n++)ae(a),he(a),n+1<s&&le(a),se(a,h,4*n);for(r=0;r<4;r++)for(i=0;i<4;i++)o.push(a[i][r]);return o}const fe=function(t,e,r){return t[e]&1<<r?1:0},pe=function(t){return[(4278190080&t)>>>24,(16711680&t)>>16,(65280&t)>>8,255&t]},me=function(t){let e;const r=[];for(e=0;e<t;e++)r.push(0);return r},we=[225].concat(me(15)),be=function(t,e){let r;const i=[];for(r=0;r<t.length;r++)i[r]=t[r]^e[r];return i},ge=function(t){let e,r=0,i=0;for(e=0;e<t.length;e++)i=r,r=1&t[e],t[e]=t[e]>>1,0!==i&&(t[e]=128|t[e]);return t},ye=function(t,e){let r,i,n=e.slice(),s=me(16);for(r=0;r<16;r++)for(i=7;-1!==i;i--)0!==fe(t,r,i)&&(s=be(s,n)),n=0!==fe(n,15,0)?be(ge(n),we):ge(n);return s},ve=function(t){let e;const r=t.slice();for(e=15;11!==e&&(r[e]=r[e]+1,256===r[e]);e--)r[e]=0;return r};function Ie(t,e){let r,i=me(16);for(r=0;r<t.length;r+=16)i=ye(be(i,t.slice(r,Math.min(r+16,t.length))),e);return i}function ke(t,e,r){let i,n,s,a=e;const o=[];if(0===t.length)return t;const c=Math.ceil(t.length/16);for(i=0;i<c;i++){for(s=be(t.slice(16*i,Math.min(16*(i+1),t.length)),de(a,r)),n=0;n<s.length;n++)o.push(s[n]);i+1<c&&(a=ve(a))}return o}class Pe extends h{static fromRandom(){return new Pe(Zt(32))}encrypt(t,e){const r=Zt(32);t=Ot(t,e);const{result:i,authenticationTag:n}=function(t,e,r,i){let n,s;const a=de(me(16),i);n=[...r],12===r.length?n=n.concat(me(3)).concat([1]):(r.length%16!=0&&(n=n.concat(me(16-r.length%16))),n=n.concat(me(8)),n=Ie(n.concat(me(4)).concat(pe(8*r.length)),a));const o=ke(t,ve(n),i);return s=e.slice(),0===e.length?s=s.concat(me(16)):e.length%16!=0&&(s=s.concat(me(16-e.length%16))),s=s.concat(o),0===o.length?s=s.concat(me(16)):o.length%16!=0&&(s=s.concat(me(16-o.length%16))),s=s.concat(me(4)).concat(pe(8*e.length)).concat(me(4)).concat(pe(8*o.length)),{result:o,authenticationTag:ke(Ie(s,a),n,i)}}(t,[],r,this.toArray("be",32));return Mt([...r,...i,...n],e)}decrypt(t,e){const r=(t=Ot(t,e)).slice(0,32),i=t.slice(32),n=i.slice(-16),s=function(t,e,r,i,n){let s,a;const o=de(me(16),n);s=[...r],12===r.length?s=s.concat(me(3)).concat([1]):(r.length%16!=0&&(s=s.concat(me(16-r.length%16))),s=s.concat(me(8)),s=Ie(s.concat(me(4)).concat(pe(8*r.length)),o));const c=ke(t,ve(s),n);return a=e.slice(),0===e.length?a=a.concat(me(16)):e.length%16!=0&&(a=a.concat(me(16-e.length%16))),a=a.concat(t),0===t.length?a=a.concat(me(16)):t.length%16!=0&&(a=a.concat(me(16-t.length%16))),a=a.concat(me(4)).concat(pe(8*e.length)).concat(me(4)).concat(pe(8*t.length)),ke(Ie(a,o),s,n).join()!==i.join()?null:c}(i.slice(0,-16),[],r,n,this.toArray());if(null===s)throw new Error("Decryption failed!");return Mt(s,e)}}class Ee extends $t{static SIGHASH_ALL=1;static SIGHASH_NONE=2;static SIGHASH_SINGLE=3;static SIGHASH_FORKID=64;static SIGHASH_ANYONECANPAY=128;scope;static format(t){const e={sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,sequence:t.inputSequence},r=[...t.otherInputs];function i(e){const r=new Bt;if(void 0===e)for(const e of t.outputs){const t=e.satoshis??0;r.writeUInt64LE(t);const i=e.lockingScript?.toBinary()??[];r.writeVarIntNum(i.length),r.write(i)}else{const i=t.outputs[e];if(void 0===i)throw new Error(`Output at index ${e} does not exist`);const n=i.satoshis??0;r.writeUInt64LE(n);const s=i.lockingScript?.toBinary()??[];r.writeVarIntNum(s.length),r.write(s)}const i=r.toArray();return vt(i)}r.splice(t.inputIndex,0,e);let n=new Array(32).fill(0),s=new Array(32).fill(0),a=new Array(32).fill(0);t.scope&Ee.SIGHASH_ANYONECANPAY||(n=(()=>{const t=new Bt;for(const e of r){if(void 0===e.sourceTXID){if(null==e.sourceTransaction)throw new Error("Missing sourceTransaction for input");t.write(e.sourceTransaction.hash())}else t.writeReverse(Ot(e.sourceTXID,"hex"));t.writeUInt32LE(e.sourceOutputIndex)}const e=t.toArray();return vt(e)})()),t.scope&Ee.SIGHASH_ANYONECANPAY||(31&t.scope)===Ee.SIGHASH_SINGLE||(31&t.scope)===Ee.SIGHASH_NONE||(s=(()=>{const t=new Bt;for(const e of r){const r=e.sequence??4294967295;t.writeUInt32LE(r)}const e=t.toArray();return vt(e)})()),(31&t.scope)!==Ee.SIGHASH_SINGLE&&(31&t.scope)!==Ee.SIGHASH_NONE?a=i():(31&t.scope)===Ee.SIGHASH_SINGLE&&t.inputIndex<t.outputs.length&&(a=i(t.inputIndex));const o=new Bt;o.writeInt32LE(t.transactionVersion),o.write(n),o.write(s),o.writeReverse(Ot(t.sourceTXID,"hex")),o.writeUInt32LE(t.sourceOutputIndex);const c=t.subscript.toBinary();o.writeVarIntNum(c.length),o.write(c),o.writeUInt64LE(t.sourceSatoshis);const h=e.sequence;return o.writeUInt32LE(h),o.write(a),o.writeUInt32LE(t.lockTime),o.writeUInt32LE(t.scope>>>0),o.toArray()}static fromChecksigFormat(t){if(0===t.length){const t=new h(1),e=new h(1);return new Ee(t,e,1)}const e=t[t.length-1],r=t.slice(0,t.length-1),i=$t.fromDER(r);return new Ee(i.r,i.s,e)}constructor(t,e,r){super(t,e),this.scope=r}hasLowS(){return!this.s.ltn(1)&&!this.s.gt(new h("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex"))}toChecksigFormat(){return[...this.toDER(),this.scope]}}class Se{curve;constructor(){this.curve=new Lt}generateProof(t,e,r,i){const n=re.fromRandom(),s=n.toPublicKey(),a=r.mul(n),o=this.computeChallenge(e,r,i,a,s);return{R:s,SPrime:a,z:n.add(o.mul(t)).umod(this.curve.n)}}verifyProof(t,e,r,i){const{R:n,SPrime:s,z:a}=i,o=this.computeChallenge(t,e,r,s,n),c=this.curve.g.mul(a),h=n.add(t.mul(o));if(!c.eq(h))return!1;const u=e.mul(a),l=s.add(r.mul(o));return!!u.eq(l)}computeChallenge(t,e,r,i,n){const s=[...t.encode(!0),...e.encode(!0),...r.encode(!0),...i.encode(!0),...n.encode(!0)],a=gt(s);return new h(a).umod(this.curve.n)}}const Ne={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_SPLIT:127,OP_LEFT:128,OP_NUM2BIN:128,OP_RIGHT:129,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_NOP2:177,OP_NOP3:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_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(const t in Ne)Ne[Ne[t]]=t;const Oe=Ne;class xe{chunks;static fromASM(t){const e=[],r=t.split(" ");let i=0;for(;i<r.length;){const t=r[i];let n,s=0;if(t.startsWith("OP_")&&void 0!==Oe[t]&&(n=t,s=Oe[t]),"0"===t)s=0,e.push({op:s}),i+=1;else if("-1"===t)s=Oe.OP_1NEGATE,e.push({op:s}),i+=1;else if(void 0===n){let t=r[i];t.length%2!=0&&(t="0"+t);const n=Ot(t,"hex");if(Mt(n,"hex")!==t)throw new Error("invalid hex string in script");const a=n.length;a>=0&&a<Oe.OP_PUSHDATA1?s=a:a<Math.pow(2,8)?s=Oe.OP_PUSHDATA1:a<Math.pow(2,16)?s=Oe.OP_PUSHDATA2:a<Math.pow(2,32)&&(s=Oe.OP_PUSHDATA4),e.push({data:n,op:s}),i+=1}else s===Oe.OP_PUSHDATA1||s===Oe.OP_PUSHDATA2||s===Oe.OP_PUSHDATA4?(e.push({data:Ot(r[i+2],"hex"),op:s}),i+=3):(e.push({op:s}),i+=1)}return new xe(e)}static fromHex(t){if(0===t.length)return xe.fromBinary([]);if(t.length%2!=0)throw new Error("There is an uneven number of characters in the string which suggests it is not hex encoded.");if(!/^[0-9a-fA-F]+$/.test(t))throw new Error("Some elements in this string are not hex encoded.");return xe.fromBinary(Ot(t,"hex"))}static fromBinary(t){t=[...t];const e=[],r=new Ut(t);for(;!r.eof();){const t=r.readUInt8();let i=0,n=[];if(t>0&&t<Oe.OP_PUSHDATA1)i=t,e.push({data:r.read(i),op:t});else if(t===Oe.OP_PUSHDATA1){try{i=r.readUInt8(),n=r.read(i)}catch{r.read()}e.push({data:n,op:t})}else if(t===Oe.OP_PUSHDATA2){try{i=r.readUInt16LE(),n=r.read(i)}catch{r.read()}e.push({data:n,op:t})}else if(t===Oe.OP_PUSHDATA4){try{i=r.readUInt32LE(),n=r.read(i)}catch{r.read()}e.push({data:n,op:t})}else e.push({op:t})}return new xe(e)}constructor(t=[]){this.chunks=t}toASM(){let t="";for(let e=0;e<this.chunks.length;e++){const r=this.chunks[e];t+=this._chunkToString(r)}return t.slice(1)}toHex(){return Mt(this.toBinary(),"hex")}toBinary(){const t=new Bt;for(let e=0;e<this.chunks.length;e++){const r=this.chunks[e],i=r.op;t.writeUInt8(i),null!=r.data&&(i<Oe.OP_PUSHDATA1?t.write(r.data):i===Oe.OP_PUSHDATA1?(t.writeUInt8(r.data.length),t.write(r.data)):i===Oe.OP_PUSHDATA2?(t.writeUInt16LE(r.data.length),t.write(r.data)):i===Oe.OP_PUSHDATA4&&(t.writeUInt32LE(r.data.length),t.write(r.data)))}return t.toArray()}writeScript(t){return this.chunks=this.chunks.concat(t.chunks),this}writeOpCode(t){return this.chunks.push({op:t}),this}setChunkOpCode(t,e){return this.chunks[t]={op:e},this}writeBn(t){if(t.cmpn(0)===Oe.OP_0)this.chunks.push({op:Oe.OP_0});else if(0===t.cmpn(-1))this.chunks.push({op:Oe.OP_1NEGATE});else if(t.cmpn(1)>=0&&t.cmpn(16)<=0)this.chunks.push({op:t.toNumber()+Oe.OP_1-1});else{const e=t.toSm("little");this.writeBin(e)}return this}writeBin(t){let e;if(t.length>0&&t.length<Oe.OP_PUSHDATA1)e=t.length;else if(0===t.length)e=Oe.OP_0;else if(t.length<Math.pow(2,8))e=Oe.OP_PUSHDATA1;else if(t.length<Math.pow(2,16))e=Oe.OP_PUSHDATA2;else{if(!(t.length<Math.pow(2,32)))throw new Error("You can't push that much data");e=Oe.OP_PUSHDATA4}return this.chunks.push({data:t,op:e}),this}writeNumber(t){return this.writeBn(new h(t)),this}removeCodeseparators(){const t=[];for(let e=0;e<this.chunks.length;e++)this.chunks[e].op!==Oe.OP_CODESEPARATOR&&t.push(this.chunks[e]);return this.chunks=t,this}findAndDelete(t){const e=t.toHex();for(let t=0;t<this.chunks.length;t++)e===new xe([this.chunks[t]]).toHex()&&this.chunks.splice(t,1);return this}isPushOnly(){for(let t=0;t<this.chunks.length;t++)if(this.chunks[t].op>Oe.OP_16)return!1;return!0}isLockingScript(){throw new Error("Not implemented")}isUnlockingScript(){throw new Error("Not implemented")}_chunkToString(t){const e=t.op;let r="";return r=void 0===t.data?`${r} ${Oe[e]}`:`${r} ${Nt(t.data)}`,r}}class Ae extends xe{isLockingScript(){return!0}isUnlockingScript(){return!1}}class Te extends xe{isLockingScript(){return!1}isUnlockingScript(){return!0}}const Me=1073741824,_e=Math.pow(2,31)-1,Fe=!0;class Re{sourceTXID;sourceOutputIndex;sourceSatoshis;lockingScript;transactionVersion;otherInputs;outputs;inputIndex;unlockingScript;inputSequence;lockTime;context;programCounter;lastCodeSeparator;stack;altStack;ifStack;memoryLimit;stackMem;altStackMem;constructor(t){this.sourceTXID=t.sourceTXID,this.sourceOutputIndex=t.sourceOutputIndex,this.sourceSatoshis=t.sourceSatoshis,this.lockingScript=t.lockingScript,this.transactionVersion=t.transactionVersion,this.otherInputs=t.otherInputs,this.outputs=t.outputs,this.inputIndex=t.inputIndex,this.unlockingScript=t.unlockingScript,this.inputSequence=t.inputSequence,this.lockTime=t.lockTime,this.memoryLimit=t.memoryLimit??1e5,this.stackMem=0,this.altStackMem=0,this.reset()}reset(){this.context="UnlockingScript",this.programCounter=0,this.lastCodeSeparator=null,this.stack=[],this.altStack=[],this.ifStack=[],this.stackMem=0,this.altStackMem=0}step(){let t;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;const e=()=>{t=void 0};let r;"UnlockingScript"===this.context&&this.programCounter>=this.unlockingScript.chunks.length&&(this.context="LockingScript",this.programCounter=0),r="UnlockingScript"===this.context?this.unlockingScript.chunks[this.programCounter]:this.lockingScript.chunks[this.programCounter];const i=t=>{if(0===t.length)return!0;(t=>{if(t.length<9)return!1;if(t.length>73)return!1;if(48!==t[0])return!1;if(t[1]!==t.length-3)return!1;const e=t[3];if(5+e>=t.length)return!1;const r=t[5+e];if(e+r+7!==t.length)return!1;const i=t.slice(4);if(2!==t[2])return!1;if(t[3]!==e)return!1;if(0===e)return!1;if(128&i[0])return!1;if(e>1&&0===i[0]&&!(128&i[1]))return!1;const n=t.slice(6+e);return!(2!==t[6+e-2]||t[6+e-1]!==r||0===r||128&n[0]||r>1&&0===n[0]&&!(128&n[1]))})(t)||this.scriptEvaluationError("The signature format is invalid.");const e=Ee.fromChecksigFormat(t);return e.hasLowS()||this.scriptEvaluationError("The signature must have a low S value."),!!(e.scope&Ee.SIGHASH_FORKID)||(this.scriptEvaluationError("The signature must use SIGHASH_FORKID."),!1)},n=t=>(t.length<33&&this.scriptEvaluationError("The public key is too short, it must be at least 33 bytes."),4===t[0]?65!==t.length&&this.scriptEvaluationError("The non-compressed public key must be 65 bytes."):2===t[0]||3===t[0]?33!==t.length&&this.scriptEvaluationError("The compressed public key must be 33 bytes."):this.scriptEvaluationError("The public key is in an unknown format."),!0),s=(t,e,r)=>{const i=Ee.format({sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,sourceSatoshis:this.sourceSatoshis,transactionVersion:this.transactionVersion,otherInputs:this.otherInputs,outputs:this.outputs,inputIndex:this.inputIndex,subscript:r,inputSequence:this.inputSequence,lockTime:this.lockTime,scope:t.scope}),n=new h(vt(i));return Xt(n,t,e)},a=!this.ifStack.includes(!1);let o,c,u,l,d,f,p,m,w,b,g,y,v,I,k,P,E,S,N,O,x,A,T,M,_,F,R,C,V,D,B,U;const H=r.op;var K;if(void 0===H&&this.scriptEvaluationError(`An opcode is missing in this chunk of the ${this.context}!`),Array.isArray(r.data)&&r.data.length>Me&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes."),a&&((K=H)===Oe.OP_2MUL||K===Oe.OP_2DIV||K===Oe.OP_VERIF||K===Oe.OP_VERNOTIF||K===Oe.OP_VER)&&this.scriptEvaluationError("This opcode is currently disabled."),a&&H>=0&&H<=Oe.OP_PUSHDATA4)(t=>{const e=t.data,r=t.op;return!(Array.isArray(e)&&(0===e.length?r!==Oe.OP_0:1===e.length&&e[0]>=1&&e[0]<=16?r!==Oe.OP_1+(e[0]-1):1===e.length&&129===e[0]?r!==Oe.OP_1NEGATE:e.length<=75?r!==e.length:e.length<=255?r!==Oe.OP_PUSHDATA1:e.length<=65535&&r!==Oe.OP_PUSHDATA2))})(r)||this.scriptEvaluationError("This data is not minimally-encoded."),Array.isArray(r.data)?(this.stack.push(r.data),this.stackMem+=r.data.length):(this.stack.push([]),this.stackMem+=0);else if(a||Oe.OP_IF<=H&&H<=Oe.OP_ENDIF)switch(H){case Oe.OP_1NEGATE:case Oe.OP_1:case Oe.OP_2:case Oe.OP_3:case Oe.OP_4:case Oe.OP_5:case Oe.OP_6:case Oe.OP_7:case Oe.OP_8:case Oe.OP_9:case Oe.OP_10:case Oe.OP_11:case Oe.OP_12:case Oe.OP_13:case Oe.OP_14:case Oe.OP_15:case Oe.OP_16:f=H-(Oe.OP_1-1),o=new h(f).toScriptNum(),this.stack.push(o),this.stackMem+=o.length;break;case Oe.OP_NOP:case Oe.OP_NOP2:case Oe.OP_NOP3:case Oe.OP_NOP1:case Oe.OP_NOP4:case Oe.OP_NOP5:case Oe.OP_NOP6:case Oe.OP_NOP7:case Oe.OP_NOP8:case Oe.OP_NOP9:case Oe.OP_NOP10:case Oe.OP_NOP11:case Oe.OP_NOP12:case Oe.OP_NOP13:case Oe.OP_NOP14:case Oe.OP_NOP15:case Oe.OP_NOP16:case Oe.OP_NOP17:case Oe.OP_NOP18:case Oe.OP_NOP19:case Oe.OP_NOP20:case Oe.OP_NOP21:case Oe.OP_NOP22:case Oe.OP_NOP23:case Oe.OP_NOP24:case Oe.OP_NOP25:case Oe.OP_NOP26:case Oe.OP_NOP27:case Oe.OP_NOP28:case Oe.OP_NOP29:case Oe.OP_NOP30:case Oe.OP_NOP31:case Oe.OP_NOP32:case Oe.OP_NOP33:case Oe.OP_NOP34:case Oe.OP_NOP35:case Oe.OP_NOP36:case Oe.OP_NOP37:case Oe.OP_NOP38:case Oe.OP_NOP39:case Oe.OP_NOP40:case Oe.OP_NOP41:case Oe.OP_NOP42:case Oe.OP_NOP43:case Oe.OP_NOP44:case Oe.OP_NOP45:case Oe.OP_NOP46:case Oe.OP_NOP47:case Oe.OP_NOP48:case Oe.OP_NOP49:case Oe.OP_NOP50:case Oe.OP_NOP51:case Oe.OP_NOP52:case Oe.OP_NOP53:case Oe.OP_NOP54:case Oe.OP_NOP55:case Oe.OP_NOP56:case Oe.OP_NOP57:case Oe.OP_NOP58:case Oe.OP_NOP59:case Oe.OP_NOP60:case Oe.OP_NOP61:case Oe.OP_NOP62:case Oe.OP_NOP63:case Oe.OP_NOP64:case Oe.OP_NOP65:case Oe.OP_NOP66:case Oe.OP_NOP67:case Oe.OP_NOP68:case Oe.OP_NOP69:case Oe.OP_NOP70:case Oe.OP_NOP71:case Oe.OP_NOP72:case Oe.OP_NOP73:case Oe.OP_NOP77:break;case Oe.OP_IF:case Oe.OP_NOTIF:D=!1,a&&(this.stack.length<1&&this.scriptEvaluationError("OP_IF and OP_NOTIF require at least one item on the stack when they are used!"),o=this.stacktop(-1),D=this.castToBool(o),H===Oe.OP_NOTIF&&(D=!D),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e()),this.ifStack.push(D);break;case Oe.OP_ELSE:0===this.ifStack.length&&this.scriptEvaluationError("OP_ELSE requires a preceeding OP_IF."),this.ifStack[this.ifStack.length-1]=!this.ifStack[this.ifStack.length-1];break;case Oe.OP_ENDIF:0===this.ifStack.length&&this.scriptEvaluationError("OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop();break;case Oe.OP_VERIFY:this.stack.length<1&&this.scriptEvaluationError("OP_VERIFY requires at least one item to be on the stack."),o=this.stacktop(-1),D=this.castToBool(o),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),D||this.scriptEvaluationError("OP_VERIFY requires the top stack value to be truthy.");break;case Oe.OP_RETURN:"UnlockingScript"===this.context?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.ifStack=[];break;case Oe.OP_TOALTSTACK:this.stack.length<1&&this.scriptEvaluationError("OP_TOALTSTACK requires at oeast one item to be on the stack."),t=this.stack.pop(),null!=t&&(this.altStack.push(t),this.altStackMem+=t.length,this.stackMem-=t.length),e();break;case Oe.OP_FROMALTSTACK:this.altStack.length<1&&this.scriptEvaluationError("OP_FROMALTSTACK requires at least one item to be on the stack."),t=this.altStack.pop(),null!=t&&(this.stack.push(t),this.stackMem+=t.length,this.altStackMem-=t.length),e();break;case Oe.OP_2DROP:this.stack.length<2&&this.scriptEvaluationError("OP_2DROP requires at least two items to be on the stack."),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e();break;case Oe.OP_2DUP:this.stack.length<2&&this.scriptEvaluationError("OP_2DUP requires at least two items to be on the stack."),c=this.stacktop(-2),u=this.stacktop(-1),this.stack.push([...c]),this.stackMem+=c.length,this.stack.push([...u]),this.stackMem+=u.length;break;case Oe.OP_3DUP:this.stack.length<3&&this.scriptEvaluationError("OP_3DUP requires at least three items to be on the stack."),c=this.stacktop(-3),u=this.stacktop(-2),l=this.stacktop(-1),this.stack.push([...c]),this.stackMem+=c.length,this.stack.push([...u]),this.stackMem+=u.length,this.stack.push([...l]),this.stackMem+=l.length;break;case Oe.OP_2OVER:this.stack.length<4&&this.scriptEvaluationError("OP_2OVER requires at least four items to be on the stack."),c=this.stacktop(-4),u=this.stacktop(-3),this.stack.push([...c]),this.stackMem+=c.length,this.stack.push([...u]),this.stackMem+=u.length;break;case Oe.OP_2ROT:this.stack.length<6&&this.scriptEvaluationError("OP_2ROT requires at least six items to be on the stack."),d=this.stack.splice(this.stack.length-6,2),this.stack.push(d[0]),this.stackMem+=d[0].length,this.stack.push(d[1]),this.stackMem+=d[1].length;break;case Oe.OP_2SWAP:this.stack.length<4&&this.scriptEvaluationError("OP_2SWAP requires at least four items to be on the stack."),d=this.stack.splice(this.stack.length-4,2),this.stack.push(d[0]),this.stackMem+=d[0].length,this.stack.push(d[1]),this.stackMem+=d[1].length;break;case Oe.OP_IFDUP:this.stack.length<1&&this.scriptEvaluationError("OP_IFDUP requires at least one item to be on the stack."),o=this.stacktop(-1),D=this.castToBool(o),D&&(this.stack.push([...o]),this.stackMem+=o.length);break;case Oe.OP_DEPTH:o=new h(this.stack.length).toScriptNum(),this.stack.push(o),this.stackMem+=o.length;break;case Oe.OP_DROP:this.stack.length<1&&this.scriptEvaluationError("OP_DROP requires at least one item to be on the stack."),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e();break;case Oe.OP_DUP:this.stack.length<1&&this.scriptEvaluationError("OP_DUP requires at least one item to be on the stack."),this.stack.push([...this.stacktop(-1)]),this.stackMem+=this.stacktop(-1).length;break;case Oe.OP_NIP:this.stack.length<2&&this.scriptEvaluationError("OP_NIP requires at least two items to be on the stack."),this.stack.splice(this.stack.length-2,1),this.stackMem-=this.stacktop(-1).length;break;case Oe.OP_OVER:this.stack.length<2&&this.scriptEvaluationError("OP_OVER requires at least two items to be on the stack."),this.stack.push([...this.stacktop(-2)]),this.stackMem+=this.stacktop(-2).length;break;case Oe.OP_PICK:case Oe.OP_ROLL:this.stack.length<2&&this.scriptEvaluationError(`${Oe[H]} requires at least two items to be on the stack.`),o=this.stacktop(-1),I=h.fromScriptNum(o,Fe),f=I.toNumber(),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),(f<0||f>=this.stack.length)&&this.scriptEvaluationError(`${Oe[H]} requires the top stack element to be 0 or a positive number less than the current size of the stack.`),o=this.stacktop(-f-1),H===Oe.OP_ROLL&&(this.stack.splice(this.stack.length-f-1,1),this.stackMem-=o.length),this.stack.push([...o]),this.stackMem+=o.length;break;case Oe.OP_ROT:this.stack.length<3&&this.scriptEvaluationError("OP_ROT requires at least three items to be on the stack."),g=this.stacktop(-3),y=this.stacktop(-2),v=this.stacktop(-1),this.stack[this.stack.length-3]=y,this.stack[this.stack.length-2]=v,this.stack[this.stack.length-1]=g;break;case Oe.OP_SWAP:this.stack.length<2&&this.scriptEvaluationError("OP_SWAP requires at least two items to be on the stack."),g=this.stacktop(-2),y=this.stacktop(-1),this.stack[this.stack.length-2]=y,this.stack[this.stack.length-1]=g;break;case Oe.OP_TUCK:this.stack.length<2&&this.scriptEvaluationError("OP_TUCK requires at least two items to be on the stack."),this.stack.splice(this.stack.length-2,0,[...this.stacktop(-1)]),this.stackMem+=this.stacktop(-1).length;break;case Oe.OP_SIZE:this.stack.length<1&&this.scriptEvaluationError("OP_SIZE requires at least one item to be on the stack."),I=new h(this.stacktop(-1).length),this.stack.push(I.toScriptNum()),this.stackMem+=I.toScriptNum().length;break;case Oe.OP_AND:case Oe.OP_OR:case Oe.OP_XOR:switch(this.stack.length<2&&this.scriptEvaluationError(`${Oe[H]} requires at least one item to be on the stack.`),c=this.stacktop(-2),u=this.stacktop(-1),c.length!==u.length&&this.scriptEvaluationError(`${Oe[H]} requires the top two stack items to be the same size.`),H){case Oe.OP_AND:for(let t=0;t<c.length;t++)c[t]&=u[t];break;case Oe.OP_OR:for(let t=0;t<c.length;t++)c[t]|=u[t];break;case Oe.OP_XOR:for(let t=0;t<c.length;t++)c[t]^=u[t]}t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e();break;case Oe.OP_INVERT:this.stack.length<1&&this.scriptEvaluationError("OP_INVERT requires at least one item to be on the stack."),o=this.stacktop(-1);for(let t=0;t<o.length;t++)o[t]=~o[t];break;case Oe.OP_LSHIFT:case Oe.OP_RSHIFT:if(this.stack.length<2&&this.scriptEvaluationError(`${Oe[H]} requires at least two items to be on the stack.`),c=this.stacktop(-2),0===c.length)t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e();else{let r;k=new h(c),P=h.fromScriptNum(this.stacktop(-1),Fe),f=P.toNumber(),f<0&&this.scriptEvaluationError(`${Oe[H]} requires the top item on the stack not to be negative.`),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),H===Oe.OP_LSHIFT&&(r=k.ushln(f)),H===Oe.OP_RSHIFT&&(r=k.ushrn(f));const i=((t,e)=>{const r=t;for(;r.length<e;)r.unshift(0);return r})(r.toArray().slice(-1*c.length),c.length);this.stack.push(i),this.stackMem+=i.length}break;case Oe.OP_EQUAL:case Oe.OP_EQUALVERIFY:this.stack.length<2&&this.scriptEvaluationError(`${Oe[H]} requires at least two items to be on the stack.`),c=this.stacktop(-2),u=this.stacktop(-1),B=Nt(c)===Nt(u),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),this.stack.push(B?[1]:[]),this.stackMem+=B?1:0,H===Oe.OP_EQUALVERIFY&&(this.castToBool(this.stacktop(-1))?(t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e()):this.scriptEvaluationError("OP_EQUALVERIFY requires the top two stack items to be equal."));break;case Oe.OP_1ADD:case Oe.OP_1SUB:case Oe.OP_NEGATE:case Oe.OP_ABS:case Oe.OP_NOT:case Oe.OP_0NOTEQUAL:switch(this.stack.length<1&&this.scriptEvaluationError(`${Oe[H]} requires at least one items to be on the stack.`),o=this.stacktop(-1),I=h.fromScriptNum(o,Fe),H){case Oe.OP_1ADD:I=I.addn(1);break;case Oe.OP_1SUB:I=I.subn(1);break;case Oe.OP_NEGATE:I=I.neg();break;case Oe.OP_ABS:I.cmpn(0)<0&&(I=I.neg());break;case Oe.OP_NOT:I=new h(0===I.cmpn(0)?1:0);break;case Oe.OP_0NOTEQUAL:I=new h(0!==I.cmpn(0)?1:0)}t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),this.stack.push(I.toScriptNum()),this.stackMem+=I.toScriptNum().length;break;case Oe.OP_ADD:case Oe.OP_SUB:case Oe.OP_MUL:case Oe.OP_MOD:case Oe.OP_DIV:case Oe.OP_BOOLAND:case Oe.OP_BOOLOR:case Oe.OP_NUMEQUAL:case Oe.OP_NUMEQUALVERIFY:case Oe.OP_NUMNOTEQUAL:case Oe.OP_LESSTHAN:case Oe.OP_GREATERTHAN:case Oe.OP_LESSTHANOREQUAL:case Oe.OP_GREATERTHANOREQUAL:case Oe.OP_MIN:case Oe.OP_MAX:switch(this.stack.length<2&&this.scriptEvaluationError(`${Oe[H]} requires at least two items to be on the stack.`),k=h.fromScriptNum(this.stacktop(-2),Fe),P=h.fromScriptNum(this.stacktop(-1),Fe),I=new h(0),H){case Oe.OP_ADD:I=k.add(P);break;case Oe.OP_SUB:I=k.sub(P);break;case Oe.OP_MUL:I=k.mul(P);break;case Oe.OP_DIV:0===P.cmpn(0)&&this.scriptEvaluationError("OP_DIV cannot divide by zero!"),I=k.div(P);break;case Oe.OP_MOD:0===P.cmpn(0)&&this.scriptEvaluationError("OP_MOD cannot divide by zero!"),I=k.mod(P);break;case Oe.OP_BOOLAND:I=new h(0!==k.cmpn(0)&&0!==P.cmpn(0)?1:0);break;case Oe.OP_BOOLOR:I=new h(0!==k.cmpn(0)||0!==P.cmpn(0)?1:0);break;case Oe.OP_NUMEQUAL:case Oe.OP_NUMEQUALVERIFY:I=new h(0===k.cmp(P)?1:0);break;case Oe.OP_NUMNOTEQUAL:I=new h(0!==k.cmp(P)?1:0);break;case Oe.OP_LESSTHAN:I=new h(k.cmp(P)<0?1:0);break;case Oe.OP_GREATERTHAN:I=new h(k.cmp(P)>0?1:0);break;case Oe.OP_LESSTHANOREQUAL:I=new h(k.cmp(P)<=0?1:0);break;case Oe.OP_GREATERTHANOREQUAL:I=new h(k.cmp(P)>=0?1:0);break;case Oe.OP_MIN:I=k.cmp(P)<0?k:P;break;case Oe.OP_MAX:I=k.cmp(P)>0?k:P}t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),this.stack.push(I.toScriptNum()),this.stackMem+=I.toScriptNum().length,H===Oe.OP_NUMEQUALVERIFY&&(this.castToBool(this.stacktop(-1))?(t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e()):this.scriptEvaluationError("OP_NUMEQUALVERIFY requires the top stack item to be truthy."));break;case Oe.OP_WITHIN:this.stack.length<3&&this.scriptEvaluationError("OP_WITHIN requires at least three items to be on the stack."),k=h.fromScriptNum(this.stacktop(-3),Fe),P=h.fromScriptNum(this.stacktop(-2),Fe),E=h.fromScriptNum(this.stacktop(-1),Fe),D=P.cmp(k)<=0&&k.cmp(E)<0,t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),this.stack.push(D?[1]:[]),this.stackMem+=D?1:0;break;case Oe.OP_RIPEMD160:case Oe.OP_SHA1:case Oe.OP_SHA256:case Oe.OP_HASH160:case Oe.OP_HASH256:{this.stack.length<1&&this.scriptEvaluationError(`${Oe[H]} requires at least one item to be on the stack.`);let r=[];o=this.stacktop(-1),H===Oe.OP_RIPEMD160?r=wt(o):H===Oe.OP_SHA1?r=bt(o):H===Oe.OP_SHA256?r=gt(o):H===Oe.OP_HASH160?r=It(o):H===Oe.OP_HASH256&&(r=vt(o)),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),this.stack.push(r),this.stackMem+=r.length;break}case Oe.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case Oe.OP_CHECKSIG:case Oe.OP_CHECKSIGVERIFY:this.stack.length<2&&this.scriptEvaluationError(`${Oe[H]} requires at least two items to be on the stack.`),S=this.stacktop(-2),N=this.stacktop(-1),i(S)&&n(N)||this.scriptEvaluationError(`${Oe[H]} requires correct encoding for the public key and signature.`),O="UnlockingScript"===this.context?new xe(this.unlockingScript.chunks.slice(this.lastCodeSeparator??0)):new xe(this.lockingScript.chunks.slice(this.lastCodeSeparator??0)),O.findAndDelete((new xe).writeBin(S));try{x=Ee.fromChecksigFormat(S),A=Gt.fromDER(N),U=s(x,A,O)}catch(t){U=!1}!U&&S.length>0&&this.scriptEvaluationError(`${Oe[H]} failed to verify the signature, and requires an empty signature when verification fails.`),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),this.stack.push(U?[1]:[]),this.stackMem+=U?1:0,H===Oe.OP_CHECKSIGVERIFY&&(U?(t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e()):this.scriptEvaluationError("OP_CHECKSIGVERIFY requires that a valid signature is provided."));break;case Oe.OP_CHECKMULTISIG:case Oe.OP_CHECKMULTISIGVERIFY:T=1,this.stack.length<T&&this.scriptEvaluationError(`${Oe[H]} requires at least 1 item to be on the stack.`),_=h.fromScriptNum(this.stacktop(-T),Fe).toNumber(),(_<0||_>_e)&&this.scriptEvaluationError(`${Oe[H]} requires a key count between 0 and ${_e}.`),F=++T,T+=_,R=_+2,this.stack.length<T&&this.scriptEvaluationError(`${Oe[H]} requires the number of stack items not to be less than the number of keys used.`),C=h.fromScriptNum(this.stacktop(-T),Fe).toNumber(),(C<0||C>_)&&this.scriptEvaluationError(`${Oe[H]} requires the number of signatures to be no greater than the number of keys.`),V=++T,T+=C,this.stack.length<T&&this.scriptEvaluationError(`${Oe[H]} requires the number of stack items not to be less than the number of signatures provided.`),O="UnlockingScript"===this.context?new xe(this.unlockingScript.chunks.slice(this.lastCodeSeparator??0)):new xe(this.lockingScript.chunks.slice(this.lastCodeSeparator??0));for(let t=0;t<C;t++)S=this.stacktop(-V-t),O.findAndDelete((new xe).writeBin(S));for(U=!0;U&&C>0;){S=this.stacktop(-V),N=this.stacktop(-F),i(S)&&n(N)||this.scriptEvaluationError(`${Oe[H]} requires correct encoding for the public key and signature.`);try{x=Ee.fromChecksigFormat(S),A=Gt.fromString(Nt(N)),M=s(x,A,O)}catch(t){M=!1}M&&(V++,C--),F++,_--,C>_&&(U=!1)}for(;T-- >1;)!U&&0===R&&this.stacktop(-1).length>0&&this.scriptEvaluationError(`${Oe[H]} failed to verify a signature, and requires an empty signature when verification fails.`),R>0&&R--,t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e();this.stack.length<1&&this.scriptEvaluationError(`${Oe[H]} requires an extra item to be on the stack.`),this.stacktop(-1).length>0&&this.scriptEvaluationError(`${Oe[H]} requires the extra stack item to be empty.`),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),this.stack.push(U?[1]:[]),this.stackMem+=U?1:0,H===Oe.OP_CHECKMULTISIGVERIFY&&(U?(t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e()):this.scriptEvaluationError("OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."));break;case Oe.OP_CAT:this.stack.length<2&&this.scriptEvaluationError("OP_CAT requires at least two items to be on the stack."),c=this.stacktop(-2),u=this.stacktop(-1),c.length+u.length>Me&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes."),this.stack[this.stack.length-2]=[...c,...u],this.stackMem-=c.length,this.stackMem-=u.length,this.stackMem+=c.length+u.length,t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e();break;case Oe.OP_SPLIT:this.stack.length<2&&this.scriptEvaluationError("OP_SPLIT requires at least two items to be on the stack."),c=this.stacktop(-2),f=h.fromScriptNum(this.stacktop(-1),Fe).toNumber(),(f<0||f>c.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."),u=[...c],this.stack[this.stack.length-2]=u.slice(0,f),this.stackMem-=c.length,this.stackMem+=f,this.stack[this.stack.length-1]=u.slice(f),this.stackMem+=c.length-f;break;case Oe.OP_NUM2BIN:if(this.stack.length<2&&this.scriptEvaluationError("OP_NUM2BIN requires at least two items to be on the stack."),p=h.fromScriptNum(this.stacktop(-1),Fe).toNumber(),p>Me&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes."),t=this.stack.pop(),null!=t&&(this.stackMem-=t.length),e(),m=this.stacktop(-1),m=Ht(m),m.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."),m.length===p){this.stack[this.stack.length-1]=m;break}for(b=0,m.length>0&&(b=128&m[m.length-1],m[m.length-1]&=127),w=new Array(p),w.fill(0),f=0;f<p;f++)w[f]=m[f];for(f=m.length-1;f++<p-2;)w[f]=0;w[f]=b,this.stack[this.stack.length-1]=w,this.stackMem-=m.length,this.stackMem+=p;break;case Oe.OP_BIN2NUM:this.stack.length<1&&this.scriptEvaluationError("OP_BIN2NUM requires at least one item to be on the stack."),c=this.stacktop(-1),u=Ht(c),this.stack[this.stack.length-1]=u,this.stackMem-=c.length,this.stackMem+=u.length,((t,e=Number.MAX_SAFE_INTEGER)=>!(t.length>e||t.length>0&&!(127&t[t.length-1]||!(t.length<=1)&&128&t[t.length-2])))(u)||this.scriptEvaluationError("OP_BIN2NUM requires that the resulting number is valid.");break;default:this.scriptEvaluationError("Invalid opcode!")}return this.programCounter++,!0}validate(){for(this.unlockingScript.isPushOnly()||this.scriptEvaluationError("Unlocking scripts can only contain push operations, and no other opcodes.");this.step()&&!("LockingScript"===this.context&&this.programCounter>=this.lockingScript.chunks.length););return this.ifStack.length>0&&this.scriptEvaluationError("Every OP_IF must be terminated prior to the end of the script."),1!==this.stack.length&&this.scriptEvaluationError("The clean stack rule requires exactly one item to be on the stack after script execution."),this.castToBool(this.stacktop(-1))||this.scriptEvaluationError("The top stack element must be truthy after script evaluation."),!0}stacktop(t){return this.stack[this.stack.length+t]}castToBool(t){for(let e=0;e<t.length;e++)if(0!==t[e])return e!==t.length-1||128!==t[e];return!1}scriptEvaluationError(t){throw new Error(`Script evaluation error: ${t}\n\nSource TXID: ${this.sourceTXID}\nSource output index: ${this.sourceOutputIndex}\nContext: ${this.context}\nProgram counter: ${this.programCounter}\nStack size: ${this.stack.length}\nAlt stack size: ${this.altStack.length}`)}}function Ce(t){if(null==t)throw new Error("must have value");return t}class Ve{lock(t){let e;if("string"==typeof t){const r=Dt(t);if(0!==r.prefix[0]&&111!==r.prefix[0])throw new Error("only P2PKH is supported");e=r.data}else e=t;if(20!==e.length)throw new Error("P2PKH hash length must be 20 bytes");return new Ae([{op:Oe.OP_DUP},{op:Oe.OP_HASH160},{op:e.length,data:e},{op:Oe.OP_EQUALVERIFY},{op:Oe.OP_CHECKSIG}])}unlock(t,e="all",r=!1,i,n){return{sign:async(s,a)=>{let o=Ee.SIGHASH_FORKID;"all"===e&&(o|=Ee.SIGHASH_ALL),"none"===e&&(o|=Ee.SIGHASH_NONE),"single"===e&&(o|=Ee.SIGHASH_SINGLE),r&&(o|=Ee.SIGHASH_ANYONECANPAY);const c=s.inputs[a],h=s.inputs.filter(((t,e)=>e!==a)),u=c.sourceTXID??c.sourceTransaction?.id("hex");if(null==u||void 0===u)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(""===u)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(i||=c.sourceTransaction?.outputs[c.sourceOutputIndex].satoshis,null==i||void 0===i)throw new Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(n||=c.sourceTransaction?.outputs[c.sourceOutputIndex].lockingScript,null==n)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");const l=Ee.format({sourceTXID:u,sourceOutputIndex:Ce(c.sourceOutputIndex),sourceSatoshis:i,transactionVersion:s.version,otherInputs:h,inputIndex:a,outputs:s.outputs,inputSequence:Ce(c.sequence),subscript:n,lockTime:s.lockTime,scope:o}),d=t.sign(gt(l)),f=new Ee(d.r,d.s,o).toChecksigFormat(),p=t.toPublicKey().encode(!0);return new Te([{op:f.length,data:f},{op:p.length,data:p}])},estimateLength:async()=>108}}}class De{type="raw";constructor(t="raw"){this.type=t}lock(t){const e=[{op:Oe.OP_OVER},{op:Oe.OP_3},{op:Oe.OP_SPLIT},{op:Oe.OP_NIP},{op:Oe.OP_1},{op:Oe.OP_SPLIT},{op:Oe.OP_SWAP},{op:Oe.OP_SPLIT},{op:Oe.OP_DROP}];return"raw"!==this.type&&e.push({op:Oe["OP_"+this.type]}),e.push({op:t.length,data:t}),e.push({op:Oe.OP_EQUALVERIFY}),e.push({op:Oe.OP_CHECKSIG}),new Ae(e)}unlock(t,e,r="all",i=!1){return{sign:async(n,s)=>{void 0===e&&(e=re.fromRandom());let a=Ee.SIGHASH_FORKID;"all"===r&&(a|=Ee.SIGHASH_ALL),"none"===r&&(a|=Ee.SIGHASH_NONE),"single"===r&&(a|=Ee.SIGHASH_SINGLE),i&&(a|=Ee.SIGHASH_ANYONECANPAY);const o=[...n.inputs],[c]=o.splice(s,1);if("object"!=typeof c.sourceTransaction)throw new Error("The source transaction is needed for transaction signing.");const h=Ee.format({sourceTXID:c.sourceTransaction?.id("hex")??"",sourceOutputIndex:c.sourceOutputIndex??0,sourceSatoshis:c.sourceTransaction?.outputs[c.sourceOutputIndex]?.satoshis??0,transactionVersion:n.version,otherInputs:o,inputIndex:s,outputs:n.outputs,inputSequence:c.sequence??4294967295,subscript:c.sourceTransaction?.outputs[c.sourceOutputIndex]?.lockingScript??new xe,lockTime:n.lockTime,scope:a}),u=e.sign(gt(h),void 0,!0,t),l=new Ee(u.r,u.s,a).toChecksigFormat(),d=e.toPublicKey().encode(!0);return new Te([{op:l.length,data:l},{op:d.length,data:d}])},estimateLength:async()=>108}}}function Be(t){if(null==t)throw new Error("must have value");return t}class Ue{wallet;originator;static decode(t){const e=Gt.fromString(Nt(Be(t.chunks[0].data))),r=[];for(let e=2;e<t.chunks.length;e++){const i=t.chunks[e+1]?.op;let n=t.chunks[e].data??[];if(0===n.length&&(t.chunks[e].op>=80&&t.chunks[e].op<=95?n=[t.chunks[e].op-80]:0===t.chunks[e].op?n=[0]:79===t.chunks[e].op&&(n=[129])),r.push(n),i===Oe.OP_DROP||i===Oe.OP_2DROP)break}return{fields:r,lockingPublicKey:e}}constructor(t,e){this.wallet=t,this.originator=e}async lock(t,e,r,i,n=!1,s=!0,a="before"){const{publicKey:o}=await this.wallet.getPublicKey({protocolID:e,keyID:r,counterparty:i,forSelf:n},this.originator),c=[],h=[];if(c.push({op:o.length/2,data:Ot(o,"hex")}),c.push({op:Oe.OP_CHECKSIG}),s){const n=t.reduce(((t,e)=>[...t,...e]),[]),{signature:s}=await this.wallet.createSignature({data:n,protocolID:e,keyID:r,counterparty:i},this.originator);t.push(s)}for(const e of t)h.push(0===(u=e).length||1===u.length&&0===u[0]?{op:0}:1===u.length&&u[0]>0&&u[0]<=16?{op:80+u[0]}:1===u.length&&129===u[0]?{op:79}:u.length<=75?{op:u.length,data:u}:u.length<=255?{op:76,data:u}:u.length<=65535?{op:77,data:u}:{op:78,data:u});var u;let l=t.length;for(;l>1;)h.push({op:Oe.OP_2DROP}),l-=2;return 0!==l&&h.push({op:Oe.OP_DROP}),new Ae("before"===a?[...c,...h]:[...h,...c])}unlock(t,e,r,i="all",n=!1,s,a){return{sign:async(o,c)=>{let h=Ee.SIGHASH_FORKID;"all"===i&&(h|=Ee.SIGHASH_ALL),"none"===i&&(h|=Ee.SIGHASH_NONE),"single"===i&&(h|=Ee.SIGHASH_SINGLE),n&&(h|=Ee.SIGHASH_ANYONECANPAY);const u=o.inputs[c],l=o.inputs.filter(((t,e)=>e!==c)),d=u.sourceTXID??u.sourceTransaction?.id("hex");if(null==d||void 0===d)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(s||=u.sourceTransaction?.outputs[u.sourceOutputIndex].satoshis,null==s||void 0===s)throw new Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(a||=u.sourceTransaction?.outputs[u.sourceOutputIndex].lockingScript,null==a)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");const f=Ee.format({sourceTXID:d,sourceOutputIndex:Be(u.sourceOutputIndex),sourceSatoshis:s,transactionVersion:o.version,otherInputs:l,inputIndex:c,outputs:o.outputs,inputSequence:u.sequence??4294967295,subscript:a,lockTime:o.lockTime,scope:h}),p=gt(f),{signature:m}=await this.wallet.createSignature({data:p,protocolID:t,keyID:e,counterparty:r},this.originator),w=$t.fromDER([...m]),b=new Ee(w.r,w.s,h).toChecksigFormat();return new Te([{op:b.length,data:b}])},estimateLength:async()=>73}}}class He{value;constructor(t){this.value=t}async computeFee(t){const e=t=>t>2**32?9:t>65536?5:t>253?3:1;let r=4;r+=e(t.inputs.length);for(let i=0;i<t.inputs.length;i++){const n=t.inputs[i];let s;if(r+=40,"object"==typeof n.unlockingScript)s=n.unlockingScript.toBinary().length;else{if("object"!=typeof n.unlockingScriptTemplate)throw new Error("All inputs must have an unlocking script or an unlocking script template for sat/kb fee computation.");s=await n.unlockingScriptTemplate.estimateLength(t,i)}r+=e(s),r+=s}r+=e(t.outputs.length);for(const i of t.outputs){r+=8;const t=i.lockingScript.toBinary().length;r+=e(t),r+=t}return r+=4,Math.ceil(r/1e3*this.value)}}class Ke{https;constructor(t){this.https=t}async request(t,e){return await new Promise(((r,i)=>{const n=this.https.request(t,e,(t=>{let e="";t.on("data",(t=>{e+=t})),t.on("end",(()=>{const i=t.statusCode>=200&&t.statusCode<=299,n=t.headers["content-type"],s=""!==e&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(e):e;r({status:t.statusCode,statusText:t.statusMessage,ok:i,data:s})}))}));n.on("error",(t=>{i(t)})),null!==e.data&&void 0!==e.data&&n.write(JSON.stringify(e.data)),n.end()}))}}class qe{fetch;constructor(t){this.fetch=t}async request(t,e){const r={method:e.method,headers:e.headers,body:JSON.stringify(e.data)},i=await this.fetch(t,r),n=i.headers.get("Content-Type"),s=n?.startsWith("application/json")?await i.json():await i.text();return{ok:i.ok,status:i.status,statusText:i.statusText,data:s}}}function Le(){const t={async request(...t){throw new Error("No method available to perform HTTP request")}};if("undefined"!=typeof window&&"function"==typeof window.fetch)return new qe(window.fetch.bind(window));if("undefined"==typeof require)return t;try{const t=require("https");return new Ke(t)}catch(e){return t}}function $e(){return`ts-sdk-${Nt(Zt(16))}`}class ze{URL;apiKey;deploymentId;callbackUrl;callbackToken;headers;httpClient;constructor(t,e){if(this.URL=t,"string"==typeof e)this.apiKey=e,this.httpClient=Le(),this.deploymentId=$e(),this.callbackToken=void 0,this.callbackUrl=void 0;else{const t=e??{},{apiKey:r,deploymentId:i,httpClient:n,callbackToken:s,callbackUrl:a,headers:o}=t;this.apiKey=r,this.httpClient=n??Le(),this.deploymentId=i??$e(),this.callbackToken=s,this.callbackUrl=a,this.headers=o}}requestHeaders(){const t={"Content-Type":"application/json","XDeployment-ID":this.deploymentId};if(null!=this.apiKey&&""!==this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),null!=this.callbackUrl&&""!==this.callbackUrl&&(t["X-CallbackUrl"]=this.callbackUrl),null!=this.callbackToken&&""!==this.callbackToken&&(t["X-CallbackToken"]=this.callbackToken),null!=this.headers)for(const e in this.headers)t[e]=this.headers[e];return t}async broadcast(t){let e;try{e=t.toHexEF()}catch(r){if("All inputs must have source transactions when serializing to EF format"!==r.message)throw r;e=t.toHex()}const r={method:"POST",headers:this.requestHeaders(),data:{rawTx:e}};try{const t=await this.httpClient.request(`${this.URL}/v1/tx`,r);if(t.ok){const{txid:e,extraInfo:r,txStatus:i,competingTxs:n}=t.data,s={status:"success",txid:e,message:`${i} ${r}`};return null!=n&&(s.competingTxs=n),s}{const e=typeof t.status,r={status:"error",code:"number"===e||"string"===e?t.status.toString():"ERR_UNKNOWN",description:"Unknown error"};let i=t.data;if("string"==typeof i)try{i=JSON.parse(t.data)}catch{}return"object"==typeof i&&(null!==i&&(r.more=i),null!=i&&"string"==typeof i.txid&&(r.txid=i.txid),null!=i&&"detail"in i&&"string"==typeof i.detail&&(r.description=i.detail)),r}}catch(t){return{status:"error",code:"500",description:"string"==typeof t.message?t.message:"Internal Server Error"}}}async broadcastMany(t){const e=t.map((t=>{try{return{rawTx:t.toHexEF()}}catch(e){if("All inputs must have source transactions when serializing to EF format"===e.message)return{rawTx:t.toHex()};throw e}})),r={method:"POST",headers:this.requestHeaders(),data:e};try{return(await this.httpClient.request(`${this.URL}/v1/txs`,r)).data}catch(e){const r={status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"};return t.map((()=>r))}}}function je(t=!1,e={}){return new ze(t?"https://arc-test.taal.com":"https://arc.taal.com",e)}class We{network;apiKey;URL;httpClient;constructor(t="main",e={}){const{apiKey:r,httpClient:i}=e;this.network=t,this.URL=`https://api.whatsonchain.com/v1/bsv/${t}`,this.httpClient=i??Le(),this.apiKey=r??""}async isValidRootForHeight(t,e){const r={method:"GET",headers:this.getHttpHeaders()},i=await this.httpClient.request(`${this.URL}/block/${e}/header`,r);if(i.ok){const{merkleroot:e}=i.data;return e===t}if(404===i.status)return!1;throw new Error(`Failed to verify merkleroot for height ${e} because of an error: ${JSON.stringify(i.data)} `)}async currentHeight(){try{const t={method:"GET",headers:this.getHttpHeaders()},e=await this.httpClient.request(`${this.URL}/block/headers`,t);if(e.ok)return e.data[0].height;throw new Error(`Failed to get current height because of an error: ${JSON.stringify(e.data)} `)}catch(t){throw new Error(`Failed to get current height because of an error: ${t instanceof Error?t.message:String(t)}`)}}getHttpHeaders(){const t={Accept:"application/json"};return"string"==typeof this.apiKey&&""!==this.apiKey.trim()&&(t.Authorization=this.apiKey),t}}function Xe(){return new We}class Ge{blockHeight;path;static fromHex(t){return Ge.fromBinary(Ot(t,"hex"))}static fromReader(t,e=!0){const r=t.readVarIntNum(),i=t.readUInt8(),n=Array(i).fill(null).map((()=>[]));let s,a,o;for(let e=0;e<i;e++){for(o=t.readVarIntNum();o>0;){a=t.readVarIntNum(),s=t.readUInt8();const r={offset:a};1&s?r.duplicate=!0:(2&s&&(r.txid=!0),r.hash=Nt(t.read(32).reverse())),Array.isArray(n[e])&&0!==n[e].length||(n[e]=[]),n[e].push(r),o--}n[e].sort(((t,e)=>t.offset-e.offset))}return new Ge(r,n,e)}static fromBinary(t){const e=new Ut(t);return Ge.fromReader(e)}static fromCoinbaseTxidAndHeight(t,e){return new Ge(e,[[{offset:0,hash:t,txid:!0}]])}constructor(t,e,r=!0){this.blockHeight=t,this.path=e;const i=Array(this.path.length).fill(0).map((()=>new Set));let n;this.path.forEach(((t,e)=>{if(0===t.length&&0===e)throw new Error(`Empty level at height: ${e}`);const n=new Set;t.forEach((t=>{if(n.has(t.offset))throw new Error(`Duplicate offset: ${t.offset}, at height: ${e}`);if(n.add(t.offset),0===e){if(!0!==t.duplicate)for(let e=1;e<this.path.length;e++)i[e].add(t.offset>>e^1)}else if(r&&!i[e].has(t.offset))throw new Error(`Invalid offset: ${t.offset}, at height: ${e}, with legal offsets: ${Array.from(i[e]).join(", ")}`)}))})),this.path[0].forEach(((t,e)=>{if(0===e&&(n=this.computeRoot(t.hash)),n!==this.computeRoot(t.hash))throw new Error("Mismatched roots")}))}toBinary(){const t=new Bt;t.writeVarIntNum(this.blockHeight);const e=this.path.length;t.writeUInt8(e);for(let r=0;r<e;r++){const e=Object.keys(this.path[r]).length;t.writeVarIntNum(e);for(const e of this.path[r]){t.writeVarIntNum(e.offset);let r=0;!0===e?.duplicate&&(r|=1),void 0!==e?.txid&&null!==e.txid&&(r|=2),t.writeUInt8(r),1&r||t.write(Ot(e.hash,"hex").reverse())}}return t.toArray()}toHex(){return Nt(this.toBinary())}indexOf(t){const e=this.path[0].find((e=>e.hash===t));if(null==e)throw new Error(`Transaction ID ${t} not found in the Merkle Path`);return e.offset}computeRoot(t){if("string"!=typeof t){const e=this.path[0].find((t=>Boolean(t?.hash)));if(null==e)throw new Error("No valid leaf found in the Merkle Path");t=e.hash}if("string"!=typeof t)throw new Error("Transaction ID is undefined");const e=this.indexOf(t);if("number"!=typeof e)throw new Error(`This proof does not contain the txid: ${t??"undefined"}`);const r=t=>Nt(vt(Ot(t,"hex").reverse()).reverse());let i=t;if(1===this.path.length&&1===this.path[0].length)return i;for(let t=0;t<this.path.length;t++){this.path[t];const n=e>>t^1,s=this.findOrComputeLeaf(t,n);if("object"!=typeof s)throw new Error(`Missing hash for index ${e} at height ${t}`);i=!0===s.duplicate?r((i??"")+(i??"")):r(n%2!=0?(s.hash??"")+(i??""):(i??"")+(s.hash??""))}return i}findOrComputeLeaf(t,e){const r=t=>Nt(vt(Ot(t,"hex").reverse()).reverse());let i=this.path[t].find((t=>t.offset===e));if(null!=i)return i;if(0===t)return;const n=t-1,s=e<<1,a=this.findOrComputeLeaf(n,s);if(null==a||null==a.hash||""===a.hash)return;const o=this.findOrComputeLeaf(n,s+1);if(null==o)return;let c;return c=!0===o.duplicate?r(a.hash+a.hash):r((o.hash??"")+(a.hash??"")),i={offset:e,hash:c},i}async verify(t,e){const r=this.computeRoot(t);if(0===this.indexOf(t)){const t=await e.currentHeight();if(this.blockHeight+100<t)return!1}return await e.isValidRootForHeight(r,this.blockHeight)}combine(t){if(this.blockHeight!==t.blockHeight)throw new Error("You cannot combine paths which do not have the same block height.");if(this.computeRoot()!==t.computeRoot())throw new Error("You cannot combine paths which do not have the same root.");const e=[];for(let r=0;r<this.path.length;r++){e.push([]);for(let t=0;t<this.path[r].length;t++)e[r].push(this.path[r][t]);for(let i=0;i<t.path[r].length;i++)if(void 0===e[r].find((e=>e.offset===t.path[r][i].offset)))e[r].push(t.path[r][i]);else if(void 0!==t.path[r][i]?.txid&&null!==t.path[r][i]?.txid){const n=e[r].find((e=>e.offset===t.path[r][i].offset));null!=n&&(n.txid=!0)}}this.path=e,this.trim()}trim(){const t=(t,e)=>{0!==e.length&&e.slice(-1)[0]===t||e.push(t)},e=(t,e)=>{for(let r=t.length;r>=0;r--){const i=this.path[e].findIndex((e=>e.offset===t[r]));i>=0&&this.path[e].splice(i,1)}},r=e=>{const r=[];for(const i of e)t(i>>1,r);return r};let i=[],n=[];for(let t=0;t<this.path.length;t++)this.path[t].sort(((t,e)=>t.offset-e.offset));for(let e=0;e<this.path[0].length;e++){const r=this.path[0][e];if(!0===r.txid)t(r.offset>>1,i);else{const i=r.offset%2==1,s=this.path[0][e+(i?-1:1)];void 0!==s.txid&&null!==s.txid&&s.txid||t(s.offset,n)}}e(n,0);for(let t=1;t<this.path.length;t++)n=i,i=r(i),e(n,t)}}class Ye{_bumpIndex;_tx;_rawTx;_txid;inputTxids=[];isValid=void 0;get bumpIndex(){return this._bumpIndex}set bumpIndex(t){this._bumpIndex=t,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=Nt(vt(this._rawTx)),this._txid;throw new Error("Internal")}get tx(){return null!=this._tx?this._tx:null!=this._rawTx?(this._tx=ir.fromBinary(this._rawTx),this._tx):void 0}get rawTx(){return null!=this._rawTx?this._rawTx:null!=this._tx?(this._rawTx=this._tx.toBinary(),this._rawTx):void 0}constructor(t,e){"string"==typeof t?this._txid=t:Array.isArray(t)?this._rawTx=t:this._tx=t,this.bumpIndex=e,this.updateInputTxids()}static fromTx(t,e){return new Ye(t,e)}static fromRawTx(t,e){return new Ye(t,e)}static fromTxid(t,e){return new Ye(t,e)}updateInputTxids(){if(this.hasProof||null==this.tx)this.inputTxids=[];else{const t={};for(const e of this.tx.inputs)void 0!==e.sourceTXID&&null!==e.sourceTXID&&""!==e.sourceTXID&&(t[e.sourceTXID]=!0);this.inputTxids=Object.keys(t)}}toWriter(t,e){const r=e=>{t.writeUInt8(e)},i=()=>{if(null!=this._rawTx)t.write(this._rawTx);else{if(null==this._tx)throw new Error("a valid serialized Transaction is expected");t.write(this._tx.toBinary())}};e===Qe?this.isTxidOnly?(r(er.TXID_ONLY),(()=>{if(null==this._txid)throw new Error("Transaction ID (_txid) is undefined");t.writeReverse(Ot(this._txid,"hex"))})()):void 0!==this.bumpIndex?(r(er.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex),i()):(r(er.RAWTX),i()):(i(),(()=>{void 0===this.bumpIndex?r(er.RAWTX):(r(er.RAWTX_AND_BUMP_INDEX),t.writeVarIntNum(this.bumpIndex))})())}static fromReader(t,e){let r,i,n;if(e===Qe){const e=t.readUInt8();e===er.TXID_ONLY?n=Ye.fromTxid(Nt(t.readReverse(32))):(e===er.RAWTX_AND_BUMP_INDEX&&(i=t.readVarIntNum()),r=ir.fromReader(t),n=Ye.fromTx(r,i))}else r=ir.fromReader(t),i=0!==t.readUInt8()?t.readVarIntNum():void 0,n=Ye.fromTx(r,i);return n}}function Je(t){if(null==t)throw new Error("Expected a valid value, but got undefined.");return t}const Ze=4022206465,Qe=4022206466,tr=16843009;var er;!function(t){t[t.RAWTX=0]="RAWTX",t[t.RAWTX_AND_BUMP_INDEX=1]="RAWTX_AND_BUMP_INDEX",t[t.TXID_ONLY=2]="TXID_ONLY"}(er||(er={}));class rr{bumps=[];txs=[];version=Qe;atomicTxid=void 0;constructor(t=Qe){this.version=t}findTxid(t){return this.txs.find((e=>e.txid===t))}makeTxidOnly(t){const e=this.txs.findIndex((e=>e.txid===t));if(-1===e)return;let r=this.txs[e];return r.isTxidOnly||(this.txs.splice(e,1),r=this.mergeTxidOnly(t)),r}findBump(t){return this.bumps.find((e=>e.path[0].some((e=>e.hash===t))))}findTransactionForSigning(t){const e=this.findTxid(t);if(null!=e&&null!=e.tx){for(const t of e.tx.inputs)if(null==t.sourceTransaction){const e=this.findTxid(Je(t.sourceTXID));null!=e&&(t.sourceTransaction=e.tx)}return e.tx}}findAtomicTransaction(t){const e=this.findTxid(t);if(null==e||null==e.tx)return;const r=(t,e)=>{const i=t.findBump(e.id("hex"));if(null!=i)e.merklePath=i;else for(const i of e.inputs){if(null==i.sourceTransaction){const e=t.findTxid(Je(i.sourceTXID));null!=e&&(i.sourceTransaction=e.tx)}if(null!=i.sourceTransaction){const e=t.findBump(i.sourceTransaction.id("hex"));null!=e?i.sourceTransaction.merklePath=e:r(t,i.sourceTransaction)}}};return r(this,e.tx),e.tx}mergeBump(t){let e;for(let r=0;r<this.bumps.length;r++){const i=this.bumps[r];if(i===t)return r;if(i.blockHeight===t.blockHeight&&i.computeRoot()===t.computeRoot()){i.combine(t),e=r;break}}void 0===e&&(e=this.bumps.length,this.bumps.push(t));const r=this.bumps[e];for(const t of this.txs){const i=t.txid;if(null==t.bumpIndex)for(const n of r.path[0])if(n.hash===i){t.bumpIndex=e,n.txid=!0;break}}return e}mergeRawTx(t,e){const r=new Ye(t,e);return this.removeExistingTxid(r.txid),this.txs.push(r),this.tryToValidateBumpIndex(r),r}mergeTransaction(t){const e=t.id("hex");let r;this.removeExistingTxid(e),null!=t.merklePath&&(r=this.mergeBump(t.merklePath));const i=new Ye(t,r);if(this.txs.push(i),this.tryToValidateBumpIndex(i),r=i.bumpIndex,void 0===r)for(const e of t.inputs)null!=e.sourceTransaction&&this.mergeTransaction(e.sourceTransaction);return i}removeExistingTxid(t){const e=this.txs.findIndex((e=>e.txid===t));e>=0&&this.txs.splice(e,1)}mergeTxidOnly(t){let e=this.txs.find((e=>e.txid===t));return null==e&&(e=new Ye(t),this.txs.push(e),this.tryToValidateBumpIndex(e)),e}mergeBeefTx(t){let e=this.findTxid(t.txid);if(t.isTxidOnly&&null==e?e=this.mergeTxidOnly(t.txid):null==t._tx||null!=e&&!e.isTxidOnly?null==t._rawTx||null!=e&&!e.isTxidOnly||(e=this.mergeRawTx(t._rawTx)):e=this.mergeTransaction(t._tx),null==e)throw new Error(`Failed to merge BeefTx for txid: ${t.txid}`);return e}mergeBeef(t){const e=Array.isArray(t)?rr.fromBinary(t):t;for(const t of e.bumps)this.mergeBump(t);for(const t of e.txs)this.mergeBeefTx(t)}isValid(t){return this.verifyValid(t).valid}async verify(t,e){const r=this.verifyValid(e);if(!r.valid)return!1;for(const e of Object.keys(r.roots))if(!await t.isValidRootForHeight(r.roots[e],Number(e)))return!1;return!0}verifyValid(t){const e={valid:!1,roots:{}},r=this.sortTxs();if(r.missingInputs.length>0||r.notValid.length>0||r.txidOnly.length>0&&!0!==t||r.withMissingInputs.length>0)return e;const i={};for(const r of this.txs)if(r.isTxidOnly){if(!0!==t)return e;i[r.txid]=!0}const n=(t,r)=>{const i=t.computeRoot(r);return void 0!==e.roots[t.blockHeight]&&""!==e.roots[t.blockHeight]||(e.roots[t.blockHeight]=i),e.roots[t.blockHeight]===i};for(const t of this.bumps)for(const r of t.path[0])if(!0===r.txid&&"string"==typeof r.hash&&r.hash.length>0&&(i[r.hash]=!0,!n(t,r.hash)))return e;for(const t of this.txs)if(void 0!==t.bumpIndex&&null==this.bumps[t.bumpIndex].path[0].find((e=>e.hash===t.txid)))return e;for(const t of this.txs){for(const r of t.inputTxids)if(!i[r])return e;i[t.txid]=!0}return e.valid=!0,e}toWriter(t){t.writeUInt32LE(this.version),t.writeVarIntNum(this.bumps.length);for(const e of this.bumps)t.write(e.toBinary());t.writeVarIntNum(this.txs.length);for(const e of this.txs)e.toWriter(t,this.version)}toBinary(){this.sortTxs();const t=new Bt;return this.toWriter(t),t.toArray()}toBinaryAtomic(t){this.sortTxs();const e=this.findTxid(t);if(null==e)throw new Error(`${t} does not exist in this Beef`);const r=this.txs[this.txs.length-1]===e?this:this.clone();if(r!==this){const e=this.txs.findIndex((e=>e.txid===t));r.txs.splice(e+1)}const i=new Bt;return i.writeUInt32LE(tr),i.writeReverse(Ot(t,"hex")),r.toWriter(i),i.toArray()}toHex(){return Nt(this.toBinary())}static fromReader(t){let e,r=t.readUInt32LE();if(r===tr&&(e=Nt(t.readReverse(32)),r=t.readUInt32LE()),r!==Ze&&r!==Qe)throw new Error(`Serialized BEEF must start with ${Ze} or ${Qe} but starts with ${r}`);const i=new rr(r),n=t.readVarIntNum();for(let e=0;e<n;e++){const e=Ge.fromReader(t,!1);i.bumps.push(e)}const s=t.readVarIntNum();for(let e=0;e<s;e++){const e=Ye.fromReader(t,r);i.txs.push(e)}return i.atomicTxid=e,i}static fromBinary(t){const e=new Ut(t);return rr.fromReader(e)}static fromString(t,e="hex"){const r=Ot(t,e),i=new Ut(r);return rr.fromReader(i)}tryToValidateBumpIndex(t){if(void 0!==t.bumpIndex)return!0;const e=t.txid;for(let r=0;r<this.bumps.length;r++){const i=this.bumps[r].path[0].findIndex((t=>t.hash===e));if(i>=0)return t.bumpIndex=r,this.bumps[r].path[0][i].txid=!0,!0}return!1}sortTxs(){const t={},e={};let r=[];const i=[],n=[];for(const 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,n.push(s)):r.push(s);const s={},a=[],o=r;r=[];for(const t of o){let i=!1;for(const r of t.inputTxids)void 0===e[r]&&(s[r]=!0,i=!0);i?a.push(t):r.push(t)}for(;r.length>0;){const e=r;r=[];for(const n of e)n.inputTxids.every((e=>t[e]))?(t[n.txid]=!0,i.push(n)):r.push(n);if(e.length===r.length)break}const c=r;return this.txs=a.concat(c).concat(n).concat(i),{missingInputs:Object.keys(s),notValid:c.map((t=>t.txid)),valid:Object.keys(t),withMissingInputs:a.map((t=>t.txid)),txidOnly:n.map((t=>t.txid))}}clone(){const t=new rr;return t.version=this.version,t.bumps=Array.from(this.bumps),t.txs=Array.from(this.txs),t}trimKnownTxids(t){for(let e=0;e<this.txs.length;){const r=this.txs[e];r.isTxidOnly&&t.includes(r.txid)?this.txs.splice(e,1):e++}}getValidTxids(){return this.sortTxs().valid}toLogString(){let t="";t+=`BEEF with ${this.bumps.length} BUMPS and ${this.txs.length} Transactions, isValid ${this.isValid().toString()}\n`;let e=-1;for(const r of this.bumps)e++,t+=` BUMP ${e}\n block: ${r.blockHeight}\n txids: [\n${r.path[0].filter((t=>!0===t.txid)).map((t=>` '${t.hash??""}'`)).join(",\n")}\n ]\n`;e=-1;for(const r of this.txs)e++,t+=` TX ${e}\n txid: ${r.txid}\n`,void 0!==r.bumpIndex&&(t+=` bumpIndex: ${r.bumpIndex}\n`),r.isTxidOnly?t+=" txidOnly\n":t+=` rawTx length=${r.rawTx?.length??0}\n`,r.inputTxids.length>0&&(t+=` inputs: [\n${r.inputTxids.map((t=>` '${t}'`)).join(",\n")}\n ]\n`);return t}addComputedLeaves(){for(const e of this.bumps)for(let r=1;r<e.path.length;r++)for(const i of e.path[r-1])if("string"==typeof i.hash&&!(1&i.offset)){const n=e.path[r-1].find((t=>t.offset===i.offset+1)),s=i.offset>>1;void 0!==n&&"string"==typeof n.hash&&e.path[r].every((t=>t.offset!==s))&&e.path[r].push({offset:s,hash:(t=n.hash+i.hash,Nt(vt(Ot(t,"hex").reverse()).reverse()))})}var t}}class ir{version;inputs;outputs;lockTime;metadata;merklePath;cachedHash;static addPathOrInputs(t,e,r){if("number"==typeof t.pathIndex){const e=r[t.pathIndex];if("object"!=typeof e)throw new Error("Invalid merkle path index found in BEEF!");t.tx.merklePath=e}else for(const i of t.tx.inputs){if(void 0===i.sourceTXID)throw new Error("Input sourceTXID is undefined");const t=e[i.sourceTXID];if("object"!=typeof t)throw new Error(`Reference to unknown TXID in BEEF: ${i.sourceTXID??"undefined"}`);i.sourceTransaction=t.tx,this.addPathOrInputs(t,e,r)}}static fromBEEF(t,e){const{tx:r}=ir.fromAnyBeef(t,e);return r}static fromAtomicBEEF(t){const{tx:e,txid:r,beef:i}=ir.fromAnyBeef(t);if(r!==i.atomicTxid)throw i.atomicTxid?new Error(`Transaction with TXID ${i.atomicTxid} not found in BEEF data.`):new Error("beef must conform to BRC-95 and must contain the subject txid.");return e}static fromAnyBeef(t,e){const r=rr.fromBinary(t);if(r.txs.length<1)throw new Error("beef must include at least one transaction.");const i=e||r.atomicTxid||r.txs.slice(-1)[0].txid,n=r.findAtomicTransaction(i);if(null==n)throw e?new Error(`Transaction with TXID ${i} not found in BEEF data.`):new Error("beef does not contain transaction for atomic txid.");return{tx:n,beef:r,txid:i}}static fromEF(t){const e=new Ut(t),r=e.readUInt32LE();if("0000000000ef"!==Nt(e.read(6)))throw new Error("Invalid EF marker");const i=e.readVarIntNum(),n=[];for(let t=0;t<i;t++){const t=Nt(e.readReverse(32)),r=e.readUInt32LE(),i=e.readVarIntNum(),s=e.read(i),a=Te.fromBinary(s),o=e.readUInt32LE(),c=e.readUInt64LEBn().toNumber(),h=e.readVarIntNum(),u=e.read(h),l=Ae.fromBinary(u),d=new ir(void 0,[],[],void 0);d.outputs=Array(r+1).fill(null),d.outputs[r]={satoshis:c,lockingScript:l},n.push({sourceTransaction:d,sourceTXID:t,sourceOutputIndex:r,unlockingScript:a,sequence:o})}const s=e.readVarIntNum(),a=[];for(let t=0;t<s;t++){const t=e.readUInt64LEBn().toNumber(),r=e.readVarIntNum(),i=e.read(r),n=Ae.fromBinary(i);a.push({satoshis:t,lockingScript:n})}const o=e.readUInt32LE();return new ir(r,n,a,o)}static parseScriptOffsets(t){const e=new Ut(t),r=[],i=[];e.pos+=4;const n=e.readVarIntNum();for(let t=0;t<n;t++){e.pos+=36;const i=e.readVarIntNum();r.push({vin:t,offset:e.pos,length:i}),e.pos+=i+4}const s=e.readVarIntNum();for(let t=0;t<s;t++){e.pos+=8;const r=e.readVarIntNum();i.push({vout:t,offset:e.pos,length:r}),e.pos+=r}return{inputs:r,outputs:i}}static fromReader(t){const e=t.readUInt32LE(),r=t.readVarIntNum(),i=[];for(let e=0;e<r;e++){const e=Nt(t.readReverse(32)),r=t.readUInt32LE(),n=t.readVarIntNum(),s=t.read(n),a=Te.fromBinary(s),o=t.readUInt32LE();i.push({sourceTXID:e,sourceOutputIndex:r,unlockingScript:a,sequence:o})}const n=t.readVarIntNum(),s=[];for(let e=0;e<n;e++){const e=t.readUInt64LEBn().toNumber(),r=t.readVarIntNum(),i=t.read(r),n=Ae.fromBinary(i);s.push({satoshis:e,lockingScript:n})}const a=t.readUInt32LE();return new ir(e,i,s,a)}static fromBinary(t){const e=new Ut(t);return ir.fromReader(e)}static fromHex(t){return ir.fromBinary(Ot(t,"hex"))}static fromHexEF(t){return ir.fromEF(Ot(t,"hex"))}static fromHexBEEF(t,e){return ir.fromBEEF(Ot(t,"hex"),e)}constructor(t=1,e=[],r=[],i=0,n={},s){this.version=t,this.inputs=e,this.outputs=r,this.lockTime=i,this.metadata=n,this.merklePath=s}addInput(t){if(void 0===t.sourceTXID&&void 0===t.sourceTransaction)throw new Error("A reference to an an input transaction is required. If the input transaction itself cannot be referenced, its TXID must still be provided.");void 0===t.sequence&&(t.sequence=4294967295),this.cachedHash=void 0,this.inputs.push(t)}addOutput(t){if(this.cachedHash=void 0,!0!==t.change){if(void 0===t.satoshis)throw new Error("either satoshis must be defined or change must be set to true");if(t.satoshis<0)throw new Error("satoshis must be a positive integer or zero")}if(null==t.lockingScript)throw new Error("lockingScript must be defined");this.outputs.push(t)}addP2PKHOutput(t,e){const r=(new Ve).lock(t);if(void 0===e)return this.addOutput({lockingScript:r,change:!0});this.addOutput({lockingScript:r,satoshis:e})}updateMetadata(t){this.metadata={...this.metadata,...t}}async fee(t=new He(1),e="equal"){if(this.cachedHash=void 0,"number"==typeof t){const e=t;t={computeFee:async()=>e}}const r=await t.computeFee(this),i=this.calculateChange(r);i<=0?this.outputs=this.outputs.filter((t=>!0!==t.change)):this.distributeChange(i,e)}calculateChange(t){let e=0;for(const t of this.inputs){if("object"!=typeof t.sourceTransaction)throw new Error("Source transactions are required for all inputs during fee computation");e+=t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0}e-=t;for(const t of this.outputs)!0!==t.change&&void 0!==t.satoshis&&(e-=t.satoshis);return e}distributeChange(t,e){let r=0;const i=this.outputs.filter((t=>t.change));if("random"===e?r=this.distributeRandomChange(t,i):"equal"===e&&(r=this.distributeEqualChange(t,i)),r<t){const e=this.outputs[this.outputs.length-1];void 0!==e.satoshis?e.satoshis+=t-r:e.satoshis=t-r}}distributeRandomChange(t,e){let r=0,i=t;const n=Array(e.length).fill(1);i-=e.length,r+=e.length;for(let t=0;t<e.length-1;t++){const e=this.benfordNumber(0,i);n[t]=n[t]+e,r+=e,i-=e}for(const t of this.outputs)!0===t.change&&(t.satoshis=n.shift());return r}distributeEqualChange(t,e){let r=0;const i=Math.floor(t/e.length);for(const t of e)r+=i,t.satoshis=i;return r}benfordNumber(t,e){const r=Math.floor(9*Math.random())+1;return Math.floor(t+(e-t)*Math.log10(1+1/r)/Math.log10(10))}getFee(){let t=0;for(const e of this.inputs){if("object"!=typeof e.sourceTransaction)throw new Error("Source transactions or sourceSatoshis are required for all inputs to calculate fee");t+=e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0}let e=0;for(const t of this.outputs)e+=t.satoshis??0;return t-e}async sign(){this.cachedHash=void 0;for(const t of this.outputs)if(void 0===t.satoshis)throw!0===t.change?new Error("There are still change outputs with uncomputed amounts. Use the fee() method to compute the change amounts and transaction fees prior to signing."):new Error("One or more transaction outputs is missing an amount. Ensure all output amounts are provided before signing.");const t=await Promise.all(this.inputs.map((async(t,e)=>"object"==typeof this.inputs[e].unlockingScriptTemplate?await(this.inputs[e]?.unlockingScriptTemplate?.sign(this,e)):await Promise.resolve(void 0))));for(let e=0,r=this.inputs.length;e<r;e++)"object"==typeof this.inputs[e].unlockingScriptTemplate&&(this.inputs[e].unlockingScript=t[e])}async broadcast(t=je()){return await t.broadcast(this)}toBinary(){const t=new Bt;t.writeUInt32LE(this.version),t.writeVarIntNum(this.inputs.length);for(const e of this.inputs){if(void 0===e.sourceTXID){if(null==e.sourceTransaction)throw new Error("sourceTransaction is undefined");t.write(e.sourceTransaction.hash())}else t.writeReverse(Ot(e.sourceTXID,"hex"));if(t.writeUInt32LE(e.sourceOutputIndex),null==e.unlockingScript)throw new Error("unlockingScript is undefined");const r=e.unlockingScript.toBinary();t.writeVarIntNum(r.length),t.write(r),t.writeUInt32LE(e.sequence??0)}t.writeVarIntNum(this.outputs.length);for(const e of this.outputs){t.writeUInt64LE(e.satoshis??0);const r=e.lockingScript.toBinary();t.writeVarIntNum(r.length),t.write(r)}return t.writeUInt32LE(this.lockTime),t.toArray()}toEF(){const t=new Bt;t.writeUInt32LE(this.version),t.write([0,0,0,0,0,239]),t.writeVarIntNum(this.inputs.length);for(const e of this.inputs){if(void 0===e.sourceTransaction)throw new Error("All inputs must have source transactions when serializing to EF format");if(void 0===e.sourceTXID?t.write(e.sourceTransaction.hash()):t.write(Ot(e.sourceTXID,"hex").reverse()),t.writeUInt32LE(e.sourceOutputIndex),null==e.unlockingScript)throw new Error("unlockingScript is undefined");const r=e.unlockingScript.toBinary();t.writeVarIntNum(r.length),t.write(r),t.writeUInt32LE(e.sequence??0),t.writeUInt64LE(e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0);const i=e.sourceTransaction.outputs[e.sourceOutputIndex].lockingScript.toBinary();t.writeVarIntNum(i.length),t.write(i)}t.writeVarIntNum(this.outputs.length);for(const e of this.outputs){t.writeUInt64LE(e.satoshis??0);const r=e.lockingScript.toBinary();t.writeVarIntNum(r.length),t.write(r)}return t.writeUInt32LE(this.lockTime),t.toArray()}toHexEF(){return Nt(this.toEF())}toHex(){return Nt(this.toBinary())}toHexBEEF(){return Nt(this.toBEEF())}toHexAtomicBEEF(){return Nt(this.toAtomicBEEF())}hash(t){let e;return null!=this.cachedHash?e=this.cachedHash:(e=vt(this.toBinary()),this.cachedHash=e),"hex"===t?Nt(e):e}id(t){const e=[...this.hash()];return e.reverse(),"hex"===t?Nt(e):e}async verify(t=Xe(),e,r){const i=new Set,n=[this];for(;n.length>0;){const s=n.shift(),a=s?.id("hex")??"";if(null!=a&&""!==a&&i.has(a))continue;if("object"==typeof s?.merklePath){if("scripts only"===t){null!=a&&i.add(a);continue}if(await s.merklePath.verify(a,t)){i.add(a);continue}}if(void 0!==e){if(void 0===s)throw new Error("Transaction is undefined");const t=ir.fromEF(s.toEF());if(delete t.outputs[0].satoshis,t.outputs[0].change=!0,await t.fee(e),s.getFee()<t.getFee())throw new Error(`Verification failed because the transaction ${a} has an insufficient fee and has not been mined.`)}let o=0;if(void 0===s)throw new Error("Transaction is undefined");for(let t=0;t<s.inputs.length;t++){const e=s.inputs[t];if("object"!=typeof e.sourceTransaction)throw new Error(`Verification failed because the input at index ${t} 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 e.unlockingScript)throw new Error(`Verification failed because the input at index ${t} 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.`);const c=e.sourceTransaction.outputs[e.sourceOutputIndex];o+=c.satoshis??0;const h=e.sourceTransaction.id("hex");i.has(h)||n.push(e.sourceTransaction);const u=s.inputs.filter(((e,r)=>r!==t));if(void 0===e.sourceTXID&&(e.sourceTXID=h),!new Re({sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,lockingScript:c.lockingScript,sourceSatoshis:c.satoshis??0,transactionVersion:s.version,otherInputs:u,unlockingScript:e.unlockingScript,inputSequence:e.sequence??0,inputIndex:t,outputs:s.outputs,lockTime:s.lockTime,memoryLimit:r}).validate())return!1}let c=0;for(const t of s.outputs){if("number"!=typeof t.satoshis)throw new Error("Every output must have a defined amount during transaction verification.");c+=t.satoshis}if(c>o)return!1;i.add(a)}return!0}toBEEF(t){const e=new Bt;e.writeUInt32LE(Ze);const r=[],i=[],n=e=>{const s={tx:e},a="object"==typeof e.merklePath;if(a){let t=!1;for(let i=0;i<r.length;i++){if(r[i]===e.merklePath){s.pathIndex=i,t=!0;break}if(null!==e.merklePath&&void 0!==e.merklePath&&r[i].blockHeight===e.merklePath.blockHeight&&r[i].computeRoot()===e.merklePath.computeRoot()){r[i].combine(e.merklePath),s.pathIndex=i,t=!0;break}}t||(s.pathIndex=r.length,null!==e.merklePath&&void 0!==e.merklePath&&r.push(e.merklePath))}if(i.some((t=>t.tx.id("hex")===e.id("hex")))||i.unshift(s),!a)for(let r=0;r<e.inputs.length;r++){const i=e.inputs[r];if("object"==typeof i.sourceTransaction)n(i.sourceTransaction);else if(!1===t)throw new Error("A required source transaction is missing!")}};n(this),e.writeVarIntNum(r.length);for(const t of r)e.write(t.toBinary());e.writeVarIntNum(i.length);for(const t of i)e.write(t.tx.toBinary()),"number"==typeof t.pathIndex?(e.writeUInt8(1),e.writeVarIntNum(t.pathIndex)):e.writeUInt8(0);return e.toArray()}toAtomicBEEF(t){const e=new Bt;e.writeUInt32LE(16843009),e.write(this.hash());const r=this.toBEEF(t);return e.write(r),e.toArray()}}function nr(t){return"success"===t.status}function sr(t){return"error"===t.status}const ar=class extends rr{knownTo={};constructor(t){if(super(),null!=t)for(const e of t)this.addParty(e)}isParty(t){return Object.keys(this.knownTo).includes(t)}addParty(t){if(this.isParty(t))throw new Error(`Party ${t} already exists.`);this.knownTo[t]={}}getKnownTxidsForParty(t){const e=this.knownTo[t];if(void 0===e)throw new Error(`Party ${t} is unknown.`);return Object.keys(e)}getTrimmedBeefForParty(t){const e=this.getKnownTxidsForParty(t),r=this.clone();return r.trimKnownTxids(e),r}addKnownTxidsForParty(t,e){this.isParty(t)||this.addParty(t);const r=this.knownTo[t];for(const t of e)r[t]=!0,this.mergeTxidOnly(t)}mergeBeefFromParty(t,e){const r=Array.isArray(e)?rr.fromBinary(e):e,i=r.getValidTxids();this.mergeBeef(r),this.addKnownTxidsForParty(t,i)}};class or{network;URL;httpClient;constructor(t="main",e=Le()){this.network=t,this.URL=`https://api.whatsonchain.com/v1/bsv/${t}/tx/raw`,this.httpClient=e}async broadcast(t){const e={method:"POST",headers:{"Content-Type":"application/json",Accept:"text/plain"},data:{txhex:t.toHex()}};try{const t=await this.httpClient.request(this.URL,e);return t.ok?{status:"success",txid:t.data,message:"broadcast successful"}:{status:"error",code:t.status.toString()??"ERR_UNKNOWN",description:t.data??"Unknown error"}}catch(t){return{status:"error",code:"500",description:"string"==typeof t.message?t.message:"Internal Server Error"}}}}class cr{https;constructor(t){this.https=t}async request(t,e){return await new Promise(((r,i)=>{const n=this.https.request(t,e,(t=>{let e="";t.on("data",(t=>{e+=t})),t.on("end",(()=>{const i=t.statusCode>=200&&t.statusCode<=299,n=t.headers["content-type"],s=""!==e&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(e):e;r({status:t.statusCode,statusText:t.statusMessage,ok:i,data:s})}))}));n.on("error",(t=>{i(t)})),null!==e.data&&void 0!==e.data&&n.write(Buffer.from(e.data)),n.end()}))}}class hr{fetch;constructor(t){this.fetch=t}async request(t,e){const r={method:e.method,headers:e.headers,body:e.data},i=await this.fetch(t,r),n=await i.text();return{ok:i.ok,status:i.status,statusText:i.statusText,data:n}}}function ur(){const t={async request(...t){throw new Error("No method available to perform HTTP request")}};if("undefined"!=typeof window&&"function"==typeof window.fetch)return new hr(window.fetch.bind(window));if("undefined"==typeof require)return t;try{const t=require("https");return new cr(t)}catch(e){return t}}class lr{URL;httpClient;constructor(t,e=ur()){this.URL=t,this.httpClient=e}async broadcast(t){const e=t.toEF(),r={method:"POST",headers:{"Content-Type":"application/octet-stream"},data:new Blob([new Uint8Array(e)])};try{const e=await this.httpClient.request(this.URL,r);return e.ok?{status:"success",txid:t.id("hex"),message:"broadcast successful"}:{status:"error",code:e.status.toString()??"ERR_UNKNOWN",description:e.data??"Unknown error"}}catch(t){return{status:"error",code:"500",description:"string"==typeof t.message?t.message:"Internal Server Error"}}}}const dr="42423301",fr=(t,e,r)=>{const i="object"!=typeof r;if(i){const t=new Lt,e=new re(1),i=t.g.mul(e);r=new Gt(i.x,i.y)}const n=Zt(32),s=`2-message signing-${_t(n)}`,a=e.deriveChild(r,s).sign(t).toDER(),o=e.toPublicKey().encode(!0);return[...Ot(dr,"hex"),...o,...i?[0]:r.encode(!0),...n,...a]},pr=(t,e,r)=>{const i=new Ut(e),n=Nt(i.read(4));if(n!==dr)throw new Error(`Message version mismatch: Expected ${dr}, received ${n}`);const s=Gt.fromString(Nt(i.read(33))),[a]=i.read(1);if(0===a)r=new re(1);else{const t=i.read(32),e=Nt([a,...t]);if("object"!=typeof r)throw new Error(`This signature can only be verified with knowledge of a specific private key. The associated public key is: ${e}`);const n=r.toPublicKey().encode(!0,"hex");if(e!==n)throw new Error(`The recipient public key is ${n} but the signature requres the recipient to have public key ${e}`)}const o=_t(i.read(32)),c=Nt(i.read(i.bin.length-i.pos)),h=$t.fromDER(c,"hex"),u=`2-message signing-${o}`;return s.deriveChild(r,u).verify(t,h)},mr="42421033",wr=(t,e,r)=>{const i=Zt(32),n=`2-message encryption-${_t(i)}`,s=e.deriveChild(r,n),a=r.deriveChild(e,n),o=s.deriveSharedSecret(a),c=new Pe(o.encode(!0).slice(1)).encrypt(t),h=e.toPublicKey().encode(!0);return[...Ot(mr,"hex"),...h,...r.encode(!0),...i,...c]},br=(t,e)=>{const r=new Ut(t),i=Nt(r.read(4));if(i!==mr)throw new Error(`Message version mismatch: Expected ${mr}, received ${i}`);const n=Gt.fromString(Nt(r.read(33))),s=Nt(r.read(33)),a=e.toPublicKey().encode(!0,"hex");if(s!==a)throw new Error(`The encrypted message expects a recipient public key of ${s}, but the provided key is ${a}`);const o=_t(r.read(32)),c=r.read(r.bin.length-r.pos),h=`2-message encryption-${o}`,u=n.deriveChild(e,h),l=e.deriveChild(n,h),d=u.deriveSharedSecret(l);return new Pe(d.encode(!0).slice(1)).decrypt(c)},gr=t=>{const e=new Bt;e.writeVarIntNum(24),e.write(Ot("Bitcoin Signed Message:\n","utf8")),e.writeVarIntNum(t.length),e.write(t);const r=e.toArray();return vt(r)},yr=(t,e,r="base64")=>{const i=gr(t),n=Wt(new h(i),e,!0);if("raw"===r)return n;const s=new h(i),a=n.CalculateRecoveryFactor(e.toPublicKey(),s);return n.toCompact(a,!0,"base64")},vr=(t,e,r)=>{const i=gr(t);return Xt(new h(i),e,r)};class Ir{versionBytesNum;depth;parentFingerPrint;childIndex;chainCode;privKey;pubKey;constants={pubKey:76067358,privKey:76066276};constructor(t,e,r,i,n,s,a){this.versionBytesNum=t,this.depth=e,this.parentFingerPrint=r,this.childIndex=i,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=Zt(32),this.privKey=re.fromRandom(),this.pubKey=this.privKey.toPublicKey(),this}static fromRandom(){return(new this).fromRandom()}static fromString(t){return(new this).fromString(t)}fromString(t){const e=Dt(t);return this.fromBinary([...e.prefix,...e.data])}static fromSeed(t){return(new this).fromSeed(t)}fromSeed(t){if(t.length<16)throw new Error("Need more than 128 bits of entropy");if(t.length>64)throw new Error("More than 512 bits of entropy is nonstandard");const e=Pt(Ot("Bitcoin seed","utf8"),t);return this.depth=0,this.parentFingerPrint=[0,0,0,0],this.childIndex=0,this.chainCode=e.slice(32,64),this.versionBytesNum=this.constants.privKey,this.privKey=new re(e.slice(0,32)),this.pubKey=this.privKey.toPublicKey(),this}static fromBinary(t){return(new this).fromBinary(t)}fromBinary(t){if(78!==t.length)throw new Error("incorrect bip32 data length");const e=new Ut(t);this.versionBytesNum=e.readUInt32BE(),this.depth=e.readUInt8(),this.parentFingerPrint=e.read(4),this.childIndex=e.readUInt32BE(),this.chainCode=e.read(32);const r=e.read(33),i=this.versionBytesNum===this.constants.privKey,n=this.versionBytesNum===this.constants.pubKey;if(i&&0===r[0])this.privKey=new re(r.slice(1,33)),this.pubKey=this.privKey.toPublicKey();else{if(!n||2!==r[0]&&3!==r[0])throw new Error("Invalid key");this.pubKey=Gt.fromString(Nt(r))}return this}toString(){const t=this.toBinary();return Vt(t,[])}derive(t){if("m"===t)return this;const e=t.split("/");let r=this;for(const[t,i]of e.entries()){if(0===t){if("m"!==i)throw new Error("invalid path");continue}if(parseInt(i.replace("'",""),10).toString()!==i.replace("'",""))throw new Error("invalid path");const e=i.length>1&&"'"===i[i.length-1];let n=2147483647&parseInt(e?i.slice(0,i.length-1):i,10);e&&(n+=2147483648),r=r.deriveChild(n)}return r}deriveChild(t){if("number"!=typeof t)throw new Error("i must be a number");const e=[];e.push(t>>24&255),e.push(t>>16&255),e.push(t>>8&255),e.push(255&t);const r=[...e],i=!!(2147483648&t),n=this.versionBytesNum===this.constants.privKey;if(i&&(null===this.privKey||void 0===this.privKey||!n))throw new Error("Cannot do private key derivation without private key");let s=null;if(null!==this.privKey&&void 0!==this.privKey){let t=null;t=i?[0,...this.privKey.toArray("be",32),...r]:[...this.pubKey.encode(!0),...r];const e=Pt(this.chainCode,t),n=new h(e.slice(0,32)),a=e.slice(32,64),o=n.add(this.privKey).mod((new Lt).n);s=new Ir,s.chainCode=a,s.privKey=new re(o.toArray()),s.pubKey=s.privKey.toPublicKey()}else{const t=[...this.pubKey.encode(!0),...r],e=Pt(this.chainCode,t),i=new h(e.slice(0,32)),n=e.slice(32,64),a=(new Lt).g.mul(i),o=this.pubKey,c=a.add(o),u=new Gt(c.x,c.y);s=new Ir,s.chainCode=n,s.pubKey=u}s.childIndex=t;const a=It(this.pubKey.encode(!0));return s.parentFingerPrint=a.slice(0,4),s.versionBytesNum=this.versionBytesNum,s.depth=this.depth+1,s}toPublic(){const t=new Ir(this.versionBytesNum,this.depth,this.parentFingerPrint,this.childIndex,this.chainCode,this.privKey,this.pubKey);return t.versionBytesNum=this.constants.pubKey,t.privKey=void 0,t}toBinary(){const t=this.versionBytesNum===this.constants.privKey,e=this.versionBytesNum===this.constants.pubKey;if(t)return(new Bt).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(e)return(new Bt).writeUInt32BE(this.versionBytesNum).writeUInt8(this.depth).write(this.parentFingerPrint).writeUInt32BE(this.childIndex).write(this.chainCode).write(this.pubKey.encode(!0)).toArray();throw new Error("bip32: invalid versionBytesNum byte")}isPrivate(){return this.versionBytesNum===this.constants.privKey}}const kr={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 Pr{mnemonic;seed;Wordlist;constructor(t,e,r=kr){this.mnemonic=t??"",this.seed=e??[],this.Wordlist=r}toBinary(){const t=new Bt;if(""!==this.mnemonic){const e=Ot(this.mnemonic,"utf8");t.writeVarIntNum(e.length),t.write(e)}else t.writeVarIntNum(0);return this.seed.length>0?(t.writeVarIntNum(this.seed.length),t.write(this.seed)):t.writeVarIntNum(0),t.toArray()}fromBinary(t){const e=new Ut(t),r=e.readVarIntNum();r>0&&(this.mnemonic=Mt(e.read(r),"utf8"));const i=e.readVarIntNum();return i>0&&(this.seed=e.read(i)),this}fromRandom(t){if((null==t||isNaN(t)||0===t)&&(t=128),t%32!=0)throw new Error("bits must be multiple of 32");if(t<128)throw new Error("bits must be at least 128");const e=Zt(t/8);return this.entropy2Mnemonic(e),this.mnemonic2Seed(),this}static fromRandom(t){return(new this).fromRandom(t)}fromEntropy(t){return this.entropy2Mnemonic(t),this}static fromEntropy(t){return(new this).fromEntropy(t)}fromString(t){return this.mnemonic=t,this}static fromString(t){return(new this).fromString(t)}toString(){return this.mnemonic}toSeed(t){return this.mnemonic2Seed(t),this.seed}entropy2Mnemonic(t){if(t.length<16)throw new Error("Entropy is less than 128 bits. It must be 128 bits or more.");const e=gt(t);let r="";const i=8*t.length;for(let e=0;e<t.length;e++)r+=("00000000"+t[e].toString(2)).slice(-8);let n=e[0].toString(2);if(n=("00000000"+n).slice(-8).slice(0,i/32),r+=n,r.length%11!=0)throw new Error("internal error - entropy not an even multiple of 11 bits - "+r.length.toString());let s="";for(let t=0;t<r.length/11;t++){""!==s&&(s+=this.Wordlist.space);const e=parseInt(r.slice(11*t,11*(t+1)),2);s+=this.Wordlist.value[e]}return this.mnemonic=s,this}check(){const t=this.mnemonic.split(this.Wordlist.space);let e="";for(let r=0;r<t.length;r++){const i=this.Wordlist.value.indexOf(t[r]);if(i<0)return!1;e+=("00000000000"+i.toString(2)).slice(-11)}if(e.length%11!=0)throw new Error("internal error - entropy not an even multiple of 11 bits - "+e.length.toString());const r=e.length/33,i=e.slice(-r),n=e.slice(0,e.length-r),s=[];for(let t=0;t<n.length/8;t++)s.push(parseInt(e.slice(8*t,8*(t+1)),2));let a=gt(s.slice(0,n.length/8))[0].toString(2);return a=("00000000"+a).slice(-8).slice(0,r),a===i}mnemonic2Seed(t=""){let e=this.mnemonic;if(!this.check())throw new Error("Mnemonic does not pass the check - was the mnemonic typed incorrectly? Are there extra spaces?");if("string"!=typeof t)throw new Error("passphrase must be a string or undefined");e=e.normalize("NFKD"),t=t.normalize("NFKD");const r=Ot(e,"utf8"),i=[...Ot("mnemonic","utf8"),...Ot(t,"utf8")];return this.seed=Et(r,i,2048,64,"sha512"),this}isValid(t=""){let e;try{this.mnemonic2Seed(t),e=!0}catch{e=!1}return e}static isValid(t,e=""){return new Pr(t).isValid(e)}}function Er(t){let e,r,i;0===this._tables[0][0][0]&&this._precompute();const n=this._tables[0][4],s=this._tables[1],a=t.length;let o,c=1;if(4!==a&&6!==a&&8!==a)throw new Error("invalid aes key size");for(this._key=[r=t.slice(0),i=[]],o=a;o<4*a+28;o++)e=r[o-1],(o%a==0||8===a&&o%a==4)&&(e=n[e>>>24]<<24^n[e>>16&255]<<16^n[e>>8&255]<<8^n[255&e],o%a==0&&(e=e<<8^e>>>24^c<<24,c=c<<1^283*(c>>7))),r[o]=r[o-a]^e;for(let t=0;o>0;t++,o--)e=r[3&t?o:o-4],i[t]=o<=4||t<4?e:s[0][n[e>>>24]]^s[1][n[e>>16&255]]^s[2][n[e>>8&255]]^s[3][n[255&e]]}Er.prototype={encrypt:function(t){return this._crypt(t,0)},decrypt:function(t){return this._crypt(t,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(){const t=this._tables[0],e=this._tables[1],r=t[4],i=e[4];let n,s,a;const o=new Uint8Array(256),c=new Uint8Array(256);let h,u,l,d,f,p;for(n=0;n<256;n++)c[(o[n]=n<<1^283*(n>>7))^n]=n;for(s=a=0;0===r[s];s^=0!==h?h:1,a=0!==c[a]?c[a]:1)for(d=a^a<<1^a<<2^a<<3^a<<4,d=d>>8^255&d^99,r[s]=d,i[d]=s,l=o[u=o[h=o[s]]],p=16843009*l^65537*u^257*h^16843008*s,f=257*o[d]^16843008*d,n=0;n<4;n++)t[n][s]=f=f<<24^f>>>8,e[n][d]=p=p<<24^p>>>8},_crypt:function(t,e){if(4!==t.length)throw new Error("invalid aes block size");const r=this._key[e];let i,n,s,a=t[0]^r[0],o=t[1===e?3:1]^r[1],c=t[2]^r[2],h=t[1===e?1:3]^r[3];const u=r.length/4-2;let l,d=4;const f=new Uint32Array(4),p=this._tables[e],m=p[0],w=p[1],b=p[2],g=p[3],y=p[4];for(l=0;l<u;l++)i=m[a>>>24]^w[o>>16&255]^b[c>>8&255]^g[255&h]^r[d],n=m[o>>>24]^w[c>>16&255]^b[h>>8&255]^g[255&a]^r[d+1],s=m[c>>>24]^w[h>>16&255]^b[a>>8&255]^g[255&o]^r[d+2],h=m[h>>>24]^w[a>>16&255]^b[o>>8&255]^g[255&c]^r[d+3],d+=4,a=i,o=n,c=s;for(l=0;l<4;l++)f[1===e?3&-l:l]=y[a>>>24]<<24^y[o>>16&255]<<16^y[c>>8&255]<<8^y[255&h]^r[d++],i=a,a=o,o=c,c=h,h=i;return f}};class Sr{static encrypt(t,e){const r=Sr.buf2Words(e),i=Sr.buf2Words(t),n=new Er(r).encrypt(i);return Sr.words2Buf(n)}static decrypt(t,e){const r=Sr.buf2Words(t),i=new Er(Sr.buf2Words(e)).decrypt(r);return Sr.words2Buf(i)}static buf2Words(t){if(t.length%4!=0)throw new Error("buf length must be a multiple of 4");const e=[];for(let r=0;r<t.length/4;r++){const i=16777216*t[4*r]+(t[4*r+1]<<16|t[4*r+2]<<8|t[4*r+3]);e.push(i)}return e}static words2Buf(t){const e=new Array(4*t.length);for(let r=0;r<t.length;r++){const i=t[r];e[4*r]=i>>>24&255,e[4*r+1]=i>>>16&255,e[4*r+2]=i>>>8&255,e[4*r+3]=255&i}return e}}class Nr{static buf2BlocksBuf(t,e){const r=e/8,i=[];for(let n=0;n<=t.length/r;n++){let s=t.slice(n*r,n*r+r);s.length<e&&(s=Nr.pkcs7Pad(s,e)),i.push(s)}return i}static blockBufs2Buf(t){let e=t[t.length-1];return e=Nr.pkcs7Unpad(e),t[t.length-1]=e,t.flat()}static encrypt(t,e,r,i){const n=8*e.length,s=Nr.buf2BlocksBuf(t,n);return Nr.encryptBlocks(s,e,r,i).flat()}static decrypt(t,e,r,i){const n=e.length,s=[];for(let e=0;e<t.length/n;e++)s.push(t.slice(e*n,e*n+n));const a=Nr.decryptBlocks(s,e,r,i);return Nr.blockBufs2Buf(a)}static encryptBlock(t,e,r,i){const n=Nr.xorBufs(t,e);return r.encrypt(n,i)}static decryptBlock(t,e,r,i){const n=r.decrypt(t,i);return Nr.xorBufs(n,e)}static encryptBlocks(t,e,r,i){const n=[];for(let s=0;s<t.length;s++){const a=t[s],o=Nr.encryptBlock(a,e,r,i);n.push(o),e=o}return n}static decryptBlocks(t,e,r,i){const n=[];for(let s=0;s<t.length;s++){const a=t[s],o=Nr.decryptBlock(a,e,r,i);n.push(o),e=a}return n}static pkcs7Pad(t,e){const r=e/8-t.length,i=new Array(r);return i.fill(r),[...t,...i]}static pkcs7Unpad(t){const e=t[t.length-1],r=t.slice(t.length-e,t.length),i=new Array(e);if(i.fill(e),Nt(r)!==Nt(i))throw new Error("invalid padding");return t.slice(0,t.length-e)}static xorBufs(t,e){if(t.length!==e.length)throw new Error("bufs must have the same length");const r=new Array(t.length);for(let i=0;i<t.length;i++)r[i]=t[i]^e[i];return r}}class Or{static encrypt(t,e,r,i=!0){r=r??Zt(16);const n=Nr.encrypt(t,r,Sr,e);return i?[...r,...n]:[...n]}static decrypt(t,e,r){if(null==r){r=t.slice(0,16);const i=t.slice(16);return Nr.decrypt(i,r,Sr,e)}{const i=t;return Nr.decrypt(i,r,Sr,e)}}}class xr{static ivkEkM(t,e){const r=t,i=e.mul(r),n=new Gt(i.x,i.y).encode(!0),s=yt(n);return{iv:s.slice(0,16),kE:s.slice(16,32),kM:s.slice(32,64)}}static electrumEncrypt(t,e,r,i=!1){let n=null;null==r&&(r=re.fromRandom()),i||(n=r.toPublicKey().encode(!0));const{iv:s,kE:a,kM:o}=xr.ivkEkM(r,e),c=Or.encrypt(t,a,s,!1),h=Ot("BIE1","utf8");let u;u=null!=n&&n.length>0?[...h,...n,...c]:[...h,...c];const l=kt(o,u);return[...u,...l]}static electrumDecrypt(t,e,r){const i=t.slice(0,4);if("BIE1"!==Mt(i,"utf8"))throw new Error("Invalid Magic");let n=4,s=null;if(t.length-n-32>=33){const e=t[n];2===e||3===e?(s=t.slice(n,n+33),n+=33):4===e&&(s=t.slice(n,n+65),n+=65)}if(null!==s)null==r&&(r=Gt.fromString(Nt(s)));else if(null==r)throw new Error("Sender public key is required");const{iv:a,kE:o,kM:c}=xr.ivkEkM(e,r),h=t.slice(n,t.length-32),u=t.slice(t.length-32,t.length),l=kt(c,t.slice(0,t.length-32));if(Nt(u)!==Nt(l))throw new Error("Invalid checksum");return Or.decrypt(h,o,a)}static bitcoreEncrypt(t,e,r,i){null==r&&(r=re.fromRandom()),null==i&&(i=Zt(16));const n=r,s=r.toPublicKey().encode(!0),a=e.mul(n).getX().toArray("be",32),o=yt(a),c=o.slice(0,32),h=o.slice(32,64),u=Or.encrypt(t,c,i),l=kt(h,[...u]);return[...s,...u,...l]}static bitcoreDecrypt(t,e){const r=e,i=Gt.fromString(Nt(t.slice(0,33))).mul(r);if(i.eq(new Kt(0,0)))throw new Error("P equals 0");const n=i.getX().toArray("be",32),s=yt(n),a=s.slice(0,32),o=s.slice(32,64),c=t.slice(33,t.length-32),h=t.slice(t.length-32,t.length),u=kt(o,c);if(Nt(h)!==Nt(u))throw new Error("Invalid checksum");return[...Or.decrypt(c,a)]}}function Ar(t,e){const r=new ir(0,[],[],0);return r.outputs=Array(t.vout+1).fill(null),r.outputs[t.vout]={satoshis:t.satoshis,lockingScript:Ae.fromHex(t.script)},{sourceTransaction:r,sourceTXID:t.txid,sourceOutputIndex:t.vout,unlockingScriptTemplate:e,sequence:4294967295}}class Tr{static generate(t,e){const r=this.withDefaultOptions(e);return Mr(t,this.getCounter(r.timestamp,r.period),r)}static validate(t,e,r){const i=this.withDefaultValidateOptions(r);if((e=e.trim()).length!==i.digits)return!1;const n=this.getCounter(i.timestamp,i.period),s=[n];for(let t=1;t<=i.skew;t++)s.push(n+t),s.push(n-t);for(const r of s)if(e===Mr(t,r,i))return!0;return!1}static getCounter(t,e){const r=Math.floor(t/1e3);return Math.floor(r/e)}static withDefaultOptions(t){return{digits:2,algorithm:"SHA-1",period:30,timestamp:Date.now(),...t}}static withDefaultValidateOptions(t){return{skew:1,...this.withDefaultOptions(t)}}}function Mr(t,e,r){const i=function(t,e,r){switch(r){case"SHA-1":return new pt(t).update(e);case"SHA-256":return new ft(t).update(e);case"SHA-512":return new mt(t).update(e);default:throw new Error("unsupported HMAC algorithm")}}(t,new h(e).toArray("be",8),r.algorithm),n=i.digest(),s=15&n[n.length-1],a=n.slice(s,s+4);return(2147483647&new h(a).toNumber()).toString().slice(-r.digits)}var _r;!function(t){t[t.Silent=0]="Silent",t[t.App=1]="App",t[t.Counterparty=2]="Counterparty"}(_r||(_r={}));class Fr{rootKey;identityKey;constructor(t){this.rootKey="anyone"===t?new re(1):t,this.identityKey=this.rootKey.toPublicKey().toString()}derivePublicKey(t,e,r,i=!1){return r=this.normalizeCounterparty(r),i?this.rootKey.deriveChild(r,this.computeInvoiceNumber(t,e)).toPublicKey():r.deriveChild(this.rootKey,this.computeInvoiceNumber(t,e))}derivePrivateKey(t,e,r){return r=this.normalizeCounterparty(r),this.rootKey.deriveChild(r,this.computeInvoiceNumber(t,e))}deriveSymmetricKey(t,e,r){"anyone"===r&&(r=new re(1).toPublicKey()),r=this.normalizeCounterparty(r);const i=this.derivePublicKey(t,e,r),n=this.derivePrivateKey(t,e,r);return new Pe(n.deriveSharedSecret(i)?.x?.toArray()??[])}revealCounterpartySecret(t){if("self"===t)throw new Error("Counterparty secrets cannot be revealed for counterparty=self.");t=this.normalizeCounterparty(t);const e=this.rootKey.toPublicKey();if(this.rootKey.deriveChild(e,"test").toHex()===this.rootKey.deriveChild(t,"test").toHex())throw new Error("Counterparty secrets cannot be revealed for counterparty=self.");return this.rootKey.deriveSharedSecret(t).encode(!0)}revealSpecificSecret(t,e,r){t=this.normalizeCounterparty(t);const i=this.rootKey.deriveSharedSecret(t),n=Ot(this.computeInvoiceNumber(e,r),"utf8");return kt(i.encode(!0),n)}normalizeCounterparty(t){if(null==t)throw new Error("counterparty must be self, anyone or a public key!");return"self"===t?this.rootKey.toPublicKey():"anyone"===t?new re(1).toPublicKey():"string"==typeof t?Gt.fromString(t):t}computeInvoiceNumber(t,e){const r=t[0];if(!Number.isInteger(r)||r<0||r>2)throw new Error("Protocol security level must be 0, 1, or 2");const i=t[1].toLowerCase().trim();if(e.length>800)throw new Error("Key IDs must be 800 characters or less");if(e.length<1)throw new Error("Key IDs must be 1 character or more");if(i.length>400){if(!i.startsWith("specific linkage revelation "))throw new Error("Protocol names must be 400 characters or less");if(i.length>430)throw new Error("Specific linkage revelation protocol names must be 430 characters or less")}if(i.length<5)throw new Error("Protocol names must be 5 characters or more");if(i.includes(" "))throw new Error('Protocol names cannot contain multiple consecutive spaces (" ")');if(!/^[a-z0-9 ]+$/g.test(i))throw new Error("Protocol names can only contain letters, numbers and spaces");if(i.endsWith(" protocol"))throw new Error('No need to end your protocol name with " protocol"');return`${r}-${i}-${e}`}}class Rr{keyDeriver;cache;maxCacheSize;constructor(t,e){this.keyDeriver=new Fr(t),this.cache=new Map;const r=e?.maxCacheSize;this.maxCacheSize=null!=r&&!isNaN(r)&&r>0?r:1e3}derivePublicKey(t,e,r,i=!1){const n=this.generateCacheKey("derivePublicKey",t,e,r,i);if(this.cache.has(n)){const t=this.cacheGet(n);if(void 0===t)throw new Error("Cached value is undefined");return t}{const s=this.keyDeriver.derivePublicKey(t,e,r,i);return this.cacheSet(n,s),s}}derivePrivateKey(t,e,r){const i=this.generateCacheKey("derivePrivateKey",t,e,r);if(this.cache.has(i)){const t=this.cacheGet(i);if(void 0===t)throw new Error("Cached value is undefined");return t}{const n=this.keyDeriver.derivePrivateKey(t,e,r);return this.cacheSet(i,n),n}}deriveSymmetricKey(t,e,r){const i=this.generateCacheKey("deriveSymmetricKey",t,e,r);if(this.cache.has(i)){const t=this.cacheGet(i);if(void 0===t)throw new Error("Cached value is undefined");return t}{const n=this.keyDeriver.deriveSymmetricKey(t,e,r);return this.cacheSet(i,n),n}}revealCounterpartySecret(t){const e=this.generateCacheKey("revealCounterpartySecret",t);if(this.cache.has(e)){const t=this.cacheGet(e);if(void 0===t)throw new Error("Cached value is undefined");return t}{const r=this.keyDeriver.revealCounterpartySecret(t);return this.cacheSet(e,r),r}}revealSpecificSecret(t,e,r){const i=this.generateCacheKey("revealSpecificSecret",t,e,r);if(this.cache.has(i)){const t=this.cacheGet(i);if(void 0===t)throw new Error("Cached value is undefined");return t}{const n=this.keyDeriver.revealSpecificSecret(t,e,r);return this.cacheSet(i,n),n}}generateCacheKey(t,...e){return`${t}|${e.map((t=>this.serializeArgument(t))).join("|")}`}serializeArgument(t){return t instanceof Gt||t instanceof re?t.toString():Array.isArray(t)?t.map((t=>this.serializeArgument(t))).join(","):"object"==typeof t&&null!==t?JSON.stringify(t):String(t)}cacheGet(t){const e=this.cache.get(t);return this.cache.delete(t),void 0!==e&&this.cache.set(t,e),e}cacheSet(t,e){if(this.cache.size>=this.maxCacheSize){const t=this.cache.keys().next().value;this.cache.delete(t)}this.cache.set(t,e)}}const Cr=class{keyDeriver;constructor(t){"string"!=typeof t.identityKey&&(t=new Fr(t)),this.keyDeriver=t}async getPublicKey(t){if(t.identityKey){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==t.protocolID||null==t.keyID||""===t.keyID)throw new Error("protocolID and keyID are required if identityKey is false or undefined.");return{publicKey:(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePublicKey(t.protocolID,t.keyID,t.counterparty??"self",t.forSelf).toString()}}async revealCounterpartyKeyLinkage(t){const{publicKey:e}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const r=this.keyDeriver.revealCounterpartySecret(t.counterparty),i=(new Se).generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),Gt.fromString(t.counterparty),Kt.fromDER(r)),n=[...i.R.encode(!0),...i.SPrime.encode(!0),...i.z.toArray()],s=(new Date).toISOString(),{ciphertext:a}=await this.encrypt({plaintext:r,protocolID:[2,"counterparty linkage revelation"],keyID:s,counterparty:t.verifier}),{ciphertext:o}=await this.encrypt({plaintext:n,protocolID:[2,"counterparty linkage revelation"],keyID:s,counterparty:t.verifier});return{prover:e,verifier:t.verifier,counterparty:t.counterparty,revelationTime:s,encryptedLinkage:a,encryptedLinkageProof:o}}async revealSpecificKeyLinkage(t){const{publicKey:e}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const r=this.keyDeriver.revealSpecificSecret(t.counterparty,t.protocolID,t.keyID),{ciphertext:i}=await this.encrypt({plaintext:r,protocolID:[2,`specific linkage revelation ${t.protocolID[0]} ${t.protocolID[1]}`],keyID:t.keyID,counterparty:t.verifier}),{ciphertext:n}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${t.protocolID[0]} ${t.protocolID[1]}`],keyID:t.keyID,counterparty:t.verifier});return{prover:e,verifier:t.verifier,counterparty:t.counterparty,protocolID:t.protocolID,keyID:t.keyID,encryptedLinkage:i,encryptedLinkageProof:n,proofType:0}}async encrypt(t){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{ciphertext:this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self").encrypt(t.plaintext)}}async decrypt(t){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{plaintext:this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self").decrypt(t.ciphertext)}}async createHmac(t){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const e=this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self");return{hmac:kt(e.toArray(),t.data)}}async verifyHmac(t){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const e=this.keyDeriver.deriveSymmetricKey(t.protocolID,t.keyID,t.counterparty??"self"),r=kt(e.toArray(),t.data).toString()===t.hmac.toString();if(!r){const t=new Error("HMAC is not valid");throw t.code="ERR_INVALID_HMAC",t}return{valid:r}}async createSignature(t){if(null==t.hashToDirectlySign&&null==t.data)throw new Error("args.data or args.hashToDirectlySign must be valid");const e=t.hashToDirectlySign??gt(t.data??[]),r=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePrivateKey(t.protocolID,t.keyID,t.counterparty??"anyone");return{signature:Wt(new h(e),r,!0).toDER()}}async verifySignature(t){if(null==t.hashToDirectlyVerify&&null==t.data)throw new Error("args.data or args.hashToDirectlyVerify must be valid");const e=t.hashToDirectlyVerify??gt(t.data??[]),r=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePublicKey(t.protocolID,t.keyID,t.counterparty??"self",t.forSelf),i=Xt(new h(e),$t.fromDER(t.signature),r);if(!i){const t=new Error("Signature is not valid");throw t.code="ERR_INVALID_SIGNATURE",t}return{valid:i}}};class Vr{CWI;constructor(){if("object"!=typeof window)throw new Error("The window.CWI substrate requires a global window object.");if("object"!=typeof window.CWI)throw new Error("The window.CWI interface does not appear to be bound to the window object.");this.CWI=window.CWI}async createAction(t,e){return await this.CWI.createAction(t,e)}async signAction(t,e){return await this.CWI.signAction(t,e)}async abortAction(t,e){return await this.CWI.abortAction(t,e)}async listActions(t,e){return await this.CWI.listActions(t,e)}async internalizeAction(t,e){return await this.CWI.internalizeAction(t,e)}async listOutputs(t,e){return await this.CWI.listOutputs(t,e)}async relinquishOutput(t,e){return await this.CWI.relinquishOutput(t,e)}async getPublicKey(t,e){return await this.CWI.getPublicKey(t,e)}async revealCounterpartyKeyLinkage(t,e){return await this.CWI.revealCounterpartyKeyLinkage(t,e)}async revealSpecificKeyLinkage(t,e){return await this.CWI.revealSpecificKeyLinkage(t,e)}async encrypt(t,e){return await this.CWI.encrypt(t,e)}async decrypt(t,e){return await this.CWI.decrypt(t,e)}async createHmac(t,e){return await this.CWI.createHmac(t,e)}async verifyHmac(t,e){return await this.CWI.verifyHmac(t,e)}async createSignature(t,e){return await this.CWI.createSignature(t,e)}async verifySignature(t,e){return await this.CWI.verifySignature(t,e)}async acquireCertificate(t,e){return await this.CWI.acquireCertificate(t,e)}async listCertificates(t,e){return await this.CWI.listCertificates(t,e)}async proveCertificate(t,e){return await this.CWI.proveCertificate(t,e)}async relinquishCertificate(t,e){return await this.CWI.relinquishCertificate(t,e)}async discoverByIdentityKey(t,e){return await this.CWI.discoverByIdentityKey(t,e)}async discoverByAttributes(t,e){return await this.CWI.discoverByAttributes(t,e)}async isAuthenticated(t,e){return await this.CWI.isAuthenticated(t,e)}async waitForAuthentication(t,e){return await this.CWI.waitForAuthentication(t,e)}async getHeight(t,e){return await this.CWI.getHeight(t,e)}async getHeaderForHeight(t,e){return await this.CWI.getHeaderForHeight(t,e)}async getNetwork(t,e){return await this.CWI.getNetwork(t,e)}async getVersion(t,e){return await this.CWI.getVersion(t,e)}}class Dr extends Error{code;isError=!0;constructor(t,e=1,r){super(t),this.code=e,this.name=this.constructor.name,null!=r&&""!==r?this.stack=r:Error.captureStackTrace(this,this.constructor)}}var Br;!function(t){t[t.unknownError=1]="unknownError",t[t.unsupportedAction=2]="unsupportedAction",t[t.invalidHmac=3]="invalidHmac",t[t.invalidSignature=4]="invalidSignature",t[t.reviewActions=5]="reviewActions"}(Br||(Br={}));const Ur=Dr;class Hr{domain;constructor(t="*"){if("object"!=typeof window)throw new Error("The XDM substrate requires a global window object.");if("function"!=typeof window.postMessage)throw new Error("The window object does not seem to support postMessage calls.");this.domain=t}async invoke(t,e){return await new Promise(((r,i)=>{const n=_t(Zt(12)),s=t=>{if("CWI"===t.data.type&&t.isTrusted&&t.data.id===n&&!0!==t.data.isInvocation)if("function"==typeof window.removeEventListener&&window.removeEventListener("message",s),"error"===t.data.status){const e=new Dr(t.data.description,t.data.code);i(e)}else r(t.data.result)};window.addEventListener("message",s),window.parent.postMessage({type:"CWI",isInvocation:!0,id:n,call:t,args:e},this.domain)}))}async createAction(t){return await this.invoke("createAction",t)}async signAction(t){return await this.invoke("signAction",t)}async abortAction(t){return await this.invoke("abortAction",t)}async listActions(t){return await this.invoke("listActions",t)}async internalizeAction(t){return await this.invoke("internalizeAction",t)}async listOutputs(t){return await this.invoke("listOutputs",t)}async relinquishOutput(t){return await this.invoke("relinquishOutput",t)}async getPublicKey(t){return await this.invoke("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.invoke("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.invoke("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.invoke("encrypt",t)}async decrypt(t){return await this.invoke("decrypt",t)}async createHmac(t){return await this.invoke("createHmac",t)}async verifyHmac(t){return await this.invoke("verifyHmac",t)}async createSignature(t){return await this.invoke("createSignature",t)}async verifySignature(t){return await this.invoke("verifySignature",t)}async acquireCertificate(t){return await this.invoke("acquireCertificate",t)}async listCertificates(t){return await this.invoke("listCertificates",t)}async proveCertificate(t){return await this.invoke("proveCertificate",t)}async relinquishCertificate(t){return await this.invoke("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.invoke("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.invoke("discoverByAttributes",t)}async isAuthenticated(t){return await this.invoke("isAuthenticated",t)}async waitForAuthentication(t){return await this.invoke("waitForAuthentication",t)}async getHeight(t){return await this.invoke("getHeight",t)}async getHeaderForHeight(t){return await this.invoke("getHeaderForHeight",t)}async getNetwork(t){return await this.invoke("getNetwork",t)}async getVersion(t){return await this.invoke("getVersion",t)}}class Kr{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(t,e,r,i,n,s,a){this.type=t,this.serialNumber=e,this.subject=r,this.certifier=i,this.revocationOutpoint=n,this.fields=s,this.signature=a}toBinary(t=!0){const e=new Bt,r=Ot(this.type,"base64");e.write(r);const i=Ot(this.serialNumber,"base64");e.write(i);const n=Ot(this.subject,"hex");e.write(n);const s=Ot(this.certifier,"hex");e.write(s);const[a,o]=this.revocationOutpoint.split("."),c=Ot(a,"hex");e.write(c),e.writeVarIntNum(Number(o));const h=Object.keys(this.fields).sort();e.writeVarIntNum(h.length);for(const t of h){const r=this.fields[t],i=Ot(t,"utf8");e.writeVarIntNum(i.length),e.write(i);const n=Ot(r,"utf8");e.writeVarIntNum(n.length),e.write(n)}if(t&&(this.signature??"").length>0){const t=Ot(this.signature,"hex");e.write(t)}return e.toArray()}static fromBinary(t){const e=new Ut(t),r=_t(e.read(32)),i=_t(e.read(32)),n=e.read(33),s=Nt(n),a=e.read(33),o=Nt(a),c=e.read(32),h=`${Nt(c)}.${e.readVarIntNum()}`,u=e.readVarIntNum(),l={};for(let t=0;t<u;t++){const t=e.readVarIntNum(),r=e.read(t),i=Tt(r),n=e.readVarIntNum(),s=e.read(n),a=Tt(s);l[i]=a}let d;if(!e.eof()){const t=e.read();d=$t.fromDER(t).toString("hex")}return new Kr(r,i,s,o,h,l,d)}async verify(){const t=new Cr("anyone"),e=this.toBinary(!1),r=this.signature??"",{valid:i}=await t.verifySignature({signature:Ot(r,"hex"),data:e,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`,counterparty:this.certifier});return i}async sign(t){if(null!=this.signature&&this.signature.length>0)throw new Error(`Certificate has already been signed! Signature present: ${this.signature}`);this.certifier=(await t.getPublicKey({identityKey:!0})).publicKey;const e=this.toBinary(!1),{signature:r}=await t.createSignature({data:e,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`});this.signature=Nt(r)}static getCertificateFieldEncryptionDetails(t,e){return{protocolID:[2,"certificate field encryption"],keyID:e?`${e} ${t}`:t}}}var qr;!function(t){t[t.createAction=1]="createAction",t[t.signAction=2]="signAction",t[t.abortAction=3]="abortAction",t[t.listActions=4]="listActions",t[t.internalizeAction=5]="internalizeAction",t[t.listOutputs=6]="listOutputs",t[t.relinquishOutput=7]="relinquishOutput",t[t.getPublicKey=8]="getPublicKey",t[t.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",t[t.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",t[t.encrypt=11]="encrypt",t[t.decrypt=12]="decrypt",t[t.createHmac=13]="createHmac",t[t.verifyHmac=14]="verifyHmac",t[t.createSignature=15]="createSignature",t[t.verifySignature=16]="verifySignature",t[t.acquireCertificate=17]="acquireCertificate",t[t.listCertificates=18]="listCertificates",t[t.proveCertificate=19]="proveCertificate",t[t.relinquishCertificate=20]="relinquishCertificate",t[t.discoverByIdentityKey=21]="discoverByIdentityKey",t[t.discoverByAttributes=22]="discoverByAttributes",t[t.isAuthenticated=23]="isAuthenticated",t[t.waitForAuthentication=24]="waitForAuthentication",t[t.getHeight=25]="getHeight",t[t.getHeaderForHeight=26]="getHeaderForHeight",t[t.getNetwork=27]="getNetwork",t[t.getVersion=28]="getVersion"}(qr||(qr={}));const Lr=qr;class $r{wire;constructor(t){this.wire=t}async transmit(t,e="",r=[]){const i=new Bt;i.writeUInt8(Lr[t]);const n=Ot(e,"utf8");i.writeUInt8(n.length),i.write(n),r.length>0&&i.write(r);const s=i.toArray(),a=await this.wire.transmitToWallet(s),o=new Ut(a),c=o.readUInt8();if(0===c)return o.read();{const t=o.readVarIntNum(),e=o.read(t),r=Tt(e),i=o.readVarIntNum(),n=o.read(i),s=Tt(n);throw new Dr(r,c,s)}}async createAction(t,e){const r=new Bt,i=Ot(t.description,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=t.inputBEEF?(r.writeVarIntNum(t.inputBEEF.length),r.write(t.inputBEEF)):r.writeVarIntNum(-1),null!=t.inputs){r.writeVarIntNum(t.inputs.length);for(const e of t.inputs){if(r.write(this.encodeOutpoint(e.outpoint)),null!=e.unlockingScript&&""!==e.unlockingScript){const t=Ot(e.unlockingScript,"hex");r.writeVarIntNum(t.length),r.write(t)}else r.writeVarIntNum(-1),r.writeVarIntNum(e.unlockingScriptLength??0);const t=Ot(e.inputDescription,"utf8");r.writeVarIntNum(t.length),r.write(t),"number"==typeof e.sequenceNumber?r.writeVarIntNum(e.sequenceNumber):r.writeVarIntNum(-1)}}else r.writeVarIntNum(-1);if(null!=t.outputs){r.writeVarIntNum(t.outputs.length);for(const e of t.outputs){const t=Ot(e.lockingScript,"hex");r.writeVarIntNum(t.length),r.write(t),r.writeVarIntNum(e.satoshis);const i=Ot(e.outputDescription,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=e.basket&&""!==e.basket){const t=Ot(e.basket,"utf8");r.writeVarIntNum(t.length),r.write(t)}else r.writeVarIntNum(-1);if(null!=e.customInstructions&&""!==e.customInstructions){const t=Ot(e.customInstructions,"utf8");r.writeVarIntNum(t.length),r.write(t)}else r.writeVarIntNum(-1);if(null!=e.tags){r.writeVarIntNum(e.tags.length);for(const t of e.tags){const e=Ot(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}}else r.writeVarIntNum(-1)}}else r.writeVarIntNum(-1);if("number"==typeof t.lockTime?r.writeVarIntNum(t.lockTime):r.writeVarIntNum(-1),"number"==typeof t.version?r.writeVarIntNum(t.version):r.writeVarIntNum(-1),null!=t.labels){r.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=Ot(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}}else r.writeVarIntNum(-1);if(null!=t.options){if(r.writeInt8(1),"boolean"==typeof t.options.signAndProcess?r.writeInt8(t.options.signAndProcess?1:0):r.writeInt8(-1),"boolean"==typeof t.options.acceptDelayedBroadcast?r.writeInt8(t.options.acceptDelayedBroadcast?1:0):r.writeInt8(-1),"known"===t.options.trustSelf?r.writeInt8(1):r.writeInt8(-1),null!=t.options.knownTxids){r.writeVarIntNum(t.options.knownTxids.length);for(const e of t.options.knownTxids){const t=Ot(e,"hex");r.write(t)}}else r.writeVarIntNum(-1);if("boolean"==typeof t.options.returnTXIDOnly?r.writeInt8(t.options.returnTXIDOnly?1:0):r.writeInt8(-1),"boolean"==typeof t.options.noSend?r.writeInt8(t.options.noSend?1:0):r.writeInt8(-1),null!=t.options.noSendChange){r.writeVarIntNum(t.options.noSendChange.length);for(const e of t.options.noSendChange)r.write(this.encodeOutpoint(e))}else r.writeVarIntNum(-1);if(null!=t.options.sendWith){r.writeVarIntNum(t.options.sendWith.length);for(const e of t.options.sendWith){const t=Ot(e,"hex");r.write(t)}}else r.writeVarIntNum(-1);"boolean"==typeof t.options.randomizeOutputs?r.writeInt8(t.options.randomizeOutputs?1:0):r.writeInt8(-1)}else r.writeInt8(0);const n=await this.transmit("createAction",e,r.toArray()),s=new Ut(n),a={};if(1===s.readInt8()){const t=s.read(32);a.txid=Nt(t)}if(1===s.readInt8()){const t=s.readVarIntNum();a.tx=s.read(t)}const o=s.readVarIntNum();if(o>=0){a.noSendChange=[];for(let t=0;t<o;t++){const t=this.readOutpoint(s);a.noSendChange.push(t)}}const c=s.readVarIntNum();if(c>=0){a.sendWithResults=[];for(let t=0;t<c;t++){const t=s.read(32),e=Nt(t),r=s.readInt8();let i="unproven";1===r?i="unproven":2===r?i="sending":3===r&&(i="failed"),a.sendWithResults.push({txid:e,status:i})}}if(1===s.readInt8()){const t=s.readVarIntNum(),e=s.read(t),r=s.readVarIntNum(),i=s.read(r);a.signableTransaction={tx:e,reference:_t(i)}}return a}async signAction(t,e){const r=new Bt,i=Object.keys(t.spends);r.writeVarIntNum(i.length);for(const e of i){r.writeVarIntNum(Number(e));const i=t.spends[Number(e)],n=Ot(i.unlockingScript,"hex");r.writeVarIntNum(n.length),r.write(n),"number"==typeof i.sequenceNumber?r.writeVarIntNum(i.sequenceNumber):r.writeVarIntNum(-1)}const n=Ot(t.reference,"base64");if(r.writeVarIntNum(n.length),r.write(n),null!=t.options)if(r.writeInt8(1),"boolean"==typeof t.options.acceptDelayedBroadcast?r.writeInt8(t.options.acceptDelayedBroadcast?1:0):r.writeInt8(-1),"boolean"==typeof t.options.returnTXIDOnly?r.writeInt8(t.options.returnTXIDOnly?1:0):r.writeInt8(-1),"boolean"==typeof t.options.noSend?r.writeInt8(t.options.noSend?1:0):r.writeInt8(-1),null!=t.options.sendWith){r.writeVarIntNum(t.options.sendWith.length);for(const e of t.options.sendWith){const t=Ot(e,"hex");r.write(t)}}else r.writeVarIntNum(-1);else r.writeInt8(0);const s=await this.transmit("signAction",e,r.toArray()),a=new Ut(s),o={};if(1===a.readInt8()){const t=a.read(32);o.txid=Nt(t)}if(1===a.readInt8()){const t=a.readVarIntNum();o.tx=a.read(t)}const c=a.readVarIntNum();if(c>=0){o.sendWithResults=[];for(let t=0;t<c;t++){const t=a.read(32),e=Nt(t),r=a.readInt8();let i="unproven";1===r?i="unproven":2===r?i="sending":3===r&&(i="failed"),o.sendWithResults.push({txid:e,status:i})}}return o}async abortAction(t,e){return await this.transmit("abortAction",e,Ot(t.reference,"base64")),{aborted:!0}}async listActions(t,e){const r=new Bt;r.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=Ot(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}"any"===t.labelQueryMode?r.writeInt8(1):"all"===t.labelQueryMode?r.writeInt8(2):r.writeInt8(-1);const i=[t.includeLabels,t.includeInputs,t.includeInputSourceLockingScripts,t.includeInputUnlockingScripts,t.includeOutputs,t.includeOutputLockingScripts];for(const t of i)"boolean"==typeof t?r.writeInt8(t?1:0):r.writeInt8(-1);"number"==typeof t.limit?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),"number"==typeof t.offset?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const n=await this.transmit("listActions",e,r.toArray()),s=new Ut(n),a=s.readVarIntNum(),o=[];for(let t=0;t<a;t++){const t=s.read(32),e=Nt(t),r=s.readVarIntNum(),i=s.readInt8();let n;switch(i){case 1:n="completed";break;case 2:n="unprocessed";break;case 3:n="sending";break;case 4:n="unproven";break;case 5:n="unsigned";break;case 6:n="nosend";break;case 7:n="nonfinal";break;case 8:n="failed";break;default:throw new Error(`Unknown status code: ${i}`)}const a=1===s.readInt8(),c=s.readVarIntNum(),h=s.read(c),u={txid:e,satoshis:r,status:n,isOutgoing:a,description:Tt(h),version:0,lockTime:0},l=s.readVarIntNum();if(l>=0){u.labels=[];for(let t=0;t<l;t++){const t=s.readVarIntNum(),e=s.read(t);u.labels.push(Tt(e))}}u.version=s.readVarIntNum(),u.lockTime=s.readVarIntNum();const d=s.readVarIntNum();if(d>=0){u.inputs=[];for(let t=0;t<d;t++){const t=this.readOutpoint(s),e=s.readVarIntNum(),r=s.readVarIntNum();let i;if(r>=0){const t=s.read(r);i=Nt(t)}const n=s.readVarIntNum();let a;if(n>=0){const t=s.read(n);a=Nt(t)}const o=s.readVarIntNum(),c=s.read(o),h=Tt(c),l=s.readVarIntNum();u.inputs.push({sourceOutpoint:t,sourceSatoshis:e,sourceLockingScript:i,unlockingScript:a,inputDescription:h,sequenceNumber:l})}}const f=s.readVarIntNum();if(f>=0){u.outputs=[];for(let t=0;t<f;t++){const t=s.readVarIntNum(),e=s.readVarIntNum(),r=s.readVarIntNum();let i;if(r>=0){const t=s.read(r);i=Nt(t)}const n=1===s.readInt8(),a=s.readVarIntNum(),o=s.read(a),c=Tt(o),h=s.readVarIntNum();let l;if(h>=0){const t=s.read(h);l=Tt(t)}const d=s.readVarIntNum(),f=[];if(d>=0)for(let t=0;t<d;t++){const t=s.readVarIntNum(),e=s.read(t);f.push(Tt(e))}const p=s.readVarIntNum();let m;if(p>=0){const t=s.read(p);m=Tt(t)}u.outputs.push({outputIndex:t,satoshis:e,lockingScript:i,spendable:n,outputDescription:c,basket:l,tags:f,customInstructions:m})}}o.push(u)}return{totalActions:a,actions:o}}async internalizeAction(t,e){const r=new Bt;r.writeVarIntNum(t.tx.length),r.write(t.tx),r.writeVarIntNum(t.outputs.length);for(const e of t.outputs)if(r.writeVarIntNum(e.outputIndex),"wallet payment"===e.protocol){if(null==e.paymentRemittance)throw new Error("Payment remittance is required for wallet payment");r.writeUInt8(1),r.write(Ot(e.paymentRemittance.senderIdentityKey,"hex"));const t=Ot(e.paymentRemittance.derivationPrefix,"base64");r.writeVarIntNum(t.length),r.write(t);const i=Ot(e.paymentRemittance.derivationSuffix,"base64");r.writeVarIntNum(i.length),r.write(i)}else{r.writeUInt8(2);const t=Ot(e.insertionRemittance?.basket,"utf8");if(r.writeVarIntNum(t.length),r.write(t),"string"==typeof e.insertionRemittance?.customInstructions&&""!==e.insertionRemittance.customInstructions){const t=Ot(e.insertionRemittance.customInstructions,"utf8");r.writeVarIntNum(t.length),r.write(t)}else r.writeVarIntNum(-1);if("object"==typeof e.insertionRemittance?.tags){r.writeVarIntNum(e.insertionRemittance.tags.length);for(const t of e.insertionRemittance.tags){const e=Ot(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}}else r.writeVarIntNum(0)}if("object"==typeof t.labels){r.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=Ot(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}}else r.writeVarIntNum(-1);const i=Ot(t.description);return r.writeVarIntNum(i.length),r.write(i),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),await this.transmit("internalizeAction",e,r.toArray()),{accepted:!0}}async listOutputs(t,e){const r=new Bt,i=Ot(t.basket,"utf8");if(r.writeVarIntNum(i.length),r.write(i),"object"==typeof t.tags){r.writeVarIntNum(t.tags.length);for(const e of t.tags){const t=Ot(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}}else r.writeVarIntNum(0);"all"===t.tagQueryMode?r.writeInt8(1):"any"===t.tagQueryMode?r.writeInt8(2):r.writeInt8(-1),"locking scripts"===t.include?r.writeInt8(1):"entire transactions"===t.include?r.writeInt8(2):r.writeInt8(-1),"boolean"==typeof t.includeCustomInstructions?r.writeInt8(t.includeCustomInstructions?1:0):r.writeInt8(-1),"boolean"==typeof t.includeTags?r.writeInt8(t.includeTags?1:0):r.writeInt8(-1),"boolean"==typeof t.includeLabels?r.writeInt8(t.includeLabels?1:0):r.writeInt8(-1),"number"==typeof t.limit?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),"number"==typeof t.offset?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const n=await this.transmit("listOutputs",e,r.toArray()),s=new Ut(n),a=s.readVarIntNum(),o=s.readVarIntNum();let c;o>=0&&(c=s.read(o));const h=[];for(let t=0;t<a;t++){const t={spendable:!0,outpoint:this.readOutpoint(s),satoshis:s.readVarIntNum()},e=s.readVarIntNum();e>=0&&(t.lockingScript=Nt(s.read(e)));const r=s.readVarIntNum();r>=0&&(t.customInstructions=Tt(s.read(r)));const i=s.readVarIntNum();if(-1!==i){const e=[];for(let t=0;t<i;t++){const t=s.readVarIntNum();e.push(Tt(s.read(t)))}t.tags=e}const n=s.readVarIntNum();if(-1!==n){const e=[];for(let t=0;t<n;t++){const t=s.readVarIntNum();e.push(Tt(s.read(t)))}t.labels=e}h.push(t)}return{totalOutputs:a,BEEF:c,outputs:h}}async relinquishOutput(t,e){const r=new Bt,i=Ot(t.basket,"utf8");return r.writeVarIntNum(i.length),r.write(i),r.write(this.encodeOutpoint(t.output)),await this.transmit("relinquishOutput",e,r.toArray()),{relinquished:!0}}encodeOutpoint(t){const e=new Bt,[r,i]=t.split(".");return e.write(Ot(r,"hex")),e.writeVarIntNum(Number(i)),e.toArray()}readOutpoint(t){return`${Nt(t.read(32))}.${t.readVarIntNum()}`}async getPublicKey(t,e){const r=new Bt;r.writeUInt8(t.identityKey?1:0),t.identityKey?r.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)):(r.write(this.encodeKeyRelatedParams(t.protocolID??=[_r.Silent,"default"],t.keyID??="",t.counterparty,t.privileged,t.privilegedReason)),"boolean"==typeof t.forSelf?r.writeInt8(t.forSelf?1:0):r.writeInt8(-1)),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const i=await this.transmit("getPublicKey",e,r.toArray());return{publicKey:Nt(i)}}async revealCounterpartyKeyLinkage(t,e){const r=new Bt;r.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)),r.write(Ot(t.counterparty,"hex")),r.write(Ot(t.verifier,"hex"));const i=await this.transmit("revealCounterpartyKeyLinkage",e,r.toArray()),n=new Ut(i),s=Nt(n.read(33)),a=Nt(n.read(33)),o=Nt(n.read(33)),c=n.readVarIntNum(),h=Tt(n.read(c)),u=n.readVarIntNum(),l=n.read(u),d=n.readVarIntNum();return{prover:s,verifier:a,counterparty:o,revelationTime:h,encryptedLinkage:l,encryptedLinkageProof:n.read(d)}}async revealSpecificKeyLinkage(t,e){const r=new Bt;r.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),r.write(Ot(t.verifier,"hex"));const i=await this.transmit("revealSpecificKeyLinkage",e,r.toArray()),n=new Ut(i),s=Nt(n.read(33)),a=Nt(n.read(33)),o=Nt(n.read(33)),c=n.readUInt8(),h=n.readVarIntNum(),u=Tt(n.read(h)),l=n.readVarIntNum(),d=Tt(n.read(l)),f=n.readVarIntNum(),p=n.read(f),m=n.readVarIntNum();return{prover:s,verifier:a,counterparty:o,protocolID:[c,u],keyID:d,encryptedLinkage:p,encryptedLinkageProof:n.read(m),proofType:n.readUInt8()}}async encrypt(t,e){const r=new Bt;return r.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),r.writeVarIntNum(t.plaintext.length),r.write(t.plaintext),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),{ciphertext:await this.transmit("encrypt",e,r.toArray())}}async decrypt(t,e){const r=new Bt;return r.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),r.writeVarIntNum(t.ciphertext.length),r.write(t.ciphertext),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),{plaintext:await this.transmit("decrypt",e,r.toArray())}}async createHmac(t,e){const r=new Bt;return r.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),r.writeVarIntNum(t.data.length),r.write(t.data),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),{hmac:await this.transmit("createHmac",e,r.toArray())}}async verifyHmac(t,e){const r=new Bt;return r.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),r.write(t.hmac),r.writeVarIntNum(t.data.length),r.write(t.data),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),await this.transmit("verifyHmac",e,r.toArray()),{valid:!0}}async createSignature(t,e){const r=new Bt;return r.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),"object"==typeof t.data?(r.writeUInt8(1),r.writeVarIntNum(t.data.length),r.write(t.data)):(r.writeUInt8(2),r.write(t.hashToDirectlySign??=[])),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),{signature:await this.transmit("createSignature",e,r.toArray())}}async verifySignature(t,e){const r=new Bt;return r.write(this.encodeKeyRelatedParams(t.protocolID,t.keyID,t.counterparty,t.privileged,t.privilegedReason)),"boolean"==typeof t.forSelf?r.writeInt8(t.forSelf?1:0):r.writeInt8(-1),r.writeVarIntNum(t.signature.length),r.write(t.signature),"object"==typeof t.data?(r.writeUInt8(1),r.writeVarIntNum(t.data.length),r.write(t.data)):(r.writeUInt8(2),r.write(t.hashToDirectlyVerify??[])),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1),await this.transmit("verifySignature",e,r.toArray()),{valid:!0}}encodeKeyRelatedParams(t,e,r,i,n){const s=new Bt;s.writeUInt8(t[0]);const a=Ot(t[1],"utf8");s.writeVarIntNum(a.length),s.write(a);const o=Ot(e,"utf8");return s.writeVarIntNum(o.length),s.write(o),"string"!=typeof r?s.writeUInt8(0):"self"===r?s.writeUInt8(11):"anyone"===r?s.writeUInt8(12):s.write(Ot(r,"hex")),s.write(this.encodePrivilegedParams(i,n)),s.toArray()}async acquireCertificate(t,e){const r=new Bt;r.write(Ot(t.type,"base64")),r.write(Ot(t.certifier,"hex"));const i=Object.entries(t.fields);r.writeVarIntNum(i.length);for(const[t,e]of i){const i=Ot(t,"utf8"),n=Ot(e,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(n.length),r.write(n)}if(r.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason)),r.writeUInt8("direct"===t.acquisitionProtocol?1:2),"direct"===t.acquisitionProtocol){r.write(Ot(t.serialNumber,"base64")),r.write(this.encodeOutpoint(t.revocationOutpoint??""));const e=Ot(t.signature,"hex");r.writeVarIntNum(e.length),r.write(e);const i="certifier"!==t.keyringRevealer?Ot(t.keyringRevealer,"hex"):[11];r.write(i);const n=Object.keys(t.keyringForSubject??{});r.writeVarIntNum(n.length);for(let e=0;e<n.length;e++){const i=Ot(n[e],"utf8");r.writeVarIntNum(i.length),r.write(i);const s=Ot(t.keyringForSubject?.[n[e]],"base64");r.writeVarIntNum(s.length),r.write(s)}}else{const e=Ot(t.certifierUrl,"utf8");r.writeVarIntNum(e.length),r.write(e)}const n=await this.transmit("acquireCertificate",e,r.toArray()),s=Kr.fromBinary(n);return{...s,signature:s.signature}}encodePrivilegedParams(t,e){const r=new Bt;if("boolean"==typeof t?r.writeInt8(t?1:0):r.writeInt8(-1),"string"==typeof e){const t=Ot(e,"utf8");r.writeInt8(t.length),r.write(t)}else r.writeInt8(-1);return r.toArray()}async listCertificates(t,e){const r=new Bt;r.writeVarIntNum(t.certifiers.length);for(let e=0;e<t.certifiers.length;e++)r.write(Ot(t.certifiers[e],"hex"));r.writeVarIntNum(t.types.length);for(let e=0;e<t.types.length;e++)r.write(Ot(t.types[e],"base64"));"number"==typeof t.limit?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),"number"==typeof t.offset?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),r.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason));const i=await this.transmit("listCertificates",e,r.toArray()),n=new Ut(i),s=n.readVarIntNum(),a=[];for(let t=0;t<s;t++){const t=n.readVarIntNum(),e=n.read(t),r=Kr.fromBinary(e);a.push({...r,signature:r.signature})}return{totalCertificates:s,certificates:a}}async proveCertificate(t,e){const r=new Bt,i=Ot(t.certificate.type,"base64");r.write(i);const n=Ot(t.certificate.subject,"hex");r.write(n);const s=Ot(t.certificate.serialNumber,"base64");r.write(s);const a=Ot(t.certificate.certifier,"hex");r.write(a);const o=this.encodeOutpoint(t.certificate.revocationOutpoint??"");r.write(o);const c=Ot(t.certificate.signature,"hex");r.writeVarIntNum(c.length),r.write(c);const h=Object.entries(t.certificate.fields??{});r.writeVarIntNum(h.length);for(const[t,e]of h){const i=Ot(t,"utf8"),n=Ot(e,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(n.length),r.write(n)}r.writeVarIntNum(t.fieldsToReveal.length);for(const e of t.fieldsToReveal){const t=Ot(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}r.write(Ot(t.verifier,"hex")),r.write(this.encodePrivilegedParams(t.privileged,t.privilegedReason));const u=await this.transmit("proveCertificate",e,r.toArray()),l=new Ut(u),d=l.readVarIntNum(),f={};for(let t=0;t<d;t++){const t=l.readVarIntNum(),e=Tt(l.read(t)),r=l.readVarIntNum();f[e]=_t(l.read(r))}return{keyringForVerifier:f}}async relinquishCertificate(t,e){const r=new Bt,i=Ot(t.type,"base64");r.write(i);const n=Ot(t.serialNumber,"base64");r.write(n);const s=Ot(t.certifier,"hex");return r.write(s),await this.transmit("relinquishCertificate",e,r.toArray()),{relinquished:!0}}parseDiscoveryResult(t){const e=new Ut(t),r=e.readVarIntNum(),i=[];for(let t=0;t<r;t++){const t=e.readVarIntNum(),r=e.read(t),n=Kr.fromBinary(r),s=e.readVarIntNum(),a=Tt(e.read(s)),o=e.readVarIntNum(),c=Tt(e.read(o)),h=e.readVarIntNum(),u=Tt(e.read(h)),l=e.readUInt8(),d={},f=e.readVarIntNum();for(let t=0;t<f;t++){const t=e.readVarIntNum(),r=Tt(e.read(t)),i=e.readVarIntNum();d[r]=e.read(i)}const p={},m=e.readVarIntNum();for(let t=0;t<m;t++){const t=e.readVarIntNum(),r=Tt(e.read(t)),i=e.readVarIntNum();p[r]=Tt(e.read(i))}i.push({...n,signature:n.signature,certifierInfo:{iconUrl:c,name:a,description:u,trust:l},publiclyRevealedKeyring:d,decryptedFields:p})}return{totalCertificates:r,certificates:i}}async discoverByIdentityKey(t,e){const r=new Bt;r.write(Ot(t.identityKey,"hex")),"number"==typeof t.limit?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),"number"==typeof t.offset?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const i=await this.transmit("discoverByIdentityKey",e,r.toArray());return this.parseDiscoveryResult(i)}async discoverByAttributes(t,e){const r=new Bt,i=Object.keys(t.attributes);r.writeVarIntNum(i.length);for(let e=0;e<i.length;e++)r.writeVarIntNum(i[e].length),r.write(Ot(i[e],"utf8")),r.writeVarIntNum(t.attributes[i[e]].length),r.write(Ot(t.attributes[i[e]],"utf8"));"number"==typeof t.limit?r.writeVarIntNum(t.limit):r.writeVarIntNum(-1),"number"==typeof t.offset?r.writeVarIntNum(t.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof t.seekPermission?t.seekPermission?1:0:-1);const n=await this.transmit("discoverByAttributes",e,r.toArray());return this.parseDiscoveryResult(n)}async isAuthenticated(t,e){return{authenticated:1===(await this.transmit("isAuthenticated",e))[0]}}async waitForAuthentication(t,e){return await this.transmit("waitForAuthentication",e),{authenticated:!0}}async getHeight(t,e){const r=await this.transmit("getHeight",e);return{height:new Ut(r).readVarIntNum()}}async getHeaderForHeight(t,e){const r=new Bt;r.writeVarIntNum(t.height);const i=await this.transmit("getHeaderForHeight",e,r.toArray());return{header:Nt(i)}}async getNetwork(t,e){return{network:0===(await this.transmit("getNetwork",e))[0]?"mainnet":"testnet"}}async getVersion(t,e){const r=await this.transmit("getVersion",e);return{version:Tt(r)}}}class zr{baseUrl;httpClient;originator;constructor(t,e="http://localhost:3301",r=fetch){this.baseUrl=e,this.httpClient=r,this.originator=t}async transmitToWallet(t){const e=new Ut(t),r=e.readUInt8(),i=Lr[r];if(void 0===i||""===i)throw new Error(`Invalid call code: ${r}`);const n=e.readUInt8();let s;if(n>0){const t=e.read(n);s=Tt(t)}const a=e.read(),o=await fetch(`${this.baseUrl}/${i}`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Origin:s??""},body:new Uint8Array(a)}),c=await o.arrayBuffer();return Array.from(new Uint8Array(c))}}class jr extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(t,e,r,i,n){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=t,this.sendWithResults=e,this.txid=r,this.tx=i,this.noSendChange=n,this.code=5,this.name=this.constructor.name}}const Wr=jr;class Xr{baseUrl;httpClient;originator;api;constructor(t,e="http://localhost:3321",r=fetch){this.baseUrl=e,this.originator=t,this.httpClient=r,this.api=async(t,e)=>{const i=await await r(`${this.baseUrl}/${t}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Originator:this.originator??""},body:JSON.stringify(e)}),n=await i.json();if(!i.ok){if(400===i.status&&n.isError&&5===n.code)throw new jr(n.reviewActionResults,n.sendWithResults,n.txid,n.tx,n.noSendChange);{const r={call:t,args:e,message:n.message??`HTTP Client error ${i.status}`};throw new Error(JSON.stringify(r))}}return n}}async createAction(t){return await this.api("createAction",t)}async signAction(t){return await this.api("signAction",t)}async abortAction(t){return await this.api("abortAction",t)}async listActions(t){return await this.api("listActions",t)}async internalizeAction(t){return await this.api("internalizeAction",t)}async listOutputs(t){return await this.api("listOutputs",t)}async relinquishOutput(t){return await this.api("relinquishOutput",t)}async getPublicKey(t){return await this.api("getPublicKey",t)}async revealCounterpartyKeyLinkage(t){return await this.api("revealCounterpartyKeyLinkage",t)}async revealSpecificKeyLinkage(t){return await this.api("revealSpecificKeyLinkage",t)}async encrypt(t){return await this.api("encrypt",t)}async decrypt(t){return await this.api("decrypt",t)}async createHmac(t){return await this.api("createHmac",t)}async verifyHmac(t){return await this.api("verifyHmac",t)}async createSignature(t){return await this.api("createSignature",t)}async verifySignature(t){return await this.api("verifySignature",t)}async acquireCertificate(t){return await this.api("acquireCertificate",t)}async listCertificates(t){return await this.api("listCertificates",t)}async proveCertificate(t){return await this.api("proveCertificate",t)}async relinquishCertificate(t){return await this.api("relinquishCertificate",t)}async discoverByIdentityKey(t){return await this.api("discoverByIdentityKey",t)}async discoverByAttributes(t){return await this.api("discoverByAttributes",t)}async isAuthenticated(t){return await this.api("isAuthenticated",t)}async waitForAuthentication(t){return await this.api("waitForAuthentication",t)}async getHeight(t){return await this.api("getHeight",t)}async getHeaderForHeight(t){return await this.api("getHeaderForHeight",t)}async getNetwork(t){return await this.api("getNetwork",t)}async getVersion(t){return await this.api("getVersion",t)}}class Gr{substrate;originator;constructor(t="auto",e){"Cicada"===t&&(t=new $r(new zr(e))),"window.CWI"===t&&(t=new Vr),"XDM"===t&&(t=new Hr),"json-api"===t&&(t=new Xr(e)),this.substrate=t,this.originator=e}async connectToSubstrate(){if("object"==typeof this.substrate)return;let t;const e=async e=>{let r;if(r="number"==typeof e?await Promise.race([t.getVersion({}),new Promise(((t,r)=>setTimeout((()=>r(new Error("Timed out."))),e)))]):await t.getVersion({}),"object"!=typeof r||"string"!=typeof r.version)throw new Error("Failed to use substrate.")};try{t=new Vr,await e(),this.substrate=t}catch(r){try{t=new Hr,await e(200),this.substrate=t}catch(r){try{t=new $r(new zr(this.originator)),await e(),this.substrate=t}catch(r){try{t=new Xr(this.originator),await e(),this.substrate=t}catch(t){throw new Error("No wallet available over any communication substrate. Install a BSV wallet today!")}}}}}async createAction(t){return await this.connectToSubstrate(),await this.substrate.createAction(t,this.originator)}async signAction(t){return await this.connectToSubstrate(),await this.substrate.signAction(t,this.originator)}async abortAction(t){return await this.connectToSubstrate(),await this.substrate.abortAction(t,this.originator)}async listActions(t){return await this.connectToSubstrate(),await this.substrate.listActions(t,this.originator)}async internalizeAction(t){return await this.connectToSubstrate(),await this.substrate.internalizeAction(t,this.originator)}async listOutputs(t){return await this.connectToSubstrate(),await this.substrate.listOutputs(t,this.originator)}async relinquishOutput(t){return await this.connectToSubstrate(),await this.substrate.relinquishOutput(t,this.originator)}async getPublicKey(t){return await this.connectToSubstrate(),await this.substrate.getPublicKey(t,this.originator)}async revealCounterpartyKeyLinkage(t){return await this.connectToSubstrate(),await this.substrate.revealCounterpartyKeyLinkage(t,this.originator)}async revealSpecificKeyLinkage(t){return await this.connectToSubstrate(),await this.substrate.revealSpecificKeyLinkage(t,this.originator)}async encrypt(t){return await this.connectToSubstrate(),await this.substrate.encrypt(t,this.originator)}async decrypt(t){return await this.substrate.decrypt(t,this.originator)}async createHmac(t){return await this.connectToSubstrate(),await this.substrate.createHmac(t,this.originator)}async verifyHmac(t){return await this.connectToSubstrate(),await this.substrate.verifyHmac(t,this.originator)}async createSignature(t){return await this.connectToSubstrate(),await this.substrate.createSignature(t,this.originator)}async verifySignature(t){return await this.connectToSubstrate(),await this.substrate.verifySignature(t,this.originator)}async acquireCertificate(t){return await this.connectToSubstrate(),await this.substrate.acquireCertificate(t,this.originator)}async listCertificates(t){return await this.connectToSubstrate(),await this.substrate.listCertificates(t,this.originator)}async proveCertificate(t){return await this.connectToSubstrate(),await this.substrate.proveCertificate(t,this.originator)}async relinquishCertificate(t){return await this.connectToSubstrate(),await this.substrate.relinquishCertificate(t,this.originator)}async discoverByIdentityKey(t){return await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(t,this.originator)}async discoverByAttributes(t){return await this.connectToSubstrate(),await this.substrate.discoverByAttributes(t,this.originator)}async isAuthenticated(t={}){return await this.connectToSubstrate(),await this.substrate.isAuthenticated(t,this.originator)}async waitForAuthentication(t={}){return await this.connectToSubstrate(),await this.substrate.waitForAuthentication(t,this.originator)}async getHeight(t={}){return await this.connectToSubstrate(),await this.substrate.getHeight(t,this.originator)}async getHeaderForHeight(t){return await this.connectToSubstrate(),await this.substrate.getHeaderForHeight(t,this.originator)}async getNetwork(t={}){return await this.connectToSubstrate(),await this.substrate.getNetwork(t,this.originator)}async getVersion(t={}){return await this.connectToSubstrate(),await this.substrate.getVersion(t,this.originator)}}class Yr{wallet;constructor(t){this.wallet=t}decodeOutpoint(t){const e=t.read(32);return`${Nt(e)}.${t.readVarIntNum()}`}encodeOutpoint(t){const e=new Bt,[r,i]=t.split(".");return e.write(Ot(r,"hex")),e.writeVarIntNum(Number(i)),e.toArray()}async transmitToWallet(t){const e=new Ut(t);try{const t=e.readUInt8(),r=Lr[t];if(void 0===r||""===r)throw new Error(`Invalid call code: ${t}`);const i=e.readUInt8(),n=e.read(i),s=Tt(n),a=e;switch(r){case"createAction":{const t={},e=a.readVarIntNum(),r=a.read(e);t.description=Tt(r);const i=a.readVarIntNum();t.inputBEEF=i>=0?a.read(i):void 0;const n=a.readVarIntNum();if(n>=0){t.inputs=[];for(let e=0;e<n;e++){const e={};e.outpoint=this.decodeOutpoint(a);const r=a.readVarIntNum();if(r>=0){const t=a.read(r);e.unlockingScript=Nt(t)}else{e.unlockingScript=void 0;const t=a.readVarIntNum();e.unlockingScriptLength=t}const i=a.readVarIntNum(),n=a.read(i);e.inputDescription=Tt(n);const s=a.readVarIntNum();e.sequenceNumber=s>=0?s:void 0,t.inputs.push(e)}}else t.inputs=void 0;const o=a.readVarIntNum();if(o>=0){t.outputs=[];for(let e=0;e<o;e++){const e={},r=a.readVarIntNum(),i=a.read(r);e.lockingScript=Nt(i),e.satoshis=a.readVarIntNum();const n=a.readVarIntNum(),s=a.read(n);e.outputDescription=Tt(s);const o=a.readVarIntNum();if(o>=0){const t=a.read(o);e.basket=Tt(t)}else e.basket=void 0;const c=a.readVarIntNum();if(c>=0){const t=a.read(c);e.customInstructions=Tt(t)}else e.customInstructions=void 0;const h=a.readVarIntNum();if(h>=0){e.tags=[];for(let t=0;t<h;t++){const t=a.readVarIntNum(),r=a.read(t),i=Tt(r);e.tags.push(i)}}else e.tags=void 0;t.outputs.push(e)}}else t.outputs=void 0;const c=a.readVarIntNum();t.lockTime=c>=0?c:void 0;const h=a.readVarIntNum();t.version=h>=0?h:void 0;const u=a.readVarIntNum();if(u>=0){t.labels=[];for(let e=0;e<u;e++){const e=a.readVarIntNum(),r=a.read(e),i=Tt(r);t.labels.push(i)}}else t.labels=void 0;if(1===a.readInt8()){t.options={};const e=a.readInt8();t.options.signAndProcess=-1===e?void 0:1===e;const r=a.readInt8();t.options.acceptDelayedBroadcast=-1===r?void 0:1===r;const i=a.readInt8();-1===i?t.options.trustSelf=void 0:1===i&&(t.options.trustSelf="known");const n=a.readVarIntNum();if(n>=0){t.options.knownTxids=[];for(let e=0;e<n;e++){const e=a.read(32),r=Nt(e);t.options.knownTxids.push(r)}}else t.options.knownTxids=void 0;const s=a.readInt8();t.options.returnTXIDOnly=-1===s?void 0:1===s;const o=a.readInt8();t.options.noSend=-1===o?void 0:1===o;const c=a.readVarIntNum();if(c>=0){t.options.noSendChange=[];for(let e=0;e<c;e++){const e=this.decodeOutpoint(a);t.options.noSendChange.push(e)}}else t.options.noSendChange=void 0;const h=a.readVarIntNum();if(h>=0){t.options.sendWith=[];for(let e=0;e<h;e++){const e=a.read(32),r=Nt(e);t.options.sendWith.push(r)}}else t.options.sendWith=void 0;const u=a.readInt8();t.options.randomizeOutputs=-1===u?void 0:1===u}else t.options=void 0;const l=await this.wallet.createAction(t,s),d=new Bt;if(null!=l.txid&&""!==l.txid?(d.writeInt8(1),d.write(Ot(l.txid,"hex"))):d.writeInt8(0),null!=l.tx?(d.writeInt8(1),d.writeVarIntNum(l.tx.length),d.write(l.tx)):d.writeInt8(0),null!=l.noSendChange){d.writeVarIntNum(l.noSendChange.length);for(const t of l.noSendChange)d.write(this.encodeOutpoint(t))}else d.writeVarIntNum(-1);if(null!=l.sendWithResults){d.writeVarIntNum(l.sendWithResults.length);for(const t of l.sendWithResults){let e;d.write(Ot(t.txid,"hex")),"unproven"===t.status?e=1:"sending"===t.status?e=2:"failed"===t.status&&(e=3),d.writeInt8(e)}}else d.writeVarIntNum(-1);if(null!=l.signableTransaction){d.writeInt8(1),d.writeVarIntNum(l.signableTransaction.tx.length),d.write(l.signableTransaction.tx);const t=Ot(l.signableTransaction.reference,"base64");d.writeVarIntNum(t.length),d.write(t)}else d.writeInt8(0);const f=new Bt;return f.writeUInt8(0),f.write(d.toArray()),f.toArray()}case"signAction":{const t={},e=a.readVarIntNum();t.spends={};for(let r=0;r<e;r++){const e=a.readVarIntNum(),r={},i=a.readVarIntNum(),n=a.read(i);r.unlockingScript=Nt(n);const s=a.readVarIntNum();r.sequenceNumber=s>=0?s:void 0,t.spends[e]=r}const r=a.readVarIntNum(),i=a.read(r);if(t.reference=_t(i),1===a.readInt8()){t.options={};const e=a.readInt8();t.options.acceptDelayedBroadcast=-1===e?void 0:1===e;const r=a.readInt8();t.options.returnTXIDOnly=-1===r?void 0:1===r;const i=a.readInt8();t.options.noSend=-1===i?void 0:1===i;const n=a.readVarIntNum();if(n>=0){t.options.sendWith=[];for(let e=0;e<n;e++){const e=a.read(32),r=Nt(e);t.options.sendWith.push(r)}}else t.options.sendWith=void 0}else t.options=void 0;const n=await this.wallet.signAction(t,s),o=new Bt;if(null!=n.txid&&""!==n.txid?(o.writeInt8(1),o.write(Ot(n.txid,"hex"))):o.writeInt8(0),null!=n.tx?(o.writeInt8(1),o.writeVarIntNum(n.tx.length),o.write(n.tx)):o.writeInt8(0),null!=n.sendWithResults){o.writeVarIntNum(n.sendWithResults.length);for(const t of n.sendWithResults){let e;o.write(Ot(t.txid,"hex")),"unproven"===t.status?e=1:"sending"===t.status?e=2:"failed"===t.status&&(e=3),o.writeInt8(e)}}else o.writeVarIntNum(-1);const c=new Bt;return c.writeUInt8(0),c.write(o.toArray()),c.toArray()}case"abortAction":{const t=_t(a.read());await this.wallet.abortAction({reference:t},s);const e=new Bt;return e.writeUInt8(0),e.toArray()}case"listActions":{const t={},e=a.readVarIntNum();t.labels=[];for(let r=0;r<e;r++){const e=a.readVarIntNum(),r=a.read(e);t.labels.push(Tt(r))}const r=a.readInt8();-1===r?t.labelQueryMode=void 0:1===r?t.labelQueryMode="any":2===r&&(t.labelQueryMode="all");const i=["includeLabels","includeInputs","includeInputSourceLockingScripts","includeInputUnlockingScripts","includeOutputs","includeOutputLockingScripts"];for(const e of i){const r=a.readInt8();t[e]=-1===r?void 0:1===r}const n=a.readVarIntNum();t.limit=n>=0?n:void 0;const o=a.readVarIntNum();t.offset=o>=0?o:void 0;const c=a.readInt8();t.seekPermission=c>=0?1===c:void 0;const h=await this.wallet.listActions(t,s),u=new Bt;u.writeVarIntNum(h.totalActions);for(const t of h.actions){let e;switch(u.write(Ot(t.txid,"hex")),u.writeVarIntNum(t.satoshis),t.status){case"completed":e=1;break;case"unprocessed":e=2;break;case"sending":e=3;break;case"unproven":e=4;break;case"unsigned":e=5;break;case"nosend":e=6;break;case"nonfinal":e=7;break;case"failed":e=8;break;default:e=-1}u.writeInt8(e),u.writeInt8(t.isOutgoing?1:0);const r=Ot(t.description,"utf8");if(u.writeVarIntNum(r.length),u.write(r),void 0!==t.labels){u.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=Ot(e,"utf8");u.writeVarIntNum(t.length),u.write(t)}}else u.writeVarIntNum(-1);if(u.writeVarIntNum(t.version),u.writeVarIntNum(t.lockTime),void 0!==t.inputs){u.writeVarIntNum(t.inputs.length);for(const e of t.inputs){if(u.write(this.encodeOutpoint(e.sourceOutpoint)),u.writeVarIntNum(e.sourceSatoshis),void 0!==e.sourceLockingScript){const t=Ot(e.sourceLockingScript,"hex");u.writeVarIntNum(t.length),u.write(t)}else u.writeVarIntNum(-1);if(void 0!==e.unlockingScript){const t=Ot(e.unlockingScript,"hex");u.writeVarIntNum(t.length),u.write(t)}else u.writeVarIntNum(-1);const t=Ot(e.inputDescription,"utf8");u.writeVarIntNum(t.length),u.write(t),u.writeVarIntNum(e.sequenceNumber)}}else u.writeVarIntNum(-1);if(void 0!==t.outputs){u.writeVarIntNum(t.outputs.length);for(const e of t.outputs){if(u.writeVarIntNum(e.outputIndex),u.writeVarIntNum(e.satoshis),void 0!==e.lockingScript){const t=Ot(e.lockingScript,"hex");u.writeVarIntNum(t.length),u.write(t)}else u.writeVarIntNum(-1);u.writeInt8(e.spendable?1:0);const t=Ot(e.outputDescription,"utf8");if(u.writeVarIntNum(t.length),u.write(t),void 0!==e.basket){const t=Ot(e.basket,"utf8");u.writeVarIntNum(t.length),u.write(t)}else u.writeVarIntNum(-1);if(void 0!==e.tags){u.writeVarIntNum(e.tags.length);for(const t of e.tags){const e=Ot(t,"utf8");u.writeVarIntNum(e.length),u.write(e)}}else u.writeVarIntNum(-1);if(void 0!==e.customInstructions){const t=Ot(e.customInstructions,"utf8");u.writeVarIntNum(t.length),u.write(t)}else u.writeVarIntNum(-1)}}else u.writeVarIntNum(-1)}const l=new Bt;return l.writeUInt8(0),l.write(u.toArray()),l.toArray()}case"internalizeAction":{const t={},e=a.readVarIntNum();t.tx=a.read(e);const r=a.readVarIntNum();t.outputs=[];for(let e=0;e<r;e++){const e={};e.outputIndex=a.readVarIntNum();const r=a.readUInt8();if(1===r){e.protocol="wallet payment",e.paymentRemittance={};const t=a.read(33);e.paymentRemittance.senderIdentityKey=Nt(t);const r=a.readVarIntNum(),i=a.read(r);e.paymentRemittance.derivationPrefix=_t(i);const n=a.readVarIntNum(),s=a.read(n);e.paymentRemittance.derivationSuffix=_t(s)}else if(2===r){e.protocol="basket insertion",e.insertionRemittance={};const t=a.readVarIntNum(),r=a.read(t);e.insertionRemittance.basket=Tt(r);const i=a.readVarIntNum();if(i>=0){const t=a.read(i);e.insertionRemittance.customInstructions=Tt(t)}const n=a.readVarIntNum();if(n>0){e.insertionRemittance.tags=[];for(let t=0;t<n;t++){const t=a.readVarIntNum(),r=a.read(t);e.insertionRemittance.tags.push(Tt(r))}}else e.insertionRemittance.tags=[]}t.outputs.push(e)}const i=a.readVarIntNum();if(i>=0){t.labels=[];for(let e=0;e<i;e++){const e=a.readVarIntNum();t.labels.push(Tt(a.read(e)))}}const n=a.readVarIntNum();t.description=Tt(a.read(n));const o=a.readInt8();t.seekPermission=o>=0?1===o:void 0,await this.wallet.internalizeAction(t,s);const c=new Bt;return c.writeUInt8(0),c.toArray()}case"listOutputs":{const t={},e=a.readVarIntNum(),r=a.read(e);t.basket=Tt(r);const i=a.readVarIntNum();if(i>0){t.tags=[];for(let e=0;e<i;e++){const e=a.readVarIntNum(),r=a.read(e);t.tags.push(Tt(r))}}else t.tags=void 0;const n=a.readInt8();t.tagQueryMode=1===n?"all":2===n?"any":void 0;const o=a.readInt8();t.include=1===o?"locking scripts":2===o?"entire transactions":void 0;const c=a.readInt8();t.includeCustomInstructions=-1===c?void 0:1===c;const h=a.readInt8();t.includeTags=-1===h?void 0:1===h;const u=a.readInt8();t.includeLabels=-1===u?void 0:1===u;const l=a.readVarIntNum();t.limit=l>=0?l:void 0;const d=a.readVarIntNum();t.offset=d>=0?d:void 0;const f=a.readInt8();t.seekPermission=f>=0?1===f:void 0;const p=await this.wallet.listOutputs(t,s),m=new Bt;m.writeVarIntNum(p.totalOutputs),null!=p.BEEF?(m.writeVarIntNum(p.BEEF.length),m.write(p.BEEF)):m.writeVarIntNum(-1);for(const t of p.outputs){if(m.write(this.encodeOutpoint(t.outpoint)),m.writeVarIntNum(t.satoshis),void 0!==t.lockingScript){const e=Ot(t.lockingScript,"hex");m.writeVarIntNum(e.length),m.write(e)}else m.writeVarIntNum(-1);if(void 0!==t.customInstructions){const e=Ot(t.customInstructions,"utf8");m.writeVarIntNum(e.length),m.write(e)}else m.writeVarIntNum(-1);if(void 0!==t.tags){m.writeVarIntNum(t.tags.length);for(const e of t.tags){const t=Ot(e,"utf8");m.writeVarIntNum(t.length),m.write(t)}}else m.writeVarIntNum(-1);if(void 0!==t.labels){m.writeVarIntNum(t.labels.length);for(const e of t.labels){const t=Ot(e,"utf8");m.writeVarIntNum(t.length),m.write(t)}}else m.writeVarIntNum(-1)}const w=new Bt;return w.writeUInt8(0),w.write(m.toArray()),w.toArray()}case"relinquishOutput":{const t={},e=a.readVarIntNum(),r=a.read(e);t.basket=Tt(r),t.output=this.decodeOutpoint(a),await this.wallet.relinquishOutput(t,s);const i=new Bt;return i.writeUInt8(0),i.toArray()}case"getPublicKey":{const t={},e=a.readUInt8();if(t.identityKey=1===e,!0!==t.identityKey){t.protocolID=this.decodeProtocolID(a),t.keyID=this.decodeString(a),t.counterparty=this.decodeCounterparty(a);const e=a.readInt8();t.privileged=-1===e?void 0:1===e;const r=a.readInt8();if(-1!==r){const e=a.read(r);t.privilegedReason=Tt(e)}else t.privilegedReason=void 0;const i=a.readInt8();t.forSelf=-1===i?void 0:1===i}else{const e=a.readInt8();t.privileged=-1===e?void 0:1===e;const r=a.readInt8();if(-1!==r){const e=a.read(r);t.privilegedReason=Tt(e)}else t.privilegedReason=void 0}const r=a.readInt8();t.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.getPublicKey(t,s),n=new Bt;n.writeUInt8(0);const o=Ot(i.publicKey,"hex");return n.write(o),n.toArray()}case"encrypt":{const t=this.decodeKeyRelatedParams(a),e=a.readVarIntNum();t.plaintext=a.read(e);const r=a.readInt8();t.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.encrypt(t,s),n=new Bt;return n.writeUInt8(0),n.write(i.ciphertext),n.toArray()}case"decrypt":{const t=this.decodeKeyRelatedParams(a),e=a.readVarIntNum();t.ciphertext=a.read(e);const r=a.readInt8();t.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.decrypt(t,s),n=new Bt;return n.writeUInt8(0),n.write(i.plaintext),n.toArray()}case"createHmac":{const t=this.decodeKeyRelatedParams(a),e=a.readVarIntNum();t.data=a.read(e);const r=a.readInt8();t.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.createHmac(t,s),n=new Bt;return n.writeUInt8(0),n.write(i.hmac),n.toArray()}case"verifyHmac":{const t=this.decodeKeyRelatedParams(a);t.hmac=a.read(32);const e=a.readVarIntNum();t.data=a.read(e);const r=a.readInt8();t.seekPermission=r>=0?1===r:void 0,await this.wallet.verifyHmac(t,s);const i=new Bt;return i.writeUInt8(0),i.toArray()}case"createSignature":{const t=this.decodeKeyRelatedParams(a),e=a.readUInt8();if(1===e){const e=a.readVarIntNum();t.data=a.read(e)}else 2===e&&(t.hashToDirectlySign=a.read(32));const r=a.readInt8();t.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.createSignature(t,s),n=new Bt;return n.writeUInt8(0),n.write(i.signature),n.toArray()}case"verifySignature":{const t=this.decodeKeyRelatedParams(a),e=a.readInt8();t.forSelf=-1===e?void 0:1===e;const r=a.readVarIntNum();t.signature=a.read(r);const i=a.readUInt8();if(1===i){const e=a.readVarIntNum();t.data=a.read(e)}else 2===i&&(t.hashToDirectlyVerify=a.read(32));const n=a.readInt8();t.seekPermission=n>=0?1===n:void 0,await this.wallet.verifySignature(t,s);const o=new Bt;return o.writeUInt8(0),o.toArray()}case"isAuthenticated":{const t=await this.wallet.isAuthenticated({},s),e=new Bt;return e.writeUInt8(0),e.writeUInt8(t.authenticated?1:0),e.toArray()}case"waitForAuthentication":{await this.wallet.waitForAuthentication({},s);const t=new Bt;return t.writeUInt8(0),t.toArray()}case"getHeight":{const t=await this.wallet.getHeight({},s),e=new Bt;return e.writeUInt8(0),e.writeVarIntNum(t.height),e.toArray()}case"getHeaderForHeight":{const t={};t.height=a.readVarIntNum();const e=await this.wallet.getHeaderForHeight(t,s),r=new Bt;r.writeUInt8(0);const i=Ot(e.header,"hex");return r.write(i),r.toArray()}case"getNetwork":{const t=await this.wallet.getNetwork({},s),e=new Bt;return e.writeUInt8(0),e.writeUInt8("mainnet"===t.network?0:1),e.toArray()}case"getVersion":{const t=await this.wallet.getVersion({},s),e=new Bt;e.writeUInt8(0);const r=Ot(t.version,"utf8");return e.write(r),e.toArray()}case"revealCounterpartyKeyLinkage":{const t={},e=a.readInt8();t.privileged=-1===e?void 0:1===e;const r=a.readInt8();if(-1===r)t.privilegedReason=void 0;else{const e=a.read(r);t.privilegedReason=Tt(e)}const i=a.read(33);t.counterparty=Nt(i);const n=a.read(33);t.verifier=Nt(n);const o=await this.wallet.revealCounterpartyKeyLinkage(t,s),c=new Bt;c.write(Ot(o.prover,"hex")),c.write(Ot(o.verifier,"hex")),c.write(Ot(o.counterparty,"hex"));const h=Ot(o.revelationTime,"utf8");c.writeVarIntNum(h.length),c.write(h),c.writeVarIntNum(o.encryptedLinkage.length),c.write(o.encryptedLinkage),c.writeVarIntNum(o.encryptedLinkageProof.length),c.write(o.encryptedLinkageProof);const u=new Bt;return u.writeUInt8(0),u.write(c.toArray()),u.toArray()}case"revealSpecificKeyLinkage":{const t=this.decodeKeyRelatedParams(a),e=a.read(33);t.verifier=Nt(e);const r=await this.wallet.revealSpecificKeyLinkage(t,s),i=new Bt;i.write(Ot(r.prover,"hex")),i.write(Ot(r.verifier,"hex")),i.write(Ot(r.counterparty,"hex")),i.writeUInt8(r.protocolID[0]);const n=Ot(r.protocolID[1],"utf8");i.writeVarIntNum(n.length),i.write(n);const o=Ot(r.keyID,"utf8");i.writeVarIntNum(o.length),i.write(o),i.writeVarIntNum(r.encryptedLinkage.length),i.write(r.encryptedLinkage),i.writeVarIntNum(r.encryptedLinkageProof.length),i.write(r.encryptedLinkageProof),i.writeUInt8(r.proofType);const c=new Bt;return c.writeUInt8(0),c.write(i.toArray()),c.toArray()}case"acquireCertificate":{const t={},e=a.read(32);t.type=_t(e);const r=a.read(33);t.certifier=Nt(r);const i=a.readVarIntNum();t.fields={};for(let e=0;e<i;e++){const e=a.readVarIntNum(),r=a.read(e),i=Tt(r),n=a.readVarIntNum(),s=a.read(n),o=Tt(s);t.fields[i]=o}const n=a.readInt8();t.privileged=-1===n?void 0:1===n;const o=a.readInt8();if(-1===o)t.privilegedReason=void 0;else{const e=a.read(o);t.privilegedReason=Tt(e)}const c=a.readUInt8();if(t.acquisitionProtocol=1===c?"direct":"issuance","direct"===t.acquisitionProtocol){const e=a.read(32);t.serialNumber=_t(e),t.revocationOutpoint=this.decodeOutpoint(a);const r=a.readVarIntNum(),i=a.read(r);t.signature=Nt(i);const n=a.readUInt8();if(11===n)t.keyringRevealer="certifier";else{const e=[n].concat(a.read(32));t.keyringRevealer=Nt(e)}const s=a.readVarIntNum();t.keyringForSubject={};for(let e=0;e<s;e++){const e=a.readVarIntNum(),r=a.read(e),i=Tt(r),n=a.readVarIntNum(),s=_t(a.read(n));t.keyringForSubject[i]=s}}else{const e=a.readVarIntNum(),r=a.read(e);t.certifierUrl=Tt(r)}const h=await this.wallet.acquireCertificate(t,s),u=new Kr(h.type,h.serialNumber,h.subject,h.certifier,h.revocationOutpoint,h.fields,h.signature).toBinary(),l=new Bt;return l.writeUInt8(0),l.write(u),l.toArray()}case"listCertificates":{const t={},e=a.readVarIntNum();t.certifiers=[];for(let r=0;r<e;r++){const e=a.read(33);t.certifiers.push(Nt(e))}const r=a.readVarIntNum();t.types=[];for(let e=0;e<r;e++){const e=a.read(32);t.types.push(_t(e))}const i=a.readVarIntNum();t.limit=i>=0?i:void 0;const n=a.readVarIntNum();t.offset=n>=0?n:void 0;const o=a.readInt8();t.privileged=-1===o?void 0:1===o;const c=a.readInt8();if(-1===c)t.privilegedReason=void 0;else{const e=a.read(c);t.privilegedReason=Tt(e)}const h=await this.wallet.listCertificates(t,s),u=new Bt;u.writeVarIntNum(h.totalCertificates);for(const t of h.certificates){const e=new Kr(t.type,t.serialNumber,t.subject,t.certifier,t.revocationOutpoint,t.fields,t.signature).toBinary();u.writeVarIntNum(e.length),u.write(e)}const l=new Bt;return l.writeUInt8(0),l.write(u.toArray()),l.toArray()}case"proveCertificate":{const t={},e={},r=a.read(32);e.type=_t(r);const i=a.read(33);e.subject=Nt(i);const n=a.read(32);e.serialNumber=_t(n);const o=a.read(33);e.certifier=Nt(o),e.revocationOutpoint=this.decodeOutpoint(a);const c=a.readVarIntNum(),h=a.read(c);e.signature=Nt(h);const u=a.readVarIntNum();e.fields={};for(let t=0;t<u;t++){const t=a.readVarIntNum(),r=a.read(t),i=Tt(r),n=a.readVarIntNum(),s=a.read(n),o=Tt(s);e.fields[i]=o}t.certificate=e;const l=a.readVarIntNum();t.fieldsToReveal=[];for(let e=0;e<l;e++){const e=a.readVarIntNum(),r=a.read(e),i=Tt(r);t.fieldsToReveal.push(i)}const d=a.read(33);t.verifier=Nt(d);const f=a.readInt8();t.privileged=-1===f?void 0:1===f;const p=a.readInt8();if(-1===p)t.privilegedReason=void 0;else{const e=a.read(p);t.privilegedReason=Tt(e)}const m=await this.wallet.proveCertificate(t,s),w=new Bt,b=Object.entries(m.keyringForVerifier);w.writeVarIntNum(b.length);for(const[t,e]of b){const r=Ot(t,"utf8");w.writeVarIntNum(r.length),w.write(r);const i=Ot(e,"base64");w.writeVarIntNum(i.length),w.write(i)}const g=new Bt;return g.writeUInt8(0),g.write(w.toArray()),g.toArray()}case"relinquishCertificate":{const t={},e=a.read(32);t.type=_t(e);const r=a.read(32);t.serialNumber=_t(r);const i=a.read(33);t.certifier=Nt(i),await this.wallet.relinquishCertificate(t,s);const n=new Bt;return n.writeUInt8(0),n.toArray()}case"discoverByIdentityKey":{const t={},e=a.read(33);t.identityKey=Nt(e);const r=a.readVarIntNum();t.limit=r>=0?r:void 0;const i=a.readVarIntNum();t.offset=i>=0?i:void 0;const n=a.readInt8();t.seekPermission=n>=0?1===n:void 0;const o=await this.wallet.discoverByIdentityKey(t,s),c=this.serializeDiscoveryResult(o),h=new Bt;return h.writeUInt8(0),h.write(c),h.toArray()}case"discoverByAttributes":{const t={},e=a.readVarIntNum();t.attributes={};for(let r=0;r<e;r++){const e=a.readVarIntNum(),r=a.read(e),i=Tt(r),n=a.readVarIntNum(),s=a.read(n),o=Tt(s);t.attributes[i]=o}const r=a.readVarIntNum();t.limit=r>=0?r:void 0;const i=a.readVarIntNum();t.offset=i>=0?i:void 0;const n=a.readInt8();t.seekPermission=n>=0?1===n:void 0;const o=await this.wallet.discoverByAttributes(t,s),c=this.serializeDiscoveryResult(o),h=new Bt;return h.writeUInt8(0),h.write(c),h.toArray()}default:throw new Error(`Method ${r} not implemented`)}}catch(t){const e=new Bt;e.writeUInt8("number"==typeof t.code?t.code:1);const r="string"==typeof t.message?t.message:"Unknown error",i=Ot(r,"utf8");e.writeVarIntNum(i.length),e.write(i);const n="string"==typeof t.stack?t.stack:"",s=Ot(n,"utf8");return e.writeVarIntNum(s.length),e.write(s),e.toArray()}}decodeProtocolID(t){const e=t.readUInt8(),r=t.readVarIntNum(),i=t.read(r);return[e,Tt(i)]}decodeString(t){const e=t.readVarIntNum(),r=t.read(e);return Tt(r)}decodeCounterparty(t){const e=t.readUInt8();if(11===e)return"self";if(12===e)return"anyone";if(0!==e){const r=t.read(32);return Nt([e,...r])}}serializeDiscoveryResult(t){const e=new Bt;e.writeVarIntNum(t.totalCertificates);for(const r of t.certificates){const t=new Kr(r.type,r.serialNumber,r.subject,r.certifier,r.revocationOutpoint,r.fields,r.signaturre).toBinary();e.writeVarIntNum(t.length),e.write(t);const i=Ot(r.certifierInfo.name,"utf8");e.writeVarIntNum(i.length),e.write(i);const n=Ot(r.certifierInfo.iconUrl,"utf8");e.writeVarIntNum(n.length),e.write(n);const s=Ot(r.certifierInfo.description,"utf8");e.writeVarIntNum(s.length),e.write(s),e.writeUInt8(r.certifierInfo.trust);const a=Object.entries(r.publiclyRevealedKeyring);e.writeVarIntNum(a.length);for(const[t,r]of a){const i=Ot(t,"utf8");e.writeVarIntNum(i.length),e.write(i);const n=Ot(r,"base64");e.writeVarIntNum(n.length),e.write(n)}const o=Object.entries(r.decryptedFields);e.writeVarIntNum(o.length);for(const[t,r]of o){const i=Ot(t,"utf8");e.writeVarIntNum(i.length),e.write(i);const n=Ot(r,"utf8");e.writeVarIntNum(n.length),e.write(n)}}return e.toArray()}decodeKeyRelatedParams(t){const e={};e.protocolID=this.decodeProtocolID(t);const r=t.readVarIntNum(),i=t.read(r);e.keyID=Tt(i),e.counterparty=this.decodeCounterparty(t);const n=t.readInt8();e.privileged=-1===n?void 0:1===n;const s=t.readInt8();if(-1===s)e.privilegedReason=void 0;else{const r=t.read(s);e.privilegedReason=Tt(r)}return e}}class Jr extends Kr{masterKeyring;constructor(t,e,r,i,n,s,a,o){super(t,e,r,i,n,s,o);for(const t of Object.keys(s))if(void 0===a[t]||""===a[t])throw new Error(`Master keyring must contain a value for every field. Missing or empty key for field: "${t}".`);this.masterKeyring=a}static async createCertificateFields(t,e,r,i,n){const s={},a={};for(const[o,c]of Object.entries(r)){const r=Pe.fromRandom(),h=r.encrypt(Ot(c,"utf8"));s[o]=_t(h);const{ciphertext:u}=await t.encrypt({plaintext:r.toArray(),...Kr.getCertificateFieldEncryptionDetails(o),counterparty:e,privileged:i,privilegedReason:n});a[o]=_t(u)}return{certificateFields:s,masterKeyring:a}}static async createKeyringForVerifier(t,e,r,i,n,s,a,o,c){if(!Array.isArray(n))throw new Error("fieldsToReveal must be an array of strings");const h={};for(const u of n){if(void 0===i[u]||null===i[u]||""===i[u])throw new Error(`Fields to reveal must be a subset of the certificate fields. Missing the "${u}" field.`);const n=(await this.decryptField(t,s,u,i[u],e,o,c)).fieldRevelationKey,{ciphertext:l}=await t.encrypt({plaintext:n,...Kr.getCertificateFieldEncryptionDetails(u,a),counterparty:r,privileged:o,privilegedReason:c});h[u]=_t(l)}return h}static async issueCertificateForSubject(t,e,r,i,n=async t=>"Certificate revocation not tracked.",s){const a=s??_t(Zt(32)),{certificateFields:o,masterKeyring:c}=await this.createCertificateFields(t,e,r),h=await n(a),u=new Jr(i,a,e,(await t.getPublicKey({identityKey:!0})).publicKey,h,o,c);return await u.sign(t),u}static async decryptFields(t,e,r,i,n,s){if(null==e||0===Object.keys(e).length)throw new Error("A MasterCertificate must have a valid masterKeyring!");try{const a={};for(const o of Object.keys(r))a[o]=(await this.decryptField(t,e,o,r[o],i,n,s)).decryptedFieldValue;return a}catch{throw new Error("Failed to decrypt all master certificate fields.")}}static async decryptField(t,e,r,i,n,s,a){if(null==e||0===Object.keys(e).length)throw new Error("A MasterCertificate must have a valid masterKeyring!");try{const{plaintext:o}=await t.decrypt({ciphertext:Ot(e[r],"base64"),...Kr.getCertificateFieldEncryptionDetails(r),counterparty:n,privileged:s,privilegedReason:a}),c=new Pe(o).decrypt(Ot(i,"base64"));return{fieldRevelationKey:o,decryptedFieldValue:Tt(c)}}catch{throw new Error("Failed to decrypt certificate field!")}}}class Zr extends Kr{keyring;decryptedFields;constructor(t,e,r,i,n,s,a,o,c){super(t,e,r,i,n,s,o),this.keyring=a,this.decryptedFields=c}static fromCertificate(t,e){return new Zr(t.type,t.serialNumber,t.subject,t.certifier,t.revocationOutpoint,t.fields,e,t.signature)}async decryptFields(t,e,r){if(null==this.keyring||0===Object.keys(this.keyring).length)throw new Error("A keyring is required to decrypt certificate fields for the verifier.");try{const i={};for(const n in this.keyring){const{plaintext:s}=await t.decrypt({ciphertext:Ot(this.keyring[n],"base64"),...Kr.getCertificateFieldEncryptionDetails(n,this.serialNumber),counterparty:this.subject,privileged:e,privilegedReason:r}),a=new Pe(s).decrypt(Ot(this.fields[n],"base64"));i[n]=Tt(a)}return i}catch(t){throw new Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(t instanceof Error?t.message:t)}`)}}}class Qr extends Cr{keyDeriver;constructor(t){if(super(t),t instanceof Fr)this.keyDeriver=t;else{if(!("string"==typeof t||t instanceof re))throw new Error("Invalid key deriver provided");this.keyDeriver=new Fr(t)}}async isAuthenticated(){throw new Error("not implemented")}async waitForAuthentication(){throw new Error("not implemented")}async getNetwork(){throw new Error("not implemented")}async getVersion(){throw new Error("not implemented")}async getPublicKey(t){if(!0===t.privileged)throw new Error("no privilege support");if(!0===t.identityKey){if(null===this.keyDeriver||void 0===this.keyDeriver)throw new Error("keyDeriver is not initialized");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==t.protocolID||"string"!=typeof t.keyID||""===t.keyID.trim())throw new Error("protocolID and keyID are required if identityKey is false or undefined.");if(null===this.keyDeriver||void 0===this.keyDeriver)throw new Error("keyDeriver is not initialized");return{publicKey:this.keyDeriver.derivePublicKey(t.protocolID,t.keyID,"string"==typeof t.counterparty&&""!==t.counterparty.trim()?t.counterparty:"self",Boolean(t.forSelf)).toString()}}async createAction(){throw new Error("not implemented")}async signAction(){throw new Error("not implemented")}async abortAction(){throw new Error("not implemented")}async listActions(){throw new Error("not implemented")}async internalizeAction(){throw new Error("not implemented")}async listOutputs(){throw new Error("not implemented")}async relinquishOutput(){throw new Error("not implemented")}async acquireCertificate(){throw new Error("not implemented")}async listCertificates(){throw new Error("not implemented")}async proveCertificate(){throw new Error("not implemented")}async relinquishCertificate(){throw new Error("not implemented")}async discoverByIdentityKey(){throw new Error("not implemented")}async discoverByAttributes(){throw new Error("not implemented")}async getHeight(){throw new Error("not implemented")}async getHeaderForHeight(){throw new Error("not implemented")}}class ti{sessionNonceToSession;identityKeyToNonces;constructor(){this.sessionNonceToSession=new Map,this.identityKeyToNonces=new Map}addSession(t){if("string"!=typeof t.sessionNonce)throw new Error("Invalid session: sessionNonce is required to add a session.");if(this.sessionNonceToSession.set(t.sessionNonce,t),"string"==typeof t.peerIdentityKey){let e=this.identityKeyToNonces.get(t.peerIdentityKey);null==e&&(e=new Set,this.identityKeyToNonces.set(t.peerIdentityKey,e)),e.add(t.sessionNonce)}}updateSession(t){this.removeSession(t),this.addSession(t)}getSession(t){const e=this.sessionNonceToSession.get(t);if(null!=e)return e;const r=this.identityKeyToNonces.get(t);if(null==r||0===r.size)return;let i;for(const t of r){const e=this.sessionNonceToSession.get(t);null!=e&&(null==i||(e.lastUpdate??0)>(i.lastUpdate??0))&&(i=e)}return i}removeSession(t){if("string"==typeof t.sessionNonce&&this.sessionNonceToSession.delete(t.sessionNonce),"string"==typeof t.peerIdentityKey){const e=this.identityKeyToNonces.get(t.peerIdentityKey);null!=e&&(e.delete(t.sessionNonce??""),0===e.size&&this.identityKeyToNonces.delete(t.peerIdentityKey))}}hasSession(t){if(this.sessionNonceToSession.has(t))return!0;const e=this.identityKeyToNonces.get(t);return!(null==e)&&e.size>0}}async function ei(t,e,r="self"){const i=Ot(t,"base64"),n=i.slice(0,16),s=i.slice(16),{valid:a}=await e.verifyHmac({data:n,hmac:s,protocolID:[2,"server hmac"],keyID:Tt(n),counterparty:r});return a}async function ri(t,e="self"){const r=Zt(16),{hmac:i}=await t.createHmac({protocolID:[2,"server hmac"],keyID:Tt(r),data:r,counterparty:e});return _t([...r,...i])}const ii=async(t,e,r)=>{const i=await t.listCertificates({certifiers:e.certifiers,types:Object.keys(e.types)});return await Promise.all(i.certificates.map((async i=>{const{keyringForVerifier:n}=await t.proveCertificate({certificate:i,fieldsToReveal:e.types[i.type],verifier:r});return new Zr(i.type,i.serialNumber,i.subject,i.certifier,i.revocationOutpoint,i.fields,n,i.signature)})))},ni=async(t,e,r)=>{if(null==e.certificates||0===e.certificates.length)throw new Error("No certificates were provided in the AuthMessage.");await Promise.all(e.certificates.map((async i=>{if(i.subject!==e.identityKey)throw new Error(`The subject of one of your certificates ("${i.subject}") is not the same as the request sender ("${e.identityKey}").`);const n=new Zr(i.type,i.serialNumber,i.subject,i.certifier,i.revocationOutpoint,i.fields,i.keyring,i.signature);if(!await n.verify())throw new Error(`The signature for the certificate with serial number ${n.serialNumber} is invalid!`);if(null!=r){const{certifiers:t,types:e}=r;if(!t.includes(n.certifier))throw new Error(`Certificate with serial number ${n.serialNumber} has an unrequested certifier: ${n.certifier}`);if(null==e[n.type])throw new Error(`Certificate with type ${n.type} was not requested`)}await n.decryptFields(t)})))},si="0.1";class ai{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;constructor(t,e,r,i,n){this.wallet=t,this.transport=e,this.certificatesToRequest=r??{certifiers:[],types:{}},this.transport.onData(this.handleIncomingMessage.bind(this)).catch((t=>{throw t})),this.sessionManager=null!=i?i:new ti,this.autoPersistLastSession=!1!==n}async toPeer(t,e,r){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof e&&(e=this.lastInteractedWithPeer);const i=await this.getAuthenticatedSession(e,r),n=_t(Zt(32)),{signature:s}=await this.wallet.createSignature({data:t,protocolID:[2,"auth message signature"],keyID:`${n} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey}),a={version:si,messageType:"general",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,nonce:n,yourNonce:i.peerNonce,payload:t,signature:s};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(a)}catch(t){const e=new Error(`Failed to send message to peer ${i.peerIdentityKey??"unknown"}: ${String(t.message)}`);throw e.stack=t.stack,e}}async requestCertificates(t,e,r=1e4){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof e&&(e=this.lastInteractedWithPeer);const i=await this.getAuthenticatedSession(e,r),n=_t(Zt(32)),{signature:s}=await this.wallet.createSignature({data:Ot(JSON.stringify(t),"utf8"),protocolID:[2,"auth message signature"],keyID:`${n} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey}),a={version:si,messageType:"certificateRequest",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,nonce:n,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,requestedCertificates:t,signature:s};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(a)}catch(t){throw new Error(`Failed to send certificate request message to peer ${i.peerIdentityKey??"unknown"}: ${String(t.message)}`)}}async getAuthenticatedSession(t,e){if(void 0===this.transport)throw new Error("Peer transport is not connected!");let r;if("string"==typeof t&&(r=this.sessionManager.getSession(t)),null==r||!r.isAuthenticated){const i=await this.initiateHandshake(t,e);if(r=this.sessionManager.getSession(i),null==r||!r.isAuthenticated)throw new Error("Unable to establish mutual authentication with peer!")}return r}listenForGeneralMessages(t){const e=this.callbackIdCounter++;return this.onGeneralMessageReceivedCallbacks.set(e,t),e}stopListeningForGeneralMessages(t){this.onGeneralMessageReceivedCallbacks.delete(t)}listenForCertificatesReceived(t){const e=this.callbackIdCounter++;return this.onCertificatesReceivedCallbacks.set(e,t),e}stopListeningForCertificatesReceived(t){this.onCertificatesReceivedCallbacks.delete(t)}listenForCertificatesRequested(t){const e=this.callbackIdCounter++;return this.onCertificateRequestReceivedCallbacks.set(e,t),e}stopListeningForCertificatesRequested(t){this.onCertificateRequestReceivedCallbacks.delete(t)}async initiateHandshake(t,e=1e4){const r=await ri(this.wallet),i=Date.now();this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:r,peerIdentityKey:t,lastUpdate:i});const n={version:si,messageType:"initialRequest",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,initialNonce:r,requestedCertificates:this.certificatesToRequest};return await this.transport.send(n),await this.waitForInitialResponse(r,e)}async waitForInitialResponse(t,e=1e4){return await new Promise(((r,i)=>{const n=this.listenForInitialResponse(t,(t=>{clearTimeout(s),this.stopListeningForInitialResponses(n),r(t)})),s=setTimeout((()=>{this.stopListeningForInitialResponses(n),i(new Error("Initial response timed out."))}),e)}))}listenForInitialResponse(t,e){const r=this.callbackIdCounter++;return this.onInitialResponseReceivedCallbacks.set(r,{callback:e,sessionNonce:t}),r}stopListeningForInitialResponses(t){this.onInitialResponseReceivedCallbacks.delete(t)}async handleIncomingMessage(t){if("string"!=typeof t.version||t.version!==si)throw new Error(`Invalid or unsupported message auth version! Received: ${t.version}, expected: ${si}`);switch(t.messageType){case"initialRequest":await this.processInitialRequest(t);break;case"initialResponse":await this.processInitialResponse(t);break;case"certificateRequest":await this.processCertificateRequest(t);break;case"certificateResponse":await this.processCertificateResponse(t);break;case"general":await this.processGeneralMessage(t);break;default:throw new Error(`Unknown message type of ${String(t.messageType)} from ${String(t.identityKey)}`)}}async processInitialRequest(t){if("string"!=typeof t.identityKey||"string"!=typeof t.initialNonce||""===t.initialNonce)throw new Error("Missing required fields in initialRequest message.");const e=await ri(this.wallet),r=Date.now();let i;this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:e,peerNonce:t.initialNonce,peerIdentityKey:t.identityKey,lastUpdate:r}),null!=t.requestedCertificates&&Array.isArray(t.requestedCertificates.certifiers)&&t.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach((e=>{e(t.identityKey,t.requestedCertificates)})):i=await ii(this.wallet,t.requestedCertificates,t.identityKey));const{signature:n}=await this.wallet.createSignature({data:Ot(t.initialNonce+e,"base64"),protocolID:[2,"auth message signature"],keyID:`${t.initialNonce} ${e}`,counterparty:t.identityKey}),s={version:si,messageType:"initialResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,initialNonce:e,yourNonce:t.initialNonce,certificates:i,requestedCertificates:this.certificatesToRequest,signature:n};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=t.identityKey),await this.transport.send(s)}async processInitialResponse(t){if(!await ei(t.yourNonce,this.wallet))throw new Error(`Initial response nonce verification failed from peer: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Peer session not found for peer: ${t.identityKey}`);const r=Ot((e.sessionNonce??"")+(t.initialNonce??""),"base64"),{valid:i}=await this.wallet.verifySignature({data:r,signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${e.sessionNonce??""} ${t.initialNonce??""}`,counterparty:t.identityKey});if(!i)throw new Error(`Unable to verify initial response signature for peer: ${t.identityKey}`);if(e.peerNonce=t.initialNonce,e.peerIdentityKey=t.identityKey,e.isAuthenticated=!0,e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),this.certificatesToRequest?.certifiers?.length>0&&t.certificates?.length>0&&(await ni(this.wallet,t,this.certificatesToRequest),this.onCertificatesReceivedCallbacks.forEach((e=>e(t.identityKey,t.certificates)))),this.lastInteractedWithPeer=t.identityKey,this.onInitialResponseReceivedCallbacks.forEach((t=>{t.sessionNonce===e.sessionNonce&&t.callback(e.sessionNonce)})),null!=t.requestedCertificates&&Array.isArray(t.requestedCertificates.certifiers)&&t.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach((e=>{e(t.identityKey,t.requestedCertificates)}));else{const e=await ii(this.wallet,t.requestedCertificates,t.identityKey);await this.sendCertificateResponse(t.identityKey,e)}}async processCertificateRequest(t){if(!await ei(t.yourNonce,this.wallet))throw new Error(`Unable to verify nonce for certificate request message from: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Session not found for nonce: ${t.yourNonce}`);const{valid:r}=await this.wallet.verifySignature({data:Ot(JSON.stringify(t.requestedCertificates),"utf8"),signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:e.peerIdentityKey});if(!r)throw new Error(`Invalid signature in certificate request message from ${e.peerIdentityKey}`);if(e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),null!=t.requestedCertificates&&Array.isArray(t.requestedCertificates.certifiers)&&t.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach((e=>{e(t.identityKey,t.requestedCertificates)}));else{const e=await ii(this.wallet,t.requestedCertificates,t.identityKey);await this.sendCertificateResponse(t.identityKey,e)}}async sendCertificateResponse(t,e){const r=await this.getAuthenticatedSession(t),i=_t(Zt(32)),{signature:n}=await this.wallet.createSignature({data:Ot(JSON.stringify(e),"utf8"),protocolID:[2,"auth message signature"],keyID:`${i} ${r.peerNonce??""}`,counterparty:r.peerIdentityKey}),s={version:si,messageType:"certificateResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,nonce:i,initialNonce:r.sessionNonce,yourNonce:r.peerNonce,certificates:e,signature:n};r.lastUpdate=Date.now(),this.sessionManager.updateSession(r);try{await this.transport.send(s)}catch(t){const e=t instanceof Error?t.message:String(t);throw new Error(`Failed to send certificate response message to peer ${r.peerIdentityKey??"unknown"}: ${e}`)}}async processCertificateResponse(t){if(!await ei(t.yourNonce,this.wallet))throw new Error(`Unable to verify nonce for certificate response from: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Session not found for nonce: ${t.yourNonce}`);const{valid:r}=await this.wallet.verifySignature({data:Ot(JSON.stringify(t.certificates),"utf8"),signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:t.identityKey});if(!r)throw new Error(`Unable to verify certificate response signature for peer: ${t.identityKey}`);await ni(this.wallet,t,t.requestedCertificates),this.onCertificatesReceivedCallbacks.forEach((e=>{e(t.identityKey,t.certificates??[])})),e.lastUpdate=Date.now(),this.sessionManager.updateSession(e)}async processGeneralMessage(t){if(!await ei(t.yourNonce,this.wallet))throw new Error(`Unable to verify nonce for general message from: ${t.identityKey}`);const e=this.sessionManager.getSession(t.yourNonce);if(null==e)throw new Error(`Session not found for nonce: ${t.yourNonce}`);const{valid:r}=await this.wallet.verifySignature({data:t.payload,signature:t.signature,protocolID:[2,"auth message signature"],keyID:`${t.nonce??""} ${e.sessionNonce??""}`,counterparty:e.peerIdentityKey});if(!r)throw new Error(`Invalid signature in generalMessage from ${e.peerIdentityKey}`);e.lastUpdate=Date.now(),this.sessionManager.updateSession(e),this.lastInteractedWithPeer=t.identityKey,this.onGeneralMessageReceivedCallbacks.forEach((e=>{e(t.identityKey,t.payload??[])}))}}const oi="undefined"!=typeof window?fetch.bind(window):fetch;class ci{onDataCallback;fetchClient;baseUrl;constructor(t,e=oi){this.fetchClient=e,this.baseUrl=t}async send(t){if(!this.onDataCallback)throw new Error("Listen before you start speaking. God gave you two ears and one mouth for a reason.");if("general"!==t.messageType)return new Promise((async(e,r)=>{try{const r=this.fetchClient(`${this.baseUrl}/.well-known/auth`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});"initialRequest"!==t.messageType&&e();const i=await r;if(!i.ok||!this.onDataCallback)throw new Error("HTTP server failed to authenticate");{const t=await i.json();this.onDataCallback(t)}"initialRequest"===t.messageType&&e()}catch(t){return void r(t)}}));{const e=this.deserializeRequestPayload(t.payload),r=`${this.baseUrl}${e.urlPostfix}`;let i=e;if("object"!=typeof e.headers&&(i.headers={}),i.headers["x-bsv-auth-version"]=t.version,i.headers["x-bsv-auth-identity-key"]=t.identityKey,i.headers["x-bsv-auth-nonce"]=t.nonce,i.headers["x-bsv-auth-your-nonce"]=t.yourNonce,i.headers["x-bsv-auth-signature"]=Nt(t.signature),i.headers["x-bsv-auth-request-id"]=e.requestId,i.body){const t=i.headers;if(!t["content-type"])throw new Error("Content-Type header is required for requests with a body.");const e=t["content-type"];e.includes("application/json")||e.includes("application/x-www-form-urlencoded")||e.includes("text/plain")?i.body=Tt(i.body):i.body=new Uint8Array(i.body)}const n=await this.fetchClient(r,{method:i.method,headers:i.headers,body:i.body});if(500===n.status&&!n.headers.get("x-bsv-auth-request-id")){const t=await n.json();throw new Error(`HTTP ${n.status} - ${JSON.stringify(t)}`)}const s=await n.arrayBuffer(),a=new Bt;a.write(Ot(n.headers.get("x-bsv-auth-request-id"),"base64")),a.writeVarIntNum(n.status);const o=[];n.headers.forEach(((t,e)=>{const r=e.toLowerCase();!r.startsWith("x-bsv-")&&"authorization"!==r||r.startsWith("x-bsv-auth")||o.push([r,t])})),o.sort((([t],[e])=>t.localeCompare(e))),a.writeVarIntNum(o.length);for(let t=0;t<o.length;t++){const e=Ot(o[t][0],"utf8");a.writeVarIntNum(e.length),a.write(e);const r=Ot(o[t][1],"utf8");a.writeVarIntNum(r.length),a.write(r)}if(s){const t=Array.from(new Uint8Array(s));a.writeVarIntNum(t.length),a.write(t)}else a.writeVarIntNum(-1);const c={version:n.headers.get("x-bsv-auth-version"),messageType:"certificateRequest"===n.headers.get("x-bsv-auth-message-type")?"certificateRequest":"general",identityKey:n.headers.get("x-bsv-auth-identity-key"),nonce:n.headers.get("x-bsv-auth-nonce"),yourNonce:n.headers.get("x-bsv-auth-your-nonce"),requestedCertificates:JSON.parse(n.headers.get("x-bsv-auth-requested-certificates")),payload:a.toArray(),signature:Ot(n.headers.get("x-bsv-auth-signature"),"hex")};if(!c.version)throw new Error("HTTP server failed to authenticate");this.onDataCallback(c)}}async onData(t){this.onDataCallback=e=>{t(e)}}deserializeRequestPayload(t){const e=new Ut(t),r=_t(e.read(32)),i=e.readVarIntNum();let n="GET";i>0&&(n=Tt(e.read(i)));const s=e.readVarIntNum();let a="";s>0&&(a=Tt(e.read(s)));const o=e.readVarIntNum();let c="";o>0&&(c=Tt(e.read(o)));const h={},u=e.readVarIntNum();if(u>0)for(let t=0;t<u;t++){const t=e.readVarIntNum(),r=e.read(t),i=Tt(r),n=e.readVarIntNum(),s=e.read(n),a=Tt(s);h[i]=a}let l;const d=e.readVarIntNum();return d>0&&(l=e.read(d)),{urlPostfix:a+c,method:n,headers:h,body:l,requestId:r}}}class hi{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;peers={};constructor(t,e,r){this.wallet=t,this.requestedCertificates=e,this.sessionManager=r||new ti}async fetch(t,e={}){if("number"==typeof e.retryCounter){if(e.retryCounter<=0)throw new Error("Request failed after maximum number of retries.");e.retryCounter--}const r=await new Promise((async(r,i)=>{try{const{method:n="GET",headers:s={},body:a}=e,o=new URL(t),c=o.origin;let h;if(void 0===this.peers[c]){const t=new ci(c);h={peer:new ai(this.wallet,t,this.requestedCertificates,this.sessionManager),pendingCertificateRequests:[]},this.peers[c]=h,this.peers[c].peer.listenForCertificatesReceived(((t,e)=>{this.certificatesReceived.push(...e)})),this.peers[c].peer.listenForCertificatesRequested((async(t,e)=>{try{this.peers[c].pendingCertificateRequests.push(!0);const r=await ii(this.wallet,e,t);await this.peers[c].peer.sendCertificateResponse(t,r)}finally{await new Promise((t=>setTimeout(t,500))),this.peers[c].pendingCertificateRequests.shift()}}))}else{if(!1===this.peers[c].supportsMutualAuth){try{const i=await this.handleFetchAndValidate(t,e,this.peers[c]);r(i)}catch(t){i(t)}return}h=this.peers[c]}const u=Zt(32),l=_t(u),d=await this.serializeRequest(n,s,a,o,u);this.callbacks[l]={resolve:r,reject:i};const f=h.peer.listenForGeneralMessages(((t,e)=>{const r=new Ut(e);if(_t(r.read(32))!==l)return;h.peer.stopListeningForGeneralMessages(f),this.peers[c].identityKey=t,this.peers[c].supportsMutualAuth=!0;const i=r.readVarIntNum(),n={},s=r.readVarIntNum();if(s>0)for(let t=0;t<s;t++){const t=r.readVarIntNum(),e=r.read(t),i=Tt(e),s=r.readVarIntNum(),a=r.read(s),o=Tt(a);n[i]=o}let a;n["x-bsv-auth-identity-key"]=t;const o=r.readVarIntNum();o>0&&(a=r.read(o));const u=new Response(a?new Uint8Array(a):null,{status:i,statusText:`${i}`,headers:new Headers(n)});this.callbacks[l].resolve(u),delete this.callbacks[l]}));h.pendingCertificateRequests.length>0&&await new Promise((t=>{setInterval((()=>{0===h.pendingCertificateRequests.length&&t()}),100)})),await h.peer.toPeer(d.toArray(),h.identityKey).catch((async n=>{if(n.message.includes("Session not found for nonce")){delete this.peers[c],e.retryCounter??=3;const i=await this.fetch(t,e);r(i)}else if(n.message.includes("HTTP server failed to authenticate"))try{const i=await this.handleFetchAndValidate(t,e,h);return void r(i)}catch(t){i(t)}else i(n)}))}catch(t){i(t)}}));return 402===r.status?await this.handlePaymentAndRetry(t,e,r):r}async sendCertificateRequest(t,e){const r=new URL(t).origin;let i;if(void 0!==this.peers[r])i={peer:this.peers[r].peer};else{const t=new ci(r);i={peer:new ai(this.wallet,t,this.requestedCertificates,this.sessionManager)},this.peers[r]=i}return await new Promise((async(t,r)=>{const n=i.peer.listenForCertificatesReceived(((e,r)=>{i.peer.stopListeningForCertificatesReceived(n),this.certificatesReceived.push(...r),t(r)}));try{await i.peer.requestCertificates(e,i.identityKey)}catch(t){i.peer.stopListeningForCertificatesReceived(n),r(t)}}))}consumeReceivedCertificates(){return this.certificatesReceived.splice(0)}async serializeRequest(t,e,r,i,n){const s=new Bt;if(s.write(n),s.writeVarIntNum(t.length),s.write(Ot(t)),i.pathname.length>0){const t=Ot(i.pathname);s.writeVarIntNum(t.length),s.write(t)}else s.writeVarIntNum(-1);if(i.search.length>0){const t=Ot(i.search);s.writeVarIntNum(t.length),s.write(t)}else s.writeVarIntNum(-1);const a=[];for(let[t,r]of Object.entries(e))if(t=t.toLowerCase(),t.startsWith("x-bsv-")||"authorization"===t){if(t.startsWith("x-bsv-auth"))throw new Error("No BSV auth headers allowed here!");a.push([t,r])}else{if(!t.startsWith("content-type"))throw new Error("Unsupported header in the simplified fetch implementation. Only content-type, authorization, and x-bsv-* headers are supported.");r=r.split(";")[0].trim(),a.push([t,r])}a.sort((([t],[e])=>t.localeCompare(e))),s.writeVarIntNum(a.length);for(let t=0;t<a.length;t++){const e=Ot(a[t][0],"utf8");s.writeVarIntNum(e.length),s.write(e);const r=Ot(a[t][1],"utf8");s.writeVarIntNum(r.length),s.write(r)}if(["POST","PUT","PATCH","DELETE"].includes(t.toUpperCase())&&void 0===r){const t=a.find((([t])=>"content-type"===t));r=t&&t[1].includes("application/json")?"{}":""}if(r){const t=await this.normalizeBodyToNumberArray(r);s.writeVarIntNum(t.length),s.write(t)}else s.writeVarIntNum(-1);return s}async handleFetchAndValidate(t,e,r){const i=await fetch(t,e);if(i.headers.forEach((t=>{if(t.toLocaleLowerCase().startsWith("x-bsv"))throw new Error("The server is trying to claim it has been authenticated when it has not!")})),i.ok)return r.supportsMutualAuth=!1,i;throw new Error(`Request failed with status: ${i.status}`)}async handlePaymentAndRetry(t,e={},r){const i=r.headers.get("x-bsv-payment-version");if(!i||"1.0"!==i)throw new Error(`Unsupported x-bsv-payment-version response header. Client version: 1.0, Server version: ${i}`);const n=r.headers.get("x-bsv-payment-satoshis-required");if(!n)throw new Error("Missing x-bsv-payment-satoshis-required response header.");const s=parseInt(n);if(isNaN(s)||s<=0)throw new Error("Invalid x-bsv-payment-satoshis-required response header value.");const a=r.headers.get("x-bsv-auth-identity-key");if(!a)throw new Error("Missing x-bsv-auth-identity-key response header.");const o=r.headers.get("x-bsv-payment-derivation-prefix");if("string"!=typeof o||o.length<1)throw new Error("Missing x-bsv-payment-derivation-prefix response header.");const c=await ri(this.wallet),{publicKey:h}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${o} ${c}`,counterparty:a}),u=(new Ve).lock(Gt.fromString(h).toAddress()).toHex(),{tx:l}=await this.wallet.createAction({description:`Payment for request to ${new URL(t).origin}`,outputs:[{satoshis:s,lockingScript:u,customInstructions:JSON.stringify({derivationPrefix:o,derivationSuffix:c,payee:a}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}});return e.headers=e.headers||{},e.headers["x-bsv-payment"]=JSON.stringify({derivationPrefix:o,derivationSuffix:c,transaction:_t(l)}),e.retryCounter??=3,this.fetch(t,e)}async normalizeBodyToNumberArray(t){if(null==t)return[];if("object"==typeof t)return Ot(JSON.stringify(t,"utf8"));if(Array.isArray(t)&&t.every((t=>"number"==typeof t)))return t;if("string"==typeof t)return Ot(t,"utf8");if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)){const e=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer);return Array.from(e)}if(t instanceof Blob){const e=await t.arrayBuffer();return Array.from(new Uint8Array(e))}if(t instanceof FormData){const e=[];t.forEach(((t,r)=>{e.push([r,t.toString()])}));const r=new URLSearchParams(e).toString();return Ot(r,"utf8")}if(t instanceof URLSearchParams)return Ot(t.toString(),"utf8");if(t instanceof ReadableStream)throw new Error("ReadableStream cannot be directly converted to number[].");throw new Error("Unsupported body type in this SimplifiedFetch implementation.")}}class ui{pushDrop;static decode(t){const e=Ue.decode(t);if(e.fields.length<4)throw new Error("Invalid SHIP/SLAP advertisement!");const r=Tt(e.fields[0]);if("SHIP"!==r&&"SLAP"!==r)throw new Error("Invalid protocol type!");return{protocol:r,identityKey:Nt(e.fields[1]),domain:Tt(e.fields[2]),topicOrService:Tt(e.fields[3])}}constructor(t){this.pushDrop=new Ue(t)}async lock(t,e,r){const{publicKey:i}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([Ot(t,"utf8"),Ot(i,"hex"),Ot(e,"utf8"),Ot(r,"utf8")],[2,"SHIP"===t?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}unlock(t){return this.pushDrop.unlock([2,"SHIP"===t?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}}const li=["https://users.bapp.dev"],di=["https://testnet-users.bapp.dev"];class fi{fetchClient;allowHTTP;constructor(t=fetch,e=!1){this.fetchClient=t,this.allowHTTP=e}async lookup(t,e,r=5e3){if(!t.startsWith("https:")&&!this.allowHTTP)throw new Error('HTTPS facilitator can only use URLs that start with "https:"');const i=new Promise(((t,e)=>setTimeout((()=>e(new Error("Request timed out"))),r))),n=fetch(`${t}/lookup`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:e.service,query:e.query})}),s=await Promise.race([n,i]);if(s.ok)return await s.json();throw new Error("Failed to facilitate lookup")}}class pi{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;constructor(t={}){this.networkPreset=t.networkPreset??"mainnet",this.facilitator=t.facilitator??new fi(void 0,"local"===this.networkPreset),this.slapTrackers=t.slapTrackers??("mainnet"===this.networkPreset?li:di),this.hostOverrides=t.hostOverrides??{},this.additionalHosts=t.additionalHosts??{}}async query(t,e){let r=[];if(r="ls_slap"===t.service?"local"===this.networkPreset?["http://localhost:8080"]:this.slapTrackers:null!=this.hostOverrides[t.service]?this.hostOverrides[t.service]:"local"===this.networkPreset?["http://localhost:8080"]:await this.findCompetentHosts(t.service),this.additionalHosts[t.service]?.length>0&&(r=[...r,...this.additionalHosts[t.service]]),r.length<1)throw new Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${t.service}`);const i=(await Promise.allSettled(r.map((async r=>await this.facilitator.lookup(r,t,e))))).filter((t=>"fulfilled"===t.status)).map((t=>t.value));if(0===i.length)throw new Error("No successful responses from any hosts");if("freeform"===i[0].type)return i[0];const n=new Map;for(const t of i)if("output-list"===t.type)try{for(const e of t.outputs)try{const t=String(ir.fromBEEF(e.beef).id("hex"));if(""!==t){const r=`${String(t)}.${String(e.outputIndex)}`;n.set(r,e)}else console.warn("Invalid transaction ID:",t)}catch{continue}}catch(t){}return{type:"output-list",outputs:Array.from(n.values())}}async findCompetentHosts(t){const e={service:"ls_slap",query:{service:t}},r=await Promise.allSettled(this.slapTrackers.map((async t=>await this.facilitator.lookup(t,e,5e3)))),i=new Set;for(const e of r)if("fulfilled"===e.status){const r=e.value;if("output-list"!==r.type)continue;for(const e of r.outputs)try{const r=ir.fromBEEF(e.beef).outputs[e.outputIndex].lockingScript,n=ui.decode(r);if(n.topicOrService!==t||"SLAP"!==n.protocol)continue;i.add(n.domain)}catch{continue}}return[...i]}}class mi{httpClient;allowHTTP;constructor(t=fetch,e=!1){this.httpClient=t,this.allowHTTP=e}async send(t,e){if(console.log(t),!t.startsWith("https:")&&!this.allowHTTP)throw new Error('HTTPS facilitator can only use URLs that start with "https:"');const r=await fetch(`${t}/submit`,{method:"POST",headers:{"Content-Type":"application/octet-stream","X-Topics":JSON.stringify(e.topics)},body:new Uint8Array(e.beef)});if(r.ok)return await r.json();throw new Error("Failed to facilitate broadcast")}}class wi{topics;facilitator;resolver;requireAcknowledgmentFromAllHostsForTopics;requireAcknowledgmentFromAnyHostForTopics;requireAcknowledgmentFromSpecificHostsForTopics;networkPreset;constructor(t,e={}){if(0===t.length)throw new Error("At least one topic is required for broadcast.");if(t.some((t=>!t.startsWith("tm_"))))throw new Error('Every topic must start with "tm_".');this.topics=t,this.networkPreset=e.networkPreset??"mainnet",this.facilitator=e.facilitator??new mi(void 0,"local"===this.networkPreset),this.resolver=e.resolver??new pi({networkPreset:this.networkPreset}),this.requireAcknowledgmentFromAllHostsForTopics=e.requireAcknowledgmentFromAllHostsForTopics??[],this.requireAcknowledgmentFromAnyHostForTopics=e.requireAcknowledgmentFromAnyHostForTopics??"all",this.requireAcknowledgmentFromSpecificHostsForTopics=e.requireAcknowledgmentFromSpecificHostsForTopics??{}}async broadcast(t){let e;console.log(t);try{e=t.toBEEF()}catch(t){throw new Error("Transactions sent via SHIP to Overlay Services must be serializable to BEEF format.")}const r=await this.findInterestedHosts();if(console.log(r),0===Object.keys(r).length)return{status:"error",code:"ERR_NO_HOSTS_INTERESTED",description:`No ${this.networkPreset} hosts are interested in receiving this transaction.`};const i=Object.entries(r).map((async([t,r])=>{try{const i=await this.facilitator.send(t,{beef:e,topics:[...r]});if(null==i||0===Object.keys(i).length)throw new Error("Steak has no topics.");return{host:t,success:!0,steak:i}}catch(e){return console.error(e),{host:t,success:!1,error:e}}})),n=(await Promise.all(i)).filter((t=>t.success));if(0===n.length)return{status:"error",code:"ERR_ALL_HOSTS_REJECTED",description:`All ${this.networkPreset} topical hosts have rejected the transaction.`};const s={};for(const t of n){const e=t.host,r=t.steak,i=new Set;for(const[t,e]of Object.entries(r)){const r=e.outputsToAdmit,n=e.coinsToRetain,s=e.coinsRemoved;(r?.length>0||n?.length>0||s?.length>0)&&i.add(t)}s[e]=i}let a,o,c,h;return"all"===this.requireAcknowledgmentFromAllHostsForTopics?(a=this.topics,o="all"):"any"===this.requireAcknowledgmentFromAllHostsForTopics?(a=this.topics,o="any"):Array.isArray(this.requireAcknowledgmentFromAllHostsForTopics)?(a=this.requireAcknowledgmentFromAllHostsForTopics,o="all"):(a=this.topics,o="all"),a.length>0&&!this.checkAcknowledgmentFromAllHosts(s,a,o)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ALL_HOSTS_FAILED",description:"Not all hosts acknowledged the required topics."}:("all"===this.requireAcknowledgmentFromAnyHostForTopics?(c=this.topics,h="all"):"any"===this.requireAcknowledgmentFromAnyHostForTopics?(c=this.topics,h="any"):Array.isArray(this.requireAcknowledgmentFromAnyHostForTopics)?(c=this.requireAcknowledgmentFromAnyHostForTopics,h="all"):(c=[],h="all"),c.length>0&&!this.checkAcknowledgmentFromAnyHost(s,c,h)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ANY_HOST_FAILED",description:"No host acknowledged the required topics."}:Object.keys(this.requireAcknowledgmentFromSpecificHostsForTopics).length>0&&!this.checkAcknowledgmentFromSpecificHosts(s,this.requireAcknowledgmentFromSpecificHostsForTopics)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_SPECIFIC_HOSTS_FAILED",description:"Specific hosts did not acknowledge the required topics."}:{status:"success",txid:t.id("hex"),message:`Sent to ${n.length} Overlay Services ${1===n.length?"host":"hosts"}.`})}checkAcknowledgmentFromAllHosts(t,e,r){for(const i of Object.values(t))if("all"===r){for(const t of e)if(!i.has(t))return!1}else if("any"===r){let t=!1;for(const r of e)if(i.has(r)){t=!0;break}if(!t)return!1}return!0}checkAcknowledgmentFromAnyHost(t,e,r){if("all"===r){for(const r of Object.values(t)){let t=!0;for(const i of e)if(!r.has(i)){t=!1;break}if(t)return!0}return!1}for(const r of Object.values(t))for(const t of e)if(r.has(t))return!0;return!1}checkAcknowledgmentFromSpecificHosts(t,e){for(const[r,i]of Object.entries(e)){const e=t[r];if(null==e)return!1;let n,s;if("all"===i||"any"===i)s=i,n=this.topics;else{if(!Array.isArray(i))continue;n=i,s="all"}if("all"===s){for(const t of n)if(!e.has(t))return!1}else if("any"===s){let t=!1;for(const r of n)if(e.has(r)){t=!0;break}if(!t)return!1}}return!0}async findInterestedHosts(){if("local"===this.networkPreset){const t=new Set;for(let e=0;e<this.topics.length;e++)t.add(this.topics[e]);return{"http://localhost:8080":t}}const t={},e=await this.resolver.query({service:"ls_ship",query:{topics:this.topics}},5e3);if("output-list"!==e.type)throw new Error("SHIP answer is not an output list.");for(const r of e.outputs)try{const e=ir.fromBEEF(r.beef).outputs[r.outputIndex].lockingScript,i=ui.decode(e);if(!this.topics.includes(i.topicOrService)||"SHIP"!==i.protocol)continue;void 0===t[i.domain]&&(t[i.domain]=new Set),t[i.domain].add(i.topicOrService)}catch(t){continue}return t}}const bi=t=>(t.toLowerCase().startsWith("uhrp:")&&(t=t.slice(5)),t.startsWith("//")&&(t=t.slice(2)),t),gi=t=>{if(32!==t.length)throw new Error("Hash length must be 32 bytes (sha256)");return Vt(t,Ot("ce00","hex"))},yi=t=>{const e=gt(t);return gi(e)},vi=t=>{t=bi(t);const{data:e,prefix:r}=Dt(t,void 0,2);if(32!==e.length)throw new Error("Invalid length!");if("ce00"!==Nt(r))throw new Error("Bad prefix");return e},Ii=t=>{try{return vi(t),!0}catch(t){return!1}};class ki{authFetch;baseURL;constructor(t){this.baseURL=t.storageURL,this.authFetch=new hi(t.wallet)}async getUploadInfo(t,e){const r=`${this.baseURL}/upload`,i={fileSize:t,retentionPeriod:e},n=await this.authFetch.fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!n.ok)throw new Error(`Upload info request failed: HTTP ${n.status}`);const s=await n.json();if("error"===s.status)throw new Error("Upload route returned an error.");return{uploadURL:s.uploadURL,requiredHeaders:s.requiredHeaders,amount:s.amount}}async uploadFile(t,e,r){const i=Uint8Array.from(e.data),n=await fetch(t,{method:"PUT",body:i,headers:{"Content-Type":e.type,...r}});if(!n.ok)throw new Error(`File upload failed: HTTP ${n.status}`);return{published:!0,uhrpURL:await yi(e.data)}}async publishFile(t){const{file:e,retentionPeriod:r}=t,i=e.data.length,{uploadURL:n,requiredHeaders:s}=await this.getUploadInfo(i,r);return await this.uploadFile(n,e,s)}async findFile(t){const e=new URL(`${this.baseURL}/find`);e.searchParams.set("uhrpUrl",t);const r=await this.authFetch.fetch(e.toString(),{method:"GET"});if(!r.ok)throw new Error(`findFile request failed: HTTP ${r.status}`);const i=await r.json();if("error"===i.status){const t=i.code??"unknown-code",e=i.description??"no-description";throw new Error(`findFile returned an error: ${t} - ${e}`)}return i.data}async listUploads(){const t=`${this.baseURL}/list`,e=await this.authFetch.fetch(t,{method:"GET"});if(!e.ok)throw new Error(`listUploads request failed: HTTP ${e.status}`);const r=await e.json();if("error"===r.status){const t=r.code??"unknown-code",e=r.description??"no-description";throw new Error(`listUploads returned an error: ${t} - ${e}`)}return r.uploads}async renewFile(t,e){const r=`${this.baseURL}/renew`,i={uhrpUrl:t,additionalMinutes:e},n=await this.authFetch.fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!n.ok)throw new Error(`renewFile request failed: HTTP ${n.status}`);const s=await n.json();if("error"===s.status){const t=s.code??"unknown-code",e=s.description??"no-description";throw new Error(`renewFile returned an error: ${t} - ${e}`)}return{status:s.status,prevExpiryTime:s.prevExpiryTime,newExpiryTime:s.newExpiryTime,amount:s.amount}}}class Pi{networkPreset="mainnet";constructor(t){this.networkPreset=t?.networkPreset}async resolve(t){const e=new pi({networkPreset:this.networkPreset}),r=await e.query({service:"ls_uhrp",query:{uhrpUrl:t}});if("output-list"!==r.type)throw new Error("Lookup answer must be an output list");const i=[],n=Math.floor(Date.now()/1e3);for(let t=0;t<r.outputs.length;t++){const e=ir.fromBEEF(r.outputs[t].beef),{fields:s}=Ue.decode(e.outputs[r.outputs[t].outputIndex].lockingScript);new Ut(s[3]).readVarIntNum()<n||i.push(Tt(s[2]))}return i}async download(t){if(!Ii(t))throw new Error("Invalid parameter UHRP url");const e=vi(t),r=await this.resolve(t);if(!Array.isArray(r)||0===r.length)throw new Error("No one currently hosts this file!");for(let t=0;t<r.length;t++)try{const i=await fetch(r[t],{method:"GET"});if(!i.ok||i.status>=400)continue;const n=await i.arrayBuffer(),s=[...new Uint8Array(n)],a=gt(s);for(let t=0;t<a.length;++t)if(a[t]!==e[t])throw new Error("Value of content does not match hash of the url given");return{data:s,mimeType:i.headers.get("Content-Type")}}catch(t){continue}throw new Error(`Unable to download content from ${t}`)}}const Ei={name:"Unknown Identity",avatarURL:"XUUB8bbn9fEthk15Ge3zTQXypUShfC94vFjp65v7u5CQ8qkpxzst",identityKey:"",abbreviatedKey:"",badgeIconURL:"XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",badgeLabel:"Not verified by anyone you trust.",badgeClickURL:"https://projectbabbage.com/docs/unknown-identity"},Si={protocolID:[1,"identity"],keyID:"1",tokenAmount:1,outputIndex:0},Ni={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="};class Oi{options;originator;authClient;wallet;constructor(t,e=Si,r){this.options=e,this.originator=r,this.wallet=t??new Gr,this.authClient=new hi(this.wallet)}async publiclyRevealAttributes(t,e){if(0===Object.keys(t.fields).length)throw new Error("Public reveal failed: Certificate has no fields to reveal!");if(0===e.length)throw new Error("Public reveal failed: You must reveal at least one field!");try{const e=new Kr(t.type,t.serialNumber,t.subject,t.certifier,t.revocationOutpoint,t.fields,t.signature);await e.verify()}catch(t){throw new Error("Public reveal failed: Certificate verification failed!")}const{keyringForVerifier:r}=await this.wallet.proveCertificate({certificate:t,fieldsToReveal:e,verifier:new re(1).toPublicKey().toString()}),i=await new Ue(this.wallet).lock([Ot(JSON.stringify({...t,keyring:r}))],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:i.toHex(),outputDescription:"Identity Token"}],options:{randomizeOutputs:!1}});if(void 0!==n){const t=new wi(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network});return await t.broadcast(ir.fromAtomicBEEF(n))}throw new Error("Public reveal failed: failed to create action!")}async resolveByIdentityKey(t){const{certificates:e}=await this.wallet.discoverByIdentityKey(t,this.originator);return e.map((t=>Oi.parseIdentity(t)))}async resolveByAttributes(t){const{certificates:e}=await this.wallet.discoverByAttributes(t,this.originator);return e.map((t=>Oi.parseIdentity(t)))}static parseIdentity(t){const{type:e,decryptedFields:r,certifierInfo:i}=t;let n,s,a,o,c;switch(e){case Ni.xCert:n=r.userName,s=r.profilePhoto,a=`X account certified by ${i.name}`,o=i.iconUrl,c="https://socialcert.net";break;case Ni.discordCert:n=r.userName,s=r.profilePhoto,a=`Discord account certified by ${i.name}`,o=i.iconUrl,c="https://socialcert.net";break;case Ni.emailCert:n=r.email,s="XUTZxep7BBghAJbSBwTjNfmcsDdRFs5EaGEgkESGSgjJVYgMEizu",a=`Email certified by ${i.name}`,o=i.iconUrl,c="https://socialcert.net";break;case Ni.phoneCert:n=r.phoneNumber,s="XUTLxtX3ELNUwRhLwL7kWNGbdnFM8WG2eSLv84J7654oH8HaJWrU",a=`Phone certified by ${i.name}`,o=i.iconUrl,c="https://socialcert.net";break;case Ni.identiCert:n=`${r.firstName} ${r.lastName}`,s=r.profilePhoto,a=`Government ID certified by ${i.name}`,o=i.iconUrl,c="https://identicert.me";break;case Ni.registrant:n=r.name,s=r.icon,a=`Entity certified by ${i.name}`,o=i.iconUrl,c="https://projectbabbage.com/docs/registrant";break;case Ni.coolCert:n="true"===r.cool?"Cool Person!":"Not cool!";break;case Ni.anyone:n="Anyone",s="XUT4bpQ6cpBaXi1oMzZsXfpkWGbtp2JTUYAoN7PzhStFJ6wLfoeR",a="Represents the ability for anyone to access this information.",o="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",c="https://projectbabbage.com/docs/anyone-identity";break;case Ni.self:n="You",s="XUT9jHGk2qace148jeCX5rDsMftkSGYKmigLwU2PLLBc7Hm63VYR",a="Represents your ability to access this information.",o="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",c="https://projectbabbage.com/docs/self-identity";break;default:n=Ei.name,s=r.profilePhoto,a=Ei.badgeLabel,o=Ei.badgeIconURL,c=Ei.badgeClickURL}return{name:n,avatarURL:s,abbreviatedKey:t.subject.length>0?`${t.subject.substring(0,10)}...`:"",identityKey:t.subject,badgeIconURL:o,badgeLabel:a,badgeClickURL:c}}}class xi{wallet;network;constructor(t=new Gr){this.wallet=t}async registerDefinition(t){const e=(await this.wallet.getPublicKey({identityKey:!0})).publicKey,r=new Ue(this.wallet),i=this.buildPushDropFields(t,e),n=this.mapDefinitionTypeToWalletProtocol(t.definitionType),s=await r.lock(i,n,"1","anyone",!0),{tx:a}=await this.wallet.createAction({description:`Register a new ${t.definitionType} item`,outputs:[{satoshis:1,lockingScript:s.toHex(),outputDescription:`New ${t.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(t.definitionType)}],options:{randomizeOutputs:!1}});if(void 0===a)throw new Error(`Failed to create ${t.definitionType} registration transaction!`);const o=new wi([this.mapDefinitionTypeToTopic(t.definitionType)],{networkPreset:this.network??=(await this.wallet.getNetwork({})).network});return await o.broadcast(ir.fromAtomicBEEF(a))}async resolve(t,e){const r=new pi,i=this.mapDefinitionTypeToServiceName(t),n=await r.query({service:i,query:e});if("output-list"!==n.type)return[];const s=[];for(const e of n.outputs)try{const r=ir.fromBEEF(e.beef).outputs[e.outputIndex].lockingScript,i=await this.parseLockingScript(t,r);s.push(i)}catch{}return s}async listOwnRegistryEntries(t){const e=this.mapDefinitionTypeToBasketName(t),{outputs:r,BEEF:i}=await this.wallet.listOutputs({basket:e,include:"entire transactions"}),n=[];for(const e of r)if(e.spendable)try{const[r,s]=e.outpoint.split("."),a=ir.fromBEEF(i).outputs[s].lockingScript,o=await this.parseLockingScript(t,a);n.push({...o,txid:r,outputIndex:Number(s),satoshis:e.satoshis,lockingScript:a.toHex(),beef:i})}catch{}return n}async revokeOwnRegistryEntry(t){if(void 0===t.txid||void 0===t.outputIndex||void 0===t.lockingScript)throw new Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");const e=(await this.wallet.getPublicKey({identityKey:!0})).publicKey;if(t.registryOperator!==e)throw new Error("This registry token does not belong to the current wallet.");const r="basket"===t.definitionType?t.basketID:"protocol"===t.definitionType?t.name:"certificate"===t.definitionType?void 0!==t.name?t.name:t.type:"unknown",i=`${t.txid}.${t.outputIndex}`,{signableTransaction:n}=await this.wallet.createAction({description:`Revoke ${t.definitionType} item: ${r}`,inputBEEF:t.beef,inputs:[{outpoint:i,unlockingScriptLength:73,inputDescription:`Revoking ${t.definitionType} token`}]});if(void 0===n)throw new Error("Failed to create signable transaction.");const s=ir.fromBEEF(n.tx),a=new Ue(this.wallet),o=await a.unlock(this.mapDefinitionTypeToWalletProtocol(t.definitionType),"1","anyone","all",!1,t.satoshis,Ae.fromHex(t.lockingScript)),c=await o.sign(s,t.outputIndex),{tx:h}=await this.wallet.signAction({reference:n.reference,spends:{[t.outputIndex]:{unlockingScript:c.toHex()}},options:{acceptDelayedBroadcast:!1}});if(void 0===h)throw new Error("Failed to finalize the transaction signature.");const u=new wi([this.mapDefinitionTypeToTopic(t.definitionType)],{networkPreset:this.network??=(await this.wallet.getNetwork({})).network});return await u.broadcast(ir.fromAtomicBEEF(h))}buildPushDropFields(t,e){let r;switch(t.definitionType){case"basket":r=[t.basketID,t.name,t.iconURL,t.description,t.documentationURL];break;case"protocol":r=[JSON.stringify(t.protocolID),t.name,t.iconURL,t.description,t.documentationURL];break;case"certificate":r=[t.type,t.name,t.iconURL,t.description,t.documentationURL,JSON.stringify(t.fields)];break;default:throw new Error("Unsupported definition type")}return r.push(e),r.map((t=>Ot(t)))}async parseLockingScript(t,e){const r=Ue.decode(e);if(0===r.fields.length)throw new Error("Not a valid registry pushdrop script.");let i,n;switch(t){case"basket":{if(7!==r.fields.length)throw new Error("Unexpected field count for basket type.");const[t,e,s,a,o,c]=r.fields;i=Tt(c),n={definitionType:"basket",basketID:Tt(t),name:Tt(e),iconURL:Tt(s),description:Tt(a),documentationURL:Tt(o)};break}case"protocol":{if(7!==r.fields.length)throw new Error("Unexpected field count for protocol type.");const[t,e,s,a,o,c]=r.fields;i=Tt(c),n={definitionType:"protocol",protocolID:Ai(Tt(t)),name:Tt(e),iconURL:Tt(s),description:Tt(a),documentationURL:Tt(o)};break}case"certificate":{if(8!==r.fields.length)throw new Error("Unexpected field count for certificate type.");const[t,e,s,a,o,c,h]=r.fields;i=Tt(h);let u={};try{u=JSON.parse(Tt(c))}catch{}n={definitionType:"certificate",type:Tt(t),name:Tt(e),iconURL:Tt(s),description:Tt(a),documentationURL:Tt(o),fields:u};break}default:throw new Error(`Unsupported definition type: ${t}`)}return{...n,registryOperator:i}}mapDefinitionTypeToWalletProtocol(t){switch(t){case"basket":return[1,"basketmap"];case"protocol":return[1,"protomap"];case"certificate":return[1,"certmap"];default:throw new Error(`Unknown definition type: ${t}`)}}mapDefinitionTypeToBasketName(t){switch(t){case"basket":return"basketmap";case"protocol":return"protomap";case"certificate":return"certmap";default:throw new Error(`Unknown definition type: ${t}`)}}mapDefinitionTypeToTopic(t){switch(t){case"basket":return"tm_basketmap";case"protocol":return"tm_protomap";case"certificate":return"tm_certmap";default:throw new Error(`Unknown definition type: ${t}`)}}mapDefinitionTypeToServiceName(t){switch(t){case"basket":return"ls_basketmap";case"protocol":return"ls_protomap";case"certificate":return"ls_certmap";default:throw new Error(`Unknown definition type: ${t}`)}}}function Ai(t){const e=JSON.parse(t);if(!Array.isArray(e)||2!==e.length)throw new Error("Invalid wallet protocol format.");const[r,i]=e;if(![0,1,2].includes(r))throw new Error("Invalid security level.");if("string"!=typeof i)throw new Error("Invalid protocolID");return[r,i]}class Ti{wallet;context;encrypt;originator;constructor(t=new Gr,e="kvstore default",r=!0,i){if("string"!=typeof e||e.length<1)throw new Error("A context in which to operate is required.");this.wallet=t,this.context=e,this.encrypt=r,this.originator=i}getProtocol(t){return{protocolID:[2,this.context],keyID:t}}async getOutputs(t,e){return await this.wallet.listOutputs({basket:this.context,tags:[t],tagQueryMode:"all",include:"entire transactions",limit:e})}async get(t,e=void 0){return(await this.lookupValue(t,e,5)).value}getLockingScript(t,e){const[r,i]=t.outpoint.split("."),n=e.findTxid(r)?.tx;if(null==n)throw new Error(`beef must contain txid ${r}`);return n.outputs[Number(i)].lockingScript}async lookupValue(t,e,r){const i=await this.getOutputs(t,r),n={value:e,outpoint:void 0,lor:i},{outputs:s}=i;if(0===s.length)return n;const a=s.slice(-1)[0];let o;n.outpoint=a.outpoint;try{if(void 0===i.BEEF)throw new Error("entire transactions listOutputs option must return valid BEEF");const t=this.getLockingScript(a,rr.fromBinary(i.BEEF)),e=Ue.decode(t);if(e.fields.length<1||e.fields.length>2)throw new Error("Invalid token.");o=e.fields[0]}catch(t){throw new Error(`Invalid value found. You need to call set to collapse the corrupted state (or relinquish the corrupted ${s[0].outpoint} output from the ${this.context} basket) before you can get this value again.`)}if(this.encrypt){const{plaintext:e}=await this.wallet.decrypt({...this.getProtocol(t),ciphertext:o});n.value=Tt(e)}else n.value=Tt(o);return n}getInputs(t){const e=[];for(let r=0;r<t.length;r++)e.push({outpoint:t[r].outpoint,unlockingScriptLength:74,inputDescription:"Previous key-value token"});return e}async getSpends(t,e,r,i){const n=this.getProtocol(t),s=ir.fromAtomicBEEF(i),a={};for(let t=0;t<e.length;t++){const e=r.unlock(n.protocolID,n.keyID,"self"),i=await e.sign(s,t);a[t]={unlockingScript:i.toHex()}}return a}async set(t,e){const r=await this.lookupValue(t,void 0,10);if(r.value===e){if(void 0===r.outpoint)throw new Error("outpoint must be valid when value is valid and unchanged");return r.outpoint}const i=this.getProtocol(t);let n=Ot(e,"utf8");if(this.encrypt){const{ciphertext:t}=await this.wallet.encrypt({...i,plaintext:n});n=t}const s=new Ue(this.wallet,this.originator),a=await s.lock([n],i.protocolID,i.keyID,"self"),{outputs:o,BEEF:c}=r.lor;let h;try{const e=this.getInputs(o),{txid:r,signableTransaction:i}=await this.wallet.createAction({description:`Update ${t} in ${this.context}`,inputBEEF:c,inputs:e,outputs:[{basket:this.context,tags:[t],lockingScript:a.toHex(),satoshis:1,outputDescription:"Key-value token"}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}});if(o.length>0&&"object"!=typeof i)throw new Error("Wallet did not return a signable transaction when expected.");if(null==i)h=`${r}.0`;else{const e=await this.getSpends(t,o,s,i.tx),{txid:r}=await this.wallet.signAction({reference:i.reference,spends:e});h=`${r}.0`}}catch(e){throw new Error(`There are ${o.length} outputs with tag ${t} that cannot be unlocked.`)}return h}async remove(t){const e=[];for(;;){const{outputs:r,BEEF:i,totalOutputs:n}=await this.getOutputs(t);if(r.length>0){const s=new Ue(this.wallet,this.originator);try{const n=this.getInputs(r),{signableTransaction:a}=await this.wallet.createAction({description:`Remove ${t} in ${this.context}`,inputBEEF:i,inputs:n,options:{acceptDelayedBroadcast:!1}});if("object"!=typeof a)throw new Error("Wallet did not return a signable transaction when expected.");const o=await this.getSpends(t,r,s,a.tx),{txid:c}=await this.wallet.signAction({reference:a.reference,spends:o});if(void 0===c)throw new Error("signAction must return a valid txid");e.push(c)}catch(e){throw new Error(`There are ${n} outputs with tag ${t} that cannot be unlocked.`)}}if(r.length===n)break}return e}}return e})()));
|