@bsv/sdk 2.0.1 → 2.0.3

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.
Files changed (44) hide show
  1. package/dist/cjs/package.json +1 -1
  2. package/dist/cjs/src/identity/ContactsManager.js +26 -14
  3. package/dist/cjs/src/identity/ContactsManager.js.map +1 -1
  4. package/dist/cjs/src/identity/IdentityClient.js +12 -8
  5. package/dist/cjs/src/identity/IdentityClient.js.map +1 -1
  6. package/dist/cjs/src/overlay-tools/LookupResolver.js +85 -41
  7. package/dist/cjs/src/overlay-tools/LookupResolver.js.map +1 -1
  8. package/dist/cjs/src/overlay-tools/SHIPBroadcaster.js +28 -4
  9. package/dist/cjs/src/overlay-tools/SHIPBroadcaster.js.map +1 -1
  10. package/dist/cjs/src/wallet/WalletClient.js +3 -3
  11. package/dist/cjs/src/wallet/WalletClient.js.map +1 -1
  12. package/dist/cjs/src/wallet/substrates/WalletWireTransceiver.js.map +1 -1
  13. package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
  14. package/dist/esm/src/identity/ContactsManager.js +26 -14
  15. package/dist/esm/src/identity/ContactsManager.js.map +1 -1
  16. package/dist/esm/src/identity/IdentityClient.js +12 -8
  17. package/dist/esm/src/identity/IdentityClient.js.map +1 -1
  18. package/dist/esm/src/overlay-tools/LookupResolver.js +85 -41
  19. package/dist/esm/src/overlay-tools/LookupResolver.js.map +1 -1
  20. package/dist/esm/src/overlay-tools/SHIPBroadcaster.js +29 -4
  21. package/dist/esm/src/overlay-tools/SHIPBroadcaster.js.map +1 -1
  22. package/dist/esm/src/wallet/WalletClient.js +3 -3
  23. package/dist/esm/src/wallet/WalletClient.js.map +1 -1
  24. package/dist/esm/src/wallet/substrates/WalletWireTransceiver.js.map +1 -1
  25. package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
  26. package/dist/types/src/identity/ContactsManager.d.ts.map +1 -1
  27. package/dist/types/src/identity/IdentityClient.d.ts.map +1 -1
  28. package/dist/types/src/overlay-tools/LookupResolver.d.ts +6 -0
  29. package/dist/types/src/overlay-tools/LookupResolver.d.ts.map +1 -1
  30. package/dist/types/src/overlay-tools/SHIPBroadcaster.d.ts +8 -0
  31. package/dist/types/src/overlay-tools/SHIPBroadcaster.d.ts.map +1 -1
  32. package/dist/types/tsconfig.types.tsbuildinfo +1 -1
  33. package/dist/umd/bundle.js +1 -1
  34. package/dist/umd/bundle.js.map +1 -1
  35. package/package.json +1 -1
  36. package/src/identity/ContactsManager.ts +27 -15
  37. package/src/identity/IdentityClient.ts +13 -11
  38. package/src/identity/__tests/IdentityClient.test.ts +2 -2
  39. package/src/overlay-tools/LookupResolver.ts +83 -46
  40. package/src/overlay-tools/SHIPBroadcaster.ts +32 -4
  41. package/src/overlay-tools/__tests/LookupResolver.test.ts +36 -55
  42. package/src/overlay-tools/__tests/SHIPBroadcaster.test.ts +18 -6
  43. package/src/wallet/WalletClient.ts +3 -3
  44. package/src/wallet/substrates/WalletWireTransceiver.ts +1 -1
@@ -16,5 +16,5 @@ ${i.path[0].filter(e=>!0===e.txid).map(e=>` '${e.hash??""}'`).join(",\n")}
16
16
  `,i.inputTxids.length>0&&(e+=` inputs: [
17
17
  ${i.inputTxids.map(e=>` '${e}'`).join(",\n")}
18
18
  ]
19
- `);return e}addComputedLeaves(){let e=e=>te(eo(ti(e,"hex").reverse()).reverse());for(let t of this.bumps)for(let i=1;i<t.path.length;i++)for(let r of t.path[i-1])if("string"==typeof r.hash&&(1&r.offset)==0){let n=t.path[i-1].find(e=>e.offset===r.offset+1),a=r.offset>>1;void 0!==n&&"string"==typeof n.hash&&t.path[i].every(e=>e.offset!==a)&&t.path[i].push({offset:a,hash:e(n.hash+r.hash)})}}}class i3{version;inputs;outputs;lockTime;metadata;merklePath;cachedHash;rawBytesCache;hexCache;static addPathOrInputs(e,t,i){if("number"==typeof e.pathIndex){let t=i[e.pathIndex];if("object"!=typeof t)throw Error("Invalid merkle path index found in BEEF!");e.tx.merklePath=t}else for(let r of e.tx.inputs){if(void 0===r.sourceTXID)throw Error("Input sourceTXID is undefined");let e=t[r.sourceTXID];if("object"!=typeof e)throw Error(`Reference to unknown TXID in BEEF: ${r.sourceTXID??"undefined"}`);r.sourceTransaction=e.tx,this.addPathOrInputs(e,t,i)}}static fromBEEF(e,t){let{tx:i}=i3.fromAnyBeef(e,t);return i}static fromAtomicBEEF(e){let{tx:t,txid:i,beef:r}=i3.fromAnyBeef(e);if(i!==r.atomicTxid)if(null!=r.atomicTxid)throw Error(`Transaction with TXID ${r.atomicTxid} not found in BEEF data.`);else throw Error("beef must conform to BRC-95 and must contain the subject txid.");return t}static fromAnyBeef(e,t){let i=i8.fromBinary(e);if(i.txs.length<1)throw Error("beef must include at least one transaction.");let r=t??i.atomicTxid??i.txs.slice(-1)[0].txid,n=i.findAtomicTransaction(r);if(null==n)if(null!=t)throw Error(`Transaction with TXID ${r} not found in BEEF data.`);else throw Error("beef does not contain transaction for atomic txid.");return{tx:n,beef:i,txid:r}}static fromEF(e){let t=e3.makeReader(e),i=t.readUInt32LE();if("0000000000ef"!==te(t.read(6)))throw Error("Invalid EF marker");let r=t.readVarIntNum(),n=[];for(let e=0;e<r;e++){let e=te(t.readReverse(32)),i=t.readUInt32LE(),r=t.readVarIntNum(),a=t.read(r),s=i_.fromBinary(a),o=t.readUInt32LE(),c=t.readUInt64LEBn().toNumber(),l=t.readVarIntNum(),h=t.read(l),d=iT.fromBinary(h),u=new i3(void 0,[],[],void 0);u.outputs=Array(i+1).fill(null),u.outputs[i]={satoshis:c,lockingScript:d},n.push({sourceTransaction:u,sourceTXID:e,sourceOutputIndex:i,unlockingScript:s,sequence:o})}let a=t.readVarIntNum(),s=[];for(let e=0;e<a;e++){let e=t.readUInt64LEBn().toNumber(),i=t.readVarIntNum(),r=t.read(i),n=iT.fromBinary(r);s.push({satoshis:e,lockingScript:n})}return new i3(i,n,s,t.readUInt32LE())}static parseScriptOffsets(e){let t=e3.makeReader(e),i=[],r=[];t.pos+=4;let n=t.readVarIntNum();for(let e=0;e<n;e++){t.pos+=36;let r=t.readVarIntNum();i.push({vin:e,offset:t.pos,length:r}),t.pos+=r+4}let a=t.readVarIntNum();for(let e=0;e<a;e++){t.pos+=8;let i=t.readVarIntNum();r.push({vout:e,offset:t.pos,length:i}),t.pos+=i}return{inputs:i,outputs:r}}static fromReader(e){let t=e.readUInt32LE(),i=e.readVarIntNum(),r=[];for(let t=0;t<i;t++){let t=te(e.readReverse(32)),i=e.readUInt32LE(),n=e.readVarIntNum(),a=e.read(n),s=i_.fromBinary(a),o=e.readUInt32LE();r.push({sourceTXID:t,sourceOutputIndex:i,unlockingScript:s,sequence:o})}let n=e.readVarIntNum(),a=[];for(let t=0;t<n;t++){let t=e.readUInt64LEBn().toNumber(),i=e.readVarIntNum(),r=e.read(i),n=iT.fromBinary(r);a.push({satoshis:t,lockingScript:n})}return new i3(t,r,a,e.readUInt32LE())}static fromBinary(e){let t=e.slice(),i=Uint8Array.from(t),r=new e3(i),n=i3.fromReader(r);return n.rawBytesCache=i,n}static fromHex(e){let t=tt(e,"hex"),i=new e3(t),r=i3.fromReader(i);return r.rawBytesCache=t,r.hexCache=te(t),r}static fromHexEF(e){return i3.fromEF(tt(e,"hex"))}static fromHexBEEF(e,t){return i3.fromBEEF(ti(e,"hex"),t)}constructor(e=1,t=[],i=[],r=0,n=new Map,a){this.version=e,this.inputs=t,this.outputs=i,this.lockTime=r,this.metadata=n,this.merklePath=a}invalidateSerializationCaches(){this.cachedHash=void 0,this.rawBytesCache=void 0,this.hexCache=void 0}addInput(e){if(void 0===e.sourceTXID&&void 0===e.sourceTransaction)throw 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=0xffffffff),this.invalidateSerializationCaches(),this.inputs.push(e)}addOutput(e){if(this.cachedHash=void 0,!0!==e.change){if(void 0===e.satoshis)throw Error("either satoshis must be defined or change must be set to true");if(e.satoshis<0)throw Error("satoshis must be a positive integer or zero")}if(null==e.lockingScript)throw Error("lockingScript must be defined");this.outputs.push(e)}addP2PKHOutput(e,t){let i=new iL().lock(e);if(void 0===t)return this.addOutput({lockingScript:i,change:!0});this.addOutput({lockingScript:i,satoshis:t})}updateMetadata(e){this.metadata={...this.metadata,...e}}async fee(e=iq.getInstance(),t="equal"){if(this.invalidateSerializationCaches(),"number"==typeof e){let t=e;e={computeFee:async()=>t}}let i=await e.computeFee(this),r=this.calculateChange(i);if(r<=0){this.outputs=this.outputs.filter(e=>!0!==e.change);return}this.distributeChange(r,t)}calculateChange(e){let t=0;for(let e of this.inputs){if("object"!=typeof e.sourceTransaction)throw Error("Source transactions are required for all inputs during fee computation");t+=e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0}for(let i of(t-=e,this.outputs))!0!==i.change&&void 0!==i.satoshis&&(t-=i.satoshis);return t}distributeChange(e,t){let i=0,r=this.outputs.filter(e=>e.change);if("random"===t?i=this.distributeRandomChange(e,r):"equal"===t&&(i=this.distributeEqualChange(e,r)),i<e){let t=this.outputs[this.outputs.length-1];void 0!==t.satoshis?t.satoshis+=e-i:t.satoshis=e-i}}distributeRandomChange(e,t){let i=0,r=e,n=Array(t.length).fill(1);r-=t.length,i+=t.length;for(let e=0;e<t.length-1;e++){let t=this.benfordNumber(0,r);n[e]=n[e]+t,i+=t,r-=t}for(let e of this.outputs)!0===e.change&&(e.satoshis=n.shift());return i}distributeEqualChange(e,t){let i=0,r=Math.floor(e/t.length);for(let e of t)i+=r,e.satoshis=r;return i}benfordNumber(e,t){return Math.floor(e+(t-e)*Math.log10(1+1/(Math.floor(9*Math.random())+1))/Math.log10(10))}getFee(){let e=0;for(let t of this.inputs){if("object"!=typeof t.sourceTransaction)throw 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(let e of this.outputs)t+=e.satoshis??0;return e-t}async sign(){for(let e of(this.invalidateSerializationCaches(),this.outputs))if(void 0===e.satoshis)if(!0===e.change)throw Error("There are still change outputs with uncomputed amounts. Use the fee() method to compute the change amounts and transaction fees prior to signing.");else throw Error("One or more transaction outputs is missing an amount. Ensure all output amounts are provided before signing.");let e=await Promise.all(this.inputs.map(async(e,t)=>"object"==typeof this.inputs[t].unlockingScriptTemplate?await this.inputs[t]?.unlockingScriptTemplate?.sign(this,t):await Promise.resolve(void 0)));for(let t=0,i=this.inputs.length;t<i;t++)"object"==typeof this.inputs[t].unlockingScriptTemplate&&(this.inputs[t].unlockingScript=e[t])}async broadcast(e=iG()){return await e.broadcast(this)}writeTransactionBody(e){for(let t of(e.writeUInt32LE(this.version),e.writeVarIntNum(this.inputs.length),this.inputs)){if(void 0===t.sourceTXID)if(null!=t.sourceTransaction)e.write(t.sourceTransaction.hash());else throw Error("sourceTransaction is undefined");else e.writeReverse(ti(t.sourceTXID,"hex"));if(e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw Error("unlockingScript is undefined");let i=t.unlockingScript.toUint8Array();e.writeVarIntNum(i.length),e.write(i),e.writeUInt32LE(t.sequence??0xffffffff)}for(let t of(e.writeVarIntNum(this.outputs.length),this.outputs)){e.writeUInt64LE(t.satoshis??0);let i=t.lockingScript.toUint8Array();e.writeVarIntNum(i.length),e.write(i)}e.writeUInt32LE(this.lockTime)}buildSerializedBytes(){let e=new e8;return this.writeTransactionBody(e),e.toUint8Array()}getSerializedBytes(){return null==this.rawBytesCache&&(this.rawBytesCache=this.buildSerializedBytes()),this.rawBytesCache}toBinary(){return Array.from(this.getSerializedBytes())}toUint8Array(){return this.getSerializedBytes()}writeEF(e){for(let t of(e.writeUInt32LE(this.version),e.write([0,0,0,0,0,239]),e.writeVarIntNum(this.inputs.length),this.inputs)){if(void 0===t.sourceTransaction)throw Error("All inputs must have source transactions when serializing to EF format");if(void 0===t.sourceTXID?e.write(t.sourceTransaction.hash()):e.write(ti(t.sourceTXID,"hex").reverse()),e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw Error("unlockingScript is undefined");let i=t.unlockingScript.toBinary();e.writeVarIntNum(i.length),e.write(i),e.writeUInt32LE(t.sequence??0xffffffff),e.writeUInt64LE(t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0);let r=t.sourceTransaction.outputs[t.sourceOutputIndex].lockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r)}for(let t of(e.writeVarIntNum(this.outputs.length),this.outputs)){e.writeUInt64LE(t.satoshis??0);let i=t.lockingScript.toBinary();e.writeVarIntNum(i.length),e.write(i)}e.writeUInt32LE(this.lockTime)}toEF(){let e=new tp;return this.writeEF(e),e.toArray()}toEFUint8Array(){let e=new e8;return this.writeEF(e),e.toUint8Array()}toHexEF(){return te(this.toEFUint8Array())}toHex(){if(null!=this.hexCache)return this.hexCache;let e=te(this.getSerializedBytes());return this.hexCache=e,e}toHexBEEF(){return te(this.toBEEF())}toHexAtomicBEEF(){return te(this.toAtomicBEEF())}hash(e){return(null==this.cachedHash&&(this.cachedHash=eo(this.getSerializedBytes())),"hex"===e)?te(this.cachedHash):this.cachedHash}id(e){let t=[...this.hash()];return(t.reverse(),"hex"===e)?te(t):t}async verify(e=iJ(),t,i){let r=new Set,n=[this];for(;n.length>0;){let a=n.shift(),s=a?.id("hex")??"";if(null!=s&&""!==s&&r.has(s))continue;if("object"==typeof a?.merklePath)if("scripts only"===e){null!=s&&r.add(s);continue}else{if(await a.merklePath.verify(s,e)){r.add(s);continue}throw Error(`Invalid merkle path for transaction ${s}`)}if(void 0!==t){if(void 0===a)throw Error("Transaction is undefined");let e=i3.fromEF(a.toEF());if(delete e.outputs[0].satoshis,e.outputs[0].change=!0,await e.fee(t),a.getFee()<e.getFee())throw Error(`Verification failed because the transaction ${s} has an insufficient fee and has not been mined.`)}let o=0;if(void 0===a)throw Error("Transaction is undefined");for(let e=0;e<a.inputs.length;e++){let t=a.inputs[e];if("object"!=typeof t.sourceTransaction)throw Error(`Verification failed because the input at index ${e} of transaction ${s} 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 Error(`Verification failed because the input at index ${e} of transaction ${s} is missing an associated unlocking script. This script is required for transaction verification because there is no merkle proof for the transaction spending the UTXO.`);let c=t.sourceTransaction.outputs[t.sourceOutputIndex];o+=c.satoshis??0;let l=t.sourceTransaction.id("hex");r.has(l)||n.push(t.sourceTransaction);let h=a.inputs.filter((t,i)=>i!==e);if(void 0===t.sourceTXID&&(t.sourceTXID=l),!new iD({sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,lockingScript:c.lockingScript,sourceSatoshis:c.satoshis??0,transactionVersion:a.version,otherInputs:h,unlockingScript:t.unlockingScript,inputSequence:t.sequence??0xffffffff,inputIndex:e,outputs:a.outputs,lockTime:a.lockTime,memoryLimit:i}).validate())return!1}let c=0;for(let e of a.outputs){if("number"!=typeof e.satoshis)throw Error("Every output must have a defined amount during transaction verification.");c+=e.satoshis}if(c>o)return!1;r.add(s)}return!0}writeSerializedBEEF(e,t){e.writeUInt32LE(i0);let i=[],r=new Map,n=new Map,a=[],s=new Set,o=e=>{let c=e.id("hex");if(s.has(c))return;let l={tx:e},h=e.merklePath,d="object"==typeof h;if(d&&null!=h&&(l.pathIndex=(e=>{let t=r.get(e);if(void 0!==t)return t;let a=`${e.blockHeight}:${e.computeRoot()}`,s=n.get(a);if(void 0!==s)return i[s].combine(e),r.set(e,s),s;let o=i.length;return i.push(e),r.set(e,o),n.set(a,o),o})(h)),!d)for(let i=e.inputs.length-1;i>=0;i--){let r=e.inputs[i];if("object"==typeof r.sourceTransaction)o(r.sourceTransaction);else if(!1===t)throw Error("A required source transaction is missing!")}s.add(c),a.push(l)};for(let t of(o(this),e.writeVarIntNum(i.length),i))e.write(t.toBinary());for(let t of(e.writeVarIntNum(a.length),a))e.write(t.tx.toBinary()),"number"==typeof t.pathIndex?(e.writeUInt8(1),e.writeVarIntNum(t.pathIndex)):e.writeUInt8(0);return e.toArray()}toBEEF(e){let t=new tp;return this.writeSerializedBEEF(t,e),t.toArray()}toBEEFUint8Array(e){let t=new e8;return this.writeSerializedBEEF(t,e),t.toArray()}toAtomicBEEF(e){return[1,1,1,1].concat(this.hash(),this.toBEEF(e))}toAtomicBEEFUint8Array(e){let t=new e8;t.write([1,1,1,1]);let i=this.hash();return t.write(i),this.writeSerializedBEEF(t,e),t.toUint8Array()}async completeWithWallet(e,t,i,r){let n,a=this.inputs.length,s=this.outputs.length,o={description:t??`Transaction with ${a} input(s) and ${s} output(s)`,inputs:[],outputs:[],lockTime:this.lockTime,version:this.version},c=this.inputs.some(e=>null!=e.unlockingScriptTemplate),l=new i8;for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];if(null==t.sourceTransaction)throw Error("All inputs must have a sourceTransaction when using completeWithWallet");let i=t.sourceTransaction.toBEEF();l.mergeBeef(i);let r=t.sourceTransaction.id("hex"),n={outpoint:`${r}.${t.sourceOutputIndex}`,inputDescription:"Input from source transaction",sequenceNumber:t.sequence};if(c)if(null!=t.unlockingScriptTemplate)n.unlockingScriptLength=await t.unlockingScriptTemplate.estimateLength(this,e);else if(null!=t.unlockingScript)n.unlockingScript=t.unlockingScript.toHex();else throw Error(`Input ${e} must have either an unlockingScript or unlockingScriptTemplate`);else{if(null==t.unlockingScript)throw Error("All inputs must have an unlockingScript when using completeWithWallet");n.unlockingScript=t.unlockingScript.toHex()}o.inputs.push(n)}for(let e of(this.inputs.length>0&&(o.inputBEEF=l.toBinary()),this.outputs))o.outputs.push({satoshis:e.satoshis,lockingScript:e.lockingScript.toHex(),outputDescription:"Output from source transaction"});if(this.metadata?.labels!=null&&Array.isArray(this.metadata.labels)&&(o.labels=this.metadata.labels),c){o.options={...r,signAndProcess:!1};let{signableTransaction:t}=await e.createAction(o,i);if(null==t)throw Error("Wallet createAction did not return signableTransaction");let a=i3.fromBEEF(t.tx),s={};for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];if(null!=t.unlockingScriptTemplate){let i=await t.unlockingScriptTemplate.sign(a,e);s[e]={unlockingScript:i.toHex()}}else null!=t.unlockingScript&&(s[e]={unlockingScript:t.unlockingScript.toHex()})}let c=null!=r?{acceptDelayedBroadcast:r.acceptDelayedBroadcast,returnTXIDOnly:r.returnTXIDOnly,noSend:r.noSend,sendWith:r.sendWith}:void 0,l=await e.signAction({reference:t.reference,spends:s,options:c},i);if(null==l.tx)throw Error("Wallet signAction did not return transaction data");n=l.tx}else{null!=r&&(o.options=r);let{tx:t}=await e.createAction(o,i);if(null==t)throw Error("Wallet createAction did not return transaction data");n=t}let h=i3.fromAtomicBEEF(n);this.version=h.version,this.inputs=h.inputs,this.outputs=h.outputs,this.lockTime=h.lockTime,this.merklePath=h.merklePath,this.cachedHash=h.cachedHash,this.metadata={...this.metadata,...h.metadata}}}function i6(e){return"success"===e.status}function i4(e){return"error"===e.status}let i5=class extends i8{knownTo={};constructor(e){if(super(),null!=e)for(const t of e)this.addParty(t)}isParty(e){return Object.keys(this.knownTo).includes(e)}addParty(e){if(this.isParty(e))throw Error(`Party ${e} already exists.`);this.knownTo[e]={}}getKnownTxidsForParty(e){let t=this.knownTo[e];if(void 0===t)throw Error(`Party ${e} is unknown.`);return Object.keys(t)}getTrimmedBeefForParty(e){let t=this.getKnownTxidsForParty(e),i=this.clone();return i.trimKnownTxids(t),i}addKnownTxidsForParty(e,t){this.isParty(e)||this.addParty(e);let i=this.knownTo[e];for(let e of t)i[e]=!0,this.mergeTxidOnly(e)}mergeBeefFromParty(e,t){let i=Array.isArray(t)?i8.fromBinary(t):t,r=i.getValidTxids();this.mergeBeef(i),this.addKnownTxidsForParty(e,r)}};class i7{network;URL;httpClient;constructor(e="main",t=iW()){this.network=e,this.URL=`https://api.whatsonchain.com/v1/bsv/${e}/tx/raw`,this.httpClient=t}async broadcast(e){let t=e.toHex();try{let e=await this.httpClient.request(this.URL,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/plain"},data:{txhex:t}});if(!e.ok)return{status:"error",code:e.status.toString()??"ERR_UNKNOWN",description:e.data??"Unknown error"};{let t=e.data;return{status:"success",txid:t,message:"broadcast successful"}}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class i9{https;constructor(e){this.https=e}async request(e,t){return await new Promise((i,r)=>{let n=this.https.request(e,t,e=>{let t="";e.on("data",e=>{t+=e}),e.on("end",()=>{let r=e.statusCode>=200&&e.statusCode<=299,n=e.headers["content-type"],a=""!==t&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(t):t;i({status:e.statusCode,statusText:e.statusMessage,ok:r,data:a})})});n.on("error",e=>{r(e)}),null!==t.data&&void 0!==t.data&&n.write(Buffer.from(t.data)),n.end()})}}class re{fetch;constructor(e){this.fetch=e}async request(e,t){let i={method:t.method,headers:t.headers,body:t.data},r=await this.fetch(e,i),n=await r.text();return{ok:r.ok,status:r.status,statusText:r.statusText,data:n}}}function rt(){let e={async request(){throw Error("No method available to perform HTTP request")}};if("u">typeof window&&"function"==typeof window.fetch)return new re(window.fetch.bind(window));if(!("u">typeof require))return e;try{let e=require("https");return new i9(e)}catch(t){return e}}class ri{URL;httpClient;constructor(e,t=rt()){this.URL=e,this.httpClient=t}async broadcast(e){let t={method:"POST",headers:{"Content-Type":"application/octet-stream"},data:new Blob([new Uint8Array(e.toEF())])};try{let i=await this.httpClient.request(this.URL,t);if(!i.ok)return{status:"error",code:i.status.toString()??"ERR_UNKNOWN",description:i.data??"Unknown error"};{let t=e.id("hex");return{status:"success",txid:t,message:"broadcast successful"}}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class rr{baseUrl;httpClient;apiKey;constructor(e,t={}){const{httpClient:i,apiKey:r}=t;this.baseUrl=e,this.httpClient=i??iW(),this.apiKey=r??""}async isValidRootForHeight(e,t){let i={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.apiKey}`},data:[{blockHeight:t,merkleRoot:e}]};try{let e=await this.httpClient.request(`${this.baseUrl}/api/v1/chain/merkleroot/verify`,i);if(e.ok)return"CONFIRMED"===e.data.confirmationState;throw Error(`Failed to verify merkleroot for height ${t} because of an error: ${JSON.stringify(e.data)}`)}catch(e){throw Error(`Failed to verify merkleroot for height ${t} because of an error: ${e instanceof Error?e.message:String(e)}`)}}async currentHeight(){let e={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`}};try{let t=await this.httpClient.request(`${this.baseUrl}/api/v1/chain/tip/longest`,e);if(t.ok&&t.data&&"number"==typeof t.data.height)return t.data.height;throw Error(`Failed to get current height because of an error: ${JSON.stringify(t.data)}`)}catch(e){throw Error(`Failed to get current height because of an error: ${e instanceof Error?e.message:String(e)}`)}}}let rn="42423301",ra=(e,t,i)=>{let r="object"!=typeof i;if(r){let e=new tH,t=new t3(1),r=e.g.mul(t);i=new tJ(r.x,r.y)}let n=t0(32),a=tc(n),s=`2-message signing-${a}`,o=t.deriveChild(i,s).sign(e).toDER(),c=t.toPublicKey().encode(!0);return[...ti(rn,"hex"),...c,...r?[0]:i.encode(!0),...n,...o]},rs=(e,t,i)=>{let r=new tg(t),n=te(r.read(4));if(n!==rn)throw Error(`Message version mismatch: Expected ${rn}, received ${n}`);let a=tJ.fromString(te(r.read(33))),[s]=r.read(1);if(0===s)i=new t3(1);else{let e=te([s,...r.read(32)]);if("object"!=typeof i)throw Error(`This signature can only be verified with knowledge of a specific private key. The associated public key is: ${e}`);let t=i.toPublicKey().encode(!0,"hex");if(e!==t)throw Error(`The recipient public key is ${t} but the signature requres the recipient to have public key ${e}`)}let o=tc(r.read(32)),c=te(r.read(r.bin.length-r.pos)),l=tK.fromDER(c,"hex"),h=`2-message signing-${o}`;return a.deriveChild(i,h).verify(e,l)},ro="42421033",rc=(e,t,i)=>{let r=t0(32),n=tc(r),a=`2-message encryption-${n}`,s=t.deriveChild(i,a),o=i.deriveChild(t,a),c=new ip(s.deriveSharedSecret(o).encode(!0).slice(1)).encrypt(e),l=t.toPublicKey().encode(!0);return[...ti(ro,"hex"),...l,...i.encode(!0),...r,...c]},rl=(e,t)=>{let i=new tg(e),r=te(i.read(4));if(r!==ro)throw Error(`Message version mismatch: Expected ${ro}, received ${r}`);let n=tJ.fromString(te(i.read(33))),a=te(i.read(33)),s=t.toPublicKey().encode(!0,"hex");if(a!==s)throw Error(`The encrypted message expects a recipient public key of ${a}, but the provided key is ${s}`);let o=tc(i.read(32)),c=i.read(i.bin.length-i.pos),l=`2-message encryption-${o}`,h=n.deriveChild(t,l),d=t.deriveChild(n,l);return new ip(h.deriveSharedSecret(d).encode(!0).slice(1)).decrypt(c)},rh="Bitcoin Signed Message:\n",rd=e=>{let t=new tp;return t.writeVarIntNum(rh.length),t.write(ti(rh,"utf8")),t.writeVarIntNum(e.length),t.write(e),eo(t.toArray())},ru=(e,t,i="base64")=>{let r=rd(e),n=tG(new P(r),t,!0);if("raw"===i)return n;let a=new P(r),s=n.CalculateRecoveryFactor(t.toPublicKey(),a);return n.toCompact(s,!0,"base64")},rf=(e,t,i)=>tY(new P(rd(e)),t,i);class rp{versionBytesNum;depth;parentFingerPrint;childIndex;chainCode;privKey;pubKey;constants={pubKey:0x488b21e,privKey:0x488ade4};constructor(e,t,i,r,n,a,s){this.versionBytesNum=e,this.depth=t,this.parentFingerPrint=i,this.childIndex=r,this.chainCode=n,this.privKey=a,this.pubKey=s}fromRandom(){return this.versionBytesNum=this.constants.privKey,this.depth=0,this.parentFingerPrint=[0,0,0,0],this.childIndex=0,this.chainCode=t0(32),this.privKey=t3.fromRandom(),this.pubKey=this.privKey.toPublicKey(),this}static fromRandom(){return new this().fromRandom()}static fromString(e){return new this().fromString(e)}fromString(e){let t=tf(e);return this.fromBinary([...t.prefix,...t.data])}static fromSeed(e){return new this().fromSeed(e)}fromSeed(e){if(e.length<16)throw Error("Need more than 128 bits of entropy");if(e.length>64)throw Error("More than 512 bits of entropy is nonstandard");let t=eh(ti("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 t3(t.slice(0,32)),this.pubKey=this.privKey.toPublicKey(),this}static fromBinary(e){return new this().fromBinary(e)}fromBinary(e){if(78!==e.length)throw Error("incorrect bip32 data length");let t=new tg(e);this.versionBytesNum=t.readUInt32BE(),this.depth=t.readUInt8(),this.parentFingerPrint=t.read(4),this.childIndex=t.readUInt32BE(),this.chainCode=t.read(32);let i=t.read(33),r=this.versionBytesNum===this.constants.privKey,n=this.versionBytesNum===this.constants.pubKey;if(r&&0===i[0])this.privKey=new t3(i.slice(1,33)),this.pubKey=this.privKey.toPublicKey();else if(n&&(2===i[0]||3===i[0]))this.pubKey=tJ.fromString(te(i));else throw Error("Invalid key");return this}toString(){return tu(this.toBinary(),[])}derive(e){if("m"===e)return this;let t=e.split("/"),i=this;for(let[e,r]of t.entries()){if(0===e){if("m"!==r)throw Error("invalid path");continue}if(parseInt(r.replace("'",""),10).toString()!==r.replace("'",""))throw Error("invalid path");let t=r.length>1&&"'"===r[r.length-1],n=0x7fffffff&parseInt(t?r.slice(0,r.length-1):r,10);t&&(n+=0x80000000),i=i.deriveChild(n)}return i}deriveChild(e){if("number"!=typeof e)throw Error("i must be a number");let t=[];t.push(e>>24&255),t.push(e>>16&255),t.push(e>>8&255),t.push(255&e);let i=[...t],r=(0x80000000&e)!=0,n=this.versionBytesNum===this.constants.privKey;if(r&&(null===this.privKey||void 0===this.privKey||!n))throw Error("Cannot do private key derivation without private key");let a=null;if(null!==this.privKey&&void 0!==this.privKey){let e=null;e=r?[0,...this.privKey.toArray("be",32),...i]:[...this.pubKey.encode(!0),...i];let t=eh(this.chainCode,e),n=new P(t.slice(0,32)),s=t.slice(32,64),o=n.add(this.privKey).mod(new tH().n);(a=new rp).chainCode=s,a.privKey=new t3(o.toArray()),a.pubKey=a.privKey.toPublicKey()}else{let e=[...this.pubKey.encode(!0),...i],t=eh(this.chainCode,e),r=new P(t.slice(0,32)),n=t.slice(32,64),s=new tH().g.mul(r),o=this.pubKey,c=s.add(o),l=new tJ(c.x,c.y);(a=new rp).chainCode=n,a.pubKey=l}a.childIndex=e;let s=ec(this.pubKey.encode(!0));return a.parentFingerPrint=s.slice(0,4),a.versionBytesNum=this.versionBytesNum,a.depth=this.depth+1,a}toPublic(){let e=new rp(this.versionBytesNum,this.depth,this.parentFingerPrint,this.childIndex,this.chainCode,this.privKey,this.pubKey);return e.versionBytesNum=this.constants.pubKey,e.privKey=void 0,e}toBinary(){let e=this.versionBytesNum===this.constants.privKey,t=this.versionBytesNum===this.constants.pubKey;if(e)return new tp().writeUInt32BE(this.versionBytesNum).writeUInt8(this.depth).write(this.parentFingerPrint).writeUInt32BE(this.childIndex).write(this.chainCode).writeUInt8(0).write(this.privKey.toArray("be",32)).toArray();if(t)return new tp().writeUInt32BE(this.versionBytesNum).writeUInt8(this.depth).write(this.parentFingerPrint).writeUInt32BE(this.childIndex).write(this.chainCode).write(this.pubKey.encode(!0)).toArray();throw Error("bip32: invalid versionBytesNum byte")}isPrivate(){return this.versionBytesNum===this.constants.privKey}}let rg={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 rm{mnemonic;seed;Wordlist;constructor(e,t,i=rg){this.mnemonic=e??"",this.seed=t??[],this.Wordlist=i}toBinary(){let e=new tp;if(""!==this.mnemonic){let t=ti(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){let t=new tg(e),i=t.readVarIntNum();i>0&&(this.mnemonic=to(t.read(i),"utf8"));let r=t.readVarIntNum();return r>0&&(this.seed=t.read(r)),this}fromRandom(e){if((null==e||isNaN(e)||0===e)&&(e=128),e%32!=0)throw Error("bits must be multiple of 32");if(e<128)throw Error("bits must be at least 128");let t=t0(e/8);return this.entropy2Mnemonic(t),this.mnemonic2Seed(),this}static fromRandom(e){return new this().fromRandom(e)}fromEntropy(e){return this.entropy2Mnemonic(e),this}static fromEntropy(e){return new this().fromEntropy(e)}fromString(e){return this.mnemonic=e,this}static fromString(e){return new this().fromString(e)}toString(){return this.mnemonic}toSeed(e){return this.mnemonic2Seed(e),this.seed}entropy2Mnemonic(e){if(e.length<16)throw Error("Entropy is less than 128 bits. It must be 128 bits or more.");let t=ea(e),i="",r=8*e.length;for(let t=0;t<e.length;t++)i+=("00000000"+e[t].toString(2)).slice(-8);let n=t[0].toString(2);if((i+=n=("00000000"+n).slice(-8).slice(0,r/32)).length%11!=0)throw Error("internal error - entropy not an even multiple of 11 bits - "+i.length.toString());let a="";for(let e=0;e<i.length/11;e++){""!==a&&(a+=this.Wordlist.space);let t=parseInt(i.slice(11*e,(e+1)*11),2);a+=this.Wordlist.value[t]}return this.mnemonic=a,this}check(){let e=this.mnemonic.split(this.Wordlist.space),t="";for(let i=0;i<e.length;i++){let r=this.Wordlist.value.indexOf(e[i]);if(r<0)return!1;t+=("00000000000"+r.toString(2)).slice(-11)}if(t.length%11!=0)throw Error("internal error - entropy not an even multiple of 11 bits - "+t.length.toString());let i=t.length/33,r=t.slice(-i),n=t.slice(0,t.length-i),a=[];for(let e=0;e<n.length/8;e++)a.push(parseInt(t.slice(8*e,(e+1)*8),2));let s=ea(a.slice(0,n.length/8))[0].toString(2);return(s=("00000000"+s).slice(-8).slice(0,i))===r}mnemonic2Seed(e=""){let t=this.mnemonic;if(!this.check())throw Error("Mnemonic does not pass the check - was the mnemonic typed incorrectly? Are there extra spaces?");if("string"!=typeof e)throw Error("passphrase must be a string or undefined");t=t.normalize("NFKD"),e=e.normalize("NFKD");let i=ti(t,"utf8"),r=[...ti("mnemonic","utf8"),...ti(e,"utf8")];return this.seed=eQ(i,r,2048,64,"sha512"),this}isValid(e=""){let t;try{this.mnemonic2Seed(e),t=!0}catch{t=!1}return t}static isValid(e,t=""){return new rm(e).isValid(t)}}function ry(e){let t,i,r,n;0===this._tables[0][0][0]&&this._precompute();let a=this._tables[0][4],s=this._tables[1],o=e.length,c=1;if(4!==o&&6!==o&&8!==o)throw Error("invalid aes key size");for(this._key=[i=e.slice(0),r=[]],n=o;n<4*o+28;n++)t=i[n-1],(n%o==0||8===o&&n%o==4)&&(t=a[t>>>24]<<24^a[t>>16&255]<<16^a[t>>8&255]<<8^a[255&t],n%o==0&&(t=t<<8^t>>>24^c<<24,c=c<<1^(c>>7)*283)),i[n]=i[n-o]^t;for(let e=0;n>0;e++,n--)t=i[(3&e)!=0?n:n-4],n<=4||e<4?r[e]=t:r[e]=s[0][a[t>>>24]]^s[1][a[t>>16&255]]^s[2][a[t>>8&255]]^s[3][a[255&t]]}ry.prototype={encrypt:function(e){return this._crypt(e,0)},decrypt:function(e){return this._crypt(e,1)},_tables:[[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)]],_precompute:function(){let e,t,i,r,n,a,s,o,c=this._tables[0],l=this._tables[1],h=c[4],d=l[4],u=new Uint8Array(256),f=new Uint8Array(256);for(e=0;e<256;e++)f[(u[e]=e<<1^(e>>7)*283)^e]=e;for(t=i=0;0===h[t];t^=0!==r?r:1,i=0!==f[i]?f[i]:1)for(e=0,a=(a=i^i<<1^i<<2^i<<3^i<<4)>>8^255&a^99,h[t]=a,d[a]=t,o=0x1010101*u[n=u[r=u[t]]]^65537*n^257*r^0x1010100*t,s=257*u[a]^0x1010100*a;e<4;e++)c[e][t]=s=s<<24^s>>>8,l[e][a]=o=o<<24^o>>>8},_crypt:function(e,t){let i,r,n,a;if(4!==e.length)throw Error("invalid aes block size");let s=this._key[t],o=e[0]^s[0],c=e[1===t?3:1]^s[1],l=e[2]^s[2],h=e[1===t?1:3]^s[3],d=s.length/4-2,u=4,f=new Uint32Array(4),p=this._tables[t],g=p[0],m=p[1],y=p[2],b=p[3],w=p[4];for(a=0;a<d;a++)i=g[o>>>24]^m[c>>16&255]^y[l>>8&255]^b[255&h]^s[u],r=g[c>>>24]^m[l>>16&255]^y[h>>8&255]^b[255&o]^s[u+1],n=g[l>>>24]^m[h>>16&255]^y[o>>8&255]^b[255&c]^s[u+2],h=g[h>>>24]^m[o>>16&255]^y[c>>8&255]^b[255&l]^s[u+3],u+=4,o=i,c=r,l=n;for(a=0;a<4;a++)f[1===t?3&-a:a]=w[o>>>24]<<24^w[c>>16&255]<<16^w[l>>8&255]<<8^w[255&h]^s[u++],i=o,o=c,c=l,l=h,h=i;return f}};class rb{static encrypt(e,t){let i=rb.buf2Words(t),r=rb.buf2Words(e),n=new ry(i).encrypt(r);return rb.words2Buf(n)}static decrypt(e,t){let i=rb.buf2Words(e),r=new ry(rb.buf2Words(t)).decrypt(i);return rb.words2Buf(r)}static buf2Words(e){if(e.length%4!=0)throw Error("buf length must be a multiple of 4");let t=[];for(let i=0;i<e.length/4;i++){let r=0x1000000*e[4*i]+(e[4*i+1]<<16|e[4*i+2]<<8|e[4*i+3]);t.push(r)}return t}static words2Buf(e){let t=Array(4*e.length);for(let i=0;i<e.length;i++){let r=e[i];t[4*i]=r>>>24&255,t[4*i+1]=r>>>16&255,t[4*i+2]=r>>>8&255,t[4*i+3]=255&r}return t}}class rw{static buf2BlocksBuf(e,t){let i=t/8,r=[];for(let n=0;n<=e.length/i;n++){let a=e.slice(n*i,n*i+i);a.length<t&&(a=rw.pkcs7Pad(a,t)),r.push(a)}return r}static blockBufs2Buf(e){let t=e[e.length-1];return t=rw.pkcs7Unpad(t),e[e.length-1]=t,e.flat()}static encrypt(e,t,i,r){let n=8*t.length,a=rw.buf2BlocksBuf(e,n);return rw.encryptBlocks(a,t,i,r).flat()}static decrypt(e,t,i,r){let n=t.length,a=[];for(let t=0;t<e.length/n;t++)a.push(e.slice(t*n,t*n+n));let s=rw.decryptBlocks(a,t,i,r);return rw.blockBufs2Buf(s)}static encryptBlock(e,t,i,r){let n=rw.xorBufs(e,t);return i.encrypt(n,r)}static decryptBlock(e,t,i,r){let n=i.decrypt(e,r);return rw.xorBufs(n,t)}static encryptBlocks(e,t,i,r){let n=[];for(let a=0;a<e.length;a++){let s=e[a],o=rw.encryptBlock(s,t,i,r);n.push(o),t=o}return n}static decryptBlocks(e,t,i,r){let n=[];for(let a=0;a<e.length;a++){let s=e[a],o=rw.decryptBlock(s,t,i,r);n.push(o),t=s}return n}static pkcs7Pad(e,t){let i=t/8-e.length,r=Array(i);return r.fill(i),[...e,...r]}static pkcs7Unpad(e){let t=e[e.length-1],i=e.slice(e.length-t,e.length),r=Array(t);if(r.fill(t),te(i)!==te(r))throw Error("invalid padding");return e.slice(0,e.length-t)}static xorBufs(e,t){if(e.length!==t.length)throw Error("bufs must have the same length");let i=Array(e.length);for(let r=0;r<e.length;r++)i[r]=e[r]^t[r];return i}}class rv{static encrypt(e,t,i,r=!0){i=i??t0(16);let n=rw.encrypt(e,i,rb,t);return r?[...i,...n]:[...n]}static decrypt(e,t,i){if(null!=i)return rw.decrypt(e,i,rb,t);{i=e.slice(0,16);let r=e.slice(16);return rw.decrypt(r,i,rb,t)}}}class rI{static ivkEkM(e,t){let i=t.mul(e),r=es(new tJ(i.x,i.y).encode(!0));return{iv:r.slice(0,16),kE:r.slice(16,32),kM:r.slice(32,64)}}static electrumEncrypt(e,t,i,r=!1){let n,a=null;null==i&&(i=t3.fromRandom()),r||(a=i.toPublicKey().encode(!0));let{iv:s,kE:o,kM:c}=rI.ivkEkM(i,t),l=rv.encrypt(e,o,s,!1),h=ti("BIE1","utf8"),d=el(c,n=null!=a&&a.length>0?[...h,...a,...l]:[...h,...l]);return[...n,...d]}static electrumDecrypt(e,t,i){if("BIE1"!==to(e.slice(0,4),"utf8"))throw Error("Invalid Magic");let r=4,n=null;if(e.length-r-32>=33){let t=e[r];2===t||3===t?(n=e.slice(r,r+33),r+=33):4===t&&(n=e.slice(r,r+65),r+=65)}if(null!==n)null==i&&(i=tJ.fromString(te(n)));else if(null==i)throw Error("Sender public key is required");let{iv:a,kE:s,kM:o}=rI.ivkEkM(t,i),c=e.slice(r,e.length-32),l=e.slice(e.length-32,e.length),h=el(o,e.slice(0,e.length-32));if(te(l)!==te(h))throw Error("Invalid checksum");return rv.decrypt(c,s,a)}static bitcoreEncrypt(e,t,i,r){null==i&&(i=t3.fromRandom()),null==r&&(r=t0(16));let n=i,a=i.toPublicKey().encode(!0),s=es(t.mul(n).getX().toArray("be",32)),o=s.slice(0,32),c=s.slice(32,64),l=rv.encrypt(e,o,r),h=el(c,[...l]);return[...a,...l,...h]}static bitcoreDecrypt(e,t){let i=tJ.fromString(te(e.slice(0,33))).mul(t);if(i.eq(new tF(0,0)))throw Error("P equals 0");let r=es(i.getX().toArray("be",32)),n=r.slice(0,32),a=r.slice(32,64),s=e.slice(33,e.length-32),o=e.slice(e.length-32,e.length),c=el(a,s);if(te(o)!==te(c))throw Error("Invalid checksum");return[...rv.decrypt(s,n)]}}function rk(e,t){let i=new i3(0,[],[],0);return i.outputs=Array(e.vout+1).fill(null),i.outputs[e.vout]={satoshis:e.satoshis,lockingScript:iT.fromHex(e.script)},{sourceTransaction:i,sourceTXID:e.txid,sourceOutputIndex:e.vout,unlockingScriptTemplate:t,sequence:0xffffffff}}class rS{static generate(e,t){let i=this.withDefaultOptions(t);return rE(e,this.getCounter(i.timestamp,i.period),i)}static validate(e,t,i){let r=this.withDefaultValidateOptions(i);if((t=t.trim()).length!==r.digits)return!1;let n=this.getCounter(r.timestamp,r.period),a=[n];for(let e=1;e<=r.skew;e++)a.push(n+e),a.push(n-e);for(let i of a){let n=rE(e,i,r);if(tv(ti(t,"utf8"),ti(n,"utf8")))return!0}return!1}static getCounter(e,t){return Math.floor(Math.floor(e/1e3)/t)}static withDefaultOptions(e){return{digits:2,algorithm:"SHA-1",period:30,timestamp:Date.now(),...e}}static withDefaultValidateOptions(e){return{skew:1,...this.withDefaultOptions(e)}}}function rE(e,t,i){let r=(function(e,t,i){switch(i){case"SHA-1":return new et(e).update(t);case"SHA-256":return new ee(e).update(t);case"SHA-512":return new ei(e).update(t);default:throw Error("unsupported HMAC algorithm")}})(e,new P(t).toArray("be",8),i.algorithm).digest(),n=15&r[r.length-1];return(0x7fffffff&new P(r.slice(n,n+4)).toNumber()).toString().slice(-i.digits)}(s=h||(h={}))[s.Silent=0]="Silent",s[s.App=1]="App",s[s.Counterparty=2]="Counterparty";class rx{cacheSharedSecret;retrieveCachedSharedSecret;rootKey;identityKey;anyone;constructor(e,t,i){this.cacheSharedSecret=t,this.retrieveCachedSharedSecret=i,this.anyone=new t3(1).toPublicKey(),"anyone"===e?this.rootKey=new t3(1):this.rootKey=e,this.identityKey=this.rootKey.toPublicKey().toString()}derivePublicKey(e,t,i,r=!1){return(i=this.normalizeCounterparty(i),r)?this.rootKey.deriveChild(i,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret).toPublicKey():i.deriveChild(this.rootKey,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}derivePrivateKey(e,t,i){return i=this.normalizeCounterparty(i),this.rootKey.deriveChild(i,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}deriveSymmetricKey(e,t,i){i="anyone"===i?this.anyone:this.normalizeCounterparty(i);let r=this.derivePublicKey(e,t,i),n=this.derivePrivateKey(e,t,i);return new ip(n.deriveSharedSecret(r)?.x?.toArray()??[])}revealCounterpartySecret(e){if("self"===e)throw Error("Counterparty secrets cannot be revealed for counterparty=self.");e=this.normalizeCounterparty(e);let t=this.rootKey.toPublicKey();if(this.rootKey.deriveChild(t,"test").toHex()===this.rootKey.deriveChild(e,"test").toHex())throw Error("Counterparty secrets cannot be revealed for counterparty=self.");return this.rootKey.deriveSharedSecret(e).encode(!0)}revealSpecificSecret(e,t,i){e=this.normalizeCounterparty(e);let r=this.rootKey.deriveSharedSecret(e),n=ti(this.computeInvoiceNumber(t,i),"utf8");return el(r.encode(!0),n)}normalizeCounterparty(e){if(null==e)throw Error("counterparty must be self, anyone or a public key!");return"self"===e?this.rootKey.toPublicKey():"anyone"===e?new t3(1).toPublicKey():"string"==typeof e?tJ.fromString(e):e}computeInvoiceNumber(e,t){let i=e[0];if(!Number.isInteger(i)||i<0||i>2)throw Error("Protocol security level must be 0, 1, or 2");let r=e[1].toLowerCase().trim();if(t.length>800)throw Error("Key IDs must be 800 characters or less");if(t.length<1)throw Error("Key IDs must be 1 character or more");if(r.length>400)if(r.startsWith("specific linkage revelation ")){if(r.length>430)throw Error("Specific linkage revelation protocol names must be 430 characters or less")}else throw Error("Protocol names must be 400 characters or less");if(r.length<5)throw Error("Protocol names must be 5 characters or more");if(r.includes(" "))throw Error('Protocol names cannot contain multiple consecutive spaces (" ")');if(!/^[a-z0-9 ]+$/g.test(r))throw Error("Protocol names can only contain letters, numbers and spaces");if(r.endsWith(" protocol"))throw Error('No need to end your protocol name with " protocol"');return`${i}-${r}-${t}`}}class rP{keyDeriver;cache;maxCacheSize;rootKey;identityKey;constructor(e,t){"anyone"===e?this.rootKey=new t3(1):this.rootKey=e,this.keyDeriver=new rx(this.rootKey,(e,t,i)=>{this.cacheSet(`${e.toString()}-${t.toString()}`,i)},(e,t)=>this.cacheGet(`${e.toString()}-${t.toString()}`)),this.identityKey=this.rootKey.toPublicKey().toString(),this.cache=new Map;const i=t?.maxCacheSize;this.maxCacheSize=null!=i&&!isNaN(i)&&i>0?i:1e3}derivePublicKey(e,t,i,r=!1){let n=this.generateCacheKey("derivePublicKey",e,t,i,r);if(this.cache.has(n)){let e=this.cacheGet(n);if(void 0===e)throw Error("Cached value is undefined");return e}{let a=this.keyDeriver.derivePublicKey(e,t,i,r);return this.cacheSet(n,a),a}}derivePrivateKey(e,t,i){let r=this.generateCacheKey("derivePrivateKey",e,t,i);if(this.cache.has(r)){let e=this.cacheGet(r);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.derivePrivateKey(e,t,i);return this.cacheSet(r,n),n}}deriveSymmetricKey(e,t,i){let r=this.generateCacheKey("deriveSymmetricKey",e,t,i);if(this.cache.has(r)){let e=this.cacheGet(r);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.deriveSymmetricKey(e,t,i);return this.cacheSet(r,n),n}}revealCounterpartySecret(e){let t=this.generateCacheKey("revealCounterpartySecret",e);if(this.cache.has(t)){let e=this.cacheGet(t);if(void 0===e)throw Error("Cached value is undefined");return e}{let i=this.keyDeriver.revealCounterpartySecret(e);return this.cacheSet(t,i),i}}revealSpecificSecret(e,t,i){let r=this.generateCacheKey("revealSpecificSecret",e,t,i);if(this.cache.has(r)){let e=this.cacheGet(r);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.revealSpecificSecret(e,t,i);return this.cacheSet(r,n),n}}generateCacheKey(e,...t){let i=t.map(e=>this.serializeArgument(e)).join("|");return`${e}|${i}`}serializeArgument(e){return e instanceof tJ||e instanceof t3?e.toString():Array.isArray(e)?e.map(e=>this.serializeArgument(e)).join(","):"object"==typeof e&&null!==e?JSON.stringify(e):String(e)}cacheGet(e){let t=this.cache.get(e);return this.cache.delete(e),void 0!==t&&this.cache.set(e,t),t}cacheSet(e,t){if(this.cache.size>=this.maxCacheSize){let e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(e,t)}}class rA{keyDeriver;constructor(e){"string"!=typeof e.identityKey&&(e=new rP(e)),this.keyDeriver=e}async getPublicKey(e){if(e.identityKey){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==e.protocolID||null==e.keyID||""===e.keyID)throw Error("protocolID and keyID are required if identityKey is false or undefined.");return{publicKey:(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf).toString()}}async revealCounterpartyKeyLinkage(e){let{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let i=this.keyDeriver.revealCounterpartySecret(e.counterparty),r=new iI().generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),tJ.fromString(e.counterparty),tF.fromDER(i)),n=[...r.R.encode(!0),...r.SPrime.encode(!0),...r.z.toArray()],a=new Date().toISOString(),{ciphertext:s}=await this.encrypt({plaintext:i,protocolID:[2,"counterparty linkage revelation"],keyID:a,counterparty:e.verifier}),{ciphertext:o}=await this.encrypt({plaintext:n,protocolID:[2,"counterparty linkage revelation"],keyID:a,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,revelationTime:a,encryptedLinkage:s,encryptedLinkageProof:o}}async revealSpecificKeyLinkage(e){let{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let i=this.keyDeriver.revealSpecificSecret(e.counterparty,e.protocolID,e.keyID),{ciphertext:r}=await this.encrypt({plaintext:i,protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier}),{ciphertext:n}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,protocolID:e.protocolID,keyID:e.keyID,encryptedLinkage:r,encryptedLinkageProof:n,proofType:0}}async encrypt(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{ciphertext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").encrypt(e.plaintext)}}async decrypt(e,t){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{plaintext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").decrypt(e.ciphertext)}}async createHmac(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{hmac:el(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data)}}async verifyHmac(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let t=el(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data),i=e.hmac,r=tv(ti(t),ti(i));if(!r){let e=Error("HMAC is not valid");throw e.code="ERR_INVALID_HMAC",e}return{valid:r}}async createSignature(e){if(null==e.hashToDirectlySign&&null==e.data)throw Error("args.data or args.hashToDirectlySign must be valid");let t=e.hashToDirectlySign??ea(e.data??[]),i=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePrivateKey(e.protocolID,e.keyID,e.counterparty??"anyone");return{signature:tG(new P(t),i,!0).toDER()}}async verifySignature(e){if(null==e.hashToDirectlyVerify&&null==e.data)throw Error("args.data or args.hashToDirectlyVerify must be valid");let t=e.hashToDirectlyVerify??ea(e.data??[]),i=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf),r=tY(new P(t),tK.fromDER(e.signature),i);if(!r){let e=Error("Signature is not valid");throw e.code="ERR_INVALID_SIGNATURE",e}return{valid:r}}}let rN=rA;class rO{CWI;constructor(){if("object"!=typeof window)throw Error("The window.CWI substrate requires a global window object.");if("object"!=typeof window.CWI)throw 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 rT extends Error{code;isError=!0;constructor(e,t=1,i){super(e),this.code=t,this.name=this.constructor.name,null!=i&&""!==i?this.stack=i:Error.captureStackTrace(this,this.constructor)}static unknownToJson(e){let t;return!0===e.isError&&String(e.name).startsWith("WERR_")?"WERR_REVIEW_ACTIONS"===(t={name:e.name,message:e.message,isError:!0}).name?(t.reviewActionResults=e.reviewActionResults,t.sendWithResults=e.sendWithResults,t.txid=e.txid,t.tx=e.tx,t.noSendChange=e.noSendChange,t.code=5):"WERR_INVALID_PARAMETER"===t.name?(t.parameter=e.parameter,t.code=6):"WERR_INSUFFICIENT_FUNDS"===t.name&&(t.totalSatoshisNeeded=e.totalSatoshisNeeded,t.moreSatoshisNeeded=e.moreSatoshisNeeded,t.code=7):t=e instanceof Error?{name:e.constructor.name,message:e.message,isError:!0}:{name:"WERR_UNKNOWN",message:String(e),isError:!0},JSON.stringify(t)}}(o=d||(d={}))[o.unknownError=1]="unknownError",o[o.unsupportedAction=2]="unsupportedAction",o[o.invalidHmac=3]="invalidHmac",o[o.invalidSignature=4]="invalidSignature",o[o.reviewActions=5]="reviewActions",o[o.invalidParameter=6]="invalidParameter",o[o.insufficientFunds=7]="insufficientFunds";let r_=rT;class rR{domain;constructor(e="*"){if("object"!=typeof window)throw Error("The XDM substrate requires a global window object.");if("function"!=typeof window.postMessage)throw Error("The window object does not seem to support postMessage calls.");this.domain=e}async invoke(e,t){return await new Promise((i,r)=>{let n=tc(t0(12)),a=e=>{"CWI"===e.data.type&&e.isTrusted&&e.data.id===n&&!0!==e.data.isInvocation&&("function"==typeof window.removeEventListener&&window.removeEventListener("message",a),"error"===e.data.status?r(new rT(e.data.description,e.data.code)):i(e.data.result))};window.addEventListener("message",a),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 rC{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(e,t,i,r,n,a,s){this.type=e,this.serialNumber=t,this.subject=i,this.certifier=r,this.revocationOutpoint=n,this.fields=a,this.signature=s}toBinary(e=!0){let t=new tp,i=ti(this.type,"base64");t.write(i);let r=ti(this.serialNumber,"base64");t.write(r);let n=ti(this.subject,"hex");t.write(n);let a=ti(this.certifier,"hex");t.write(a);let[s,o]=this.revocationOutpoint.split("."),c=ti(s,"hex");t.write(c),t.writeVarIntNum(Number(o));let l=Object.keys(this.fields).sort();for(let e of(t.writeVarIntNum(l.length),l)){let i=this.fields[e],r=ti(e,"utf8");t.writeVarIntNum(r.length),t.write(r);let n=ti(i,"utf8");t.writeVarIntNum(n.length),t.write(n)}if(e&&(this.signature??"").length>0){let e=ti(this.signature,"hex");t.write(e)}return t.toArray()}static fromBinary(e){let t,i=new tg(e),r=tc(i.read(32)),n=tc(i.read(32)),a=te(i.read(33)),s=te(i.read(33)),o=te(i.read(32)),c=i.readVarIntNum(),l=`${o}.${c}`,h=i.readVarIntNum(),d={};for(let e=0;e<h;e++){let e=i.readVarIntNum(),t=ts(i.read(e)),r=i.readVarIntNum(),n=ts(i.read(r));d[t]=n}if(!i.eof()){let e=i.read();t=tK.fromDER(e).toString("hex")}return new rC(r,n,a,s,l,d,t)}async verify(){let e=new rN("anyone"),t=this.toBinary(!1),i=this.signature??"",{valid:r}=await e.verifySignature({signature:ti(i,"hex"),data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`,counterparty:this.certifier});return r}async sign(e){if(null!=this.signature&&this.signature.length>0)throw Error(`Certificate has already been signed! Signature present: ${this.signature}`);this.certifier=(await e.getPublicKey({identityKey:!0})).publicKey;let t=this.toBinary(!1),{signature:i}=await e.createSignature({data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`});this.signature=te(i)}static getCertificateFieldEncryptionDetails(e,t){return{protocolID:[2,"certificate field encryption"],keyID:t?`${t} ${e}`:e}}static fromObject(e){return new rC(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature)}}(c=u||(u={}))[c.createAction=1]="createAction",c[c.signAction=2]="signAction",c[c.abortAction=3]="abortAction",c[c.listActions=4]="listActions",c[c.internalizeAction=5]="internalizeAction",c[c.listOutputs=6]="listOutputs",c[c.relinquishOutput=7]="relinquishOutput",c[c.getPublicKey=8]="getPublicKey",c[c.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",c[c.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",c[c.encrypt=11]="encrypt",c[c.decrypt=12]="decrypt",c[c.createHmac=13]="createHmac",c[c.verifyHmac=14]="verifyHmac",c[c.createSignature=15]="createSignature",c[c.verifySignature=16]="verifySignature",c[c.acquireCertificate=17]="acquireCertificate",c[c.listCertificates=18]="listCertificates",c[c.proveCertificate=19]="proveCertificate",c[c.relinquishCertificate=20]="relinquishCertificate",c[c.discoverByIdentityKey=21]="discoverByIdentityKey",c[c.discoverByAttributes=22]="discoverByAttributes",c[c.isAuthenticated=23]="isAuthenticated",c[c.waitForAuthentication=24]="waitForAuthentication",c[c.getHeight=25]="getHeight",c[c.getHeaderForHeight=26]="getHeaderForHeight",c[c.getNetwork=27]="getNetwork",c[c.getVersion=28]="getVersion";let rB=u;class rU{wire;constructor(e){this.wire=e}async transmit(e,t="",i=[]){let r=new tp;r.writeUInt8(rB[e]);let n=ti(t,"utf8");r.writeUInt8(n.length),r.write(n),i.length>0&&r.write(i);let a=r.toArray(),s=new tg(await this.wire.transmitToWallet(a)),o=s.readUInt8();if(0===o)return s.read();{let e=s.readVarIntNum(),t=ts(s.read(e)),i=s.readVarIntNum();throw new rT(t,o,ts(s.read(i)))}}async createAction(e,t){let i=new tp,r=ti(e.description,"utf8");if(i.writeVarIntNum(r.length),i.write(r),null!=e.inputBEEF?(i.writeVarIntNum(e.inputBEEF.length),i.write(e.inputBEEF)):i.writeVarIntNum(-1),null!=e.inputs)for(let t of(i.writeVarIntNum(e.inputs.length),e.inputs)){if(i.write(this.encodeOutpoint(t.outpoint)),null!=t.unlockingScript&&""!==t.unlockingScript){let e=ti(t.unlockingScript,"hex");i.writeVarIntNum(e.length),i.write(e)}else i.writeVarIntNum(-1),i.writeVarIntNum(t.unlockingScriptLength??0);let e=ti(t.inputDescription,"utf8");i.writeVarIntNum(e.length),i.write(e),"number"==typeof t.sequenceNumber?i.writeVarIntNum(t.sequenceNumber):i.writeVarIntNum(-1)}else i.writeVarIntNum(-1);if(null!=e.outputs)for(let t of(i.writeVarIntNum(e.outputs.length),e.outputs)){let e=ti(t.lockingScript,"hex");i.writeVarIntNum(e.length),i.write(e),i.writeVarIntNum(t.satoshis);let r=ti(t.outputDescription,"utf8");if(i.writeVarIntNum(r.length),i.write(r),null!=t.basket&&""!==t.basket){let e=ti(t.basket,"utf8");i.writeVarIntNum(e.length),i.write(e)}else i.writeVarIntNum(-1);if(null!=t.customInstructions&&""!==t.customInstructions){let e=ti(t.customInstructions,"utf8");i.writeVarIntNum(e.length),i.write(e)}else i.writeVarIntNum(-1);if(null!=t.tags)for(let e of(i.writeVarIntNum(t.tags.length),t.tags)){let t=ti(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(-1)}else i.writeVarIntNum(-1);if("number"==typeof e.lockTime?i.writeVarIntNum(e.lockTime):i.writeVarIntNum(-1),"number"==typeof e.version?i.writeVarIntNum(e.version):i.writeVarIntNum(-1),null!=e.labels)for(let t of(i.writeVarIntNum(e.labels.length),e.labels)){let e=ti(t,"utf8");i.writeVarIntNum(e.length),i.write(e)}else i.writeVarIntNum(-1);if(null!=e.options){if(i.writeInt8(1),"boolean"==typeof e.options.signAndProcess?i.writeInt8(+!!e.options.signAndProcess):i.writeInt8(-1),"boolean"==typeof e.options.acceptDelayedBroadcast?i.writeInt8(+!!e.options.acceptDelayedBroadcast):i.writeInt8(-1),"known"===e.options.trustSelf?i.writeInt8(1):i.writeInt8(-1),null!=e.options.knownTxids)for(let t of(i.writeVarIntNum(e.options.knownTxids.length),e.options.knownTxids)){let e=ti(t,"hex");i.write(e)}else i.writeVarIntNum(-1);if("boolean"==typeof e.options.returnTXIDOnly?i.writeInt8(+!!e.options.returnTXIDOnly):i.writeInt8(-1),"boolean"==typeof e.options.noSend?i.writeInt8(+!!e.options.noSend):i.writeInt8(-1),null!=e.options.noSendChange)for(let t of(i.writeVarIntNum(e.options.noSendChange.length),e.options.noSendChange))i.write(this.encodeOutpoint(t));else i.writeVarIntNum(-1);if(null!=e.options.sendWith)for(let t of(i.writeVarIntNum(e.options.sendWith.length),e.options.sendWith)){let e=ti(t,"hex");i.write(e)}else i.writeVarIntNum(-1);"boolean"==typeof e.options.randomizeOutputs?i.writeInt8(+!!e.options.randomizeOutputs):i.writeInt8(-1)}else i.writeInt8(0);let n=new tg(await this.transmit("createAction",t,i.toArray())),a={};if(1===n.readInt8()&&(a.txid=te(n.read(32))),1===n.readInt8()){let e=n.readVarIntNum();a.tx=n.read(e)}let s=n.readVarIntNum();if(s>=0){a.noSendChange=[];for(let e=0;e<s;e++){let e=this.readOutpoint(n);a.noSendChange.push(e)}}let o=n.readVarIntNum();if(o>=0){a.sendWithResults=[];for(let e=0;e<o;e++){let e=te(n.read(32)),t=n.readInt8(),i="unproven";1===t?i="unproven":2===t?i="sending":3===t&&(i="failed"),a.sendWithResults.push({txid:e,status:i})}}if(1===n.readInt8()){let e=n.readVarIntNum(),t=n.read(e),i=n.readVarIntNum();a.signableTransaction={tx:t,reference:tc(n.read(i))}}return a}async signAction(e,t){let i=new tp,r=Object.keys(e.spends);for(let t of(i.writeVarIntNum(r.length),r)){i.writeVarIntNum(Number(t));let r=e.spends[Number(t)],n=ti(r.unlockingScript,"hex");i.writeVarIntNum(n.length),i.write(n),"number"==typeof r.sequenceNumber?i.writeVarIntNum(r.sequenceNumber):i.writeVarIntNum(-1)}let n=ti(e.reference,"base64");if(i.writeVarIntNum(n.length),i.write(n),null!=e.options)if(i.writeInt8(1),"boolean"==typeof e.options.acceptDelayedBroadcast?i.writeInt8(+!!e.options.acceptDelayedBroadcast):i.writeInt8(-1),"boolean"==typeof e.options.returnTXIDOnly?i.writeInt8(+!!e.options.returnTXIDOnly):i.writeInt8(-1),"boolean"==typeof e.options.noSend?i.writeInt8(+!!e.options.noSend):i.writeInt8(-1),null!=e.options.sendWith)for(let t of(i.writeVarIntNum(e.options.sendWith.length),e.options.sendWith)){let e=ti(t,"hex");i.write(e)}else i.writeVarIntNum(-1);else i.writeInt8(0);let a=new tg(await this.transmit("signAction",t,i.toArray())),s={};if(1===a.readInt8()&&(s.txid=te(a.read(32))),1===a.readInt8()){let e=a.readVarIntNum();s.tx=a.read(e)}let o=a.readVarIntNum();if(o>=0){s.sendWithResults=[];for(let e=0;e<o;e++){let e=te(a.read(32)),t=a.readInt8(),i="unproven";1===t?i="unproven":2===t?i="sending":3===t&&(i="failed"),s.sendWithResults.push({txid:e,status:i})}}return s}async abortAction(e,t){return await this.transmit("abortAction",t,ti(e.reference,"base64")),{aborted:!0}}async listActions(e,t){let i=new tp;for(let t of(i.writeVarIntNum(e.labels.length),e.labels)){let e=ti(t,"utf8");i.writeVarIntNum(e.length),i.write(e)}for(let t of("any"===e.labelQueryMode?i.writeInt8(1):"all"===e.labelQueryMode?i.writeInt8(2):i.writeInt8(-1),[e.includeLabels,e.includeInputs,e.includeInputSourceLockingScripts,e.includeInputUnlockingScripts,e.includeOutputs,e.includeOutputLockingScripts]))"boolean"==typeof t?i.writeInt8(+!!t):i.writeInt8(-1);"number"==typeof e.limit?i.writeVarIntNum(e.limit):i.writeVarIntNum(-1),"number"==typeof e.offset?i.writeVarIntNum(e.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1);let r=new tg(await this.transmit("listActions",t,i.toArray())),n=r.readVarIntNum(),a=[];for(let e=0;e<n;e++){let e,t=te(r.read(32)),i=r.readVarIntNum(),n=r.readInt8();switch(n){case 1:e="completed";break;case 2:e="unprocessed";break;case 3:e="sending";break;case 4:e="unproven";break;case 5:e="unsigned";break;case 6:e="nosend";break;case 7:e="nonfinal";break;case 8:e="failed";break;default:throw Error(`Unknown status code: ${n}`)}let s=1===r.readInt8(),o=r.readVarIntNum(),c={txid:t,satoshis:i,status:e,isOutgoing:s,description:ts(r.read(o)),version:0,lockTime:0},l=r.readVarIntNum();if(l>=0){c.labels=[];for(let e=0;e<l;e++){let e=r.readVarIntNum(),t=r.read(e);c.labels.push(ts(t))}}c.version=r.readVarIntNum(),c.lockTime=r.readVarIntNum();let h=r.readVarIntNum();if(h>=0){c.inputs=[];for(let e=0;e<h;e++){let e,t,i=this.readOutpoint(r),n=r.readVarIntNum(),a=r.readVarIntNum();a>=0&&(e=te(r.read(a)));let s=r.readVarIntNum();s>=0&&(t=te(r.read(s)));let o=r.readVarIntNum(),l=ts(r.read(o)),h=r.readVarIntNum();c.inputs.push({sourceOutpoint:i,sourceSatoshis:n,sourceLockingScript:e,unlockingScript:t,inputDescription:l,sequenceNumber:h})}}let d=r.readVarIntNum();if(d>=0){c.outputs=[];for(let e=0;e<d;e++){let e,t,i,n=r.readVarIntNum(),a=r.readVarIntNum(),s=r.readVarIntNum();s>=0&&(e=te(r.read(s)));let o=1===r.readInt8(),l=r.readVarIntNum(),h=ts(r.read(l)),d=r.readVarIntNum();d>=0&&(t=ts(r.read(d)));let u=r.readVarIntNum(),f=[];if(u>=0)for(let e=0;e<u;e++){let e=r.readVarIntNum(),t=r.read(e);f.push(ts(t))}let p=r.readVarIntNum();p>=0&&(i=ts(r.read(p))),c.outputs.push({outputIndex:n,satoshis:a,lockingScript:e,spendable:o,outputDescription:h,basket:t,tags:f,customInstructions:i})}}a.push(c)}return{totalActions:n,actions:a}}async internalizeAction(e,t){let i=new tp;for(let t of(i.writeVarIntNum(e.tx.length),i.write(e.tx),i.writeVarIntNum(e.outputs.length),e.outputs))if(i.writeVarIntNum(t.outputIndex),"wallet payment"===t.protocol){if(null==t.paymentRemittance)throw Error("Payment remittance is required for wallet payment");i.writeUInt8(1),i.write(ti(t.paymentRemittance.senderIdentityKey,"hex"));let e=ti(t.paymentRemittance.derivationPrefix,"base64");i.writeVarIntNum(e.length),i.write(e);let r=ti(t.paymentRemittance.derivationSuffix,"base64");i.writeVarIntNum(r.length),i.write(r)}else{i.writeUInt8(2);let e=ti(t.insertionRemittance?.basket,"utf8");if(i.writeVarIntNum(e.length),i.write(e),"string"==typeof t.insertionRemittance?.customInstructions&&""!==t.insertionRemittance.customInstructions){let e=ti(t.insertionRemittance.customInstructions,"utf8");i.writeVarIntNum(e.length),i.write(e)}else i.writeVarIntNum(-1);if("object"==typeof t.insertionRemittance?.tags)for(let e of(i.writeVarIntNum(t.insertionRemittance.tags.length),t.insertionRemittance.tags)){let t=ti(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(0)}if("object"==typeof e.labels)for(let t of(i.writeVarIntNum(e.labels.length),e.labels)){let e=ti(t,"utf8");i.writeVarIntNum(e.length),i.write(e)}else i.writeVarIntNum(-1);let r=ti(e.description);return i.writeVarIntNum(r.length),i.write(r),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),await this.transmit("internalizeAction",t,i.toArray()),{accepted:!0}}async listOutputs(e,t){let i,r=new tp,n=ti(e.basket,"utf8");if(r.writeVarIntNum(n.length),r.write(n),"object"==typeof e.tags)for(let t of(r.writeVarIntNum(e.tags.length),e.tags)){let e=ti(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):r.writeInt8(-1),"boolean"==typeof e.includeTags?r.writeInt8(+!!e.includeTags):r.writeInt8(-1),"boolean"==typeof e.includeLabels?r.writeInt8(+!!e.includeLabels):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);let a=new tg(await this.transmit("listOutputs",t,r.toArray())),s=a.readVarIntNum(),o=a.readVarIntNum();o>=0&&(i=a.read(o));let c=[];for(let e=0;e<s;e++){let e={spendable:!0,outpoint:this.readOutpoint(a),satoshis:a.readVarIntNum()},t=a.readVarIntNum();t>=0&&(e.lockingScript=te(a.read(t)));let i=a.readVarIntNum();i>=0&&(e.customInstructions=ts(a.read(i)));let r=a.readVarIntNum();if(-1!==r){let t=[];for(let e=0;e<r;e++){let e=a.readVarIntNum();t.push(ts(a.read(e)))}e.tags=t}let n=a.readVarIntNum();if(-1!==n){let t=[];for(let e=0;e<n;e++){let e=a.readVarIntNum();t.push(ts(a.read(e)))}e.labels=t}c.push(e)}return{totalOutputs:s,BEEF:i,outputs:c}}async relinquishOutput(e,t){let i=new tp,r=ti(e.basket,"utf8");return i.writeVarIntNum(r.length),i.write(r),i.write(this.encodeOutpoint(e.output)),await this.transmit("relinquishOutput",t,i.toArray()),{relinquished:!0}}encodeOutpoint(e){let t=new tp,[i,r]=e.split(".");return t.write(ti(i,"hex")),t.writeVarIntNum(Number(r)),t.toArray()}readOutpoint(e){let t=te(e.read(32)),i=e.readVarIntNum();return`${t}.${i}`}async getPublicKey(e,t){let i=new tp;return i.writeUInt8(+!!e.identityKey),e.identityKey?i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)):(i.write(this.encodeKeyRelatedParams(e.protocolID??=[h.Silent,"default"],e.keyID??="",e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?i.writeInt8(+!!e.forSelf):i.writeInt8(-1)),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{publicKey:te(await this.transmit("getPublicKey",t,i.toArray()))}}async revealCounterpartyKeyLinkage(e,t){let i=new tp;i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),i.write(ti(e.counterparty,"hex")),i.write(ti(e.verifier,"hex"));let r=new tg(await this.transmit("revealCounterpartyKeyLinkage",t,i.toArray())),n=te(r.read(33)),a=te(r.read(33)),s=te(r.read(33)),o=r.readVarIntNum(),c=ts(r.read(o)),l=r.readVarIntNum(),h=r.read(l),d=r.readVarIntNum();return{prover:n,verifier:a,counterparty:s,revelationTime:c,encryptedLinkage:h,encryptedLinkageProof:r.read(d)}}async revealSpecificKeyLinkage(e,t){let i=new tp;i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.write(ti(e.verifier,"hex"));let r=new tg(await this.transmit("revealSpecificKeyLinkage",t,i.toArray())),n=te(r.read(33)),a=te(r.read(33)),s=te(r.read(33)),o=r.readUInt8(),c=r.readVarIntNum(),l=ts(r.read(c)),h=r.readVarIntNum(),d=ts(r.read(h)),u=r.readVarIntNum(),f=r.read(u),p=r.readVarIntNum();return{prover:n,verifier:a,counterparty:s,protocolID:[o,l],keyID:d,encryptedLinkage:f,encryptedLinkageProof:r.read(p),proofType:r.readUInt8()}}async encrypt(e,t){let i=new tp;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.writeVarIntNum(e.plaintext.length),i.write(e.plaintext),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{ciphertext:await this.transmit("encrypt",t,i.toArray())}}async decrypt(e,t){let i=new tp;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.writeVarIntNum(e.ciphertext.length),i.write(e.ciphertext),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{plaintext:await this.transmit("decrypt",t,i.toArray())}}async createHmac(e,t){let i=new tp;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.writeVarIntNum(e.data.length),i.write(e.data),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{hmac:await this.transmit("createHmac",t,i.toArray())}}async verifyHmac(e,t){let i=new tp;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.write(e.hmac),i.writeVarIntNum(e.data.length),i.write(e.data),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),await this.transmit("verifyHmac",t,i.toArray()),{valid:!0}}async createSignature(e,t){let i=new tp;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"object"==typeof e.data?(i.writeUInt8(1),i.writeVarIntNum(e.data.length),i.write(e.data)):(i.writeUInt8(2),i.write(e.hashToDirectlySign??=[])),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{signature:await this.transmit("createSignature",t,i.toArray())}}async verifySignature(e,t){let i=new tp;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?i.writeInt8(+!!e.forSelf):i.writeInt8(-1),i.writeVarIntNum(e.signature.length),i.write(e.signature),"object"==typeof e.data?(i.writeUInt8(1),i.writeVarIntNum(e.data.length),i.write(e.data)):(i.writeUInt8(2),i.write(e.hashToDirectlyVerify??[])),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),await this.transmit("verifySignature",t,i.toArray()),{valid:!0}}encodeKeyRelatedParams(e,t,i,r,n){let a=new tp;a.writeUInt8(e[0]);let s=ti(e[1],"utf8");a.writeVarIntNum(s.length),a.write(s);let o=ti(t,"utf8");return a.writeVarIntNum(o.length),a.write(o),"string"!=typeof i?a.writeUInt8(0):"self"===i?a.writeUInt8(11):"anyone"===i?a.writeUInt8(12):a.write(ti(i,"hex")),a.write(this.encodePrivilegedParams(r,n)),a.toArray()}async acquireCertificate(e,t){let i=new tp;i.write(ti(e.type,"base64")),i.write(ti(e.certifier,"hex"));let r=Object.entries(e.fields);for(let[e,t]of(i.writeVarIntNum(r.length),r)){let r=ti(e,"utf8"),n=ti(t,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(n.length),i.write(n)}if(i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),i.writeUInt8("direct"===e.acquisitionProtocol?1:2),"direct"===e.acquisitionProtocol){i.write(ti(e.serialNumber,"base64")),i.write(this.encodeOutpoint(e.revocationOutpoint??""));let t=ti(e.signature,"hex");i.writeVarIntNum(t.length),i.write(t);let r="certifier"!==e.keyringRevealer?ti(e.keyringRevealer,"hex"):[11];i.write(r);let n=Object.keys(e.keyringForSubject??{});i.writeVarIntNum(n.length);for(let t=0;t<n.length;t++){let r=ti(n[t],"utf8");i.writeVarIntNum(r.length),i.write(r);let a=ti(e.keyringForSubject?.[n[t]],"base64");i.writeVarIntNum(a.length),i.write(a)}}else{let t=ti(e.certifierUrl,"utf8");i.writeVarIntNum(t.length),i.write(t)}let n=await this.transmit("acquireCertificate",t,i.toArray()),a=rC.fromBinary(n);return{...a,signature:a.signature}}encodePrivilegedParams(e,t){let i=new tp;if("boolean"==typeof e?i.writeInt8(+!!e):i.writeInt8(-1),"string"==typeof t){let e=ti(t,"utf8");i.writeInt8(e.length),i.write(e)}else i.writeInt8(-1);return i.toArray()}async listCertificates(e,t){let i=new tp;i.writeVarIntNum(e.certifiers.length);for(let t=0;t<e.certifiers.length;t++)i.write(ti(e.certifiers[t],"hex"));i.writeVarIntNum(e.types.length);for(let t=0;t<e.types.length;t++)i.write(ti(e.types[t],"base64"));"number"==typeof e.limit?i.writeVarIntNum(e.limit):i.writeVarIntNum(-1),"number"==typeof e.offset?i.writeVarIntNum(e.offset):i.writeVarIntNum(-1),i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let r=new tg(await this.transmit("listCertificates",t,i.toArray())),n=r.readVarIntNum(),a=[];for(let e=0;e<n;e++){let e,t=r.readVarIntNum(),i=r.read(t),n=rC.fromBinary(i),s={};if(1===r.readInt8()){let e=r.readVarIntNum();for(let t=0;t<e;t++){let e=r.readVarIntNum(),t=ts(r.read(e)),i=r.readVarIntNum();s[t]=tc(r.read(i))}}let o=r.readVarIntNum();o>0&&(e=ts(r.read(o))),a.push({...n,signature:n.signature,keyring:s,verifier:e})}return{totalCertificates:n,certificates:a}}async proveCertificate(e,t){let i=new tp,r=ti(e.certificate.type,"base64");i.write(r);let n=ti(e.certificate.subject,"hex");i.write(n);let a=ti(e.certificate.serialNumber,"base64");i.write(a);let s=ti(e.certificate.certifier,"hex");i.write(s);let o=this.encodeOutpoint(e.certificate.revocationOutpoint??"");i.write(o);let c=ti(e.certificate.signature,"hex");i.writeVarIntNum(c.length),i.write(c);let l=Object.entries(e.certificate.fields??{});for(let[e,t]of(i.writeVarIntNum(l.length),l)){let r=ti(e,"utf8"),n=ti(t,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(n.length),i.write(n)}for(let t of(i.writeVarIntNum(e.fieldsToReveal.length),e.fieldsToReveal)){let e=ti(t,"utf8");i.writeVarIntNum(e.length),i.write(e)}i.write(ti(e.verifier,"hex")),i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let h=new tg(await this.transmit("proveCertificate",t,i.toArray())),d=h.readVarIntNum(),u={};for(let e=0;e<d;e++){let e=h.readVarIntNum(),t=ts(h.read(e)),i=h.readVarIntNum();u[t]=tc(h.read(i))}return{keyringForVerifier:u}}async relinquishCertificate(e,t){let i=new tp,r=ti(e.type,"base64");i.write(r);let n=ti(e.serialNumber,"base64");i.write(n);let a=ti(e.certifier,"hex");return i.write(a),await this.transmit("relinquishCertificate",t,i.toArray()),{relinquished:!0}}parseDiscoveryResult(e){let t=new tg(e),i=t.readVarIntNum(),r=[];for(let e=0;e<i;e++){let e=t.readVarIntNum(),i=t.read(e),n=rC.fromBinary(i),a=t.readVarIntNum(),s=ts(t.read(a)),o=t.readVarIntNum(),c=ts(t.read(o)),l=t.readVarIntNum(),h=ts(t.read(l)),d=t.readUInt8(),u={},f=t.readVarIntNum();for(let e=0;e<f;e++){let e=t.readVarIntNum(),i=ts(t.read(e)),r=t.readVarIntNum();u[i]=t.read(r)}let p={},g=t.readVarIntNum();for(let e=0;e<g;e++){let e=t.readVarIntNum(),i=ts(t.read(e)),r=t.readVarIntNum();p[i]=ts(t.read(r))}r.push({...n,signature:n.signature,certifierInfo:{iconUrl:c,name:s,description:h,trust:d},publiclyRevealedKeyring:u,decryptedFields:p})}return{totalCertificates:i,certificates:r}}async discoverByIdentityKey(e,t){let i=new tp;i.write(ti(e.identityKey,"hex")),"number"==typeof e.limit?i.writeVarIntNum(e.limit):i.writeVarIntNum(-1),"number"==typeof e.offset?i.writeVarIntNum(e.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1);let r=await this.transmit("discoverByIdentityKey",t,i.toArray());return this.parseDiscoveryResult(r)}async discoverByAttributes(e,t){let i=new tp,r=Object.keys(e.attributes);i.writeVarIntNum(r.length);for(let t=0;t<r.length;t++)i.writeVarIntNum(r[t].length),i.write(ti(r[t],"utf8")),i.writeVarIntNum(e.attributes[r[t]].length),i.write(ti(e.attributes[r[t]],"utf8"));"number"==typeof e.limit?i.writeVarIntNum(e.limit):i.writeVarIntNum(-1),"number"==typeof e.offset?i.writeVarIntNum(e.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1);let n=await this.transmit("discoverByAttributes",t,i.toArray());return this.parseDiscoveryResult(n)}async isAuthenticated(e,t){return{authenticated:1===(await this.transmit("isAuthenticated",t))[0]}}async waitForAuthentication(e,t){return await this.transmit("waitForAuthentication",t),{authenticated:!0}}async getHeight(e,t){return{height:new tg(await this.transmit("getHeight",t)).readVarIntNum()}}async getHeaderForHeight(e,t){let i=new tp;return i.writeVarIntNum(e.height),{header:te(await this.transmit("getHeaderForHeight",t,i.toArray()))}}async getNetwork(e,t){return{network:0===(await this.transmit("getNetwork",t))[0]?"mainnet":"testnet"}}async getVersion(e,t){return{version:ts(await this.transmit("getVersion",t))}}}class rV{baseUrl;httpClient;originator;constructor(e,t="http://localhost:3301",i=fetch){this.baseUrl=t,this.httpClient=i,this.originator=e}async transmitToWallet(e){let t,i=new tg(e),r=i.readUInt8(),n=rB[r];if(void 0===n||""===n)throw Error(`Invalid call code: ${r}`);let a=i.readUInt8();a>0&&(t=ts(i.read(a)));let s=i.read(),o=await fetch(`${this.baseUrl}/${n}`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Origin:t??""},body:new Uint8Array(s)});return Array.from(new Uint8Array(await o.arrayBuffer()))}}class rD extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(e,t,i,r,n){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=e,this.sendWithResults=t,this.txid=i,this.tx=r,this.noSendChange=n,this.code=5,this.name=this.constructor.name}}let rL=rD;class rF extends Error{parameter;code;isError=!0;constructor(e,t){super(`The ${e} parameter must be ${t??"valid."}`),this.parameter=e,this.code=6,this.name=this.constructor.name}}let rH=rF,rK=class extends Error{totalSatoshisNeeded;moreSatoshisNeeded;code;isError=!0;constructor(e,t){super(`Insufficient funds in the available inputs to cover the cost of the required outputs and the transaction fee (${t} more satoshis are needed, for a total of ${e}), plus whatever would be required in order to pay the fee to unlock and spend the outputs used to provide the additional satoshis.`),this.totalSatoshisNeeded=e,this.moreSatoshisNeeded=t,this.code=7,this.name=this.constructor.name}};class rM{baseUrl;httpClient;originator;api;constructor(e,t="http://localhost:3321",i=fetch){this.baseUrl=t,this.originator=e,this.httpClient=i;const r="u">typeof window&&"u">typeof document&&window?.origin!=="file://";this.api=async(e,t)=>{let n=!r&&this.originator?function(e,t="http"){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))try{return new URL(e).origin}catch{}try{return new URL(`${t}://${e}`).origin}catch{throw Error(`Invalid originator value: ${e}`)}}(this.originator,"http"):void 0;r||void 0!==n||console.error("Originator is required in Node.js environments");let a=await await i(`${this.baseUrl}/${e}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...n?{Origin:n}:{},...n?{Originator:n}:{}},body:JSON.stringify(t)}),s=await a.json();if(!a.ok){if(400===a.status&&s.isError){let e;switch(s.code){case 5:e=new rD(s.reviewActionResults,s.sendWithResults,s.txid,s.tx,s.noSendChange);break;case 6:(e=new rF(s.parameter)).message=s.message;break;case 7:e=new rK(s.totalSatoshisNeeded,s.moreSatoshisNeeded)}if(e)throw e}throw Error(JSON.stringify({call:e,args:t,message:s.message??`HTTP Client error ${a.status}`}))}return s}}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 rq{domain;constructor(e="*"){if("object"!=typeof window)throw Error("The XDM substrate requires a global window object.");if(!window.hasOwnProperty("ReactNativeWebView"))throw Error("The window object does not have a ReactNativeWebView property.");if("function"!=typeof window.ReactNativeWebView.postMessage)throw Error("The window.ReactNativeWebView property does not seem to support postMessage calls.");this.domain=e}async invoke(e,t){return await new Promise((i,r)=>{let n=tc(t0(12)),a=e=>{let t=JSON.parse(e.data);"CWI"===t.type&&t.id===n&&!0!==t.isInvocation&&("function"==typeof window.removeEventListener&&window.removeEventListener("message",a),"error"===t.status?r(new rT(t.description,t.code)):i(t.result))};window.addEventListener("message",a),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)}}function r$(e){let[t,i]=e.split(".");return{txid:t,vout:Number(i)}}function rz(e){return e??!1}function rW(e,t,i,r){if(void 0!==e)return rJ(e,t,i,r)}function rj(e,t,i){if(void 0===e||!Number.isInteger(e)||e<0||e>21e14)throw new rH(t,"a valid number of satoshis");if(void 0!==i&&e<i)throw new rH(t,`at least ${i} satoshis.`);return e}function rX(e,t,i,r){if(void 0!==e)return rG(e,t,void 0,i,r)}function rG(e,t,i,r,n){if(void 0===e){if(void 0!==i)return i;throw new rH(t,"a valid integer")}if(!Number.isInteger(e))throw new rH(t,"an integer");if(e=Number(e),void 0!==r&&e<r)throw new rH(t,`at least ${r} length.`);if(void 0!==n&&e>n)throw new rH(t,`no more than ${n} length.`);return e}function rY(e,t){return rG(e,t,0,0)}function rJ(e,t,i,r){let n=ti(e,"utf8").length;if(void 0!==i&&n<i)throw new rH(t,`at least ${i} length.`);if(void 0!==r&&n>r)throw new rH(t,`no more than ${r} length.`);return e}function rZ(e){return r1(e,"basket",1,300)}function rQ(e){return r1(e,"label",1,300)}function r0(e){return r1(e,"tag",1,300)}function r1(e,t,i,r){let n=ti(e=e.trim().toLowerCase(),"utf8").length;if(void 0!==i&&n<i)throw new rH(t,`at least ${i} length.`);if(void 0!==r&&n>r)throw new rH(t,`no more than ${r} length.`);return e}function r2(e,t,i,r){if(void 0!==e)return r8(e,t,i,r)}function r8(e,t,i,r){if(0===(e=e.trim()).length)throw new rH(t,"valid base64 string");let n=0;for(let i=0;i<e.length;i++){let r=e.charCodeAt(i);if((!(r>=65)||!(r<=90))&&(!(r>=97)||!(r<=122))&&(!(r>=48)||!(r<=57))&&43!==r&&47!==r){if(61===r){if(i<e.length-2)throw new rH(t,"valid base64 string");n++;continue}throw new rH(t,"valid base64 string")}}if(n>2||n>0&&e.length%4!=0)throw new rH(t,"valid base64 string");let a=e.length%4;if(0!==a&&a!==4-n)throw new rH(t,"valid base64 string");let s=Math.floor(3*(e.length-n)/4);if(void 0!==i&&s<i)throw new rH(t,`at least ${i} bytes`);if(void 0!==r&&s>r)throw new rH(t,`no more than ${r} bytes`);return e}function r3(e,t,i,r){if(void 0!==e)return r6(e,t,i,r)}function r6(e,t,i,r){if((e=e.trim().toLowerCase()).length%2==1)throw new rH(t,`even length, not ${e.length}.`);if(!/^[0-9A-Fa-f]+$/.test(e))throw new rH(t,"hexadecimal string.");if(void 0!==i&&e.length<i)throw new rH(t,`at least ${i} length.`);if(void 0!==r&&e.length>r)throw new rH(t,`no more than ${r} length.`);return e}function r4(e){return(e=e.trim()).length%2!=1&&!!/^[0-9A-Fa-f]+$/.test(e)}function r5(e){if(void 0===e.unlockingScript&&void 0===e.unlockingScriptLength)throw new rH("unlockingScript, unlockingScriptLength","at least one valid value.");let t=r3(e.unlockingScript,"unlockingScript"),i=e.unlockingScriptLength??(null!=t?t.length/2:0);if(t&&i!==t.length/2)throw new rH("unlockingScriptLength","length unlockingScript if both valid.");return{outpoint:r$(e.outpoint),inputDescription:rJ(e.inputDescription,"inputDescription",5,2e3),unlockingScript:t,unlockingScriptLength:i,sequenceNumber:e.sequenceNumber??0xffffffff}}function r7(e){return{lockingScript:r6(e.lockingScript,"lockingScript"),satoshis:rj(e.satoshis,"satoshis"),outputDescription:rJ(e.outputDescription,"outputDescription",5,2e3),basket:function(e){if(void 0!==e)return rZ(e)}(e.basket),customInstructions:e.customInstructions,tags:(e.tags??[]).map(e=>r0(e))}}function r9(e){let t=null!=e?e:{};return{signAndProcess:t.signAndProcess??!0,acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,knownTxids:t.knownTxids??[],returnTXIDOnly:rz(t.returnTXIDOnly),noSend:rz(t.noSend),noSendChange:(t.noSendChange??[]).map(e=>r$(e)),sendWith:t.sendWith??[],randomizeOutputs:t.randomizeOutputs??!0}}function ne(e,t){let i={description:rJ(e.description,"description",5,2e3),inputBEEF:e.inputBEEF,inputs:(e.inputs??[]).map(e=>r5(e)),outputs:(e.outputs??[]).map(e=>r7(e)),lockTime:e.lockTime??0,version:e.version??1,labels:e.labels?.map(e=>rQ(e))??[],options:r9(e.options),logger:t,isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!1,isRemixChange:!1,isSignAction:!1,randomVals:void 0,includeAllSourceTransactions:!1,isTestWerrReviewActions:!1};return i.isTestWerrReviewActions=i.labels.includes(nk),i.isSendWith=i.options.sendWith.length>0,i.isRemixChange=!i.isSendWith&&0===i.inputs.length&&0===i.outputs.length,i.isNewTx=i.isRemixChange||i.inputs.length>0||i.outputs.length>0,i.isSignAction=i.isNewTx&&(!i.options.signAndProcess||i.inputs.some(e=>void 0===e.unlockingScript)),i.isDelayed=i.options.acceptDelayedBroadcast,i.isNoSend=i.options.noSend,i}function nt(e){let t=null!=e?e:{};return{acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,returnTXIDOnly:rz(t.returnTXIDOnly),noSend:rz(t.noSend),sendWith:t.sendWith??[]}}function ni(e){let t={spends:e.spends,reference:e.reference,options:nt(e.options),isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!0,isRemixChange:!1,isTestWerrReviewActions:!1};return t.isSendWith=t.options.sendWith.length>0,t.isDelayed=t.options.acceptDelayedBroadcast,t.isNoSend=t.options.noSend,t}function nr(e){return{reference:r8(e.reference,"reference")}}function nn(e){if(void 0!==e)return{derivationPrefix:r8(e.derivationPrefix,"derivationPrefix"),derivationSuffix:r8(e.derivationSuffix,"derivationSuffix"),senderIdentityKey:r6(e.senderIdentityKey,"senderIdentityKey")}}function na(e){if(void 0!==e)return{basket:rZ(e.basket),customInstructions:rW(e.customInstructions,"customInstructions",0,1e3),tags:(e.tags??[]).map(e=>r0(e))}}function ns(e){if("basket insertion"!==e.protocol&&"wallet payment"!==e.protocol)throw new rH("protocol","'basket insertion' or 'wallet payment'");return{outputIndex:rY(e.outputIndex,"outputIndex"),protocol:e.protocol,paymentRemittance:nn(e.paymentRemittance),insertionRemittance:na(e.insertionRemittance)}}function no(e){if(void 0!==e){for(let t of(rJ(e=e.trim().toLowerCase(),"originator",1,250),e.split(".")))rJ(t,"originator part",1,63);return e}}function nc(e){let t={tx:e.tx,outputs:e.outputs.map(e=>ns(e)),description:rJ(e.description,"description",5,2e3),labels:(null!=e.labels?e.labels:[]).map(e=>rQ(e)),seekPermission:e.seekPermission??!0};try{if(i8.fromBinary(t.tx).txs.length<1)throw new rH("tx","at least one transaction to internalize an output from")}catch{throw new rH("tx","valid with at least one transaction to internalize an output from")}if(t.outputs.length<1)throw new rH("outputs","at least one output to internalize from the transaction");return t}function nl(e,t){if(void 0!==e)return nh(e,t)}function nh(e,t){let i=e.split(".");if(2!==i.length||!Number.isInteger(Number(i[1])))throw new rH(t,"txid as hex string and numeric output index joined with '.'");let r=r6(i[0],`${t} txid`,void 0,64),n=rY(Number(i[1]),`${t} vout`);return`${r}.${n}`}function nd(e){return{basket:rZ(e.basket),output:nh(e.output,"output")}}function nu(e){return{type:r8(e.type,"type"),serialNumber:r8(e.serialNumber,"serialNumber"),certifier:r6(e.certifier,"certifier")}}function nf(e){return{certifiers:e.certifiers.map(e=>r6(e.trim(),"certifiers"))??[],types:e.types.map(e=>r8(e.trim(),"types"))??[],limit:rG(e.limit,"limit",10,1,1e4),offset:rY(e.offset??0,"offset"),privileged:rz(e.privileged),privilegedReason:rW(e.privilegedReason,"privilegedReason",5,50),partial:void 0}}function np(e){for(let t of Object.keys(e))rJ(t,"field name",1,50);return e}function ng(e){if("issuance"!==e.acquisitionProtocol)throw Error("Only acquire certificate via issuance requests allowed here.");if(e.serialNumber)throw new rH("serialNumber",'valid when acquisitionProtocol is "direct"');if(e.signature)throw new rH("signature",'valid when acquisitionProtocol is "direct"');if(e.revocationOutpoint)throw new rH("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(e.keyringRevealer)throw new rH("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null!=e.keyringForSubject)throw new rH("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(!e.certifierUrl)throw new rH("certifierUrl",'valid when acquisitionProtocol is "issuance"');if(e.privileged&&!e.privilegedReason)throw new rH("privilegedReason","valid when 'privileged' is true ");return{type:r8(e.type,"type"),certifier:r6(e.certifier,"certifier"),certifierUrl:e.certifierUrl,fields:np(e.fields),privileged:rz(e.privileged),privilegedReason:rW(e.privilegedReason,"privilegedReason",5,50),subject:""}}function nm(e){var t;if("direct"!==e.acquisitionProtocol)throw Error("Only acquire direct certificate requests allowed here.");if(!e.serialNumber)throw new rH("serialNumber",'valid when acquisitionProtocol is "direct"');if(!e.signature)throw new rH("signature",'valid when acquisitionProtocol is "direct"');if(!e.revocationOutpoint)throw new rH("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(!e.keyringRevealer)throw new rH("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null==e.keyringForSubject)throw new rH("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(e.privileged&&!e.privilegedReason)throw new rH("privilegedReason","valid when 'privileged' is true ");return{type:r8(e.type,"type"),serialNumber:r8(e.serialNumber,"serialNumber"),certifier:r6(e.certifier,"certifier"),revocationOutpoint:nh(e.revocationOutpoint,"revocationOutpoint"),fields:np(e.fields),signature:r6(e.signature,"signature"),keyringRevealer:(t=e.keyringRevealer,"certifier"===t?t:r6(t,"keyringRevealer")),keyringForSubject:function(e,t){for(let i of Object.keys(e))rJ(i,`${t} field name`,1,50),r8(e[i],`${t} field value`);return e}(e.keyringForSubject,"keyringForSubject"),privileged:rz(e.privileged),privilegedReason:rW(e.privilegedReason,"privilegedReason",5,50),subject:""}}function ny(e){if(e.privileged&&!e.privilegedReason)throw new rH("privilegedReason","valid when 'privileged' is true ");return{type:r2(e.certificate.type,"certificate.type"),serialNumber:r2(e.certificate.serialNumber,"certificate.serialNumber"),certifier:r3(e.certificate.certifier,"certificate.certifier"),subject:r3(e.certificate.subject,"certificate.subject"),revocationOutpoint:nl(e.certificate.revocationOutpoint,"certificate.revocationOutpoint"),signature:r3(e.certificate.signature,"certificate.signature"),fieldsToReveal:(e.fieldsToReveal??[]).map(e=>rJ(e,`fieldsToReveal ${e}`,1,50)),verifier:r6(e.verifier,"verifier"),privileged:rz(e.privileged),privilegedReason:rW(e.privilegedReason,"privilegedReason",5,50)}}function nb(e){return{identityKey:r6(e.identityKey,"identityKey",66,66),limit:rG(e.limit,"limit",10,1,1e4),offset:rY(e.offset??0,"offset"),seekPermission:rz(e.seekPermission)}}function nw(e){return{attributes:function(e){for(let t of Object.keys(e))rJ(t,`field name ${t}`,1,50);return e}(e.attributes),limit:rG(e.limit,"limit",10,1,1e4),offset:rY(e.offset??0,"offset"),seekPermission:rz(e.seekPermission)}}function nv(e){let t;if(void 0===e.tagQueryMode||"any"===e.tagQueryMode)t="any";else if("all"===e.tagQueryMode)t="all";else throw new rH("tagQueryMode","undefined, 'any', or 'all'");return{basket:rJ(e.basket,"basket",1,300),tags:(null!=e.tags?e.tags:[]).map(e=>rJ(e,"tag",1,300)),tagQueryMode:t,includeLockingScripts:"locking scripts"===e.include,includeTransactions:"entire transactions"===e.include,includeCustomInstructions:rz(e.includeCustomInstructions),includeTags:rz(e.includeTags),includeLabels:rz(e.includeLabels),limit:rG(e.limit,"limit",10,1,1e4),offset:rG(e.offset,"offset",0,void 0,void 0),seekPermission:e.seekPermission??!0,knownTxids:[]}}function nI(e){let t;if(void 0===e.labelQueryMode||"any"===e.labelQueryMode)t="any";else if("all"===e.labelQueryMode)t="all";else throw new rH("labelQueryMode","undefined, 'any', or 'all'");return{labels:(null!=e.labels?e.labels:[]).map(e=>rQ(e)),labelQueryMode:t,includeLabels:rz(e.includeLabels),includeInputs:rz(e.includeInputs),includeInputSourceLockingScripts:rz(e.includeInputSourceLockingScripts),includeInputUnlockingScripts:rz(e.includeInputUnlockingScripts),includeOutputs:rz(e.includeOutputs),includeOutputLockingScripts:rz(e.includeOutputLockingScripts),limit:rG(e.limit,"limit",10,1,1e4),offset:rG(e.offset,"offset",0,0),seekPermission:e.seekPermission??!0}}let nk="a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a";class nS{substrate;originator;constructor(e="auto",t){"Cicada"===e&&(e=new rU(new rV(t))),"window.CWI"===e&&(e=new rO),"XDM"===e&&(e=new rR),"json-api"===e&&(e=new rM(t)),"react-native"===e&&(e=new rq(t)),"secure-json-api"===e&&(e=new rM(t,"https://localhost:2121")),this.substrate=e,this.originator=t}async connectToSubstrate(){if("object"==typeof this.substrate)return;let e=async(e,t)=>{try{let i,r=e();if(i="number"==typeof t?await Promise.race([r.getVersion({}),new Promise((e,i)=>setTimeout(()=>i(Error("Timed out.")),t))]):await r.getVersion({}),"object"!=typeof i||"string"!=typeof i.version)return{success:!1};return{success:!0,sub:r}}catch{return{success:!1}}},t=[e(()=>new rO),e(()=>new rM(this.originator,"https://localhost:2121")),e(()=>new rM(this.originator)),e(()=>new rq(this.originator)),e(()=>new rU(new rV(this.originator)))],i=(await Promise.allSettled(t)).filter(e=>"fulfilled"===e.status&&e.value.success&&void 0!==e.value.sub).map(e=>e.value.sub);if(i.length>0){this.substrate=i[0];return}let r=await e(()=>new rR,200);if(r.success&&void 0!==r.sub)this.substrate=r.sub;else throw Error("No wallet available over any communication substrate. Install a BSV wallet today!")}async createAction(e){return ne(e),await this.connectToSubstrate(),await this.substrate.createAction(e,this.originator)}async signAction(e){return ni(e),await this.connectToSubstrate(),await this.substrate.signAction(e,this.originator)}async abortAction(e){return nr(e),await this.connectToSubstrate(),await this.substrate.abortAction(e,this.originator)}async listActions(e){return nI(e),await this.connectToSubstrate(),await this.substrate.listActions(e,this.originator)}async internalizeAction(e){return nc(e),await this.connectToSubstrate(),await this.substrate.internalizeAction(e,this.originator)}async listOutputs(e){return nv(e),await this.connectToSubstrate(),await this.substrate.listOutputs(e,this.originator)}async relinquishOutput(e){return nd(e),await this.connectToSubstrate(),await this.substrate.relinquishOutput(e,this.originator)}async getPublicKey(e){return await this.connectToSubstrate(),await this.substrate.getPublicKey(e,this.originator)}async revealCounterpartyKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealCounterpartyKeyLinkage(e,this.originator)}async revealSpecificKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealSpecificKeyLinkage(e,this.originator)}async encrypt(e){return await this.connectToSubstrate(),await this.substrate.encrypt(e,this.originator)}async decrypt(e){return await this.connectToSubstrate(),await this.substrate.decrypt(e,this.originator)}async createHmac(e){return await this.connectToSubstrate(),await this.substrate.createHmac(e,this.originator)}async verifyHmac(e){return await this.connectToSubstrate(),await this.substrate.verifyHmac(e,this.originator)}async createSignature(e){return await this.connectToSubstrate(),await this.substrate.createSignature(e,this.originator)}async verifySignature(e){return await this.connectToSubstrate(),await this.substrate.verifySignature(e,this.originator)}async acquireCertificate(e){if("direct"===e.acquisitionProtocol)nm(e);else if("issuance"===e.acquisitionProtocol)ng(e);else throw new rF("acquisitionProtocol",`valid. ${String(e.acquisitionProtocol)} is unrecognized.`);return await this.connectToSubstrate(),await this.substrate.acquireCertificate(e,this.originator)}async listCertificates(e){return nf(e),await this.connectToSubstrate(),await this.substrate.listCertificates(e,this.originator)}async proveCertificate(e){return ny(e),await this.connectToSubstrate(),await this.substrate.proveCertificate(e,this.originator)}async relinquishCertificate(e){return nu(e),await this.connectToSubstrate(),await this.substrate.relinquishCertificate(e,this.originator)}async discoverByIdentityKey(e){return nb(e),await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(e,this.originator)}async discoverByAttributes(e){return nw(e),await this.connectToSubstrate(),await this.substrate.discoverByAttributes(e,this.originator)}async isAuthenticated(e={}){return await this.connectToSubstrate(),await this.substrate.isAuthenticated(e,this.originator)}async waitForAuthentication(e={}){return await this.connectToSubstrate(),await this.substrate.waitForAuthentication(e,this.originator)}async getHeight(e={}){return await this.connectToSubstrate(),await this.substrate.getHeight(e,this.originator)}async getHeaderForHeight(e){return await this.connectToSubstrate(),await this.substrate.getHeaderForHeight(e,this.originator)}async getNetwork(e={}){return await this.connectToSubstrate(),await this.substrate.getNetwork(e,this.originator)}async getVersion(e={}){return await this.connectToSubstrate(),await this.substrate.getVersion(e,this.originator)}}class nE{wallet;constructor(e){this.wallet=e}decodeOutpoint(e){let t=te(e.read(32)),i=e.readVarIntNum();return`${t}.${i}`}encodeOutpoint(e){let t=new tp,[i,r]=e.split(".");return t.write(ti(i,"hex")),t.writeVarIntNum(Number(r)),t.toArray()}async transmitToWallet(e){let t=new tg(e);try{let e=t.readUInt8(),i=rB[e];if(void 0===i||""===i)throw Error(`Invalid call code: ${e}`);let r=t.readUInt8(),n=t.read(r),a=ts(n);switch(i){case"createAction":{let e={},i=t.readVarIntNum(),r=t.read(i);e.description=ts(r);let n=t.readVarIntNum();n>=0?e.inputBEEF=t.read(n):e.inputBEEF=void 0;let s=t.readVarIntNum();if(s>=0){e.inputs=[];for(let i=0;i<s;i++){let i={};i.outpoint=this.decodeOutpoint(t);let r=t.readVarIntNum();if(r>=0){let e=t.read(r);i.unlockingScript=te(e)}else i.unlockingScript=void 0,i.unlockingScriptLength=t.readVarIntNum();let n=t.readVarIntNum(),a=t.read(n);i.inputDescription=ts(a);let s=t.readVarIntNum();s>=0?i.sequenceNumber=s:i.sequenceNumber=void 0,e.inputs.push(i)}}else e.inputs=void 0;let o=t.readVarIntNum();if(o>=0){e.outputs=[];for(let i=0;i<o;i++){let i={},r=t.readVarIntNum(),n=t.read(r);i.lockingScript=te(n),i.satoshis=t.readVarIntNum();let a=t.readVarIntNum(),s=t.read(a);i.outputDescription=ts(s);let o=t.readVarIntNum();if(o>=0){let e=t.read(o);i.basket=ts(e)}else i.basket=void 0;let c=t.readVarIntNum();if(c>=0){let e=t.read(c);i.customInstructions=ts(e)}else i.customInstructions=void 0;let l=t.readVarIntNum();if(l>=0){i.tags=[];for(let e=0;e<l;e++){let e=t.readVarIntNum(),r=t.read(e),n=ts(r);i.tags.push(n)}}else i.tags=void 0;e.outputs.push(i)}}else e.outputs=void 0;let c=t.readVarIntNum();c>=0?e.lockTime=c:e.lockTime=void 0;let l=t.readVarIntNum();l>=0?e.version=l:e.version=void 0;let h=t.readVarIntNum();if(h>=0){e.labels=[];for(let i=0;i<h;i++){let i=t.readVarIntNum(),r=t.read(i),n=ts(r);e.labels.push(n)}}else e.labels=void 0;let d=t.readInt8();if(1===d){e.options={};let i=t.readInt8();-1===i?e.options.signAndProcess=void 0:e.options.signAndProcess=1===i;let r=t.readInt8();-1===r?e.options.acceptDelayedBroadcast=void 0:e.options.acceptDelayedBroadcast=1===r;let n=t.readInt8();-1===n?e.options.trustSelf=void 0:1===n&&(e.options.trustSelf="known");let a=t.readVarIntNum();if(a>=0){e.options.knownTxids=[];for(let i=0;i<a;i++){let i=t.read(32),r=te(i);e.options.knownTxids.push(r)}}else e.options.knownTxids=void 0;let s=t.readInt8();-1===s?e.options.returnTXIDOnly=void 0:e.options.returnTXIDOnly=1===s;let o=t.readInt8();-1===o?e.options.noSend=void 0:e.options.noSend=1===o;let c=t.readVarIntNum();if(c>=0){e.options.noSendChange=[];for(let i=0;i<c;i++){let i=this.decodeOutpoint(t);e.options.noSendChange.push(i)}}else e.options.noSendChange=void 0;let l=t.readVarIntNum();if(l>=0){e.options.sendWith=[];for(let i=0;i<l;i++){let i=t.read(32),r=te(i);e.options.sendWith.push(r)}}else e.options.sendWith=void 0;let h=t.readInt8();-1===h?e.options.randomizeOutputs=void 0:e.options.randomizeOutputs=1===h}else e.options=void 0;let u=await this.wallet.createAction(e,a),f=new tp;if(null!=u.txid&&""!==u.txid?(f.writeInt8(1),f.write(ti(u.txid,"hex"))):f.writeInt8(0),null!=u.tx?(f.writeInt8(1),f.writeVarIntNum(u.tx.length),f.write(u.tx)):f.writeInt8(0),null!=u.noSendChange)for(let e of(f.writeVarIntNum(u.noSendChange.length),u.noSendChange))f.write(this.encodeOutpoint(e));else f.writeVarIntNum(-1);if(null!=u.sendWithResults)for(let e of(f.writeVarIntNum(u.sendWithResults.length),u.sendWithResults)){let t;f.write(ti(e.txid,"hex")),"unproven"===e.status?t=1:"sending"===e.status?t=2:"failed"===e.status&&(t=3),f.writeInt8(t)}else f.writeVarIntNum(-1);if(null!=u.signableTransaction){f.writeInt8(1),f.writeVarIntNum(u.signableTransaction.tx.length),f.write(u.signableTransaction.tx);let e=ti(u.signableTransaction.reference,"base64");f.writeVarIntNum(e.length),f.write(e)}else f.writeInt8(0);let p=new tp;return p.writeUInt8(0),p.write(f.toArray()),p.toArray()}case"signAction":{let e={},i=t.readVarIntNum();e.spends={};for(let r=0;r<i;r++){let i=t.readVarIntNum(),r={},n=t.readVarIntNum(),a=t.read(n);r.unlockingScript=te(a);let s=t.readVarIntNum();s>=0?r.sequenceNumber=s:r.sequenceNumber=void 0,e.spends[i]=r}let r=t.readVarIntNum(),n=t.read(r);e.reference=tc(n);let s=t.readInt8();if(1===s){e.options={};let i=t.readInt8();-1===i?e.options.acceptDelayedBroadcast=void 0:e.options.acceptDelayedBroadcast=1===i;let r=t.readInt8();-1===r?e.options.returnTXIDOnly=void 0:e.options.returnTXIDOnly=1===r;let n=t.readInt8();-1===n?e.options.noSend=void 0:e.options.noSend=1===n;let a=t.readVarIntNum();if(a>=0){e.options.sendWith=[];for(let i=0;i<a;i++){let i=t.read(32),r=te(i);e.options.sendWith.push(r)}}else e.options.sendWith=void 0}else e.options=void 0;let o=await this.wallet.signAction(e,a),c=new tp;if(null!=o.txid&&""!==o.txid?(c.writeInt8(1),c.write(ti(o.txid,"hex"))):c.writeInt8(0),null!=o.tx?(c.writeInt8(1),c.writeVarIntNum(o.tx.length),c.write(o.tx)):c.writeInt8(0),null!=o.sendWithResults)for(let e of(c.writeVarIntNum(o.sendWithResults.length),o.sendWithResults)){let t;c.write(ti(e.txid,"hex")),"unproven"===e.status?t=1:"sending"===e.status?t=2:"failed"===e.status&&(t=3),c.writeInt8(t)}else c.writeVarIntNum(-1);let l=new tp;return l.writeUInt8(0),l.write(c.toArray()),l.toArray()}case"abortAction":{let e=t.read(),i=tc(e);await this.wallet.abortAction({reference:i},a);let r=new tp;return r.writeUInt8(0),r.toArray()}case"listActions":{let e={},i=t.readVarIntNum();e.labels=[];for(let r=0;r<i;r++){let i=t.readVarIntNum(),r=t.read(i);e.labels.push(ts(r))}let r=t.readInt8();for(let i of(-1===r?e.labelQueryMode=void 0:1===r?e.labelQueryMode="any":2===r&&(e.labelQueryMode="all"),["includeLabels","includeInputs","includeInputSourceLockingScripts","includeInputUnlockingScripts","includeOutputs","includeOutputLockingScripts"])){let r=t.readInt8();-1===r?e[i]=void 0:e[i]=1===r}let n=t.readVarIntNum();n>=0?e.limit=n:e.limit=void 0;let s=t.readVarIntNum();s>=0?e.offset=s:e.offset=void 0;let o=t.readInt8();o>=0?e.seekPermission=1===o:e.seekPermission=void 0;let c=await this.wallet.listActions(e,a),l=new tp;for(let e of(l.writeVarIntNum(c.totalActions),c.actions)){let t;switch(l.write(ti(e.txid,"hex")),l.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}l.writeInt8(t),l.writeInt8(+!!e.isOutgoing);let i=ti(e.description,"utf8");if(l.writeVarIntNum(i.length),l.write(i),void 0!==e.labels)for(let t of(l.writeVarIntNum(e.labels.length),e.labels)){let e=ti(t,"utf8");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);if(l.writeVarIntNum(e.version),l.writeVarIntNum(e.lockTime),void 0!==e.inputs)for(let t of(l.writeVarIntNum(e.inputs.length),e.inputs)){if(l.write(this.encodeOutpoint(t.sourceOutpoint)),l.writeVarIntNum(t.sourceSatoshis),void 0!==t.sourceLockingScript){let e=ti(t.sourceLockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);if(void 0!==t.unlockingScript){let e=ti(t.unlockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);let e=ti(t.inputDescription,"utf8");l.writeVarIntNum(e.length),l.write(e),l.writeVarIntNum(t.sequenceNumber)}else l.writeVarIntNum(-1);if(void 0!==e.outputs)for(let t of(l.writeVarIntNum(e.outputs.length),e.outputs)){if(l.writeVarIntNum(t.outputIndex),l.writeVarIntNum(t.satoshis),void 0!==t.lockingScript){let e=ti(t.lockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);l.writeInt8(+!!t.spendable);let e=ti(t.outputDescription,"utf8");if(l.writeVarIntNum(e.length),l.write(e),void 0!==t.basket){let e=ti(t.basket,"utf8");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);if(void 0!==t.tags)for(let e of(l.writeVarIntNum(t.tags.length),t.tags)){let t=ti(e,"utf8");l.writeVarIntNum(t.length),l.write(t)}else l.writeVarIntNum(-1);if(void 0!==t.customInstructions){let e=ti(t.customInstructions,"utf8");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1)}else l.writeVarIntNum(-1)}let h=new tp;return h.writeUInt8(0),h.write(l.toArray()),h.toArray()}case"internalizeAction":{let e={},i=t.readVarIntNum();e.tx=t.read(i);let r=t.readVarIntNum();e.outputs=[];for(let i=0;i<r;i++){let i={};i.outputIndex=t.readVarIntNum();let r=t.readUInt8();if(1===r){i.protocol="wallet payment",i.paymentRemittance={};let e=t.read(33);i.paymentRemittance.senderIdentityKey=te(e);let r=t.readVarIntNum(),n=t.read(r);i.paymentRemittance.derivationPrefix=tc(n);let a=t.readVarIntNum(),s=t.read(a);i.paymentRemittance.derivationSuffix=tc(s)}else if(2===r){i.protocol="basket insertion",i.insertionRemittance={};let e=t.readVarIntNum(),r=t.read(e);i.insertionRemittance.basket=ts(r);let n=t.readVarIntNum();if(n>=0){let e=t.read(n);i.insertionRemittance.customInstructions=ts(e)}let a=t.readVarIntNum();if(a>0){i.insertionRemittance.tags=[];for(let e=0;e<a;e++){let e=t.readVarIntNum(),r=t.read(e);i.insertionRemittance.tags.push(ts(r))}}else i.insertionRemittance.tags=[]}e.outputs.push(i)}let n=t.readVarIntNum();if(n>=0){e.labels=[];for(let i=0;i<n;i++){let i=t.readVarIntNum();e.labels.push(ts(t.read(i)))}}let s=t.readVarIntNum();e.description=ts(t.read(s));let o=t.readInt8();o>=0?e.seekPermission=1===o:e.seekPermission=void 0,await this.wallet.internalizeAction(e,a);let c=new tp;return c.writeUInt8(0),c.toArray()}case"listOutputs":{let e={},i=t.readVarIntNum(),r=t.read(i);e.basket=ts(r);let n=t.readVarIntNum();if(n>0){e.tags=[];for(let i=0;i<n;i++){let i=t.readVarIntNum(),r=t.read(i);e.tags.push(ts(r))}}else e.tags=void 0;let s=t.readInt8();1===s?e.tagQueryMode="all":2===s?e.tagQueryMode="any":e.tagQueryMode=void 0;let o=t.readInt8();1===o?e.include="locking scripts":2===o?e.include="entire transactions":e.include=void 0;let c=t.readInt8();-1===c?e.includeCustomInstructions=void 0:e.includeCustomInstructions=1===c;let l=t.readInt8();-1===l?e.includeTags=void 0:e.includeTags=1===l;let h=t.readInt8();-1===h?e.includeLabels=void 0:e.includeLabels=1===h;let d=t.readVarIntNum();d>=0?e.limit=d:e.limit=void 0;let u=t.readVarIntNum();u>=0?e.offset=u:e.offset=void 0;let f=t.readInt8();f>=0?e.seekPermission=1===f:e.seekPermission=void 0;let p=await this.wallet.listOutputs(e,a),g=new tp;for(let e of(g.writeVarIntNum(p.totalOutputs),null!=p.BEEF?(g.writeVarIntNum(p.BEEF.length),g.write(p.BEEF)):g.writeVarIntNum(-1),p.outputs)){if(g.write(this.encodeOutpoint(e.outpoint)),g.writeVarIntNum(e.satoshis),void 0!==e.lockingScript){let t=ti(e.lockingScript,"hex");g.writeVarIntNum(t.length),g.write(t)}else g.writeVarIntNum(-1);if(void 0!==e.customInstructions){let t=ti(e.customInstructions,"utf8");g.writeVarIntNum(t.length),g.write(t)}else g.writeVarIntNum(-1);if(void 0!==e.tags)for(let t of(g.writeVarIntNum(e.tags.length),e.tags)){let e=ti(t,"utf8");g.writeVarIntNum(e.length),g.write(e)}else g.writeVarIntNum(-1);if(void 0!==e.labels)for(let t of(g.writeVarIntNum(e.labels.length),e.labels)){let e=ti(t,"utf8");g.writeVarIntNum(e.length),g.write(e)}else g.writeVarIntNum(-1)}let m=new tp;return m.writeUInt8(0),m.write(g.toArray()),m.toArray()}case"relinquishOutput":{let e={},i=t.readVarIntNum(),r=t.read(i);e.basket=ts(r),e.output=this.decodeOutpoint(t),await this.wallet.relinquishOutput(e,a);let n=new tp;return n.writeUInt8(0),n.toArray()}case"getPublicKey":{let e={},i=t.readUInt8();if(e.identityKey=1===i,!0!==e.identityKey){e.protocolID=this.decodeProtocolID(t),e.keyID=this.decodeString(t),e.counterparty=this.decodeCounterparty(t);let i=t.readInt8();-1===i?e.privileged=void 0:e.privileged=1===i;let r=t.readInt8();if(-1!==r){let i=t.read(r);e.privilegedReason=ts(i)}else e.privilegedReason=void 0;let n=t.readInt8();-1===n?e.forSelf=void 0:e.forSelf=1===n}else{let i=t.readInt8();-1===i?e.privileged=void 0:e.privileged=1===i;let r=t.readInt8();if(-1!==r){let i=t.read(r);e.privilegedReason=ts(i)}else e.privilegedReason=void 0}let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.getPublicKey(e,a),s=new tp;s.writeUInt8(0);let o=ti(n.publicKey,"hex");return s.write(o),s.toArray()}case"encrypt":{let e=this.decodeKeyRelatedParams(t),i=t.readVarIntNum();e.plaintext=t.read(i);let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.encrypt(e,a),s=new tp;return s.writeUInt8(0),s.write(n.ciphertext),s.toArray()}case"decrypt":{let e=this.decodeKeyRelatedParams(t),i=t.readVarIntNum();e.ciphertext=t.read(i);let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.decrypt(e,a),s=new tp;return s.writeUInt8(0),s.write(n.plaintext),s.toArray()}case"createHmac":{let e=this.decodeKeyRelatedParams(t),i=t.readVarIntNum();e.data=t.read(i);let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.createHmac(e,a),s=new tp;return s.writeUInt8(0),s.write(n.hmac),s.toArray()}case"verifyHmac":{let e=this.decodeKeyRelatedParams(t);e.hmac=t.read(32);let i=t.readVarIntNum();e.data=t.read(i);let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0,await this.wallet.verifyHmac(e,a);let n=new tp;return n.writeUInt8(0),n.toArray()}case"createSignature":{let e=this.decodeKeyRelatedParams(t),i=t.readUInt8();if(1===i){let i=t.readVarIntNum();e.data=t.read(i)}else 2===i&&(e.hashToDirectlySign=t.read(32));let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.createSignature(e,a),s=new tp;return s.writeUInt8(0),s.write(n.signature),s.toArray()}case"verifySignature":{let e=this.decodeKeyRelatedParams(t),i=t.readInt8();-1===i?e.forSelf=void 0:e.forSelf=1===i;let r=t.readVarIntNum();e.signature=t.read(r);let n=t.readUInt8();if(1===n){let i=t.readVarIntNum();e.data=t.read(i)}else 2===n&&(e.hashToDirectlyVerify=t.read(32));let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0,await this.wallet.verifySignature(e,a);let o=new tp;return o.writeUInt8(0),o.toArray()}case"isAuthenticated":{let e=await this.wallet.isAuthenticated({},a),t=new tp;return t.writeUInt8(0),t.writeUInt8(+!!e.authenticated),t.toArray()}case"waitForAuthentication":{await this.wallet.waitForAuthentication({},a);let e=new tp;return e.writeUInt8(0),e.toArray()}case"getHeight":{let e=await this.wallet.getHeight({},a),t=new tp;return t.writeUInt8(0),t.writeVarIntNum(e.height),t.toArray()}case"getHeaderForHeight":{let e={};e.height=t.readVarIntNum();let i=await this.wallet.getHeaderForHeight(e,a),r=new tp;r.writeUInt8(0);let n=ti(i.header,"hex");return r.write(n),r.toArray()}case"getNetwork":{let e=await this.wallet.getNetwork({},a),t=new tp;return t.writeUInt8(0),t.writeUInt8(+("mainnet"!==e.network)),t.toArray()}case"getVersion":{let e=await this.wallet.getVersion({},a),t=new tp;t.writeUInt8(0);let i=ti(e.version,"utf8");return t.write(i),t.toArray()}case"revealCounterpartyKeyLinkage":{let e={},i=t.readInt8();-1===i?e.privileged=void 0:e.privileged=1===i;let r=t.readInt8();if(-1===r)e.privilegedReason=void 0;else{let i=t.read(r);e.privilegedReason=ts(i)}let n=t.read(33);e.counterparty=te(n);let s=t.read(33);e.verifier=te(s);let o=await this.wallet.revealCounterpartyKeyLinkage(e,a),c=new tp;c.write(ti(o.prover,"hex")),c.write(ti(o.verifier,"hex")),c.write(ti(o.counterparty,"hex"));let l=ti(o.revelationTime,"utf8");c.writeVarIntNum(l.length),c.write(l),c.writeVarIntNum(o.encryptedLinkage.length),c.write(o.encryptedLinkage),c.writeVarIntNum(o.encryptedLinkageProof.length),c.write(o.encryptedLinkageProof);let h=new tp;return h.writeUInt8(0),h.write(c.toArray()),h.toArray()}case"revealSpecificKeyLinkage":{let e=this.decodeKeyRelatedParams(t),i=t.read(33);e.verifier=te(i);let r=await this.wallet.revealSpecificKeyLinkage(e,a),n=new tp;n.write(ti(r.prover,"hex")),n.write(ti(r.verifier,"hex")),n.write(ti(r.counterparty,"hex")),n.writeUInt8(r.protocolID[0]);let s=ti(r.protocolID[1],"utf8");n.writeVarIntNum(s.length),n.write(s);let o=ti(r.keyID,"utf8");n.writeVarIntNum(o.length),n.write(o),n.writeVarIntNum(r.encryptedLinkage.length),n.write(r.encryptedLinkage),n.writeVarIntNum(r.encryptedLinkageProof.length),n.write(r.encryptedLinkageProof),n.writeUInt8(r.proofType);let c=new tp;return c.writeUInt8(0),c.write(n.toArray()),c.toArray()}case"acquireCertificate":{let e={},i=t.read(32);e.type=tc(i);let r=t.read(33);e.certifier=te(r);let n=t.readVarIntNum();e.fields={};for(let i=0;i<n;i++){let i=t.readVarIntNum(),r=t.read(i),n=ts(r),a=t.readVarIntNum(),s=t.read(a),o=ts(s);e.fields[n]=o}let s=t.readInt8();-1===s?e.privileged=void 0:e.privileged=1===s;let o=t.readInt8();if(-1===o)e.privilegedReason=void 0;else{let i=t.read(o);e.privilegedReason=ts(i)}let c=t.readUInt8();if(e.acquisitionProtocol=1===c?"direct":"issuance","direct"===e.acquisitionProtocol){let i=t.read(32);e.serialNumber=tc(i),e.revocationOutpoint=this.decodeOutpoint(t);let r=t.readVarIntNum(),n=t.read(r);e.signature=te(n);let a=t.readUInt8();if(11===a)e.keyringRevealer="certifier";else{let i=[a].concat(t.read(32));e.keyringRevealer=te(i)}let s=t.readVarIntNum();e.keyringForSubject={};for(let i=0;i<s;i++){let i=t.readVarIntNum(),r=t.read(i),n=ts(r),a=t.readVarIntNum(),s=t.read(a),o=tc(s);e.keyringForSubject[n]=o}}else{let i=t.readVarIntNum(),r=t.read(i);e.certifierUrl=ts(r)}let l=await this.wallet.acquireCertificate(e,a),h=new rC(l.type,l.serialNumber,l.subject,l.certifier,l.revocationOutpoint,l.fields,l.signature).toBinary(),d=new tp;return d.writeUInt8(0),d.write(h),d.toArray()}case"listCertificates":{let e={},i=t.readVarIntNum();e.certifiers=[];for(let r=0;r<i;r++){let i=t.read(33);e.certifiers.push(te(i))}let r=t.readVarIntNum();e.types=[];for(let i=0;i<r;i++){let i=t.read(32);e.types.push(tc(i))}let n=t.readVarIntNum();n>=0?e.limit=n:e.limit=void 0;let s=t.readVarIntNum();s>=0?e.offset=s:e.offset=void 0;let o=t.readInt8();-1===o?e.privileged=void 0:e.privileged=1===o;let c=t.readInt8();if(-1===c)e.privilegedReason=void 0;else{let i=t.read(c);e.privilegedReason=ts(i)}let l=await this.wallet.listCertificates(e,a),h=new tp;for(let e of(h.writeVarIntNum(l.totalCertificates),l.certificates)){let t=new rC(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature).toBinary();if(h.writeVarIntNum(t.length),h.write(t),e.keyring&&Object.keys(e.keyring).length>0){h.writeInt8(1);let t=Object.entries(e.keyring);for(let[e,i]of(h.writeVarIntNum(t.length),t)){let t=ti(e,"utf8");h.writeVarIntNum(t.length),h.write(t);let r=ti(i,"base64");h.writeVarIntNum(r.length),h.write(r)}}else h.writeInt8(0);let i=ti(e.verifier,"hex");h.writeVarIntNum(i.length),h.write(i)}let d=new tp;return d.writeUInt8(0),d.write(h.toArray()),d.toArray()}case"proveCertificate":{let e={},i={},r=t.read(32);i.type=tc(r);let n=t.read(33);i.subject=te(n);let s=t.read(32);i.serialNumber=tc(s);let o=t.read(33);i.certifier=te(o),i.revocationOutpoint=this.decodeOutpoint(t);let c=t.readVarIntNum(),l=t.read(c);i.signature=te(l);let h=t.readVarIntNum();i.fields={};for(let e=0;e<h;e++){let e=t.readVarIntNum(),r=t.read(e),n=ts(r),a=t.readVarIntNum(),s=t.read(a),o=ts(s);i.fields[n]=o}e.certificate=i;let d=t.readVarIntNum();e.fieldsToReveal=[];for(let i=0;i<d;i++){let i=t.readVarIntNum(),r=t.read(i),n=ts(r);e.fieldsToReveal.push(n)}let u=t.read(33);e.verifier=te(u);let f=t.readInt8();-1===f?e.privileged=void 0:e.privileged=1===f;let p=t.readInt8();if(-1===p)e.privilegedReason=void 0;else{let i=t.read(p);e.privilegedReason=ts(i)}let g=await this.wallet.proveCertificate(e,a),m=new tp,y=Object.entries(g.keyringForVerifier);for(let[e,t]of(m.writeVarIntNum(y.length),y)){let i=ti(e,"utf8");m.writeVarIntNum(i.length),m.write(i);let r=ti(t,"base64");m.writeVarIntNum(r.length),m.write(r)}let b=new tp;return b.writeUInt8(0),b.write(m.toArray()),b.toArray()}case"relinquishCertificate":{let e={},i=t.read(32);e.type=tc(i);let r=t.read(32);e.serialNumber=tc(r);let n=t.read(33);e.certifier=te(n),await this.wallet.relinquishCertificate(e,a);let s=new tp;return s.writeUInt8(0),s.toArray()}case"discoverByIdentityKey":{let e={},i=t.read(33);e.identityKey=te(i);let r=t.readVarIntNum();r>=0?e.limit=r:e.limit=void 0;let n=t.readVarIntNum();n>=0?e.offset=n:e.offset=void 0;let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0;let o=await this.wallet.discoverByIdentityKey(e,a),c=this.serializeDiscoveryResult(o),l=new tp;return l.writeUInt8(0),l.write(c),l.toArray()}case"discoverByAttributes":{let e={},i=t.readVarIntNum();e.attributes={};for(let r=0;r<i;r++){let i=t.readVarIntNum(),r=t.read(i),n=ts(r),a=t.readVarIntNum(),s=t.read(a),o=ts(s);e.attributes[n]=o}let r=t.readVarIntNum();r>=0?e.limit=r:e.limit=void 0;let n=t.readVarIntNum();n>=0?e.offset=n:e.offset=void 0;let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0;let o=await this.wallet.discoverByAttributes(e,a),c=this.serializeDiscoveryResult(o),l=new tp;return l.writeUInt8(0),l.write(c),l.toArray()}default:throw Error(`Method ${i} not implemented`)}}catch(r){let e=new tp;e.writeUInt8("number"==typeof r.code?r.code:1);let t=ti("string"==typeof r.message?r.message:"Unknown error","utf8");e.writeVarIntNum(t.length),e.write(t);let i=ti("string"==typeof r.stack?r.stack:"","utf8");return e.writeVarIntNum(i.length),e.write(i),e.toArray()}}decodeProtocolID(e){let t=e.readUInt8(),i=e.readVarIntNum();return[t,ts(e.read(i))]}decodeString(e){let t=e.readVarIntNum();return ts(e.read(t))}decodeCounterparty(e){let t=e.readUInt8();return 11===t?"self":12===t?"anyone":0!==t?te([t,...e.read(32)]):void 0}serializeDiscoveryResult(e){let t=new tp;for(let i of(t.writeVarIntNum(e.totalCertificates),e.certificates)){let e=new rC(i.type,i.serialNumber,i.subject,i.certifier,i.revocationOutpoint,i.fields,i.signature).toBinary();t.writeVarIntNum(e.length),t.write(e);let r=ti(i.certifierInfo.name,"utf8");t.writeVarIntNum(r.length),t.write(r);let n=ti(i.certifierInfo.iconUrl,"utf8");t.writeVarIntNum(n.length),t.write(n);let a=ti(i.certifierInfo.description,"utf8");t.writeVarIntNum(a.length),t.write(a),t.writeUInt8(i.certifierInfo.trust);let s=Object.entries(i.publiclyRevealedKeyring);for(let[e,i]of(t.writeVarIntNum(s.length),s)){let r=ti(e,"utf8");t.writeVarIntNum(r.length),t.write(r);let n=ti(i,"base64");t.writeVarIntNum(n.length),t.write(n)}let o=Object.entries(i.decryptedFields);for(let[e,i]of(t.writeVarIntNum(o.length),o)){let r=ti(e,"utf8");t.writeVarIntNum(r.length),t.write(r);let n=ti(i,"utf8");t.writeVarIntNum(n.length),t.write(n)}}return t.toArray()}decodeKeyRelatedParams(e){let t={};t.protocolID=this.decodeProtocolID(e);let i=e.readVarIntNum();t.keyID=ts(e.read(i)),t.counterparty=this.decodeCounterparty(e);let r=e.readInt8();-1===r?t.privileged=void 0:t.privileged=1===r;let n=e.readInt8();return -1===n?t.privilegedReason=void 0:t.privilegedReason=ts(e.read(n)),t}}class nx extends rC{masterKeyring;constructor(e,t,i,r,n,a,s,o){for(const c of(super(e,t,i,r,n,a,o),Object.keys(a)))if(void 0===s[c]||""===s[c])throw Error(`Master keyring must contain a value for every field. Missing or empty key for field: "${c}".`);this.masterKeyring=s}static async createCertificateFields(e,t,i,r,n){let a={},s={};for(let[o,c]of Object.entries(i)){let i=ip.fromRandom(),l=i.encrypt(ti(c,"utf8"));a[o]=tc(l);let{ciphertext:h}=await e.encrypt({plaintext:i.toArray(),...rC.getCertificateFieldEncryptionDetails(o),counterparty:t,privileged:r,privilegedReason:n});s[o]=tc(h)}return{certificateFields:a,masterKeyring:s}}static async createKeyringForVerifier(e,t,i,r,n,a,s,o,c){if(!Array.isArray(n))throw Error("fieldsToReveal must be an array of strings");let l={};for(let h of n){if(void 0===r[h]||null===r[h]||""===r[h])throw Error(`Fields to reveal must be a subset of the certificate fields. Missing the "${h}" field.`);let n=(await this.decryptField(e,a,h,r[h],t,o,c)).fieldRevelationKey,{ciphertext:d}=await e.encrypt({plaintext:n,...rC.getCertificateFieldEncryptionDetails(h,s),counterparty:i,privileged:o,privilegedReason:c});l[h]=tc(d)}return l}static async issueCertificateForSubject(e,t,i,r,n=async e=>"00".repeat(32),a){let s=a??tc(t0(32)),{certificateFields:o,masterKeyring:c}=await this.createCertificateFields(e,t,i),l=await n(s),h=new nx(r,s,"self"===t?(await e.getPublicKey({identityKey:!0})).publicKey:t,(await e.getPublicKey({identityKey:!0})).publicKey,l,o,c);return await h.sign(e),h}static async decryptFields(e,t,i,r,n,a){if(null==t||0===Object.keys(t).length)throw Error("A MasterCertificate must have a valid masterKeyring!");try{let s={};for(let o of Object.keys(i))s[o]=(await this.decryptField(e,t,o,i[o],r,n,a)).decryptedFieldValue;return s}catch{throw Error("Failed to decrypt all master certificate fields.")}}static async decryptField(e,t,i,r,n,a,s){if(null==t||0===Object.keys(t).length)throw Error("A MasterCertificate must have a valid masterKeyring!");try{let{plaintext:o}=await e.decrypt({ciphertext:ti(t[i],"base64"),...rC.getCertificateFieldEncryptionDetails(i),counterparty:n,privileged:a,privilegedReason:s}),c=new ip(o).decrypt(ti(r,"base64"));return{fieldRevelationKey:o,decryptedFieldValue:ts(c)}}catch{throw Error("Failed to decrypt certificate field!")}}}class nP extends rC{keyring;decryptedFields;constructor(e,t,i,r,n,a,s,o,c){super(e,t,i,r,n,a,o),this.keyring=s,this.decryptedFields=c}static fromCertificate(e,t){return new nP(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,t,e.signature)}async decryptFields(e,t,i,r){if(null==this.keyring||0===Object.keys(this.keyring).length)throw Error("A keyring is required to decrypt certificate fields for the verifier.");try{let n={};for(let a in this.keyring){let{plaintext:s}=await e.decrypt({ciphertext:ti(this.keyring[a],"base64"),...rC.getCertificateFieldEncryptionDetails(a,this.serialNumber),counterparty:this.subject,privileged:t,privilegedReason:i},r),o=new ip(s).decrypt(ti(this.fields[a],"base64"));n[a]=ts(o)}return n}catch(e){throw Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(e instanceof Error?e.message:e)}`)}}}class nA extends rN{keyDeriver;constructor(e){if(super(e),e instanceof rx)this.keyDeriver=e;else if("string"==typeof e||e instanceof t3)this.keyDeriver=new rP(e);else throw Error("Invalid key deriver provided")}async isAuthenticated(){throw Error("not implemented")}async waitForAuthentication(){throw Error("not implemented")}async getNetwork(){throw Error("not implemented")}async getVersion(){throw Error("not implemented")}async getPublicKey(e){if(!0===e.privileged)throw Error("no privilege support");if(!0===e.identityKey){if(null===this.keyDeriver||void 0===this.keyDeriver)throw Error("keyDeriver is not initialized");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==e.protocolID||"string"!=typeof e.keyID||""===e.keyID.trim())throw Error("protocolID and keyID are required if identityKey is false or undefined.");if(null===this.keyDeriver||void 0===this.keyDeriver)throw Error("keyDeriver is not initialized");return{publicKey:this.keyDeriver.derivePublicKey(e.protocolID,e.keyID,"string"==typeof e.counterparty&&""!==e.counterparty.trim()?e.counterparty:"self",!!e.forSelf).toString()}}async createAction(){throw Error("not implemented")}async signAction(){throw Error("not implemented")}async abortAction(){throw Error("not implemented")}async listActions(){throw Error("not implemented")}async internalizeAction(){throw Error("not implemented")}async listOutputs(){throw Error("not implemented")}async relinquishOutput(){throw Error("not implemented")}async acquireCertificate(){throw Error("not implemented")}async listCertificates(){throw Error("not implemented")}async proveCertificate(){throw Error("not implemented")}async relinquishCertificate(){throw Error("not implemented")}async discoverByIdentityKey(){throw Error("not implemented")}async discoverByAttributes(){throw Error("not implemented")}async getHeight(){throw Error("not implemented")}async getHeaderForHeight(){throw Error("not implemented")}}class nN{sessionNonceToSession;identityKeyToNonces;constructor(){this.sessionNonceToSession=new Map,this.identityKeyToNonces=new Map}addSession(e){if("string"!=typeof e.sessionNonce)throw 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){let t,i=this.sessionNonceToSession.get(e);if(null!=i)return i;let r=this.identityKeyToNonces.get(e);if(null!=r&&0!==r.size){for(let e of r){let i=this.sessionNonceToSession.get(e);null!=i&&(null==t?t=i:(i.lastUpdate??0)>(t.lastUpdate??0)&&(t=i))}return t}}removeSession(e){if("string"==typeof e.sessionNonce&&this.sessionNonceToSession.delete(e.sessionNonce),"string"==typeof e.peerIdentityKey){let t=this.identityKeyToNonces.get(e.peerIdentityKey);null!=t&&(t.delete(e.sessionNonce??""),0===t.size&&this.identityKeyToNonces.delete(e.peerIdentityKey))}}hasSession(e){if(this.sessionNonceToSession.has(e))return!0;let t=this.identityKeyToNonces.get(e);return null!=t&&t.size>0}}async function nO(e,t,i="self",r){let n=ti(e,"base64"),a=n.slice(0,16),s=n.slice(16),{valid:o}=await t.verifyHmac({data:a,hmac:s,protocolID:[2,"server hmac"],keyID:ts(a),counterparty:i},r);return o}async function nT(e,t="self",i){let r=t0(16),{hmac:n}=await e.createHmac({protocolID:[2,"server hmac"],keyID:ts(r),data:r,counterparty:t},i);return tc([...r,...n])}let n_=async(e,t,i,r)=>{let n=await e.listCertificates({certifiers:t.certifiers,types:Object.keys(t.types)},r);return await Promise.all(n.certificates.map(async n=>{let{keyringForVerifier:a}=await e.proveCertificate({certificate:n,fieldsToReveal:t.types[n.type],verifier:i},r);return new nP(n.type,n.serialNumber,n.subject,n.certifier,n.revocationOutpoint,n.fields,a,n.signature)}))},nR=async(e,t,i,r)=>{if(null==t.certificates||0===t.certificates.length)throw Error("No certificates were provided in the AuthMessage.");await Promise.all(t.certificates.map(async n=>{if(n.subject!==t.identityKey)throw Error(`The subject of one of your certificates ("${n.subject}") is not the same as the request sender ("${t.identityKey}").`);let a=new nP(n.type,n.serialNumber,n.subject,n.certifier,n.revocationOutpoint,n.fields,n.keyring,n.signature);if(!await a.verify())throw Error(`The signature for the certificate with serial number ${a.serialNumber} is invalid!`);if(null!=i){let{certifiers:e,types:t}=i;if(!e.includes(a.certifier))throw Error(`Certificate with serial number ${a.serialNumber} has an unrequested certifier: ${a.certifier}`);if(null==t[a.type])throw Error(`Certificate with type ${a.type} was not requested`)}await a.decryptFields(e,void 0,void 0,r)}))},nC="u">typeof globalThis?globalThis.Buffer:void 0;class nB{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;certificateValidationPromises=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;originator;identityPublicKey;constructor(e,t,i,r,n,a){this.wallet=e,this.originator=a,this.transport=t,this.certificatesToRequest=i??{certifiers:[],types:{}},this.transport.onData(this.handleIncomingMessage.bind(this)).catch(e=>{throw e}),this.sessionManager=null!=r?r:new nN,!1===n?this.autoPersistLastSession=!1:this.autoPersistLastSession=!0}async toPeer(e,t){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);let i=await this.getAuthenticatedSession(t);if(null==i.peerIdentityKey)throw Error("Peer identity is not established");if(!0===i.certificatesRequired&&!0!==i.certificatesValidated)throw Error("Cannot send general message before certificate validation is complete");let r=tc(t0(32)),{signature:n}=await this.wallet.createSignature({data:e,protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),a={version:"0.1",messageType:"general",identityKey:await this.getIdentityPublicKey(),nonce:r,yourNonce:i.peerNonce,payload:e,signature:n};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(a)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}async requestCertificates(e,t){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);let i=await this.getAuthenticatedSession(t),r=tc(t0(32)),{signature:n}=await this.wallet.createSignature({data:nB.utf8ToBytes(JSON.stringify(e)),protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),a={version:"0.1",messageType:"certificateRequest",identityKey:await this.getIdentityPublicKey(),nonce:r,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,requestedCertificates:e,signature:n};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(a)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}async getAuthenticatedSession(e){let t;if(void 0===this.transport)throw Error("Peer transport is not connected!");if("string"==typeof e&&(t=this.sessionManager.getSession(e)),null==t||!t.isAuthenticated){let i=await this.initiateHandshake(e);if(null==(t=this.sessionManager.getSession(i))||!t.isAuthenticated)throw Error("Unable to establish mutual authentication with peer!")}return t}listenForGeneralMessages(e){let t=this.callbackIdCounter++;return this.onGeneralMessageReceivedCallbacks.set(t,e),t}stopListeningForGeneralMessages(e){this.onGeneralMessageReceivedCallbacks.delete(e)}listenForCertificatesReceived(e){let t=this.callbackIdCounter++;return this.onCertificatesReceivedCallbacks.set(t,e),t}stopListeningForCertificatesReceived(e){this.onCertificatesReceivedCallbacks.delete(e)}listenForCertificatesRequested(e){let t=this.callbackIdCounter++;return this.onCertificateRequestReceivedCallbacks.set(t,e),t}stopListeningForCertificatesRequested(e){this.onCertificateRequestReceivedCallbacks.delete(e)}async initiateHandshake(e){let t=await nT(this.wallet,void 0,this.originator),i=Date.now(),r=this.certificatesToRequest.certifiers.length>0;this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:t,peerIdentityKey:e,lastUpdate:i,certificatesRequired:r,certificatesValidated:!r});let n={version:"0.1",messageType:"initialRequest",identityKey:await this.getIdentityPublicKey(),initialNonce:t,requestedCertificates:this.certificatesToRequest};return await this.transport.send(n),await this.waitForInitialResponse(t)}async waitForInitialResponse(e){return await new Promise(t=>{let i=this.listenForInitialResponse(e,e=>{this.stopListeningForInitialResponses(i),t(e)})})}listenForInitialResponse(e,t){let i=this.callbackIdCounter++;return this.onInitialResponseReceivedCallbacks.set(i,{callback:t,sessionNonce:e}),i}stopListeningForInitialResponses(e){this.onInitialResponseReceivedCallbacks.delete(e)}propagateTransportError(e,t){if(t instanceof Error){if(null!=e){let i=t.details;null!=i&&"object"==typeof i?null==i.peerIdentityKey&&(i.peerIdentityKey=e):t.details={peerIdentityKey:e}}throw t}throw Error(`Failed to send message to peer ${e??"unknown"}: ${String(t)}`)}async handleIncomingMessage(e){if("string"!=typeof e.version||"0.1"!==e.version)throw Error(`Invalid or unsupported message auth version! Received: ${e.version}, expected: 0.1`);try{switch(e.messageType){case"initialRequest":await this.processInitialRequest(e);break;case"initialResponse":await this.processInitialResponse(e);break;case"certificateRequest":await this.processCertificateRequest(e);break;case"certificateResponse":await this.processCertificateResponse(e);break;case"general":await this.processGeneralMessage(e);break;default:throw Error(`Unknown message type of ${String(e.messageType)} from ${String(e.identityKey)}`)}}catch(e){}}async processInitialRequest(e){let t;if("string"!=typeof e.identityKey||"string"!=typeof e.initialNonce||""===e.initialNonce)throw Error("Missing required fields in initialRequest message.");let i=await nT(this.wallet,void 0,this.originator),r=Date.now(),n=Array.isArray(this.certificatesToRequest?.certifiers)&&this.certificatesToRequest.certifiers.length>0;this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:i,peerNonce:e.initialNonce,peerIdentityKey:e.identityKey,lastUpdate:r,certificatesRequired:n,certificatesValidated:!n}),Array.isArray(e.requestedCertificates?.certifiers)&&e.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)}):t=await n_(this.wallet,e.requestedCertificates,e.identityKey,this.originator));let{signature:a}=await this.wallet.createSignature({data:[...nB.base64ToBytes(e.initialNonce),...nB.base64ToBytes(i)],protocolID:[2,"auth message signature"],keyID:`${e.initialNonce} ${i}`,counterparty:e.identityKey},this.originator),s={version:"0.1",messageType:"initialResponse",identityKey:await this.getIdentityPublicKey(),initialNonce:i,yourNonce:e.initialNonce,certificates:t,requestedCertificates:this.certificatesToRequest,signature:a};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=e.identityKey),await this.transport.send(s)}async processInitialResponse(e){if(!await nO(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Initial response nonce verification failed from peer: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Peer session not found for peer: ${e.identityKey}`);let i=nB.base64ToBytes((t.sessionNonce??"")+(e.initialNonce??"")),{valid:r}=await this.wallet.verifySignature({data:i,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${t.sessionNonce??""} ${e.initialNonce??""}`,counterparty:e.identityKey},this.originator);if(!r)throw Error(`Unable to verify initial response signature for peer: ${e.identityKey}`);if(t.peerNonce=e.initialNonce,t.peerIdentityKey=e.identityKey,t.isAuthenticated=!0,t.certificatesRequired=Array.isArray(this.certificatesToRequest?.certifiers)&&this.certificatesToRequest.certifiers.length>0,t.certificatesValidated=!t.certificatesRequired,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),t.certificatesRequired&&Array.isArray(e.certificates)&&e.certificates.length>0&&(await nR(this.wallet,e,this.certificatesToRequest,this.originator),t.certificatesValidated=!0,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),null!=t.sessionNonce&&this.resolveCertificateValidation(t.sessionNonce),this.onCertificatesReceivedCallbacks.forEach(t=>t(e.identityKey,e.certificates))),this.lastInteractedWithPeer=e.identityKey,this.onInitialResponseReceivedCallbacks.forEach(e=>{e.sessionNonce===t.sessionNonce&&e.callback(t.sessionNonce)}),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)});else{let t=await n_(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async processCertificateRequest(e){if(!await nO(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for certificate request message from: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let{valid:i}=await this.wallet.verifySignature({data:nB.utf8ToBytes(JSON.stringify(e.requestedCertificates)),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!i)throw Error(`Invalid signature in certificate request message from ${t.peerIdentityKey}`);if(t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)});else{let t=await n_(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async sendCertificateResponse(e,t){let i=await this.getAuthenticatedSession(e),r=tc(t0(32)),{signature:n}=await this.wallet.createSignature({data:nB.utf8ToBytes(JSON.stringify(t)),protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),a={version:"0.1",messageType:"certificateResponse",identityKey:await this.getIdentityPublicKey(),nonce:r,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,certificates:t,signature:n};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(a)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}async processCertificateResponse(e){if(!await nO(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for certificate response from: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let{valid:i}=await this.wallet.verifySignature({data:nB.utf8ToBytes(JSON.stringify(e.certificates)),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:e.identityKey},this.originator);if(!i)throw Error(`Unable to verify certificate response signature for peer: ${e.identityKey}`);await nR(this.wallet,e,e.requestedCertificates,this.originator),t.certificatesValidated=!0,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),null!=t.sessionNonce&&this.resolveCertificateValidation(t.sessionNonce),this.onCertificatesReceivedCallbacks.forEach(t=>{t(e.identityKey,e.certificates??[])})}async processGeneralMessage(e){if(!await nO(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for general message from: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let i=!0===t.certificatesRequired,r=!0===t.certificatesValidated;if(i&&!r){let e=t.sessionNonce;if(null==e)throw Error("Session nonce is required for certificate validation");await new Promise((i,r)=>{let n=setTimeout(()=>{null!=this.certificateValidationPromises.get(e)&&(this.certificateValidationPromises.delete(e),r(Error(`Timeout waiting for certificate validation from peer ${t.peerIdentityKey??"unknown"}`)))},3e4);"object"==typeof n&&"unref"in n&&n.unref(),this.certificateValidationPromises.set(e,{resolve:()=>{clearTimeout(n),i()},reject:e=>{clearTimeout(n),r(e)}})})}let{valid:n}=await this.wallet.verifySignature({data:e.payload,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!n)throw Error(`Invalid signature in generalMessage from ${t.peerIdentityKey}`);t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.lastInteractedWithPeer=e.identityKey,this.onGeneralMessageReceivedCallbacks.forEach(t=>{t(e.identityKey,e.payload??[])})}resolveCertificateValidation(e){let t=this.certificateValidationPromises.get(e);null!=t&&(t.resolve(),this.certificateValidationPromises.delete(e))}async getIdentityPublicKey(){if(null!=this.identityPublicKey)return this.identityPublicKey;let{publicKey:e}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return this.identityPublicKey=e,e}static utf8ToBytes(e){return null!=nC?Array.from(nC.from(e,"utf8")):"u">typeof TextEncoder?Array.from(new TextEncoder().encode(e)):ti(e,"utf8")}static base64ToBytes(e){return null!=nC?Array.from(nC.from(e,"base64")):ti(e,"base64")}}let nU="u">typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch;class nV{onDataCallback;fetchClient;baseUrl;constructor(e,t=nU){if("function"!=typeof t)throw Error("SimplifiedFetchTransport requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=t,this.baseUrl=e}async send(e){if(null==this.onDataCallback)throw Error("Listen before you start speaking. God gave you two ears and one mouth for a reason.");if("general"!==e.messageType)return await new Promise((t,i)=>{(async()=>{try{let i=`${this.baseUrl}/.well-known/auth`,r=(async()=>{try{return await this.fetchClient(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(e){throw this.createNetworkError(i,e)}})();"initialRequest"!==e.messageType&&t();let n=await r;if(!n.ok){let e=Array.from(new Uint8Array(await n.arrayBuffer()));throw this.createUnauthenticatedResponseError(i,n,e)}if(null!=this.onDataCallback){let e=await n.json();this.onDataCallback(e)}"initialRequest"===e.messageType&&t()}catch(e){i(e)}})()});{let t,i,r=this.deserializeRequestPayload(e.payload),n=`${this.baseUrl}${r.urlPostfix}`;if("object"!=typeof r.headers&&(r.headers={}),r.headers["x-bsv-auth-version"]=e.version,r.headers["x-bsv-auth-identity-key"]=e.identityKey,r.headers["x-bsv-auth-nonce"]=e.nonce,r.headers["x-bsv-auth-your-nonce"]=e.yourNonce,r.headers["x-bsv-auth-signature"]=te(e.signature),r.headers["x-bsv-auth-request-id"]=r.requestId,null!=r.body){let e=r.headers;if(null==e["content-type"])throw Error("Content-Type header is required for requests with a body.");let t=String(e["content-type"]??"");t.includes("application/json")||t.includes("application/x-www-form-urlencoded")||t.includes("text/plain")?r.body=ts(r.body):r.body=new Uint8Array(r.body)}try{t=await this.fetchClient(n,{method:r.method,headers:r.headers,body:r.body})}catch(e){throw this.createNetworkError(n,e)}let a=Array.from(new Uint8Array(await t.arrayBuffer())),s=["x-bsv-auth-version","x-bsv-auth-identity-key","x-bsv-auth-signature"].filter(e=>{let i=t.headers.get(e);return null==i||0===i.trim().length});if(s.length>0)throw this.createUnauthenticatedResponseError(n,t,a,s);let o=t.headers.get("x-bsv-auth-requested-certificates");if(null!=o)try{i=JSON.parse(o)}catch(e){throw this.createMalformedHeaderError(n,"x-bsv-auth-requested-certificates",o,e)}let c=new tp;null!=t.headers.get("x-bsv-auth-request-id")&&c.write(ti(t.headers.get("x-bsv-auth-request-id"),"base64")),c.writeVarIntNum(t.status);let l=[];t.headers.forEach((e,t)=>{let i=t.toLowerCase();(i.startsWith("x-bsv-")||"authorization"===i)&&!i.startsWith("x-bsv-auth")&&l.push([i,e])}),l.sort(([e],[t])=>e.localeCompare(t)),c.writeVarIntNum(l.length);for(let e=0;e<l.length;e++){let t=ti(l[e][0],"utf8");c.writeVarIntNum(t.length),c.write(t);let i=ti(l[e][1],"utf8");c.writeVarIntNum(i.length),c.write(i)}c.writeVarIntNum(a.length),a.length>0&&c.write(a);let h={version:t.headers.get("x-bsv-auth-version"),messageType:"certificateRequest"===t.headers.get("x-bsv-auth-message-type")?"certificateRequest":"general",identityKey:t.headers.get("x-bsv-auth-identity-key"),nonce:t.headers.get("x-bsv-auth-nonce")??void 0,yourNonce:t.headers.get("x-bsv-auth-your-nonce")??void 0,requestedCertificates:i,payload:c.toArray(),signature:ti(t.headers.get("x-bsv-auth-signature"),"hex")};if(null==h.version)throw this.createUnauthenticatedResponseError(n,t,a);this.onDataCallback(h)}}async onData(e){this.onDataCallback=t=>{e(t)}}createNetworkError(e,t){let i=`Network error while sending authenticated request to ${e}`;if(t instanceof Error){let e=Error(`${i}: ${t.message}`);return e.stack=t.stack,e.cause=t,e}return Error(`${i}: ${String(t)}`)}createUnauthenticatedResponseError(e,t,i,r=[]){let n=(t.statusText??"").trim(),a=n.length>0?`${t.status} ${n}`:`${t.status}`,s=r.length>0?`missing headers: ${r.join(", ")}`:"response lacked required BSV auth headers",o=this.getBodyPreview(i,t.headers.get("content-type")),c=[`Received HTTP ${a} from ${e} without valid BSV authentication (${s})`];null!=o&&c.push(`body preview: ${o}`);let l=Error(c.join(" - "));return l.details={url:e,status:t.status,statusText:t.statusText,missingHeaders:r,bodyPreview:o},l}createMalformedHeaderError(e,t,i,r){let n=`Failed to parse ${t} returned by ${e}: ${i}`;if(r instanceof Error){let e=Error(`${n}. ${r.message}`);return e.stack=r.stack,e.cause=r,e}return Error(`${n}. ${String(r)}`)}getBodyPreview(e,t){let i;if(0===e.length)return;let r=e.length>1024,n=r?e.slice(0,1024):e;if(this.isTextualContent(t,n))try{i=ts(n)}catch{i=this.formatBinaryPreview(n,r)}else i=this.formatBinaryPreview(n,r);return i.length>512&&(i=`${i.slice(0,512)}…`),r&&(i=`${i} (truncated)`),i}isTextualContent(e,t){if(0===t.length)return!1;if(null!=e){let t=e.toLowerCase();if(["application/json","application/problem+json","application/xml","application/xhtml+xml","application/javascript","application/ecmascript","application/x-www-form-urlencoded","text/"].some(e=>t.includes(e))||t.includes("charset="))return!0}return t.reduce((e,t)=>9===t||10===t||13===t||t>=32&&t<=126?e+1:e,0)/t.length>.8}formatBinaryPreview(e,t){let i=e.map(e=>e.toString(16).padStart(2,"0")).join("");return`0x${i}${t?"…":""}`}deserializeRequestPayload(e){let t,i=new tg(e),r=tc(i.read(32)),n=i.readVarIntNum(),a="GET";n>0&&(a=ts(i.read(n)));let s=i.readVarIntNum(),o="";s>0&&(o=ts(i.read(s)));let c=i.readVarIntNum(),l="";c>0&&(l=ts(i.read(c)));let h={},d=i.readVarIntNum();if(d>0)for(let e=0;e<d;e++){let e=i.readVarIntNum(),t=ts(i.read(e)),r=i.readVarIntNum(),n=ts(i.read(r));h[t]=n}let u=i.readVarIntNum();return u>0&&(t=i.read(u)),{urlPostfix:o+l,method:a,headers:h,body:t,requestId:r}}}class nD{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;originator;peers={};constructor(e,t,i,r){this.wallet=e,this.requestedCertificates=t,this.sessionManager=i??new nN,this.originator=r}async fetch(e,t={}){if("number"==typeof t.retryCounter){if(t.retryCounter<=0)throw Error("Request failed after maximum number of retries.");t.retryCounter--}let i=await new Promise(async(i,r)=>{try{let n,{method:a="GET",headers:s={},body:o}=t,c=new URL(e),l=c.origin;if(void 0===this.peers[l]){let e=new nV(l);n={peer:new nB(this.wallet,e,this.requestedCertificates,this.sessionManager,void 0,this.originator),pendingCertificateRequests:[]},this.peers[l]=n,this.peers[l].peer.listenForCertificatesReceived((e,t)=>{this.certificatesReceived.push(...t)}),this.peers[l].peer.listenForCertificatesRequested(async(e,t)=>{try{this.peers[l].pendingCertificateRequests.push(!0);let i=await n_(this.wallet,t,e,this.originator);await this.peers[l].peer.sendCertificateResponse(e,i)}finally{await new Promise(e=>setTimeout(e,500)),this.peers[l].pendingCertificateRequests.shift()}})}else{if(!1===this.peers[l].supportsMutualAuth){try{let r=await this.handleFetchAndValidate(e,t,this.peers[l]);i(r)}catch(e){r(e)}return}n=this.peers[l]}let h=t0(32),d=tc(h),u=await this.serializeRequest(a,s,o,c,h);this.callbacks[d]={resolve:i,reject:r};let f=n.peer.listenForGeneralMessages((e,t)=>{let i,r=new tg(t);if(tc(r.read(32))!==d)return;n.peer.stopListeningForGeneralMessages(f),this.peers[l].identityKey=e,this.peers[l].supportsMutualAuth=!0;let a=r.readVarIntNum(),s={},o=r.readVarIntNum();if(o>0)for(let e=0;e<o;e++){let e=r.readVarIntNum(),t=r.read(e),i=ts(t),n=r.readVarIntNum(),a=r.read(n),o=ts(a);s[i]=o}s["x-bsv-auth-identity-key"]=e;let c=r.readVarIntNum();c>0&&(i=r.read(c));let h=new Response(i?new Uint8Array(i):null,{status:a,statusText:`${a}`,headers:new Headers(s)});this.callbacks[d].resolve(h),delete this.callbacks[d]});n.pendingCertificateRequests.length>0&&await new Promise((e,t)=>{let i=Date.now(),r=()=>{0===n.pendingCertificateRequests.length?e():Date.now()-i>3e4?t(Error("Timeout waiting for certificate request to complete")):setTimeout(r,100)};r()}),await n.peer.toPeer(u.toArray(),n.identityKey).catch(async a=>{if(a.message.includes("Session not found for nonce")){delete this.peers[l],t.retryCounter??=3;let r=await this.fetch(e,t);i(r);return}if(a.message.includes("HTTP server failed to authenticate"))try{let r=await this.handleFetchAndValidate(e,t,n);i(r);return}catch(e){r(e)}else r(a)})}catch(e){r(e)}});return 402===i.status?await this.handlePaymentAndRetry(e,t,i):i}async sendCertificateRequest(e,t){let i,r=new URL(e).origin;if(void 0!==this.peers[r])i={peer:this.peers[r].peer};else{let e=new nV(r);i={peer:new nB(this.wallet,e,this.requestedCertificates,this.sessionManager,this.originator)},this.peers[r]=i}return await new Promise(async(e,r)=>{let 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,i,r,n){let a=new tp;if(a.write(n),a.writeVarIntNum(e.length),a.write(ti(e)),r.pathname.length>0){let e=ti(r.pathname);a.writeVarIntNum(e.length),a.write(e)}else a.writeVarIntNum(-1);if(r.search.length>0){let e=ti(r.search);a.writeVarIntNum(e.length),a.write(e)}else a.writeVarIntNum(-1);let s=[];for(let[e,i]of Object.entries(t))if((e=e.toLowerCase()).startsWith("x-bsv-")||"authorization"===e){if(e.startsWith("x-bsv-auth"))throw Error("No BSV auth headers allowed here!");s.push([e,i])}else if(e.startsWith("content-type"))i=i.split(";")[0].trim(),s.push([e,i]);else throw Error("Unsupported header in the simplified fetch implementation. Only content-type, authorization, and x-bsv-* headers are supported.");s.sort(([e],[t])=>e.localeCompare(t)),a.writeVarIntNum(s.length);for(let e=0;e<s.length;e++){let t=ti(s[e][0],"utf8");a.writeVarIntNum(t.length),a.write(t);let i=ti(s[e][1],"utf8");a.writeVarIntNum(i.length),a.write(i)}if(["POST","PUT","PATCH","DELETE"].includes(e.toUpperCase())&&void 0===i){let e=s.find(([e])=>"content-type"===e);i=e&&e[1].includes("application/json")?"{}":""}if(i){let e=await this.normalizeBodyToNumberArray(i);a.writeVarIntNum(e.length),a.write(e)}else a.writeVarIntNum(-1);return a}async handleFetchAndValidate(e,t,i){let r=await fetch(e,t);if(r.headers.forEach(e=>{if(e.toLocaleLowerCase().startsWith("x-bsv"))throw Error("The server is trying to claim it has been authenticated when it has not!")}),r.ok)return i.supportsMutualAuth=!1,r;throw Error(`Request failed with status: ${r.status}`)}async handlePaymentAndRetry(e,t={},i){let r=i.headers.get("x-bsv-payment-version");if(!r||"1.0"!==r)throw Error(`Unsupported x-bsv-payment-version response header. Client version: 1.0, Server version: ${r}`);let n=i.headers.get("x-bsv-payment-satoshis-required");if(!n)throw Error("Missing x-bsv-payment-satoshis-required response header.");let a=parseInt(n);if(isNaN(a)||a<=0)throw Error("Invalid x-bsv-payment-satoshis-required response header value.");let s=i.headers.get("x-bsv-auth-identity-key");if("string"!=typeof s)throw Error("Missing x-bsv-auth-identity-key response header.");let o=i.headers.get("x-bsv-payment-derivation-prefix");if("string"!=typeof o||o.length<1)throw Error("Missing x-bsv-payment-derivation-prefix response header.");let c=t.paymentContext;if(null!=c?this.isPaymentContextCompatible(c,a,s,o)||(this.logPaymentAttempt("warn","Server adjusted payment requirements; regenerating transaction",this.composePaymentLogDetails(e,c)),c=await this.createPaymentContext(e,t,a,s,o)):c=await this.createPaymentContext(e,t,a,s,o),c.attempts>=c.maxAttempts)throw this.buildPaymentFailureError(e,c,Error("Maximum payment attempts exceeded before retrying"));let l={...t.headers??{}};l["x-bsv-payment"]=JSON.stringify({derivationPrefix:c.derivationPrefix,derivationSuffix:c.derivationSuffix,transaction:c.transactionBase64});let h={...t,headers:l,paymentContext:c};"number"!=typeof h.retryCounter&&(h.retryCounter=3);let d=c.attempts+1,u=c.maxAttempts;c.attempts=d;let f=this.composePaymentLogDetails(e,c);this.logPaymentAttempt("warn",`Attempting paid request (${d}/${u})`,f);try{let t=await this.fetch(e,h);return this.logPaymentAttempt("info",`Paid request attempt ${d} succeeded`,f),t}catch(n){let t=this.createPaymentErrorEntry(c.attempts,n);if(c.errors.push(t),this.logPaymentAttempt("error",`Paid request attempt ${d} failed`,{...f,error:{message:t.message,stack:t.stack}}),c.attempts>=c.maxAttempts)throw this.buildPaymentFailureError(e,c,n);let r=this.getPaymentRetryDelay(c.attempts);return await this.wait(r),this.handlePaymentAndRetry(e,h,i)}}isPaymentContextCompatible(e,t,i,r){return e.satoshisRequired===t&&e.serverIdentityKey===i&&e.derivationPrefix===r}async createPaymentContext(e,t,i,r,n){let a=await nT(this.wallet,void 0,this.originator),{publicKey:s}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${n} ${a}`,counterparty:r},this.originator),o=new iL().lock(tJ.fromString(s).toAddress()).toHex(),{tx:c}=await this.wallet.createAction({description:`Payment for request to ${new URL(e).origin}`,outputs:[{satoshis:i,lockingScript:o,customInstructions:JSON.stringify({derivationPrefix:n,derivationSuffix:a,payee:r}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}},this.originator),{publicKey:l}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return{satoshisRequired:i,transactionBase64:tc(c),derivationPrefix:n,derivationSuffix:a,serverIdentityKey:r,clientIdentityKey:l,attempts:0,maxAttempts:this.getMaxPaymentAttempts(t),errors:[],requestSummary:this.buildPaymentRequestSummary(e,t)}}getMaxPaymentAttempts(e){let t="number"==typeof e.paymentRetryAttempts?e.paymentRetryAttempts:void 0;return"number"==typeof t&&t>0?Math.floor(t):3}buildPaymentRequestSummary(e,t){let i={...t.headers??{}},r="string"==typeof t.method?t.method.toUpperCase():"GET",n=this.describeRequestBodyForLogging(t.body);return{url:e,method:r,headers:i,bodyType:n.type,bodyByteLength:n.byteLength}}describeRequestBodyForLogging(e){if(null==e)return{type:"none",byteLength:0};if("string"==typeof e)return{type:"string",byteLength:ti(e,"utf8").length};if(Array.isArray(e))return e.every(e=>"number"==typeof e)?{type:"number[]",byteLength:e.length}:{type:"array",byteLength:e.length};if("u">typeof ArrayBuffer&&e instanceof ArrayBuffer)return{type:"ArrayBuffer",byteLength:e.byteLength};if("u">typeof ArrayBuffer&&ArrayBuffer.isView(e))return{type:null!=e.constructor?e.constructor.name:"TypedArray",byteLength:e.byteLength};if("u">typeof Blob&&e instanceof Blob)return{type:"Blob",byteLength:e.size};if("u">typeof FormData&&e instanceof FormData)return{type:"FormData",byteLength:0};if("u">typeof URLSearchParams&&e instanceof URLSearchParams)return{type:"URLSearchParams",byteLength:ti(e.toString(),"utf8").length};if("u">typeof ReadableStream&&e instanceof ReadableStream)return{type:"ReadableStream",byteLength:0};try{let t=JSON.stringify(e);if("string"==typeof t)return{type:"object",byteLength:ti(t,"utf8").length}}catch(e){}return{type:typeof e,byteLength:0}}composePaymentLogDetails(e,t){return{url:e,request:t.requestSummary,payment:{satoshis:t.satoshisRequired,transactionBase64:t.transactionBase64,derivationPrefix:t.derivationPrefix,derivationSuffix:t.derivationSuffix,serverIdentityKey:t.serverIdentityKey,clientIdentityKey:t.clientIdentityKey},attempts:{used:t.attempts,max:t.maxAttempts},errors:t.errors}}logPaymentAttempt(e,t,i){let r="[AuthFetch][Payment]";"error"===e?console.error(`${r} ${t}`,i):"warn"===e?console.warn(`${r} ${t}`,i):"function"==typeof console.info?console.info(`${r} ${t}`,i):console.log(`${r} ${t}`,i)}createPaymentErrorEntry(e,t){let i={attempt:e,timestamp:new Date().toISOString(),message:"",stack:void 0};return t instanceof Error?(i.message=t.message,i.stack=t.stack??void 0):i.message=String(t),i}getPaymentRetryDelay(e){return 250*Math.min(e,5)}async wait(e){e<=0||await new Promise(t=>setTimeout(t,e))}buildPaymentFailureError(e,t,i){let r=Error(`Paid request to ${e} failed after ${t.attempts}/${t.maxAttempts} attempts. Sent ${t.satoshisRequired} satoshis to ${t.serverIdentityKey}.`);return r.details={request:t.requestSummary,payment:{satoshis:t.satoshisRequired,transactionBase64:t.transactionBase64,derivationPrefix:t.derivationPrefix,derivationSuffix:t.derivationSuffix,serverIdentityKey:t.serverIdentityKey,clientIdentityKey:t.clientIdentityKey},attempts:{used:t.attempts,max:t.maxAttempts},errors:t.errors},i instanceof Error&&(r.cause=i),r}async normalizeBodyToNumberArray(e){if(null==e)return[];if("object"==typeof e)return ti(JSON.stringify(e,"utf8"));if(Array.isArray(e)&&e.every(e=>"number"==typeof e))return e;if("string"==typeof e)return ti(e,"utf8");if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Array.from(new Uint8Array(e instanceof ArrayBuffer?e:e.buffer));if(e instanceof Blob)return Array.from(new Uint8Array(await e.arrayBuffer()));if(e instanceof FormData){let t=[];return e.forEach((e,i)=>{t.push([i,e.toString()])}),ti(new URLSearchParams(t).toString(),"utf8")}if(e instanceof URLSearchParams)return ti(e.toString(),"utf8");if(e instanceof ReadableStream)throw Error("ReadableStream cannot be directly converted to number[].");throw Error("Unsupported body type in this SimplifiedFetch implementation.")}}class nL{pushDrop;static decode(e){let t=iK.decode(e);if(t.fields.length<4)throw Error("Invalid SHIP/SLAP advertisement!");let i=ts(t.fields[0]);if("SHIP"!==i&&"SLAP"!==i)throw Error("Invalid protocol type!");let r=te(t.fields[1]);return{protocol:i,identityKey:r,domain:ts(t.fields[2]),topicOrService:ts(t.fields[3])}}constructor(e,t){this.pushDrop=new iK(e,t)}async lock(e,t,i){let{publicKey:r}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([ti(e,"utf8"),ti(r,"hex"),ti(t,"utf8"),ti(i,"utf8")],[2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}unlock(e){return this.pushDrop.unlock([2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}}let nF="bsvsdk_overlay_host_reputation_v1";class nH{stats;store;constructor(e){this.stats=new Map,this.store=e??this.getLocalStorageAdapter(),this.loadFromStorage()}reset(){this.stats.clear()}recordSuccess(e,t){let i=this.getOrCreate(e),r=Date.now(),n=Number.isFinite(t)&&t>=0?t:1500;null===i.avgLatencyMs?i.avgLatencyMs=n:i.avgLatencyMs=.75*i.avgLatencyMs+.25*n,i.lastLatencyMs=n,i.totalSuccesses+=1,i.consecutiveFailures=0,i.backoffUntil=0,i.lastUpdatedAt=r,i.lastError=void 0,this.saveToStorage()}recordFailure(e,t){let i=this.getOrCreate(e),r=Date.now();i.totalFailures+=1,i.consecutiveFailures+=1;let n="string"==typeof t?t:t instanceof Error?t.message:void 0;"string"==typeof n&&(n.includes("ERR_NAME_NOT_RESOLVED")||n.includes("ENOTFOUND")||n.includes("getaddrinfo")||n.includes("Failed to fetch"))&&i.consecutiveFailures<3&&(i.consecutiveFailures=3);let a=Math.max(i.consecutiveFailures-2,0);0===a?i.backoffUntil=0:i.backoffUntil=r+Math.min(6e4,1e3*Math.pow(2,a-1)),i.lastUpdatedAt=r,i.lastError="string"==typeof t?t:t instanceof Error?t.message:void 0,this.saveToStorage()}rankHosts(e,t=Date.now()){let i=new Map;e.forEach((e,t)=>{"string"==typeof e&&0!==e.length&&(i.has(e)||i.set(e,t))});let r=Array.from(i.keys()).map(e=>{let r=this.getOrCreate(e);return{...r,score:this.computeScore(r,t),originalOrder:i.get(e)??0}});return r.sort((e,i)=>{let r=e.backoffUntil>t;return r!==i.backoffUntil>t?r?1:-1:e.score!==i.score?e.score-i.score:e.totalSuccesses!==i.totalSuccesses?i.totalSuccesses-e.totalSuccesses:e.originalOrder-i.originalOrder}),r.map(({originalOrder:e,...t})=>t)}snapshot(e){let t=this.stats.get(e);return null!=t?{...t}:void 0}getStorage(){try{let e="object"==typeof globalThis?globalThis:void 0;if(null==e||null==e.localStorage)return;return e.localStorage}catch{return}}getLocalStorageAdapter(){let e=this.getStorage();if(null!=e)return{get:t=>{try{return e.getItem(t)}catch{return null}},set:(t,i)=>{try{e.setItem(t,i)}catch{}}}}loadFromStorage(){let e=this.store;if(null!=e)try{let t=e.get(nF);if("string"!=typeof t||0===t.length)return;let i=JSON.parse(t);if("object"!=typeof i||null===i)return;for(let e of(this.stats.clear(),Object.keys(i))){let t=i[e];if(null!=t&&"object"==typeof t){let i={host:String(t.host??e),totalSuccesses:Number(t.totalSuccesses??0),totalFailures:Number(t.totalFailures??0),consecutiveFailures:Number(t.consecutiveFailures??0),avgLatencyMs:null==t.avgLatencyMs?null:Number(t.avgLatencyMs),lastLatencyMs:null==t.lastLatencyMs?null:Number(t.lastLatencyMs),backoffUntil:Number(t.backoffUntil??0),lastUpdatedAt:Number(t.lastUpdatedAt??0),lastError:"string"==typeof t.lastError?t.lastError:void 0};this.stats.set(i.host,i)}}}catch{}}saveToStorage(){let e=this.store;if(null!=e)try{let t={};for(let[e,i]of this.stats.entries())t[e]=i;e.set(nF,JSON.stringify(t))}catch{}}computeScore(e,t){let i=e.avgLatencyMs??1500,r=400*e.consecutiveFailures,n=Math.min(30*e.totalSuccesses,i/2);return i+r+(e.backoffUntil>t?e.backoffUntil-t:0)-n}getOrCreate(e){let t=this.stats.get(e);return null==t&&(t={host:e,totalSuccesses:0,totalFailures:0,consecutiveFailures:0,avgLatencyMs:null,lastLatencyMs:null,backoffUntil:0,lastUpdatedAt:0},this.stats.set(e,t)),t}}let nK=new nH,nM="u">typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch,nq=["https://overlay-us-1.bsvb.tech","https://overlay-eu-1.bsvb.tech","https://overlay-ap-1.bsvb.tech","https://users.bapp.dev"],n$=["https://testnet-users.bapp.dev"];class nz{fetchClient;allowHTTP;constructor(e=nM,t=!1){if("function"!=typeof e)throw Error("HTTPSOverlayLookupFacilitator requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=e,this.allowHTTP=t}async lookup(e,t,i=5e3){if(!e.startsWith("https:")&&!this.allowHTTP)throw Error('HTTPS facilitator can only use URLs that start with "https:"');let r="u">typeof AbortController?new AbortController:void 0,n=setTimeout(()=>{try{r?.abort()}catch{}},i);try{let i={method:"POST",headers:{"Content-Type":"application/json","X-Aggregation":"yes"},body:JSON.stringify({service:t.service,query:t.query}),signal:r?.signal},n=await this.fetchClient(`${e}/lookup`,i);if(!n.ok)throw Error(`Failed to facilitate lookup (HTTP ${n.status})`);if("application/octet-stream"!==n.headers.get("content-type"))return await n.json();{let e=await n.arrayBuffer(),t=new tg([...new Uint8Array(e)]),i=t.readVarIntNum(),r=[];for(let e=0;e<i;e++){let e,i=te(t.read(32)),n=t.readVarIntNum(),a=t.readVarIntNum();a>0&&(e=t.read(a)),r.push({txid:i,outputIndex:n,context:e})}let a=t.read();return{type:"output-list",outputs:r.map(e=>({outputIndex:e.outputIndex,context:e.context,beef:i3.fromBEEF(a,e.txid).toBEEF()}))}}}catch(e){if(e?.name==="AbortError")throw Error("Request timed out");throw e}finally{clearTimeout(n)}}}class nW{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;hostReputation;hostsCache;hostsInFlight;hostsTtlMs;hostsMaxEntries;txMemo;txMemoTtlMs;constructor(e={}){this.networkPreset=e.networkPreset??"mainnet",this.facilitator=e.facilitator??new nz(void 0,"local"===this.networkPreset),this.slapTrackers=e.slapTrackers??("mainnet"===this.networkPreset?nq:n$);const t=e.hostOverrides??{};this.assertValidOverrideServices(t),this.hostOverrides=t,this.additionalHosts=e.additionalHosts??{};const i=e.reputationStorage;"localStorage"===i?this.hostReputation=new nH:"object"==typeof i&&null!==i&&"function"==typeof i.get&&"function"==typeof i.set?this.hostReputation=new nH(i):this.hostReputation=nK,this.hostsTtlMs=e.cache?.hostsTtlMs??3e5,this.hostsMaxEntries=e.cache?.hostsMaxEntries??128,this.txMemoTtlMs=e.cache?.txMemoTtlMs??6e5,this.hostsCache=new Map,this.hostsInFlight=new Map,this.txMemo=new Map}async query(e,t){let i=[];if(i="ls_slap"===e.service?"local"===this.networkPreset?["http://localhost:8080"]:this.slapTrackers:null!=this.hostOverrides[e.service]?this.hostOverrides[e.service]:"local"===this.networkPreset?["http://localhost:8080"]:await this.getCompetentHostsCached(e.service),this.additionalHosts[e.service]?.length>0){let t=this.additionalHosts[e.service],r=new Set(i);for(let e of t)r.has(e)||i.push(e)}if(i.length<1)throw Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${e.service}`);let r=this.prepareHostsForQuery(i,`lookup service ${e.service}`);if(r.length<1)throw Error(`All competent hosts for ${e.service} are temporarily unavailable due to backoff.`);let n=await Promise.allSettled(r.map(async i=>await this.lookupHostWithTracking(i,e,t))),a=new Map,s=e=>"object"!=typeof e?"":e.join(",");for(let e of n){if("fulfilled"!==e.status)continue;let t=e.value;if(t?.type==="output-list"&&Array.isArray(t.outputs))for(let e of t.outputs){let t=s(e.beef),i=this.txMemo.get(t),r=Date.now();if("object"!=typeof i||null===i||i.expiresAt<=r)try{i={txId:i3.fromBEEF(e.beef).id("hex"),expiresAt:r+this.txMemoTtlMs},this.txMemo.size>4096&&this.evictOldest(this.txMemo),this.txMemo.set(t,i)}catch{continue}let n=`${i.txId}.${e.outputIndex}`;a.set(n,e)}}return{type:"output-list",outputs:Array.from(a.values())}}async getCompetentHostsCached(e){let t=Date.now(),i=this.hostsCache.get(e);if("object"==typeof i&&i.expiresAt>t)return i.hosts.slice();if("object"==typeof i&&i.expiresAt<=t)return this.hostsInFlight.has(e)||this.hostsInFlight.set(e,this.refreshHosts(e).finally(()=>{this.hostsInFlight.delete(e)})),i.hosts.slice();if(this.hostsInFlight.has(e))try{let t=await this.hostsInFlight.get(e);if("object"!=typeof t)throw Error("Hosts is not defined.");return t.slice()}catch{}let r=this.refreshHosts(e).finally(()=>{this.hostsInFlight.delete(e)});return this.hostsInFlight.set(e,r),(await r).slice()}async refreshHosts(e){let t=await this.findCompetentHosts(e),i=Date.now()+this.hostsTtlMs;if(!this.hostsCache.has(e)&&this.hostsCache.size>=this.hostsMaxEntries){let e=this.hostsCache.keys().next().value;void 0!==e&&this.hostsCache.delete(e)}return this.hostsCache.set(e,{hosts:t,expiresAt:i}),t}async findCompetentHosts(e){let t={service:"ls_slap",query:{service:e}},i=this.prepareHostsForQuery(this.slapTrackers,"SLAP trackers");if(0===i.length)return[];let r=await Promise.allSettled(i.map(async e=>await this.lookupHostWithTracking(e,t,5e3))),n=new Set;for(let t of r){if("fulfilled"!==t.status)continue;let i=t.value;if("output-list"===i.type)for(let t of i.outputs)try{let i=i3.fromBEEF(t.beef),r=i.outputs[t.outputIndex]?.lockingScript;if("object"!=typeof r||null===r)continue;let a=nL.decode(r);if(a.topicOrService!==e||"SLAP"!==a.protocol)continue;"string"==typeof a.domain&&a.domain.length>0&&n.add(a.domain)}catch{continue}}return[...n]}evictOldest(e){let t=e.keys().next().value;void 0!==t&&e.delete(t)}assertValidOverrideServices(e){for(let t of Object.keys(e))if(!t.startsWith("ls_"))throw Error(`Host override service names must start with "ls_": ${t}`)}prepareHostsForQuery(e,t){if(0===e.length)return[];let i=Date.now(),r=this.hostReputation.rankHosts(e,i),n=r.filter(e=>e.backoffUntil<=i).map(e=>e.host);if(n.length>0)return n;let a=Math.max(Math.min(...r.map(e=>e.backoffUntil))-i,0);throw Error(`All ${t} hosts are backing off for approximately ${a}ms due to repeated failures.`)}async lookupHostWithTracking(e,t,i){let r=Date.now();try{let n=await this.facilitator.lookup(e,t,i),a=Date.now()-r;return"object"==typeof n&&null!==n&&"output-list"===n.type&&Array.isArray(n.outputs)?this.hostReputation.recordSuccess(e,a):this.hostReputation.recordFailure(e,"Invalid lookup response"),n}catch(t){throw this.hostReputation.recordFailure(e,t),t}}}class nj{httpClient;allowHTTP;constructor(e=fetch,t=!1){this.httpClient=e,this.allowHTTP=t}async send(e,t){let i;if(!e.startsWith("https:")&&!this.allowHTTP)throw Error('HTTPS facilitator can only use URLs that start with "https:"');let r={"Content-Type":"application/octet-stream","X-Topics":JSON.stringify(t.topics)};if(Array.isArray(t.offChainValues)){r["x-includes-off-chain-values"]="true";let e=new tp;e.writeVarIntNum(t.beef.length),e.write(t.beef),e.write(t.offChainValues),i=new Uint8Array(e.toArray())}else i=new Uint8Array(t.beef);let n=await fetch(`${e}/submit`,{method:"POST",headers:r,body:i});if(n.ok)return await n.json();throw Error("Failed to facilitate broadcast")}}class nX{topics;facilitator;resolver;requireAcknowledgmentFromAllHostsForTopics;requireAcknowledgmentFromAnyHostForTopics;requireAcknowledgmentFromSpecificHostsForTopics;networkPreset;constructor(e,t={}){if(0===e.length)throw Error("At least one topic is required for broadcast.");if(e.some(e=>!e.startsWith("tm_")))throw Error('Every topic must start with "tm_".');this.topics=e,this.networkPreset=t.networkPreset??"mainnet",this.facilitator=t.facilitator??new nj(void 0,"local"===this.networkPreset),this.resolver=t.resolver??new nW({networkPreset:this.networkPreset}),this.requireAcknowledgmentFromAllHostsForTopics=t.requireAcknowledgmentFromAllHostsForTopics??[],this.requireAcknowledgmentFromAnyHostForTopics=t.requireAcknowledgmentFromAnyHostForTopics??"all",this.requireAcknowledgmentFromSpecificHostsForTopics=t.requireAcknowledgmentFromSpecificHostsForTopics??{}}async broadcast(e){let t,i,r,n,a,s=e.metadata.get("OffChainValues");try{t=e.toBEEF()}catch(e){throw Error("Transactions sent via SHIP to Overlay Services must be serializable to BEEF format.")}let o=await this.findInterestedHosts();if(0===Object.keys(o).length)return{status:"error",code:"ERR_NO_HOSTS_INTERESTED",description:`No ${this.networkPreset} hosts are interested in receiving this transaction.`};let c=Object.entries(o).map(async([e,i])=>{try{let r=await this.facilitator.send(e,{beef:t,offChainValues:s,topics:[...i]});if(null==r||0===Object.keys(r).length)throw Error("Steak has no topics.");return{host:e,success:!0,steak:r}}catch(t){return console.error(t),{host:e,success:!1,error:t}}}),l=(await Promise.all(c)).filter(e=>e.success);if(0===l.length)return{status:"error",code:"ERR_ALL_HOSTS_REJECTED",description:`All ${this.networkPreset} topical hosts have rejected the transaction.`};let h={};for(let e of l){let t=e.host,i=e.steak,r=new Set;for(let[e,t]of Object.entries(i)){let i=t.outputsToAdmit,n=t.coinsToRetain,a=t.coinsRemoved;(i?.length>0||n?.length>0||a?.length>0)&&r.add(e)}h[t]=r}return("all"===this.requireAcknowledgmentFromAllHostsForTopics?(i=this.topics,r="all"):"any"===this.requireAcknowledgmentFromAllHostsForTopics?(i=this.topics,r="any"):(i=Array.isArray(this.requireAcknowledgmentFromAllHostsForTopics)?this.requireAcknowledgmentFromAllHostsForTopics:this.topics,r="all"),i.length>0&&!this.checkAcknowledgmentFromAllHosts(h,i,r))?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ALL_HOSTS_FAILED",description:"Not all hosts acknowledged the required topics."}:("all"===this.requireAcknowledgmentFromAnyHostForTopics?(n=this.topics,a="all"):"any"===this.requireAcknowledgmentFromAnyHostForTopics?(n=this.topics,a="any"):(n=Array.isArray(this.requireAcknowledgmentFromAnyHostForTopics)?this.requireAcknowledgmentFromAnyHostForTopics:[],a="all"),n.length>0&&!this.checkAcknowledgmentFromAnyHost(h,n,a))?{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(h,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 ${l.length} Overlay Services ${1===l.length?"host":"hosts"}.`}}checkAcknowledgmentFromAllHosts(e,t,i){for(let r of Object.values(e))if("all"===i){for(let e of t)if(!r.has(e))return!1}else if("any"===i){let e=!1;for(let i of t)if(r.has(i)){e=!0;break}if(!e)return!1}return!0}checkAcknowledgmentFromAnyHost(e,t,i){if("all"===i){for(let i of Object.values(e)){let e=!0;for(let r of t)if(!i.has(r)){e=!1;break}if(e)return!0}return!1}for(let i of Object.values(e))for(let e of t)if(i.has(e))return!0;return!1}checkAcknowledgmentFromSpecificHosts(e,t){for(let[i,r]of Object.entries(t)){let t,n,a=e[i];if(null==a)return!1;if("all"===r||"any"===r)n=r,t=this.topics;else{if(!Array.isArray(r))continue;t=r,n="all"}if("all"===n){for(let e of t)if(!a.has(e))return!1}else if("any"===n){let e=!1;for(let i of t)if(a.has(i)){e=!0;break}if(!e)return!1}}return!0}async findInterestedHosts(){if("local"===this.networkPreset){let e=new Set;for(let t=0;t<this.topics.length;t++)e.add(this.topics[t]);return{"http://localhost:8080":e}}let e={},t=await this.resolver.query({service:"ls_ship",query:{topics:this.topics}},5e3);if("output-list"!==t.type)throw Error("SHIP answer is not an output list.");for(let i of t.outputs)try{let t=i3.fromBEEF(i.beef).outputs[i.outputIndex].lockingScript,r=nL.decode(t);if(!this.topics.includes(r.topicOrService)||"SHIP"!==r.protocol)continue;void 0===e[r.domain]&&(e[r.domain]=new Set),e[r.domain].add(r.topicOrService)}catch(e){continue}return e}}async function nG(e,t,i=5){let r=0;for(;r<i;){r++;try{return await e()}catch(e){if(r<i&&"WERR_REVIEW_ACTIONS"===e.name){let n=e.reviewActionResults.find(e=>"doubleSpend"===e.status);if(n?.competingBeef!=null&&n?.competingTxs!=null&&n?.competingTxs.length>0){let e=i3.fromBEEF(n.competingBeef,n.competingTxs[0]);await nG(async()=>await t.broadcast(e),t,i-r);continue}}throw e}}throw Error("Unexpected end of retry loop")}let nY=e=>(e.toLowerCase().startsWith("uhrp:")&&(e=e.slice(5)),e.startsWith("//")&&(e=e.slice(2)),e),nJ=e=>{if(32!==e.length)throw Error("Hash length must be 32 bytes (sha256)");return tu(e,ti("ce00","hex"))},nZ=e=>{let t=e instanceof Uint8Array?e:Uint8Array.from(e),i=new J;for(let e=0;e<t.length;e+=1048576){let r=t.subarray(e,e+1048576);i.update(Array.from(r))}return nJ(i.digest())},nQ=e=>{let{data:t,prefix:i}=tf(e=nY(e),void 0,2);if(32!==t.length)throw Error("Invalid length!");if("ce00"!==te(i))throw Error("Bad prefix");return t},n0=e=>{try{return nQ(e),!0}catch(e){return!1}};class n1{authFetch;baseURL;constructor(e){this.baseURL=e.storageURL,this.authFetch=new nD(e.wallet)}async getUploadInfo(e,t){let i=`${this.baseURL}/upload`,r=await this.authFetch.fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileSize:e,retentionPeriod:t})});if(!r.ok)throw Error(`Upload info request failed: HTTP ${r.status}`);let n=await r.json();if("error"===n.status)throw Error("Upload route returned an error.");return{uploadURL:n.uploadURL,requiredHeaders:n.requiredHeaders,amount:n.amount}}async uploadFile(e,t,i){let r=t.data instanceof Uint8Array?t.data:Uint8Array.from(t.data),n=await fetch(e,{method:"PUT",body:r,headers:{"Content-Type":t.type,...i}});if(!n.ok)throw Error(`File upload failed: HTTP ${n.status}`);return{published:!0,uhrpURL:nZ(r)}}async publishFile(e){let{file:t,retentionPeriod:i}=e,r=t.data instanceof Uint8Array?t.data:Uint8Array.from(t.data),n=r.byteLength,{uploadURL:a,requiredHeaders:s}=await this.getUploadInfo(n,i);return await this.uploadFile(a,{data:r,type:t.type},s)}async findFile(e){let t=new URL(`${this.baseURL}/find`);t.searchParams.set("uhrpUrl",e);let i=await this.authFetch.fetch(t.toString(),{method:"GET"});if(!i.ok)throw Error(`findFile request failed: HTTP ${i.status}`);let r=await i.json();if("error"===r.status){let e=r.code??"unknown-code",t=r.description??"no-description";throw Error(`findFile returned an error: ${e} - ${t}`)}return r.data}async listUploads(){let e=`${this.baseURL}/list`,t=await this.authFetch.fetch(e,{method:"GET"});if(!t.ok)throw Error(`listUploads request failed: HTTP ${t.status}`);let i=await t.json();if("error"===i.status){let e=i.code??"unknown-code",t=i.description??"no-description";throw Error(`listUploads returned an error: ${e} - ${t}`)}return i.uploads}async renewFile(e,t){let i=`${this.baseURL}/renew`,r=await this.authFetch.fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({uhrpUrl:e,additionalMinutes:t})});if(!r.ok)throw Error(`renewFile request failed: HTTP ${r.status}`);let n=await r.json();if("error"===n.status){let e=n.code??"unknown-code",t=n.description??"no-description";throw Error(`renewFile returned an error: ${e} - ${t}`)}return{status:n.status,prevExpiryTime:n.prevExpiryTime,newExpiryTime:n.newExpiryTime,amount:n.amount}}}class n2{networkPreset="mainnet";lookupResolver;constructor(e){this.networkPreset=e?.networkPreset??"mainnet",this.lookupResolver=new nW({networkPreset:this.networkPreset})}async resolve(e){let t=await this.lookupResolver.query({service:"ls_uhrp",query:{uhrpUrl:e}});if("output-list"!==t.type)throw Error("Lookup answer must be an output list");let i=[],r=Math.floor(Date.now()/1e3);for(let e=0;e<t.outputs.length;e++){let n=i3.fromBEEF(t.outputs[e].beef),{fields:a}=iK.decode(n.outputs[t.outputs[e].outputIndex].lockingScript);new tg(a[3]).readVarIntNum()<r||i.push(ts(a[2]))}return i}async download(e){if(!n0(e))throw Error("Invalid parameter UHRP url");let t=te(nQ(e)),i=await this.resolve(e);if(!Array.isArray(i)||0===i.length)throw Error("No one currently hosts this file!");for(let e=0;e<i.length;e++)try{let r=await fetch(i[e],{method:"GET"});if(!r.ok||r.status>=400||null==r.body)continue;let n=r.body.getReader(),a=new J,s=[],o=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;a.update(Array.from(t)),s.push(t),o+=t.length}if(te(a.digest())!==t)throw Error("Data integrity error: value of content does not match hash of the url given");let c=new Uint8Array(o),l=0;for(let e of s)c.set(e,l),l+=e.length;return{data:c,mimeType:r.headers.get("Content-Type")}}catch(e){continue}throw Error(`Unable to download content from ${e}`)}}let n8={name:"Unknown Identity",avatarURL:"XUUB8bbn9fEthk15Ge3zTQXypUShfC94vFjp65v7u5CQ8qkpxzst",identityKey:"",abbreviatedKey:"",badgeIconURL:"XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",badgeLabel:"Not verified by anyone you trust.",badgeClickURL:"https://projectbabbage.com/docs/unknown-identity"},n3={protocolID:[1,"identity"],keyID:"1",tokenAmount:1,outputIndex:0},n6={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="},n4=[2,"contact"];class n5{cache=new Map;getItem(e){return this.cache.get(e)??null}setItem(e,t){this.cache.set(e,t)}removeItem(e){this.cache.delete(e)}clear(){this.cache.clear()}}class n7{wallet;cache=new n5;CONTACTS_CACHE_KEY="metanet-contacts";originator;constructor(e,t){this.wallet=e??new nS,this.originator=t}async getContacts(e,t=!1,i=1e3){if(!t){let t=this.cache.getItem(this.CONTACTS_CACHE_KEY);if(null!=t&&""!==t)try{let i=JSON.parse(t);return null!=e?i.filter(t=>t.identityKey===e):i}catch(e){console.warn("Invalid cached contacts JSON; will reload from chain",e)}}let r=[];if(null!=e){let{hmac:t}=await this.wallet.createHmac({protocolID:n4,keyID:e,counterparty:"self",data:ti(e,"utf8")},this.originator);r.push(`identityKey ${te(t)}`)}let n=await this.wallet.listOutputs({basket:"contacts",include:"locking scripts",includeCustomInstructions:!0,tags:r,limit:i},this.originator);if(null==n.outputs||0===n.outputs.length)return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify([])),[];let a=[];for(let e of n.outputs)try{if(null==e.lockingScript)continue;let t=iK.decode(iT.fromHex(e.lockingScript));if(null==e.customInstructions)continue;let i=JSON.parse(e.customInstructions).keyID,{plaintext:r}=await this.wallet.decrypt({ciphertext:t.fields[0],protocolID:n4,keyID:i,counterparty:"self"},this.originator),n=JSON.parse(ts(r));a.push(n)}catch(e){console.warn("ContactsManager: Failed to decode contact output:",e)}return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(a)),null!=e?a.filter(t=>t.identityKey===e):a}async saveContact(e,t){let i,r=this.cache.getItem(this.CONTACTS_CACHE_KEY),n=(i=null!=r&&""!==r?JSON.parse(r):await this.getContacts()).findIndex(t=>t.identityKey===e.identityKey),a={...e,metadata:t};n>=0?i[n]=a:i.push(a);let{hmac:s}=await this.wallet.createHmac({protocolID:n4,keyID:e.identityKey,counterparty:"self",data:ti(e.identityKey,"utf8")},this.originator),o=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:[`identityKey ${te(s)}`],limit:100},this.originator),c=null,l=tc(t0(32));if(null!=o.outputs)for(let t of o.outputs)try{let[i,r]=t.outpoint.split("."),n=i3.fromBEEF(o.BEEF,i),a=iK.decode(n.outputs[Number(r)].lockingScript);if(null==t.customInstructions)continue;l=JSON.parse(t.customInstructions).keyID;let{plaintext:s}=await this.wallet.decrypt({ciphertext:a.fields[0],protocolID:n4,keyID:l,counterparty:"self"},this.originator);if(JSON.parse(ts(s)).identityKey===e.identityKey){c=t;break}}catch(e){}let h={...e,metadata:t},{ciphertext:d}=await this.wallet.encrypt({plaintext:ti(JSON.stringify(h),"utf8"),protocolID:n4,keyID:l,counterparty:"self"},this.originator),u=await new iK(this.wallet,this.originator).lock([d],n4,l,"self");if(null!=c){let[t,i]=String(c.outpoint).split("."),r=`${t}.${i}`,n=new iK(this.wallet,this.originator),{signableTransaction:a}=await this.wallet.createAction({description:"Update Contact",inputBEEF:o.BEEF,inputs:[{outpoint:r,unlockingScriptLength:74,inputDescription:"Spend previous contact output"}],outputs:[{basket:"contacts",satoshis:1,lockingScript:u.toHex(),outputDescription:`Updated Contact: ${e.name??e.identityKey.slice(0,10)}`,tags:[`identityKey ${te(s)}`],customInstructions:JSON.stringify({keyID:l})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==a)throw Error("Unable to update contact");let h=n.unlock(n4,l,"self"),d=await h.sign(i3.fromBEEF(a.tx),0),{tx:f}=await this.wallet.signAction({reference:a.reference,spends:{0:{unlockingScript:d.toHex()}}},this.originator);if(null==f)throw Error("Failed to update contact output")}else{let{tx:t}=await this.wallet.createAction({description:"Add Contact",outputs:[{basket:"contacts",satoshis:1,lockingScript:u.toHex(),outputDescription:`Contact: ${e.name??e.identityKey.slice(0,10)}`,tags:[`identityKey ${te(s)}`],customInstructions:JSON.stringify({keyID:l})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==t)throw Error("Failed to create contact output")}this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(i))}async removeContact(e){let t=this.cache.getItem(this.CONTACTS_CACHE_KEY);if(null!=t&&""!==t)try{let i=JSON.parse(t).filter(t=>t.identityKey!==e);this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(i))}catch(e){console.warn("Failed to update cache after contact removal:",e)}let i=[],{hmac:r}=await this.wallet.createHmac({protocolID:n4,keyID:e,counterparty:"self",data:ti(e,"utf8")},this.originator);i.push(`identityKey ${te(r)}`);let n=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:i,limit:100},this.originator);if(null!=n.outputs)for(let t of n.outputs)try{let[i,r]=String(t.outpoint).split("."),a=i3.fromBEEF(n.BEEF,i),s=iK.decode(a.outputs[Number(r)].lockingScript);if(null==t.customInstructions)continue;let o=JSON.parse(t.customInstructions).keyID,{plaintext:c}=await this.wallet.decrypt({ciphertext:s.fields[0],protocolID:n4,keyID:o,counterparty:"self"},this.originator);if(JSON.parse(ts(c)).identityKey===e){let e=`${i}.${r}`,t=new iK(this.wallet,this.originator),{signableTransaction:a}=await this.wallet.createAction({description:"Delete Contact",inputBEEF:n.BEEF,inputs:[{outpoint:e,unlockingScriptLength:74,inputDescription:"Spend contact output to delete"}],outputs:[],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==a)throw Error("Unable to delete contact");let s=t.unlock(n4,o,"self"),c=await s.sign(i3.fromBEEF(a.tx),0),{tx:l}=await this.wallet.signAction({reference:a.reference,spends:{0:{unlockingScript:c.toHex()}}},this.originator);if(null==l)throw Error("Failed to delete contact output");return}}catch(e){}}}class n9{options;originator;wallet;contactsManager;constructor(e,t=n3,i){this.options=t,this.originator=i,this.originator=i,this.wallet=e??new nS,this.contactsManager=new n7(this.wallet,this.originator)}async publiclyRevealAttributes(e,t){if(0===Object.keys(e.fields).length)throw Error("Public reveal failed: Certificate has no fields to reveal!");if(0===t.length)throw Error("Public reveal failed: You must reveal at least one field!");try{let t=new rC(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature);await t.verify()}catch(e){throw Error("Public reveal failed: Certificate verification failed!")}let{keyringForVerifier:i}=await this.wallet.proveCertificate({certificate:e,fieldsToReveal:t,verifier:new t3(1).toPublicKey().toString()},this.originator),r=await new iK(this.wallet,this.originator).lock([ti(JSON.stringify({...e,keyring:i}))],this.options.protocolID,this.options.keyID,"anyone",!0,!0),{tx:n}=await this.wallet.createAction({description:"Create a new Identity Token",outputs:[{satoshis:this.options.tokenAmount,lockingScript:r.toHex(),outputDescription:"Identity Token"}],options:{randomizeOutputs:!1}},this.originator);if(void 0!==n){let e=new nX(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network});return await e.broadcast(i3.fromAtomicBEEF(n))}throw Error("Public reveal failed: failed to create action!")}async resolveByIdentityKey(e,t=!0){if(t){let t=await this.contactsManager.getContacts(e.identityKey);if(t.length>0)return t}let{certificates:i}=await this.wallet.discoverByIdentityKey(e,this.originator);return i.map(e=>n9.parseIdentity(e))}async resolveByAttributes(e,t=!0){let[i,r]=await Promise.all([t?this.contactsManager.getContacts():Promise.resolve([]),this.wallet.discoverByAttributes(e,this.originator)]),n=new Map(i.map(e=>[e.identityKey,e]));return(r?.certificates??[]).map(e=>n.get(e.subject)??n9.parseIdentity(e))}async revokeCertificateRevelation(e){let t=new nW({networkPreset:(await this.wallet.getNetwork({})).network}),i=await t.query({service:"ls_identity",query:{serialNumber:e}});if("output-list"!==i.type)throw Error("Failed to get lookup result");let r=new nX(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network,requireAcknowledgmentFromAllHostsForTopics:[],requireAcknowledgmentFromAnyHostForTopics:[],requireAcknowledgmentFromSpecificHostsForTopics:{tm_identity:[]}});await nG(async()=>{let e=i3.fromBEEF(i.outputs[0].beef),t=`${e.id("hex")}.${this.options.outputIndex}`;if(void 0===e.outputs[this.options.outputIndex].lockingScript||void 0===t)throw Error("Failed to get locking script for revelation output!");let{signableTransaction:n}=await this.wallet.createAction({description:"Spend certificate revelation token",inputBEEF:i.outputs[0].beef,inputs:[{inputDescription:"Revelation token",outpoint:t,unlockingScriptLength:74}],options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1,noSend:!0}},this.originator);if(void 0===n)throw Error("Failed to create signable transaction");let a=i3.fromBEEF(n.tx),s=new iK(this.wallet,this.originator).unlock(this.options.protocolID,this.options.keyID,"anyone"),o=await s.sign(a,this.options.outputIndex),{tx:c}=await this.wallet.signAction({reference:n.reference,spends:{[this.options.outputIndex]:{unlockingScript:o.toHex()}},options:{acceptDelayedBroadcast:!1,noSend:!0}},this.originator);if(void 0===c)throw Error("Failed to sign transaction");await r.broadcast(i3.fromAtomicBEEF(c))},r)}async getContacts(e,t=!1,i=1e3){return await this.contactsManager.getContacts(e,t,i)}async saveContact(e,t){return await this.contactsManager.saveContact(e,t)}async removeContact(e){return await this.contactsManager.removeContact(e)}static parseIdentity(e){let t,i,r,n,a,{type:s,decryptedFields:o,certifierInfo:c}=e;switch(s){case n6.xCert:t=o.userName,i=o.profilePhoto,r=`X account certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n6.discordCert:t=o.userName,i=o.profilePhoto,r=`Discord account certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n6.emailCert:t=o.email,i="XUTZxep7BBghAJbSBwTjNfmcsDdRFs5EaGEgkESGSgjJVYgMEizu",r=`Email certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n6.phoneCert:t=o.phoneNumber,i="XUTLxtX3ELNUwRhLwL7kWNGbdnFM8WG2eSLv84J7654oH8HaJWrU",r=`Phone certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n6.identiCert:t=`${o.firstName} ${o.lastName}`,i=o.profilePhoto,r=`Government ID certified by ${c.name}`,n=c.iconUrl,a="https://identicert.me";break;case n6.registrant:t=o.name,i=o.icon,r=`Entity certified by ${c.name}`,n=c.iconUrl,a="https://projectbabbage.com/docs/registrant";break;case n6.coolCert:t="true"===o.cool?"Cool Person!":"Not cool!";break;case n6.anyone:t="Anyone",i="XUT4bpQ6cpBaXi1oMzZsXfpkWGbtp2JTUYAoN7PzhStFJ6wLfoeR",r="Represents the ability for anyone to access this information.",n="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",a="https://projectbabbage.com/docs/anyone-identity";break;case n6.self:t="You",i="XUT9jHGk2qace148jeCX5rDsMftkSGYKmigLwU2PLLBc7Hm63VYR",r="Represents your ability to access this information.",n="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",a="https://projectbabbage.com/docs/self-identity";break;default:{let e=n9.tryToParseGenericIdentity(s,o,c);t=e.name,i=e.avatarURL,r=e.badgeLabel,n=e.badgeIconURL,a=e.badgeClickURL}}return{name:t,avatarURL:i,abbreviatedKey:e.subject.length>0?`${e.subject.substring(0,10)}...`:"",identityKey:e.subject,badgeIconURL:n,badgeLabel:r,badgeClickURL:a}}static hasValue(e){return null!=e&&""!==e}static tryToParseGenericIdentity(e,t,i){let r=t.firstName,n=t.lastName,a=n9.hasValue(r)&&n9.hasValue(n)?`${r} ${n}`:n9.hasValue(r)?r:n9.hasValue(n)?n:void 0,s=n9.hasValue(t.name)?t.name:n9.hasValue(t.userName)?t.userName:a??(n9.hasValue(t.email)?t.email:n8.name),o=n9.hasValue(t.profilePhoto)?t.profilePhoto:n9.hasValue(t.avatar)?t.avatar:n9.hasValue(t.icon)?t.icon:n9.hasValue(t.photo)?t.photo:n8.avatarURL,c=n9.hasValue(i?.name)?`${e} certified by ${String(i.name)}`:n8.badgeLabel;return{name:s,avatarURL:o,badgeLabel:c,badgeIconURL:n9.hasValue(i?.iconUrl)?i.iconUrl:n8.badgeIconURL,badgeClickURL:n8.badgeClickURL}}}class ae{wallet;originator;network;resolver;cachedIdentityKey;acceptDelayedBroadcast;constructor(e=new nS,t={},i){this.wallet=e,this.originator=i,this.acceptDelayedBroadcast=t.acceptDelayedBroadcast??!1,this.resolver=t.resolver??new nW}async getIdentityKey(){return void 0===this.cachedIdentityKey&&(this.cachedIdentityKey=(await this.wallet.getPublicKey({identityKey:!0})).publicKey),this.cachedIdentityKey}async getNetwork(){return void 0===this.network&&(this.network=(await this.wallet.getNetwork({})).network),this.network}async registerDefinition(e){let t=await this.getIdentityKey(),i=new iK(this.wallet,this.originator),r=this.buildPushDropFields(e,t),n=this.mapDefinitionTypeToWalletProtocol(e.definitionType),a=await i.lock(r,n,"1","anyone",!0),{tx:s}=await this.wallet.createAction({description:`Register a new ${e.definitionType} item`,outputs:[{satoshis:1,lockingScript:a.toHex(),outputDescription:`New ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===s)throw Error(`Failed to create ${e.definitionType} registration transaction!`);let o=new nX([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await o.broadcast(i3.fromAtomicBEEF(s))}async resolve(e,t){let i=this.mapDefinitionTypeToServiceName(e),r=await this.resolver.query({service:i,query:t});if("output-list"!==r.type)return[];let n=[];for(let t of r.outputs)try{let i=i3.fromBEEF(t.beef).outputs[t.outputIndex].lockingScript,r=await this.parseLockingScript(e,i);n.push(r)}catch{}return n}async listOwnRegistryEntries(e){let t=this.mapDefinitionTypeToBasketName(e),{outputs:i,BEEF:r}=await this.wallet.listOutputs({basket:t,include:"entire transactions"}),n=[];for(let t of i)if(t.spendable)try{let[i,a]=t.outpoint.split("."),s=i3.fromBEEF(r,i).outputs[Number(a)].lockingScript,o=await this.parseLockingScript(e,s);n.push({...o,txid:i,outputIndex:Number(a),satoshis:t.satoshis,lockingScript:s.toHex(),beef:r})}catch{}return n}async removeDefinition(e){if(void 0===e.txid||void 0===e.outputIndex||void 0===e.lockingScript)throw Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");let t=await this.getIdentityKey();if(e.registryOperator!==t)throw Error("This registry token does not belong to the current wallet.");let i="basket"===e.definitionType?e.basketID:"protocol"===e.definitionType?e.name:"certificate"===e.definitionType?void 0!==e.name?e.name:e.type:"unknown",r=`${e.txid}.${e.outputIndex}`,{signableTransaction:n}=await this.wallet.createAction({description:`Remove ${e.definitionType} item: ${i}`,inputBEEF:e.beef,inputs:[{outpoint:r,unlockingScriptLength:74,inputDescription:`Removing ${e.definitionType} token`}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===n)throw Error("Failed to create signable transaction.");let a=i3.fromAtomicBEEF(n.tx),s=new iK(this.wallet,this.originator).unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone"),o=await s.sign(a,0),{tx:c}=await this.wallet.signAction({reference:n.reference,spends:{0:{unlockingScript:o.toHex()}},options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if(void 0===c)throw Error("Failed to finalize the transaction signature.");let l=new nX([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await l.broadcast(i3.fromAtomicBEEF(c))}async updateDefinition(e,t){if(void 0===e.txid||void 0===e.outputIndex||void 0===e.lockingScript)throw Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");if(e.definitionType!==t.definitionType)throw Error(`Cannot change definition type from ${e.definitionType} to ${t.definitionType}`);let i=await this.getIdentityKey();if(e.registryOperator!==i)throw Error("This registry token does not belong to the current wallet.");let r="basket"===e.definitionType?e.basketID:"protocol"===e.definitionType?e.name:"certificate"===e.definitionType?void 0!==e.name?e.name:e.type:"unknown",n=new iK(this.wallet,this.originator),a=this.buildPushDropFields(t,i),s=this.mapDefinitionTypeToWalletProtocol(t.definitionType),o=await n.lock(a,s,"1","anyone",!0),c=`${e.txid}.${e.outputIndex}`,{signableTransaction:l}=await this.wallet.createAction({description:`Update ${e.definitionType} item: ${r}`,inputBEEF:e.beef,inputs:[{outpoint:c,unlockingScriptLength:74,inputDescription:`Updating ${e.definitionType} token`}],outputs:[{satoshis:1,lockingScript:o.toHex(),outputDescription:`Updated ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===l)throw Error("Failed to create signable transaction.");let h=i3.fromAtomicBEEF(l.tx),d=n.unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone"),u=await d.sign(h,0),{tx:f}=await this.wallet.signAction({reference:l.reference,spends:{0:{unlockingScript:u.toHex()}},options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if(void 0===f)throw Error("Failed to finalize the transaction signature.");let p=new nX([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await p.broadcast(i3.fromAtomicBEEF(f))}buildPushDropFields(e,t){let i;switch(e.definitionType){case"basket":i=[e.basketID,e.name,e.iconURL,e.description,e.documentationURL];break;case"protocol":i=[JSON.stringify(e.protocolID),e.name,e.iconURL,e.description,e.documentationURL];break;case"certificate":i=[e.type,e.name,e.iconURL,e.description,e.documentationURL,JSON.stringify(e.fields)];break;default:throw Error("Unsupported definition type")}return i.push(t),i.map(e=>ti(e))}async parseLockingScript(e,t){let i,r,n=iK.decode(t);if(0===n.fields.length)throw Error("Not a valid registry pushdrop script.");switch(e){case"basket":{if(7!==n.fields.length)throw Error("Unexpected field count for basket type.");let[e,t,a,s,o,c]=n.fields;i=ts(c),r={definitionType:"basket",basketID:ts(e),name:ts(t),iconURL:ts(a),description:ts(s),documentationURL:ts(o)};break}case"protocol":{if(7!==n.fields.length)throw Error("Unexpected field count for protocol type.");let[e,t,a,s,o,c]=n.fields;i=ts(c),r={definitionType:"protocol",protocolID:at(ts(e)),name:ts(t),iconURL:ts(a),description:ts(s),documentationURL:ts(o)};break}case"certificate":{if(8!==n.fields.length)throw Error("Unexpected field count for certificate type.");let[e,t,a,s,o,c,l]=n.fields;i=ts(l);let h={};try{h=JSON.parse(ts(c))}catch{}r={definitionType:"certificate",type:ts(e),name:ts(t),iconURL:ts(a),description:ts(s),documentationURL:ts(o),fields:h};break}default:throw Error(`Unsupported definition type: ${e}`)}return{...r,registryOperator:i}}mapDefinitionTypeToWalletProtocol(e){switch(e){case"basket":return[1,"basketmap"];case"protocol":return[1,"protomap"];case"certificate":return[1,"certmap"];default:throw Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToBasketName(e){switch(e){case"basket":return"basketmap";case"protocol":return"protomap";case"certificate":return"certmap";default:throw Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToTopic(e){switch(e){case"basket":return"tm_basketmap";case"protocol":return"tm_protomap";case"certificate":return"tm_certmap";default:throw Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToServiceName(e){switch(e){case"basket":return"ls_basketmap";case"protocol":return"ls_protomap";case"certificate":return"ls_certmap";default:throw Error(`Unknown definition type: ${e}`)}}}function at(e){let t=JSON.parse(e);if(!Array.isArray(t)||2!==t.length)throw Error("Invalid wallet protocol format.");let[i,r]=t;if(![0,1,2].includes(i))throw Error("Invalid security level.");if("string"!=typeof r)throw Error("Invalid protocolID");return[i,r]}class ai{wallet;context;encrypt;originator;acceptDelayedBroadcast=!1;keyLocks=new Map;constructor(e=new nS,t="kvstore default",i=!0,r,n=!1){if("string"!=typeof t||t.length<1)throw Error("A context in which to operate is required.");this.wallet=e,this.context=t,this.encrypt=i,this.originator=r,this.acceptDelayedBroadcast=n}async queueOperationOnKey(e){let t=this.keyLocks.get(e);null==t&&(t=[],this.keyLocks.set(e,t));let i=()=>{},r=new Promise(e=>{i=e,null!=t&&t.push(e)});return 1===t.length&&i(),await r,t}finishOperationOnKey(e,t){t.shift(),t.length>0&&t[0]()}getProtocol(e){return{protocolID:[2,this.context],keyID:e}}async getOutputs(e,t){return await this.wallet.listOutputs({basket:this.context,tags:[e],tagQueryMode:"all",include:"entire transactions",limit:t},this.originator)}async get(e,t){let i=await this.queueOperationOnKey(e);try{return(await this.lookupValue(e,t,5)).value}finally{this.finishOperationOnKey(e,i)}}getLockingScript(e,t){let[i,r]=e.outpoint.split("."),n=t.findTxid(i)?.tx;if(null==n)throw Error(`beef must contain txid ${i}`);return n.outputs[Number(r)].lockingScript}async lookupValue(e,t,i){let r,n=await this.getOutputs(e,i),a={value:t,outpoint:void 0,lor:n},{outputs:s}=n;if(0===s.length)return a;let o=s.slice(-1)[0];a.outpoint=o.outpoint;try{if(void 0===n.BEEF)throw Error("entire transactions listOutputs option must return valid BEEF");let e=this.getLockingScript(o,i8.fromBinary(n.BEEF)),t=iK.decode(e);if(t.fields.length<1||t.fields.length>2)throw Error("Invalid token.");r=t.fields[0]}catch(e){throw Error(`Invalid value found. You need to call set to collapse the corrupted state (or relinquish the corrupted ${s[0].outpoint} output from the ${this.context} basket) before you can get this value again. Original error: ${e instanceof Error?e.message:String(e)}`)}if(this.encrypt){let{plaintext:t}=await this.wallet.decrypt({...this.getProtocol(e),ciphertext:r},this.originator);a.value=ts(t)}else a.value=ts(r);return a}getInputs(e){let t=[];for(let i=0;i<e.length;i++)t.push({outpoint:e[i].outpoint,unlockingScriptLength:74,inputDescription:"Previous key-value token"});return t}async getSpends(e,t,i,r){let n=this.getProtocol(e),a=i3.fromAtomicBEEF(r),s={};for(let e=0;e<t.length;e++){let t=i.unlock(n.protocolID,n.keyID,"self"),r=await t.sign(a,e);s[e]={unlockingScript:r.toHex()}}return s}async set(e,t){let i=await this.queueOperationOnKey(e);try{let i,r=await this.lookupValue(e,void 0,10);if(r.value===t){if(void 0===r.outpoint)throw Error("outpoint must be valid when value is valid and unchanged");return r.outpoint}let n=this.getProtocol(e),a=ti(t,"utf8");if(this.encrypt){let{ciphertext:e}=await this.wallet.encrypt({...n,plaintext:a},this.originator);a=e}let s=new iK(this.wallet,this.originator),o=await s.lock([a],n.protocolID,n.keyID,"self"),{outputs:c,BEEF:l}=r.lor;try{let t=this.getInputs(c),{txid:r,signableTransaction:n}=await this.wallet.createAction({description:`Update ${e} in ${this.context}`,inputBEEF:l,inputs:t,outputs:[{basket:this.context,tags:[e],lockingScript:o.toHex(),satoshis:1,outputDescription:"Key-value token"}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(c.length>0&&"object"!=typeof n)throw Error("Wallet did not return a signable transaction when expected.");if(null==n)i=`${r}.0`;else{let t=await this.getSpends(e,c,s,n.tx),{txid:r}=await this.wallet.signAction({reference:n.reference,spends:t},this.originator);i=`${r}.0`}}catch(t){throw Error(`There are ${c.length} outputs with tag ${e} that cannot be unlocked. Original error: ${t instanceof Error?t.message:String(t)}`)}return i}finally{this.finishOperationOnKey(e,i)}}async remove(e){let t=await this.queueOperationOnKey(e);try{let t=[];for(;;){let{outputs:i,BEEF:r,totalOutputs:n}=await this.getOutputs(e);if(i.length>0){let a=new iK(this.wallet,this.originator);try{let n=this.getInputs(i),{signableTransaction:s}=await this.wallet.createAction({description:`Remove ${e} in ${this.context}`,inputBEEF:r,inputs:n,options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if("object"!=typeof s)throw Error("Wallet did not return a signable transaction when expected.");let o=await this.getSpends(e,i,a,s.tx),{txid:c}=await this.wallet.signAction({reference:s.reference,spends:o},this.originator);if(void 0===c)throw Error("signAction must return a valid txid");t.push(c)}catch(t){throw Error(`There are ${n} outputs with tag ${e} that cannot be unlocked. Original error: ${t instanceof Error?t.message:String(t)}`)}}if(i.length===n)break}return t}finally{this.finishOperationOnKey(e,t)}}}class ar{interpreter;debug;historyCache;interpreterVersion;ctxKeyFn;constructor(e,t){this.interpreter=e,this.debug=t?.debug??!1,this.historyCache=t?.historyCache,this.interpreterVersion=t?.interpreterVersion??"v1",this.ctxKeyFn=t?.ctxKeyFn??(e=>{try{return JSON.stringify(e??null)}catch{return""}})}historyKey(e,t){let i=e.id("hex"),r=this.ctxKeyFn(t);return`${this.interpreterVersion}|${i}|${r}`}async buildHistory(e,t){if(null!=this.historyCache){let i=this.historyKey(e,t);if(this.historyCache.has(i)){let e=this.historyCache.get(i);if(null!=e)return this.debug&&console.log("[Historian] History cache hit:",i),e.slice()}}let i=[],r=new Set,n=async e=>{let a=e.id("hex");if(r.has(a)){this.debug&&console.log(`[Historian] Skipping already visited transaction: ${a}`);return}r.add(a),this.debug&&console.log(`[Historian] Processing transaction: ${a}`);for(let r=0;r<e.outputs.length;r++)try{let n=await Promise.resolve(this.interpreter(e,r,t));void 0!==n&&(i.push(n),this.debug&&console.log("[Historian] Added value to history:",n))}catch(e){this.debug&&console.log(`[Historian] Failed to interpret output ${r}:`,e)}for(let t of e.inputs)null!=t.sourceTransaction?await n(t.sourceTransaction):this.debug&&console.log("[Historian] Input missing sourceTransaction, skipping")};await n(e);let a=i.reverse();if(null!=this.historyCache){let i=this.historyKey(e,t);this.historyCache.set(i,Object.freeze(a.slice())),this.debug&&console.log("[Historian] History cached:",i)}return a}}let an={protocolID:0,key:1,value:2,controller:3,tags:4,signature:5},aa=async(e,t,i)=>{try{let r=e.outputs[t];if(null==r||null==r.lockingScript||null==i||null==i.key)return;let n=iK.decode(r.lockingScript),a=Object.keys(an).length,s=n.fields.length===a;if(n.fields.length!==a-1&&!s)return;let o=ts(n.fields[an.key]),c=ts(n.fields[an.protocolID]);if(o!==i.key||c!==JSON.stringify(i.protocolID))return;try{return ts(n.fields[an.value])}catch{return}}catch{return}},as={protocolID:[1,"kvstore"],serviceName:"ls_kvstore",tokenAmount:1,topics:["tm_kvstore"],networkPreset:"mainnet",acceptDelayedBroadcast:!1,overlayBroadcast:!1,tokenSetDescription:"",tokenUpdateDescription:"",tokenRemovalDescription:""};class ao{wallet;config;historian;lookupResolver;topicBroadcaster;keyLocks=new Map;cachedIdentityKey=null;constructor(e={}){this.config={...as,...e},this.wallet=e.wallet??new nS,this.historian=new ar(aa),this.lookupResolver=new nW({networkPreset:this.config.networkPreset}),this.topicBroadcaster=new nX(this.config.topics,{networkPreset:this.config.networkPreset})}async get(e,t={}){if(0===Object.keys(e).length)throw Error("Must specify either key, controller, or protocolID");if(null!=e.key&&null!=e.controller){let i=await this.queryOverlay(e,t);return i.length>0?i[0]:void 0}return await this.queryOverlay(e,t)}async set(e,t,i={}){if("string"!=typeof e||0===e.length)throw Error("Key must be a non-empty string.");if("string"!=typeof t)throw Error("Value must be a string.");let r=await this.getIdentityKey(),n=await this.queueOperationOnKey(e),a=i.protocolID??this.config.protocolID,s=null!=i.tokenSetDescription&&""!==i.tokenSetDescription?i.tokenSetDescription:`Create KVStore value for ${e}`,o=null!=i.tokenUpdateDescription&&""!==i.tokenUpdateDescription?i.tokenUpdateDescription:`Update KVStore value for ${e}`,c=i.tokenAmount??this.config.tokenAmount,l=i.tags??[];try{let i=new iK(this.wallet,this.config.originator),n=[ti(JSON.stringify(a),"utf8"),ti(e,"utf8"),ti(t,"utf8"),ti(r,"hex")];l.length>0&&n.push(ti(JSON.stringify(l),"utf8"));let h=await i.lock(n,a??this.config.protocolID,ts(ti(e,"utf8")),"anyone",!0);return await nG(async()=>{let t=await this.queryOverlay({key:e,controller:r},{includeToken:!0}),n=t.length>0?t[0].token:void 0;if(null!=n){let t=[{outpoint:`${n.txid}.${n.outputIndex}`,unlockingScriptLength:74,inputDescription:"Previous KVStore token"}],r=n.beef,{signableTransaction:a}=await this.wallet.createAction({description:o,inputBEEF:r.toBinary(),inputs:t,outputs:[{satoshis:c??this.config.tokenAmount,lockingScript:h.toHex(),outputDescription:"KVStore token"}],options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast,randomizeOutputs:!1}},this.config.originator);if(null==a)throw Error("Unable to create update transaction");let s=i3.fromAtomicBEEF(a.tx),l=i.unlock(this.config.protocolID,e,"anyone"),d=await l.sign(s,0),{tx:u}=await this.wallet.signAction({reference:a.reference,spends:{0:{unlockingScript:d.toHex()}},options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==u)throw Error("Unable to finalize update transaction");let f=i3.fromAtomicBEEF(u);return await this.submitToOverlay(f),`${f.id("hex")}.0`}{let{tx:e}=await this.wallet.createAction({description:s,outputs:[{satoshis:c??this.config.tokenAmount,lockingScript:h.toHex(),outputDescription:"KVStore token"}],options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast,randomizeOutputs:!1}},this.config.originator);if(null==e)throw Error("Failed to create transaction");let t=i3.fromAtomicBEEF(e);return await this.submitToOverlay(t),`${t.id("hex")}.0`}},this.topicBroadcaster)}finally{n.length>0&&this.finishOperationOnKey(e,n)}}async remove(e,t,i={}){if("string"!=typeof e||0===e.length)throw Error("Key must be a non-empty string.");let r=await this.getIdentityKey(),n=await this.queueOperationOnKey(e),a=i.protocolID??this.config.protocolID,s=null!=i.tokenRemovalDescription&&""!==i.tokenRemovalDescription?i.tokenRemovalDescription:`Remove KVStore value for ${e}`;try{let i=new iK(this.wallet,this.config.originator);return await nG(async()=>{let n=await this.queryOverlay({key:e,controller:r},{includeToken:!0});if(0===n.length||null==n[0].token)throw Error("The item did not exist, no item was deleted.");let o=n[0].token,c=[{outpoint:`${o.txid}.${o.outputIndex}`,unlockingScriptLength:74,inputDescription:"KVStore token to remove"}],{signableTransaction:l}=await this.wallet.createAction({description:s,inputBEEF:o.beef.toBinary(),inputs:c,outputs:t,options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,randomizeOutputs:!1,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==l)throw Error("Unable to create removal transaction");let h=i3.fromAtomicBEEF(l.tx),d=i.unlock(a??this.config.protocolID,e,"anyone"),u=await d.sign(h,0),{tx:f}=await this.wallet.signAction({reference:l.reference,spends:{0:{unlockingScript:u.toHex()}},options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==f)throw Error("Unable to finalize removal transaction");let p=i3.fromAtomicBEEF(f);return await this.submitToOverlay(p),p.id("hex")},this.topicBroadcaster)}finally{n.length>0&&this.finishOperationOnKey(e,n)}}async queueOperationOnKey(e){let t=this.keyLocks.get(e);null==t&&(t=[],this.keyLocks.set(e,t));let i=()=>{},r=new Promise(e=>{i=e,null!=t&&t.push(e)});return 1===t.length&&i(),await r,t}finishOperationOnKey(e,t){t.shift(),t.length>0?t[0]():this.keyLocks.delete(e)}async getIdentityKey(){return null==this.cachedIdentityKey&&(this.cachedIdentityKey=(await this.wallet.getPublicKey({identityKey:!0},this.config.originator)).publicKey),this.cachedIdentityKey}async queryOverlay(e,t={}){let i=await this.lookupResolver.query({service:t.serviceName??this.config.serviceName,query:e});if("output-list"!==i.type||0===i.outputs.length)return[];let r=[];for(let e of i.outputs)try{let i,n=i3.fromBEEF(e.beef),a=n.outputs[e.outputIndex],s=iK.decode(a.lockingScript),o=Object.keys(an).length,c=s.fields.length===o;if(s.fields.length!==o-1&&!c)continue;let l=new rA("anyone"),h=s.fields.pop();try{await l.verifySignature({data:s.fields.reduce((e,t)=>[...e,...t],[]),signature:h,counterparty:te(s.fields[an.controller]),protocolID:JSON.parse(ts(s.fields[an.protocolID])),keyID:ts(s.fields[an.key])})}catch(e){continue}if(c&&null!=s.fields[an.tags])try{i=JSON.parse(ts(s.fields[an.tags]))}catch(e){i=void 0}let d={key:ts(s.fields[an.key]),value:ts(s.fields[an.value]),controller:te(s.fields[an.controller]),protocolID:JSON.parse(ts(s.fields[an.protocolID])),tags:i};!0===t.includeToken&&(d.token={txid:n.id("hex"),outputIndex:e.outputIndex,beef:i8.fromBinary(e.beef),satoshis:a.satoshis??1}),!0===t.history&&(d.history=await this.historian.buildHistory(n,{key:d.key,protocolID:d.protocolID})),r.push(d)}catch(e){continue}return r}async submitToOverlay(e){return await this.topicBroadcaster.broadcast(e)}}let ac=ao,al={new:["identityRequested","invoiced","settled","terminated","errored"],identityRequested:["identityResponded","identityAcknowledged","invoiced","settled","terminated","errored"],identityResponded:["identityAcknowledged","invoiced","settled","terminated","errored"],identityAcknowledged:["invoiced","settled","terminated","errored"],invoiced:["identityRequested","identityResponded","identityAcknowledged","settled","terminated","errored"],settled:["receipted","terminated","errored"],receipted:["terminated","errored"],terminated:["errored"],errored:[]},ah={namespace:"bsv",code:"sat",decimals:0},ad="remittance_inbox";class au{wallet;comms;cfg;messageBox;now;threadIdFactory;moduleRegistry;runtime;eventListeners;stateWaiters;eventHandlers;defaultPaymentOptionId;threads;myIdentityKey;constructor(e,t,i,r=[]){this.cfg=e,this.wallet=t,this.comms=i,this.messageBox=e.messageBox??ad,this.now=e.now??(()=>Date.now()),this.threadIdFactory=e.threadIdFactory??ag,this.moduleRegistry=new Map(e.remittanceModules.map(e=>[e.id,e])),this.eventListeners=new Set,this.stateWaiters=new Map,this.eventHandlers=e.events,"function"==typeof e.onEvent&&this.eventListeners.add(e.onEvent),this.runtime={identityOptions:e.options?.identityOptions??{makerRequestIdentity:"never",takerRequestIdentity:"never"},receiptProvided:e.options?.receiptProvided??!0,autoIssueReceipt:e.options?.autoIssueReceipt??!0,invoiceExpirySeconds:e.options?.invoiceExpirySeconds??3600,identityTimeoutMs:e.options?.identityTimeoutMs??3e4,identityPollIntervalMs:e.options?.identityPollIntervalMs??500},this.threads=r.map(e=>this.ensureThreadState(e))}async init(){if("function"!=typeof this.cfg.stateLoader)return;let e=await this.cfg.stateLoader();"object"==typeof e&&(this.loadState(e),"string"==typeof e.defaultPaymentOptionId&&(this.defaultPaymentOptionId=e.defaultPaymentOptionId),await this.refreshMyIdentityKey())}onEvent(e){return this.eventListeners.add(e),()=>{this.eventListeners.delete(e)}}preselectPaymentOption(e){this.defaultPaymentOptionId=e}saveState(){return{v:1,threads:JSON.parse(JSON.stringify(this.threads)),defaultPaymentOptionId:this.defaultPaymentOptionId}}loadState(e){if(1!==e.v)throw Error("Unsupported RemittanceManagerState version");this.threads=(e.threads??[]).map(e=>this.ensureThreadState(e)),this.defaultPaymentOptionId=e.defaultPaymentOptionId}async persistState(){null!=this.cfg.stateSaver&&await this.cfg.stateSaver(this.saveState())}async syncThreads(e){for(let t of(await this.refreshMyIdentityKey(),await this.comms.listMessages({messageBox:this.messageBox,host:e})))await this.handleInboundMessage(t)}async startListening(e){if("function"!=typeof this.comms.listenForLiveMessages)throw Error("CommsLayer does not support live message listening");await this.comms.listenForLiveMessages({messageBox:this.messageBox,overrideHost:e,onMessage:e=>{this.handleInboundMessage(e)}})}async sendInvoice(e,t,i){await this.refreshMyIdentityKey();let r=this.threadIdFactory(),n=this.now(),a=this.requireMyIdentityKey("sendInvoice requires the wallet to provide an identity key"),s={threadId:r,counterparty:e,myRole:"maker",theirRole:"taker",createdAt:n,updatedAt:n,state:"new",stateLog:[],processedMessageIds:[],protocolLog:[],identity:{certsSent:[],certsReceived:[],requestSent:!1,responseSent:!1,acknowledgmentSent:!1,acknowledgmentReceived:!1},flags:{hasIdentified:!1,hasInvoiced:!1,hasPaid:!1,hasReceipted:!1,error:!1}};this.threads.push(s),this.emitEvent({type:"threadCreated",threadId:s.threadId,thread:s}),s.identity.responseSent&&!s.flags.hasIdentified&&await this.waitForIdentityAcknowledgment(r,{timeoutMs:this.runtime.identityTimeoutMs,pollIntervalMs:this.runtime.identityPollIntervalMs}),this.shouldRequestIdentity(s,"beforeInvoicing")&&await this.ensureIdentityExchange(s,i);let o=await this.composeInvoice(r,a,e,t);for(let e of(s.invoice=o,s.flags.hasInvoiced=!0,this.transitionThreadState(s,"invoiced","invoice created"),this.moduleRegistry.values())){if("function"!=typeof e.createOption)continue;let t=await e.createOption({threadId:r,invoice:o},this.moduleContext());o.options[e.id]=t}let c=this.makeEnvelope("invoice",r,o),l=await this.sendEnvelope(e,c,i);return s.protocolLog.push({direction:"out",envelope:c,transportMessageId:l}),this.emitEvent({type:"invoiceSent",threadId:s.threadId,invoice:o}),s.updatedAt=this.now(),await this.persistState(),new ap(this,r)}async sendInvoiceForThread(e,t,i){await this.refreshMyIdentityKey();let r=this.getThreadOrThrow(e);if(r.flags.error)throw Error("Thread is in error state");if("maker"!==r.myRole)throw Error("Only makers can send invoices");if(null!=r.invoice)throw Error("Thread already has an invoice");r.identity.responseSent&&!r.flags.hasIdentified&&await this.waitForIdentityAcknowledgment(e,{timeoutMs:this.runtime.identityTimeoutMs,pollIntervalMs:this.runtime.identityPollIntervalMs}),this.shouldRequestIdentity(r,"beforeInvoicing")&&await this.ensureIdentityExchange(r,i);let n=this.requireMyIdentityKey("sendInvoice requires the wallet to provide an identity key"),a=await this.composeInvoice(e,n,r.counterparty,t);for(let t of(r.invoice=a,r.flags.hasInvoiced=!0,this.transitionThreadState(r,"invoiced","invoice created"),this.moduleRegistry.values())){if("function"!=typeof t.createOption)continue;let i=await t.createOption({threadId:e,invoice:a},this.moduleContext());a.options[t.id]=i}let s=this.makeEnvelope("invoice",e,a),o=await this.sendEnvelope(r.counterparty,s,i);return r.protocolLog.push({direction:"out",envelope:s,transportMessageId:o}),this.emitEvent({type:"invoiceSent",threadId:r.threadId,invoice:a}),r.updatedAt=this.now(),await this.persistState(),new ap(this,e)}findInvoicesPayable(e){let t="string"==typeof e&&e.length>0;return this.threads.filter(e=>"taker"===e.myRole&&null!=e.invoice&&null==e.settlement&&!e.flags.error).filter(i=>!t||i.counterparty===e).map(e=>new ap(this,e.threadId))}findReceivableInvoices(e){let t="string"==typeof e&&e.length>0;return this.threads.filter(e=>"maker"===e.myRole&&null!=e.invoice&&null==e.settlement&&!e.flags.error).filter(i=>!t||i.counterparty===e).map(e=>new ap(this,e.threadId))}async pay(e,t,i){await this.refreshMyIdentityKey();let r=this.getThreadOrThrow(e);if(null==r.invoice)throw Error("Thread has no invoice to pay");if(r.flags.error)throw Error("Thread is in error state");if(null!=r.settlement)throw Error("Invoice already paid (settlement exists)");r.identity.responseSent&&!r.flags.hasIdentified&&await this.waitForIdentityAcknowledgment(e,{timeoutMs:this.runtime.identityTimeoutMs,pollIntervalMs:this.runtime.identityPollIntervalMs}),this.shouldRequestIdentity(r,"beforeSettlement")&&await this.ensureIdentityExchange(r,i);let n=r.invoice.expiresAt;if("number"==typeof n&&this.now()>n)throw Error("Invoice is expired");let a=t??this.defaultPaymentOptionId??Object.keys(r.invoice.options)[0];if(null==a||""===a)throw Error("No remittance options available on invoice");let s=this.moduleRegistry.get(a);if(null==s)throw Error(`No configured remittance module for option: ${a}`);let o=r.invoice.options[a],c=this.requireMyIdentityKey("pay() requires the wallet to provide an identity key"),l=await s.buildSettlement({threadId:e,invoice:r.invoice,option:o,note:r.invoice.note},this.moduleContext());if("terminate"===l.action){let e=l.termination;return await this.sendTermination(r,r.counterparty,e.message,e.details,e.code),await this.persistState(),e}let h={kind:"settlement",threadId:e,moduleId:s.id,optionId:a,sender:c,createdAt:this.now(),artifact:l.artifact,note:r.invoice.note},d=this.makeEnvelope("settlement",e,h),u=await this.sendEnvelope(r.invoice.payee,d,i);if(r.protocolLog.push({direction:"out",envelope:d,transportMessageId:u}),this.emitEvent({type:"settlementSent",threadId:r.threadId,settlement:h}),r.settlement=h,r.flags.hasPaid=!0,this.transitionThreadState(r,"settled","settlement sent"),r.updatedAt=this.now(),await this.persistState(),this.runtime.receiptProvided)return await this.waitForReceipt(e)}async waitForReceipt(e,t={}){let i=t.timeoutMs??3e4,r=t.pollIntervalMs??500,n=this.now();for(;this.now()-n<i;){let t=this.getThreadOrThrow(e);if("object"==typeof t.receipt)return t.receipt;if("object"==typeof t.termination)return t.termination;await this.syncThreads(),await am(r)}throw Error("Timed out waiting for receipt")}async waitForState(e,t,i={}){let r,n,a=i.timeoutMs??3e4,s=i.pollIntervalMs??500,o=this.now(),c=this.getThreadOrThrow(e);if(c.state===t)return c;if("terminated"===c.state||"errored"===c.state)throw Error(`Thread entered terminal state: ${c.state}`);let l=!1,h=!1,d={state:t,resolve:()=>{l||h||(l=!0,r())},reject:e=>{l||h||(l=!0,n(e))}},u=new Promise((t,i)=>{r=t,n=i;let a=this.stateWaiters.get(e)??[];a.push(d),this.stateWaiters.set(e,a)}),f=()=>{let t=this.stateWaiters.get(e);if(null==t)return;let i=t.filter(e=>e!==d);0===i.length?this.stateWaiters.delete(e):this.stateWaiters.set(e,i)},p=(async()=>{for(;this.now()-o<a;){if(l)return;let i=this.getThreadOrThrow(e);if(i.state===t)return void this.resolveStateWaiters(e,t);if("terminated"===i.state||"errored"===i.state)throw Error(`Thread entered terminal state: ${i.state}`);await this.syncThreads(),await am(s)}})();if(await Promise.race([u,p]).catch(e=>{throw f(),e}),this.now()-o>=a&&!l)throw h=!0,f(),Error(`Timed out waiting for state: ${t}`);return f(),this.getThreadOrThrow(e)}async waitForIdentity(e,t){return await this.waitForState(e,"identityAcknowledged",t)}async waitForSettlement(e,t={}){let i=t.timeoutMs??3e4,r=t.pollIntervalMs??500,n=this.now();for(;this.now()-n<i;){let t=this.getThreadOrThrow(e);if("object"==typeof t.settlement)return t.settlement;if("object"==typeof t.termination)return t.termination;await this.syncThreads(),await am(r)}throw Error("Timed out waiting for settlement")}async sendUnsolicitedSettlement(e,t,i){await this.refreshMyIdentityKey();let r=this.moduleRegistry.get(t.moduleId);if(null==r)throw Error(`No configured remittance module for option: ${t.moduleId}`);if(!r.allowUnsolicitedSettlements)throw Error(`Remittance module ${t.moduleId} does not allow unsolicited settlements`);let n=this.threadIdFactory(),a=this.now(),s=this.requireMyIdentityKey("sendUnsolicitedSettlement requires the wallet to provide an identity key"),o={threadId:n,counterparty:e,myRole:"taker",theirRole:"maker",createdAt:a,updatedAt:a,state:"new",stateLog:[],processedMessageIds:[],protocolLog:[],identity:{certsSent:[],certsReceived:[],requestSent:!1,responseSent:!1,acknowledgmentSent:!1,acknowledgmentReceived:!1},flags:{hasIdentified:!1,hasInvoiced:!1,hasPaid:!1,hasReceipted:!1,error:!1}};this.threads.push(o),this.emitEvent({type:"threadCreated",threadId:o.threadId,thread:o}),this.shouldRequestIdentity(o,"beforeSettlement")&&await this.ensureIdentityExchange(o,i);let c=await r.buildSettlement({threadId:n,option:t.option,note:t.note},this.moduleContext());if("terminate"===c.action)return await this.sendTermination(o,e,c.termination.message,c.termination.details,c.termination.code),await this.persistState(),new af(this,n);let l={kind:"settlement",threadId:n,moduleId:r.id,optionId:t.optionId??r.id,sender:s,createdAt:this.now(),artifact:c.artifact,note:t.note},h=this.makeEnvelope("settlement",n,l),d=await this.sendEnvelope(e,h,i);return o.protocolLog.push({direction:"out",envelope:h,transportMessageId:d}),this.emitEvent({type:"settlementSent",threadId:o.threadId,settlement:l}),o.settlement=l,o.flags.hasPaid=!0,this.transitionThreadState(o,"settled","settlement sent"),o.updatedAt=this.now(),await this.persistState(),new af(this,n)}getThread(e){return this.threads.find(t=>t.threadId===e)}getThreadHandle(e){return this.getThreadOrThrow(e),new af(this,e)}getThreadOrThrow(e){let t=this.getThread(e);if("object"!=typeof t)throw Error(`Unknown thread: ${e}`);return this.ensureThreadState(t)}moduleContext(){return{wallet:this.wallet,originator:this.cfg.originator,now:this.now,logger:this.cfg.logger}}makeEnvelope(e,t,i){return{v:1,id:this.threadIdFactory(),kind:e,threadId:t,createdAt:this.now(),payload:i}}async sendEnvelope(e,t,i){let r=JSON.stringify(t);if("function"==typeof this.comms.sendLiveMessage)try{let n=await this.comms.sendLiveMessage({recipient:e,messageBox:this.messageBox,body:r},i);return this.emitEvent({type:"envelopeSent",threadId:t.threadId,envelope:t,transportMessageId:n}),n}catch(e){this.cfg.logger?.warn?.("[RemittanceManager] sendLiveMessage failed, falling back to non-live",e)}let n=await this.comms.sendMessage({recipient:e,messageBox:this.messageBox,body:r},i);return this.emitEvent({type:"envelopeSent",threadId:t.threadId,envelope:t,transportMessageId:n}),n}getOrCreateThreadFromInboundEnvelope(e,t){let i=this.getThread(e.threadId);if("object"==typeof i)return i;let r=this.now(),n=(()=>{if("invoice"===e.kind)return"taker";if("settlement"===e.kind)return"maker";if("receipt"===e.kind||"termination"===e.kind)return"taker";if("identityVerificationRequest"===e.kind||"identityVerificationResponse"===e.kind||"identityVerificationAcknowledgment"===e.kind){let t,i=this.runtime.identityOptions?.makerRequestIdentity??"never",r=this.runtime.identityOptions?.takerRequestIdentity??"never",n="never"!==i,a="never"!==r;return(n&&!a?t="maker":a&&!n?t="taker":n&&a&&i!==r&&(t="beforeInvoicing"===i&&"beforeSettlement"===r?"maker":"beforeSettlement"===i&&"beforeInvoicing"===r?"taker":void 0),"string"!=typeof t)?"taker":"identityVerificationResponse"===e.kind?t:"maker"===t?"taker":"maker"}return"taker"})(),a={threadId:e.threadId,counterparty:t.sender,myRole:n,theirRole:"maker"===n?"taker":"maker",createdAt:r,updatedAt:r,state:"new",stateLog:[],processedMessageIds:[],protocolLog:[],identity:{certsSent:[],certsReceived:[],requestSent:!1,responseSent:!1,acknowledgmentSent:!1,acknowledgmentReceived:!1},flags:{hasIdentified:!1,hasInvoiced:!1,hasPaid:!1,hasReceipted:!1,error:!1}};return this.threads.push(a),this.emitEvent({type:"threadCreated",threadId:a.threadId,thread:a}),a}async handleInboundMessage(e){let t=function(e){try{let t=JSON.parse(e);if("object"!=typeof t||1!==t.v||"string"!=typeof t.kind||"string"!=typeof t.threadId||"string"!=typeof t.id)return;return t}catch{return}}(e.body);if(null==t)return;let i=this.getOrCreateThreadFromInboundEnvelope(t,e);if(i.processedMessageIds.includes(e.messageId))return void await this.safeAck([e.messageId]);try{await this.applyInboundEnvelope(i,t,e),i.processedMessageIds.push(e.messageId),i.updatedAt=this.now(),await this.persistState(),await this.safeAck([e.messageId])}catch(e){this.markThreadError(i,e),await this.persistState()}}async applyInboundEnvelope(e,t,i){switch(e.protocolLog.push({direction:"in",envelope:t,transportMessageId:i.messageId}),this.emitEvent({type:"envelopeReceived",threadId:e.threadId,envelope:t,transportMessageId:i.messageId}),t.kind){case"identityVerificationRequest":{let r=t.payload;if("object"!=typeof r)throw Error("Identity verification request payload missing data");if(null==this.cfg.identityLayer)return void await this.sendTermination(e,i.sender,"Identity verification requested but no identity layer is configured");this.transitionThreadState(e,"identityRequested","identity request received"),this.emitEvent({type:"identityRequested",threadId:e.threadId,direction:"in",request:r});let n=await this.cfg.identityLayer.respondToRequest({counterparty:i.sender,threadId:e.threadId,request:r},this.moduleContext());if("terminate"===n.action)return void await this.sendTermination(e,i.sender,n.termination.message,n.termination.details,n.termination.code);let a=this.makeEnvelope("identityVerificationResponse",e.threadId,n.response),s=await this.sendEnvelope(i.sender,a);e.protocolLog.push({direction:"out",envelope:a,transportMessageId:s}),e.identity.certsSent=n.response.certificates,e.identity.responseSent=!0,this.transitionThreadState(e,"identityResponded","identity response sent"),this.emitEvent({type:"identityResponded",threadId:e.threadId,direction:"out",response:n.response});return}case"identityVerificationResponse":{let r=t.payload;if("object"!=typeof r)throw Error("Identity verification response payload missing data");if(null==this.cfg.identityLayer)return void await this.sendTermination(e,i.sender,"Identity verification response received but no identity layer is configured");e.identity.certsReceived=r.certificates,this.transitionThreadState(e,"identityResponded","identity response received"),this.emitEvent({type:"identityResponded",threadId:e.threadId,direction:"in",response:r});let n=await this.cfg.identityLayer.assessReceivedCertificateSufficiency(i.sender,r,e.threadId);if("message"in n)return void await this.sendTermination(e,i.sender,n.message,n.details,n.code);if("identityVerificationAcknowledgment"===n.kind){let t=this.makeEnvelope("identityVerificationAcknowledgment",e.threadId,n),r=await this.sendEnvelope(i.sender,t);e.protocolLog.push({direction:"out",envelope:t,transportMessageId:r}),e.identity.acknowledgmentSent=!0,e.flags.hasIdentified=!0,this.transitionThreadState(e,"identityAcknowledged","identity acknowledgment sent"),this.emitEvent({type:"identityAcknowledged",threadId:e.threadId,direction:"out",acknowledgment:n});return}throw Error("Unknown identity verification decision")}case"identityVerificationAcknowledgment":{let i=t.payload;if("object"!=typeof i)throw Error("Identity verification acknowledgment payload missing data");e.identity.acknowledgmentReceived=!0,e.flags.hasIdentified=!0,this.transitionThreadState(e,"identityAcknowledged","identity acknowledgment received"),this.emitEvent({type:"identityAcknowledged",threadId:e.threadId,direction:"in",acknowledgment:i});return}case"invoice":{let i=t.payload;if("object"!=typeof i)throw Error("Invoice payload missing invoice data");e.invoice=i,e.flags.hasInvoiced=!0,this.transitionThreadState(e,"invoiced","invoice received"),this.emitEvent({type:"invoiceReceived",threadId:e.threadId,invoice:i});return}case"settlement":{let r=t.payload;if("object"!=typeof r)throw Error("Settlement payload missing settlement data");if(this.shouldRequireIdentityBeforeSettlement(e)&&!e.flags.hasIdentified)return void await this.sendTermination(e,i.sender,"Identity verification is required before settlement");e.settlement=r,e.flags.hasPaid=!0,this.transitionThreadState(e,"settled","settlement received"),this.emitEvent({type:"settlementReceived",threadId:e.threadId,settlement:r});let n=this.moduleRegistry.get(r.moduleId);if("object"!=typeof n)return void await this.maybeSendTermination(e,r,i.sender,`Unsupported module: ${r.moduleId}`);if(null==e.invoice&&!n.allowUnsolicitedSettlements)return void await this.maybeSendTermination(e,r,i.sender,"Unsolicited settlement not supported");let a=await n.acceptSettlement({threadId:e.threadId,invoice:e.invoice,settlement:r.artifact,sender:i.sender},this.moduleContext()).catch(async t=>{let n=t instanceof Error?t.message:String(t);throw await this.maybeSendTermination(e,r,i.sender,`Settlement processing failed: ${n}`),t});if("accept"===a.action){let t=this.requireMyIdentityKey("Receiving settlement requires identity key"),n=i.sender,s={kind:"receipt",threadId:e.threadId,moduleId:r.moduleId,optionId:r.optionId,payee:t,payer:n,createdAt:this.now(),receiptData:a.receiptData};if(e.receipt=s,e.flags.hasReceipted=!0,this.transitionThreadState(e,"receipted","receipt issued"),this.runtime.receiptProvided&&this.runtime.autoIssueReceipt){let t=this.makeEnvelope("receipt",e.threadId,s),r=await this.sendEnvelope(i.sender,t);e.protocolLog.push({direction:"out",envelope:t,transportMessageId:r}),this.emitEvent({type:"receiptSent",threadId:e.threadId,receipt:s})}}else if("terminate"===a.action)await this.maybeSendTermination(e,r,i.sender,a.termination.message,a.termination.details);else throw Error("Unknown settlement acceptance action");return}case"receipt":{let r=t.payload;if("object"!=typeof r)throw Error("Receipt payload missing receipt data");e.receipt=r,e.flags.hasReceipted=!0,this.transitionThreadState(e,"receipted","receipt received"),this.emitEvent({type:"receiptReceived",threadId:e.threadId,receipt:r});let n=this.moduleRegistry.get(r.moduleId);n?.processReceipt!=null&&await n.processReceipt({threadId:e.threadId,invoice:e.invoice,receiptData:r.receiptData,sender:i.sender},this.moduleContext());return}case"termination":{let r=t.payload;if("object"!=typeof r)throw Error("Termination payload missing data");if(e.termination=r,e.lastError={message:r.message,at:this.now()},e.flags.error=!0,this.transitionThreadState(e,"terminated","termination received"),this.emitEvent({type:"terminationReceived",threadId:e.threadId,termination:r}),null!=e.settlement){let t=this.moduleRegistry.get(e.settlement.moduleId);t?.processTermination!=null&&await t.processTermination({threadId:e.threadId,invoice:e.invoice,settlement:e.settlement,termination:r,sender:i.sender},this.moduleContext())}return}default:{let e=t.kind;throw Error(`Unknown envelope kind: ${String(e)}`)}}}async maybeSendTermination(e,t,i,r,n){let a={code:"error",message:r,details:n},s=this.makeEnvelope("termination",e.threadId,a),o=await this.sendEnvelope(i,s);e.protocolLog.push({direction:"out",envelope:s,transportMessageId:o}),this.emitEvent({type:"terminationSent",threadId:e.threadId,termination:a}),e.termination=a,e.lastError={message:`Sent termination: ${r}`,at:this.now()},e.flags.error=!0,this.transitionThreadState(e,"terminated","termination sent")}async sendTermination(e,t,i,r,n="error"){let a={code:n,message:i,details:r},s=this.makeEnvelope("termination",e.threadId,a),o=await this.sendEnvelope(t,s);e.protocolLog.push({direction:"out",envelope:s,transportMessageId:o}),this.emitEvent({type:"terminationSent",threadId:e.threadId,termination:a}),e.termination=a,e.lastError={message:`Sent termination: ${i}`,at:this.now()},e.flags.error=!0,this.transitionThreadState(e,"terminated","termination sent")}shouldRequestIdentity(e,t){let{makerRequestIdentity:i="never",takerRequestIdentity:r="never"}=this.runtime.identityOptions??{};if(!("maker"===e.myRole?i===t:r===t))return!1;if(null==this.cfg.identityLayer)throw Error("Identity layer is required by runtime options but is not configured");return!0}shouldRequireIdentityBeforeSettlement(e){return"maker"===e.myRole&&(this.runtime.identityOptions?.makerRequestIdentity??"never")==="beforeSettlement"}async ensureIdentityExchange(e,t){if(null!=this.cfg.identityLayer&&!e.flags.hasIdentified){if(!e.identity.requestSent){let i=await this.cfg.identityLayer.determineCertificatesToRequest({counterparty:e.counterparty,threadId:e.threadId},this.moduleContext()),r=this.makeEnvelope("identityVerificationRequest",e.threadId,i),n=await this.sendEnvelope(e.counterparty,r,t);e.protocolLog.push({direction:"out",envelope:r,transportMessageId:n}),e.identity.requestSent=!0,this.transitionThreadState(e,"identityRequested","identity request sent"),this.emitEvent({type:"identityRequested",threadId:e.threadId,direction:"out",request:i}),e.updatedAt=this.now(),await this.persistState()}await this.waitForIdentityAcknowledgment(e.threadId,{timeoutMs:this.runtime.identityTimeoutMs,pollIntervalMs:this.runtime.identityPollIntervalMs})}}async waitForIdentityAcknowledgment(e,t={}){await this.waitForState(e,"identityAcknowledged",t)}async safeAck(e){try{await this.comms.acknowledgeMessage({messageIds:e})}catch(e){this.cfg.logger?.warn?.("[RemittanceManager] Failed to acknowledge message(s)",e)}}markThreadError(e,t){e.flags.error=!0,this.transitionThreadState(e,"errored","thread error"),e.lastError={message:String(t?.message??t),at:this.now()},this.cfg.logger?.error?.("[RemittanceManager] Thread error",e.threadId,t),this.emitEvent({type:"error",threadId:e.threadId,error:String(t?.message??t)})}ensureThreadState(e){return e.identity=e.identity??{certsSent:[],certsReceived:[],requestSent:!1,responseSent:!1,acknowledgmentSent:!1,acknowledgmentReceived:!1},e.identity.certsSent??=[],e.identity.certsReceived??=[],e.identity.requestSent??=!1,e.identity.responseSent??=!1,e.identity.acknowledgmentSent??=!1,e.identity.acknowledgmentReceived??=!1,e.flags=e.flags??{hasIdentified:!1,hasInvoiced:!1,hasPaid:!1,hasReceipted:!1,error:!1},e.processedMessageIds??=[],e.protocolLog??=[],e.stateLog??=[],null==e.state&&(e.state=this.deriveThreadState(e)),e}deriveThreadState(e){return e.flags.error?"errored":null!=e.termination?"terminated":null!=e.receipt?"receipted":null!=e.settlement?"settled":null!=e.invoice?"invoiced":e.identity.acknowledgmentReceived||e.identity.acknowledgmentSent||e.flags.hasIdentified?"identityAcknowledged":e.identity.responseSent||e.identity.certsSent.length>0?"identityResponded":e.identity.requestSent||e.identity.certsReceived.length>0?"identityRequested":"new"}transitionThreadState(e,t,i){let r=e.state;if(r!==t){if(!(al[r]??[]).includes(t))throw Error(`Invalid remittance state transition: ${r} -> ${t}`);e.state=t,e.updatedAt=this.now(),e.stateLog.push({at:this.now(),from:r,to:t,reason:i}),this.emitEvent({type:"stateChanged",threadId:e.threadId,previous:r,next:t,reason:i}),this.resolveStateWaiters(e.threadId,t),("terminated"===t||"errored"===t)&&this.rejectStateWaiters(e.threadId,Error(`Thread entered terminal state: ${t}`))}}resolveStateWaiters(e,t){let i=this.stateWaiters.get(e);if(null==i)return;let r=[];for(let e of i)e.state===t?e.resolve():r.push(e);0===r.length?this.stateWaiters.delete(e):this.stateWaiters.set(e,r)}rejectStateWaiters(e,t){let i=this.stateWaiters.get(e);if(null!=i){for(let e of i)e.reject(t);this.stateWaiters.delete(e)}}emitEvent(e){let t=this.eventHandlers;if(null!=t)try{switch(e.type){case"threadCreated":t.onThreadCreated?.(e);break;case"stateChanged":t.onStateChanged?.(e);break;case"envelopeSent":t.onEnvelopeSent?.(e);break;case"envelopeReceived":t.onEnvelopeReceived?.(e);break;case"identityRequested":t.onIdentityRequested?.(e);break;case"identityResponded":t.onIdentityResponded?.(e);break;case"identityAcknowledged":t.onIdentityAcknowledged?.(e);break;case"invoiceSent":t.onInvoiceSent?.(e);break;case"invoiceReceived":t.onInvoiceReceived?.(e);break;case"settlementSent":t.onSettlementSent?.(e);break;case"settlementReceived":t.onSettlementReceived?.(e);break;case"receiptSent":t.onReceiptSent?.(e);break;case"receiptReceived":t.onReceiptReceived?.(e);break;case"terminationSent":t.onTerminationSent?.(e);break;case"terminationReceived":t.onTerminationReceived?.(e);break;case"error":t.onError?.(e)}}catch(e){this.cfg.logger?.warn?.("[RemittanceManager] Event handler error",e)}for(let t of this.eventListeners)try{t(e)}catch(e){this.cfg.logger?.warn?.("[RemittanceManager] Event listener error",e)}}async refreshMyIdentityKey(){if("string"==typeof this.myIdentityKey||"object"!=typeof this.wallet)return;let{publicKey:e}=await this.wallet.getPublicKey({identityKey:!0},this.cfg.originator);"string"==typeof e&&""!==e.trim()&&(this.myIdentityKey=e)}requireMyIdentityKey(e){if("string"!=typeof this.myIdentityKey)throw Error(e);return this.myIdentityKey}async composeInvoice(e,t,i,r){let n=this.now(),a=this.runtime.invoiceExpirySeconds>=0?n+1e3*this.runtime.invoiceExpirySeconds:void 0;return{kind:"invoice",threadId:e,payee:t,payer:i,note:r.note,lineItems:r.lineItems,total:r.total,invoiceNumber:r.invoiceNumber??e,createdAt:n,expiresAt:a,arbitrary:r.arbitrary,options:{}}}}class af{manager;threadId;constructor(e,t){this.manager=e,this.threadId=t}get thread(){return this.manager.getThreadOrThrow(this.threadId)}async waitForState(e,t){return await this.manager.waitForState(this.threadId,e,t)}async waitForIdentity(e){return await this.manager.waitForIdentity(this.threadId,e)}async waitForSettlement(e){return await this.manager.waitForSettlement(this.threadId,e)}async waitForReceipt(e){return await this.manager.waitForReceipt(this.threadId,e)}}class ap extends af{get invoice(){let e=this.thread.invoice;if("object"!=typeof e)throw Error("Thread has no invoice");return e}async pay(e){return await this.manager.pay(this.threadId,e)}}function ag(){return tc(t0(32))}async function am(e){return await new Promise(t=>setTimeout(t,e))}let ay={createNonce:async(e,t,i)=>await nT(e,t,i)},ab={async pubKeyToP2PKHLockingScript(e){let t=tJ.fromString(e).toAddress();return new iL().lock(t).toHex()}};class aw{id="brc29.p2pkh";name="BSV (BRC-29 derived P2PKH)";allowUnsolicitedSettlements=!0;protocolID;labels;description;outputDescription;refundFeeSatoshis;minRefundSatoshis;internalizeProtocol;nonceProvider;lockingScriptProvider;constructor(e={}){this.protocolID=e.protocolID??[2,"3241645161d8"],this.labels=e.labels??["brc29"],this.description=e.description??"BRC-29 payment",this.outputDescription=e.outputDescription??"Payment for remittance invoice",this.refundFeeSatoshis=e.refundFeeSatoshis??1e3,this.minRefundSatoshis=e.minRefundSatoshis??1e3,this.internalizeProtocol=e.internalizeProtocol??"wallet payment",this.nonceProvider=e.nonceProvider??ay,this.lockingScriptProvider=e.lockingScriptProvider??ab}async buildSettlement(e,t){let i,{wallet:r,originator:n}=t;try{i=function(e){if(null==e||"object"!=typeof e)throw Error("BRC-29 option terms are required");let t=e.amountSatoshis;if(!Number.isInteger(t)||t<=0)throw Error("BRC-29 option amount must be a positive integer");let i=e.outputIndex;if(null!=i&&(!Number.isInteger(i)||i<0))throw Error("BRC-29 option outputIndex must be a non-negative integer");let r=e.protocolID;if(null!=r){if(!Array.isArray(r)||2!==r.length)throw Error("BRC-29 option protocolID must be a tuple [number, string]");let[e,t]=r;if(!Number.isInteger(e)||e<0||!ak(t))throw Error("BRC-29 option protocolID must be a tuple [number, string]")}let n=e.labels;if(null!=n&&(!Array.isArray(n)||n.some(e=>!ak(e))))throw Error("BRC-29 option labels must be a list of non-empty strings");let a=e.description;if(null!=a&&!ak(a))throw Error("BRC-29 option description must be a non-empty string");return e}(e.option)}catch(e){return av("brc29.invalid_option",e instanceof Error?e.message:String(e))}let a=i.amountSatoshis;try{let t=await this.nonceProvider.createNonce(r,"self",n),s=await this.nonceProvider.createNonce(r,"self",n),o=i.protocolID??this.protocolID,c=`${t} ${s}`,{publicKey:l}=await r.getPublicKey({protocolID:o,keyID:c,counterparty:i.payee},n);if("string"!=typeof l||""===l.trim())return av("brc29.public_key_missing","Failed to derive payee public key for BRC-29 settlement.");let h=await this.lockingScriptProvider.pubKeyToP2PKHLockingScript(l);if("string"!=typeof h||""===h.trim())return av("brc29.locking_script_missing","Failed to produce P2PKH locking script.");let d=await r.createAction({description:i.description??this.description,labels:i.labels??this.labels,outputs:[{satoshis:a,lockingScript:h,customInstructions:JSON.stringify({derivationPrefix:t,derivationSuffix:s,payee:i.payee,threadId:e.threadId,note:e.note}),outputDescription:this.outputDescription}],options:{randomizeOutputs:!1}},n),u=d.tx??d.signableTransaction?.tx;if(null==u)return av("brc29.missing_tx","wallet.createAction did not return a transaction.");if(!aI(u))return av("brc29.invalid_tx","wallet.createAction returned an invalid transaction payload.");return{action:"settle",artifact:{customInstructions:{derivationPrefix:t,derivationSuffix:s},transaction:u,amountSatoshis:i.amountSatoshis,outputIndex:i.outputIndex??0}}}catch(t){let e=t instanceof Error?t.message:String(t);return av("brc29.build_failed",`BRC-29 settlement failed: ${e}`)}}async acceptSettlement(e,t){let{wallet:i,originator:r}=t;console.log("acceptSettlement",e);try{let t=function(e){if(null==e||"object"!=typeof e)throw Error("BRC-29 settlement artifact is required");let t=e.customInstructions;if(null==t||"object"!=typeof t)throw Error("BRC-29 settlement requires customInstructions");if(!ak(t.derivationPrefix)||!ak(t.derivationSuffix))throw Error("BRC-29 settlement derivation values are required");let i=e.amountSatoshis;if(!Number.isInteger(i)||i<=0)throw Error("BRC-29 settlement amount must be a positive integer");let r=e.outputIndex;if(null!=r&&(!Number.isInteger(r)||r<0))throw Error("BRC-29 settlement outputIndex must be a non-negative integer");if(!aI(e.transaction))throw Error("BRC-29 settlement transaction must be a non-empty byte array");return e}(e.settlement),n=t.outputIndex??0,a=await i.internalizeAction({tx:t.transaction,outputs:[{paymentRemittance:{derivationPrefix:t.customInstructions.derivationPrefix,derivationSuffix:t.customInstructions.derivationSuffix,senderIdentityKey:e.sender},outputIndex:n,protocol:this.internalizeProtocol}],labels:this.labels,description:"BRC-29 payment received"},r);return{action:"accept",receiptData:{internalizeResult:a}}}catch(t){let e=t instanceof Error?t.message:String(t);return av("brc29.internalize_failed",`Failed to internalize BRC-29 settlement: ${e}`)}}}function av(e,t,i){return{action:"terminate",termination:{code:e,message:t,details:i}}}function aI(e){return!!Array.isArray(e)&&0!==e.length&&e.every(e=>Number.isInteger(e)&&e>=0&&e<=255)}function ak(e){return"string"==typeof e&&e.trim().length>0}return p})());
19
+ `);return e}addComputedLeaves(){let e=e=>te(eo(ti(e,"hex").reverse()).reverse());for(let t of this.bumps)for(let i=1;i<t.path.length;i++)for(let r of t.path[i-1])if("string"==typeof r.hash&&(1&r.offset)==0){let n=t.path[i-1].find(e=>e.offset===r.offset+1),a=r.offset>>1;void 0!==n&&"string"==typeof n.hash&&t.path[i].every(e=>e.offset!==a)&&t.path[i].push({offset:a,hash:e(n.hash+r.hash)})}}}class i3{version;inputs;outputs;lockTime;metadata;merklePath;cachedHash;rawBytesCache;hexCache;static addPathOrInputs(e,t,i){if("number"==typeof e.pathIndex){let t=i[e.pathIndex];if("object"!=typeof t)throw Error("Invalid merkle path index found in BEEF!");e.tx.merklePath=t}else for(let r of e.tx.inputs){if(void 0===r.sourceTXID)throw Error("Input sourceTXID is undefined");let e=t[r.sourceTXID];if("object"!=typeof e)throw Error(`Reference to unknown TXID in BEEF: ${r.sourceTXID??"undefined"}`);r.sourceTransaction=e.tx,this.addPathOrInputs(e,t,i)}}static fromBEEF(e,t){let{tx:i}=i3.fromAnyBeef(e,t);return i}static fromAtomicBEEF(e){let{tx:t,txid:i,beef:r}=i3.fromAnyBeef(e);if(i!==r.atomicTxid)if(null!=r.atomicTxid)throw Error(`Transaction with TXID ${r.atomicTxid} not found in BEEF data.`);else throw Error("beef must conform to BRC-95 and must contain the subject txid.");return t}static fromAnyBeef(e,t){let i=i8.fromBinary(e);if(i.txs.length<1)throw Error("beef must include at least one transaction.");let r=t??i.atomicTxid??i.txs.slice(-1)[0].txid,n=i.findAtomicTransaction(r);if(null==n)if(null!=t)throw Error(`Transaction with TXID ${r} not found in BEEF data.`);else throw Error("beef does not contain transaction for atomic txid.");return{tx:n,beef:i,txid:r}}static fromEF(e){let t=e3.makeReader(e),i=t.readUInt32LE();if("0000000000ef"!==te(t.read(6)))throw Error("Invalid EF marker");let r=t.readVarIntNum(),n=[];for(let e=0;e<r;e++){let e=te(t.readReverse(32)),i=t.readUInt32LE(),r=t.readVarIntNum(),a=t.read(r),s=i_.fromBinary(a),o=t.readUInt32LE(),c=t.readUInt64LEBn().toNumber(),l=t.readVarIntNum(),h=t.read(l),d=iT.fromBinary(h),u=new i3(void 0,[],[],void 0);u.outputs=Array(i+1).fill(null),u.outputs[i]={satoshis:c,lockingScript:d},n.push({sourceTransaction:u,sourceTXID:e,sourceOutputIndex:i,unlockingScript:s,sequence:o})}let a=t.readVarIntNum(),s=[];for(let e=0;e<a;e++){let e=t.readUInt64LEBn().toNumber(),i=t.readVarIntNum(),r=t.read(i),n=iT.fromBinary(r);s.push({satoshis:e,lockingScript:n})}return new i3(i,n,s,t.readUInt32LE())}static parseScriptOffsets(e){let t=e3.makeReader(e),i=[],r=[];t.pos+=4;let n=t.readVarIntNum();for(let e=0;e<n;e++){t.pos+=36;let r=t.readVarIntNum();i.push({vin:e,offset:t.pos,length:r}),t.pos+=r+4}let a=t.readVarIntNum();for(let e=0;e<a;e++){t.pos+=8;let i=t.readVarIntNum();r.push({vout:e,offset:t.pos,length:i}),t.pos+=i}return{inputs:i,outputs:r}}static fromReader(e){let t=e.readUInt32LE(),i=e.readVarIntNum(),r=[];for(let t=0;t<i;t++){let t=te(e.readReverse(32)),i=e.readUInt32LE(),n=e.readVarIntNum(),a=e.read(n),s=i_.fromBinary(a),o=e.readUInt32LE();r.push({sourceTXID:t,sourceOutputIndex:i,unlockingScript:s,sequence:o})}let n=e.readVarIntNum(),a=[];for(let t=0;t<n;t++){let t=e.readUInt64LEBn().toNumber(),i=e.readVarIntNum(),r=e.read(i),n=iT.fromBinary(r);a.push({satoshis:t,lockingScript:n})}return new i3(t,r,a,e.readUInt32LE())}static fromBinary(e){let t=e.slice(),i=Uint8Array.from(t),r=new e3(i),n=i3.fromReader(r);return n.rawBytesCache=i,n}static fromHex(e){let t=tt(e,"hex"),i=new e3(t),r=i3.fromReader(i);return r.rawBytesCache=t,r.hexCache=te(t),r}static fromHexEF(e){return i3.fromEF(tt(e,"hex"))}static fromHexBEEF(e,t){return i3.fromBEEF(ti(e,"hex"),t)}constructor(e=1,t=[],i=[],r=0,n=new Map,a){this.version=e,this.inputs=t,this.outputs=i,this.lockTime=r,this.metadata=n,this.merklePath=a}invalidateSerializationCaches(){this.cachedHash=void 0,this.rawBytesCache=void 0,this.hexCache=void 0}addInput(e){if(void 0===e.sourceTXID&&void 0===e.sourceTransaction)throw 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=0xffffffff),this.invalidateSerializationCaches(),this.inputs.push(e)}addOutput(e){if(this.cachedHash=void 0,!0!==e.change){if(void 0===e.satoshis)throw Error("either satoshis must be defined or change must be set to true");if(e.satoshis<0)throw Error("satoshis must be a positive integer or zero")}if(null==e.lockingScript)throw Error("lockingScript must be defined");this.outputs.push(e)}addP2PKHOutput(e,t){let i=new iL().lock(e);if(void 0===t)return this.addOutput({lockingScript:i,change:!0});this.addOutput({lockingScript:i,satoshis:t})}updateMetadata(e){this.metadata={...this.metadata,...e}}async fee(e=iq.getInstance(),t="equal"){if(this.invalidateSerializationCaches(),"number"==typeof e){let t=e;e={computeFee:async()=>t}}let i=await e.computeFee(this),r=this.calculateChange(i);if(r<=0){this.outputs=this.outputs.filter(e=>!0!==e.change);return}this.distributeChange(r,t)}calculateChange(e){let t=0;for(let e of this.inputs){if("object"!=typeof e.sourceTransaction)throw Error("Source transactions are required for all inputs during fee computation");t+=e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0}for(let i of(t-=e,this.outputs))!0!==i.change&&void 0!==i.satoshis&&(t-=i.satoshis);return t}distributeChange(e,t){let i=0,r=this.outputs.filter(e=>e.change);if("random"===t?i=this.distributeRandomChange(e,r):"equal"===t&&(i=this.distributeEqualChange(e,r)),i<e){let t=this.outputs[this.outputs.length-1];void 0!==t.satoshis?t.satoshis+=e-i:t.satoshis=e-i}}distributeRandomChange(e,t){let i=0,r=e,n=Array(t.length).fill(1);r-=t.length,i+=t.length;for(let e=0;e<t.length-1;e++){let t=this.benfordNumber(0,r);n[e]=n[e]+t,i+=t,r-=t}for(let e of this.outputs)!0===e.change&&(e.satoshis=n.shift());return i}distributeEqualChange(e,t){let i=0,r=Math.floor(e/t.length);for(let e of t)i+=r,e.satoshis=r;return i}benfordNumber(e,t){return Math.floor(e+(t-e)*Math.log10(1+1/(Math.floor(9*Math.random())+1))/Math.log10(10))}getFee(){let e=0;for(let t of this.inputs){if("object"!=typeof t.sourceTransaction)throw 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(let e of this.outputs)t+=e.satoshis??0;return e-t}async sign(){for(let e of(this.invalidateSerializationCaches(),this.outputs))if(void 0===e.satoshis)if(!0===e.change)throw Error("There are still change outputs with uncomputed amounts. Use the fee() method to compute the change amounts and transaction fees prior to signing.");else throw Error("One or more transaction outputs is missing an amount. Ensure all output amounts are provided before signing.");let e=await Promise.all(this.inputs.map(async(e,t)=>"object"==typeof this.inputs[t].unlockingScriptTemplate?await this.inputs[t]?.unlockingScriptTemplate?.sign(this,t):await Promise.resolve(void 0)));for(let t=0,i=this.inputs.length;t<i;t++)"object"==typeof this.inputs[t].unlockingScriptTemplate&&(this.inputs[t].unlockingScript=e[t])}async broadcast(e=iG()){return await e.broadcast(this)}writeTransactionBody(e){for(let t of(e.writeUInt32LE(this.version),e.writeVarIntNum(this.inputs.length),this.inputs)){if(void 0===t.sourceTXID)if(null!=t.sourceTransaction)e.write(t.sourceTransaction.hash());else throw Error("sourceTransaction is undefined");else e.writeReverse(ti(t.sourceTXID,"hex"));if(e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw Error("unlockingScript is undefined");let i=t.unlockingScript.toUint8Array();e.writeVarIntNum(i.length),e.write(i),e.writeUInt32LE(t.sequence??0xffffffff)}for(let t of(e.writeVarIntNum(this.outputs.length),this.outputs)){e.writeUInt64LE(t.satoshis??0);let i=t.lockingScript.toUint8Array();e.writeVarIntNum(i.length),e.write(i)}e.writeUInt32LE(this.lockTime)}buildSerializedBytes(){let e=new e8;return this.writeTransactionBody(e),e.toUint8Array()}getSerializedBytes(){return null==this.rawBytesCache&&(this.rawBytesCache=this.buildSerializedBytes()),this.rawBytesCache}toBinary(){return Array.from(this.getSerializedBytes())}toUint8Array(){return this.getSerializedBytes()}writeEF(e){for(let t of(e.writeUInt32LE(this.version),e.write([0,0,0,0,0,239]),e.writeVarIntNum(this.inputs.length),this.inputs)){if(void 0===t.sourceTransaction)throw Error("All inputs must have source transactions when serializing to EF format");if(void 0===t.sourceTXID?e.write(t.sourceTransaction.hash()):e.write(ti(t.sourceTXID,"hex").reverse()),e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw Error("unlockingScript is undefined");let i=t.unlockingScript.toBinary();e.writeVarIntNum(i.length),e.write(i),e.writeUInt32LE(t.sequence??0xffffffff),e.writeUInt64LE(t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0);let r=t.sourceTransaction.outputs[t.sourceOutputIndex].lockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r)}for(let t of(e.writeVarIntNum(this.outputs.length),this.outputs)){e.writeUInt64LE(t.satoshis??0);let i=t.lockingScript.toBinary();e.writeVarIntNum(i.length),e.write(i)}e.writeUInt32LE(this.lockTime)}toEF(){let e=new tp;return this.writeEF(e),e.toArray()}toEFUint8Array(){let e=new e8;return this.writeEF(e),e.toUint8Array()}toHexEF(){return te(this.toEFUint8Array())}toHex(){if(null!=this.hexCache)return this.hexCache;let e=te(this.getSerializedBytes());return this.hexCache=e,e}toHexBEEF(){return te(this.toBEEF())}toHexAtomicBEEF(){return te(this.toAtomicBEEF())}hash(e){return(null==this.cachedHash&&(this.cachedHash=eo(this.getSerializedBytes())),"hex"===e)?te(this.cachedHash):this.cachedHash}id(e){let t=[...this.hash()];return(t.reverse(),"hex"===e)?te(t):t}async verify(e=iJ(),t,i){let r=new Set,n=[this];for(;n.length>0;){let a=n.shift(),s=a?.id("hex")??"";if(null!=s&&""!==s&&r.has(s))continue;if("object"==typeof a?.merklePath)if("scripts only"===e){null!=s&&r.add(s);continue}else{if(await a.merklePath.verify(s,e)){r.add(s);continue}throw Error(`Invalid merkle path for transaction ${s}`)}if(void 0!==t){if(void 0===a)throw Error("Transaction is undefined");let e=i3.fromEF(a.toEF());if(delete e.outputs[0].satoshis,e.outputs[0].change=!0,await e.fee(t),a.getFee()<e.getFee())throw Error(`Verification failed because the transaction ${s} has an insufficient fee and has not been mined.`)}let o=0;if(void 0===a)throw Error("Transaction is undefined");for(let e=0;e<a.inputs.length;e++){let t=a.inputs[e];if("object"!=typeof t.sourceTransaction)throw Error(`Verification failed because the input at index ${e} of transaction ${s} 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 Error(`Verification failed because the input at index ${e} of transaction ${s} is missing an associated unlocking script. This script is required for transaction verification because there is no merkle proof for the transaction spending the UTXO.`);let c=t.sourceTransaction.outputs[t.sourceOutputIndex];o+=c.satoshis??0;let l=t.sourceTransaction.id("hex");r.has(l)||n.push(t.sourceTransaction);let h=a.inputs.filter((t,i)=>i!==e);if(void 0===t.sourceTXID&&(t.sourceTXID=l),!new iD({sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,lockingScript:c.lockingScript,sourceSatoshis:c.satoshis??0,transactionVersion:a.version,otherInputs:h,unlockingScript:t.unlockingScript,inputSequence:t.sequence??0xffffffff,inputIndex:e,outputs:a.outputs,lockTime:a.lockTime,memoryLimit:i}).validate())return!1}let c=0;for(let e of a.outputs){if("number"!=typeof e.satoshis)throw Error("Every output must have a defined amount during transaction verification.");c+=e.satoshis}if(c>o)return!1;r.add(s)}return!0}writeSerializedBEEF(e,t){e.writeUInt32LE(i0);let i=[],r=new Map,n=new Map,a=[],s=new Set,o=e=>{let c=e.id("hex");if(s.has(c))return;let l={tx:e},h=e.merklePath,d="object"==typeof h;if(d&&null!=h&&(l.pathIndex=(e=>{let t=r.get(e);if(void 0!==t)return t;let a=`${e.blockHeight}:${e.computeRoot()}`,s=n.get(a);if(void 0!==s)return i[s].combine(e),r.set(e,s),s;let o=i.length;return i.push(e),r.set(e,o),n.set(a,o),o})(h)),!d)for(let i=e.inputs.length-1;i>=0;i--){let r=e.inputs[i];if("object"==typeof r.sourceTransaction)o(r.sourceTransaction);else if(!1===t)throw Error("A required source transaction is missing!")}s.add(c),a.push(l)};for(let t of(o(this),e.writeVarIntNum(i.length),i))e.write(t.toBinary());for(let t of(e.writeVarIntNum(a.length),a))e.write(t.tx.toBinary()),"number"==typeof t.pathIndex?(e.writeUInt8(1),e.writeVarIntNum(t.pathIndex)):e.writeUInt8(0);return e.toArray()}toBEEF(e){let t=new tp;return this.writeSerializedBEEF(t,e),t.toArray()}toBEEFUint8Array(e){let t=new e8;return this.writeSerializedBEEF(t,e),t.toArray()}toAtomicBEEF(e){return[1,1,1,1].concat(this.hash(),this.toBEEF(e))}toAtomicBEEFUint8Array(e){let t=new e8;t.write([1,1,1,1]);let i=this.hash();return t.write(i),this.writeSerializedBEEF(t,e),t.toUint8Array()}async completeWithWallet(e,t,i,r){let n,a=this.inputs.length,s=this.outputs.length,o={description:t??`Transaction with ${a} input(s) and ${s} output(s)`,inputs:[],outputs:[],lockTime:this.lockTime,version:this.version},c=this.inputs.some(e=>null!=e.unlockingScriptTemplate),l=new i8;for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];if(null==t.sourceTransaction)throw Error("All inputs must have a sourceTransaction when using completeWithWallet");let i=t.sourceTransaction.toBEEF();l.mergeBeef(i);let r=t.sourceTransaction.id("hex"),n={outpoint:`${r}.${t.sourceOutputIndex}`,inputDescription:"Input from source transaction",sequenceNumber:t.sequence};if(c)if(null!=t.unlockingScriptTemplate)n.unlockingScriptLength=await t.unlockingScriptTemplate.estimateLength(this,e);else if(null!=t.unlockingScript)n.unlockingScript=t.unlockingScript.toHex();else throw Error(`Input ${e} must have either an unlockingScript or unlockingScriptTemplate`);else{if(null==t.unlockingScript)throw Error("All inputs must have an unlockingScript when using completeWithWallet");n.unlockingScript=t.unlockingScript.toHex()}o.inputs.push(n)}for(let e of(this.inputs.length>0&&(o.inputBEEF=l.toBinary()),this.outputs))o.outputs.push({satoshis:e.satoshis,lockingScript:e.lockingScript.toHex(),outputDescription:"Output from source transaction"});if(this.metadata?.labels!=null&&Array.isArray(this.metadata.labels)&&(o.labels=this.metadata.labels),c){o.options={...r,signAndProcess:!1};let{signableTransaction:t}=await e.createAction(o,i);if(null==t)throw Error("Wallet createAction did not return signableTransaction");let a=i3.fromBEEF(t.tx),s={};for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];if(null!=t.unlockingScriptTemplate){let i=await t.unlockingScriptTemplate.sign(a,e);s[e]={unlockingScript:i.toHex()}}else null!=t.unlockingScript&&(s[e]={unlockingScript:t.unlockingScript.toHex()})}let c=null!=r?{acceptDelayedBroadcast:r.acceptDelayedBroadcast,returnTXIDOnly:r.returnTXIDOnly,noSend:r.noSend,sendWith:r.sendWith}:void 0,l=await e.signAction({reference:t.reference,spends:s,options:c},i);if(null==l.tx)throw Error("Wallet signAction did not return transaction data");n=l.tx}else{null!=r&&(o.options=r);let{tx:t}=await e.createAction(o,i);if(null==t)throw Error("Wallet createAction did not return transaction data");n=t}let h=i3.fromAtomicBEEF(n);this.version=h.version,this.inputs=h.inputs,this.outputs=h.outputs,this.lockTime=h.lockTime,this.merklePath=h.merklePath,this.cachedHash=h.cachedHash,this.metadata={...this.metadata,...h.metadata}}}function i6(e){return"success"===e.status}function i4(e){return"error"===e.status}let i5=class extends i8{knownTo={};constructor(e){if(super(),null!=e)for(const t of e)this.addParty(t)}isParty(e){return Object.keys(this.knownTo).includes(e)}addParty(e){if(this.isParty(e))throw Error(`Party ${e} already exists.`);this.knownTo[e]={}}getKnownTxidsForParty(e){let t=this.knownTo[e];if(void 0===t)throw Error(`Party ${e} is unknown.`);return Object.keys(t)}getTrimmedBeefForParty(e){let t=this.getKnownTxidsForParty(e),i=this.clone();return i.trimKnownTxids(t),i}addKnownTxidsForParty(e,t){this.isParty(e)||this.addParty(e);let i=this.knownTo[e];for(let e of t)i[e]=!0,this.mergeTxidOnly(e)}mergeBeefFromParty(e,t){let i=Array.isArray(t)?i8.fromBinary(t):t,r=i.getValidTxids();this.mergeBeef(i),this.addKnownTxidsForParty(e,r)}};class i7{network;URL;httpClient;constructor(e="main",t=iW()){this.network=e,this.URL=`https://api.whatsonchain.com/v1/bsv/${e}/tx/raw`,this.httpClient=t}async broadcast(e){let t=e.toHex();try{let e=await this.httpClient.request(this.URL,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/plain"},data:{txhex:t}});if(!e.ok)return{status:"error",code:e.status.toString()??"ERR_UNKNOWN",description:e.data??"Unknown error"};{let t=e.data;return{status:"success",txid:t,message:"broadcast successful"}}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class i9{https;constructor(e){this.https=e}async request(e,t){return await new Promise((i,r)=>{let n=this.https.request(e,t,e=>{let t="";e.on("data",e=>{t+=e}),e.on("end",()=>{let r=e.statusCode>=200&&e.statusCode<=299,n=e.headers["content-type"],a=""!==t&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(t):t;i({status:e.statusCode,statusText:e.statusMessage,ok:r,data:a})})});n.on("error",e=>{r(e)}),null!==t.data&&void 0!==t.data&&n.write(Buffer.from(t.data)),n.end()})}}class re{fetch;constructor(e){this.fetch=e}async request(e,t){let i={method:t.method,headers:t.headers,body:t.data},r=await this.fetch(e,i),n=await r.text();return{ok:r.ok,status:r.status,statusText:r.statusText,data:n}}}function rt(){let e={async request(){throw Error("No method available to perform HTTP request")}};if("u">typeof window&&"function"==typeof window.fetch)return new re(window.fetch.bind(window));if(!("u">typeof require))return e;try{let e=require("https");return new i9(e)}catch(t){return e}}class ri{URL;httpClient;constructor(e,t=rt()){this.URL=e,this.httpClient=t}async broadcast(e){let t={method:"POST",headers:{"Content-Type":"application/octet-stream"},data:new Blob([new Uint8Array(e.toEF())])};try{let i=await this.httpClient.request(this.URL,t);if(!i.ok)return{status:"error",code:i.status.toString()??"ERR_UNKNOWN",description:i.data??"Unknown error"};{let t=e.id("hex");return{status:"success",txid:t,message:"broadcast successful"}}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class rr{baseUrl;httpClient;apiKey;constructor(e,t={}){const{httpClient:i,apiKey:r}=t;this.baseUrl=e,this.httpClient=i??iW(),this.apiKey=r??""}async isValidRootForHeight(e,t){let i={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.apiKey}`},data:[{blockHeight:t,merkleRoot:e}]};try{let e=await this.httpClient.request(`${this.baseUrl}/api/v1/chain/merkleroot/verify`,i);if(e.ok)return"CONFIRMED"===e.data.confirmationState;throw Error(`Failed to verify merkleroot for height ${t} because of an error: ${JSON.stringify(e.data)}`)}catch(e){throw Error(`Failed to verify merkleroot for height ${t} because of an error: ${e instanceof Error?e.message:String(e)}`)}}async currentHeight(){let e={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`}};try{let t=await this.httpClient.request(`${this.baseUrl}/api/v1/chain/tip/longest`,e);if(t.ok&&t.data&&"number"==typeof t.data.height)return t.data.height;throw Error(`Failed to get current height because of an error: ${JSON.stringify(t.data)}`)}catch(e){throw Error(`Failed to get current height because of an error: ${e instanceof Error?e.message:String(e)}`)}}}let rn="42423301",ra=(e,t,i)=>{let r="object"!=typeof i;if(r){let e=new tH,t=new t3(1),r=e.g.mul(t);i=new tJ(r.x,r.y)}let n=t0(32),a=tc(n),s=`2-message signing-${a}`,o=t.deriveChild(i,s).sign(e).toDER(),c=t.toPublicKey().encode(!0);return[...ti(rn,"hex"),...c,...r?[0]:i.encode(!0),...n,...o]},rs=(e,t,i)=>{let r=new tg(t),n=te(r.read(4));if(n!==rn)throw Error(`Message version mismatch: Expected ${rn}, received ${n}`);let a=tJ.fromString(te(r.read(33))),[s]=r.read(1);if(0===s)i=new t3(1);else{let e=te([s,...r.read(32)]);if("object"!=typeof i)throw Error(`This signature can only be verified with knowledge of a specific private key. The associated public key is: ${e}`);let t=i.toPublicKey().encode(!0,"hex");if(e!==t)throw Error(`The recipient public key is ${t} but the signature requres the recipient to have public key ${e}`)}let o=tc(r.read(32)),c=te(r.read(r.bin.length-r.pos)),l=tK.fromDER(c,"hex"),h=`2-message signing-${o}`;return a.deriveChild(i,h).verify(e,l)},ro="42421033",rc=(e,t,i)=>{let r=t0(32),n=tc(r),a=`2-message encryption-${n}`,s=t.deriveChild(i,a),o=i.deriveChild(t,a),c=new ip(s.deriveSharedSecret(o).encode(!0).slice(1)).encrypt(e),l=t.toPublicKey().encode(!0);return[...ti(ro,"hex"),...l,...i.encode(!0),...r,...c]},rl=(e,t)=>{let i=new tg(e),r=te(i.read(4));if(r!==ro)throw Error(`Message version mismatch: Expected ${ro}, received ${r}`);let n=tJ.fromString(te(i.read(33))),a=te(i.read(33)),s=t.toPublicKey().encode(!0,"hex");if(a!==s)throw Error(`The encrypted message expects a recipient public key of ${a}, but the provided key is ${s}`);let o=tc(i.read(32)),c=i.read(i.bin.length-i.pos),l=`2-message encryption-${o}`,h=n.deriveChild(t,l),d=t.deriveChild(n,l);return new ip(h.deriveSharedSecret(d).encode(!0).slice(1)).decrypt(c)},rh="Bitcoin Signed Message:\n",rd=e=>{let t=new tp;return t.writeVarIntNum(rh.length),t.write(ti(rh,"utf8")),t.writeVarIntNum(e.length),t.write(e),eo(t.toArray())},ru=(e,t,i="base64")=>{let r=rd(e),n=tG(new P(r),t,!0);if("raw"===i)return n;let a=new P(r),s=n.CalculateRecoveryFactor(t.toPublicKey(),a);return n.toCompact(s,!0,"base64")},rf=(e,t,i)=>tY(new P(rd(e)),t,i);class rp{versionBytesNum;depth;parentFingerPrint;childIndex;chainCode;privKey;pubKey;constants={pubKey:0x488b21e,privKey:0x488ade4};constructor(e,t,i,r,n,a,s){this.versionBytesNum=e,this.depth=t,this.parentFingerPrint=i,this.childIndex=r,this.chainCode=n,this.privKey=a,this.pubKey=s}fromRandom(){return this.versionBytesNum=this.constants.privKey,this.depth=0,this.parentFingerPrint=[0,0,0,0],this.childIndex=0,this.chainCode=t0(32),this.privKey=t3.fromRandom(),this.pubKey=this.privKey.toPublicKey(),this}static fromRandom(){return new this().fromRandom()}static fromString(e){return new this().fromString(e)}fromString(e){let t=tf(e);return this.fromBinary([...t.prefix,...t.data])}static fromSeed(e){return new this().fromSeed(e)}fromSeed(e){if(e.length<16)throw Error("Need more than 128 bits of entropy");if(e.length>64)throw Error("More than 512 bits of entropy is nonstandard");let t=eh(ti("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 t3(t.slice(0,32)),this.pubKey=this.privKey.toPublicKey(),this}static fromBinary(e){return new this().fromBinary(e)}fromBinary(e){if(78!==e.length)throw Error("incorrect bip32 data length");let t=new tg(e);this.versionBytesNum=t.readUInt32BE(),this.depth=t.readUInt8(),this.parentFingerPrint=t.read(4),this.childIndex=t.readUInt32BE(),this.chainCode=t.read(32);let i=t.read(33),r=this.versionBytesNum===this.constants.privKey,n=this.versionBytesNum===this.constants.pubKey;if(r&&0===i[0])this.privKey=new t3(i.slice(1,33)),this.pubKey=this.privKey.toPublicKey();else if(n&&(2===i[0]||3===i[0]))this.pubKey=tJ.fromString(te(i));else throw Error("Invalid key");return this}toString(){return tu(this.toBinary(),[])}derive(e){if("m"===e)return this;let t=e.split("/"),i=this;for(let[e,r]of t.entries()){if(0===e){if("m"!==r)throw Error("invalid path");continue}if(parseInt(r.replace("'",""),10).toString()!==r.replace("'",""))throw Error("invalid path");let t=r.length>1&&"'"===r[r.length-1],n=0x7fffffff&parseInt(t?r.slice(0,r.length-1):r,10);t&&(n+=0x80000000),i=i.deriveChild(n)}return i}deriveChild(e){if("number"!=typeof e)throw Error("i must be a number");let t=[];t.push(e>>24&255),t.push(e>>16&255),t.push(e>>8&255),t.push(255&e);let i=[...t],r=(0x80000000&e)!=0,n=this.versionBytesNum===this.constants.privKey;if(r&&(null===this.privKey||void 0===this.privKey||!n))throw Error("Cannot do private key derivation without private key");let a=null;if(null!==this.privKey&&void 0!==this.privKey){let e=null;e=r?[0,...this.privKey.toArray("be",32),...i]:[...this.pubKey.encode(!0),...i];let t=eh(this.chainCode,e),n=new P(t.slice(0,32)),s=t.slice(32,64),o=n.add(this.privKey).mod(new tH().n);(a=new rp).chainCode=s,a.privKey=new t3(o.toArray()),a.pubKey=a.privKey.toPublicKey()}else{let e=[...this.pubKey.encode(!0),...i],t=eh(this.chainCode,e),r=new P(t.slice(0,32)),n=t.slice(32,64),s=new tH().g.mul(r),o=this.pubKey,c=s.add(o),l=new tJ(c.x,c.y);(a=new rp).chainCode=n,a.pubKey=l}a.childIndex=e;let s=ec(this.pubKey.encode(!0));return a.parentFingerPrint=s.slice(0,4),a.versionBytesNum=this.versionBytesNum,a.depth=this.depth+1,a}toPublic(){let e=new rp(this.versionBytesNum,this.depth,this.parentFingerPrint,this.childIndex,this.chainCode,this.privKey,this.pubKey);return e.versionBytesNum=this.constants.pubKey,e.privKey=void 0,e}toBinary(){let e=this.versionBytesNum===this.constants.privKey,t=this.versionBytesNum===this.constants.pubKey;if(e)return new tp().writeUInt32BE(this.versionBytesNum).writeUInt8(this.depth).write(this.parentFingerPrint).writeUInt32BE(this.childIndex).write(this.chainCode).writeUInt8(0).write(this.privKey.toArray("be",32)).toArray();if(t)return new tp().writeUInt32BE(this.versionBytesNum).writeUInt8(this.depth).write(this.parentFingerPrint).writeUInt32BE(this.childIndex).write(this.chainCode).write(this.pubKey.encode(!0)).toArray();throw Error("bip32: invalid versionBytesNum byte")}isPrivate(){return this.versionBytesNum===this.constants.privKey}}let rg={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 rm{mnemonic;seed;Wordlist;constructor(e,t,i=rg){this.mnemonic=e??"",this.seed=t??[],this.Wordlist=i}toBinary(){let e=new tp;if(""!==this.mnemonic){let t=ti(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){let t=new tg(e),i=t.readVarIntNum();i>0&&(this.mnemonic=to(t.read(i),"utf8"));let r=t.readVarIntNum();return r>0&&(this.seed=t.read(r)),this}fromRandom(e){if((null==e||isNaN(e)||0===e)&&(e=128),e%32!=0)throw Error("bits must be multiple of 32");if(e<128)throw Error("bits must be at least 128");let t=t0(e/8);return this.entropy2Mnemonic(t),this.mnemonic2Seed(),this}static fromRandom(e){return new this().fromRandom(e)}fromEntropy(e){return this.entropy2Mnemonic(e),this}static fromEntropy(e){return new this().fromEntropy(e)}fromString(e){return this.mnemonic=e,this}static fromString(e){return new this().fromString(e)}toString(){return this.mnemonic}toSeed(e){return this.mnemonic2Seed(e),this.seed}entropy2Mnemonic(e){if(e.length<16)throw Error("Entropy is less than 128 bits. It must be 128 bits or more.");let t=ea(e),i="",r=8*e.length;for(let t=0;t<e.length;t++)i+=("00000000"+e[t].toString(2)).slice(-8);let n=t[0].toString(2);if((i+=n=("00000000"+n).slice(-8).slice(0,r/32)).length%11!=0)throw Error("internal error - entropy not an even multiple of 11 bits - "+i.length.toString());let a="";for(let e=0;e<i.length/11;e++){""!==a&&(a+=this.Wordlist.space);let t=parseInt(i.slice(11*e,(e+1)*11),2);a+=this.Wordlist.value[t]}return this.mnemonic=a,this}check(){let e=this.mnemonic.split(this.Wordlist.space),t="";for(let i=0;i<e.length;i++){let r=this.Wordlist.value.indexOf(e[i]);if(r<0)return!1;t+=("00000000000"+r.toString(2)).slice(-11)}if(t.length%11!=0)throw Error("internal error - entropy not an even multiple of 11 bits - "+t.length.toString());let i=t.length/33,r=t.slice(-i),n=t.slice(0,t.length-i),a=[];for(let e=0;e<n.length/8;e++)a.push(parseInt(t.slice(8*e,(e+1)*8),2));let s=ea(a.slice(0,n.length/8))[0].toString(2);return(s=("00000000"+s).slice(-8).slice(0,i))===r}mnemonic2Seed(e=""){let t=this.mnemonic;if(!this.check())throw Error("Mnemonic does not pass the check - was the mnemonic typed incorrectly? Are there extra spaces?");if("string"!=typeof e)throw Error("passphrase must be a string or undefined");t=t.normalize("NFKD"),e=e.normalize("NFKD");let i=ti(t,"utf8"),r=[...ti("mnemonic","utf8"),...ti(e,"utf8")];return this.seed=eQ(i,r,2048,64,"sha512"),this}isValid(e=""){let t;try{this.mnemonic2Seed(e),t=!0}catch{t=!1}return t}static isValid(e,t=""){return new rm(e).isValid(t)}}function ry(e){let t,i,r,n;0===this._tables[0][0][0]&&this._precompute();let a=this._tables[0][4],s=this._tables[1],o=e.length,c=1;if(4!==o&&6!==o&&8!==o)throw Error("invalid aes key size");for(this._key=[i=e.slice(0),r=[]],n=o;n<4*o+28;n++)t=i[n-1],(n%o==0||8===o&&n%o==4)&&(t=a[t>>>24]<<24^a[t>>16&255]<<16^a[t>>8&255]<<8^a[255&t],n%o==0&&(t=t<<8^t>>>24^c<<24,c=c<<1^(c>>7)*283)),i[n]=i[n-o]^t;for(let e=0;n>0;e++,n--)t=i[(3&e)!=0?n:n-4],n<=4||e<4?r[e]=t:r[e]=s[0][a[t>>>24]]^s[1][a[t>>16&255]]^s[2][a[t>>8&255]]^s[3][a[255&t]]}ry.prototype={encrypt:function(e){return this._crypt(e,0)},decrypt:function(e){return this._crypt(e,1)},_tables:[[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)]],_precompute:function(){let e,t,i,r,n,a,s,o,c=this._tables[0],l=this._tables[1],h=c[4],d=l[4],u=new Uint8Array(256),f=new Uint8Array(256);for(e=0;e<256;e++)f[(u[e]=e<<1^(e>>7)*283)^e]=e;for(t=i=0;0===h[t];t^=0!==r?r:1,i=0!==f[i]?f[i]:1)for(e=0,a=(a=i^i<<1^i<<2^i<<3^i<<4)>>8^255&a^99,h[t]=a,d[a]=t,o=0x1010101*u[n=u[r=u[t]]]^65537*n^257*r^0x1010100*t,s=257*u[a]^0x1010100*a;e<4;e++)c[e][t]=s=s<<24^s>>>8,l[e][a]=o=o<<24^o>>>8},_crypt:function(e,t){let i,r,n,a;if(4!==e.length)throw Error("invalid aes block size");let s=this._key[t],o=e[0]^s[0],c=e[1===t?3:1]^s[1],l=e[2]^s[2],h=e[1===t?1:3]^s[3],d=s.length/4-2,u=4,f=new Uint32Array(4),p=this._tables[t],g=p[0],m=p[1],y=p[2],b=p[3],w=p[4];for(a=0;a<d;a++)i=g[o>>>24]^m[c>>16&255]^y[l>>8&255]^b[255&h]^s[u],r=g[c>>>24]^m[l>>16&255]^y[h>>8&255]^b[255&o]^s[u+1],n=g[l>>>24]^m[h>>16&255]^y[o>>8&255]^b[255&c]^s[u+2],h=g[h>>>24]^m[o>>16&255]^y[c>>8&255]^b[255&l]^s[u+3],u+=4,o=i,c=r,l=n;for(a=0;a<4;a++)f[1===t?3&-a:a]=w[o>>>24]<<24^w[c>>16&255]<<16^w[l>>8&255]<<8^w[255&h]^s[u++],i=o,o=c,c=l,l=h,h=i;return f}};class rb{static encrypt(e,t){let i=rb.buf2Words(t),r=rb.buf2Words(e),n=new ry(i).encrypt(r);return rb.words2Buf(n)}static decrypt(e,t){let i=rb.buf2Words(e),r=new ry(rb.buf2Words(t)).decrypt(i);return rb.words2Buf(r)}static buf2Words(e){if(e.length%4!=0)throw Error("buf length must be a multiple of 4");let t=[];for(let i=0;i<e.length/4;i++){let r=0x1000000*e[4*i]+(e[4*i+1]<<16|e[4*i+2]<<8|e[4*i+3]);t.push(r)}return t}static words2Buf(e){let t=Array(4*e.length);for(let i=0;i<e.length;i++){let r=e[i];t[4*i]=r>>>24&255,t[4*i+1]=r>>>16&255,t[4*i+2]=r>>>8&255,t[4*i+3]=255&r}return t}}class rw{static buf2BlocksBuf(e,t){let i=t/8,r=[];for(let n=0;n<=e.length/i;n++){let a=e.slice(n*i,n*i+i);a.length<t&&(a=rw.pkcs7Pad(a,t)),r.push(a)}return r}static blockBufs2Buf(e){let t=e[e.length-1];return t=rw.pkcs7Unpad(t),e[e.length-1]=t,e.flat()}static encrypt(e,t,i,r){let n=8*t.length,a=rw.buf2BlocksBuf(e,n);return rw.encryptBlocks(a,t,i,r).flat()}static decrypt(e,t,i,r){let n=t.length,a=[];for(let t=0;t<e.length/n;t++)a.push(e.slice(t*n,t*n+n));let s=rw.decryptBlocks(a,t,i,r);return rw.blockBufs2Buf(s)}static encryptBlock(e,t,i,r){let n=rw.xorBufs(e,t);return i.encrypt(n,r)}static decryptBlock(e,t,i,r){let n=i.decrypt(e,r);return rw.xorBufs(n,t)}static encryptBlocks(e,t,i,r){let n=[];for(let a=0;a<e.length;a++){let s=e[a],o=rw.encryptBlock(s,t,i,r);n.push(o),t=o}return n}static decryptBlocks(e,t,i,r){let n=[];for(let a=0;a<e.length;a++){let s=e[a],o=rw.decryptBlock(s,t,i,r);n.push(o),t=s}return n}static pkcs7Pad(e,t){let i=t/8-e.length,r=Array(i);return r.fill(i),[...e,...r]}static pkcs7Unpad(e){let t=e[e.length-1],i=e.slice(e.length-t,e.length),r=Array(t);if(r.fill(t),te(i)!==te(r))throw Error("invalid padding");return e.slice(0,e.length-t)}static xorBufs(e,t){if(e.length!==t.length)throw Error("bufs must have the same length");let i=Array(e.length);for(let r=0;r<e.length;r++)i[r]=e[r]^t[r];return i}}class rv{static encrypt(e,t,i,r=!0){i=i??t0(16);let n=rw.encrypt(e,i,rb,t);return r?[...i,...n]:[...n]}static decrypt(e,t,i){if(null!=i)return rw.decrypt(e,i,rb,t);{i=e.slice(0,16);let r=e.slice(16);return rw.decrypt(r,i,rb,t)}}}class rI{static ivkEkM(e,t){let i=t.mul(e),r=es(new tJ(i.x,i.y).encode(!0));return{iv:r.slice(0,16),kE:r.slice(16,32),kM:r.slice(32,64)}}static electrumEncrypt(e,t,i,r=!1){let n,a=null;null==i&&(i=t3.fromRandom()),r||(a=i.toPublicKey().encode(!0));let{iv:s,kE:o,kM:c}=rI.ivkEkM(i,t),l=rv.encrypt(e,o,s,!1),h=ti("BIE1","utf8"),d=el(c,n=null!=a&&a.length>0?[...h,...a,...l]:[...h,...l]);return[...n,...d]}static electrumDecrypt(e,t,i){if("BIE1"!==to(e.slice(0,4),"utf8"))throw Error("Invalid Magic");let r=4,n=null;if(e.length-r-32>=33){let t=e[r];2===t||3===t?(n=e.slice(r,r+33),r+=33):4===t&&(n=e.slice(r,r+65),r+=65)}if(null!==n)null==i&&(i=tJ.fromString(te(n)));else if(null==i)throw Error("Sender public key is required");let{iv:a,kE:s,kM:o}=rI.ivkEkM(t,i),c=e.slice(r,e.length-32),l=e.slice(e.length-32,e.length),h=el(o,e.slice(0,e.length-32));if(te(l)!==te(h))throw Error("Invalid checksum");return rv.decrypt(c,s,a)}static bitcoreEncrypt(e,t,i,r){null==i&&(i=t3.fromRandom()),null==r&&(r=t0(16));let n=i,a=i.toPublicKey().encode(!0),s=es(t.mul(n).getX().toArray("be",32)),o=s.slice(0,32),c=s.slice(32,64),l=rv.encrypt(e,o,r),h=el(c,[...l]);return[...a,...l,...h]}static bitcoreDecrypt(e,t){let i=tJ.fromString(te(e.slice(0,33))).mul(t);if(i.eq(new tF(0,0)))throw Error("P equals 0");let r=es(i.getX().toArray("be",32)),n=r.slice(0,32),a=r.slice(32,64),s=e.slice(33,e.length-32),o=e.slice(e.length-32,e.length),c=el(a,s);if(te(o)!==te(c))throw Error("Invalid checksum");return[...rv.decrypt(s,n)]}}function rk(e,t){let i=new i3(0,[],[],0);return i.outputs=Array(e.vout+1).fill(null),i.outputs[e.vout]={satoshis:e.satoshis,lockingScript:iT.fromHex(e.script)},{sourceTransaction:i,sourceTXID:e.txid,sourceOutputIndex:e.vout,unlockingScriptTemplate:t,sequence:0xffffffff}}class rS{static generate(e,t){let i=this.withDefaultOptions(t);return rE(e,this.getCounter(i.timestamp,i.period),i)}static validate(e,t,i){let r=this.withDefaultValidateOptions(i);if((t=t.trim()).length!==r.digits)return!1;let n=this.getCounter(r.timestamp,r.period),a=[n];for(let e=1;e<=r.skew;e++)a.push(n+e),a.push(n-e);for(let i of a){let n=rE(e,i,r);if(tv(ti(t,"utf8"),ti(n,"utf8")))return!0}return!1}static getCounter(e,t){return Math.floor(Math.floor(e/1e3)/t)}static withDefaultOptions(e){return{digits:2,algorithm:"SHA-1",period:30,timestamp:Date.now(),...e}}static withDefaultValidateOptions(e){return{skew:1,...this.withDefaultOptions(e)}}}function rE(e,t,i){let r=(function(e,t,i){switch(i){case"SHA-1":return new et(e).update(t);case"SHA-256":return new ee(e).update(t);case"SHA-512":return new ei(e).update(t);default:throw Error("unsupported HMAC algorithm")}})(e,new P(t).toArray("be",8),i.algorithm).digest(),n=15&r[r.length-1];return(0x7fffffff&new P(r.slice(n,n+4)).toNumber()).toString().slice(-i.digits)}(s=h||(h={}))[s.Silent=0]="Silent",s[s.App=1]="App",s[s.Counterparty=2]="Counterparty";class rx{cacheSharedSecret;retrieveCachedSharedSecret;rootKey;identityKey;anyone;constructor(e,t,i){this.cacheSharedSecret=t,this.retrieveCachedSharedSecret=i,this.anyone=new t3(1).toPublicKey(),"anyone"===e?this.rootKey=new t3(1):this.rootKey=e,this.identityKey=this.rootKey.toPublicKey().toString()}derivePublicKey(e,t,i,r=!1){return(i=this.normalizeCounterparty(i),r)?this.rootKey.deriveChild(i,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret).toPublicKey():i.deriveChild(this.rootKey,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}derivePrivateKey(e,t,i){return i=this.normalizeCounterparty(i),this.rootKey.deriveChild(i,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}deriveSymmetricKey(e,t,i){i="anyone"===i?this.anyone:this.normalizeCounterparty(i);let r=this.derivePublicKey(e,t,i),n=this.derivePrivateKey(e,t,i);return new ip(n.deriveSharedSecret(r)?.x?.toArray()??[])}revealCounterpartySecret(e){if("self"===e)throw Error("Counterparty secrets cannot be revealed for counterparty=self.");e=this.normalizeCounterparty(e);let t=this.rootKey.toPublicKey();if(this.rootKey.deriveChild(t,"test").toHex()===this.rootKey.deriveChild(e,"test").toHex())throw Error("Counterparty secrets cannot be revealed for counterparty=self.");return this.rootKey.deriveSharedSecret(e).encode(!0)}revealSpecificSecret(e,t,i){e=this.normalizeCounterparty(e);let r=this.rootKey.deriveSharedSecret(e),n=ti(this.computeInvoiceNumber(t,i),"utf8");return el(r.encode(!0),n)}normalizeCounterparty(e){if(null==e)throw Error("counterparty must be self, anyone or a public key!");return"self"===e?this.rootKey.toPublicKey():"anyone"===e?new t3(1).toPublicKey():"string"==typeof e?tJ.fromString(e):e}computeInvoiceNumber(e,t){let i=e[0];if(!Number.isInteger(i)||i<0||i>2)throw Error("Protocol security level must be 0, 1, or 2");let r=e[1].toLowerCase().trim();if(t.length>800)throw Error("Key IDs must be 800 characters or less");if(t.length<1)throw Error("Key IDs must be 1 character or more");if(r.length>400)if(r.startsWith("specific linkage revelation ")){if(r.length>430)throw Error("Specific linkage revelation protocol names must be 430 characters or less")}else throw Error("Protocol names must be 400 characters or less");if(r.length<5)throw Error("Protocol names must be 5 characters or more");if(r.includes(" "))throw Error('Protocol names cannot contain multiple consecutive spaces (" ")');if(!/^[a-z0-9 ]+$/g.test(r))throw Error("Protocol names can only contain letters, numbers and spaces");if(r.endsWith(" protocol"))throw Error('No need to end your protocol name with " protocol"');return`${i}-${r}-${t}`}}class rP{keyDeriver;cache;maxCacheSize;rootKey;identityKey;constructor(e,t){"anyone"===e?this.rootKey=new t3(1):this.rootKey=e,this.keyDeriver=new rx(this.rootKey,(e,t,i)=>{this.cacheSet(`${e.toString()}-${t.toString()}`,i)},(e,t)=>this.cacheGet(`${e.toString()}-${t.toString()}`)),this.identityKey=this.rootKey.toPublicKey().toString(),this.cache=new Map;const i=t?.maxCacheSize;this.maxCacheSize=null!=i&&!isNaN(i)&&i>0?i:1e3}derivePublicKey(e,t,i,r=!1){let n=this.generateCacheKey("derivePublicKey",e,t,i,r);if(this.cache.has(n)){let e=this.cacheGet(n);if(void 0===e)throw Error("Cached value is undefined");return e}{let a=this.keyDeriver.derivePublicKey(e,t,i,r);return this.cacheSet(n,a),a}}derivePrivateKey(e,t,i){let r=this.generateCacheKey("derivePrivateKey",e,t,i);if(this.cache.has(r)){let e=this.cacheGet(r);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.derivePrivateKey(e,t,i);return this.cacheSet(r,n),n}}deriveSymmetricKey(e,t,i){let r=this.generateCacheKey("deriveSymmetricKey",e,t,i);if(this.cache.has(r)){let e=this.cacheGet(r);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.deriveSymmetricKey(e,t,i);return this.cacheSet(r,n),n}}revealCounterpartySecret(e){let t=this.generateCacheKey("revealCounterpartySecret",e);if(this.cache.has(t)){let e=this.cacheGet(t);if(void 0===e)throw Error("Cached value is undefined");return e}{let i=this.keyDeriver.revealCounterpartySecret(e);return this.cacheSet(t,i),i}}revealSpecificSecret(e,t,i){let r=this.generateCacheKey("revealSpecificSecret",e,t,i);if(this.cache.has(r)){let e=this.cacheGet(r);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.revealSpecificSecret(e,t,i);return this.cacheSet(r,n),n}}generateCacheKey(e,...t){let i=t.map(e=>this.serializeArgument(e)).join("|");return`${e}|${i}`}serializeArgument(e){return e instanceof tJ||e instanceof t3?e.toString():Array.isArray(e)?e.map(e=>this.serializeArgument(e)).join(","):"object"==typeof e&&null!==e?JSON.stringify(e):String(e)}cacheGet(e){let t=this.cache.get(e);return this.cache.delete(e),void 0!==t&&this.cache.set(e,t),t}cacheSet(e,t){if(this.cache.size>=this.maxCacheSize){let e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(e,t)}}class rA{keyDeriver;constructor(e){"string"!=typeof e.identityKey&&(e=new rP(e)),this.keyDeriver=e}async getPublicKey(e){if(e.identityKey){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==e.protocolID||null==e.keyID||""===e.keyID)throw Error("protocolID and keyID are required if identityKey is false or undefined.");return{publicKey:(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf).toString()}}async revealCounterpartyKeyLinkage(e){let{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let i=this.keyDeriver.revealCounterpartySecret(e.counterparty),r=new iI().generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),tJ.fromString(e.counterparty),tF.fromDER(i)),n=[...r.R.encode(!0),...r.SPrime.encode(!0),...r.z.toArray()],a=new Date().toISOString(),{ciphertext:s}=await this.encrypt({plaintext:i,protocolID:[2,"counterparty linkage revelation"],keyID:a,counterparty:e.verifier}),{ciphertext:o}=await this.encrypt({plaintext:n,protocolID:[2,"counterparty linkage revelation"],keyID:a,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,revelationTime:a,encryptedLinkage:s,encryptedLinkageProof:o}}async revealSpecificKeyLinkage(e){let{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let i=this.keyDeriver.revealSpecificSecret(e.counterparty,e.protocolID,e.keyID),{ciphertext:r}=await this.encrypt({plaintext:i,protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier}),{ciphertext:n}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,protocolID:e.protocolID,keyID:e.keyID,encryptedLinkage:r,encryptedLinkageProof:n,proofType:0}}async encrypt(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{ciphertext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").encrypt(e.plaintext)}}async decrypt(e,t){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{plaintext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").decrypt(e.ciphertext)}}async createHmac(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{hmac:el(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data)}}async verifyHmac(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let t=el(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data),i=e.hmac,r=tv(ti(t),ti(i));if(!r){let e=Error("HMAC is not valid");throw e.code="ERR_INVALID_HMAC",e}return{valid:r}}async createSignature(e){if(null==e.hashToDirectlySign&&null==e.data)throw Error("args.data or args.hashToDirectlySign must be valid");let t=e.hashToDirectlySign??ea(e.data??[]),i=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePrivateKey(e.protocolID,e.keyID,e.counterparty??"anyone");return{signature:tG(new P(t),i,!0).toDER()}}async verifySignature(e){if(null==e.hashToDirectlyVerify&&null==e.data)throw Error("args.data or args.hashToDirectlyVerify must be valid");let t=e.hashToDirectlyVerify??ea(e.data??[]),i=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf),r=tY(new P(t),tK.fromDER(e.signature),i);if(!r){let e=Error("Signature is not valid");throw e.code="ERR_INVALID_SIGNATURE",e}return{valid:r}}}let rN=rA;class rO{CWI;constructor(){if("object"!=typeof window)throw Error("The window.CWI substrate requires a global window object.");if("object"!=typeof window.CWI)throw 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 rT extends Error{code;isError=!0;constructor(e,t=1,i){super(e),this.code=t,this.name=this.constructor.name,null!=i&&""!==i?this.stack=i:Error.captureStackTrace(this,this.constructor)}static unknownToJson(e){let t;return!0===e.isError&&String(e.name).startsWith("WERR_")?"WERR_REVIEW_ACTIONS"===(t={name:e.name,message:e.message,isError:!0}).name?(t.reviewActionResults=e.reviewActionResults,t.sendWithResults=e.sendWithResults,t.txid=e.txid,t.tx=e.tx,t.noSendChange=e.noSendChange,t.code=5):"WERR_INVALID_PARAMETER"===t.name?(t.parameter=e.parameter,t.code=6):"WERR_INSUFFICIENT_FUNDS"===t.name&&(t.totalSatoshisNeeded=e.totalSatoshisNeeded,t.moreSatoshisNeeded=e.moreSatoshisNeeded,t.code=7):t=e instanceof Error?{name:e.constructor.name,message:e.message,isError:!0}:{name:"WERR_UNKNOWN",message:String(e),isError:!0},JSON.stringify(t)}}(o=d||(d={}))[o.unknownError=1]="unknownError",o[o.unsupportedAction=2]="unsupportedAction",o[o.invalidHmac=3]="invalidHmac",o[o.invalidSignature=4]="invalidSignature",o[o.reviewActions=5]="reviewActions",o[o.invalidParameter=6]="invalidParameter",o[o.insufficientFunds=7]="insufficientFunds";let r_=rT;class rR{domain;constructor(e="*"){if("object"!=typeof window)throw Error("The XDM substrate requires a global window object.");if("function"!=typeof window.postMessage)throw Error("The window object does not seem to support postMessage calls.");this.domain=e}async invoke(e,t){return await new Promise((i,r)=>{let n=tc(t0(12)),a=e=>{"CWI"===e.data.type&&e.isTrusted&&e.data.id===n&&!0!==e.data.isInvocation&&("function"==typeof window.removeEventListener&&window.removeEventListener("message",a),"error"===e.data.status?r(new rT(e.data.description,e.data.code)):i(e.data.result))};window.addEventListener("message",a),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 rC{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(e,t,i,r,n,a,s){this.type=e,this.serialNumber=t,this.subject=i,this.certifier=r,this.revocationOutpoint=n,this.fields=a,this.signature=s}toBinary(e=!0){let t=new tp,i=ti(this.type,"base64");t.write(i);let r=ti(this.serialNumber,"base64");t.write(r);let n=ti(this.subject,"hex");t.write(n);let a=ti(this.certifier,"hex");t.write(a);let[s,o]=this.revocationOutpoint.split("."),c=ti(s,"hex");t.write(c),t.writeVarIntNum(Number(o));let l=Object.keys(this.fields).sort();for(let e of(t.writeVarIntNum(l.length),l)){let i=this.fields[e],r=ti(e,"utf8");t.writeVarIntNum(r.length),t.write(r);let n=ti(i,"utf8");t.writeVarIntNum(n.length),t.write(n)}if(e&&(this.signature??"").length>0){let e=ti(this.signature,"hex");t.write(e)}return t.toArray()}static fromBinary(e){let t,i=new tg(e),r=tc(i.read(32)),n=tc(i.read(32)),a=te(i.read(33)),s=te(i.read(33)),o=te(i.read(32)),c=i.readVarIntNum(),l=`${o}.${c}`,h=i.readVarIntNum(),d={};for(let e=0;e<h;e++){let e=i.readVarIntNum(),t=ts(i.read(e)),r=i.readVarIntNum(),n=ts(i.read(r));d[t]=n}if(!i.eof()){let e=i.read();t=tK.fromDER(e).toString("hex")}return new rC(r,n,a,s,l,d,t)}async verify(){let e=new rN("anyone"),t=this.toBinary(!1),i=this.signature??"",{valid:r}=await e.verifySignature({signature:ti(i,"hex"),data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`,counterparty:this.certifier});return r}async sign(e){if(null!=this.signature&&this.signature.length>0)throw Error(`Certificate has already been signed! Signature present: ${this.signature}`);this.certifier=(await e.getPublicKey({identityKey:!0})).publicKey;let t=this.toBinary(!1),{signature:i}=await e.createSignature({data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`});this.signature=te(i)}static getCertificateFieldEncryptionDetails(e,t){return{protocolID:[2,"certificate field encryption"],keyID:t?`${t} ${e}`:e}}static fromObject(e){return new rC(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature)}}(c=u||(u={}))[c.createAction=1]="createAction",c[c.signAction=2]="signAction",c[c.abortAction=3]="abortAction",c[c.listActions=4]="listActions",c[c.internalizeAction=5]="internalizeAction",c[c.listOutputs=6]="listOutputs",c[c.relinquishOutput=7]="relinquishOutput",c[c.getPublicKey=8]="getPublicKey",c[c.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",c[c.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",c[c.encrypt=11]="encrypt",c[c.decrypt=12]="decrypt",c[c.createHmac=13]="createHmac",c[c.verifyHmac=14]="verifyHmac",c[c.createSignature=15]="createSignature",c[c.verifySignature=16]="verifySignature",c[c.acquireCertificate=17]="acquireCertificate",c[c.listCertificates=18]="listCertificates",c[c.proveCertificate=19]="proveCertificate",c[c.relinquishCertificate=20]="relinquishCertificate",c[c.discoverByIdentityKey=21]="discoverByIdentityKey",c[c.discoverByAttributes=22]="discoverByAttributes",c[c.isAuthenticated=23]="isAuthenticated",c[c.waitForAuthentication=24]="waitForAuthentication",c[c.getHeight=25]="getHeight",c[c.getHeaderForHeight=26]="getHeaderForHeight",c[c.getNetwork=27]="getNetwork",c[c.getVersion=28]="getVersion";let rB=u;class rU{wire;constructor(e){this.wire=e}async transmit(e,t="",i=[]){let r=new tp;r.writeUInt8(rB[e]);let n=ti(t,"utf8");r.writeUInt8(n.length),r.write(n),i.length>0&&r.write(i);let a=r.toArray(),s=new tg(await this.wire.transmitToWallet(a)),o=s.readUInt8();if(0===o)return s.read();{let e=s.readVarIntNum(),t=ts(s.read(e)),i=s.readVarIntNum();throw new rT(t,o,ts(s.read(i)))}}async createAction(e,t){let i=new tp,r=ti(e.description,"utf8");if(i.writeVarIntNum(r.length),i.write(r),null!=e.inputBEEF?(i.writeVarIntNum(e.inputBEEF.length),i.write(e.inputBEEF)):i.writeVarIntNum(-1),null!=e.inputs)for(let t of(i.writeVarIntNum(e.inputs.length),e.inputs)){if(i.write(this.encodeOutpoint(t.outpoint)),null!=t.unlockingScript&&""!==t.unlockingScript){let e=ti(t.unlockingScript,"hex");i.writeVarIntNum(e.length),i.write(e)}else i.writeVarIntNum(-1),i.writeVarIntNum(t.unlockingScriptLength??0);let e=ti(t.inputDescription,"utf8");i.writeVarIntNum(e.length),i.write(e),"number"==typeof t.sequenceNumber?i.writeVarIntNum(t.sequenceNumber):i.writeVarIntNum(-1)}else i.writeVarIntNum(-1);if(null!=e.outputs)for(let t of(i.writeVarIntNum(e.outputs.length),e.outputs)){let e=ti(t.lockingScript,"hex");i.writeVarIntNum(e.length),i.write(e),i.writeVarIntNum(t.satoshis);let r=ti(t.outputDescription,"utf8");if(i.writeVarIntNum(r.length),i.write(r),null!=t.basket&&""!==t.basket){let e=ti(t.basket,"utf8");i.writeVarIntNum(e.length),i.write(e)}else i.writeVarIntNum(-1);if(null!=t.customInstructions&&""!==t.customInstructions){let e=ti(t.customInstructions,"utf8");i.writeVarIntNum(e.length),i.write(e)}else i.writeVarIntNum(-1);if(null!=t.tags)for(let e of(i.writeVarIntNum(t.tags.length),t.tags)){let t=ti(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(-1)}else i.writeVarIntNum(-1);if("number"==typeof e.lockTime?i.writeVarIntNum(e.lockTime):i.writeVarIntNum(-1),"number"==typeof e.version?i.writeVarIntNum(e.version):i.writeVarIntNum(-1),null!=e.labels)for(let t of(i.writeVarIntNum(e.labels.length),e.labels)){let e=ti(t,"utf8");i.writeVarIntNum(e.length),i.write(e)}else i.writeVarIntNum(-1);if(null!=e.options){if(i.writeInt8(1),"boolean"==typeof e.options.signAndProcess?i.writeInt8(+!!e.options.signAndProcess):i.writeInt8(-1),"boolean"==typeof e.options.acceptDelayedBroadcast?i.writeInt8(+!!e.options.acceptDelayedBroadcast):i.writeInt8(-1),"known"===e.options.trustSelf?i.writeInt8(1):i.writeInt8(-1),null!=e.options.knownTxids)for(let t of(i.writeVarIntNum(e.options.knownTxids.length),e.options.knownTxids)){let e=ti(t,"hex");i.write(e)}else i.writeVarIntNum(-1);if("boolean"==typeof e.options.returnTXIDOnly?i.writeInt8(+!!e.options.returnTXIDOnly):i.writeInt8(-1),"boolean"==typeof e.options.noSend?i.writeInt8(+!!e.options.noSend):i.writeInt8(-1),null!=e.options.noSendChange)for(let t of(i.writeVarIntNum(e.options.noSendChange.length),e.options.noSendChange))i.write(this.encodeOutpoint(t));else i.writeVarIntNum(-1);if(null!=e.options.sendWith)for(let t of(i.writeVarIntNum(e.options.sendWith.length),e.options.sendWith)){let e=ti(t,"hex");i.write(e)}else i.writeVarIntNum(-1);"boolean"==typeof e.options.randomizeOutputs?i.writeInt8(+!!e.options.randomizeOutputs):i.writeInt8(-1)}else i.writeInt8(0);let n=new tg(await this.transmit("createAction",t,i.toArray())),a={};if(1===n.readInt8()&&(a.txid=te(n.read(32))),1===n.readInt8()){let e=n.readVarIntNum();a.tx=n.read(e)}let s=n.readVarIntNum();if(s>=0){a.noSendChange=[];for(let e=0;e<s;e++){let e=this.readOutpoint(n);a.noSendChange.push(e)}}let o=n.readVarIntNum();if(o>=0){a.sendWithResults=[];for(let e=0;e<o;e++){let e=te(n.read(32)),t=n.readInt8(),i="unproven";1===t?i="unproven":2===t?i="sending":3===t&&(i="failed"),a.sendWithResults.push({txid:e,status:i})}}if(1===n.readInt8()){let e=n.readVarIntNum(),t=n.read(e),i=n.readVarIntNum();a.signableTransaction={tx:t,reference:tc(n.read(i))}}return a}async signAction(e,t){let i=new tp,r=Object.keys(e.spends);for(let t of(i.writeVarIntNum(r.length),r)){i.writeVarIntNum(Number(t));let r=e.spends[Number(t)],n=ti(r.unlockingScript,"hex");i.writeVarIntNum(n.length),i.write(n),"number"==typeof r.sequenceNumber?i.writeVarIntNum(r.sequenceNumber):i.writeVarIntNum(-1)}let n=ti(e.reference,"base64");if(i.writeVarIntNum(n.length),i.write(n),null!=e.options)if(i.writeInt8(1),"boolean"==typeof e.options.acceptDelayedBroadcast?i.writeInt8(+!!e.options.acceptDelayedBroadcast):i.writeInt8(-1),"boolean"==typeof e.options.returnTXIDOnly?i.writeInt8(+!!e.options.returnTXIDOnly):i.writeInt8(-1),"boolean"==typeof e.options.noSend?i.writeInt8(+!!e.options.noSend):i.writeInt8(-1),null!=e.options.sendWith)for(let t of(i.writeVarIntNum(e.options.sendWith.length),e.options.sendWith)){let e=ti(t,"hex");i.write(e)}else i.writeVarIntNum(-1);else i.writeInt8(0);let a=new tg(await this.transmit("signAction",t,i.toArray())),s={};if(1===a.readInt8()&&(s.txid=te(a.read(32))),1===a.readInt8()){let e=a.readVarIntNum();s.tx=a.read(e)}let o=a.readVarIntNum();if(o>=0){s.sendWithResults=[];for(let e=0;e<o;e++){let e=te(a.read(32)),t=a.readInt8(),i="unproven";1===t?i="unproven":2===t?i="sending":3===t&&(i="failed"),s.sendWithResults.push({txid:e,status:i})}}return s}async abortAction(e,t){return await this.transmit("abortAction",t,ti(e.reference,"base64")),{aborted:!0}}async listActions(e,t){let i=new tp;for(let t of(i.writeVarIntNum(e.labels.length),e.labels)){let e=ti(t,"utf8");i.writeVarIntNum(e.length),i.write(e)}for(let t of("any"===e.labelQueryMode?i.writeInt8(1):"all"===e.labelQueryMode?i.writeInt8(2):i.writeInt8(-1),[e.includeLabels,e.includeInputs,e.includeInputSourceLockingScripts,e.includeInputUnlockingScripts,e.includeOutputs,e.includeOutputLockingScripts]))"boolean"==typeof t?i.writeInt8(+!!t):i.writeInt8(-1);"number"==typeof e.limit?i.writeVarIntNum(e.limit):i.writeVarIntNum(-1),"number"==typeof e.offset?i.writeVarIntNum(e.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1);let r=new tg(await this.transmit("listActions",t,i.toArray())),n=r.readVarIntNum(),a=[];for(let e=0;e<n;e++){let e,t=te(r.read(32)),i=r.readVarIntNum(),n=r.readInt8();switch(n){case 1:e="completed";break;case 2:e="unprocessed";break;case 3:e="sending";break;case 4:e="unproven";break;case 5:e="unsigned";break;case 6:e="nosend";break;case 7:e="nonfinal";break;case 8:e="failed";break;default:throw Error(`Unknown status code: ${n}`)}let s=1===r.readInt8(),o=r.readVarIntNum(),c={txid:t,satoshis:i,status:e,isOutgoing:s,description:ts(r.read(o)),version:0,lockTime:0},l=r.readVarIntNum();if(l>=0){c.labels=[];for(let e=0;e<l;e++){let e=r.readVarIntNum(),t=r.read(e);c.labels.push(ts(t))}}c.version=r.readVarIntNum(),c.lockTime=r.readVarIntNum();let h=r.readVarIntNum();if(h>=0){c.inputs=[];for(let e=0;e<h;e++){let e,t,i=this.readOutpoint(r),n=r.readVarIntNum(),a=r.readVarIntNum();a>=0&&(e=te(r.read(a)));let s=r.readVarIntNum();s>=0&&(t=te(r.read(s)));let o=r.readVarIntNum(),l=ts(r.read(o)),h=r.readVarIntNum();c.inputs.push({sourceOutpoint:i,sourceSatoshis:n,sourceLockingScript:e,unlockingScript:t,inputDescription:l,sequenceNumber:h})}}let d=r.readVarIntNum();if(d>=0){c.outputs=[];for(let e=0;e<d;e++){let e,t,i,n=r.readVarIntNum(),a=r.readVarIntNum(),s=r.readVarIntNum();s>=0&&(e=te(r.read(s)));let o=1===r.readInt8(),l=r.readVarIntNum(),h=ts(r.read(l)),d=r.readVarIntNum();d>=0&&(t=ts(r.read(d)));let u=r.readVarIntNum(),f=[];if(u>=0)for(let e=0;e<u;e++){let e=r.readVarIntNum(),t=r.read(e);f.push(ts(t))}let p=r.readVarIntNum();p>=0&&(i=ts(r.read(p))),c.outputs.push({outputIndex:n,satoshis:a,lockingScript:e,spendable:o,outputDescription:h,basket:t,tags:f,customInstructions:i})}}a.push(c)}return{totalActions:n,actions:a}}async internalizeAction(e,t){let i=new tp;for(let t of(i.writeVarIntNum(e.tx.length),i.write(e.tx),i.writeVarIntNum(e.outputs.length),e.outputs))if(i.writeVarIntNum(t.outputIndex),"wallet payment"===t.protocol){if(null==t.paymentRemittance)throw Error("Payment remittance is required for wallet payment");i.writeUInt8(1),i.write(ti(t.paymentRemittance.senderIdentityKey,"hex"));let e=ti(t.paymentRemittance.derivationPrefix,"base64");i.writeVarIntNum(e.length),i.write(e);let r=ti(t.paymentRemittance.derivationSuffix,"base64");i.writeVarIntNum(r.length),i.write(r)}else{i.writeUInt8(2);let e=ti(t.insertionRemittance?.basket,"utf8");if(i.writeVarIntNum(e.length),i.write(e),"string"==typeof t.insertionRemittance?.customInstructions&&""!==t.insertionRemittance.customInstructions){let e=ti(t.insertionRemittance.customInstructions,"utf8");i.writeVarIntNum(e.length),i.write(e)}else i.writeVarIntNum(-1);if("object"==typeof t.insertionRemittance?.tags)for(let e of(i.writeVarIntNum(t.insertionRemittance.tags.length),t.insertionRemittance.tags)){let t=ti(e,"utf8");i.writeVarIntNum(t.length),i.write(t)}else i.writeVarIntNum(0)}if("object"==typeof e.labels)for(let t of(i.writeVarIntNum(e.labels.length),e.labels)){let e=ti(t,"utf8");i.writeVarIntNum(e.length),i.write(e)}else i.writeVarIntNum(-1);let r=ti(e.description);return i.writeVarIntNum(r.length),i.write(r),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),await this.transmit("internalizeAction",t,i.toArray()),{accepted:!0}}async listOutputs(e,t){let i,r=new tp,n=ti(e.basket,"utf8");if(r.writeVarIntNum(n.length),r.write(n),"object"==typeof e.tags)for(let t of(r.writeVarIntNum(e.tags.length),e.tags)){let e=ti(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):r.writeInt8(-1),"boolean"==typeof e.includeTags?r.writeInt8(+!!e.includeTags):r.writeInt8(-1),"boolean"==typeof e.includeLabels?r.writeInt8(+!!e.includeLabels):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);let a=new tg(await this.transmit("listOutputs",t,r.toArray())),s=a.readVarIntNum(),o=a.readVarIntNum();o>=0&&(i=a.read(o));let c=[];for(let e=0;e<s;e++){let e={spendable:!0,outpoint:this.readOutpoint(a),satoshis:a.readVarIntNum()},t=a.readVarIntNum();t>=0&&(e.lockingScript=te(a.read(t)));let i=a.readVarIntNum();i>=0&&(e.customInstructions=ts(a.read(i)));let r=a.readVarIntNum();if(-1!==r){let t=[];for(let e=0;e<r;e++){let e=a.readVarIntNum();t.push(ts(a.read(e)))}e.tags=t}let n=a.readVarIntNum();if(-1!==n){let t=[];for(let e=0;e<n;e++){let e=a.readVarIntNum();t.push(ts(a.read(e)))}e.labels=t}c.push(e)}return{totalOutputs:s,BEEF:i,outputs:c}}async relinquishOutput(e,t){let i=new tp,r=ti(e.basket,"utf8");return i.writeVarIntNum(r.length),i.write(r),i.write(this.encodeOutpoint(e.output)),await this.transmit("relinquishOutput",t,i.toArray()),{relinquished:!0}}encodeOutpoint(e){let t=new tp,[i,r]=e.split(".");return t.write(ti(i,"hex")),t.writeVarIntNum(Number(r)),t.toArray()}readOutpoint(e){let t=te(e.read(32)),i=e.readVarIntNum();return`${t}.${i}`}async getPublicKey(e,t){let i=new tp;return i.writeUInt8(+!!e.identityKey),e.identityKey?i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)):(i.write(this.encodeKeyRelatedParams(e.protocolID??=[h.Silent,"default"],e.keyID??="",e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?i.writeInt8(+!!e.forSelf):i.writeInt8(-1)),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{publicKey:te(await this.transmit("getPublicKey",t,i.toArray()))}}async revealCounterpartyKeyLinkage(e,t){let i=new tp;i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),i.write(ti(e.counterparty,"hex")),i.write(ti(e.verifier,"hex"));let r=new tg(await this.transmit("revealCounterpartyKeyLinkage",t,i.toArray())),n=te(r.read(33)),a=te(r.read(33)),s=te(r.read(33)),o=r.readVarIntNum(),c=ts(r.read(o)),l=r.readVarIntNum(),h=r.read(l),d=r.readVarIntNum();return{prover:n,verifier:a,counterparty:s,revelationTime:c,encryptedLinkage:h,encryptedLinkageProof:r.read(d)}}async revealSpecificKeyLinkage(e,t){let i=new tp;i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.write(ti(e.verifier,"hex"));let r=new tg(await this.transmit("revealSpecificKeyLinkage",t,i.toArray())),n=te(r.read(33)),a=te(r.read(33)),s=te(r.read(33)),o=r.readUInt8(),c=r.readVarIntNum(),l=ts(r.read(c)),h=r.readVarIntNum(),d=ts(r.read(h)),u=r.readVarIntNum(),f=r.read(u),p=r.readVarIntNum();return{prover:n,verifier:a,counterparty:s,protocolID:[o,l],keyID:d,encryptedLinkage:f,encryptedLinkageProof:r.read(p),proofType:r.readUInt8()}}async encrypt(e,t){let i=new tp;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.writeVarIntNum(e.plaintext.length),i.write(e.plaintext),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{ciphertext:await this.transmit("encrypt",t,i.toArray())}}async decrypt(e,t){let i=new tp;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.writeVarIntNum(e.ciphertext.length),i.write(e.ciphertext),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{plaintext:await this.transmit("decrypt",t,i.toArray())}}async createHmac(e,t){let i=new tp;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.writeVarIntNum(e.data.length),i.write(e.data),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{hmac:await this.transmit("createHmac",t,i.toArray())}}async verifyHmac(e,t){let i=new tp;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),i.write(e.hmac),i.writeVarIntNum(e.data.length),i.write(e.data),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),await this.transmit("verifyHmac",t,i.toArray()),{valid:!0}}async createSignature(e,t){let i=new tp;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"object"==typeof e.data?(i.writeUInt8(1),i.writeVarIntNum(e.data.length),i.write(e.data)):(i.writeUInt8(2),i.write(e.hashToDirectlySign??=[])),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{signature:await this.transmit("createSignature",t,i.toArray())}}async verifySignature(e,t){let i=new tp;return i.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?i.writeInt8(+!!e.forSelf):i.writeInt8(-1),i.writeVarIntNum(e.signature.length),i.write(e.signature),"object"==typeof e.data?(i.writeUInt8(1),i.writeVarIntNum(e.data.length),i.write(e.data)):(i.writeUInt8(2),i.write(e.hashToDirectlyVerify??[])),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),await this.transmit("verifySignature",t,i.toArray()),{valid:!0}}encodeKeyRelatedParams(e,t,i,r,n){let a=new tp;a.writeUInt8(e[0]);let s=ti(e[1],"utf8");a.writeVarIntNum(s.length),a.write(s);let o=ti(t,"utf8");return a.writeVarIntNum(o.length),a.write(o),"string"!=typeof i?a.writeUInt8(0):"self"===i?a.writeUInt8(11):"anyone"===i?a.writeUInt8(12):a.write(ti(i,"hex")),a.write(this.encodePrivilegedParams(r,n)),a.toArray()}async acquireCertificate(e,t){let i=new tp;i.write(ti(e.type,"base64")),i.write(ti(e.certifier,"hex"));let r=Object.entries(e.fields);for(let[e,t]of(i.writeVarIntNum(r.length),r)){let r=ti(e,"utf8"),n=ti(t,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(n.length),i.write(n)}if(i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),i.writeUInt8("direct"===e.acquisitionProtocol?1:2),"direct"===e.acquisitionProtocol){i.write(ti(e.serialNumber,"base64")),i.write(this.encodeOutpoint(e.revocationOutpoint??""));let t=ti(e.signature,"hex");i.writeVarIntNum(t.length),i.write(t);let r="certifier"!==e.keyringRevealer?ti(e.keyringRevealer,"hex"):[11];i.write(r);let n=Object.keys(e.keyringForSubject??{});i.writeVarIntNum(n.length);for(let t=0;t<n.length;t++){let r=ti(n[t],"utf8");i.writeVarIntNum(r.length),i.write(r);let a=ti(e.keyringForSubject?.[n[t]],"base64");i.writeVarIntNum(a.length),i.write(a)}}else{let t=ti(e.certifierUrl,"utf8");i.writeVarIntNum(t.length),i.write(t)}let n=await this.transmit("acquireCertificate",t,i.toArray()),a=rC.fromBinary(n);return{...a,signature:a.signature}}encodePrivilegedParams(e,t){let i=new tp;if("boolean"==typeof e?i.writeInt8(+!!e):i.writeInt8(-1),"string"==typeof t){let e=ti(t,"utf8");i.writeInt8(e.length),i.write(e)}else i.writeInt8(-1);return i.toArray()}async listCertificates(e,t){let i=new tp;i.writeVarIntNum(e.certifiers.length);for(let t=0;t<e.certifiers.length;t++)i.write(ti(e.certifiers[t],"hex"));i.writeVarIntNum(e.types.length);for(let t=0;t<e.types.length;t++)i.write(ti(e.types[t],"base64"));"number"==typeof e.limit?i.writeVarIntNum(e.limit):i.writeVarIntNum(-1),"number"==typeof e.offset?i.writeVarIntNum(e.offset):i.writeVarIntNum(-1),i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let r=new tg(await this.transmit("listCertificates",t,i.toArray())),n=r.readVarIntNum(),a=[];for(let e=0;e<n;e++){let e,t=r.readVarIntNum(),i=r.read(t),n=rC.fromBinary(i),s={};if(1===r.readInt8()){let e=r.readVarIntNum();for(let t=0;t<e;t++){let e=r.readVarIntNum(),t=ts(r.read(e)),i=r.readVarIntNum();s[t]=tc(r.read(i))}}let o=r.readVarIntNum();o>0&&(e=ts(r.read(o))),a.push({...n,signature:n.signature,keyring:s,verifier:e})}return{totalCertificates:n,certificates:a}}async proveCertificate(e,t){let i=new tp,r=ti(e.certificate.type,"base64");i.write(r);let n=ti(e.certificate.subject,"hex");i.write(n);let a=ti(e.certificate.serialNumber,"base64");i.write(a);let s=ti(e.certificate.certifier,"hex");i.write(s);let o=this.encodeOutpoint(e.certificate.revocationOutpoint??"");i.write(o);let c=ti(e.certificate.signature,"hex");i.writeVarIntNum(c.length),i.write(c);let l=Object.entries(e.certificate.fields??{});for(let[e,t]of(i.writeVarIntNum(l.length),l)){let r=ti(e,"utf8"),n=ti(t,"utf8");i.writeVarIntNum(r.length),i.write(r),i.writeVarIntNum(n.length),i.write(n)}for(let t of(i.writeVarIntNum(e.fieldsToReveal.length),e.fieldsToReveal)){let e=ti(t,"utf8");i.writeVarIntNum(e.length),i.write(e)}i.write(ti(e.verifier,"hex")),i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let h=new tg(await this.transmit("proveCertificate",t,i.toArray())),d=h.readVarIntNum(),u={};for(let e=0;e<d;e++){let e=h.readVarIntNum(),t=ts(h.read(e)),i=h.readVarIntNum();u[t]=tc(h.read(i))}return{keyringForVerifier:u}}async relinquishCertificate(e,t){let i=new tp,r=ti(e.type,"base64");i.write(r);let n=ti(e.serialNumber,"base64");i.write(n);let a=ti(e.certifier,"hex");return i.write(a),await this.transmit("relinquishCertificate",t,i.toArray()),{relinquished:!0}}parseDiscoveryResult(e){let t=new tg(e),i=t.readVarIntNum(),r=[];for(let e=0;e<i;e++){let e=t.readVarIntNum(),i=t.read(e),n=rC.fromBinary(i),a=t.readVarIntNum(),s=ts(t.read(a)),o=t.readVarIntNum(),c=ts(t.read(o)),l=t.readVarIntNum(),h=ts(t.read(l)),d=t.readUInt8(),u={},f=t.readVarIntNum();for(let e=0;e<f;e++){let e=t.readVarIntNum(),i=ts(t.read(e)),r=t.readVarIntNum();u[i]=t.read(r)}let p={},g=t.readVarIntNum();for(let e=0;e<g;e++){let e=t.readVarIntNum(),i=ts(t.read(e)),r=t.readVarIntNum();p[i]=ts(t.read(r))}r.push({...n,signature:n.signature,certifierInfo:{iconUrl:c,name:s,description:h,trust:d},publiclyRevealedKeyring:u,decryptedFields:p})}return{totalCertificates:i,certificates:r}}async discoverByIdentityKey(e,t){let i=new tp;i.write(ti(e.identityKey,"hex")),"number"==typeof e.limit?i.writeVarIntNum(e.limit):i.writeVarIntNum(-1),"number"==typeof e.offset?i.writeVarIntNum(e.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1);let r=await this.transmit("discoverByIdentityKey",t,i.toArray());return this.parseDiscoveryResult(r)}async discoverByAttributes(e,t){let i=new tp,r=Object.keys(e.attributes);i.writeVarIntNum(r.length);for(let t=0;t<r.length;t++)i.writeVarIntNum(r[t].length),i.write(ti(r[t],"utf8")),i.writeVarIntNum(e.attributes[r[t]].length),i.write(ti(e.attributes[r[t]],"utf8"));"number"==typeof e.limit?i.writeVarIntNum(e.limit):i.writeVarIntNum(-1),"number"==typeof e.offset?i.writeVarIntNum(e.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1);let n=await this.transmit("discoverByAttributes",t,i.toArray());return this.parseDiscoveryResult(n)}async isAuthenticated(e,t){return{authenticated:1===(await this.transmit("isAuthenticated",t))[0]}}async waitForAuthentication(e,t){return await this.transmit("waitForAuthentication",t),{authenticated:!0}}async getHeight(e,t){return{height:new tg(await this.transmit("getHeight",t)).readVarIntNum()}}async getHeaderForHeight(e,t){let i=new tp;return i.writeVarIntNum(e.height),{header:te(await this.transmit("getHeaderForHeight",t,i.toArray()))}}async getNetwork(e,t){return{network:0===(await this.transmit("getNetwork",t))[0]?"mainnet":"testnet"}}async getVersion(e,t){return{version:ts(await this.transmit("getVersion",t))}}}class rV{baseUrl;httpClient;originator;constructor(e,t="http://localhost:3301",i=fetch){this.baseUrl=t,this.httpClient=i,this.originator=e}async transmitToWallet(e){let t,i=new tg(e),r=i.readUInt8(),n=rB[r];if(void 0===n||""===n)throw Error(`Invalid call code: ${r}`);let a=i.readUInt8();a>0&&(t=ts(i.read(a)));let s=i.read(),o=await fetch(`${this.baseUrl}/${n}`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Origin:t??""},body:new Uint8Array(s)});return Array.from(new Uint8Array(await o.arrayBuffer()))}}class rD extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(e,t,i,r,n){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=e,this.sendWithResults=t,this.txid=i,this.tx=r,this.noSendChange=n,this.code=5,this.name=this.constructor.name}}let rL=rD;class rF extends Error{parameter;code;isError=!0;constructor(e,t){super(`The ${e} parameter must be ${t??"valid."}`),this.parameter=e,this.code=6,this.name=this.constructor.name}}let rH=rF,rK=class extends Error{totalSatoshisNeeded;moreSatoshisNeeded;code;isError=!0;constructor(e,t){super(`Insufficient funds in the available inputs to cover the cost of the required outputs and the transaction fee (${t} more satoshis are needed, for a total of ${e}), plus whatever would be required in order to pay the fee to unlock and spend the outputs used to provide the additional satoshis.`),this.totalSatoshisNeeded=e,this.moreSatoshisNeeded=t,this.code=7,this.name=this.constructor.name}};class rM{baseUrl;httpClient;originator;api;constructor(e,t="http://localhost:3321",i=fetch){this.baseUrl=t,this.originator=e,this.httpClient=i;const r="u">typeof window&&"u">typeof document&&window?.origin!=="file://";this.api=async(e,t)=>{let n=!r&&this.originator?function(e,t="http"){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))try{return new URL(e).origin}catch{}try{return new URL(`${t}://${e}`).origin}catch{throw Error(`Invalid originator value: ${e}`)}}(this.originator,"http"):void 0;r||void 0!==n||console.error("Originator is required in Node.js environments");let a=await await i(`${this.baseUrl}/${e}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...n?{Origin:n}:{},...n?{Originator:n}:{}},body:JSON.stringify(t)}),s=await a.json();if(!a.ok){if(400===a.status&&s.isError){let e;switch(s.code){case 5:e=new rD(s.reviewActionResults,s.sendWithResults,s.txid,s.tx,s.noSendChange);break;case 6:(e=new rF(s.parameter)).message=s.message;break;case 7:e=new rK(s.totalSatoshisNeeded,s.moreSatoshisNeeded)}if(e)throw e}throw Error(JSON.stringify({call:e,args:t,message:s.message??`HTTP Client error ${a.status}`}))}return s}}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 rq{domain;constructor(e="*"){if("object"!=typeof window)throw Error("The XDM substrate requires a global window object.");if(!window.hasOwnProperty("ReactNativeWebView"))throw Error("The window object does not have a ReactNativeWebView property.");if("function"!=typeof window.ReactNativeWebView.postMessage)throw Error("The window.ReactNativeWebView property does not seem to support postMessage calls.");this.domain=e}async invoke(e,t){return await new Promise((i,r)=>{let n=tc(t0(12)),a=e=>{let t=JSON.parse(e.data);"CWI"===t.type&&t.id===n&&!0!==t.isInvocation&&("function"==typeof window.removeEventListener&&window.removeEventListener("message",a),"error"===t.status?r(new rT(t.description,t.code)):i(t.result))};window.addEventListener("message",a),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)}}function r$(e){let[t,i]=e.split(".");return{txid:t,vout:Number(i)}}function rz(e){return e??!1}function rW(e,t,i,r){if(void 0!==e)return rJ(e,t,i,r)}function rj(e,t,i){if(void 0===e||!Number.isInteger(e)||e<0||e>21e14)throw new rH(t,"a valid number of satoshis");if(void 0!==i&&e<i)throw new rH(t,`at least ${i} satoshis.`);return e}function rX(e,t,i,r){if(void 0!==e)return rG(e,t,void 0,i,r)}function rG(e,t,i,r,n){if(void 0===e){if(void 0!==i)return i;throw new rH(t,"a valid integer")}if(!Number.isInteger(e))throw new rH(t,"an integer");if(e=Number(e),void 0!==r&&e<r)throw new rH(t,`at least ${r} length.`);if(void 0!==n&&e>n)throw new rH(t,`no more than ${n} length.`);return e}function rY(e,t){return rG(e,t,0,0)}function rJ(e,t,i,r){let n=ti(e,"utf8").length;if(void 0!==i&&n<i)throw new rH(t,`at least ${i} length.`);if(void 0!==r&&n>r)throw new rH(t,`no more than ${r} length.`);return e}function rZ(e){return r1(e,"basket",1,300)}function rQ(e){return r1(e,"label",1,300)}function r0(e){return r1(e,"tag",1,300)}function r1(e,t,i,r){let n=ti(e=e.trim().toLowerCase(),"utf8").length;if(void 0!==i&&n<i)throw new rH(t,`at least ${i} length.`);if(void 0!==r&&n>r)throw new rH(t,`no more than ${r} length.`);return e}function r2(e,t,i,r){if(void 0!==e)return r8(e,t,i,r)}function r8(e,t,i,r){if(0===(e=e.trim()).length)throw new rH(t,"valid base64 string");let n=0;for(let i=0;i<e.length;i++){let r=e.charCodeAt(i);if((!(r>=65)||!(r<=90))&&(!(r>=97)||!(r<=122))&&(!(r>=48)||!(r<=57))&&43!==r&&47!==r){if(61===r){if(i<e.length-2)throw new rH(t,"valid base64 string");n++;continue}throw new rH(t,"valid base64 string")}}if(n>2||n>0&&e.length%4!=0)throw new rH(t,"valid base64 string");let a=e.length%4;if(0!==a&&a!==4-n)throw new rH(t,"valid base64 string");let s=Math.floor(3*(e.length-n)/4);if(void 0!==i&&s<i)throw new rH(t,`at least ${i} bytes`);if(void 0!==r&&s>r)throw new rH(t,`no more than ${r} bytes`);return e}function r3(e,t,i,r){if(void 0!==e)return r6(e,t,i,r)}function r6(e,t,i,r){if((e=e.trim().toLowerCase()).length%2==1)throw new rH(t,`even length, not ${e.length}.`);if(!/^[0-9A-Fa-f]+$/.test(e))throw new rH(t,"hexadecimal string.");if(void 0!==i&&e.length<i)throw new rH(t,`at least ${i} length.`);if(void 0!==r&&e.length>r)throw new rH(t,`no more than ${r} length.`);return e}function r4(e){return(e=e.trim()).length%2!=1&&!!/^[0-9A-Fa-f]+$/.test(e)}function r5(e){if(void 0===e.unlockingScript&&void 0===e.unlockingScriptLength)throw new rH("unlockingScript, unlockingScriptLength","at least one valid value.");let t=r3(e.unlockingScript,"unlockingScript"),i=e.unlockingScriptLength??(null!=t?t.length/2:0);if(t&&i!==t.length/2)throw new rH("unlockingScriptLength","length unlockingScript if both valid.");return{outpoint:r$(e.outpoint),inputDescription:rJ(e.inputDescription,"inputDescription",5,2e3),unlockingScript:t,unlockingScriptLength:i,sequenceNumber:e.sequenceNumber??0xffffffff}}function r7(e){return{lockingScript:r6(e.lockingScript,"lockingScript"),satoshis:rj(e.satoshis,"satoshis"),outputDescription:rJ(e.outputDescription,"outputDescription",5,2e3),basket:function(e){if(void 0!==e)return rZ(e)}(e.basket),customInstructions:e.customInstructions,tags:(e.tags??[]).map(e=>r0(e))}}function r9(e){let t=null!=e?e:{};return{signAndProcess:t.signAndProcess??!0,acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,knownTxids:t.knownTxids??[],returnTXIDOnly:rz(t.returnTXIDOnly),noSend:rz(t.noSend),noSendChange:(t.noSendChange??[]).map(e=>r$(e)),sendWith:t.sendWith??[],randomizeOutputs:t.randomizeOutputs??!0}}function ne(e,t){let i={description:rJ(e.description,"description",5,2e3),inputBEEF:e.inputBEEF,inputs:(e.inputs??[]).map(e=>r5(e)),outputs:(e.outputs??[]).map(e=>r7(e)),lockTime:e.lockTime??0,version:e.version??1,labels:e.labels?.map(e=>rQ(e))??[],options:r9(e.options),logger:t,isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!1,isRemixChange:!1,isSignAction:!1,randomVals:void 0,includeAllSourceTransactions:!1,isTestWerrReviewActions:!1};return i.isTestWerrReviewActions=i.labels.includes(nk),i.isSendWith=i.options.sendWith.length>0,i.isRemixChange=!i.isSendWith&&0===i.inputs.length&&0===i.outputs.length,i.isNewTx=i.isRemixChange||i.inputs.length>0||i.outputs.length>0,i.isSignAction=i.isNewTx&&(!i.options.signAndProcess||i.inputs.some(e=>void 0===e.unlockingScript)),i.isDelayed=i.options.acceptDelayedBroadcast,i.isNoSend=i.options.noSend,i}function nt(e){let t=null!=e?e:{};return{acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,returnTXIDOnly:rz(t.returnTXIDOnly),noSend:rz(t.noSend),sendWith:t.sendWith??[]}}function ni(e){let t={spends:e.spends,reference:e.reference,options:nt(e.options),isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!0,isRemixChange:!1,isTestWerrReviewActions:!1};return t.isSendWith=t.options.sendWith.length>0,t.isDelayed=t.options.acceptDelayedBroadcast,t.isNoSend=t.options.noSend,t}function nr(e){return{reference:r8(e.reference,"reference")}}function nn(e){if(void 0!==e)return{derivationPrefix:r8(e.derivationPrefix,"derivationPrefix"),derivationSuffix:r8(e.derivationSuffix,"derivationSuffix"),senderIdentityKey:r6(e.senderIdentityKey,"senderIdentityKey")}}function na(e){if(void 0!==e)return{basket:rZ(e.basket),customInstructions:rW(e.customInstructions,"customInstructions",0,1e3),tags:(e.tags??[]).map(e=>r0(e))}}function ns(e){if("basket insertion"!==e.protocol&&"wallet payment"!==e.protocol)throw new rH("protocol","'basket insertion' or 'wallet payment'");return{outputIndex:rY(e.outputIndex,"outputIndex"),protocol:e.protocol,paymentRemittance:nn(e.paymentRemittance),insertionRemittance:na(e.insertionRemittance)}}function no(e){if(void 0!==e){for(let t of(rJ(e=e.trim().toLowerCase(),"originator",1,250),e.split(".")))rJ(t,"originator part",1,63);return e}}function nc(e){let t={tx:e.tx,outputs:e.outputs.map(e=>ns(e)),description:rJ(e.description,"description",5,2e3),labels:(null!=e.labels?e.labels:[]).map(e=>rQ(e)),seekPermission:e.seekPermission??!0};try{if(i8.fromBinary(t.tx).txs.length<1)throw new rH("tx","at least one transaction to internalize an output from")}catch{throw new rH("tx","valid with at least one transaction to internalize an output from")}if(t.outputs.length<1)throw new rH("outputs","at least one output to internalize from the transaction");return t}function nl(e,t){if(void 0!==e)return nh(e,t)}function nh(e,t){let i=e.split(".");if(2!==i.length||!Number.isInteger(Number(i[1])))throw new rH(t,"txid as hex string and numeric output index joined with '.'");let r=r6(i[0],`${t} txid`,void 0,64),n=rY(Number(i[1]),`${t} vout`);return`${r}.${n}`}function nd(e){return{basket:rZ(e.basket),output:nh(e.output,"output")}}function nu(e){return{type:r8(e.type,"type"),serialNumber:r8(e.serialNumber,"serialNumber"),certifier:r6(e.certifier,"certifier")}}function nf(e){return{certifiers:e.certifiers.map(e=>r6(e.trim(),"certifiers"))??[],types:e.types.map(e=>r8(e.trim(),"types"))??[],limit:rG(e.limit,"limit",10,1,1e4),offset:rY(e.offset??0,"offset"),privileged:rz(e.privileged),privilegedReason:rW(e.privilegedReason,"privilegedReason",5,50),partial:void 0}}function np(e){for(let t of Object.keys(e))rJ(t,"field name",1,50);return e}function ng(e){if("issuance"!==e.acquisitionProtocol)throw Error("Only acquire certificate via issuance requests allowed here.");if(e.serialNumber)throw new rH("serialNumber",'valid when acquisitionProtocol is "direct"');if(e.signature)throw new rH("signature",'valid when acquisitionProtocol is "direct"');if(e.revocationOutpoint)throw new rH("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(e.keyringRevealer)throw new rH("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null!=e.keyringForSubject)throw new rH("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(!e.certifierUrl)throw new rH("certifierUrl",'valid when acquisitionProtocol is "issuance"');if(e.privileged&&!e.privilegedReason)throw new rH("privilegedReason","valid when 'privileged' is true ");return{type:r8(e.type,"type"),certifier:r6(e.certifier,"certifier"),certifierUrl:e.certifierUrl,fields:np(e.fields),privileged:rz(e.privileged),privilegedReason:rW(e.privilegedReason,"privilegedReason",5,50),subject:""}}function nm(e){var t;if("direct"!==e.acquisitionProtocol)throw Error("Only acquire direct certificate requests allowed here.");if(!e.serialNumber)throw new rH("serialNumber",'valid when acquisitionProtocol is "direct"');if(!e.signature)throw new rH("signature",'valid when acquisitionProtocol is "direct"');if(!e.revocationOutpoint)throw new rH("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(!e.keyringRevealer)throw new rH("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null==e.keyringForSubject)throw new rH("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(e.privileged&&!e.privilegedReason)throw new rH("privilegedReason","valid when 'privileged' is true ");return{type:r8(e.type,"type"),serialNumber:r8(e.serialNumber,"serialNumber"),certifier:r6(e.certifier,"certifier"),revocationOutpoint:nh(e.revocationOutpoint,"revocationOutpoint"),fields:np(e.fields),signature:r6(e.signature,"signature"),keyringRevealer:(t=e.keyringRevealer,"certifier"===t?t:r6(t,"keyringRevealer")),keyringForSubject:function(e,t){for(let i of Object.keys(e))rJ(i,`${t} field name`,1,50),r8(e[i],`${t} field value`);return e}(e.keyringForSubject,"keyringForSubject"),privileged:rz(e.privileged),privilegedReason:rW(e.privilegedReason,"privilegedReason",5,50),subject:""}}function ny(e){if(e.privileged&&!e.privilegedReason)throw new rH("privilegedReason","valid when 'privileged' is true ");return{type:r2(e.certificate.type,"certificate.type"),serialNumber:r2(e.certificate.serialNumber,"certificate.serialNumber"),certifier:r3(e.certificate.certifier,"certificate.certifier"),subject:r3(e.certificate.subject,"certificate.subject"),revocationOutpoint:nl(e.certificate.revocationOutpoint,"certificate.revocationOutpoint"),signature:r3(e.certificate.signature,"certificate.signature"),fieldsToReveal:(e.fieldsToReveal??[]).map(e=>rJ(e,`fieldsToReveal ${e}`,1,50)),verifier:r6(e.verifier,"verifier"),privileged:rz(e.privileged),privilegedReason:rW(e.privilegedReason,"privilegedReason",5,50)}}function nb(e){return{identityKey:r6(e.identityKey,"identityKey",66,66),limit:rG(e.limit,"limit",10,1,1e4),offset:rY(e.offset??0,"offset"),seekPermission:rz(e.seekPermission)}}function nw(e){return{attributes:function(e){for(let t of Object.keys(e))rJ(t,`field name ${t}`,1,50);return e}(e.attributes),limit:rG(e.limit,"limit",10,1,1e4),offset:rY(e.offset??0,"offset"),seekPermission:rz(e.seekPermission)}}function nv(e){let t;if(void 0===e.tagQueryMode||"any"===e.tagQueryMode)t="any";else if("all"===e.tagQueryMode)t="all";else throw new rH("tagQueryMode","undefined, 'any', or 'all'");return{basket:rJ(e.basket,"basket",1,300),tags:(null!=e.tags?e.tags:[]).map(e=>rJ(e,"tag",1,300)),tagQueryMode:t,includeLockingScripts:"locking scripts"===e.include,includeTransactions:"entire transactions"===e.include,includeCustomInstructions:rz(e.includeCustomInstructions),includeTags:rz(e.includeTags),includeLabels:rz(e.includeLabels),limit:rG(e.limit,"limit",10,1,1e4),offset:rG(e.offset,"offset",0,void 0,void 0),seekPermission:e.seekPermission??!0,knownTxids:[]}}function nI(e){let t;if(void 0===e.labelQueryMode||"any"===e.labelQueryMode)t="any";else if("all"===e.labelQueryMode)t="all";else throw new rH("labelQueryMode","undefined, 'any', or 'all'");return{labels:(null!=e.labels?e.labels:[]).map(e=>rQ(e)),labelQueryMode:t,includeLabels:rz(e.includeLabels),includeInputs:rz(e.includeInputs),includeInputSourceLockingScripts:rz(e.includeInputSourceLockingScripts),includeInputUnlockingScripts:rz(e.includeInputUnlockingScripts),includeOutputs:rz(e.includeOutputs),includeOutputLockingScripts:rz(e.includeOutputLockingScripts),limit:rG(e.limit,"limit",10,1,1e4),offset:rG(e.offset,"offset",0,0),seekPermission:e.seekPermission??!0}}let nk="a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a";class nS{substrate;originator;constructor(e="auto",t){"Cicada"===e&&(e=new rU(new rV(t))),"window.CWI"===e&&(e=new rO),"XDM"===e&&(e=new rR),"json-api"===e&&(e=new rM(t)),"react-native"===e&&(e=new rq(t)),"secure-json-api"===e&&(e=new rM(t,"https://localhost:2121")),this.substrate=e,this.originator=t}async connectToSubstrate(){if("object"==typeof this.substrate)return;let e=async(e,t)=>{try{let i,r=e();if(i="number"==typeof t?await Promise.race([r.getVersion({}),new Promise((e,i)=>setTimeout(()=>i(Error("Timed out.")),t))]):await r.getVersion({}),"object"!=typeof i||"string"!=typeof i.version)return{success:!1};return{success:!0,sub:r}}catch{return{success:!1}}},t=[e(()=>new rO),e(()=>new rU(new rV(this.originator))),e(()=>new rM(this.originator,"https://localhost:2121")),e(()=>new rM(this.originator)),e(()=>new rq(this.originator))],i=(await Promise.allSettled(t)).filter(e=>"fulfilled"===e.status&&e.value.success&&void 0!==e.value.sub).map(e=>e.value.sub);if(i.length>0){this.substrate=i[0];return}let r=await e(()=>new rR,200);if(r.success&&void 0!==r.sub)this.substrate=r.sub;else throw Error("No wallet available over any communication substrate. Install a BSV wallet today!")}async createAction(e){return ne(e),await this.connectToSubstrate(),await this.substrate.createAction(e,this.originator)}async signAction(e){return ni(e),await this.connectToSubstrate(),await this.substrate.signAction(e,this.originator)}async abortAction(e){return nr(e),await this.connectToSubstrate(),await this.substrate.abortAction(e,this.originator)}async listActions(e){return nI(e),await this.connectToSubstrate(),await this.substrate.listActions(e,this.originator)}async internalizeAction(e){return nc(e),await this.connectToSubstrate(),await this.substrate.internalizeAction(e,this.originator)}async listOutputs(e){return nv(e),await this.connectToSubstrate(),await this.substrate.listOutputs(e,this.originator)}async relinquishOutput(e){return nd(e),await this.connectToSubstrate(),await this.substrate.relinquishOutput(e,this.originator)}async getPublicKey(e){return await this.connectToSubstrate(),await this.substrate.getPublicKey(e,this.originator)}async revealCounterpartyKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealCounterpartyKeyLinkage(e,this.originator)}async revealSpecificKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealSpecificKeyLinkage(e,this.originator)}async encrypt(e){return await this.connectToSubstrate(),await this.substrate.encrypt(e,this.originator)}async decrypt(e){return await this.connectToSubstrate(),await this.substrate.decrypt(e,this.originator)}async createHmac(e){return await this.connectToSubstrate(),await this.substrate.createHmac(e,this.originator)}async verifyHmac(e){return await this.connectToSubstrate(),await this.substrate.verifyHmac(e,this.originator)}async createSignature(e){return await this.connectToSubstrate(),await this.substrate.createSignature(e,this.originator)}async verifySignature(e){return await this.connectToSubstrate(),await this.substrate.verifySignature(e,this.originator)}async acquireCertificate(e){if("direct"===e.acquisitionProtocol)nm(e);else if("issuance"===e.acquisitionProtocol)ng(e);else throw new rF("acquisitionProtocol",`valid. ${String(e.acquisitionProtocol)} is unrecognized.`);return await this.connectToSubstrate(),await this.substrate.acquireCertificate(e,this.originator)}async listCertificates(e){return nf(e),await this.connectToSubstrate(),await this.substrate.listCertificates(e,this.originator)}async proveCertificate(e){return ny(e),await this.connectToSubstrate(),await this.substrate.proveCertificate(e,this.originator)}async relinquishCertificate(e){return nu(e),await this.connectToSubstrate(),await this.substrate.relinquishCertificate(e,this.originator)}async discoverByIdentityKey(e){return nb(e),await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(e,this.originator)}async discoverByAttributes(e){return nw(e),await this.connectToSubstrate(),await this.substrate.discoverByAttributes(e,this.originator)}async isAuthenticated(e={}){return await this.connectToSubstrate(),await this.substrate.isAuthenticated(e,this.originator)}async waitForAuthentication(e={}){return await this.connectToSubstrate(),await this.substrate.waitForAuthentication(e,this.originator)}async getHeight(e={}){return await this.connectToSubstrate(),await this.substrate.getHeight(e,this.originator)}async getHeaderForHeight(e){return await this.connectToSubstrate(),await this.substrate.getHeaderForHeight(e,this.originator)}async getNetwork(e={}){return await this.connectToSubstrate(),await this.substrate.getNetwork(e,this.originator)}async getVersion(e={}){return await this.connectToSubstrate(),await this.substrate.getVersion(e,this.originator)}}class nE{wallet;constructor(e){this.wallet=e}decodeOutpoint(e){let t=te(e.read(32)),i=e.readVarIntNum();return`${t}.${i}`}encodeOutpoint(e){let t=new tp,[i,r]=e.split(".");return t.write(ti(i,"hex")),t.writeVarIntNum(Number(r)),t.toArray()}async transmitToWallet(e){let t=new tg(e);try{let e=t.readUInt8(),i=rB[e];if(void 0===i||""===i)throw Error(`Invalid call code: ${e}`);let r=t.readUInt8(),n=t.read(r),a=ts(n);switch(i){case"createAction":{let e={},i=t.readVarIntNum(),r=t.read(i);e.description=ts(r);let n=t.readVarIntNum();n>=0?e.inputBEEF=t.read(n):e.inputBEEF=void 0;let s=t.readVarIntNum();if(s>=0){e.inputs=[];for(let i=0;i<s;i++){let i={};i.outpoint=this.decodeOutpoint(t);let r=t.readVarIntNum();if(r>=0){let e=t.read(r);i.unlockingScript=te(e)}else i.unlockingScript=void 0,i.unlockingScriptLength=t.readVarIntNum();let n=t.readVarIntNum(),a=t.read(n);i.inputDescription=ts(a);let s=t.readVarIntNum();s>=0?i.sequenceNumber=s:i.sequenceNumber=void 0,e.inputs.push(i)}}else e.inputs=void 0;let o=t.readVarIntNum();if(o>=0){e.outputs=[];for(let i=0;i<o;i++){let i={},r=t.readVarIntNum(),n=t.read(r);i.lockingScript=te(n),i.satoshis=t.readVarIntNum();let a=t.readVarIntNum(),s=t.read(a);i.outputDescription=ts(s);let o=t.readVarIntNum();if(o>=0){let e=t.read(o);i.basket=ts(e)}else i.basket=void 0;let c=t.readVarIntNum();if(c>=0){let e=t.read(c);i.customInstructions=ts(e)}else i.customInstructions=void 0;let l=t.readVarIntNum();if(l>=0){i.tags=[];for(let e=0;e<l;e++){let e=t.readVarIntNum(),r=t.read(e),n=ts(r);i.tags.push(n)}}else i.tags=void 0;e.outputs.push(i)}}else e.outputs=void 0;let c=t.readVarIntNum();c>=0?e.lockTime=c:e.lockTime=void 0;let l=t.readVarIntNum();l>=0?e.version=l:e.version=void 0;let h=t.readVarIntNum();if(h>=0){e.labels=[];for(let i=0;i<h;i++){let i=t.readVarIntNum(),r=t.read(i),n=ts(r);e.labels.push(n)}}else e.labels=void 0;let d=t.readInt8();if(1===d){e.options={};let i=t.readInt8();-1===i?e.options.signAndProcess=void 0:e.options.signAndProcess=1===i;let r=t.readInt8();-1===r?e.options.acceptDelayedBroadcast=void 0:e.options.acceptDelayedBroadcast=1===r;let n=t.readInt8();-1===n?e.options.trustSelf=void 0:1===n&&(e.options.trustSelf="known");let a=t.readVarIntNum();if(a>=0){e.options.knownTxids=[];for(let i=0;i<a;i++){let i=t.read(32),r=te(i);e.options.knownTxids.push(r)}}else e.options.knownTxids=void 0;let s=t.readInt8();-1===s?e.options.returnTXIDOnly=void 0:e.options.returnTXIDOnly=1===s;let o=t.readInt8();-1===o?e.options.noSend=void 0:e.options.noSend=1===o;let c=t.readVarIntNum();if(c>=0){e.options.noSendChange=[];for(let i=0;i<c;i++){let i=this.decodeOutpoint(t);e.options.noSendChange.push(i)}}else e.options.noSendChange=void 0;let l=t.readVarIntNum();if(l>=0){e.options.sendWith=[];for(let i=0;i<l;i++){let i=t.read(32),r=te(i);e.options.sendWith.push(r)}}else e.options.sendWith=void 0;let h=t.readInt8();-1===h?e.options.randomizeOutputs=void 0:e.options.randomizeOutputs=1===h}else e.options=void 0;let u=await this.wallet.createAction(e,a),f=new tp;if(null!=u.txid&&""!==u.txid?(f.writeInt8(1),f.write(ti(u.txid,"hex"))):f.writeInt8(0),null!=u.tx?(f.writeInt8(1),f.writeVarIntNum(u.tx.length),f.write(u.tx)):f.writeInt8(0),null!=u.noSendChange)for(let e of(f.writeVarIntNum(u.noSendChange.length),u.noSendChange))f.write(this.encodeOutpoint(e));else f.writeVarIntNum(-1);if(null!=u.sendWithResults)for(let e of(f.writeVarIntNum(u.sendWithResults.length),u.sendWithResults)){let t;f.write(ti(e.txid,"hex")),"unproven"===e.status?t=1:"sending"===e.status?t=2:"failed"===e.status&&(t=3),f.writeInt8(t)}else f.writeVarIntNum(-1);if(null!=u.signableTransaction){f.writeInt8(1),f.writeVarIntNum(u.signableTransaction.tx.length),f.write(u.signableTransaction.tx);let e=ti(u.signableTransaction.reference,"base64");f.writeVarIntNum(e.length),f.write(e)}else f.writeInt8(0);let p=new tp;return p.writeUInt8(0),p.write(f.toArray()),p.toArray()}case"signAction":{let e={},i=t.readVarIntNum();e.spends={};for(let r=0;r<i;r++){let i=t.readVarIntNum(),r={},n=t.readVarIntNum(),a=t.read(n);r.unlockingScript=te(a);let s=t.readVarIntNum();s>=0?r.sequenceNumber=s:r.sequenceNumber=void 0,e.spends[i]=r}let r=t.readVarIntNum(),n=t.read(r);e.reference=tc(n);let s=t.readInt8();if(1===s){e.options={};let i=t.readInt8();-1===i?e.options.acceptDelayedBroadcast=void 0:e.options.acceptDelayedBroadcast=1===i;let r=t.readInt8();-1===r?e.options.returnTXIDOnly=void 0:e.options.returnTXIDOnly=1===r;let n=t.readInt8();-1===n?e.options.noSend=void 0:e.options.noSend=1===n;let a=t.readVarIntNum();if(a>=0){e.options.sendWith=[];for(let i=0;i<a;i++){let i=t.read(32),r=te(i);e.options.sendWith.push(r)}}else e.options.sendWith=void 0}else e.options=void 0;let o=await this.wallet.signAction(e,a),c=new tp;if(null!=o.txid&&""!==o.txid?(c.writeInt8(1),c.write(ti(o.txid,"hex"))):c.writeInt8(0),null!=o.tx?(c.writeInt8(1),c.writeVarIntNum(o.tx.length),c.write(o.tx)):c.writeInt8(0),null!=o.sendWithResults)for(let e of(c.writeVarIntNum(o.sendWithResults.length),o.sendWithResults)){let t;c.write(ti(e.txid,"hex")),"unproven"===e.status?t=1:"sending"===e.status?t=2:"failed"===e.status&&(t=3),c.writeInt8(t)}else c.writeVarIntNum(-1);let l=new tp;return l.writeUInt8(0),l.write(c.toArray()),l.toArray()}case"abortAction":{let e=t.read(),i=tc(e);await this.wallet.abortAction({reference:i},a);let r=new tp;return r.writeUInt8(0),r.toArray()}case"listActions":{let e={},i=t.readVarIntNum();e.labels=[];for(let r=0;r<i;r++){let i=t.readVarIntNum(),r=t.read(i);e.labels.push(ts(r))}let r=t.readInt8();for(let i of(-1===r?e.labelQueryMode=void 0:1===r?e.labelQueryMode="any":2===r&&(e.labelQueryMode="all"),["includeLabels","includeInputs","includeInputSourceLockingScripts","includeInputUnlockingScripts","includeOutputs","includeOutputLockingScripts"])){let r=t.readInt8();-1===r?e[i]=void 0:e[i]=1===r}let n=t.readVarIntNum();n>=0?e.limit=n:e.limit=void 0;let s=t.readVarIntNum();s>=0?e.offset=s:e.offset=void 0;let o=t.readInt8();o>=0?e.seekPermission=1===o:e.seekPermission=void 0;let c=await this.wallet.listActions(e,a),l=new tp;for(let e of(l.writeVarIntNum(c.totalActions),c.actions)){let t;switch(l.write(ti(e.txid,"hex")),l.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}l.writeInt8(t),l.writeInt8(+!!e.isOutgoing);let i=ti(e.description,"utf8");if(l.writeVarIntNum(i.length),l.write(i),void 0!==e.labels)for(let t of(l.writeVarIntNum(e.labels.length),e.labels)){let e=ti(t,"utf8");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);if(l.writeVarIntNum(e.version),l.writeVarIntNum(e.lockTime),void 0!==e.inputs)for(let t of(l.writeVarIntNum(e.inputs.length),e.inputs)){if(l.write(this.encodeOutpoint(t.sourceOutpoint)),l.writeVarIntNum(t.sourceSatoshis),void 0!==t.sourceLockingScript){let e=ti(t.sourceLockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);if(void 0!==t.unlockingScript){let e=ti(t.unlockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);let e=ti(t.inputDescription,"utf8");l.writeVarIntNum(e.length),l.write(e),l.writeVarIntNum(t.sequenceNumber)}else l.writeVarIntNum(-1);if(void 0!==e.outputs)for(let t of(l.writeVarIntNum(e.outputs.length),e.outputs)){if(l.writeVarIntNum(t.outputIndex),l.writeVarIntNum(t.satoshis),void 0!==t.lockingScript){let e=ti(t.lockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);l.writeInt8(+!!t.spendable);let e=ti(t.outputDescription,"utf8");if(l.writeVarIntNum(e.length),l.write(e),void 0!==t.basket){let e=ti(t.basket,"utf8");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);if(void 0!==t.tags)for(let e of(l.writeVarIntNum(t.tags.length),t.tags)){let t=ti(e,"utf8");l.writeVarIntNum(t.length),l.write(t)}else l.writeVarIntNum(-1);if(void 0!==t.customInstructions){let e=ti(t.customInstructions,"utf8");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1)}else l.writeVarIntNum(-1)}let h=new tp;return h.writeUInt8(0),h.write(l.toArray()),h.toArray()}case"internalizeAction":{let e={},i=t.readVarIntNum();e.tx=t.read(i);let r=t.readVarIntNum();e.outputs=[];for(let i=0;i<r;i++){let i={};i.outputIndex=t.readVarIntNum();let r=t.readUInt8();if(1===r){i.protocol="wallet payment",i.paymentRemittance={};let e=t.read(33);i.paymentRemittance.senderIdentityKey=te(e);let r=t.readVarIntNum(),n=t.read(r);i.paymentRemittance.derivationPrefix=tc(n);let a=t.readVarIntNum(),s=t.read(a);i.paymentRemittance.derivationSuffix=tc(s)}else if(2===r){i.protocol="basket insertion",i.insertionRemittance={};let e=t.readVarIntNum(),r=t.read(e);i.insertionRemittance.basket=ts(r);let n=t.readVarIntNum();if(n>=0){let e=t.read(n);i.insertionRemittance.customInstructions=ts(e)}let a=t.readVarIntNum();if(a>0){i.insertionRemittance.tags=[];for(let e=0;e<a;e++){let e=t.readVarIntNum(),r=t.read(e);i.insertionRemittance.tags.push(ts(r))}}else i.insertionRemittance.tags=[]}e.outputs.push(i)}let n=t.readVarIntNum();if(n>=0){e.labels=[];for(let i=0;i<n;i++){let i=t.readVarIntNum();e.labels.push(ts(t.read(i)))}}let s=t.readVarIntNum();e.description=ts(t.read(s));let o=t.readInt8();o>=0?e.seekPermission=1===o:e.seekPermission=void 0,await this.wallet.internalizeAction(e,a);let c=new tp;return c.writeUInt8(0),c.toArray()}case"listOutputs":{let e={},i=t.readVarIntNum(),r=t.read(i);e.basket=ts(r);let n=t.readVarIntNum();if(n>0){e.tags=[];for(let i=0;i<n;i++){let i=t.readVarIntNum(),r=t.read(i);e.tags.push(ts(r))}}else e.tags=void 0;let s=t.readInt8();1===s?e.tagQueryMode="all":2===s?e.tagQueryMode="any":e.tagQueryMode=void 0;let o=t.readInt8();1===o?e.include="locking scripts":2===o?e.include="entire transactions":e.include=void 0;let c=t.readInt8();-1===c?e.includeCustomInstructions=void 0:e.includeCustomInstructions=1===c;let l=t.readInt8();-1===l?e.includeTags=void 0:e.includeTags=1===l;let h=t.readInt8();-1===h?e.includeLabels=void 0:e.includeLabels=1===h;let d=t.readVarIntNum();d>=0?e.limit=d:e.limit=void 0;let u=t.readVarIntNum();u>=0?e.offset=u:e.offset=void 0;let f=t.readInt8();f>=0?e.seekPermission=1===f:e.seekPermission=void 0;let p=await this.wallet.listOutputs(e,a),g=new tp;for(let e of(g.writeVarIntNum(p.totalOutputs),null!=p.BEEF?(g.writeVarIntNum(p.BEEF.length),g.write(p.BEEF)):g.writeVarIntNum(-1),p.outputs)){if(g.write(this.encodeOutpoint(e.outpoint)),g.writeVarIntNum(e.satoshis),void 0!==e.lockingScript){let t=ti(e.lockingScript,"hex");g.writeVarIntNum(t.length),g.write(t)}else g.writeVarIntNum(-1);if(void 0!==e.customInstructions){let t=ti(e.customInstructions,"utf8");g.writeVarIntNum(t.length),g.write(t)}else g.writeVarIntNum(-1);if(void 0!==e.tags)for(let t of(g.writeVarIntNum(e.tags.length),e.tags)){let e=ti(t,"utf8");g.writeVarIntNum(e.length),g.write(e)}else g.writeVarIntNum(-1);if(void 0!==e.labels)for(let t of(g.writeVarIntNum(e.labels.length),e.labels)){let e=ti(t,"utf8");g.writeVarIntNum(e.length),g.write(e)}else g.writeVarIntNum(-1)}let m=new tp;return m.writeUInt8(0),m.write(g.toArray()),m.toArray()}case"relinquishOutput":{let e={},i=t.readVarIntNum(),r=t.read(i);e.basket=ts(r),e.output=this.decodeOutpoint(t),await this.wallet.relinquishOutput(e,a);let n=new tp;return n.writeUInt8(0),n.toArray()}case"getPublicKey":{let e={},i=t.readUInt8();if(e.identityKey=1===i,!0!==e.identityKey){e.protocolID=this.decodeProtocolID(t),e.keyID=this.decodeString(t),e.counterparty=this.decodeCounterparty(t);let i=t.readInt8();-1===i?e.privileged=void 0:e.privileged=1===i;let r=t.readInt8();if(-1!==r){let i=t.read(r);e.privilegedReason=ts(i)}else e.privilegedReason=void 0;let n=t.readInt8();-1===n?e.forSelf=void 0:e.forSelf=1===n}else{let i=t.readInt8();-1===i?e.privileged=void 0:e.privileged=1===i;let r=t.readInt8();if(-1!==r){let i=t.read(r);e.privilegedReason=ts(i)}else e.privilegedReason=void 0}let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.getPublicKey(e,a),s=new tp;s.writeUInt8(0);let o=ti(n.publicKey,"hex");return s.write(o),s.toArray()}case"encrypt":{let e=this.decodeKeyRelatedParams(t),i=t.readVarIntNum();e.plaintext=t.read(i);let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.encrypt(e,a),s=new tp;return s.writeUInt8(0),s.write(n.ciphertext),s.toArray()}case"decrypt":{let e=this.decodeKeyRelatedParams(t),i=t.readVarIntNum();e.ciphertext=t.read(i);let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.decrypt(e,a),s=new tp;return s.writeUInt8(0),s.write(n.plaintext),s.toArray()}case"createHmac":{let e=this.decodeKeyRelatedParams(t),i=t.readVarIntNum();e.data=t.read(i);let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.createHmac(e,a),s=new tp;return s.writeUInt8(0),s.write(n.hmac),s.toArray()}case"verifyHmac":{let e=this.decodeKeyRelatedParams(t);e.hmac=t.read(32);let i=t.readVarIntNum();e.data=t.read(i);let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0,await this.wallet.verifyHmac(e,a);let n=new tp;return n.writeUInt8(0),n.toArray()}case"createSignature":{let e=this.decodeKeyRelatedParams(t),i=t.readUInt8();if(1===i){let i=t.readVarIntNum();e.data=t.read(i)}else 2===i&&(e.hashToDirectlySign=t.read(32));let r=t.readInt8();r>=0?e.seekPermission=1===r:e.seekPermission=void 0;let n=await this.wallet.createSignature(e,a),s=new tp;return s.writeUInt8(0),s.write(n.signature),s.toArray()}case"verifySignature":{let e=this.decodeKeyRelatedParams(t),i=t.readInt8();-1===i?e.forSelf=void 0:e.forSelf=1===i;let r=t.readVarIntNum();e.signature=t.read(r);let n=t.readUInt8();if(1===n){let i=t.readVarIntNum();e.data=t.read(i)}else 2===n&&(e.hashToDirectlyVerify=t.read(32));let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0,await this.wallet.verifySignature(e,a);let o=new tp;return o.writeUInt8(0),o.toArray()}case"isAuthenticated":{let e=await this.wallet.isAuthenticated({},a),t=new tp;return t.writeUInt8(0),t.writeUInt8(+!!e.authenticated),t.toArray()}case"waitForAuthentication":{await this.wallet.waitForAuthentication({},a);let e=new tp;return e.writeUInt8(0),e.toArray()}case"getHeight":{let e=await this.wallet.getHeight({},a),t=new tp;return t.writeUInt8(0),t.writeVarIntNum(e.height),t.toArray()}case"getHeaderForHeight":{let e={};e.height=t.readVarIntNum();let i=await this.wallet.getHeaderForHeight(e,a),r=new tp;r.writeUInt8(0);let n=ti(i.header,"hex");return r.write(n),r.toArray()}case"getNetwork":{let e=await this.wallet.getNetwork({},a),t=new tp;return t.writeUInt8(0),t.writeUInt8(+("mainnet"!==e.network)),t.toArray()}case"getVersion":{let e=await this.wallet.getVersion({},a),t=new tp;t.writeUInt8(0);let i=ti(e.version,"utf8");return t.write(i),t.toArray()}case"revealCounterpartyKeyLinkage":{let e={},i=t.readInt8();-1===i?e.privileged=void 0:e.privileged=1===i;let r=t.readInt8();if(-1===r)e.privilegedReason=void 0;else{let i=t.read(r);e.privilegedReason=ts(i)}let n=t.read(33);e.counterparty=te(n);let s=t.read(33);e.verifier=te(s);let o=await this.wallet.revealCounterpartyKeyLinkage(e,a),c=new tp;c.write(ti(o.prover,"hex")),c.write(ti(o.verifier,"hex")),c.write(ti(o.counterparty,"hex"));let l=ti(o.revelationTime,"utf8");c.writeVarIntNum(l.length),c.write(l),c.writeVarIntNum(o.encryptedLinkage.length),c.write(o.encryptedLinkage),c.writeVarIntNum(o.encryptedLinkageProof.length),c.write(o.encryptedLinkageProof);let h=new tp;return h.writeUInt8(0),h.write(c.toArray()),h.toArray()}case"revealSpecificKeyLinkage":{let e=this.decodeKeyRelatedParams(t),i=t.read(33);e.verifier=te(i);let r=await this.wallet.revealSpecificKeyLinkage(e,a),n=new tp;n.write(ti(r.prover,"hex")),n.write(ti(r.verifier,"hex")),n.write(ti(r.counterparty,"hex")),n.writeUInt8(r.protocolID[0]);let s=ti(r.protocolID[1],"utf8");n.writeVarIntNum(s.length),n.write(s);let o=ti(r.keyID,"utf8");n.writeVarIntNum(o.length),n.write(o),n.writeVarIntNum(r.encryptedLinkage.length),n.write(r.encryptedLinkage),n.writeVarIntNum(r.encryptedLinkageProof.length),n.write(r.encryptedLinkageProof),n.writeUInt8(r.proofType);let c=new tp;return c.writeUInt8(0),c.write(n.toArray()),c.toArray()}case"acquireCertificate":{let e={},i=t.read(32);e.type=tc(i);let r=t.read(33);e.certifier=te(r);let n=t.readVarIntNum();e.fields={};for(let i=0;i<n;i++){let i=t.readVarIntNum(),r=t.read(i),n=ts(r),a=t.readVarIntNum(),s=t.read(a),o=ts(s);e.fields[n]=o}let s=t.readInt8();-1===s?e.privileged=void 0:e.privileged=1===s;let o=t.readInt8();if(-1===o)e.privilegedReason=void 0;else{let i=t.read(o);e.privilegedReason=ts(i)}let c=t.readUInt8();if(e.acquisitionProtocol=1===c?"direct":"issuance","direct"===e.acquisitionProtocol){let i=t.read(32);e.serialNumber=tc(i),e.revocationOutpoint=this.decodeOutpoint(t);let r=t.readVarIntNum(),n=t.read(r);e.signature=te(n);let a=t.readUInt8();if(11===a)e.keyringRevealer="certifier";else{let i=[a].concat(t.read(32));e.keyringRevealer=te(i)}let s=t.readVarIntNum();e.keyringForSubject={};for(let i=0;i<s;i++){let i=t.readVarIntNum(),r=t.read(i),n=ts(r),a=t.readVarIntNum(),s=t.read(a),o=tc(s);e.keyringForSubject[n]=o}}else{let i=t.readVarIntNum(),r=t.read(i);e.certifierUrl=ts(r)}let l=await this.wallet.acquireCertificate(e,a),h=new rC(l.type,l.serialNumber,l.subject,l.certifier,l.revocationOutpoint,l.fields,l.signature).toBinary(),d=new tp;return d.writeUInt8(0),d.write(h),d.toArray()}case"listCertificates":{let e={},i=t.readVarIntNum();e.certifiers=[];for(let r=0;r<i;r++){let i=t.read(33);e.certifiers.push(te(i))}let r=t.readVarIntNum();e.types=[];for(let i=0;i<r;i++){let i=t.read(32);e.types.push(tc(i))}let n=t.readVarIntNum();n>=0?e.limit=n:e.limit=void 0;let s=t.readVarIntNum();s>=0?e.offset=s:e.offset=void 0;let o=t.readInt8();-1===o?e.privileged=void 0:e.privileged=1===o;let c=t.readInt8();if(-1===c)e.privilegedReason=void 0;else{let i=t.read(c);e.privilegedReason=ts(i)}let l=await this.wallet.listCertificates(e,a),h=new tp;for(let e of(h.writeVarIntNum(l.totalCertificates),l.certificates)){let t=new rC(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature).toBinary();if(h.writeVarIntNum(t.length),h.write(t),e.keyring&&Object.keys(e.keyring).length>0){h.writeInt8(1);let t=Object.entries(e.keyring);for(let[e,i]of(h.writeVarIntNum(t.length),t)){let t=ti(e,"utf8");h.writeVarIntNum(t.length),h.write(t);let r=ti(i,"base64");h.writeVarIntNum(r.length),h.write(r)}}else h.writeInt8(0);let i=ti(e.verifier,"hex");h.writeVarIntNum(i.length),h.write(i)}let d=new tp;return d.writeUInt8(0),d.write(h.toArray()),d.toArray()}case"proveCertificate":{let e={},i={},r=t.read(32);i.type=tc(r);let n=t.read(33);i.subject=te(n);let s=t.read(32);i.serialNumber=tc(s);let o=t.read(33);i.certifier=te(o),i.revocationOutpoint=this.decodeOutpoint(t);let c=t.readVarIntNum(),l=t.read(c);i.signature=te(l);let h=t.readVarIntNum();i.fields={};for(let e=0;e<h;e++){let e=t.readVarIntNum(),r=t.read(e),n=ts(r),a=t.readVarIntNum(),s=t.read(a),o=ts(s);i.fields[n]=o}e.certificate=i;let d=t.readVarIntNum();e.fieldsToReveal=[];for(let i=0;i<d;i++){let i=t.readVarIntNum(),r=t.read(i),n=ts(r);e.fieldsToReveal.push(n)}let u=t.read(33);e.verifier=te(u);let f=t.readInt8();-1===f?e.privileged=void 0:e.privileged=1===f;let p=t.readInt8();if(-1===p)e.privilegedReason=void 0;else{let i=t.read(p);e.privilegedReason=ts(i)}let g=await this.wallet.proveCertificate(e,a),m=new tp,y=Object.entries(g.keyringForVerifier);for(let[e,t]of(m.writeVarIntNum(y.length),y)){let i=ti(e,"utf8");m.writeVarIntNum(i.length),m.write(i);let r=ti(t,"base64");m.writeVarIntNum(r.length),m.write(r)}let b=new tp;return b.writeUInt8(0),b.write(m.toArray()),b.toArray()}case"relinquishCertificate":{let e={},i=t.read(32);e.type=tc(i);let r=t.read(32);e.serialNumber=tc(r);let n=t.read(33);e.certifier=te(n),await this.wallet.relinquishCertificate(e,a);let s=new tp;return s.writeUInt8(0),s.toArray()}case"discoverByIdentityKey":{let e={},i=t.read(33);e.identityKey=te(i);let r=t.readVarIntNum();r>=0?e.limit=r:e.limit=void 0;let n=t.readVarIntNum();n>=0?e.offset=n:e.offset=void 0;let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0;let o=await this.wallet.discoverByIdentityKey(e,a),c=this.serializeDiscoveryResult(o),l=new tp;return l.writeUInt8(0),l.write(c),l.toArray()}case"discoverByAttributes":{let e={},i=t.readVarIntNum();e.attributes={};for(let r=0;r<i;r++){let i=t.readVarIntNum(),r=t.read(i),n=ts(r),a=t.readVarIntNum(),s=t.read(a),o=ts(s);e.attributes[n]=o}let r=t.readVarIntNum();r>=0?e.limit=r:e.limit=void 0;let n=t.readVarIntNum();n>=0?e.offset=n:e.offset=void 0;let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0;let o=await this.wallet.discoverByAttributes(e,a),c=this.serializeDiscoveryResult(o),l=new tp;return l.writeUInt8(0),l.write(c),l.toArray()}default:throw Error(`Method ${i} not implemented`)}}catch(r){let e=new tp;e.writeUInt8("number"==typeof r.code?r.code:1);let t=ti("string"==typeof r.message?r.message:"Unknown error","utf8");e.writeVarIntNum(t.length),e.write(t);let i=ti("string"==typeof r.stack?r.stack:"","utf8");return e.writeVarIntNum(i.length),e.write(i),e.toArray()}}decodeProtocolID(e){let t=e.readUInt8(),i=e.readVarIntNum();return[t,ts(e.read(i))]}decodeString(e){let t=e.readVarIntNum();return ts(e.read(t))}decodeCounterparty(e){let t=e.readUInt8();return 11===t?"self":12===t?"anyone":0!==t?te([t,...e.read(32)]):void 0}serializeDiscoveryResult(e){let t=new tp;for(let i of(t.writeVarIntNum(e.totalCertificates),e.certificates)){let e=new rC(i.type,i.serialNumber,i.subject,i.certifier,i.revocationOutpoint,i.fields,i.signature).toBinary();t.writeVarIntNum(e.length),t.write(e);let r=ti(i.certifierInfo.name,"utf8");t.writeVarIntNum(r.length),t.write(r);let n=ti(i.certifierInfo.iconUrl,"utf8");t.writeVarIntNum(n.length),t.write(n);let a=ti(i.certifierInfo.description,"utf8");t.writeVarIntNum(a.length),t.write(a),t.writeUInt8(i.certifierInfo.trust);let s=Object.entries(i.publiclyRevealedKeyring);for(let[e,i]of(t.writeVarIntNum(s.length),s)){let r=ti(e,"utf8");t.writeVarIntNum(r.length),t.write(r);let n=ti(i,"base64");t.writeVarIntNum(n.length),t.write(n)}let o=Object.entries(i.decryptedFields);for(let[e,i]of(t.writeVarIntNum(o.length),o)){let r=ti(e,"utf8");t.writeVarIntNum(r.length),t.write(r);let n=ti(i,"utf8");t.writeVarIntNum(n.length),t.write(n)}}return t.toArray()}decodeKeyRelatedParams(e){let t={};t.protocolID=this.decodeProtocolID(e);let i=e.readVarIntNum();t.keyID=ts(e.read(i)),t.counterparty=this.decodeCounterparty(e);let r=e.readInt8();-1===r?t.privileged=void 0:t.privileged=1===r;let n=e.readInt8();return -1===n?t.privilegedReason=void 0:t.privilegedReason=ts(e.read(n)),t}}class nx extends rC{masterKeyring;constructor(e,t,i,r,n,a,s,o){for(const c of(super(e,t,i,r,n,a,o),Object.keys(a)))if(void 0===s[c]||""===s[c])throw Error(`Master keyring must contain a value for every field. Missing or empty key for field: "${c}".`);this.masterKeyring=s}static async createCertificateFields(e,t,i,r,n){let a={},s={};for(let[o,c]of Object.entries(i)){let i=ip.fromRandom(),l=i.encrypt(ti(c,"utf8"));a[o]=tc(l);let{ciphertext:h}=await e.encrypt({plaintext:i.toArray(),...rC.getCertificateFieldEncryptionDetails(o),counterparty:t,privileged:r,privilegedReason:n});s[o]=tc(h)}return{certificateFields:a,masterKeyring:s}}static async createKeyringForVerifier(e,t,i,r,n,a,s,o,c){if(!Array.isArray(n))throw Error("fieldsToReveal must be an array of strings");let l={};for(let h of n){if(void 0===r[h]||null===r[h]||""===r[h])throw Error(`Fields to reveal must be a subset of the certificate fields. Missing the "${h}" field.`);let n=(await this.decryptField(e,a,h,r[h],t,o,c)).fieldRevelationKey,{ciphertext:d}=await e.encrypt({plaintext:n,...rC.getCertificateFieldEncryptionDetails(h,s),counterparty:i,privileged:o,privilegedReason:c});l[h]=tc(d)}return l}static async issueCertificateForSubject(e,t,i,r,n=async e=>"00".repeat(32),a){let s=a??tc(t0(32)),{certificateFields:o,masterKeyring:c}=await this.createCertificateFields(e,t,i),l=await n(s),h=new nx(r,s,"self"===t?(await e.getPublicKey({identityKey:!0})).publicKey:t,(await e.getPublicKey({identityKey:!0})).publicKey,l,o,c);return await h.sign(e),h}static async decryptFields(e,t,i,r,n,a){if(null==t||0===Object.keys(t).length)throw Error("A MasterCertificate must have a valid masterKeyring!");try{let s={};for(let o of Object.keys(i))s[o]=(await this.decryptField(e,t,o,i[o],r,n,a)).decryptedFieldValue;return s}catch{throw Error("Failed to decrypt all master certificate fields.")}}static async decryptField(e,t,i,r,n,a,s){if(null==t||0===Object.keys(t).length)throw Error("A MasterCertificate must have a valid masterKeyring!");try{let{plaintext:o}=await e.decrypt({ciphertext:ti(t[i],"base64"),...rC.getCertificateFieldEncryptionDetails(i),counterparty:n,privileged:a,privilegedReason:s}),c=new ip(o).decrypt(ti(r,"base64"));return{fieldRevelationKey:o,decryptedFieldValue:ts(c)}}catch{throw Error("Failed to decrypt certificate field!")}}}class nP extends rC{keyring;decryptedFields;constructor(e,t,i,r,n,a,s,o,c){super(e,t,i,r,n,a,o),this.keyring=s,this.decryptedFields=c}static fromCertificate(e,t){return new nP(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,t,e.signature)}async decryptFields(e,t,i,r){if(null==this.keyring||0===Object.keys(this.keyring).length)throw Error("A keyring is required to decrypt certificate fields for the verifier.");try{let n={};for(let a in this.keyring){let{plaintext:s}=await e.decrypt({ciphertext:ti(this.keyring[a],"base64"),...rC.getCertificateFieldEncryptionDetails(a,this.serialNumber),counterparty:this.subject,privileged:t,privilegedReason:i},r),o=new ip(s).decrypt(ti(this.fields[a],"base64"));n[a]=ts(o)}return n}catch(e){throw Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(e instanceof Error?e.message:e)}`)}}}class nA extends rN{keyDeriver;constructor(e){if(super(e),e instanceof rx)this.keyDeriver=e;else if("string"==typeof e||e instanceof t3)this.keyDeriver=new rP(e);else throw Error("Invalid key deriver provided")}async isAuthenticated(){throw Error("not implemented")}async waitForAuthentication(){throw Error("not implemented")}async getNetwork(){throw Error("not implemented")}async getVersion(){throw Error("not implemented")}async getPublicKey(e){if(!0===e.privileged)throw Error("no privilege support");if(!0===e.identityKey){if(null===this.keyDeriver||void 0===this.keyDeriver)throw Error("keyDeriver is not initialized");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==e.protocolID||"string"!=typeof e.keyID||""===e.keyID.trim())throw Error("protocolID and keyID are required if identityKey is false or undefined.");if(null===this.keyDeriver||void 0===this.keyDeriver)throw Error("keyDeriver is not initialized");return{publicKey:this.keyDeriver.derivePublicKey(e.protocolID,e.keyID,"string"==typeof e.counterparty&&""!==e.counterparty.trim()?e.counterparty:"self",!!e.forSelf).toString()}}async createAction(){throw Error("not implemented")}async signAction(){throw Error("not implemented")}async abortAction(){throw Error("not implemented")}async listActions(){throw Error("not implemented")}async internalizeAction(){throw Error("not implemented")}async listOutputs(){throw Error("not implemented")}async relinquishOutput(){throw Error("not implemented")}async acquireCertificate(){throw Error("not implemented")}async listCertificates(){throw Error("not implemented")}async proveCertificate(){throw Error("not implemented")}async relinquishCertificate(){throw Error("not implemented")}async discoverByIdentityKey(){throw Error("not implemented")}async discoverByAttributes(){throw Error("not implemented")}async getHeight(){throw Error("not implemented")}async getHeaderForHeight(){throw Error("not implemented")}}class nN{sessionNonceToSession;identityKeyToNonces;constructor(){this.sessionNonceToSession=new Map,this.identityKeyToNonces=new Map}addSession(e){if("string"!=typeof e.sessionNonce)throw 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){let t,i=this.sessionNonceToSession.get(e);if(null!=i)return i;let r=this.identityKeyToNonces.get(e);if(null!=r&&0!==r.size){for(let e of r){let i=this.sessionNonceToSession.get(e);null!=i&&(null==t?t=i:(i.lastUpdate??0)>(t.lastUpdate??0)&&(t=i))}return t}}removeSession(e){if("string"==typeof e.sessionNonce&&this.sessionNonceToSession.delete(e.sessionNonce),"string"==typeof e.peerIdentityKey){let t=this.identityKeyToNonces.get(e.peerIdentityKey);null!=t&&(t.delete(e.sessionNonce??""),0===t.size&&this.identityKeyToNonces.delete(e.peerIdentityKey))}}hasSession(e){if(this.sessionNonceToSession.has(e))return!0;let t=this.identityKeyToNonces.get(e);return null!=t&&t.size>0}}async function nO(e,t,i="self",r){let n=ti(e,"base64"),a=n.slice(0,16),s=n.slice(16),{valid:o}=await t.verifyHmac({data:a,hmac:s,protocolID:[2,"server hmac"],keyID:ts(a),counterparty:i},r);return o}async function nT(e,t="self",i){let r=t0(16),{hmac:n}=await e.createHmac({protocolID:[2,"server hmac"],keyID:ts(r),data:r,counterparty:t},i);return tc([...r,...n])}let n_=async(e,t,i,r)=>{let n=await e.listCertificates({certifiers:t.certifiers,types:Object.keys(t.types)},r);return await Promise.all(n.certificates.map(async n=>{let{keyringForVerifier:a}=await e.proveCertificate({certificate:n,fieldsToReveal:t.types[n.type],verifier:i},r);return new nP(n.type,n.serialNumber,n.subject,n.certifier,n.revocationOutpoint,n.fields,a,n.signature)}))},nR=async(e,t,i,r)=>{if(null==t.certificates||0===t.certificates.length)throw Error("No certificates were provided in the AuthMessage.");await Promise.all(t.certificates.map(async n=>{if(n.subject!==t.identityKey)throw Error(`The subject of one of your certificates ("${n.subject}") is not the same as the request sender ("${t.identityKey}").`);let a=new nP(n.type,n.serialNumber,n.subject,n.certifier,n.revocationOutpoint,n.fields,n.keyring,n.signature);if(!await a.verify())throw Error(`The signature for the certificate with serial number ${a.serialNumber} is invalid!`);if(null!=i){let{certifiers:e,types:t}=i;if(!e.includes(a.certifier))throw Error(`Certificate with serial number ${a.serialNumber} has an unrequested certifier: ${a.certifier}`);if(null==t[a.type])throw Error(`Certificate with type ${a.type} was not requested`)}await a.decryptFields(e,void 0,void 0,r)}))},nC="u">typeof globalThis?globalThis.Buffer:void 0;class nB{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;certificateValidationPromises=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;originator;identityPublicKey;constructor(e,t,i,r,n,a){this.wallet=e,this.originator=a,this.transport=t,this.certificatesToRequest=i??{certifiers:[],types:{}},this.transport.onData(this.handleIncomingMessage.bind(this)).catch(e=>{throw e}),this.sessionManager=null!=r?r:new nN,!1===n?this.autoPersistLastSession=!1:this.autoPersistLastSession=!0}async toPeer(e,t){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);let i=await this.getAuthenticatedSession(t);if(null==i.peerIdentityKey)throw Error("Peer identity is not established");if(!0===i.certificatesRequired&&!0!==i.certificatesValidated)throw Error("Cannot send general message before certificate validation is complete");let r=tc(t0(32)),{signature:n}=await this.wallet.createSignature({data:e,protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),a={version:"0.1",messageType:"general",identityKey:await this.getIdentityPublicKey(),nonce:r,yourNonce:i.peerNonce,payload:e,signature:n};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(a)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}async requestCertificates(e,t){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);let i=await this.getAuthenticatedSession(t),r=tc(t0(32)),{signature:n}=await this.wallet.createSignature({data:nB.utf8ToBytes(JSON.stringify(e)),protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),a={version:"0.1",messageType:"certificateRequest",identityKey:await this.getIdentityPublicKey(),nonce:r,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,requestedCertificates:e,signature:n};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(a)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}async getAuthenticatedSession(e){let t;if(void 0===this.transport)throw Error("Peer transport is not connected!");if("string"==typeof e&&(t=this.sessionManager.getSession(e)),null==t||!t.isAuthenticated){let i=await this.initiateHandshake(e);if(null==(t=this.sessionManager.getSession(i))||!t.isAuthenticated)throw Error("Unable to establish mutual authentication with peer!")}return t}listenForGeneralMessages(e){let t=this.callbackIdCounter++;return this.onGeneralMessageReceivedCallbacks.set(t,e),t}stopListeningForGeneralMessages(e){this.onGeneralMessageReceivedCallbacks.delete(e)}listenForCertificatesReceived(e){let t=this.callbackIdCounter++;return this.onCertificatesReceivedCallbacks.set(t,e),t}stopListeningForCertificatesReceived(e){this.onCertificatesReceivedCallbacks.delete(e)}listenForCertificatesRequested(e){let t=this.callbackIdCounter++;return this.onCertificateRequestReceivedCallbacks.set(t,e),t}stopListeningForCertificatesRequested(e){this.onCertificateRequestReceivedCallbacks.delete(e)}async initiateHandshake(e){let t=await nT(this.wallet,void 0,this.originator),i=Date.now(),r=this.certificatesToRequest.certifiers.length>0;this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:t,peerIdentityKey:e,lastUpdate:i,certificatesRequired:r,certificatesValidated:!r});let n={version:"0.1",messageType:"initialRequest",identityKey:await this.getIdentityPublicKey(),initialNonce:t,requestedCertificates:this.certificatesToRequest};return await this.transport.send(n),await this.waitForInitialResponse(t)}async waitForInitialResponse(e){return await new Promise(t=>{let i=this.listenForInitialResponse(e,e=>{this.stopListeningForInitialResponses(i),t(e)})})}listenForInitialResponse(e,t){let i=this.callbackIdCounter++;return this.onInitialResponseReceivedCallbacks.set(i,{callback:t,sessionNonce:e}),i}stopListeningForInitialResponses(e){this.onInitialResponseReceivedCallbacks.delete(e)}propagateTransportError(e,t){if(t instanceof Error){if(null!=e){let i=t.details;null!=i&&"object"==typeof i?null==i.peerIdentityKey&&(i.peerIdentityKey=e):t.details={peerIdentityKey:e}}throw t}throw Error(`Failed to send message to peer ${e??"unknown"}: ${String(t)}`)}async handleIncomingMessage(e){if("string"!=typeof e.version||"0.1"!==e.version)throw Error(`Invalid or unsupported message auth version! Received: ${e.version}, expected: 0.1`);try{switch(e.messageType){case"initialRequest":await this.processInitialRequest(e);break;case"initialResponse":await this.processInitialResponse(e);break;case"certificateRequest":await this.processCertificateRequest(e);break;case"certificateResponse":await this.processCertificateResponse(e);break;case"general":await this.processGeneralMessage(e);break;default:throw Error(`Unknown message type of ${String(e.messageType)} from ${String(e.identityKey)}`)}}catch(e){}}async processInitialRequest(e){let t;if("string"!=typeof e.identityKey||"string"!=typeof e.initialNonce||""===e.initialNonce)throw Error("Missing required fields in initialRequest message.");let i=await nT(this.wallet,void 0,this.originator),r=Date.now(),n=Array.isArray(this.certificatesToRequest?.certifiers)&&this.certificatesToRequest.certifiers.length>0;this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:i,peerNonce:e.initialNonce,peerIdentityKey:e.identityKey,lastUpdate:r,certificatesRequired:n,certificatesValidated:!n}),Array.isArray(e.requestedCertificates?.certifiers)&&e.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)}):t=await n_(this.wallet,e.requestedCertificates,e.identityKey,this.originator));let{signature:a}=await this.wallet.createSignature({data:[...nB.base64ToBytes(e.initialNonce),...nB.base64ToBytes(i)],protocolID:[2,"auth message signature"],keyID:`${e.initialNonce} ${i}`,counterparty:e.identityKey},this.originator),s={version:"0.1",messageType:"initialResponse",identityKey:await this.getIdentityPublicKey(),initialNonce:i,yourNonce:e.initialNonce,certificates:t,requestedCertificates:this.certificatesToRequest,signature:a};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=e.identityKey),await this.transport.send(s)}async processInitialResponse(e){if(!await nO(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Initial response nonce verification failed from peer: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Peer session not found for peer: ${e.identityKey}`);let i=nB.base64ToBytes((t.sessionNonce??"")+(e.initialNonce??"")),{valid:r}=await this.wallet.verifySignature({data:i,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${t.sessionNonce??""} ${e.initialNonce??""}`,counterparty:e.identityKey},this.originator);if(!r)throw Error(`Unable to verify initial response signature for peer: ${e.identityKey}`);if(t.peerNonce=e.initialNonce,t.peerIdentityKey=e.identityKey,t.isAuthenticated=!0,t.certificatesRequired=Array.isArray(this.certificatesToRequest?.certifiers)&&this.certificatesToRequest.certifiers.length>0,t.certificatesValidated=!t.certificatesRequired,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),t.certificatesRequired&&Array.isArray(e.certificates)&&e.certificates.length>0&&(await nR(this.wallet,e,this.certificatesToRequest,this.originator),t.certificatesValidated=!0,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),null!=t.sessionNonce&&this.resolveCertificateValidation(t.sessionNonce),this.onCertificatesReceivedCallbacks.forEach(t=>t(e.identityKey,e.certificates))),this.lastInteractedWithPeer=e.identityKey,this.onInitialResponseReceivedCallbacks.forEach(e=>{e.sessionNonce===t.sessionNonce&&e.callback(t.sessionNonce)}),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)});else{let t=await n_(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async processCertificateRequest(e){if(!await nO(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for certificate request message from: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let{valid:i}=await this.wallet.verifySignature({data:nB.utf8ToBytes(JSON.stringify(e.requestedCertificates)),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!i)throw Error(`Invalid signature in certificate request message from ${t.peerIdentityKey}`);if(t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)});else{let t=await n_(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async sendCertificateResponse(e,t){let i=await this.getAuthenticatedSession(e),r=tc(t0(32)),{signature:n}=await this.wallet.createSignature({data:nB.utf8ToBytes(JSON.stringify(t)),protocolID:[2,"auth message signature"],keyID:`${r} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),a={version:"0.1",messageType:"certificateResponse",identityKey:await this.getIdentityPublicKey(),nonce:r,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,certificates:t,signature:n};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(a)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}async processCertificateResponse(e){if(!await nO(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for certificate response from: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let{valid:i}=await this.wallet.verifySignature({data:nB.utf8ToBytes(JSON.stringify(e.certificates)),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:e.identityKey},this.originator);if(!i)throw Error(`Unable to verify certificate response signature for peer: ${e.identityKey}`);await nR(this.wallet,e,e.requestedCertificates,this.originator),t.certificatesValidated=!0,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),null!=t.sessionNonce&&this.resolveCertificateValidation(t.sessionNonce),this.onCertificatesReceivedCallbacks.forEach(t=>{t(e.identityKey,e.certificates??[])})}async processGeneralMessage(e){if(!await nO(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for general message from: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let i=!0===t.certificatesRequired,r=!0===t.certificatesValidated;if(i&&!r){let e=t.sessionNonce;if(null==e)throw Error("Session nonce is required for certificate validation");await new Promise((i,r)=>{let n=setTimeout(()=>{null!=this.certificateValidationPromises.get(e)&&(this.certificateValidationPromises.delete(e),r(Error(`Timeout waiting for certificate validation from peer ${t.peerIdentityKey??"unknown"}`)))},3e4);"object"==typeof n&&"unref"in n&&n.unref(),this.certificateValidationPromises.set(e,{resolve:()=>{clearTimeout(n),i()},reject:e=>{clearTimeout(n),r(e)}})})}let{valid:n}=await this.wallet.verifySignature({data:e.payload,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!n)throw Error(`Invalid signature in generalMessage from ${t.peerIdentityKey}`);t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.lastInteractedWithPeer=e.identityKey,this.onGeneralMessageReceivedCallbacks.forEach(t=>{t(e.identityKey,e.payload??[])})}resolveCertificateValidation(e){let t=this.certificateValidationPromises.get(e);null!=t&&(t.resolve(),this.certificateValidationPromises.delete(e))}async getIdentityPublicKey(){if(null!=this.identityPublicKey)return this.identityPublicKey;let{publicKey:e}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return this.identityPublicKey=e,e}static utf8ToBytes(e){return null!=nC?Array.from(nC.from(e,"utf8")):"u">typeof TextEncoder?Array.from(new TextEncoder().encode(e)):ti(e,"utf8")}static base64ToBytes(e){return null!=nC?Array.from(nC.from(e,"base64")):ti(e,"base64")}}let nU="u">typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch;class nV{onDataCallback;fetchClient;baseUrl;constructor(e,t=nU){if("function"!=typeof t)throw Error("SimplifiedFetchTransport requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=t,this.baseUrl=e}async send(e){if(null==this.onDataCallback)throw Error("Listen before you start speaking. God gave you two ears and one mouth for a reason.");if("general"!==e.messageType)return await new Promise((t,i)=>{(async()=>{try{let i=`${this.baseUrl}/.well-known/auth`,r=(async()=>{try{return await this.fetchClient(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(e){throw this.createNetworkError(i,e)}})();"initialRequest"!==e.messageType&&t();let n=await r;if(!n.ok){let e=Array.from(new Uint8Array(await n.arrayBuffer()));throw this.createUnauthenticatedResponseError(i,n,e)}if(null!=this.onDataCallback){let e=await n.json();this.onDataCallback(e)}"initialRequest"===e.messageType&&t()}catch(e){i(e)}})()});{let t,i,r=this.deserializeRequestPayload(e.payload),n=`${this.baseUrl}${r.urlPostfix}`;if("object"!=typeof r.headers&&(r.headers={}),r.headers["x-bsv-auth-version"]=e.version,r.headers["x-bsv-auth-identity-key"]=e.identityKey,r.headers["x-bsv-auth-nonce"]=e.nonce,r.headers["x-bsv-auth-your-nonce"]=e.yourNonce,r.headers["x-bsv-auth-signature"]=te(e.signature),r.headers["x-bsv-auth-request-id"]=r.requestId,null!=r.body){let e=r.headers;if(null==e["content-type"])throw Error("Content-Type header is required for requests with a body.");let t=String(e["content-type"]??"");t.includes("application/json")||t.includes("application/x-www-form-urlencoded")||t.includes("text/plain")?r.body=ts(r.body):r.body=new Uint8Array(r.body)}try{t=await this.fetchClient(n,{method:r.method,headers:r.headers,body:r.body})}catch(e){throw this.createNetworkError(n,e)}let a=Array.from(new Uint8Array(await t.arrayBuffer())),s=["x-bsv-auth-version","x-bsv-auth-identity-key","x-bsv-auth-signature"].filter(e=>{let i=t.headers.get(e);return null==i||0===i.trim().length});if(s.length>0)throw this.createUnauthenticatedResponseError(n,t,a,s);let o=t.headers.get("x-bsv-auth-requested-certificates");if(null!=o)try{i=JSON.parse(o)}catch(e){throw this.createMalformedHeaderError(n,"x-bsv-auth-requested-certificates",o,e)}let c=new tp;null!=t.headers.get("x-bsv-auth-request-id")&&c.write(ti(t.headers.get("x-bsv-auth-request-id"),"base64")),c.writeVarIntNum(t.status);let l=[];t.headers.forEach((e,t)=>{let i=t.toLowerCase();(i.startsWith("x-bsv-")||"authorization"===i)&&!i.startsWith("x-bsv-auth")&&l.push([i,e])}),l.sort(([e],[t])=>e.localeCompare(t)),c.writeVarIntNum(l.length);for(let e=0;e<l.length;e++){let t=ti(l[e][0],"utf8");c.writeVarIntNum(t.length),c.write(t);let i=ti(l[e][1],"utf8");c.writeVarIntNum(i.length),c.write(i)}c.writeVarIntNum(a.length),a.length>0&&c.write(a);let h={version:t.headers.get("x-bsv-auth-version"),messageType:"certificateRequest"===t.headers.get("x-bsv-auth-message-type")?"certificateRequest":"general",identityKey:t.headers.get("x-bsv-auth-identity-key"),nonce:t.headers.get("x-bsv-auth-nonce")??void 0,yourNonce:t.headers.get("x-bsv-auth-your-nonce")??void 0,requestedCertificates:i,payload:c.toArray(),signature:ti(t.headers.get("x-bsv-auth-signature"),"hex")};if(null==h.version)throw this.createUnauthenticatedResponseError(n,t,a);this.onDataCallback(h)}}async onData(e){this.onDataCallback=t=>{e(t)}}createNetworkError(e,t){let i=`Network error while sending authenticated request to ${e}`;if(t instanceof Error){let e=Error(`${i}: ${t.message}`);return e.stack=t.stack,e.cause=t,e}return Error(`${i}: ${String(t)}`)}createUnauthenticatedResponseError(e,t,i,r=[]){let n=(t.statusText??"").trim(),a=n.length>0?`${t.status} ${n}`:`${t.status}`,s=r.length>0?`missing headers: ${r.join(", ")}`:"response lacked required BSV auth headers",o=this.getBodyPreview(i,t.headers.get("content-type")),c=[`Received HTTP ${a} from ${e} without valid BSV authentication (${s})`];null!=o&&c.push(`body preview: ${o}`);let l=Error(c.join(" - "));return l.details={url:e,status:t.status,statusText:t.statusText,missingHeaders:r,bodyPreview:o},l}createMalformedHeaderError(e,t,i,r){let n=`Failed to parse ${t} returned by ${e}: ${i}`;if(r instanceof Error){let e=Error(`${n}. ${r.message}`);return e.stack=r.stack,e.cause=r,e}return Error(`${n}. ${String(r)}`)}getBodyPreview(e,t){let i;if(0===e.length)return;let r=e.length>1024,n=r?e.slice(0,1024):e;if(this.isTextualContent(t,n))try{i=ts(n)}catch{i=this.formatBinaryPreview(n,r)}else i=this.formatBinaryPreview(n,r);return i.length>512&&(i=`${i.slice(0,512)}…`),r&&(i=`${i} (truncated)`),i}isTextualContent(e,t){if(0===t.length)return!1;if(null!=e){let t=e.toLowerCase();if(["application/json","application/problem+json","application/xml","application/xhtml+xml","application/javascript","application/ecmascript","application/x-www-form-urlencoded","text/"].some(e=>t.includes(e))||t.includes("charset="))return!0}return t.reduce((e,t)=>9===t||10===t||13===t||t>=32&&t<=126?e+1:e,0)/t.length>.8}formatBinaryPreview(e,t){let i=e.map(e=>e.toString(16).padStart(2,"0")).join("");return`0x${i}${t?"…":""}`}deserializeRequestPayload(e){let t,i=new tg(e),r=tc(i.read(32)),n=i.readVarIntNum(),a="GET";n>0&&(a=ts(i.read(n)));let s=i.readVarIntNum(),o="";s>0&&(o=ts(i.read(s)));let c=i.readVarIntNum(),l="";c>0&&(l=ts(i.read(c)));let h={},d=i.readVarIntNum();if(d>0)for(let e=0;e<d;e++){let e=i.readVarIntNum(),t=ts(i.read(e)),r=i.readVarIntNum(),n=ts(i.read(r));h[t]=n}let u=i.readVarIntNum();return u>0&&(t=i.read(u)),{urlPostfix:o+l,method:a,headers:h,body:t,requestId:r}}}class nD{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;originator;peers={};constructor(e,t,i,r){this.wallet=e,this.requestedCertificates=t,this.sessionManager=i??new nN,this.originator=r}async fetch(e,t={}){if("number"==typeof t.retryCounter){if(t.retryCounter<=0)throw Error("Request failed after maximum number of retries.");t.retryCounter--}let i=await new Promise(async(i,r)=>{try{let n,{method:a="GET",headers:s={},body:o}=t,c=new URL(e),l=c.origin;if(void 0===this.peers[l]){let e=new nV(l);n={peer:new nB(this.wallet,e,this.requestedCertificates,this.sessionManager,void 0,this.originator),pendingCertificateRequests:[]},this.peers[l]=n,this.peers[l].peer.listenForCertificatesReceived((e,t)=>{this.certificatesReceived.push(...t)}),this.peers[l].peer.listenForCertificatesRequested(async(e,t)=>{try{this.peers[l].pendingCertificateRequests.push(!0);let i=await n_(this.wallet,t,e,this.originator);await this.peers[l].peer.sendCertificateResponse(e,i)}finally{await new Promise(e=>setTimeout(e,500)),this.peers[l].pendingCertificateRequests.shift()}})}else{if(!1===this.peers[l].supportsMutualAuth){try{let r=await this.handleFetchAndValidate(e,t,this.peers[l]);i(r)}catch(e){r(e)}return}n=this.peers[l]}let h=t0(32),d=tc(h),u=await this.serializeRequest(a,s,o,c,h);this.callbacks[d]={resolve:i,reject:r};let f=n.peer.listenForGeneralMessages((e,t)=>{let i,r=new tg(t);if(tc(r.read(32))!==d)return;n.peer.stopListeningForGeneralMessages(f),this.peers[l].identityKey=e,this.peers[l].supportsMutualAuth=!0;let a=r.readVarIntNum(),s={},o=r.readVarIntNum();if(o>0)for(let e=0;e<o;e++){let e=r.readVarIntNum(),t=r.read(e),i=ts(t),n=r.readVarIntNum(),a=r.read(n),o=ts(a);s[i]=o}s["x-bsv-auth-identity-key"]=e;let c=r.readVarIntNum();c>0&&(i=r.read(c));let h=new Response(i?new Uint8Array(i):null,{status:a,statusText:`${a}`,headers:new Headers(s)});this.callbacks[d].resolve(h),delete this.callbacks[d]});n.pendingCertificateRequests.length>0&&await new Promise((e,t)=>{let i=Date.now(),r=()=>{0===n.pendingCertificateRequests.length?e():Date.now()-i>3e4?t(Error("Timeout waiting for certificate request to complete")):setTimeout(r,100)};r()}),await n.peer.toPeer(u.toArray(),n.identityKey).catch(async a=>{if(a.message.includes("Session not found for nonce")){delete this.peers[l],t.retryCounter??=3;let r=await this.fetch(e,t);i(r);return}if(a.message.includes("HTTP server failed to authenticate"))try{let r=await this.handleFetchAndValidate(e,t,n);i(r);return}catch(e){r(e)}else r(a)})}catch(e){r(e)}});return 402===i.status?await this.handlePaymentAndRetry(e,t,i):i}async sendCertificateRequest(e,t){let i,r=new URL(e).origin;if(void 0!==this.peers[r])i={peer:this.peers[r].peer};else{let e=new nV(r);i={peer:new nB(this.wallet,e,this.requestedCertificates,this.sessionManager,this.originator)},this.peers[r]=i}return await new Promise(async(e,r)=>{let 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,i,r,n){let a=new tp;if(a.write(n),a.writeVarIntNum(e.length),a.write(ti(e)),r.pathname.length>0){let e=ti(r.pathname);a.writeVarIntNum(e.length),a.write(e)}else a.writeVarIntNum(-1);if(r.search.length>0){let e=ti(r.search);a.writeVarIntNum(e.length),a.write(e)}else a.writeVarIntNum(-1);let s=[];for(let[e,i]of Object.entries(t))if((e=e.toLowerCase()).startsWith("x-bsv-")||"authorization"===e){if(e.startsWith("x-bsv-auth"))throw Error("No BSV auth headers allowed here!");s.push([e,i])}else if(e.startsWith("content-type"))i=i.split(";")[0].trim(),s.push([e,i]);else throw Error("Unsupported header in the simplified fetch implementation. Only content-type, authorization, and x-bsv-* headers are supported.");s.sort(([e],[t])=>e.localeCompare(t)),a.writeVarIntNum(s.length);for(let e=0;e<s.length;e++){let t=ti(s[e][0],"utf8");a.writeVarIntNum(t.length),a.write(t);let i=ti(s[e][1],"utf8");a.writeVarIntNum(i.length),a.write(i)}if(["POST","PUT","PATCH","DELETE"].includes(e.toUpperCase())&&void 0===i){let e=s.find(([e])=>"content-type"===e);i=e&&e[1].includes("application/json")?"{}":""}if(i){let e=await this.normalizeBodyToNumberArray(i);a.writeVarIntNum(e.length),a.write(e)}else a.writeVarIntNum(-1);return a}async handleFetchAndValidate(e,t,i){let r=await fetch(e,t);if(r.headers.forEach(e=>{if(e.toLocaleLowerCase().startsWith("x-bsv"))throw Error("The server is trying to claim it has been authenticated when it has not!")}),r.ok)return i.supportsMutualAuth=!1,r;throw Error(`Request failed with status: ${r.status}`)}async handlePaymentAndRetry(e,t={},i){let r=i.headers.get("x-bsv-payment-version");if(!r||"1.0"!==r)throw Error(`Unsupported x-bsv-payment-version response header. Client version: 1.0, Server version: ${r}`);let n=i.headers.get("x-bsv-payment-satoshis-required");if(!n)throw Error("Missing x-bsv-payment-satoshis-required response header.");let a=parseInt(n);if(isNaN(a)||a<=0)throw Error("Invalid x-bsv-payment-satoshis-required response header value.");let s=i.headers.get("x-bsv-auth-identity-key");if("string"!=typeof s)throw Error("Missing x-bsv-auth-identity-key response header.");let o=i.headers.get("x-bsv-payment-derivation-prefix");if("string"!=typeof o||o.length<1)throw Error("Missing x-bsv-payment-derivation-prefix response header.");let c=t.paymentContext;if(null!=c?this.isPaymentContextCompatible(c,a,s,o)||(this.logPaymentAttempt("warn","Server adjusted payment requirements; regenerating transaction",this.composePaymentLogDetails(e,c)),c=await this.createPaymentContext(e,t,a,s,o)):c=await this.createPaymentContext(e,t,a,s,o),c.attempts>=c.maxAttempts)throw this.buildPaymentFailureError(e,c,Error("Maximum payment attempts exceeded before retrying"));let l={...t.headers??{}};l["x-bsv-payment"]=JSON.stringify({derivationPrefix:c.derivationPrefix,derivationSuffix:c.derivationSuffix,transaction:c.transactionBase64});let h={...t,headers:l,paymentContext:c};"number"!=typeof h.retryCounter&&(h.retryCounter=3);let d=c.attempts+1,u=c.maxAttempts;c.attempts=d;let f=this.composePaymentLogDetails(e,c);this.logPaymentAttempt("warn",`Attempting paid request (${d}/${u})`,f);try{let t=await this.fetch(e,h);return this.logPaymentAttempt("info",`Paid request attempt ${d} succeeded`,f),t}catch(n){let t=this.createPaymentErrorEntry(c.attempts,n);if(c.errors.push(t),this.logPaymentAttempt("error",`Paid request attempt ${d} failed`,{...f,error:{message:t.message,stack:t.stack}}),c.attempts>=c.maxAttempts)throw this.buildPaymentFailureError(e,c,n);let r=this.getPaymentRetryDelay(c.attempts);return await this.wait(r),this.handlePaymentAndRetry(e,h,i)}}isPaymentContextCompatible(e,t,i,r){return e.satoshisRequired===t&&e.serverIdentityKey===i&&e.derivationPrefix===r}async createPaymentContext(e,t,i,r,n){let a=await nT(this.wallet,void 0,this.originator),{publicKey:s}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${n} ${a}`,counterparty:r},this.originator),o=new iL().lock(tJ.fromString(s).toAddress()).toHex(),{tx:c}=await this.wallet.createAction({description:`Payment for request to ${new URL(e).origin}`,outputs:[{satoshis:i,lockingScript:o,customInstructions:JSON.stringify({derivationPrefix:n,derivationSuffix:a,payee:r}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}},this.originator),{publicKey:l}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return{satoshisRequired:i,transactionBase64:tc(c),derivationPrefix:n,derivationSuffix:a,serverIdentityKey:r,clientIdentityKey:l,attempts:0,maxAttempts:this.getMaxPaymentAttempts(t),errors:[],requestSummary:this.buildPaymentRequestSummary(e,t)}}getMaxPaymentAttempts(e){let t="number"==typeof e.paymentRetryAttempts?e.paymentRetryAttempts:void 0;return"number"==typeof t&&t>0?Math.floor(t):3}buildPaymentRequestSummary(e,t){let i={...t.headers??{}},r="string"==typeof t.method?t.method.toUpperCase():"GET",n=this.describeRequestBodyForLogging(t.body);return{url:e,method:r,headers:i,bodyType:n.type,bodyByteLength:n.byteLength}}describeRequestBodyForLogging(e){if(null==e)return{type:"none",byteLength:0};if("string"==typeof e)return{type:"string",byteLength:ti(e,"utf8").length};if(Array.isArray(e))return e.every(e=>"number"==typeof e)?{type:"number[]",byteLength:e.length}:{type:"array",byteLength:e.length};if("u">typeof ArrayBuffer&&e instanceof ArrayBuffer)return{type:"ArrayBuffer",byteLength:e.byteLength};if("u">typeof ArrayBuffer&&ArrayBuffer.isView(e))return{type:null!=e.constructor?e.constructor.name:"TypedArray",byteLength:e.byteLength};if("u">typeof Blob&&e instanceof Blob)return{type:"Blob",byteLength:e.size};if("u">typeof FormData&&e instanceof FormData)return{type:"FormData",byteLength:0};if("u">typeof URLSearchParams&&e instanceof URLSearchParams)return{type:"URLSearchParams",byteLength:ti(e.toString(),"utf8").length};if("u">typeof ReadableStream&&e instanceof ReadableStream)return{type:"ReadableStream",byteLength:0};try{let t=JSON.stringify(e);if("string"==typeof t)return{type:"object",byteLength:ti(t,"utf8").length}}catch(e){}return{type:typeof e,byteLength:0}}composePaymentLogDetails(e,t){return{url:e,request:t.requestSummary,payment:{satoshis:t.satoshisRequired,transactionBase64:t.transactionBase64,derivationPrefix:t.derivationPrefix,derivationSuffix:t.derivationSuffix,serverIdentityKey:t.serverIdentityKey,clientIdentityKey:t.clientIdentityKey},attempts:{used:t.attempts,max:t.maxAttempts},errors:t.errors}}logPaymentAttempt(e,t,i){let r="[AuthFetch][Payment]";"error"===e?console.error(`${r} ${t}`,i):"warn"===e?console.warn(`${r} ${t}`,i):"function"==typeof console.info?console.info(`${r} ${t}`,i):console.log(`${r} ${t}`,i)}createPaymentErrorEntry(e,t){let i={attempt:e,timestamp:new Date().toISOString(),message:"",stack:void 0};return t instanceof Error?(i.message=t.message,i.stack=t.stack??void 0):i.message=String(t),i}getPaymentRetryDelay(e){return 250*Math.min(e,5)}async wait(e){e<=0||await new Promise(t=>setTimeout(t,e))}buildPaymentFailureError(e,t,i){let r=Error(`Paid request to ${e} failed after ${t.attempts}/${t.maxAttempts} attempts. Sent ${t.satoshisRequired} satoshis to ${t.serverIdentityKey}.`);return r.details={request:t.requestSummary,payment:{satoshis:t.satoshisRequired,transactionBase64:t.transactionBase64,derivationPrefix:t.derivationPrefix,derivationSuffix:t.derivationSuffix,serverIdentityKey:t.serverIdentityKey,clientIdentityKey:t.clientIdentityKey},attempts:{used:t.attempts,max:t.maxAttempts},errors:t.errors},i instanceof Error&&(r.cause=i),r}async normalizeBodyToNumberArray(e){if(null==e)return[];if("object"==typeof e)return ti(JSON.stringify(e,"utf8"));if(Array.isArray(e)&&e.every(e=>"number"==typeof e))return e;if("string"==typeof e)return ti(e,"utf8");if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Array.from(new Uint8Array(e instanceof ArrayBuffer?e:e.buffer));if(e instanceof Blob)return Array.from(new Uint8Array(await e.arrayBuffer()));if(e instanceof FormData){let t=[];return e.forEach((e,i)=>{t.push([i,e.toString()])}),ti(new URLSearchParams(t).toString(),"utf8")}if(e instanceof URLSearchParams)return ti(e.toString(),"utf8");if(e instanceof ReadableStream)throw Error("ReadableStream cannot be directly converted to number[].");throw Error("Unsupported body type in this SimplifiedFetch implementation.")}}class nL{pushDrop;static decode(e){let t=iK.decode(e);if(t.fields.length<4)throw Error("Invalid SHIP/SLAP advertisement!");let i=ts(t.fields[0]);if("SHIP"!==i&&"SLAP"!==i)throw Error("Invalid protocol type!");let r=te(t.fields[1]);return{protocol:i,identityKey:r,domain:ts(t.fields[2]),topicOrService:ts(t.fields[3])}}constructor(e,t){this.pushDrop=new iK(e,t)}async lock(e,t,i){let{publicKey:r}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([ti(e,"utf8"),ti(r,"hex"),ti(t,"utf8"),ti(i,"utf8")],[2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}unlock(e){return this.pushDrop.unlock([2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}}let nF="bsvsdk_overlay_host_reputation_v1";class nH{stats;store;constructor(e){this.stats=new Map,this.store=e??this.getLocalStorageAdapter(),this.loadFromStorage()}reset(){this.stats.clear()}recordSuccess(e,t){let i=this.getOrCreate(e),r=Date.now(),n=Number.isFinite(t)&&t>=0?t:1500;null===i.avgLatencyMs?i.avgLatencyMs=n:i.avgLatencyMs=.75*i.avgLatencyMs+.25*n,i.lastLatencyMs=n,i.totalSuccesses+=1,i.consecutiveFailures=0,i.backoffUntil=0,i.lastUpdatedAt=r,i.lastError=void 0,this.saveToStorage()}recordFailure(e,t){let i=this.getOrCreate(e),r=Date.now();i.totalFailures+=1,i.consecutiveFailures+=1;let n="string"==typeof t?t:t instanceof Error?t.message:void 0;"string"==typeof n&&(n.includes("ERR_NAME_NOT_RESOLVED")||n.includes("ENOTFOUND")||n.includes("getaddrinfo")||n.includes("Failed to fetch"))&&i.consecutiveFailures<3&&(i.consecutiveFailures=3);let a=Math.max(i.consecutiveFailures-2,0);0===a?i.backoffUntil=0:i.backoffUntil=r+Math.min(6e4,1e3*Math.pow(2,a-1)),i.lastUpdatedAt=r,i.lastError="string"==typeof t?t:t instanceof Error?t.message:void 0,this.saveToStorage()}rankHosts(e,t=Date.now()){let i=new Map;e.forEach((e,t)=>{"string"==typeof e&&0!==e.length&&(i.has(e)||i.set(e,t))});let r=Array.from(i.keys()).map(e=>{let r=this.getOrCreate(e);return{...r,score:this.computeScore(r,t),originalOrder:i.get(e)??0}});return r.sort((e,i)=>{let r=e.backoffUntil>t;return r!==i.backoffUntil>t?r?1:-1:e.score!==i.score?e.score-i.score:e.totalSuccesses!==i.totalSuccesses?i.totalSuccesses-e.totalSuccesses:e.originalOrder-i.originalOrder}),r.map(({originalOrder:e,...t})=>t)}snapshot(e){let t=this.stats.get(e);return null!=t?{...t}:void 0}getStorage(){try{let e="object"==typeof globalThis?globalThis:void 0;if(null==e||null==e.localStorage)return;return e.localStorage}catch{return}}getLocalStorageAdapter(){let e=this.getStorage();if(null!=e)return{get:t=>{try{return e.getItem(t)}catch{return null}},set:(t,i)=>{try{e.setItem(t,i)}catch{}}}}loadFromStorage(){let e=this.store;if(null!=e)try{let t=e.get(nF);if("string"!=typeof t||0===t.length)return;let i=JSON.parse(t);if("object"!=typeof i||null===i)return;for(let e of(this.stats.clear(),Object.keys(i))){let t=i[e];if(null!=t&&"object"==typeof t){let i={host:String(t.host??e),totalSuccesses:Number(t.totalSuccesses??0),totalFailures:Number(t.totalFailures??0),consecutiveFailures:Number(t.consecutiveFailures??0),avgLatencyMs:null==t.avgLatencyMs?null:Number(t.avgLatencyMs),lastLatencyMs:null==t.lastLatencyMs?null:Number(t.lastLatencyMs),backoffUntil:Number(t.backoffUntil??0),lastUpdatedAt:Number(t.lastUpdatedAt??0),lastError:"string"==typeof t.lastError?t.lastError:void 0};this.stats.set(i.host,i)}}}catch{}}saveToStorage(){let e=this.store;if(null!=e)try{let t={};for(let[e,i]of this.stats.entries())t[e]=i;e.set(nF,JSON.stringify(t))}catch{}}computeScore(e,t){let i=e.avgLatencyMs??1500,r=400*e.consecutiveFailures,n=Math.min(30*e.totalSuccesses,i/2);return i+r+(e.backoffUntil>t?e.backoffUntil-t:0)-n}getOrCreate(e){let t=this.stats.get(e);return null==t&&(t={host:e,totalSuccesses:0,totalFailures:0,consecutiveFailures:0,avgLatencyMs:null,lastLatencyMs:null,backoffUntil:0,lastUpdatedAt:0},this.stats.set(e,t)),t}}let nK=new nH,nM="u">typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch,nq=["https://overlay-us-1.bsvb.tech","https://overlay-eu-1.bsvb.tech","https://overlay-ap-1.bsvb.tech","https://users.bapp.dev"],n$=["https://testnet-users.bapp.dev"];class nz{fetchClient;allowHTTP;constructor(e=nM,t=!1){if("function"!=typeof e)throw Error("HTTPSOverlayLookupFacilitator requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=e,this.allowHTTP=t}async lookup(e,t,i=5e3){if(!e.startsWith("https:")&&!this.allowHTTP)throw Error('HTTPS facilitator can only use URLs that start with "https:"');let r="u">typeof AbortController?new AbortController:void 0,n=setTimeout(()=>{try{r?.abort()}catch{}},i);try{let i={method:"POST",headers:{"Content-Type":"application/json","X-Aggregation":"yes"},body:JSON.stringify({service:t.service,query:t.query}),signal:r?.signal},n=await this.fetchClient(`${e}/lookup`,i);if(!n.ok)throw Error(`Failed to facilitate lookup (HTTP ${n.status})`);if("application/octet-stream"!==n.headers.get("content-type"))return await n.json();{let e=await n.arrayBuffer(),t=new tg([...new Uint8Array(e)]),i=t.readVarIntNum(),r=[];for(let e=0;e<i;e++){let e,i=te(t.read(32)),n=t.readVarIntNum(),a=t.readVarIntNum();a>0&&(e=t.read(a)),r.push({txid:i,outputIndex:n,context:e})}let a=t.read();return{type:"output-list",outputs:r.map(e=>({outputIndex:e.outputIndex,context:e.context,beef:i3.fromBEEF(a,e.txid).toBEEF()}))}}}catch(e){if(e?.name==="AbortError")throw Error("Request timed out");throw e}finally{clearTimeout(n)}}}class nW{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;hostReputation;hostsCache;hostsInFlight;hostsTtlMs;hostsMaxEntries;txMemo;txMemoTtlMs;constructor(e={}){this.networkPreset=e.networkPreset??"mainnet",this.facilitator=e.facilitator??new nz(void 0,"local"===this.networkPreset),this.slapTrackers=e.slapTrackers??("mainnet"===this.networkPreset?nq:n$);const t=e.hostOverrides??{};this.assertValidOverrideServices(t),this.hostOverrides=t,this.additionalHosts=e.additionalHosts??{};const i=e.reputationStorage;"localStorage"===i?this.hostReputation=new nH:"object"==typeof i&&null!==i&&"function"==typeof i.get&&"function"==typeof i.set?this.hostReputation=new nH(i):this.hostReputation=nK,this.hostsTtlMs=e.cache?.hostsTtlMs??3e5,this.hostsMaxEntries=e.cache?.hostsMaxEntries??128,this.txMemoTtlMs=e.cache?.txMemoTtlMs??6e5,this.hostsCache=new Map,this.hostsInFlight=new Map,this.txMemo=new Map}async query(e,t){let i=[];if(i="ls_slap"===e.service?"local"===this.networkPreset?["http://localhost:8080"]:this.slapTrackers:null!=this.hostOverrides[e.service]?this.hostOverrides[e.service]:"local"===this.networkPreset?["http://localhost:8080"]:await this.getCompetentHostsCached(e.service),this.additionalHosts[e.service]?.length>0){let t=this.additionalHosts[e.service],r=new Set(i);for(let e of t)r.has(e)||i.push(e)}if(i.length<1)throw Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${e.service}`);let r=this.prepareHostsForQuery(i,`lookup service ${e.service}`);if(r.length<1)throw Error(`All competent hosts for ${e.service} are temporarily unavailable due to backoff.`);let n=await new Promise(i=>{let n=[],a=r.length,s=null,o=()=>{null!==s&&clearTimeout(s),i(n)};for(let i of r)this.lookupHostWithTracking(i,e,t).then(e=>{e?.type==="output-list"&&Array.isArray(e.outputs)&&e.outputs.length>0&&(n.push(e),1===n.length&&a>1&&(s=setTimeout(o,200)))}).catch(()=>{}).finally(()=>{0==--a&&o()})}),a=new Map,s=e=>"object"!=typeof e?"":e.join(",");for(let e of n)for(let t of e.outputs){let e=s(t.beef),i=this.txMemo.get(e),r=Date.now();if("object"!=typeof i||null===i||i.expiresAt<=r)try{i={txId:i3.fromBEEF(t.beef).id("hex"),expiresAt:r+this.txMemoTtlMs},this.txMemo.size>4096&&this.evictOldest(this.txMemo),this.txMemo.set(e,i)}catch{continue}let n=`${i.txId}.${t.outputIndex}`;a.set(n,t)}return{type:"output-list",outputs:Array.from(a.values())}}async getCompetentHostsCached(e){let t=Date.now(),i=this.hostsCache.get(e);if("object"==typeof i&&i.expiresAt>t)return i.hosts.slice();if("object"==typeof i&&i.expiresAt<=t)return this.hostsInFlight.has(e)||this.hostsInFlight.set(e,this.refreshHosts(e).finally(()=>{this.hostsInFlight.delete(e)})),i.hosts.slice();if(this.hostsInFlight.has(e))try{let t=await this.hostsInFlight.get(e);if("object"!=typeof t)throw Error("Hosts is not defined.");return t.slice()}catch{}let r=this.refreshHosts(e).finally(()=>{this.hostsInFlight.delete(e)});return this.hostsInFlight.set(e,r),(await r).slice()}async refreshHosts(e){let t=await this.findCompetentHosts(e),i=Date.now()+this.hostsTtlMs;if(!this.hostsCache.has(e)&&this.hostsCache.size>=this.hostsMaxEntries){let e=this.hostsCache.keys().next().value;void 0!==e&&this.hostsCache.delete(e)}return this.hostsCache.set(e,{hosts:t,expiresAt:i}),t}extractHostsFromAnswer(e,t){let i=[];if("output-list"!==e.type)return i;for(let r of e.outputs)try{let e=i3.fromBEEF(r.beef),n=e.outputs[r.outputIndex]?.lockingScript;if("object"!=typeof n||null===n)continue;let a=nL.decode(n);if(a.topicOrService!==t||"SLAP"!==a.protocol)continue;"string"==typeof a.domain&&a.domain.length>0&&i.push(a.domain)}catch{continue}return i}async findCompetentHosts(e){let t={service:"ls_slap",query:{service:e}},i=this.prepareHostsForQuery(this.slapTrackers,"SLAP trackers");return 0===i.length?[]:await new Promise(r=>{let n=new Set,a=!1,s=i.length;for(let o of i)this.lookupHostWithTracking(o,t,5e3).then(t=>{for(let i of this.extractHostsFromAnswer(t,e))n.add(i);!a&&n.size>0&&(a=!0,r([...n]))}).catch(()=>{}).finally(()=>{0!=--s||a||(a=!0,r([...n]))})})}evictOldest(e){let t=e.keys().next().value;void 0!==t&&e.delete(t)}assertValidOverrideServices(e){for(let t of Object.keys(e))if(!t.startsWith("ls_"))throw Error(`Host override service names must start with "ls_": ${t}`)}prepareHostsForQuery(e,t){if(0===e.length)return[];let i=Date.now(),r=this.hostReputation.rankHosts(e,i),n=r.filter(e=>e.backoffUntil<=i).map(e=>e.host);if(n.length>0)return n;let a=Math.max(Math.min(...r.map(e=>e.backoffUntil))-i,0);throw Error(`All ${t} hosts are backing off for approximately ${a}ms due to repeated failures.`)}async lookupHostWithTracking(e,t,i){let r=Date.now();try{let n=await this.facilitator.lookup(e,t,i),a=Date.now()-r;return"object"==typeof n&&null!==n&&"output-list"===n.type&&Array.isArray(n.outputs)?this.hostReputation.recordSuccess(e,a):this.hostReputation.recordFailure(e,"Invalid lookup response"),n}catch(t){throw this.hostReputation.recordFailure(e,t),t}}}class nj{httpClient;allowHTTP;constructor(e=fetch,t=!1){this.httpClient=e,this.allowHTTP=t}async send(e,t){let i;if(!e.startsWith("https:")&&!this.allowHTTP)throw Error('HTTPS facilitator can only use URLs that start with "https:"');let r={"Content-Type":"application/octet-stream","X-Topics":JSON.stringify(t.topics)};if(Array.isArray(t.offChainValues)){r["x-includes-off-chain-values"]="true";let e=new tp;e.writeVarIntNum(t.beef.length),e.write(t.beef),e.write(t.offChainValues),i=new Uint8Array(e.toArray())}else i=new Uint8Array(t.beef);let n=await fetch(`${e}/submit`,{method:"POST",headers:r,body:i});if(n.ok)return await n.json();throw Error("Failed to facilitate broadcast")}}class nX{topics;facilitator;resolver;requireAcknowledgmentFromAllHostsForTopics;requireAcknowledgmentFromAnyHostForTopics;requireAcknowledgmentFromSpecificHostsForTopics;networkPreset;interestedHostsCache=null;interestedHostsInFlight=null;interestedHostsTtlMs;constructor(e,t={}){if(0===e.length)throw Error("At least one topic is required for broadcast.");if(e.some(e=>!e.startsWith("tm_")))throw Error('Every topic must start with "tm_".');this.topics=e,this.networkPreset=t.networkPreset??"mainnet",this.facilitator=t.facilitator??new nj(void 0,"local"===this.networkPreset),this.resolver=t.resolver??new nW({networkPreset:this.networkPreset}),this.requireAcknowledgmentFromAllHostsForTopics=t.requireAcknowledgmentFromAllHostsForTopics??[],this.requireAcknowledgmentFromAnyHostForTopics=t.requireAcknowledgmentFromAnyHostForTopics??"all",this.requireAcknowledgmentFromSpecificHostsForTopics=t.requireAcknowledgmentFromSpecificHostsForTopics??{},this.interestedHostsTtlMs=3e5}async broadcast(e){let t,i,r,n,a,s=e.metadata.get("OffChainValues");try{t=e.toBEEF()}catch(e){throw Error("Transactions sent via SHIP to Overlay Services must be serializable to BEEF format.")}let o=await this.findInterestedHosts();if(0===Object.keys(o).length)return{status:"error",code:"ERR_NO_HOSTS_INTERESTED",description:`No ${this.networkPreset} hosts are interested in receiving this transaction.`};let c=Object.entries(o).map(async([e,i])=>{try{let r=await this.facilitator.send(e,{beef:t,offChainValues:s,topics:[...i]});if(null==r||0===Object.keys(r).length)throw Error("Steak has no topics.");return{host:e,success:!0,steak:r}}catch(t){return console.error(t),{host:e,success:!1,error:t}}}),l=(await Promise.all(c)).filter(e=>e.success);if(0===l.length)return{status:"error",code:"ERR_ALL_HOSTS_REJECTED",description:`All ${this.networkPreset} topical hosts have rejected the transaction.`};let h={};for(let e of l){let t=e.host,i=e.steak,r=new Set;for(let[e,t]of Object.entries(i)){let i=t.outputsToAdmit,n=t.coinsToRetain,a=t.coinsRemoved;(i?.length>0||n?.length>0||a?.length>0)&&r.add(e)}h[t]=r}return("all"===this.requireAcknowledgmentFromAllHostsForTopics?(i=this.topics,r="all"):"any"===this.requireAcknowledgmentFromAllHostsForTopics?(i=this.topics,r="any"):(i=Array.isArray(this.requireAcknowledgmentFromAllHostsForTopics)?this.requireAcknowledgmentFromAllHostsForTopics:this.topics,r="all"),i.length>0&&!this.checkAcknowledgmentFromAllHosts(h,i,r))?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ALL_HOSTS_FAILED",description:"Not all hosts acknowledged the required topics."}:("all"===this.requireAcknowledgmentFromAnyHostForTopics?(n=this.topics,a="all"):"any"===this.requireAcknowledgmentFromAnyHostForTopics?(n=this.topics,a="any"):(n=Array.isArray(this.requireAcknowledgmentFromAnyHostForTopics)?this.requireAcknowledgmentFromAnyHostForTopics:[],a="all"),n.length>0&&!this.checkAcknowledgmentFromAnyHost(h,n,a))?{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(h,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 ${l.length} Overlay Services ${1===l.length?"host":"hosts"}.`}}checkAcknowledgmentFromAllHosts(e,t,i){for(let r of Object.values(e))if("all"===i){for(let e of t)if(!r.has(e))return!1}else if("any"===i){let e=!1;for(let i of t)if(r.has(i)){e=!0;break}if(!e)return!1}return!0}checkAcknowledgmentFromAnyHost(e,t,i){if("all"===i){for(let i of Object.values(e)){let e=!0;for(let r of t)if(!i.has(r)){e=!1;break}if(e)return!0}return!1}for(let i of Object.values(e))for(let e of t)if(i.has(e))return!0;return!1}checkAcknowledgmentFromSpecificHosts(e,t){for(let[i,r]of Object.entries(t)){let t,n,a=e[i];if(null==a)return!1;if("all"===r||"any"===r)n=r,t=this.topics;else{if(!Array.isArray(r))continue;t=r,n="all"}if("all"===n){for(let e of t)if(!a.has(e))return!1}else if("any"===n){let e=!1;for(let i of t)if(a.has(i)){e=!0;break}if(!e)return!1}}return!0}async findInterestedHosts(){if("local"===this.networkPreset){let e=new Set;for(let t=0;t<this.topics.length;t++)e.add(this.topics[t]);return{"http://localhost:8080":e}}let e=Date.now();if(null!=this.interestedHostsCache&&this.interestedHostsCache.expiresAt>e)return this.interestedHostsCache.hosts;if(null!=this.interestedHostsInFlight)return await this.interestedHostsInFlight;this.interestedHostsInFlight=this.fetchInterestedHosts();try{let e=await this.interestedHostsInFlight;return this.interestedHostsCache={hosts:e,expiresAt:Date.now()+this.interestedHostsTtlMs},e}finally{this.interestedHostsInFlight=null}}async fetchInterestedHosts(){let e={},t=await this.resolver.query({service:"ls_ship",query:{topics:this.topics}},5e3);if("output-list"!==t.type)throw Error("SHIP answer is not an output list.");for(let i of t.outputs)try{let t=i3.fromBEEF(i.beef).outputs[i.outputIndex].lockingScript,r=nL.decode(t);if(!this.topics.includes(r.topicOrService)||"SHIP"!==r.protocol)continue;void 0===e[r.domain]&&(e[r.domain]=new Set),e[r.domain].add(r.topicOrService)}catch(e){continue}return e}}async function nG(e,t,i=5){let r=0;for(;r<i;){r++;try{return await e()}catch(e){if(r<i&&"WERR_REVIEW_ACTIONS"===e.name){let n=e.reviewActionResults.find(e=>"doubleSpend"===e.status);if(n?.competingBeef!=null&&n?.competingTxs!=null&&n?.competingTxs.length>0){let e=i3.fromBEEF(n.competingBeef,n.competingTxs[0]);await nG(async()=>await t.broadcast(e),t,i-r);continue}}throw e}}throw Error("Unexpected end of retry loop")}let nY=e=>(e.toLowerCase().startsWith("uhrp:")&&(e=e.slice(5)),e.startsWith("//")&&(e=e.slice(2)),e),nJ=e=>{if(32!==e.length)throw Error("Hash length must be 32 bytes (sha256)");return tu(e,ti("ce00","hex"))},nZ=e=>{let t=e instanceof Uint8Array?e:Uint8Array.from(e),i=new J;for(let e=0;e<t.length;e+=1048576){let r=t.subarray(e,e+1048576);i.update(Array.from(r))}return nJ(i.digest())},nQ=e=>{let{data:t,prefix:i}=tf(e=nY(e),void 0,2);if(32!==t.length)throw Error("Invalid length!");if("ce00"!==te(i))throw Error("Bad prefix");return t},n0=e=>{try{return nQ(e),!0}catch(e){return!1}};class n1{authFetch;baseURL;constructor(e){this.baseURL=e.storageURL,this.authFetch=new nD(e.wallet)}async getUploadInfo(e,t){let i=`${this.baseURL}/upload`,r=await this.authFetch.fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileSize:e,retentionPeriod:t})});if(!r.ok)throw Error(`Upload info request failed: HTTP ${r.status}`);let n=await r.json();if("error"===n.status)throw Error("Upload route returned an error.");return{uploadURL:n.uploadURL,requiredHeaders:n.requiredHeaders,amount:n.amount}}async uploadFile(e,t,i){let r=t.data instanceof Uint8Array?t.data:Uint8Array.from(t.data),n=await fetch(e,{method:"PUT",body:r,headers:{"Content-Type":t.type,...i}});if(!n.ok)throw Error(`File upload failed: HTTP ${n.status}`);return{published:!0,uhrpURL:nZ(r)}}async publishFile(e){let{file:t,retentionPeriod:i}=e,r=t.data instanceof Uint8Array?t.data:Uint8Array.from(t.data),n=r.byteLength,{uploadURL:a,requiredHeaders:s}=await this.getUploadInfo(n,i);return await this.uploadFile(a,{data:r,type:t.type},s)}async findFile(e){let t=new URL(`${this.baseURL}/find`);t.searchParams.set("uhrpUrl",e);let i=await this.authFetch.fetch(t.toString(),{method:"GET"});if(!i.ok)throw Error(`findFile request failed: HTTP ${i.status}`);let r=await i.json();if("error"===r.status){let e=r.code??"unknown-code",t=r.description??"no-description";throw Error(`findFile returned an error: ${e} - ${t}`)}return r.data}async listUploads(){let e=`${this.baseURL}/list`,t=await this.authFetch.fetch(e,{method:"GET"});if(!t.ok)throw Error(`listUploads request failed: HTTP ${t.status}`);let i=await t.json();if("error"===i.status){let e=i.code??"unknown-code",t=i.description??"no-description";throw Error(`listUploads returned an error: ${e} - ${t}`)}return i.uploads}async renewFile(e,t){let i=`${this.baseURL}/renew`,r=await this.authFetch.fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({uhrpUrl:e,additionalMinutes:t})});if(!r.ok)throw Error(`renewFile request failed: HTTP ${r.status}`);let n=await r.json();if("error"===n.status){let e=n.code??"unknown-code",t=n.description??"no-description";throw Error(`renewFile returned an error: ${e} - ${t}`)}return{status:n.status,prevExpiryTime:n.prevExpiryTime,newExpiryTime:n.newExpiryTime,amount:n.amount}}}class n2{networkPreset="mainnet";lookupResolver;constructor(e){this.networkPreset=e?.networkPreset??"mainnet",this.lookupResolver=new nW({networkPreset:this.networkPreset})}async resolve(e){let t=await this.lookupResolver.query({service:"ls_uhrp",query:{uhrpUrl:e}});if("output-list"!==t.type)throw Error("Lookup answer must be an output list");let i=[],r=Math.floor(Date.now()/1e3);for(let e=0;e<t.outputs.length;e++){let n=i3.fromBEEF(t.outputs[e].beef),{fields:a}=iK.decode(n.outputs[t.outputs[e].outputIndex].lockingScript);new tg(a[3]).readVarIntNum()<r||i.push(ts(a[2]))}return i}async download(e){if(!n0(e))throw Error("Invalid parameter UHRP url");let t=te(nQ(e)),i=await this.resolve(e);if(!Array.isArray(i)||0===i.length)throw Error("No one currently hosts this file!");for(let e=0;e<i.length;e++)try{let r=await fetch(i[e],{method:"GET"});if(!r.ok||r.status>=400||null==r.body)continue;let n=r.body.getReader(),a=new J,s=[],o=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;a.update(Array.from(t)),s.push(t),o+=t.length}if(te(a.digest())!==t)throw Error("Data integrity error: value of content does not match hash of the url given");let c=new Uint8Array(o),l=0;for(let e of s)c.set(e,l),l+=e.length;return{data:c,mimeType:r.headers.get("Content-Type")}}catch(e){continue}throw Error(`Unable to download content from ${e}`)}}let n8={name:"Unknown Identity",avatarURL:"XUUB8bbn9fEthk15Ge3zTQXypUShfC94vFjp65v7u5CQ8qkpxzst",identityKey:"",abbreviatedKey:"",badgeIconURL:"XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",badgeLabel:"Not verified by anyone you trust.",badgeClickURL:"https://projectbabbage.com/docs/unknown-identity"},n3={protocolID:[1,"identity"],keyID:"1",tokenAmount:1,outputIndex:0},n6={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="},n4=[2,"contact"];class n5{cache=new Map;getItem(e){return this.cache.get(e)??null}setItem(e,t){this.cache.set(e,t)}removeItem(e){this.cache.delete(e)}clear(){this.cache.clear()}}class n7{wallet;cache=new n5;CONTACTS_CACHE_KEY="metanet-contacts";originator;constructor(e,t){this.wallet=e??new nS,this.originator=t}async getContacts(e,t=!1,i=1e3){if(!t){let t=this.cache.getItem(this.CONTACTS_CACHE_KEY);if(null!=t&&""!==t)try{let i=JSON.parse(t);return null!=e?i.filter(t=>t.identityKey===e):i}catch(e){console.warn("Invalid cached contacts JSON; will reload from chain",e)}}let r=[];if(null!=e){let{hmac:t}=await this.wallet.createHmac({protocolID:n4,keyID:e,counterparty:"self",data:ti(e,"utf8")},this.originator);r.push(`identityKey ${te(t)}`)}let n=await this.wallet.listOutputs({basket:"contacts",include:"locking scripts",includeCustomInstructions:!0,tags:r,limit:i},this.originator);if(null==n.outputs||0===n.outputs.length)return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify([])),[];let a=[];for(let e of n.outputs)try{if(null==e.lockingScript)continue;let t=iK.decode(iT.fromHex(e.lockingScript));if(null==e.customInstructions)continue;let i=JSON.parse(e.customInstructions).keyID;a.push({keyID:i,ciphertext:t.fields[0]})}catch(e){console.warn("ContactsManager: Failed to decode contact output:",e)}let s=await Promise.allSettled(a.map(async e=>await this.wallet.decrypt({ciphertext:e.ciphertext,protocolID:n4,keyID:e.keyID,counterparty:"self"},this.originator))),o=[];for(let e=0;e<s.length;e++){let t=s[e];if("fulfilled"===t.status)try{let e=JSON.parse(ts(t.value.plaintext));o.push(e)}catch(e){console.warn("ContactsManager: Failed to parse contact data:",e)}else console.warn("ContactsManager: Failed to decrypt contact output:",t.reason)}return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(o)),null!=e?o.filter(t=>t.identityKey===e):o}async saveContact(e,t){let i,r=this.cache.getItem(this.CONTACTS_CACHE_KEY),n=(i=null!=r&&""!==r?JSON.parse(r):await this.getContacts()).findIndex(t=>t.identityKey===e.identityKey),a={...e,metadata:t};n>=0?i[n]=a:i.push(a);let{hmac:s}=await this.wallet.createHmac({protocolID:n4,keyID:e.identityKey,counterparty:"self",data:ti(e.identityKey,"utf8")},this.originator),o=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:[`identityKey ${te(s)}`],limit:100},this.originator),c=null,l=tc(t0(32));if(null!=o.outputs)for(let t of o.outputs)try{let[i,r]=t.outpoint.split("."),n=i3.fromBEEF(o.BEEF,i),a=iK.decode(n.outputs[Number(r)].lockingScript);if(null==t.customInstructions)continue;l=JSON.parse(t.customInstructions).keyID;let{plaintext:s}=await this.wallet.decrypt({ciphertext:a.fields[0],protocolID:n4,keyID:l,counterparty:"self"},this.originator);if(JSON.parse(ts(s)).identityKey===e.identityKey){c=t;break}}catch(e){}let h={...e,metadata:t},{ciphertext:d}=await this.wallet.encrypt({plaintext:ti(JSON.stringify(h),"utf8"),protocolID:n4,keyID:l,counterparty:"self"},this.originator),u=await new iK(this.wallet,this.originator).lock([d],n4,l,"self");if(null!=c){let[t,i]=String(c.outpoint).split("."),r=`${t}.${i}`,n=new iK(this.wallet,this.originator),{signableTransaction:a}=await this.wallet.createAction({description:"Update Contact",inputBEEF:o.BEEF,inputs:[{outpoint:r,unlockingScriptLength:74,inputDescription:"Spend previous contact output"}],outputs:[{basket:"contacts",satoshis:1,lockingScript:u.toHex(),outputDescription:`Updated Contact: ${e.name??e.identityKey.slice(0,10)}`,tags:[`identityKey ${te(s)}`],customInstructions:JSON.stringify({keyID:l})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==a)throw Error("Unable to update contact");let h=n.unlock(n4,l,"self"),d=await h.sign(i3.fromBEEF(a.tx),0),{tx:f}=await this.wallet.signAction({reference:a.reference,spends:{0:{unlockingScript:d.toHex()}}},this.originator);if(null==f)throw Error("Failed to update contact output")}else{let{tx:t}=await this.wallet.createAction({description:"Add Contact",outputs:[{basket:"contacts",satoshis:1,lockingScript:u.toHex(),outputDescription:`Contact: ${e.name??e.identityKey.slice(0,10)}`,tags:[`identityKey ${te(s)}`],customInstructions:JSON.stringify({keyID:l})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==t)throw Error("Failed to create contact output")}this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(i))}async removeContact(e){let t=this.cache.getItem(this.CONTACTS_CACHE_KEY);if(null!=t&&""!==t)try{let i=JSON.parse(t).filter(t=>t.identityKey!==e);this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(i))}catch(e){console.warn("Failed to update cache after contact removal:",e)}let i=[],{hmac:r}=await this.wallet.createHmac({protocolID:n4,keyID:e,counterparty:"self",data:ti(e,"utf8")},this.originator);i.push(`identityKey ${te(r)}`);let n=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:i,limit:100},this.originator);if(null!=n.outputs)for(let t of n.outputs)try{let[i,r]=String(t.outpoint).split("."),a=i3.fromBEEF(n.BEEF,i),s=iK.decode(a.outputs[Number(r)].lockingScript);if(null==t.customInstructions)continue;let o=JSON.parse(t.customInstructions).keyID,{plaintext:c}=await this.wallet.decrypt({ciphertext:s.fields[0],protocolID:n4,keyID:o,counterparty:"self"},this.originator);if(JSON.parse(ts(c)).identityKey===e){let e=`${i}.${r}`,t=new iK(this.wallet,this.originator),{signableTransaction:a}=await this.wallet.createAction({description:"Delete Contact",inputBEEF:n.BEEF,inputs:[{outpoint:e,unlockingScriptLength:74,inputDescription:"Spend contact output to delete"}],outputs:[],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==a)throw Error("Unable to delete contact");let s=t.unlock(n4,o,"self"),c=await s.sign(i3.fromBEEF(a.tx),0),{tx:l}=await this.wallet.signAction({reference:a.reference,spends:{0:{unlockingScript:c.toHex()}}},this.originator);if(null==l)throw Error("Failed to delete contact output");return}}catch(e){}}}class n9{options;originator;wallet;contactsManager;constructor(e,t=n3,i){this.options=t,this.originator=i,this.originator=i,this.wallet=e??new nS,this.contactsManager=new n7(this.wallet,this.originator)}async publiclyRevealAttributes(e,t){if(0===Object.keys(e.fields).length)throw Error("Public reveal failed: Certificate has no fields to reveal!");if(0===t.length)throw Error("Public reveal failed: You must reveal at least one field!");try{let t=new rC(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature);await t.verify()}catch(e){throw Error("Public reveal failed: Certificate verification failed!")}let{keyringForVerifier:i}=await this.wallet.proveCertificate({certificate:e,fieldsToReveal:t,verifier:new t3(1).toPublicKey().toString()},this.originator),r=await new iK(this.wallet,this.originator).lock([ti(JSON.stringify({...e,keyring:i}))],this.options.protocolID,this.options.keyID,"anyone",!0,!0),{tx:n}=await this.wallet.createAction({description:"Create a new Identity Token",outputs:[{satoshis:this.options.tokenAmount,lockingScript:r.toHex(),outputDescription:"Identity Token"}],options:{randomizeOutputs:!1}},this.originator);if(void 0!==n){let e=new nX(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network});return await e.broadcast(i3.fromAtomicBEEF(n))}throw Error("Public reveal failed: failed to create action!")}async resolveByIdentityKey(e,t=!0){let[i,r]=await Promise.all([t?this.contactsManager.getContacts(e.identityKey):Promise.resolve([]),this.wallet.discoverByIdentityKey(e,this.originator)]);return i.length>0?i:(r?.certificates??[]).map(e=>n9.parseIdentity(e))}async resolveByAttributes(e,t=!0){let[i,r]=await Promise.all([t?this.contactsManager.getContacts():Promise.resolve([]),this.wallet.discoverByAttributes(e,this.originator)]),n=new Map(i.map(e=>[e.identityKey,e]));return(r?.certificates??[]).map(e=>n.get(e.subject)??n9.parseIdentity(e))}async revokeCertificateRevelation(e){let t=new nW({networkPreset:(await this.wallet.getNetwork({})).network}),i=await t.query({service:"ls_identity",query:{serialNumber:e}});if("output-list"!==i.type)throw Error("Failed to get lookup result");let r=new nX(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network,requireAcknowledgmentFromAllHostsForTopics:[],requireAcknowledgmentFromAnyHostForTopics:[],requireAcknowledgmentFromSpecificHostsForTopics:{tm_identity:[]}});await nG(async()=>{let e=i3.fromBEEF(i.outputs[0].beef),t=`${e.id("hex")}.${this.options.outputIndex}`;if(void 0===e.outputs[this.options.outputIndex].lockingScript||void 0===t)throw Error("Failed to get locking script for revelation output!");let{signableTransaction:n}=await this.wallet.createAction({description:"Spend certificate revelation token",inputBEEF:i.outputs[0].beef,inputs:[{inputDescription:"Revelation token",outpoint:t,unlockingScriptLength:74}],options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1,noSend:!0}},this.originator);if(void 0===n)throw Error("Failed to create signable transaction");let a=i3.fromBEEF(n.tx),s=new iK(this.wallet,this.originator).unlock(this.options.protocolID,this.options.keyID,"anyone"),o=await s.sign(a,this.options.outputIndex),{tx:c}=await this.wallet.signAction({reference:n.reference,spends:{[this.options.outputIndex]:{unlockingScript:o.toHex()}},options:{acceptDelayedBroadcast:!1,noSend:!0}},this.originator);if(void 0===c)throw Error("Failed to sign transaction");await r.broadcast(i3.fromAtomicBEEF(c))},r)}async getContacts(e,t=!1,i=1e3){return await this.contactsManager.getContacts(e,t,i)}async saveContact(e,t){return await this.contactsManager.saveContact(e,t)}async removeContact(e){return await this.contactsManager.removeContact(e)}static parseIdentity(e){let t,i,r,n,a,{type:s,decryptedFields:o,certifierInfo:c}=e;switch(s){case n6.xCert:t=o.userName,i=o.profilePhoto,r=`X account certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n6.discordCert:t=o.userName,i=o.profilePhoto,r=`Discord account certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n6.emailCert:t=o.email,i="XUTZxep7BBghAJbSBwTjNfmcsDdRFs5EaGEgkESGSgjJVYgMEizu",r=`Email certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n6.phoneCert:t=o.phoneNumber,i="XUTLxtX3ELNUwRhLwL7kWNGbdnFM8WG2eSLv84J7654oH8HaJWrU",r=`Phone certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n6.identiCert:t=`${o.firstName} ${o.lastName}`,i=o.profilePhoto,r=`Government ID certified by ${c.name}`,n=c.iconUrl,a="https://identicert.me";break;case n6.registrant:t=o.name,i=o.icon,r=`Entity certified by ${c.name}`,n=c.iconUrl,a="https://projectbabbage.com/docs/registrant";break;case n6.coolCert:t="true"===o.cool?"Cool Person!":"Not cool!";break;case n6.anyone:t="Anyone",i="XUT4bpQ6cpBaXi1oMzZsXfpkWGbtp2JTUYAoN7PzhStFJ6wLfoeR",r="Represents the ability for anyone to access this information.",n="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",a="https://projectbabbage.com/docs/anyone-identity";break;case n6.self:t="You",i="XUT9jHGk2qace148jeCX5rDsMftkSGYKmigLwU2PLLBc7Hm63VYR",r="Represents your ability to access this information.",n="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",a="https://projectbabbage.com/docs/self-identity";break;default:{let e=n9.tryToParseGenericIdentity(s,o,c);t=e.name,i=e.avatarURL,r=e.badgeLabel,n=e.badgeIconURL,a=e.badgeClickURL}}return{name:t,avatarURL:i,abbreviatedKey:e.subject.length>0?`${e.subject.substring(0,10)}...`:"",identityKey:e.subject,badgeIconURL:n,badgeLabel:r,badgeClickURL:a}}static hasValue(e){return null!=e&&""!==e}static tryToParseGenericIdentity(e,t,i){let r=t.firstName,n=t.lastName,a=n9.hasValue(r)&&n9.hasValue(n)?`${r} ${n}`:n9.hasValue(r)?r:n9.hasValue(n)?n:void 0,s=n9.hasValue(t.name)?t.name:n9.hasValue(t.userName)?t.userName:a??(n9.hasValue(t.email)?t.email:n8.name),o=n9.hasValue(t.profilePhoto)?t.profilePhoto:n9.hasValue(t.avatar)?t.avatar:n9.hasValue(t.icon)?t.icon:n9.hasValue(t.photo)?t.photo:n8.avatarURL,c=n9.hasValue(i?.name)?`${e} certified by ${String(i.name)}`:n8.badgeLabel;return{name:s,avatarURL:o,badgeLabel:c,badgeIconURL:n9.hasValue(i?.iconUrl)?i.iconUrl:n8.badgeIconURL,badgeClickURL:n8.badgeClickURL}}}class ae{wallet;originator;network;resolver;cachedIdentityKey;acceptDelayedBroadcast;constructor(e=new nS,t={},i){this.wallet=e,this.originator=i,this.acceptDelayedBroadcast=t.acceptDelayedBroadcast??!1,this.resolver=t.resolver??new nW}async getIdentityKey(){return void 0===this.cachedIdentityKey&&(this.cachedIdentityKey=(await this.wallet.getPublicKey({identityKey:!0})).publicKey),this.cachedIdentityKey}async getNetwork(){return void 0===this.network&&(this.network=(await this.wallet.getNetwork({})).network),this.network}async registerDefinition(e){let t=await this.getIdentityKey(),i=new iK(this.wallet,this.originator),r=this.buildPushDropFields(e,t),n=this.mapDefinitionTypeToWalletProtocol(e.definitionType),a=await i.lock(r,n,"1","anyone",!0),{tx:s}=await this.wallet.createAction({description:`Register a new ${e.definitionType} item`,outputs:[{satoshis:1,lockingScript:a.toHex(),outputDescription:`New ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===s)throw Error(`Failed to create ${e.definitionType} registration transaction!`);let o=new nX([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await o.broadcast(i3.fromAtomicBEEF(s))}async resolve(e,t){let i=this.mapDefinitionTypeToServiceName(e),r=await this.resolver.query({service:i,query:t});if("output-list"!==r.type)return[];let n=[];for(let t of r.outputs)try{let i=i3.fromBEEF(t.beef).outputs[t.outputIndex].lockingScript,r=await this.parseLockingScript(e,i);n.push(r)}catch{}return n}async listOwnRegistryEntries(e){let t=this.mapDefinitionTypeToBasketName(e),{outputs:i,BEEF:r}=await this.wallet.listOutputs({basket:t,include:"entire transactions"}),n=[];for(let t of i)if(t.spendable)try{let[i,a]=t.outpoint.split("."),s=i3.fromBEEF(r,i).outputs[Number(a)].lockingScript,o=await this.parseLockingScript(e,s);n.push({...o,txid:i,outputIndex:Number(a),satoshis:t.satoshis,lockingScript:s.toHex(),beef:r})}catch{}return n}async removeDefinition(e){if(void 0===e.txid||void 0===e.outputIndex||void 0===e.lockingScript)throw Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");let t=await this.getIdentityKey();if(e.registryOperator!==t)throw Error("This registry token does not belong to the current wallet.");let i="basket"===e.definitionType?e.basketID:"protocol"===e.definitionType?e.name:"certificate"===e.definitionType?void 0!==e.name?e.name:e.type:"unknown",r=`${e.txid}.${e.outputIndex}`,{signableTransaction:n}=await this.wallet.createAction({description:`Remove ${e.definitionType} item: ${i}`,inputBEEF:e.beef,inputs:[{outpoint:r,unlockingScriptLength:74,inputDescription:`Removing ${e.definitionType} token`}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===n)throw Error("Failed to create signable transaction.");let a=i3.fromAtomicBEEF(n.tx),s=new iK(this.wallet,this.originator).unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone"),o=await s.sign(a,0),{tx:c}=await this.wallet.signAction({reference:n.reference,spends:{0:{unlockingScript:o.toHex()}},options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if(void 0===c)throw Error("Failed to finalize the transaction signature.");let l=new nX([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await l.broadcast(i3.fromAtomicBEEF(c))}async updateDefinition(e,t){if(void 0===e.txid||void 0===e.outputIndex||void 0===e.lockingScript)throw Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");if(e.definitionType!==t.definitionType)throw Error(`Cannot change definition type from ${e.definitionType} to ${t.definitionType}`);let i=await this.getIdentityKey();if(e.registryOperator!==i)throw Error("This registry token does not belong to the current wallet.");let r="basket"===e.definitionType?e.basketID:"protocol"===e.definitionType?e.name:"certificate"===e.definitionType?void 0!==e.name?e.name:e.type:"unknown",n=new iK(this.wallet,this.originator),a=this.buildPushDropFields(t,i),s=this.mapDefinitionTypeToWalletProtocol(t.definitionType),o=await n.lock(a,s,"1","anyone",!0),c=`${e.txid}.${e.outputIndex}`,{signableTransaction:l}=await this.wallet.createAction({description:`Update ${e.definitionType} item: ${r}`,inputBEEF:e.beef,inputs:[{outpoint:c,unlockingScriptLength:74,inputDescription:`Updating ${e.definitionType} token`}],outputs:[{satoshis:1,lockingScript:o.toHex(),outputDescription:`Updated ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===l)throw Error("Failed to create signable transaction.");let h=i3.fromAtomicBEEF(l.tx),d=n.unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone"),u=await d.sign(h,0),{tx:f}=await this.wallet.signAction({reference:l.reference,spends:{0:{unlockingScript:u.toHex()}},options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if(void 0===f)throw Error("Failed to finalize the transaction signature.");let p=new nX([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await p.broadcast(i3.fromAtomicBEEF(f))}buildPushDropFields(e,t){let i;switch(e.definitionType){case"basket":i=[e.basketID,e.name,e.iconURL,e.description,e.documentationURL];break;case"protocol":i=[JSON.stringify(e.protocolID),e.name,e.iconURL,e.description,e.documentationURL];break;case"certificate":i=[e.type,e.name,e.iconURL,e.description,e.documentationURL,JSON.stringify(e.fields)];break;default:throw Error("Unsupported definition type")}return i.push(t),i.map(e=>ti(e))}async parseLockingScript(e,t){let i,r,n=iK.decode(t);if(0===n.fields.length)throw Error("Not a valid registry pushdrop script.");switch(e){case"basket":{if(7!==n.fields.length)throw Error("Unexpected field count for basket type.");let[e,t,a,s,o,c]=n.fields;i=ts(c),r={definitionType:"basket",basketID:ts(e),name:ts(t),iconURL:ts(a),description:ts(s),documentationURL:ts(o)};break}case"protocol":{if(7!==n.fields.length)throw Error("Unexpected field count for protocol type.");let[e,t,a,s,o,c]=n.fields;i=ts(c),r={definitionType:"protocol",protocolID:at(ts(e)),name:ts(t),iconURL:ts(a),description:ts(s),documentationURL:ts(o)};break}case"certificate":{if(8!==n.fields.length)throw Error("Unexpected field count for certificate type.");let[e,t,a,s,o,c,l]=n.fields;i=ts(l);let h={};try{h=JSON.parse(ts(c))}catch{}r={definitionType:"certificate",type:ts(e),name:ts(t),iconURL:ts(a),description:ts(s),documentationURL:ts(o),fields:h};break}default:throw Error(`Unsupported definition type: ${e}`)}return{...r,registryOperator:i}}mapDefinitionTypeToWalletProtocol(e){switch(e){case"basket":return[1,"basketmap"];case"protocol":return[1,"protomap"];case"certificate":return[1,"certmap"];default:throw Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToBasketName(e){switch(e){case"basket":return"basketmap";case"protocol":return"protomap";case"certificate":return"certmap";default:throw Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToTopic(e){switch(e){case"basket":return"tm_basketmap";case"protocol":return"tm_protomap";case"certificate":return"tm_certmap";default:throw Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToServiceName(e){switch(e){case"basket":return"ls_basketmap";case"protocol":return"ls_protomap";case"certificate":return"ls_certmap";default:throw Error(`Unknown definition type: ${e}`)}}}function at(e){let t=JSON.parse(e);if(!Array.isArray(t)||2!==t.length)throw Error("Invalid wallet protocol format.");let[i,r]=t;if(![0,1,2].includes(i))throw Error("Invalid security level.");if("string"!=typeof r)throw Error("Invalid protocolID");return[i,r]}class ai{wallet;context;encrypt;originator;acceptDelayedBroadcast=!1;keyLocks=new Map;constructor(e=new nS,t="kvstore default",i=!0,r,n=!1){if("string"!=typeof t||t.length<1)throw Error("A context in which to operate is required.");this.wallet=e,this.context=t,this.encrypt=i,this.originator=r,this.acceptDelayedBroadcast=n}async queueOperationOnKey(e){let t=this.keyLocks.get(e);null==t&&(t=[],this.keyLocks.set(e,t));let i=()=>{},r=new Promise(e=>{i=e,null!=t&&t.push(e)});return 1===t.length&&i(),await r,t}finishOperationOnKey(e,t){t.shift(),t.length>0&&t[0]()}getProtocol(e){return{protocolID:[2,this.context],keyID:e}}async getOutputs(e,t){return await this.wallet.listOutputs({basket:this.context,tags:[e],tagQueryMode:"all",include:"entire transactions",limit:t},this.originator)}async get(e,t){let i=await this.queueOperationOnKey(e);try{return(await this.lookupValue(e,t,5)).value}finally{this.finishOperationOnKey(e,i)}}getLockingScript(e,t){let[i,r]=e.outpoint.split("."),n=t.findTxid(i)?.tx;if(null==n)throw Error(`beef must contain txid ${i}`);return n.outputs[Number(r)].lockingScript}async lookupValue(e,t,i){let r,n=await this.getOutputs(e,i),a={value:t,outpoint:void 0,lor:n},{outputs:s}=n;if(0===s.length)return a;let o=s.slice(-1)[0];a.outpoint=o.outpoint;try{if(void 0===n.BEEF)throw Error("entire transactions listOutputs option must return valid BEEF");let e=this.getLockingScript(o,i8.fromBinary(n.BEEF)),t=iK.decode(e);if(t.fields.length<1||t.fields.length>2)throw Error("Invalid token.");r=t.fields[0]}catch(e){throw Error(`Invalid value found. You need to call set to collapse the corrupted state (or relinquish the corrupted ${s[0].outpoint} output from the ${this.context} basket) before you can get this value again. Original error: ${e instanceof Error?e.message:String(e)}`)}if(this.encrypt){let{plaintext:t}=await this.wallet.decrypt({...this.getProtocol(e),ciphertext:r},this.originator);a.value=ts(t)}else a.value=ts(r);return a}getInputs(e){let t=[];for(let i=0;i<e.length;i++)t.push({outpoint:e[i].outpoint,unlockingScriptLength:74,inputDescription:"Previous key-value token"});return t}async getSpends(e,t,i,r){let n=this.getProtocol(e),a=i3.fromAtomicBEEF(r),s={};for(let e=0;e<t.length;e++){let t=i.unlock(n.protocolID,n.keyID,"self"),r=await t.sign(a,e);s[e]={unlockingScript:r.toHex()}}return s}async set(e,t){let i=await this.queueOperationOnKey(e);try{let i,r=await this.lookupValue(e,void 0,10);if(r.value===t){if(void 0===r.outpoint)throw Error("outpoint must be valid when value is valid and unchanged");return r.outpoint}let n=this.getProtocol(e),a=ti(t,"utf8");if(this.encrypt){let{ciphertext:e}=await this.wallet.encrypt({...n,plaintext:a},this.originator);a=e}let s=new iK(this.wallet,this.originator),o=await s.lock([a],n.protocolID,n.keyID,"self"),{outputs:c,BEEF:l}=r.lor;try{let t=this.getInputs(c),{txid:r,signableTransaction:n}=await this.wallet.createAction({description:`Update ${e} in ${this.context}`,inputBEEF:l,inputs:t,outputs:[{basket:this.context,tags:[e],lockingScript:o.toHex(),satoshis:1,outputDescription:"Key-value token"}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(c.length>0&&"object"!=typeof n)throw Error("Wallet did not return a signable transaction when expected.");if(null==n)i=`${r}.0`;else{let t=await this.getSpends(e,c,s,n.tx),{txid:r}=await this.wallet.signAction({reference:n.reference,spends:t},this.originator);i=`${r}.0`}}catch(t){throw Error(`There are ${c.length} outputs with tag ${e} that cannot be unlocked. Original error: ${t instanceof Error?t.message:String(t)}`)}return i}finally{this.finishOperationOnKey(e,i)}}async remove(e){let t=await this.queueOperationOnKey(e);try{let t=[];for(;;){let{outputs:i,BEEF:r,totalOutputs:n}=await this.getOutputs(e);if(i.length>0){let a=new iK(this.wallet,this.originator);try{let n=this.getInputs(i),{signableTransaction:s}=await this.wallet.createAction({description:`Remove ${e} in ${this.context}`,inputBEEF:r,inputs:n,options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if("object"!=typeof s)throw Error("Wallet did not return a signable transaction when expected.");let o=await this.getSpends(e,i,a,s.tx),{txid:c}=await this.wallet.signAction({reference:s.reference,spends:o},this.originator);if(void 0===c)throw Error("signAction must return a valid txid");t.push(c)}catch(t){throw Error(`There are ${n} outputs with tag ${e} that cannot be unlocked. Original error: ${t instanceof Error?t.message:String(t)}`)}}if(i.length===n)break}return t}finally{this.finishOperationOnKey(e,t)}}}class ar{interpreter;debug;historyCache;interpreterVersion;ctxKeyFn;constructor(e,t){this.interpreter=e,this.debug=t?.debug??!1,this.historyCache=t?.historyCache,this.interpreterVersion=t?.interpreterVersion??"v1",this.ctxKeyFn=t?.ctxKeyFn??(e=>{try{return JSON.stringify(e??null)}catch{return""}})}historyKey(e,t){let i=e.id("hex"),r=this.ctxKeyFn(t);return`${this.interpreterVersion}|${i}|${r}`}async buildHistory(e,t){if(null!=this.historyCache){let i=this.historyKey(e,t);if(this.historyCache.has(i)){let e=this.historyCache.get(i);if(null!=e)return this.debug&&console.log("[Historian] History cache hit:",i),e.slice()}}let i=[],r=new Set,n=async e=>{let a=e.id("hex");if(r.has(a)){this.debug&&console.log(`[Historian] Skipping already visited transaction: ${a}`);return}r.add(a),this.debug&&console.log(`[Historian] Processing transaction: ${a}`);for(let r=0;r<e.outputs.length;r++)try{let n=await Promise.resolve(this.interpreter(e,r,t));void 0!==n&&(i.push(n),this.debug&&console.log("[Historian] Added value to history:",n))}catch(e){this.debug&&console.log(`[Historian] Failed to interpret output ${r}:`,e)}for(let t of e.inputs)null!=t.sourceTransaction?await n(t.sourceTransaction):this.debug&&console.log("[Historian] Input missing sourceTransaction, skipping")};await n(e);let a=i.reverse();if(null!=this.historyCache){let i=this.historyKey(e,t);this.historyCache.set(i,Object.freeze(a.slice())),this.debug&&console.log("[Historian] History cached:",i)}return a}}let an={protocolID:0,key:1,value:2,controller:3,tags:4,signature:5},aa=async(e,t,i)=>{try{let r=e.outputs[t];if(null==r||null==r.lockingScript||null==i||null==i.key)return;let n=iK.decode(r.lockingScript),a=Object.keys(an).length,s=n.fields.length===a;if(n.fields.length!==a-1&&!s)return;let o=ts(n.fields[an.key]),c=ts(n.fields[an.protocolID]);if(o!==i.key||c!==JSON.stringify(i.protocolID))return;try{return ts(n.fields[an.value])}catch{return}}catch{return}},as={protocolID:[1,"kvstore"],serviceName:"ls_kvstore",tokenAmount:1,topics:["tm_kvstore"],networkPreset:"mainnet",acceptDelayedBroadcast:!1,overlayBroadcast:!1,tokenSetDescription:"",tokenUpdateDescription:"",tokenRemovalDescription:""};class ao{wallet;config;historian;lookupResolver;topicBroadcaster;keyLocks=new Map;cachedIdentityKey=null;constructor(e={}){this.config={...as,...e},this.wallet=e.wallet??new nS,this.historian=new ar(aa),this.lookupResolver=new nW({networkPreset:this.config.networkPreset}),this.topicBroadcaster=new nX(this.config.topics,{networkPreset:this.config.networkPreset})}async get(e,t={}){if(0===Object.keys(e).length)throw Error("Must specify either key, controller, or protocolID");if(null!=e.key&&null!=e.controller){let i=await this.queryOverlay(e,t);return i.length>0?i[0]:void 0}return await this.queryOverlay(e,t)}async set(e,t,i={}){if("string"!=typeof e||0===e.length)throw Error("Key must be a non-empty string.");if("string"!=typeof t)throw Error("Value must be a string.");let r=await this.getIdentityKey(),n=await this.queueOperationOnKey(e),a=i.protocolID??this.config.protocolID,s=null!=i.tokenSetDescription&&""!==i.tokenSetDescription?i.tokenSetDescription:`Create KVStore value for ${e}`,o=null!=i.tokenUpdateDescription&&""!==i.tokenUpdateDescription?i.tokenUpdateDescription:`Update KVStore value for ${e}`,c=i.tokenAmount??this.config.tokenAmount,l=i.tags??[];try{let i=new iK(this.wallet,this.config.originator),n=[ti(JSON.stringify(a),"utf8"),ti(e,"utf8"),ti(t,"utf8"),ti(r,"hex")];l.length>0&&n.push(ti(JSON.stringify(l),"utf8"));let h=await i.lock(n,a??this.config.protocolID,ts(ti(e,"utf8")),"anyone",!0);return await nG(async()=>{let t=await this.queryOverlay({key:e,controller:r},{includeToken:!0}),n=t.length>0?t[0].token:void 0;if(null!=n){let t=[{outpoint:`${n.txid}.${n.outputIndex}`,unlockingScriptLength:74,inputDescription:"Previous KVStore token"}],r=n.beef,{signableTransaction:a}=await this.wallet.createAction({description:o,inputBEEF:r.toBinary(),inputs:t,outputs:[{satoshis:c??this.config.tokenAmount,lockingScript:h.toHex(),outputDescription:"KVStore token"}],options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast,randomizeOutputs:!1}},this.config.originator);if(null==a)throw Error("Unable to create update transaction");let s=i3.fromAtomicBEEF(a.tx),l=i.unlock(this.config.protocolID,e,"anyone"),d=await l.sign(s,0),{tx:u}=await this.wallet.signAction({reference:a.reference,spends:{0:{unlockingScript:d.toHex()}},options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==u)throw Error("Unable to finalize update transaction");let f=i3.fromAtomicBEEF(u);return await this.submitToOverlay(f),`${f.id("hex")}.0`}{let{tx:e}=await this.wallet.createAction({description:s,outputs:[{satoshis:c??this.config.tokenAmount,lockingScript:h.toHex(),outputDescription:"KVStore token"}],options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast,randomizeOutputs:!1}},this.config.originator);if(null==e)throw Error("Failed to create transaction");let t=i3.fromAtomicBEEF(e);return await this.submitToOverlay(t),`${t.id("hex")}.0`}},this.topicBroadcaster)}finally{n.length>0&&this.finishOperationOnKey(e,n)}}async remove(e,t,i={}){if("string"!=typeof e||0===e.length)throw Error("Key must be a non-empty string.");let r=await this.getIdentityKey(),n=await this.queueOperationOnKey(e),a=i.protocolID??this.config.protocolID,s=null!=i.tokenRemovalDescription&&""!==i.tokenRemovalDescription?i.tokenRemovalDescription:`Remove KVStore value for ${e}`;try{let i=new iK(this.wallet,this.config.originator);return await nG(async()=>{let n=await this.queryOverlay({key:e,controller:r},{includeToken:!0});if(0===n.length||null==n[0].token)throw Error("The item did not exist, no item was deleted.");let o=n[0].token,c=[{outpoint:`${o.txid}.${o.outputIndex}`,unlockingScriptLength:74,inputDescription:"KVStore token to remove"}],{signableTransaction:l}=await this.wallet.createAction({description:s,inputBEEF:o.beef.toBinary(),inputs:c,outputs:t,options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,randomizeOutputs:!1,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==l)throw Error("Unable to create removal transaction");let h=i3.fromAtomicBEEF(l.tx),d=i.unlock(a??this.config.protocolID,e,"anyone"),u=await d.sign(h,0),{tx:f}=await this.wallet.signAction({reference:l.reference,spends:{0:{unlockingScript:u.toHex()}},options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==f)throw Error("Unable to finalize removal transaction");let p=i3.fromAtomicBEEF(f);return await this.submitToOverlay(p),p.id("hex")},this.topicBroadcaster)}finally{n.length>0&&this.finishOperationOnKey(e,n)}}async queueOperationOnKey(e){let t=this.keyLocks.get(e);null==t&&(t=[],this.keyLocks.set(e,t));let i=()=>{},r=new Promise(e=>{i=e,null!=t&&t.push(e)});return 1===t.length&&i(),await r,t}finishOperationOnKey(e,t){t.shift(),t.length>0?t[0]():this.keyLocks.delete(e)}async getIdentityKey(){return null==this.cachedIdentityKey&&(this.cachedIdentityKey=(await this.wallet.getPublicKey({identityKey:!0},this.config.originator)).publicKey),this.cachedIdentityKey}async queryOverlay(e,t={}){let i=await this.lookupResolver.query({service:t.serviceName??this.config.serviceName,query:e});if("output-list"!==i.type||0===i.outputs.length)return[];let r=[];for(let e of i.outputs)try{let i,n=i3.fromBEEF(e.beef),a=n.outputs[e.outputIndex],s=iK.decode(a.lockingScript),o=Object.keys(an).length,c=s.fields.length===o;if(s.fields.length!==o-1&&!c)continue;let l=new rA("anyone"),h=s.fields.pop();try{await l.verifySignature({data:s.fields.reduce((e,t)=>[...e,...t],[]),signature:h,counterparty:te(s.fields[an.controller]),protocolID:JSON.parse(ts(s.fields[an.protocolID])),keyID:ts(s.fields[an.key])})}catch(e){continue}if(c&&null!=s.fields[an.tags])try{i=JSON.parse(ts(s.fields[an.tags]))}catch(e){i=void 0}let d={key:ts(s.fields[an.key]),value:ts(s.fields[an.value]),controller:te(s.fields[an.controller]),protocolID:JSON.parse(ts(s.fields[an.protocolID])),tags:i};!0===t.includeToken&&(d.token={txid:n.id("hex"),outputIndex:e.outputIndex,beef:i8.fromBinary(e.beef),satoshis:a.satoshis??1}),!0===t.history&&(d.history=await this.historian.buildHistory(n,{key:d.key,protocolID:d.protocolID})),r.push(d)}catch(e){continue}return r}async submitToOverlay(e){return await this.topicBroadcaster.broadcast(e)}}let ac=ao,al={new:["identityRequested","invoiced","settled","terminated","errored"],identityRequested:["identityResponded","identityAcknowledged","invoiced","settled","terminated","errored"],identityResponded:["identityAcknowledged","invoiced","settled","terminated","errored"],identityAcknowledged:["invoiced","settled","terminated","errored"],invoiced:["identityRequested","identityResponded","identityAcknowledged","settled","terminated","errored"],settled:["receipted","terminated","errored"],receipted:["terminated","errored"],terminated:["errored"],errored:[]},ah={namespace:"bsv",code:"sat",decimals:0},ad="remittance_inbox";class au{wallet;comms;cfg;messageBox;now;threadIdFactory;moduleRegistry;runtime;eventListeners;stateWaiters;eventHandlers;defaultPaymentOptionId;threads;myIdentityKey;constructor(e,t,i,r=[]){this.cfg=e,this.wallet=t,this.comms=i,this.messageBox=e.messageBox??ad,this.now=e.now??(()=>Date.now()),this.threadIdFactory=e.threadIdFactory??ag,this.moduleRegistry=new Map(e.remittanceModules.map(e=>[e.id,e])),this.eventListeners=new Set,this.stateWaiters=new Map,this.eventHandlers=e.events,"function"==typeof e.onEvent&&this.eventListeners.add(e.onEvent),this.runtime={identityOptions:e.options?.identityOptions??{makerRequestIdentity:"never",takerRequestIdentity:"never"},receiptProvided:e.options?.receiptProvided??!0,autoIssueReceipt:e.options?.autoIssueReceipt??!0,invoiceExpirySeconds:e.options?.invoiceExpirySeconds??3600,identityTimeoutMs:e.options?.identityTimeoutMs??3e4,identityPollIntervalMs:e.options?.identityPollIntervalMs??500},this.threads=r.map(e=>this.ensureThreadState(e))}async init(){if("function"!=typeof this.cfg.stateLoader)return;let e=await this.cfg.stateLoader();"object"==typeof e&&(this.loadState(e),"string"==typeof e.defaultPaymentOptionId&&(this.defaultPaymentOptionId=e.defaultPaymentOptionId),await this.refreshMyIdentityKey())}onEvent(e){return this.eventListeners.add(e),()=>{this.eventListeners.delete(e)}}preselectPaymentOption(e){this.defaultPaymentOptionId=e}saveState(){return{v:1,threads:JSON.parse(JSON.stringify(this.threads)),defaultPaymentOptionId:this.defaultPaymentOptionId}}loadState(e){if(1!==e.v)throw Error("Unsupported RemittanceManagerState version");this.threads=(e.threads??[]).map(e=>this.ensureThreadState(e)),this.defaultPaymentOptionId=e.defaultPaymentOptionId}async persistState(){null!=this.cfg.stateSaver&&await this.cfg.stateSaver(this.saveState())}async syncThreads(e){for(let t of(await this.refreshMyIdentityKey(),await this.comms.listMessages({messageBox:this.messageBox,host:e})))await this.handleInboundMessage(t)}async startListening(e){if("function"!=typeof this.comms.listenForLiveMessages)throw Error("CommsLayer does not support live message listening");await this.comms.listenForLiveMessages({messageBox:this.messageBox,overrideHost:e,onMessage:e=>{this.handleInboundMessage(e)}})}async sendInvoice(e,t,i){await this.refreshMyIdentityKey();let r=this.threadIdFactory(),n=this.now(),a=this.requireMyIdentityKey("sendInvoice requires the wallet to provide an identity key"),s={threadId:r,counterparty:e,myRole:"maker",theirRole:"taker",createdAt:n,updatedAt:n,state:"new",stateLog:[],processedMessageIds:[],protocolLog:[],identity:{certsSent:[],certsReceived:[],requestSent:!1,responseSent:!1,acknowledgmentSent:!1,acknowledgmentReceived:!1},flags:{hasIdentified:!1,hasInvoiced:!1,hasPaid:!1,hasReceipted:!1,error:!1}};this.threads.push(s),this.emitEvent({type:"threadCreated",threadId:s.threadId,thread:s}),s.identity.responseSent&&!s.flags.hasIdentified&&await this.waitForIdentityAcknowledgment(r,{timeoutMs:this.runtime.identityTimeoutMs,pollIntervalMs:this.runtime.identityPollIntervalMs}),this.shouldRequestIdentity(s,"beforeInvoicing")&&await this.ensureIdentityExchange(s,i);let o=await this.composeInvoice(r,a,e,t);for(let e of(s.invoice=o,s.flags.hasInvoiced=!0,this.transitionThreadState(s,"invoiced","invoice created"),this.moduleRegistry.values())){if("function"!=typeof e.createOption)continue;let t=await e.createOption({threadId:r,invoice:o},this.moduleContext());o.options[e.id]=t}let c=this.makeEnvelope("invoice",r,o),l=await this.sendEnvelope(e,c,i);return s.protocolLog.push({direction:"out",envelope:c,transportMessageId:l}),this.emitEvent({type:"invoiceSent",threadId:s.threadId,invoice:o}),s.updatedAt=this.now(),await this.persistState(),new ap(this,r)}async sendInvoiceForThread(e,t,i){await this.refreshMyIdentityKey();let r=this.getThreadOrThrow(e);if(r.flags.error)throw Error("Thread is in error state");if("maker"!==r.myRole)throw Error("Only makers can send invoices");if(null!=r.invoice)throw Error("Thread already has an invoice");r.identity.responseSent&&!r.flags.hasIdentified&&await this.waitForIdentityAcknowledgment(e,{timeoutMs:this.runtime.identityTimeoutMs,pollIntervalMs:this.runtime.identityPollIntervalMs}),this.shouldRequestIdentity(r,"beforeInvoicing")&&await this.ensureIdentityExchange(r,i);let n=this.requireMyIdentityKey("sendInvoice requires the wallet to provide an identity key"),a=await this.composeInvoice(e,n,r.counterparty,t);for(let t of(r.invoice=a,r.flags.hasInvoiced=!0,this.transitionThreadState(r,"invoiced","invoice created"),this.moduleRegistry.values())){if("function"!=typeof t.createOption)continue;let i=await t.createOption({threadId:e,invoice:a},this.moduleContext());a.options[t.id]=i}let s=this.makeEnvelope("invoice",e,a),o=await this.sendEnvelope(r.counterparty,s,i);return r.protocolLog.push({direction:"out",envelope:s,transportMessageId:o}),this.emitEvent({type:"invoiceSent",threadId:r.threadId,invoice:a}),r.updatedAt=this.now(),await this.persistState(),new ap(this,e)}findInvoicesPayable(e){let t="string"==typeof e&&e.length>0;return this.threads.filter(e=>"taker"===e.myRole&&null!=e.invoice&&null==e.settlement&&!e.flags.error).filter(i=>!t||i.counterparty===e).map(e=>new ap(this,e.threadId))}findReceivableInvoices(e){let t="string"==typeof e&&e.length>0;return this.threads.filter(e=>"maker"===e.myRole&&null!=e.invoice&&null==e.settlement&&!e.flags.error).filter(i=>!t||i.counterparty===e).map(e=>new ap(this,e.threadId))}async pay(e,t,i){await this.refreshMyIdentityKey();let r=this.getThreadOrThrow(e);if(null==r.invoice)throw Error("Thread has no invoice to pay");if(r.flags.error)throw Error("Thread is in error state");if(null!=r.settlement)throw Error("Invoice already paid (settlement exists)");r.identity.responseSent&&!r.flags.hasIdentified&&await this.waitForIdentityAcknowledgment(e,{timeoutMs:this.runtime.identityTimeoutMs,pollIntervalMs:this.runtime.identityPollIntervalMs}),this.shouldRequestIdentity(r,"beforeSettlement")&&await this.ensureIdentityExchange(r,i);let n=r.invoice.expiresAt;if("number"==typeof n&&this.now()>n)throw Error("Invoice is expired");let a=t??this.defaultPaymentOptionId??Object.keys(r.invoice.options)[0];if(null==a||""===a)throw Error("No remittance options available on invoice");let s=this.moduleRegistry.get(a);if(null==s)throw Error(`No configured remittance module for option: ${a}`);let o=r.invoice.options[a],c=this.requireMyIdentityKey("pay() requires the wallet to provide an identity key"),l=await s.buildSettlement({threadId:e,invoice:r.invoice,option:o,note:r.invoice.note},this.moduleContext());if("terminate"===l.action){let e=l.termination;return await this.sendTermination(r,r.counterparty,e.message,e.details,e.code),await this.persistState(),e}let h={kind:"settlement",threadId:e,moduleId:s.id,optionId:a,sender:c,createdAt:this.now(),artifact:l.artifact,note:r.invoice.note},d=this.makeEnvelope("settlement",e,h),u=await this.sendEnvelope(r.invoice.payee,d,i);if(r.protocolLog.push({direction:"out",envelope:d,transportMessageId:u}),this.emitEvent({type:"settlementSent",threadId:r.threadId,settlement:h}),r.settlement=h,r.flags.hasPaid=!0,this.transitionThreadState(r,"settled","settlement sent"),r.updatedAt=this.now(),await this.persistState(),this.runtime.receiptProvided)return await this.waitForReceipt(e)}async waitForReceipt(e,t={}){let i=t.timeoutMs??3e4,r=t.pollIntervalMs??500,n=this.now();for(;this.now()-n<i;){let t=this.getThreadOrThrow(e);if("object"==typeof t.receipt)return t.receipt;if("object"==typeof t.termination)return t.termination;await this.syncThreads(),await am(r)}throw Error("Timed out waiting for receipt")}async waitForState(e,t,i={}){let r,n,a=i.timeoutMs??3e4,s=i.pollIntervalMs??500,o=this.now(),c=this.getThreadOrThrow(e);if(c.state===t)return c;if("terminated"===c.state||"errored"===c.state)throw Error(`Thread entered terminal state: ${c.state}`);let l=!1,h=!1,d={state:t,resolve:()=>{l||h||(l=!0,r())},reject:e=>{l||h||(l=!0,n(e))}},u=new Promise((t,i)=>{r=t,n=i;let a=this.stateWaiters.get(e)??[];a.push(d),this.stateWaiters.set(e,a)}),f=()=>{let t=this.stateWaiters.get(e);if(null==t)return;let i=t.filter(e=>e!==d);0===i.length?this.stateWaiters.delete(e):this.stateWaiters.set(e,i)},p=(async()=>{for(;this.now()-o<a;){if(l)return;let i=this.getThreadOrThrow(e);if(i.state===t)return void this.resolveStateWaiters(e,t);if("terminated"===i.state||"errored"===i.state)throw Error(`Thread entered terminal state: ${i.state}`);await this.syncThreads(),await am(s)}})();if(await Promise.race([u,p]).catch(e=>{throw f(),e}),this.now()-o>=a&&!l)throw h=!0,f(),Error(`Timed out waiting for state: ${t}`);return f(),this.getThreadOrThrow(e)}async waitForIdentity(e,t){return await this.waitForState(e,"identityAcknowledged",t)}async waitForSettlement(e,t={}){let i=t.timeoutMs??3e4,r=t.pollIntervalMs??500,n=this.now();for(;this.now()-n<i;){let t=this.getThreadOrThrow(e);if("object"==typeof t.settlement)return t.settlement;if("object"==typeof t.termination)return t.termination;await this.syncThreads(),await am(r)}throw Error("Timed out waiting for settlement")}async sendUnsolicitedSettlement(e,t,i){await this.refreshMyIdentityKey();let r=this.moduleRegistry.get(t.moduleId);if(null==r)throw Error(`No configured remittance module for option: ${t.moduleId}`);if(!r.allowUnsolicitedSettlements)throw Error(`Remittance module ${t.moduleId} does not allow unsolicited settlements`);let n=this.threadIdFactory(),a=this.now(),s=this.requireMyIdentityKey("sendUnsolicitedSettlement requires the wallet to provide an identity key"),o={threadId:n,counterparty:e,myRole:"taker",theirRole:"maker",createdAt:a,updatedAt:a,state:"new",stateLog:[],processedMessageIds:[],protocolLog:[],identity:{certsSent:[],certsReceived:[],requestSent:!1,responseSent:!1,acknowledgmentSent:!1,acknowledgmentReceived:!1},flags:{hasIdentified:!1,hasInvoiced:!1,hasPaid:!1,hasReceipted:!1,error:!1}};this.threads.push(o),this.emitEvent({type:"threadCreated",threadId:o.threadId,thread:o}),this.shouldRequestIdentity(o,"beforeSettlement")&&await this.ensureIdentityExchange(o,i);let c=await r.buildSettlement({threadId:n,option:t.option,note:t.note},this.moduleContext());if("terminate"===c.action)return await this.sendTermination(o,e,c.termination.message,c.termination.details,c.termination.code),await this.persistState(),new af(this,n);let l={kind:"settlement",threadId:n,moduleId:r.id,optionId:t.optionId??r.id,sender:s,createdAt:this.now(),artifact:c.artifact,note:t.note},h=this.makeEnvelope("settlement",n,l),d=await this.sendEnvelope(e,h,i);return o.protocolLog.push({direction:"out",envelope:h,transportMessageId:d}),this.emitEvent({type:"settlementSent",threadId:o.threadId,settlement:l}),o.settlement=l,o.flags.hasPaid=!0,this.transitionThreadState(o,"settled","settlement sent"),o.updatedAt=this.now(),await this.persistState(),new af(this,n)}getThread(e){return this.threads.find(t=>t.threadId===e)}getThreadHandle(e){return this.getThreadOrThrow(e),new af(this,e)}getThreadOrThrow(e){let t=this.getThread(e);if("object"!=typeof t)throw Error(`Unknown thread: ${e}`);return this.ensureThreadState(t)}moduleContext(){return{wallet:this.wallet,originator:this.cfg.originator,now:this.now,logger:this.cfg.logger}}makeEnvelope(e,t,i){return{v:1,id:this.threadIdFactory(),kind:e,threadId:t,createdAt:this.now(),payload:i}}async sendEnvelope(e,t,i){let r=JSON.stringify(t);if("function"==typeof this.comms.sendLiveMessage)try{let n=await this.comms.sendLiveMessage({recipient:e,messageBox:this.messageBox,body:r},i);return this.emitEvent({type:"envelopeSent",threadId:t.threadId,envelope:t,transportMessageId:n}),n}catch(e){this.cfg.logger?.warn?.("[RemittanceManager] sendLiveMessage failed, falling back to non-live",e)}let n=await this.comms.sendMessage({recipient:e,messageBox:this.messageBox,body:r},i);return this.emitEvent({type:"envelopeSent",threadId:t.threadId,envelope:t,transportMessageId:n}),n}getOrCreateThreadFromInboundEnvelope(e,t){let i=this.getThread(e.threadId);if("object"==typeof i)return i;let r=this.now(),n=(()=>{if("invoice"===e.kind)return"taker";if("settlement"===e.kind)return"maker";if("receipt"===e.kind||"termination"===e.kind)return"taker";if("identityVerificationRequest"===e.kind||"identityVerificationResponse"===e.kind||"identityVerificationAcknowledgment"===e.kind){let t,i=this.runtime.identityOptions?.makerRequestIdentity??"never",r=this.runtime.identityOptions?.takerRequestIdentity??"never",n="never"!==i,a="never"!==r;return(n&&!a?t="maker":a&&!n?t="taker":n&&a&&i!==r&&(t="beforeInvoicing"===i&&"beforeSettlement"===r?"maker":"beforeSettlement"===i&&"beforeInvoicing"===r?"taker":void 0),"string"!=typeof t)?"taker":"identityVerificationResponse"===e.kind?t:"maker"===t?"taker":"maker"}return"taker"})(),a={threadId:e.threadId,counterparty:t.sender,myRole:n,theirRole:"maker"===n?"taker":"maker",createdAt:r,updatedAt:r,state:"new",stateLog:[],processedMessageIds:[],protocolLog:[],identity:{certsSent:[],certsReceived:[],requestSent:!1,responseSent:!1,acknowledgmentSent:!1,acknowledgmentReceived:!1},flags:{hasIdentified:!1,hasInvoiced:!1,hasPaid:!1,hasReceipted:!1,error:!1}};return this.threads.push(a),this.emitEvent({type:"threadCreated",threadId:a.threadId,thread:a}),a}async handleInboundMessage(e){let t=function(e){try{let t=JSON.parse(e);if("object"!=typeof t||1!==t.v||"string"!=typeof t.kind||"string"!=typeof t.threadId||"string"!=typeof t.id)return;return t}catch{return}}(e.body);if(null==t)return;let i=this.getOrCreateThreadFromInboundEnvelope(t,e);if(i.processedMessageIds.includes(e.messageId))return void await this.safeAck([e.messageId]);try{await this.applyInboundEnvelope(i,t,e),i.processedMessageIds.push(e.messageId),i.updatedAt=this.now(),await this.persistState(),await this.safeAck([e.messageId])}catch(e){this.markThreadError(i,e),await this.persistState()}}async applyInboundEnvelope(e,t,i){switch(e.protocolLog.push({direction:"in",envelope:t,transportMessageId:i.messageId}),this.emitEvent({type:"envelopeReceived",threadId:e.threadId,envelope:t,transportMessageId:i.messageId}),t.kind){case"identityVerificationRequest":{let r=t.payload;if("object"!=typeof r)throw Error("Identity verification request payload missing data");if(null==this.cfg.identityLayer)return void await this.sendTermination(e,i.sender,"Identity verification requested but no identity layer is configured");this.transitionThreadState(e,"identityRequested","identity request received"),this.emitEvent({type:"identityRequested",threadId:e.threadId,direction:"in",request:r});let n=await this.cfg.identityLayer.respondToRequest({counterparty:i.sender,threadId:e.threadId,request:r},this.moduleContext());if("terminate"===n.action)return void await this.sendTermination(e,i.sender,n.termination.message,n.termination.details,n.termination.code);let a=this.makeEnvelope("identityVerificationResponse",e.threadId,n.response),s=await this.sendEnvelope(i.sender,a);e.protocolLog.push({direction:"out",envelope:a,transportMessageId:s}),e.identity.certsSent=n.response.certificates,e.identity.responseSent=!0,this.transitionThreadState(e,"identityResponded","identity response sent"),this.emitEvent({type:"identityResponded",threadId:e.threadId,direction:"out",response:n.response});return}case"identityVerificationResponse":{let r=t.payload;if("object"!=typeof r)throw Error("Identity verification response payload missing data");if(null==this.cfg.identityLayer)return void await this.sendTermination(e,i.sender,"Identity verification response received but no identity layer is configured");e.identity.certsReceived=r.certificates,this.transitionThreadState(e,"identityResponded","identity response received"),this.emitEvent({type:"identityResponded",threadId:e.threadId,direction:"in",response:r});let n=await this.cfg.identityLayer.assessReceivedCertificateSufficiency(i.sender,r,e.threadId);if("message"in n)return void await this.sendTermination(e,i.sender,n.message,n.details,n.code);if("identityVerificationAcknowledgment"===n.kind){let t=this.makeEnvelope("identityVerificationAcknowledgment",e.threadId,n),r=await this.sendEnvelope(i.sender,t);e.protocolLog.push({direction:"out",envelope:t,transportMessageId:r}),e.identity.acknowledgmentSent=!0,e.flags.hasIdentified=!0,this.transitionThreadState(e,"identityAcknowledged","identity acknowledgment sent"),this.emitEvent({type:"identityAcknowledged",threadId:e.threadId,direction:"out",acknowledgment:n});return}throw Error("Unknown identity verification decision")}case"identityVerificationAcknowledgment":{let i=t.payload;if("object"!=typeof i)throw Error("Identity verification acknowledgment payload missing data");e.identity.acknowledgmentReceived=!0,e.flags.hasIdentified=!0,this.transitionThreadState(e,"identityAcknowledged","identity acknowledgment received"),this.emitEvent({type:"identityAcknowledged",threadId:e.threadId,direction:"in",acknowledgment:i});return}case"invoice":{let i=t.payload;if("object"!=typeof i)throw Error("Invoice payload missing invoice data");e.invoice=i,e.flags.hasInvoiced=!0,this.transitionThreadState(e,"invoiced","invoice received"),this.emitEvent({type:"invoiceReceived",threadId:e.threadId,invoice:i});return}case"settlement":{let r=t.payload;if("object"!=typeof r)throw Error("Settlement payload missing settlement data");if(this.shouldRequireIdentityBeforeSettlement(e)&&!e.flags.hasIdentified)return void await this.sendTermination(e,i.sender,"Identity verification is required before settlement");e.settlement=r,e.flags.hasPaid=!0,this.transitionThreadState(e,"settled","settlement received"),this.emitEvent({type:"settlementReceived",threadId:e.threadId,settlement:r});let n=this.moduleRegistry.get(r.moduleId);if("object"!=typeof n)return void await this.maybeSendTermination(e,r,i.sender,`Unsupported module: ${r.moduleId}`);if(null==e.invoice&&!n.allowUnsolicitedSettlements)return void await this.maybeSendTermination(e,r,i.sender,"Unsolicited settlement not supported");let a=await n.acceptSettlement({threadId:e.threadId,invoice:e.invoice,settlement:r.artifact,sender:i.sender},this.moduleContext()).catch(async t=>{let n=t instanceof Error?t.message:String(t);throw await this.maybeSendTermination(e,r,i.sender,`Settlement processing failed: ${n}`),t});if("accept"===a.action){let t=this.requireMyIdentityKey("Receiving settlement requires identity key"),n=i.sender,s={kind:"receipt",threadId:e.threadId,moduleId:r.moduleId,optionId:r.optionId,payee:t,payer:n,createdAt:this.now(),receiptData:a.receiptData};if(e.receipt=s,e.flags.hasReceipted=!0,this.transitionThreadState(e,"receipted","receipt issued"),this.runtime.receiptProvided&&this.runtime.autoIssueReceipt){let t=this.makeEnvelope("receipt",e.threadId,s),r=await this.sendEnvelope(i.sender,t);e.protocolLog.push({direction:"out",envelope:t,transportMessageId:r}),this.emitEvent({type:"receiptSent",threadId:e.threadId,receipt:s})}}else if("terminate"===a.action)await this.maybeSendTermination(e,r,i.sender,a.termination.message,a.termination.details);else throw Error("Unknown settlement acceptance action");return}case"receipt":{let r=t.payload;if("object"!=typeof r)throw Error("Receipt payload missing receipt data");e.receipt=r,e.flags.hasReceipted=!0,this.transitionThreadState(e,"receipted","receipt received"),this.emitEvent({type:"receiptReceived",threadId:e.threadId,receipt:r});let n=this.moduleRegistry.get(r.moduleId);n?.processReceipt!=null&&await n.processReceipt({threadId:e.threadId,invoice:e.invoice,receiptData:r.receiptData,sender:i.sender},this.moduleContext());return}case"termination":{let r=t.payload;if("object"!=typeof r)throw Error("Termination payload missing data");if(e.termination=r,e.lastError={message:r.message,at:this.now()},e.flags.error=!0,this.transitionThreadState(e,"terminated","termination received"),this.emitEvent({type:"terminationReceived",threadId:e.threadId,termination:r}),null!=e.settlement){let t=this.moduleRegistry.get(e.settlement.moduleId);t?.processTermination!=null&&await t.processTermination({threadId:e.threadId,invoice:e.invoice,settlement:e.settlement,termination:r,sender:i.sender},this.moduleContext())}return}default:{let e=t.kind;throw Error(`Unknown envelope kind: ${String(e)}`)}}}async maybeSendTermination(e,t,i,r,n){let a={code:"error",message:r,details:n},s=this.makeEnvelope("termination",e.threadId,a),o=await this.sendEnvelope(i,s);e.protocolLog.push({direction:"out",envelope:s,transportMessageId:o}),this.emitEvent({type:"terminationSent",threadId:e.threadId,termination:a}),e.termination=a,e.lastError={message:`Sent termination: ${r}`,at:this.now()},e.flags.error=!0,this.transitionThreadState(e,"terminated","termination sent")}async sendTermination(e,t,i,r,n="error"){let a={code:n,message:i,details:r},s=this.makeEnvelope("termination",e.threadId,a),o=await this.sendEnvelope(t,s);e.protocolLog.push({direction:"out",envelope:s,transportMessageId:o}),this.emitEvent({type:"terminationSent",threadId:e.threadId,termination:a}),e.termination=a,e.lastError={message:`Sent termination: ${i}`,at:this.now()},e.flags.error=!0,this.transitionThreadState(e,"terminated","termination sent")}shouldRequestIdentity(e,t){let{makerRequestIdentity:i="never",takerRequestIdentity:r="never"}=this.runtime.identityOptions??{};if(!("maker"===e.myRole?i===t:r===t))return!1;if(null==this.cfg.identityLayer)throw Error("Identity layer is required by runtime options but is not configured");return!0}shouldRequireIdentityBeforeSettlement(e){return"maker"===e.myRole&&(this.runtime.identityOptions?.makerRequestIdentity??"never")==="beforeSettlement"}async ensureIdentityExchange(e,t){if(null!=this.cfg.identityLayer&&!e.flags.hasIdentified){if(!e.identity.requestSent){let i=await this.cfg.identityLayer.determineCertificatesToRequest({counterparty:e.counterparty,threadId:e.threadId},this.moduleContext()),r=this.makeEnvelope("identityVerificationRequest",e.threadId,i),n=await this.sendEnvelope(e.counterparty,r,t);e.protocolLog.push({direction:"out",envelope:r,transportMessageId:n}),e.identity.requestSent=!0,this.transitionThreadState(e,"identityRequested","identity request sent"),this.emitEvent({type:"identityRequested",threadId:e.threadId,direction:"out",request:i}),e.updatedAt=this.now(),await this.persistState()}await this.waitForIdentityAcknowledgment(e.threadId,{timeoutMs:this.runtime.identityTimeoutMs,pollIntervalMs:this.runtime.identityPollIntervalMs})}}async waitForIdentityAcknowledgment(e,t={}){await this.waitForState(e,"identityAcknowledged",t)}async safeAck(e){try{await this.comms.acknowledgeMessage({messageIds:e})}catch(e){this.cfg.logger?.warn?.("[RemittanceManager] Failed to acknowledge message(s)",e)}}markThreadError(e,t){e.flags.error=!0,this.transitionThreadState(e,"errored","thread error"),e.lastError={message:String(t?.message??t),at:this.now()},this.cfg.logger?.error?.("[RemittanceManager] Thread error",e.threadId,t),this.emitEvent({type:"error",threadId:e.threadId,error:String(t?.message??t)})}ensureThreadState(e){return e.identity=e.identity??{certsSent:[],certsReceived:[],requestSent:!1,responseSent:!1,acknowledgmentSent:!1,acknowledgmentReceived:!1},e.identity.certsSent??=[],e.identity.certsReceived??=[],e.identity.requestSent??=!1,e.identity.responseSent??=!1,e.identity.acknowledgmentSent??=!1,e.identity.acknowledgmentReceived??=!1,e.flags=e.flags??{hasIdentified:!1,hasInvoiced:!1,hasPaid:!1,hasReceipted:!1,error:!1},e.processedMessageIds??=[],e.protocolLog??=[],e.stateLog??=[],null==e.state&&(e.state=this.deriveThreadState(e)),e}deriveThreadState(e){return e.flags.error?"errored":null!=e.termination?"terminated":null!=e.receipt?"receipted":null!=e.settlement?"settled":null!=e.invoice?"invoiced":e.identity.acknowledgmentReceived||e.identity.acknowledgmentSent||e.flags.hasIdentified?"identityAcknowledged":e.identity.responseSent||e.identity.certsSent.length>0?"identityResponded":e.identity.requestSent||e.identity.certsReceived.length>0?"identityRequested":"new"}transitionThreadState(e,t,i){let r=e.state;if(r!==t){if(!(al[r]??[]).includes(t))throw Error(`Invalid remittance state transition: ${r} -> ${t}`);e.state=t,e.updatedAt=this.now(),e.stateLog.push({at:this.now(),from:r,to:t,reason:i}),this.emitEvent({type:"stateChanged",threadId:e.threadId,previous:r,next:t,reason:i}),this.resolveStateWaiters(e.threadId,t),("terminated"===t||"errored"===t)&&this.rejectStateWaiters(e.threadId,Error(`Thread entered terminal state: ${t}`))}}resolveStateWaiters(e,t){let i=this.stateWaiters.get(e);if(null==i)return;let r=[];for(let e of i)e.state===t?e.resolve():r.push(e);0===r.length?this.stateWaiters.delete(e):this.stateWaiters.set(e,r)}rejectStateWaiters(e,t){let i=this.stateWaiters.get(e);if(null!=i){for(let e of i)e.reject(t);this.stateWaiters.delete(e)}}emitEvent(e){let t=this.eventHandlers;if(null!=t)try{switch(e.type){case"threadCreated":t.onThreadCreated?.(e);break;case"stateChanged":t.onStateChanged?.(e);break;case"envelopeSent":t.onEnvelopeSent?.(e);break;case"envelopeReceived":t.onEnvelopeReceived?.(e);break;case"identityRequested":t.onIdentityRequested?.(e);break;case"identityResponded":t.onIdentityResponded?.(e);break;case"identityAcknowledged":t.onIdentityAcknowledged?.(e);break;case"invoiceSent":t.onInvoiceSent?.(e);break;case"invoiceReceived":t.onInvoiceReceived?.(e);break;case"settlementSent":t.onSettlementSent?.(e);break;case"settlementReceived":t.onSettlementReceived?.(e);break;case"receiptSent":t.onReceiptSent?.(e);break;case"receiptReceived":t.onReceiptReceived?.(e);break;case"terminationSent":t.onTerminationSent?.(e);break;case"terminationReceived":t.onTerminationReceived?.(e);break;case"error":t.onError?.(e)}}catch(e){this.cfg.logger?.warn?.("[RemittanceManager] Event handler error",e)}for(let t of this.eventListeners)try{t(e)}catch(e){this.cfg.logger?.warn?.("[RemittanceManager] Event listener error",e)}}async refreshMyIdentityKey(){if("string"==typeof this.myIdentityKey||"object"!=typeof this.wallet)return;let{publicKey:e}=await this.wallet.getPublicKey({identityKey:!0},this.cfg.originator);"string"==typeof e&&""!==e.trim()&&(this.myIdentityKey=e)}requireMyIdentityKey(e){if("string"!=typeof this.myIdentityKey)throw Error(e);return this.myIdentityKey}async composeInvoice(e,t,i,r){let n=this.now(),a=this.runtime.invoiceExpirySeconds>=0?n+1e3*this.runtime.invoiceExpirySeconds:void 0;return{kind:"invoice",threadId:e,payee:t,payer:i,note:r.note,lineItems:r.lineItems,total:r.total,invoiceNumber:r.invoiceNumber??e,createdAt:n,expiresAt:a,arbitrary:r.arbitrary,options:{}}}}class af{manager;threadId;constructor(e,t){this.manager=e,this.threadId=t}get thread(){return this.manager.getThreadOrThrow(this.threadId)}async waitForState(e,t){return await this.manager.waitForState(this.threadId,e,t)}async waitForIdentity(e){return await this.manager.waitForIdentity(this.threadId,e)}async waitForSettlement(e){return await this.manager.waitForSettlement(this.threadId,e)}async waitForReceipt(e){return await this.manager.waitForReceipt(this.threadId,e)}}class ap extends af{get invoice(){let e=this.thread.invoice;if("object"!=typeof e)throw Error("Thread has no invoice");return e}async pay(e){return await this.manager.pay(this.threadId,e)}}function ag(){return tc(t0(32))}async function am(e){return await new Promise(t=>setTimeout(t,e))}let ay={createNonce:async(e,t,i)=>await nT(e,t,i)},ab={async pubKeyToP2PKHLockingScript(e){let t=tJ.fromString(e).toAddress();return new iL().lock(t).toHex()}};class aw{id="brc29.p2pkh";name="BSV (BRC-29 derived P2PKH)";allowUnsolicitedSettlements=!0;protocolID;labels;description;outputDescription;refundFeeSatoshis;minRefundSatoshis;internalizeProtocol;nonceProvider;lockingScriptProvider;constructor(e={}){this.protocolID=e.protocolID??[2,"3241645161d8"],this.labels=e.labels??["brc29"],this.description=e.description??"BRC-29 payment",this.outputDescription=e.outputDescription??"Payment for remittance invoice",this.refundFeeSatoshis=e.refundFeeSatoshis??1e3,this.minRefundSatoshis=e.minRefundSatoshis??1e3,this.internalizeProtocol=e.internalizeProtocol??"wallet payment",this.nonceProvider=e.nonceProvider??ay,this.lockingScriptProvider=e.lockingScriptProvider??ab}async buildSettlement(e,t){let i,{wallet:r,originator:n}=t;try{i=function(e){if(null==e||"object"!=typeof e)throw Error("BRC-29 option terms are required");let t=e.amountSatoshis;if(!Number.isInteger(t)||t<=0)throw Error("BRC-29 option amount must be a positive integer");let i=e.outputIndex;if(null!=i&&(!Number.isInteger(i)||i<0))throw Error("BRC-29 option outputIndex must be a non-negative integer");let r=e.protocolID;if(null!=r){if(!Array.isArray(r)||2!==r.length)throw Error("BRC-29 option protocolID must be a tuple [number, string]");let[e,t]=r;if(!Number.isInteger(e)||e<0||!ak(t))throw Error("BRC-29 option protocolID must be a tuple [number, string]")}let n=e.labels;if(null!=n&&(!Array.isArray(n)||n.some(e=>!ak(e))))throw Error("BRC-29 option labels must be a list of non-empty strings");let a=e.description;if(null!=a&&!ak(a))throw Error("BRC-29 option description must be a non-empty string");return e}(e.option)}catch(e){return av("brc29.invalid_option",e instanceof Error?e.message:String(e))}let a=i.amountSatoshis;try{let t=await this.nonceProvider.createNonce(r,"self",n),s=await this.nonceProvider.createNonce(r,"self",n),o=i.protocolID??this.protocolID,c=`${t} ${s}`,{publicKey:l}=await r.getPublicKey({protocolID:o,keyID:c,counterparty:i.payee},n);if("string"!=typeof l||""===l.trim())return av("brc29.public_key_missing","Failed to derive payee public key for BRC-29 settlement.");let h=await this.lockingScriptProvider.pubKeyToP2PKHLockingScript(l);if("string"!=typeof h||""===h.trim())return av("brc29.locking_script_missing","Failed to produce P2PKH locking script.");let d=await r.createAction({description:i.description??this.description,labels:i.labels??this.labels,outputs:[{satoshis:a,lockingScript:h,customInstructions:JSON.stringify({derivationPrefix:t,derivationSuffix:s,payee:i.payee,threadId:e.threadId,note:e.note}),outputDescription:this.outputDescription}],options:{randomizeOutputs:!1}},n),u=d.tx??d.signableTransaction?.tx;if(null==u)return av("brc29.missing_tx","wallet.createAction did not return a transaction.");if(!aI(u))return av("brc29.invalid_tx","wallet.createAction returned an invalid transaction payload.");return{action:"settle",artifact:{customInstructions:{derivationPrefix:t,derivationSuffix:s},transaction:u,amountSatoshis:i.amountSatoshis,outputIndex:i.outputIndex??0}}}catch(t){let e=t instanceof Error?t.message:String(t);return av("brc29.build_failed",`BRC-29 settlement failed: ${e}`)}}async acceptSettlement(e,t){let{wallet:i,originator:r}=t;console.log("acceptSettlement",e);try{let t=function(e){if(null==e||"object"!=typeof e)throw Error("BRC-29 settlement artifact is required");let t=e.customInstructions;if(null==t||"object"!=typeof t)throw Error("BRC-29 settlement requires customInstructions");if(!ak(t.derivationPrefix)||!ak(t.derivationSuffix))throw Error("BRC-29 settlement derivation values are required");let i=e.amountSatoshis;if(!Number.isInteger(i)||i<=0)throw Error("BRC-29 settlement amount must be a positive integer");let r=e.outputIndex;if(null!=r&&(!Number.isInteger(r)||r<0))throw Error("BRC-29 settlement outputIndex must be a non-negative integer");if(!aI(e.transaction))throw Error("BRC-29 settlement transaction must be a non-empty byte array");return e}(e.settlement),n=t.outputIndex??0,a=await i.internalizeAction({tx:t.transaction,outputs:[{paymentRemittance:{derivationPrefix:t.customInstructions.derivationPrefix,derivationSuffix:t.customInstructions.derivationSuffix,senderIdentityKey:e.sender},outputIndex:n,protocol:this.internalizeProtocol}],labels:this.labels,description:"BRC-29 payment received"},r);return{action:"accept",receiptData:{internalizeResult:a}}}catch(t){let e=t instanceof Error?t.message:String(t);return av("brc29.internalize_failed",`Failed to internalize BRC-29 settlement: ${e}`)}}}function av(e,t,i){return{action:"terminate",termination:{code:e,message:t,details:i}}}function aI(e){return!!Array.isArray(e)&&0!==e.length&&e.every(e=>Number.isInteger(e)&&e>=0&&e<=255)}function ak(e){return"string"==typeof e&&e.trim().length>0}return p})());
20
20
  //# sourceMappingURL=bundle.js.map