@bsv/sdk 1.6.3 → 1.6.5
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/transaction/chaintrackers/BlockHeadersService.js +91 -0
- package/dist/cjs/src/transaction/chaintrackers/BlockHeadersService.js.map +1 -0
- package/dist/cjs/src/transaction/chaintrackers/index.js +3 -1
- package/dist/cjs/src/transaction/chaintrackers/index.js.map +1 -1
- package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
- package/dist/esm/src/transaction/chaintrackers/BlockHeadersService.js +90 -0
- package/dist/esm/src/transaction/chaintrackers/BlockHeadersService.js.map +1 -0
- package/dist/esm/src/transaction/chaintrackers/index.js +1 -0
- package/dist/esm/src/transaction/chaintrackers/index.js.map +1 -1
- package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
- package/dist/types/src/script/index.d.ts +1 -0
- package/dist/types/src/script/index.d.ts.map +1 -1
- package/dist/types/src/transaction/chaintrackers/BlockHeadersService.d.ts +46 -0
- package/dist/types/src/transaction/chaintrackers/BlockHeadersService.d.ts.map +1 -0
- package/dist/types/src/transaction/chaintrackers/index.d.ts +1 -0
- package/dist/types/src/transaction/chaintrackers/index.d.ts.map +1 -1
- package/dist/types/tsconfig.types.tsbuildinfo +1 -1
- package/dist/umd/bundle.js +1 -1
- package/docs/overlay-tools.md +2 -3
- package/docs/primitives.md +20 -53
- package/docs/transaction.md +1 -1
- package/package.json +1 -1
- package/src/script/index.ts +1 -0
- package/src/transaction/chaintrackers/BlockHeadersService.ts +138 -0
- package/src/transaction/chaintrackers/index.ts +1 -0
package/dist/umd/bundle.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.bsv=t():e.bsv=t()}(this,(()=>(()=>{"use strict";var e={d:(t,r)=>{for(var i in r)e.o(r,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:r[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{ARC:()=>jt,ATOMIC_BEEF:()=>rr,AuthFetch:()=>li,BEEF_V1:()=>er,BEEF_V2:()=>tr,BSM:()=>o,Beef:()=>nr,BeefParty:()=>cr,BeefTx:()=>Zt,BigNumber:()=>d,CachedKeyDeriver:()=>Dr,Certificate:()=>Mr,CompletedProtoWallet:()=>ri,Curve:()=>Me,DEFAULT_IDENTITY_CLIENT_OPTIONS:()=>_i,DEFAULT_SLAP_TRACKERS:()=>pi,DEFAULT_TESTNET_SLAP_TRACKERS:()=>bi,DRBG:()=>ze,ECDSA:()=>n,ECIES:()=>Ar,EncryptedMessage:()=>a,FetchHttpClient:()=>$t,HD:()=>Sr,HTTPSOverlayBroadcastFacilitator:()=>mi,HTTPSOverlayLookupFacilitator:()=>wi,HTTPWalletJSON:()=>Yr,HTTPWalletWire:()=>jr,Hash:()=>r,IdentityClient:()=>Ai,KNOWN_IDENTITY_TYPES:()=>xi,KeyDeriver:()=>Vr,KeyShares:()=>tt,LocalKVStore:()=>Ri,LockingScript:()=>xt,LookupResolver:()=>gi,MasterCertificate:()=>ei,MerklePath:()=>Jt,Mnemonic:()=>Pr,NodejsHttpClient:()=>Mt,OP:()=>Ot,OverlayAdminTokenTemplate:()=>fi,P2PKH:()=>Ut,Peer:()=>di,Point:()=>He,PointInFiniteField:()=>Qe,Polynomial:()=>et,PrivateKey:()=>rt,ProtoWallet:()=>Br,PublicKey:()=>Ge,PushDrop:()=>Ht,RPuzzle:()=>Lt,Random:()=>Ze,ReactNativeWebView:()=>Jr,RegistryClient:()=>Ti,SHIPBroadcaster:()=>yi,SHIPCast:()=>yi,SatoshisPerKilobyte:()=>qt,Schnorr:()=>Pt,Script:()=>_t,SecurityLevels:()=>Cr,SessionManager:()=>ii,Signature:()=>$e,SignedMessage:()=>s,SimplifiedFetchTransport:()=>hi,Spend:()=>Dt,StorageDownloader:()=>Ni,StorageUploader:()=>Pi,StorageUtils:()=>c,SymmetricKey:()=>St,TOTP:()=>Fr,TX_DATA_FORMAT:()=>ir,Teranode:()=>fr,TopicBroadcaster:()=>yi,Transaction:()=>sr,TransactionSignature:()=>Et,UnlockingScript:()=>At,Utils:()=>i,VerifiableCertificate:()=>ti,WERR_REVIEW_ACTIONS:()=>Gr,WalletClient:()=>Zr,WalletError:()=>Lr,WalletErrors:()=>Hr,WalletWireProcessor:()=>Qr,WalletWireTransceiver:()=>Wr,WhatsOnChain:()=>Gt,WhatsOnChainBroadcaster:()=>dr,WindowCWISubstrate:()=>Ur,XDM:()=>qr,binaryHttpClient:()=>lr,createNonce:()=>si,defaultBroadcaster:()=>Xt,defaultChainTracker:()=>Yt,defaultHttpClient:()=>zt,defaultIdentity:()=>Oi,deserializeWalletProtocol:()=>Fi,fromUtxo:()=>Tr,getVerifiableCertificates:()=>ai,isBroadcastFailure:()=>or,isBroadcastResponse:()=>ar,validateCertificates:()=>oi,verifyNonce:()=>ni,walletErrors:()=>Kr});var r={};e.r(r),e.d(r,{RIPEMD160:()=>J,SHA1:()=>Q,SHA1HMAC:()=>pe,SHA256:()=>Z,SHA256HMAC:()=>fe,SHA512:()=>ee,SHA512HMAC:()=>be,hash160:()=>ve,hash256:()=>Ie,pbkdf2:()=>Ee,ripemd160:()=>we,sha1:()=>ge,sha256:()=>me,sha256hmac:()=>ke,sha512:()=>ye,sha512hmac:()=>Se,toArray:()=>y});var i={};e.r(i),e.d(i,{Reader:()=>Le,Writer:()=>Ue,encode:()=>Te,fromBase58:()=>Ce,fromBase58Check:()=>Be,minimallyEncode:()=>Ke,toArray:()=>Oe,toBase58:()=>Ve,toBase58Check:()=>De,toBase64:()=>Fe,toHex:()=>Ne,toUTF8:()=>Ae,zero2:()=>Pe});var n={};e.r(n),e.d(n,{sign:()=>je,verify:()=>Xe});var s={};e.r(s),e.d(s,{sign:()=>br,verify:()=>wr});var a={};e.r(a),e.d(a,{decrypt:()=>yr,encrypt:()=>mr});var o={};e.r(o),e.d(o,{magicHash:()=>Ir,sign:()=>vr,verify:()=>kr});var c={};e.r(c),e.d(c,{getHashFromURL:()=>Si,getURLForFile:()=>ki,getURLForHash:()=>vi,isValidURL:()=>Ei,normalizeURL:()=>Ii});class d{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;static WORD_SIZE_BIGINT=BigInt(d.wordSize);static WORD_MASK=(1n<<d.WORD_SIZE_BIGINT)-1n;static MAX_SAFE_INTEGER_BIGINT=BigInt(Number.MAX_SAFE_INTEGER);static MIN_SAFE_INTEGER_BIGINT=BigInt(Number.MIN_SAFE_INTEGER);static MAX_IMULN_ARG=67108863;static MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT=(1n<<53n)-1n;_magnitude;_sign;_nominalWordLength;red;get negative(){return this._sign}set negative(e){this.assert(0===e||1===e,"Negative property must be 0 or 1");const t=1===e?1:0;0n===this._magnitude?this._sign=0:this._sign=t}get _computedWordsArray(){if(0n===this._magnitude)return[0];const e=[];let t=this._magnitude;for(;t>0n;)e.push(Number(t&d.WORD_MASK)),t>>=d.WORD_SIZE_BIGINT;return e.length>0?e:[0]}get words(){const e=this._computedWordsArray;if(this._nominalWordLength<=e.length)return e;const t=new Array(this._nominalWordLength).fill(0);for(let r=0;r<e.length;r++)t[r]=e[r];return t}set words(e){const t=this._sign;let r=0n;const i=e.length>0?e.length:1;for(let t=i-1;t>=0;t--){const i=void 0===e[t]?0:e[t];r=r<<d.WORD_SIZE_BIGINT|BigInt(i&Number(d.WORD_MASK))}this._magnitude=r,this._sign=t,this._nominalWordLength=i,this.normSign()}get length(){return Math.max(1,this._nominalWordLength)}static isBN(e){return e instanceof d||null!==e&&"object"==typeof e&&e.constructor?.wordSize===d.wordSize&&Array.isArray(e.words)}static max(e,t){return e.cmp(t)>0?e:t}static min(e,t){return e.cmp(t)<0?e:t}constructor(e=0,t=10,r="be"){if(this._magnitude=0n,this._sign=0,this._nominalWordLength=1,this.red=null,void 0===e&&(e=0),null===e)return void this._initializeState(0n,0);if("bigint"==typeof e)return this._initializeState(e<0n?-e:e,e<0n?1:0),void this.normSign();let i=t,n=r;if("le"!==t&&"be"!==t||(n=t,i=10),"number"!=typeof e)if(Array.isArray(e))this.initArray(e,n);else if("string"==typeof e){"hex"===i&&(i=16),this.assert("number"==typeof i&&i===(0|i)&&i>=2&&i<=36,"Base must be an integer between 2 and 36");const t=e.toString().replace(/\s+/g,"");let r=0,s=0;t.startsWith("-")?(r++,s=1):t.startsWith("+")&&r++;const a=t.substring(r);if(0===a.length)return this._initializeState(0n,1===s&&t.startsWith("-")?1:0),void this.normSign();if(16===i){let e;if("le"===n){const e=[];let t=a;t.length%2!=0&&(t="0"+t);for(let r=0;r<t.length;r+=2){const i=t.substring(r,r+2),n=parseInt(i,16);if(isNaN(n))throw new Error("Invalid character in "+t);e.push(n)}return this.initArray(e,"le"),this._sign=s,void this.normSign()}try{e=BigInt("0x"+a)}catch(e){throw new Error("Invalid character in "+a)}this._initializeState(e,s),this.normSign()}else try{if(this._parseBaseString(a,i),this._sign=s,this.normSign(),"le"===n){const e=this._sign;this.initArray(this.toArray("be"),"le"),this._sign=e,this.normSign()}}catch(e){const t=e;if(t.message.includes("Invalid character in string")||t.message.includes("Invalid digit for base")||t.message.startsWith("Invalid character:"))throw new Error("Invalid character");throw t}}else 0!==e?this.assert(!1,"Unsupported input type for BigNumber constructor"):this._initializeState(0n,0);else this.initNumber(e,n)}_bigIntToStringInBase(e,t){if(0n===e)return"0";if(t<2||t>36)throw new Error("Base must be between 2 and 36");let r="",i=e>0n?e:-e;const n=BigInt(t);for(;i>0n;)r="0123456789abcdefghijklmnopqrstuvwxyz"[Number(i%n)]+r,i/=n;return r}_parseBaseString(e,t){if(0===e.length)return this._magnitude=0n,void this._finishInitialization();this._magnitude=0n;const r=BigInt(t);let i=d.groupSizes[t],n=BigInt(d.groupBases[t]);0!==i&&0n!==n||(i=Math.floor(Math.log(67108863)/Math.log(t)),0===i&&(i=1),n=r**BigInt(i));let s=0;const a=e.length;let o=a%i;if(0===o&&a>0&&(o=i),o>0){const r=e.substring(s,s+o);this._magnitude=BigInt(this._parseBaseWord(r,t)),s+=o}for(;s<a;){const r=e.substring(s,s+i),a=BigInt(this._parseBaseWord(r,t));this._magnitude=this._magnitude*n+a,s+=i}this._finishInitialization()}_parseBaseWord(e,t){let r=0;for(let i=0;i<e.length;i++){const n=e.charCodeAt(i);let s;if(n>=48&&n<=57)s=n-48;else if(n>=65&&n<=90)s=n-65+10;else{if(!(n>=97&&n<=122))throw new Error("Invalid character: "+e[i]);s=n-97+10}if(s>=t)throw new Error("Invalid character");r=r*t+s}return r}_initializeState(e,t){this._magnitude=e,this._sign=0n===e?0:t,this._finishInitialization()}_finishInitialization(){if(0n===this._magnitude)this._nominalWordLength=1,this._sign=0;else{const e=this._magnitude.toString(2).length;this._nominalWordLength=Math.max(1,Math.ceil(e/d.wordSize))}}assert(e,t="Assertion failed"){if(!e)throw new Error(t)}initNumber(e,t="be"){if(this.assert(BigInt(Math.abs(e))<=d.MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT,"The number is larger than 2 ^ 53 (unsafe)"),this.assert(e%1==0,"Number must be an integer for BigNumber conversion"),this._initializeState(BigInt(Math.abs(e)),e<0?1:0),"le"===t){const e=this._sign,t=this.toArray("be");this.initArray(t,"le"),this._sign=e,this.normSign()}return this}initArray(e,t){if(0===e.length)return this._initializeState(0n,0),this;let r=0n;if("be"===t)for(let t=0;t<e.length;t++)r=r<<8n|BigInt(255&e[t]);else for(let t=e.length-1;t>=0;t--)r=r<<8n|BigInt(255&e[t]);return this._initializeState(r,0),this}copy(e){e._magnitude=this._magnitude,e._sign=this._sign,e._nominalWordLength=this._nominalWordLength,e.red=this.red}static move(e,t){e._magnitude=t._magnitude,e._sign=t._sign,e._nominalWordLength=t._nominalWordLength,e.red=t.red}clone(){const e=new d(0n);return this.copy(e),e}expand(e){return this.assert(e>=0,"Expand size must be non-negative"),this._nominalWordLength=Math.max(this._nominalWordLength,e,1),this}strip(){return this._finishInitialization(),this.normSign()}normSign(){return 0n===this._magnitude&&(this._sign=0),this}inspect(){return(null!==this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}_getMinimalHex(){return 0n===this._magnitude?"0":this._magnitude.toString(16)}toString(e=10,t=1){if(16===e||"hex"===e){let e=this._getMinimalHex();if(t>1)for("0"!==e&&e.length%2!=0&&(e="0"+e);e.length%t!=0;)e="0"+e;return(this.isNeg()?"-":"")+e}if("number"!=typeof e||e<2||e>36||e%1!=0)throw new Error("Base should be an integer between 2 and 36");return this.toBaseString(e,t)}toBaseString(e,t){if(0n===this._magnitude){let e="0";if(t>1)for(;e.length<t;)e="0"+e;return e}let r=d.groupSizes[e],i=BigInt(d.groupBases[e]);0!==r&&0n!==i||(r=Math.floor(Math.log(Number.MAX_SAFE_INTEGER)/Math.log(e)),0===r&&(r=1),i=BigInt(e)**BigInt(r));let n="",s=this._magnitude;for(;s>0n;){const t=s%i;s/=i;const a=this._bigIntToStringInBase(t,e);if(s>0n){const e=r-a.length;n=e>0&&e<d.zeros.length?d.zeros[e]+a+n:e>0?"0".repeat(e)+a+n:a+n}else n=a+n}if(t>0)for(;n.length<t;)n="0"+n;return(1===this._sign?"-":"")+n}toNumber(){const e=this._getSignedValue();if(e>d.MAX_SAFE_INTEGER_BIGINT||e<d.MIN_SAFE_INTEGER_BIGINT)throw new Error("Number can only safely store up to 53 bits");return Number(e)}toJSON(){const e=this._getMinimalHex();return(this.isNeg()?"-":"")+e}toArrayLikeGeneric(e,t){let r=this._magnitude,i=t?0:e.length-1;const n=t?1:-1;for(let t=0;t<e.length;++t){if(0n===r&&i>=0&&i<e.length)e[i]=0;else{if(!(i>=0&&i<e.length))break;e[i]=Number(0xffn&r)}r>>=8n,i+=n}}toArray(e="be",t){this.strip();const r=this.byteLength(),i=t??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).fill(0);return 0n===this._magnitude&&i>0?n:0n===this._magnitude&&0===i?[]:(this.toArrayLikeGeneric(n,"le"===e),n)}bitLength(){return 0n===this._magnitude?0:this._magnitude.toString(2).length}static toBitArray(e){const t=e.bitLength();if(0===t)return[];const r=new Array(t),i=e._magnitude;for(let e=0;e<t;e++)r[e]=0n!==(i>>BigInt(e)&1n)?1:0;return r}toBitArray(){return d.toBitArray(this)}zeroBits(){if(0n===this._magnitude)return 0;let e=0,t=this._magnitude;for(;0n===(1n&t)&&0n!==t;)e++,t>>=1n;return e}byteLength(){return 0n===this._magnitude?0:Math.ceil(this.bitLength()/8)}_getSignedValue(){return 1===this._sign?-this._magnitude:this._magnitude}_setValueFromSigned(e){e<0n?(this._magnitude=-e,this._sign=1):(this._magnitude=e,this._sign=0),this._finishInitialization(),this.normSign()}toTwos(e){this.assert(e>=0);const t=BigInt(e);let r=this._getSignedValue();1===this._sign&&0n!==this._magnitude&&(r=(1n<<t)+r),r&=(1n<<t)-1n;const i=new d(0n);return i._initializeState(r,0),i}fromTwos(e){this.assert(e>=0);const t=BigInt(e),r=this._magnitude;if(e>0&&0n!==(r>>t-1n&1n)&&0===this._sign){const e=r-(1n<<t),i=new d(0n);return i._setValueFromSigned(e),i}return this.clone()}isNeg(){return 1===this._sign&&0n!==this._magnitude}neg(){return this.clone().ineg()}ineg(){return 0n!==this._magnitude&&(this._sign=1===this._sign?0:1),this}_iuop(e,t){const r=t(this._magnitude,e._magnitude),i=t===((e,t)=>e^t);let n=this._nominalWordLength;return i&&(n=Math.max(this.length,e.length)),this._magnitude=r,this._finishInitialization(),i&&(this._nominalWordLength=Math.max(this._nominalWordLength,n)),this.strip()}iuor(e){return this._iuop(e,((e,t)=>e|t))}iuand(e){return this._iuop(e,((e,t)=>e&t))}iuxor(e){return this._iuop(e,((e,t)=>e^t))}_iop(e,t){return this.assert(0===this._sign&&0===e._sign),this._iuop(e,t)}ior(e){return this._iop(e,((e,t)=>e|t))}iand(e){return this._iop(e,((e,t)=>e&t))}ixor(e){return this._iop(e,((e,t)=>e^t))}_uop_new(e,t){return this.length>=e.length?this.clone()[t](e):e.clone()[t](this)}or(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuor")}uor(e){return this._uop_new(e,"iuor")}and(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuand")}uand(e){return this._uop_new(e,"iuand")}xor(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuxor")}uxor(e){return this._uop_new(e,"iuxor")}inotn(e){this.assert("number"==typeof e&&e>=0);const t=(1n<<BigInt(e))-1n;this._magnitude=~this._magnitude&t;const r=0===e?1:Math.ceil(e/d.wordSize);return this._nominalWordLength=Math.max(1,r),this.strip(),this._nominalWordLength=Math.max(this._nominalWordLength,Math.max(1,r)),this}notn(e){return this.clone().inotn(e)}setn(e,t){this.assert("number"==typeof e&&e>=0);const r=BigInt(e);1===t||!0===t?this._magnitude|=1n<<r:this._magnitude&=~(1n<<r);const i=Math.floor(e/d.wordSize)+1;return this._nominalWordLength=Math.max(this._nominalWordLength,i),this._finishInitialization(),this.strip()}iadd(e){return this._setValueFromSigned(this._getSignedValue()+e._getSignedValue()),this}add(e){const t=new d(0n);return t._setValueFromSigned(this._getSignedValue()+e._getSignedValue()),t}isub(e){return this._setValueFromSigned(this._getSignedValue()-e._getSignedValue()),this}sub(e){const t=new d(0n);return t._setValueFromSigned(this._getSignedValue()-e._getSignedValue()),t}mul(e){const t=new d(0n);return t._magnitude=this._magnitude*e._magnitude,t._sign=0n===t._magnitude?0:this._sign^e._sign,t._nominalWordLength=this.length+e.length,t.red=null,t.normSign()}imul(e){return this._magnitude*=e._magnitude,this._sign=0n===this._magnitude?0:this._sign^e._sign,this._nominalWordLength=this.length+e.length,this.red=null,this.normSign()}imuln(e){return this.assert("number"==typeof e,"Assertion failed"),this.assert(Math.abs(e)<=d.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()*BigInt(e)),this}muln(e){return this.clone().imuln(e)}sqr(){const e=new d(0n);return e._magnitude=this._magnitude*this._magnitude,e._sign=0,e._nominalWordLength=2*this.length,e.red=null,e}isqr(){return this._magnitude*=this._magnitude,this._sign=0,this._nominalWordLength=2*this.length,this.red=null,this}pow(e){if(this.assert(0===e._sign,"Exponent for pow must be non-negative"),e.isZero())return new d(1n);const t=new d(1n),r=this.clone(),i=e.clone(),n=r.isNeg(),s=i.isOdd();for(n&&r.ineg();!i.isZero();)i.isOdd()&&t.imul(r),r.isqr(),i.iushrn(1);return n&&s&&t.ineg(),t}iushln(e){return this.assert("number"==typeof e&&e>=0),0===e?this:(this._magnitude<<=BigInt(e),this._finishInitialization(),this.strip())}ishln(e){return this.assert(0===this._sign,"ishln requires positive number"),this.iushln(e)}iushrn(e,t,r){if(this.assert("number"==typeof e&&e>=0),0===e)return null!=r&&r._initializeState(0n,0),this;if(null!=r){const t=(1n<<BigInt(e))-1n,i=this._magnitude&t;r._initializeState(i,0)}return this._magnitude>>=BigInt(e),this._finishInitialization(),this.strip()}ishrn(e,t,r){return this.assert(0===this._sign,"ishrn requires positive number"),this.iushrn(e,t,r)}shln(e){return this.clone().ishln(e)}ushln(e){return this.clone().iushln(e)}shrn(e){return this.clone().ishrn(e)}ushrn(e){return this.clone().iushrn(e)}testn(e){return this.assert("number"==typeof e&&e>=0),0n!==(this._magnitude>>BigInt(e)&1n)}imaskn(e){this.assert("number"==typeof e&&e>=0),this.assert(0===this._sign,"imaskn works only with positive numbers");const t=BigInt(e),r=0n===t?0n:(1n<<t)-1n;this._magnitude&=r;const i=0===e?1:Math.max(1,Math.ceil(e/d.wordSize));return this._nominalWordLength=i,this._finishInitialization(),this._nominalWordLength=Math.max(this._nominalWordLength,i),this.strip()}maskn(e){return this.clone().imaskn(e)}iaddn(e){return this.assert("number"==typeof e),this.assert(Math.abs(e)<=d.MAX_IMULN_ARG,"num is too large"),this._setValueFromSigned(this._getSignedValue()+BigInt(e)),this}_iaddn(e){return this.iaddn(e)}isubn(e){return this.assert("number"==typeof e),this.assert(Math.abs(e)<=d.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()-BigInt(e)),this}addn(e){return this.clone().iaddn(e)}subn(e){return this.clone().isubn(e)}iabs(){return this._sign=0,this}abs(){return this.clone().iabs()}divmod(e,t,r){if(this.assert(!e.isZero(),"Division by zero"),this.isZero()){const e=new d(0n);return{div:"mod"!==t?e:null,mod:"div"!==t?e:null}}const i=this._getSignedValue(),n=e._getSignedValue();let s=null,a=null;"mod"!==t&&(s=i/n),"div"!==t&&(a=i%n,!0===r&&a<0n&&(a+=n<0n?-n:n));const o=null!==s?new d(0n):null;null!==o&&null!==s&&o._setValueFromSigned(s);const c=null!==a?new d(0n):null;return null!==c&&null!==a&&c._setValueFromSigned(a),{div:o,mod:c}}div(e){return this.divmod(e,"div",!1).div}mod(e){return this.divmod(e,"mod",!1).mod}umod(e){return this.divmod(e,"mod",!0).mod}divRound(e){this.assert(!e.isZero());const t=this._getSignedValue(),r=e._getSignedValue();let i=t/r;const n=t%r;if(0n===n){const e=new d(0n);return e._setValueFromSigned(i),e}2n*(n<0n?-n:n)>=(r<0n?-r:r)&&(t>0n&&r>0n||t<0n&&r<0n?i+=1n:i-=1n);const s=new d(0n);return s._setValueFromSigned(i),s}modrn(e){this.assert(0!==e,"Division by zero in modrn");const t=BigInt(Math.abs(e));if(0n===t)throw new Error("Division by zero in modrn");const r=this._magnitude%t;return Number(e<0?-r:r)}idivn(e){return this.assert(0!==e),this.assert(Math.abs(e)<=d.MAX_IMULN_ARG,"num is too large"),this._setValueFromSigned(this._getSignedValue()/BigInt(e)),this}divn(e){return this.clone().idivn(e)}egcd(e){this.assert(0===e._sign,"p must not be negative"),this.assert(!e.isZero(),"p must not be zero");let t=this._getSignedValue(),r=e._magnitude,i=1n,n=0n,s=0n,a=1n;for(;0n!==r;){const e=t/r;let o=r;r=t%r,t=o,o=n,n=i-e*n,i=o,o=a,a=s-e*a,s=o}const o=new d(0n);o._setValueFromSigned(i);const c=new d(0n);c._setValueFromSigned(s);const u=new d(0n);return u._initializeState(t<0n?-t:t,0),{a:o,b:c,gcd:u}}gcd(e){let t=this._magnitude,r=e._magnitude;if(0n===t){const e=new d(0n);return e._setValueFromSigned(r),e.iabs()}if(0n===r){const e=new d(0n);return e._setValueFromSigned(t),e.iabs()}for(;0n!==r;){const e=t%r;t=r,r=e}const i=new d(0n);return i._initializeState(t,0),i}invm(e){this.assert(!e.isZero()&&0===e._sign,"Modulus for invm must be positive and non-zero");const t=this.egcd(e);if(!t.gcd.eqn(1))throw new Error("Inverse does not exist (numbers are not coprime).");return t.a.umod(e)}isEven(){return this._magnitude%2n===0n}isOdd(){return this._magnitude%2n===1n}andln(e){return this.assert(e>=0),Number(this._magnitude&BigInt(e))}bincn(e){this.assert("number"==typeof e&&e>=0);const t=1n<<BigInt(e);return this._setValueFromSigned(this._getSignedValue()+t),this}isZero(){return 0n===this._magnitude}cmpn(e){this.assert(Math.abs(e)<=d.MAX_IMULN_ARG,"Number is too big");const t=this._getSignedValue(),r=BigInt(e);return t<r?-1:t>r?1:0}cmp(e){const t=this._getSignedValue(),r=e._getSignedValue();return t<r?-1:t>r?1:0}ucmp(e){return this._magnitude<e._magnitude?-1:this._magnitude>e._magnitude?1:0}gtn(e){return 1===this.cmpn(e)}gt(e){return 1===this.cmp(e)}gten(e){return this.cmpn(e)>=0}gte(e){return this.cmp(e)>=0}ltn(e){return-1===this.cmpn(e)}lt(e){return-1===this.cmp(e)}lten(e){return this.cmpn(e)<=0}lte(e){return this.cmp(e)<=0}eqn(e){return 0===this.cmpn(e)}eq(e){return 0===this.cmp(e)}toRed(e){return this.assert(null==this.red,"Already a number in reduction context"),this.assert(0===this._sign,"toRed works only with positives"),e.convertTo(this).forceRed(e)}fromRed(){return this.assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)}forceRed(e){return this.red=e,this}redAdd(e){return this.assert(this.red,"redAdd works only with red numbers"),this.red.add(this,e)}redIAdd(e){return this.assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)}redSub(e){return this.assert(this.red,"redSub works only with red numbers"),this.red.sub(this,e)}redISub(e){return this.assert(this.red,"redISub works only with red numbers"),this.red.isub(this,e)}redShl(e){return this.assert(this.red,"redShl works only with red numbers"),this.red.shl(this,e)}redMul(e){return this.assert(this.red,"redMul works only with red numbers"),this.red.verify2(this,e),this.red.mul(this,e)}redIMul(e){return this.assert(this.red,"redIMul works only with red numbers"),this.red.verify2(this,e),this.red.imul(this,e)}redSqr(){return this.assert(this.red,"redSqr works only with red numbers"),this.red.verify1(this),this.red.sqr(this)}redISqr(){return this.assert(this.red,"redISqr works only with red numbers"),this.red.verify1(this),this.red.isqr(this)}redSqrt(){return this.assert(this.red,"redSqrt works only with red numbers"),this.red.verify1(this),this.red.sqrt(this)}redInvm(){return this.assert(this.red,"redInvm works only with red numbers"),this.red.verify1(this),this.red.invm(this)}redNeg(){return this.assert(this.red,"redNeg works only with red numbers"),this.red.verify1(this),this.red.neg(this)}redPow(e){return this.assert(null!=this.red&&null==e.red,"redPow(normalNum)"),this.red.verify1(this),this.red.pow(this,e)}static fromHex(e,t){let r="be";return"little"!==t&&"le"!==t||(r="le"),new d(e,16,r)}toHex(e=0){if(this.isZero()&&0===e)return"";let t=this._getMinimalHex();"0"!==t&&t.length%2!=0&&(t="0"+t);const r=2*e;for(;t.length<r;)t="0"+t;return(this.isNeg()?"-":"")+t}static fromJSON(e){return new d(e,16)}static fromNumber(e){return new d(e)}static fromString(e,t){return new d(e,t)}static fromSm(e,t="big"){if(0===e.length)return new d(0n);let r=0,i="";if("little"===t){const t=e.length-1;let n=e[t];128&n&&(r=1,n&=127),i+=(n<16?"0":"")+n.toString(16);for(let r=t-1;r>=0;r--){const t=e[r];i+=(t<16?"0":"")+t.toString(16)}}else{let t=e[0];128&t&&(r=1,t&=127),i+=(t<16?"0":"")+t.toString(16);for(let t=1;t<e.length;t++){const r=e[t];i+=(r<16?"0":"")+r.toString(16)}}const n=""===i?0n:BigInt("0x"+i),s=new d(0n);return s._initializeState(n,r),s}toSm(e="big"){if(0n===this._magnitude)return 1===this._sign?[128]:[];let t=this._getMinimalHex();t.length%2!=0&&(t="0"+t);const r=t.length/2,i=new Array(r);for(let e=0,r=0;e<t.length;e+=2)i[r++]=parseInt(t.slice(e,e+2),16);return 1===this._sign?128&i[0]?i.unshift(128):i[0]|=128:128&i[0]&&i.unshift(0),"little"===e?i.reverse():i}static fromBits(e,t=!1){const r=e>>>24,i=8388607&e,n=!!(8388608&e);if(t&&n)throw new Error("negative bit set");if(0===r&&0===i){if(n&&t)throw new Error("negative bit set for zero value");return new d(0n)}const s=new d(i);return r<=3?s.iushrn(8*(3-r)):s.iushln(8*(r-3)),n&&s.ineg(),s}toBits(){if(this.strip(),this.isZero()&&!this.isNeg())return 0;const e=this.isNeg(),t=this.abs();let r=t.toArray("be"),i=0;for(;i<r.length-1&&0===r[i];)i++;r=r.slice(i);let n,s=r.length;if(0!==s||t.isZero()||(r=[0],s=1),t.isZero()&&(s=0,r=[]),0===s)n=0;else if(s<=3){n=0;for(let e=0;e<s;e++)n=n<<8|r[e]}else n=r[0]<<16|r[1]<<8|r[2];8388608&n&&s<=255&&(n>>>=8,s++);let a=s<<24|n;return e&&(a|=8388608),a>>>0}static fromScriptNum(e,t=!1,r){if(void 0!==r&&e.length>r)throw new Error("script number overflow");if(0===e.length)return new d(0n);if(t&&!(127&e[e.length-1]||!(e.length<=1)&&128&e[e.length-2]))throw new Error("non-minimally encoded script number");return d.fromSm(e,"little")}toScriptNum(){return this.toSm("little")}_invmp(e){this.assert(0===e._sign,"p must not be negative for _invmp"),this.assert(!e.isZero(),"p must not be zero for _invmp");let t=this.umod(e)._magnitude,r=e._magnitude,i=1n,n=0n;const s=e._magnitude;for(;t>1n&&r>1n;){let e=0;for(;0n===(t>>BigInt(e)&1n);)e++;if(e>0){t>>=BigInt(e);for(let t=0;t<e;++t)0n!==(1n&i)&&(i+=s),i>>=1n}let a=0;for(;0n===(r>>BigInt(a)&1n);)a++;if(a>0){r>>=BigInt(a);for(let e=0;e<a;++e)0n!==(1n&n)&&(n+=s),n>>=1n}t>=r?(t-=r,i-=n):(r-=t,n-=i)}let a;if(1n===t)a=i;else if(1n===r)a=n;else if(0n===t&&1n===r)a=n;else{if(0n!==r||1n!==t)throw new Error("_invmp: GCD is not 1, inverse does not exist. aVal="+t+", bVal="+r);a=i}a%=s,a<0n&&(a+=s);const o=new d(0n);return o._initializeState(a,0),o}mulTo(e,t){return t._magnitude=this._magnitude*e._magnitude,t._sign=0n===t._magnitude?0:this._sign^e._sign,t._nominalWordLength=this.length+e.length,t.red=null,t.normSign(),t}}class u{name;p;k;n;tmp;constructor(e,t){this.name=e,this.p=new d(t,16),this.n=this.p.bitLength(),this.k=new d(BigInt(1)).iushln(this.n).isub(this.p),this.tmp=this._tmp()}_tmp(){const e=new d(BigInt(0)),t=Math.ceil(this.n/d.wordSize);return e.expand(Math.max(1,t)),e}ireduce(e){const t=e;let r;do{this.split(t,this.tmp),this.imulK(t),t.iadd(this.tmp),r=t.bitLength()}while(r>this.n);const i=r<this.n?-1:t.ucmp(this.p);return 0===i?t.words=[0]:i>0&&t.isub(this.p),t.strip(),t}split(e,t){e.iushrn(this.n,0,t)}imulK(e){return e.imul(this.k)}}class h extends u{constructor(){super("k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}split(e,t){const r=4194303,i=e.words,n=e.length,s=Math.min(n,9),a=new Array(s+(n>9?1:0)).fill(0);for(let e=0;e<s;e++)a[e]=i[e];let o=s;if(n<=9){const r=new Array(o);for(let e=0;e<o;++e)r[e]=a[e];return t.words=r,void(e.words=[0])}let c=i[9];a[o++]=c&r;const d=new Array(o);for(let e=0;e<o;++e)d[e]=a[e];t.words=d;const u=new Array(Math.max(1,n-9)).fill(0);let h=0;for(let e=10;e<n;e++){const t=0|i[e];h<u.length&&(u[h++]=(t&r)<<4|c>>>22),c=t}c>>>=22,h<u.length?u[h++]=c:0!==c&&u.length;const l=new Array(h);for(let e=0;e<h;++e)l[e]=u[e];e.words=l}imulK(e){const t=e.words,r=e.length,i=r+2,n=new Array(i).fill(0);for(let e=0;e<r;e++)n[e]=t[e];let s=0;for(let e=0;e<i;e++){const t=0|n[e];s+=977*t,n[e]=67108863&s,s=64*t+(s/67108864|0)}return e.words=n,e}}class l{prime;m;constructor(e){if("k256"===e){const e=new h;this.m=e.p,this.prime=e}else this.assert(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}assert(e,t="Assertion failed"){if(!e)throw new Error(t)}verify1(e){this.assert(0===e.negative,"red works only with positives"),this.assert(e.red,"red works only with red numbers")}verify2(e,t){this.assert(!(e.negative|t.negative),"red works only with positives"),this.assert(null!=e.red&&e.red===t.red,"red works only with red numbers")}imod(e){return null!=this.prime?this.prime.ireduce(e).forceRed(this):(d.move(e,e.umod(this.m).forceRed(this)),e)}neg(e){return e.isZero()?e.clone():this.m.sub(e).forceRed(this)}add(e,t){this.verify2(e,t);const r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r.forceRed(this)}iadd(e,t){this.verify2(e,t);const r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r}sub(e,t){this.verify2(e,t);const r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r.forceRed(this)}isub(e,t){this.verify2(e,t);const r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r}shl(e,t){return this.verify1(e),this.imod(e.ushln(t))}imul(e,t){return this.verify2(e,t),this.imod(e.imul(t))}mul(e,t){return this.verify2(e,t),this.imod(e.mul(t))}isqr(e){return this.imul(e,e.clone())}sqr(e){return this.mul(e,e)}sqrt(e){if(e.isZero())return e.clone();const t=this.m.andln(3);if(this.assert(t%2==1),3===t){const t=this.m.add(new d(1)).iushrn(2);return this.pow(e,t)}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 d(1).toRed(this),s=n.redNeg(),a=this.m.subn(1).iushrn(1),o=this.m.bitLength(),c=new d(2*o*o).toRed(this);for(;0!==this.pow(c,a).cmp(s);)c.redIAdd(s);let u=this.pow(c,r),h=this.pow(e,r.addn(1).iushrn(1)),l=this.pow(e,r),f=i;for(;0!==l.cmp(n);){let e=l,t=0;for(;0!==e.cmp(n);t++)e=e.redSqr();this.assert(t<f);const r=this.pow(u,new d(1).iushln(f-t-1));h=h.redMul(r),u=r.redSqr(),l=l.redMul(u),f=t}return h}invm(e){const t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)}pow(e,t){if(t.isZero())return new d(1).toRed(this);if(0===t.cmpn(1))return e.clone();const r=new Array(16);r[0]=new d(1).toRed(this),r[1]=e;let i=2;for(;i<r.length;i++)r[i]=this.mul(r[i-1],e);let n=r[0],s=0,a=0,o=t.bitLength()%26;for(0===o&&(o=26),i=t.length-1;i>=0;i--){const e=t.words[i];for(let t=o-1;t>=0;t--){const o=e>>t&1;n!==r[0]&&(n=this.sqr(n)),0!==o||0!==s?(s<<=1,s|=o,a++,(4===a||0===i&&0===t)&&(n=this.mul(n,r[s]),a=0,s=0)):a=0}o=26}return n}convertTo(e){const t=e.umod(this.m);return t===e?t.clone():t}convertFrom(e){const t=e.clone();return t.red=null,t}}class f extends l{shift;r;r2;rinv;minv;constructor(e){super(e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new d(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}convertTo(e){return this.imod(e.ushln(this.shift))}convertFrom(e){const t=this.imod(e.mul(this.rinv));return t.red=null,t}imul(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;const r=e.imul(t),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(e,t){if(e.isZero()||t.isZero())return new d(0).forceRed(this);const r=e.mul(t),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(e){return this.imod(e._invmp(this.m).mul(this.r2)).forceRed(this)}}class p{curve;type;precomputed;constructor(e){this.curve=new Me,this.type=e,this.precomputed=null}}class b extends p{x;y;z;zOne;constructor(e,t,r){super("jacobian"),null===e&&null===t&&null===r?(this.x=this.curve.one,this.y=this.curve.one,this.z=new d(0)):(d.isBN(e)||(e=new d(e,16)),this.x=e,d.isBN(t)||(t=new d(t,16)),this.y=t,d.isBN(r)||(r=new d(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 He(null,null);const e=this.z.redInvm(),t=e.redSqr(),r=this.x.redMul(t),i=this.y.redMul(t).redMul(e);return new He(r,i)}neg(){return new b(this.x,this.y.redNeg(),this.z)}add(e){if(this.isInfinity())return e;if(e.isInfinity())return this;const t=e.z.redSqr(),r=this.z.redSqr(),i=this.x.redMul(t),n=e.x.redMul(r),s=this.y.redMul(t.redMul(e.z)),a=e.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 b(null,null,null):this.dbl();const d=o.redSqr(),u=d.redMul(o),h=i.redMul(d),l=c.redSqr().redIAdd(u).redISub(h).redISub(h),f=c.redMul(h.redISub(l)).redISub(s.redMul(u)),p=this.z.redMul(e.z).redMul(o);return new b(l,f,p)}mixedAdd(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;if(null===e.x||null===e.y)throw new Error("Point coordinates cannot be null");const t=this.z.redSqr(),r=this.x,i=e.x.redMul(t),n=this.y,s=e.y.redMul(t).redMul(this.z),a=r.redSub(i),o=n.redSub(s);if(0===a.cmpn(0))return 0!==o.cmpn(0)?new b(null,null,null):this.dbl();const c=a.redSqr(),d=c.redMul(a),u=r.redMul(c),h=o.redSqr().redIAdd(d).redISub(u).redISub(u),l=o.redMul(u.redISub(h)).redISub(n.redMul(d)),f=this.z.redMul(a);return new b(h,l,f)}dblp(e){if(0===e)return this;if(this.isInfinity())return this;if(void 0===e)return this.dbl();let t=this;for(let r=0;r<e;r++)t=t.dbl();return t}dbl(){if(this.isInfinity())return this;let e,t,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 d=s.redIAdd(s);d=d.redIAdd(d),d=d.redIAdd(d),e=c,t=o.redMul(a.redISub(c)).redISub(d),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 d=s.redIAdd(s);d=d.redIAdd(d),d=d.redIAdd(d),e=c.redISub(a).redISub(a),t=o.redMul(a.redISub(e)).redISub(d),r=this.y.redMul(this.z),r=r.redIAdd(r)}return new b(e,t,r)}eq(e){if("affine"===e.type)return this.eq(e.toJ());if(this===e)return!0;const t=this.z.redSqr(),r=e.z.redSqr();if(0!==this.x.redMul(r).redISub(e.x.redMul(t)).cmpn(0))return!1;const i=t.redMul(this.z),n=r.redMul(e.z);return 0===this.y.redMul(n).redISub(e.y.redMul(i)).cmpn(0)}eqXToP(e){const t=this.z.redSqr(),r=e.toRed(this.curve?.red).redMul(t);if(0===this.x.cmp(r))return!0;const i=e.clone();if(null===this.curve||null==this.curve.redN)throw new Error("Curve or redN is not initialized.");const n=this.curve.redN.redMul(t);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=(e,t="Hash assertion failed")=>{if(!e)throw new Error(t)};class g{pending;pendingTotal;blockSize;outSize;endian;_delta8;_delta32;padLength;hmacStrength;constructor(e,t,r,i){this.pending=null,this.pendingTotal=0,this.blockSize=e,this.outSize=t,this.hmacStrength=r,this.padLength=i/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}_update(e,t){throw new Error("Not implemented")}_digest(){throw new Error("Not implemented")}_digestHex(){throw new Error("Not implemented")}update(e,t){if(e=y(e,t),null==this.pending?this.pending=e:this.pending=this.pending.concat(e),this.pendingTotal+=e.length,this.pending.length>=this._delta8){const t=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-t,e.length),0===this.pending.length&&(this.pending=null),e=function(e,t,r,i){const n=r-0;w(n%4==0);const s=new Array(n/4);for(let t=0,r=0;t<s.length;t++,r+=4){let n;n="big"===i?e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3]:e[r+3]<<24|e[r+2]<<16|e[r+1]<<8|e[r],s[t]=n>>>0}return s}(e,0,e.length-t,this.endian);for(let t=0;t<e.length;t+=this._delta32)this._update(e,t)}return this}digest(){return this.update(this._pad()),w(null===this.pending),this._digest()}digestHex(){return this.update(this._pad()),w(null===this.pending),this._digestHex()}_pad(){let e=this.pendingTotal;const t=this._delta8,r=t-(e+this.padLength)%t,i=new Array(r+this.padLength);let n,s;for(i[0]=128,n=1;n<r;n++)i[n]=0;if(e<<=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++]=e>>>24&255,i[n++]=e>>>16&255,i[n++]=e>>>8&255,i[n++]=255&e}else for(i[n++]=255&e,i[n++]=e>>>8&255,i[n++]=e>>>16&255,i[n++]=e>>>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 m(e,t){return 55296==(64512&e.charCodeAt(t))&&!(t<0||t+1>=e.length)&&56320==(64512&e.charCodeAt(t+1))}function y(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];const r=[];if("string"==typeof e)if("hex"!==t){let t=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);n<128?r[t++]=n:n<2048?(r[t++]=n>>6|192,r[t++]=63&n|128):m(e,i)?(n=65536+((1023&n)<<10)+(1023&e.charCodeAt(++i)),r[t++]=n>>18|240,r[t++]=n>>12&63|128,r[t++]=n>>6&63|128,r[t++]=63&n|128):(r[t++]=n>>12|224,r[t++]=n>>6&63|128,r[t++]=63&n|128)}}else{(e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e);for(let t=0;t<e.length;t+=2)r.push(parseInt(e[t]+e[t+1],16))}else for(let t=0;t<e.length;t++)r[t]=0|e[t];return r}function I(e){return(e>>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}function v(e,t){let r="";for(let n=0;n<e.length;n++){let s=e[n];"little"===t&&(s=I(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(e,t){const r=new Array(4*e.length);for(let i=0,n=0;i<e.length;i++,n+=4){const s=e[i];"big"===t?(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 S(e,t){return e>>>t|e<<32-t}function E(e,t){return e<<t|e>>>32-t}function P(e,t){return e+t>>>0}function N(e,t,r){return e+t+r>>>0}function O(e,t,r,i){return e+t+r+i>>>0}function _(e,t,r,i,n){return e+t+r+i+n>>>0}function x(e,t,r,i){return 0===e?A(t,r,i):1===e||3===e?function(e,t,r){return e^t^r}(t,r,i):2===e?T(t,r,i):void 0}function A(e,t,r){return e&t^~e&r}function T(e,t,r){return e&t^e&r^t&r}function F(e){return S(e,2)^S(e,13)^S(e,22)}function R(e){return S(e,6)^S(e,11)^S(e,25)}function C(e){return S(e,7)^S(e,18)^e>>>3}const V=[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],D=[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],B=[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],U=[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 L(e,t,r,i){return e<=15?t^r^i:e<=31?t&r|~t&i:e<=47?(t|~r)^i:e<=63?t&i|r&~i:t^(r|~i)}function K(e){return e<=15?0:e<=31?1518500249:e<=47?1859775393:e<=63?2400959708:2840853838}function H(e){return e<=15?1352829926:e<=31?1548603684:e<=47?1836072691:e<=63?2053994217:0}function q(e,t,r,i){const n=e[t],s=i+e[t+1]>>>0,a=(s<i?1:0)+r+n;e[t]=a>>>0,e[t+1]=s}function M(e,t,r,i){return(t+i>>>0<t?1:0)+e+r>>>0}function $(e,t,r,i){return t+i>>>0}function z(e,t,r,i,n,s,a,o){let c=0,d=t;return d=d+i>>>0,c+=d<t?1:0,d=d+s>>>0,c+=d<s?1:0,d=d+o>>>0,c+=d<o?1:0,e+r+n+a+c>>>0}function W(e,t,r,i,n,s,a,o,c,d){let u=0,h=t;return h=h+i>>>0,u+=h<t?1:0,h=h+s>>>0,u+=h<s?1:0,h=h+o>>>0,u+=h<o?1:0,h=h+d>>>0,u+=h<d?1:0,e+r+n+a+c+u>>>0}function j(e,t,r){return(t<<32-r|e>>>r)>>>0}function X(e,t,r){return(e<<32-r|t>>>r)>>>0}function G(e,t,r){return e>>>r}function Y(e,t,r){return(e<<32-r|t>>>r)>>>0}class J extends g{h;constructor(){super(512,160,192,64),this.endian="little",this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}_update(e,t){let r,i=this.h[0],n=this.h[1],s=this.h[2],a=this.h[3],o=this.h[4],c=i,d=n,u=s,h=a,l=o;for(let f=0;f<80;f++)r=P(E(O(i,L(f,n,s,a),e[V[f]+t],K(f)),B[f]),o),i=o,o=a,a=E(s,10),s=n,n=r,r=P(E(O(c,L(79-f,d,u,h),e[D[f]+t],H(f)),U[f]),l),c=l,l=h,h=E(u,10),u=d,d=r;r=N(this.h[1],s,h),this.h[1]=N(this.h[2],a,l),this.h[2]=N(this.h[3],o,c),this.h[3]=N(this.h[4],i,d),this.h[4]=N(this.h[0],n,u),this.h[0]=r}_digest(){return k(this.h,"little")}_digestHex(){return v(this.h,"little")}}class Z extends g{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(e,t){const r=this.W;let i;for(void 0===t&&(t=0),i=0;i<16;i++)r[i]=e[t+i];for(;i<r.length;i++)r[i]=O(S(n=r[i-2],17)^S(n,19)^n>>>10,r[i-7],C(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],d=this.h[4],u=this.h[5],h=this.h[6],l=this.h[7];for(w(this.k.length===r.length),i=0;i<r.length;i++){const e=_(l,R(d),A(d,u,h),this.k[i],r[i]),t=P(F(s),T(s,a,o));l=h,h=u,u=d,d=P(c,e),c=o,o=a,a=s,s=P(e,t)}this.h[0]=P(this.h[0],s),this.h[1]=P(this.h[1],a),this.h[2]=P(this.h[2],o),this.h[3]=P(this.h[3],c),this.h[4]=P(this.h[4],d),this.h[5]=P(this.h[5],u),this.h[6]=P(this.h[6],h),this.h[7]=P(this.h[7],l)}_digest(){return k(this.h,"big")}_digestHex(){return v(this.h,"big")}}class Q extends g{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(e,t){const r=this.W;let i;for(void 0===t&&(t=0),i=0;i<16;i++)r[i]=e[t+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 e=~~(i/20),t=_(E(n,5),x(e,s,a,o),c,r[i],this.k[e]);c=o,o=a,a=E(s,30),s=n,n=t}this.h[0]=P(this.h[0],n),this.h[1]=P(this.h[1],s),this.h[2]=P(this.h[2],a),this.h[3]=P(this.h[3],o),this.h[4]=P(this.h[4],c)}_digest(){return k(this.h,"big")}_digestHex(){return v(this.h,"big")}}class ee extends g{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(e,t){const r=this.W;let i;for(i=0;i<32;i++)r[i]=e[t+i];for(;i<r.length;i+=2){const e=he(r[i-4],r[i-3]),t=le(r[i-4],r[i-3]),n=r[i-14],s=r[i-13],a=de(r[i-30],r[i-29]),o=ue(r[i-30],r[i-29]),c=r[i-32],d=r[i-31];r[i]=z(e,t,n,s,a,o,c,d),r[i+1]=t+s+o+d>>>0}}_update(e,t){this._prepareBlock(e,t);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],d=this.h[6],u=this.h[7],h=this.h[8],l=this.h[9],f=this.h[10],p=this.h[11],b=this.h[12],g=this.h[13],m=this.h[14],y=this.h[15];w(this.k.length===r.length);for(let e=0;e<r.length;e+=2){let t=m,w=y,I=oe(h,l),v=ce(h,l);const k=te(h,0,f,0,b),S=re(0,l,0,p,0,g),E=this.k[e],P=this.k[e+1],N=r[e],O=r[e+1],_=W(t,w,I,v,k,S,E,P,N,O),x=w+v+S+P+O>>>0;t=se(i,n),w=ae(i,n),I=ie(i,0,s,0,o),v=ne(0,n,0,a,0,c);const A=M(t,w,I,v),T=$(0,w,0,v);m=b,y=g,b=f,g=p,f=h,p=l,h=M(d,u,_,x),l=$(0,u,0,x),d=o,u=c,o=s,c=a,s=i,a=n,i=M(_,x,A,T),n=$(0,x,0,T)}q(this.h,0,i,n),q(this.h,2,s,a),q(this.h,4,o,c),q(this.h,6,d,u),q(this.h,8,h,l),q(this.h,10,f,p),q(this.h,12,b,g),q(this.h,14,m,y)}_digest(){return k(this.h,"big")}_digestHex(){return v(this.h,"big")}}function te(e,t,r,i,n,s){let a=e&r^~e&n;return a<0&&(a+=4294967296),a}function re(e,t,r,i,n,s){let a=t&i^~t&s;return a<0&&(a+=4294967296),a}function ie(e,t,r,i,n,s){let a=e&r^e&n^r&n;return a<0&&(a+=4294967296),a}function ne(e,t,r,i,n,s){let a=t&i^t&s^i&s;return a<0&&(a+=4294967296),a}function se(e,t){let r=j(e,t,28)^j(t,e,2)^j(t,e,7);return r<0&&(r+=4294967296),r}function ae(e,t){let r=X(e,t,28)^X(t,e,2)^X(t,e,7);return r<0&&(r+=4294967296),r}function oe(e,t){let r=j(e,t,14)^j(e,t,18)^j(t,e,9);return r<0&&(r+=4294967296),r}function ce(e,t){let r=X(e,t,14)^X(e,t,18)^X(t,e,9);return r<0&&(r+=4294967296),r}function de(e,t){let r=j(e,t,1)^j(e,t,8)^G(e,0,7);return r<0&&(r+=4294967296),r}function ue(e,t){let r=X(e,t,1)^X(e,t,8)^Y(e,t,7);return r<0&&(r+=4294967296),r}function he(e,t){let r=j(e,t,19)^j(t,e,29)^G(e,0,6);return r<0&&(r+=4294967296),r}function le(e,t){let r=X(e,t,19)^X(t,e,29)^Y(e,t,6);return r<0&&(r+=4294967296),r}class fe{inner;outer;blockSize=64;outSize=32;constructor(e){let t;for((e=y(e,"hex")).length>this.blockSize&&(e=(new Z).update(e).digest()),w(e.length<=this.blockSize),t=e.length;t<this.blockSize;t++)e.push(0);for(t=0;t<e.length;t++)e[t]^=54;for(this.inner=(new Z).update(e),t=0;t<e.length;t++)e[t]^=106;this.outer=(new Z).update(e)}update(e,t){return this.inner.update(e,t),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}}class pe{inner;outer;blockSize=64;constructor(e){let t;for((e=y(e,"hex")).length>this.blockSize&&(e=(new Q).update(e).digest()),t=e.length;t<this.blockSize;t++)e.push(0);for(t=0;t<e.length;t++)e[t]^=54;for(this.inner=(new Q).update(e),t=0;t<e.length;t++)e[t]^=106;this.outer=(new Q).update(e)}update(e,t){return this.inner.update(e,t),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}}class be{inner;outer;blockSize=128;outSize=32;constructor(e){let t;for((e=y(e,"hex")).length>this.blockSize&&(e=(new ee).update(e).digest()),w(e.length<=this.blockSize),t=e.length;t<this.blockSize;t++)e.push(0);for(t=0;t<e.length;t++)e[t]^=54;for(this.inner=(new ee).update(e),t=0;t<e.length;t++)e[t]^=106;this.outer=(new ee).update(e)}update(e,t){return this.inner.update(e,t),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}}const we=(e,t)=>(new J).update(e,t).digest(),ge=(e,t)=>(new Q).update(e,t).digest(),me=(e,t)=>(new Z).update(e,t).digest(),ye=(e,t)=>(new ee).update(e,t).digest(),Ie=(e,t)=>{const r=(new Z).update(e,t).digest();return(new Z).update(r).digest()},ve=(e,t)=>{const r=(new Z).update(e,t).digest();return(new J).update(r).digest()},ke=(e,t,r)=>new fe(e).update(t,r).digest(),Se=(e,t,r)=>new be(e).update(t,r).digest();function Ee(e,t,r,i,n="sha512"){if("sha512"!==n)throw new Error("Only sha512 is supported in this PBKDF2 implementation");const s=new Array(i),a=[...t,0,0,0,0];let o=0;const c=Math.ceil(i/64);for(let i=1;i<=c;i++){a[t.length]=i>>24&255,a[t.length+1]=i>>16&255,a[t.length+2]=i>>8&255,a[t.length+3]=255&i;const n=Se(e,a);let c=n;for(let t=1;t<r;t++){c=Se(e,c);for(let e=0;e<64;e++)n[e]^=c[e]}for(let e=0;e<n.length;e++)s[o+e]=n[e];o+=64}return s.slice(0,i)}const Pe=e=>e.length%2==1?"0"+e:e,Ne=e=>{let t="";for(const r of e)t+=Pe(r.toString(16));return t},Oe=(e,t)=>{if(Array.isArray(e))return e.slice();if(void 0===e)return[];if("string"!=typeof e)return Array.from(e,(e=>0|e));switch(t){case"hex":return _e(e);case"base64":return xe(e);default:return function(e){const t=[];for(let r=0;r<e.length;r++){const i=e.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?t.push(n):n<=2047?t.push(192|n>>6,128|63&n):n<=65535?t.push(224|n>>12,128|n>>6&63,128|63&n):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}return t}(e)}},_e=e=>{(e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e);const t=[];for(let r=0;r<e.length;r+=2)t.push(parseInt(e[r]+e[r+1],16));return t},xe=e=>{const t=[];let r=0,i=0;for(const n of e.replace(/=+$/,""))r=r<<6|"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(n),i+=6,i>=8&&(i-=8,t.push(r>>i&255),r&=(1<<i)-1);return t},Ae=e=>{let t="",r=0;for(let i=0;i<e.length;i++){const n=e[i];if(r>0)r--;else if(n<=127)t+=String.fromCharCode(n);else if(n>=192&&n<=223){r=1;const s=(31&n)<<6|63&e[i+1];t+=String.fromCharCode(s)}else if(n>=224&&n<=239){r=2;const s=(15&n)<<12|(63&e[i+1])<<6|63&e[i+2];t+=String.fromCharCode(s)}else if(n>=240&&n<=247){r=3;const s=(7&n)<<18|(63&e[i+1])<<12|(63&e[i+2])<<6|63&e[i+3],a=55296+(s-65536>>10),o=56320+(s-65536&1023);t+=String.fromCharCode(a,o)}}return t},Te=(e,t)=>{switch(t){case"hex":return Ne(e);case"utf8":return Ae(e);default:return e}};function Fe(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r,i="";for(r=0;r<e.length;r+=3){const n=e[r],s=r+1<e.length?e[r+1]:0,a=r+2<e.length?e[r+2]:0,o=(3&n)<<4|s>>4,c=(15&s)<<2|a>>6,d=63&a;i+=t.charAt(n>>2)+t.charAt(o),i+=r+1<e.length?t.charAt(c):"=",i+=r+2<e.length?t.charAt(d):"="}return i}const Re="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Ce=e=>{if(""===e||"string"!=typeof e)throw new Error(`Expected base58 string but got “${e}”`);const t=e.match(/[IOl0]/gmu);if(null!==t)throw new Error(`Invalid base58 character “${t.join("")}”`);const r=e.match(/^1+/gmu),i=null!==r?r[0].length:0,n=(e.length-i)*(Math.log(58)/Math.log(256))+1>>>0;var s;return[...new Uint8Array([...new Uint8Array(i),...(e.match(/./gmu)??[]).map((e=>Re.indexOf(e))).reduce(((e,t)=>e.map((e=>{const r=58*e+t;return t=r>>8,r}))),new Uint8Array(n)).reverse().filter((s=!1,e=>s=s||e))])]},Ve=e=>{const t=Array(256).fill(-1);for(let e=0;e<58;++e)t[Re.charCodeAt(e)]=e;const r=[];for(const i of e){let e=i;for(let i=0;i<r.length;++i){const n=(t[r[i]]<<8)+e;r[i]=Re.charCodeAt(n%58),e=n/58|0}for(;0!==e;)r.push(Re.charCodeAt(e%58)),e=e/58|0}for(const t of e){if(0!==t)break;r.push("1".charCodeAt(0))}return r.reverse(),String.fromCharCode(...r)},De=(e,t=[0])=>{let r=Ie([...t,...e]);return r=[...t,...e,...r.slice(0,4)],Ve(r)},Be=(e,t,r=1)=>{const i=Ce(e);let n=i.slice(0,r),s=i.slice(r,-4),a=[...n,...s];return a=Ie(a),i.slice(-4).forEach(((e,t)=>{if(e!==a[t])throw new Error("Invalid checksum")})),"hex"===t&&(n=Ne(n),s=Ne(s)),{prefix:n,data:s}};class Ue{bufs;length;constructor(e){this.bufs=void 0!==e?e:[],this.length=0;for(const e of this.bufs)this.length+=e.length}getLength(){return this.length}toArray(){const e=this.length,t=new Array(e);let r=0;for(const e of this.bufs)for(const i of e)t[r++]=i;return t}write(e){return this.bufs.push(e),this.length+=e.length,this}writeReverse(e){const t=new Array(e.length);for(let r=0;r<t.length;r++)t[r]=e[e.length-1-r];return this.bufs.push(t),this.length+=t.length,this}writeUInt8(e){const t=new Array(1);return t[0]=e,this.write(t),this}writeInt8(e){const t=new Array(1);return t[0]=255&e,this.write(t),this}writeUInt16BE(e){const t=[e>>8&255,255&e];return this.bufs.push(t),this.length+=2,this}writeInt16BE(e){return this.writeUInt16BE(65535&e)}writeUInt16LE(e){const t=[255&e,e>>8&255];return this.bufs.push(t),this.length+=2,this}writeInt16LE(e){return this.writeUInt16LE(65535&e)}writeUInt32BE(e){const t=[e>>24&255,e>>16&255,e>>8&255,255&e];return this.bufs.push(t),this.length+=4,this}writeInt32BE(e){return this.writeUInt32BE(e>>>0)}writeUInt32LE(e){const t=[255&e,e>>8&255,e>>16&255,e>>24&255];return this.bufs.push(t),this.length+=4,this}writeInt32LE(e){return this.writeUInt32LE(e>>>0)}writeUInt64BEBn(e){const t=e.toArray("be",8);return this.write(t),this}writeUInt64LEBn(e){const t=e.toArray("be",8);return this.writeReverse(t),this}writeUInt64LE(e){const t=new d(e).toArray("be",8);return this.writeReverse(t),this}writeVarIntNum(e){const t=Ue.varIntNum(e);return this.write(t),this}writeVarIntBn(e){const t=Ue.varIntBn(e);return this.write(t),this}static varIntNum(e){let t;if(e<253)t=[e];else if(e<65536)t=[253,255&e,e>>8&255];else if(e<4294967296)t=[254,255&e,e>>8&255,e>>16&255,e>>24&255];else{const r=4294967295&e,i=4294967295&Math.floor(e/4294967296);t=[255,255&r,r>>8&255,r>>16&255,r>>24&255,255&i,i>>8&255,i>>16&255,i>>24&255]}return t}static varIntBn(e){let t;if(e.ltn(253))t=[e.toNumber()];else if(e.ltn(65536)){const r=e.toNumber();t=[253,255&r,r>>8&255]}else if(e.lt(new d(4294967296))){const r=e.toNumber();t=[254,255&r,r>>8&255,r>>16&255,r>>24&255]}else{const r=new Ue;r.writeUInt8(255),r.writeUInt64LEBn(e),t=r.toArray()}return t}}class Le{bin;pos;length;constructor(e=[],t=0){this.bin=e,this.pos=t,this.length=e.length}eof(){return this.pos>=this.length}read(e=this.length){const t=this.pos,r=this.pos+e;return this.pos=r,this.bin.slice(t,r)}readReverse(e=this.length){const t=new Array(e);for(let r=0;r<e;r++)t[r]=this.bin[this.pos+e-1-r];return this.pos+=e,t}readUInt8(){const e=this.bin[this.pos];return this.pos+=1,e}readInt8(){const e=this.bin[this.pos];return this.pos+=1,128&e?e-256:e}readUInt16BE(){const e=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,e}readInt16BE(){const e=this.readUInt16BE();return 32768&e?e-65536:e}readUInt16LE(){const e=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,e}readInt16LE(){const e=this.readUInt16LE();return 32768&e?e-65536:e}readUInt32BE(){const e=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,e}readInt32BE(){const e=this.readUInt32BE();return 2147483648&e?e-4294967296:e}readUInt32LE(){const e=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,e}readInt32LE(){const e=this.readUInt32LE();return 2147483648&e?e-4294967296:e}readUInt64BEBn(){const e=this.bin.slice(this.pos,this.pos+8),t=new d(e);return this.pos=this.pos+8,t}readUInt64LEBn(){const e=this.readReverse(8);return new d(e)}readVarIntNum(){const e=this.readUInt8();let t;switch(e){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if(t=this.readUInt64LEBn(),t.lte(new d(2).pow(new d(53))))return t.toNumber();throw new Error("number too large to retain precision - use readVarIntBn");default:return e}}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 e=this.readUInt8();switch(e){case 253:return new d(this.readUInt16LE());case 254:return new d(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new d(e)}}}const Ke=e=>{if(0===e.length)return e;const t=e[e.length-1];if(127&t)return e;if(1===e.length)return[];if(128&e[e.length-2])return e;for(let r=e.length-1;r>0;r--)if(0!==e[r-1])return 128&e[r-1]?(e[r]=t,e.slice(0,r+1)):(e[r-1]|=t,e.slice(0,r));return[]};class He extends p{static red=new l("k256");static a=new d(0).toRed(He.red);static b=new d(7).toRed(He.red);static zero=new d(0).toRed(He.red);x;y;inf;static fromDER(e){if((4===e[0]||6===e[0]||7===e[0])&&e.length-1==64){if(6===e[0]){if(e[e.length-1]%2!=0)throw new Error("Point string value is wrong length")}else if(7===e[0]&&e[e.length-1]%2!=1)throw new Error("Point string value is wrong length");return new He(e.slice(1,33),e.slice(33,65))}if((2===e[0]||3===e[0])&&e.length-1==32)return He.fromX(e.slice(1,33),3===e[0]);throw new Error("Unknown point format")}static fromString(e){const t=Oe(e,"hex");return He.fromDER(t)}static redSqrtOptimized(e){const t=He.red.m.addn(1).iushrn(2);return e.redPow(t)}static fromX(e,t){if("function"==typeof BigInt){function r(e,t){return(e%t+t)%t}function i(e,t,i){let n=BigInt(1);for(e=r(e,i);t>BigInt(0);)(t&BigInt(1))===BigInt(1)&&(n=r(n*e,i)),t>>=BigInt(1),e=r(e*e,i);return n}function n(e,t){const n=i(e,t+BigInt(1)>>BigInt(2),t);return r(n*n,t)===r(e,t)?n:null}const s=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),a=BigInt(7);let o;if(e instanceof d)o=BigInt("0x"+e.toString(16));else if("string"==typeof e)o=BigInt("0x"+e);else if(Array.isArray(e))o=BigInt("0x"+Ne(e).padStart(64,"0"));else{if("number"!=typeof e)throw new Error("Invalid x-coordinate type");o=BigInt(e)}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);(t&&!u||!t&&u)&&(c=s-c);const h=new d(o.toString(16),16),f=new d(c.toString(16),16);return new He(h,f)}{const p=new l("k256"),b=new d(0).toRed(p),w=new d(7).toRed(p),g=new d(0).toRed(p);d.isBN(e)||(e=new d(e,16)),null==e.red&&(e=e.toRed(p));const m=e.redSqr().redMul(e).redIAdd(e.redMul(b)).redIAdd(w);let y=m.redSqrt();if(0!==y.redSqr().redSub(m).cmp(g))throw new Error("invalid point");const I=y.fromRed().isOdd();return(t&&!I||!t&&I)&&(y=y.redNeg()),new He(e,y)}}static fromJSON(e,t){"string"==typeof e&&(e=JSON.parse(e));const r=new He(e[0],e[1],t);if("object"!=typeof e[2])return r;const i=e=>new He(e[0],e[1],t),n=e[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(e,t,r=!0){super("affine"),this.precomputed=null,null===e&&null===t?(this.x=null,this.y=null,this.inf=!0):(d.isBN(e)||(e=new d(e,16)),this.x=e,d.isBN(t)||(t=new d(t,16)),this.y=t,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(e=!0,t){const r=this.curve.p.byteLength(),i=this.getX().toArray("be",r);let n;return n=e?[this.getY().isEven()?2:3].concat(i):[4].concat(i,this.getY().toArray("be",r)),"hex"!==t?n:Ne(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(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return new He(new d(0),new d(0));if(0===this.x?.cmp(e.x??new d(0)))return new He(new d(0),new d(0));let t=this.y?.redSub(e.y??new d(0))??new d(0);0!==t.cmpn(0)&&(t=t.redMul(this.x?.redSub(e.x??new d(0)).redInvm()??new d(1)));const r=t?.redSqr().redISub(this.x??new d(0)).redISub(e.x??new d(0)),i=(t??new d(1)).redMul((this.x??new d(0)).redSub(r??new d(0))).redISub(this.y??new d(0));return new He(r??new d(0),i??new d(0))}dbl(){if(this.inf)return this;const e=(this.y??new d(0)).redAdd(this.y??new d(0));if(0===e.cmpn(0))return new He(new d(0),new d(0));const t=this.curve.a,r=(this.x??new d(0)).redSqr(),i=e.redInvm(),n=r.redAdd(r).redIAdd(r).redIAdd(t).redMul(i),s=n.redSqr().redISub((this.x??new d(0)).redAdd(this.x??new d(0))),a=n.redMul((this.x??new d(0)).redSub(s)).redISub(this.y??new d(0));return new He(s,a)}getX(){return(this.x??new d(0)).fromRed()}getY(){return(this.y??new d(0)).fromRed()}mul(e){return d.isBN(e)||(e=new d(e,16)),this.isInfinity()?this:this._hasDoubles(e)?this._fixedNafMul(e):this._endoWnafMulAdd([this],[e])}mulAdd(e,t,r){const i=[this,t],n=[e,r];return this._endoWnafMulAdd(i,n)}jmulAdd(e,t,r){const i=[this,t],n=[e,r];return this._endoWnafMulAdd(i,n,!0)}eq(e){return this===e||this.inf===e.inf&&(this.inf||0===(this.x??new d(0)).cmp(e.x??new d(0))&&0===(this.y??new d(0)).cmp(e.y??new d(0)))}neg(e){if(this.inf)return this;const t=new He(this.x,(this.y??new d(0)).redNeg());if(!0===e&&null!=this.precomputed){const e=this.precomputed,r=e=>e.neg();t.precomputed={naf:null!=e.naf?{wnd:e.naf.wnd,points:e.naf.points.map(r)}:void 0,doubles:null!=e.doubles?{step:e.doubles.step,points:e.doubles.points.map((e=>e.neg()))}:void 0,beta:void 0}}return t}dblp(e){let t=this;for(let r=0;r<e;r++)t=t.dbl();return t}toJ(){return this.inf?new b(null,null,null):new b(this.x,this.y,this.curve.one)}_getBeta(){if("object"!=typeof this.curve.endo)return;const e=this.precomputed;if("object"==typeof e&&null!==e&&"object"==typeof e.beta&&null!==e.beta)return e.beta;const t=new He((this.x??new d(0)).redMul(this.curve.endo.beta),this.y);if(null!=e){const r=this.curve,i=e=>{if(null===e.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 He(e.x.redMul(r.endo.beta),e.y)};e.beta=t,t.precomputed={beta:null,naf:null!=e.naf?{wnd:e.naf.wnd,points:e.naf.points.map(i)}:void 0,doubles:null!=e.doubles?{step:e.doubles.step,points:e.doubles.points.map(i)}:void 0}}return t}_fixedNafMul(e){if("object"!=typeof this.precomputed||null===this.precomputed)throw new Error("_fixedNafMul requires precomputed values for the point");const t=this._getDoubles(),r=this.curve.getNAF(e,1,this.curve._bitLength);let i=(1<<t.step+1)-(t.step%2==0?2:1);i/=3;const n=[];for(let e=0;e<r.length;e+=t.step){let i=0;for(let n=e+t.step-1;n>=e;n--)i=(i<<1)+r[n];n.push(i)}let s=new b(null,null,null),a=new b(null,null,null);for(let e=i;e>0;e--){for(let r=0;r<n.length;r++){const i=n[r];i===e?a=a.mixedAdd(t.points[r]):i===-e&&(a=a.mixedAdd(t.points[r].neg()))}s=s.add(a)}return s.toP()}_wnafMulAdd(e,t,r,i,n){const s=this.curve._wnafT1.map((e=>e.toNumber())),a=this.curve._wnafT2.map((()=>[])),o=this.curve._wnafT3.map((()=>[]));let c=0;for(let r=0;r<i;r++){const i=t[r]._getNAFPoints(e);s[r]=i.wnd,a[r]=i.points}for(let e=i-1;e>=1;e-=2){const i=e-1,n=e;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=[t[i],null,null,t[n]];0===(t[i].y??new d(0)).cmp(t[n].y??new d(0))?(u[1]=t[i].add(t[n]),u[2]=t[i].toJ().mixedAdd(t[n].neg())):0===(t[i].y??new d(0)).cmp((t[n].y??new d(0)).redNeg())?(u[1]=t[i].toJ().mixedAdd(t[n]),u[2]=t[i].add(t[n].neg())):(u[1]=t[i].toJ().mixedAdd(t[n]),u[2]=t[i].toJ().mixedAdd(t[n].neg()));const h=[-3,-1,-5,-7,0,7,5,1,3],l=this.curve.getJSF(r[i],r[n]);c=Math.max(l[0].length,c),o[i]=new Array(c),o[n]=new Array(c);for(let e=0;e<c;e++){const t=0|l[0][e],r=0|l[1][e];o[i][e]=h[3*(t+1)+(r+1)],o[n][e]=0,a[i]=u}}let u=new b(null,null,null);const h=this.curve._wnafT4;for(let e=c;e>=0;e--){let t=0;for(;e>=0;){let r=!0;for(let t=0;t<i;t++)h[t]=new d("number"==typeof o[t][e]?o[t][e]:0),h[t].isZero()||(r=!1);if(!r)break;t++,e--}if(e>=0&&t++,u=u.dblp(t),e<0)break;const r=new d(1),n=new d(2);for(let e=0;e<i;e++){const t=h[e];let i;0!==t.cmpn(0)&&(i=t.isNeg()?a[e][t.neg().sub(r).div(n).toNumber()].neg():a[e][t.sub(r).div(n).toNumber()],u="affine"===i.type?u.mixedAdd(i):u.add(i))}}for(let e=0;e<i;e++)a[e]=[];return!0===n?u:u.toP()}_endoWnafMulAdd(e,t,r){const i=new Array(2*e.length),n=new Array(2*e.length);let s;for(s=0;s<e.length;s++){const r=this.curve._endoSplit(t[s]);let a=e[s],o=a._getBeta()??new He(new d(0),new d(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 e=0;e<2*s;e++)i[e]=null,n[e]=null;return a}_hasDoubles(e){if(null==this.precomputed)return!1;const t=this.precomputed.doubles;return"object"==typeof t&&t.points.length>=Math.ceil((e.bitLength()+1)/t.step)}_getDoubles(e,t){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.doubles&&null!==this.precomputed.doubles)return this.precomputed.doubles;const r=[this];let i=this;for(let n=0;n<(t??0);n+=e??1){for(let t=0;t<(e??1);t++)i=i.dbl();r.push(i)}return{step:e??1,points:r}}_getNAFPoints(e){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.naf&&null!==this.precomputed.naf)return this.precomputed.naf;const t=[this],r=(1<<e)-1,i=1===r?null:this.dbl();for(let e=1;e<r;e++)null!==i&&(t[e]=t[e-1].add(i));return{wnd:e,points:t}}}let qe;class Me{p;red;redN;zero;one;two;g;n;a;b;tinv;zeroA;threeA;endo;_endoWnafT1;_endoWnafT2;_wnafT1;_wnafT2;_wnafT3;_wnafT4;_bitLength;static assert(e,t="Elliptic curve assertion failed"){if(!e)throw new Error(t)}getNAF(e,t,r){const i=new Array(Math.max(e.bitLength(),r)+1);i.fill(0);const n=1<<t+1,s=e.clone();for(let e=0;e<i.length;e++){let t;const r=s.andln(n-1);s.isOdd()?(t=r>(n>>1)-1?(n>>1)-r:r,s.isubn(t)):t=0,i[e]=t,s.iushrn(1)}return i}getJSF(e,t){const r=[[],[]];e=e.clone(),t=t.clone();let i=0,n=0;for(;e.cmpn(-i)>0||t.cmpn(-n)>0;){let s,a,o=e.andln(3)+i&3,c=t.andln(3)+n&3;if(3===o&&(o=-1),3===c&&(c=-1),1&o){const t=e.andln(7)+i&7;s=3!==t&&5!==t||2!==c?o:-o}else s=0;if(r[0].push(s),1&c){const e=t.andln(7)+n&7;a=3!==e&&5!==e||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),e.iushrn(1),t.iushrn(1)}return r}static cachedProperty(e,t,r){const i="_"+t;e.prototype[t]=function(){return void 0!==this[i]?this[i]:this[i]=r.call(this)}}static parseBytes(e){return"string"==typeof e?Oe(e,"hex"):e}static intFromLE(e){return new d(e,"hex","le")}constructor(){if(void 0!==qe)return qe;qe=this;const e={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 d(e.p,16),this.red=new l(e.prime),this.zero=new d(0).toRed(this.red),this.one=new d(1).toRed(this.red),this.two=new d(2).toRed(this.red),this.n=new d(e.n,16),this.g=He.fromJSON(e.g,e.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 d(e.a,16).toRed(this.red),this.b=new d(e.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(e),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}_getEndomorphism(e){if(!this.zeroA||1!==this.p.modrn(3))return;let t,r,i;if(void 0!==e.beta)t=new d(e.beta,16).toRed(this.red);else{const e=this._getEndoRoots(this.p);if(null===e)throw new Error("Failed to get endomorphism roots for beta.");t=e[0].cmp(e[1])<0?e[0]:e[1],t=t.toRed(this.red)}if(void 0!==e.lambda)r=new d(e.lambda,16);else{const e=this._getEndoRoots(this.n);if(null===e)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(e[0])?.x,n=null!=this.g.x?this.g.x.redMul(t):void 0;if(null!=i&&null!=n&&0===i.cmp(n))r=e[0];else{if(r=e[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(t):void 0;if(null==i||null==n)throw new Error("Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.");Me.assert(0===i.cmp(n),"Lambda selection does not match computed beta.")}}return i="object"==typeof e.basis&&null!==e.basis?e.basis.map((function(e){return{a:new d(e.a,16),b:new d(e.b,16)}})):this._getEndoBasis(r),{beta:t,lambda:r,basis:i}}_getEndoRoots(e){const t=e===this.p?this.red:new f(e),r=new d(2).toRed(t).redInvm(),i=r.redNeg(),n=new d(3).toRed(t).redNeg().redSqrt().redMul(r);return[i.redAdd(n).fromRed(),i.redSub(n).fromRed()]}_getEndoBasis(e){const t=this.n.ushrn(Math.floor(this.n.bitLength()/2));let r,i,n,s,a,o,c=e,u=this.n.clone(),h=new d(1),l=new d(0),f=new d(0),p=new d(1),b=new d(0),w=0,g=new d(0),m=new d(0);for(;0!==c.cmpn(0);){const e=u.div(c);g=u.sub(e.mul(c)),m=f.sub(e.mul(h));const a=p.sub(e.mul(l));if(void 0===n&&g.cmp(t)<0)r=b.neg(),i=h,n=g.neg(),s=m;else if(void 0!==n&&2==++w)break;b=g,u=c,c=g,f=h,h=m,p=l,l=a}if(void 0===r||void 0===i||void 0===n||void 0===s)throw new Error("Failed to compute Endo Basis values");a=g.neg(),o=m;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(e){if(null==this.endo)throw new Error("Endomorphism is not defined.");const t=this.endo.basis,r=t[0],i=t[1],n=i.b.mul(e).divRound(this.n),s=r.b.neg().mul(e).divRound(this.n),a=n.mul(r.a),o=s.mul(i.a),c=n.mul(r.b),d=s.mul(i.b);return{k1:e.sub(a).sub(o),k2:c.add(d).neg()}}validate(e){if(e.inf)return!0;const t=e.x,r=e.y;if(null===t||null===r)throw new Error("Point coordinates cannot be null");const i=this.a.redMul(t),n=t.redSqr().redMul(t).redIAdd(i).redIAdd(this.b);return 0===r.redSqr().redISub(n).cmpn(0)}}class $e{r;s;static fromDER(e,t){const r=(e,t)=>{const r=e[t.place++];if(128&r)throw new Error("Invalid DER entity length");return r};e=Oe(e,t);const i=new class{place;constructor(){this.place=0}};if(48!==e[i.place++])throw new Error("Signature DER must start with 0x30");if(r(e,i)+i.place!==e.length)throw new Error("Signature DER invalid");if(2!==e[i.place++])throw new Error("Signature DER invalid");const n=r(e,i);let s=e.slice(i.place,n+i.place);if(i.place+=n,2!==e[i.place++])throw new Error("Signature DER invalid");const a=r(e,i);if(e.length!==a+i.place)throw new Error("Invalid R-length in signature DER");let o=e.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 $e(new d(s),new d(o))}static fromCompact(e,t){if(65!==(e=Oe(e,t)).length)throw new Error("Invalid Compact Signature");const r=e[0];if(r<27||r>=35)throw new Error("Invalid Compact Byte");return new $e(new d(e.slice(1,33)),new d(e.slice(33,65)))}constructor(e,t){this.r=e,this.s=t}verify(e,t,r){const i=new d(me(e,r),16);return Xe(i,this,t)}toString(e){return this.toDER(e)}toDER(e){const t=(e,t)=>{if(!(t<128))throw new Error("len must be < 0x80");e.push(t)},r=e=>{let t=0;const r=e.length-1;for(;0===e[t]&&!(128&e[t+1])&&t<r;)t++;return 0===t?e:e.slice(t)};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];t(s,i.length),s=s.concat(i),s.push(2),t(s,n.length);const a=s.concat(n);let o=[48];return t(o,a.length),o=o.concat(a),"hex"===e?Ne(o):"base64"===e?Fe(o):o}toCompact(e,t,r){if(e<0||e>3)throw new Error("Invalid recovery param");if("boolean"!=typeof t)throw new Error("Invalid compressed param");let i=27+e;t&&(i+=4);let n=[i];return n=n.concat(this.r.toArray("be",32)),n=n.concat(this.s.toArray("be",32)),"hex"===r?Ne(n):"base64"===r?Fe(n):n}RecoverPublicKey(e,t){const r=this.r,i=this.s,n=!!(1&e),s=e>>1,a=new Me,o=a.n,c=a.g,d=0!==s?r.add(o):r,u=He.fromX(d,n);if(!u.mul(o).isInfinity())throw new Error("nR is not at infinity");const h=t.neg().umod(o),l=r.invm(o),f=l.mul(i).umod(o),p=l.mul(h).umod(o),b=c.mul(p).add(u.mul(f)),w=new Ge(b);return w.validate(),w}CalculateRecoveryFactor(e,t){for(let r=0;r<4;r++){let i;try{i=this.RecoverPublicKey(r,t)}catch{continue}if(e.eq(i))return r}throw new Error("Unable to find valid recovery factor")}}class ze{K;V;constructor(e,t){if(e=Oe(e,"hex"),t=Oe(t,"hex"),e.length<32)throw new Error("Not enough entropy. Minimum is 256 bits");const r=e.concat(t);this.K=new Array(32),this.V=new Array(32);for(let e=0;e<32;e++)this.K[e]=0,this.V[e]=1;this.update(r)}hmac(){return new fe(this.K)}update(e){let t=this.hmac().update(this.V).update([0]);void 0!==e&&(t=t.update(e)),this.K=t.digest(),this.V=this.hmac().update(this.V).digest(),void 0!==e&&(this.K=this.hmac().update(this.V).update([1]).update(e).digest(),this.V=this.hmac().update(this.V).digest())}generate(e){let t=[];for(;t.length<e;)this.V=this.hmac().update(this.V).digest(),t=t.concat(this.V);const r=t.slice(0,e);return this.update(),Ne(r)}}function We(e,t,r=new Me){const i=8*e.byteLength()-r.n.bitLength();return i>0&&e.iushrn(i),null===t&&e.cmp(r.n)>=0?e.sub(r.n):e}const je=(e,t,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")},h=BigInt("0x"+e.toString(16)),l=BigInt("0x"+t.toString(16));if(l<=n||l>=o)throw new Error("Invalid private key");function f(e,t){const r=e.toString(16).padStart(2*t,"0"),i=new Uint8Array(t);for(let e=0;e<t;e++)i[e]=parseInt(r.substr(2*e,2),16);return i}const p=32,b=f(l,p),w=f(h,p),g=new ze(Array.from(b),Array.from(w)),m=o-s;let y=0;function I(e,t,r=!0){const i=e.toString(2).length-t.toString(2).length;return i>0&&(e>>=BigInt(i)),!r&&e>=t?e-t:e}function v(e){if("function"==typeof e){const t=e(y).toString(16);return BigInt("0x"+t)}if(null!=e&&d.isBN(e)){const t=e.toString(16);return BigInt("0x"+t)}{const e=g.generate(p);return BigInt("0x"+e)}}function k(e,t){return(e%t+t)%t}function S(e,t){let r=s,i=n,a=k(e,t),o=t;for(;a>s;){const e=o/a,t=i-r*e,n=o-a*e;i=r,r=t,o=a,a=n}return k(r,t)}function E(e,t){if(null===e)return t;if(null===t)return e;if(e.x===t.x&&e.y===k(-t.y,c))return null;let r;if(e.x===t.x&&e.y===t.y){if(e.y===n)return null;const t=k(BigInt(3)*e.x*e.x,c);r=k(t*S(a*e.y,c),c)}else{const i=k(t.y-e.y,c);r=k(i*S(t.x-e.x,c),c)}const i=k(r*r-e.x-t.x,c);return{x:i,y:k(r*(e.x-i)-e.y,c)}}function P(e,t){let r=t,i=null;for(;e>BigInt(0);)e%BigInt(2)===BigInt(1)&&(i=null===i?r:E(i,r)??i),r=E(r,r)??r,e>>=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=v(i);if(O=I(O,o,!0),O<=s||O>=m){if(i instanceof d)throw new Error("Invalid fixed custom K value (must be more than 1 and less than N-1)");continue}const _=P(O,u);if(null===_){if(i instanceof d)throw new Error("Invalid fixed custom K value (must not create a point at infinity when multiplied by the generator point)");continue}const x=k(_.x,o);if(x===n){if(i instanceof d)throw new Error("Invalid fixed custom K value (when multiplied by G, the resulting x coordinate mod N must not be zero)");continue}const A=S(O,o),T=k(x*l,o);let F=k(A*(h+T),o);if(F===n){if(i instanceof d)throw new Error("Invalid fixed custom K value (when used with the key, it cannot create a zero value for S)");continue}r&&F>o/a&&(F=o-F);const R=new d(x.toString(16),16),C=new d(F.toString(16),16);return new $e(R,C)}}else{const V=new Me;e=We(e);const D=V.n.byteLength(),B=t.toArray("be",D),U=e.toArray("be",D),L=new ze(B,U),K=V.n.subn(1);for(let H=0;;H++){let q="function"==typeof i?i(H):d.isBN(i)?i:new d(L.generate(D),16);if(null==q)throw new Error("k is undefined");if(q=We(q,!0),q.cmpn(1)<=0||q.cmp(K)>=0){if(d.isBN(i))throw new Error("Invalid fixed custom K value (must be more than 1 and less than N-1)");continue}const M=V.g.mul(q);if(M.isInfinity()){if(d.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 $=M.getX().umod(V.n);if(0===$.cmpn(0)){if(d.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(V.n).mul($.mul(t).iadd(e));if(z=z.umod(V.n),0!==z.cmpn(0))return r&&z.cmp(V.n.ushrn(1))>0&&(z=V.n.sub(z)),new $e($,z);if(d.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")},Xe=(e,t,r)=>{if("function"==typeof BigInt){const i=BigInt(0),n=BigInt(1),s=BigInt(2),a=BigInt(3),o=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),c=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),d={x:BigInt("0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"),y:BigInt("0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8")},u=(e,t)=>(e%t+t)%t,h=(e,t)=>{let[r,s]=[e,t],[a,o]=[BigInt(1),BigInt(0)];for(;s!==i;){const e=r/s;[r,s]=[s,r-e*s],[a,o]=[o,a-e*o]}return r>n?i:u(a,t)},l=(e,t,r)=>u(e*t,r),f=(e,t,r)=>u(e-t,r),p=BigInt(4),b=BigInt(8),w=e=>{const{X:t,Y:r,Z:c}=e;if(r===i)return{X:i,Y:n,Z:i};const d=l(r,r,o),u=l(p,l(t,d,o),o),h=l(a,l(t,t,o),o),w=f(l(h,h,o),l(s,u,o),o);return{X:w,Y:f(l(h,f(u,w,o),o),l(b,l(d,d,o),o),o),Z:l(s,l(r,c,o),o)}},g=(e,t)=>{if(e.Z===i)return t;if(t.Z===i)return e;const r=l(e.Z,e.Z,o),a=l(t.Z,t.Z,o),c=l(e.X,a,o),d=l(t.X,r,o),u=l(e.Y,l(a,t.Z,o),o),h=l(t.Y,l(r,e.Z,o),o),p=f(d,c,o),b=f(h,u,o);if(p===i)return b===i?w(e):{X:i,Y:n,Z:i};const g=l(p,p,o),m=l(p,g,o),y=l(c,g,o),I=f(f(l(b,b,o),m,o),l(s,y,o),o);return{X:I,Y:f(l(b,f(y,I,o),o),l(u,m,o),o),Z:l(p,l(e.Z,t.Z,o),o)}},m=(e,t)=>{const r={X:t.x,Y:t.y,Z:n};let s={X:i,Y:n,Z:i};const a=e.toString(2);for(let e=0;e<a.length;e++)s=w(s),"1"===a[e]&&(s=g(s,r));return s},y=(e,t,r)=>{const{r:n,s}=r,a=e;if(n<=i||n>=c||s<=i||s>=c)return!1;const f=h(s,c);if(f===i)return!1;const p=l(a,f,c),b=l(n,f,c),w=m(p,d),y=m(b,t),I=g(w,y);if(I.Z===i)return!1;const v=h(I.Z,o);if(v===i)return!1;const k=l(v,v,o),S=l(I.X,k,o);return u(S,c)===n},I=BigInt("0x"+e.toString(16));if(null==r.x||null==r.y)throw new Error("Invalid public key: missing coordinates.");return y(I,{x:BigInt("0x"+r.x.toString(16)),y:BigInt("0x"+r.y.toString(16))},{r:BigInt("0x"+t.r.toString(16)),s:BigInt("0x"+t.s.toString(16))})}{const i=new Me;e=We(e);const n=t.r,s=t.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(e).umod(i.n),c=a.mul(n).umod(i.n),d=i.g.jmulAdd(o,r,c);return!d.isInfinity()&&d.eqXToP(n)}};class Ge extends He{static fromPrivateKey(e){const t=(new Me).g.mul(e);return new Ge(t.x,t.y)}static fromString(e){const t=He.fromString(e);return new Ge(t.x,t.y)}static fromDER(e){const t=He.fromDER(e);return new Ge(t.x,t.y)}constructor(e,t=null,r=!0){if(e instanceof He)super(e.getX(),e.getY());else{if(null===t&&r&&"string"==typeof e&&(66===e.length||130===e.length))throw new Error('You are using the "new PublicKey()" constructor with a DER hex string. You need to use "PublicKey.fromString()" instead.');super(e,t,r)}}deriveSharedSecret(e){if(!this.validate())throw new Error("Public key not valid for ECDH secret derivation");return this.mul(e)}verify(e,t,r){const i=new d(me(e,r),16);return Xe(i,t,this)}toDER(e){return"hex"===e?this.encode(!0,e):this.encode(!0)}toHash(e){const t=ve(this.encode(!0));return"hex"===e?Ne(t):t}toAddress(e=[0]){if("string"==typeof e)if("testnet"===e||"test"===e)e=[111];else{if("mainnet"!==e&&"main"!==e)throw new Error(`Invalid prefix ${e}`);e=[0]}return De(this.toHash(),e)}deriveChild(e,t){const r=this.deriveSharedSecret(e),i=Oe(t,"utf8"),n=ke(r.encode(!0),i),s=(new Me).g.mul(new d(n)),a=this.add(s);return new Ge(a.x,a.y)}static fromMsgHashAndCompactSignature(e,t,r){const i=Oe(t,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 $e(new d(i.slice(1,33)),new d(i.slice(33,65))).RecoverPublicKey(s,e)}}class Ye{_rand;constructor(){const e=()=>{throw new Error("No secure random number generator is available in this environment.")};if(this._rand=e,"object"==typeof self)self.crypto?.getRandomValues?this._rand=e=>{const t=new Uint8Array(e);return self.crypto.getRandomValues(t),[...t]}:this._rand=e;else try{const e=require("crypto");"function"==typeof e.randomBytes&&(this._rand=t=>[...e.randomBytes(t)])}catch{this._rand=e}}generate(e){return this._rand(e)}}let Je=null;const Ze=e=>(null==Je&&(Je=new Ye),Je.generate(e));class Qe{x;y;constructor(e,t){const r=(new Me).p;this.x=e.umod(r),this.y=t.umod(r)}toString(){return Ve(this.x.toArray())+"."+Ve(this.y.toArray())}static fromString(e){const[t,r]=e.split(".");return new Qe(new d(Ce(t)),new d(Ce(r)))}}class et{points;threshold;constructor(e,t){this.points=e,this.threshold=t??e.length}static fromPrivateKey(e,t){const r=(new Me).p,i=[new Qe(new d(0),new d(e.toArray()))];for(let e=1;e<t;e++){const e=new d(Ze(32)).umod(r),t=new d(Ze(32)).umod(r);i.push(new Qe(e,t))}return new et(i)}valueAt(e){const t=(new Me).p;let r=new d(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=e.sub(s).umod(t),c=a.sub(s).umod(t).invm(t),d=o.mul(c).umod(t);n=n.mul(d).umod(t)}r=r.add(n).umod(t)}return r}}class tt{points;threshold;integrity;constructor(e,t,r){this.points=e,this.threshold=t,this.integrity=r}static fromBackupFormat(e){let t=0,r="";const i=e.map(((e,i)=>{const n=e.split(".");if(4!==n.length)throw new Error("Invalid share format in share "+i.toString()+'. Expected format: "x.y.t.i" - received '+e);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 d=parseInt(o);if(0!==i&&t!==d)throw new Error("Threshold mismatch in share "+i.toString());if(0!==i&&r!==c)throw new Error("Integrity mismatch in share "+i.toString());return t=d,r=c,Qe.fromString([s,a].join("."))}));return new tt(i,t,r)}toBackupFormat(){return this.points.map((e=>e.toString()+"."+this.threshold.toString()+"."+this.integrity))}}class rt extends d{static fromRandom(){return new rt(Ze(32))}static fromString(e,t="hex"){return new rt(super.fromString(e,t).toArray())}static fromHex(e){return new rt(super.fromHex(e,"big"))}static fromWif(e,t=1){const r=Be(e,void 0,t);if(33!==r.data.length)throw new Error("Invalid WIF length");if(1!==r.data[32])throw new Error("Invalid WIF padding");return new rt(r.data.slice(0,32))}constructor(e=0,t=10,r="be",i="apply"){if(e instanceof d?(super(),e.copy(this)):super(e,t,r),"nocheck"!==i){const e=this.checkInField();if(!e.inField){if("error"===i)throw new Error("Input is out of field");d.move(this,e.modN)}}}checkInField(){const e=new Me,t=this.mod(e.n);return{inField:0===this.cmp(t),modN:t}}isValid(){return this.checkInField().inField}sign(e,t,r=!0,i){const n=new d(me(e,t),16);return je(n,this,r,i)}verify(e,t,r){const i=new d(me(e,r),16);return Xe(i,t,this.toPublicKey())}toPublicKey(){const e=(new Me).g.mul(this);return new Ge(e.x,e.y)}toWif(e=[128]){if(!this.isValid())throw new Error("Value is out of field");return De([...this.toArray("be",32),1],e)}toAddress(e=[0]){return this.toPublicKey().toAddress(e)}toHex(){return super.toHex(32)}toString(e="hex",t=64){return super.toString(e,t)}deriveSharedSecret(e){if(!e.validate())throw new Error("Public key not valid for ECDH secret derivation");return e.mul(this)}deriveChild(e,t){const r=this.deriveSharedSecret(e),i=Oe(t,"utf8"),n=ke(r.encode(!0),i),s=new Me;return new rt(this.add(new d(n)).mod(s.n).toArray())}toKeyShares(e,t){if("number"!=typeof e||"number"!=typeof t)throw new Error("threshold and totalShares must be numbers");if(e<2)throw new Error("threshold must be at least 2");if(t<2)throw new Error("totalShares must be at least 2");if(e>t)throw new Error("threshold should be less than or equal to totalShares");const r=et.fromPrivateKey(this,e),i=[];for(let e=0;e<t;e++){const e=new d(rt.fromRandom().toArray()),t=r.valueAt(e);i.push(new Qe(e,t))}const n=this.toPublicKey().toHash("hex").slice(0,8);return new tt(i,e,n)}toBackupShares(e,t){return this.toKeyShares(e,t).toBackupFormat()}static fromBackupShares(e){return rt.fromKeyShares(tt.fromBackupFormat(e))}static fromKeyShares(e){const{points:t,threshold:r,integrity:i}=e;if(r<2)throw new Error("threshold must be at least 2");if(t.length<r)throw new Error(`At least ${r} shares are required to reconstruct the private key`);for(let e=0;e<r;e++)for(let i=e+1;i<r;i++)if(t[e].x.eq(t[i].x))throw new Error("Duplicate share detected, each must be unique.");const n=new et(t,r),s=new rt(n.valueAt(new d(0)).toArray());if(s.toPublicKey().toHash("hex").slice(0,8)!==i)throw new Error("Integrity hash mismatch");return s}}const it=new Uint8Array([99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22]),nt=[[0,0,0,0],[1,0,0,0],[2,0,0,0],[4,0,0,0],[8,0,0,0],[16,0,0,0],[32,0,0,0],[64,0,0,0],[128,0,0,0],[27,0,0,0],[54,0,0,0]].map((e=>new Uint8Array(e))),st=new Uint8Array(256),at=new Uint8Array(256);for(let e=0;e<256;e++){const t=255&(e<<1^(128&e?27:0));st[e]=t,at[e]=t^e}function ot(e,t,r){for(let i=0;i<4;i++){const n=t[r+i];for(let t=0;t<4;t++)e[t][i]^=n[t]}}function ct(e){for(let t=0;t<4;t++)for(let r=0;r<4;r++)e[t][r]=it[e[t][r]]}function dt(e){for(let t=0;t<4;t++)e[t]=it[e[t]]}function ut(e){const t=e[0];e[0]=e[1],e[1]=e[2],e[2]=e[3],e[3]=t}function ht(e){let t=e[1][0];e[1][0]=e[1][1],e[1][1]=e[1][2],e[1][2]=e[1][3],e[1][3]=t,t=e[2][0];const r=e[2][1];e[2][0]=e[2][2],e[2][1]=e[2][3],e[2][2]=t,e[2][3]=r,t=e[3][3],e[3][3]=e[3][2],e[3][2]=e[3][1],e[3][1]=e[3][0],e[3][0]=t}function lt(e){for(let t=0;t<4;t++){const r=e[0][t],i=e[1][t],n=e[2][t],s=e[3][t];e[0][t]=st[r]^at[i]^n^s,e[1][t]=r^st[i]^at[n]^s,e[2][t]=r^i^st[n]^at[s],e[3][t]=at[r]^i^n^st[s]}}function ft(e,t){let r,i,n,s;const a=[[],[],[],[]],o=[],c=Array.from(t);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(!(t.length<=32))throw new Error("Illegal key length: "+String(t.length));for(;c.length<32;)c.unshift(0);s=15}const d=function(e,t){const r=t.length/4,i=[];for(let e=0;e<t.length;e++)e%4==0&&i.push([]),i[e>>2].push(t[e]);for(let t=r;t<4*e;t++){i[t]=[];const e=i[t-1].slice();if(t%r==0){ut(e),dt(e);const i=nt[t/r];for(let t=0;t<4;t++)e[t]^=i[t]}else r>6&&t%r==4&&dt(e);for(let n=0;n<4;n++)i[t][n]=i[t-r][n]^e[n]}return i}(s,c);for(let t=0;t<4;t++)a[0][t]=e[4*t],a[1][t]=e[4*t+1],a[2][t]=e[4*t+2],a[3][t]=e[4*t+3];for(ot(a,d,0),n=1;n<s;n++)ct(a),ht(a),n+1<s&<(a),ot(a,d,4*n);for(r=0;r<4;r++)for(i=0;i<4;i++)o.push(a[i][r]);return o}const pt=function(e){return[(4278190080&e)>>>24,(16711680&e)>>16,(65280&e)>>8,255&e]},bt=function(e){return new Array(e).fill(0)},wt=[225].concat(bt(15)),gt=function(e,t){for(let r=0;r<e.length;r++)e[r]^=t[r]},mt=function(e){let t,r=0,i=0;for(t=0;t<e.length;t++)i=r,r=1&e[t],e[t]=e[t]>>1,0!==i&&(e[t]=128|e[t]);return e},yt=function(e,t){const r=t.slice(),i=bt(16);for(let t=0;t<16;t++)for(let n=7;n>=0;n--)e[t]&1<<n&>(i,r),1&r[15]?(mt(r),gt(r,wt)):mt(r);return i},It=function(e){let t;const r=e.slice();for(t=15;11!==t&&(r[t]=r[t]+1,256===r[t]);t--)r[t]=0;return r};function vt(e,t){let r=bt(16);for(let i=0;i<e.length;i+=16){const n=r.slice();for(let t=0;t<16;t++)n[t]^=e[i+t]??0;r=yt(n,t)}return r}function kt(e,t,r){if(0===e.length)return[];const i=new Array(e.length);let n=t,s=0;const a=Math.ceil(e.length/16);for(let t=0;t<a;t++){const o=ft(n,r),c=Math.min(16,e.length-s);for(let t=0;t<c;t++)i[s]=e[s]^o[t],s++;t+1<a&&(n=It(n))}return i}class St extends d{static fromRandom(){return new St(Ze(32))}encrypt(e,t){const r=Ze(32);e=Oe(e,t);const{result:i,authenticationTag:n}=function(e,t,r,i){let n,s;const a=ft(bt(16),i);n=[...r],12===r.length?n=n.concat(bt(3)).concat([1]):(r.length%16!=0&&(n=n.concat(bt(16-r.length%16))),n=n.concat(bt(8)),n=vt(n.concat(bt(4)).concat(pt(8*r.length)),a));const o=kt(e,It(n),i);return s=t.slice(),0===t.length?s=s.concat(bt(16)):t.length%16!=0&&(s=s.concat(bt(16-t.length%16))),s=s.concat(o),0===o.length?s=s.concat(bt(16)):o.length%16!=0&&(s=s.concat(bt(16-o.length%16))),s=s.concat(bt(4)).concat(pt(8*t.length)).concat(bt(4)).concat(pt(8*o.length)),{result:o,authenticationTag:kt(vt(s,a),n,i)}}(e,[],r,this.toArray("be",32));return Te([...r,...i,...n],t)}decrypt(e,t){const r=(e=Oe(e,t)).slice(0,32),i=e.slice(32),n=i.slice(-16),s=function(e,t,r,i,n){let s,a;const o=ft(bt(16),n);s=[...r],12===r.length?s=s.concat(bt(3)).concat([1]):(r.length%16!=0&&(s=s.concat(bt(16-r.length%16))),s=s.concat(bt(8)),s=vt(s.concat(bt(4)).concat(pt(8*r.length)),o));const c=kt(e,It(s),n);return a=t.slice(),0===t.length?a=a.concat(bt(16)):t.length%16!=0&&(a=a.concat(bt(16-t.length%16))),a=a.concat(e),0===e.length?a=a.concat(bt(16)):e.length%16!=0&&(a=a.concat(bt(16-e.length%16))),a=a.concat(bt(4)).concat(pt(8*t.length)).concat(bt(4)).concat(pt(8*e.length)),kt(vt(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 Te(s,t)}}class Et extends $e{static SIGHASH_ALL=1;static SIGHASH_NONE=2;static SIGHASH_SINGLE=3;static SIGHASH_FORKID=64;static SIGHASH_ANYONECANPAY=128;scope;static format(e){const t={sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,sequence:e.inputSequence},r=[...e.otherInputs];function i(t){const r=new Ue;if(void 0===t)for(const t of e.outputs){const e=t.satoshis??0;r.writeUInt64LE(e);const i=t.lockingScript?.toBinary()??[];r.writeVarIntNum(i.length),r.write(i)}else{const i=e.outputs[t];if(void 0===i)throw new Error(`Output at index ${t} 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 Ie(i)}r.splice(e.inputIndex,0,t);let n=new Array(32).fill(0),s=new Array(32).fill(0),a=new Array(32).fill(0);e.scope&Et.SIGHASH_ANYONECANPAY||(n=(()=>{const e=new Ue;for(const t of r){if(void 0===t.sourceTXID){if(null==t.sourceTransaction)throw new Error("Missing sourceTransaction for input");e.write(t.sourceTransaction.hash())}else e.writeReverse(Oe(t.sourceTXID,"hex"));e.writeUInt32LE(t.sourceOutputIndex)}const t=e.toArray();return Ie(t)})()),e.scope&Et.SIGHASH_ANYONECANPAY||(31&e.scope)===Et.SIGHASH_SINGLE||(31&e.scope)===Et.SIGHASH_NONE||(s=(()=>{const e=new Ue;for(const t of r){const r=t.sequence??4294967295;e.writeUInt32LE(r)}const t=e.toArray();return Ie(t)})()),(31&e.scope)!==Et.SIGHASH_SINGLE&&(31&e.scope)!==Et.SIGHASH_NONE?a=i():(31&e.scope)===Et.SIGHASH_SINGLE&&e.inputIndex<e.outputs.length&&(a=i(e.inputIndex));const o=new Ue;o.writeInt32LE(e.transactionVersion),o.write(n),o.write(s),o.writeReverse(Oe(e.sourceTXID,"hex")),o.writeUInt32LE(e.sourceOutputIndex);const c=e.subscript.toBinary();o.writeVarIntNum(c.length),o.write(c),o.writeUInt64LE(e.sourceSatoshis);const d=t.sequence;return o.writeUInt32LE(d),o.write(a),o.writeUInt32LE(e.lockTime),o.writeUInt32LE(e.scope>>>0),o.toArray()}static fromChecksigFormat(e){if(0===e.length){const e=new d(1),t=new d(1);return new Et(e,t,1)}const t=e[e.length-1],r=e.slice(0,e.length-1),i=$e.fromDER(r);return new Et(i.r,i.s,t)}constructor(e,t,r){super(e,t),this.scope=r}hasLowS(){return!this.s.ltn(1)&&!this.s.gt(new d("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex"))}toChecksigFormat(){return[...this.toDER(),this.scope]}}class Pt{curve;constructor(){this.curve=new Me}generateProof(e,t,r,i){const n=rt.fromRandom(),s=n.toPublicKey(),a=r.mul(n),o=this.computeChallenge(t,r,i,a,s);return{R:s,SPrime:a,z:n.add(o.mul(e)).umod(this.curve.n)}}verifyProof(e,t,r,i){const{R:n,SPrime:s,z:a}=i,o=this.computeChallenge(e,t,r,s,n),c=this.curve.g.mul(a),d=n.add(e.mul(o));if(!c.eq(d))return!1;const u=t.mul(a),h=s.add(r.mul(o));return!!u.eq(h)}computeChallenge(e,t,r,i,n){const s=[...e.encode(!0),...t.encode(!0),...r.encode(!0),...i.encode(!0),...n.encode(!0)],a=me(s);return new d(a).umod(this.curve.n)}}const Nt={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 e in Nt)Nt[Nt[e]]=e;const Ot=Nt;class _t{chunks;static fromASM(e){const t=[],r=e.split(" ");let i=0;for(;i<r.length;){const e=r[i];let n,s=0;if(e.startsWith("OP_")&&void 0!==Ot[e]&&(n=e,s=Ot[e]),"0"===e)s=0,t.push({op:s}),i+=1;else if("-1"===e)s=Ot.OP_1NEGATE,t.push({op:s}),i+=1;else if(void 0===n){let e=r[i];e.length%2!=0&&(e="0"+e);const n=Oe(e,"hex");if(Te(n,"hex")!==e)throw new Error("invalid hex string in script");const a=n.length;a>=0&&a<Ot.OP_PUSHDATA1?s=a:a<Math.pow(2,8)?s=Ot.OP_PUSHDATA1:a<Math.pow(2,16)?s=Ot.OP_PUSHDATA2:a<Math.pow(2,32)&&(s=Ot.OP_PUSHDATA4),t.push({data:n,op:s}),i+=1}else s===Ot.OP_PUSHDATA1||s===Ot.OP_PUSHDATA2||s===Ot.OP_PUSHDATA4?(t.push({data:Oe(r[i+2],"hex"),op:s}),i+=3):(t.push({op:s}),i+=1)}return new _t(t)}static fromHex(e){if(0===e.length)return _t.fromBinary([]);if(e.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(e))throw new Error("Some elements in this string are not hex encoded.");return _t.fromBinary(Oe(e,"hex"))}static fromBinary(e){e=[...e];const t=[];let r=0;const i=new Le(e);for(;!i.eof();){const e=i.readUInt8();if(e===Ot.OP_RETURN&&0===r){t.push({op:e,data:i.read()});break}e===Ot.OP_IF||e===Ot.OP_NOTIF||e===Ot.OP_VERIF||e===Ot.OP_VERNOTIF?r++:e===Ot.OP_ENDIF&&r--;let n=0,s=[];if(e>0&&e<Ot.OP_PUSHDATA1)n=e,t.push({data:i.read(n),op:e});else if(e===Ot.OP_PUSHDATA1){try{n=i.readUInt8(),s=i.read(n)}catch{i.read()}t.push({data:s,op:e})}else if(e===Ot.OP_PUSHDATA2){try{n=i.readUInt16LE(),s=i.read(n)}catch{i.read()}t.push({data:s,op:e})}else if(e===Ot.OP_PUSHDATA4){try{n=i.readUInt32LE(),s=i.read(n)}catch{i.read()}t.push({data:s,op:e})}else t.push({op:e})}return new _t(t)}constructor(e=[]){this.chunks=e}toASM(){let e="";for(let t=0;t<this.chunks.length;t++){const r=this.chunks[t];e+=this._chunkToString(r)}return e.slice(1)}toHex(){return Te(this.toBinary(),"hex")}toBinary(){const e=new Ue;for(let t=0;t<this.chunks.length;t++){const r=this.chunks[t],i=r.op;if(e.writeUInt8(i),i===Ot.OP_RETURN&&null!=r.data){e.write(r.data);break}null!=r.data&&(i<Ot.OP_PUSHDATA1?e.write(r.data):i===Ot.OP_PUSHDATA1?(e.writeUInt8(r.data.length),e.write(r.data)):i===Ot.OP_PUSHDATA2?(e.writeUInt16LE(r.data.length),e.write(r.data)):i===Ot.OP_PUSHDATA4&&(e.writeUInt32LE(r.data.length),e.write(r.data)))}return e.toArray()}writeScript(e){return this.chunks=this.chunks.concat(e.chunks),this}writeOpCode(e){return this.chunks.push({op:e}),this}setChunkOpCode(e,t){return this.chunks[e]={op:t},this}writeBn(e){if(e.cmpn(0)===Ot.OP_0)this.chunks.push({op:Ot.OP_0});else if(0===e.cmpn(-1))this.chunks.push({op:Ot.OP_1NEGATE});else if(e.cmpn(1)>=0&&e.cmpn(16)<=0)this.chunks.push({op:e.toNumber()+Ot.OP_1-1});else{const t=e.toSm("little");this.writeBin(t)}return this}writeBin(e){let t;if(e.length>0&&e.length<Ot.OP_PUSHDATA1)t=e.length;else if(0===e.length)t=Ot.OP_0;else if(e.length<Math.pow(2,8))t=Ot.OP_PUSHDATA1;else if(e.length<Math.pow(2,16))t=Ot.OP_PUSHDATA2;else{if(!(e.length<Math.pow(2,32)))throw new Error("You can't push that much data");t=Ot.OP_PUSHDATA4}return this.chunks.push({data:e,op:t}),this}writeNumber(e){return this.writeBn(new d(e)),this}removeCodeseparators(){const e=[];for(let t=0;t<this.chunks.length;t++)this.chunks[t].op!==Ot.OP_CODESEPARATOR&&e.push(this.chunks[t]);return this.chunks=e,this}findAndDelete(e){const t=e.toHex();for(let e=0;e<this.chunks.length;e++)t===new _t([this.chunks[e]]).toHex()&&this.chunks.splice(e,1);return this}isPushOnly(){for(let e=0;e<this.chunks.length;e++)if(this.chunks[e].op>Ot.OP_16)return!1;return!0}isLockingScript(){throw new Error("Not implemented")}isUnlockingScript(){throw new Error("Not implemented")}_chunkToString(e){const t=e.op;let r="";return r=void 0===e.data?`${r} ${Ot[t]}`:`${r} ${Ne(e.data)}`,r}}class xt extends _t{isLockingScript(){return!0}isUnlockingScript(){return!1}}class At extends _t{isLockingScript(){return!1}isUnlockingScript(){return!0}}const Tt=1073741824,Ft=Math.pow(2,31)-1,Rt=!0,Ct=Object.freeze(new d(-1).toScriptNum()),Vt=Object.freeze(Array.from({length:17},((e,t)=>Object.freeze(new d(t).toScriptNum()))));class Dt{sourceTXID;sourceOutputIndex;sourceSatoshis;lockingScript;transactionVersion;otherInputs;outputs;inputIndex;unlockingScript;inputSequence;lockTime;context;programCounter;lastCodeSeparator;stack;altStack;ifStack;memoryLimit;stackMem;altStackMem;constructor(e){this.sourceTXID=e.sourceTXID,this.sourceOutputIndex=e.sourceOutputIndex,this.sourceSatoshis=e.sourceSatoshis,this.lockingScript=e.lockingScript,this.transactionVersion=e.transactionVersion,this.otherInputs=e.otherInputs,this.outputs=e.outputs,this.inputIndex=e.inputIndex,this.unlockingScript=e.unlockingScript,this.inputSequence=e.inputSequence,this.lockTime=e.lockTime,this.memoryLimit=e.memoryLimit??32e6,this.stack=[],this.altStack=[],this.ifStack=[],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}ensureStackMem(e){this.stackMem+e>this.memoryLimit&&this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}ensureAltStackMem(e){this.altStackMem+e>this.memoryLimit&&this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}pushStack(e){this.ensureStackMem(e.length),this.stack.push(e),this.stackMem+=e.length}pushStackCopy(e){this.ensureStackMem(e.length);const t=e.slice();this.stack.push(t),this.stackMem+=t.length}popStack(){0===this.stack.length&&this.scriptEvaluationError("Attempted to pop from an empty stack.");const e=this.stack.pop();return this.stackMem-=e.length,e}stackTop(e=-1){return(0===this.stack.length||this.stack.length<Math.abs(e)||e>=0&&e>=this.stack.length)&&this.scriptEvaluationError(`Stack underflow accessing element at index ${e}. Stack length is ${this.stack.length}.`),this.stack[this.stack.length+e]}pushAltStack(e){this.ensureAltStackMem(e.length),this.altStack.push(e),this.altStackMem+=e.length}popAltStack(){0===this.altStack.length&&this.scriptEvaluationError("Attempted to pop from an empty alt stack.");const e=this.altStack.pop();return this.altStackMem-=e.length,e}checkSignatureEncoding(e){if(0===e.length)return!0;if(!function(e){if(e.length<9||e.length>73)return!1;if(48!==e[0])return!1;if(e[1]!==e.length-3)return!1;const t=e[2],r=e[3];if(2!==t)return!1;if(0===r)return!1;if(5+r>=e.length)return!1;const i=4+r,n=e[i],s=e[i+1];if(2!==n)return!1;if(0===s)return!1;if(128&e[4])return!1;if(r>1&&0===e[4]&&!(128&e[5]))return!1;const a=i+2;return!(128&e[a]||s>1&&0===e[a]&&!(128&e[a+1])||r+s+7!==e.length)}(e))return this.scriptEvaluationError("The signature format is invalid."),!1;try{const t=Et.fromChecksigFormat(e);if(!t.hasLowS())return this.scriptEvaluationError("The signature must have a low S value."),!1;if(!(t.scope&Et.SIGHASH_FORKID))return this.scriptEvaluationError("The signature must use SIGHASH_FORKID."),!1}catch(e){return this.scriptEvaluationError("The signature format is invalid."),!1}return!0}checkPublicKeyEncoding(e){if(0===e.length)return this.scriptEvaluationError("Public key is empty."),!1;if(e.length<33)return this.scriptEvaluationError("The public key is too short, it must be at least 33 bytes."),!1;if(4===e[0]){if(65!==e.length)return this.scriptEvaluationError("The non-compressed public key must be 65 bytes."),!1}else{if(2!==e[0]&&3!==e[0])return this.scriptEvaluationError("The public key is in an unknown format."),!1;if(33!==e.length)return this.scriptEvaluationError("The compressed public key must be 33 bytes."),!1}try{Ge.fromDER(e)}catch(e){return this.scriptEvaluationError("The public key is in an unknown format."),!1}return!0}verifySignature(e,t,r){const i=Et.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:e.scope}),n=new d(Ie(i));return Xe(n,e,t)}step(){if(this.stackMem>this.memoryLimit)return this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;if(this.altStackMem>this.memoryLimit)return this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;"UnlockingScript"===this.context&&this.programCounter>=this.unlockingScript.chunks.length&&(this.context="LockingScript",this.programCounter=0);const e="UnlockingScript"===this.context?this.unlockingScript:this.lockingScript;if(this.programCounter>=e.chunks.length)return!1;const t=e.chunks[this.programCounter],r=t.op;void 0===r&&this.scriptEvaluationError(`Missing opcode in ${this.context} at pc=${this.programCounter}.`),Array.isArray(t.data)&&t.data.length>Tt&&this.scriptEvaluationError(`Data push > 1073741824 bytes (pc=${this.programCounter}).`);const i=!this.ifStack.includes(!1);var n;if(i&&((n=r)===Ot.OP_2MUL||n===Ot.OP_2DIV||n===Ot.OP_VERIF||n===Ot.OP_VERNOTIF||n===Ot.OP_VER)&&this.scriptEvaluationError(`This opcode is currently disabled. (Opcode: ${Ot[r]}, PC: ${this.programCounter})`),i&&r>=0&&r<=Ot.OP_PUSHDATA4)(function(e){const t=e.data,r=e.op;return!(Array.isArray(t)&&(0===t.length?r!==Ot.OP_0:1===t.length&&t[0]>=1&&t[0]<=16?r!==Ot.OP_1+(t[0]-1):1===t.length&&129===t[0]?r!==Ot.OP_1NEGATE:t.length<=75?r!==t.length:t.length<=255?r!==Ot.OP_PUSHDATA1:t.length<=65535&&r!==Ot.OP_PUSHDATA2))})(t)||this.scriptEvaluationError(`This data is not minimally-encoded. (PC: ${this.programCounter})`),this.pushStack(Array.isArray(t.data)?t.data:[]);else if(i||r>=Ot.OP_IF&&r<=Ot.OP_ENDIF){let e,t,n,s,a,o,c,u,h,l,f,p,b,w,g,m,y,I,v,k,S,E,P,N,O,_;switch(r){case Ot.OP_1NEGATE:this.pushStackCopy(Ct);break;case Ot.OP_0:this.pushStackCopy(Vt[0]);break;case Ot.OP_1:case Ot.OP_2:case Ot.OP_3:case Ot.OP_4:case Ot.OP_5:case Ot.OP_6:case Ot.OP_7:case Ot.OP_8:case Ot.OP_9:case Ot.OP_10:case Ot.OP_11:case Ot.OP_12:case Ot.OP_13:case Ot.OP_14:case Ot.OP_15:case Ot.OP_16:p=r-(Ot.OP_1-1),this.pushStackCopy(Vt[p]);break;case Ot.OP_NOP:case Ot.OP_NOP2:case Ot.OP_NOP3:case Ot.OP_NOP1:case Ot.OP_NOP4:case Ot.OP_NOP5:case Ot.OP_NOP6:case Ot.OP_NOP7:case Ot.OP_NOP8:case Ot.OP_NOP9:case Ot.OP_NOP10:case Ot.OP_NOP11:case Ot.OP_NOP12:case Ot.OP_NOP13:case Ot.OP_NOP14:case Ot.OP_NOP15:case Ot.OP_NOP16:case Ot.OP_NOP17:case Ot.OP_NOP18:case Ot.OP_NOP19:case Ot.OP_NOP20:case Ot.OP_NOP21:case Ot.OP_NOP22:case Ot.OP_NOP23:case Ot.OP_NOP24:case Ot.OP_NOP25:case Ot.OP_NOP26:case Ot.OP_NOP27:case Ot.OP_NOP28:case Ot.OP_NOP29:case Ot.OP_NOP30:case Ot.OP_NOP31:case Ot.OP_NOP32:case Ot.OP_NOP33:case Ot.OP_NOP34:case Ot.OP_NOP35:case Ot.OP_NOP36:case Ot.OP_NOP37:case Ot.OP_NOP38:case Ot.OP_NOP39:case Ot.OP_NOP40:case Ot.OP_NOP41:case Ot.OP_NOP42:case Ot.OP_NOP43:case Ot.OP_NOP44:case Ot.OP_NOP45:case Ot.OP_NOP46:case Ot.OP_NOP47:case Ot.OP_NOP48:case Ot.OP_NOP49:case Ot.OP_NOP50:case Ot.OP_NOP51:case Ot.OP_NOP52:case Ot.OP_NOP53:case Ot.OP_NOP54:case Ot.OP_NOP55:case Ot.OP_NOP56:case Ot.OP_NOP57:case Ot.OP_NOP58:case Ot.OP_NOP59:case Ot.OP_NOP60:case Ot.OP_NOP61:case Ot.OP_NOP62:case Ot.OP_NOP63:case Ot.OP_NOP64:case Ot.OP_NOP65:case Ot.OP_NOP66:case Ot.OP_NOP67:case Ot.OP_NOP68:case Ot.OP_NOP69:case Ot.OP_NOP70:case Ot.OP_NOP71:case Ot.OP_NOP72:case Ot.OP_NOP73:case Ot.OP_NOP77:break;case Ot.OP_IF:case Ot.OP_NOTIF:w=!1,i&&(this.stack.length<1&&this.scriptEvaluationError("OP_IF and OP_NOTIF require at least one item on the stack when they are used!"),e=this.popStack(),w=this.castToBool(e),r===Ot.OP_NOTIF&&(w=!w)),this.ifStack.push(w);break;case Ot.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 Ot.OP_ENDIF:0===this.ifStack.length&&this.scriptEvaluationError("OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop();break;case Ot.OP_VERIFY:this.stack.length<1&&this.scriptEvaluationError("OP_VERIFY requires at least one item to be on the stack."),t=this.stackTop(),w=this.castToBool(t),w||this.scriptEvaluationError("OP_VERIFY requires the top stack value to be truthy."),this.popStack();break;case Ot.OP_RETURN:"UnlockingScript"===this.context?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.ifStack=[],this.programCounter--;break;case Ot.OP_TOALTSTACK:this.stack.length<1&&this.scriptEvaluationError("OP_TOALTSTACK requires at oeast one item to be on the stack."),this.pushAltStack(this.popStack());break;case Ot.OP_FROMALTSTACK:this.altStack.length<1&&this.scriptEvaluationError("OP_FROMALTSTACK requires at least one item to be on the stack."),this.pushStack(this.popAltStack());break;case Ot.OP_2DROP:this.stack.length<2&&this.scriptEvaluationError("OP_2DROP requires at least two items to be on the stack."),this.popStack(),this.popStack();break;case Ot.OP_2DUP:this.stack.length<2&&this.scriptEvaluationError("OP_2DUP requires at least two items to be on the stack."),t=this.stackTop(-2),n=this.stackTop(-1),this.pushStackCopy(t),this.pushStackCopy(n);break;case Ot.OP_3DUP:this.stack.length<3&&this.scriptEvaluationError("OP_3DUP requires at least three items to be on the stack."),t=this.stackTop(-3),n=this.stackTop(-2),s=this.stackTop(-1),this.pushStackCopy(t),this.pushStackCopy(n),this.pushStackCopy(s);break;case Ot.OP_2OVER:this.stack.length<4&&this.scriptEvaluationError("OP_2OVER requires at least four items to be on the stack."),t=this.stackTop(-4),n=this.stackTop(-3),this.pushStackCopy(t),this.pushStackCopy(n);break;case Ot.OP_2ROT:{this.stack.length<6&&this.scriptEvaluationError("OP_2ROT requires at least six items to be on the stack.");const e=this.popStack(),t=this.popStack(),r=this.popStack(),i=this.popStack(),n=this.popStack(),s=this.popStack();this.pushStack(i),this.pushStack(r),this.pushStack(t),this.pushStack(e),this.pushStack(s),this.pushStack(n);break}case Ot.OP_2SWAP:{this.stack.length<4&&this.scriptEvaluationError("OP_2SWAP requires at least four items to be on the stack.");const e=this.popStack(),t=this.popStack(),r=this.popStack(),i=this.popStack();this.pushStack(t),this.pushStack(e),this.pushStack(i),this.pushStack(r);break}case Ot.OP_IFDUP:this.stack.length<1&&this.scriptEvaluationError("OP_IFDUP requires at least one item to be on the stack."),t=this.stackTop(),this.castToBool(t)&&this.pushStackCopy(t);break;case Ot.OP_DEPTH:this.pushStack(new d(this.stack.length).toScriptNum());break;case Ot.OP_DROP:this.stack.length<1&&this.scriptEvaluationError("OP_DROP requires at least one item to be on the stack."),this.popStack();break;case Ot.OP_DUP:this.stack.length<1&&this.scriptEvaluationError("OP_DUP requires at least one item to be on the stack."),this.pushStackCopy(this.stackTop());break;case Ot.OP_NIP:this.stack.length<2&&this.scriptEvaluationError("OP_NIP requires at least two items to be on the stack."),n=this.popStack(),this.popStack(),this.pushStack(n);break;case Ot.OP_OVER:this.stack.length<2&&this.scriptEvaluationError("OP_OVER requires at least two items to be on the stack."),this.pushStackCopy(this.stackTop(-2));break;case Ot.OP_PICK:case Ot.OP_ROLL:{this.stack.length<2&&this.scriptEvaluationError(`${Ot[r]} requires at least two items to be on the stack.`),u=d.fromScriptNum(this.popStack(),Rt),p=u.toNumber(),(p<0||p>=this.stack.length)&&this.scriptEvaluationError(`${Ot[r]} requires the top stack element to be 0 or a positive number less than the current size of the stack.`);const e=this.stack[this.stack.length-1-p];r===Ot.OP_ROLL?(this.stack.splice(this.stack.length-1-p,1),this.stackMem-=e.length,this.pushStack(e)):this.pushStackCopy(e);break}case Ot.OP_ROT:this.stack.length<3&&this.scriptEvaluationError("OP_ROT requires at least three items to be on the stack."),c=this.popStack(),o=this.popStack(),a=this.popStack(),this.pushStack(o),this.pushStack(c),this.pushStack(a);break;case Ot.OP_SWAP:this.stack.length<2&&this.scriptEvaluationError("OP_SWAP requires at least two items to be on the stack."),o=this.popStack(),a=this.popStack(),this.pushStack(o),this.pushStack(a);break;case Ot.OP_TUCK:this.stack.length<2&&this.scriptEvaluationError("OP_TUCK requires at least two items to be on the stack."),t=this.stackTop(-1),this.ensureStackMem(t.length),this.stack.splice(this.stack.length-2,0,t.slice()),this.stackMem+=t.length;break;case Ot.OP_SIZE:this.stack.length<1&&this.scriptEvaluationError("OP_SIZE requires at least one item to be on the stack."),this.pushStack(new d(this.stackTop().length).toScriptNum());break;case Ot.OP_AND:case Ot.OP_OR:case Ot.OP_XOR:{this.stack.length<2&&this.scriptEvaluationError(`${Ot[r]} requires at least two items on the stack.`),n=this.popStack(),t=this.popStack(),t.length!==n.length&&this.scriptEvaluationError(`${Ot[r]} requires the top two stack items to be the same size.`);const e=new Array(t.length);for(let i=0;i<t.length;i++)r===Ot.OP_AND?e[i]=t[i]&n[i]:r===Ot.OP_OR?e[i]=t[i]|n[i]:e[i]=t[i]^n[i];this.pushStack(e);break}case Ot.OP_INVERT:{this.stack.length<1&&this.scriptEvaluationError("OP_INVERT requires at least one item to be on the stack."),e=this.popStack();const t=new Array(e.length);for(let r=0;r<e.length;r++)t[r]=255&~e[r];this.pushStack(t);break}case Ot.OP_LSHIFT:case Ot.OP_RSHIFT:{if(this.stack.length<2&&this.scriptEvaluationError(`${Ot[r]} requires at least two items to be on the stack.`),l=d.fromScriptNum(this.popStack(),Rt),t=this.popStack(),p=l.toNumber(),p<0&&this.scriptEvaluationError(`${Ot[r]} requires the top item on the stack not to be negative.`),0===t.length){this.pushStack([]);break}let e;h=new d(t),e=r===Ot.OP_LSHIFT?h.ushln(p):h.ushrn(p);const i=e.toArray("le",t.length);this.pushStack(i);break}case Ot.OP_EQUAL:case Ot.OP_EQUALVERIFY:this.stack.length<2&&this.scriptEvaluationError(`${Ot[r]} requires at least two items to be on the stack.`),n=this.popStack(),t=this.popStack(),w=function(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}(t,n),this.pushStack(w?[1]:[]),r===Ot.OP_EQUALVERIFY&&(w||this.scriptEvaluationError("OP_EQUALVERIFY requires the top two stack items to be equal."),this.popStack());break;case Ot.OP_1ADD:case Ot.OP_1SUB:case Ot.OP_NEGATE:case Ot.OP_ABS:case Ot.OP_NOT:case Ot.OP_0NOTEQUAL:switch(this.stack.length<1&&this.scriptEvaluationError(`${Ot[r]} requires at least one item to be on the stack.`),u=d.fromScriptNum(this.popStack(),Rt),r){case Ot.OP_1ADD:u=u.add(new d(1));break;case Ot.OP_1SUB:u=u.sub(new d(1));break;case Ot.OP_NEGATE:u=u.neg();break;case Ot.OP_ABS:u.isNeg()&&(u=u.neg());break;case Ot.OP_NOT:u=new d(0===u.cmpn(0)?1:0);break;case Ot.OP_0NOTEQUAL:u=new d(0!==u.cmpn(0)?1:0)}this.pushStack(u.toScriptNum());break;case Ot.OP_ADD:case Ot.OP_SUB:case Ot.OP_MUL:case Ot.OP_DIV:case Ot.OP_MOD:case Ot.OP_BOOLAND:case Ot.OP_BOOLOR:case Ot.OP_NUMEQUAL:case Ot.OP_NUMEQUALVERIFY:case Ot.OP_NUMNOTEQUAL:case Ot.OP_LESSTHAN:case Ot.OP_GREATERTHAN:case Ot.OP_LESSTHANOREQUAL:case Ot.OP_GREATERTHANOREQUAL:case Ot.OP_MIN:case Ot.OP_MAX:{this.stack.length<2&&this.scriptEvaluationError(`${Ot[r]} requires at least two items to be on the stack.`),n=this.popStack(),t=this.popStack(),l=d.fromScriptNum(n,Rt),h=d.fromScriptNum(t,Rt);let e=0;switch(r){case Ot.OP_MUL:e=h.byteLength()+l.byteLength();break;case Ot.OP_ADD:case Ot.OP_SUB:e=Math.max(h.byteLength(),l.byteLength())+1;break;default:e=Math.max(h.byteLength(),l.byteLength())}this.ensureStackMem(e);let i=new d(0);switch(r){case Ot.OP_ADD:i=h.add(l);break;case Ot.OP_SUB:i=h.sub(l);break;case Ot.OP_MUL:i=h.mul(l);break;case Ot.OP_DIV:0===l.cmpn(0)&&this.scriptEvaluationError("OP_DIV cannot divide by zero!"),i=h.div(l);break;case Ot.OP_MOD:0===l.cmpn(0)&&this.scriptEvaluationError("OP_MOD cannot divide by zero!"),i=h.mod(l);break;case Ot.OP_BOOLAND:i=new d(0!==h.cmpn(0)&&0!==l.cmpn(0)?1:0);break;case Ot.OP_BOOLOR:i=new d(0!==h.cmpn(0)||0!==l.cmpn(0)?1:0);break;case Ot.OP_NUMEQUAL:case Ot.OP_NUMEQUALVERIFY:i=new d(0===h.cmp(l)?1:0);break;case Ot.OP_NUMNOTEQUAL:i=new d(0!==h.cmp(l)?1:0);break;case Ot.OP_LESSTHAN:i=new d(h.cmp(l)<0?1:0);break;case Ot.OP_GREATERTHAN:i=new d(h.cmp(l)>0?1:0);break;case Ot.OP_LESSTHANOREQUAL:i=new d(h.cmp(l)<=0?1:0);break;case Ot.OP_GREATERTHANOREQUAL:i=new d(h.cmp(l)>=0?1:0);break;case Ot.OP_MIN:i=h.cmp(l)<0?h:l;break;case Ot.OP_MAX:i=h.cmp(l)>0?h:l}this.pushStack(i.toScriptNum()),r===Ot.OP_NUMEQUALVERIFY&&(this.castToBool(this.stackTop())||this.scriptEvaluationError("OP_NUMEQUALVERIFY requires the top stack item to be truthy."),this.popStack());break}case Ot.OP_WITHIN:this.stack.length<3&&this.scriptEvaluationError("OP_WITHIN requires at least three items to be on the stack."),f=d.fromScriptNum(this.popStack(),Rt),l=d.fromScriptNum(this.popStack(),Rt),h=d.fromScriptNum(this.popStack(),Rt),w=h.cmp(l)>=0&&h.cmp(f)<0,this.pushStack(w?[1]:[]);break;case Ot.OP_RIPEMD160:case Ot.OP_SHA1:case Ot.OP_SHA256:case Ot.OP_HASH160:case Ot.OP_HASH256:{this.stack.length<1&&this.scriptEvaluationError(`${Ot[r]} requires at least one item to be on the stack.`),e=this.popStack();let t=[];r===Ot.OP_RIPEMD160?t=we(e):r===Ot.OP_SHA1?t=ge(e):r===Ot.OP_SHA256?t=me(e):r===Ot.OP_HASH160?t=ve(e):r===Ot.OP_HASH256&&(t=Ie(e)),this.pushStack(t);break}case Ot.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case Ot.OP_CHECKSIG:case Ot.OP_CHECKSIGVERIFY:{this.stack.length<2&&this.scriptEvaluationError(`${Ot[r]} requires at least two items to be on the stack.`),I=this.popStack(),y=this.popStack(),this.checkSignatureEncoding(y)&&this.checkPublicKeyEncoding(I)||this.scriptEvaluationError(`${Ot[r]} requires correct encoding for the public key and signature.`);const e=("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1);if(m=new _t(e),m.findAndDelete((new _t).writeBin(y)),g=!1,y.length>0)try{v=Et.fromChecksigFormat(y),k=Ge.fromDER(I),g=this.verifySignature(v,k,m)}catch(e){g=!1}this.pushStack(g?[1]:[]),r===Ot.OP_CHECKSIGVERIFY&&(g||this.scriptEvaluationError("OP_CHECKSIGVERIFY requires that a valid signature is provided."),this.popStack());break}case Ot.OP_CHECKMULTISIG:case Ot.OP_CHECKMULTISIGVERIFY:{S=1,this.stack.length<S&&this.scriptEvaluationError(`${Ot[r]} requires at least 1 item for nKeys.`),N=d.fromScriptNum(this.stackTop(-S),Rt).toNumber(),(N<0||N>Ft)&&this.scriptEvaluationError(`${Ot[r]} requires a key count between 0 and ${Ft}.`),E=++S,S+=N,this.stack.length<S&&this.scriptEvaluationError(`${Ot[r]} stack too small for nKeys and keys. Need ${S}, have ${this.stack.length}.`),O=d.fromScriptNum(this.stackTop(-S),Rt).toNumber(),(O<0||O>N)&&this.scriptEvaluationError(`${Ot[r]} requires the number of signatures to be no greater than the number of keys.`),P=++S,S+=O,this.stack.length<S&&this.scriptEvaluationError(`${Ot[r]} stack too small for N, keys, M, sigs, and dummy. Need ${S}, have ${this.stack.length}.`);const e=("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1);m=new _t(e);for(let e=0;e<O;e++)y=this.stackTop(-P-e),m.findAndDelete((new _t).writeBin(y));for(g=!0;g&&O>0;){if(0===N){g=!1;break}if(y=this.stackTop(-P),I=this.stackTop(-E),this.checkSignatureEncoding(y)&&this.checkPublicKeyEncoding(I)||this.scriptEvaluationError(`${Ot[r]} requires correct encoding for the public key and signature.`),_=!1,y.length>0)try{v=Et.fromChecksigFormat(y),k=Ge.fromDER(I),_=this.verifySignature(v,k,m)}catch(e){_=!1}_&&(P++,O--),E++,N--,O>N&&(g=!1)}let t=1+d.fromScriptNum(this.stackTop(-1),!1).toNumber()+1+d.fromScriptNum(this.stackTop(-(1+d.fromScriptNum(this.stackTop(-1),!1).toNumber()+1)),!1).toNumber()+1-1;for(;t>0;)this.popStack(),t--;this.stack.length<1&&this.scriptEvaluationError(`${Ot[r]} requires an extra item (dummy) to be on the stack.`),this.popStack().length>0&&this.scriptEvaluationError(`${Ot[r]} requires the extra stack item (dummy) to be empty.`),this.pushStack(g?[1]:[]),r===Ot.OP_CHECKMULTISIGVERIFY&&(g||this.scriptEvaluationError("OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."),this.popStack());break}case Ot.OP_CAT:{this.stack.length<2&&this.scriptEvaluationError("OP_CAT requires at least two items to be on the stack."),n=this.popStack(),t=this.popStack();const e=t.concat(n);e.length>Tt&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes."),this.pushStack(e);break}case Ot.OP_SPLIT:{this.stack.length<2&&this.scriptEvaluationError("OP_SPLIT requires at least two items to be on the stack.");const e=this.popStack(),t=this.popStack();p=d.fromScriptNum(e,Rt).toNumber(),(p<0||p>t.length)&&this.scriptEvaluationError("OP_SPLIT requires the first stack item to be a non-negative number less than or equal to the size of the second-from-top stack item."),this.pushStack(t.slice(0,p)),this.pushStack(t.slice(p));break}case Ot.OP_NUM2BIN:{this.stack.length<2&&this.scriptEvaluationError("OP_NUM2BIN requires at least two items to be on the stack."),b=d.fromScriptNum(this.popStack(),Rt).toNumber(),(b>Tt||b<0)&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes or negative size.");let e=this.popStack();if(e=Ke(e),e.length>b&&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."),e.length===b){this.pushStack(e);break}const t=new Array(b).fill(0);let r=0;e.length>0&&(r=128&e[e.length-1],e[e.length-1]&=127);for(let r=0;r<e.length;r++)t[r]=e[r];0!==r&&(t[b-1]|=128),this.pushStack(t);break}case Ot.OP_BIN2NUM:{this.stack.length<1&&this.scriptEvaluationError("OP_BIN2NUM requires at least one item to be on the stack."),t=this.popStack();const e=Ke(t);(function(e,t=Number.MAX_SAFE_INTEGER){return!(e.length>t||e.length>0&&!(127&e[e.length-1]||!(e.length<=1)&&128&e[e.length-2]))})(e)||this.scriptEvaluationError("OP_BIN2NUM requires that the resulting number is valid."),this.pushStack(e);break}default:this.scriptEvaluationError(`Invalid opcode ${r} (pc=${this.programCounter}).`)}}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, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF 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, found ${this.stack.length}.`),0===this.stack.length?this.scriptEvaluationError("The top stack element must be truthy after script evaluation (stack is empty)."):this.castToBool(this.stackTop())||this.scriptEvaluationError("The top stack element must be truthy after script evaluation."),!0}castToBool(e){if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(0!==e[t])return!(t===e.length-1&&128===e[t]);return!1}scriptEvaluationError(e){const t=`Context: ${this.context}, PC: ${this.programCounter}`,r=this.stack.map((e=>null!=e&&void 0!==e.length?Ne(e):null==e?"null/undef":"INVALID_STACK_ITEM")).join(", "),i=this.altStack.map((e=>null!=e&&void 0!==e.length?Ne(e):null==e?"null/undef":"INVALID_STACK_ITEM")).join(", "),n=`Stack: [${r}] (len: ${this.stack.length}, mem: ${this.stackMem})`,s=`AltStack: [${i}] (len: ${this.altStack.length}, mem: ${this.altStackMem})`,a=`IfStack: [${this.ifStack.join(", ")}]`;throw new Error(`Script evaluation error: ${e}\nTXID: ${this.sourceTXID}, OutputIdx: ${this.sourceOutputIndex}\n${t}\n${n}\n${s}\n${a}`)}}function Bt(e){if(null==e)throw new Error("must have value");return e}class Ut{lock(e){let t;if("string"==typeof e){const r=Be(e);if(0!==r.prefix[0]&&111!==r.prefix[0])throw new Error("only P2PKH is supported");t=r.data}else t=e;if(20!==t.length)throw new Error("P2PKH hash length must be 20 bytes");return new xt([{op:Ot.OP_DUP},{op:Ot.OP_HASH160},{op:t.length,data:t},{op:Ot.OP_EQUALVERIFY},{op:Ot.OP_CHECKSIG}])}unlock(e,t="all",r=!1,i,n){return{sign:async(s,a)=>{let o=Et.SIGHASH_FORKID;"all"===t&&(o|=Et.SIGHASH_ALL),"none"===t&&(o|=Et.SIGHASH_NONE),"single"===t&&(o|=Et.SIGHASH_SINGLE),r&&(o|=Et.SIGHASH_ANYONECANPAY);const c=s.inputs[a],d=s.inputs.filter(((e,t)=>t!==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 h=Et.format({sourceTXID:u,sourceOutputIndex:Bt(c.sourceOutputIndex),sourceSatoshis:i,transactionVersion:s.version,otherInputs:d,inputIndex:a,outputs:s.outputs,inputSequence:Bt(c.sequence),subscript:n,lockTime:s.lockTime,scope:o}),l=e.sign(me(h)),f=new Et(l.r,l.s,o).toChecksigFormat(),p=e.toPublicKey().encode(!0);return new At([{op:f.length,data:f},{op:p.length,data:p}])},estimateLength:async()=>108}}}class Lt{type="raw";constructor(e="raw"){this.type=e}lock(e){const t=[{op:Ot.OP_OVER},{op:Ot.OP_3},{op:Ot.OP_SPLIT},{op:Ot.OP_NIP},{op:Ot.OP_1},{op:Ot.OP_SPLIT},{op:Ot.OP_SWAP},{op:Ot.OP_SPLIT},{op:Ot.OP_DROP}];return"raw"!==this.type&&t.push({op:Ot["OP_"+this.type]}),t.push({op:e.length,data:e}),t.push({op:Ot.OP_EQUALVERIFY}),t.push({op:Ot.OP_CHECKSIG}),new xt(t)}unlock(e,t,r="all",i=!1){return{sign:async(n,s)=>{void 0===t&&(t=rt.fromRandom());let a=Et.SIGHASH_FORKID;"all"===r&&(a|=Et.SIGHASH_ALL),"none"===r&&(a|=Et.SIGHASH_NONE),"single"===r&&(a|=Et.SIGHASH_SINGLE),i&&(a|=Et.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 d=Et.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 _t,lockTime:n.lockTime,scope:a}),u=t.sign(me(d),void 0,!0,e),h=new Et(u.r,u.s,a).toChecksigFormat(),l=t.toPublicKey().encode(!0);return new At([{op:h.length,data:h},{op:l.length,data:l}])},estimateLength:async()=>108}}}function Kt(e){if(null==e)throw new Error("must have value");return e}class Ht{wallet;originator;static decode(e){const t=Ge.fromString(Ne(Kt(e.chunks[0].data))),r=[];for(let t=2;t<e.chunks.length;t++){const i=e.chunks[t+1]?.op;let n=e.chunks[t].data??[];if(0===n.length&&(e.chunks[t].op>=80&&e.chunks[t].op<=95?n=[e.chunks[t].op-80]:0===e.chunks[t].op?n=[0]:79===e.chunks[t].op&&(n=[129])),r.push(n),i===Ot.OP_DROP||i===Ot.OP_2DROP)break}return{fields:r,lockingPublicKey:t}}constructor(e,t){this.wallet=e,this.originator=t}async lock(e,t,r,i,n=!1,s=!0,a="before"){const{publicKey:o}=await this.wallet.getPublicKey({protocolID:t,keyID:r,counterparty:i,forSelf:n},this.originator),c=[],d=[];if(c.push({op:o.length/2,data:Oe(o,"hex")}),c.push({op:Ot.OP_CHECKSIG}),s){const n=e.reduce(((e,t)=>[...e,...t]),[]),{signature:s}=await this.wallet.createSignature({data:n,protocolID:t,keyID:r,counterparty:i},this.originator);e.push(s)}for(const t of e)d.push(0===(u=t).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 h=e.length;for(;h>1;)d.push({op:Ot.OP_2DROP}),h-=2;return 0!==h&&d.push({op:Ot.OP_DROP}),new xt("before"===a?[...c,...d]:[...d,...c])}unlock(e,t,r,i="all",n=!1,s,a){return{sign:async(o,c)=>{let d=Et.SIGHASH_FORKID;"all"===i&&(d|=Et.SIGHASH_ALL),"none"===i&&(d|=Et.SIGHASH_NONE),"single"===i&&(d|=Et.SIGHASH_SINGLE),n&&(d|=Et.SIGHASH_ANYONECANPAY);const u=o.inputs[c],h=o.inputs.filter(((e,t)=>t!==c)),l=u.sourceTXID??u.sourceTransaction?.id("hex");if(null==l||void 0===l)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=Et.format({sourceTXID:l,sourceOutputIndex:Kt(u.sourceOutputIndex),sourceSatoshis:s,transactionVersion:o.version,otherInputs:h,inputIndex:c,outputs:o.outputs,inputSequence:u.sequence??4294967295,subscript:a,lockTime:o.lockTime,scope:d}),p=me(f),{signature:b}=await this.wallet.createSignature({data:p,protocolID:e,keyID:t,counterparty:r},this.originator),w=$e.fromDER([...b]),g=new Et(w.r,w.s,d).toChecksigFormat();return new At([{op:g.length,data:g}])},estimateLength:async()=>73}}}class qt{value;constructor(e){this.value=e}async computeFee(e){const t=e=>e>2**32?9:e>65536?5:e>253?3:1;let r=4;r+=t(e.inputs.length);for(let i=0;i<e.inputs.length;i++){const n=e.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(e,i)}r+=t(s),r+=s}r+=t(e.outputs.length);for(const i of e.outputs){r+=8;const e=i.lockingScript.toBinary().length;r+=t(e),r+=e}return r+=4,Math.ceil(r/1e3*this.value)}}class Mt{https;constructor(e){this.https=e}async request(e,t){return await new Promise(((r,i)=>{const n=this.https.request(e,t,(e=>{let t="";e.on("data",(e=>{t+=e})),e.on("end",(()=>{const i=e.statusCode>=200&&e.statusCode<=299,n=e.headers["content-type"],s=""!==t&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(t):t;r({status:e.statusCode,statusText:e.statusMessage,ok:i,data:s})}))}));n.on("error",(e=>{i(e)})),null!==t.data&&void 0!==t.data&&n.write(JSON.stringify(t.data)),n.end()}))}}class $t{fetch;constructor(e){this.fetch=e}async request(e,t){const r={method:t.method,headers:t.headers,body:JSON.stringify(t.data)},i=await this.fetch(e,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 zt(){const e={async request(...e){throw new Error("No method available to perform HTTP request")}};if("undefined"!=typeof window&&"function"==typeof window.fetch)return new $t(window.fetch.bind(window));if("undefined"==typeof require)return e;try{const e=require("https");return new Mt(e)}catch(t){return e}}function Wt(){return`ts-sdk-${Ne(Ze(16))}`}class jt{URL;apiKey;deploymentId;callbackUrl;callbackToken;headers;httpClient;constructor(e,t){if(this.URL=e,"string"==typeof t)this.apiKey=t,this.httpClient=zt(),this.deploymentId=Wt(),this.callbackToken=void 0,this.callbackUrl=void 0;else{const e=t??{},{apiKey:r,deploymentId:i,httpClient:n,callbackToken:s,callbackUrl:a,headers:o}=e;this.apiKey=r,this.httpClient=n??zt(),this.deploymentId=i??Wt(),this.callbackToken=s,this.callbackUrl=a,this.headers=o}}requestHeaders(){const e={"Content-Type":"application/json","XDeployment-ID":this.deploymentId};if(null!=this.apiKey&&""!==this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),null!=this.callbackUrl&&""!==this.callbackUrl&&(e["X-CallbackUrl"]=this.callbackUrl),null!=this.callbackToken&&""!==this.callbackToken&&(e["X-CallbackToken"]=this.callbackToken),null!=this.headers)for(const t in this.headers)e[t]=this.headers[t];return e}async broadcast(e){let t;try{t=e.toHexEF()}catch(r){if("All inputs must have source transactions when serializing to EF format"!==r.message)throw r;t=e.toHex()}const r={method:"POST",headers:this.requestHeaders(),data:{rawTx:t}};try{const e=await this.httpClient.request(`${this.URL}/v1/tx`,r);if(e.ok){const{txid:t,extraInfo:r,txStatus:i,competingTxs:n}=e.data,s={status:"success",txid:t,message:`${i} ${r}`};return null!=n&&(s.competingTxs=n),s}{const t=typeof e.status,r={status:"error",code:"number"===t||"string"===t?e.status.toString():"ERR_UNKNOWN",description:"Unknown error"};let i=e.data;if("string"==typeof i)try{i=JSON.parse(e.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(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}async broadcastMany(e){const t=e.map((e=>{try{return{rawTx:e.toHexEF()}}catch(t){if("All inputs must have source transactions when serializing to EF format"===t.message)return{rawTx:e.toHex()};throw t}})),r={method:"POST",headers:this.requestHeaders(),data:t};try{return(await this.httpClient.request(`${this.URL}/v1/txs`,r)).data}catch(t){const r={status:"error",code:"500",description:"string"==typeof t.message?t.message:"Internal Server Error"};return e.map((()=>r))}}}function Xt(e=!1,t={}){return new jt(e?"https://arc-test.taal.com":"https://arc.taal.com",t)}class Gt{network;apiKey;URL;httpClient;constructor(e="main",t={}){const{apiKey:r,httpClient:i}=t;this.network=e,this.URL=`https://api.whatsonchain.com/v1/bsv/${e}`,this.httpClient=i??zt(),this.apiKey=r??""}async isValidRootForHeight(e,t){const r={method:"GET",headers:this.getHttpHeaders()},i=await this.httpClient.request(`${this.URL}/block/${t}/header`,r);if(i.ok){const{merkleroot:t}=i.data;return t===e}if(404===i.status)return!1;throw new Error(`Failed to verify merkleroot for height ${t} because of an error: ${JSON.stringify(i.data)} `)}async currentHeight(){try{const e={method:"GET",headers:this.getHttpHeaders()},t=await this.httpClient.request(`${this.URL}/block/headers`,e);if(t.ok)return t.data[0].height;throw new Error(`Failed to get current height because of an error: ${JSON.stringify(t.data)} `)}catch(e){throw new Error(`Failed to get current height because of an error: ${e instanceof Error?e.message:String(e)}`)}}getHttpHeaders(){const e={Accept:"application/json"};return"string"==typeof this.apiKey&&""!==this.apiKey.trim()&&(e.Authorization=this.apiKey),e}}function Yt(){return new Gt}class Jt{blockHeight;path;static fromHex(e){return Jt.fromBinary(Oe(e,"hex"))}static fromReader(e,t=!0){const r=e.readVarIntNum(),i=e.readUInt8(),n=Array(i).fill(null).map((()=>[]));let s,a,o;for(let t=0;t<i;t++){for(o=e.readVarIntNum();o>0;){a=e.readVarIntNum(),s=e.readUInt8();const r={offset:a};1&s?r.duplicate=!0:(2&s&&(r.txid=!0),r.hash=Ne(e.read(32).reverse())),Array.isArray(n[t])&&0!==n[t].length||(n[t]=[]),n[t].push(r),o--}n[t].sort(((e,t)=>e.offset-t.offset))}return new Jt(r,n,t)}static fromBinary(e){const t=new Le(e);return Jt.fromReader(t)}static fromCoinbaseTxidAndHeight(e,t){return new Jt(t,[[{offset:0,hash:e,txid:!0}]])}constructor(e,t,r=!0){this.blockHeight=e,this.path=t;const i=Array(this.path.length).fill(0).map((()=>new Set));let n;this.path.forEach(((e,t)=>{if(0===e.length&&0===t)throw new Error(`Empty level at height: ${t}`);const n=new Set;e.forEach((e=>{if(n.has(e.offset))throw new Error(`Duplicate offset: ${e.offset}, at height: ${t}`);if(n.add(e.offset),0===t){if(!0!==e.duplicate)for(let t=1;t<this.path.length;t++)i[t].add(e.offset>>t^1)}else if(r&&!i[t].has(e.offset))throw new Error(`Invalid offset: ${e.offset}, at height: ${t}, with legal offsets: ${Array.from(i[t]).join(", ")}`)}))})),this.path[0].forEach(((e,t)=>{if(0===t&&(n=this.computeRoot(e.hash)),n!==this.computeRoot(e.hash))throw new Error("Mismatched roots")}))}toBinary(){const e=new Ue;e.writeVarIntNum(this.blockHeight);const t=this.path.length;e.writeUInt8(t);for(let r=0;r<t;r++){const t=Object.keys(this.path[r]).length;e.writeVarIntNum(t);for(const t of this.path[r]){e.writeVarIntNum(t.offset);let r=0;!0===t?.duplicate&&(r|=1),void 0!==t?.txid&&null!==t.txid&&(r|=2),e.writeUInt8(r),1&r||e.write(Oe(t.hash,"hex").reverse())}}return e.toArray()}toHex(){return Ne(this.toBinary())}indexOf(e){const t=this.path[0].find((t=>t.hash===e));if(null==t)throw new Error(`Transaction ID ${e} not found in the Merkle Path`);return t.offset}computeRoot(e){if("string"!=typeof e){const t=this.path[0].find((e=>Boolean(e?.hash)));if(null==t)throw new Error("No valid leaf found in the Merkle Path");e=t.hash}if("string"!=typeof e)throw new Error("Transaction ID is undefined");const t=this.indexOf(e);if("number"!=typeof t)throw new Error(`This proof does not contain the txid: ${e??"undefined"}`);const r=e=>Ne(Ie(Oe(e,"hex").reverse()).reverse());let i=e;if(1===this.path.length&&1===this.path[0].length)return i;for(let e=0;e<this.path.length;e++){this.path[e];const n=t>>e^1,s=this.findOrComputeLeaf(e,n);if("object"!=typeof s)throw new Error(`Missing hash for index ${t} at height ${e}`);i=!0===s.duplicate?r((i??"")+(i??"")):r(n%2!=0?(s.hash??"")+(i??""):(i??"")+(s.hash??""))}return i}findOrComputeLeaf(e,t){const r=e=>Ne(Ie(Oe(e,"hex").reverse()).reverse());let i=this.path[e].find((e=>e.offset===t));if(null!=i)return i;if(0===e)return;const n=e-1,s=t<<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:t,hash:c},i}async verify(e,t){const r=this.computeRoot(e);if(0===this.indexOf(e)){const e=await t.currentHeight();if(this.blockHeight+100<e)return!1}return await t.isValidRootForHeight(r,this.blockHeight)}combine(e){if(this.blockHeight!==e.blockHeight)throw new Error("You cannot combine paths which do not have the same block height.");if(this.computeRoot()!==e.computeRoot())throw new Error("You cannot combine paths which do not have the same root.");const t=[];for(let r=0;r<this.path.length;r++){t.push([]);for(let e=0;e<this.path[r].length;e++)t[r].push(this.path[r][e]);for(let i=0;i<e.path[r].length;i++)if(void 0===t[r].find((t=>t.offset===e.path[r][i].offset)))t[r].push(e.path[r][i]);else if(void 0!==e.path[r][i]?.txid&&null!==e.path[r][i]?.txid){const n=t[r].find((t=>t.offset===e.path[r][i].offset));null!=n&&(n.txid=!0)}}this.path=t,this.trim()}trim(){const e=(e,t)=>{0!==t.length&&t.slice(-1)[0]===e||t.push(e)},t=(e,t)=>{for(let r=e.length;r>=0;r--){const i=this.path[t].findIndex((t=>t.offset===e[r]));i>=0&&this.path[t].splice(i,1)}},r=t=>{const r=[];for(const i of t)e(i>>1,r);return r};let i=[],n=[];for(let e=0;e<this.path.length;e++)this.path[e].sort(((e,t)=>e.offset-t.offset));for(let t=0;t<this.path[0].length;t++){const r=this.path[0][t];if(!0===r.txid)e(r.offset>>1,i);else{const i=r.offset%2==1,s=this.path[0][t+(i?-1:1)];void 0!==s.txid&&null!==s.txid&&s.txid||e(s.offset,n)}}t(n,0);for(let e=1;e<this.path.length;e++)n=i,i=r(i),t(n,e)}}class Zt{_bumpIndex;_tx;_rawTx;_txid;inputTxids=[];isValid=void 0;get bumpIndex(){return this._bumpIndex}set bumpIndex(e){this._bumpIndex=e,this.updateInputTxids()}get hasProof(){return void 0!==this._bumpIndex}get isTxidOnly(){return void 0!==this._txid&&null!==this._txid&&null==this._rawTx&&null==this._tx}get txid(){if(void 0!==this._txid&&null!==this._txid&&""!==this._txid)return this._txid;if(null!=this._tx)return this._txid=this._tx.id("hex"),this._txid;if(null!=this._rawTx)return this._txid=Ne(Ie(this._rawTx)),this._txid;throw new Error("Internal")}get tx(){return null!=this._tx?this._tx:null!=this._rawTx?(this._tx=sr.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(e,t){"string"==typeof e?this._txid=e:Array.isArray(e)?this._rawTx=e:this._tx=e,this.bumpIndex=t,this.updateInputTxids()}static fromTx(e,t){return new Zt(e,t)}static fromRawTx(e,t){return new Zt(e,t)}static fromTxid(e,t){return new Zt(e,t)}updateInputTxids(){if(this.hasProof||null==this.tx)this.inputTxids=[];else{const e={};for(const t of this.tx.inputs)void 0!==t.sourceTXID&&null!==t.sourceTXID&&""!==t.sourceTXID&&(e[t.sourceTXID]=!0);this.inputTxids=Object.keys(e)}}toWriter(e,t){const r=t=>{e.writeUInt8(t)},i=()=>{if(null!=this._rawTx)e.write(this._rawTx);else{if(null==this._tx)throw new Error("a valid serialized Transaction is expected");e.write(this._tx.toBinary())}};t===tr?this.isTxidOnly?(r(ir.TXID_ONLY),(()=>{if(null==this._txid)throw new Error("Transaction ID (_txid) is undefined");e.writeReverse(Oe(this._txid,"hex"))})()):void 0!==this.bumpIndex?(r(ir.RAWTX_AND_BUMP_INDEX),e.writeVarIntNum(this.bumpIndex),i()):(r(ir.RAWTX),i()):(i(),(()=>{void 0===this.bumpIndex?r(ir.RAWTX):(r(ir.RAWTX_AND_BUMP_INDEX),e.writeVarIntNum(this.bumpIndex))})())}static fromReader(e,t){let r,i,n;if(t===tr){const t=e.readUInt8();t===ir.TXID_ONLY?n=Zt.fromTxid(Ne(e.readReverse(32))):(t===ir.RAWTX_AND_BUMP_INDEX&&(i=e.readVarIntNum()),r=sr.fromReader(e),n=Zt.fromTx(r,i))}else r=sr.fromReader(e),i=0!==e.readUInt8()?e.readVarIntNum():void 0,n=Zt.fromTx(r,i);return n}}function Qt(e){if(null==e)throw new Error("Expected a valid value, but got undefined.");return e}const er=4022206465,tr=4022206466,rr=16843009;var ir;!function(e){e[e.RAWTX=0]="RAWTX",e[e.RAWTX_AND_BUMP_INDEX=1]="RAWTX_AND_BUMP_INDEX",e[e.TXID_ONLY=2]="TXID_ONLY"}(ir||(ir={}));class nr{bumps=[];txs=[];version=tr;atomicTxid=void 0;constructor(e=tr){this.version=e}findTxid(e){return this.txs.find((t=>t.txid===e))}makeTxidOnly(e){const t=this.txs.findIndex((t=>t.txid===e));if(-1===t)return;let r=this.txs[t];return r.isTxidOnly||(this.txs.splice(t,1),r=this.mergeTxidOnly(e)),r}findBump(e){return this.bumps.find((t=>t.path[0].some((t=>t.hash===e))))}findTransactionForSigning(e){const t=this.findTxid(e);if(null!=t&&null!=t.tx){for(const e of t.tx.inputs)if(null==e.sourceTransaction){const t=this.findTxid(Qt(e.sourceTXID));null!=t&&(e.sourceTransaction=t.tx)}return t.tx}}findAtomicTransaction(e){const t=this.findTxid(e);if(null==t||null==t.tx)return;const r=(e,t)=>{const i=e.findBump(t.id("hex"));if(null!=i)t.merklePath=i;else for(const i of t.inputs){if(null==i.sourceTransaction){const t=e.findTxid(Qt(i.sourceTXID));null!=t&&(i.sourceTransaction=t.tx)}if(null!=i.sourceTransaction){const t=e.findBump(i.sourceTransaction.id("hex"));null!=t?i.sourceTransaction.merklePath=t:r(e,i.sourceTransaction)}}};return r(this,t.tx),t.tx}mergeBump(e){let t;for(let r=0;r<this.bumps.length;r++){const i=this.bumps[r];if(i===e)return r;if(i.blockHeight===e.blockHeight&&i.computeRoot()===e.computeRoot()){i.combine(e),t=r;break}}void 0===t&&(t=this.bumps.length,this.bumps.push(e));const r=this.bumps[t];for(const e of this.txs){const i=e.txid;if(null==e.bumpIndex)for(const n of r.path[0])if(n.hash===i){e.bumpIndex=t,n.txid=!0;break}}return t}mergeRawTx(e,t){const r=new Zt(e,t);return this.removeExistingTxid(r.txid),this.txs.push(r),this.tryToValidateBumpIndex(r),r}mergeTransaction(e){const t=e.id("hex");let r;this.removeExistingTxid(t),null!=e.merklePath&&(r=this.mergeBump(e.merklePath));const i=new Zt(e,r);if(this.txs.push(i),this.tryToValidateBumpIndex(i),r=i.bumpIndex,void 0===r)for(const t of e.inputs)null!=t.sourceTransaction&&this.mergeTransaction(t.sourceTransaction);return i}removeExistingTxid(e){const t=this.txs.findIndex((t=>t.txid===e));t>=0&&this.txs.splice(t,1)}mergeTxidOnly(e){let t=this.txs.find((t=>t.txid===e));return null==t&&(t=new Zt(e),this.txs.push(t),this.tryToValidateBumpIndex(t)),t}mergeBeefTx(e){let t=this.findTxid(e.txid);if(e.isTxidOnly&&null==t?t=this.mergeTxidOnly(e.txid):null==e._tx||null!=t&&!t.isTxidOnly?null==e._rawTx||null!=t&&!t.isTxidOnly||(t=this.mergeRawTx(e._rawTx)):t=this.mergeTransaction(e._tx),null==t)throw new Error(`Failed to merge BeefTx for txid: ${e.txid}`);return t}mergeBeef(e){const t=Array.isArray(e)?nr.fromBinary(e):e;for(const e of t.bumps)this.mergeBump(e);for(const e of t.txs)this.mergeBeefTx(e)}isValid(e){return this.verifyValid(e).valid}async verify(e,t){const r=this.verifyValid(t);if(!r.valid)return!1;for(const t of Object.keys(r.roots))if(!await e.isValidRootForHeight(r.roots[t],Number(t)))return!1;return!0}verifyValid(e){const t={valid:!1,roots:{}},r=this.sortTxs();if(r.missingInputs.length>0||r.notValid.length>0||r.txidOnly.length>0&&!0!==e||r.withMissingInputs.length>0)return t;const i={};for(const r of this.txs)if(r.isTxidOnly){if(!0!==e)return t;i[r.txid]=!0}const n=(e,r)=>{const i=e.computeRoot(r);return void 0!==t.roots[e.blockHeight]&&""!==t.roots[e.blockHeight]||(t.roots[e.blockHeight]=i),t.roots[e.blockHeight]===i};for(const e of this.bumps)for(const r of e.path[0])if(!0===r.txid&&"string"==typeof r.hash&&r.hash.length>0&&(i[r.hash]=!0,!n(e,r.hash)))return t;for(const e of this.txs)if(void 0!==e.bumpIndex&&null==this.bumps[e.bumpIndex].path[0].find((t=>t.hash===e.txid)))return t;for(const e of this.txs){for(const r of e.inputTxids)if(!i[r])return t;i[e.txid]=!0}return t.valid=!0,t}toWriter(e){e.writeUInt32LE(this.version),e.writeVarIntNum(this.bumps.length);for(const t of this.bumps)e.write(t.toBinary());e.writeVarIntNum(this.txs.length);for(const t of this.txs)t.toWriter(e,this.version)}toBinary(){this.sortTxs();const e=new Ue;return this.toWriter(e),e.toArray()}toBinaryAtomic(e){this.sortTxs();const t=this.findTxid(e);if(null==t)throw new Error(`${e} does not exist in this Beef`);const r=this.txs[this.txs.length-1]===t?this:this.clone();if(r!==this){const t=this.txs.findIndex((t=>t.txid===e));r.txs.splice(t+1)}const i=new Ue;return i.writeUInt32LE(rr),i.writeReverse(Oe(e,"hex")),r.toWriter(i),i.toArray()}toHex(){return Ne(this.toBinary())}static fromReader(e){let t,r=e.readUInt32LE();if(r===rr&&(t=Ne(e.readReverse(32)),r=e.readUInt32LE()),r!==er&&r!==tr)throw new Error(`Serialized BEEF must start with ${er} or ${tr} but starts with ${r}`);const i=new nr(r),n=e.readVarIntNum();for(let t=0;t<n;t++){const t=Jt.fromReader(e,!1);i.bumps.push(t)}const s=e.readVarIntNum();for(let t=0;t<s;t++){const t=Zt.fromReader(e,r);i.txs.push(t)}return i.atomicTxid=t,i}static fromBinary(e){const t=new Le(e);return nr.fromReader(t)}static fromString(e,t="hex"){const r=Oe(e,t),i=new Le(r);return nr.fromReader(i)}tryToValidateBumpIndex(e){if(void 0!==e.bumpIndex)return!0;const t=e.txid;for(let r=0;r<this.bumps.length;r++){const i=this.bumps[r].path[0].findIndex((e=>e.hash===t));if(i>=0)return e.bumpIndex=r,this.bumps[r].path[0][i].txid=!0,!0}return!1}sortTxs(){const e={},t={};let r=[];const i=[],n=[];for(const s of this.txs)t[s.txid]=s,s.isValid=s.hasProof,s.isValid?(e[s.txid]=!0,i.push(s)):s.isTxidOnly&&0===s.inputTxids.length?(e[s.txid]=!0,n.push(s)):r.push(s);const s={},a=[],o=r;r=[];for(const e of o){let i=!1;for(const r of e.inputTxids)void 0===t[r]&&(s[r]=!0,i=!0);i?a.push(e):r.push(e)}for(;r.length>0;){const t=r;r=[];for(const n of t)n.inputTxids.every((t=>e[t]))?(e[n.txid]=!0,i.push(n)):r.push(n);if(t.length===r.length)break}const c=r;return this.txs=a.concat(c).concat(n).concat(i),{missingInputs:Object.keys(s),notValid:c.map((e=>e.txid)),valid:Object.keys(e),withMissingInputs:a.map((e=>e.txid)),txidOnly:n.map((e=>e.txid))}}clone(){const e=new nr;return e.version=this.version,e.bumps=Array.from(this.bumps),e.txs=Array.from(this.txs),e}trimKnownTxids(e){for(let t=0;t<this.txs.length;){const r=this.txs[t];r.isTxidOnly&&e.includes(r.txid)?this.txs.splice(t,1):t++}}getValidTxids(){return this.sortTxs().valid}toLogString(){let e="";e+=`BEEF with ${this.bumps.length} BUMPS and ${this.txs.length} Transactions, isValid ${this.isValid().toString()}\n`;let t=-1;for(const r of this.bumps)t++,e+=` BUMP ${t}\n block: ${r.blockHeight}\n txids: [\n${r.path[0].filter((e=>!0===e.txid)).map((e=>` '${e.hash??""}'`)).join(",\n")}\n ]\n`;t=-1;for(const r of this.txs)t++,e+=` TX ${t}\n txid: ${r.txid}\n`,void 0!==r.bumpIndex&&(e+=` bumpIndex: ${r.bumpIndex}\n`),r.isTxidOnly?e+=" txidOnly\n":e+=` rawTx length=${r.rawTx?.length??0}\n`,r.inputTxids.length>0&&(e+=` inputs: [\n${r.inputTxids.map((e=>` '${e}'`)).join(",\n")}\n ]\n`);return e}addComputedLeaves(){for(const t of this.bumps)for(let r=1;r<t.path.length;r++)for(const i of t.path[r-1])if("string"==typeof i.hash&&!(1&i.offset)){const n=t.path[r-1].find((e=>e.offset===i.offset+1)),s=i.offset>>1;void 0!==n&&"string"==typeof n.hash&&t.path[r].every((e=>e.offset!==s))&&t.path[r].push({offset:s,hash:(e=n.hash+i.hash,Ne(Ie(Oe(e,"hex").reverse()).reverse()))})}var e}}class sr{version;inputs;outputs;lockTime;metadata;merklePath;cachedHash;static addPathOrInputs(e,t,r){if("number"==typeof e.pathIndex){const t=r[e.pathIndex];if("object"!=typeof t)throw new Error("Invalid merkle path index found in BEEF!");e.tx.merklePath=t}else for(const i of e.tx.inputs){if(void 0===i.sourceTXID)throw new Error("Input sourceTXID is undefined");const e=t[i.sourceTXID];if("object"!=typeof e)throw new Error(`Reference to unknown TXID in BEEF: ${i.sourceTXID??"undefined"}`);i.sourceTransaction=e.tx,this.addPathOrInputs(e,t,r)}}static fromBEEF(e,t){const{tx:r}=sr.fromAnyBeef(e,t);return r}static fromAtomicBEEF(e){const{tx:t,txid:r,beef:i}=sr.fromAnyBeef(e);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 t}static fromAnyBeef(e,t){const r=nr.fromBinary(e);if(r.txs.length<1)throw new Error("beef must include at least one transaction.");const i=t||r.atomicTxid||r.txs.slice(-1)[0].txid,n=r.findAtomicTransaction(i);if(null==n)throw t?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(e){const t=new Le(e),r=t.readUInt32LE();if("0000000000ef"!==Ne(t.read(6)))throw new Error("Invalid EF marker");const i=t.readVarIntNum(),n=[];for(let e=0;e<i;e++){const e=Ne(t.readReverse(32)),r=t.readUInt32LE(),i=t.readVarIntNum(),s=t.read(i),a=At.fromBinary(s),o=t.readUInt32LE(),c=t.readUInt64LEBn().toNumber(),d=t.readVarIntNum(),u=t.read(d),h=xt.fromBinary(u),l=new sr(void 0,[],[],void 0);l.outputs=Array(r+1).fill(null),l.outputs[r]={satoshis:c,lockingScript:h},n.push({sourceTransaction:l,sourceTXID:e,sourceOutputIndex:r,unlockingScript:a,sequence:o})}const s=t.readVarIntNum(),a=[];for(let e=0;e<s;e++){const e=t.readUInt64LEBn().toNumber(),r=t.readVarIntNum(),i=t.read(r),n=xt.fromBinary(i);a.push({satoshis:e,lockingScript:n})}const o=t.readUInt32LE();return new sr(r,n,a,o)}static parseScriptOffsets(e){const t=new Le(e),r=[],i=[];t.pos+=4;const n=t.readVarIntNum();for(let e=0;e<n;e++){t.pos+=36;const i=t.readVarIntNum();r.push({vin:e,offset:t.pos,length:i}),t.pos+=i+4}const s=t.readVarIntNum();for(let e=0;e<s;e++){t.pos+=8;const r=t.readVarIntNum();i.push({vout:e,offset:t.pos,length:r}),t.pos+=r}return{inputs:r,outputs:i}}static fromReader(e){const t=e.readUInt32LE(),r=e.readVarIntNum(),i=[];for(let t=0;t<r;t++){const t=Ne(e.readReverse(32)),r=e.readUInt32LE(),n=e.readVarIntNum(),s=e.read(n),a=At.fromBinary(s),o=e.readUInt32LE();i.push({sourceTXID:t,sourceOutputIndex:r,unlockingScript:a,sequence:o})}const n=e.readVarIntNum(),s=[];for(let t=0;t<n;t++){const t=e.readUInt64LEBn().toNumber(),r=e.readVarIntNum(),i=e.read(r),n=xt.fromBinary(i);s.push({satoshis:t,lockingScript:n})}const a=e.readUInt32LE();return new sr(t,i,s,a)}static fromBinary(e){const t=new Le(e);return sr.fromReader(t)}static fromHex(e){return sr.fromBinary(Oe(e,"hex"))}static fromHexEF(e){return sr.fromEF(Oe(e,"hex"))}static fromHexBEEF(e,t){return sr.fromBEEF(Oe(e,"hex"),t)}constructor(e=1,t=[],r=[],i=0,n=new Map,s){this.version=e,this.inputs=t,this.outputs=r,this.lockTime=i,this.metadata=n,this.merklePath=s}addInput(e){if(void 0===e.sourceTXID&&void 0===e.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===e.sequence&&(e.sequence=4294967295),this.cachedHash=void 0,this.inputs.push(e)}addOutput(e){if(this.cachedHash=void 0,!0!==e.change){if(void 0===e.satoshis)throw new Error("either satoshis must be defined or change must be set to true");if(e.satoshis<0)throw new Error("satoshis must be a positive integer or zero")}if(null==e.lockingScript)throw new Error("lockingScript must be defined");this.outputs.push(e)}addP2PKHOutput(e,t){const r=(new Ut).lock(e);if(void 0===t)return this.addOutput({lockingScript:r,change:!0});this.addOutput({lockingScript:r,satoshis:t})}updateMetadata(e){this.metadata={...this.metadata,...e}}async fee(e=new qt(1),t="equal"){if(this.cachedHash=void 0,"number"==typeof e){const t=e;e={computeFee:async()=>t}}const r=await e.computeFee(this),i=this.calculateChange(r);i<=0?this.outputs=this.outputs.filter((e=>!0!==e.change)):this.distributeChange(i,t)}calculateChange(e){let t=0;for(const e of this.inputs){if("object"!=typeof e.sourceTransaction)throw new Error("Source transactions are required for all inputs during fee computation");t+=e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0}t-=e;for(const e of this.outputs)!0!==e.change&&void 0!==e.satoshis&&(t-=e.satoshis);return t}distributeChange(e,t){let r=0;const i=this.outputs.filter((e=>e.change));if("random"===t?r=this.distributeRandomChange(e,i):"equal"===t&&(r=this.distributeEqualChange(e,i)),r<e){const t=this.outputs[this.outputs.length-1];void 0!==t.satoshis?t.satoshis+=e-r:t.satoshis=e-r}}distributeRandomChange(e,t){let r=0,i=e;const n=Array(t.length).fill(1);i-=t.length,r+=t.length;for(let e=0;e<t.length-1;e++){const t=this.benfordNumber(0,i);n[e]=n[e]+t,r+=t,i-=t}for(const e of this.outputs)!0===e.change&&(e.satoshis=n.shift());return r}distributeEqualChange(e,t){let r=0;const i=Math.floor(e/t.length);for(const e of t)r+=i,e.satoshis=i;return r}benfordNumber(e,t){const r=Math.floor(9*Math.random())+1;return Math.floor(e+(t-e)*Math.log10(1+1/r)/Math.log10(10))}getFee(){let e=0;for(const t of this.inputs){if("object"!=typeof t.sourceTransaction)throw new Error("Source transactions or sourceSatoshis are required for all inputs to calculate fee");e+=t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0}let t=0;for(const e of this.outputs)t+=e.satoshis??0;return e-t}async sign(){this.cachedHash=void 0;for(const e of this.outputs)if(void 0===e.satoshis)throw!0===e.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 e=await Promise.all(this.inputs.map((async(e,t)=>"object"==typeof this.inputs[t].unlockingScriptTemplate?await(this.inputs[t]?.unlockingScriptTemplate?.sign(this,t)):await Promise.resolve(void 0))));for(let t=0,r=this.inputs.length;t<r;t++)"object"==typeof this.inputs[t].unlockingScriptTemplate&&(this.inputs[t].unlockingScript=e[t])}async broadcast(e=Xt()){return await e.broadcast(this)}toBinary(){const e=new Ue;e.writeUInt32LE(this.version),e.writeVarIntNum(this.inputs.length);for(const t of this.inputs){if(void 0===t.sourceTXID){if(null==t.sourceTransaction)throw new Error("sourceTransaction is undefined");e.write(t.sourceTransaction.hash())}else e.writeReverse(Oe(t.sourceTXID,"hex"));if(e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw new Error("unlockingScript is undefined");const r=t.unlockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r),e.writeUInt32LE(t.sequence??0)}e.writeVarIntNum(this.outputs.length);for(const t of this.outputs){e.writeUInt64LE(t.satoshis??0);const r=t.lockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r)}return e.writeUInt32LE(this.lockTime),e.toArray()}toEF(){const e=new Ue;e.writeUInt32LE(this.version),e.write([0,0,0,0,0,239]),e.writeVarIntNum(this.inputs.length);for(const t of this.inputs){if(void 0===t.sourceTransaction)throw new Error("All inputs must have source transactions when serializing to EF format");if(void 0===t.sourceTXID?e.write(t.sourceTransaction.hash()):e.write(Oe(t.sourceTXID,"hex").reverse()),e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw new Error("unlockingScript is undefined");const r=t.unlockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r),e.writeUInt32LE(t.sequence??0),e.writeUInt64LE(t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0);const i=t.sourceTransaction.outputs[t.sourceOutputIndex].lockingScript.toBinary();e.writeVarIntNum(i.length),e.write(i)}e.writeVarIntNum(this.outputs.length);for(const t of this.outputs){e.writeUInt64LE(t.satoshis??0);const r=t.lockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r)}return e.writeUInt32LE(this.lockTime),e.toArray()}toHexEF(){return Ne(this.toEF())}toHex(){return Ne(this.toBinary())}toHexBEEF(){return Ne(this.toBEEF())}toHexAtomicBEEF(){return Ne(this.toAtomicBEEF())}hash(e){let t;return null!=this.cachedHash?t=this.cachedHash:(t=Ie(this.toBinary()),this.cachedHash=t),"hex"===e?Ne(t):t}id(e){const t=[...this.hash()];return t.reverse(),"hex"===e?Ne(t):t}async verify(e=Yt(),t,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"===e){null!=a&&i.add(a);continue}if(await s.merklePath.verify(a,e)){i.add(a);continue}}if(void 0!==t){if(void 0===s)throw new Error("Transaction is undefined");const e=sr.fromEF(s.toEF());if(delete e.outputs[0].satoshis,e.outputs[0].change=!0,await e.fee(t),s.getFee()<e.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 e=0;e<s.inputs.length;e++){const t=s.inputs[e];if("object"!=typeof t.sourceTransaction)throw new Error(`Verification failed because the input at index ${e} of transaction ${a} is missing an associated source transaction. This source transaction is required for transaction verification because there is no merkle proof for the transaction spending a UTXO it contains.`);if("object"!=typeof t.unlockingScript)throw new Error(`Verification failed because the input at index ${e} of transaction ${a} is missing an associated unlocking script. This script is required for transaction verification because there is no merkle proof for the transaction spending the UTXO.`);const c=t.sourceTransaction.outputs[t.sourceOutputIndex];o+=c.satoshis??0;const d=t.sourceTransaction.id("hex");i.has(d)||n.push(t.sourceTransaction);const u=s.inputs.filter(((t,r)=>r!==e));if(void 0===t.sourceTXID&&(t.sourceTXID=d),!new Dt({sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,lockingScript:c.lockingScript,sourceSatoshis:c.satoshis??0,transactionVersion:s.version,otherInputs:u,unlockingScript:t.unlockingScript,inputSequence:t.sequence??0,inputIndex:e,outputs:s.outputs,lockTime:s.lockTime,memoryLimit:r}).validate())return!1}let c=0;for(const e of s.outputs){if("number"!=typeof e.satoshis)throw new Error("Every output must have a defined amount during transaction verification.");c+=e.satoshis}if(c>o)return!1;i.add(a)}return!0}toBEEF(e){const t=new Ue;t.writeUInt32LE(er);const r=[],i=[],n=t=>{const s={tx:t},a="object"==typeof t.merklePath;if(a){let e=!1;for(let i=0;i<r.length;i++){if(r[i]===t.merklePath){s.pathIndex=i,e=!0;break}if(null!==t.merklePath&&void 0!==t.merklePath&&r[i].blockHeight===t.merklePath.blockHeight&&r[i].computeRoot()===t.merklePath.computeRoot()){r[i].combine(t.merklePath),s.pathIndex=i,e=!0;break}}e||(s.pathIndex=r.length,null!==t.merklePath&&void 0!==t.merklePath&&r.push(t.merklePath))}if(i.some((e=>e.tx.id("hex")===t.id("hex")))||i.unshift(s),!a)for(let r=0;r<t.inputs.length;r++){const i=t.inputs[r];if("object"==typeof i.sourceTransaction)n(i.sourceTransaction);else if(!1===e)throw new Error("A required source transaction is missing!")}};n(this),t.writeVarIntNum(r.length);for(const e of r)t.write(e.toBinary());t.writeVarIntNum(i.length);for(const e of i)t.write(e.tx.toBinary()),"number"==typeof e.pathIndex?(t.writeUInt8(1),t.writeVarIntNum(e.pathIndex)):t.writeUInt8(0);return t.toArray()}toAtomicBEEF(e){const t=new Ue;t.writeUInt32LE(16843009),t.write(this.hash());const r=this.toBEEF(e);return t.write(r),t.toArray()}}function ar(e){return"success"===e.status}function or(e){return"error"===e.status}const cr=class extends nr{knownTo={};constructor(e){if(super(),null!=e)for(const t of e)this.addParty(t)}isParty(e){return Object.keys(this.knownTo).includes(e)}addParty(e){if(this.isParty(e))throw new Error(`Party ${e} already exists.`);this.knownTo[e]={}}getKnownTxidsForParty(e){const t=this.knownTo[e];if(void 0===t)throw new Error(`Party ${e} is unknown.`);return Object.keys(t)}getTrimmedBeefForParty(e){const t=this.getKnownTxidsForParty(e),r=this.clone();return r.trimKnownTxids(t),r}addKnownTxidsForParty(e,t){this.isParty(e)||this.addParty(e);const r=this.knownTo[e];for(const e of t)r[e]=!0,this.mergeTxidOnly(e)}mergeBeefFromParty(e,t){const r=Array.isArray(t)?nr.fromBinary(t):t,i=r.getValidTxids();this.mergeBeef(r),this.addKnownTxidsForParty(e,i)}};class dr{network;URL;httpClient;constructor(e="main",t=zt()){this.network=e,this.URL=`https://api.whatsonchain.com/v1/bsv/${e}/tx/raw`,this.httpClient=t}async broadcast(e){const t={method:"POST",headers:{"Content-Type":"application/json",Accept:"text/plain"},data:{txhex:e.toHex()}};try{const e=await this.httpClient.request(this.URL,t);return e.ok?{status:"success",txid:e.data,message:"broadcast successful"}:{status:"error",code:e.status.toString()??"ERR_UNKNOWN",description:e.data??"Unknown error"}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class ur{https;constructor(e){this.https=e}async request(e,t){return await new Promise(((r,i)=>{const n=this.https.request(e,t,(e=>{let t="";e.on("data",(e=>{t+=e})),e.on("end",(()=>{const i=e.statusCode>=200&&e.statusCode<=299,n=e.headers["content-type"],s=""!==t&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(t):t;r({status:e.statusCode,statusText:e.statusMessage,ok:i,data:s})}))}));n.on("error",(e=>{i(e)})),null!==t.data&&void 0!==t.data&&n.write(Buffer.from(t.data)),n.end()}))}}class hr{fetch;constructor(e){this.fetch=e}async request(e,t){const r={method:t.method,headers:t.headers,body:t.data},i=await this.fetch(e,r),n=await i.text();return{ok:i.ok,status:i.status,statusText:i.statusText,data:n}}}function lr(){const e={async request(...e){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 e;try{const e=require("https");return new ur(e)}catch(t){return e}}class fr{URL;httpClient;constructor(e,t=lr()){this.URL=e,this.httpClient=t}async broadcast(e){const t=e.toEF(),r={method:"POST",headers:{"Content-Type":"application/octet-stream"},data:new Blob([new Uint8Array(t)])};try{const t=await this.httpClient.request(this.URL,r);return t.ok?{status:"success",txid:e.id("hex"),message:"broadcast successful"}:{status:"error",code:t.status.toString()??"ERR_UNKNOWN",description:t.data??"Unknown error"}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}const pr="42423301",br=(e,t,r)=>{const i="object"!=typeof r;if(i){const e=new Me,t=new rt(1),i=e.g.mul(t);r=new Ge(i.x,i.y)}const n=Ze(32),s=`2-message signing-${Fe(n)}`,a=t.deriveChild(r,s).sign(e).toDER(),o=t.toPublicKey().encode(!0);return[...Oe(pr,"hex"),...o,...i?[0]:r.encode(!0),...n,...a]},wr=(e,t,r)=>{const i=new Le(t),n=Ne(i.read(4));if(n!==pr)throw new Error(`Message version mismatch: Expected ${pr}, received ${n}`);const s=Ge.fromString(Ne(i.read(33))),[a]=i.read(1);if(0===a)r=new rt(1);else{const e=i.read(32),t=Ne([a,...e]);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: ${t}`);const n=r.toPublicKey().encode(!0,"hex");if(t!==n)throw new Error(`The recipient public key is ${n} but the signature requres the recipient to have public key ${t}`)}const o=Fe(i.read(32)),c=Ne(i.read(i.bin.length-i.pos)),d=$e.fromDER(c,"hex"),u=`2-message signing-${o}`;return s.deriveChild(r,u).verify(e,d)},gr="42421033",mr=(e,t,r)=>{const i=Ze(32),n=`2-message encryption-${Fe(i)}`,s=t.deriveChild(r,n),a=r.deriveChild(t,n),o=s.deriveSharedSecret(a),c=new St(o.encode(!0).slice(1)).encrypt(e),d=t.toPublicKey().encode(!0);return[...Oe(gr,"hex"),...d,...r.encode(!0),...i,...c]},yr=(e,t)=>{const r=new Le(e),i=Ne(r.read(4));if(i!==gr)throw new Error(`Message version mismatch: Expected ${gr}, received ${i}`);const n=Ge.fromString(Ne(r.read(33))),s=Ne(r.read(33)),a=t.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=Fe(r.read(32)),c=r.read(r.bin.length-r.pos),d=`2-message encryption-${o}`,u=n.deriveChild(t,d),h=t.deriveChild(n,d),l=u.deriveSharedSecret(h);return new St(l.encode(!0).slice(1)).decrypt(c)},Ir=e=>{const t=new Ue;t.writeVarIntNum(24),t.write(Oe("Bitcoin Signed Message:\n","utf8")),t.writeVarIntNum(e.length),t.write(e);const r=t.toArray();return Ie(r)},vr=(e,t,r="base64")=>{const i=Ir(e),n=je(new d(i),t,!0);if("raw"===r)return n;const s=new d(i),a=n.CalculateRecoveryFactor(t.toPublicKey(),s);return n.toCompact(a,!0,"base64")},kr=(e,t,r)=>{const i=Ir(e);return Xe(new d(i),t,r)};class Sr{versionBytesNum;depth;parentFingerPrint;childIndex;chainCode;privKey;pubKey;constants={pubKey:76067358,privKey:76066276};constructor(e,t,r,i,n,s,a){this.versionBytesNum=e,this.depth=t,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=Ze(32),this.privKey=rt.fromRandom(),this.pubKey=this.privKey.toPublicKey(),this}static fromRandom(){return(new this).fromRandom()}static fromString(e){return(new this).fromString(e)}fromString(e){const t=Be(e);return this.fromBinary([...t.prefix,...t.data])}static fromSeed(e){return(new this).fromSeed(e)}fromSeed(e){if(e.length<16)throw new Error("Need more than 128 bits of entropy");if(e.length>64)throw new Error("More than 512 bits of entropy is nonstandard");const t=Se(Oe("Bitcoin seed","utf8"),e);return this.depth=0,this.parentFingerPrint=[0,0,0,0],this.childIndex=0,this.chainCode=t.slice(32,64),this.versionBytesNum=this.constants.privKey,this.privKey=new rt(t.slice(0,32)),this.pubKey=this.privKey.toPublicKey(),this}static fromBinary(e){return(new this).fromBinary(e)}fromBinary(e){if(78!==e.length)throw new Error("incorrect bip32 data length");const t=new Le(e);this.versionBytesNum=t.readUInt32BE(),this.depth=t.readUInt8(),this.parentFingerPrint=t.read(4),this.childIndex=t.readUInt32BE(),this.chainCode=t.read(32);const r=t.read(33),i=this.versionBytesNum===this.constants.privKey,n=this.versionBytesNum===this.constants.pubKey;if(i&&0===r[0])this.privKey=new rt(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=Ge.fromString(Ne(r))}return this}toString(){const e=this.toBinary();return De(e,[])}derive(e){if("m"===e)return this;const t=e.split("/");let r=this;for(const[e,i]of t.entries()){if(0===e){if("m"!==i)throw new Error("invalid path");continue}if(parseInt(i.replace("'",""),10).toString()!==i.replace("'",""))throw new Error("invalid path");const t=i.length>1&&"'"===i[i.length-1];let n=2147483647&parseInt(t?i.slice(0,i.length-1):i,10);t&&(n+=2147483648),r=r.deriveChild(n)}return r}deriveChild(e){if("number"!=typeof e)throw new Error("i must be a number");const t=[];t.push(e>>24&255),t.push(e>>16&255),t.push(e>>8&255),t.push(255&e);const r=[...t],i=!!(2147483648&e),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 e=null;e=i?[0,...this.privKey.toArray("be",32),...r]:[...this.pubKey.encode(!0),...r];const t=Se(this.chainCode,e),n=new d(t.slice(0,32)),a=t.slice(32,64),o=n.add(this.privKey).mod((new Me).n);s=new Sr,s.chainCode=a,s.privKey=new rt(o.toArray()),s.pubKey=s.privKey.toPublicKey()}else{const e=[...this.pubKey.encode(!0),...r],t=Se(this.chainCode,e),i=new d(t.slice(0,32)),n=t.slice(32,64),a=(new Me).g.mul(i),o=this.pubKey,c=a.add(o),u=new Ge(c.x,c.y);s=new Sr,s.chainCode=n,s.pubKey=u}s.childIndex=e;const a=ve(this.pubKey.encode(!0));return s.parentFingerPrint=a.slice(0,4),s.versionBytesNum=this.versionBytesNum,s.depth=this.depth+1,s}toPublic(){const e=new Sr(this.versionBytesNum,this.depth,this.parentFingerPrint,this.childIndex,this.chainCode,this.privKey,this.pubKey);return e.versionBytesNum=this.constants.pubKey,e.privKey=void 0,e}toBinary(){const e=this.versionBytesNum===this.constants.privKey,t=this.versionBytesNum===this.constants.pubKey;if(e)return(new Ue).writeUInt32BE(this.versionBytesNum).writeUInt8(this.depth).write(this.parentFingerPrint).writeUInt32BE(this.childIndex).write(this.chainCode).writeUInt8(0).write(this.privKey.toArray("be",32)).toArray();if(t)return(new Ue).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 Er={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(e,t,r=Er){this.mnemonic=e??"",this.seed=t??[],this.Wordlist=r}toBinary(){const e=new Ue;if(""!==this.mnemonic){const t=Oe(this.mnemonic,"utf8");e.writeVarIntNum(t.length),e.write(t)}else e.writeVarIntNum(0);return this.seed.length>0?(e.writeVarIntNum(this.seed.length),e.write(this.seed)):e.writeVarIntNum(0),e.toArray()}fromBinary(e){const t=new Le(e),r=t.readVarIntNum();r>0&&(this.mnemonic=Te(t.read(r),"utf8"));const i=t.readVarIntNum();return i>0&&(this.seed=t.read(i)),this}fromRandom(e){if((null==e||isNaN(e)||0===e)&&(e=128),e%32!=0)throw new Error("bits must be multiple of 32");if(e<128)throw new Error("bits must be at least 128");const t=Ze(e/8);return this.entropy2Mnemonic(t),this.mnemonic2Seed(),this}static fromRandom(e){return(new this).fromRandom(e)}fromEntropy(e){return this.entropy2Mnemonic(e),this}static fromEntropy(e){return(new this).fromEntropy(e)}fromString(e){return this.mnemonic=e,this}static fromString(e){return(new this).fromString(e)}toString(){return this.mnemonic}toSeed(e){return this.mnemonic2Seed(e),this.seed}entropy2Mnemonic(e){if(e.length<16)throw new Error("Entropy is less than 128 bits. It must be 128 bits or more.");const t=me(e);let r="";const i=8*e.length;for(let t=0;t<e.length;t++)r+=("00000000"+e[t].toString(2)).slice(-8);let n=t[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 e=0;e<r.length/11;e++){""!==s&&(s+=this.Wordlist.space);const t=parseInt(r.slice(11*e,11*(e+1)),2);s+=this.Wordlist.value[t]}return this.mnemonic=s,this}check(){const e=this.mnemonic.split(this.Wordlist.space);let t="";for(let r=0;r<e.length;r++){const i=this.Wordlist.value.indexOf(e[r]);if(i<0)return!1;t+=("00000000000"+i.toString(2)).slice(-11)}if(t.length%11!=0)throw new Error("internal error - entropy not an even multiple of 11 bits - "+t.length.toString());const r=t.length/33,i=t.slice(-r),n=t.slice(0,t.length-r),s=[];for(let e=0;e<n.length/8;e++)s.push(parseInt(t.slice(8*e,8*(e+1)),2));let a=me(s.slice(0,n.length/8))[0].toString(2);return a=("00000000"+a).slice(-8).slice(0,r),a===i}mnemonic2Seed(e=""){let t=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 e)throw new Error("passphrase must be a string or undefined");t=t.normalize("NFKD"),e=e.normalize("NFKD");const r=Oe(t,"utf8"),i=[...Oe("mnemonic","utf8"),...Oe(e,"utf8")];return this.seed=Ee(r,i,2048,64,"sha512"),this}isValid(e=""){let t;try{this.mnemonic2Seed(e),t=!0}catch{t=!1}return t}static isValid(e,t=""){return new Pr(e).isValid(t)}}function Nr(e){let t,r,i;0===this._tables[0][0][0]&&this._precompute();const n=this._tables[0][4],s=this._tables[1],a=e.length;let o,c=1;if(4!==a&&6!==a&&8!==a)throw new Error("invalid aes key size");for(this._key=[r=e.slice(0),i=[]],o=a;o<4*a+28;o++)t=r[o-1],(o%a==0||8===a&&o%a==4)&&(t=n[t>>>24]<<24^n[t>>16&255]<<16^n[t>>8&255]<<8^n[255&t],o%a==0&&(t=t<<8^t>>>24^c<<24,c=c<<1^283*(c>>7))),r[o]=r[o-a]^t;for(let e=0;o>0;e++,o--)t=r[3&e?o:o-4],i[e]=o<=4||e<4?t:s[0][n[t>>>24]]^s[1][n[t>>16&255]]^s[2][n[t>>8&255]]^s[3][n[255&t]]}Nr.prototype={encrypt:function(e){return this._crypt(e,0)},decrypt:function(e){return this._crypt(e,1)},_tables:[[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)]],_precompute:function(){const e=this._tables[0],t=this._tables[1],r=e[4],i=t[4];let n,s,a;const o=new Uint8Array(256),c=new Uint8Array(256);let d,u,h,l,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!==d?d:1,a=0!==c[a]?c[a]:1)for(l=a^a<<1^a<<2^a<<3^a<<4,l=l>>8^255&l^99,r[s]=l,i[l]=s,h=o[u=o[d=o[s]]],p=16843009*h^65537*u^257*d^16843008*s,f=257*o[l]^16843008*l,n=0;n<4;n++)e[n][s]=f=f<<24^f>>>8,t[n][l]=p=p<<24^p>>>8},_crypt:function(e,t){if(4!==e.length)throw new Error("invalid aes block size");const r=this._key[t];let i,n,s,a=e[0]^r[0],o=e[1===t?3:1]^r[1],c=e[2]^r[2],d=e[1===t?1:3]^r[3];const u=r.length/4-2;let h,l=4;const f=new Uint32Array(4),p=this._tables[t],b=p[0],w=p[1],g=p[2],m=p[3],y=p[4];for(h=0;h<u;h++)i=b[a>>>24]^w[o>>16&255]^g[c>>8&255]^m[255&d]^r[l],n=b[o>>>24]^w[c>>16&255]^g[d>>8&255]^m[255&a]^r[l+1],s=b[c>>>24]^w[d>>16&255]^g[a>>8&255]^m[255&o]^r[l+2],d=b[d>>>24]^w[a>>16&255]^g[o>>8&255]^m[255&c]^r[l+3],l+=4,a=i,o=n,c=s;for(h=0;h<4;h++)f[1===t?3&-h:h]=y[a>>>24]<<24^y[o>>16&255]<<16^y[c>>8&255]<<8^y[255&d]^r[l++],i=a,a=o,o=c,c=d,d=i;return f}};class Or{static encrypt(e,t){const r=Or.buf2Words(t),i=Or.buf2Words(e),n=new Nr(r).encrypt(i);return Or.words2Buf(n)}static decrypt(e,t){const r=Or.buf2Words(e),i=new Nr(Or.buf2Words(t)).decrypt(r);return Or.words2Buf(i)}static buf2Words(e){if(e.length%4!=0)throw new Error("buf length must be a multiple of 4");const t=[];for(let r=0;r<e.length/4;r++){const i=16777216*e[4*r]+(e[4*r+1]<<16|e[4*r+2]<<8|e[4*r+3]);t.push(i)}return t}static words2Buf(e){const t=new Array(4*e.length);for(let r=0;r<e.length;r++){const i=e[r];t[4*r]=i>>>24&255,t[4*r+1]=i>>>16&255,t[4*r+2]=i>>>8&255,t[4*r+3]=255&i}return t}}class _r{static buf2BlocksBuf(e,t){const r=t/8,i=[];for(let n=0;n<=e.length/r;n++){let s=e.slice(n*r,n*r+r);s.length<t&&(s=_r.pkcs7Pad(s,t)),i.push(s)}return i}static blockBufs2Buf(e){let t=e[e.length-1];return t=_r.pkcs7Unpad(t),e[e.length-1]=t,e.flat()}static encrypt(e,t,r,i){const n=8*t.length,s=_r.buf2BlocksBuf(e,n);return _r.encryptBlocks(s,t,r,i).flat()}static decrypt(e,t,r,i){const n=t.length,s=[];for(let t=0;t<e.length/n;t++)s.push(e.slice(t*n,t*n+n));const a=_r.decryptBlocks(s,t,r,i);return _r.blockBufs2Buf(a)}static encryptBlock(e,t,r,i){const n=_r.xorBufs(e,t);return r.encrypt(n,i)}static decryptBlock(e,t,r,i){const n=r.decrypt(e,i);return _r.xorBufs(n,t)}static encryptBlocks(e,t,r,i){const n=[];for(let s=0;s<e.length;s++){const a=e[s],o=_r.encryptBlock(a,t,r,i);n.push(o),t=o}return n}static decryptBlocks(e,t,r,i){const n=[];for(let s=0;s<e.length;s++){const a=e[s],o=_r.decryptBlock(a,t,r,i);n.push(o),t=a}return n}static pkcs7Pad(e,t){const r=t/8-e.length,i=new Array(r);return i.fill(r),[...e,...i]}static pkcs7Unpad(e){const t=e[e.length-1],r=e.slice(e.length-t,e.length),i=new Array(t);if(i.fill(t),Ne(r)!==Ne(i))throw new Error("invalid padding");return e.slice(0,e.length-t)}static xorBufs(e,t){if(e.length!==t.length)throw new Error("bufs must have the same length");const r=new Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}}class xr{static encrypt(e,t,r,i=!0){r=r??Ze(16);const n=_r.encrypt(e,r,Or,t);return i?[...r,...n]:[...n]}static decrypt(e,t,r){if(null==r){r=e.slice(0,16);const i=e.slice(16);return _r.decrypt(i,r,Or,t)}{const i=e;return _r.decrypt(i,r,Or,t)}}}class Ar{static ivkEkM(e,t){const r=e,i=t.mul(r),n=new Ge(i.x,i.y).encode(!0),s=ye(n);return{iv:s.slice(0,16),kE:s.slice(16,32),kM:s.slice(32,64)}}static electrumEncrypt(e,t,r,i=!1){let n=null;null==r&&(r=rt.fromRandom()),i||(n=r.toPublicKey().encode(!0));const{iv:s,kE:a,kM:o}=Ar.ivkEkM(r,t),c=xr.encrypt(e,a,s,!1),d=Oe("BIE1","utf8");let u;u=null!=n&&n.length>0?[...d,...n,...c]:[...d,...c];const h=ke(o,u);return[...u,...h]}static electrumDecrypt(e,t,r){const i=e.slice(0,4);if("BIE1"!==Te(i,"utf8"))throw new Error("Invalid Magic");let n=4,s=null;if(e.length-n-32>=33){const t=e[n];2===t||3===t?(s=e.slice(n,n+33),n+=33):4===t&&(s=e.slice(n,n+65),n+=65)}if(null!==s)null==r&&(r=Ge.fromString(Ne(s)));else if(null==r)throw new Error("Sender public key is required");const{iv:a,kE:o,kM:c}=Ar.ivkEkM(t,r),d=e.slice(n,e.length-32),u=e.slice(e.length-32,e.length),h=ke(c,e.slice(0,e.length-32));if(Ne(u)!==Ne(h))throw new Error("Invalid checksum");return xr.decrypt(d,o,a)}static bitcoreEncrypt(e,t,r,i){null==r&&(r=rt.fromRandom()),null==i&&(i=Ze(16));const n=r,s=r.toPublicKey().encode(!0),a=t.mul(n).getX().toArray("be",32),o=ye(a),c=o.slice(0,32),d=o.slice(32,64),u=xr.encrypt(e,c,i),h=ke(d,[...u]);return[...s,...u,...h]}static bitcoreDecrypt(e,t){const r=t,i=Ge.fromString(Ne(e.slice(0,33))).mul(r);if(i.eq(new He(0,0)))throw new Error("P equals 0");const n=i.getX().toArray("be",32),s=ye(n),a=s.slice(0,32),o=s.slice(32,64),c=e.slice(33,e.length-32),d=e.slice(e.length-32,e.length),u=ke(o,c);if(Ne(d)!==Ne(u))throw new Error("Invalid checksum");return[...xr.decrypt(c,a)]}}function Tr(e,t){const r=new sr(0,[],[],0);return r.outputs=Array(e.vout+1).fill(null),r.outputs[e.vout]={satoshis:e.satoshis,lockingScript:xt.fromHex(e.script)},{sourceTransaction:r,sourceTXID:e.txid,sourceOutputIndex:e.vout,unlockingScriptTemplate:t,sequence:4294967295}}class Fr{static generate(e,t){const r=this.withDefaultOptions(t);return Rr(e,this.getCounter(r.timestamp,r.period),r)}static validate(e,t,r){const i=this.withDefaultValidateOptions(r);if((t=t.trim()).length!==i.digits)return!1;const n=this.getCounter(i.timestamp,i.period),s=[n];for(let e=1;e<=i.skew;e++)s.push(n+e),s.push(n-e);for(const r of s)if(t===Rr(e,r,i))return!0;return!1}static getCounter(e,t){const r=Math.floor(e/1e3);return Math.floor(r/t)}static withDefaultOptions(e){return{digits:2,algorithm:"SHA-1",period:30,timestamp:Date.now(),...e}}static withDefaultValidateOptions(e){return{skew:1,...this.withDefaultOptions(e)}}}function Rr(e,t,r){const i=function(e,t,r){switch(r){case"SHA-1":return new pe(e).update(t);case"SHA-256":return new fe(e).update(t);case"SHA-512":return new be(e).update(t);default:throw new Error("unsupported HMAC algorithm")}}(e,new d(t).toArray("be",8),r.algorithm),n=i.digest(),s=15&n[n.length-1],a=n.slice(s,s+4);return(2147483647&new d(a).toNumber()).toString().slice(-r.digits)}var Cr;!function(e){e[e.Silent=0]="Silent",e[e.App=1]="App",e[e.Counterparty=2]="Counterparty"}(Cr||(Cr={}));class Vr{rootKey;identityKey;constructor(e){this.rootKey="anyone"===e?new rt(1):e,this.identityKey=this.rootKey.toPublicKey().toString()}derivePublicKey(e,t,r,i=!1){return r=this.normalizeCounterparty(r),i?this.rootKey.deriveChild(r,this.computeInvoiceNumber(e,t)).toPublicKey():r.deriveChild(this.rootKey,this.computeInvoiceNumber(e,t))}derivePrivateKey(e,t,r){return r=this.normalizeCounterparty(r),this.rootKey.deriveChild(r,this.computeInvoiceNumber(e,t))}deriveSymmetricKey(e,t,r){"anyone"===r&&(r=new rt(1).toPublicKey()),r=this.normalizeCounterparty(r);const i=this.derivePublicKey(e,t,r),n=this.derivePrivateKey(e,t,r);return new St(n.deriveSharedSecret(i)?.x?.toArray()??[])}revealCounterpartySecret(e){if("self"===e)throw new Error("Counterparty secrets cannot be revealed for counterparty=self.");e=this.normalizeCounterparty(e);const t=this.rootKey.toPublicKey();if(this.rootKey.deriveChild(t,"test").toHex()===this.rootKey.deriveChild(e,"test").toHex())throw new Error("Counterparty secrets cannot be revealed for counterparty=self.");return this.rootKey.deriveSharedSecret(e).encode(!0)}revealSpecificSecret(e,t,r){e=this.normalizeCounterparty(e);const i=this.rootKey.deriveSharedSecret(e),n=Oe(this.computeInvoiceNumber(t,r),"utf8");return ke(i.encode(!0),n)}normalizeCounterparty(e){if(null==e)throw new Error("counterparty must be self, anyone or a public key!");return"self"===e?this.rootKey.toPublicKey():"anyone"===e?new rt(1).toPublicKey():"string"==typeof e?Ge.fromString(e):e}computeInvoiceNumber(e,t){const r=e[0];if(!Number.isInteger(r)||r<0||r>2)throw new Error("Protocol security level must be 0, 1, or 2");const i=e[1].toLowerCase().trim();if(t.length>800)throw new Error("Key IDs must be 800 characters or less");if(t.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}-${t}`}}class Dr{keyDeriver;cache;maxCacheSize;constructor(e,t){this.keyDeriver=new Vr(e),this.cache=new Map;const r=t?.maxCacheSize;this.maxCacheSize=null!=r&&!isNaN(r)&&r>0?r:1e3}derivePublicKey(e,t,r,i=!1){const n=this.generateCacheKey("derivePublicKey",e,t,r,i);if(this.cache.has(n)){const e=this.cacheGet(n);if(void 0===e)throw new Error("Cached value is undefined");return e}{const s=this.keyDeriver.derivePublicKey(e,t,r,i);return this.cacheSet(n,s),s}}derivePrivateKey(e,t,r){const i=this.generateCacheKey("derivePrivateKey",e,t,r);if(this.cache.has(i)){const e=this.cacheGet(i);if(void 0===e)throw new Error("Cached value is undefined");return e}{const n=this.keyDeriver.derivePrivateKey(e,t,r);return this.cacheSet(i,n),n}}deriveSymmetricKey(e,t,r){const i=this.generateCacheKey("deriveSymmetricKey",e,t,r);if(this.cache.has(i)){const e=this.cacheGet(i);if(void 0===e)throw new Error("Cached value is undefined");return e}{const n=this.keyDeriver.deriveSymmetricKey(e,t,r);return this.cacheSet(i,n),n}}revealCounterpartySecret(e){const t=this.generateCacheKey("revealCounterpartySecret",e);if(this.cache.has(t)){const e=this.cacheGet(t);if(void 0===e)throw new Error("Cached value is undefined");return e}{const r=this.keyDeriver.revealCounterpartySecret(e);return this.cacheSet(t,r),r}}revealSpecificSecret(e,t,r){const i=this.generateCacheKey("revealSpecificSecret",e,t,r);if(this.cache.has(i)){const e=this.cacheGet(i);if(void 0===e)throw new Error("Cached value is undefined");return e}{const n=this.keyDeriver.revealSpecificSecret(e,t,r);return this.cacheSet(i,n),n}}generateCacheKey(e,...t){return`${e}|${t.map((e=>this.serializeArgument(e))).join("|")}`}serializeArgument(e){return e instanceof Ge||e instanceof rt?e.toString():Array.isArray(e)?e.map((e=>this.serializeArgument(e))).join(","):"object"==typeof e&&null!==e?JSON.stringify(e):String(e)}cacheGet(e){const t=this.cache.get(e);return this.cache.delete(e),void 0!==t&&this.cache.set(e,t),t}cacheSet(e,t){if(this.cache.size>=this.maxCacheSize){const e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(e,t)}}const Br=class{keyDeriver;constructor(e){"string"!=typeof e.identityKey&&(e=new Vr(e)),this.keyDeriver=e}async getPublicKey(e){if(e.identityKey){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==e.protocolID||null==e.keyID||""===e.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(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf).toString()}}async revealCounterpartyKeyLinkage(e){const{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const r=this.keyDeriver.revealCounterpartySecret(e.counterparty),i=(new Pt).generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),Ge.fromString(e.counterparty),He.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:e.verifier}),{ciphertext:o}=await this.encrypt({plaintext:n,protocolID:[2,"counterparty linkage revelation"],keyID:s,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,revelationTime:s,encryptedLinkage:a,encryptedLinkageProof:o}}async revealSpecificKeyLinkage(e){const{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const r=this.keyDeriver.revealSpecificSecret(e.counterparty,e.protocolID,e.keyID),{ciphertext:i}=await this.encrypt({plaintext:r,protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier}),{ciphertext:n}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,protocolID:e.protocolID,keyID:e.keyID,encryptedLinkage:i,encryptedLinkageProof:n,proofType:0}}async encrypt(e){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{ciphertext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").encrypt(e.plaintext)}}async decrypt(e){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{plaintext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").decrypt(e.ciphertext)}}async createHmac(e){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const t=this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self");return{hmac:ke(t.toArray(),e.data)}}async verifyHmac(e){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const t=this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self"),r=ke(t.toArray(),e.data).toString()===e.hmac.toString();if(!r){const e=new Error("HMAC is not valid");throw e.code="ERR_INVALID_HMAC",e}return{valid:r}}async createSignature(e){if(null==e.hashToDirectlySign&&null==e.data)throw new Error("args.data or args.hashToDirectlySign must be valid");const t=e.hashToDirectlySign??me(e.data??[]),r=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePrivateKey(e.protocolID,e.keyID,e.counterparty??"anyone");return{signature:je(new d(t),r,!0).toDER()}}async verifySignature(e){if(null==e.hashToDirectlyVerify&&null==e.data)throw new Error("args.data or args.hashToDirectlyVerify must be valid");const t=e.hashToDirectlyVerify??me(e.data??[]),r=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf),i=Xe(new d(t),$e.fromDER(e.signature),r);if(!i){const e=new Error("Signature is not valid");throw e.code="ERR_INVALID_SIGNATURE",e}return{valid:i}}};class Ur{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(e,t){return await this.CWI.createAction(e,t)}async signAction(e,t){return await this.CWI.signAction(e,t)}async abortAction(e,t){return await this.CWI.abortAction(e,t)}async listActions(e,t){return await this.CWI.listActions(e,t)}async internalizeAction(e,t){return await this.CWI.internalizeAction(e,t)}async listOutputs(e,t){return await this.CWI.listOutputs(e,t)}async relinquishOutput(e,t){return await this.CWI.relinquishOutput(e,t)}async getPublicKey(e,t){return await this.CWI.getPublicKey(e,t)}async revealCounterpartyKeyLinkage(e,t){return await this.CWI.revealCounterpartyKeyLinkage(e,t)}async revealSpecificKeyLinkage(e,t){return await this.CWI.revealSpecificKeyLinkage(e,t)}async encrypt(e,t){return await this.CWI.encrypt(e,t)}async decrypt(e,t){return await this.CWI.decrypt(e,t)}async createHmac(e,t){return await this.CWI.createHmac(e,t)}async verifyHmac(e,t){return await this.CWI.verifyHmac(e,t)}async createSignature(e,t){return await this.CWI.createSignature(e,t)}async verifySignature(e,t){return await this.CWI.verifySignature(e,t)}async acquireCertificate(e,t){return await this.CWI.acquireCertificate(e,t)}async listCertificates(e,t){return await this.CWI.listCertificates(e,t)}async proveCertificate(e,t){return await this.CWI.proveCertificate(e,t)}async relinquishCertificate(e,t){return await this.CWI.relinquishCertificate(e,t)}async discoverByIdentityKey(e,t){return await this.CWI.discoverByIdentityKey(e,t)}async discoverByAttributes(e,t){return await this.CWI.discoverByAttributes(e,t)}async isAuthenticated(e,t){return await this.CWI.isAuthenticated(e,t)}async waitForAuthentication(e,t){return await this.CWI.waitForAuthentication(e,t)}async getHeight(e,t){return await this.CWI.getHeight(e,t)}async getHeaderForHeight(e,t){return await this.CWI.getHeaderForHeight(e,t)}async getNetwork(e,t){return await this.CWI.getNetwork(e,t)}async getVersion(e,t){return await this.CWI.getVersion(e,t)}}class Lr extends Error{code;isError=!0;constructor(e,t=1,r){super(e),this.code=t,this.name=this.constructor.name,null!=r&&""!==r?this.stack=r:Error.captureStackTrace(this,this.constructor)}}var Kr;!function(e){e[e.unknownError=1]="unknownError",e[e.unsupportedAction=2]="unsupportedAction",e[e.invalidHmac=3]="invalidHmac",e[e.invalidSignature=4]="invalidSignature",e[e.reviewActions=5]="reviewActions"}(Kr||(Kr={}));const Hr=Lr;class qr{domain;constructor(e="*"){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=e}async invoke(e,t){return await new Promise(((r,i)=>{const n=Fe(Ze(12)),s=e=>{if("CWI"===e.data.type&&e.isTrusted&&e.data.id===n&&!0!==e.data.isInvocation)if("function"==typeof window.removeEventListener&&window.removeEventListener("message",s),"error"===e.data.status){const t=new Lr(e.data.description,e.data.code);i(t)}else r(e.data.result)};window.addEventListener("message",s),window.parent.postMessage({type:"CWI",isInvocation:!0,id:n,call:e,args:t},this.domain)}))}async createAction(e){return await this.invoke("createAction",e)}async signAction(e){return await this.invoke("signAction",e)}async abortAction(e){return await this.invoke("abortAction",e)}async listActions(e){return await this.invoke("listActions",e)}async internalizeAction(e){return await this.invoke("internalizeAction",e)}async listOutputs(e){return await this.invoke("listOutputs",e)}async relinquishOutput(e){return await this.invoke("relinquishOutput",e)}async getPublicKey(e){return await this.invoke("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.invoke("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.invoke("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.invoke("encrypt",e)}async decrypt(e){return await this.invoke("decrypt",e)}async createHmac(e){return await this.invoke("createHmac",e)}async verifyHmac(e){return await this.invoke("verifyHmac",e)}async createSignature(e){return await this.invoke("createSignature",e)}async verifySignature(e){return await this.invoke("verifySignature",e)}async acquireCertificate(e){return await this.invoke("acquireCertificate",e)}async listCertificates(e){return await this.invoke("listCertificates",e)}async proveCertificate(e){return await this.invoke("proveCertificate",e)}async relinquishCertificate(e){return await this.invoke("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.invoke("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.invoke("discoverByAttributes",e)}async isAuthenticated(e){return await this.invoke("isAuthenticated",e)}async waitForAuthentication(e){return await this.invoke("waitForAuthentication",e)}async getHeight(e){return await this.invoke("getHeight",e)}async getHeaderForHeight(e){return await this.invoke("getHeaderForHeight",e)}async getNetwork(e){return await this.invoke("getNetwork",e)}async getVersion(e){return await this.invoke("getVersion",e)}}class Mr{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(e,t,r,i,n,s,a){this.type=e,this.serialNumber=t,this.subject=r,this.certifier=i,this.revocationOutpoint=n,this.fields=s,this.signature=a}toBinary(e=!0){const t=new Ue,r=Oe(this.type,"base64");t.write(r);const i=Oe(this.serialNumber,"base64");t.write(i);const n=Oe(this.subject,"hex");t.write(n);const s=Oe(this.certifier,"hex");t.write(s);const[a,o]=this.revocationOutpoint.split("."),c=Oe(a,"hex");t.write(c),t.writeVarIntNum(Number(o));const d=Object.keys(this.fields).sort();t.writeVarIntNum(d.length);for(const e of d){const r=this.fields[e],i=Oe(e,"utf8");t.writeVarIntNum(i.length),t.write(i);const n=Oe(r,"utf8");t.writeVarIntNum(n.length),t.write(n)}if(e&&(this.signature??"").length>0){const e=Oe(this.signature,"hex");t.write(e)}return t.toArray()}static fromBinary(e){const t=new Le(e),r=Fe(t.read(32)),i=Fe(t.read(32)),n=t.read(33),s=Ne(n),a=t.read(33),o=Ne(a),c=t.read(32),d=`${Ne(c)}.${t.readVarIntNum()}`,u=t.readVarIntNum(),h={};for(let e=0;e<u;e++){const e=t.readVarIntNum(),r=t.read(e),i=Ae(r),n=t.readVarIntNum(),s=t.read(n),a=Ae(s);h[i]=a}let l;if(!t.eof()){const e=t.read();l=$e.fromDER(e).toString("hex")}return new Mr(r,i,s,o,d,h,l)}async verify(){const e=new Br("anyone"),t=this.toBinary(!1),r=this.signature??"",{valid:i}=await e.verifySignature({signature:Oe(r,"hex"),data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`,counterparty:this.certifier});return i}async sign(e){if(null!=this.signature&&this.signature.length>0)throw new Error(`Certificate has already been signed! Signature present: ${this.signature}`);this.certifier=(await e.getPublicKey({identityKey:!0})).publicKey;const t=this.toBinary(!1),{signature:r}=await e.createSignature({data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`});this.signature=Ne(r)}static getCertificateFieldEncryptionDetails(e,t){return{protocolID:[2,"certificate field encryption"],keyID:t?`${t} ${e}`:e}}}var $r;!function(e){e[e.createAction=1]="createAction",e[e.signAction=2]="signAction",e[e.abortAction=3]="abortAction",e[e.listActions=4]="listActions",e[e.internalizeAction=5]="internalizeAction",e[e.listOutputs=6]="listOutputs",e[e.relinquishOutput=7]="relinquishOutput",e[e.getPublicKey=8]="getPublicKey",e[e.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",e[e.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",e[e.encrypt=11]="encrypt",e[e.decrypt=12]="decrypt",e[e.createHmac=13]="createHmac",e[e.verifyHmac=14]="verifyHmac",e[e.createSignature=15]="createSignature",e[e.verifySignature=16]="verifySignature",e[e.acquireCertificate=17]="acquireCertificate",e[e.listCertificates=18]="listCertificates",e[e.proveCertificate=19]="proveCertificate",e[e.relinquishCertificate=20]="relinquishCertificate",e[e.discoverByIdentityKey=21]="discoverByIdentityKey",e[e.discoverByAttributes=22]="discoverByAttributes",e[e.isAuthenticated=23]="isAuthenticated",e[e.waitForAuthentication=24]="waitForAuthentication",e[e.getHeight=25]="getHeight",e[e.getHeaderForHeight=26]="getHeaderForHeight",e[e.getNetwork=27]="getNetwork",e[e.getVersion=28]="getVersion"}($r||($r={}));const zr=$r;class Wr{wire;constructor(e){this.wire=e}async transmit(e,t="",r=[]){const i=new Ue;i.writeUInt8(zr[e]);const n=Oe(t,"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 Le(a),c=o.readUInt8();if(0===c)return o.read();{const e=o.readVarIntNum(),t=o.read(e),r=Ae(t),i=o.readVarIntNum(),n=o.read(i),s=Ae(n);throw new Lr(r,c,s)}}async createAction(e,t){const r=new Ue,i=Oe(e.description,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=e.inputBEEF?(r.writeVarIntNum(e.inputBEEF.length),r.write(e.inputBEEF)):r.writeVarIntNum(-1),null!=e.inputs){r.writeVarIntNum(e.inputs.length);for(const t of e.inputs){if(r.write(this.encodeOutpoint(t.outpoint)),null!=t.unlockingScript&&""!==t.unlockingScript){const e=Oe(t.unlockingScript,"hex");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1),r.writeVarIntNum(t.unlockingScriptLength??0);const e=Oe(t.inputDescription,"utf8");r.writeVarIntNum(e.length),r.write(e),"number"==typeof t.sequenceNumber?r.writeVarIntNum(t.sequenceNumber):r.writeVarIntNum(-1)}}else r.writeVarIntNum(-1);if(null!=e.outputs){r.writeVarIntNum(e.outputs.length);for(const t of e.outputs){const e=Oe(t.lockingScript,"hex");r.writeVarIntNum(e.length),r.write(e),r.writeVarIntNum(t.satoshis);const i=Oe(t.outputDescription,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=t.basket&&""!==t.basket){const e=Oe(t.basket,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=t.customInstructions&&""!==t.customInstructions){const e=Oe(t.customInstructions,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=t.tags){r.writeVarIntNum(t.tags.length);for(const e of t.tags){const t=Oe(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}}else r.writeVarIntNum(-1)}}else r.writeVarIntNum(-1);if("number"==typeof e.lockTime?r.writeVarIntNum(e.lockTime):r.writeVarIntNum(-1),"number"==typeof e.version?r.writeVarIntNum(e.version):r.writeVarIntNum(-1),null!=e.labels){r.writeVarIntNum(e.labels.length);for(const t of e.labels){const e=Oe(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}}else r.writeVarIntNum(-1);if(null!=e.options){if(r.writeInt8(1),"boolean"==typeof e.options.signAndProcess?r.writeInt8(e.options.signAndProcess?1:0):r.writeInt8(-1),"boolean"==typeof e.options.acceptDelayedBroadcast?r.writeInt8(e.options.acceptDelayedBroadcast?1:0):r.writeInt8(-1),"known"===e.options.trustSelf?r.writeInt8(1):r.writeInt8(-1),null!=e.options.knownTxids){r.writeVarIntNum(e.options.knownTxids.length);for(const t of e.options.knownTxids){const e=Oe(t,"hex");r.write(e)}}else r.writeVarIntNum(-1);if("boolean"==typeof e.options.returnTXIDOnly?r.writeInt8(e.options.returnTXIDOnly?1:0):r.writeInt8(-1),"boolean"==typeof e.options.noSend?r.writeInt8(e.options.noSend?1:0):r.writeInt8(-1),null!=e.options.noSendChange){r.writeVarIntNum(e.options.noSendChange.length);for(const t of e.options.noSendChange)r.write(this.encodeOutpoint(t))}else r.writeVarIntNum(-1);if(null!=e.options.sendWith){r.writeVarIntNum(e.options.sendWith.length);for(const t of e.options.sendWith){const e=Oe(t,"hex");r.write(e)}}else r.writeVarIntNum(-1);"boolean"==typeof e.options.randomizeOutputs?r.writeInt8(e.options.randomizeOutputs?1:0):r.writeInt8(-1)}else r.writeInt8(0);const n=await this.transmit("createAction",t,r.toArray()),s=new Le(n),a={};if(1===s.readInt8()){const e=s.read(32);a.txid=Ne(e)}if(1===s.readInt8()){const e=s.readVarIntNum();a.tx=s.read(e)}const o=s.readVarIntNum();if(o>=0){a.noSendChange=[];for(let e=0;e<o;e++){const e=this.readOutpoint(s);a.noSendChange.push(e)}}const c=s.readVarIntNum();if(c>=0){a.sendWithResults=[];for(let e=0;e<c;e++){const e=s.read(32),t=Ne(e),r=s.readInt8();let i="unproven";1===r?i="unproven":2===r?i="sending":3===r&&(i="failed"),a.sendWithResults.push({txid:t,status:i})}}if(1===s.readInt8()){const e=s.readVarIntNum(),t=s.read(e),r=s.readVarIntNum(),i=s.read(r);a.signableTransaction={tx:t,reference:Fe(i)}}return a}async signAction(e,t){const r=new Ue,i=Object.keys(e.spends);r.writeVarIntNum(i.length);for(const t of i){r.writeVarIntNum(Number(t));const i=e.spends[Number(t)],n=Oe(i.unlockingScript,"hex");r.writeVarIntNum(n.length),r.write(n),"number"==typeof i.sequenceNumber?r.writeVarIntNum(i.sequenceNumber):r.writeVarIntNum(-1)}const n=Oe(e.reference,"base64");if(r.writeVarIntNum(n.length),r.write(n),null!=e.options)if(r.writeInt8(1),"boolean"==typeof e.options.acceptDelayedBroadcast?r.writeInt8(e.options.acceptDelayedBroadcast?1:0):r.writeInt8(-1),"boolean"==typeof e.options.returnTXIDOnly?r.writeInt8(e.options.returnTXIDOnly?1:0):r.writeInt8(-1),"boolean"==typeof e.options.noSend?r.writeInt8(e.options.noSend?1:0):r.writeInt8(-1),null!=e.options.sendWith){r.writeVarIntNum(e.options.sendWith.length);for(const t of e.options.sendWith){const e=Oe(t,"hex");r.write(e)}}else r.writeVarIntNum(-1);else r.writeInt8(0);const s=await this.transmit("signAction",t,r.toArray()),a=new Le(s),o={};if(1===a.readInt8()){const e=a.read(32);o.txid=Ne(e)}if(1===a.readInt8()){const e=a.readVarIntNum();o.tx=a.read(e)}const c=a.readVarIntNum();if(c>=0){o.sendWithResults=[];for(let e=0;e<c;e++){const e=a.read(32),t=Ne(e),r=a.readInt8();let i="unproven";1===r?i="unproven":2===r?i="sending":3===r&&(i="failed"),o.sendWithResults.push({txid:t,status:i})}}return o}async abortAction(e,t){return await this.transmit("abortAction",t,Oe(e.reference,"base64")),{aborted:!0}}async listActions(e,t){const r=new Ue;r.writeVarIntNum(e.labels.length);for(const t of e.labels){const e=Oe(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}"any"===e.labelQueryMode?r.writeInt8(1):"all"===e.labelQueryMode?r.writeInt8(2):r.writeInt8(-1);const i=[e.includeLabels,e.includeInputs,e.includeInputSourceLockingScripts,e.includeInputUnlockingScripts,e.includeOutputs,e.includeOutputLockingScripts];for(const e of i)"boolean"==typeof e?r.writeInt8(e?1:0):r.writeInt8(-1);"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1);const n=await this.transmit("listActions",t,r.toArray()),s=new Le(n),a=s.readVarIntNum(),o=[];for(let e=0;e<a;e++){const e=s.read(32),t=Ne(e),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(),d=s.read(c),u={txid:t,satoshis:r,status:n,isOutgoing:a,description:Ae(d),version:0,lockTime:0},h=s.readVarIntNum();if(h>=0){u.labels=[];for(let e=0;e<h;e++){const e=s.readVarIntNum(),t=s.read(e);u.labels.push(Ae(t))}}u.version=s.readVarIntNum(),u.lockTime=s.readVarIntNum();const l=s.readVarIntNum();if(l>=0){u.inputs=[];for(let e=0;e<l;e++){const e=this.readOutpoint(s),t=s.readVarIntNum(),r=s.readVarIntNum();let i;if(r>=0){const e=s.read(r);i=Ne(e)}const n=s.readVarIntNum();let a;if(n>=0){const e=s.read(n);a=Ne(e)}const o=s.readVarIntNum(),c=s.read(o),d=Ae(c),h=s.readVarIntNum();u.inputs.push({sourceOutpoint:e,sourceSatoshis:t,sourceLockingScript:i,unlockingScript:a,inputDescription:d,sequenceNumber:h})}}const f=s.readVarIntNum();if(f>=0){u.outputs=[];for(let e=0;e<f;e++){const e=s.readVarIntNum(),t=s.readVarIntNum(),r=s.readVarIntNum();let i;if(r>=0){const e=s.read(r);i=Ne(e)}const n=1===s.readInt8(),a=s.readVarIntNum(),o=s.read(a),c=Ae(o),d=s.readVarIntNum();let h;if(d>=0){const e=s.read(d);h=Ae(e)}const l=s.readVarIntNum(),f=[];if(l>=0)for(let e=0;e<l;e++){const e=s.readVarIntNum(),t=s.read(e);f.push(Ae(t))}const p=s.readVarIntNum();let b;if(p>=0){const e=s.read(p);b=Ae(e)}u.outputs.push({outputIndex:e,satoshis:t,lockingScript:i,spendable:n,outputDescription:c,basket:h,tags:f,customInstructions:b})}}o.push(u)}return{totalActions:a,actions:o}}async internalizeAction(e,t){const r=new Ue;r.writeVarIntNum(e.tx.length),r.write(e.tx),r.writeVarIntNum(e.outputs.length);for(const t of e.outputs)if(r.writeVarIntNum(t.outputIndex),"wallet payment"===t.protocol){if(null==t.paymentRemittance)throw new Error("Payment remittance is required for wallet payment");r.writeUInt8(1),r.write(Oe(t.paymentRemittance.senderIdentityKey,"hex"));const e=Oe(t.paymentRemittance.derivationPrefix,"base64");r.writeVarIntNum(e.length),r.write(e);const i=Oe(t.paymentRemittance.derivationSuffix,"base64");r.writeVarIntNum(i.length),r.write(i)}else{r.writeUInt8(2);const e=Oe(t.insertionRemittance?.basket,"utf8");if(r.writeVarIntNum(e.length),r.write(e),"string"==typeof t.insertionRemittance?.customInstructions&&""!==t.insertionRemittance.customInstructions){const e=Oe(t.insertionRemittance.customInstructions,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if("object"==typeof t.insertionRemittance?.tags){r.writeVarIntNum(t.insertionRemittance.tags.length);for(const e of t.insertionRemittance.tags){const t=Oe(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}}else r.writeVarIntNum(0)}if("object"==typeof e.labels){r.writeVarIntNum(e.labels.length);for(const t of e.labels){const e=Oe(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}}else r.writeVarIntNum(-1);const i=Oe(e.description);return r.writeVarIntNum(i.length),r.write(i),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1),await this.transmit("internalizeAction",t,r.toArray()),{accepted:!0}}async listOutputs(e,t){const r=new Ue,i=Oe(e.basket,"utf8");if(r.writeVarIntNum(i.length),r.write(i),"object"==typeof e.tags){r.writeVarIntNum(e.tags.length);for(const t of e.tags){const e=Oe(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}}else r.writeVarIntNum(0);"all"===e.tagQueryMode?r.writeInt8(1):"any"===e.tagQueryMode?r.writeInt8(2):r.writeInt8(-1),"locking scripts"===e.include?r.writeInt8(1):"entire transactions"===e.include?r.writeInt8(2):r.writeInt8(-1),"boolean"==typeof e.includeCustomInstructions?r.writeInt8(e.includeCustomInstructions?1:0):r.writeInt8(-1),"boolean"==typeof e.includeTags?r.writeInt8(e.includeTags?1:0):r.writeInt8(-1),"boolean"==typeof e.includeLabels?r.writeInt8(e.includeLabels?1:0):r.writeInt8(-1),"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1);const n=await this.transmit("listOutputs",t,r.toArray()),s=new Le(n),a=s.readVarIntNum(),o=s.readVarIntNum();let c;o>=0&&(c=s.read(o));const d=[];for(let e=0;e<a;e++){const e={spendable:!0,outpoint:this.readOutpoint(s),satoshis:s.readVarIntNum()},t=s.readVarIntNum();t>=0&&(e.lockingScript=Ne(s.read(t)));const r=s.readVarIntNum();r>=0&&(e.customInstructions=Ae(s.read(r)));const i=s.readVarIntNum();if(-1!==i){const t=[];for(let e=0;e<i;e++){const e=s.readVarIntNum();t.push(Ae(s.read(e)))}e.tags=t}const n=s.readVarIntNum();if(-1!==n){const t=[];for(let e=0;e<n;e++){const e=s.readVarIntNum();t.push(Ae(s.read(e)))}e.labels=t}d.push(e)}return{totalOutputs:a,BEEF:c,outputs:d}}async relinquishOutput(e,t){const r=new Ue,i=Oe(e.basket,"utf8");return r.writeVarIntNum(i.length),r.write(i),r.write(this.encodeOutpoint(e.output)),await this.transmit("relinquishOutput",t,r.toArray()),{relinquished:!0}}encodeOutpoint(e){const t=new Ue,[r,i]=e.split(".");return t.write(Oe(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}readOutpoint(e){return`${Ne(e.read(32))}.${e.readVarIntNum()}`}async getPublicKey(e,t){const r=new Ue;r.writeUInt8(e.identityKey?1:0),e.identityKey?r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)):(r.write(this.encodeKeyRelatedParams(e.protocolID??=[Cr.Silent,"default"],e.keyID??="",e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?r.writeInt8(e.forSelf?1:0):r.writeInt8(-1)),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1);const i=await this.transmit("getPublicKey",t,r.toArray());return{publicKey:Ne(i)}}async revealCounterpartyKeyLinkage(e,t){const r=new Ue;r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),r.write(Oe(e.counterparty,"hex")),r.write(Oe(e.verifier,"hex"));const i=await this.transmit("revealCounterpartyKeyLinkage",t,r.toArray()),n=new Le(i),s=Ne(n.read(33)),a=Ne(n.read(33)),o=Ne(n.read(33)),c=n.readVarIntNum(),d=Ae(n.read(c)),u=n.readVarIntNum(),h=n.read(u),l=n.readVarIntNum();return{prover:s,verifier:a,counterparty:o,revelationTime:d,encryptedLinkage:h,encryptedLinkageProof:n.read(l)}}async revealSpecificKeyLinkage(e,t){const r=new Ue;r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.write(Oe(e.verifier,"hex"));const i=await this.transmit("revealSpecificKeyLinkage",t,r.toArray()),n=new Le(i),s=Ne(n.read(33)),a=Ne(n.read(33)),o=Ne(n.read(33)),c=n.readUInt8(),d=n.readVarIntNum(),u=Ae(n.read(d)),h=n.readVarIntNum(),l=Ae(n.read(h)),f=n.readVarIntNum(),p=n.read(f),b=n.readVarIntNum();return{prover:s,verifier:a,counterparty:o,protocolID:[c,u],keyID:l,encryptedLinkage:p,encryptedLinkageProof:n.read(b),proofType:n.readUInt8()}}async encrypt(e,t){const r=new Ue;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.writeVarIntNum(e.plaintext.length),r.write(e.plaintext),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1),{ciphertext:await this.transmit("encrypt",t,r.toArray())}}async decrypt(e,t){const r=new Ue;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.writeVarIntNum(e.ciphertext.length),r.write(e.ciphertext),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1),{plaintext:await this.transmit("decrypt",t,r.toArray())}}async createHmac(e,t){const r=new Ue;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.writeVarIntNum(e.data.length),r.write(e.data),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1),{hmac:await this.transmit("createHmac",t,r.toArray())}}async verifyHmac(e,t){const r=new Ue;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.write(e.hmac),r.writeVarIntNum(e.data.length),r.write(e.data),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1),await this.transmit("verifyHmac",t,r.toArray()),{valid:!0}}async createSignature(e,t){const r=new Ue;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"object"==typeof e.data?(r.writeUInt8(1),r.writeVarIntNum(e.data.length),r.write(e.data)):(r.writeUInt8(2),r.write(e.hashToDirectlySign??=[])),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1),{signature:await this.transmit("createSignature",t,r.toArray())}}async verifySignature(e,t){const r=new Ue;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?r.writeInt8(e.forSelf?1:0):r.writeInt8(-1),r.writeVarIntNum(e.signature.length),r.write(e.signature),"object"==typeof e.data?(r.writeUInt8(1),r.writeVarIntNum(e.data.length),r.write(e.data)):(r.writeUInt8(2),r.write(e.hashToDirectlyVerify??[])),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1),await this.transmit("verifySignature",t,r.toArray()),{valid:!0}}encodeKeyRelatedParams(e,t,r,i,n){const s=new Ue;s.writeUInt8(e[0]);const a=Oe(e[1],"utf8");s.writeVarIntNum(a.length),s.write(a);const o=Oe(t,"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(Oe(r,"hex")),s.write(this.encodePrivilegedParams(i,n)),s.toArray()}async acquireCertificate(e,t){const r=new Ue;r.write(Oe(e.type,"base64")),r.write(Oe(e.certifier,"hex"));const i=Object.entries(e.fields);r.writeVarIntNum(i.length);for(const[e,t]of i){const i=Oe(e,"utf8"),n=Oe(t,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(n.length),r.write(n)}if(r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),r.writeUInt8("direct"===e.acquisitionProtocol?1:2),"direct"===e.acquisitionProtocol){r.write(Oe(e.serialNumber,"base64")),r.write(this.encodeOutpoint(e.revocationOutpoint??""));const t=Oe(e.signature,"hex");r.writeVarIntNum(t.length),r.write(t);const i="certifier"!==e.keyringRevealer?Oe(e.keyringRevealer,"hex"):[11];r.write(i);const n=Object.keys(e.keyringForSubject??{});r.writeVarIntNum(n.length);for(let t=0;t<n.length;t++){const i=Oe(n[t],"utf8");r.writeVarIntNum(i.length),r.write(i);const s=Oe(e.keyringForSubject?.[n[t]],"base64");r.writeVarIntNum(s.length),r.write(s)}}else{const t=Oe(e.certifierUrl,"utf8");r.writeVarIntNum(t.length),r.write(t)}const n=await this.transmit("acquireCertificate",t,r.toArray()),s=Mr.fromBinary(n);return{...s,signature:s.signature}}encodePrivilegedParams(e,t){const r=new Ue;if("boolean"==typeof e?r.writeInt8(e?1:0):r.writeInt8(-1),"string"==typeof t){const e=Oe(t,"utf8");r.writeInt8(e.length),r.write(e)}else r.writeInt8(-1);return r.toArray()}async listCertificates(e,t){const r=new Ue;r.writeVarIntNum(e.certifiers.length);for(let t=0;t<e.certifiers.length;t++)r.write(Oe(e.certifiers[t],"hex"));r.writeVarIntNum(e.types.length);for(let t=0;t<e.types.length;t++)r.write(Oe(e.types[t],"base64"));"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));const i=await this.transmit("listCertificates",t,r.toArray()),n=new Le(i),s=n.readVarIntNum(),a=[];for(let e=0;e<s;e++){const e=n.readVarIntNum(),t=n.read(e),r=Mr.fromBinary(t);a.push({...r,signature:r.signature})}return{totalCertificates:s,certificates:a}}async proveCertificate(e,t){const r=new Ue,i=Oe(e.certificate.type,"base64");r.write(i);const n=Oe(e.certificate.subject,"hex");r.write(n);const s=Oe(e.certificate.serialNumber,"base64");r.write(s);const a=Oe(e.certificate.certifier,"hex");r.write(a);const o=this.encodeOutpoint(e.certificate.revocationOutpoint??"");r.write(o);const c=Oe(e.certificate.signature,"hex");r.writeVarIntNum(c.length),r.write(c);const d=Object.entries(e.certificate.fields??{});r.writeVarIntNum(d.length);for(const[e,t]of d){const i=Oe(e,"utf8"),n=Oe(t,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(n.length),r.write(n)}r.writeVarIntNum(e.fieldsToReveal.length);for(const t of e.fieldsToReveal){const e=Oe(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}r.write(Oe(e.verifier,"hex")),r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));const u=await this.transmit("proveCertificate",t,r.toArray()),h=new Le(u),l=h.readVarIntNum(),f={};for(let e=0;e<l;e++){const e=h.readVarIntNum(),t=Ae(h.read(e)),r=h.readVarIntNum();f[t]=Fe(h.read(r))}return{keyringForVerifier:f}}async relinquishCertificate(e,t){const r=new Ue,i=Oe(e.type,"base64");r.write(i);const n=Oe(e.serialNumber,"base64");r.write(n);const s=Oe(e.certifier,"hex");return r.write(s),await this.transmit("relinquishCertificate",t,r.toArray()),{relinquished:!0}}parseDiscoveryResult(e){const t=new Le(e),r=t.readVarIntNum(),i=[];for(let e=0;e<r;e++){const e=t.readVarIntNum(),r=t.read(e),n=Mr.fromBinary(r),s=t.readVarIntNum(),a=Ae(t.read(s)),o=t.readVarIntNum(),c=Ae(t.read(o)),d=t.readVarIntNum(),u=Ae(t.read(d)),h=t.readUInt8(),l={},f=t.readVarIntNum();for(let e=0;e<f;e++){const e=t.readVarIntNum(),r=Ae(t.read(e)),i=t.readVarIntNum();l[r]=t.read(i)}const p={},b=t.readVarIntNum();for(let e=0;e<b;e++){const e=t.readVarIntNum(),r=Ae(t.read(e)),i=t.readVarIntNum();p[r]=Ae(t.read(i))}i.push({...n,signature:n.signature,certifierInfo:{iconUrl:c,name:a,description:u,trust:h},publiclyRevealedKeyring:l,decryptedFields:p})}return{totalCertificates:r,certificates:i}}async discoverByIdentityKey(e,t){const r=new Ue;r.write(Oe(e.identityKey,"hex")),"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1);const i=await this.transmit("discoverByIdentityKey",t,r.toArray());return this.parseDiscoveryResult(i)}async discoverByAttributes(e,t){const r=new Ue,i=Object.keys(e.attributes);r.writeVarIntNum(i.length);for(let t=0;t<i.length;t++)r.writeVarIntNum(i[t].length),r.write(Oe(i[t],"utf8")),r.writeVarIntNum(e.attributes[i[t]].length),r.write(Oe(e.attributes[i[t]],"utf8"));"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1);const n=await this.transmit("discoverByAttributes",t,r.toArray());return this.parseDiscoveryResult(n)}async isAuthenticated(e,t){return{authenticated:1===(await this.transmit("isAuthenticated",t))[0]}}async waitForAuthentication(e,t){return await this.transmit("waitForAuthentication",t),{authenticated:!0}}async getHeight(e,t){const r=await this.transmit("getHeight",t);return{height:new Le(r).readVarIntNum()}}async getHeaderForHeight(e,t){const r=new Ue;r.writeVarIntNum(e.height);const i=await this.transmit("getHeaderForHeight",t,r.toArray());return{header:Ne(i)}}async getNetwork(e,t){return{network:0===(await this.transmit("getNetwork",t))[0]?"mainnet":"testnet"}}async getVersion(e,t){const r=await this.transmit("getVersion",t);return{version:Ae(r)}}}class jr{baseUrl;httpClient;originator;constructor(e,t="http://localhost:3301",r=fetch){this.baseUrl=t,this.httpClient=r,this.originator=e}async transmitToWallet(e){const t=new Le(e),r=t.readUInt8(),i=zr[r];if(void 0===i||""===i)throw new Error(`Invalid call code: ${r}`);const n=t.readUInt8();let s;if(n>0){const e=t.read(n);s=Ae(e)}const a=t.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 Xr extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(e,t,r,i,n){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=e,this.sendWithResults=t,this.txid=r,this.tx=i,this.noSendChange=n,this.code=5,this.name=this.constructor.name}}const Gr=Xr;class Yr{baseUrl;httpClient;originator;api;constructor(e,t="http://localhost:3321",r=fetch){this.baseUrl=t,this.originator=e,this.httpClient=r,this.api=async(e,t)=>{const i=await await r(`${this.baseUrl}/${e}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Originator:this.originator??""},body:JSON.stringify(t)}),n=await i.json();if(!i.ok){if(400===i.status&&n.isError&&5===n.code)throw new Xr(n.reviewActionResults,n.sendWithResults,n.txid,n.tx,n.noSendChange);{const r={call:e,args:t,message:n.message??`HTTP Client error ${i.status}`};throw new Error(JSON.stringify(r))}}return n}}async createAction(e){return await this.api("createAction",e)}async signAction(e){return await this.api("signAction",e)}async abortAction(e){return await this.api("abortAction",e)}async listActions(e){return await this.api("listActions",e)}async internalizeAction(e){return await this.api("internalizeAction",e)}async listOutputs(e){return await this.api("listOutputs",e)}async relinquishOutput(e){return await this.api("relinquishOutput",e)}async getPublicKey(e){return await this.api("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.api("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.api("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.api("encrypt",e)}async decrypt(e){return await this.api("decrypt",e)}async createHmac(e){return await this.api("createHmac",e)}async verifyHmac(e){return await this.api("verifyHmac",e)}async createSignature(e){return await this.api("createSignature",e)}async verifySignature(e){return await this.api("verifySignature",e)}async acquireCertificate(e){return await this.api("acquireCertificate",e)}async listCertificates(e){return await this.api("listCertificates",e)}async proveCertificate(e){return await this.api("proveCertificate",e)}async relinquishCertificate(e){return await this.api("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.api("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.api("discoverByAttributes",e)}async isAuthenticated(e){return await this.api("isAuthenticated",e)}async waitForAuthentication(e){return await this.api("waitForAuthentication",e)}async getHeight(e){return await this.api("getHeight",e)}async getHeaderForHeight(e){return await this.api("getHeaderForHeight",e)}async getNetwork(e){return await this.api("getNetwork",e)}async getVersion(e){return await this.api("getVersion",e)}}class Jr{domain;constructor(e="*"){if("object"!=typeof window)throw new Error("The XDM substrate requires a global window object.");if(!window.hasOwnProperty("ReactNativeWebView"))throw new Error("The window object does not have a ReactNativeWebView property.");if("function"!=typeof window.ReactNativeWebView.postMessage)throw new Error("The window.ReactNativeWebView property does not seem to support postMessage calls.");this.domain=e}async invoke(e,t){return await new Promise(((r,i)=>{const n=Fe(Ze(12)),s=e=>{const t=JSON.parse(e.data);if("CWI"===t.type&&t.id===n&&!0!==t.isInvocation)if("function"==typeof window.removeEventListener&&window.removeEventListener("message",s),"error"===t.status){const e=new Lr(t.description,t.code);i(e)}else r(t.result)};window.addEventListener("message",s),window.ReactNativeWebView.postMessage(JSON.stringify({type:"CWI",isInvocation:!0,id:n,call:e,args:t}))}))}async createAction(e){return await this.invoke("createAction",e)}async signAction(e){return await this.invoke("signAction",e)}async abortAction(e){return await this.invoke("abortAction",e)}async listActions(e){return await this.invoke("listActions",e)}async internalizeAction(e){return await this.invoke("internalizeAction",e)}async listOutputs(e){return await this.invoke("listOutputs",e)}async relinquishOutput(e){return await this.invoke("relinquishOutput",e)}async getPublicKey(e){return await this.invoke("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.invoke("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.invoke("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.invoke("encrypt",e)}async decrypt(e){return await this.invoke("decrypt",e)}async createHmac(e){return await this.invoke("createHmac",e)}async verifyHmac(e){return await this.invoke("verifyHmac",e)}async createSignature(e){return await this.invoke("createSignature",e)}async verifySignature(e){return await this.invoke("verifySignature",e)}async acquireCertificate(e){return await this.invoke("acquireCertificate",e)}async listCertificates(e){return await this.invoke("listCertificates",e)}async proveCertificate(e){return await this.invoke("proveCertificate",e)}async relinquishCertificate(e){return await this.invoke("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.invoke("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.invoke("discoverByAttributes",e)}async isAuthenticated(e){return await this.invoke("isAuthenticated",e)}async waitForAuthentication(e){return await this.invoke("waitForAuthentication",e)}async getHeight(e){return await this.invoke("getHeight",e)}async getHeaderForHeight(e){return await this.invoke("getHeaderForHeight",e)}async getNetwork(e){return await this.invoke("getNetwork",e)}async getVersion(e){return await this.invoke("getVersion",e)}}class Zr{substrate;originator;constructor(e="auto",t){"Cicada"===e&&(e=new Wr(new jr(t))),"window.CWI"===e&&(e=new Ur),"XDM"===e&&(e=new qr),"json-api"===e&&(e=new Yr(t)),"react-native"===e&&(e=new Jr(t)),this.substrate=e,this.originator=t}async connectToSubstrate(){if("object"==typeof this.substrate)return;let e;const t=async t=>{let r;if(r="number"==typeof t?await Promise.race([e.getVersion({}),new Promise(((e,r)=>setTimeout((()=>r(new Error("Timed out."))),t)))]):await e.getVersion({}),"object"!=typeof r||"string"!=typeof r.version)throw new Error("Failed to use substrate.")};try{e=new Ur,await t(),this.substrate=e}catch(r){try{e=new qr,await t(200),this.substrate=e}catch(r){try{e=new Wr(new jr(this.originator)),await t(),this.substrate=e}catch(r){try{e=new Yr(this.originator),await t(),this.substrate=e}catch(r){try{e=new Jr(this.originator),await t(),this.substrate=e}catch(e){throw new Error("No wallet available over any communication substrate. Install a BSV wallet today!")}}}}}}async createAction(e){return await this.connectToSubstrate(),await this.substrate.createAction(e,this.originator)}async signAction(e){return await this.connectToSubstrate(),await this.substrate.signAction(e,this.originator)}async abortAction(e){return await this.connectToSubstrate(),await this.substrate.abortAction(e,this.originator)}async listActions(e){return await this.connectToSubstrate(),await this.substrate.listActions(e,this.originator)}async internalizeAction(e){return await this.connectToSubstrate(),await this.substrate.internalizeAction(e,this.originator)}async listOutputs(e){return await this.connectToSubstrate(),await this.substrate.listOutputs(e,this.originator)}async relinquishOutput(e){return await this.connectToSubstrate(),await this.substrate.relinquishOutput(e,this.originator)}async getPublicKey(e){return await this.connectToSubstrate(),await this.substrate.getPublicKey(e,this.originator)}async revealCounterpartyKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealCounterpartyKeyLinkage(e,this.originator)}async revealSpecificKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealSpecificKeyLinkage(e,this.originator)}async encrypt(e){return await this.connectToSubstrate(),await this.substrate.encrypt(e,this.originator)}async decrypt(e){return await this.substrate.decrypt(e,this.originator)}async createHmac(e){return await this.connectToSubstrate(),await this.substrate.createHmac(e,this.originator)}async verifyHmac(e){return await this.connectToSubstrate(),await this.substrate.verifyHmac(e,this.originator)}async createSignature(e){return await this.connectToSubstrate(),await this.substrate.createSignature(e,this.originator)}async verifySignature(e){return await this.connectToSubstrate(),await this.substrate.verifySignature(e,this.originator)}async acquireCertificate(e){return await this.connectToSubstrate(),await this.substrate.acquireCertificate(e,this.originator)}async listCertificates(e){return await this.connectToSubstrate(),await this.substrate.listCertificates(e,this.originator)}async proveCertificate(e){return await this.connectToSubstrate(),await this.substrate.proveCertificate(e,this.originator)}async relinquishCertificate(e){return await this.connectToSubstrate(),await this.substrate.relinquishCertificate(e,this.originator)}async discoverByIdentityKey(e){return await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(e,this.originator)}async discoverByAttributes(e){return await this.connectToSubstrate(),await this.substrate.discoverByAttributes(e,this.originator)}async isAuthenticated(e={}){return await this.connectToSubstrate(),await this.substrate.isAuthenticated(e,this.originator)}async waitForAuthentication(e={}){return await this.connectToSubstrate(),await this.substrate.waitForAuthentication(e,this.originator)}async getHeight(e={}){return await this.connectToSubstrate(),await this.substrate.getHeight(e,this.originator)}async getHeaderForHeight(e){return await this.connectToSubstrate(),await this.substrate.getHeaderForHeight(e,this.originator)}async getNetwork(e={}){return await this.connectToSubstrate(),await this.substrate.getNetwork(e,this.originator)}async getVersion(e={}){return await this.connectToSubstrate(),await this.substrate.getVersion(e,this.originator)}}class Qr{wallet;constructor(e){this.wallet=e}decodeOutpoint(e){const t=e.read(32);return`${Ne(t)}.${e.readVarIntNum()}`}encodeOutpoint(e){const t=new Ue,[r,i]=e.split(".");return t.write(Oe(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}async transmitToWallet(e){const t=new Le(e);try{const e=t.readUInt8(),r=zr[e];if(void 0===r||""===r)throw new Error(`Invalid call code: ${e}`);const i=t.readUInt8(),n=t.read(i),s=Ae(n),a=t;switch(r){case"createAction":{const e={},t=a.readVarIntNum(),r=a.read(t);e.description=Ae(r);const i=a.readVarIntNum();e.inputBEEF=i>=0?a.read(i):void 0;const n=a.readVarIntNum();if(n>=0){e.inputs=[];for(let t=0;t<n;t++){const t={};t.outpoint=this.decodeOutpoint(a);const r=a.readVarIntNum();if(r>=0){const e=a.read(r);t.unlockingScript=Ne(e)}else{t.unlockingScript=void 0;const e=a.readVarIntNum();t.unlockingScriptLength=e}const i=a.readVarIntNum(),n=a.read(i);t.inputDescription=Ae(n);const s=a.readVarIntNum();t.sequenceNumber=s>=0?s:void 0,e.inputs.push(t)}}else e.inputs=void 0;const o=a.readVarIntNum();if(o>=0){e.outputs=[];for(let t=0;t<o;t++){const t={},r=a.readVarIntNum(),i=a.read(r);t.lockingScript=Ne(i),t.satoshis=a.readVarIntNum();const n=a.readVarIntNum(),s=a.read(n);t.outputDescription=Ae(s);const o=a.readVarIntNum();if(o>=0){const e=a.read(o);t.basket=Ae(e)}else t.basket=void 0;const c=a.readVarIntNum();if(c>=0){const e=a.read(c);t.customInstructions=Ae(e)}else t.customInstructions=void 0;const d=a.readVarIntNum();if(d>=0){t.tags=[];for(let e=0;e<d;e++){const e=a.readVarIntNum(),r=a.read(e),i=Ae(r);t.tags.push(i)}}else t.tags=void 0;e.outputs.push(t)}}else e.outputs=void 0;const c=a.readVarIntNum();e.lockTime=c>=0?c:void 0;const d=a.readVarIntNum();e.version=d>=0?d:void 0;const u=a.readVarIntNum();if(u>=0){e.labels=[];for(let t=0;t<u;t++){const t=a.readVarIntNum(),r=a.read(t),i=Ae(r);e.labels.push(i)}}else e.labels=void 0;if(1===a.readInt8()){e.options={};const t=a.readInt8();e.options.signAndProcess=-1===t?void 0:1===t;const r=a.readInt8();e.options.acceptDelayedBroadcast=-1===r?void 0:1===r;const i=a.readInt8();-1===i?e.options.trustSelf=void 0:1===i&&(e.options.trustSelf="known");const n=a.readVarIntNum();if(n>=0){e.options.knownTxids=[];for(let t=0;t<n;t++){const t=a.read(32),r=Ne(t);e.options.knownTxids.push(r)}}else e.options.knownTxids=void 0;const s=a.readInt8();e.options.returnTXIDOnly=-1===s?void 0:1===s;const o=a.readInt8();e.options.noSend=-1===o?void 0:1===o;const c=a.readVarIntNum();if(c>=0){e.options.noSendChange=[];for(let t=0;t<c;t++){const t=this.decodeOutpoint(a);e.options.noSendChange.push(t)}}else e.options.noSendChange=void 0;const d=a.readVarIntNum();if(d>=0){e.options.sendWith=[];for(let t=0;t<d;t++){const t=a.read(32),r=Ne(t);e.options.sendWith.push(r)}}else e.options.sendWith=void 0;const u=a.readInt8();e.options.randomizeOutputs=-1===u?void 0:1===u}else e.options=void 0;const h=await this.wallet.createAction(e,s),l=new Ue;if(null!=h.txid&&""!==h.txid?(l.writeInt8(1),l.write(Oe(h.txid,"hex"))):l.writeInt8(0),null!=h.tx?(l.writeInt8(1),l.writeVarIntNum(h.tx.length),l.write(h.tx)):l.writeInt8(0),null!=h.noSendChange){l.writeVarIntNum(h.noSendChange.length);for(const e of h.noSendChange)l.write(this.encodeOutpoint(e))}else l.writeVarIntNum(-1);if(null!=h.sendWithResults){l.writeVarIntNum(h.sendWithResults.length);for(const e of h.sendWithResults){let t;l.write(Oe(e.txid,"hex")),"unproven"===e.status?t=1:"sending"===e.status?t=2:"failed"===e.status&&(t=3),l.writeInt8(t)}}else l.writeVarIntNum(-1);if(null!=h.signableTransaction){l.writeInt8(1),l.writeVarIntNum(h.signableTransaction.tx.length),l.write(h.signableTransaction.tx);const e=Oe(h.signableTransaction.reference,"base64");l.writeVarIntNum(e.length),l.write(e)}else l.writeInt8(0);const f=new Ue;return f.writeUInt8(0),f.write(l.toArray()),f.toArray()}case"signAction":{const e={},t=a.readVarIntNum();e.spends={};for(let r=0;r<t;r++){const t=a.readVarIntNum(),r={},i=a.readVarIntNum(),n=a.read(i);r.unlockingScript=Ne(n);const s=a.readVarIntNum();r.sequenceNumber=s>=0?s:void 0,e.spends[t]=r}const r=a.readVarIntNum(),i=a.read(r);if(e.reference=Fe(i),1===a.readInt8()){e.options={};const t=a.readInt8();e.options.acceptDelayedBroadcast=-1===t?void 0:1===t;const r=a.readInt8();e.options.returnTXIDOnly=-1===r?void 0:1===r;const i=a.readInt8();e.options.noSend=-1===i?void 0:1===i;const n=a.readVarIntNum();if(n>=0){e.options.sendWith=[];for(let t=0;t<n;t++){const t=a.read(32),r=Ne(t);e.options.sendWith.push(r)}}else e.options.sendWith=void 0}else e.options=void 0;const n=await this.wallet.signAction(e,s),o=new Ue;if(null!=n.txid&&""!==n.txid?(o.writeInt8(1),o.write(Oe(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 e of n.sendWithResults){let t;o.write(Oe(e.txid,"hex")),"unproven"===e.status?t=1:"sending"===e.status?t=2:"failed"===e.status&&(t=3),o.writeInt8(t)}}else o.writeVarIntNum(-1);const c=new Ue;return c.writeUInt8(0),c.write(o.toArray()),c.toArray()}case"abortAction":{const e=Fe(a.read());await this.wallet.abortAction({reference:e},s);const t=new Ue;return t.writeUInt8(0),t.toArray()}case"listActions":{const e={},t=a.readVarIntNum();e.labels=[];for(let r=0;r<t;r++){const t=a.readVarIntNum(),r=a.read(t);e.labels.push(Ae(r))}const r=a.readInt8();-1===r?e.labelQueryMode=void 0:1===r?e.labelQueryMode="any":2===r&&(e.labelQueryMode="all");const i=["includeLabels","includeInputs","includeInputSourceLockingScripts","includeInputUnlockingScripts","includeOutputs","includeOutputLockingScripts"];for(const t of i){const r=a.readInt8();e[t]=-1===r?void 0:1===r}const n=a.readVarIntNum();e.limit=n>=0?n:void 0;const o=a.readVarIntNum();e.offset=o>=0?o:void 0;const c=a.readInt8();e.seekPermission=c>=0?1===c:void 0;const d=await this.wallet.listActions(e,s),u=new Ue;u.writeVarIntNum(d.totalActions);for(const e of d.actions){let t;switch(u.write(Oe(e.txid,"hex")),u.writeVarIntNum(e.satoshis),e.status){case"completed":t=1;break;case"unprocessed":t=2;break;case"sending":t=3;break;case"unproven":t=4;break;case"unsigned":t=5;break;case"nosend":t=6;break;case"nonfinal":t=7;break;case"failed":t=8;break;default:t=-1}u.writeInt8(t),u.writeInt8(e.isOutgoing?1:0);const r=Oe(e.description,"utf8");if(u.writeVarIntNum(r.length),u.write(r),void 0!==e.labels){u.writeVarIntNum(e.labels.length);for(const t of e.labels){const e=Oe(t,"utf8");u.writeVarIntNum(e.length),u.write(e)}}else u.writeVarIntNum(-1);if(u.writeVarIntNum(e.version),u.writeVarIntNum(e.lockTime),void 0!==e.inputs){u.writeVarIntNum(e.inputs.length);for(const t of e.inputs){if(u.write(this.encodeOutpoint(t.sourceOutpoint)),u.writeVarIntNum(t.sourceSatoshis),void 0!==t.sourceLockingScript){const e=Oe(t.sourceLockingScript,"hex");u.writeVarIntNum(e.length),u.write(e)}else u.writeVarIntNum(-1);if(void 0!==t.unlockingScript){const e=Oe(t.unlockingScript,"hex");u.writeVarIntNum(e.length),u.write(e)}else u.writeVarIntNum(-1);const e=Oe(t.inputDescription,"utf8");u.writeVarIntNum(e.length),u.write(e),u.writeVarIntNum(t.sequenceNumber)}}else u.writeVarIntNum(-1);if(void 0!==e.outputs){u.writeVarIntNum(e.outputs.length);for(const t of e.outputs){if(u.writeVarIntNum(t.outputIndex),u.writeVarIntNum(t.satoshis),void 0!==t.lockingScript){const e=Oe(t.lockingScript,"hex");u.writeVarIntNum(e.length),u.write(e)}else u.writeVarIntNum(-1);u.writeInt8(t.spendable?1:0);const e=Oe(t.outputDescription,"utf8");if(u.writeVarIntNum(e.length),u.write(e),void 0!==t.basket){const e=Oe(t.basket,"utf8");u.writeVarIntNum(e.length),u.write(e)}else u.writeVarIntNum(-1);if(void 0!==t.tags){u.writeVarIntNum(t.tags.length);for(const e of t.tags){const t=Oe(e,"utf8");u.writeVarIntNum(t.length),u.write(t)}}else u.writeVarIntNum(-1);if(void 0!==t.customInstructions){const e=Oe(t.customInstructions,"utf8");u.writeVarIntNum(e.length),u.write(e)}else u.writeVarIntNum(-1)}}else u.writeVarIntNum(-1)}const h=new Ue;return h.writeUInt8(0),h.write(u.toArray()),h.toArray()}case"internalizeAction":{const e={},t=a.readVarIntNum();e.tx=a.read(t);const r=a.readVarIntNum();e.outputs=[];for(let t=0;t<r;t++){const t={};t.outputIndex=a.readVarIntNum();const r=a.readUInt8();if(1===r){t.protocol="wallet payment",t.paymentRemittance={};const e=a.read(33);t.paymentRemittance.senderIdentityKey=Ne(e);const r=a.readVarIntNum(),i=a.read(r);t.paymentRemittance.derivationPrefix=Fe(i);const n=a.readVarIntNum(),s=a.read(n);t.paymentRemittance.derivationSuffix=Fe(s)}else if(2===r){t.protocol="basket insertion",t.insertionRemittance={};const e=a.readVarIntNum(),r=a.read(e);t.insertionRemittance.basket=Ae(r);const i=a.readVarIntNum();if(i>=0){const e=a.read(i);t.insertionRemittance.customInstructions=Ae(e)}const n=a.readVarIntNum();if(n>0){t.insertionRemittance.tags=[];for(let e=0;e<n;e++){const e=a.readVarIntNum(),r=a.read(e);t.insertionRemittance.tags.push(Ae(r))}}else t.insertionRemittance.tags=[]}e.outputs.push(t)}const i=a.readVarIntNum();if(i>=0){e.labels=[];for(let t=0;t<i;t++){const t=a.readVarIntNum();e.labels.push(Ae(a.read(t)))}}const n=a.readVarIntNum();e.description=Ae(a.read(n));const o=a.readInt8();e.seekPermission=o>=0?1===o:void 0,await this.wallet.internalizeAction(e,s);const c=new Ue;return c.writeUInt8(0),c.toArray()}case"listOutputs":{const e={},t=a.readVarIntNum(),r=a.read(t);e.basket=Ae(r);const i=a.readVarIntNum();if(i>0){e.tags=[];for(let t=0;t<i;t++){const t=a.readVarIntNum(),r=a.read(t);e.tags.push(Ae(r))}}else e.tags=void 0;const n=a.readInt8();e.tagQueryMode=1===n?"all":2===n?"any":void 0;const o=a.readInt8();e.include=1===o?"locking scripts":2===o?"entire transactions":void 0;const c=a.readInt8();e.includeCustomInstructions=-1===c?void 0:1===c;const d=a.readInt8();e.includeTags=-1===d?void 0:1===d;const u=a.readInt8();e.includeLabels=-1===u?void 0:1===u;const h=a.readVarIntNum();e.limit=h>=0?h:void 0;const l=a.readVarIntNum();e.offset=l>=0?l:void 0;const f=a.readInt8();e.seekPermission=f>=0?1===f:void 0;const p=await this.wallet.listOutputs(e,s),b=new Ue;b.writeVarIntNum(p.totalOutputs),null!=p.BEEF?(b.writeVarIntNum(p.BEEF.length),b.write(p.BEEF)):b.writeVarIntNum(-1);for(const e of p.outputs){if(b.write(this.encodeOutpoint(e.outpoint)),b.writeVarIntNum(e.satoshis),void 0!==e.lockingScript){const t=Oe(e.lockingScript,"hex");b.writeVarIntNum(t.length),b.write(t)}else b.writeVarIntNum(-1);if(void 0!==e.customInstructions){const t=Oe(e.customInstructions,"utf8");b.writeVarIntNum(t.length),b.write(t)}else b.writeVarIntNum(-1);if(void 0!==e.tags){b.writeVarIntNum(e.tags.length);for(const t of e.tags){const e=Oe(t,"utf8");b.writeVarIntNum(e.length),b.write(e)}}else b.writeVarIntNum(-1);if(void 0!==e.labels){b.writeVarIntNum(e.labels.length);for(const t of e.labels){const e=Oe(t,"utf8");b.writeVarIntNum(e.length),b.write(e)}}else b.writeVarIntNum(-1)}const w=new Ue;return w.writeUInt8(0),w.write(b.toArray()),w.toArray()}case"relinquishOutput":{const e={},t=a.readVarIntNum(),r=a.read(t);e.basket=Ae(r),e.output=this.decodeOutpoint(a),await this.wallet.relinquishOutput(e,s);const i=new Ue;return i.writeUInt8(0),i.toArray()}case"getPublicKey":{const e={},t=a.readUInt8();if(e.identityKey=1===t,!0!==e.identityKey){e.protocolID=this.decodeProtocolID(a),e.keyID=this.decodeString(a),e.counterparty=this.decodeCounterparty(a);const t=a.readInt8();e.privileged=-1===t?void 0:1===t;const r=a.readInt8();if(-1!==r){const t=a.read(r);e.privilegedReason=Ae(t)}else e.privilegedReason=void 0;const i=a.readInt8();e.forSelf=-1===i?void 0:1===i}else{const t=a.readInt8();e.privileged=-1===t?void 0:1===t;const r=a.readInt8();if(-1!==r){const t=a.read(r);e.privilegedReason=Ae(t)}else e.privilegedReason=void 0}const r=a.readInt8();e.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.getPublicKey(e,s),n=new Ue;n.writeUInt8(0);const o=Oe(i.publicKey,"hex");return n.write(o),n.toArray()}case"encrypt":{const e=this.decodeKeyRelatedParams(a),t=a.readVarIntNum();e.plaintext=a.read(t);const r=a.readInt8();e.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.encrypt(e,s),n=new Ue;return n.writeUInt8(0),n.write(i.ciphertext),n.toArray()}case"decrypt":{const e=this.decodeKeyRelatedParams(a),t=a.readVarIntNum();e.ciphertext=a.read(t);const r=a.readInt8();e.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.decrypt(e,s),n=new Ue;return n.writeUInt8(0),n.write(i.plaintext),n.toArray()}case"createHmac":{const e=this.decodeKeyRelatedParams(a),t=a.readVarIntNum();e.data=a.read(t);const r=a.readInt8();e.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.createHmac(e,s),n=new Ue;return n.writeUInt8(0),n.write(i.hmac),n.toArray()}case"verifyHmac":{const e=this.decodeKeyRelatedParams(a);e.hmac=a.read(32);const t=a.readVarIntNum();e.data=a.read(t);const r=a.readInt8();e.seekPermission=r>=0?1===r:void 0,await this.wallet.verifyHmac(e,s);const i=new Ue;return i.writeUInt8(0),i.toArray()}case"createSignature":{const e=this.decodeKeyRelatedParams(a),t=a.readUInt8();if(1===t){const t=a.readVarIntNum();e.data=a.read(t)}else 2===t&&(e.hashToDirectlySign=a.read(32));const r=a.readInt8();e.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.createSignature(e,s),n=new Ue;return n.writeUInt8(0),n.write(i.signature),n.toArray()}case"verifySignature":{const e=this.decodeKeyRelatedParams(a),t=a.readInt8();e.forSelf=-1===t?void 0:1===t;const r=a.readVarIntNum();e.signature=a.read(r);const i=a.readUInt8();if(1===i){const t=a.readVarIntNum();e.data=a.read(t)}else 2===i&&(e.hashToDirectlyVerify=a.read(32));const n=a.readInt8();e.seekPermission=n>=0?1===n:void 0,await this.wallet.verifySignature(e,s);const o=new Ue;return o.writeUInt8(0),o.toArray()}case"isAuthenticated":{const e=await this.wallet.isAuthenticated({},s),t=new Ue;return t.writeUInt8(0),t.writeUInt8(e.authenticated?1:0),t.toArray()}case"waitForAuthentication":{await this.wallet.waitForAuthentication({},s);const e=new Ue;return e.writeUInt8(0),e.toArray()}case"getHeight":{const e=await this.wallet.getHeight({},s),t=new Ue;return t.writeUInt8(0),t.writeVarIntNum(e.height),t.toArray()}case"getHeaderForHeight":{const e={};e.height=a.readVarIntNum();const t=await this.wallet.getHeaderForHeight(e,s),r=new Ue;r.writeUInt8(0);const i=Oe(t.header,"hex");return r.write(i),r.toArray()}case"getNetwork":{const e=await this.wallet.getNetwork({},s),t=new Ue;return t.writeUInt8(0),t.writeUInt8("mainnet"===e.network?0:1),t.toArray()}case"getVersion":{const e=await this.wallet.getVersion({},s),t=new Ue;t.writeUInt8(0);const r=Oe(e.version,"utf8");return t.write(r),t.toArray()}case"revealCounterpartyKeyLinkage":{const e={},t=a.readInt8();e.privileged=-1===t?void 0:1===t;const r=a.readInt8();if(-1===r)e.privilegedReason=void 0;else{const t=a.read(r);e.privilegedReason=Ae(t)}const i=a.read(33);e.counterparty=Ne(i);const n=a.read(33);e.verifier=Ne(n);const o=await this.wallet.revealCounterpartyKeyLinkage(e,s),c=new Ue;c.write(Oe(o.prover,"hex")),c.write(Oe(o.verifier,"hex")),c.write(Oe(o.counterparty,"hex"));const d=Oe(o.revelationTime,"utf8");c.writeVarIntNum(d.length),c.write(d),c.writeVarIntNum(o.encryptedLinkage.length),c.write(o.encryptedLinkage),c.writeVarIntNum(o.encryptedLinkageProof.length),c.write(o.encryptedLinkageProof);const u=new Ue;return u.writeUInt8(0),u.write(c.toArray()),u.toArray()}case"revealSpecificKeyLinkage":{const e=this.decodeKeyRelatedParams(a),t=a.read(33);e.verifier=Ne(t);const r=await this.wallet.revealSpecificKeyLinkage(e,s),i=new Ue;i.write(Oe(r.prover,"hex")),i.write(Oe(r.verifier,"hex")),i.write(Oe(r.counterparty,"hex")),i.writeUInt8(r.protocolID[0]);const n=Oe(r.protocolID[1],"utf8");i.writeVarIntNum(n.length),i.write(n);const o=Oe(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 Ue;return c.writeUInt8(0),c.write(i.toArray()),c.toArray()}case"acquireCertificate":{const e={},t=a.read(32);e.type=Fe(t);const r=a.read(33);e.certifier=Ne(r);const i=a.readVarIntNum();e.fields={};for(let t=0;t<i;t++){const t=a.readVarIntNum(),r=a.read(t),i=Ae(r),n=a.readVarIntNum(),s=a.read(n),o=Ae(s);e.fields[i]=o}const n=a.readInt8();e.privileged=-1===n?void 0:1===n;const o=a.readInt8();if(-1===o)e.privilegedReason=void 0;else{const t=a.read(o);e.privilegedReason=Ae(t)}const c=a.readUInt8();if(e.acquisitionProtocol=1===c?"direct":"issuance","direct"===e.acquisitionProtocol){const t=a.read(32);e.serialNumber=Fe(t),e.revocationOutpoint=this.decodeOutpoint(a);const r=a.readVarIntNum(),i=a.read(r);e.signature=Ne(i);const n=a.readUInt8();if(11===n)e.keyringRevealer="certifier";else{const t=[n].concat(a.read(32));e.keyringRevealer=Ne(t)}const s=a.readVarIntNum();e.keyringForSubject={};for(let t=0;t<s;t++){const t=a.readVarIntNum(),r=a.read(t),i=Ae(r),n=a.readVarIntNum(),s=Fe(a.read(n));e.keyringForSubject[i]=s}}else{const t=a.readVarIntNum(),r=a.read(t);e.certifierUrl=Ae(r)}const d=await this.wallet.acquireCertificate(e,s),u=new Mr(d.type,d.serialNumber,d.subject,d.certifier,d.revocationOutpoint,d.fields,d.signature).toBinary(),h=new Ue;return h.writeUInt8(0),h.write(u),h.toArray()}case"listCertificates":{const e={},t=a.readVarIntNum();e.certifiers=[];for(let r=0;r<t;r++){const t=a.read(33);e.certifiers.push(Ne(t))}const r=a.readVarIntNum();e.types=[];for(let t=0;t<r;t++){const t=a.read(32);e.types.push(Fe(t))}const i=a.readVarIntNum();e.limit=i>=0?i:void 0;const n=a.readVarIntNum();e.offset=n>=0?n:void 0;const o=a.readInt8();e.privileged=-1===o?void 0:1===o;const c=a.readInt8();if(-1===c)e.privilegedReason=void 0;else{const t=a.read(c);e.privilegedReason=Ae(t)}const d=await this.wallet.listCertificates(e,s),u=new Ue;u.writeVarIntNum(d.totalCertificates);for(const e of d.certificates){const t=new Mr(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature).toBinary();u.writeVarIntNum(t.length),u.write(t)}const h=new Ue;return h.writeUInt8(0),h.write(u.toArray()),h.toArray()}case"proveCertificate":{const e={},t={},r=a.read(32);t.type=Fe(r);const i=a.read(33);t.subject=Ne(i);const n=a.read(32);t.serialNumber=Fe(n);const o=a.read(33);t.certifier=Ne(o),t.revocationOutpoint=this.decodeOutpoint(a);const c=a.readVarIntNum(),d=a.read(c);t.signature=Ne(d);const u=a.readVarIntNum();t.fields={};for(let e=0;e<u;e++){const e=a.readVarIntNum(),r=a.read(e),i=Ae(r),n=a.readVarIntNum(),s=a.read(n),o=Ae(s);t.fields[i]=o}e.certificate=t;const h=a.readVarIntNum();e.fieldsToReveal=[];for(let t=0;t<h;t++){const t=a.readVarIntNum(),r=a.read(t),i=Ae(r);e.fieldsToReveal.push(i)}const l=a.read(33);e.verifier=Ne(l);const f=a.readInt8();e.privileged=-1===f?void 0:1===f;const p=a.readInt8();if(-1===p)e.privilegedReason=void 0;else{const t=a.read(p);e.privilegedReason=Ae(t)}const b=await this.wallet.proveCertificate(e,s),w=new Ue,g=Object.entries(b.keyringForVerifier);w.writeVarIntNum(g.length);for(const[e,t]of g){const r=Oe(e,"utf8");w.writeVarIntNum(r.length),w.write(r);const i=Oe(t,"base64");w.writeVarIntNum(i.length),w.write(i)}const m=new Ue;return m.writeUInt8(0),m.write(w.toArray()),m.toArray()}case"relinquishCertificate":{const e={},t=a.read(32);e.type=Fe(t);const r=a.read(32);e.serialNumber=Fe(r);const i=a.read(33);e.certifier=Ne(i),await this.wallet.relinquishCertificate(e,s);const n=new Ue;return n.writeUInt8(0),n.toArray()}case"discoverByIdentityKey":{const e={},t=a.read(33);e.identityKey=Ne(t);const r=a.readVarIntNum();e.limit=r>=0?r:void 0;const i=a.readVarIntNum();e.offset=i>=0?i:void 0;const n=a.readInt8();e.seekPermission=n>=0?1===n:void 0;const o=await this.wallet.discoverByIdentityKey(e,s),c=this.serializeDiscoveryResult(o),d=new Ue;return d.writeUInt8(0),d.write(c),d.toArray()}case"discoverByAttributes":{const e={},t=a.readVarIntNum();e.attributes={};for(let r=0;r<t;r++){const t=a.readVarIntNum(),r=a.read(t),i=Ae(r),n=a.readVarIntNum(),s=a.read(n),o=Ae(s);e.attributes[i]=o}const r=a.readVarIntNum();e.limit=r>=0?r:void 0;const i=a.readVarIntNum();e.offset=i>=0?i:void 0;const n=a.readInt8();e.seekPermission=n>=0?1===n:void 0;const o=await this.wallet.discoverByAttributes(e,s),c=this.serializeDiscoveryResult(o),d=new Ue;return d.writeUInt8(0),d.write(c),d.toArray()}default:throw new Error(`Method ${r} not implemented`)}}catch(e){const t=new Ue;t.writeUInt8("number"==typeof e.code?e.code:1);const r="string"==typeof e.message?e.message:"Unknown error",i=Oe(r,"utf8");t.writeVarIntNum(i.length),t.write(i);const n="string"==typeof e.stack?e.stack:"",s=Oe(n,"utf8");return t.writeVarIntNum(s.length),t.write(s),t.toArray()}}decodeProtocolID(e){const t=e.readUInt8(),r=e.readVarIntNum(),i=e.read(r);return[t,Ae(i)]}decodeString(e){const t=e.readVarIntNum(),r=e.read(t);return Ae(r)}decodeCounterparty(e){const t=e.readUInt8();if(11===t)return"self";if(12===t)return"anyone";if(0!==t){const r=e.read(32);return Ne([t,...r])}}serializeDiscoveryResult(e){const t=new Ue;t.writeVarIntNum(e.totalCertificates);for(const r of e.certificates){const e=new Mr(r.type,r.serialNumber,r.subject,r.certifier,r.revocationOutpoint,r.fields,r.signaturre).toBinary();t.writeVarIntNum(e.length),t.write(e);const i=Oe(r.certifierInfo.name,"utf8");t.writeVarIntNum(i.length),t.write(i);const n=Oe(r.certifierInfo.iconUrl,"utf8");t.writeVarIntNum(n.length),t.write(n);const s=Oe(r.certifierInfo.description,"utf8");t.writeVarIntNum(s.length),t.write(s),t.writeUInt8(r.certifierInfo.trust);const a=Object.entries(r.publiclyRevealedKeyring);t.writeVarIntNum(a.length);for(const[e,r]of a){const i=Oe(e,"utf8");t.writeVarIntNum(i.length),t.write(i);const n=Oe(r,"base64");t.writeVarIntNum(n.length),t.write(n)}const o=Object.entries(r.decryptedFields);t.writeVarIntNum(o.length);for(const[e,r]of o){const i=Oe(e,"utf8");t.writeVarIntNum(i.length),t.write(i);const n=Oe(r,"utf8");t.writeVarIntNum(n.length),t.write(n)}}return t.toArray()}decodeKeyRelatedParams(e){const t={};t.protocolID=this.decodeProtocolID(e);const r=e.readVarIntNum(),i=e.read(r);t.keyID=Ae(i),t.counterparty=this.decodeCounterparty(e);const n=e.readInt8();t.privileged=-1===n?void 0:1===n;const s=e.readInt8();if(-1===s)t.privilegedReason=void 0;else{const r=e.read(s);t.privilegedReason=Ae(r)}return t}}class ei extends Mr{masterKeyring;constructor(e,t,r,i,n,s,a,o){super(e,t,r,i,n,s,o);for(const e of Object.keys(s))if(void 0===a[e]||""===a[e])throw new Error(`Master keyring must contain a value for every field. Missing or empty key for field: "${e}".`);this.masterKeyring=a}static async createCertificateFields(e,t,r,i,n){const s={},a={};for(const[o,c]of Object.entries(r)){const r=St.fromRandom(),d=r.encrypt(Oe(c,"utf8"));s[o]=Fe(d);const{ciphertext:u}=await e.encrypt({plaintext:r.toArray(),...Mr.getCertificateFieldEncryptionDetails(o),counterparty:t,privileged:i,privilegedReason:n});a[o]=Fe(u)}return{certificateFields:s,masterKeyring:a}}static async createKeyringForVerifier(e,t,r,i,n,s,a,o,c){if(!Array.isArray(n))throw new Error("fieldsToReveal must be an array of strings");const d={};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(e,s,u,i[u],t,o,c)).fieldRevelationKey,{ciphertext:h}=await e.encrypt({plaintext:n,...Mr.getCertificateFieldEncryptionDetails(u,a),counterparty:r,privileged:o,privilegedReason:c});d[u]=Fe(h)}return d}static async issueCertificateForSubject(e,t,r,i,n=async e=>"Certificate revocation not tracked.",s){const a=s??Fe(Ze(32)),{certificateFields:o,masterKeyring:c}=await this.createCertificateFields(e,t,r),d=await n(a),u=new ei(i,a,t,(await e.getPublicKey({identityKey:!0})).publicKey,d,o,c);return await u.sign(e),u}static async decryptFields(e,t,r,i,n,s){if(null==t||0===Object.keys(t).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(e,t,o,r[o],i,n,s)).decryptedFieldValue;return a}catch{throw new Error("Failed to decrypt all master certificate fields.")}}static async decryptField(e,t,r,i,n,s,a){if(null==t||0===Object.keys(t).length)throw new Error("A MasterCertificate must have a valid masterKeyring!");try{const{plaintext:o}=await e.decrypt({ciphertext:Oe(t[r],"base64"),...Mr.getCertificateFieldEncryptionDetails(r),counterparty:n,privileged:s,privilegedReason:a}),c=new St(o).decrypt(Oe(i,"base64"));return{fieldRevelationKey:o,decryptedFieldValue:Ae(c)}}catch{throw new Error("Failed to decrypt certificate field!")}}}class ti extends Mr{keyring;decryptedFields;constructor(e,t,r,i,n,s,a,o,c){super(e,t,r,i,n,s,o),this.keyring=a,this.decryptedFields=c}static fromCertificate(e,t){return new ti(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,t,e.signature)}async decryptFields(e,t,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 e.decrypt({ciphertext:Oe(this.keyring[n],"base64"),...Mr.getCertificateFieldEncryptionDetails(n,this.serialNumber),counterparty:this.subject,privileged:t,privilegedReason:r}),a=new St(s).decrypt(Oe(this.fields[n],"base64"));i[n]=Ae(a)}return i}catch(e){throw new Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(e instanceof Error?e.message:e)}`)}}}class ri extends Br{keyDeriver;constructor(e){if(super(e),e instanceof Vr)this.keyDeriver=e;else{if(!("string"==typeof e||e instanceof rt))throw new Error("Invalid key deriver provided");this.keyDeriver=new Vr(e)}}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(e){if(!0===e.privileged)throw new Error("no privilege support");if(!0===e.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==e.protocolID||"string"!=typeof e.keyID||""===e.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(e.protocolID,e.keyID,"string"==typeof e.counterparty&&""!==e.counterparty.trim()?e.counterparty:"self",Boolean(e.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 ii{sessionNonceToSession;identityKeyToNonces;constructor(){this.sessionNonceToSession=new Map,this.identityKeyToNonces=new Map}addSession(e){if("string"!=typeof e.sessionNonce)throw new Error("Invalid session: sessionNonce is required to add a session.");if(this.sessionNonceToSession.set(e.sessionNonce,e),"string"==typeof e.peerIdentityKey){let t=this.identityKeyToNonces.get(e.peerIdentityKey);null==t&&(t=new Set,this.identityKeyToNonces.set(e.peerIdentityKey,t)),t.add(e.sessionNonce)}}updateSession(e){this.removeSession(e),this.addSession(e)}getSession(e){const t=this.sessionNonceToSession.get(e);if(null!=t)return t;const r=this.identityKeyToNonces.get(e);if(null==r||0===r.size)return;let i;for(const e of r){const t=this.sessionNonceToSession.get(e);null!=t&&(null==i||(t.lastUpdate??0)>(i.lastUpdate??0))&&(i=t)}return i}removeSession(e){if("string"==typeof e.sessionNonce&&this.sessionNonceToSession.delete(e.sessionNonce),"string"==typeof e.peerIdentityKey){const t=this.identityKeyToNonces.get(e.peerIdentityKey);null!=t&&(t.delete(e.sessionNonce??""),0===t.size&&this.identityKeyToNonces.delete(e.peerIdentityKey))}}hasSession(e){if(this.sessionNonceToSession.has(e))return!0;const t=this.identityKeyToNonces.get(e);return!(null==t)&&t.size>0}}async function ni(e,t,r="self"){const i=Oe(e,"base64"),n=i.slice(0,16),s=i.slice(16),{valid:a}=await t.verifyHmac({data:n,hmac:s,protocolID:[2,"server hmac"],keyID:Ae(n),counterparty:r});return a}async function si(e,t="self"){const r=Ze(16),{hmac:i}=await e.createHmac({protocolID:[2,"server hmac"],keyID:Ae(r),data:r,counterparty:t});return Fe([...r,...i])}const ai=async(e,t,r)=>{const i=await e.listCertificates({certifiers:t.certifiers,types:Object.keys(t.types)});return await Promise.all(i.certificates.map((async i=>{const{keyringForVerifier:n}=await e.proveCertificate({certificate:i,fieldsToReveal:t.types[i.type],verifier:r});return new ti(i.type,i.serialNumber,i.subject,i.certifier,i.revocationOutpoint,i.fields,n,i.signature)})))},oi=async(e,t,r)=>{if(null==t.certificates||0===t.certificates.length)throw new Error("No certificates were provided in the AuthMessage.");await Promise.all(t.certificates.map((async i=>{if(i.subject!==t.identityKey)throw new Error(`The subject of one of your certificates ("${i.subject}") is not the same as the request sender ("${t.identityKey}").`);const n=new ti(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:e,types:t}=r;if(!e.includes(n.certifier))throw new Error(`Certificate with serial number ${n.serialNumber} has an unrequested certifier: ${n.certifier}`);if(null==t[n.type])throw new Error(`Certificate with type ${n.type} was not requested`)}await n.decryptFields(e)})))},ci="0.1";class di{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;constructor(e,t,r,i,n){this.wallet=e,this.transport=t,this.certificatesToRequest=r??{certifiers:[],types:{}},this.transport.onData(this.handleIncomingMessage.bind(this)).catch((e=>{throw e})),this.sessionManager=null!=i?i:new ii,this.autoPersistLastSession=!1!==n}async toPeer(e,t,r){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);const i=await this.getAuthenticatedSession(t,r),n=Fe(Ze(32)),{signature:s}=await this.wallet.createSignature({data:e,protocolID:[2,"auth message signature"],keyID:`${n} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey}),a={version:ci,messageType:"general",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,nonce:n,yourNonce:i.peerNonce,payload:e,signature:s};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(a)}catch(e){const t=new Error(`Failed to send message to peer ${i.peerIdentityKey??"unknown"}: ${String(e.message)}`);throw t.stack=e.stack,t}}async requestCertificates(e,t,r=1e4){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);const i=await this.getAuthenticatedSession(t,r),n=Fe(Ze(32)),{signature:s}=await this.wallet.createSignature({data:Oe(JSON.stringify(e),"utf8"),protocolID:[2,"auth message signature"],keyID:`${n} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey}),a={version:ci,messageType:"certificateRequest",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,nonce:n,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,requestedCertificates:e,signature:s};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(a)}catch(e){throw new Error(`Failed to send certificate request message to peer ${i.peerIdentityKey??"unknown"}: ${String(e.message)}`)}}async getAuthenticatedSession(e,t){if(void 0===this.transport)throw new Error("Peer transport is not connected!");let r;if("string"==typeof e&&(r=this.sessionManager.getSession(e)),null==r||!r.isAuthenticated){const i=await this.initiateHandshake(e,t);if(r=this.sessionManager.getSession(i),null==r||!r.isAuthenticated)throw new Error("Unable to establish mutual authentication with peer!")}return r}listenForGeneralMessages(e){const t=this.callbackIdCounter++;return this.onGeneralMessageReceivedCallbacks.set(t,e),t}stopListeningForGeneralMessages(e){this.onGeneralMessageReceivedCallbacks.delete(e)}listenForCertificatesReceived(e){const t=this.callbackIdCounter++;return this.onCertificatesReceivedCallbacks.set(t,e),t}stopListeningForCertificatesReceived(e){this.onCertificatesReceivedCallbacks.delete(e)}listenForCertificatesRequested(e){const t=this.callbackIdCounter++;return this.onCertificateRequestReceivedCallbacks.set(t,e),t}stopListeningForCertificatesRequested(e){this.onCertificateRequestReceivedCallbacks.delete(e)}async initiateHandshake(e,t=1e4){const r=await si(this.wallet),i=Date.now();this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:r,peerIdentityKey:e,lastUpdate:i});const n={version:ci,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,t)}async waitForInitialResponse(e,t=1e4){return await new Promise(((r,i)=>{const n=this.listenForInitialResponse(e,(e=>{clearTimeout(s),this.stopListeningForInitialResponses(n),r(e)})),s=setTimeout((()=>{this.stopListeningForInitialResponses(n),i(new Error("Initial response timed out."))}),t)}))}listenForInitialResponse(e,t){const r=this.callbackIdCounter++;return this.onInitialResponseReceivedCallbacks.set(r,{callback:t,sessionNonce:e}),r}stopListeningForInitialResponses(e){this.onInitialResponseReceivedCallbacks.delete(e)}async handleIncomingMessage(e){if("string"!=typeof e.version||e.version!==ci)throw new Error(`Invalid or unsupported message auth version! Received: ${e.version}, expected: ${ci}`);switch(e.messageType){case"initialRequest":await this.processInitialRequest(e);break;case"initialResponse":await this.processInitialResponse(e);break;case"certificateRequest":await this.processCertificateRequest(e);break;case"certificateResponse":await this.processCertificateResponse(e);break;case"general":await this.processGeneralMessage(e);break;default:throw new Error(`Unknown message type of ${String(e.messageType)} from ${String(e.identityKey)}`)}}async processInitialRequest(e){if("string"!=typeof e.identityKey||"string"!=typeof e.initialNonce||""===e.initialNonce)throw new Error("Missing required fields in initialRequest message.");const t=await si(this.wallet),r=Date.now();let i;this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:t,peerNonce:e.initialNonce,peerIdentityKey:e.identityKey,lastUpdate:r}),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach((t=>{t(e.identityKey,e.requestedCertificates)})):i=await ai(this.wallet,e.requestedCertificates,e.identityKey));const{signature:n}=await this.wallet.createSignature({data:Oe(e.initialNonce+t,"base64"),protocolID:[2,"auth message signature"],keyID:`${e.initialNonce} ${t}`,counterparty:e.identityKey}),s={version:ci,messageType:"initialResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,initialNonce:t,yourNonce:e.initialNonce,certificates:i,requestedCertificates:this.certificatesToRequest,signature:n};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=e.identityKey),await this.transport.send(s)}async processInitialResponse(e){if(!await ni(e.yourNonce,this.wallet))throw new Error(`Initial response nonce verification failed from peer: ${e.identityKey}`);const t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw new Error(`Peer session not found for peer: ${e.identityKey}`);const r=Oe((t.sessionNonce??"")+(e.initialNonce??""),"base64"),{valid:i}=await this.wallet.verifySignature({data:r,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${t.sessionNonce??""} ${e.initialNonce??""}`,counterparty:e.identityKey});if(!i)throw new Error(`Unable to verify initial response signature for peer: ${e.identityKey}`);if(t.peerNonce=e.initialNonce,t.peerIdentityKey=e.identityKey,t.isAuthenticated=!0,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.certificatesToRequest?.certifiers?.length>0&&e.certificates?.length>0&&(await oi(this.wallet,e,this.certificatesToRequest),this.onCertificatesReceivedCallbacks.forEach((t=>t(e.identityKey,e.certificates)))),this.lastInteractedWithPeer=e.identityKey,this.onInitialResponseReceivedCallbacks.forEach((e=>{e.sessionNonce===t.sessionNonce&&e.callback(t.sessionNonce)})),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach((t=>{t(e.identityKey,e.requestedCertificates)}));else{const t=await ai(this.wallet,e.requestedCertificates,e.identityKey);await this.sendCertificateResponse(e.identityKey,t)}}async processCertificateRequest(e){if(!await ni(e.yourNonce,this.wallet))throw new Error(`Unable to verify nonce for certificate request message from: ${e.identityKey}`);const t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw new Error(`Session not found for nonce: ${e.yourNonce}`);const{valid:r}=await this.wallet.verifySignature({data:Oe(JSON.stringify(e.requestedCertificates),"utf8"),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey});if(!r)throw new Error(`Invalid signature in certificate request message from ${t.peerIdentityKey}`);if(t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach((t=>{t(e.identityKey,e.requestedCertificates)}));else{const t=await ai(this.wallet,e.requestedCertificates,e.identityKey);await this.sendCertificateResponse(e.identityKey,t)}}async sendCertificateResponse(e,t){const r=await this.getAuthenticatedSession(e),i=Fe(Ze(32)),{signature:n}=await this.wallet.createSignature({data:Oe(JSON.stringify(t),"utf8"),protocolID:[2,"auth message signature"],keyID:`${i} ${r.peerNonce??""}`,counterparty:r.peerIdentityKey}),s={version:ci,messageType:"certificateResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,nonce:i,initialNonce:r.sessionNonce,yourNonce:r.peerNonce,certificates:t,signature:n};r.lastUpdate=Date.now(),this.sessionManager.updateSession(r);try{await this.transport.send(s)}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`Failed to send certificate response message to peer ${r.peerIdentityKey??"unknown"}: ${t}`)}}async processCertificateResponse(e){if(!await ni(e.yourNonce,this.wallet))throw new Error(`Unable to verify nonce for certificate response from: ${e.identityKey}`);const t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw new Error(`Session not found for nonce: ${e.yourNonce}`);const{valid:r}=await this.wallet.verifySignature({data:Oe(JSON.stringify(e.certificates),"utf8"),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:e.identityKey});if(!r)throw new Error(`Unable to verify certificate response signature for peer: ${e.identityKey}`);await oi(this.wallet,e,e.requestedCertificates),this.onCertificatesReceivedCallbacks.forEach((t=>{t(e.identityKey,e.certificates??[])})),t.lastUpdate=Date.now(),this.sessionManager.updateSession(t)}async processGeneralMessage(e){if(!await ni(e.yourNonce,this.wallet))throw new Error(`Unable to verify nonce for general message from: ${e.identityKey}`);const t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw new Error(`Session not found for nonce: ${e.yourNonce}`);const{valid:r}=await this.wallet.verifySignature({data:e.payload,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey});if(!r)throw new Error(`Invalid signature in generalMessage from ${t.peerIdentityKey}`);t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.lastInteractedWithPeer=e.identityKey,this.onGeneralMessageReceivedCallbacks.forEach((t=>{t(e.identityKey,e.payload??[])}))}}const ui="undefined"!=typeof window?fetch.bind(window):fetch;class hi{onDataCallback;fetchClient;baseUrl;constructor(e,t=ui){this.fetchClient=t,this.baseUrl=e}async send(e){if(!this.onDataCallback)throw new Error("Listen before you start speaking. God gave you two ears and one mouth for a reason.");if("general"!==e.messageType)return new Promise((async(t,r)=>{try{const r=this.fetchClient(`${this.baseUrl}/.well-known/auth`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});"initialRequest"!==e.messageType&&t();const i=await r;if(!i.ok||!this.onDataCallback)throw new Error("HTTP server failed to authenticate");{const e=await i.json();this.onDataCallback(e)}"initialRequest"===e.messageType&&t()}catch(e){return void r(e)}}));{const t=this.deserializeRequestPayload(e.payload),r=`${this.baseUrl}${t.urlPostfix}`;let i=t;if("object"!=typeof t.headers&&(i.headers={}),i.headers["x-bsv-auth-version"]=e.version,i.headers["x-bsv-auth-identity-key"]=e.identityKey,i.headers["x-bsv-auth-nonce"]=e.nonce,i.headers["x-bsv-auth-your-nonce"]=e.yourNonce,i.headers["x-bsv-auth-signature"]=Ne(e.signature),i.headers["x-bsv-auth-request-id"]=t.requestId,i.body){const e=i.headers;if(!e["content-type"])throw new Error("Content-Type header is required for requests with a body.");const t=e["content-type"];t.includes("application/json")||t.includes("application/x-www-form-urlencoded")||t.includes("text/plain")?i.body=Ae(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&&null==n.headers.get("x-bsv-auth-request-id")&&null==n.headers.get("x-bsv-auth-requested-certificates")){const e=await n.json();throw new Error(`HTTP ${n.status} - ${JSON.stringify(e)}`)}const s=await n.arrayBuffer(),a=new Ue;null!=n.headers.get("x-bsv-auth-request-id")&&a.write(Oe(n.headers.get("x-bsv-auth-request-id"),"base64")),a.writeVarIntNum(n.status);const o=[];n.headers.forEach(((e,t)=>{const r=t.toLowerCase();!r.startsWith("x-bsv-")&&"authorization"!==r||r.startsWith("x-bsv-auth")||o.push([r,e])})),o.sort((([e],[t])=>e.localeCompare(t))),a.writeVarIntNum(o.length);for(let e=0;e<o.length;e++){const t=Oe(o[e][0],"utf8");a.writeVarIntNum(t.length),a.write(t);const r=Oe(o[e][1],"utf8");a.writeVarIntNum(r.length),a.write(r)}if(s){const e=Array.from(new Uint8Array(s));a.writeVarIntNum(e.length),a.write(e)}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:Oe(n.headers.get("x-bsv-auth-signature"),"hex")};if(!c.version)throw new Error("HTTP server failed to authenticate");this.onDataCallback(c)}}async onData(e){this.onDataCallback=t=>{e(t)}}deserializeRequestPayload(e){const t=new Le(e),r=Fe(t.read(32)),i=t.readVarIntNum();let n="GET";i>0&&(n=Ae(t.read(i)));const s=t.readVarIntNum();let a="";s>0&&(a=Ae(t.read(s)));const o=t.readVarIntNum();let c="";o>0&&(c=Ae(t.read(o)));const d={},u=t.readVarIntNum();if(u>0)for(let e=0;e<u;e++){const e=t.readVarIntNum(),r=t.read(e),i=Ae(r),n=t.readVarIntNum(),s=t.read(n),a=Ae(s);d[i]=a}let h;const l=t.readVarIntNum();return l>0&&(h=t.read(l)),{urlPostfix:a+c,method:n,headers:d,body:h,requestId:r}}}class li{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;peers={};constructor(e,t,r){this.wallet=e,this.requestedCertificates=t,this.sessionManager=r||new ii}async fetch(e,t={}){if("number"==typeof t.retryCounter){if(t.retryCounter<=0)throw new Error("Request failed after maximum number of retries.");t.retryCounter--}const r=await new Promise((async(r,i)=>{try{const{method:n="GET",headers:s={},body:a}=t,o=new URL(e),c=o.origin;let d;if(void 0===this.peers[c]){const e=new hi(c);d={peer:new di(this.wallet,e,this.requestedCertificates,this.sessionManager),pendingCertificateRequests:[]},this.peers[c]=d,this.peers[c].peer.listenForCertificatesReceived(((e,t)=>{this.certificatesReceived.push(...t)})),this.peers[c].peer.listenForCertificatesRequested((async(e,t)=>{try{this.peers[c].pendingCertificateRequests.push(!0);const r=await ai(this.wallet,t,e);await this.peers[c].peer.sendCertificateResponse(e,r)}finally{await new Promise((e=>setTimeout(e,500))),this.peers[c].pendingCertificateRequests.shift()}}))}else{if(!1===this.peers[c].supportsMutualAuth){try{const i=await this.handleFetchAndValidate(e,t,this.peers[c]);r(i)}catch(e){i(e)}return}d=this.peers[c]}const u=Ze(32),h=Fe(u),l=await this.serializeRequest(n,s,a,o,u);this.callbacks[h]={resolve:r,reject:i};const f=d.peer.listenForGeneralMessages(((e,t)=>{const r=new Le(t);if(Fe(r.read(32))!==h)return;d.peer.stopListeningForGeneralMessages(f),this.peers[c].identityKey=e,this.peers[c].supportsMutualAuth=!0;const i=r.readVarIntNum(),n={},s=r.readVarIntNum();if(s>0)for(let e=0;e<s;e++){const e=r.readVarIntNum(),t=r.read(e),i=Ae(t),s=r.readVarIntNum(),a=r.read(s),o=Ae(a);n[i]=o}let a;n["x-bsv-auth-identity-key"]=e;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[h].resolve(u),delete this.callbacks[h]}));d.pendingCertificateRequests.length>0&&await new Promise((e=>{setInterval((()=>{0===d.pendingCertificateRequests.length&&e()}),100)})),await d.peer.toPeer(l.toArray(),d.identityKey).catch((async n=>{if(n.message.includes("Session not found for nonce")){delete this.peers[c],t.retryCounter??=3;const i=await this.fetch(e,t);r(i)}else if(n.message.includes("HTTP server failed to authenticate"))try{const i=await this.handleFetchAndValidate(e,t,d);return void r(i)}catch(e){i(e)}else i(n)}))}catch(e){i(e)}}));return 402===r.status?await this.handlePaymentAndRetry(e,t,r):r}async sendCertificateRequest(e,t){const r=new URL(e).origin;let i;if(void 0!==this.peers[r])i={peer:this.peers[r].peer};else{const e=new hi(r);i={peer:new di(this.wallet,e,this.requestedCertificates,this.sessionManager)},this.peers[r]=i}return await new Promise((async(e,r)=>{const n=i.peer.listenForCertificatesReceived(((t,r)=>{i.peer.stopListeningForCertificatesReceived(n),this.certificatesReceived.push(...r),e(r)}));try{await i.peer.requestCertificates(t,i.identityKey)}catch(e){i.peer.stopListeningForCertificatesReceived(n),r(e)}}))}consumeReceivedCertificates(){return this.certificatesReceived.splice(0)}async serializeRequest(e,t,r,i,n){const s=new Ue;if(s.write(n),s.writeVarIntNum(e.length),s.write(Oe(e)),i.pathname.length>0){const e=Oe(i.pathname);s.writeVarIntNum(e.length),s.write(e)}else s.writeVarIntNum(-1);if(i.search.length>0){const e=Oe(i.search);s.writeVarIntNum(e.length),s.write(e)}else s.writeVarIntNum(-1);const a=[];for(let[e,r]of Object.entries(t))if(e=e.toLowerCase(),e.startsWith("x-bsv-")||"authorization"===e){if(e.startsWith("x-bsv-auth"))throw new Error("No BSV auth headers allowed here!");a.push([e,r])}else{if(!e.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([e,r])}a.sort((([e],[t])=>e.localeCompare(t))),s.writeVarIntNum(a.length);for(let e=0;e<a.length;e++){const t=Oe(a[e][0],"utf8");s.writeVarIntNum(t.length),s.write(t);const r=Oe(a[e][1],"utf8");s.writeVarIntNum(r.length),s.write(r)}if(["POST","PUT","PATCH","DELETE"].includes(e.toUpperCase())&&void 0===r){const e=a.find((([e])=>"content-type"===e));r=e&&e[1].includes("application/json")?"{}":""}if(r){const e=await this.normalizeBodyToNumberArray(r);s.writeVarIntNum(e.length),s.write(e)}else s.writeVarIntNum(-1);return s}async handleFetchAndValidate(e,t,r){const i=await fetch(e,t);if(i.headers.forEach((e=>{if(e.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(e,t={},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 si(this.wallet),{publicKey:d}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${o} ${c}`,counterparty:a}),u=(new Ut).lock(Ge.fromString(d).toAddress()).toHex(),{tx:h}=await this.wallet.createAction({description:`Payment for request to ${new URL(e).origin}`,outputs:[{satoshis:s,lockingScript:u,customInstructions:JSON.stringify({derivationPrefix:o,derivationSuffix:c,payee:a}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}});return t.headers=t.headers||{},t.headers["x-bsv-payment"]=JSON.stringify({derivationPrefix:o,derivationSuffix:c,transaction:Fe(h)}),t.retryCounter??=3,this.fetch(e,t)}async normalizeBodyToNumberArray(e){if(null==e)return[];if("object"==typeof e)return Oe(JSON.stringify(e,"utf8"));if(Array.isArray(e)&&e.every((e=>"number"==typeof e)))return e;if("string"==typeof e)return Oe(e,"utf8");if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){const t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer);return Array.from(t)}if(e instanceof Blob){const t=await e.arrayBuffer();return Array.from(new Uint8Array(t))}if(e instanceof FormData){const t=[];e.forEach(((e,r)=>{t.push([r,e.toString()])}));const r=new URLSearchParams(t).toString();return Oe(r,"utf8")}if(e instanceof URLSearchParams)return Oe(e.toString(),"utf8");if(e instanceof ReadableStream)throw new Error("ReadableStream cannot be directly converted to number[].");throw new Error("Unsupported body type in this SimplifiedFetch implementation.")}}class fi{pushDrop;static decode(e){const t=Ht.decode(e);if(t.fields.length<4)throw new Error("Invalid SHIP/SLAP advertisement!");const r=Ae(t.fields[0]);if("SHIP"!==r&&"SLAP"!==r)throw new Error("Invalid protocol type!");return{protocol:r,identityKey:Ne(t.fields[1]),domain:Ae(t.fields[2]),topicOrService:Ae(t.fields[3])}}constructor(e){this.pushDrop=new Ht(e)}async lock(e,t,r){const{publicKey:i}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([Oe(e,"utf8"),Oe(i,"hex"),Oe(t,"utf8"),Oe(r,"utf8")],[2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}unlock(e){return this.pushDrop.unlock([2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}}const pi=["https://users.bapp.dev"],bi=["https://testnet-users.bapp.dev"];class wi{fetchClient;allowHTTP;constructor(e=fetch,t=!1){this.fetchClient=e,this.allowHTTP=t}async lookup(e,t,r=5e3){if(!e.startsWith("https:")&&!this.allowHTTP)throw new Error('HTTPS facilitator can only use URLs that start with "https:"');const i=new Promise(((e,t)=>setTimeout((()=>t(new Error("Request timed out"))),r))),n=fetch(`${e}/lookup`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:t.service,query:t.query})}),s=await Promise.race([n,i]);if(s.ok)return await s.json();throw new Error("Failed to facilitate lookup")}}class gi{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;constructor(e={}){this.networkPreset=e.networkPreset??"mainnet",this.facilitator=e.facilitator??new wi(void 0,"local"===this.networkPreset),this.slapTrackers=e.slapTrackers??("mainnet"===this.networkPreset?pi:bi),this.hostOverrides=e.hostOverrides??{},this.additionalHosts=e.additionalHosts??{}}async query(e,t){let r=[];if(r="ls_slap"===e.service?"local"===this.networkPreset?["http://localhost:8080"]:this.slapTrackers:null!=this.hostOverrides[e.service]?this.hostOverrides[e.service]:"local"===this.networkPreset?["http://localhost:8080"]:await this.findCompetentHosts(e.service),this.additionalHosts[e.service]?.length>0&&(r=[...r,...this.additionalHosts[e.service]]),r.length<1)throw new Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${e.service}`);const i=(await Promise.allSettled(r.map((async r=>await this.facilitator.lookup(r,e,t))))).filter((e=>"fulfilled"===e.status)).map((e=>e.value));if(0===i.length)throw new Error("No successful responses from any hosts");const n=new Map;for(const e of i)if("output-list"===e.type)try{for(const t of e.outputs)try{const e=`${sr.fromBEEF(t.beef).id("hex")}.${t.outputIndex}`;n.set(e,t)}catch{continue}}catch(e){}return{type:"output-list",outputs:Array.from(n.values())}}async findCompetentHosts(e){const t={service:"ls_slap",query:{service:e}},r=await Promise.allSettled(this.slapTrackers.map((async e=>await this.facilitator.lookup(e,t,5e3)))),i=new Set;for(const t of r)if("fulfilled"===t.status){const r=t.value;if("output-list"!==r.type)continue;for(const t of r.outputs)try{const r=sr.fromBEEF(t.beef).outputs[t.outputIndex].lockingScript,n=fi.decode(r);if(n.topicOrService!==e||"SLAP"!==n.protocol)continue;i.add(n.domain)}catch{continue}}return[...i]}}class mi{httpClient;allowHTTP;constructor(e=fetch,t=!1){this.httpClient=e,this.allowHTTP=t}async send(e,t){if(!e.startsWith("https:")&&!this.allowHTTP)throw new Error('HTTPS facilitator can only use URLs that start with "https:"');const r={"Content-Type":"application/octet-stream","X-Topics":JSON.stringify(t.topics)};let i;if(Array.isArray(t.offChainValues)){r["x-includes-off-chain-values"]="true";const e=new Ue;e.writeVarIntNum(t.beef.length),e.write(t.beef),e.write(t.offChainValues),i=new Uint8Array(e.toArray())}else i=new Uint8Array(t.beef);const n=await fetch(`${e}/submit`,{method:"POST",headers:r,body:i});if(n.ok)return await n.json();throw new Error("Failed to facilitate broadcast")}}class yi{topics;facilitator;resolver;requireAcknowledgmentFromAllHostsForTopics;requireAcknowledgmentFromAnyHostForTopics;requireAcknowledgmentFromSpecificHostsForTopics;networkPreset;constructor(e,t={}){if(0===e.length)throw new Error("At least one topic is required for broadcast.");if(e.some((e=>!e.startsWith("tm_"))))throw new Error('Every topic must start with "tm_".');this.topics=e,this.networkPreset=t.networkPreset??"mainnet",this.facilitator=t.facilitator??new mi(void 0,"local"===this.networkPreset),this.resolver=t.resolver??new gi({networkPreset:this.networkPreset}),this.requireAcknowledgmentFromAllHostsForTopics=t.requireAcknowledgmentFromAllHostsForTopics??[],this.requireAcknowledgmentFromAnyHostForTopics=t.requireAcknowledgmentFromAnyHostForTopics??"all",this.requireAcknowledgmentFromSpecificHostsForTopics=t.requireAcknowledgmentFromSpecificHostsForTopics??{}}async broadcast(e){let t;const r=e.metadata.get("OffChainValues");try{t=e.toBEEF()}catch(e){throw new Error("Transactions sent via SHIP to Overlay Services must be serializable to BEEF format.")}const i=await this.findInterestedHosts();if(0===Object.keys(i).length)return{status:"error",code:"ERR_NO_HOSTS_INTERESTED",description:`No ${this.networkPreset} hosts are interested in receiving this transaction.`};const n=Object.entries(i).map((async([e,i])=>{try{const n=await this.facilitator.send(e,{beef:t,offChainValues:r,topics:[...i]});if(null==n||0===Object.keys(n).length)throw new Error("Steak has no topics.");return{host:e,success:!0,steak:n}}catch(t){return console.error(t),{host:e,success:!1,error:t}}})),s=(await Promise.all(n)).filter((e=>e.success));if(0===s.length)return{status:"error",code:"ERR_ALL_HOSTS_REJECTED",description:`All ${this.networkPreset} topical hosts have rejected the transaction.`};const a={};for(const e of s){const t=e.host,r=e.steak,i=new Set;for(const[e,t]of Object.entries(r)){const r=t.outputsToAdmit,n=t.coinsToRetain,s=t.coinsRemoved;(r?.length>0||n?.length>0||s?.length>0)&&i.add(e)}a[t]=i}let o,c,d,u;return"all"===this.requireAcknowledgmentFromAllHostsForTopics?(o=this.topics,c="all"):"any"===this.requireAcknowledgmentFromAllHostsForTopics?(o=this.topics,c="any"):Array.isArray(this.requireAcknowledgmentFromAllHostsForTopics)?(o=this.requireAcknowledgmentFromAllHostsForTopics,c="all"):(o=this.topics,c="all"),o.length>0&&!this.checkAcknowledgmentFromAllHosts(a,o,c)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ALL_HOSTS_FAILED",description:"Not all hosts acknowledged the required topics."}:("all"===this.requireAcknowledgmentFromAnyHostForTopics?(d=this.topics,u="all"):"any"===this.requireAcknowledgmentFromAnyHostForTopics?(d=this.topics,u="any"):Array.isArray(this.requireAcknowledgmentFromAnyHostForTopics)?(d=this.requireAcknowledgmentFromAnyHostForTopics,u="all"):(d=[],u="all"),d.length>0&&!this.checkAcknowledgmentFromAnyHost(a,d,u)?{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(a,this.requireAcknowledgmentFromSpecificHostsForTopics)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_SPECIFIC_HOSTS_FAILED",description:"Specific hosts did not acknowledge the required topics."}:{status:"success",txid:e.id("hex"),message:`Sent to ${s.length} Overlay Services ${1===s.length?"host":"hosts"}.`})}checkAcknowledgmentFromAllHosts(e,t,r){for(const i of Object.values(e))if("all"===r){for(const e of t)if(!i.has(e))return!1}else if("any"===r){let e=!1;for(const r of t)if(i.has(r)){e=!0;break}if(!e)return!1}return!0}checkAcknowledgmentFromAnyHost(e,t,r){if("all"===r){for(const r of Object.values(e)){let e=!0;for(const i of t)if(!r.has(i)){e=!1;break}if(e)return!0}return!1}for(const r of Object.values(e))for(const e of t)if(r.has(e))return!0;return!1}checkAcknowledgmentFromSpecificHosts(e,t){for(const[r,i]of Object.entries(t)){const t=e[r];if(null==t)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 e of n)if(!t.has(e))return!1}else if("any"===s){let e=!1;for(const r of n)if(t.has(r)){e=!0;break}if(!e)return!1}}return!0}async findInterestedHosts(){if("local"===this.networkPreset){const e=new Set;for(let t=0;t<this.topics.length;t++)e.add(this.topics[t]);return{"http://localhost:8080":e}}const e={},t=await this.resolver.query({service:"ls_ship",query:{topics:this.topics}},5e3);if("output-list"!==t.type)throw new Error("SHIP answer is not an output list.");for(const r of t.outputs)try{const t=sr.fromBEEF(r.beef).outputs[r.outputIndex].lockingScript,i=fi.decode(t);if(!this.topics.includes(i.topicOrService)||"SHIP"!==i.protocol)continue;void 0===e[i.domain]&&(e[i.domain]=new Set),e[i.domain].add(i.topicOrService)}catch(e){continue}return e}}const Ii=e=>(e.toLowerCase().startsWith("uhrp:")&&(e=e.slice(5)),e.startsWith("//")&&(e=e.slice(2)),e),vi=e=>{if(32!==e.length)throw new Error("Hash length must be 32 bytes (sha256)");return De(e,Oe("ce00","hex"))},ki=e=>{const t=me(e);return vi(t)},Si=e=>{e=Ii(e);const{data:t,prefix:r}=Be(e,void 0,2);if(32!==t.length)throw new Error("Invalid length!");if("ce00"!==Ne(r))throw new Error("Bad prefix");return t},Ei=e=>{try{return Si(e),!0}catch(e){return!1}};class Pi{authFetch;baseURL;constructor(e){this.baseURL=e.storageURL,this.authFetch=new li(e.wallet)}async getUploadInfo(e,t){const r=`${this.baseURL}/upload`,i={fileSize:e,retentionPeriod:t},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(e,t,r){const i=Uint8Array.from(t.data),n=await fetch(e,{method:"PUT",body:i,headers:{"Content-Type":t.type,...r}});if(!n.ok)throw new Error(`File upload failed: HTTP ${n.status}`);return{published:!0,uhrpURL:await ki(t.data)}}async publishFile(e){const{file:t,retentionPeriod:r}=e,i=t.data.length,{uploadURL:n,requiredHeaders:s}=await this.getUploadInfo(i,r);return await this.uploadFile(n,t,s)}async findFile(e){const t=new URL(`${this.baseURL}/find`);t.searchParams.set("uhrpUrl",e);const r=await this.authFetch.fetch(t.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 e=i.code??"unknown-code",t=i.description??"no-description";throw new Error(`findFile returned an error: ${e} - ${t}`)}return i.data}async listUploads(){const e=`${this.baseURL}/list`,t=await this.authFetch.fetch(e,{method:"GET"});if(!t.ok)throw new Error(`listUploads request failed: HTTP ${t.status}`);const r=await t.json();if("error"===r.status){const e=r.code??"unknown-code",t=r.description??"no-description";throw new Error(`listUploads returned an error: ${e} - ${t}`)}return r.uploads}async renewFile(e,t){const r=`${this.baseURL}/renew`,i={uhrpUrl:e,additionalMinutes:t},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 e=s.code??"unknown-code",t=s.description??"no-description";throw new Error(`renewFile returned an error: ${e} - ${t}`)}return{status:s.status,prevExpiryTime:s.prevExpiryTime,newExpiryTime:s.newExpiryTime,amount:s.amount}}}class Ni{networkPreset="mainnet";constructor(e){this.networkPreset=e?.networkPreset}async resolve(e){const t=new gi({networkPreset:this.networkPreset}),r=await t.query({service:"ls_uhrp",query:{uhrpUrl:e}});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 e=0;e<r.outputs.length;e++){const t=sr.fromBEEF(r.outputs[e].beef),{fields:s}=Ht.decode(t.outputs[r.outputs[e].outputIndex].lockingScript);new Le(s[3]).readVarIntNum()<n||i.push(Ae(s[2]))}return i}async download(e){if(!Ei(e))throw new Error("Invalid parameter UHRP url");const t=Si(e),r=await this.resolve(e);if(!Array.isArray(r)||0===r.length)throw new Error("No one currently hosts this file!");for(let e=0;e<r.length;e++)try{const i=await fetch(r[e],{method:"GET"});if(!i.ok||i.status>=400)continue;const n=await i.arrayBuffer(),s=[...new Uint8Array(n)],a=me(s);for(let e=0;e<a.length;++e)if(a[e]!==t[e])throw new Error("Value of content does not match hash of the url given");return{data:s,mimeType:i.headers.get("Content-Type")}}catch(e){continue}throw new Error(`Unable to download content from ${e}`)}}const Oi={name:"Unknown Identity",avatarURL:"XUUB8bbn9fEthk15Ge3zTQXypUShfC94vFjp65v7u5CQ8qkpxzst",identityKey:"",abbreviatedKey:"",badgeIconURL:"XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",badgeLabel:"Not verified by anyone you trust.",badgeClickURL:"https://projectbabbage.com/docs/unknown-identity"},_i={protocolID:[1,"identity"],keyID:"1",tokenAmount:1,outputIndex:0},xi={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 Ai{options;originator;authClient;wallet;constructor(e,t=_i,r){this.options=t,this.originator=r,this.wallet=e??new Zr,this.authClient=new li(this.wallet)}async publiclyRevealAttributes(e,t){if(0===Object.keys(e.fields).length)throw new Error("Public reveal failed: Certificate has no fields to reveal!");if(0===t.length)throw new Error("Public reveal failed: You must reveal at least one field!");try{const t=new Mr(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature);await t.verify()}catch(e){throw new Error("Public reveal failed: Certificate verification failed!")}const{keyringForVerifier:r}=await this.wallet.proveCertificate({certificate:e,fieldsToReveal:t,verifier:new rt(1).toPublicKey().toString()}),i=await new Ht(this.wallet).lock([Oe(JSON.stringify({...e,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 e=new yi(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network});return await e.broadcast(sr.fromAtomicBEEF(n))}throw new Error("Public reveal failed: failed to create action!")}async resolveByIdentityKey(e){const{certificates:t}=await this.wallet.discoverByIdentityKey(e,this.originator);return t.map((e=>Ai.parseIdentity(e)))}async resolveByAttributes(e){const{certificates:t}=await this.wallet.discoverByAttributes(e,this.originator);return t.map((e=>Ai.parseIdentity(e)))}static parseIdentity(e){const{type:t,decryptedFields:r,certifierInfo:i}=e;let n,s,a,o,c;switch(t){case xi.xCert:n=r.userName,s=r.profilePhoto,a=`X account certified by ${i.name}`,o=i.iconUrl,c="https://socialcert.net";break;case xi.discordCert:n=r.userName,s=r.profilePhoto,a=`Discord account certified by ${i.name}`,o=i.iconUrl,c="https://socialcert.net";break;case xi.emailCert:n=r.email,s="XUTZxep7BBghAJbSBwTjNfmcsDdRFs5EaGEgkESGSgjJVYgMEizu",a=`Email certified by ${i.name}`,o=i.iconUrl,c="https://socialcert.net";break;case xi.phoneCert:n=r.phoneNumber,s="XUTLxtX3ELNUwRhLwL7kWNGbdnFM8WG2eSLv84J7654oH8HaJWrU",a=`Phone certified by ${i.name}`,o=i.iconUrl,c="https://socialcert.net";break;case xi.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 xi.registrant:n=r.name,s=r.icon,a=`Entity certified by ${i.name}`,o=i.iconUrl,c="https://projectbabbage.com/docs/registrant";break;case xi.coolCert:n="true"===r.cool?"Cool Person!":"Not cool!";break;case xi.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 xi.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=Oi.name,s=r.profilePhoto,a=Oi.badgeLabel,o=Oi.badgeIconURL,c=Oi.badgeClickURL}return{name:n,avatarURL:s,abbreviatedKey:e.subject.length>0?`${e.subject.substring(0,10)}...`:"",identityKey:e.subject,badgeIconURL:o,badgeLabel:a,badgeClickURL:c}}}class Ti{wallet;network;constructor(e=new Zr){this.wallet=e}async registerDefinition(e){const t=(await this.wallet.getPublicKey({identityKey:!0})).publicKey,r=new Ht(this.wallet),i=this.buildPushDropFields(e,t),n=this.mapDefinitionTypeToWalletProtocol(e.definitionType),s=await r.lock(i,n,"1","anyone",!0),{tx:a}=await this.wallet.createAction({description:`Register a new ${e.definitionType} item`,outputs:[{satoshis:1,lockingScript:s.toHex(),outputDescription:`New ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{randomizeOutputs:!1}});if(void 0===a)throw new Error(`Failed to create ${e.definitionType} registration transaction!`);const o=new yi([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:this.network??=(await this.wallet.getNetwork({})).network});return await o.broadcast(sr.fromAtomicBEEF(a))}async resolve(e,t){const r=new gi,i=this.mapDefinitionTypeToServiceName(e),n=await r.query({service:i,query:t});if("output-list"!==n.type)return[];const s=[];for(const t of n.outputs)try{const r=sr.fromBEEF(t.beef).outputs[t.outputIndex].lockingScript,i=await this.parseLockingScript(e,r);s.push(i)}catch{}return s}async listOwnRegistryEntries(e){const t=this.mapDefinitionTypeToBasketName(e),{outputs:r,BEEF:i}=await this.wallet.listOutputs({basket:t,include:"entire transactions"}),n=[];for(const t of r)if(t.spendable)try{const[r,s]=t.outpoint.split("."),a=sr.fromBEEF(i).outputs[s].lockingScript,o=await this.parseLockingScript(e,a);n.push({...o,txid:r,outputIndex:Number(s),satoshis:t.satoshis,lockingScript:a.toHex(),beef:i})}catch{}return n}async revokeOwnRegistryEntry(e){if(void 0===e.txid||void 0===e.outputIndex||void 0===e.lockingScript)throw new Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");const t=(await this.wallet.getPublicKey({identityKey:!0})).publicKey;if(e.registryOperator!==t)throw new Error("This registry token does not belong to the current wallet.");const r="basket"===e.definitionType?e.basketID:"protocol"===e.definitionType?e.name:"certificate"===e.definitionType?void 0!==e.name?e.name:e.type:"unknown",i=`${e.txid}.${e.outputIndex}`,{signableTransaction:n}=await this.wallet.createAction({description:`Revoke ${e.definitionType} item: ${r}`,inputBEEF:e.beef,inputs:[{outpoint:i,unlockingScriptLength:73,inputDescription:`Revoking ${e.definitionType} token`}]});if(void 0===n)throw new Error("Failed to create signable transaction.");const s=sr.fromBEEF(n.tx),a=new Ht(this.wallet),o=await a.unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone","all",!1,e.satoshis,xt.fromHex(e.lockingScript)),c=await o.sign(s,e.outputIndex),{tx:d}=await this.wallet.signAction({reference:n.reference,spends:{[e.outputIndex]:{unlockingScript:c.toHex()}},options:{acceptDelayedBroadcast:!1}});if(void 0===d)throw new Error("Failed to finalize the transaction signature.");const u=new yi([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:this.network??=(await this.wallet.getNetwork({})).network});return await u.broadcast(sr.fromAtomicBEEF(d))}buildPushDropFields(e,t){let r;switch(e.definitionType){case"basket":r=[e.basketID,e.name,e.iconURL,e.description,e.documentationURL];break;case"protocol":r=[JSON.stringify(e.protocolID),e.name,e.iconURL,e.description,e.documentationURL];break;case"certificate":r=[e.type,e.name,e.iconURL,e.description,e.documentationURL,JSON.stringify(e.fields)];break;default:throw new Error("Unsupported definition type")}return r.push(t),r.map((e=>Oe(e)))}async parseLockingScript(e,t){const r=Ht.decode(t);if(0===r.fields.length)throw new Error("Not a valid registry pushdrop script.");let i,n;switch(e){case"basket":{if(7!==r.fields.length)throw new Error("Unexpected field count for basket type.");const[e,t,s,a,o,c]=r.fields;i=Ae(c),n={definitionType:"basket",basketID:Ae(e),name:Ae(t),iconURL:Ae(s),description:Ae(a),documentationURL:Ae(o)};break}case"protocol":{if(7!==r.fields.length)throw new Error("Unexpected field count for protocol type.");const[e,t,s,a,o,c]=r.fields;i=Ae(c),n={definitionType:"protocol",protocolID:Fi(Ae(e)),name:Ae(t),iconURL:Ae(s),description:Ae(a),documentationURL:Ae(o)};break}case"certificate":{if(8!==r.fields.length)throw new Error("Unexpected field count for certificate type.");const[e,t,s,a,o,c,d]=r.fields;i=Ae(d);let u={};try{u=JSON.parse(Ae(c))}catch{}n={definitionType:"certificate",type:Ae(e),name:Ae(t),iconURL:Ae(s),description:Ae(a),documentationURL:Ae(o),fields:u};break}default:throw new Error(`Unsupported definition type: ${e}`)}return{...n,registryOperator:i}}mapDefinitionTypeToWalletProtocol(e){switch(e){case"basket":return[1,"basketmap"];case"protocol":return[1,"protomap"];case"certificate":return[1,"certmap"];default:throw new Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToBasketName(e){switch(e){case"basket":return"basketmap";case"protocol":return"protomap";case"certificate":return"certmap";default:throw new Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToTopic(e){switch(e){case"basket":return"tm_basketmap";case"protocol":return"tm_protomap";case"certificate":return"tm_certmap";default:throw new Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToServiceName(e){switch(e){case"basket":return"ls_basketmap";case"protocol":return"ls_protomap";case"certificate":return"ls_certmap";default:throw new Error(`Unknown definition type: ${e}`)}}}function Fi(e){const t=JSON.parse(e);if(!Array.isArray(t)||2!==t.length)throw new Error("Invalid wallet protocol format.");const[r,i]=t;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 Ri{wallet;context;encrypt;originator;constructor(e=new Zr,t="kvstore default",r=!0,i){if("string"!=typeof t||t.length<1)throw new Error("A context in which to operate is required.");this.wallet=e,this.context=t,this.encrypt=r,this.originator=i}getProtocol(e){return{protocolID:[2,this.context],keyID:e}}async getOutputs(e,t){return await this.wallet.listOutputs({basket:this.context,tags:[e],tagQueryMode:"all",include:"entire transactions",limit:t})}async get(e,t=void 0){return(await this.lookupValue(e,t,5)).value}getLockingScript(e,t){const[r,i]=e.outpoint.split("."),n=t.findTxid(r)?.tx;if(null==n)throw new Error(`beef must contain txid ${r}`);return n.outputs[Number(i)].lockingScript}async lookupValue(e,t,r){const i=await this.getOutputs(e,r),n={value:t,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 e=this.getLockingScript(a,nr.fromBinary(i.BEEF)),t=Ht.decode(e);if(t.fields.length<1||t.fields.length>2)throw new Error("Invalid token.");o=t.fields[0]}catch(e){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:t}=await this.wallet.decrypt({...this.getProtocol(e),ciphertext:o});n.value=Ae(t)}else n.value=Ae(o);return n}getInputs(e){const t=[];for(let r=0;r<e.length;r++)t.push({outpoint:e[r].outpoint,unlockingScriptLength:74,inputDescription:"Previous key-value token"});return t}async getSpends(e,t,r,i){const n=this.getProtocol(e),s=sr.fromAtomicBEEF(i),a={};for(let e=0;e<t.length;e++){const t=r.unlock(n.protocolID,n.keyID,"self"),i=await t.sign(s,e);a[e]={unlockingScript:i.toHex()}}return a}async set(e,t){const r=await this.lookupValue(e,void 0,10);if(r.value===t){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(e);let n=Oe(t,"utf8");if(this.encrypt){const{ciphertext:e}=await this.wallet.encrypt({...i,plaintext:n});n=e}const s=new Ht(this.wallet,this.originator),a=await s.lock([n],i.protocolID,i.keyID,"self"),{outputs:o,BEEF:c}=r.lor;let d;try{const t=this.getInputs(o),{txid:r,signableTransaction:i}=await this.wallet.createAction({description:`Update ${e} in ${this.context}`,inputBEEF:c,inputs:t,outputs:[{basket:this.context,tags:[e],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)d=`${r}.0`;else{const t=await this.getSpends(e,o,s,i.tx),{txid:r}=await this.wallet.signAction({reference:i.reference,spends:t});d=`${r}.0`}}catch(t){throw new Error(`There are ${o.length} outputs with tag ${e} that cannot be unlocked.`)}return d}async remove(e){const t=[];for(;;){const{outputs:r,BEEF:i,totalOutputs:n}=await this.getOutputs(e);if(r.length>0){const s=new Ht(this.wallet,this.originator);try{const n=this.getInputs(r),{signableTransaction:a}=await this.wallet.createAction({description:`Remove ${e} 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(e,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");t.push(c)}catch(t){throw new Error(`There are ${n} outputs with tag ${e} that cannot be unlocked.`)}}if(r.length===n)break}return t}}return t})()));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.bsv=t():e.bsv=t()}(this,(()=>(()=>{"use strict";var e={d:(t,r)=>{for(var i in r)e.o(r,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:r[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{ARC:()=>jt,ATOMIC_BEEF:()=>rr,AuthFetch:()=>fi,BEEF_V1:()=>er,BEEF_V2:()=>tr,BSM:()=>o,Beef:()=>nr,BeefParty:()=>cr,BeefTx:()=>Zt,BigNumber:()=>d,BlockHeadersService:()=>pr,CachedKeyDeriver:()=>Dr,Certificate:()=>$r,CompletedProtoWallet:()=>ii,Curve:()=>Me,DEFAULT_IDENTITY_CLIENT_OPTIONS:()=>Ai,DEFAULT_SLAP_TRACKERS:()=>bi,DEFAULT_TESTNET_SLAP_TRACKERS:()=>wi,DRBG:()=>ze,ECDSA:()=>n,ECIES:()=>Tr,EncryptedMessage:()=>a,FetchHttpClient:()=>$t,HD:()=>Er,HTTPSOverlayBroadcastFacilitator:()=>yi,HTTPSOverlayLookupFacilitator:()=>gi,HTTPWalletJSON:()=>Jr,HTTPWalletWire:()=>Xr,Hash:()=>r,IdentityClient:()=>Ti,KNOWN_IDENTITY_TYPES:()=>xi,KeyDeriver:()=>Br,KeyShares:()=>tt,LocalKVStore:()=>Ri,LockingScript:()=>At,LookupResolver:()=>mi,MasterCertificate:()=>ti,MerklePath:()=>Jt,Mnemonic:()=>Nr,NodejsHttpClient:()=>Mt,OP:()=>Ot,OverlayAdminTokenTemplate:()=>pi,P2PKH:()=>Ut,Peer:()=>ui,Point:()=>He,PointInFiniteField:()=>Qe,Polynomial:()=>et,PrivateKey:()=>rt,ProtoWallet:()=>Ur,PublicKey:()=>Ge,PushDrop:()=>Ht,RPuzzle:()=>Kt,Random:()=>Ze,ReactNativeWebView:()=>Zr,RegistryClient:()=>Fi,SHIPBroadcaster:()=>Ii,SHIPCast:()=>Ii,SatoshisPerKilobyte:()=>qt,Schnorr:()=>Pt,Script:()=>_t,SecurityLevels:()=>Vr,SessionManager:()=>ni,Signature:()=>$e,SignedMessage:()=>s,SimplifiedFetchTransport:()=>li,Spend:()=>Bt,StorageDownloader:()=>Oi,StorageUploader:()=>Ni,StorageUtils:()=>c,SymmetricKey:()=>St,TOTP:()=>Cr,TX_DATA_FORMAT:()=>ir,Teranode:()=>fr,TopicBroadcaster:()=>Ii,Transaction:()=>sr,TransactionSignature:()=>Et,UnlockingScript:()=>xt,Utils:()=>i,VerifiableCertificate:()=>ri,WERR_REVIEW_ACTIONS:()=>Yr,WalletClient:()=>Qr,WalletError:()=>Lr,WalletErrors:()=>qr,WalletWireProcessor:()=>ei,WalletWireTransceiver:()=>jr,WhatsOnChain:()=>Gt,WhatsOnChainBroadcaster:()=>dr,WindowCWISubstrate:()=>Kr,XDM:()=>Mr,binaryHttpClient:()=>lr,createNonce:()=>ai,defaultBroadcaster:()=>Xt,defaultChainTracker:()=>Yt,defaultHttpClient:()=>zt,defaultIdentity:()=>_i,deserializeWalletProtocol:()=>Ci,fromUtxo:()=>Fr,getVerifiableCertificates:()=>oi,isBroadcastFailure:()=>or,isBroadcastResponse:()=>ar,validateCertificates:()=>ci,verifyNonce:()=>si,walletErrors:()=>Hr});var r={};e.r(r),e.d(r,{RIPEMD160:()=>J,SHA1:()=>Q,SHA1HMAC:()=>pe,SHA256:()=>Z,SHA256HMAC:()=>fe,SHA512:()=>ee,SHA512HMAC:()=>be,hash160:()=>ve,hash256:()=>Ie,pbkdf2:()=>Ee,ripemd160:()=>we,sha1:()=>ge,sha256:()=>me,sha256hmac:()=>ke,sha512:()=>ye,sha512hmac:()=>Se,toArray:()=>y});var i={};e.r(i),e.d(i,{Reader:()=>Ke,Writer:()=>Ue,encode:()=>Te,fromBase58:()=>Re,fromBase58Check:()=>De,minimallyEncode:()=>Le,toArray:()=>Oe,toBase58:()=>Ve,toBase58Check:()=>Be,toBase64:()=>Fe,toHex:()=>Ne,toUTF8:()=>xe,zero2:()=>Pe});var n={};e.r(n),e.d(n,{sign:()=>je,verify:()=>Xe});var s={};e.r(s),e.d(s,{sign:()=>wr,verify:()=>gr});var a={};e.r(a),e.d(a,{decrypt:()=>Ir,encrypt:()=>yr});var o={};e.r(o),e.d(o,{magicHash:()=>vr,sign:()=>kr,verify:()=>Sr});var c={};e.r(c),e.d(c,{getHashFromURL:()=>Ei,getURLForFile:()=>Si,getURLForHash:()=>ki,isValidURL:()=>Pi,normalizeURL:()=>vi});class d{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;static WORD_SIZE_BIGINT=BigInt(d.wordSize);static WORD_MASK=(1n<<d.WORD_SIZE_BIGINT)-1n;static MAX_SAFE_INTEGER_BIGINT=BigInt(Number.MAX_SAFE_INTEGER);static MIN_SAFE_INTEGER_BIGINT=BigInt(Number.MIN_SAFE_INTEGER);static MAX_IMULN_ARG=67108863;static MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT=(1n<<53n)-1n;_magnitude;_sign;_nominalWordLength;red;get negative(){return this._sign}set negative(e){this.assert(0===e||1===e,"Negative property must be 0 or 1");const t=1===e?1:0;0n===this._magnitude?this._sign=0:this._sign=t}get _computedWordsArray(){if(0n===this._magnitude)return[0];const e=[];let t=this._magnitude;for(;t>0n;)e.push(Number(t&d.WORD_MASK)),t>>=d.WORD_SIZE_BIGINT;return e.length>0?e:[0]}get words(){const e=this._computedWordsArray;if(this._nominalWordLength<=e.length)return e;const t=new Array(this._nominalWordLength).fill(0);for(let r=0;r<e.length;r++)t[r]=e[r];return t}set words(e){const t=this._sign;let r=0n;const i=e.length>0?e.length:1;for(let t=i-1;t>=0;t--){const i=void 0===e[t]?0:e[t];r=r<<d.WORD_SIZE_BIGINT|BigInt(i&Number(d.WORD_MASK))}this._magnitude=r,this._sign=t,this._nominalWordLength=i,this.normSign()}get length(){return Math.max(1,this._nominalWordLength)}static isBN(e){return e instanceof d||null!==e&&"object"==typeof e&&e.constructor?.wordSize===d.wordSize&&Array.isArray(e.words)}static max(e,t){return e.cmp(t)>0?e:t}static min(e,t){return e.cmp(t)<0?e:t}constructor(e=0,t=10,r="be"){if(this._magnitude=0n,this._sign=0,this._nominalWordLength=1,this.red=null,void 0===e&&(e=0),null===e)return void this._initializeState(0n,0);if("bigint"==typeof e)return this._initializeState(e<0n?-e:e,e<0n?1:0),void this.normSign();let i=t,n=r;if("le"!==t&&"be"!==t||(n=t,i=10),"number"!=typeof e)if(Array.isArray(e))this.initArray(e,n);else if("string"==typeof e){"hex"===i&&(i=16),this.assert("number"==typeof i&&i===(0|i)&&i>=2&&i<=36,"Base must be an integer between 2 and 36");const t=e.toString().replace(/\s+/g,"");let r=0,s=0;t.startsWith("-")?(r++,s=1):t.startsWith("+")&&r++;const a=t.substring(r);if(0===a.length)return this._initializeState(0n,1===s&&t.startsWith("-")?1:0),void this.normSign();if(16===i){let e;if("le"===n){const e=[];let t=a;t.length%2!=0&&(t="0"+t);for(let r=0;r<t.length;r+=2){const i=t.substring(r,r+2),n=parseInt(i,16);if(isNaN(n))throw new Error("Invalid character in "+t);e.push(n)}return this.initArray(e,"le"),this._sign=s,void this.normSign()}try{e=BigInt("0x"+a)}catch(e){throw new Error("Invalid character in "+a)}this._initializeState(e,s),this.normSign()}else try{if(this._parseBaseString(a,i),this._sign=s,this.normSign(),"le"===n){const e=this._sign;this.initArray(this.toArray("be"),"le"),this._sign=e,this.normSign()}}catch(e){const t=e;if(t.message.includes("Invalid character in string")||t.message.includes("Invalid digit for base")||t.message.startsWith("Invalid character:"))throw new Error("Invalid character");throw t}}else 0!==e?this.assert(!1,"Unsupported input type for BigNumber constructor"):this._initializeState(0n,0);else this.initNumber(e,n)}_bigIntToStringInBase(e,t){if(0n===e)return"0";if(t<2||t>36)throw new Error("Base must be between 2 and 36");let r="",i=e>0n?e:-e;const n=BigInt(t);for(;i>0n;)r="0123456789abcdefghijklmnopqrstuvwxyz"[Number(i%n)]+r,i/=n;return r}_parseBaseString(e,t){if(0===e.length)return this._magnitude=0n,void this._finishInitialization();this._magnitude=0n;const r=BigInt(t);let i=d.groupSizes[t],n=BigInt(d.groupBases[t]);0!==i&&0n!==n||(i=Math.floor(Math.log(67108863)/Math.log(t)),0===i&&(i=1),n=r**BigInt(i));let s=0;const a=e.length;let o=a%i;if(0===o&&a>0&&(o=i),o>0){const r=e.substring(s,s+o);this._magnitude=BigInt(this._parseBaseWord(r,t)),s+=o}for(;s<a;){const r=e.substring(s,s+i),a=BigInt(this._parseBaseWord(r,t));this._magnitude=this._magnitude*n+a,s+=i}this._finishInitialization()}_parseBaseWord(e,t){let r=0;for(let i=0;i<e.length;i++){const n=e.charCodeAt(i);let s;if(n>=48&&n<=57)s=n-48;else if(n>=65&&n<=90)s=n-65+10;else{if(!(n>=97&&n<=122))throw new Error("Invalid character: "+e[i]);s=n-97+10}if(s>=t)throw new Error("Invalid character");r=r*t+s}return r}_initializeState(e,t){this._magnitude=e,this._sign=0n===e?0:t,this._finishInitialization()}_finishInitialization(){if(0n===this._magnitude)this._nominalWordLength=1,this._sign=0;else{const e=this._magnitude.toString(2).length;this._nominalWordLength=Math.max(1,Math.ceil(e/d.wordSize))}}assert(e,t="Assertion failed"){if(!e)throw new Error(t)}initNumber(e,t="be"){if(this.assert(BigInt(Math.abs(e))<=d.MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT,"The number is larger than 2 ^ 53 (unsafe)"),this.assert(e%1==0,"Number must be an integer for BigNumber conversion"),this._initializeState(BigInt(Math.abs(e)),e<0?1:0),"le"===t){const e=this._sign,t=this.toArray("be");this.initArray(t,"le"),this._sign=e,this.normSign()}return this}initArray(e,t){if(0===e.length)return this._initializeState(0n,0),this;let r=0n;if("be"===t)for(let t=0;t<e.length;t++)r=r<<8n|BigInt(255&e[t]);else for(let t=e.length-1;t>=0;t--)r=r<<8n|BigInt(255&e[t]);return this._initializeState(r,0),this}copy(e){e._magnitude=this._magnitude,e._sign=this._sign,e._nominalWordLength=this._nominalWordLength,e.red=this.red}static move(e,t){e._magnitude=t._magnitude,e._sign=t._sign,e._nominalWordLength=t._nominalWordLength,e.red=t.red}clone(){const e=new d(0n);return this.copy(e),e}expand(e){return this.assert(e>=0,"Expand size must be non-negative"),this._nominalWordLength=Math.max(this._nominalWordLength,e,1),this}strip(){return this._finishInitialization(),this.normSign()}normSign(){return 0n===this._magnitude&&(this._sign=0),this}inspect(){return(null!==this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}_getMinimalHex(){return 0n===this._magnitude?"0":this._magnitude.toString(16)}toString(e=10,t=1){if(16===e||"hex"===e){let e=this._getMinimalHex();if(t>1)for("0"!==e&&e.length%2!=0&&(e="0"+e);e.length%t!=0;)e="0"+e;return(this.isNeg()?"-":"")+e}if("number"!=typeof e||e<2||e>36||e%1!=0)throw new Error("Base should be an integer between 2 and 36");return this.toBaseString(e,t)}toBaseString(e,t){if(0n===this._magnitude){let e="0";if(t>1)for(;e.length<t;)e="0"+e;return e}let r=d.groupSizes[e],i=BigInt(d.groupBases[e]);0!==r&&0n!==i||(r=Math.floor(Math.log(Number.MAX_SAFE_INTEGER)/Math.log(e)),0===r&&(r=1),i=BigInt(e)**BigInt(r));let n="",s=this._magnitude;for(;s>0n;){const t=s%i;s/=i;const a=this._bigIntToStringInBase(t,e);if(s>0n){const e=r-a.length;n=e>0&&e<d.zeros.length?d.zeros[e]+a+n:e>0?"0".repeat(e)+a+n:a+n}else n=a+n}if(t>0)for(;n.length<t;)n="0"+n;return(1===this._sign?"-":"")+n}toNumber(){const e=this._getSignedValue();if(e>d.MAX_SAFE_INTEGER_BIGINT||e<d.MIN_SAFE_INTEGER_BIGINT)throw new Error("Number can only safely store up to 53 bits");return Number(e)}toJSON(){const e=this._getMinimalHex();return(this.isNeg()?"-":"")+e}toArrayLikeGeneric(e,t){let r=this._magnitude,i=t?0:e.length-1;const n=t?1:-1;for(let t=0;t<e.length;++t){if(0n===r&&i>=0&&i<e.length)e[i]=0;else{if(!(i>=0&&i<e.length))break;e[i]=Number(0xffn&r)}r>>=8n,i+=n}}toArray(e="be",t){this.strip();const r=this.byteLength(),i=t??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).fill(0);return 0n===this._magnitude&&i>0?n:0n===this._magnitude&&0===i?[]:(this.toArrayLikeGeneric(n,"le"===e),n)}bitLength(){return 0n===this._magnitude?0:this._magnitude.toString(2).length}static toBitArray(e){const t=e.bitLength();if(0===t)return[];const r=new Array(t),i=e._magnitude;for(let e=0;e<t;e++)r[e]=0n!==(i>>BigInt(e)&1n)?1:0;return r}toBitArray(){return d.toBitArray(this)}zeroBits(){if(0n===this._magnitude)return 0;let e=0,t=this._magnitude;for(;0n===(1n&t)&&0n!==t;)e++,t>>=1n;return e}byteLength(){return 0n===this._magnitude?0:Math.ceil(this.bitLength()/8)}_getSignedValue(){return 1===this._sign?-this._magnitude:this._magnitude}_setValueFromSigned(e){e<0n?(this._magnitude=-e,this._sign=1):(this._magnitude=e,this._sign=0),this._finishInitialization(),this.normSign()}toTwos(e){this.assert(e>=0);const t=BigInt(e);let r=this._getSignedValue();1===this._sign&&0n!==this._magnitude&&(r=(1n<<t)+r),r&=(1n<<t)-1n;const i=new d(0n);return i._initializeState(r,0),i}fromTwos(e){this.assert(e>=0);const t=BigInt(e),r=this._magnitude;if(e>0&&0n!==(r>>t-1n&1n)&&0===this._sign){const e=r-(1n<<t),i=new d(0n);return i._setValueFromSigned(e),i}return this.clone()}isNeg(){return 1===this._sign&&0n!==this._magnitude}neg(){return this.clone().ineg()}ineg(){return 0n!==this._magnitude&&(this._sign=1===this._sign?0:1),this}_iuop(e,t){const r=t(this._magnitude,e._magnitude),i=t===((e,t)=>e^t);let n=this._nominalWordLength;return i&&(n=Math.max(this.length,e.length)),this._magnitude=r,this._finishInitialization(),i&&(this._nominalWordLength=Math.max(this._nominalWordLength,n)),this.strip()}iuor(e){return this._iuop(e,((e,t)=>e|t))}iuand(e){return this._iuop(e,((e,t)=>e&t))}iuxor(e){return this._iuop(e,((e,t)=>e^t))}_iop(e,t){return this.assert(0===this._sign&&0===e._sign),this._iuop(e,t)}ior(e){return this._iop(e,((e,t)=>e|t))}iand(e){return this._iop(e,((e,t)=>e&t))}ixor(e){return this._iop(e,((e,t)=>e^t))}_uop_new(e,t){return this.length>=e.length?this.clone()[t](e):e.clone()[t](this)}or(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuor")}uor(e){return this._uop_new(e,"iuor")}and(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuand")}uand(e){return this._uop_new(e,"iuand")}xor(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuxor")}uxor(e){return this._uop_new(e,"iuxor")}inotn(e){this.assert("number"==typeof e&&e>=0);const t=(1n<<BigInt(e))-1n;this._magnitude=~this._magnitude&t;const r=0===e?1:Math.ceil(e/d.wordSize);return this._nominalWordLength=Math.max(1,r),this.strip(),this._nominalWordLength=Math.max(this._nominalWordLength,Math.max(1,r)),this}notn(e){return this.clone().inotn(e)}setn(e,t){this.assert("number"==typeof e&&e>=0);const r=BigInt(e);1===t||!0===t?this._magnitude|=1n<<r:this._magnitude&=~(1n<<r);const i=Math.floor(e/d.wordSize)+1;return this._nominalWordLength=Math.max(this._nominalWordLength,i),this._finishInitialization(),this.strip()}iadd(e){return this._setValueFromSigned(this._getSignedValue()+e._getSignedValue()),this}add(e){const t=new d(0n);return t._setValueFromSigned(this._getSignedValue()+e._getSignedValue()),t}isub(e){return this._setValueFromSigned(this._getSignedValue()-e._getSignedValue()),this}sub(e){const t=new d(0n);return t._setValueFromSigned(this._getSignedValue()-e._getSignedValue()),t}mul(e){const t=new d(0n);return t._magnitude=this._magnitude*e._magnitude,t._sign=0n===t._magnitude?0:this._sign^e._sign,t._nominalWordLength=this.length+e.length,t.red=null,t.normSign()}imul(e){return this._magnitude*=e._magnitude,this._sign=0n===this._magnitude?0:this._sign^e._sign,this._nominalWordLength=this.length+e.length,this.red=null,this.normSign()}imuln(e){return this.assert("number"==typeof e,"Assertion failed"),this.assert(Math.abs(e)<=d.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()*BigInt(e)),this}muln(e){return this.clone().imuln(e)}sqr(){const e=new d(0n);return e._magnitude=this._magnitude*this._magnitude,e._sign=0,e._nominalWordLength=2*this.length,e.red=null,e}isqr(){return this._magnitude*=this._magnitude,this._sign=0,this._nominalWordLength=2*this.length,this.red=null,this}pow(e){if(this.assert(0===e._sign,"Exponent for pow must be non-negative"),e.isZero())return new d(1n);const t=new d(1n),r=this.clone(),i=e.clone(),n=r.isNeg(),s=i.isOdd();for(n&&r.ineg();!i.isZero();)i.isOdd()&&t.imul(r),r.isqr(),i.iushrn(1);return n&&s&&t.ineg(),t}iushln(e){return this.assert("number"==typeof e&&e>=0),0===e?this:(this._magnitude<<=BigInt(e),this._finishInitialization(),this.strip())}ishln(e){return this.assert(0===this._sign,"ishln requires positive number"),this.iushln(e)}iushrn(e,t,r){if(this.assert("number"==typeof e&&e>=0),0===e)return null!=r&&r._initializeState(0n,0),this;if(null!=r){const t=(1n<<BigInt(e))-1n,i=this._magnitude&t;r._initializeState(i,0)}return this._magnitude>>=BigInt(e),this._finishInitialization(),this.strip()}ishrn(e,t,r){return this.assert(0===this._sign,"ishrn requires positive number"),this.iushrn(e,t,r)}shln(e){return this.clone().ishln(e)}ushln(e){return this.clone().iushln(e)}shrn(e){return this.clone().ishrn(e)}ushrn(e){return this.clone().iushrn(e)}testn(e){return this.assert("number"==typeof e&&e>=0),0n!==(this._magnitude>>BigInt(e)&1n)}imaskn(e){this.assert("number"==typeof e&&e>=0),this.assert(0===this._sign,"imaskn works only with positive numbers");const t=BigInt(e),r=0n===t?0n:(1n<<t)-1n;this._magnitude&=r;const i=0===e?1:Math.max(1,Math.ceil(e/d.wordSize));return this._nominalWordLength=i,this._finishInitialization(),this._nominalWordLength=Math.max(this._nominalWordLength,i),this.strip()}maskn(e){return this.clone().imaskn(e)}iaddn(e){return this.assert("number"==typeof e),this.assert(Math.abs(e)<=d.MAX_IMULN_ARG,"num is too large"),this._setValueFromSigned(this._getSignedValue()+BigInt(e)),this}_iaddn(e){return this.iaddn(e)}isubn(e){return this.assert("number"==typeof e),this.assert(Math.abs(e)<=d.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()-BigInt(e)),this}addn(e){return this.clone().iaddn(e)}subn(e){return this.clone().isubn(e)}iabs(){return this._sign=0,this}abs(){return this.clone().iabs()}divmod(e,t,r){if(this.assert(!e.isZero(),"Division by zero"),this.isZero()){const e=new d(0n);return{div:"mod"!==t?e:null,mod:"div"!==t?e:null}}const i=this._getSignedValue(),n=e._getSignedValue();let s=null,a=null;"mod"!==t&&(s=i/n),"div"!==t&&(a=i%n,!0===r&&a<0n&&(a+=n<0n?-n:n));const o=null!==s?new d(0n):null;null!==o&&null!==s&&o._setValueFromSigned(s);const c=null!==a?new d(0n):null;return null!==c&&null!==a&&c._setValueFromSigned(a),{div:o,mod:c}}div(e){return this.divmod(e,"div",!1).div}mod(e){return this.divmod(e,"mod",!1).mod}umod(e){return this.divmod(e,"mod",!0).mod}divRound(e){this.assert(!e.isZero());const t=this._getSignedValue(),r=e._getSignedValue();let i=t/r;const n=t%r;if(0n===n){const e=new d(0n);return e._setValueFromSigned(i),e}2n*(n<0n?-n:n)>=(r<0n?-r:r)&&(t>0n&&r>0n||t<0n&&r<0n?i+=1n:i-=1n);const s=new d(0n);return s._setValueFromSigned(i),s}modrn(e){this.assert(0!==e,"Division by zero in modrn");const t=BigInt(Math.abs(e));if(0n===t)throw new Error("Division by zero in modrn");const r=this._magnitude%t;return Number(e<0?-r:r)}idivn(e){return this.assert(0!==e),this.assert(Math.abs(e)<=d.MAX_IMULN_ARG,"num is too large"),this._setValueFromSigned(this._getSignedValue()/BigInt(e)),this}divn(e){return this.clone().idivn(e)}egcd(e){this.assert(0===e._sign,"p must not be negative"),this.assert(!e.isZero(),"p must not be zero");let t=this._getSignedValue(),r=e._magnitude,i=1n,n=0n,s=0n,a=1n;for(;0n!==r;){const e=t/r;let o=r;r=t%r,t=o,o=n,n=i-e*n,i=o,o=a,a=s-e*a,s=o}const o=new d(0n);o._setValueFromSigned(i);const c=new d(0n);c._setValueFromSigned(s);const u=new d(0n);return u._initializeState(t<0n?-t:t,0),{a:o,b:c,gcd:u}}gcd(e){let t=this._magnitude,r=e._magnitude;if(0n===t){const e=new d(0n);return e._setValueFromSigned(r),e.iabs()}if(0n===r){const e=new d(0n);return e._setValueFromSigned(t),e.iabs()}for(;0n!==r;){const e=t%r;t=r,r=e}const i=new d(0n);return i._initializeState(t,0),i}invm(e){this.assert(!e.isZero()&&0===e._sign,"Modulus for invm must be positive and non-zero");const t=this.egcd(e);if(!t.gcd.eqn(1))throw new Error("Inverse does not exist (numbers are not coprime).");return t.a.umod(e)}isEven(){return this._magnitude%2n===0n}isOdd(){return this._magnitude%2n===1n}andln(e){return this.assert(e>=0),Number(this._magnitude&BigInt(e))}bincn(e){this.assert("number"==typeof e&&e>=0);const t=1n<<BigInt(e);return this._setValueFromSigned(this._getSignedValue()+t),this}isZero(){return 0n===this._magnitude}cmpn(e){this.assert(Math.abs(e)<=d.MAX_IMULN_ARG,"Number is too big");const t=this._getSignedValue(),r=BigInt(e);return t<r?-1:t>r?1:0}cmp(e){const t=this._getSignedValue(),r=e._getSignedValue();return t<r?-1:t>r?1:0}ucmp(e){return this._magnitude<e._magnitude?-1:this._magnitude>e._magnitude?1:0}gtn(e){return 1===this.cmpn(e)}gt(e){return 1===this.cmp(e)}gten(e){return this.cmpn(e)>=0}gte(e){return this.cmp(e)>=0}ltn(e){return-1===this.cmpn(e)}lt(e){return-1===this.cmp(e)}lten(e){return this.cmpn(e)<=0}lte(e){return this.cmp(e)<=0}eqn(e){return 0===this.cmpn(e)}eq(e){return 0===this.cmp(e)}toRed(e){return this.assert(null==this.red,"Already a number in reduction context"),this.assert(0===this._sign,"toRed works only with positives"),e.convertTo(this).forceRed(e)}fromRed(){return this.assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)}forceRed(e){return this.red=e,this}redAdd(e){return this.assert(this.red,"redAdd works only with red numbers"),this.red.add(this,e)}redIAdd(e){return this.assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)}redSub(e){return this.assert(this.red,"redSub works only with red numbers"),this.red.sub(this,e)}redISub(e){return this.assert(this.red,"redISub works only with red numbers"),this.red.isub(this,e)}redShl(e){return this.assert(this.red,"redShl works only with red numbers"),this.red.shl(this,e)}redMul(e){return this.assert(this.red,"redMul works only with red numbers"),this.red.verify2(this,e),this.red.mul(this,e)}redIMul(e){return this.assert(this.red,"redIMul works only with red numbers"),this.red.verify2(this,e),this.red.imul(this,e)}redSqr(){return this.assert(this.red,"redSqr works only with red numbers"),this.red.verify1(this),this.red.sqr(this)}redISqr(){return this.assert(this.red,"redISqr works only with red numbers"),this.red.verify1(this),this.red.isqr(this)}redSqrt(){return this.assert(this.red,"redSqrt works only with red numbers"),this.red.verify1(this),this.red.sqrt(this)}redInvm(){return this.assert(this.red,"redInvm works only with red numbers"),this.red.verify1(this),this.red.invm(this)}redNeg(){return this.assert(this.red,"redNeg works only with red numbers"),this.red.verify1(this),this.red.neg(this)}redPow(e){return this.assert(null!=this.red&&null==e.red,"redPow(normalNum)"),this.red.verify1(this),this.red.pow(this,e)}static fromHex(e,t){let r="be";return"little"!==t&&"le"!==t||(r="le"),new d(e,16,r)}toHex(e=0){if(this.isZero()&&0===e)return"";let t=this._getMinimalHex();"0"!==t&&t.length%2!=0&&(t="0"+t);const r=2*e;for(;t.length<r;)t="0"+t;return(this.isNeg()?"-":"")+t}static fromJSON(e){return new d(e,16)}static fromNumber(e){return new d(e)}static fromString(e,t){return new d(e,t)}static fromSm(e,t="big"){if(0===e.length)return new d(0n);let r=0,i="";if("little"===t){const t=e.length-1;let n=e[t];128&n&&(r=1,n&=127),i+=(n<16?"0":"")+n.toString(16);for(let r=t-1;r>=0;r--){const t=e[r];i+=(t<16?"0":"")+t.toString(16)}}else{let t=e[0];128&t&&(r=1,t&=127),i+=(t<16?"0":"")+t.toString(16);for(let t=1;t<e.length;t++){const r=e[t];i+=(r<16?"0":"")+r.toString(16)}}const n=""===i?0n:BigInt("0x"+i),s=new d(0n);return s._initializeState(n,r),s}toSm(e="big"){if(0n===this._magnitude)return 1===this._sign?[128]:[];let t=this._getMinimalHex();t.length%2!=0&&(t="0"+t);const r=t.length/2,i=new Array(r);for(let e=0,r=0;e<t.length;e+=2)i[r++]=parseInt(t.slice(e,e+2),16);return 1===this._sign?128&i[0]?i.unshift(128):i[0]|=128:128&i[0]&&i.unshift(0),"little"===e?i.reverse():i}static fromBits(e,t=!1){const r=e>>>24,i=8388607&e,n=!!(8388608&e);if(t&&n)throw new Error("negative bit set");if(0===r&&0===i){if(n&&t)throw new Error("negative bit set for zero value");return new d(0n)}const s=new d(i);return r<=3?s.iushrn(8*(3-r)):s.iushln(8*(r-3)),n&&s.ineg(),s}toBits(){if(this.strip(),this.isZero()&&!this.isNeg())return 0;const e=this.isNeg(),t=this.abs();let r=t.toArray("be"),i=0;for(;i<r.length-1&&0===r[i];)i++;r=r.slice(i);let n,s=r.length;if(0!==s||t.isZero()||(r=[0],s=1),t.isZero()&&(s=0,r=[]),0===s)n=0;else if(s<=3){n=0;for(let e=0;e<s;e++)n=n<<8|r[e]}else n=r[0]<<16|r[1]<<8|r[2];8388608&n&&s<=255&&(n>>>=8,s++);let a=s<<24|n;return e&&(a|=8388608),a>>>0}static fromScriptNum(e,t=!1,r){if(void 0!==r&&e.length>r)throw new Error("script number overflow");if(0===e.length)return new d(0n);if(t&&!(127&e[e.length-1]||!(e.length<=1)&&128&e[e.length-2]))throw new Error("non-minimally encoded script number");return d.fromSm(e,"little")}toScriptNum(){return this.toSm("little")}_invmp(e){this.assert(0===e._sign,"p must not be negative for _invmp"),this.assert(!e.isZero(),"p must not be zero for _invmp");let t=this.umod(e)._magnitude,r=e._magnitude,i=1n,n=0n;const s=e._magnitude;for(;t>1n&&r>1n;){let e=0;for(;0n===(t>>BigInt(e)&1n);)e++;if(e>0){t>>=BigInt(e);for(let t=0;t<e;++t)0n!==(1n&i)&&(i+=s),i>>=1n}let a=0;for(;0n===(r>>BigInt(a)&1n);)a++;if(a>0){r>>=BigInt(a);for(let e=0;e<a;++e)0n!==(1n&n)&&(n+=s),n>>=1n}t>=r?(t-=r,i-=n):(r-=t,n-=i)}let a;if(1n===t)a=i;else if(1n===r)a=n;else if(0n===t&&1n===r)a=n;else{if(0n!==r||1n!==t)throw new Error("_invmp: GCD is not 1, inverse does not exist. aVal="+t+", bVal="+r);a=i}a%=s,a<0n&&(a+=s);const o=new d(0n);return o._initializeState(a,0),o}mulTo(e,t){return t._magnitude=this._magnitude*e._magnitude,t._sign=0n===t._magnitude?0:this._sign^e._sign,t._nominalWordLength=this.length+e.length,t.red=null,t.normSign(),t}}class u{name;p;k;n;tmp;constructor(e,t){this.name=e,this.p=new d(t,16),this.n=this.p.bitLength(),this.k=new d(BigInt(1)).iushln(this.n).isub(this.p),this.tmp=this._tmp()}_tmp(){const e=new d(BigInt(0)),t=Math.ceil(this.n/d.wordSize);return e.expand(Math.max(1,t)),e}ireduce(e){const t=e;let r;do{this.split(t,this.tmp),this.imulK(t),t.iadd(this.tmp),r=t.bitLength()}while(r>this.n);const i=r<this.n?-1:t.ucmp(this.p);return 0===i?t.words=[0]:i>0&&t.isub(this.p),t.strip(),t}split(e,t){e.iushrn(this.n,0,t)}imulK(e){return e.imul(this.k)}}class h extends u{constructor(){super("k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}split(e,t){const r=4194303,i=e.words,n=e.length,s=Math.min(n,9),a=new Array(s+(n>9?1:0)).fill(0);for(let e=0;e<s;e++)a[e]=i[e];let o=s;if(n<=9){const r=new Array(o);for(let e=0;e<o;++e)r[e]=a[e];return t.words=r,void(e.words=[0])}let c=i[9];a[o++]=c&r;const d=new Array(o);for(let e=0;e<o;++e)d[e]=a[e];t.words=d;const u=new Array(Math.max(1,n-9)).fill(0);let h=0;for(let e=10;e<n;e++){const t=0|i[e];h<u.length&&(u[h++]=(t&r)<<4|c>>>22),c=t}c>>>=22,h<u.length?u[h++]=c:0!==c&&u.length;const l=new Array(h);for(let e=0;e<h;++e)l[e]=u[e];e.words=l}imulK(e){const t=e.words,r=e.length,i=r+2,n=new Array(i).fill(0);for(let e=0;e<r;e++)n[e]=t[e];let s=0;for(let e=0;e<i;e++){const t=0|n[e];s+=977*t,n[e]=67108863&s,s=64*t+(s/67108864|0)}return e.words=n,e}}class l{prime;m;constructor(e){if("k256"===e){const e=new h;this.m=e.p,this.prime=e}else this.assert(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}assert(e,t="Assertion failed"){if(!e)throw new Error(t)}verify1(e){this.assert(0===e.negative,"red works only with positives"),this.assert(e.red,"red works only with red numbers")}verify2(e,t){this.assert(!(e.negative|t.negative),"red works only with positives"),this.assert(null!=e.red&&e.red===t.red,"red works only with red numbers")}imod(e){return null!=this.prime?this.prime.ireduce(e).forceRed(this):(d.move(e,e.umod(this.m).forceRed(this)),e)}neg(e){return e.isZero()?e.clone():this.m.sub(e).forceRed(this)}add(e,t){this.verify2(e,t);const r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r.forceRed(this)}iadd(e,t){this.verify2(e,t);const r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r}sub(e,t){this.verify2(e,t);const r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r.forceRed(this)}isub(e,t){this.verify2(e,t);const r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r}shl(e,t){return this.verify1(e),this.imod(e.ushln(t))}imul(e,t){return this.verify2(e,t),this.imod(e.imul(t))}mul(e,t){return this.verify2(e,t),this.imod(e.mul(t))}isqr(e){return this.imul(e,e.clone())}sqr(e){return this.mul(e,e)}sqrt(e){if(e.isZero())return e.clone();const t=this.m.andln(3);if(this.assert(t%2==1),3===t){const t=this.m.add(new d(1)).iushrn(2);return this.pow(e,t)}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 d(1).toRed(this),s=n.redNeg(),a=this.m.subn(1).iushrn(1),o=this.m.bitLength(),c=new d(2*o*o).toRed(this);for(;0!==this.pow(c,a).cmp(s);)c.redIAdd(s);let u=this.pow(c,r),h=this.pow(e,r.addn(1).iushrn(1)),l=this.pow(e,r),f=i;for(;0!==l.cmp(n);){let e=l,t=0;for(;0!==e.cmp(n);t++)e=e.redSqr();this.assert(t<f);const r=this.pow(u,new d(1).iushln(f-t-1));h=h.redMul(r),u=r.redSqr(),l=l.redMul(u),f=t}return h}invm(e){const t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)}pow(e,t){if(t.isZero())return new d(1).toRed(this);if(0===t.cmpn(1))return e.clone();const r=new Array(16);r[0]=new d(1).toRed(this),r[1]=e;let i=2;for(;i<r.length;i++)r[i]=this.mul(r[i-1],e);let n=r[0],s=0,a=0,o=t.bitLength()%26;for(0===o&&(o=26),i=t.length-1;i>=0;i--){const e=t.words[i];for(let t=o-1;t>=0;t--){const o=e>>t&1;n!==r[0]&&(n=this.sqr(n)),0!==o||0!==s?(s<<=1,s|=o,a++,(4===a||0===i&&0===t)&&(n=this.mul(n,r[s]),a=0,s=0)):a=0}o=26}return n}convertTo(e){const t=e.umod(this.m);return t===e?t.clone():t}convertFrom(e){const t=e.clone();return t.red=null,t}}class f extends l{shift;r;r2;rinv;minv;constructor(e){super(e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new d(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}convertTo(e){return this.imod(e.ushln(this.shift))}convertFrom(e){const t=this.imod(e.mul(this.rinv));return t.red=null,t}imul(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;const r=e.imul(t),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(e,t){if(e.isZero()||t.isZero())return new d(0).forceRed(this);const r=e.mul(t),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(e){return this.imod(e._invmp(this.m).mul(this.r2)).forceRed(this)}}class p{curve;type;precomputed;constructor(e){this.curve=new Me,this.type=e,this.precomputed=null}}class b extends p{x;y;z;zOne;constructor(e,t,r){super("jacobian"),null===e&&null===t&&null===r?(this.x=this.curve.one,this.y=this.curve.one,this.z=new d(0)):(d.isBN(e)||(e=new d(e,16)),this.x=e,d.isBN(t)||(t=new d(t,16)),this.y=t,d.isBN(r)||(r=new d(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 He(null,null);const e=this.z.redInvm(),t=e.redSqr(),r=this.x.redMul(t),i=this.y.redMul(t).redMul(e);return new He(r,i)}neg(){return new b(this.x,this.y.redNeg(),this.z)}add(e){if(this.isInfinity())return e;if(e.isInfinity())return this;const t=e.z.redSqr(),r=this.z.redSqr(),i=this.x.redMul(t),n=e.x.redMul(r),s=this.y.redMul(t.redMul(e.z)),a=e.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 b(null,null,null):this.dbl();const d=o.redSqr(),u=d.redMul(o),h=i.redMul(d),l=c.redSqr().redIAdd(u).redISub(h).redISub(h),f=c.redMul(h.redISub(l)).redISub(s.redMul(u)),p=this.z.redMul(e.z).redMul(o);return new b(l,f,p)}mixedAdd(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;if(null===e.x||null===e.y)throw new Error("Point coordinates cannot be null");const t=this.z.redSqr(),r=this.x,i=e.x.redMul(t),n=this.y,s=e.y.redMul(t).redMul(this.z),a=r.redSub(i),o=n.redSub(s);if(0===a.cmpn(0))return 0!==o.cmpn(0)?new b(null,null,null):this.dbl();const c=a.redSqr(),d=c.redMul(a),u=r.redMul(c),h=o.redSqr().redIAdd(d).redISub(u).redISub(u),l=o.redMul(u.redISub(h)).redISub(n.redMul(d)),f=this.z.redMul(a);return new b(h,l,f)}dblp(e){if(0===e)return this;if(this.isInfinity())return this;if(void 0===e)return this.dbl();let t=this;for(let r=0;r<e;r++)t=t.dbl();return t}dbl(){if(this.isInfinity())return this;let e,t,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 d=s.redIAdd(s);d=d.redIAdd(d),d=d.redIAdd(d),e=c,t=o.redMul(a.redISub(c)).redISub(d),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 d=s.redIAdd(s);d=d.redIAdd(d),d=d.redIAdd(d),e=c.redISub(a).redISub(a),t=o.redMul(a.redISub(e)).redISub(d),r=this.y.redMul(this.z),r=r.redIAdd(r)}return new b(e,t,r)}eq(e){if("affine"===e.type)return this.eq(e.toJ());if(this===e)return!0;const t=this.z.redSqr(),r=e.z.redSqr();if(0!==this.x.redMul(r).redISub(e.x.redMul(t)).cmpn(0))return!1;const i=t.redMul(this.z),n=r.redMul(e.z);return 0===this.y.redMul(n).redISub(e.y.redMul(i)).cmpn(0)}eqXToP(e){const t=this.z.redSqr(),r=e.toRed(this.curve?.red).redMul(t);if(0===this.x.cmp(r))return!0;const i=e.clone();if(null===this.curve||null==this.curve.redN)throw new Error("Curve or redN is not initialized.");const n=this.curve.redN.redMul(t);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=(e,t="Hash assertion failed")=>{if(!e)throw new Error(t)};class g{pending;pendingTotal;blockSize;outSize;endian;_delta8;_delta32;padLength;hmacStrength;constructor(e,t,r,i){this.pending=null,this.pendingTotal=0,this.blockSize=e,this.outSize=t,this.hmacStrength=r,this.padLength=i/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}_update(e,t){throw new Error("Not implemented")}_digest(){throw new Error("Not implemented")}_digestHex(){throw new Error("Not implemented")}update(e,t){if(e=y(e,t),null==this.pending?this.pending=e:this.pending=this.pending.concat(e),this.pendingTotal+=e.length,this.pending.length>=this._delta8){const t=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-t,e.length),0===this.pending.length&&(this.pending=null),e=function(e,t,r,i){const n=r-0;w(n%4==0);const s=new Array(n/4);for(let t=0,r=0;t<s.length;t++,r+=4){let n;n="big"===i?e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3]:e[r+3]<<24|e[r+2]<<16|e[r+1]<<8|e[r],s[t]=n>>>0}return s}(e,0,e.length-t,this.endian);for(let t=0;t<e.length;t+=this._delta32)this._update(e,t)}return this}digest(){return this.update(this._pad()),w(null===this.pending),this._digest()}digestHex(){return this.update(this._pad()),w(null===this.pending),this._digestHex()}_pad(){let e=this.pendingTotal;const t=this._delta8,r=t-(e+this.padLength)%t,i=new Array(r+this.padLength);let n,s;for(i[0]=128,n=1;n<r;n++)i[n]=0;if(e<<=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++]=e>>>24&255,i[n++]=e>>>16&255,i[n++]=e>>>8&255,i[n++]=255&e}else for(i[n++]=255&e,i[n++]=e>>>8&255,i[n++]=e>>>16&255,i[n++]=e>>>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 m(e,t){return 55296==(64512&e.charCodeAt(t))&&!(t<0||t+1>=e.length)&&56320==(64512&e.charCodeAt(t+1))}function y(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];const r=[];if("string"==typeof e)if("hex"!==t){let t=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);n<128?r[t++]=n:n<2048?(r[t++]=n>>6|192,r[t++]=63&n|128):m(e,i)?(n=65536+((1023&n)<<10)+(1023&e.charCodeAt(++i)),r[t++]=n>>18|240,r[t++]=n>>12&63|128,r[t++]=n>>6&63|128,r[t++]=63&n|128):(r[t++]=n>>12|224,r[t++]=n>>6&63|128,r[t++]=63&n|128)}}else{(e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e);for(let t=0;t<e.length;t+=2)r.push(parseInt(e[t]+e[t+1],16))}else for(let t=0;t<e.length;t++)r[t]=0|e[t];return r}function I(e){return(e>>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}function v(e,t){let r="";for(let n=0;n<e.length;n++){let s=e[n];"little"===t&&(s=I(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(e,t){const r=new Array(4*e.length);for(let i=0,n=0;i<e.length;i++,n+=4){const s=e[i];"big"===t?(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 S(e,t){return e>>>t|e<<32-t}function E(e,t){return e<<t|e>>>32-t}function P(e,t){return e+t>>>0}function N(e,t,r){return e+t+r>>>0}function O(e,t,r,i){return e+t+r+i>>>0}function _(e,t,r,i,n){return e+t+r+i+n>>>0}function A(e,t,r,i){return 0===e?x(t,r,i):1===e||3===e?function(e,t,r){return e^t^r}(t,r,i):2===e?T(t,r,i):void 0}function x(e,t,r){return e&t^~e&r}function T(e,t,r){return e&t^e&r^t&r}function F(e){return S(e,2)^S(e,13)^S(e,22)}function C(e){return S(e,6)^S(e,11)^S(e,25)}function R(e){return S(e,7)^S(e,18)^e>>>3}const V=[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],B=[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],U=[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 K(e,t,r,i){return e<=15?t^r^i:e<=31?t&r|~t&i:e<=47?(t|~r)^i:e<=63?t&i|r&~i:t^(r|~i)}function L(e){return e<=15?0:e<=31?1518500249:e<=47?1859775393:e<=63?2400959708:2840853838}function H(e){return e<=15?1352829926:e<=31?1548603684:e<=47?1836072691:e<=63?2053994217:0}function q(e,t,r,i){const n=e[t],s=i+e[t+1]>>>0,a=(s<i?1:0)+r+n;e[t]=a>>>0,e[t+1]=s}function M(e,t,r,i){return(t+i>>>0<t?1:0)+e+r>>>0}function $(e,t,r,i){return t+i>>>0}function z(e,t,r,i,n,s,a,o){let c=0,d=t;return d=d+i>>>0,c+=d<t?1:0,d=d+s>>>0,c+=d<s?1:0,d=d+o>>>0,c+=d<o?1:0,e+r+n+a+c>>>0}function W(e,t,r,i,n,s,a,o,c,d){let u=0,h=t;return h=h+i>>>0,u+=h<t?1:0,h=h+s>>>0,u+=h<s?1:0,h=h+o>>>0,u+=h<o?1:0,h=h+d>>>0,u+=h<d?1:0,e+r+n+a+c+u>>>0}function j(e,t,r){return(t<<32-r|e>>>r)>>>0}function X(e,t,r){return(e<<32-r|t>>>r)>>>0}function G(e,t,r){return e>>>r}function Y(e,t,r){return(e<<32-r|t>>>r)>>>0}class J extends g{h;constructor(){super(512,160,192,64),this.endian="little",this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}_update(e,t){let r,i=this.h[0],n=this.h[1],s=this.h[2],a=this.h[3],o=this.h[4],c=i,d=n,u=s,h=a,l=o;for(let f=0;f<80;f++)r=P(E(O(i,K(f,n,s,a),e[V[f]+t],L(f)),D[f]),o),i=o,o=a,a=E(s,10),s=n,n=r,r=P(E(O(c,K(79-f,d,u,h),e[B[f]+t],H(f)),U[f]),l),c=l,l=h,h=E(u,10),u=d,d=r;r=N(this.h[1],s,h),this.h[1]=N(this.h[2],a,l),this.h[2]=N(this.h[3],o,c),this.h[3]=N(this.h[4],i,d),this.h[4]=N(this.h[0],n,u),this.h[0]=r}_digest(){return k(this.h,"little")}_digestHex(){return v(this.h,"little")}}class Z extends g{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(e,t){const r=this.W;let i;for(void 0===t&&(t=0),i=0;i<16;i++)r[i]=e[t+i];for(;i<r.length;i++)r[i]=O(S(n=r[i-2],17)^S(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],d=this.h[4],u=this.h[5],h=this.h[6],l=this.h[7];for(w(this.k.length===r.length),i=0;i<r.length;i++){const e=_(l,C(d),x(d,u,h),this.k[i],r[i]),t=P(F(s),T(s,a,o));l=h,h=u,u=d,d=P(c,e),c=o,o=a,a=s,s=P(e,t)}this.h[0]=P(this.h[0],s),this.h[1]=P(this.h[1],a),this.h[2]=P(this.h[2],o),this.h[3]=P(this.h[3],c),this.h[4]=P(this.h[4],d),this.h[5]=P(this.h[5],u),this.h[6]=P(this.h[6],h),this.h[7]=P(this.h[7],l)}_digest(){return k(this.h,"big")}_digestHex(){return v(this.h,"big")}}class Q extends g{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(e,t){const r=this.W;let i;for(void 0===t&&(t=0),i=0;i<16;i++)r[i]=e[t+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 e=~~(i/20),t=_(E(n,5),A(e,s,a,o),c,r[i],this.k[e]);c=o,o=a,a=E(s,30),s=n,n=t}this.h[0]=P(this.h[0],n),this.h[1]=P(this.h[1],s),this.h[2]=P(this.h[2],a),this.h[3]=P(this.h[3],o),this.h[4]=P(this.h[4],c)}_digest(){return k(this.h,"big")}_digestHex(){return v(this.h,"big")}}class ee extends g{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(e,t){const r=this.W;let i;for(i=0;i<32;i++)r[i]=e[t+i];for(;i<r.length;i+=2){const e=he(r[i-4],r[i-3]),t=le(r[i-4],r[i-3]),n=r[i-14],s=r[i-13],a=de(r[i-30],r[i-29]),o=ue(r[i-30],r[i-29]),c=r[i-32],d=r[i-31];r[i]=z(e,t,n,s,a,o,c,d),r[i+1]=t+s+o+d>>>0}}_update(e,t){this._prepareBlock(e,t);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],d=this.h[6],u=this.h[7],h=this.h[8],l=this.h[9],f=this.h[10],p=this.h[11],b=this.h[12],g=this.h[13],m=this.h[14],y=this.h[15];w(this.k.length===r.length);for(let e=0;e<r.length;e+=2){let t=m,w=y,I=oe(h,l),v=ce(h,l);const k=te(h,0,f,0,b),S=re(0,l,0,p,0,g),E=this.k[e],P=this.k[e+1],N=r[e],O=r[e+1],_=W(t,w,I,v,k,S,E,P,N,O),A=w+v+S+P+O>>>0;t=se(i,n),w=ae(i,n),I=ie(i,0,s,0,o),v=ne(0,n,0,a,0,c);const x=M(t,w,I,v),T=$(0,w,0,v);m=b,y=g,b=f,g=p,f=h,p=l,h=M(d,u,_,A),l=$(0,u,0,A),d=o,u=c,o=s,c=a,s=i,a=n,i=M(_,A,x,T),n=$(0,A,0,T)}q(this.h,0,i,n),q(this.h,2,s,a),q(this.h,4,o,c),q(this.h,6,d,u),q(this.h,8,h,l),q(this.h,10,f,p),q(this.h,12,b,g),q(this.h,14,m,y)}_digest(){return k(this.h,"big")}_digestHex(){return v(this.h,"big")}}function te(e,t,r,i,n,s){let a=e&r^~e&n;return a<0&&(a+=4294967296),a}function re(e,t,r,i,n,s){let a=t&i^~t&s;return a<0&&(a+=4294967296),a}function ie(e,t,r,i,n,s){let a=e&r^e&n^r&n;return a<0&&(a+=4294967296),a}function ne(e,t,r,i,n,s){let a=t&i^t&s^i&s;return a<0&&(a+=4294967296),a}function se(e,t){let r=j(e,t,28)^j(t,e,2)^j(t,e,7);return r<0&&(r+=4294967296),r}function ae(e,t){let r=X(e,t,28)^X(t,e,2)^X(t,e,7);return r<0&&(r+=4294967296),r}function oe(e,t){let r=j(e,t,14)^j(e,t,18)^j(t,e,9);return r<0&&(r+=4294967296),r}function ce(e,t){let r=X(e,t,14)^X(e,t,18)^X(t,e,9);return r<0&&(r+=4294967296),r}function de(e,t){let r=j(e,t,1)^j(e,t,8)^G(e,0,7);return r<0&&(r+=4294967296),r}function ue(e,t){let r=X(e,t,1)^X(e,t,8)^Y(e,t,7);return r<0&&(r+=4294967296),r}function he(e,t){let r=j(e,t,19)^j(t,e,29)^G(e,0,6);return r<0&&(r+=4294967296),r}function le(e,t){let r=X(e,t,19)^X(t,e,29)^Y(e,t,6);return r<0&&(r+=4294967296),r}class fe{inner;outer;blockSize=64;outSize=32;constructor(e){let t;for((e=y(e,"hex")).length>this.blockSize&&(e=(new Z).update(e).digest()),w(e.length<=this.blockSize),t=e.length;t<this.blockSize;t++)e.push(0);for(t=0;t<e.length;t++)e[t]^=54;for(this.inner=(new Z).update(e),t=0;t<e.length;t++)e[t]^=106;this.outer=(new Z).update(e)}update(e,t){return this.inner.update(e,t),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}}class pe{inner;outer;blockSize=64;constructor(e){let t;for((e=y(e,"hex")).length>this.blockSize&&(e=(new Q).update(e).digest()),t=e.length;t<this.blockSize;t++)e.push(0);for(t=0;t<e.length;t++)e[t]^=54;for(this.inner=(new Q).update(e),t=0;t<e.length;t++)e[t]^=106;this.outer=(new Q).update(e)}update(e,t){return this.inner.update(e,t),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}}class be{inner;outer;blockSize=128;outSize=32;constructor(e){let t;for((e=y(e,"hex")).length>this.blockSize&&(e=(new ee).update(e).digest()),w(e.length<=this.blockSize),t=e.length;t<this.blockSize;t++)e.push(0);for(t=0;t<e.length;t++)e[t]^=54;for(this.inner=(new ee).update(e),t=0;t<e.length;t++)e[t]^=106;this.outer=(new ee).update(e)}update(e,t){return this.inner.update(e,t),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}}const we=(e,t)=>(new J).update(e,t).digest(),ge=(e,t)=>(new Q).update(e,t).digest(),me=(e,t)=>(new Z).update(e,t).digest(),ye=(e,t)=>(new ee).update(e,t).digest(),Ie=(e,t)=>{const r=(new Z).update(e,t).digest();return(new Z).update(r).digest()},ve=(e,t)=>{const r=(new Z).update(e,t).digest();return(new J).update(r).digest()},ke=(e,t,r)=>new fe(e).update(t,r).digest(),Se=(e,t,r)=>new be(e).update(t,r).digest();function Ee(e,t,r,i,n="sha512"){if("sha512"!==n)throw new Error("Only sha512 is supported in this PBKDF2 implementation");const s=new Array(i),a=[...t,0,0,0,0];let o=0;const c=Math.ceil(i/64);for(let i=1;i<=c;i++){a[t.length]=i>>24&255,a[t.length+1]=i>>16&255,a[t.length+2]=i>>8&255,a[t.length+3]=255&i;const n=Se(e,a);let c=n;for(let t=1;t<r;t++){c=Se(e,c);for(let e=0;e<64;e++)n[e]^=c[e]}for(let e=0;e<n.length;e++)s[o+e]=n[e];o+=64}return s.slice(0,i)}const Pe=e=>e.length%2==1?"0"+e:e,Ne=e=>{let t="";for(const r of e)t+=Pe(r.toString(16));return t},Oe=(e,t)=>{if(Array.isArray(e))return e.slice();if(void 0===e)return[];if("string"!=typeof e)return Array.from(e,(e=>0|e));switch(t){case"hex":return _e(e);case"base64":return Ae(e);default:return function(e){const t=[];for(let r=0;r<e.length;r++){const i=e.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?t.push(n):n<=2047?t.push(192|n>>6,128|63&n):n<=65535?t.push(224|n>>12,128|n>>6&63,128|63&n):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}return t}(e)}},_e=e=>{(e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e);const t=[];for(let r=0;r<e.length;r+=2)t.push(parseInt(e[r]+e[r+1],16));return t},Ae=e=>{const t=[];let r=0,i=0;for(const n of e.replace(/=+$/,""))r=r<<6|"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(n),i+=6,i>=8&&(i-=8,t.push(r>>i&255),r&=(1<<i)-1);return t},xe=e=>{let t="",r=0;for(let i=0;i<e.length;i++){const n=e[i];if(r>0)r--;else if(n<=127)t+=String.fromCharCode(n);else if(n>=192&&n<=223){r=1;const s=(31&n)<<6|63&e[i+1];t+=String.fromCharCode(s)}else if(n>=224&&n<=239){r=2;const s=(15&n)<<12|(63&e[i+1])<<6|63&e[i+2];t+=String.fromCharCode(s)}else if(n>=240&&n<=247){r=3;const s=(7&n)<<18|(63&e[i+1])<<12|(63&e[i+2])<<6|63&e[i+3],a=55296+(s-65536>>10),o=56320+(s-65536&1023);t+=String.fromCharCode(a,o)}}return t},Te=(e,t)=>{switch(t){case"hex":return Ne(e);case"utf8":return xe(e);default:return e}};function Fe(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r,i="";for(r=0;r<e.length;r+=3){const n=e[r],s=r+1<e.length?e[r+1]:0,a=r+2<e.length?e[r+2]:0,o=(3&n)<<4|s>>4,c=(15&s)<<2|a>>6,d=63&a;i+=t.charAt(n>>2)+t.charAt(o),i+=r+1<e.length?t.charAt(c):"=",i+=r+2<e.length?t.charAt(d):"="}return i}const Ce="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Re=e=>{if(""===e||"string"!=typeof e)throw new Error(`Expected base58 string but got “${e}”`);const t=e.match(/[IOl0]/gmu);if(null!==t)throw new Error(`Invalid base58 character “${t.join("")}”`);const r=e.match(/^1+/gmu),i=null!==r?r[0].length:0,n=(e.length-i)*(Math.log(58)/Math.log(256))+1>>>0;var s;return[...new Uint8Array([...new Uint8Array(i),...(e.match(/./gmu)??[]).map((e=>Ce.indexOf(e))).reduce(((e,t)=>e.map((e=>{const r=58*e+t;return t=r>>8,r}))),new Uint8Array(n)).reverse().filter((s=!1,e=>s=s||e))])]},Ve=e=>{const t=Array(256).fill(-1);for(let e=0;e<58;++e)t[Ce.charCodeAt(e)]=e;const r=[];for(const i of e){let e=i;for(let i=0;i<r.length;++i){const n=(t[r[i]]<<8)+e;r[i]=Ce.charCodeAt(n%58),e=n/58|0}for(;0!==e;)r.push(Ce.charCodeAt(e%58)),e=e/58|0}for(const t of e){if(0!==t)break;r.push("1".charCodeAt(0))}return r.reverse(),String.fromCharCode(...r)},Be=(e,t=[0])=>{let r=Ie([...t,...e]);return r=[...t,...e,...r.slice(0,4)],Ve(r)},De=(e,t,r=1)=>{const i=Re(e);let n=i.slice(0,r),s=i.slice(r,-4),a=[...n,...s];return a=Ie(a),i.slice(-4).forEach(((e,t)=>{if(e!==a[t])throw new Error("Invalid checksum")})),"hex"===t&&(n=Ne(n),s=Ne(s)),{prefix:n,data:s}};class Ue{bufs;length;constructor(e){this.bufs=void 0!==e?e:[],this.length=0;for(const e of this.bufs)this.length+=e.length}getLength(){return this.length}toArray(){const e=this.length,t=new Array(e);let r=0;for(const e of this.bufs)for(const i of e)t[r++]=i;return t}write(e){return this.bufs.push(e),this.length+=e.length,this}writeReverse(e){const t=new Array(e.length);for(let r=0;r<t.length;r++)t[r]=e[e.length-1-r];return this.bufs.push(t),this.length+=t.length,this}writeUInt8(e){const t=new Array(1);return t[0]=e,this.write(t),this}writeInt8(e){const t=new Array(1);return t[0]=255&e,this.write(t),this}writeUInt16BE(e){const t=[e>>8&255,255&e];return this.bufs.push(t),this.length+=2,this}writeInt16BE(e){return this.writeUInt16BE(65535&e)}writeUInt16LE(e){const t=[255&e,e>>8&255];return this.bufs.push(t),this.length+=2,this}writeInt16LE(e){return this.writeUInt16LE(65535&e)}writeUInt32BE(e){const t=[e>>24&255,e>>16&255,e>>8&255,255&e];return this.bufs.push(t),this.length+=4,this}writeInt32BE(e){return this.writeUInt32BE(e>>>0)}writeUInt32LE(e){const t=[255&e,e>>8&255,e>>16&255,e>>24&255];return this.bufs.push(t),this.length+=4,this}writeInt32LE(e){return this.writeUInt32LE(e>>>0)}writeUInt64BEBn(e){const t=e.toArray("be",8);return this.write(t),this}writeUInt64LEBn(e){const t=e.toArray("be",8);return this.writeReverse(t),this}writeUInt64LE(e){const t=new d(e).toArray("be",8);return this.writeReverse(t),this}writeVarIntNum(e){const t=Ue.varIntNum(e);return this.write(t),this}writeVarIntBn(e){const t=Ue.varIntBn(e);return this.write(t),this}static varIntNum(e){let t;if(e<253)t=[e];else if(e<65536)t=[253,255&e,e>>8&255];else if(e<4294967296)t=[254,255&e,e>>8&255,e>>16&255,e>>24&255];else{const r=4294967295&e,i=4294967295&Math.floor(e/4294967296);t=[255,255&r,r>>8&255,r>>16&255,r>>24&255,255&i,i>>8&255,i>>16&255,i>>24&255]}return t}static varIntBn(e){let t;if(e.ltn(253))t=[e.toNumber()];else if(e.ltn(65536)){const r=e.toNumber();t=[253,255&r,r>>8&255]}else if(e.lt(new d(4294967296))){const r=e.toNumber();t=[254,255&r,r>>8&255,r>>16&255,r>>24&255]}else{const r=new Ue;r.writeUInt8(255),r.writeUInt64LEBn(e),t=r.toArray()}return t}}class Ke{bin;pos;length;constructor(e=[],t=0){this.bin=e,this.pos=t,this.length=e.length}eof(){return this.pos>=this.length}read(e=this.length){const t=this.pos,r=this.pos+e;return this.pos=r,this.bin.slice(t,r)}readReverse(e=this.length){const t=new Array(e);for(let r=0;r<e;r++)t[r]=this.bin[this.pos+e-1-r];return this.pos+=e,t}readUInt8(){const e=this.bin[this.pos];return this.pos+=1,e}readInt8(){const e=this.bin[this.pos];return this.pos+=1,128&e?e-256:e}readUInt16BE(){const e=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,e}readInt16BE(){const e=this.readUInt16BE();return 32768&e?e-65536:e}readUInt16LE(){const e=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,e}readInt16LE(){const e=this.readUInt16LE();return 32768&e?e-65536:e}readUInt32BE(){const e=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,e}readInt32BE(){const e=this.readUInt32BE();return 2147483648&e?e-4294967296:e}readUInt32LE(){const e=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,e}readInt32LE(){const e=this.readUInt32LE();return 2147483648&e?e-4294967296:e}readUInt64BEBn(){const e=this.bin.slice(this.pos,this.pos+8),t=new d(e);return this.pos=this.pos+8,t}readUInt64LEBn(){const e=this.readReverse(8);return new d(e)}readVarIntNum(){const e=this.readUInt8();let t;switch(e){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if(t=this.readUInt64LEBn(),t.lte(new d(2).pow(new d(53))))return t.toNumber();throw new Error("number too large to retain precision - use readVarIntBn");default:return e}}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 e=this.readUInt8();switch(e){case 253:return new d(this.readUInt16LE());case 254:return new d(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new d(e)}}}const Le=e=>{if(0===e.length)return e;const t=e[e.length-1];if(127&t)return e;if(1===e.length)return[];if(128&e[e.length-2])return e;for(let r=e.length-1;r>0;r--)if(0!==e[r-1])return 128&e[r-1]?(e[r]=t,e.slice(0,r+1)):(e[r-1]|=t,e.slice(0,r));return[]};class He extends p{static red=new l("k256");static a=new d(0).toRed(He.red);static b=new d(7).toRed(He.red);static zero=new d(0).toRed(He.red);x;y;inf;static fromDER(e){if((4===e[0]||6===e[0]||7===e[0])&&e.length-1==64){if(6===e[0]){if(e[e.length-1]%2!=0)throw new Error("Point string value is wrong length")}else if(7===e[0]&&e[e.length-1]%2!=1)throw new Error("Point string value is wrong length");return new He(e.slice(1,33),e.slice(33,65))}if((2===e[0]||3===e[0])&&e.length-1==32)return He.fromX(e.slice(1,33),3===e[0]);throw new Error("Unknown point format")}static fromString(e){const t=Oe(e,"hex");return He.fromDER(t)}static redSqrtOptimized(e){const t=He.red.m.addn(1).iushrn(2);return e.redPow(t)}static fromX(e,t){if("function"==typeof BigInt){function r(e,t){return(e%t+t)%t}function i(e,t,i){let n=BigInt(1);for(e=r(e,i);t>BigInt(0);)(t&BigInt(1))===BigInt(1)&&(n=r(n*e,i)),t>>=BigInt(1),e=r(e*e,i);return n}function n(e,t){const n=i(e,t+BigInt(1)>>BigInt(2),t);return r(n*n,t)===r(e,t)?n:null}const s=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),a=BigInt(7);let o;if(e instanceof d)o=BigInt("0x"+e.toString(16));else if("string"==typeof e)o=BigInt("0x"+e);else if(Array.isArray(e))o=BigInt("0x"+Ne(e).padStart(64,"0"));else{if("number"!=typeof e)throw new Error("Invalid x-coordinate type");o=BigInt(e)}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);(t&&!u||!t&&u)&&(c=s-c);const h=new d(o.toString(16),16),f=new d(c.toString(16),16);return new He(h,f)}{const p=new l("k256"),b=new d(0).toRed(p),w=new d(7).toRed(p),g=new d(0).toRed(p);d.isBN(e)||(e=new d(e,16)),null==e.red&&(e=e.toRed(p));const m=e.redSqr().redMul(e).redIAdd(e.redMul(b)).redIAdd(w);let y=m.redSqrt();if(0!==y.redSqr().redSub(m).cmp(g))throw new Error("invalid point");const I=y.fromRed().isOdd();return(t&&!I||!t&&I)&&(y=y.redNeg()),new He(e,y)}}static fromJSON(e,t){"string"==typeof e&&(e=JSON.parse(e));const r=new He(e[0],e[1],t);if("object"!=typeof e[2])return r;const i=e=>new He(e[0],e[1],t),n=e[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(e,t,r=!0){super("affine"),this.precomputed=null,null===e&&null===t?(this.x=null,this.y=null,this.inf=!0):(d.isBN(e)||(e=new d(e,16)),this.x=e,d.isBN(t)||(t=new d(t,16)),this.y=t,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(e=!0,t){const r=this.curve.p.byteLength(),i=this.getX().toArray("be",r);let n;return n=e?[this.getY().isEven()?2:3].concat(i):[4].concat(i,this.getY().toArray("be",r)),"hex"!==t?n:Ne(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(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return new He(new d(0),new d(0));if(0===this.x?.cmp(e.x??new d(0)))return new He(new d(0),new d(0));let t=this.y?.redSub(e.y??new d(0))??new d(0);0!==t.cmpn(0)&&(t=t.redMul(this.x?.redSub(e.x??new d(0)).redInvm()??new d(1)));const r=t?.redSqr().redISub(this.x??new d(0)).redISub(e.x??new d(0)),i=(t??new d(1)).redMul((this.x??new d(0)).redSub(r??new d(0))).redISub(this.y??new d(0));return new He(r??new d(0),i??new d(0))}dbl(){if(this.inf)return this;const e=(this.y??new d(0)).redAdd(this.y??new d(0));if(0===e.cmpn(0))return new He(new d(0),new d(0));const t=this.curve.a,r=(this.x??new d(0)).redSqr(),i=e.redInvm(),n=r.redAdd(r).redIAdd(r).redIAdd(t).redMul(i),s=n.redSqr().redISub((this.x??new d(0)).redAdd(this.x??new d(0))),a=n.redMul((this.x??new d(0)).redSub(s)).redISub(this.y??new d(0));return new He(s,a)}getX(){return(this.x??new d(0)).fromRed()}getY(){return(this.y??new d(0)).fromRed()}mul(e){return d.isBN(e)||(e=new d(e,16)),this.isInfinity()?this:this._hasDoubles(e)?this._fixedNafMul(e):this._endoWnafMulAdd([this],[e])}mulAdd(e,t,r){const i=[this,t],n=[e,r];return this._endoWnafMulAdd(i,n)}jmulAdd(e,t,r){const i=[this,t],n=[e,r];return this._endoWnafMulAdd(i,n,!0)}eq(e){return this===e||this.inf===e.inf&&(this.inf||0===(this.x??new d(0)).cmp(e.x??new d(0))&&0===(this.y??new d(0)).cmp(e.y??new d(0)))}neg(e){if(this.inf)return this;const t=new He(this.x,(this.y??new d(0)).redNeg());if(!0===e&&null!=this.precomputed){const e=this.precomputed,r=e=>e.neg();t.precomputed={naf:null!=e.naf?{wnd:e.naf.wnd,points:e.naf.points.map(r)}:void 0,doubles:null!=e.doubles?{step:e.doubles.step,points:e.doubles.points.map((e=>e.neg()))}:void 0,beta:void 0}}return t}dblp(e){let t=this;for(let r=0;r<e;r++)t=t.dbl();return t}toJ(){return this.inf?new b(null,null,null):new b(this.x,this.y,this.curve.one)}_getBeta(){if("object"!=typeof this.curve.endo)return;const e=this.precomputed;if("object"==typeof e&&null!==e&&"object"==typeof e.beta&&null!==e.beta)return e.beta;const t=new He((this.x??new d(0)).redMul(this.curve.endo.beta),this.y);if(null!=e){const r=this.curve,i=e=>{if(null===e.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 He(e.x.redMul(r.endo.beta),e.y)};e.beta=t,t.precomputed={beta:null,naf:null!=e.naf?{wnd:e.naf.wnd,points:e.naf.points.map(i)}:void 0,doubles:null!=e.doubles?{step:e.doubles.step,points:e.doubles.points.map(i)}:void 0}}return t}_fixedNafMul(e){if("object"!=typeof this.precomputed||null===this.precomputed)throw new Error("_fixedNafMul requires precomputed values for the point");const t=this._getDoubles(),r=this.curve.getNAF(e,1,this.curve._bitLength);let i=(1<<t.step+1)-(t.step%2==0?2:1);i/=3;const n=[];for(let e=0;e<r.length;e+=t.step){let i=0;for(let n=e+t.step-1;n>=e;n--)i=(i<<1)+r[n];n.push(i)}let s=new b(null,null,null),a=new b(null,null,null);for(let e=i;e>0;e--){for(let r=0;r<n.length;r++){const i=n[r];i===e?a=a.mixedAdd(t.points[r]):i===-e&&(a=a.mixedAdd(t.points[r].neg()))}s=s.add(a)}return s.toP()}_wnafMulAdd(e,t,r,i,n){const s=this.curve._wnafT1.map((e=>e.toNumber())),a=this.curve._wnafT2.map((()=>[])),o=this.curve._wnafT3.map((()=>[]));let c=0;for(let r=0;r<i;r++){const i=t[r]._getNAFPoints(e);s[r]=i.wnd,a[r]=i.points}for(let e=i-1;e>=1;e-=2){const i=e-1,n=e;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=[t[i],null,null,t[n]];0===(t[i].y??new d(0)).cmp(t[n].y??new d(0))?(u[1]=t[i].add(t[n]),u[2]=t[i].toJ().mixedAdd(t[n].neg())):0===(t[i].y??new d(0)).cmp((t[n].y??new d(0)).redNeg())?(u[1]=t[i].toJ().mixedAdd(t[n]),u[2]=t[i].add(t[n].neg())):(u[1]=t[i].toJ().mixedAdd(t[n]),u[2]=t[i].toJ().mixedAdd(t[n].neg()));const h=[-3,-1,-5,-7,0,7,5,1,3],l=this.curve.getJSF(r[i],r[n]);c=Math.max(l[0].length,c),o[i]=new Array(c),o[n]=new Array(c);for(let e=0;e<c;e++){const t=0|l[0][e],r=0|l[1][e];o[i][e]=h[3*(t+1)+(r+1)],o[n][e]=0,a[i]=u}}let u=new b(null,null,null);const h=this.curve._wnafT4;for(let e=c;e>=0;e--){let t=0;for(;e>=0;){let r=!0;for(let t=0;t<i;t++)h[t]=new d("number"==typeof o[t][e]?o[t][e]:0),h[t].isZero()||(r=!1);if(!r)break;t++,e--}if(e>=0&&t++,u=u.dblp(t),e<0)break;const r=new d(1),n=new d(2);for(let e=0;e<i;e++){const t=h[e];let i;0!==t.cmpn(0)&&(i=t.isNeg()?a[e][t.neg().sub(r).div(n).toNumber()].neg():a[e][t.sub(r).div(n).toNumber()],u="affine"===i.type?u.mixedAdd(i):u.add(i))}}for(let e=0;e<i;e++)a[e]=[];return!0===n?u:u.toP()}_endoWnafMulAdd(e,t,r){const i=new Array(2*e.length),n=new Array(2*e.length);let s;for(s=0;s<e.length;s++){const r=this.curve._endoSplit(t[s]);let a=e[s],o=a._getBeta()??new He(new d(0),new d(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 e=0;e<2*s;e++)i[e]=null,n[e]=null;return a}_hasDoubles(e){if(null==this.precomputed)return!1;const t=this.precomputed.doubles;return"object"==typeof t&&t.points.length>=Math.ceil((e.bitLength()+1)/t.step)}_getDoubles(e,t){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.doubles&&null!==this.precomputed.doubles)return this.precomputed.doubles;const r=[this];let i=this;for(let n=0;n<(t??0);n+=e??1){for(let t=0;t<(e??1);t++)i=i.dbl();r.push(i)}return{step:e??1,points:r}}_getNAFPoints(e){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.naf&&null!==this.precomputed.naf)return this.precomputed.naf;const t=[this],r=(1<<e)-1,i=1===r?null:this.dbl();for(let e=1;e<r;e++)null!==i&&(t[e]=t[e-1].add(i));return{wnd:e,points:t}}}let qe;class Me{p;red;redN;zero;one;two;g;n;a;b;tinv;zeroA;threeA;endo;_endoWnafT1;_endoWnafT2;_wnafT1;_wnafT2;_wnafT3;_wnafT4;_bitLength;static assert(e,t="Elliptic curve assertion failed"){if(!e)throw new Error(t)}getNAF(e,t,r){const i=new Array(Math.max(e.bitLength(),r)+1);i.fill(0);const n=1<<t+1,s=e.clone();for(let e=0;e<i.length;e++){let t;const r=s.andln(n-1);s.isOdd()?(t=r>(n>>1)-1?(n>>1)-r:r,s.isubn(t)):t=0,i[e]=t,s.iushrn(1)}return i}getJSF(e,t){const r=[[],[]];e=e.clone(),t=t.clone();let i=0,n=0;for(;e.cmpn(-i)>0||t.cmpn(-n)>0;){let s,a,o=e.andln(3)+i&3,c=t.andln(3)+n&3;if(3===o&&(o=-1),3===c&&(c=-1),1&o){const t=e.andln(7)+i&7;s=3!==t&&5!==t||2!==c?o:-o}else s=0;if(r[0].push(s),1&c){const e=t.andln(7)+n&7;a=3!==e&&5!==e||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),e.iushrn(1),t.iushrn(1)}return r}static cachedProperty(e,t,r){const i="_"+t;e.prototype[t]=function(){return void 0!==this[i]?this[i]:this[i]=r.call(this)}}static parseBytes(e){return"string"==typeof e?Oe(e,"hex"):e}static intFromLE(e){return new d(e,"hex","le")}constructor(){if(void 0!==qe)return qe;qe=this;const e={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 d(e.p,16),this.red=new l(e.prime),this.zero=new d(0).toRed(this.red),this.one=new d(1).toRed(this.red),this.two=new d(2).toRed(this.red),this.n=new d(e.n,16),this.g=He.fromJSON(e.g,e.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 d(e.a,16).toRed(this.red),this.b=new d(e.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(e),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}_getEndomorphism(e){if(!this.zeroA||1!==this.p.modrn(3))return;let t,r,i;if(void 0!==e.beta)t=new d(e.beta,16).toRed(this.red);else{const e=this._getEndoRoots(this.p);if(null===e)throw new Error("Failed to get endomorphism roots for beta.");t=e[0].cmp(e[1])<0?e[0]:e[1],t=t.toRed(this.red)}if(void 0!==e.lambda)r=new d(e.lambda,16);else{const e=this._getEndoRoots(this.n);if(null===e)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(e[0])?.x,n=null!=this.g.x?this.g.x.redMul(t):void 0;if(null!=i&&null!=n&&0===i.cmp(n))r=e[0];else{if(r=e[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(t):void 0;if(null==i||null==n)throw new Error("Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.");Me.assert(0===i.cmp(n),"Lambda selection does not match computed beta.")}}return i="object"==typeof e.basis&&null!==e.basis?e.basis.map((function(e){return{a:new d(e.a,16),b:new d(e.b,16)}})):this._getEndoBasis(r),{beta:t,lambda:r,basis:i}}_getEndoRoots(e){const t=e===this.p?this.red:new f(e),r=new d(2).toRed(t).redInvm(),i=r.redNeg(),n=new d(3).toRed(t).redNeg().redSqrt().redMul(r);return[i.redAdd(n).fromRed(),i.redSub(n).fromRed()]}_getEndoBasis(e){const t=this.n.ushrn(Math.floor(this.n.bitLength()/2));let r,i,n,s,a,o,c=e,u=this.n.clone(),h=new d(1),l=new d(0),f=new d(0),p=new d(1),b=new d(0),w=0,g=new d(0),m=new d(0);for(;0!==c.cmpn(0);){const e=u.div(c);g=u.sub(e.mul(c)),m=f.sub(e.mul(h));const a=p.sub(e.mul(l));if(void 0===n&&g.cmp(t)<0)r=b.neg(),i=h,n=g.neg(),s=m;else if(void 0!==n&&2==++w)break;b=g,u=c,c=g,f=h,h=m,p=l,l=a}if(void 0===r||void 0===i||void 0===n||void 0===s)throw new Error("Failed to compute Endo Basis values");a=g.neg(),o=m;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(e){if(null==this.endo)throw new Error("Endomorphism is not defined.");const t=this.endo.basis,r=t[0],i=t[1],n=i.b.mul(e).divRound(this.n),s=r.b.neg().mul(e).divRound(this.n),a=n.mul(r.a),o=s.mul(i.a),c=n.mul(r.b),d=s.mul(i.b);return{k1:e.sub(a).sub(o),k2:c.add(d).neg()}}validate(e){if(e.inf)return!0;const t=e.x,r=e.y;if(null===t||null===r)throw new Error("Point coordinates cannot be null");const i=this.a.redMul(t),n=t.redSqr().redMul(t).redIAdd(i).redIAdd(this.b);return 0===r.redSqr().redISub(n).cmpn(0)}}class $e{r;s;static fromDER(e,t){const r=(e,t)=>{const r=e[t.place++];if(128&r)throw new Error("Invalid DER entity length");return r};e=Oe(e,t);const i=new class{place;constructor(){this.place=0}};if(48!==e[i.place++])throw new Error("Signature DER must start with 0x30");if(r(e,i)+i.place!==e.length)throw new Error("Signature DER invalid");if(2!==e[i.place++])throw new Error("Signature DER invalid");const n=r(e,i);let s=e.slice(i.place,n+i.place);if(i.place+=n,2!==e[i.place++])throw new Error("Signature DER invalid");const a=r(e,i);if(e.length!==a+i.place)throw new Error("Invalid R-length in signature DER");let o=e.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 $e(new d(s),new d(o))}static fromCompact(e,t){if(65!==(e=Oe(e,t)).length)throw new Error("Invalid Compact Signature");const r=e[0];if(r<27||r>=35)throw new Error("Invalid Compact Byte");return new $e(new d(e.slice(1,33)),new d(e.slice(33,65)))}constructor(e,t){this.r=e,this.s=t}verify(e,t,r){const i=new d(me(e,r),16);return Xe(i,this,t)}toString(e){return this.toDER(e)}toDER(e){const t=(e,t)=>{if(!(t<128))throw new Error("len must be < 0x80");e.push(t)},r=e=>{let t=0;const r=e.length-1;for(;0===e[t]&&!(128&e[t+1])&&t<r;)t++;return 0===t?e:e.slice(t)};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];t(s,i.length),s=s.concat(i),s.push(2),t(s,n.length);const a=s.concat(n);let o=[48];return t(o,a.length),o=o.concat(a),"hex"===e?Ne(o):"base64"===e?Fe(o):o}toCompact(e,t,r){if(e<0||e>3)throw new Error("Invalid recovery param");if("boolean"!=typeof t)throw new Error("Invalid compressed param");let i=27+e;t&&(i+=4);let n=[i];return n=n.concat(this.r.toArray("be",32)),n=n.concat(this.s.toArray("be",32)),"hex"===r?Ne(n):"base64"===r?Fe(n):n}RecoverPublicKey(e,t){const r=this.r,i=this.s,n=!!(1&e),s=e>>1,a=new Me,o=a.n,c=a.g,d=0!==s?r.add(o):r,u=He.fromX(d,n);if(!u.mul(o).isInfinity())throw new Error("nR is not at infinity");const h=t.neg().umod(o),l=r.invm(o),f=l.mul(i).umod(o),p=l.mul(h).umod(o),b=c.mul(p).add(u.mul(f)),w=new Ge(b);return w.validate(),w}CalculateRecoveryFactor(e,t){for(let r=0;r<4;r++){let i;try{i=this.RecoverPublicKey(r,t)}catch{continue}if(e.eq(i))return r}throw new Error("Unable to find valid recovery factor")}}class ze{K;V;constructor(e,t){if(e=Oe(e,"hex"),t=Oe(t,"hex"),e.length<32)throw new Error("Not enough entropy. Minimum is 256 bits");const r=e.concat(t);this.K=new Array(32),this.V=new Array(32);for(let e=0;e<32;e++)this.K[e]=0,this.V[e]=1;this.update(r)}hmac(){return new fe(this.K)}update(e){let t=this.hmac().update(this.V).update([0]);void 0!==e&&(t=t.update(e)),this.K=t.digest(),this.V=this.hmac().update(this.V).digest(),void 0!==e&&(this.K=this.hmac().update(this.V).update([1]).update(e).digest(),this.V=this.hmac().update(this.V).digest())}generate(e){let t=[];for(;t.length<e;)this.V=this.hmac().update(this.V).digest(),t=t.concat(this.V);const r=t.slice(0,e);return this.update(),Ne(r)}}function We(e,t,r=new Me){const i=8*e.byteLength()-r.n.bitLength();return i>0&&e.iushrn(i),null===t&&e.cmp(r.n)>=0?e.sub(r.n):e}const je=(e,t,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")},h=BigInt("0x"+e.toString(16)),l=BigInt("0x"+t.toString(16));if(l<=n||l>=o)throw new Error("Invalid private key");function f(e,t){const r=e.toString(16).padStart(2*t,"0"),i=new Uint8Array(t);for(let e=0;e<t;e++)i[e]=parseInt(r.substr(2*e,2),16);return i}const p=32,b=f(l,p),w=f(h,p),g=new ze(Array.from(b),Array.from(w)),m=o-s;let y=0;function I(e,t,r=!0){const i=e.toString(2).length-t.toString(2).length;return i>0&&(e>>=BigInt(i)),!r&&e>=t?e-t:e}function v(e){if("function"==typeof e){const t=e(y).toString(16);return BigInt("0x"+t)}if(null!=e&&d.isBN(e)){const t=e.toString(16);return BigInt("0x"+t)}{const e=g.generate(p);return BigInt("0x"+e)}}function k(e,t){return(e%t+t)%t}function S(e,t){let r=s,i=n,a=k(e,t),o=t;for(;a>s;){const e=o/a,t=i-r*e,n=o-a*e;i=r,r=t,o=a,a=n}return k(r,t)}function E(e,t){if(null===e)return t;if(null===t)return e;if(e.x===t.x&&e.y===k(-t.y,c))return null;let r;if(e.x===t.x&&e.y===t.y){if(e.y===n)return null;const t=k(BigInt(3)*e.x*e.x,c);r=k(t*S(a*e.y,c),c)}else{const i=k(t.y-e.y,c);r=k(i*S(t.x-e.x,c),c)}const i=k(r*r-e.x-t.x,c);return{x:i,y:k(r*(e.x-i)-e.y,c)}}function P(e,t){let r=t,i=null;for(;e>BigInt(0);)e%BigInt(2)===BigInt(1)&&(i=null===i?r:E(i,r)??i),r=E(r,r)??r,e>>=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=v(i);if(O=I(O,o,!0),O<=s||O>=m){if(i instanceof d)throw new Error("Invalid fixed custom K value (must be more than 1 and less than N-1)");continue}const _=P(O,u);if(null===_){if(i instanceof d)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,o);if(A===n){if(i instanceof d)throw new Error("Invalid fixed custom K value (when multiplied by G, the resulting x coordinate mod N must not be zero)");continue}const x=S(O,o),T=k(A*l,o);let F=k(x*(h+T),o);if(F===n){if(i instanceof d)throw new Error("Invalid fixed custom K value (when used with the key, it cannot create a zero value for S)");continue}r&&F>o/a&&(F=o-F);const C=new d(A.toString(16),16),R=new d(F.toString(16),16);return new $e(C,R)}}else{const V=new Me;e=We(e);const B=V.n.byteLength(),D=t.toArray("be",B),U=e.toArray("be",B),K=new ze(D,U),L=V.n.subn(1);for(let H=0;;H++){let q="function"==typeof i?i(H):d.isBN(i)?i:new d(K.generate(B),16);if(null==q)throw new Error("k is undefined");if(q=We(q,!0),q.cmpn(1)<=0||q.cmp(L)>=0){if(d.isBN(i))throw new Error("Invalid fixed custom K value (must be more than 1 and less than N-1)");continue}const M=V.g.mul(q);if(M.isInfinity()){if(d.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 $=M.getX().umod(V.n);if(0===$.cmpn(0)){if(d.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(V.n).mul($.mul(t).iadd(e));if(z=z.umod(V.n),0!==z.cmpn(0))return r&&z.cmp(V.n.ushrn(1))>0&&(z=V.n.sub(z)),new $e($,z);if(d.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")},Xe=(e,t,r)=>{if("function"==typeof BigInt){const i=BigInt(0),n=BigInt(1),s=BigInt(2),a=BigInt(3),o=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),c=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),d={x:BigInt("0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"),y:BigInt("0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8")},u=(e,t)=>(e%t+t)%t,h=(e,t)=>{let[r,s]=[e,t],[a,o]=[BigInt(1),BigInt(0)];for(;s!==i;){const e=r/s;[r,s]=[s,r-e*s],[a,o]=[o,a-e*o]}return r>n?i:u(a,t)},l=(e,t,r)=>u(e*t,r),f=(e,t,r)=>u(e-t,r),p=BigInt(4),b=BigInt(8),w=e=>{const{X:t,Y:r,Z:c}=e;if(r===i)return{X:i,Y:n,Z:i};const d=l(r,r,o),u=l(p,l(t,d,o),o),h=l(a,l(t,t,o),o),w=f(l(h,h,o),l(s,u,o),o);return{X:w,Y:f(l(h,f(u,w,o),o),l(b,l(d,d,o),o),o),Z:l(s,l(r,c,o),o)}},g=(e,t)=>{if(e.Z===i)return t;if(t.Z===i)return e;const r=l(e.Z,e.Z,o),a=l(t.Z,t.Z,o),c=l(e.X,a,o),d=l(t.X,r,o),u=l(e.Y,l(a,t.Z,o),o),h=l(t.Y,l(r,e.Z,o),o),p=f(d,c,o),b=f(h,u,o);if(p===i)return b===i?w(e):{X:i,Y:n,Z:i};const g=l(p,p,o),m=l(p,g,o),y=l(c,g,o),I=f(f(l(b,b,o),m,o),l(s,y,o),o);return{X:I,Y:f(l(b,f(y,I,o),o),l(u,m,o),o),Z:l(p,l(e.Z,t.Z,o),o)}},m=(e,t)=>{const r={X:t.x,Y:t.y,Z:n};let s={X:i,Y:n,Z:i};const a=e.toString(2);for(let e=0;e<a.length;e++)s=w(s),"1"===a[e]&&(s=g(s,r));return s},y=(e,t,r)=>{const{r:n,s}=r,a=e;if(n<=i||n>=c||s<=i||s>=c)return!1;const f=h(s,c);if(f===i)return!1;const p=l(a,f,c),b=l(n,f,c),w=m(p,d),y=m(b,t),I=g(w,y);if(I.Z===i)return!1;const v=h(I.Z,o);if(v===i)return!1;const k=l(v,v,o),S=l(I.X,k,o);return u(S,c)===n},I=BigInt("0x"+e.toString(16));if(null==r.x||null==r.y)throw new Error("Invalid public key: missing coordinates.");return y(I,{x:BigInt("0x"+r.x.toString(16)),y:BigInt("0x"+r.y.toString(16))},{r:BigInt("0x"+t.r.toString(16)),s:BigInt("0x"+t.s.toString(16))})}{const i=new Me;e=We(e);const n=t.r,s=t.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(e).umod(i.n),c=a.mul(n).umod(i.n),d=i.g.jmulAdd(o,r,c);return!d.isInfinity()&&d.eqXToP(n)}};class Ge extends He{static fromPrivateKey(e){const t=(new Me).g.mul(e);return new Ge(t.x,t.y)}static fromString(e){const t=He.fromString(e);return new Ge(t.x,t.y)}static fromDER(e){const t=He.fromDER(e);return new Ge(t.x,t.y)}constructor(e,t=null,r=!0){if(e instanceof He)super(e.getX(),e.getY());else{if(null===t&&r&&"string"==typeof e&&(66===e.length||130===e.length))throw new Error('You are using the "new PublicKey()" constructor with a DER hex string. You need to use "PublicKey.fromString()" instead.');super(e,t,r)}}deriveSharedSecret(e){if(!this.validate())throw new Error("Public key not valid for ECDH secret derivation");return this.mul(e)}verify(e,t,r){const i=new d(me(e,r),16);return Xe(i,t,this)}toDER(e){return"hex"===e?this.encode(!0,e):this.encode(!0)}toHash(e){const t=ve(this.encode(!0));return"hex"===e?Ne(t):t}toAddress(e=[0]){if("string"==typeof e)if("testnet"===e||"test"===e)e=[111];else{if("mainnet"!==e&&"main"!==e)throw new Error(`Invalid prefix ${e}`);e=[0]}return Be(this.toHash(),e)}deriveChild(e,t){const r=this.deriveSharedSecret(e),i=Oe(t,"utf8"),n=ke(r.encode(!0),i),s=(new Me).g.mul(new d(n)),a=this.add(s);return new Ge(a.x,a.y)}static fromMsgHashAndCompactSignature(e,t,r){const i=Oe(t,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 $e(new d(i.slice(1,33)),new d(i.slice(33,65))).RecoverPublicKey(s,e)}}class Ye{_rand;constructor(){const e=()=>{throw new Error("No secure random number generator is available in this environment.")};if(this._rand=e,"object"==typeof self)self.crypto?.getRandomValues?this._rand=e=>{const t=new Uint8Array(e);return self.crypto.getRandomValues(t),[...t]}:this._rand=e;else try{const e=require("crypto");"function"==typeof e.randomBytes&&(this._rand=t=>[...e.randomBytes(t)])}catch{this._rand=e}}generate(e){return this._rand(e)}}let Je=null;const Ze=e=>(null==Je&&(Je=new Ye),Je.generate(e));class Qe{x;y;constructor(e,t){const r=(new Me).p;this.x=e.umod(r),this.y=t.umod(r)}toString(){return Ve(this.x.toArray())+"."+Ve(this.y.toArray())}static fromString(e){const[t,r]=e.split(".");return new Qe(new d(Re(t)),new d(Re(r)))}}class et{points;threshold;constructor(e,t){this.points=e,this.threshold=t??e.length}static fromPrivateKey(e,t){const r=(new Me).p,i=[new Qe(new d(0),new d(e.toArray()))];for(let e=1;e<t;e++){const e=new d(Ze(32)).umod(r),t=new d(Ze(32)).umod(r);i.push(new Qe(e,t))}return new et(i)}valueAt(e){const t=(new Me).p;let r=new d(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=e.sub(s).umod(t),c=a.sub(s).umod(t).invm(t),d=o.mul(c).umod(t);n=n.mul(d).umod(t)}r=r.add(n).umod(t)}return r}}class tt{points;threshold;integrity;constructor(e,t,r){this.points=e,this.threshold=t,this.integrity=r}static fromBackupFormat(e){let t=0,r="";const i=e.map(((e,i)=>{const n=e.split(".");if(4!==n.length)throw new Error("Invalid share format in share "+i.toString()+'. Expected format: "x.y.t.i" - received '+e);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 d=parseInt(o);if(0!==i&&t!==d)throw new Error("Threshold mismatch in share "+i.toString());if(0!==i&&r!==c)throw new Error("Integrity mismatch in share "+i.toString());return t=d,r=c,Qe.fromString([s,a].join("."))}));return new tt(i,t,r)}toBackupFormat(){return this.points.map((e=>e.toString()+"."+this.threshold.toString()+"."+this.integrity))}}class rt extends d{static fromRandom(){return new rt(Ze(32))}static fromString(e,t="hex"){return new rt(super.fromString(e,t).toArray())}static fromHex(e){return new rt(super.fromHex(e,"big"))}static fromWif(e,t=1){const r=De(e,void 0,t);if(33!==r.data.length)throw new Error("Invalid WIF length");if(1!==r.data[32])throw new Error("Invalid WIF padding");return new rt(r.data.slice(0,32))}constructor(e=0,t=10,r="be",i="apply"){if(e instanceof d?(super(),e.copy(this)):super(e,t,r),"nocheck"!==i){const e=this.checkInField();if(!e.inField){if("error"===i)throw new Error("Input is out of field");d.move(this,e.modN)}}}checkInField(){const e=new Me,t=this.mod(e.n);return{inField:0===this.cmp(t),modN:t}}isValid(){return this.checkInField().inField}sign(e,t,r=!0,i){const n=new d(me(e,t),16);return je(n,this,r,i)}verify(e,t,r){const i=new d(me(e,r),16);return Xe(i,t,this.toPublicKey())}toPublicKey(){const e=(new Me).g.mul(this);return new Ge(e.x,e.y)}toWif(e=[128]){if(!this.isValid())throw new Error("Value is out of field");return Be([...this.toArray("be",32),1],e)}toAddress(e=[0]){return this.toPublicKey().toAddress(e)}toHex(){return super.toHex(32)}toString(e="hex",t=64){return super.toString(e,t)}deriveSharedSecret(e){if(!e.validate())throw new Error("Public key not valid for ECDH secret derivation");return e.mul(this)}deriveChild(e,t){const r=this.deriveSharedSecret(e),i=Oe(t,"utf8"),n=ke(r.encode(!0),i),s=new Me;return new rt(this.add(new d(n)).mod(s.n).toArray())}toKeyShares(e,t){if("number"!=typeof e||"number"!=typeof t)throw new Error("threshold and totalShares must be numbers");if(e<2)throw new Error("threshold must be at least 2");if(t<2)throw new Error("totalShares must be at least 2");if(e>t)throw new Error("threshold should be less than or equal to totalShares");const r=et.fromPrivateKey(this,e),i=[];for(let e=0;e<t;e++){const e=new d(rt.fromRandom().toArray()),t=r.valueAt(e);i.push(new Qe(e,t))}const n=this.toPublicKey().toHash("hex").slice(0,8);return new tt(i,e,n)}toBackupShares(e,t){return this.toKeyShares(e,t).toBackupFormat()}static fromBackupShares(e){return rt.fromKeyShares(tt.fromBackupFormat(e))}static fromKeyShares(e){const{points:t,threshold:r,integrity:i}=e;if(r<2)throw new Error("threshold must be at least 2");if(t.length<r)throw new Error(`At least ${r} shares are required to reconstruct the private key`);for(let e=0;e<r;e++)for(let i=e+1;i<r;i++)if(t[e].x.eq(t[i].x))throw new Error("Duplicate share detected, each must be unique.");const n=new et(t,r),s=new rt(n.valueAt(new d(0)).toArray());if(s.toPublicKey().toHash("hex").slice(0,8)!==i)throw new Error("Integrity hash mismatch");return s}}const it=new Uint8Array([99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22]),nt=[[0,0,0,0],[1,0,0,0],[2,0,0,0],[4,0,0,0],[8,0,0,0],[16,0,0,0],[32,0,0,0],[64,0,0,0],[128,0,0,0],[27,0,0,0],[54,0,0,0]].map((e=>new Uint8Array(e))),st=new Uint8Array(256),at=new Uint8Array(256);for(let e=0;e<256;e++){const t=255&(e<<1^(128&e?27:0));st[e]=t,at[e]=t^e}function ot(e,t,r){for(let i=0;i<4;i++){const n=t[r+i];for(let t=0;t<4;t++)e[t][i]^=n[t]}}function ct(e){for(let t=0;t<4;t++)for(let r=0;r<4;r++)e[t][r]=it[e[t][r]]}function dt(e){for(let t=0;t<4;t++)e[t]=it[e[t]]}function ut(e){const t=e[0];e[0]=e[1],e[1]=e[2],e[2]=e[3],e[3]=t}function ht(e){let t=e[1][0];e[1][0]=e[1][1],e[1][1]=e[1][2],e[1][2]=e[1][3],e[1][3]=t,t=e[2][0];const r=e[2][1];e[2][0]=e[2][2],e[2][1]=e[2][3],e[2][2]=t,e[2][3]=r,t=e[3][3],e[3][3]=e[3][2],e[3][2]=e[3][1],e[3][1]=e[3][0],e[3][0]=t}function lt(e){for(let t=0;t<4;t++){const r=e[0][t],i=e[1][t],n=e[2][t],s=e[3][t];e[0][t]=st[r]^at[i]^n^s,e[1][t]=r^st[i]^at[n]^s,e[2][t]=r^i^st[n]^at[s],e[3][t]=at[r]^i^n^st[s]}}function ft(e,t){let r,i,n,s;const a=[[],[],[],[]],o=[],c=Array.from(t);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(!(t.length<=32))throw new Error("Illegal key length: "+String(t.length));for(;c.length<32;)c.unshift(0);s=15}const d=function(e,t){const r=t.length/4,i=[];for(let e=0;e<t.length;e++)e%4==0&&i.push([]),i[e>>2].push(t[e]);for(let t=r;t<4*e;t++){i[t]=[];const e=i[t-1].slice();if(t%r==0){ut(e),dt(e);const i=nt[t/r];for(let t=0;t<4;t++)e[t]^=i[t]}else r>6&&t%r==4&&dt(e);for(let n=0;n<4;n++)i[t][n]=i[t-r][n]^e[n]}return i}(s,c);for(let t=0;t<4;t++)a[0][t]=e[4*t],a[1][t]=e[4*t+1],a[2][t]=e[4*t+2],a[3][t]=e[4*t+3];for(ot(a,d,0),n=1;n<s;n++)ct(a),ht(a),n+1<s&<(a),ot(a,d,4*n);for(r=0;r<4;r++)for(i=0;i<4;i++)o.push(a[i][r]);return o}const pt=function(e){return[(4278190080&e)>>>24,(16711680&e)>>16,(65280&e)>>8,255&e]},bt=function(e){return new Array(e).fill(0)},wt=[225].concat(bt(15)),gt=function(e,t){for(let r=0;r<e.length;r++)e[r]^=t[r]},mt=function(e){let t,r=0,i=0;for(t=0;t<e.length;t++)i=r,r=1&e[t],e[t]=e[t]>>1,0!==i&&(e[t]=128|e[t]);return e},yt=function(e,t){const r=t.slice(),i=bt(16);for(let t=0;t<16;t++)for(let n=7;n>=0;n--)e[t]&1<<n&>(i,r),1&r[15]?(mt(r),gt(r,wt)):mt(r);return i},It=function(e){let t;const r=e.slice();for(t=15;11!==t&&(r[t]=r[t]+1,256===r[t]);t--)r[t]=0;return r};function vt(e,t){let r=bt(16);for(let i=0;i<e.length;i+=16){const n=r.slice();for(let t=0;t<16;t++)n[t]^=e[i+t]??0;r=yt(n,t)}return r}function kt(e,t,r){if(0===e.length)return[];const i=new Array(e.length);let n=t,s=0;const a=Math.ceil(e.length/16);for(let t=0;t<a;t++){const o=ft(n,r),c=Math.min(16,e.length-s);for(let t=0;t<c;t++)i[s]=e[s]^o[t],s++;t+1<a&&(n=It(n))}return i}class St extends d{static fromRandom(){return new St(Ze(32))}encrypt(e,t){const r=Ze(32);e=Oe(e,t);const{result:i,authenticationTag:n}=function(e,t,r,i){let n,s;const a=ft(bt(16),i);n=[...r],12===r.length?n=n.concat(bt(3)).concat([1]):(r.length%16!=0&&(n=n.concat(bt(16-r.length%16))),n=n.concat(bt(8)),n=vt(n.concat(bt(4)).concat(pt(8*r.length)),a));const o=kt(e,It(n),i);return s=t.slice(),0===t.length?s=s.concat(bt(16)):t.length%16!=0&&(s=s.concat(bt(16-t.length%16))),s=s.concat(o),0===o.length?s=s.concat(bt(16)):o.length%16!=0&&(s=s.concat(bt(16-o.length%16))),s=s.concat(bt(4)).concat(pt(8*t.length)).concat(bt(4)).concat(pt(8*o.length)),{result:o,authenticationTag:kt(vt(s,a),n,i)}}(e,[],r,this.toArray("be",32));return Te([...r,...i,...n],t)}decrypt(e,t){const r=(e=Oe(e,t)).slice(0,32),i=e.slice(32),n=i.slice(-16),s=function(e,t,r,i,n){let s,a;const o=ft(bt(16),n);s=[...r],12===r.length?s=s.concat(bt(3)).concat([1]):(r.length%16!=0&&(s=s.concat(bt(16-r.length%16))),s=s.concat(bt(8)),s=vt(s.concat(bt(4)).concat(pt(8*r.length)),o));const c=kt(e,It(s),n);return a=t.slice(),0===t.length?a=a.concat(bt(16)):t.length%16!=0&&(a=a.concat(bt(16-t.length%16))),a=a.concat(e),0===e.length?a=a.concat(bt(16)):e.length%16!=0&&(a=a.concat(bt(16-e.length%16))),a=a.concat(bt(4)).concat(pt(8*t.length)).concat(bt(4)).concat(pt(8*e.length)),kt(vt(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 Te(s,t)}}class Et extends $e{static SIGHASH_ALL=1;static SIGHASH_NONE=2;static SIGHASH_SINGLE=3;static SIGHASH_FORKID=64;static SIGHASH_ANYONECANPAY=128;scope;static format(e){const t={sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,sequence:e.inputSequence},r=[...e.otherInputs];function i(t){const r=new Ue;if(void 0===t)for(const t of e.outputs){const e=t.satoshis??0;r.writeUInt64LE(e);const i=t.lockingScript?.toBinary()??[];r.writeVarIntNum(i.length),r.write(i)}else{const i=e.outputs[t];if(void 0===i)throw new Error(`Output at index ${t} 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 Ie(i)}r.splice(e.inputIndex,0,t);let n=new Array(32).fill(0),s=new Array(32).fill(0),a=new Array(32).fill(0);e.scope&Et.SIGHASH_ANYONECANPAY||(n=(()=>{const e=new Ue;for(const t of r){if(void 0===t.sourceTXID){if(null==t.sourceTransaction)throw new Error("Missing sourceTransaction for input");e.write(t.sourceTransaction.hash())}else e.writeReverse(Oe(t.sourceTXID,"hex"));e.writeUInt32LE(t.sourceOutputIndex)}const t=e.toArray();return Ie(t)})()),e.scope&Et.SIGHASH_ANYONECANPAY||(31&e.scope)===Et.SIGHASH_SINGLE||(31&e.scope)===Et.SIGHASH_NONE||(s=(()=>{const e=new Ue;for(const t of r){const r=t.sequence??4294967295;e.writeUInt32LE(r)}const t=e.toArray();return Ie(t)})()),(31&e.scope)!==Et.SIGHASH_SINGLE&&(31&e.scope)!==Et.SIGHASH_NONE?a=i():(31&e.scope)===Et.SIGHASH_SINGLE&&e.inputIndex<e.outputs.length&&(a=i(e.inputIndex));const o=new Ue;o.writeInt32LE(e.transactionVersion),o.write(n),o.write(s),o.writeReverse(Oe(e.sourceTXID,"hex")),o.writeUInt32LE(e.sourceOutputIndex);const c=e.subscript.toBinary();o.writeVarIntNum(c.length),o.write(c),o.writeUInt64LE(e.sourceSatoshis);const d=t.sequence;return o.writeUInt32LE(d),o.write(a),o.writeUInt32LE(e.lockTime),o.writeUInt32LE(e.scope>>>0),o.toArray()}static fromChecksigFormat(e){if(0===e.length){const e=new d(1),t=new d(1);return new Et(e,t,1)}const t=e[e.length-1],r=e.slice(0,e.length-1),i=$e.fromDER(r);return new Et(i.r,i.s,t)}constructor(e,t,r){super(e,t),this.scope=r}hasLowS(){return!this.s.ltn(1)&&!this.s.gt(new d("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex"))}toChecksigFormat(){return[...this.toDER(),this.scope]}}class Pt{curve;constructor(){this.curve=new Me}generateProof(e,t,r,i){const n=rt.fromRandom(),s=n.toPublicKey(),a=r.mul(n),o=this.computeChallenge(t,r,i,a,s);return{R:s,SPrime:a,z:n.add(o.mul(e)).umod(this.curve.n)}}verifyProof(e,t,r,i){const{R:n,SPrime:s,z:a}=i,o=this.computeChallenge(e,t,r,s,n),c=this.curve.g.mul(a),d=n.add(e.mul(o));if(!c.eq(d))return!1;const u=t.mul(a),h=s.add(r.mul(o));return!!u.eq(h)}computeChallenge(e,t,r,i,n){const s=[...e.encode(!0),...t.encode(!0),...r.encode(!0),...i.encode(!0),...n.encode(!0)],a=me(s);return new d(a).umod(this.curve.n)}}const Nt={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 e in Nt)Nt[Nt[e]]=e;const Ot=Nt;class _t{chunks;static fromASM(e){const t=[],r=e.split(" ");let i=0;for(;i<r.length;){const e=r[i];let n,s=0;if(e.startsWith("OP_")&&void 0!==Ot[e]&&(n=e,s=Ot[e]),"0"===e)s=0,t.push({op:s}),i+=1;else if("-1"===e)s=Ot.OP_1NEGATE,t.push({op:s}),i+=1;else if(void 0===n){let e=r[i];e.length%2!=0&&(e="0"+e);const n=Oe(e,"hex");if(Te(n,"hex")!==e)throw new Error("invalid hex string in script");const a=n.length;a>=0&&a<Ot.OP_PUSHDATA1?s=a:a<Math.pow(2,8)?s=Ot.OP_PUSHDATA1:a<Math.pow(2,16)?s=Ot.OP_PUSHDATA2:a<Math.pow(2,32)&&(s=Ot.OP_PUSHDATA4),t.push({data:n,op:s}),i+=1}else s===Ot.OP_PUSHDATA1||s===Ot.OP_PUSHDATA2||s===Ot.OP_PUSHDATA4?(t.push({data:Oe(r[i+2],"hex"),op:s}),i+=3):(t.push({op:s}),i+=1)}return new _t(t)}static fromHex(e){if(0===e.length)return _t.fromBinary([]);if(e.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(e))throw new Error("Some elements in this string are not hex encoded.");return _t.fromBinary(Oe(e,"hex"))}static fromBinary(e){e=[...e];const t=[];let r=0;const i=new Ke(e);for(;!i.eof();){const e=i.readUInt8();if(e===Ot.OP_RETURN&&0===r){t.push({op:e,data:i.read()});break}e===Ot.OP_IF||e===Ot.OP_NOTIF||e===Ot.OP_VERIF||e===Ot.OP_VERNOTIF?r++:e===Ot.OP_ENDIF&&r--;let n=0,s=[];if(e>0&&e<Ot.OP_PUSHDATA1)n=e,t.push({data:i.read(n),op:e});else if(e===Ot.OP_PUSHDATA1){try{n=i.readUInt8(),s=i.read(n)}catch{i.read()}t.push({data:s,op:e})}else if(e===Ot.OP_PUSHDATA2){try{n=i.readUInt16LE(),s=i.read(n)}catch{i.read()}t.push({data:s,op:e})}else if(e===Ot.OP_PUSHDATA4){try{n=i.readUInt32LE(),s=i.read(n)}catch{i.read()}t.push({data:s,op:e})}else t.push({op:e})}return new _t(t)}constructor(e=[]){this.chunks=e}toASM(){let e="";for(let t=0;t<this.chunks.length;t++){const r=this.chunks[t];e+=this._chunkToString(r)}return e.slice(1)}toHex(){return Te(this.toBinary(),"hex")}toBinary(){const e=new Ue;for(let t=0;t<this.chunks.length;t++){const r=this.chunks[t],i=r.op;if(e.writeUInt8(i),i===Ot.OP_RETURN&&null!=r.data){e.write(r.data);break}null!=r.data&&(i<Ot.OP_PUSHDATA1?e.write(r.data):i===Ot.OP_PUSHDATA1?(e.writeUInt8(r.data.length),e.write(r.data)):i===Ot.OP_PUSHDATA2?(e.writeUInt16LE(r.data.length),e.write(r.data)):i===Ot.OP_PUSHDATA4&&(e.writeUInt32LE(r.data.length),e.write(r.data)))}return e.toArray()}writeScript(e){return this.chunks=this.chunks.concat(e.chunks),this}writeOpCode(e){return this.chunks.push({op:e}),this}setChunkOpCode(e,t){return this.chunks[e]={op:t},this}writeBn(e){if(e.cmpn(0)===Ot.OP_0)this.chunks.push({op:Ot.OP_0});else if(0===e.cmpn(-1))this.chunks.push({op:Ot.OP_1NEGATE});else if(e.cmpn(1)>=0&&e.cmpn(16)<=0)this.chunks.push({op:e.toNumber()+Ot.OP_1-1});else{const t=e.toSm("little");this.writeBin(t)}return this}writeBin(e){let t;if(e.length>0&&e.length<Ot.OP_PUSHDATA1)t=e.length;else if(0===e.length)t=Ot.OP_0;else if(e.length<Math.pow(2,8))t=Ot.OP_PUSHDATA1;else if(e.length<Math.pow(2,16))t=Ot.OP_PUSHDATA2;else{if(!(e.length<Math.pow(2,32)))throw new Error("You can't push that much data");t=Ot.OP_PUSHDATA4}return this.chunks.push({data:e,op:t}),this}writeNumber(e){return this.writeBn(new d(e)),this}removeCodeseparators(){const e=[];for(let t=0;t<this.chunks.length;t++)this.chunks[t].op!==Ot.OP_CODESEPARATOR&&e.push(this.chunks[t]);return this.chunks=e,this}findAndDelete(e){const t=e.toHex();for(let e=0;e<this.chunks.length;e++)t===new _t([this.chunks[e]]).toHex()&&this.chunks.splice(e,1);return this}isPushOnly(){for(let e=0;e<this.chunks.length;e++)if(this.chunks[e].op>Ot.OP_16)return!1;return!0}isLockingScript(){throw new Error("Not implemented")}isUnlockingScript(){throw new Error("Not implemented")}_chunkToString(e){const t=e.op;let r="";return r=void 0===e.data?`${r} ${Ot[t]}`:`${r} ${Ne(e.data)}`,r}}class At extends _t{isLockingScript(){return!0}isUnlockingScript(){return!1}}class xt extends _t{isLockingScript(){return!1}isUnlockingScript(){return!0}}const Tt=1073741824,Ft=Math.pow(2,31)-1,Ct=!0,Rt=Object.freeze(new d(-1).toScriptNum()),Vt=Object.freeze(Array.from({length:17},((e,t)=>Object.freeze(new d(t).toScriptNum()))));class Bt{sourceTXID;sourceOutputIndex;sourceSatoshis;lockingScript;transactionVersion;otherInputs;outputs;inputIndex;unlockingScript;inputSequence;lockTime;context;programCounter;lastCodeSeparator;stack;altStack;ifStack;memoryLimit;stackMem;altStackMem;constructor(e){this.sourceTXID=e.sourceTXID,this.sourceOutputIndex=e.sourceOutputIndex,this.sourceSatoshis=e.sourceSatoshis,this.lockingScript=e.lockingScript,this.transactionVersion=e.transactionVersion,this.otherInputs=e.otherInputs,this.outputs=e.outputs,this.inputIndex=e.inputIndex,this.unlockingScript=e.unlockingScript,this.inputSequence=e.inputSequence,this.lockTime=e.lockTime,this.memoryLimit=e.memoryLimit??32e6,this.stack=[],this.altStack=[],this.ifStack=[],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}ensureStackMem(e){this.stackMem+e>this.memoryLimit&&this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}ensureAltStackMem(e){this.altStackMem+e>this.memoryLimit&&this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}pushStack(e){this.ensureStackMem(e.length),this.stack.push(e),this.stackMem+=e.length}pushStackCopy(e){this.ensureStackMem(e.length);const t=e.slice();this.stack.push(t),this.stackMem+=t.length}popStack(){0===this.stack.length&&this.scriptEvaluationError("Attempted to pop from an empty stack.");const e=this.stack.pop();return this.stackMem-=e.length,e}stackTop(e=-1){return(0===this.stack.length||this.stack.length<Math.abs(e)||e>=0&&e>=this.stack.length)&&this.scriptEvaluationError(`Stack underflow accessing element at index ${e}. Stack length is ${this.stack.length}.`),this.stack[this.stack.length+e]}pushAltStack(e){this.ensureAltStackMem(e.length),this.altStack.push(e),this.altStackMem+=e.length}popAltStack(){0===this.altStack.length&&this.scriptEvaluationError("Attempted to pop from an empty alt stack.");const e=this.altStack.pop();return this.altStackMem-=e.length,e}checkSignatureEncoding(e){if(0===e.length)return!0;if(!function(e){if(e.length<9||e.length>73)return!1;if(48!==e[0])return!1;if(e[1]!==e.length-3)return!1;const t=e[2],r=e[3];if(2!==t)return!1;if(0===r)return!1;if(5+r>=e.length)return!1;const i=4+r,n=e[i],s=e[i+1];if(2!==n)return!1;if(0===s)return!1;if(128&e[4])return!1;if(r>1&&0===e[4]&&!(128&e[5]))return!1;const a=i+2;return!(128&e[a]||s>1&&0===e[a]&&!(128&e[a+1])||r+s+7!==e.length)}(e))return this.scriptEvaluationError("The signature format is invalid."),!1;try{const t=Et.fromChecksigFormat(e);if(!t.hasLowS())return this.scriptEvaluationError("The signature must have a low S value."),!1;if(!(t.scope&Et.SIGHASH_FORKID))return this.scriptEvaluationError("The signature must use SIGHASH_FORKID."),!1}catch(e){return this.scriptEvaluationError("The signature format is invalid."),!1}return!0}checkPublicKeyEncoding(e){if(0===e.length)return this.scriptEvaluationError("Public key is empty."),!1;if(e.length<33)return this.scriptEvaluationError("The public key is too short, it must be at least 33 bytes."),!1;if(4===e[0]){if(65!==e.length)return this.scriptEvaluationError("The non-compressed public key must be 65 bytes."),!1}else{if(2!==e[0]&&3!==e[0])return this.scriptEvaluationError("The public key is in an unknown format."),!1;if(33!==e.length)return this.scriptEvaluationError("The compressed public key must be 33 bytes."),!1}try{Ge.fromDER(e)}catch(e){return this.scriptEvaluationError("The public key is in an unknown format."),!1}return!0}verifySignature(e,t,r){const i=Et.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:e.scope}),n=new d(Ie(i));return Xe(n,e,t)}step(){if(this.stackMem>this.memoryLimit)return this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;if(this.altStackMem>this.memoryLimit)return this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;"UnlockingScript"===this.context&&this.programCounter>=this.unlockingScript.chunks.length&&(this.context="LockingScript",this.programCounter=0);const e="UnlockingScript"===this.context?this.unlockingScript:this.lockingScript;if(this.programCounter>=e.chunks.length)return!1;const t=e.chunks[this.programCounter],r=t.op;void 0===r&&this.scriptEvaluationError(`Missing opcode in ${this.context} at pc=${this.programCounter}.`),Array.isArray(t.data)&&t.data.length>Tt&&this.scriptEvaluationError(`Data push > 1073741824 bytes (pc=${this.programCounter}).`);const i=!this.ifStack.includes(!1);var n;if(i&&((n=r)===Ot.OP_2MUL||n===Ot.OP_2DIV||n===Ot.OP_VERIF||n===Ot.OP_VERNOTIF||n===Ot.OP_VER)&&this.scriptEvaluationError(`This opcode is currently disabled. (Opcode: ${Ot[r]}, PC: ${this.programCounter})`),i&&r>=0&&r<=Ot.OP_PUSHDATA4)(function(e){const t=e.data,r=e.op;return!(Array.isArray(t)&&(0===t.length?r!==Ot.OP_0:1===t.length&&t[0]>=1&&t[0]<=16?r!==Ot.OP_1+(t[0]-1):1===t.length&&129===t[0]?r!==Ot.OP_1NEGATE:t.length<=75?r!==t.length:t.length<=255?r!==Ot.OP_PUSHDATA1:t.length<=65535&&r!==Ot.OP_PUSHDATA2))})(t)||this.scriptEvaluationError(`This data is not minimally-encoded. (PC: ${this.programCounter})`),this.pushStack(Array.isArray(t.data)?t.data:[]);else if(i||r>=Ot.OP_IF&&r<=Ot.OP_ENDIF){let e,t,n,s,a,o,c,u,h,l,f,p,b,w,g,m,y,I,v,k,S,E,P,N,O,_;switch(r){case Ot.OP_1NEGATE:this.pushStackCopy(Rt);break;case Ot.OP_0:this.pushStackCopy(Vt[0]);break;case Ot.OP_1:case Ot.OP_2:case Ot.OP_3:case Ot.OP_4:case Ot.OP_5:case Ot.OP_6:case Ot.OP_7:case Ot.OP_8:case Ot.OP_9:case Ot.OP_10:case Ot.OP_11:case Ot.OP_12:case Ot.OP_13:case Ot.OP_14:case Ot.OP_15:case Ot.OP_16:p=r-(Ot.OP_1-1),this.pushStackCopy(Vt[p]);break;case Ot.OP_NOP:case Ot.OP_NOP2:case Ot.OP_NOP3:case Ot.OP_NOP1:case Ot.OP_NOP4:case Ot.OP_NOP5:case Ot.OP_NOP6:case Ot.OP_NOP7:case Ot.OP_NOP8:case Ot.OP_NOP9:case Ot.OP_NOP10:case Ot.OP_NOP11:case Ot.OP_NOP12:case Ot.OP_NOP13:case Ot.OP_NOP14:case Ot.OP_NOP15:case Ot.OP_NOP16:case Ot.OP_NOP17:case Ot.OP_NOP18:case Ot.OP_NOP19:case Ot.OP_NOP20:case Ot.OP_NOP21:case Ot.OP_NOP22:case Ot.OP_NOP23:case Ot.OP_NOP24:case Ot.OP_NOP25:case Ot.OP_NOP26:case Ot.OP_NOP27:case Ot.OP_NOP28:case Ot.OP_NOP29:case Ot.OP_NOP30:case Ot.OP_NOP31:case Ot.OP_NOP32:case Ot.OP_NOP33:case Ot.OP_NOP34:case Ot.OP_NOP35:case Ot.OP_NOP36:case Ot.OP_NOP37:case Ot.OP_NOP38:case Ot.OP_NOP39:case Ot.OP_NOP40:case Ot.OP_NOP41:case Ot.OP_NOP42:case Ot.OP_NOP43:case Ot.OP_NOP44:case Ot.OP_NOP45:case Ot.OP_NOP46:case Ot.OP_NOP47:case Ot.OP_NOP48:case Ot.OP_NOP49:case Ot.OP_NOP50:case Ot.OP_NOP51:case Ot.OP_NOP52:case Ot.OP_NOP53:case Ot.OP_NOP54:case Ot.OP_NOP55:case Ot.OP_NOP56:case Ot.OP_NOP57:case Ot.OP_NOP58:case Ot.OP_NOP59:case Ot.OP_NOP60:case Ot.OP_NOP61:case Ot.OP_NOP62:case Ot.OP_NOP63:case Ot.OP_NOP64:case Ot.OP_NOP65:case Ot.OP_NOP66:case Ot.OP_NOP67:case Ot.OP_NOP68:case Ot.OP_NOP69:case Ot.OP_NOP70:case Ot.OP_NOP71:case Ot.OP_NOP72:case Ot.OP_NOP73:case Ot.OP_NOP77:break;case Ot.OP_IF:case Ot.OP_NOTIF:w=!1,i&&(this.stack.length<1&&this.scriptEvaluationError("OP_IF and OP_NOTIF require at least one item on the stack when they are used!"),e=this.popStack(),w=this.castToBool(e),r===Ot.OP_NOTIF&&(w=!w)),this.ifStack.push(w);break;case Ot.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 Ot.OP_ENDIF:0===this.ifStack.length&&this.scriptEvaluationError("OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop();break;case Ot.OP_VERIFY:this.stack.length<1&&this.scriptEvaluationError("OP_VERIFY requires at least one item to be on the stack."),t=this.stackTop(),w=this.castToBool(t),w||this.scriptEvaluationError("OP_VERIFY requires the top stack value to be truthy."),this.popStack();break;case Ot.OP_RETURN:"UnlockingScript"===this.context?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.ifStack=[],this.programCounter--;break;case Ot.OP_TOALTSTACK:this.stack.length<1&&this.scriptEvaluationError("OP_TOALTSTACK requires at oeast one item to be on the stack."),this.pushAltStack(this.popStack());break;case Ot.OP_FROMALTSTACK:this.altStack.length<1&&this.scriptEvaluationError("OP_FROMALTSTACK requires at least one item to be on the stack."),this.pushStack(this.popAltStack());break;case Ot.OP_2DROP:this.stack.length<2&&this.scriptEvaluationError("OP_2DROP requires at least two items to be on the stack."),this.popStack(),this.popStack();break;case Ot.OP_2DUP:this.stack.length<2&&this.scriptEvaluationError("OP_2DUP requires at least two items to be on the stack."),t=this.stackTop(-2),n=this.stackTop(-1),this.pushStackCopy(t),this.pushStackCopy(n);break;case Ot.OP_3DUP:this.stack.length<3&&this.scriptEvaluationError("OP_3DUP requires at least three items to be on the stack."),t=this.stackTop(-3),n=this.stackTop(-2),s=this.stackTop(-1),this.pushStackCopy(t),this.pushStackCopy(n),this.pushStackCopy(s);break;case Ot.OP_2OVER:this.stack.length<4&&this.scriptEvaluationError("OP_2OVER requires at least four items to be on the stack."),t=this.stackTop(-4),n=this.stackTop(-3),this.pushStackCopy(t),this.pushStackCopy(n);break;case Ot.OP_2ROT:{this.stack.length<6&&this.scriptEvaluationError("OP_2ROT requires at least six items to be on the stack.");const e=this.popStack(),t=this.popStack(),r=this.popStack(),i=this.popStack(),n=this.popStack(),s=this.popStack();this.pushStack(i),this.pushStack(r),this.pushStack(t),this.pushStack(e),this.pushStack(s),this.pushStack(n);break}case Ot.OP_2SWAP:{this.stack.length<4&&this.scriptEvaluationError("OP_2SWAP requires at least four items to be on the stack.");const e=this.popStack(),t=this.popStack(),r=this.popStack(),i=this.popStack();this.pushStack(t),this.pushStack(e),this.pushStack(i),this.pushStack(r);break}case Ot.OP_IFDUP:this.stack.length<1&&this.scriptEvaluationError("OP_IFDUP requires at least one item to be on the stack."),t=this.stackTop(),this.castToBool(t)&&this.pushStackCopy(t);break;case Ot.OP_DEPTH:this.pushStack(new d(this.stack.length).toScriptNum());break;case Ot.OP_DROP:this.stack.length<1&&this.scriptEvaluationError("OP_DROP requires at least one item to be on the stack."),this.popStack();break;case Ot.OP_DUP:this.stack.length<1&&this.scriptEvaluationError("OP_DUP requires at least one item to be on the stack."),this.pushStackCopy(this.stackTop());break;case Ot.OP_NIP:this.stack.length<2&&this.scriptEvaluationError("OP_NIP requires at least two items to be on the stack."),n=this.popStack(),this.popStack(),this.pushStack(n);break;case Ot.OP_OVER:this.stack.length<2&&this.scriptEvaluationError("OP_OVER requires at least two items to be on the stack."),this.pushStackCopy(this.stackTop(-2));break;case Ot.OP_PICK:case Ot.OP_ROLL:{this.stack.length<2&&this.scriptEvaluationError(`${Ot[r]} requires at least two items to be on the stack.`),u=d.fromScriptNum(this.popStack(),Ct),p=u.toNumber(),(p<0||p>=this.stack.length)&&this.scriptEvaluationError(`${Ot[r]} requires the top stack element to be 0 or a positive number less than the current size of the stack.`);const e=this.stack[this.stack.length-1-p];r===Ot.OP_ROLL?(this.stack.splice(this.stack.length-1-p,1),this.stackMem-=e.length,this.pushStack(e)):this.pushStackCopy(e);break}case Ot.OP_ROT:this.stack.length<3&&this.scriptEvaluationError("OP_ROT requires at least three items to be on the stack."),c=this.popStack(),o=this.popStack(),a=this.popStack(),this.pushStack(o),this.pushStack(c),this.pushStack(a);break;case Ot.OP_SWAP:this.stack.length<2&&this.scriptEvaluationError("OP_SWAP requires at least two items to be on the stack."),o=this.popStack(),a=this.popStack(),this.pushStack(o),this.pushStack(a);break;case Ot.OP_TUCK:this.stack.length<2&&this.scriptEvaluationError("OP_TUCK requires at least two items to be on the stack."),t=this.stackTop(-1),this.ensureStackMem(t.length),this.stack.splice(this.stack.length-2,0,t.slice()),this.stackMem+=t.length;break;case Ot.OP_SIZE:this.stack.length<1&&this.scriptEvaluationError("OP_SIZE requires at least one item to be on the stack."),this.pushStack(new d(this.stackTop().length).toScriptNum());break;case Ot.OP_AND:case Ot.OP_OR:case Ot.OP_XOR:{this.stack.length<2&&this.scriptEvaluationError(`${Ot[r]} requires at least two items on the stack.`),n=this.popStack(),t=this.popStack(),t.length!==n.length&&this.scriptEvaluationError(`${Ot[r]} requires the top two stack items to be the same size.`);const e=new Array(t.length);for(let i=0;i<t.length;i++)r===Ot.OP_AND?e[i]=t[i]&n[i]:r===Ot.OP_OR?e[i]=t[i]|n[i]:e[i]=t[i]^n[i];this.pushStack(e);break}case Ot.OP_INVERT:{this.stack.length<1&&this.scriptEvaluationError("OP_INVERT requires at least one item to be on the stack."),e=this.popStack();const t=new Array(e.length);for(let r=0;r<e.length;r++)t[r]=255&~e[r];this.pushStack(t);break}case Ot.OP_LSHIFT:case Ot.OP_RSHIFT:{if(this.stack.length<2&&this.scriptEvaluationError(`${Ot[r]} requires at least two items to be on the stack.`),l=d.fromScriptNum(this.popStack(),Ct),t=this.popStack(),p=l.toNumber(),p<0&&this.scriptEvaluationError(`${Ot[r]} requires the top item on the stack not to be negative.`),0===t.length){this.pushStack([]);break}let e;h=new d(t),e=r===Ot.OP_LSHIFT?h.ushln(p):h.ushrn(p);const i=e.toArray("le",t.length);this.pushStack(i);break}case Ot.OP_EQUAL:case Ot.OP_EQUALVERIFY:this.stack.length<2&&this.scriptEvaluationError(`${Ot[r]} requires at least two items to be on the stack.`),n=this.popStack(),t=this.popStack(),w=function(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}(t,n),this.pushStack(w?[1]:[]),r===Ot.OP_EQUALVERIFY&&(w||this.scriptEvaluationError("OP_EQUALVERIFY requires the top two stack items to be equal."),this.popStack());break;case Ot.OP_1ADD:case Ot.OP_1SUB:case Ot.OP_NEGATE:case Ot.OP_ABS:case Ot.OP_NOT:case Ot.OP_0NOTEQUAL:switch(this.stack.length<1&&this.scriptEvaluationError(`${Ot[r]} requires at least one item to be on the stack.`),u=d.fromScriptNum(this.popStack(),Ct),r){case Ot.OP_1ADD:u=u.add(new d(1));break;case Ot.OP_1SUB:u=u.sub(new d(1));break;case Ot.OP_NEGATE:u=u.neg();break;case Ot.OP_ABS:u.isNeg()&&(u=u.neg());break;case Ot.OP_NOT:u=new d(0===u.cmpn(0)?1:0);break;case Ot.OP_0NOTEQUAL:u=new d(0!==u.cmpn(0)?1:0)}this.pushStack(u.toScriptNum());break;case Ot.OP_ADD:case Ot.OP_SUB:case Ot.OP_MUL:case Ot.OP_DIV:case Ot.OP_MOD:case Ot.OP_BOOLAND:case Ot.OP_BOOLOR:case Ot.OP_NUMEQUAL:case Ot.OP_NUMEQUALVERIFY:case Ot.OP_NUMNOTEQUAL:case Ot.OP_LESSTHAN:case Ot.OP_GREATERTHAN:case Ot.OP_LESSTHANOREQUAL:case Ot.OP_GREATERTHANOREQUAL:case Ot.OP_MIN:case Ot.OP_MAX:{this.stack.length<2&&this.scriptEvaluationError(`${Ot[r]} requires at least two items to be on the stack.`),n=this.popStack(),t=this.popStack(),l=d.fromScriptNum(n,Ct),h=d.fromScriptNum(t,Ct);let e=0;switch(r){case Ot.OP_MUL:e=h.byteLength()+l.byteLength();break;case Ot.OP_ADD:case Ot.OP_SUB:e=Math.max(h.byteLength(),l.byteLength())+1;break;default:e=Math.max(h.byteLength(),l.byteLength())}this.ensureStackMem(e);let i=new d(0);switch(r){case Ot.OP_ADD:i=h.add(l);break;case Ot.OP_SUB:i=h.sub(l);break;case Ot.OP_MUL:i=h.mul(l);break;case Ot.OP_DIV:0===l.cmpn(0)&&this.scriptEvaluationError("OP_DIV cannot divide by zero!"),i=h.div(l);break;case Ot.OP_MOD:0===l.cmpn(0)&&this.scriptEvaluationError("OP_MOD cannot divide by zero!"),i=h.mod(l);break;case Ot.OP_BOOLAND:i=new d(0!==h.cmpn(0)&&0!==l.cmpn(0)?1:0);break;case Ot.OP_BOOLOR:i=new d(0!==h.cmpn(0)||0!==l.cmpn(0)?1:0);break;case Ot.OP_NUMEQUAL:case Ot.OP_NUMEQUALVERIFY:i=new d(0===h.cmp(l)?1:0);break;case Ot.OP_NUMNOTEQUAL:i=new d(0!==h.cmp(l)?1:0);break;case Ot.OP_LESSTHAN:i=new d(h.cmp(l)<0?1:0);break;case Ot.OP_GREATERTHAN:i=new d(h.cmp(l)>0?1:0);break;case Ot.OP_LESSTHANOREQUAL:i=new d(h.cmp(l)<=0?1:0);break;case Ot.OP_GREATERTHANOREQUAL:i=new d(h.cmp(l)>=0?1:0);break;case Ot.OP_MIN:i=h.cmp(l)<0?h:l;break;case Ot.OP_MAX:i=h.cmp(l)>0?h:l}this.pushStack(i.toScriptNum()),r===Ot.OP_NUMEQUALVERIFY&&(this.castToBool(this.stackTop())||this.scriptEvaluationError("OP_NUMEQUALVERIFY requires the top stack item to be truthy."),this.popStack());break}case Ot.OP_WITHIN:this.stack.length<3&&this.scriptEvaluationError("OP_WITHIN requires at least three items to be on the stack."),f=d.fromScriptNum(this.popStack(),Ct),l=d.fromScriptNum(this.popStack(),Ct),h=d.fromScriptNum(this.popStack(),Ct),w=h.cmp(l)>=0&&h.cmp(f)<0,this.pushStack(w?[1]:[]);break;case Ot.OP_RIPEMD160:case Ot.OP_SHA1:case Ot.OP_SHA256:case Ot.OP_HASH160:case Ot.OP_HASH256:{this.stack.length<1&&this.scriptEvaluationError(`${Ot[r]} requires at least one item to be on the stack.`),e=this.popStack();let t=[];r===Ot.OP_RIPEMD160?t=we(e):r===Ot.OP_SHA1?t=ge(e):r===Ot.OP_SHA256?t=me(e):r===Ot.OP_HASH160?t=ve(e):r===Ot.OP_HASH256&&(t=Ie(e)),this.pushStack(t);break}case Ot.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case Ot.OP_CHECKSIG:case Ot.OP_CHECKSIGVERIFY:{this.stack.length<2&&this.scriptEvaluationError(`${Ot[r]} requires at least two items to be on the stack.`),I=this.popStack(),y=this.popStack(),this.checkSignatureEncoding(y)&&this.checkPublicKeyEncoding(I)||this.scriptEvaluationError(`${Ot[r]} requires correct encoding for the public key and signature.`);const e=("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1);if(m=new _t(e),m.findAndDelete((new _t).writeBin(y)),g=!1,y.length>0)try{v=Et.fromChecksigFormat(y),k=Ge.fromDER(I),g=this.verifySignature(v,k,m)}catch(e){g=!1}this.pushStack(g?[1]:[]),r===Ot.OP_CHECKSIGVERIFY&&(g||this.scriptEvaluationError("OP_CHECKSIGVERIFY requires that a valid signature is provided."),this.popStack());break}case Ot.OP_CHECKMULTISIG:case Ot.OP_CHECKMULTISIGVERIFY:{S=1,this.stack.length<S&&this.scriptEvaluationError(`${Ot[r]} requires at least 1 item for nKeys.`),N=d.fromScriptNum(this.stackTop(-S),Ct).toNumber(),(N<0||N>Ft)&&this.scriptEvaluationError(`${Ot[r]} requires a key count between 0 and ${Ft}.`),E=++S,S+=N,this.stack.length<S&&this.scriptEvaluationError(`${Ot[r]} stack too small for nKeys and keys. Need ${S}, have ${this.stack.length}.`),O=d.fromScriptNum(this.stackTop(-S),Ct).toNumber(),(O<0||O>N)&&this.scriptEvaluationError(`${Ot[r]} requires the number of signatures to be no greater than the number of keys.`),P=++S,S+=O,this.stack.length<S&&this.scriptEvaluationError(`${Ot[r]} stack too small for N, keys, M, sigs, and dummy. Need ${S}, have ${this.stack.length}.`);const e=("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1);m=new _t(e);for(let e=0;e<O;e++)y=this.stackTop(-P-e),m.findAndDelete((new _t).writeBin(y));for(g=!0;g&&O>0;){if(0===N){g=!1;break}if(y=this.stackTop(-P),I=this.stackTop(-E),this.checkSignatureEncoding(y)&&this.checkPublicKeyEncoding(I)||this.scriptEvaluationError(`${Ot[r]} requires correct encoding for the public key and signature.`),_=!1,y.length>0)try{v=Et.fromChecksigFormat(y),k=Ge.fromDER(I),_=this.verifySignature(v,k,m)}catch(e){_=!1}_&&(P++,O--),E++,N--,O>N&&(g=!1)}let t=1+d.fromScriptNum(this.stackTop(-1),!1).toNumber()+1+d.fromScriptNum(this.stackTop(-(1+d.fromScriptNum(this.stackTop(-1),!1).toNumber()+1)),!1).toNumber()+1-1;for(;t>0;)this.popStack(),t--;this.stack.length<1&&this.scriptEvaluationError(`${Ot[r]} requires an extra item (dummy) to be on the stack.`),this.popStack().length>0&&this.scriptEvaluationError(`${Ot[r]} requires the extra stack item (dummy) to be empty.`),this.pushStack(g?[1]:[]),r===Ot.OP_CHECKMULTISIGVERIFY&&(g||this.scriptEvaluationError("OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."),this.popStack());break}case Ot.OP_CAT:{this.stack.length<2&&this.scriptEvaluationError("OP_CAT requires at least two items to be on the stack."),n=this.popStack(),t=this.popStack();const e=t.concat(n);e.length>Tt&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes."),this.pushStack(e);break}case Ot.OP_SPLIT:{this.stack.length<2&&this.scriptEvaluationError("OP_SPLIT requires at least two items to be on the stack.");const e=this.popStack(),t=this.popStack();p=d.fromScriptNum(e,Ct).toNumber(),(p<0||p>t.length)&&this.scriptEvaluationError("OP_SPLIT requires the first stack item to be a non-negative number less than or equal to the size of the second-from-top stack item."),this.pushStack(t.slice(0,p)),this.pushStack(t.slice(p));break}case Ot.OP_NUM2BIN:{this.stack.length<2&&this.scriptEvaluationError("OP_NUM2BIN requires at least two items to be on the stack."),b=d.fromScriptNum(this.popStack(),Ct).toNumber(),(b>Tt||b<0)&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes or negative size.");let e=this.popStack();if(e=Le(e),e.length>b&&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."),e.length===b){this.pushStack(e);break}const t=new Array(b).fill(0);let r=0;e.length>0&&(r=128&e[e.length-1],e[e.length-1]&=127);for(let r=0;r<e.length;r++)t[r]=e[r];0!==r&&(t[b-1]|=128),this.pushStack(t);break}case Ot.OP_BIN2NUM:{this.stack.length<1&&this.scriptEvaluationError("OP_BIN2NUM requires at least one item to be on the stack."),t=this.popStack();const e=Le(t);(function(e,t=Number.MAX_SAFE_INTEGER){return!(e.length>t||e.length>0&&!(127&e[e.length-1]||!(e.length<=1)&&128&e[e.length-2]))})(e)||this.scriptEvaluationError("OP_BIN2NUM requires that the resulting number is valid."),this.pushStack(e);break}default:this.scriptEvaluationError(`Invalid opcode ${r} (pc=${this.programCounter}).`)}}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, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF 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, found ${this.stack.length}.`),0===this.stack.length?this.scriptEvaluationError("The top stack element must be truthy after script evaluation (stack is empty)."):this.castToBool(this.stackTop())||this.scriptEvaluationError("The top stack element must be truthy after script evaluation."),!0}castToBool(e){if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(0!==e[t])return!(t===e.length-1&&128===e[t]);return!1}scriptEvaluationError(e){const t=`Context: ${this.context}, PC: ${this.programCounter}`,r=this.stack.map((e=>null!=e&&void 0!==e.length?Ne(e):null==e?"null/undef":"INVALID_STACK_ITEM")).join(", "),i=this.altStack.map((e=>null!=e&&void 0!==e.length?Ne(e):null==e?"null/undef":"INVALID_STACK_ITEM")).join(", "),n=`Stack: [${r}] (len: ${this.stack.length}, mem: ${this.stackMem})`,s=`AltStack: [${i}] (len: ${this.altStack.length}, mem: ${this.altStackMem})`,a=`IfStack: [${this.ifStack.join(", ")}]`;throw new Error(`Script evaluation error: ${e}\nTXID: ${this.sourceTXID}, OutputIdx: ${this.sourceOutputIndex}\n${t}\n${n}\n${s}\n${a}`)}}function Dt(e){if(null==e)throw new Error("must have value");return e}class Ut{lock(e){let t;if("string"==typeof e){const r=De(e);if(0!==r.prefix[0]&&111!==r.prefix[0])throw new Error("only P2PKH is supported");t=r.data}else t=e;if(20!==t.length)throw new Error("P2PKH hash length must be 20 bytes");return new At([{op:Ot.OP_DUP},{op:Ot.OP_HASH160},{op:t.length,data:t},{op:Ot.OP_EQUALVERIFY},{op:Ot.OP_CHECKSIG}])}unlock(e,t="all",r=!1,i,n){return{sign:async(s,a)=>{let o=Et.SIGHASH_FORKID;"all"===t&&(o|=Et.SIGHASH_ALL),"none"===t&&(o|=Et.SIGHASH_NONE),"single"===t&&(o|=Et.SIGHASH_SINGLE),r&&(o|=Et.SIGHASH_ANYONECANPAY);const c=s.inputs[a],d=s.inputs.filter(((e,t)=>t!==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 h=Et.format({sourceTXID:u,sourceOutputIndex:Dt(c.sourceOutputIndex),sourceSatoshis:i,transactionVersion:s.version,otherInputs:d,inputIndex:a,outputs:s.outputs,inputSequence:Dt(c.sequence),subscript:n,lockTime:s.lockTime,scope:o}),l=e.sign(me(h)),f=new Et(l.r,l.s,o).toChecksigFormat(),p=e.toPublicKey().encode(!0);return new xt([{op:f.length,data:f},{op:p.length,data:p}])},estimateLength:async()=>108}}}class Kt{type="raw";constructor(e="raw"){this.type=e}lock(e){const t=[{op:Ot.OP_OVER},{op:Ot.OP_3},{op:Ot.OP_SPLIT},{op:Ot.OP_NIP},{op:Ot.OP_1},{op:Ot.OP_SPLIT},{op:Ot.OP_SWAP},{op:Ot.OP_SPLIT},{op:Ot.OP_DROP}];return"raw"!==this.type&&t.push({op:Ot["OP_"+this.type]}),t.push({op:e.length,data:e}),t.push({op:Ot.OP_EQUALVERIFY}),t.push({op:Ot.OP_CHECKSIG}),new At(t)}unlock(e,t,r="all",i=!1){return{sign:async(n,s)=>{void 0===t&&(t=rt.fromRandom());let a=Et.SIGHASH_FORKID;"all"===r&&(a|=Et.SIGHASH_ALL),"none"===r&&(a|=Et.SIGHASH_NONE),"single"===r&&(a|=Et.SIGHASH_SINGLE),i&&(a|=Et.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 d=Et.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 _t,lockTime:n.lockTime,scope:a}),u=t.sign(me(d),void 0,!0,e),h=new Et(u.r,u.s,a).toChecksigFormat(),l=t.toPublicKey().encode(!0);return new xt([{op:h.length,data:h},{op:l.length,data:l}])},estimateLength:async()=>108}}}function Lt(e){if(null==e)throw new Error("must have value");return e}class Ht{wallet;originator;static decode(e){const t=Ge.fromString(Ne(Lt(e.chunks[0].data))),r=[];for(let t=2;t<e.chunks.length;t++){const i=e.chunks[t+1]?.op;let n=e.chunks[t].data??[];if(0===n.length&&(e.chunks[t].op>=80&&e.chunks[t].op<=95?n=[e.chunks[t].op-80]:0===e.chunks[t].op?n=[0]:79===e.chunks[t].op&&(n=[129])),r.push(n),i===Ot.OP_DROP||i===Ot.OP_2DROP)break}return{fields:r,lockingPublicKey:t}}constructor(e,t){this.wallet=e,this.originator=t}async lock(e,t,r,i,n=!1,s=!0,a="before"){const{publicKey:o}=await this.wallet.getPublicKey({protocolID:t,keyID:r,counterparty:i,forSelf:n},this.originator),c=[],d=[];if(c.push({op:o.length/2,data:Oe(o,"hex")}),c.push({op:Ot.OP_CHECKSIG}),s){const n=e.reduce(((e,t)=>[...e,...t]),[]),{signature:s}=await this.wallet.createSignature({data:n,protocolID:t,keyID:r,counterparty:i},this.originator);e.push(s)}for(const t of e)d.push(0===(u=t).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 h=e.length;for(;h>1;)d.push({op:Ot.OP_2DROP}),h-=2;return 0!==h&&d.push({op:Ot.OP_DROP}),new At("before"===a?[...c,...d]:[...d,...c])}unlock(e,t,r,i="all",n=!1,s,a){return{sign:async(o,c)=>{let d=Et.SIGHASH_FORKID;"all"===i&&(d|=Et.SIGHASH_ALL),"none"===i&&(d|=Et.SIGHASH_NONE),"single"===i&&(d|=Et.SIGHASH_SINGLE),n&&(d|=Et.SIGHASH_ANYONECANPAY);const u=o.inputs[c],h=o.inputs.filter(((e,t)=>t!==c)),l=u.sourceTXID??u.sourceTransaction?.id("hex");if(null==l||void 0===l)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=Et.format({sourceTXID:l,sourceOutputIndex:Lt(u.sourceOutputIndex),sourceSatoshis:s,transactionVersion:o.version,otherInputs:h,inputIndex:c,outputs:o.outputs,inputSequence:u.sequence??4294967295,subscript:a,lockTime:o.lockTime,scope:d}),p=me(f),{signature:b}=await this.wallet.createSignature({data:p,protocolID:e,keyID:t,counterparty:r},this.originator),w=$e.fromDER([...b]),g=new Et(w.r,w.s,d).toChecksigFormat();return new xt([{op:g.length,data:g}])},estimateLength:async()=>73}}}class qt{value;constructor(e){this.value=e}async computeFee(e){const t=e=>e>2**32?9:e>65536?5:e>253?3:1;let r=4;r+=t(e.inputs.length);for(let i=0;i<e.inputs.length;i++){const n=e.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(e,i)}r+=t(s),r+=s}r+=t(e.outputs.length);for(const i of e.outputs){r+=8;const e=i.lockingScript.toBinary().length;r+=t(e),r+=e}return r+=4,Math.ceil(r/1e3*this.value)}}class Mt{https;constructor(e){this.https=e}async request(e,t){return await new Promise(((r,i)=>{const n=this.https.request(e,t,(e=>{let t="";e.on("data",(e=>{t+=e})),e.on("end",(()=>{const i=e.statusCode>=200&&e.statusCode<=299,n=e.headers["content-type"],s=""!==t&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(t):t;r({status:e.statusCode,statusText:e.statusMessage,ok:i,data:s})}))}));n.on("error",(e=>{i(e)})),null!==t.data&&void 0!==t.data&&n.write(JSON.stringify(t.data)),n.end()}))}}class $t{fetch;constructor(e){this.fetch=e}async request(e,t){const r={method:t.method,headers:t.headers,body:JSON.stringify(t.data)},i=await this.fetch(e,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 zt(){const e={async request(...e){throw new Error("No method available to perform HTTP request")}};if("undefined"!=typeof window&&"function"==typeof window.fetch)return new $t(window.fetch.bind(window));if("undefined"==typeof require)return e;try{const e=require("https");return new Mt(e)}catch(t){return e}}function Wt(){return`ts-sdk-${Ne(Ze(16))}`}class jt{URL;apiKey;deploymentId;callbackUrl;callbackToken;headers;httpClient;constructor(e,t){if(this.URL=e,"string"==typeof t)this.apiKey=t,this.httpClient=zt(),this.deploymentId=Wt(),this.callbackToken=void 0,this.callbackUrl=void 0;else{const e=t??{},{apiKey:r,deploymentId:i,httpClient:n,callbackToken:s,callbackUrl:a,headers:o}=e;this.apiKey=r,this.httpClient=n??zt(),this.deploymentId=i??Wt(),this.callbackToken=s,this.callbackUrl=a,this.headers=o}}requestHeaders(){const e={"Content-Type":"application/json","XDeployment-ID":this.deploymentId};if(null!=this.apiKey&&""!==this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),null!=this.callbackUrl&&""!==this.callbackUrl&&(e["X-CallbackUrl"]=this.callbackUrl),null!=this.callbackToken&&""!==this.callbackToken&&(e["X-CallbackToken"]=this.callbackToken),null!=this.headers)for(const t in this.headers)e[t]=this.headers[t];return e}async broadcast(e){let t;try{t=e.toHexEF()}catch(r){if("All inputs must have source transactions when serializing to EF format"!==r.message)throw r;t=e.toHex()}const r={method:"POST",headers:this.requestHeaders(),data:{rawTx:t}};try{const e=await this.httpClient.request(`${this.URL}/v1/tx`,r);if(e.ok){const{txid:t,extraInfo:r,txStatus:i,competingTxs:n}=e.data,s={status:"success",txid:t,message:`${i} ${r}`};return null!=n&&(s.competingTxs=n),s}{const t=typeof e.status,r={status:"error",code:"number"===t||"string"===t?e.status.toString():"ERR_UNKNOWN",description:"Unknown error"};let i=e.data;if("string"==typeof i)try{i=JSON.parse(e.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(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}async broadcastMany(e){const t=e.map((e=>{try{return{rawTx:e.toHexEF()}}catch(t){if("All inputs must have source transactions when serializing to EF format"===t.message)return{rawTx:e.toHex()};throw t}})),r={method:"POST",headers:this.requestHeaders(),data:t};try{return(await this.httpClient.request(`${this.URL}/v1/txs`,r)).data}catch(t){const r={status:"error",code:"500",description:"string"==typeof t.message?t.message:"Internal Server Error"};return e.map((()=>r))}}}function Xt(e=!1,t={}){return new jt(e?"https://arc-test.taal.com":"https://arc.taal.com",t)}class Gt{network;apiKey;URL;httpClient;constructor(e="main",t={}){const{apiKey:r,httpClient:i}=t;this.network=e,this.URL=`https://api.whatsonchain.com/v1/bsv/${e}`,this.httpClient=i??zt(),this.apiKey=r??""}async isValidRootForHeight(e,t){const r={method:"GET",headers:this.getHttpHeaders()},i=await this.httpClient.request(`${this.URL}/block/${t}/header`,r);if(i.ok){const{merkleroot:t}=i.data;return t===e}if(404===i.status)return!1;throw new Error(`Failed to verify merkleroot for height ${t} because of an error: ${JSON.stringify(i.data)} `)}async currentHeight(){try{const e={method:"GET",headers:this.getHttpHeaders()},t=await this.httpClient.request(`${this.URL}/block/headers`,e);if(t.ok)return t.data[0].height;throw new Error(`Failed to get current height because of an error: ${JSON.stringify(t.data)} `)}catch(e){throw new Error(`Failed to get current height because of an error: ${e instanceof Error?e.message:String(e)}`)}}getHttpHeaders(){const e={Accept:"application/json"};return"string"==typeof this.apiKey&&""!==this.apiKey.trim()&&(e.Authorization=this.apiKey),e}}function Yt(){return new Gt}class Jt{blockHeight;path;static fromHex(e){return Jt.fromBinary(Oe(e,"hex"))}static fromReader(e,t=!0){const r=e.readVarIntNum(),i=e.readUInt8(),n=Array(i).fill(null).map((()=>[]));let s,a,o;for(let t=0;t<i;t++){for(o=e.readVarIntNum();o>0;){a=e.readVarIntNum(),s=e.readUInt8();const r={offset:a};1&s?r.duplicate=!0:(2&s&&(r.txid=!0),r.hash=Ne(e.read(32).reverse())),Array.isArray(n[t])&&0!==n[t].length||(n[t]=[]),n[t].push(r),o--}n[t].sort(((e,t)=>e.offset-t.offset))}return new Jt(r,n,t)}static fromBinary(e){const t=new Ke(e);return Jt.fromReader(t)}static fromCoinbaseTxidAndHeight(e,t){return new Jt(t,[[{offset:0,hash:e,txid:!0}]])}constructor(e,t,r=!0){this.blockHeight=e,this.path=t;const i=Array(this.path.length).fill(0).map((()=>new Set));let n;this.path.forEach(((e,t)=>{if(0===e.length&&0===t)throw new Error(`Empty level at height: ${t}`);const n=new Set;e.forEach((e=>{if(n.has(e.offset))throw new Error(`Duplicate offset: ${e.offset}, at height: ${t}`);if(n.add(e.offset),0===t){if(!0!==e.duplicate)for(let t=1;t<this.path.length;t++)i[t].add(e.offset>>t^1)}else if(r&&!i[t].has(e.offset))throw new Error(`Invalid offset: ${e.offset}, at height: ${t}, with legal offsets: ${Array.from(i[t]).join(", ")}`)}))})),this.path[0].forEach(((e,t)=>{if(0===t&&(n=this.computeRoot(e.hash)),n!==this.computeRoot(e.hash))throw new Error("Mismatched roots")}))}toBinary(){const e=new Ue;e.writeVarIntNum(this.blockHeight);const t=this.path.length;e.writeUInt8(t);for(let r=0;r<t;r++){const t=Object.keys(this.path[r]).length;e.writeVarIntNum(t);for(const t of this.path[r]){e.writeVarIntNum(t.offset);let r=0;!0===t?.duplicate&&(r|=1),void 0!==t?.txid&&null!==t.txid&&(r|=2),e.writeUInt8(r),1&r||e.write(Oe(t.hash,"hex").reverse())}}return e.toArray()}toHex(){return Ne(this.toBinary())}indexOf(e){const t=this.path[0].find((t=>t.hash===e));if(null==t)throw new Error(`Transaction ID ${e} not found in the Merkle Path`);return t.offset}computeRoot(e){if("string"!=typeof e){const t=this.path[0].find((e=>Boolean(e?.hash)));if(null==t)throw new Error("No valid leaf found in the Merkle Path");e=t.hash}if("string"!=typeof e)throw new Error("Transaction ID is undefined");const t=this.indexOf(e);if("number"!=typeof t)throw new Error(`This proof does not contain the txid: ${e??"undefined"}`);const r=e=>Ne(Ie(Oe(e,"hex").reverse()).reverse());let i=e;if(1===this.path.length&&1===this.path[0].length)return i;for(let e=0;e<this.path.length;e++){this.path[e];const n=t>>e^1,s=this.findOrComputeLeaf(e,n);if("object"!=typeof s)throw new Error(`Missing hash for index ${t} at height ${e}`);i=!0===s.duplicate?r((i??"")+(i??"")):r(n%2!=0?(s.hash??"")+(i??""):(i??"")+(s.hash??""))}return i}findOrComputeLeaf(e,t){const r=e=>Ne(Ie(Oe(e,"hex").reverse()).reverse());let i=this.path[e].find((e=>e.offset===t));if(null!=i)return i;if(0===e)return;const n=e-1,s=t<<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:t,hash:c},i}async verify(e,t){const r=this.computeRoot(e);if(0===this.indexOf(e)){const e=await t.currentHeight();if(this.blockHeight+100<e)return!1}return await t.isValidRootForHeight(r,this.blockHeight)}combine(e){if(this.blockHeight!==e.blockHeight)throw new Error("You cannot combine paths which do not have the same block height.");if(this.computeRoot()!==e.computeRoot())throw new Error("You cannot combine paths which do not have the same root.");const t=[];for(let r=0;r<this.path.length;r++){t.push([]);for(let e=0;e<this.path[r].length;e++)t[r].push(this.path[r][e]);for(let i=0;i<e.path[r].length;i++)if(void 0===t[r].find((t=>t.offset===e.path[r][i].offset)))t[r].push(e.path[r][i]);else if(void 0!==e.path[r][i]?.txid&&null!==e.path[r][i]?.txid){const n=t[r].find((t=>t.offset===e.path[r][i].offset));null!=n&&(n.txid=!0)}}this.path=t,this.trim()}trim(){const e=(e,t)=>{0!==t.length&&t.slice(-1)[0]===e||t.push(e)},t=(e,t)=>{for(let r=e.length;r>=0;r--){const i=this.path[t].findIndex((t=>t.offset===e[r]));i>=0&&this.path[t].splice(i,1)}},r=t=>{const r=[];for(const i of t)e(i>>1,r);return r};let i=[],n=[];for(let e=0;e<this.path.length;e++)this.path[e].sort(((e,t)=>e.offset-t.offset));for(let t=0;t<this.path[0].length;t++){const r=this.path[0][t];if(!0===r.txid)e(r.offset>>1,i);else{const i=r.offset%2==1,s=this.path[0][t+(i?-1:1)];void 0!==s.txid&&null!==s.txid&&s.txid||e(s.offset,n)}}t(n,0);for(let e=1;e<this.path.length;e++)n=i,i=r(i),t(n,e)}}class Zt{_bumpIndex;_tx;_rawTx;_txid;inputTxids=[];isValid=void 0;get bumpIndex(){return this._bumpIndex}set bumpIndex(e){this._bumpIndex=e,this.updateInputTxids()}get hasProof(){return void 0!==this._bumpIndex}get isTxidOnly(){return void 0!==this._txid&&null!==this._txid&&null==this._rawTx&&null==this._tx}get txid(){if(void 0!==this._txid&&null!==this._txid&&""!==this._txid)return this._txid;if(null!=this._tx)return this._txid=this._tx.id("hex"),this._txid;if(null!=this._rawTx)return this._txid=Ne(Ie(this._rawTx)),this._txid;throw new Error("Internal")}get tx(){return null!=this._tx?this._tx:null!=this._rawTx?(this._tx=sr.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(e,t){"string"==typeof e?this._txid=e:Array.isArray(e)?this._rawTx=e:this._tx=e,this.bumpIndex=t,this.updateInputTxids()}static fromTx(e,t){return new Zt(e,t)}static fromRawTx(e,t){return new Zt(e,t)}static fromTxid(e,t){return new Zt(e,t)}updateInputTxids(){if(this.hasProof||null==this.tx)this.inputTxids=[];else{const e={};for(const t of this.tx.inputs)void 0!==t.sourceTXID&&null!==t.sourceTXID&&""!==t.sourceTXID&&(e[t.sourceTXID]=!0);this.inputTxids=Object.keys(e)}}toWriter(e,t){const r=t=>{e.writeUInt8(t)},i=()=>{if(null!=this._rawTx)e.write(this._rawTx);else{if(null==this._tx)throw new Error("a valid serialized Transaction is expected");e.write(this._tx.toBinary())}};t===tr?this.isTxidOnly?(r(ir.TXID_ONLY),(()=>{if(null==this._txid)throw new Error("Transaction ID (_txid) is undefined");e.writeReverse(Oe(this._txid,"hex"))})()):void 0!==this.bumpIndex?(r(ir.RAWTX_AND_BUMP_INDEX),e.writeVarIntNum(this.bumpIndex),i()):(r(ir.RAWTX),i()):(i(),(()=>{void 0===this.bumpIndex?r(ir.RAWTX):(r(ir.RAWTX_AND_BUMP_INDEX),e.writeVarIntNum(this.bumpIndex))})())}static fromReader(e,t){let r,i,n;if(t===tr){const t=e.readUInt8();t===ir.TXID_ONLY?n=Zt.fromTxid(Ne(e.readReverse(32))):(t===ir.RAWTX_AND_BUMP_INDEX&&(i=e.readVarIntNum()),r=sr.fromReader(e),n=Zt.fromTx(r,i))}else r=sr.fromReader(e),i=0!==e.readUInt8()?e.readVarIntNum():void 0,n=Zt.fromTx(r,i);return n}}function Qt(e){if(null==e)throw new Error("Expected a valid value, but got undefined.");return e}const er=4022206465,tr=4022206466,rr=16843009;var ir;!function(e){e[e.RAWTX=0]="RAWTX",e[e.RAWTX_AND_BUMP_INDEX=1]="RAWTX_AND_BUMP_INDEX",e[e.TXID_ONLY=2]="TXID_ONLY"}(ir||(ir={}));class nr{bumps=[];txs=[];version=tr;atomicTxid=void 0;constructor(e=tr){this.version=e}findTxid(e){return this.txs.find((t=>t.txid===e))}makeTxidOnly(e){const t=this.txs.findIndex((t=>t.txid===e));if(-1===t)return;let r=this.txs[t];return r.isTxidOnly||(this.txs.splice(t,1),r=this.mergeTxidOnly(e)),r}findBump(e){return this.bumps.find((t=>t.path[0].some((t=>t.hash===e))))}findTransactionForSigning(e){const t=this.findTxid(e);if(null!=t&&null!=t.tx){for(const e of t.tx.inputs)if(null==e.sourceTransaction){const t=this.findTxid(Qt(e.sourceTXID));null!=t&&(e.sourceTransaction=t.tx)}return t.tx}}findAtomicTransaction(e){const t=this.findTxid(e);if(null==t||null==t.tx)return;const r=(e,t)=>{const i=e.findBump(t.id("hex"));if(null!=i)t.merklePath=i;else for(const i of t.inputs){if(null==i.sourceTransaction){const t=e.findTxid(Qt(i.sourceTXID));null!=t&&(i.sourceTransaction=t.tx)}if(null!=i.sourceTransaction){const t=e.findBump(i.sourceTransaction.id("hex"));null!=t?i.sourceTransaction.merklePath=t:r(e,i.sourceTransaction)}}};return r(this,t.tx),t.tx}mergeBump(e){let t;for(let r=0;r<this.bumps.length;r++){const i=this.bumps[r];if(i===e)return r;if(i.blockHeight===e.blockHeight&&i.computeRoot()===e.computeRoot()){i.combine(e),t=r;break}}void 0===t&&(t=this.bumps.length,this.bumps.push(e));const r=this.bumps[t];for(const e of this.txs){const i=e.txid;if(null==e.bumpIndex)for(const n of r.path[0])if(n.hash===i){e.bumpIndex=t,n.txid=!0;break}}return t}mergeRawTx(e,t){const r=new Zt(e,t);return this.removeExistingTxid(r.txid),this.txs.push(r),this.tryToValidateBumpIndex(r),r}mergeTransaction(e){const t=e.id("hex");let r;this.removeExistingTxid(t),null!=e.merklePath&&(r=this.mergeBump(e.merklePath));const i=new Zt(e,r);if(this.txs.push(i),this.tryToValidateBumpIndex(i),r=i.bumpIndex,void 0===r)for(const t of e.inputs)null!=t.sourceTransaction&&this.mergeTransaction(t.sourceTransaction);return i}removeExistingTxid(e){const t=this.txs.findIndex((t=>t.txid===e));t>=0&&this.txs.splice(t,1)}mergeTxidOnly(e){let t=this.txs.find((t=>t.txid===e));return null==t&&(t=new Zt(e),this.txs.push(t),this.tryToValidateBumpIndex(t)),t}mergeBeefTx(e){let t=this.findTxid(e.txid);if(e.isTxidOnly&&null==t?t=this.mergeTxidOnly(e.txid):null==e._tx||null!=t&&!t.isTxidOnly?null==e._rawTx||null!=t&&!t.isTxidOnly||(t=this.mergeRawTx(e._rawTx)):t=this.mergeTransaction(e._tx),null==t)throw new Error(`Failed to merge BeefTx for txid: ${e.txid}`);return t}mergeBeef(e){const t=Array.isArray(e)?nr.fromBinary(e):e;for(const e of t.bumps)this.mergeBump(e);for(const e of t.txs)this.mergeBeefTx(e)}isValid(e){return this.verifyValid(e).valid}async verify(e,t){const r=this.verifyValid(t);if(!r.valid)return!1;for(const t of Object.keys(r.roots))if(!await e.isValidRootForHeight(r.roots[t],Number(t)))return!1;return!0}verifyValid(e){const t={valid:!1,roots:{}},r=this.sortTxs();if(r.missingInputs.length>0||r.notValid.length>0||r.txidOnly.length>0&&!0!==e||r.withMissingInputs.length>0)return t;const i={};for(const r of this.txs)if(r.isTxidOnly){if(!0!==e)return t;i[r.txid]=!0}const n=(e,r)=>{const i=e.computeRoot(r);return void 0!==t.roots[e.blockHeight]&&""!==t.roots[e.blockHeight]||(t.roots[e.blockHeight]=i),t.roots[e.blockHeight]===i};for(const e of this.bumps)for(const r of e.path[0])if(!0===r.txid&&"string"==typeof r.hash&&r.hash.length>0&&(i[r.hash]=!0,!n(e,r.hash)))return t;for(const e of this.txs)if(void 0!==e.bumpIndex&&null==this.bumps[e.bumpIndex].path[0].find((t=>t.hash===e.txid)))return t;for(const e of this.txs){for(const r of e.inputTxids)if(!i[r])return t;i[e.txid]=!0}return t.valid=!0,t}toWriter(e){e.writeUInt32LE(this.version),e.writeVarIntNum(this.bumps.length);for(const t of this.bumps)e.write(t.toBinary());e.writeVarIntNum(this.txs.length);for(const t of this.txs)t.toWriter(e,this.version)}toBinary(){this.sortTxs();const e=new Ue;return this.toWriter(e),e.toArray()}toBinaryAtomic(e){this.sortTxs();const t=this.findTxid(e);if(null==t)throw new Error(`${e} does not exist in this Beef`);const r=this.txs[this.txs.length-1]===t?this:this.clone();if(r!==this){const t=this.txs.findIndex((t=>t.txid===e));r.txs.splice(t+1)}const i=new Ue;return i.writeUInt32LE(rr),i.writeReverse(Oe(e,"hex")),r.toWriter(i),i.toArray()}toHex(){return Ne(this.toBinary())}static fromReader(e){let t,r=e.readUInt32LE();if(r===rr&&(t=Ne(e.readReverse(32)),r=e.readUInt32LE()),r!==er&&r!==tr)throw new Error(`Serialized BEEF must start with ${er} or ${tr} but starts with ${r}`);const i=new nr(r),n=e.readVarIntNum();for(let t=0;t<n;t++){const t=Jt.fromReader(e,!1);i.bumps.push(t)}const s=e.readVarIntNum();for(let t=0;t<s;t++){const t=Zt.fromReader(e,r);i.txs.push(t)}return i.atomicTxid=t,i}static fromBinary(e){const t=new Ke(e);return nr.fromReader(t)}static fromString(e,t="hex"){const r=Oe(e,t),i=new Ke(r);return nr.fromReader(i)}tryToValidateBumpIndex(e){if(void 0!==e.bumpIndex)return!0;const t=e.txid;for(let r=0;r<this.bumps.length;r++){const i=this.bumps[r].path[0].findIndex((e=>e.hash===t));if(i>=0)return e.bumpIndex=r,this.bumps[r].path[0][i].txid=!0,!0}return!1}sortTxs(){const e={},t={};let r=[];const i=[],n=[];for(const s of this.txs)t[s.txid]=s,s.isValid=s.hasProof,s.isValid?(e[s.txid]=!0,i.push(s)):s.isTxidOnly&&0===s.inputTxids.length?(e[s.txid]=!0,n.push(s)):r.push(s);const s={},a=[],o=r;r=[];for(const e of o){let i=!1;for(const r of e.inputTxids)void 0===t[r]&&(s[r]=!0,i=!0);i?a.push(e):r.push(e)}for(;r.length>0;){const t=r;r=[];for(const n of t)n.inputTxids.every((t=>e[t]))?(e[n.txid]=!0,i.push(n)):r.push(n);if(t.length===r.length)break}const c=r;return this.txs=a.concat(c).concat(n).concat(i),{missingInputs:Object.keys(s),notValid:c.map((e=>e.txid)),valid:Object.keys(e),withMissingInputs:a.map((e=>e.txid)),txidOnly:n.map((e=>e.txid))}}clone(){const e=new nr;return e.version=this.version,e.bumps=Array.from(this.bumps),e.txs=Array.from(this.txs),e}trimKnownTxids(e){for(let t=0;t<this.txs.length;){const r=this.txs[t];r.isTxidOnly&&e.includes(r.txid)?this.txs.splice(t,1):t++}}getValidTxids(){return this.sortTxs().valid}toLogString(){let e="";e+=`BEEF with ${this.bumps.length} BUMPS and ${this.txs.length} Transactions, isValid ${this.isValid().toString()}\n`;let t=-1;for(const r of this.bumps)t++,e+=` BUMP ${t}\n block: ${r.blockHeight}\n txids: [\n${r.path[0].filter((e=>!0===e.txid)).map((e=>` '${e.hash??""}'`)).join(",\n")}\n ]\n`;t=-1;for(const r of this.txs)t++,e+=` TX ${t}\n txid: ${r.txid}\n`,void 0!==r.bumpIndex&&(e+=` bumpIndex: ${r.bumpIndex}\n`),r.isTxidOnly?e+=" txidOnly\n":e+=` rawTx length=${r.rawTx?.length??0}\n`,r.inputTxids.length>0&&(e+=` inputs: [\n${r.inputTxids.map((e=>` '${e}'`)).join(",\n")}\n ]\n`);return e}addComputedLeaves(){for(const t of this.bumps)for(let r=1;r<t.path.length;r++)for(const i of t.path[r-1])if("string"==typeof i.hash&&!(1&i.offset)){const n=t.path[r-1].find((e=>e.offset===i.offset+1)),s=i.offset>>1;void 0!==n&&"string"==typeof n.hash&&t.path[r].every((e=>e.offset!==s))&&t.path[r].push({offset:s,hash:(e=n.hash+i.hash,Ne(Ie(Oe(e,"hex").reverse()).reverse()))})}var e}}class sr{version;inputs;outputs;lockTime;metadata;merklePath;cachedHash;static addPathOrInputs(e,t,r){if("number"==typeof e.pathIndex){const t=r[e.pathIndex];if("object"!=typeof t)throw new Error("Invalid merkle path index found in BEEF!");e.tx.merklePath=t}else for(const i of e.tx.inputs){if(void 0===i.sourceTXID)throw new Error("Input sourceTXID is undefined");const e=t[i.sourceTXID];if("object"!=typeof e)throw new Error(`Reference to unknown TXID in BEEF: ${i.sourceTXID??"undefined"}`);i.sourceTransaction=e.tx,this.addPathOrInputs(e,t,r)}}static fromBEEF(e,t){const{tx:r}=sr.fromAnyBeef(e,t);return r}static fromAtomicBEEF(e){const{tx:t,txid:r,beef:i}=sr.fromAnyBeef(e);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 t}static fromAnyBeef(e,t){const r=nr.fromBinary(e);if(r.txs.length<1)throw new Error("beef must include at least one transaction.");const i=t||r.atomicTxid||r.txs.slice(-1)[0].txid,n=r.findAtomicTransaction(i);if(null==n)throw t?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(e){const t=new Ke(e),r=t.readUInt32LE();if("0000000000ef"!==Ne(t.read(6)))throw new Error("Invalid EF marker");const i=t.readVarIntNum(),n=[];for(let e=0;e<i;e++){const e=Ne(t.readReverse(32)),r=t.readUInt32LE(),i=t.readVarIntNum(),s=t.read(i),a=xt.fromBinary(s),o=t.readUInt32LE(),c=t.readUInt64LEBn().toNumber(),d=t.readVarIntNum(),u=t.read(d),h=At.fromBinary(u),l=new sr(void 0,[],[],void 0);l.outputs=Array(r+1).fill(null),l.outputs[r]={satoshis:c,lockingScript:h},n.push({sourceTransaction:l,sourceTXID:e,sourceOutputIndex:r,unlockingScript:a,sequence:o})}const s=t.readVarIntNum(),a=[];for(let e=0;e<s;e++){const e=t.readUInt64LEBn().toNumber(),r=t.readVarIntNum(),i=t.read(r),n=At.fromBinary(i);a.push({satoshis:e,lockingScript:n})}const o=t.readUInt32LE();return new sr(r,n,a,o)}static parseScriptOffsets(e){const t=new Ke(e),r=[],i=[];t.pos+=4;const n=t.readVarIntNum();for(let e=0;e<n;e++){t.pos+=36;const i=t.readVarIntNum();r.push({vin:e,offset:t.pos,length:i}),t.pos+=i+4}const s=t.readVarIntNum();for(let e=0;e<s;e++){t.pos+=8;const r=t.readVarIntNum();i.push({vout:e,offset:t.pos,length:r}),t.pos+=r}return{inputs:r,outputs:i}}static fromReader(e){const t=e.readUInt32LE(),r=e.readVarIntNum(),i=[];for(let t=0;t<r;t++){const t=Ne(e.readReverse(32)),r=e.readUInt32LE(),n=e.readVarIntNum(),s=e.read(n),a=xt.fromBinary(s),o=e.readUInt32LE();i.push({sourceTXID:t,sourceOutputIndex:r,unlockingScript:a,sequence:o})}const n=e.readVarIntNum(),s=[];for(let t=0;t<n;t++){const t=e.readUInt64LEBn().toNumber(),r=e.readVarIntNum(),i=e.read(r),n=At.fromBinary(i);s.push({satoshis:t,lockingScript:n})}const a=e.readUInt32LE();return new sr(t,i,s,a)}static fromBinary(e){const t=new Ke(e);return sr.fromReader(t)}static fromHex(e){return sr.fromBinary(Oe(e,"hex"))}static fromHexEF(e){return sr.fromEF(Oe(e,"hex"))}static fromHexBEEF(e,t){return sr.fromBEEF(Oe(e,"hex"),t)}constructor(e=1,t=[],r=[],i=0,n=new Map,s){this.version=e,this.inputs=t,this.outputs=r,this.lockTime=i,this.metadata=n,this.merklePath=s}addInput(e){if(void 0===e.sourceTXID&&void 0===e.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===e.sequence&&(e.sequence=4294967295),this.cachedHash=void 0,this.inputs.push(e)}addOutput(e){if(this.cachedHash=void 0,!0!==e.change){if(void 0===e.satoshis)throw new Error("either satoshis must be defined or change must be set to true");if(e.satoshis<0)throw new Error("satoshis must be a positive integer or zero")}if(null==e.lockingScript)throw new Error("lockingScript must be defined");this.outputs.push(e)}addP2PKHOutput(e,t){const r=(new Ut).lock(e);if(void 0===t)return this.addOutput({lockingScript:r,change:!0});this.addOutput({lockingScript:r,satoshis:t})}updateMetadata(e){this.metadata={...this.metadata,...e}}async fee(e=new qt(1),t="equal"){if(this.cachedHash=void 0,"number"==typeof e){const t=e;e={computeFee:async()=>t}}const r=await e.computeFee(this),i=this.calculateChange(r);i<=0?this.outputs=this.outputs.filter((e=>!0!==e.change)):this.distributeChange(i,t)}calculateChange(e){let t=0;for(const e of this.inputs){if("object"!=typeof e.sourceTransaction)throw new Error("Source transactions are required for all inputs during fee computation");t+=e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0}t-=e;for(const e of this.outputs)!0!==e.change&&void 0!==e.satoshis&&(t-=e.satoshis);return t}distributeChange(e,t){let r=0;const i=this.outputs.filter((e=>e.change));if("random"===t?r=this.distributeRandomChange(e,i):"equal"===t&&(r=this.distributeEqualChange(e,i)),r<e){const t=this.outputs[this.outputs.length-1];void 0!==t.satoshis?t.satoshis+=e-r:t.satoshis=e-r}}distributeRandomChange(e,t){let r=0,i=e;const n=Array(t.length).fill(1);i-=t.length,r+=t.length;for(let e=0;e<t.length-1;e++){const t=this.benfordNumber(0,i);n[e]=n[e]+t,r+=t,i-=t}for(const e of this.outputs)!0===e.change&&(e.satoshis=n.shift());return r}distributeEqualChange(e,t){let r=0;const i=Math.floor(e/t.length);for(const e of t)r+=i,e.satoshis=i;return r}benfordNumber(e,t){const r=Math.floor(9*Math.random())+1;return Math.floor(e+(t-e)*Math.log10(1+1/r)/Math.log10(10))}getFee(){let e=0;for(const t of this.inputs){if("object"!=typeof t.sourceTransaction)throw new Error("Source transactions or sourceSatoshis are required for all inputs to calculate fee");e+=t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0}let t=0;for(const e of this.outputs)t+=e.satoshis??0;return e-t}async sign(){this.cachedHash=void 0;for(const e of this.outputs)if(void 0===e.satoshis)throw!0===e.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 e=await Promise.all(this.inputs.map((async(e,t)=>"object"==typeof this.inputs[t].unlockingScriptTemplate?await(this.inputs[t]?.unlockingScriptTemplate?.sign(this,t)):await Promise.resolve(void 0))));for(let t=0,r=this.inputs.length;t<r;t++)"object"==typeof this.inputs[t].unlockingScriptTemplate&&(this.inputs[t].unlockingScript=e[t])}async broadcast(e=Xt()){return await e.broadcast(this)}toBinary(){const e=new Ue;e.writeUInt32LE(this.version),e.writeVarIntNum(this.inputs.length);for(const t of this.inputs){if(void 0===t.sourceTXID){if(null==t.sourceTransaction)throw new Error("sourceTransaction is undefined");e.write(t.sourceTransaction.hash())}else e.writeReverse(Oe(t.sourceTXID,"hex"));if(e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw new Error("unlockingScript is undefined");const r=t.unlockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r),e.writeUInt32LE(t.sequence??0)}e.writeVarIntNum(this.outputs.length);for(const t of this.outputs){e.writeUInt64LE(t.satoshis??0);const r=t.lockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r)}return e.writeUInt32LE(this.lockTime),e.toArray()}toEF(){const e=new Ue;e.writeUInt32LE(this.version),e.write([0,0,0,0,0,239]),e.writeVarIntNum(this.inputs.length);for(const t of this.inputs){if(void 0===t.sourceTransaction)throw new Error("All inputs must have source transactions when serializing to EF format");if(void 0===t.sourceTXID?e.write(t.sourceTransaction.hash()):e.write(Oe(t.sourceTXID,"hex").reverse()),e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw new Error("unlockingScript is undefined");const r=t.unlockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r),e.writeUInt32LE(t.sequence??0),e.writeUInt64LE(t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0);const i=t.sourceTransaction.outputs[t.sourceOutputIndex].lockingScript.toBinary();e.writeVarIntNum(i.length),e.write(i)}e.writeVarIntNum(this.outputs.length);for(const t of this.outputs){e.writeUInt64LE(t.satoshis??0);const r=t.lockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r)}return e.writeUInt32LE(this.lockTime),e.toArray()}toHexEF(){return Ne(this.toEF())}toHex(){return Ne(this.toBinary())}toHexBEEF(){return Ne(this.toBEEF())}toHexAtomicBEEF(){return Ne(this.toAtomicBEEF())}hash(e){let t;return null!=this.cachedHash?t=this.cachedHash:(t=Ie(this.toBinary()),this.cachedHash=t),"hex"===e?Ne(t):t}id(e){const t=[...this.hash()];return t.reverse(),"hex"===e?Ne(t):t}async verify(e=Yt(),t,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"===e){null!=a&&i.add(a);continue}if(await s.merklePath.verify(a,e)){i.add(a);continue}}if(void 0!==t){if(void 0===s)throw new Error("Transaction is undefined");const e=sr.fromEF(s.toEF());if(delete e.outputs[0].satoshis,e.outputs[0].change=!0,await e.fee(t),s.getFee()<e.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 e=0;e<s.inputs.length;e++){const t=s.inputs[e];if("object"!=typeof t.sourceTransaction)throw new Error(`Verification failed because the input at index ${e} of transaction ${a} is missing an associated source transaction. This source transaction is required for transaction verification because there is no merkle proof for the transaction spending a UTXO it contains.`);if("object"!=typeof t.unlockingScript)throw new Error(`Verification failed because the input at index ${e} of transaction ${a} is missing an associated unlocking script. This script is required for transaction verification because there is no merkle proof for the transaction spending the UTXO.`);const c=t.sourceTransaction.outputs[t.sourceOutputIndex];o+=c.satoshis??0;const d=t.sourceTransaction.id("hex");i.has(d)||n.push(t.sourceTransaction);const u=s.inputs.filter(((t,r)=>r!==e));if(void 0===t.sourceTXID&&(t.sourceTXID=d),!new Bt({sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,lockingScript:c.lockingScript,sourceSatoshis:c.satoshis??0,transactionVersion:s.version,otherInputs:u,unlockingScript:t.unlockingScript,inputSequence:t.sequence??0,inputIndex:e,outputs:s.outputs,lockTime:s.lockTime,memoryLimit:r}).validate())return!1}let c=0;for(const e of s.outputs){if("number"!=typeof e.satoshis)throw new Error("Every output must have a defined amount during transaction verification.");c+=e.satoshis}if(c>o)return!1;i.add(a)}return!0}toBEEF(e){const t=new Ue;t.writeUInt32LE(er);const r=[],i=[],n=t=>{const s={tx:t},a="object"==typeof t.merklePath;if(a){let e=!1;for(let i=0;i<r.length;i++){if(r[i]===t.merklePath){s.pathIndex=i,e=!0;break}if(null!==t.merklePath&&void 0!==t.merklePath&&r[i].blockHeight===t.merklePath.blockHeight&&r[i].computeRoot()===t.merklePath.computeRoot()){r[i].combine(t.merklePath),s.pathIndex=i,e=!0;break}}e||(s.pathIndex=r.length,null!==t.merklePath&&void 0!==t.merklePath&&r.push(t.merklePath))}if(i.some((e=>e.tx.id("hex")===t.id("hex")))||i.unshift(s),!a)for(let r=0;r<t.inputs.length;r++){const i=t.inputs[r];if("object"==typeof i.sourceTransaction)n(i.sourceTransaction);else if(!1===e)throw new Error("A required source transaction is missing!")}};n(this),t.writeVarIntNum(r.length);for(const e of r)t.write(e.toBinary());t.writeVarIntNum(i.length);for(const e of i)t.write(e.tx.toBinary()),"number"==typeof e.pathIndex?(t.writeUInt8(1),t.writeVarIntNum(e.pathIndex)):t.writeUInt8(0);return t.toArray()}toAtomicBEEF(e){const t=new Ue;t.writeUInt32LE(16843009),t.write(this.hash());const r=this.toBEEF(e);return t.write(r),t.toArray()}}function ar(e){return"success"===e.status}function or(e){return"error"===e.status}const cr=class extends nr{knownTo={};constructor(e){if(super(),null!=e)for(const t of e)this.addParty(t)}isParty(e){return Object.keys(this.knownTo).includes(e)}addParty(e){if(this.isParty(e))throw new Error(`Party ${e} already exists.`);this.knownTo[e]={}}getKnownTxidsForParty(e){const t=this.knownTo[e];if(void 0===t)throw new Error(`Party ${e} is unknown.`);return Object.keys(t)}getTrimmedBeefForParty(e){const t=this.getKnownTxidsForParty(e),r=this.clone();return r.trimKnownTxids(t),r}addKnownTxidsForParty(e,t){this.isParty(e)||this.addParty(e);const r=this.knownTo[e];for(const e of t)r[e]=!0,this.mergeTxidOnly(e)}mergeBeefFromParty(e,t){const r=Array.isArray(t)?nr.fromBinary(t):t,i=r.getValidTxids();this.mergeBeef(r),this.addKnownTxidsForParty(e,i)}};class dr{network;URL;httpClient;constructor(e="main",t=zt()){this.network=e,this.URL=`https://api.whatsonchain.com/v1/bsv/${e}/tx/raw`,this.httpClient=t}async broadcast(e){const t={method:"POST",headers:{"Content-Type":"application/json",Accept:"text/plain"},data:{txhex:e.toHex()}};try{const e=await this.httpClient.request(this.URL,t);return e.ok?{status:"success",txid:e.data,message:"broadcast successful"}:{status:"error",code:e.status.toString()??"ERR_UNKNOWN",description:e.data??"Unknown error"}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class ur{https;constructor(e){this.https=e}async request(e,t){return await new Promise(((r,i)=>{const n=this.https.request(e,t,(e=>{let t="";e.on("data",(e=>{t+=e})),e.on("end",(()=>{const i=e.statusCode>=200&&e.statusCode<=299,n=e.headers["content-type"],s=""!==t&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(t):t;r({status:e.statusCode,statusText:e.statusMessage,ok:i,data:s})}))}));n.on("error",(e=>{i(e)})),null!==t.data&&void 0!==t.data&&n.write(Buffer.from(t.data)),n.end()}))}}class hr{fetch;constructor(e){this.fetch=e}async request(e,t){const r={method:t.method,headers:t.headers,body:t.data},i=await this.fetch(e,r),n=await i.text();return{ok:i.ok,status:i.status,statusText:i.statusText,data:n}}}function lr(){const e={async request(...e){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 e;try{const e=require("https");return new ur(e)}catch(t){return e}}class fr{URL;httpClient;constructor(e,t=lr()){this.URL=e,this.httpClient=t}async broadcast(e){const t=e.toEF(),r={method:"POST",headers:{"Content-Type":"application/octet-stream"},data:new Blob([new Uint8Array(t)])};try{const t=await this.httpClient.request(this.URL,r);return t.ok?{status:"success",txid:e.id("hex"),message:"broadcast successful"}:{status:"error",code:t.status.toString()??"ERR_UNKNOWN",description:t.data??"Unknown error"}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class pr{baseUrl;httpClient;apiKey;constructor(e,t={}){const{httpClient:r,apiKey:i}=t;this.baseUrl=e,this.httpClient=r??zt(),this.apiKey=i??""}async isValidRootForHeight(e,t){const r={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.apiKey}`},data:[{blockHeight:t,merkleRoot:e}]};try{const e=await this.httpClient.request(`${this.baseUrl}/api/v1/chain/merkleroot/verify`,r);if(e.ok)return"CONFIRMED"===e.data.confirmationState;throw new Error(`Failed to verify merkleroot for height ${t} because of an error: ${JSON.stringify(e.data)}`)}catch(e){throw new Error(`Failed to verify merkleroot for height ${t} because of an error: ${e instanceof Error?e.message:String(e)}`)}}async currentHeight(){const e={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`}};try{const t=await this.httpClient.request(`${this.baseUrl}/api/v1/chain/tip/longest`,e);if(t.ok&&t.data&&"number"==typeof t.data.height)return t.data.height;throw new Error(`Failed to get current height because of an error: ${JSON.stringify(t.data)}`)}catch(e){throw new Error(`Failed to get current height because of an error: ${e instanceof Error?e.message:String(e)}`)}}}const br="42423301",wr=(e,t,r)=>{const i="object"!=typeof r;if(i){const e=new Me,t=new rt(1),i=e.g.mul(t);r=new Ge(i.x,i.y)}const n=Ze(32),s=`2-message signing-${Fe(n)}`,a=t.deriveChild(r,s).sign(e).toDER(),o=t.toPublicKey().encode(!0);return[...Oe(br,"hex"),...o,...i?[0]:r.encode(!0),...n,...a]},gr=(e,t,r)=>{const i=new Ke(t),n=Ne(i.read(4));if(n!==br)throw new Error(`Message version mismatch: Expected ${br}, received ${n}`);const s=Ge.fromString(Ne(i.read(33))),[a]=i.read(1);if(0===a)r=new rt(1);else{const e=i.read(32),t=Ne([a,...e]);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: ${t}`);const n=r.toPublicKey().encode(!0,"hex");if(t!==n)throw new Error(`The recipient public key is ${n} but the signature requres the recipient to have public key ${t}`)}const o=Fe(i.read(32)),c=Ne(i.read(i.bin.length-i.pos)),d=$e.fromDER(c,"hex"),u=`2-message signing-${o}`;return s.deriveChild(r,u).verify(e,d)},mr="42421033",yr=(e,t,r)=>{const i=Ze(32),n=`2-message encryption-${Fe(i)}`,s=t.deriveChild(r,n),a=r.deriveChild(t,n),o=s.deriveSharedSecret(a),c=new St(o.encode(!0).slice(1)).encrypt(e),d=t.toPublicKey().encode(!0);return[...Oe(mr,"hex"),...d,...r.encode(!0),...i,...c]},Ir=(e,t)=>{const r=new Ke(e),i=Ne(r.read(4));if(i!==mr)throw new Error(`Message version mismatch: Expected ${mr}, received ${i}`);const n=Ge.fromString(Ne(r.read(33))),s=Ne(r.read(33)),a=t.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=Fe(r.read(32)),c=r.read(r.bin.length-r.pos),d=`2-message encryption-${o}`,u=n.deriveChild(t,d),h=t.deriveChild(n,d),l=u.deriveSharedSecret(h);return new St(l.encode(!0).slice(1)).decrypt(c)},vr=e=>{const t=new Ue;t.writeVarIntNum(24),t.write(Oe("Bitcoin Signed Message:\n","utf8")),t.writeVarIntNum(e.length),t.write(e);const r=t.toArray();return Ie(r)},kr=(e,t,r="base64")=>{const i=vr(e),n=je(new d(i),t,!0);if("raw"===r)return n;const s=new d(i),a=n.CalculateRecoveryFactor(t.toPublicKey(),s);return n.toCompact(a,!0,"base64")},Sr=(e,t,r)=>{const i=vr(e);return Xe(new d(i),t,r)};class Er{versionBytesNum;depth;parentFingerPrint;childIndex;chainCode;privKey;pubKey;constants={pubKey:76067358,privKey:76066276};constructor(e,t,r,i,n,s,a){this.versionBytesNum=e,this.depth=t,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=Ze(32),this.privKey=rt.fromRandom(),this.pubKey=this.privKey.toPublicKey(),this}static fromRandom(){return(new this).fromRandom()}static fromString(e){return(new this).fromString(e)}fromString(e){const t=De(e);return this.fromBinary([...t.prefix,...t.data])}static fromSeed(e){return(new this).fromSeed(e)}fromSeed(e){if(e.length<16)throw new Error("Need more than 128 bits of entropy");if(e.length>64)throw new Error("More than 512 bits of entropy is nonstandard");const t=Se(Oe("Bitcoin seed","utf8"),e);return this.depth=0,this.parentFingerPrint=[0,0,0,0],this.childIndex=0,this.chainCode=t.slice(32,64),this.versionBytesNum=this.constants.privKey,this.privKey=new rt(t.slice(0,32)),this.pubKey=this.privKey.toPublicKey(),this}static fromBinary(e){return(new this).fromBinary(e)}fromBinary(e){if(78!==e.length)throw new Error("incorrect bip32 data length");const t=new Ke(e);this.versionBytesNum=t.readUInt32BE(),this.depth=t.readUInt8(),this.parentFingerPrint=t.read(4),this.childIndex=t.readUInt32BE(),this.chainCode=t.read(32);const r=t.read(33),i=this.versionBytesNum===this.constants.privKey,n=this.versionBytesNum===this.constants.pubKey;if(i&&0===r[0])this.privKey=new rt(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=Ge.fromString(Ne(r))}return this}toString(){const e=this.toBinary();return Be(e,[])}derive(e){if("m"===e)return this;const t=e.split("/");let r=this;for(const[e,i]of t.entries()){if(0===e){if("m"!==i)throw new Error("invalid path");continue}if(parseInt(i.replace("'",""),10).toString()!==i.replace("'",""))throw new Error("invalid path");const t=i.length>1&&"'"===i[i.length-1];let n=2147483647&parseInt(t?i.slice(0,i.length-1):i,10);t&&(n+=2147483648),r=r.deriveChild(n)}return r}deriveChild(e){if("number"!=typeof e)throw new Error("i must be a number");const t=[];t.push(e>>24&255),t.push(e>>16&255),t.push(e>>8&255),t.push(255&e);const r=[...t],i=!!(2147483648&e),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 e=null;e=i?[0,...this.privKey.toArray("be",32),...r]:[...this.pubKey.encode(!0),...r];const t=Se(this.chainCode,e),n=new d(t.slice(0,32)),a=t.slice(32,64),o=n.add(this.privKey).mod((new Me).n);s=new Er,s.chainCode=a,s.privKey=new rt(o.toArray()),s.pubKey=s.privKey.toPublicKey()}else{const e=[...this.pubKey.encode(!0),...r],t=Se(this.chainCode,e),i=new d(t.slice(0,32)),n=t.slice(32,64),a=(new Me).g.mul(i),o=this.pubKey,c=a.add(o),u=new Ge(c.x,c.y);s=new Er,s.chainCode=n,s.pubKey=u}s.childIndex=e;const a=ve(this.pubKey.encode(!0));return s.parentFingerPrint=a.slice(0,4),s.versionBytesNum=this.versionBytesNum,s.depth=this.depth+1,s}toPublic(){const e=new Er(this.versionBytesNum,this.depth,this.parentFingerPrint,this.childIndex,this.chainCode,this.privKey,this.pubKey);return e.versionBytesNum=this.constants.pubKey,e.privKey=void 0,e}toBinary(){const e=this.versionBytesNum===this.constants.privKey,t=this.versionBytesNum===this.constants.pubKey;if(e)return(new Ue).writeUInt32BE(this.versionBytesNum).writeUInt8(this.depth).write(this.parentFingerPrint).writeUInt32BE(this.childIndex).write(this.chainCode).writeUInt8(0).write(this.privKey.toArray("be",32)).toArray();if(t)return(new Ue).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 Pr={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 Nr{mnemonic;seed;Wordlist;constructor(e,t,r=Pr){this.mnemonic=e??"",this.seed=t??[],this.Wordlist=r}toBinary(){const e=new Ue;if(""!==this.mnemonic){const t=Oe(this.mnemonic,"utf8");e.writeVarIntNum(t.length),e.write(t)}else e.writeVarIntNum(0);return this.seed.length>0?(e.writeVarIntNum(this.seed.length),e.write(this.seed)):e.writeVarIntNum(0),e.toArray()}fromBinary(e){const t=new Ke(e),r=t.readVarIntNum();r>0&&(this.mnemonic=Te(t.read(r),"utf8"));const i=t.readVarIntNum();return i>0&&(this.seed=t.read(i)),this}fromRandom(e){if((null==e||isNaN(e)||0===e)&&(e=128),e%32!=0)throw new Error("bits must be multiple of 32");if(e<128)throw new Error("bits must be at least 128");const t=Ze(e/8);return this.entropy2Mnemonic(t),this.mnemonic2Seed(),this}static fromRandom(e){return(new this).fromRandom(e)}fromEntropy(e){return this.entropy2Mnemonic(e),this}static fromEntropy(e){return(new this).fromEntropy(e)}fromString(e){return this.mnemonic=e,this}static fromString(e){return(new this).fromString(e)}toString(){return this.mnemonic}toSeed(e){return this.mnemonic2Seed(e),this.seed}entropy2Mnemonic(e){if(e.length<16)throw new Error("Entropy is less than 128 bits. It must be 128 bits or more.");const t=me(e);let r="";const i=8*e.length;for(let t=0;t<e.length;t++)r+=("00000000"+e[t].toString(2)).slice(-8);let n=t[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 e=0;e<r.length/11;e++){""!==s&&(s+=this.Wordlist.space);const t=parseInt(r.slice(11*e,11*(e+1)),2);s+=this.Wordlist.value[t]}return this.mnemonic=s,this}check(){const e=this.mnemonic.split(this.Wordlist.space);let t="";for(let r=0;r<e.length;r++){const i=this.Wordlist.value.indexOf(e[r]);if(i<0)return!1;t+=("00000000000"+i.toString(2)).slice(-11)}if(t.length%11!=0)throw new Error("internal error - entropy not an even multiple of 11 bits - "+t.length.toString());const r=t.length/33,i=t.slice(-r),n=t.slice(0,t.length-r),s=[];for(let e=0;e<n.length/8;e++)s.push(parseInt(t.slice(8*e,8*(e+1)),2));let a=me(s.slice(0,n.length/8))[0].toString(2);return a=("00000000"+a).slice(-8).slice(0,r),a===i}mnemonic2Seed(e=""){let t=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 e)throw new Error("passphrase must be a string or undefined");t=t.normalize("NFKD"),e=e.normalize("NFKD");const r=Oe(t,"utf8"),i=[...Oe("mnemonic","utf8"),...Oe(e,"utf8")];return this.seed=Ee(r,i,2048,64,"sha512"),this}isValid(e=""){let t;try{this.mnemonic2Seed(e),t=!0}catch{t=!1}return t}static isValid(e,t=""){return new Nr(e).isValid(t)}}function Or(e){let t,r,i;0===this._tables[0][0][0]&&this._precompute();const n=this._tables[0][4],s=this._tables[1],a=e.length;let o,c=1;if(4!==a&&6!==a&&8!==a)throw new Error("invalid aes key size");for(this._key=[r=e.slice(0),i=[]],o=a;o<4*a+28;o++)t=r[o-1],(o%a==0||8===a&&o%a==4)&&(t=n[t>>>24]<<24^n[t>>16&255]<<16^n[t>>8&255]<<8^n[255&t],o%a==0&&(t=t<<8^t>>>24^c<<24,c=c<<1^283*(c>>7))),r[o]=r[o-a]^t;for(let e=0;o>0;e++,o--)t=r[3&e?o:o-4],i[e]=o<=4||e<4?t:s[0][n[t>>>24]]^s[1][n[t>>16&255]]^s[2][n[t>>8&255]]^s[3][n[255&t]]}Or.prototype={encrypt:function(e){return this._crypt(e,0)},decrypt:function(e){return this._crypt(e,1)},_tables:[[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)]],_precompute:function(){const e=this._tables[0],t=this._tables[1],r=e[4],i=t[4];let n,s,a;const o=new Uint8Array(256),c=new Uint8Array(256);let d,u,h,l,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!==d?d:1,a=0!==c[a]?c[a]:1)for(l=a^a<<1^a<<2^a<<3^a<<4,l=l>>8^255&l^99,r[s]=l,i[l]=s,h=o[u=o[d=o[s]]],p=16843009*h^65537*u^257*d^16843008*s,f=257*o[l]^16843008*l,n=0;n<4;n++)e[n][s]=f=f<<24^f>>>8,t[n][l]=p=p<<24^p>>>8},_crypt:function(e,t){if(4!==e.length)throw new Error("invalid aes block size");const r=this._key[t];let i,n,s,a=e[0]^r[0],o=e[1===t?3:1]^r[1],c=e[2]^r[2],d=e[1===t?1:3]^r[3];const u=r.length/4-2;let h,l=4;const f=new Uint32Array(4),p=this._tables[t],b=p[0],w=p[1],g=p[2],m=p[3],y=p[4];for(h=0;h<u;h++)i=b[a>>>24]^w[o>>16&255]^g[c>>8&255]^m[255&d]^r[l],n=b[o>>>24]^w[c>>16&255]^g[d>>8&255]^m[255&a]^r[l+1],s=b[c>>>24]^w[d>>16&255]^g[a>>8&255]^m[255&o]^r[l+2],d=b[d>>>24]^w[a>>16&255]^g[o>>8&255]^m[255&c]^r[l+3],l+=4,a=i,o=n,c=s;for(h=0;h<4;h++)f[1===t?3&-h:h]=y[a>>>24]<<24^y[o>>16&255]<<16^y[c>>8&255]<<8^y[255&d]^r[l++],i=a,a=o,o=c,c=d,d=i;return f}};class _r{static encrypt(e,t){const r=_r.buf2Words(t),i=_r.buf2Words(e),n=new Or(r).encrypt(i);return _r.words2Buf(n)}static decrypt(e,t){const r=_r.buf2Words(e),i=new Or(_r.buf2Words(t)).decrypt(r);return _r.words2Buf(i)}static buf2Words(e){if(e.length%4!=0)throw new Error("buf length must be a multiple of 4");const t=[];for(let r=0;r<e.length/4;r++){const i=16777216*e[4*r]+(e[4*r+1]<<16|e[4*r+2]<<8|e[4*r+3]);t.push(i)}return t}static words2Buf(e){const t=new Array(4*e.length);for(let r=0;r<e.length;r++){const i=e[r];t[4*r]=i>>>24&255,t[4*r+1]=i>>>16&255,t[4*r+2]=i>>>8&255,t[4*r+3]=255&i}return t}}class Ar{static buf2BlocksBuf(e,t){const r=t/8,i=[];for(let n=0;n<=e.length/r;n++){let s=e.slice(n*r,n*r+r);s.length<t&&(s=Ar.pkcs7Pad(s,t)),i.push(s)}return i}static blockBufs2Buf(e){let t=e[e.length-1];return t=Ar.pkcs7Unpad(t),e[e.length-1]=t,e.flat()}static encrypt(e,t,r,i){const n=8*t.length,s=Ar.buf2BlocksBuf(e,n);return Ar.encryptBlocks(s,t,r,i).flat()}static decrypt(e,t,r,i){const n=t.length,s=[];for(let t=0;t<e.length/n;t++)s.push(e.slice(t*n,t*n+n));const a=Ar.decryptBlocks(s,t,r,i);return Ar.blockBufs2Buf(a)}static encryptBlock(e,t,r,i){const n=Ar.xorBufs(e,t);return r.encrypt(n,i)}static decryptBlock(e,t,r,i){const n=r.decrypt(e,i);return Ar.xorBufs(n,t)}static encryptBlocks(e,t,r,i){const n=[];for(let s=0;s<e.length;s++){const a=e[s],o=Ar.encryptBlock(a,t,r,i);n.push(o),t=o}return n}static decryptBlocks(e,t,r,i){const n=[];for(let s=0;s<e.length;s++){const a=e[s],o=Ar.decryptBlock(a,t,r,i);n.push(o),t=a}return n}static pkcs7Pad(e,t){const r=t/8-e.length,i=new Array(r);return i.fill(r),[...e,...i]}static pkcs7Unpad(e){const t=e[e.length-1],r=e.slice(e.length-t,e.length),i=new Array(t);if(i.fill(t),Ne(r)!==Ne(i))throw new Error("invalid padding");return e.slice(0,e.length-t)}static xorBufs(e,t){if(e.length!==t.length)throw new Error("bufs must have the same length");const r=new Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}}class xr{static encrypt(e,t,r,i=!0){r=r??Ze(16);const n=Ar.encrypt(e,r,_r,t);return i?[...r,...n]:[...n]}static decrypt(e,t,r){if(null==r){r=e.slice(0,16);const i=e.slice(16);return Ar.decrypt(i,r,_r,t)}{const i=e;return Ar.decrypt(i,r,_r,t)}}}class Tr{static ivkEkM(e,t){const r=e,i=t.mul(r),n=new Ge(i.x,i.y).encode(!0),s=ye(n);return{iv:s.slice(0,16),kE:s.slice(16,32),kM:s.slice(32,64)}}static electrumEncrypt(e,t,r,i=!1){let n=null;null==r&&(r=rt.fromRandom()),i||(n=r.toPublicKey().encode(!0));const{iv:s,kE:a,kM:o}=Tr.ivkEkM(r,t),c=xr.encrypt(e,a,s,!1),d=Oe("BIE1","utf8");let u;u=null!=n&&n.length>0?[...d,...n,...c]:[...d,...c];const h=ke(o,u);return[...u,...h]}static electrumDecrypt(e,t,r){const i=e.slice(0,4);if("BIE1"!==Te(i,"utf8"))throw new Error("Invalid Magic");let n=4,s=null;if(e.length-n-32>=33){const t=e[n];2===t||3===t?(s=e.slice(n,n+33),n+=33):4===t&&(s=e.slice(n,n+65),n+=65)}if(null!==s)null==r&&(r=Ge.fromString(Ne(s)));else if(null==r)throw new Error("Sender public key is required");const{iv:a,kE:o,kM:c}=Tr.ivkEkM(t,r),d=e.slice(n,e.length-32),u=e.slice(e.length-32,e.length),h=ke(c,e.slice(0,e.length-32));if(Ne(u)!==Ne(h))throw new Error("Invalid checksum");return xr.decrypt(d,o,a)}static bitcoreEncrypt(e,t,r,i){null==r&&(r=rt.fromRandom()),null==i&&(i=Ze(16));const n=r,s=r.toPublicKey().encode(!0),a=t.mul(n).getX().toArray("be",32),o=ye(a),c=o.slice(0,32),d=o.slice(32,64),u=xr.encrypt(e,c,i),h=ke(d,[...u]);return[...s,...u,...h]}static bitcoreDecrypt(e,t){const r=t,i=Ge.fromString(Ne(e.slice(0,33))).mul(r);if(i.eq(new He(0,0)))throw new Error("P equals 0");const n=i.getX().toArray("be",32),s=ye(n),a=s.slice(0,32),o=s.slice(32,64),c=e.slice(33,e.length-32),d=e.slice(e.length-32,e.length),u=ke(o,c);if(Ne(d)!==Ne(u))throw new Error("Invalid checksum");return[...xr.decrypt(c,a)]}}function Fr(e,t){const r=new sr(0,[],[],0);return r.outputs=Array(e.vout+1).fill(null),r.outputs[e.vout]={satoshis:e.satoshis,lockingScript:At.fromHex(e.script)},{sourceTransaction:r,sourceTXID:e.txid,sourceOutputIndex:e.vout,unlockingScriptTemplate:t,sequence:4294967295}}class Cr{static generate(e,t){const r=this.withDefaultOptions(t);return Rr(e,this.getCounter(r.timestamp,r.period),r)}static validate(e,t,r){const i=this.withDefaultValidateOptions(r);if((t=t.trim()).length!==i.digits)return!1;const n=this.getCounter(i.timestamp,i.period),s=[n];for(let e=1;e<=i.skew;e++)s.push(n+e),s.push(n-e);for(const r of s)if(t===Rr(e,r,i))return!0;return!1}static getCounter(e,t){const r=Math.floor(e/1e3);return Math.floor(r/t)}static withDefaultOptions(e){return{digits:2,algorithm:"SHA-1",period:30,timestamp:Date.now(),...e}}static withDefaultValidateOptions(e){return{skew:1,...this.withDefaultOptions(e)}}}function Rr(e,t,r){const i=function(e,t,r){switch(r){case"SHA-1":return new pe(e).update(t);case"SHA-256":return new fe(e).update(t);case"SHA-512":return new be(e).update(t);default:throw new Error("unsupported HMAC algorithm")}}(e,new d(t).toArray("be",8),r.algorithm),n=i.digest(),s=15&n[n.length-1],a=n.slice(s,s+4);return(2147483647&new d(a).toNumber()).toString().slice(-r.digits)}var Vr;!function(e){e[e.Silent=0]="Silent",e[e.App=1]="App",e[e.Counterparty=2]="Counterparty"}(Vr||(Vr={}));class Br{rootKey;identityKey;constructor(e){this.rootKey="anyone"===e?new rt(1):e,this.identityKey=this.rootKey.toPublicKey().toString()}derivePublicKey(e,t,r,i=!1){return r=this.normalizeCounterparty(r),i?this.rootKey.deriveChild(r,this.computeInvoiceNumber(e,t)).toPublicKey():r.deriveChild(this.rootKey,this.computeInvoiceNumber(e,t))}derivePrivateKey(e,t,r){return r=this.normalizeCounterparty(r),this.rootKey.deriveChild(r,this.computeInvoiceNumber(e,t))}deriveSymmetricKey(e,t,r){"anyone"===r&&(r=new rt(1).toPublicKey()),r=this.normalizeCounterparty(r);const i=this.derivePublicKey(e,t,r),n=this.derivePrivateKey(e,t,r);return new St(n.deriveSharedSecret(i)?.x?.toArray()??[])}revealCounterpartySecret(e){if("self"===e)throw new Error("Counterparty secrets cannot be revealed for counterparty=self.");e=this.normalizeCounterparty(e);const t=this.rootKey.toPublicKey();if(this.rootKey.deriveChild(t,"test").toHex()===this.rootKey.deriveChild(e,"test").toHex())throw new Error("Counterparty secrets cannot be revealed for counterparty=self.");return this.rootKey.deriveSharedSecret(e).encode(!0)}revealSpecificSecret(e,t,r){e=this.normalizeCounterparty(e);const i=this.rootKey.deriveSharedSecret(e),n=Oe(this.computeInvoiceNumber(t,r),"utf8");return ke(i.encode(!0),n)}normalizeCounterparty(e){if(null==e)throw new Error("counterparty must be self, anyone or a public key!");return"self"===e?this.rootKey.toPublicKey():"anyone"===e?new rt(1).toPublicKey():"string"==typeof e?Ge.fromString(e):e}computeInvoiceNumber(e,t){const r=e[0];if(!Number.isInteger(r)||r<0||r>2)throw new Error("Protocol security level must be 0, 1, or 2");const i=e[1].toLowerCase().trim();if(t.length>800)throw new Error("Key IDs must be 800 characters or less");if(t.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}-${t}`}}class Dr{keyDeriver;cache;maxCacheSize;constructor(e,t){this.keyDeriver=new Br(e),this.cache=new Map;const r=t?.maxCacheSize;this.maxCacheSize=null!=r&&!isNaN(r)&&r>0?r:1e3}derivePublicKey(e,t,r,i=!1){const n=this.generateCacheKey("derivePublicKey",e,t,r,i);if(this.cache.has(n)){const e=this.cacheGet(n);if(void 0===e)throw new Error("Cached value is undefined");return e}{const s=this.keyDeriver.derivePublicKey(e,t,r,i);return this.cacheSet(n,s),s}}derivePrivateKey(e,t,r){const i=this.generateCacheKey("derivePrivateKey",e,t,r);if(this.cache.has(i)){const e=this.cacheGet(i);if(void 0===e)throw new Error("Cached value is undefined");return e}{const n=this.keyDeriver.derivePrivateKey(e,t,r);return this.cacheSet(i,n),n}}deriveSymmetricKey(e,t,r){const i=this.generateCacheKey("deriveSymmetricKey",e,t,r);if(this.cache.has(i)){const e=this.cacheGet(i);if(void 0===e)throw new Error("Cached value is undefined");return e}{const n=this.keyDeriver.deriveSymmetricKey(e,t,r);return this.cacheSet(i,n),n}}revealCounterpartySecret(e){const t=this.generateCacheKey("revealCounterpartySecret",e);if(this.cache.has(t)){const e=this.cacheGet(t);if(void 0===e)throw new Error("Cached value is undefined");return e}{const r=this.keyDeriver.revealCounterpartySecret(e);return this.cacheSet(t,r),r}}revealSpecificSecret(e,t,r){const i=this.generateCacheKey("revealSpecificSecret",e,t,r);if(this.cache.has(i)){const e=this.cacheGet(i);if(void 0===e)throw new Error("Cached value is undefined");return e}{const n=this.keyDeriver.revealSpecificSecret(e,t,r);return this.cacheSet(i,n),n}}generateCacheKey(e,...t){return`${e}|${t.map((e=>this.serializeArgument(e))).join("|")}`}serializeArgument(e){return e instanceof Ge||e instanceof rt?e.toString():Array.isArray(e)?e.map((e=>this.serializeArgument(e))).join(","):"object"==typeof e&&null!==e?JSON.stringify(e):String(e)}cacheGet(e){const t=this.cache.get(e);return this.cache.delete(e),void 0!==t&&this.cache.set(e,t),t}cacheSet(e,t){if(this.cache.size>=this.maxCacheSize){const e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(e,t)}}const Ur=class{keyDeriver;constructor(e){"string"!=typeof e.identityKey&&(e=new Br(e)),this.keyDeriver=e}async getPublicKey(e){if(e.identityKey){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==e.protocolID||null==e.keyID||""===e.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(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf).toString()}}async revealCounterpartyKeyLinkage(e){const{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const r=this.keyDeriver.revealCounterpartySecret(e.counterparty),i=(new Pt).generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),Ge.fromString(e.counterparty),He.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:e.verifier}),{ciphertext:o}=await this.encrypt({plaintext:n,protocolID:[2,"counterparty linkage revelation"],keyID:s,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,revelationTime:s,encryptedLinkage:a,encryptedLinkageProof:o}}async revealSpecificKeyLinkage(e){const{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const r=this.keyDeriver.revealSpecificSecret(e.counterparty,e.protocolID,e.keyID),{ciphertext:i}=await this.encrypt({plaintext:r,protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier}),{ciphertext:n}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,protocolID:e.protocolID,keyID:e.keyID,encryptedLinkage:i,encryptedLinkageProof:n,proofType:0}}async encrypt(e){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{ciphertext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").encrypt(e.plaintext)}}async decrypt(e){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");return{plaintext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").decrypt(e.ciphertext)}}async createHmac(e){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const t=this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self");return{hmac:ke(t.toArray(),e.data)}}async verifyHmac(e){if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const t=this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self"),r=ke(t.toArray(),e.data).toString()===e.hmac.toString();if(!r){const e=new Error("HMAC is not valid");throw e.code="ERR_INVALID_HMAC",e}return{valid:r}}async createSignature(e){if(null==e.hashToDirectlySign&&null==e.data)throw new Error("args.data or args.hashToDirectlySign must be valid");const t=e.hashToDirectlySign??me(e.data??[]),r=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePrivateKey(e.protocolID,e.keyID,e.counterparty??"anyone");return{signature:je(new d(t),r,!0).toDER()}}async verifySignature(e){if(null==e.hashToDirectlyVerify&&null==e.data)throw new Error("args.data or args.hashToDirectlyVerify must be valid");const t=e.hashToDirectlyVerify??me(e.data??[]),r=(this.keyDeriver??(()=>{throw new Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf),i=Xe(new d(t),$e.fromDER(e.signature),r);if(!i){const e=new Error("Signature is not valid");throw e.code="ERR_INVALID_SIGNATURE",e}return{valid:i}}};class Kr{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(e,t){return await this.CWI.createAction(e,t)}async signAction(e,t){return await this.CWI.signAction(e,t)}async abortAction(e,t){return await this.CWI.abortAction(e,t)}async listActions(e,t){return await this.CWI.listActions(e,t)}async internalizeAction(e,t){return await this.CWI.internalizeAction(e,t)}async listOutputs(e,t){return await this.CWI.listOutputs(e,t)}async relinquishOutput(e,t){return await this.CWI.relinquishOutput(e,t)}async getPublicKey(e,t){return await this.CWI.getPublicKey(e,t)}async revealCounterpartyKeyLinkage(e,t){return await this.CWI.revealCounterpartyKeyLinkage(e,t)}async revealSpecificKeyLinkage(e,t){return await this.CWI.revealSpecificKeyLinkage(e,t)}async encrypt(e,t){return await this.CWI.encrypt(e,t)}async decrypt(e,t){return await this.CWI.decrypt(e,t)}async createHmac(e,t){return await this.CWI.createHmac(e,t)}async verifyHmac(e,t){return await this.CWI.verifyHmac(e,t)}async createSignature(e,t){return await this.CWI.createSignature(e,t)}async verifySignature(e,t){return await this.CWI.verifySignature(e,t)}async acquireCertificate(e,t){return await this.CWI.acquireCertificate(e,t)}async listCertificates(e,t){return await this.CWI.listCertificates(e,t)}async proveCertificate(e,t){return await this.CWI.proveCertificate(e,t)}async relinquishCertificate(e,t){return await this.CWI.relinquishCertificate(e,t)}async discoverByIdentityKey(e,t){return await this.CWI.discoverByIdentityKey(e,t)}async discoverByAttributes(e,t){return await this.CWI.discoverByAttributes(e,t)}async isAuthenticated(e,t){return await this.CWI.isAuthenticated(e,t)}async waitForAuthentication(e,t){return await this.CWI.waitForAuthentication(e,t)}async getHeight(e,t){return await this.CWI.getHeight(e,t)}async getHeaderForHeight(e,t){return await this.CWI.getHeaderForHeight(e,t)}async getNetwork(e,t){return await this.CWI.getNetwork(e,t)}async getVersion(e,t){return await this.CWI.getVersion(e,t)}}class Lr extends Error{code;isError=!0;constructor(e,t=1,r){super(e),this.code=t,this.name=this.constructor.name,null!=r&&""!==r?this.stack=r:Error.captureStackTrace(this,this.constructor)}}var Hr;!function(e){e[e.unknownError=1]="unknownError",e[e.unsupportedAction=2]="unsupportedAction",e[e.invalidHmac=3]="invalidHmac",e[e.invalidSignature=4]="invalidSignature",e[e.reviewActions=5]="reviewActions"}(Hr||(Hr={}));const qr=Lr;class Mr{domain;constructor(e="*"){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=e}async invoke(e,t){return await new Promise(((r,i)=>{const n=Fe(Ze(12)),s=e=>{if("CWI"===e.data.type&&e.isTrusted&&e.data.id===n&&!0!==e.data.isInvocation)if("function"==typeof window.removeEventListener&&window.removeEventListener("message",s),"error"===e.data.status){const t=new Lr(e.data.description,e.data.code);i(t)}else r(e.data.result)};window.addEventListener("message",s),window.parent.postMessage({type:"CWI",isInvocation:!0,id:n,call:e,args:t},this.domain)}))}async createAction(e){return await this.invoke("createAction",e)}async signAction(e){return await this.invoke("signAction",e)}async abortAction(e){return await this.invoke("abortAction",e)}async listActions(e){return await this.invoke("listActions",e)}async internalizeAction(e){return await this.invoke("internalizeAction",e)}async listOutputs(e){return await this.invoke("listOutputs",e)}async relinquishOutput(e){return await this.invoke("relinquishOutput",e)}async getPublicKey(e){return await this.invoke("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.invoke("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.invoke("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.invoke("encrypt",e)}async decrypt(e){return await this.invoke("decrypt",e)}async createHmac(e){return await this.invoke("createHmac",e)}async verifyHmac(e){return await this.invoke("verifyHmac",e)}async createSignature(e){return await this.invoke("createSignature",e)}async verifySignature(e){return await this.invoke("verifySignature",e)}async acquireCertificate(e){return await this.invoke("acquireCertificate",e)}async listCertificates(e){return await this.invoke("listCertificates",e)}async proveCertificate(e){return await this.invoke("proveCertificate",e)}async relinquishCertificate(e){return await this.invoke("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.invoke("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.invoke("discoverByAttributes",e)}async isAuthenticated(e){return await this.invoke("isAuthenticated",e)}async waitForAuthentication(e){return await this.invoke("waitForAuthentication",e)}async getHeight(e){return await this.invoke("getHeight",e)}async getHeaderForHeight(e){return await this.invoke("getHeaderForHeight",e)}async getNetwork(e){return await this.invoke("getNetwork",e)}async getVersion(e){return await this.invoke("getVersion",e)}}class $r{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(e,t,r,i,n,s,a){this.type=e,this.serialNumber=t,this.subject=r,this.certifier=i,this.revocationOutpoint=n,this.fields=s,this.signature=a}toBinary(e=!0){const t=new Ue,r=Oe(this.type,"base64");t.write(r);const i=Oe(this.serialNumber,"base64");t.write(i);const n=Oe(this.subject,"hex");t.write(n);const s=Oe(this.certifier,"hex");t.write(s);const[a,o]=this.revocationOutpoint.split("."),c=Oe(a,"hex");t.write(c),t.writeVarIntNum(Number(o));const d=Object.keys(this.fields).sort();t.writeVarIntNum(d.length);for(const e of d){const r=this.fields[e],i=Oe(e,"utf8");t.writeVarIntNum(i.length),t.write(i);const n=Oe(r,"utf8");t.writeVarIntNum(n.length),t.write(n)}if(e&&(this.signature??"").length>0){const e=Oe(this.signature,"hex");t.write(e)}return t.toArray()}static fromBinary(e){const t=new Ke(e),r=Fe(t.read(32)),i=Fe(t.read(32)),n=t.read(33),s=Ne(n),a=t.read(33),o=Ne(a),c=t.read(32),d=`${Ne(c)}.${t.readVarIntNum()}`,u=t.readVarIntNum(),h={};for(let e=0;e<u;e++){const e=t.readVarIntNum(),r=t.read(e),i=xe(r),n=t.readVarIntNum(),s=t.read(n),a=xe(s);h[i]=a}let l;if(!t.eof()){const e=t.read();l=$e.fromDER(e).toString("hex")}return new $r(r,i,s,o,d,h,l)}async verify(){const e=new Ur("anyone"),t=this.toBinary(!1),r=this.signature??"",{valid:i}=await e.verifySignature({signature:Oe(r,"hex"),data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`,counterparty:this.certifier});return i}async sign(e){if(null!=this.signature&&this.signature.length>0)throw new Error(`Certificate has already been signed! Signature present: ${this.signature}`);this.certifier=(await e.getPublicKey({identityKey:!0})).publicKey;const t=this.toBinary(!1),{signature:r}=await e.createSignature({data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`});this.signature=Ne(r)}static getCertificateFieldEncryptionDetails(e,t){return{protocolID:[2,"certificate field encryption"],keyID:t?`${t} ${e}`:e}}}var zr;!function(e){e[e.createAction=1]="createAction",e[e.signAction=2]="signAction",e[e.abortAction=3]="abortAction",e[e.listActions=4]="listActions",e[e.internalizeAction=5]="internalizeAction",e[e.listOutputs=6]="listOutputs",e[e.relinquishOutput=7]="relinquishOutput",e[e.getPublicKey=8]="getPublicKey",e[e.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",e[e.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",e[e.encrypt=11]="encrypt",e[e.decrypt=12]="decrypt",e[e.createHmac=13]="createHmac",e[e.verifyHmac=14]="verifyHmac",e[e.createSignature=15]="createSignature",e[e.verifySignature=16]="verifySignature",e[e.acquireCertificate=17]="acquireCertificate",e[e.listCertificates=18]="listCertificates",e[e.proveCertificate=19]="proveCertificate",e[e.relinquishCertificate=20]="relinquishCertificate",e[e.discoverByIdentityKey=21]="discoverByIdentityKey",e[e.discoverByAttributes=22]="discoverByAttributes",e[e.isAuthenticated=23]="isAuthenticated",e[e.waitForAuthentication=24]="waitForAuthentication",e[e.getHeight=25]="getHeight",e[e.getHeaderForHeight=26]="getHeaderForHeight",e[e.getNetwork=27]="getNetwork",e[e.getVersion=28]="getVersion"}(zr||(zr={}));const Wr=zr;class jr{wire;constructor(e){this.wire=e}async transmit(e,t="",r=[]){const i=new Ue;i.writeUInt8(Wr[e]);const n=Oe(t,"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 Ke(a),c=o.readUInt8();if(0===c)return o.read();{const e=o.readVarIntNum(),t=o.read(e),r=xe(t),i=o.readVarIntNum(),n=o.read(i),s=xe(n);throw new Lr(r,c,s)}}async createAction(e,t){const r=new Ue,i=Oe(e.description,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=e.inputBEEF?(r.writeVarIntNum(e.inputBEEF.length),r.write(e.inputBEEF)):r.writeVarIntNum(-1),null!=e.inputs){r.writeVarIntNum(e.inputs.length);for(const t of e.inputs){if(r.write(this.encodeOutpoint(t.outpoint)),null!=t.unlockingScript&&""!==t.unlockingScript){const e=Oe(t.unlockingScript,"hex");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1),r.writeVarIntNum(t.unlockingScriptLength??0);const e=Oe(t.inputDescription,"utf8");r.writeVarIntNum(e.length),r.write(e),"number"==typeof t.sequenceNumber?r.writeVarIntNum(t.sequenceNumber):r.writeVarIntNum(-1)}}else r.writeVarIntNum(-1);if(null!=e.outputs){r.writeVarIntNum(e.outputs.length);for(const t of e.outputs){const e=Oe(t.lockingScript,"hex");r.writeVarIntNum(e.length),r.write(e),r.writeVarIntNum(t.satoshis);const i=Oe(t.outputDescription,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=t.basket&&""!==t.basket){const e=Oe(t.basket,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=t.customInstructions&&""!==t.customInstructions){const e=Oe(t.customInstructions,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=t.tags){r.writeVarIntNum(t.tags.length);for(const e of t.tags){const t=Oe(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}}else r.writeVarIntNum(-1)}}else r.writeVarIntNum(-1);if("number"==typeof e.lockTime?r.writeVarIntNum(e.lockTime):r.writeVarIntNum(-1),"number"==typeof e.version?r.writeVarIntNum(e.version):r.writeVarIntNum(-1),null!=e.labels){r.writeVarIntNum(e.labels.length);for(const t of e.labels){const e=Oe(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}}else r.writeVarIntNum(-1);if(null!=e.options){if(r.writeInt8(1),"boolean"==typeof e.options.signAndProcess?r.writeInt8(e.options.signAndProcess?1:0):r.writeInt8(-1),"boolean"==typeof e.options.acceptDelayedBroadcast?r.writeInt8(e.options.acceptDelayedBroadcast?1:0):r.writeInt8(-1),"known"===e.options.trustSelf?r.writeInt8(1):r.writeInt8(-1),null!=e.options.knownTxids){r.writeVarIntNum(e.options.knownTxids.length);for(const t of e.options.knownTxids){const e=Oe(t,"hex");r.write(e)}}else r.writeVarIntNum(-1);if("boolean"==typeof e.options.returnTXIDOnly?r.writeInt8(e.options.returnTXIDOnly?1:0):r.writeInt8(-1),"boolean"==typeof e.options.noSend?r.writeInt8(e.options.noSend?1:0):r.writeInt8(-1),null!=e.options.noSendChange){r.writeVarIntNum(e.options.noSendChange.length);for(const t of e.options.noSendChange)r.write(this.encodeOutpoint(t))}else r.writeVarIntNum(-1);if(null!=e.options.sendWith){r.writeVarIntNum(e.options.sendWith.length);for(const t of e.options.sendWith){const e=Oe(t,"hex");r.write(e)}}else r.writeVarIntNum(-1);"boolean"==typeof e.options.randomizeOutputs?r.writeInt8(e.options.randomizeOutputs?1:0):r.writeInt8(-1)}else r.writeInt8(0);const n=await this.transmit("createAction",t,r.toArray()),s=new Ke(n),a={};if(1===s.readInt8()){const e=s.read(32);a.txid=Ne(e)}if(1===s.readInt8()){const e=s.readVarIntNum();a.tx=s.read(e)}const o=s.readVarIntNum();if(o>=0){a.noSendChange=[];for(let e=0;e<o;e++){const e=this.readOutpoint(s);a.noSendChange.push(e)}}const c=s.readVarIntNum();if(c>=0){a.sendWithResults=[];for(let e=0;e<c;e++){const e=s.read(32),t=Ne(e),r=s.readInt8();let i="unproven";1===r?i="unproven":2===r?i="sending":3===r&&(i="failed"),a.sendWithResults.push({txid:t,status:i})}}if(1===s.readInt8()){const e=s.readVarIntNum(),t=s.read(e),r=s.readVarIntNum(),i=s.read(r);a.signableTransaction={tx:t,reference:Fe(i)}}return a}async signAction(e,t){const r=new Ue,i=Object.keys(e.spends);r.writeVarIntNum(i.length);for(const t of i){r.writeVarIntNum(Number(t));const i=e.spends[Number(t)],n=Oe(i.unlockingScript,"hex");r.writeVarIntNum(n.length),r.write(n),"number"==typeof i.sequenceNumber?r.writeVarIntNum(i.sequenceNumber):r.writeVarIntNum(-1)}const n=Oe(e.reference,"base64");if(r.writeVarIntNum(n.length),r.write(n),null!=e.options)if(r.writeInt8(1),"boolean"==typeof e.options.acceptDelayedBroadcast?r.writeInt8(e.options.acceptDelayedBroadcast?1:0):r.writeInt8(-1),"boolean"==typeof e.options.returnTXIDOnly?r.writeInt8(e.options.returnTXIDOnly?1:0):r.writeInt8(-1),"boolean"==typeof e.options.noSend?r.writeInt8(e.options.noSend?1:0):r.writeInt8(-1),null!=e.options.sendWith){r.writeVarIntNum(e.options.sendWith.length);for(const t of e.options.sendWith){const e=Oe(t,"hex");r.write(e)}}else r.writeVarIntNum(-1);else r.writeInt8(0);const s=await this.transmit("signAction",t,r.toArray()),a=new Ke(s),o={};if(1===a.readInt8()){const e=a.read(32);o.txid=Ne(e)}if(1===a.readInt8()){const e=a.readVarIntNum();o.tx=a.read(e)}const c=a.readVarIntNum();if(c>=0){o.sendWithResults=[];for(let e=0;e<c;e++){const e=a.read(32),t=Ne(e),r=a.readInt8();let i="unproven";1===r?i="unproven":2===r?i="sending":3===r&&(i="failed"),o.sendWithResults.push({txid:t,status:i})}}return o}async abortAction(e,t){return await this.transmit("abortAction",t,Oe(e.reference,"base64")),{aborted:!0}}async listActions(e,t){const r=new Ue;r.writeVarIntNum(e.labels.length);for(const t of e.labels){const e=Oe(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}"any"===e.labelQueryMode?r.writeInt8(1):"all"===e.labelQueryMode?r.writeInt8(2):r.writeInt8(-1);const i=[e.includeLabels,e.includeInputs,e.includeInputSourceLockingScripts,e.includeInputUnlockingScripts,e.includeOutputs,e.includeOutputLockingScripts];for(const e of i)"boolean"==typeof e?r.writeInt8(e?1:0):r.writeInt8(-1);"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1);const n=await this.transmit("listActions",t,r.toArray()),s=new Ke(n),a=s.readVarIntNum(),o=[];for(let e=0;e<a;e++){const e=s.read(32),t=Ne(e),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(),d=s.read(c),u={txid:t,satoshis:r,status:n,isOutgoing:a,description:xe(d),version:0,lockTime:0},h=s.readVarIntNum();if(h>=0){u.labels=[];for(let e=0;e<h;e++){const e=s.readVarIntNum(),t=s.read(e);u.labels.push(xe(t))}}u.version=s.readVarIntNum(),u.lockTime=s.readVarIntNum();const l=s.readVarIntNum();if(l>=0){u.inputs=[];for(let e=0;e<l;e++){const e=this.readOutpoint(s),t=s.readVarIntNum(),r=s.readVarIntNum();let i;if(r>=0){const e=s.read(r);i=Ne(e)}const n=s.readVarIntNum();let a;if(n>=0){const e=s.read(n);a=Ne(e)}const o=s.readVarIntNum(),c=s.read(o),d=xe(c),h=s.readVarIntNum();u.inputs.push({sourceOutpoint:e,sourceSatoshis:t,sourceLockingScript:i,unlockingScript:a,inputDescription:d,sequenceNumber:h})}}const f=s.readVarIntNum();if(f>=0){u.outputs=[];for(let e=0;e<f;e++){const e=s.readVarIntNum(),t=s.readVarIntNum(),r=s.readVarIntNum();let i;if(r>=0){const e=s.read(r);i=Ne(e)}const n=1===s.readInt8(),a=s.readVarIntNum(),o=s.read(a),c=xe(o),d=s.readVarIntNum();let h;if(d>=0){const e=s.read(d);h=xe(e)}const l=s.readVarIntNum(),f=[];if(l>=0)for(let e=0;e<l;e++){const e=s.readVarIntNum(),t=s.read(e);f.push(xe(t))}const p=s.readVarIntNum();let b;if(p>=0){const e=s.read(p);b=xe(e)}u.outputs.push({outputIndex:e,satoshis:t,lockingScript:i,spendable:n,outputDescription:c,basket:h,tags:f,customInstructions:b})}}o.push(u)}return{totalActions:a,actions:o}}async internalizeAction(e,t){const r=new Ue;r.writeVarIntNum(e.tx.length),r.write(e.tx),r.writeVarIntNum(e.outputs.length);for(const t of e.outputs)if(r.writeVarIntNum(t.outputIndex),"wallet payment"===t.protocol){if(null==t.paymentRemittance)throw new Error("Payment remittance is required for wallet payment");r.writeUInt8(1),r.write(Oe(t.paymentRemittance.senderIdentityKey,"hex"));const e=Oe(t.paymentRemittance.derivationPrefix,"base64");r.writeVarIntNum(e.length),r.write(e);const i=Oe(t.paymentRemittance.derivationSuffix,"base64");r.writeVarIntNum(i.length),r.write(i)}else{r.writeUInt8(2);const e=Oe(t.insertionRemittance?.basket,"utf8");if(r.writeVarIntNum(e.length),r.write(e),"string"==typeof t.insertionRemittance?.customInstructions&&""!==t.insertionRemittance.customInstructions){const e=Oe(t.insertionRemittance.customInstructions,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if("object"==typeof t.insertionRemittance?.tags){r.writeVarIntNum(t.insertionRemittance.tags.length);for(const e of t.insertionRemittance.tags){const t=Oe(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}}else r.writeVarIntNum(0)}if("object"==typeof e.labels){r.writeVarIntNum(e.labels.length);for(const t of e.labels){const e=Oe(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}}else r.writeVarIntNum(-1);const i=Oe(e.description);return r.writeVarIntNum(i.length),r.write(i),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1),await this.transmit("internalizeAction",t,r.toArray()),{accepted:!0}}async listOutputs(e,t){const r=new Ue,i=Oe(e.basket,"utf8");if(r.writeVarIntNum(i.length),r.write(i),"object"==typeof e.tags){r.writeVarIntNum(e.tags.length);for(const t of e.tags){const e=Oe(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}}else r.writeVarIntNum(0);"all"===e.tagQueryMode?r.writeInt8(1):"any"===e.tagQueryMode?r.writeInt8(2):r.writeInt8(-1),"locking scripts"===e.include?r.writeInt8(1):"entire transactions"===e.include?r.writeInt8(2):r.writeInt8(-1),"boolean"==typeof e.includeCustomInstructions?r.writeInt8(e.includeCustomInstructions?1:0):r.writeInt8(-1),"boolean"==typeof e.includeTags?r.writeInt8(e.includeTags?1:0):r.writeInt8(-1),"boolean"==typeof e.includeLabels?r.writeInt8(e.includeLabels?1:0):r.writeInt8(-1),"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1);const n=await this.transmit("listOutputs",t,r.toArray()),s=new Ke(n),a=s.readVarIntNum(),o=s.readVarIntNum();let c;o>=0&&(c=s.read(o));const d=[];for(let e=0;e<a;e++){const e={spendable:!0,outpoint:this.readOutpoint(s),satoshis:s.readVarIntNum()},t=s.readVarIntNum();t>=0&&(e.lockingScript=Ne(s.read(t)));const r=s.readVarIntNum();r>=0&&(e.customInstructions=xe(s.read(r)));const i=s.readVarIntNum();if(-1!==i){const t=[];for(let e=0;e<i;e++){const e=s.readVarIntNum();t.push(xe(s.read(e)))}e.tags=t}const n=s.readVarIntNum();if(-1!==n){const t=[];for(let e=0;e<n;e++){const e=s.readVarIntNum();t.push(xe(s.read(e)))}e.labels=t}d.push(e)}return{totalOutputs:a,BEEF:c,outputs:d}}async relinquishOutput(e,t){const r=new Ue,i=Oe(e.basket,"utf8");return r.writeVarIntNum(i.length),r.write(i),r.write(this.encodeOutpoint(e.output)),await this.transmit("relinquishOutput",t,r.toArray()),{relinquished:!0}}encodeOutpoint(e){const t=new Ue,[r,i]=e.split(".");return t.write(Oe(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}readOutpoint(e){return`${Ne(e.read(32))}.${e.readVarIntNum()}`}async getPublicKey(e,t){const r=new Ue;r.writeUInt8(e.identityKey?1:0),e.identityKey?r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)):(r.write(this.encodeKeyRelatedParams(e.protocolID??=[Vr.Silent,"default"],e.keyID??="",e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?r.writeInt8(e.forSelf?1:0):r.writeInt8(-1)),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1);const i=await this.transmit("getPublicKey",t,r.toArray());return{publicKey:Ne(i)}}async revealCounterpartyKeyLinkage(e,t){const r=new Ue;r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),r.write(Oe(e.counterparty,"hex")),r.write(Oe(e.verifier,"hex"));const i=await this.transmit("revealCounterpartyKeyLinkage",t,r.toArray()),n=new Ke(i),s=Ne(n.read(33)),a=Ne(n.read(33)),o=Ne(n.read(33)),c=n.readVarIntNum(),d=xe(n.read(c)),u=n.readVarIntNum(),h=n.read(u),l=n.readVarIntNum();return{prover:s,verifier:a,counterparty:o,revelationTime:d,encryptedLinkage:h,encryptedLinkageProof:n.read(l)}}async revealSpecificKeyLinkage(e,t){const r=new Ue;r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.write(Oe(e.verifier,"hex"));const i=await this.transmit("revealSpecificKeyLinkage",t,r.toArray()),n=new Ke(i),s=Ne(n.read(33)),a=Ne(n.read(33)),o=Ne(n.read(33)),c=n.readUInt8(),d=n.readVarIntNum(),u=xe(n.read(d)),h=n.readVarIntNum(),l=xe(n.read(h)),f=n.readVarIntNum(),p=n.read(f),b=n.readVarIntNum();return{prover:s,verifier:a,counterparty:o,protocolID:[c,u],keyID:l,encryptedLinkage:p,encryptedLinkageProof:n.read(b),proofType:n.readUInt8()}}async encrypt(e,t){const r=new Ue;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.writeVarIntNum(e.plaintext.length),r.write(e.plaintext),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1),{ciphertext:await this.transmit("encrypt",t,r.toArray())}}async decrypt(e,t){const r=new Ue;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.writeVarIntNum(e.ciphertext.length),r.write(e.ciphertext),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1),{plaintext:await this.transmit("decrypt",t,r.toArray())}}async createHmac(e,t){const r=new Ue;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.writeVarIntNum(e.data.length),r.write(e.data),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1),{hmac:await this.transmit("createHmac",t,r.toArray())}}async verifyHmac(e,t){const r=new Ue;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.write(e.hmac),r.writeVarIntNum(e.data.length),r.write(e.data),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1),await this.transmit("verifyHmac",t,r.toArray()),{valid:!0}}async createSignature(e,t){const r=new Ue;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"object"==typeof e.data?(r.writeUInt8(1),r.writeVarIntNum(e.data.length),r.write(e.data)):(r.writeUInt8(2),r.write(e.hashToDirectlySign??=[])),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1),{signature:await this.transmit("createSignature",t,r.toArray())}}async verifySignature(e,t){const r=new Ue;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?r.writeInt8(e.forSelf?1:0):r.writeInt8(-1),r.writeVarIntNum(e.signature.length),r.write(e.signature),"object"==typeof e.data?(r.writeUInt8(1),r.writeVarIntNum(e.data.length),r.write(e.data)):(r.writeUInt8(2),r.write(e.hashToDirectlyVerify??[])),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1),await this.transmit("verifySignature",t,r.toArray()),{valid:!0}}encodeKeyRelatedParams(e,t,r,i,n){const s=new Ue;s.writeUInt8(e[0]);const a=Oe(e[1],"utf8");s.writeVarIntNum(a.length),s.write(a);const o=Oe(t,"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(Oe(r,"hex")),s.write(this.encodePrivilegedParams(i,n)),s.toArray()}async acquireCertificate(e,t){const r=new Ue;r.write(Oe(e.type,"base64")),r.write(Oe(e.certifier,"hex"));const i=Object.entries(e.fields);r.writeVarIntNum(i.length);for(const[e,t]of i){const i=Oe(e,"utf8"),n=Oe(t,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(n.length),r.write(n)}if(r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),r.writeUInt8("direct"===e.acquisitionProtocol?1:2),"direct"===e.acquisitionProtocol){r.write(Oe(e.serialNumber,"base64")),r.write(this.encodeOutpoint(e.revocationOutpoint??""));const t=Oe(e.signature,"hex");r.writeVarIntNum(t.length),r.write(t);const i="certifier"!==e.keyringRevealer?Oe(e.keyringRevealer,"hex"):[11];r.write(i);const n=Object.keys(e.keyringForSubject??{});r.writeVarIntNum(n.length);for(let t=0;t<n.length;t++){const i=Oe(n[t],"utf8");r.writeVarIntNum(i.length),r.write(i);const s=Oe(e.keyringForSubject?.[n[t]],"base64");r.writeVarIntNum(s.length),r.write(s)}}else{const t=Oe(e.certifierUrl,"utf8");r.writeVarIntNum(t.length),r.write(t)}const n=await this.transmit("acquireCertificate",t,r.toArray()),s=$r.fromBinary(n);return{...s,signature:s.signature}}encodePrivilegedParams(e,t){const r=new Ue;if("boolean"==typeof e?r.writeInt8(e?1:0):r.writeInt8(-1),"string"==typeof t){const e=Oe(t,"utf8");r.writeInt8(e.length),r.write(e)}else r.writeInt8(-1);return r.toArray()}async listCertificates(e,t){const r=new Ue;r.writeVarIntNum(e.certifiers.length);for(let t=0;t<e.certifiers.length;t++)r.write(Oe(e.certifiers[t],"hex"));r.writeVarIntNum(e.types.length);for(let t=0;t<e.types.length;t++)r.write(Oe(e.types[t],"base64"));"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));const i=await this.transmit("listCertificates",t,r.toArray()),n=new Ke(i),s=n.readVarIntNum(),a=[];for(let e=0;e<s;e++){const e=n.readVarIntNum(),t=n.read(e),r=$r.fromBinary(t);a.push({...r,signature:r.signature})}return{totalCertificates:s,certificates:a}}async proveCertificate(e,t){const r=new Ue,i=Oe(e.certificate.type,"base64");r.write(i);const n=Oe(e.certificate.subject,"hex");r.write(n);const s=Oe(e.certificate.serialNumber,"base64");r.write(s);const a=Oe(e.certificate.certifier,"hex");r.write(a);const o=this.encodeOutpoint(e.certificate.revocationOutpoint??"");r.write(o);const c=Oe(e.certificate.signature,"hex");r.writeVarIntNum(c.length),r.write(c);const d=Object.entries(e.certificate.fields??{});r.writeVarIntNum(d.length);for(const[e,t]of d){const i=Oe(e,"utf8"),n=Oe(t,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(n.length),r.write(n)}r.writeVarIntNum(e.fieldsToReveal.length);for(const t of e.fieldsToReveal){const e=Oe(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}r.write(Oe(e.verifier,"hex")),r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));const u=await this.transmit("proveCertificate",t,r.toArray()),h=new Ke(u),l=h.readVarIntNum(),f={};for(let e=0;e<l;e++){const e=h.readVarIntNum(),t=xe(h.read(e)),r=h.readVarIntNum();f[t]=Fe(h.read(r))}return{keyringForVerifier:f}}async relinquishCertificate(e,t){const r=new Ue,i=Oe(e.type,"base64");r.write(i);const n=Oe(e.serialNumber,"base64");r.write(n);const s=Oe(e.certifier,"hex");return r.write(s),await this.transmit("relinquishCertificate",t,r.toArray()),{relinquished:!0}}parseDiscoveryResult(e){const t=new Ke(e),r=t.readVarIntNum(),i=[];for(let e=0;e<r;e++){const e=t.readVarIntNum(),r=t.read(e),n=$r.fromBinary(r),s=t.readVarIntNum(),a=xe(t.read(s)),o=t.readVarIntNum(),c=xe(t.read(o)),d=t.readVarIntNum(),u=xe(t.read(d)),h=t.readUInt8(),l={},f=t.readVarIntNum();for(let e=0;e<f;e++){const e=t.readVarIntNum(),r=xe(t.read(e)),i=t.readVarIntNum();l[r]=t.read(i)}const p={},b=t.readVarIntNum();for(let e=0;e<b;e++){const e=t.readVarIntNum(),r=xe(t.read(e)),i=t.readVarIntNum();p[r]=xe(t.read(i))}i.push({...n,signature:n.signature,certifierInfo:{iconUrl:c,name:a,description:u,trust:h},publiclyRevealedKeyring:l,decryptedFields:p})}return{totalCertificates:r,certificates:i}}async discoverByIdentityKey(e,t){const r=new Ue;r.write(Oe(e.identityKey,"hex")),"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1);const i=await this.transmit("discoverByIdentityKey",t,r.toArray());return this.parseDiscoveryResult(i)}async discoverByAttributes(e,t){const r=new Ue,i=Object.keys(e.attributes);r.writeVarIntNum(i.length);for(let t=0;t<i.length;t++)r.writeVarIntNum(i[t].length),r.write(Oe(i[t],"utf8")),r.writeVarIntNum(e.attributes[i[t]].length),r.write(Oe(e.attributes[i[t]],"utf8"));"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof e.seekPermission?e.seekPermission?1:0:-1);const n=await this.transmit("discoverByAttributes",t,r.toArray());return this.parseDiscoveryResult(n)}async isAuthenticated(e,t){return{authenticated:1===(await this.transmit("isAuthenticated",t))[0]}}async waitForAuthentication(e,t){return await this.transmit("waitForAuthentication",t),{authenticated:!0}}async getHeight(e,t){const r=await this.transmit("getHeight",t);return{height:new Ke(r).readVarIntNum()}}async getHeaderForHeight(e,t){const r=new Ue;r.writeVarIntNum(e.height);const i=await this.transmit("getHeaderForHeight",t,r.toArray());return{header:Ne(i)}}async getNetwork(e,t){return{network:0===(await this.transmit("getNetwork",t))[0]?"mainnet":"testnet"}}async getVersion(e,t){const r=await this.transmit("getVersion",t);return{version:xe(r)}}}class Xr{baseUrl;httpClient;originator;constructor(e,t="http://localhost:3301",r=fetch){this.baseUrl=t,this.httpClient=r,this.originator=e}async transmitToWallet(e){const t=new Ke(e),r=t.readUInt8(),i=Wr[r];if(void 0===i||""===i)throw new Error(`Invalid call code: ${r}`);const n=t.readUInt8();let s;if(n>0){const e=t.read(n);s=xe(e)}const a=t.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 Gr extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(e,t,r,i,n){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=e,this.sendWithResults=t,this.txid=r,this.tx=i,this.noSendChange=n,this.code=5,this.name=this.constructor.name}}const Yr=Gr;class Jr{baseUrl;httpClient;originator;api;constructor(e,t="http://localhost:3321",r=fetch){this.baseUrl=t,this.originator=e,this.httpClient=r,this.api=async(e,t)=>{const i=await await r(`${this.baseUrl}/${e}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Originator:this.originator??""},body:JSON.stringify(t)}),n=await i.json();if(!i.ok){if(400===i.status&&n.isError&&5===n.code)throw new Gr(n.reviewActionResults,n.sendWithResults,n.txid,n.tx,n.noSendChange);{const r={call:e,args:t,message:n.message??`HTTP Client error ${i.status}`};throw new Error(JSON.stringify(r))}}return n}}async createAction(e){return await this.api("createAction",e)}async signAction(e){return await this.api("signAction",e)}async abortAction(e){return await this.api("abortAction",e)}async listActions(e){return await this.api("listActions",e)}async internalizeAction(e){return await this.api("internalizeAction",e)}async listOutputs(e){return await this.api("listOutputs",e)}async relinquishOutput(e){return await this.api("relinquishOutput",e)}async getPublicKey(e){return await this.api("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.api("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.api("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.api("encrypt",e)}async decrypt(e){return await this.api("decrypt",e)}async createHmac(e){return await this.api("createHmac",e)}async verifyHmac(e){return await this.api("verifyHmac",e)}async createSignature(e){return await this.api("createSignature",e)}async verifySignature(e){return await this.api("verifySignature",e)}async acquireCertificate(e){return await this.api("acquireCertificate",e)}async listCertificates(e){return await this.api("listCertificates",e)}async proveCertificate(e){return await this.api("proveCertificate",e)}async relinquishCertificate(e){return await this.api("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.api("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.api("discoverByAttributes",e)}async isAuthenticated(e){return await this.api("isAuthenticated",e)}async waitForAuthentication(e){return await this.api("waitForAuthentication",e)}async getHeight(e){return await this.api("getHeight",e)}async getHeaderForHeight(e){return await this.api("getHeaderForHeight",e)}async getNetwork(e){return await this.api("getNetwork",e)}async getVersion(e){return await this.api("getVersion",e)}}class Zr{domain;constructor(e="*"){if("object"!=typeof window)throw new Error("The XDM substrate requires a global window object.");if(!window.hasOwnProperty("ReactNativeWebView"))throw new Error("The window object does not have a ReactNativeWebView property.");if("function"!=typeof window.ReactNativeWebView.postMessage)throw new Error("The window.ReactNativeWebView property does not seem to support postMessage calls.");this.domain=e}async invoke(e,t){return await new Promise(((r,i)=>{const n=Fe(Ze(12)),s=e=>{const t=JSON.parse(e.data);if("CWI"===t.type&&t.id===n&&!0!==t.isInvocation)if("function"==typeof window.removeEventListener&&window.removeEventListener("message",s),"error"===t.status){const e=new Lr(t.description,t.code);i(e)}else r(t.result)};window.addEventListener("message",s),window.ReactNativeWebView.postMessage(JSON.stringify({type:"CWI",isInvocation:!0,id:n,call:e,args:t}))}))}async createAction(e){return await this.invoke("createAction",e)}async signAction(e){return await this.invoke("signAction",e)}async abortAction(e){return await this.invoke("abortAction",e)}async listActions(e){return await this.invoke("listActions",e)}async internalizeAction(e){return await this.invoke("internalizeAction",e)}async listOutputs(e){return await this.invoke("listOutputs",e)}async relinquishOutput(e){return await this.invoke("relinquishOutput",e)}async getPublicKey(e){return await this.invoke("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.invoke("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.invoke("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.invoke("encrypt",e)}async decrypt(e){return await this.invoke("decrypt",e)}async createHmac(e){return await this.invoke("createHmac",e)}async verifyHmac(e){return await this.invoke("verifyHmac",e)}async createSignature(e){return await this.invoke("createSignature",e)}async verifySignature(e){return await this.invoke("verifySignature",e)}async acquireCertificate(e){return await this.invoke("acquireCertificate",e)}async listCertificates(e){return await this.invoke("listCertificates",e)}async proveCertificate(e){return await this.invoke("proveCertificate",e)}async relinquishCertificate(e){return await this.invoke("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.invoke("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.invoke("discoverByAttributes",e)}async isAuthenticated(e){return await this.invoke("isAuthenticated",e)}async waitForAuthentication(e){return await this.invoke("waitForAuthentication",e)}async getHeight(e){return await this.invoke("getHeight",e)}async getHeaderForHeight(e){return await this.invoke("getHeaderForHeight",e)}async getNetwork(e){return await this.invoke("getNetwork",e)}async getVersion(e){return await this.invoke("getVersion",e)}}class Qr{substrate;originator;constructor(e="auto",t){"Cicada"===e&&(e=new jr(new Xr(t))),"window.CWI"===e&&(e=new Kr),"XDM"===e&&(e=new Mr),"json-api"===e&&(e=new Jr(t)),"react-native"===e&&(e=new Zr(t)),this.substrate=e,this.originator=t}async connectToSubstrate(){if("object"==typeof this.substrate)return;let e;const t=async t=>{let r;if(r="number"==typeof t?await Promise.race([e.getVersion({}),new Promise(((e,r)=>setTimeout((()=>r(new Error("Timed out."))),t)))]):await e.getVersion({}),"object"!=typeof r||"string"!=typeof r.version)throw new Error("Failed to use substrate.")};try{e=new Kr,await t(),this.substrate=e}catch(r){try{e=new Mr,await t(200),this.substrate=e}catch(r){try{e=new jr(new Xr(this.originator)),await t(),this.substrate=e}catch(r){try{e=new Jr(this.originator),await t(),this.substrate=e}catch(r){try{e=new Zr(this.originator),await t(),this.substrate=e}catch(e){throw new Error("No wallet available over any communication substrate. Install a BSV wallet today!")}}}}}}async createAction(e){return await this.connectToSubstrate(),await this.substrate.createAction(e,this.originator)}async signAction(e){return await this.connectToSubstrate(),await this.substrate.signAction(e,this.originator)}async abortAction(e){return await this.connectToSubstrate(),await this.substrate.abortAction(e,this.originator)}async listActions(e){return await this.connectToSubstrate(),await this.substrate.listActions(e,this.originator)}async internalizeAction(e){return await this.connectToSubstrate(),await this.substrate.internalizeAction(e,this.originator)}async listOutputs(e){return await this.connectToSubstrate(),await this.substrate.listOutputs(e,this.originator)}async relinquishOutput(e){return await this.connectToSubstrate(),await this.substrate.relinquishOutput(e,this.originator)}async getPublicKey(e){return await this.connectToSubstrate(),await this.substrate.getPublicKey(e,this.originator)}async revealCounterpartyKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealCounterpartyKeyLinkage(e,this.originator)}async revealSpecificKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealSpecificKeyLinkage(e,this.originator)}async encrypt(e){return await this.connectToSubstrate(),await this.substrate.encrypt(e,this.originator)}async decrypt(e){return await this.substrate.decrypt(e,this.originator)}async createHmac(e){return await this.connectToSubstrate(),await this.substrate.createHmac(e,this.originator)}async verifyHmac(e){return await this.connectToSubstrate(),await this.substrate.verifyHmac(e,this.originator)}async createSignature(e){return await this.connectToSubstrate(),await this.substrate.createSignature(e,this.originator)}async verifySignature(e){return await this.connectToSubstrate(),await this.substrate.verifySignature(e,this.originator)}async acquireCertificate(e){return await this.connectToSubstrate(),await this.substrate.acquireCertificate(e,this.originator)}async listCertificates(e){return await this.connectToSubstrate(),await this.substrate.listCertificates(e,this.originator)}async proveCertificate(e){return await this.connectToSubstrate(),await this.substrate.proveCertificate(e,this.originator)}async relinquishCertificate(e){return await this.connectToSubstrate(),await this.substrate.relinquishCertificate(e,this.originator)}async discoverByIdentityKey(e){return await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(e,this.originator)}async discoverByAttributes(e){return await this.connectToSubstrate(),await this.substrate.discoverByAttributes(e,this.originator)}async isAuthenticated(e={}){return await this.connectToSubstrate(),await this.substrate.isAuthenticated(e,this.originator)}async waitForAuthentication(e={}){return await this.connectToSubstrate(),await this.substrate.waitForAuthentication(e,this.originator)}async getHeight(e={}){return await this.connectToSubstrate(),await this.substrate.getHeight(e,this.originator)}async getHeaderForHeight(e){return await this.connectToSubstrate(),await this.substrate.getHeaderForHeight(e,this.originator)}async getNetwork(e={}){return await this.connectToSubstrate(),await this.substrate.getNetwork(e,this.originator)}async getVersion(e={}){return await this.connectToSubstrate(),await this.substrate.getVersion(e,this.originator)}}class ei{wallet;constructor(e){this.wallet=e}decodeOutpoint(e){const t=e.read(32);return`${Ne(t)}.${e.readVarIntNum()}`}encodeOutpoint(e){const t=new Ue,[r,i]=e.split(".");return t.write(Oe(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}async transmitToWallet(e){const t=new Ke(e);try{const e=t.readUInt8(),r=Wr[e];if(void 0===r||""===r)throw new Error(`Invalid call code: ${e}`);const i=t.readUInt8(),n=t.read(i),s=xe(n),a=t;switch(r){case"createAction":{const e={},t=a.readVarIntNum(),r=a.read(t);e.description=xe(r);const i=a.readVarIntNum();e.inputBEEF=i>=0?a.read(i):void 0;const n=a.readVarIntNum();if(n>=0){e.inputs=[];for(let t=0;t<n;t++){const t={};t.outpoint=this.decodeOutpoint(a);const r=a.readVarIntNum();if(r>=0){const e=a.read(r);t.unlockingScript=Ne(e)}else{t.unlockingScript=void 0;const e=a.readVarIntNum();t.unlockingScriptLength=e}const i=a.readVarIntNum(),n=a.read(i);t.inputDescription=xe(n);const s=a.readVarIntNum();t.sequenceNumber=s>=0?s:void 0,e.inputs.push(t)}}else e.inputs=void 0;const o=a.readVarIntNum();if(o>=0){e.outputs=[];for(let t=0;t<o;t++){const t={},r=a.readVarIntNum(),i=a.read(r);t.lockingScript=Ne(i),t.satoshis=a.readVarIntNum();const n=a.readVarIntNum(),s=a.read(n);t.outputDescription=xe(s);const o=a.readVarIntNum();if(o>=0){const e=a.read(o);t.basket=xe(e)}else t.basket=void 0;const c=a.readVarIntNum();if(c>=0){const e=a.read(c);t.customInstructions=xe(e)}else t.customInstructions=void 0;const d=a.readVarIntNum();if(d>=0){t.tags=[];for(let e=0;e<d;e++){const e=a.readVarIntNum(),r=a.read(e),i=xe(r);t.tags.push(i)}}else t.tags=void 0;e.outputs.push(t)}}else e.outputs=void 0;const c=a.readVarIntNum();e.lockTime=c>=0?c:void 0;const d=a.readVarIntNum();e.version=d>=0?d:void 0;const u=a.readVarIntNum();if(u>=0){e.labels=[];for(let t=0;t<u;t++){const t=a.readVarIntNum(),r=a.read(t),i=xe(r);e.labels.push(i)}}else e.labels=void 0;if(1===a.readInt8()){e.options={};const t=a.readInt8();e.options.signAndProcess=-1===t?void 0:1===t;const r=a.readInt8();e.options.acceptDelayedBroadcast=-1===r?void 0:1===r;const i=a.readInt8();-1===i?e.options.trustSelf=void 0:1===i&&(e.options.trustSelf="known");const n=a.readVarIntNum();if(n>=0){e.options.knownTxids=[];for(let t=0;t<n;t++){const t=a.read(32),r=Ne(t);e.options.knownTxids.push(r)}}else e.options.knownTxids=void 0;const s=a.readInt8();e.options.returnTXIDOnly=-1===s?void 0:1===s;const o=a.readInt8();e.options.noSend=-1===o?void 0:1===o;const c=a.readVarIntNum();if(c>=0){e.options.noSendChange=[];for(let t=0;t<c;t++){const t=this.decodeOutpoint(a);e.options.noSendChange.push(t)}}else e.options.noSendChange=void 0;const d=a.readVarIntNum();if(d>=0){e.options.sendWith=[];for(let t=0;t<d;t++){const t=a.read(32),r=Ne(t);e.options.sendWith.push(r)}}else e.options.sendWith=void 0;const u=a.readInt8();e.options.randomizeOutputs=-1===u?void 0:1===u}else e.options=void 0;const h=await this.wallet.createAction(e,s),l=new Ue;if(null!=h.txid&&""!==h.txid?(l.writeInt8(1),l.write(Oe(h.txid,"hex"))):l.writeInt8(0),null!=h.tx?(l.writeInt8(1),l.writeVarIntNum(h.tx.length),l.write(h.tx)):l.writeInt8(0),null!=h.noSendChange){l.writeVarIntNum(h.noSendChange.length);for(const e of h.noSendChange)l.write(this.encodeOutpoint(e))}else l.writeVarIntNum(-1);if(null!=h.sendWithResults){l.writeVarIntNum(h.sendWithResults.length);for(const e of h.sendWithResults){let t;l.write(Oe(e.txid,"hex")),"unproven"===e.status?t=1:"sending"===e.status?t=2:"failed"===e.status&&(t=3),l.writeInt8(t)}}else l.writeVarIntNum(-1);if(null!=h.signableTransaction){l.writeInt8(1),l.writeVarIntNum(h.signableTransaction.tx.length),l.write(h.signableTransaction.tx);const e=Oe(h.signableTransaction.reference,"base64");l.writeVarIntNum(e.length),l.write(e)}else l.writeInt8(0);const f=new Ue;return f.writeUInt8(0),f.write(l.toArray()),f.toArray()}case"signAction":{const e={},t=a.readVarIntNum();e.spends={};for(let r=0;r<t;r++){const t=a.readVarIntNum(),r={},i=a.readVarIntNum(),n=a.read(i);r.unlockingScript=Ne(n);const s=a.readVarIntNum();r.sequenceNumber=s>=0?s:void 0,e.spends[t]=r}const r=a.readVarIntNum(),i=a.read(r);if(e.reference=Fe(i),1===a.readInt8()){e.options={};const t=a.readInt8();e.options.acceptDelayedBroadcast=-1===t?void 0:1===t;const r=a.readInt8();e.options.returnTXIDOnly=-1===r?void 0:1===r;const i=a.readInt8();e.options.noSend=-1===i?void 0:1===i;const n=a.readVarIntNum();if(n>=0){e.options.sendWith=[];for(let t=0;t<n;t++){const t=a.read(32),r=Ne(t);e.options.sendWith.push(r)}}else e.options.sendWith=void 0}else e.options=void 0;const n=await this.wallet.signAction(e,s),o=new Ue;if(null!=n.txid&&""!==n.txid?(o.writeInt8(1),o.write(Oe(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 e of n.sendWithResults){let t;o.write(Oe(e.txid,"hex")),"unproven"===e.status?t=1:"sending"===e.status?t=2:"failed"===e.status&&(t=3),o.writeInt8(t)}}else o.writeVarIntNum(-1);const c=new Ue;return c.writeUInt8(0),c.write(o.toArray()),c.toArray()}case"abortAction":{const e=Fe(a.read());await this.wallet.abortAction({reference:e},s);const t=new Ue;return t.writeUInt8(0),t.toArray()}case"listActions":{const e={},t=a.readVarIntNum();e.labels=[];for(let r=0;r<t;r++){const t=a.readVarIntNum(),r=a.read(t);e.labels.push(xe(r))}const r=a.readInt8();-1===r?e.labelQueryMode=void 0:1===r?e.labelQueryMode="any":2===r&&(e.labelQueryMode="all");const i=["includeLabels","includeInputs","includeInputSourceLockingScripts","includeInputUnlockingScripts","includeOutputs","includeOutputLockingScripts"];for(const t of i){const r=a.readInt8();e[t]=-1===r?void 0:1===r}const n=a.readVarIntNum();e.limit=n>=0?n:void 0;const o=a.readVarIntNum();e.offset=o>=0?o:void 0;const c=a.readInt8();e.seekPermission=c>=0?1===c:void 0;const d=await this.wallet.listActions(e,s),u=new Ue;u.writeVarIntNum(d.totalActions);for(const e of d.actions){let t;switch(u.write(Oe(e.txid,"hex")),u.writeVarIntNum(e.satoshis),e.status){case"completed":t=1;break;case"unprocessed":t=2;break;case"sending":t=3;break;case"unproven":t=4;break;case"unsigned":t=5;break;case"nosend":t=6;break;case"nonfinal":t=7;break;case"failed":t=8;break;default:t=-1}u.writeInt8(t),u.writeInt8(e.isOutgoing?1:0);const r=Oe(e.description,"utf8");if(u.writeVarIntNum(r.length),u.write(r),void 0!==e.labels){u.writeVarIntNum(e.labels.length);for(const t of e.labels){const e=Oe(t,"utf8");u.writeVarIntNum(e.length),u.write(e)}}else u.writeVarIntNum(-1);if(u.writeVarIntNum(e.version),u.writeVarIntNum(e.lockTime),void 0!==e.inputs){u.writeVarIntNum(e.inputs.length);for(const t of e.inputs){if(u.write(this.encodeOutpoint(t.sourceOutpoint)),u.writeVarIntNum(t.sourceSatoshis),void 0!==t.sourceLockingScript){const e=Oe(t.sourceLockingScript,"hex");u.writeVarIntNum(e.length),u.write(e)}else u.writeVarIntNum(-1);if(void 0!==t.unlockingScript){const e=Oe(t.unlockingScript,"hex");u.writeVarIntNum(e.length),u.write(e)}else u.writeVarIntNum(-1);const e=Oe(t.inputDescription,"utf8");u.writeVarIntNum(e.length),u.write(e),u.writeVarIntNum(t.sequenceNumber)}}else u.writeVarIntNum(-1);if(void 0!==e.outputs){u.writeVarIntNum(e.outputs.length);for(const t of e.outputs){if(u.writeVarIntNum(t.outputIndex),u.writeVarIntNum(t.satoshis),void 0!==t.lockingScript){const e=Oe(t.lockingScript,"hex");u.writeVarIntNum(e.length),u.write(e)}else u.writeVarIntNum(-1);u.writeInt8(t.spendable?1:0);const e=Oe(t.outputDescription,"utf8");if(u.writeVarIntNum(e.length),u.write(e),void 0!==t.basket){const e=Oe(t.basket,"utf8");u.writeVarIntNum(e.length),u.write(e)}else u.writeVarIntNum(-1);if(void 0!==t.tags){u.writeVarIntNum(t.tags.length);for(const e of t.tags){const t=Oe(e,"utf8");u.writeVarIntNum(t.length),u.write(t)}}else u.writeVarIntNum(-1);if(void 0!==t.customInstructions){const e=Oe(t.customInstructions,"utf8");u.writeVarIntNum(e.length),u.write(e)}else u.writeVarIntNum(-1)}}else u.writeVarIntNum(-1)}const h=new Ue;return h.writeUInt8(0),h.write(u.toArray()),h.toArray()}case"internalizeAction":{const e={},t=a.readVarIntNum();e.tx=a.read(t);const r=a.readVarIntNum();e.outputs=[];for(let t=0;t<r;t++){const t={};t.outputIndex=a.readVarIntNum();const r=a.readUInt8();if(1===r){t.protocol="wallet payment",t.paymentRemittance={};const e=a.read(33);t.paymentRemittance.senderIdentityKey=Ne(e);const r=a.readVarIntNum(),i=a.read(r);t.paymentRemittance.derivationPrefix=Fe(i);const n=a.readVarIntNum(),s=a.read(n);t.paymentRemittance.derivationSuffix=Fe(s)}else if(2===r){t.protocol="basket insertion",t.insertionRemittance={};const e=a.readVarIntNum(),r=a.read(e);t.insertionRemittance.basket=xe(r);const i=a.readVarIntNum();if(i>=0){const e=a.read(i);t.insertionRemittance.customInstructions=xe(e)}const n=a.readVarIntNum();if(n>0){t.insertionRemittance.tags=[];for(let e=0;e<n;e++){const e=a.readVarIntNum(),r=a.read(e);t.insertionRemittance.tags.push(xe(r))}}else t.insertionRemittance.tags=[]}e.outputs.push(t)}const i=a.readVarIntNum();if(i>=0){e.labels=[];for(let t=0;t<i;t++){const t=a.readVarIntNum();e.labels.push(xe(a.read(t)))}}const n=a.readVarIntNum();e.description=xe(a.read(n));const o=a.readInt8();e.seekPermission=o>=0?1===o:void 0,await this.wallet.internalizeAction(e,s);const c=new Ue;return c.writeUInt8(0),c.toArray()}case"listOutputs":{const e={},t=a.readVarIntNum(),r=a.read(t);e.basket=xe(r);const i=a.readVarIntNum();if(i>0){e.tags=[];for(let t=0;t<i;t++){const t=a.readVarIntNum(),r=a.read(t);e.tags.push(xe(r))}}else e.tags=void 0;const n=a.readInt8();e.tagQueryMode=1===n?"all":2===n?"any":void 0;const o=a.readInt8();e.include=1===o?"locking scripts":2===o?"entire transactions":void 0;const c=a.readInt8();e.includeCustomInstructions=-1===c?void 0:1===c;const d=a.readInt8();e.includeTags=-1===d?void 0:1===d;const u=a.readInt8();e.includeLabels=-1===u?void 0:1===u;const h=a.readVarIntNum();e.limit=h>=0?h:void 0;const l=a.readVarIntNum();e.offset=l>=0?l:void 0;const f=a.readInt8();e.seekPermission=f>=0?1===f:void 0;const p=await this.wallet.listOutputs(e,s),b=new Ue;b.writeVarIntNum(p.totalOutputs),null!=p.BEEF?(b.writeVarIntNum(p.BEEF.length),b.write(p.BEEF)):b.writeVarIntNum(-1);for(const e of p.outputs){if(b.write(this.encodeOutpoint(e.outpoint)),b.writeVarIntNum(e.satoshis),void 0!==e.lockingScript){const t=Oe(e.lockingScript,"hex");b.writeVarIntNum(t.length),b.write(t)}else b.writeVarIntNum(-1);if(void 0!==e.customInstructions){const t=Oe(e.customInstructions,"utf8");b.writeVarIntNum(t.length),b.write(t)}else b.writeVarIntNum(-1);if(void 0!==e.tags){b.writeVarIntNum(e.tags.length);for(const t of e.tags){const e=Oe(t,"utf8");b.writeVarIntNum(e.length),b.write(e)}}else b.writeVarIntNum(-1);if(void 0!==e.labels){b.writeVarIntNum(e.labels.length);for(const t of e.labels){const e=Oe(t,"utf8");b.writeVarIntNum(e.length),b.write(e)}}else b.writeVarIntNum(-1)}const w=new Ue;return w.writeUInt8(0),w.write(b.toArray()),w.toArray()}case"relinquishOutput":{const e={},t=a.readVarIntNum(),r=a.read(t);e.basket=xe(r),e.output=this.decodeOutpoint(a),await this.wallet.relinquishOutput(e,s);const i=new Ue;return i.writeUInt8(0),i.toArray()}case"getPublicKey":{const e={},t=a.readUInt8();if(e.identityKey=1===t,!0!==e.identityKey){e.protocolID=this.decodeProtocolID(a),e.keyID=this.decodeString(a),e.counterparty=this.decodeCounterparty(a);const t=a.readInt8();e.privileged=-1===t?void 0:1===t;const r=a.readInt8();if(-1!==r){const t=a.read(r);e.privilegedReason=xe(t)}else e.privilegedReason=void 0;const i=a.readInt8();e.forSelf=-1===i?void 0:1===i}else{const t=a.readInt8();e.privileged=-1===t?void 0:1===t;const r=a.readInt8();if(-1!==r){const t=a.read(r);e.privilegedReason=xe(t)}else e.privilegedReason=void 0}const r=a.readInt8();e.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.getPublicKey(e,s),n=new Ue;n.writeUInt8(0);const o=Oe(i.publicKey,"hex");return n.write(o),n.toArray()}case"encrypt":{const e=this.decodeKeyRelatedParams(a),t=a.readVarIntNum();e.plaintext=a.read(t);const r=a.readInt8();e.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.encrypt(e,s),n=new Ue;return n.writeUInt8(0),n.write(i.ciphertext),n.toArray()}case"decrypt":{const e=this.decodeKeyRelatedParams(a),t=a.readVarIntNum();e.ciphertext=a.read(t);const r=a.readInt8();e.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.decrypt(e,s),n=new Ue;return n.writeUInt8(0),n.write(i.plaintext),n.toArray()}case"createHmac":{const e=this.decodeKeyRelatedParams(a),t=a.readVarIntNum();e.data=a.read(t);const r=a.readInt8();e.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.createHmac(e,s),n=new Ue;return n.writeUInt8(0),n.write(i.hmac),n.toArray()}case"verifyHmac":{const e=this.decodeKeyRelatedParams(a);e.hmac=a.read(32);const t=a.readVarIntNum();e.data=a.read(t);const r=a.readInt8();e.seekPermission=r>=0?1===r:void 0,await this.wallet.verifyHmac(e,s);const i=new Ue;return i.writeUInt8(0),i.toArray()}case"createSignature":{const e=this.decodeKeyRelatedParams(a),t=a.readUInt8();if(1===t){const t=a.readVarIntNum();e.data=a.read(t)}else 2===t&&(e.hashToDirectlySign=a.read(32));const r=a.readInt8();e.seekPermission=r>=0?1===r:void 0;const i=await this.wallet.createSignature(e,s),n=new Ue;return n.writeUInt8(0),n.write(i.signature),n.toArray()}case"verifySignature":{const e=this.decodeKeyRelatedParams(a),t=a.readInt8();e.forSelf=-1===t?void 0:1===t;const r=a.readVarIntNum();e.signature=a.read(r);const i=a.readUInt8();if(1===i){const t=a.readVarIntNum();e.data=a.read(t)}else 2===i&&(e.hashToDirectlyVerify=a.read(32));const n=a.readInt8();e.seekPermission=n>=0?1===n:void 0,await this.wallet.verifySignature(e,s);const o=new Ue;return o.writeUInt8(0),o.toArray()}case"isAuthenticated":{const e=await this.wallet.isAuthenticated({},s),t=new Ue;return t.writeUInt8(0),t.writeUInt8(e.authenticated?1:0),t.toArray()}case"waitForAuthentication":{await this.wallet.waitForAuthentication({},s);const e=new Ue;return e.writeUInt8(0),e.toArray()}case"getHeight":{const e=await this.wallet.getHeight({},s),t=new Ue;return t.writeUInt8(0),t.writeVarIntNum(e.height),t.toArray()}case"getHeaderForHeight":{const e={};e.height=a.readVarIntNum();const t=await this.wallet.getHeaderForHeight(e,s),r=new Ue;r.writeUInt8(0);const i=Oe(t.header,"hex");return r.write(i),r.toArray()}case"getNetwork":{const e=await this.wallet.getNetwork({},s),t=new Ue;return t.writeUInt8(0),t.writeUInt8("mainnet"===e.network?0:1),t.toArray()}case"getVersion":{const e=await this.wallet.getVersion({},s),t=new Ue;t.writeUInt8(0);const r=Oe(e.version,"utf8");return t.write(r),t.toArray()}case"revealCounterpartyKeyLinkage":{const e={},t=a.readInt8();e.privileged=-1===t?void 0:1===t;const r=a.readInt8();if(-1===r)e.privilegedReason=void 0;else{const t=a.read(r);e.privilegedReason=xe(t)}const i=a.read(33);e.counterparty=Ne(i);const n=a.read(33);e.verifier=Ne(n);const o=await this.wallet.revealCounterpartyKeyLinkage(e,s),c=new Ue;c.write(Oe(o.prover,"hex")),c.write(Oe(o.verifier,"hex")),c.write(Oe(o.counterparty,"hex"));const d=Oe(o.revelationTime,"utf8");c.writeVarIntNum(d.length),c.write(d),c.writeVarIntNum(o.encryptedLinkage.length),c.write(o.encryptedLinkage),c.writeVarIntNum(o.encryptedLinkageProof.length),c.write(o.encryptedLinkageProof);const u=new Ue;return u.writeUInt8(0),u.write(c.toArray()),u.toArray()}case"revealSpecificKeyLinkage":{const e=this.decodeKeyRelatedParams(a),t=a.read(33);e.verifier=Ne(t);const r=await this.wallet.revealSpecificKeyLinkage(e,s),i=new Ue;i.write(Oe(r.prover,"hex")),i.write(Oe(r.verifier,"hex")),i.write(Oe(r.counterparty,"hex")),i.writeUInt8(r.protocolID[0]);const n=Oe(r.protocolID[1],"utf8");i.writeVarIntNum(n.length),i.write(n);const o=Oe(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 Ue;return c.writeUInt8(0),c.write(i.toArray()),c.toArray()}case"acquireCertificate":{const e={},t=a.read(32);e.type=Fe(t);const r=a.read(33);e.certifier=Ne(r);const i=a.readVarIntNum();e.fields={};for(let t=0;t<i;t++){const t=a.readVarIntNum(),r=a.read(t),i=xe(r),n=a.readVarIntNum(),s=a.read(n),o=xe(s);e.fields[i]=o}const n=a.readInt8();e.privileged=-1===n?void 0:1===n;const o=a.readInt8();if(-1===o)e.privilegedReason=void 0;else{const t=a.read(o);e.privilegedReason=xe(t)}const c=a.readUInt8();if(e.acquisitionProtocol=1===c?"direct":"issuance","direct"===e.acquisitionProtocol){const t=a.read(32);e.serialNumber=Fe(t),e.revocationOutpoint=this.decodeOutpoint(a);const r=a.readVarIntNum(),i=a.read(r);e.signature=Ne(i);const n=a.readUInt8();if(11===n)e.keyringRevealer="certifier";else{const t=[n].concat(a.read(32));e.keyringRevealer=Ne(t)}const s=a.readVarIntNum();e.keyringForSubject={};for(let t=0;t<s;t++){const t=a.readVarIntNum(),r=a.read(t),i=xe(r),n=a.readVarIntNum(),s=Fe(a.read(n));e.keyringForSubject[i]=s}}else{const t=a.readVarIntNum(),r=a.read(t);e.certifierUrl=xe(r)}const d=await this.wallet.acquireCertificate(e,s),u=new $r(d.type,d.serialNumber,d.subject,d.certifier,d.revocationOutpoint,d.fields,d.signature).toBinary(),h=new Ue;return h.writeUInt8(0),h.write(u),h.toArray()}case"listCertificates":{const e={},t=a.readVarIntNum();e.certifiers=[];for(let r=0;r<t;r++){const t=a.read(33);e.certifiers.push(Ne(t))}const r=a.readVarIntNum();e.types=[];for(let t=0;t<r;t++){const t=a.read(32);e.types.push(Fe(t))}const i=a.readVarIntNum();e.limit=i>=0?i:void 0;const n=a.readVarIntNum();e.offset=n>=0?n:void 0;const o=a.readInt8();e.privileged=-1===o?void 0:1===o;const c=a.readInt8();if(-1===c)e.privilegedReason=void 0;else{const t=a.read(c);e.privilegedReason=xe(t)}const d=await this.wallet.listCertificates(e,s),u=new Ue;u.writeVarIntNum(d.totalCertificates);for(const e of d.certificates){const t=new $r(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature).toBinary();u.writeVarIntNum(t.length),u.write(t)}const h=new Ue;return h.writeUInt8(0),h.write(u.toArray()),h.toArray()}case"proveCertificate":{const e={},t={},r=a.read(32);t.type=Fe(r);const i=a.read(33);t.subject=Ne(i);const n=a.read(32);t.serialNumber=Fe(n);const o=a.read(33);t.certifier=Ne(o),t.revocationOutpoint=this.decodeOutpoint(a);const c=a.readVarIntNum(),d=a.read(c);t.signature=Ne(d);const u=a.readVarIntNum();t.fields={};for(let e=0;e<u;e++){const e=a.readVarIntNum(),r=a.read(e),i=xe(r),n=a.readVarIntNum(),s=a.read(n),o=xe(s);t.fields[i]=o}e.certificate=t;const h=a.readVarIntNum();e.fieldsToReveal=[];for(let t=0;t<h;t++){const t=a.readVarIntNum(),r=a.read(t),i=xe(r);e.fieldsToReveal.push(i)}const l=a.read(33);e.verifier=Ne(l);const f=a.readInt8();e.privileged=-1===f?void 0:1===f;const p=a.readInt8();if(-1===p)e.privilegedReason=void 0;else{const t=a.read(p);e.privilegedReason=xe(t)}const b=await this.wallet.proveCertificate(e,s),w=new Ue,g=Object.entries(b.keyringForVerifier);w.writeVarIntNum(g.length);for(const[e,t]of g){const r=Oe(e,"utf8");w.writeVarIntNum(r.length),w.write(r);const i=Oe(t,"base64");w.writeVarIntNum(i.length),w.write(i)}const m=new Ue;return m.writeUInt8(0),m.write(w.toArray()),m.toArray()}case"relinquishCertificate":{const e={},t=a.read(32);e.type=Fe(t);const r=a.read(32);e.serialNumber=Fe(r);const i=a.read(33);e.certifier=Ne(i),await this.wallet.relinquishCertificate(e,s);const n=new Ue;return n.writeUInt8(0),n.toArray()}case"discoverByIdentityKey":{const e={},t=a.read(33);e.identityKey=Ne(t);const r=a.readVarIntNum();e.limit=r>=0?r:void 0;const i=a.readVarIntNum();e.offset=i>=0?i:void 0;const n=a.readInt8();e.seekPermission=n>=0?1===n:void 0;const o=await this.wallet.discoverByIdentityKey(e,s),c=this.serializeDiscoveryResult(o),d=new Ue;return d.writeUInt8(0),d.write(c),d.toArray()}case"discoverByAttributes":{const e={},t=a.readVarIntNum();e.attributes={};for(let r=0;r<t;r++){const t=a.readVarIntNum(),r=a.read(t),i=xe(r),n=a.readVarIntNum(),s=a.read(n),o=xe(s);e.attributes[i]=o}const r=a.readVarIntNum();e.limit=r>=0?r:void 0;const i=a.readVarIntNum();e.offset=i>=0?i:void 0;const n=a.readInt8();e.seekPermission=n>=0?1===n:void 0;const o=await this.wallet.discoverByAttributes(e,s),c=this.serializeDiscoveryResult(o),d=new Ue;return d.writeUInt8(0),d.write(c),d.toArray()}default:throw new Error(`Method ${r} not implemented`)}}catch(e){const t=new Ue;t.writeUInt8("number"==typeof e.code?e.code:1);const r="string"==typeof e.message?e.message:"Unknown error",i=Oe(r,"utf8");t.writeVarIntNum(i.length),t.write(i);const n="string"==typeof e.stack?e.stack:"",s=Oe(n,"utf8");return t.writeVarIntNum(s.length),t.write(s),t.toArray()}}decodeProtocolID(e){const t=e.readUInt8(),r=e.readVarIntNum(),i=e.read(r);return[t,xe(i)]}decodeString(e){const t=e.readVarIntNum(),r=e.read(t);return xe(r)}decodeCounterparty(e){const t=e.readUInt8();if(11===t)return"self";if(12===t)return"anyone";if(0!==t){const r=e.read(32);return Ne([t,...r])}}serializeDiscoveryResult(e){const t=new Ue;t.writeVarIntNum(e.totalCertificates);for(const r of e.certificates){const e=new $r(r.type,r.serialNumber,r.subject,r.certifier,r.revocationOutpoint,r.fields,r.signaturre).toBinary();t.writeVarIntNum(e.length),t.write(e);const i=Oe(r.certifierInfo.name,"utf8");t.writeVarIntNum(i.length),t.write(i);const n=Oe(r.certifierInfo.iconUrl,"utf8");t.writeVarIntNum(n.length),t.write(n);const s=Oe(r.certifierInfo.description,"utf8");t.writeVarIntNum(s.length),t.write(s),t.writeUInt8(r.certifierInfo.trust);const a=Object.entries(r.publiclyRevealedKeyring);t.writeVarIntNum(a.length);for(const[e,r]of a){const i=Oe(e,"utf8");t.writeVarIntNum(i.length),t.write(i);const n=Oe(r,"base64");t.writeVarIntNum(n.length),t.write(n)}const o=Object.entries(r.decryptedFields);t.writeVarIntNum(o.length);for(const[e,r]of o){const i=Oe(e,"utf8");t.writeVarIntNum(i.length),t.write(i);const n=Oe(r,"utf8");t.writeVarIntNum(n.length),t.write(n)}}return t.toArray()}decodeKeyRelatedParams(e){const t={};t.protocolID=this.decodeProtocolID(e);const r=e.readVarIntNum(),i=e.read(r);t.keyID=xe(i),t.counterparty=this.decodeCounterparty(e);const n=e.readInt8();t.privileged=-1===n?void 0:1===n;const s=e.readInt8();if(-1===s)t.privilegedReason=void 0;else{const r=e.read(s);t.privilegedReason=xe(r)}return t}}class ti extends $r{masterKeyring;constructor(e,t,r,i,n,s,a,o){super(e,t,r,i,n,s,o);for(const e of Object.keys(s))if(void 0===a[e]||""===a[e])throw new Error(`Master keyring must contain a value for every field. Missing or empty key for field: "${e}".`);this.masterKeyring=a}static async createCertificateFields(e,t,r,i,n){const s={},a={};for(const[o,c]of Object.entries(r)){const r=St.fromRandom(),d=r.encrypt(Oe(c,"utf8"));s[o]=Fe(d);const{ciphertext:u}=await e.encrypt({plaintext:r.toArray(),...$r.getCertificateFieldEncryptionDetails(o),counterparty:t,privileged:i,privilegedReason:n});a[o]=Fe(u)}return{certificateFields:s,masterKeyring:a}}static async createKeyringForVerifier(e,t,r,i,n,s,a,o,c){if(!Array.isArray(n))throw new Error("fieldsToReveal must be an array of strings");const d={};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(e,s,u,i[u],t,o,c)).fieldRevelationKey,{ciphertext:h}=await e.encrypt({plaintext:n,...$r.getCertificateFieldEncryptionDetails(u,a),counterparty:r,privileged:o,privilegedReason:c});d[u]=Fe(h)}return d}static async issueCertificateForSubject(e,t,r,i,n=async e=>"Certificate revocation not tracked.",s){const a=s??Fe(Ze(32)),{certificateFields:o,masterKeyring:c}=await this.createCertificateFields(e,t,r),d=await n(a),u=new ti(i,a,t,(await e.getPublicKey({identityKey:!0})).publicKey,d,o,c);return await u.sign(e),u}static async decryptFields(e,t,r,i,n,s){if(null==t||0===Object.keys(t).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(e,t,o,r[o],i,n,s)).decryptedFieldValue;return a}catch{throw new Error("Failed to decrypt all master certificate fields.")}}static async decryptField(e,t,r,i,n,s,a){if(null==t||0===Object.keys(t).length)throw new Error("A MasterCertificate must have a valid masterKeyring!");try{const{plaintext:o}=await e.decrypt({ciphertext:Oe(t[r],"base64"),...$r.getCertificateFieldEncryptionDetails(r),counterparty:n,privileged:s,privilegedReason:a}),c=new St(o).decrypt(Oe(i,"base64"));return{fieldRevelationKey:o,decryptedFieldValue:xe(c)}}catch{throw new Error("Failed to decrypt certificate field!")}}}class ri extends $r{keyring;decryptedFields;constructor(e,t,r,i,n,s,a,o,c){super(e,t,r,i,n,s,o),this.keyring=a,this.decryptedFields=c}static fromCertificate(e,t){return new ri(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,t,e.signature)}async decryptFields(e,t,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 e.decrypt({ciphertext:Oe(this.keyring[n],"base64"),...$r.getCertificateFieldEncryptionDetails(n,this.serialNumber),counterparty:this.subject,privileged:t,privilegedReason:r}),a=new St(s).decrypt(Oe(this.fields[n],"base64"));i[n]=xe(a)}return i}catch(e){throw new Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(e instanceof Error?e.message:e)}`)}}}class ii extends Ur{keyDeriver;constructor(e){if(super(e),e instanceof Br)this.keyDeriver=e;else{if(!("string"==typeof e||e instanceof rt))throw new Error("Invalid key deriver provided");this.keyDeriver=new Br(e)}}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(e){if(!0===e.privileged)throw new Error("no privilege support");if(!0===e.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==e.protocolID||"string"!=typeof e.keyID||""===e.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(e.protocolID,e.keyID,"string"==typeof e.counterparty&&""!==e.counterparty.trim()?e.counterparty:"self",Boolean(e.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 ni{sessionNonceToSession;identityKeyToNonces;constructor(){this.sessionNonceToSession=new Map,this.identityKeyToNonces=new Map}addSession(e){if("string"!=typeof e.sessionNonce)throw new Error("Invalid session: sessionNonce is required to add a session.");if(this.sessionNonceToSession.set(e.sessionNonce,e),"string"==typeof e.peerIdentityKey){let t=this.identityKeyToNonces.get(e.peerIdentityKey);null==t&&(t=new Set,this.identityKeyToNonces.set(e.peerIdentityKey,t)),t.add(e.sessionNonce)}}updateSession(e){this.removeSession(e),this.addSession(e)}getSession(e){const t=this.sessionNonceToSession.get(e);if(null!=t)return t;const r=this.identityKeyToNonces.get(e);if(null==r||0===r.size)return;let i;for(const e of r){const t=this.sessionNonceToSession.get(e);null!=t&&(null==i||(t.lastUpdate??0)>(i.lastUpdate??0))&&(i=t)}return i}removeSession(e){if("string"==typeof e.sessionNonce&&this.sessionNonceToSession.delete(e.sessionNonce),"string"==typeof e.peerIdentityKey){const t=this.identityKeyToNonces.get(e.peerIdentityKey);null!=t&&(t.delete(e.sessionNonce??""),0===t.size&&this.identityKeyToNonces.delete(e.peerIdentityKey))}}hasSession(e){if(this.sessionNonceToSession.has(e))return!0;const t=this.identityKeyToNonces.get(e);return!(null==t)&&t.size>0}}async function si(e,t,r="self"){const i=Oe(e,"base64"),n=i.slice(0,16),s=i.slice(16),{valid:a}=await t.verifyHmac({data:n,hmac:s,protocolID:[2,"server hmac"],keyID:xe(n),counterparty:r});return a}async function ai(e,t="self"){const r=Ze(16),{hmac:i}=await e.createHmac({protocolID:[2,"server hmac"],keyID:xe(r),data:r,counterparty:t});return Fe([...r,...i])}const oi=async(e,t,r)=>{const i=await e.listCertificates({certifiers:t.certifiers,types:Object.keys(t.types)});return await Promise.all(i.certificates.map((async i=>{const{keyringForVerifier:n}=await e.proveCertificate({certificate:i,fieldsToReveal:t.types[i.type],verifier:r});return new ri(i.type,i.serialNumber,i.subject,i.certifier,i.revocationOutpoint,i.fields,n,i.signature)})))},ci=async(e,t,r)=>{if(null==t.certificates||0===t.certificates.length)throw new Error("No certificates were provided in the AuthMessage.");await Promise.all(t.certificates.map((async i=>{if(i.subject!==t.identityKey)throw new Error(`The subject of one of your certificates ("${i.subject}") is not the same as the request sender ("${t.identityKey}").`);const n=new ri(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:e,types:t}=r;if(!e.includes(n.certifier))throw new Error(`Certificate with serial number ${n.serialNumber} has an unrequested certifier: ${n.certifier}`);if(null==t[n.type])throw new Error(`Certificate with type ${n.type} was not requested`)}await n.decryptFields(e)})))},di="0.1";class ui{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;constructor(e,t,r,i,n){this.wallet=e,this.transport=t,this.certificatesToRequest=r??{certifiers:[],types:{}},this.transport.onData(this.handleIncomingMessage.bind(this)).catch((e=>{throw e})),this.sessionManager=null!=i?i:new ni,this.autoPersistLastSession=!1!==n}async toPeer(e,t,r){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);const i=await this.getAuthenticatedSession(t,r),n=Fe(Ze(32)),{signature:s}=await this.wallet.createSignature({data:e,protocolID:[2,"auth message signature"],keyID:`${n} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey}),a={version:di,messageType:"general",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,nonce:n,yourNonce:i.peerNonce,payload:e,signature:s};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(a)}catch(e){const t=new Error(`Failed to send message to peer ${i.peerIdentityKey??"unknown"}: ${String(e.message)}`);throw t.stack=e.stack,t}}async requestCertificates(e,t,r=1e4){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);const i=await this.getAuthenticatedSession(t,r),n=Fe(Ze(32)),{signature:s}=await this.wallet.createSignature({data:Oe(JSON.stringify(e),"utf8"),protocolID:[2,"auth message signature"],keyID:`${n} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey}),a={version:di,messageType:"certificateRequest",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,nonce:n,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,requestedCertificates:e,signature:s};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(a)}catch(e){throw new Error(`Failed to send certificate request message to peer ${i.peerIdentityKey??"unknown"}: ${String(e.message)}`)}}async getAuthenticatedSession(e,t){if(void 0===this.transport)throw new Error("Peer transport is not connected!");let r;if("string"==typeof e&&(r=this.sessionManager.getSession(e)),null==r||!r.isAuthenticated){const i=await this.initiateHandshake(e,t);if(r=this.sessionManager.getSession(i),null==r||!r.isAuthenticated)throw new Error("Unable to establish mutual authentication with peer!")}return r}listenForGeneralMessages(e){const t=this.callbackIdCounter++;return this.onGeneralMessageReceivedCallbacks.set(t,e),t}stopListeningForGeneralMessages(e){this.onGeneralMessageReceivedCallbacks.delete(e)}listenForCertificatesReceived(e){const t=this.callbackIdCounter++;return this.onCertificatesReceivedCallbacks.set(t,e),t}stopListeningForCertificatesReceived(e){this.onCertificatesReceivedCallbacks.delete(e)}listenForCertificatesRequested(e){const t=this.callbackIdCounter++;return this.onCertificateRequestReceivedCallbacks.set(t,e),t}stopListeningForCertificatesRequested(e){this.onCertificateRequestReceivedCallbacks.delete(e)}async initiateHandshake(e,t=1e4){const r=await ai(this.wallet),i=Date.now();this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:r,peerIdentityKey:e,lastUpdate:i});const n={version:di,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,t)}async waitForInitialResponse(e,t=1e4){return await new Promise(((r,i)=>{const n=this.listenForInitialResponse(e,(e=>{clearTimeout(s),this.stopListeningForInitialResponses(n),r(e)})),s=setTimeout((()=>{this.stopListeningForInitialResponses(n),i(new Error("Initial response timed out."))}),t)}))}listenForInitialResponse(e,t){const r=this.callbackIdCounter++;return this.onInitialResponseReceivedCallbacks.set(r,{callback:t,sessionNonce:e}),r}stopListeningForInitialResponses(e){this.onInitialResponseReceivedCallbacks.delete(e)}async handleIncomingMessage(e){if("string"!=typeof e.version||e.version!==di)throw new Error(`Invalid or unsupported message auth version! Received: ${e.version}, expected: ${di}`);switch(e.messageType){case"initialRequest":await this.processInitialRequest(e);break;case"initialResponse":await this.processInitialResponse(e);break;case"certificateRequest":await this.processCertificateRequest(e);break;case"certificateResponse":await this.processCertificateResponse(e);break;case"general":await this.processGeneralMessage(e);break;default:throw new Error(`Unknown message type of ${String(e.messageType)} from ${String(e.identityKey)}`)}}async processInitialRequest(e){if("string"!=typeof e.identityKey||"string"!=typeof e.initialNonce||""===e.initialNonce)throw new Error("Missing required fields in initialRequest message.");const t=await ai(this.wallet),r=Date.now();let i;this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:t,peerNonce:e.initialNonce,peerIdentityKey:e.identityKey,lastUpdate:r}),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach((t=>{t(e.identityKey,e.requestedCertificates)})):i=await oi(this.wallet,e.requestedCertificates,e.identityKey));const{signature:n}=await this.wallet.createSignature({data:Oe(e.initialNonce+t,"base64"),protocolID:[2,"auth message signature"],keyID:`${e.initialNonce} ${t}`,counterparty:e.identityKey}),s={version:di,messageType:"initialResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,initialNonce:t,yourNonce:e.initialNonce,certificates:i,requestedCertificates:this.certificatesToRequest,signature:n};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=e.identityKey),await this.transport.send(s)}async processInitialResponse(e){if(!await si(e.yourNonce,this.wallet))throw new Error(`Initial response nonce verification failed from peer: ${e.identityKey}`);const t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw new Error(`Peer session not found for peer: ${e.identityKey}`);const r=Oe((t.sessionNonce??"")+(e.initialNonce??""),"base64"),{valid:i}=await this.wallet.verifySignature({data:r,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${t.sessionNonce??""} ${e.initialNonce??""}`,counterparty:e.identityKey});if(!i)throw new Error(`Unable to verify initial response signature for peer: ${e.identityKey}`);if(t.peerNonce=e.initialNonce,t.peerIdentityKey=e.identityKey,t.isAuthenticated=!0,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.certificatesToRequest?.certifiers?.length>0&&e.certificates?.length>0&&(await ci(this.wallet,e,this.certificatesToRequest),this.onCertificatesReceivedCallbacks.forEach((t=>t(e.identityKey,e.certificates)))),this.lastInteractedWithPeer=e.identityKey,this.onInitialResponseReceivedCallbacks.forEach((e=>{e.sessionNonce===t.sessionNonce&&e.callback(t.sessionNonce)})),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach((t=>{t(e.identityKey,e.requestedCertificates)}));else{const t=await oi(this.wallet,e.requestedCertificates,e.identityKey);await this.sendCertificateResponse(e.identityKey,t)}}async processCertificateRequest(e){if(!await si(e.yourNonce,this.wallet))throw new Error(`Unable to verify nonce for certificate request message from: ${e.identityKey}`);const t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw new Error(`Session not found for nonce: ${e.yourNonce}`);const{valid:r}=await this.wallet.verifySignature({data:Oe(JSON.stringify(e.requestedCertificates),"utf8"),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey});if(!r)throw new Error(`Invalid signature in certificate request message from ${t.peerIdentityKey}`);if(t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach((t=>{t(e.identityKey,e.requestedCertificates)}));else{const t=await oi(this.wallet,e.requestedCertificates,e.identityKey);await this.sendCertificateResponse(e.identityKey,t)}}async sendCertificateResponse(e,t){const r=await this.getAuthenticatedSession(e),i=Fe(Ze(32)),{signature:n}=await this.wallet.createSignature({data:Oe(JSON.stringify(t),"utf8"),protocolID:[2,"auth message signature"],keyID:`${i} ${r.peerNonce??""}`,counterparty:r.peerIdentityKey}),s={version:di,messageType:"certificateResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0})).publicKey,nonce:i,initialNonce:r.sessionNonce,yourNonce:r.peerNonce,certificates:t,signature:n};r.lastUpdate=Date.now(),this.sessionManager.updateSession(r);try{await this.transport.send(s)}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`Failed to send certificate response message to peer ${r.peerIdentityKey??"unknown"}: ${t}`)}}async processCertificateResponse(e){if(!await si(e.yourNonce,this.wallet))throw new Error(`Unable to verify nonce for certificate response from: ${e.identityKey}`);const t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw new Error(`Session not found for nonce: ${e.yourNonce}`);const{valid:r}=await this.wallet.verifySignature({data:Oe(JSON.stringify(e.certificates),"utf8"),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:e.identityKey});if(!r)throw new Error(`Unable to verify certificate response signature for peer: ${e.identityKey}`);await ci(this.wallet,e,e.requestedCertificates),this.onCertificatesReceivedCallbacks.forEach((t=>{t(e.identityKey,e.certificates??[])})),t.lastUpdate=Date.now(),this.sessionManager.updateSession(t)}async processGeneralMessage(e){if(!await si(e.yourNonce,this.wallet))throw new Error(`Unable to verify nonce for general message from: ${e.identityKey}`);const t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw new Error(`Session not found for nonce: ${e.yourNonce}`);const{valid:r}=await this.wallet.verifySignature({data:e.payload,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey});if(!r)throw new Error(`Invalid signature in generalMessage from ${t.peerIdentityKey}`);t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.lastInteractedWithPeer=e.identityKey,this.onGeneralMessageReceivedCallbacks.forEach((t=>{t(e.identityKey,e.payload??[])}))}}const hi="undefined"!=typeof window?fetch.bind(window):fetch;class li{onDataCallback;fetchClient;baseUrl;constructor(e,t=hi){this.fetchClient=t,this.baseUrl=e}async send(e){if(!this.onDataCallback)throw new Error("Listen before you start speaking. God gave you two ears and one mouth for a reason.");if("general"!==e.messageType)return new Promise((async(t,r)=>{try{const r=this.fetchClient(`${this.baseUrl}/.well-known/auth`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});"initialRequest"!==e.messageType&&t();const i=await r;if(!i.ok||!this.onDataCallback)throw new Error("HTTP server failed to authenticate");{const e=await i.json();this.onDataCallback(e)}"initialRequest"===e.messageType&&t()}catch(e){return void r(e)}}));{const t=this.deserializeRequestPayload(e.payload),r=`${this.baseUrl}${t.urlPostfix}`;let i=t;if("object"!=typeof t.headers&&(i.headers={}),i.headers["x-bsv-auth-version"]=e.version,i.headers["x-bsv-auth-identity-key"]=e.identityKey,i.headers["x-bsv-auth-nonce"]=e.nonce,i.headers["x-bsv-auth-your-nonce"]=e.yourNonce,i.headers["x-bsv-auth-signature"]=Ne(e.signature),i.headers["x-bsv-auth-request-id"]=t.requestId,i.body){const e=i.headers;if(!e["content-type"])throw new Error("Content-Type header is required for requests with a body.");const t=e["content-type"];t.includes("application/json")||t.includes("application/x-www-form-urlencoded")||t.includes("text/plain")?i.body=xe(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&&null==n.headers.get("x-bsv-auth-request-id")&&null==n.headers.get("x-bsv-auth-requested-certificates")){const e=await n.json();throw new Error(`HTTP ${n.status} - ${JSON.stringify(e)}`)}const s=await n.arrayBuffer(),a=new Ue;null!=n.headers.get("x-bsv-auth-request-id")&&a.write(Oe(n.headers.get("x-bsv-auth-request-id"),"base64")),a.writeVarIntNum(n.status);const o=[];n.headers.forEach(((e,t)=>{const r=t.toLowerCase();!r.startsWith("x-bsv-")&&"authorization"!==r||r.startsWith("x-bsv-auth")||o.push([r,e])})),o.sort((([e],[t])=>e.localeCompare(t))),a.writeVarIntNum(o.length);for(let e=0;e<o.length;e++){const t=Oe(o[e][0],"utf8");a.writeVarIntNum(t.length),a.write(t);const r=Oe(o[e][1],"utf8");a.writeVarIntNum(r.length),a.write(r)}if(s){const e=Array.from(new Uint8Array(s));a.writeVarIntNum(e.length),a.write(e)}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:Oe(n.headers.get("x-bsv-auth-signature"),"hex")};if(!c.version)throw new Error("HTTP server failed to authenticate");this.onDataCallback(c)}}async onData(e){this.onDataCallback=t=>{e(t)}}deserializeRequestPayload(e){const t=new Ke(e),r=Fe(t.read(32)),i=t.readVarIntNum();let n="GET";i>0&&(n=xe(t.read(i)));const s=t.readVarIntNum();let a="";s>0&&(a=xe(t.read(s)));const o=t.readVarIntNum();let c="";o>0&&(c=xe(t.read(o)));const d={},u=t.readVarIntNum();if(u>0)for(let e=0;e<u;e++){const e=t.readVarIntNum(),r=t.read(e),i=xe(r),n=t.readVarIntNum(),s=t.read(n),a=xe(s);d[i]=a}let h;const l=t.readVarIntNum();return l>0&&(h=t.read(l)),{urlPostfix:a+c,method:n,headers:d,body:h,requestId:r}}}class fi{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;peers={};constructor(e,t,r){this.wallet=e,this.requestedCertificates=t,this.sessionManager=r||new ni}async fetch(e,t={}){if("number"==typeof t.retryCounter){if(t.retryCounter<=0)throw new Error("Request failed after maximum number of retries.");t.retryCounter--}const r=await new Promise((async(r,i)=>{try{const{method:n="GET",headers:s={},body:a}=t,o=new URL(e),c=o.origin;let d;if(void 0===this.peers[c]){const e=new li(c);d={peer:new ui(this.wallet,e,this.requestedCertificates,this.sessionManager),pendingCertificateRequests:[]},this.peers[c]=d,this.peers[c].peer.listenForCertificatesReceived(((e,t)=>{this.certificatesReceived.push(...t)})),this.peers[c].peer.listenForCertificatesRequested((async(e,t)=>{try{this.peers[c].pendingCertificateRequests.push(!0);const r=await oi(this.wallet,t,e);await this.peers[c].peer.sendCertificateResponse(e,r)}finally{await new Promise((e=>setTimeout(e,500))),this.peers[c].pendingCertificateRequests.shift()}}))}else{if(!1===this.peers[c].supportsMutualAuth){try{const i=await this.handleFetchAndValidate(e,t,this.peers[c]);r(i)}catch(e){i(e)}return}d=this.peers[c]}const u=Ze(32),h=Fe(u),l=await this.serializeRequest(n,s,a,o,u);this.callbacks[h]={resolve:r,reject:i};const f=d.peer.listenForGeneralMessages(((e,t)=>{const r=new Ke(t);if(Fe(r.read(32))!==h)return;d.peer.stopListeningForGeneralMessages(f),this.peers[c].identityKey=e,this.peers[c].supportsMutualAuth=!0;const i=r.readVarIntNum(),n={},s=r.readVarIntNum();if(s>0)for(let e=0;e<s;e++){const e=r.readVarIntNum(),t=r.read(e),i=xe(t),s=r.readVarIntNum(),a=r.read(s),o=xe(a);n[i]=o}let a;n["x-bsv-auth-identity-key"]=e;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[h].resolve(u),delete this.callbacks[h]}));d.pendingCertificateRequests.length>0&&await new Promise((e=>{setInterval((()=>{0===d.pendingCertificateRequests.length&&e()}),100)})),await d.peer.toPeer(l.toArray(),d.identityKey).catch((async n=>{if(n.message.includes("Session not found for nonce")){delete this.peers[c],t.retryCounter??=3;const i=await this.fetch(e,t);r(i)}else if(n.message.includes("HTTP server failed to authenticate"))try{const i=await this.handleFetchAndValidate(e,t,d);return void r(i)}catch(e){i(e)}else i(n)}))}catch(e){i(e)}}));return 402===r.status?await this.handlePaymentAndRetry(e,t,r):r}async sendCertificateRequest(e,t){const r=new URL(e).origin;let i;if(void 0!==this.peers[r])i={peer:this.peers[r].peer};else{const e=new li(r);i={peer:new ui(this.wallet,e,this.requestedCertificates,this.sessionManager)},this.peers[r]=i}return await new Promise((async(e,r)=>{const n=i.peer.listenForCertificatesReceived(((t,r)=>{i.peer.stopListeningForCertificatesReceived(n),this.certificatesReceived.push(...r),e(r)}));try{await i.peer.requestCertificates(t,i.identityKey)}catch(e){i.peer.stopListeningForCertificatesReceived(n),r(e)}}))}consumeReceivedCertificates(){return this.certificatesReceived.splice(0)}async serializeRequest(e,t,r,i,n){const s=new Ue;if(s.write(n),s.writeVarIntNum(e.length),s.write(Oe(e)),i.pathname.length>0){const e=Oe(i.pathname);s.writeVarIntNum(e.length),s.write(e)}else s.writeVarIntNum(-1);if(i.search.length>0){const e=Oe(i.search);s.writeVarIntNum(e.length),s.write(e)}else s.writeVarIntNum(-1);const a=[];for(let[e,r]of Object.entries(t))if(e=e.toLowerCase(),e.startsWith("x-bsv-")||"authorization"===e){if(e.startsWith("x-bsv-auth"))throw new Error("No BSV auth headers allowed here!");a.push([e,r])}else{if(!e.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([e,r])}a.sort((([e],[t])=>e.localeCompare(t))),s.writeVarIntNum(a.length);for(let e=0;e<a.length;e++){const t=Oe(a[e][0],"utf8");s.writeVarIntNum(t.length),s.write(t);const r=Oe(a[e][1],"utf8");s.writeVarIntNum(r.length),s.write(r)}if(["POST","PUT","PATCH","DELETE"].includes(e.toUpperCase())&&void 0===r){const e=a.find((([e])=>"content-type"===e));r=e&&e[1].includes("application/json")?"{}":""}if(r){const e=await this.normalizeBodyToNumberArray(r);s.writeVarIntNum(e.length),s.write(e)}else s.writeVarIntNum(-1);return s}async handleFetchAndValidate(e,t,r){const i=await fetch(e,t);if(i.headers.forEach((e=>{if(e.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(e,t={},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 ai(this.wallet),{publicKey:d}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${o} ${c}`,counterparty:a}),u=(new Ut).lock(Ge.fromString(d).toAddress()).toHex(),{tx:h}=await this.wallet.createAction({description:`Payment for request to ${new URL(e).origin}`,outputs:[{satoshis:s,lockingScript:u,customInstructions:JSON.stringify({derivationPrefix:o,derivationSuffix:c,payee:a}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}});return t.headers=t.headers||{},t.headers["x-bsv-payment"]=JSON.stringify({derivationPrefix:o,derivationSuffix:c,transaction:Fe(h)}),t.retryCounter??=3,this.fetch(e,t)}async normalizeBodyToNumberArray(e){if(null==e)return[];if("object"==typeof e)return Oe(JSON.stringify(e,"utf8"));if(Array.isArray(e)&&e.every((e=>"number"==typeof e)))return e;if("string"==typeof e)return Oe(e,"utf8");if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){const t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer);return Array.from(t)}if(e instanceof Blob){const t=await e.arrayBuffer();return Array.from(new Uint8Array(t))}if(e instanceof FormData){const t=[];e.forEach(((e,r)=>{t.push([r,e.toString()])}));const r=new URLSearchParams(t).toString();return Oe(r,"utf8")}if(e instanceof URLSearchParams)return Oe(e.toString(),"utf8");if(e instanceof ReadableStream)throw new Error("ReadableStream cannot be directly converted to number[].");throw new Error("Unsupported body type in this SimplifiedFetch implementation.")}}class pi{pushDrop;static decode(e){const t=Ht.decode(e);if(t.fields.length<4)throw new Error("Invalid SHIP/SLAP advertisement!");const r=xe(t.fields[0]);if("SHIP"!==r&&"SLAP"!==r)throw new Error("Invalid protocol type!");return{protocol:r,identityKey:Ne(t.fields[1]),domain:xe(t.fields[2]),topicOrService:xe(t.fields[3])}}constructor(e){this.pushDrop=new Ht(e)}async lock(e,t,r){const{publicKey:i}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([Oe(e,"utf8"),Oe(i,"hex"),Oe(t,"utf8"),Oe(r,"utf8")],[2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}unlock(e){return this.pushDrop.unlock([2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}}const bi=["https://users.bapp.dev"],wi=["https://testnet-users.bapp.dev"];class gi{fetchClient;allowHTTP;constructor(e=fetch,t=!1){this.fetchClient=e,this.allowHTTP=t}async lookup(e,t,r=5e3){if(!e.startsWith("https:")&&!this.allowHTTP)throw new Error('HTTPS facilitator can only use URLs that start with "https:"');const i=new Promise(((e,t)=>setTimeout((()=>t(new Error("Request timed out"))),r))),n=fetch(`${e}/lookup`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:t.service,query:t.query})}),s=await Promise.race([n,i]);if(s.ok)return await s.json();throw new Error("Failed to facilitate lookup")}}class mi{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;constructor(e={}){this.networkPreset=e.networkPreset??"mainnet",this.facilitator=e.facilitator??new gi(void 0,"local"===this.networkPreset),this.slapTrackers=e.slapTrackers??("mainnet"===this.networkPreset?bi:wi),this.hostOverrides=e.hostOverrides??{},this.additionalHosts=e.additionalHosts??{}}async query(e,t){let r=[];if(r="ls_slap"===e.service?"local"===this.networkPreset?["http://localhost:8080"]:this.slapTrackers:null!=this.hostOverrides[e.service]?this.hostOverrides[e.service]:"local"===this.networkPreset?["http://localhost:8080"]:await this.findCompetentHosts(e.service),this.additionalHosts[e.service]?.length>0&&(r=[...r,...this.additionalHosts[e.service]]),r.length<1)throw new Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${e.service}`);const i=(await Promise.allSettled(r.map((async r=>await this.facilitator.lookup(r,e,t))))).filter((e=>"fulfilled"===e.status)).map((e=>e.value));if(0===i.length)throw new Error("No successful responses from any hosts");const n=new Map;for(const e of i)if("output-list"===e.type)try{for(const t of e.outputs)try{const e=`${sr.fromBEEF(t.beef).id("hex")}.${t.outputIndex}`;n.set(e,t)}catch{continue}}catch(e){}return{type:"output-list",outputs:Array.from(n.values())}}async findCompetentHosts(e){const t={service:"ls_slap",query:{service:e}},r=await Promise.allSettled(this.slapTrackers.map((async e=>await this.facilitator.lookup(e,t,5e3)))),i=new Set;for(const t of r)if("fulfilled"===t.status){const r=t.value;if("output-list"!==r.type)continue;for(const t of r.outputs)try{const r=sr.fromBEEF(t.beef).outputs[t.outputIndex].lockingScript,n=pi.decode(r);if(n.topicOrService!==e||"SLAP"!==n.protocol)continue;i.add(n.domain)}catch{continue}}return[...i]}}class yi{httpClient;allowHTTP;constructor(e=fetch,t=!1){this.httpClient=e,this.allowHTTP=t}async send(e,t){if(!e.startsWith("https:")&&!this.allowHTTP)throw new Error('HTTPS facilitator can only use URLs that start with "https:"');const r={"Content-Type":"application/octet-stream","X-Topics":JSON.stringify(t.topics)};let i;if(Array.isArray(t.offChainValues)){r["x-includes-off-chain-values"]="true";const e=new Ue;e.writeVarIntNum(t.beef.length),e.write(t.beef),e.write(t.offChainValues),i=new Uint8Array(e.toArray())}else i=new Uint8Array(t.beef);const n=await fetch(`${e}/submit`,{method:"POST",headers:r,body:i});if(n.ok)return await n.json();throw new Error("Failed to facilitate broadcast")}}class Ii{topics;facilitator;resolver;requireAcknowledgmentFromAllHostsForTopics;requireAcknowledgmentFromAnyHostForTopics;requireAcknowledgmentFromSpecificHostsForTopics;networkPreset;constructor(e,t={}){if(0===e.length)throw new Error("At least one topic is required for broadcast.");if(e.some((e=>!e.startsWith("tm_"))))throw new Error('Every topic must start with "tm_".');this.topics=e,this.networkPreset=t.networkPreset??"mainnet",this.facilitator=t.facilitator??new yi(void 0,"local"===this.networkPreset),this.resolver=t.resolver??new mi({networkPreset:this.networkPreset}),this.requireAcknowledgmentFromAllHostsForTopics=t.requireAcknowledgmentFromAllHostsForTopics??[],this.requireAcknowledgmentFromAnyHostForTopics=t.requireAcknowledgmentFromAnyHostForTopics??"all",this.requireAcknowledgmentFromSpecificHostsForTopics=t.requireAcknowledgmentFromSpecificHostsForTopics??{}}async broadcast(e){let t;const r=e.metadata.get("OffChainValues");try{t=e.toBEEF()}catch(e){throw new Error("Transactions sent via SHIP to Overlay Services must be serializable to BEEF format.")}const i=await this.findInterestedHosts();if(0===Object.keys(i).length)return{status:"error",code:"ERR_NO_HOSTS_INTERESTED",description:`No ${this.networkPreset} hosts are interested in receiving this transaction.`};const n=Object.entries(i).map((async([e,i])=>{try{const n=await this.facilitator.send(e,{beef:t,offChainValues:r,topics:[...i]});if(null==n||0===Object.keys(n).length)throw new Error("Steak has no topics.");return{host:e,success:!0,steak:n}}catch(t){return console.error(t),{host:e,success:!1,error:t}}})),s=(await Promise.all(n)).filter((e=>e.success));if(0===s.length)return{status:"error",code:"ERR_ALL_HOSTS_REJECTED",description:`All ${this.networkPreset} topical hosts have rejected the transaction.`};const a={};for(const e of s){const t=e.host,r=e.steak,i=new Set;for(const[e,t]of Object.entries(r)){const r=t.outputsToAdmit,n=t.coinsToRetain,s=t.coinsRemoved;(r?.length>0||n?.length>0||s?.length>0)&&i.add(e)}a[t]=i}let o,c,d,u;return"all"===this.requireAcknowledgmentFromAllHostsForTopics?(o=this.topics,c="all"):"any"===this.requireAcknowledgmentFromAllHostsForTopics?(o=this.topics,c="any"):Array.isArray(this.requireAcknowledgmentFromAllHostsForTopics)?(o=this.requireAcknowledgmentFromAllHostsForTopics,c="all"):(o=this.topics,c="all"),o.length>0&&!this.checkAcknowledgmentFromAllHosts(a,o,c)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ALL_HOSTS_FAILED",description:"Not all hosts acknowledged the required topics."}:("all"===this.requireAcknowledgmentFromAnyHostForTopics?(d=this.topics,u="all"):"any"===this.requireAcknowledgmentFromAnyHostForTopics?(d=this.topics,u="any"):Array.isArray(this.requireAcknowledgmentFromAnyHostForTopics)?(d=this.requireAcknowledgmentFromAnyHostForTopics,u="all"):(d=[],u="all"),d.length>0&&!this.checkAcknowledgmentFromAnyHost(a,d,u)?{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(a,this.requireAcknowledgmentFromSpecificHostsForTopics)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_SPECIFIC_HOSTS_FAILED",description:"Specific hosts did not acknowledge the required topics."}:{status:"success",txid:e.id("hex"),message:`Sent to ${s.length} Overlay Services ${1===s.length?"host":"hosts"}.`})}checkAcknowledgmentFromAllHosts(e,t,r){for(const i of Object.values(e))if("all"===r){for(const e of t)if(!i.has(e))return!1}else if("any"===r){let e=!1;for(const r of t)if(i.has(r)){e=!0;break}if(!e)return!1}return!0}checkAcknowledgmentFromAnyHost(e,t,r){if("all"===r){for(const r of Object.values(e)){let e=!0;for(const i of t)if(!r.has(i)){e=!1;break}if(e)return!0}return!1}for(const r of Object.values(e))for(const e of t)if(r.has(e))return!0;return!1}checkAcknowledgmentFromSpecificHosts(e,t){for(const[r,i]of Object.entries(t)){const t=e[r];if(null==t)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 e of n)if(!t.has(e))return!1}else if("any"===s){let e=!1;for(const r of n)if(t.has(r)){e=!0;break}if(!e)return!1}}return!0}async findInterestedHosts(){if("local"===this.networkPreset){const e=new Set;for(let t=0;t<this.topics.length;t++)e.add(this.topics[t]);return{"http://localhost:8080":e}}const e={},t=await this.resolver.query({service:"ls_ship",query:{topics:this.topics}},5e3);if("output-list"!==t.type)throw new Error("SHIP answer is not an output list.");for(const r of t.outputs)try{const t=sr.fromBEEF(r.beef).outputs[r.outputIndex].lockingScript,i=pi.decode(t);if(!this.topics.includes(i.topicOrService)||"SHIP"!==i.protocol)continue;void 0===e[i.domain]&&(e[i.domain]=new Set),e[i.domain].add(i.topicOrService)}catch(e){continue}return e}}const vi=e=>(e.toLowerCase().startsWith("uhrp:")&&(e=e.slice(5)),e.startsWith("//")&&(e=e.slice(2)),e),ki=e=>{if(32!==e.length)throw new Error("Hash length must be 32 bytes (sha256)");return Be(e,Oe("ce00","hex"))},Si=e=>{const t=me(e);return ki(t)},Ei=e=>{e=vi(e);const{data:t,prefix:r}=De(e,void 0,2);if(32!==t.length)throw new Error("Invalid length!");if("ce00"!==Ne(r))throw new Error("Bad prefix");return t},Pi=e=>{try{return Ei(e),!0}catch(e){return!1}};class Ni{authFetch;baseURL;constructor(e){this.baseURL=e.storageURL,this.authFetch=new fi(e.wallet)}async getUploadInfo(e,t){const r=`${this.baseURL}/upload`,i={fileSize:e,retentionPeriod:t},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(e,t,r){const i=Uint8Array.from(t.data),n=await fetch(e,{method:"PUT",body:i,headers:{"Content-Type":t.type,...r}});if(!n.ok)throw new Error(`File upload failed: HTTP ${n.status}`);return{published:!0,uhrpURL:await Si(t.data)}}async publishFile(e){const{file:t,retentionPeriod:r}=e,i=t.data.length,{uploadURL:n,requiredHeaders:s}=await this.getUploadInfo(i,r);return await this.uploadFile(n,t,s)}async findFile(e){const t=new URL(`${this.baseURL}/find`);t.searchParams.set("uhrpUrl",e);const r=await this.authFetch.fetch(t.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 e=i.code??"unknown-code",t=i.description??"no-description";throw new Error(`findFile returned an error: ${e} - ${t}`)}return i.data}async listUploads(){const e=`${this.baseURL}/list`,t=await this.authFetch.fetch(e,{method:"GET"});if(!t.ok)throw new Error(`listUploads request failed: HTTP ${t.status}`);const r=await t.json();if("error"===r.status){const e=r.code??"unknown-code",t=r.description??"no-description";throw new Error(`listUploads returned an error: ${e} - ${t}`)}return r.uploads}async renewFile(e,t){const r=`${this.baseURL}/renew`,i={uhrpUrl:e,additionalMinutes:t},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 e=s.code??"unknown-code",t=s.description??"no-description";throw new Error(`renewFile returned an error: ${e} - ${t}`)}return{status:s.status,prevExpiryTime:s.prevExpiryTime,newExpiryTime:s.newExpiryTime,amount:s.amount}}}class Oi{networkPreset="mainnet";constructor(e){this.networkPreset=e?.networkPreset}async resolve(e){const t=new mi({networkPreset:this.networkPreset}),r=await t.query({service:"ls_uhrp",query:{uhrpUrl:e}});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 e=0;e<r.outputs.length;e++){const t=sr.fromBEEF(r.outputs[e].beef),{fields:s}=Ht.decode(t.outputs[r.outputs[e].outputIndex].lockingScript);new Ke(s[3]).readVarIntNum()<n||i.push(xe(s[2]))}return i}async download(e){if(!Pi(e))throw new Error("Invalid parameter UHRP url");const t=Ei(e),r=await this.resolve(e);if(!Array.isArray(r)||0===r.length)throw new Error("No one currently hosts this file!");for(let e=0;e<r.length;e++)try{const i=await fetch(r[e],{method:"GET"});if(!i.ok||i.status>=400)continue;const n=await i.arrayBuffer(),s=[...new Uint8Array(n)],a=me(s);for(let e=0;e<a.length;++e)if(a[e]!==t[e])throw new Error("Value of content does not match hash of the url given");return{data:s,mimeType:i.headers.get("Content-Type")}}catch(e){continue}throw new Error(`Unable to download content from ${e}`)}}const _i={name:"Unknown Identity",avatarURL:"XUUB8bbn9fEthk15Ge3zTQXypUShfC94vFjp65v7u5CQ8qkpxzst",identityKey:"",abbreviatedKey:"",badgeIconURL:"XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",badgeLabel:"Not verified by anyone you trust.",badgeClickURL:"https://projectbabbage.com/docs/unknown-identity"},Ai={protocolID:[1,"identity"],keyID:"1",tokenAmount:1,outputIndex:0},xi={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 Ti{options;originator;authClient;wallet;constructor(e,t=Ai,r){this.options=t,this.originator=r,this.wallet=e??new Qr,this.authClient=new fi(this.wallet)}async publiclyRevealAttributes(e,t){if(0===Object.keys(e.fields).length)throw new Error("Public reveal failed: Certificate has no fields to reveal!");if(0===t.length)throw new Error("Public reveal failed: You must reveal at least one field!");try{const t=new $r(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature);await t.verify()}catch(e){throw new Error("Public reveal failed: Certificate verification failed!")}const{keyringForVerifier:r}=await this.wallet.proveCertificate({certificate:e,fieldsToReveal:t,verifier:new rt(1).toPublicKey().toString()}),i=await new Ht(this.wallet).lock([Oe(JSON.stringify({...e,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 e=new Ii(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network});return await e.broadcast(sr.fromAtomicBEEF(n))}throw new Error("Public reveal failed: failed to create action!")}async resolveByIdentityKey(e){const{certificates:t}=await this.wallet.discoverByIdentityKey(e,this.originator);return t.map((e=>Ti.parseIdentity(e)))}async resolveByAttributes(e){const{certificates:t}=await this.wallet.discoverByAttributes(e,this.originator);return t.map((e=>Ti.parseIdentity(e)))}static parseIdentity(e){const{type:t,decryptedFields:r,certifierInfo:i}=e;let n,s,a,o,c;switch(t){case xi.xCert:n=r.userName,s=r.profilePhoto,a=`X account certified by ${i.name}`,o=i.iconUrl,c="https://socialcert.net";break;case xi.discordCert:n=r.userName,s=r.profilePhoto,a=`Discord account certified by ${i.name}`,o=i.iconUrl,c="https://socialcert.net";break;case xi.emailCert:n=r.email,s="XUTZxep7BBghAJbSBwTjNfmcsDdRFs5EaGEgkESGSgjJVYgMEizu",a=`Email certified by ${i.name}`,o=i.iconUrl,c="https://socialcert.net";break;case xi.phoneCert:n=r.phoneNumber,s="XUTLxtX3ELNUwRhLwL7kWNGbdnFM8WG2eSLv84J7654oH8HaJWrU",a=`Phone certified by ${i.name}`,o=i.iconUrl,c="https://socialcert.net";break;case xi.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 xi.registrant:n=r.name,s=r.icon,a=`Entity certified by ${i.name}`,o=i.iconUrl,c="https://projectbabbage.com/docs/registrant";break;case xi.coolCert:n="true"===r.cool?"Cool Person!":"Not cool!";break;case xi.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 xi.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=_i.name,s=r.profilePhoto,a=_i.badgeLabel,o=_i.badgeIconURL,c=_i.badgeClickURL}return{name:n,avatarURL:s,abbreviatedKey:e.subject.length>0?`${e.subject.substring(0,10)}...`:"",identityKey:e.subject,badgeIconURL:o,badgeLabel:a,badgeClickURL:c}}}class Fi{wallet;network;constructor(e=new Qr){this.wallet=e}async registerDefinition(e){const t=(await this.wallet.getPublicKey({identityKey:!0})).publicKey,r=new Ht(this.wallet),i=this.buildPushDropFields(e,t),n=this.mapDefinitionTypeToWalletProtocol(e.definitionType),s=await r.lock(i,n,"1","anyone",!0),{tx:a}=await this.wallet.createAction({description:`Register a new ${e.definitionType} item`,outputs:[{satoshis:1,lockingScript:s.toHex(),outputDescription:`New ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{randomizeOutputs:!1}});if(void 0===a)throw new Error(`Failed to create ${e.definitionType} registration transaction!`);const o=new Ii([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:this.network??=(await this.wallet.getNetwork({})).network});return await o.broadcast(sr.fromAtomicBEEF(a))}async resolve(e,t){const r=new mi,i=this.mapDefinitionTypeToServiceName(e),n=await r.query({service:i,query:t});if("output-list"!==n.type)return[];const s=[];for(const t of n.outputs)try{const r=sr.fromBEEF(t.beef).outputs[t.outputIndex].lockingScript,i=await this.parseLockingScript(e,r);s.push(i)}catch{}return s}async listOwnRegistryEntries(e){const t=this.mapDefinitionTypeToBasketName(e),{outputs:r,BEEF:i}=await this.wallet.listOutputs({basket:t,include:"entire transactions"}),n=[];for(const t of r)if(t.spendable)try{const[r,s]=t.outpoint.split("."),a=sr.fromBEEF(i).outputs[s].lockingScript,o=await this.parseLockingScript(e,a);n.push({...o,txid:r,outputIndex:Number(s),satoshis:t.satoshis,lockingScript:a.toHex(),beef:i})}catch{}return n}async revokeOwnRegistryEntry(e){if(void 0===e.txid||void 0===e.outputIndex||void 0===e.lockingScript)throw new Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");const t=(await this.wallet.getPublicKey({identityKey:!0})).publicKey;if(e.registryOperator!==t)throw new Error("This registry token does not belong to the current wallet.");const r="basket"===e.definitionType?e.basketID:"protocol"===e.definitionType?e.name:"certificate"===e.definitionType?void 0!==e.name?e.name:e.type:"unknown",i=`${e.txid}.${e.outputIndex}`,{signableTransaction:n}=await this.wallet.createAction({description:`Revoke ${e.definitionType} item: ${r}`,inputBEEF:e.beef,inputs:[{outpoint:i,unlockingScriptLength:73,inputDescription:`Revoking ${e.definitionType} token`}]});if(void 0===n)throw new Error("Failed to create signable transaction.");const s=sr.fromBEEF(n.tx),a=new Ht(this.wallet),o=await a.unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone","all",!1,e.satoshis,At.fromHex(e.lockingScript)),c=await o.sign(s,e.outputIndex),{tx:d}=await this.wallet.signAction({reference:n.reference,spends:{[e.outputIndex]:{unlockingScript:c.toHex()}},options:{acceptDelayedBroadcast:!1}});if(void 0===d)throw new Error("Failed to finalize the transaction signature.");const u=new Ii([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:this.network??=(await this.wallet.getNetwork({})).network});return await u.broadcast(sr.fromAtomicBEEF(d))}buildPushDropFields(e,t){let r;switch(e.definitionType){case"basket":r=[e.basketID,e.name,e.iconURL,e.description,e.documentationURL];break;case"protocol":r=[JSON.stringify(e.protocolID),e.name,e.iconURL,e.description,e.documentationURL];break;case"certificate":r=[e.type,e.name,e.iconURL,e.description,e.documentationURL,JSON.stringify(e.fields)];break;default:throw new Error("Unsupported definition type")}return r.push(t),r.map((e=>Oe(e)))}async parseLockingScript(e,t){const r=Ht.decode(t);if(0===r.fields.length)throw new Error("Not a valid registry pushdrop script.");let i,n;switch(e){case"basket":{if(7!==r.fields.length)throw new Error("Unexpected field count for basket type.");const[e,t,s,a,o,c]=r.fields;i=xe(c),n={definitionType:"basket",basketID:xe(e),name:xe(t),iconURL:xe(s),description:xe(a),documentationURL:xe(o)};break}case"protocol":{if(7!==r.fields.length)throw new Error("Unexpected field count for protocol type.");const[e,t,s,a,o,c]=r.fields;i=xe(c),n={definitionType:"protocol",protocolID:Ci(xe(e)),name:xe(t),iconURL:xe(s),description:xe(a),documentationURL:xe(o)};break}case"certificate":{if(8!==r.fields.length)throw new Error("Unexpected field count for certificate type.");const[e,t,s,a,o,c,d]=r.fields;i=xe(d);let u={};try{u=JSON.parse(xe(c))}catch{}n={definitionType:"certificate",type:xe(e),name:xe(t),iconURL:xe(s),description:xe(a),documentationURL:xe(o),fields:u};break}default:throw new Error(`Unsupported definition type: ${e}`)}return{...n,registryOperator:i}}mapDefinitionTypeToWalletProtocol(e){switch(e){case"basket":return[1,"basketmap"];case"protocol":return[1,"protomap"];case"certificate":return[1,"certmap"];default:throw new Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToBasketName(e){switch(e){case"basket":return"basketmap";case"protocol":return"protomap";case"certificate":return"certmap";default:throw new Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToTopic(e){switch(e){case"basket":return"tm_basketmap";case"protocol":return"tm_protomap";case"certificate":return"tm_certmap";default:throw new Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToServiceName(e){switch(e){case"basket":return"ls_basketmap";case"protocol":return"ls_protomap";case"certificate":return"ls_certmap";default:throw new Error(`Unknown definition type: ${e}`)}}}function Ci(e){const t=JSON.parse(e);if(!Array.isArray(t)||2!==t.length)throw new Error("Invalid wallet protocol format.");const[r,i]=t;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 Ri{wallet;context;encrypt;originator;constructor(e=new Qr,t="kvstore default",r=!0,i){if("string"!=typeof t||t.length<1)throw new Error("A context in which to operate is required.");this.wallet=e,this.context=t,this.encrypt=r,this.originator=i}getProtocol(e){return{protocolID:[2,this.context],keyID:e}}async getOutputs(e,t){return await this.wallet.listOutputs({basket:this.context,tags:[e],tagQueryMode:"all",include:"entire transactions",limit:t})}async get(e,t=void 0){return(await this.lookupValue(e,t,5)).value}getLockingScript(e,t){const[r,i]=e.outpoint.split("."),n=t.findTxid(r)?.tx;if(null==n)throw new Error(`beef must contain txid ${r}`);return n.outputs[Number(i)].lockingScript}async lookupValue(e,t,r){const i=await this.getOutputs(e,r),n={value:t,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 e=this.getLockingScript(a,nr.fromBinary(i.BEEF)),t=Ht.decode(e);if(t.fields.length<1||t.fields.length>2)throw new Error("Invalid token.");o=t.fields[0]}catch(e){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:t}=await this.wallet.decrypt({...this.getProtocol(e),ciphertext:o});n.value=xe(t)}else n.value=xe(o);return n}getInputs(e){const t=[];for(let r=0;r<e.length;r++)t.push({outpoint:e[r].outpoint,unlockingScriptLength:74,inputDescription:"Previous key-value token"});return t}async getSpends(e,t,r,i){const n=this.getProtocol(e),s=sr.fromAtomicBEEF(i),a={};for(let e=0;e<t.length;e++){const t=r.unlock(n.protocolID,n.keyID,"self"),i=await t.sign(s,e);a[e]={unlockingScript:i.toHex()}}return a}async set(e,t){const r=await this.lookupValue(e,void 0,10);if(r.value===t){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(e);let n=Oe(t,"utf8");if(this.encrypt){const{ciphertext:e}=await this.wallet.encrypt({...i,plaintext:n});n=e}const s=new Ht(this.wallet,this.originator),a=await s.lock([n],i.protocolID,i.keyID,"self"),{outputs:o,BEEF:c}=r.lor;let d;try{const t=this.getInputs(o),{txid:r,signableTransaction:i}=await this.wallet.createAction({description:`Update ${e} in ${this.context}`,inputBEEF:c,inputs:t,outputs:[{basket:this.context,tags:[e],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)d=`${r}.0`;else{const t=await this.getSpends(e,o,s,i.tx),{txid:r}=await this.wallet.signAction({reference:i.reference,spends:t});d=`${r}.0`}}catch(t){throw new Error(`There are ${o.length} outputs with tag ${e} that cannot be unlocked.`)}return d}async remove(e){const t=[];for(;;){const{outputs:r,BEEF:i,totalOutputs:n}=await this.getOutputs(e);if(r.length>0){const s=new Ht(this.wallet,this.originator);try{const n=this.getInputs(r),{signableTransaction:a}=await this.wallet.createAction({description:`Remove ${e} 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(e,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");t.push(c)}catch(t){throw new Error(`There are ${n} outputs with tag ${e} that cannot be unlocked.`)}}if(r.length===n)break}return t}}return t})()));
|