@bsv/sdk 1.8.0 → 1.8.1

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 (52) hide show
  1. package/dist/cjs/package.json +1 -1
  2. package/dist/cjs/src/kvstore/GlobalKVStore.js +420 -0
  3. package/dist/cjs/src/kvstore/GlobalKVStore.js.map +1 -0
  4. package/dist/cjs/src/kvstore/LocalKVStore.js +6 -6
  5. package/dist/cjs/src/kvstore/LocalKVStore.js.map +1 -1
  6. package/dist/cjs/src/kvstore/kvStoreInterpreter.js +74 -0
  7. package/dist/cjs/src/kvstore/kvStoreInterpreter.js.map +1 -0
  8. package/dist/cjs/src/kvstore/types.js +11 -0
  9. package/dist/cjs/src/kvstore/types.js.map +1 -0
  10. package/dist/cjs/src/overlay-tools/Historian.js +153 -0
  11. package/dist/cjs/src/overlay-tools/Historian.js.map +1 -0
  12. package/dist/cjs/src/script/templates/PushDrop.js +2 -2
  13. package/dist/cjs/src/script/templates/PushDrop.js.map +1 -1
  14. package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
  15. package/dist/esm/src/kvstore/GlobalKVStore.js +416 -0
  16. package/dist/esm/src/kvstore/GlobalKVStore.js.map +1 -0
  17. package/dist/esm/src/kvstore/LocalKVStore.js +6 -6
  18. package/dist/esm/src/kvstore/LocalKVStore.js.map +1 -1
  19. package/dist/esm/src/kvstore/kvStoreInterpreter.js +47 -0
  20. package/dist/esm/src/kvstore/kvStoreInterpreter.js.map +1 -0
  21. package/dist/esm/src/kvstore/types.js +8 -0
  22. package/dist/esm/src/kvstore/types.js.map +1 -0
  23. package/dist/esm/src/overlay-tools/Historian.js +155 -0
  24. package/dist/esm/src/overlay-tools/Historian.js.map +1 -0
  25. package/dist/esm/src/script/templates/PushDrop.js +2 -2
  26. package/dist/esm/src/script/templates/PushDrop.js.map +1 -1
  27. package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
  28. package/dist/types/src/kvstore/GlobalKVStore.d.ts +129 -0
  29. package/dist/types/src/kvstore/GlobalKVStore.d.ts.map +1 -0
  30. package/dist/types/src/kvstore/kvStoreInterpreter.d.ts +22 -0
  31. package/dist/types/src/kvstore/kvStoreInterpreter.d.ts.map +1 -0
  32. package/dist/types/src/kvstore/types.d.ts +106 -0
  33. package/dist/types/src/kvstore/types.d.ts.map +1 -0
  34. package/dist/types/src/overlay-tools/Historian.d.ts +92 -0
  35. package/dist/types/src/overlay-tools/Historian.d.ts.map +1 -0
  36. package/dist/types/src/script/templates/PushDrop.d.ts +6 -5
  37. package/dist/types/src/script/templates/PushDrop.d.ts.map +1 -1
  38. package/dist/types/tsconfig.types.tsbuildinfo +1 -1
  39. package/dist/umd/bundle.js +1 -1
  40. package/dist/umd/bundle.js.map +1 -1
  41. package/docs/reference/script.md +7 -19
  42. package/docs/reference/transaction.md +53 -2
  43. package/package.json +1 -1
  44. package/src/kvstore/GlobalKVStore.ts +478 -0
  45. package/src/kvstore/LocalKVStore.ts +7 -7
  46. package/src/kvstore/__tests/GlobalKVStore.test.ts +965 -0
  47. package/src/kvstore/__tests/LocalKVStore.test.ts +72 -0
  48. package/src/kvstore/kvStoreInterpreter.ts +49 -0
  49. package/src/kvstore/types.ts +114 -0
  50. package/src/overlay-tools/Historian.ts +195 -0
  51. package/src/overlay-tools/__tests/Historian.test.ts +690 -0
  52. package/src/script/templates/PushDrop.ts +6 -5
@@ -16,5 +16,5 @@ ${r.path[0].filter(e=>!0===e.txid).map(e=>` '${e.hash??""}'`).join(",\n")}
16
16
  `,r.inputTxids.length>0&&(e+=` inputs: [
17
17
  ${r.inputTxids.map(e=>` '${e}'`).join(",\n")}
18
18
  ]
19
- `);return e}addComputedLeaves(){let e=e=>eK(W(eF(e,"hex").reverse()).reverse());for(let t of this.bumps)for(let r=1;r<t.path.length;r++)for(let i of t.path[r-1])if("string"==typeof i.hash&&(1&i.offset)==0){let a=t.path[r-1].find(e=>e.offset===i.offset+1),n=i.offset>>1;void 0!==a&&"string"==typeof a.hash&&t.path[r].every(e=>e.offset!==n)&&t.path[r].push({offset:n,hash:e(a.hash+i.hash)})}}}class rg{version;inputs;outputs;lockTime;metadata;merklePath;cachedHash;static addPathOrInputs(e,t,r){if("number"==typeof e.pathIndex){let t=r[e.pathIndex];if("object"!=typeof t)throw Error("Invalid merkle path index found in BEEF!");e.tx.merklePath=t}else for(let i of e.tx.inputs){if(void 0===i.sourceTXID)throw Error("Input sourceTXID is undefined");let e=t[i.sourceTXID];if("object"!=typeof e)throw Error(`Reference to unknown TXID in BEEF: ${i.sourceTXID??"undefined"}`);i.sourceTransaction=e.tx,this.addPathOrInputs(e,t,r)}}static fromBEEF(e,t){let{tx:r}=rg.fromAnyBeef(e,t);return r}static fromAtomicBEEF(e){let{tx:t,txid:r,beef:i}=rg.fromAnyBeef(e);if(r!==i.atomicTxid)if(null!=i.atomicTxid)throw Error(`Transaction with TXID ${i.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 r=rb.fromBinary(e);if(r.txs.length<1)throw Error("beef must include at least one transaction.");let i=t??r.atomicTxid??r.txs.slice(-1)[0].txid,a=r.findAtomicTransaction(i);if(null==a)if(null!=t)throw Error(`Transaction with TXID ${i} not found in BEEF data.`);else throw Error("beef does not contain transaction for atomic txid.");return{tx:a,beef:r,txid:i}}static fromEF(e){let t=new eQ(e),r=t.readUInt32LE();if("0000000000ef"!==eK(t.read(6)))throw Error("Invalid EF marker");let i=t.readVarIntNum(),a=[];for(let e=0;e<i;e++){let e=eK(t.readReverse(32)),r=t.readUInt32LE(),i=t.readVarIntNum(),n=t.read(i),s=tZ.fromBinary(n),o=t.readUInt32LE(),c=t.readUInt64LEBn().toNumber(),l=t.readVarIntNum(),h=t.read(l),d=tJ.fromBinary(h),u=new rg(void 0,[],[],void 0);u.outputs=Array(r+1).fill(null),u.outputs[r]={satoshis:c,lockingScript:d},a.push({sourceTransaction:u,sourceTXID:e,sourceOutputIndex:r,unlockingScript:s,sequence:o})}let n=t.readVarIntNum(),s=[];for(let e=0;e<n;e++){let e=t.readUInt64LEBn().toNumber(),r=t.readVarIntNum(),i=t.read(r),a=tJ.fromBinary(i);s.push({satoshis:e,lockingScript:a})}return new rg(r,a,s,t.readUInt32LE())}static parseScriptOffsets(e){let t=new eQ(e),r=[],i=[];t.pos+=4;let a=t.readVarIntNum();for(let e=0;e<a;e++){t.pos+=36;let i=t.readVarIntNum();r.push({vin:e,offset:t.pos,length:i}),t.pos+=i+4}let n=t.readVarIntNum();for(let e=0;e<n;e++){t.pos+=8;let r=t.readVarIntNum();i.push({vout:e,offset:t.pos,length:r}),t.pos+=r}return{inputs:r,outputs:i}}static fromReader(e){let t=e.readUInt32LE(),r=e.readVarIntNum(),i=[];for(let t=0;t<r;t++){let t=eK(e.readReverse(32)),r=e.readUInt32LE(),a=e.readVarIntNum(),n=e.read(a),s=tZ.fromBinary(n),o=e.readUInt32LE();i.push({sourceTXID:t,sourceOutputIndex:r,unlockingScript:s,sequence:o})}let a=e.readVarIntNum(),n=[];for(let t=0;t<a;t++){let t=e.readUInt64LEBn().toNumber(),r=e.readVarIntNum(),i=e.read(r),a=tJ.fromBinary(i);n.push({satoshis:t,lockingScript:a})}return new rg(t,i,n,e.readUInt32LE())}static fromBinary(e){let t=new eQ(e);return rg.fromReader(t)}static fromHex(e){return rg.fromBinary(eF(e,"hex"))}static fromHexEF(e){return rg.fromEF(eF(e,"hex"))}static fromHexBEEF(e,t){return rg.fromBEEF(eF(e,"hex"),t)}constructor(e=1,t=[],r=[],i=0,a=new Map,n){this.version=e,this.inputs=t,this.outputs=r,this.lockTime=i,this.metadata=a,this.merklePath=n}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.cachedHash=void 0,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 r=new t3().lock(e);if(void 0===t)return this.addOutput({lockingScript:r,change:!0});this.addOutput({lockingScript:r,satoshis:t})}updateMetadata(e){this.metadata={...this.metadata,...e}}async fee(e=re.getInstance(),t="equal"){if(this.cachedHash=void 0,"number"==typeof e){let t=e;e={computeFee:async()=>t}}let r=await e.computeFee(this),i=this.calculateChange(r);if(i<=0){this.outputs=this.outputs.filter(e=>!0!==e.change);return}this.distributeChange(i,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 r of(t-=e,this.outputs))!0!==r.change&&void 0!==r.satoshis&&(t-=r.satoshis);return t}distributeChange(e,t){let r=0,i=this.outputs.filter(e=>e.change);if("random"===t?r=this.distributeRandomChange(e,i):"equal"===t&&(r=this.distributeEqualChange(e,i)),r<e){let t=this.outputs[this.outputs.length-1];void 0!==t.satoshis?t.satoshis+=e-r:t.satoshis=e-r}}distributeRandomChange(e,t){let r=0,i=e,a=Array(t.length).fill(1);i-=t.length,r+=t.length;for(let e=0;e<t.length-1;e++){let t=this.benfordNumber(0,i);a[e]=a[e]+t,r+=t,i-=t}for(let e of this.outputs)!0===e.change&&(e.satoshis=a.shift());return r}distributeEqualChange(e,t){let r=0,i=Math.floor(e/t.length);for(let e of t)r+=i,e.satoshis=i;return r}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.cachedHash=void 0,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,r=this.inputs.length;t<r;t++)"object"==typeof this.inputs[t].unlockingScriptTemplate&&(this.inputs[t].unlockingScript=e[t])}async broadcast(e=rs()){return await e.broadcast(this)}toBinary(){let e=new eZ;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(eF(t.sourceTXID,"hex"));if(e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw Error("unlockingScript is undefined");let r=t.unlockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r),e.writeUInt32LE(t.sequence??0)}for(let t of(e.writeVarIntNum(this.outputs.length),this.outputs)){e.writeUInt64LE(t.satoshis??0);let r=t.lockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r)}return e.writeUInt32LE(this.lockTime),e.toArray()}toEF(){let e=new eZ;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(eF(t.sourceTXID,"hex").reverse()),e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw Error("unlockingScript is undefined");let r=t.unlockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r),e.writeUInt32LE(t.sequence??0),e.writeUInt64LE(t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0);let i=t.sourceTransaction.outputs[t.sourceOutputIndex].lockingScript.toBinary();e.writeVarIntNum(i.length),e.write(i)}for(let t of(e.writeVarIntNum(this.outputs.length),this.outputs)){e.writeUInt64LE(t.satoshis??0);let r=t.lockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r)}return e.writeUInt32LE(this.lockTime),e.toArray()}toHexEF(){return eK(this.toEF())}toHex(){return eK(this.toBinary())}toHexBEEF(){return eK(this.toBEEF())}toHexAtomicBEEF(){return eK(this.toAtomicBEEF())}hash(e){let t;return(null!=this.cachedHash?t=this.cachedHash:(t=W(this.toBinary()),this.cachedHash=t),"hex"===e)?eK(t):t}id(e){let t=[...this.hash()];return(t.reverse(),"hex"===e)?eK(t):t}async verify(e=rc(),t,r){let i=new Set,a=[this];for(;a.length>0;){let n=a.shift(),s=n?.id("hex")??"";if(null!=s&&""!==s&&i.has(s))continue;if("object"==typeof n?.merklePath)if("scripts only"===e){null!=s&&i.add(s);continue}else{if(await n.merklePath.verify(s,e)){i.add(s);continue}throw Error(`Invalid merkle path for transaction ${s}`)}if(void 0!==t){if(void 0===n)throw Error("Transaction is undefined");let e=rg.fromEF(n.toEF());if(delete e.outputs[0].satoshis,e.outputs[0].change=!0,await e.fee(t),n.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===n)throw Error("Transaction is undefined");for(let e=0;e<n.inputs.length;e++){let t=n.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");i.has(l)||a.push(t.sourceTransaction);let h=n.inputs.filter((t,r)=>r!==e);if(void 0===t.sourceTXID&&(t.sourceTXID=l),!new t2({sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,lockingScript:c.lockingScript,sourceSatoshis:c.satoshis??0,transactionVersion:n.version,otherInputs:h,unlockingScript:t.unlockingScript,inputSequence:t.sequence??0,inputIndex:e,outputs:n.outputs,lockTime:n.lockTime,memoryLimit:r}).validate())return!1}let c=0;for(let e of n.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;i.add(s)}return!0}toBEEF(e){let t=new eZ;t.writeUInt32LE(ru);let r=[],i=new Map,a=new Map,n=[],s=new Set,o=t=>{let c=t.id("hex");if(s.has(c))return;let l={tx:t},h=t.merklePath,d="object"==typeof h;if(d&&null!=h&&(l.pathIndex=(e=>{let t=i.get(e);if(void 0!==t)return t;let n=`${e.blockHeight}:${e.computeRoot()}`,s=a.get(n);if(void 0!==s)return r[s].combine(e),i.set(e,s),s;let o=r.length;return r.push(e),i.set(e,o),a.set(n,o),o})(h)),!d)for(let r=t.inputs.length-1;r>=0;r--){let i=t.inputs[r];if("object"==typeof i.sourceTransaction)o(i.sourceTransaction);else if(!1===e)throw Error("A required source transaction is missing!")}s.add(c),n.push(l)};for(let e of(o(this),t.writeVarIntNum(r.length),r))t.write(e.toBinary());for(let e of(t.writeVarIntNum(n.length),n))t.write(e.tx.toBinary()),"number"==typeof e.pathIndex?(t.writeUInt8(1),t.writeVarIntNum(e.pathIndex)):t.writeUInt8(0);return t.toArray()}toAtomicBEEF(e){let t=new eZ;t.writeUInt32LE(0x1010101),t.write(this.hash());let r=this.toBEEF(e);return t.write(r),t.toArray()}}function rm(e){return"success"===e.status}function ry(e){return"error"===e.status}let rw=class extends rb{knownTo={};constructor(e){if(super(),null!=e)for(let 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),r=this.clone();return r.trimKnownTxids(t),r}addKnownTxidsForParty(e,t){this.isParty(e)||this.addParty(e);let r=this.knownTo[e];for(let e of t)r[e]=!0,this.mergeTxidOnly(e)}mergeBeefFromParty(e,t){let r=Array.isArray(t)?rb.fromBinary(t):t,i=r.getValidTxids();this.mergeBeef(r),this.addKnownTxidsForParty(e,i)}};class rI{network;URL;httpClient;constructor(e="main",t=ri()){this.network=e,this.URL=`https://api.whatsonchain.com/v1/bsv/${e}/tx/raw`,this.httpClient=t}async broadcast(e){let t=e.toHex();try{let e=await this.httpClient.request(this.URL,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/plain"},data:{txhex:t}});if(!e.ok)return{status:"error",code:e.status.toString()??"ERR_UNKNOWN",description:e.data??"Unknown error"};{let t=e.data;return{status:"success",txid:t,message:"broadcast successful"}}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class rv{https;constructor(e){this.https=e}async request(e,t){return await new Promise((r,i)=>{let a=this.https.request(e,t,e=>{let t="";e.on("data",e=>{t+=e}),e.on("end",()=>{let i=e.statusCode>=200&&e.statusCode<=299,a=e.headers["content-type"],n=""!==t&&"string"==typeof a&&a.startsWith("application/json")?JSON.parse(t):t;r({status:e.statusCode,statusText:e.statusMessage,ok:i,data:n})})});a.on("error",e=>{i(e)}),null!==t.data&&void 0!==t.data&&a.write(Buffer.from(t.data)),a.end()})}}class rk{fetch;constructor(e){this.fetch=e}async request(e,t){let r={method:t.method,headers:t.headers,body:t.data},i=await this.fetch(e,r),a=await i.text();return{ok:i.ok,status:i.status,statusText:i.statusText,data:a}}}function rS(){let e={async request(){throw Error("No method available to perform HTTP request")}};if("undefined"!=typeof window&&"function"==typeof window.fetch)return new rk(window.fetch.bind(window));if("undefined"==typeof require)return e;try{let e=require("https");return new rv(e)}catch(t){return e}}class rx{URL;httpClient;constructor(e,t=rS()){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 r=await this.httpClient.request(this.URL,t);if(!r.ok)return{status:"error",code:r.status.toString()??"ERR_UNKNOWN",description:r.data??"Unknown error"};{let t=e.id("hex");return{status:"success",txid:t,message:"broadcast successful"}}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class rE{baseUrl;httpClient;apiKey;constructor(e,t={}){let{httpClient:r,apiKey:i}=t;this.baseUrl=e,this.httpClient=r??ri(),this.apiKey=i??""}async isValidRootForHeight(e,t){let r={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`,r);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",rP=(e,t,r)=>{let i="object"!=typeof r;if(i){let e=new td,t=new tO(1),i=e.g.mul(t);r=new tv(i.x,i.y)}let a=tx(32),n=eW(a),s=`2-message signing-${n}`,o=t.deriveChild(r,s).sign(e).toDER(),c=t.toPublicKey().encode(!0);return[...eF(rN,"hex"),...c,...i?[0]:r.encode(!0),...a,...o]},rO=(e,t,r)=>{let i=new eQ(t),a=eK(i.read(4));if(a!==rN)throw Error(`Message version mismatch: Expected ${rN}, received ${a}`);let n=tv.fromString(eK(i.read(33))),[s]=i.read(1);if(0===s)r=new tO(1);else{let e=eK([s,...i.read(32)]);if("object"!=typeof r)throw Error(`This signature can only be verified with knowledge of a specific private key. The associated public key is: ${e}`);let t=r.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=eW(i.read(32)),c=eK(i.read(i.bin.length-i.pos)),l=tu.fromDER(c,"hex"),h=`2-message signing-${o}`;return n.deriveChild(r,h).verify(e,l)},r_="42421033",rA=(e,t,r)=>{let i=tx(32),a=eW(i),n=`2-message encryption-${a}`,s=t.deriveChild(r,n),o=r.deriveChild(t,n),c=new tz(s.deriveSharedSecret(o).encode(!0).slice(1)).encrypt(e),l=t.toPublicKey().encode(!0);return[...eF(r_,"hex"),...l,...r.encode(!0),...i,...c]},rT=(e,t)=>{let r=new eQ(e),i=eK(r.read(4));if(i!==r_)throw Error(`Message version mismatch: Expected ${r_}, received ${i}`);let a=tv.fromString(eK(r.read(33))),n=eK(r.read(33)),s=t.toPublicKey().encode(!0,"hex");if(n!==s)throw Error(`The encrypted message expects a recipient public key of ${n}, but the provided key is ${s}`);let o=eW(r.read(32)),c=r.read(r.bin.length-r.pos),l=`2-message encryption-${o}`,h=a.deriveChild(t,l),d=t.deriveChild(a,l);return new tz(h.deriveSharedSecret(d).encode(!0).slice(1)).decrypt(c)},rC="Bitcoin Signed Message:\n",rR=e=>{let t=new eZ;return t.writeVarIntNum(rC.length),t.write(eF(rC,"utf8")),t.writeVarIntNum(e.length),t.write(e),W(t.toArray())},rV=(e,t,r="base64")=>{let i=rR(e),a=tw(new p(i),t,!0);if("raw"===r)return a;let n=new p(i),s=a.CalculateRecoveryFactor(t.toPublicKey(),n);return a.toCompact(s,!0,"base64")},rU=(e,t,r)=>tI(new p(rR(e)),t,r);class rD{versionBytesNum;depth;parentFingerPrint;childIndex;chainCode;privKey;pubKey;constants={pubKey:0x488b21e,privKey:0x488ade4};constructor(e,t,r,i,a,n,s){this.versionBytesNum=e,this.depth=t,this.parentFingerPrint=r,this.childIndex=i,this.chainCode=a,this.privKey=n,this.pubKey=s}fromRandom(){return this.versionBytesNum=this.constants.privKey,this.depth=0,this.parentFingerPrint=[0,0,0,0],this.childIndex=0,this.chainCode=tx(32),this.privKey=tO.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=eJ(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=X(eF("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 tO(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 eQ(e);this.versionBytesNum=t.readUInt32BE(),this.depth=t.readUInt8(),this.parentFingerPrint=t.read(4),this.childIndex=t.readUInt32BE(),this.chainCode=t.read(32);let r=t.read(33),i=this.versionBytesNum===this.constants.privKey,a=this.versionBytesNum===this.constants.pubKey;if(i&&0===r[0])this.privKey=new tO(r.slice(1,33)),this.pubKey=this.privKey.toPublicKey();else if(a&&(2===r[0]||3===r[0]))this.pubKey=tv.fromString(eK(r));else throw Error("Invalid key");return this}toString(){return eY(this.toBinary(),[])}derive(e){if("m"===e)return this;let t=e.split("/"),r=this;for(let[e,i]of t.entries()){if(0===e){if("m"!==i)throw Error("invalid path");continue}if(parseInt(i.replace("'",""),10).toString()!==i.replace("'",""))throw Error("invalid path");let t=i.length>1&&"'"===i[i.length-1],a=0x7fffffff&parseInt(t?i.slice(0,i.length-1):i,10);t&&(a+=0x80000000),r=r.deriveChild(a)}return r}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 r=[...t],i=(0x80000000&e)!=0,a=this.versionBytesNum===this.constants.privKey;if(i&&(null===this.privKey||void 0===this.privKey||!a))throw Error("Cannot do private key derivation without private key");let n=null;if(null!==this.privKey&&void 0!==this.privKey){let e=null;e=i?[0,...this.privKey.toArray("be",32),...r]:[...this.pubKey.encode(!0),...r];let t=X(this.chainCode,e),a=new p(t.slice(0,32)),s=t.slice(32,64),o=a.add(this.privKey).mod(new td().n);(n=new rD).chainCode=s,n.privKey=new tO(o.toArray()),n.pubKey=n.privKey.toPublicKey()}else{let e=[...this.pubKey.encode(!0),...r],t=X(this.chainCode,e),i=new p(t.slice(0,32)),a=t.slice(32,64),s=new td().g.mul(i),o=this.pubKey,c=s.add(o),l=new tv(c.x,c.y);(n=new rD).chainCode=a,n.pubKey=l}n.childIndex=e;let s=j(this.pubKey.encode(!0));return n.parentFingerPrint=s.slice(0,4),n.versionBytesNum=this.versionBytesNum,n.depth=this.depth+1,n}toPublic(){let e=new rD(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 eZ().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 eZ().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 rB={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 rH{mnemonic;seed;Wordlist;constructor(e,t,r=rB){this.mnemonic=e??"",this.seed=t??[],this.Wordlist=r}toBinary(){let e=new eZ;if(""!==this.mnemonic){let t=eF(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 eQ(e),r=t.readVarIntNum();r>0&&(this.mnemonic=ez(t.read(r),"utf8"));let i=t.readVarIntNum();return i>0&&(this.seed=t.read(i)),this}fromRandom(e){if((null==e||isNaN(e)||0===e)&&(e=128),e%32!=0)throw Error("bits must be multiple of 32");if(e<128)throw Error("bits must be at least 128");let t=tx(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=$(e),r="",i=8*e.length;for(let t=0;t<e.length;t++)r+=("00000000"+e[t].toString(2)).slice(-8);let a=t[0].toString(2);if((r+=a=("00000000"+a).slice(-8).slice(0,i/32)).length%11!=0)throw Error("internal error - entropy not an even multiple of 11 bits - "+r.length.toString());let n="";for(let e=0;e<r.length/11;e++){""!==n&&(n+=this.Wordlist.space);let t=parseInt(r.slice(11*e,(e+1)*11),2);n+=this.Wordlist.value[t]}return this.mnemonic=n,this}check(){let e=this.mnemonic.split(this.Wordlist.space),t="";for(let r=0;r<e.length;r++){let i=this.Wordlist.value.indexOf(e[r]);if(i<0)return!1;t+=("00000000000"+i.toString(2)).slice(-11)}if(t.length%11!=0)throw Error("internal error - entropy not an even multiple of 11 bits - "+t.length.toString());let r=t.length/33,i=t.slice(-r),a=t.slice(0,t.length-r),n=[];for(let e=0;e<a.length/8;e++)n.push(parseInt(t.slice(8*e,(e+1)*8),2));let s=$(n.slice(0,a.length/8))[0].toString(2);return(s=("00000000"+s).slice(-8).slice(0,r))===i}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 r=eF(t,"utf8"),i=[...eF("mnemonic","utf8"),...eF(e,"utf8")];return this.seed=eH(r,i,2048,64,"sha512"),this}isValid(e=""){let t;try{this.mnemonic2Seed(e),t=!0}catch{t=!1}return t}static isValid(e,t=""){return new rH(e).isValid(t)}}function rL(e){let t,r,i,a;0===this._tables[0][0][0]&&this._precompute();let n=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=[r=e.slice(0),i=[]],a=o;a<4*o+28;a++)t=r[a-1],(a%o==0||8===o&&a%o==4)&&(t=n[t>>>24]<<24^n[t>>16&255]<<16^n[t>>8&255]<<8^n[255&t],a%o==0&&(t=t<<8^t>>>24^c<<24,c=c<<1^(c>>7)*283)),r[a]=r[a-o]^t;for(let e=0;a>0;e++,a--)t=r[(3&e)!=0?a:a-4],a<=4||e<4?i[e]=t:i[e]=s[0][n[t>>>24]]^s[1][n[t>>16&255]]^s[2][n[t>>8&255]]^s[3][n[255&t]]}rL.prototype={encrypt:function(e){return this._crypt(e,0)},decrypt:function(e){return this._crypt(e,1)},_tables:[[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)]],_precompute:function(){let e,t,r,i,a,n,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=r=0;0===h[t];t^=0!==i?i:1,r=0!==f[r]?f[r]:1)for(e=0,n=(n=r^r<<1^r<<2^r<<3^r<<4)>>8^255&n^99,h[t]=n,d[n]=t,o=0x1010101*u[a=u[i=u[t]]]^65537*a^257*i^0x1010100*t,s=257*u[n]^0x1010100*n;e<4;e++)c[e][t]=s=s<<24^s>>>8,l[e][n]=o=o<<24^o>>>8},_crypt:function(e,t){let r,i,a,n;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],b=p[0],g=p[1],m=p[2],y=p[3],w=p[4];for(n=0;n<d;n++)r=b[o>>>24]^g[c>>16&255]^m[l>>8&255]^y[255&h]^s[u],i=b[c>>>24]^g[l>>16&255]^m[h>>8&255]^y[255&o]^s[u+1],a=b[l>>>24]^g[h>>16&255]^m[o>>8&255]^y[255&c]^s[u+2],h=b[h>>>24]^g[o>>16&255]^m[c>>8&255]^y[255&l]^s[u+3],u+=4,o=r,c=i,l=a;for(n=0;n<4;n++)f[1===t?3&-n:n]=w[o>>>24]<<24^w[c>>16&255]<<16^w[l>>8&255]<<8^w[255&h]^s[u++],r=o,o=c,c=l,l=h,h=r;return f}};class rK{static encrypt(e,t){let r=rK.buf2Words(t),i=rK.buf2Words(e),a=new rL(r).encrypt(i);return rK.words2Buf(a)}static decrypt(e,t){let r=rK.buf2Words(e),i=new rL(rK.buf2Words(t)).decrypt(r);return rK.words2Buf(i)}static buf2Words(e){if(e.length%4!=0)throw Error("buf length must be a multiple of 4");let t=[];for(let r=0;r<e.length/4;r++){let i=0x1000000*e[4*r]+(e[4*r+1]<<16|e[4*r+2]<<8|e[4*r+3]);t.push(i)}return t}static words2Buf(e){let t=Array(4*e.length);for(let r=0;r<e.length;r++){let i=e[r];t[4*r]=i>>>24&255,t[4*r+1]=i>>>16&255,t[4*r+2]=i>>>8&255,t[4*r+3]=255&i}return t}}class rF{static buf2BlocksBuf(e,t){let r=t/8,i=[];for(let a=0;a<=e.length/r;a++){let n=e.slice(a*r,a*r+r);n.length<t&&(n=rF.pkcs7Pad(n,t)),i.push(n)}return i}static blockBufs2Buf(e){let t=e[e.length-1];return t=rF.pkcs7Unpad(t),e[e.length-1]=t,e.flat()}static encrypt(e,t,r,i){let a=8*t.length,n=rF.buf2BlocksBuf(e,a);return rF.encryptBlocks(n,t,r,i).flat()}static decrypt(e,t,r,i){let a=t.length,n=[];for(let t=0;t<e.length/a;t++)n.push(e.slice(t*a,t*a+a));let s=rF.decryptBlocks(n,t,r,i);return rF.blockBufs2Buf(s)}static encryptBlock(e,t,r,i){let a=rF.xorBufs(e,t);return r.encrypt(a,i)}static decryptBlock(e,t,r,i){let a=r.decrypt(e,i);return rF.xorBufs(a,t)}static encryptBlocks(e,t,r,i){let a=[];for(let n=0;n<e.length;n++){let s=e[n],o=rF.encryptBlock(s,t,r,i);a.push(o),t=o}return a}static decryptBlocks(e,t,r,i){let a=[];for(let n=0;n<e.length;n++){let s=e[n],o=rF.decryptBlock(s,t,r,i);a.push(o),t=s}return a}static pkcs7Pad(e,t){let r=t/8-e.length,i=Array(r);return i.fill(r),[...e,...i]}static pkcs7Unpad(e){let t=e[e.length-1],r=e.slice(e.length-t,e.length),i=Array(t);if(i.fill(t),eK(r)!==eK(i))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 r=Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}}class rq{static encrypt(e,t,r,i=!0){r=r??tx(16);let a=rF.encrypt(e,r,rK,t);return i?[...r,...a]:[...a]}static decrypt(e,t,r){if(null!=r)return rF.decrypt(e,r,rK,t);{r=e.slice(0,16);let i=e.slice(16);return rF.decrypt(i,r,rK,t)}}}class rM{static ivkEkM(e,t){let r=t.mul(e),i=z(new tv(r.x,r.y).encode(!0));return{iv:i.slice(0,16),kE:i.slice(16,32),kM:i.slice(32,64)}}static electrumEncrypt(e,t,r,i=!1){let a,n=null;null==r&&(r=tO.fromRandom()),i||(n=r.toPublicKey().encode(!0));let{iv:s,kE:o,kM:c}=rM.ivkEkM(r,t),l=rq.encrypt(e,o,s,!1),h=eF("BIE1","utf8"),d=G(c,a=null!=n&&n.length>0?[...h,...n,...l]:[...h,...l]);return[...a,...d]}static electrumDecrypt(e,t,r){if("BIE1"!==ez(e.slice(0,4),"utf8"))throw Error("Invalid Magic");let i=4,a=null;if(e.length-i-32>=33){let t=e[i];2===t||3===t?(a=e.slice(i,i+33),i+=33):4===t&&(a=e.slice(i,i+65),i+=65)}if(null!==a)null==r&&(r=tv.fromString(eK(a)));else if(null==r)throw Error("Sender public key is required");let{iv:n,kE:s,kM:o}=rM.ivkEkM(t,r),c=e.slice(i,e.length-32),l=e.slice(e.length-32,e.length),h=G(o,e.slice(0,e.length-32));if(eK(l)!==eK(h))throw Error("Invalid checksum");return rq.decrypt(c,s,n)}static bitcoreEncrypt(e,t,r,i){null==r&&(r=tO.fromRandom()),null==i&&(i=tx(16));let a=r,n=r.toPublicKey().encode(!0),s=z(t.mul(a).getX().toArray("be",32)),o=s.slice(0,32),c=s.slice(32,64),l=rq.encrypt(e,o,i),h=G(c,[...l]);return[...n,...l,...h]}static bitcoreDecrypt(e,t){let r=tv.fromString(eK(e.slice(0,33))).mul(t);if(r.eq(new th(0,0)))throw Error("P equals 0");let i=z(r.getX().toArray("be",32)),a=i.slice(0,32),n=i.slice(32,64),s=e.slice(33,e.length-32),o=e.slice(e.length-32,e.length),c=G(n,s);if(eK(o)!==eK(c))throw Error("Invalid checksum");return[...rq.decrypt(s,a)]}}function r$(e,t){let r=new rg(0,[],[],0);return r.outputs=Array(e.vout+1).fill(null),r.outputs[e.vout]={satoshis:e.satoshis,lockingScript:tJ.fromHex(e.script)},{sourceTransaction:r,sourceTXID:e.txid,sourceOutputIndex:e.vout,unlockingScriptTemplate:t,sequence:0xffffffff}}class rz{static generate(e,t){let r=this.withDefaultOptions(t);return rW(e,this.getCounter(r.timestamp,r.period),r)}static validate(e,t,r){let i=this.withDefaultValidateOptions(r);if((t=t.trim()).length!==i.digits)return!1;let a=this.getCounter(i.timestamp,i.period),n=[a];for(let e=1;e<=i.skew;e++)n.push(a+e),n.push(a-e);for(let r of n)if(t===rW(e,r,i))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 rW(e,t,r){let i=(function(e,t,r){switch(r){case"SHA-1":return new K(e).update(t);case"SHA-256":return new L(e).update(t);case"SHA-512":return new F(e).update(t);default:throw Error("unsupported HMAC algorithm")}})(e,new p(t).toArray("be",8),r.algorithm).digest(),a=15&i[i.length-1];return(0x7fffffff&new p(i.slice(a,a+4)).toNumber()).toString().slice(-r.digits)}!function(e){e[e.Silent=0]="Silent",e[e.App=1]="App",e[e.Counterparty=2]="Counterparty"}(r||(r={}));class rj{cacheSharedSecret;retrieveCachedSharedSecret;rootKey;identityKey;anyone;constructor(e,t,r){this.cacheSharedSecret=t,this.retrieveCachedSharedSecret=r,this.anyone=new tO(1).toPublicKey(),"anyone"===e?this.rootKey=new tO(1):this.rootKey=e,this.identityKey=this.rootKey.toPublicKey().toString()}derivePublicKey(e,t,r,i=!1){return(r=this.normalizeCounterparty(r),i)?this.rootKey.deriveChild(r,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret).toPublicKey():r.deriveChild(this.rootKey,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}derivePrivateKey(e,t,r){return r=this.normalizeCounterparty(r),this.rootKey.deriveChild(r,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}deriveSymmetricKey(e,t,r){r="anyone"===r?this.anyone:this.normalizeCounterparty(r);let i=this.derivePublicKey(e,t,r),a=this.derivePrivateKey(e,t,r);return new tz(a.deriveSharedSecret(i)?.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,r){e=this.normalizeCounterparty(e);let i=this.rootKey.deriveSharedSecret(e),a=eF(this.computeInvoiceNumber(t,r),"utf8");return G(i.encode(!0),a)}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 tO(1).toPublicKey():"string"==typeof e?tv.fromString(e):e}computeInvoiceNumber(e,t){let r=e[0];if(!Number.isInteger(r)||r<0||r>2)throw Error("Protocol security level must be 0, 1, or 2");let i=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(i.length>400)if(i.startsWith("specific linkage revelation ")){if(i.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(i.length<5)throw Error("Protocol names must be 5 characters or more");if(i.includes(" "))throw Error('Protocol names cannot contain multiple consecutive spaces (" ")');if(!/^[a-z0-9 ]+$/g.test(i))throw Error("Protocol names can only contain letters, numbers and spaces");if(i.endsWith(" protocol"))throw Error('No need to end your protocol name with " protocol"');return`${r}-${i}-${t}`}}class rG{keyDeriver;cache;maxCacheSize;rootKey;identityKey;constructor(e,t){"anyone"===e?this.rootKey=new tO(1):this.rootKey=e,this.keyDeriver=new rj(this.rootKey,(e,t,r)=>{this.cacheSet(`${e.toString()}-${t.toString()}`,r)},(e,t)=>this.cacheGet(`${e.toString()}-${t.toString()}`)),this.identityKey=this.rootKey.toPublicKey().toString(),this.cache=new Map;let r=t?.maxCacheSize;this.maxCacheSize=null!=r&&!isNaN(r)&&r>0?r:1e3}derivePublicKey(e,t,r,i=!1){let a=this.generateCacheKey("derivePublicKey",e,t,r,i);if(this.cache.has(a)){let e=this.cacheGet(a);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.derivePublicKey(e,t,r,i);return this.cacheSet(a,n),n}}derivePrivateKey(e,t,r){let i=this.generateCacheKey("derivePrivateKey",e,t,r);if(this.cache.has(i)){let e=this.cacheGet(i);if(void 0===e)throw Error("Cached value is undefined");return e}{let a=this.keyDeriver.derivePrivateKey(e,t,r);return this.cacheSet(i,a),a}}deriveSymmetricKey(e,t,r){let i=this.generateCacheKey("deriveSymmetricKey",e,t,r);if(this.cache.has(i)){let e=this.cacheGet(i);if(void 0===e)throw Error("Cached value is undefined");return e}{let a=this.keyDeriver.deriveSymmetricKey(e,t,r);return this.cacheSet(i,a),a}}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 r=this.keyDeriver.revealCounterpartySecret(e);return this.cacheSet(t,r),r}}revealSpecificSecret(e,t,r){let i=this.generateCacheKey("revealSpecificSecret",e,t,r);if(this.cache.has(i)){let e=this.cacheGet(i);if(void 0===e)throw Error("Cached value is undefined");return e}{let a=this.keyDeriver.revealSpecificSecret(e,t,r);return this.cacheSet(i,a),a}}generateCacheKey(e,...t){let r=t.map(e=>this.serializeArgument(e)).join("|");return`${e}|${r}`}serializeArgument(e){return e instanceof tv||e instanceof tO?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)}}let rX=class{keyDeriver;constructor(e){"string"!=typeof e.identityKey&&(e=new rG(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 r=this.keyDeriver.revealCounterpartySecret(e.counterparty),i=new tj().generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),tv.fromString(e.counterparty),th.fromDER(r)),a=[...i.R.encode(!0),...i.SPrime.encode(!0),...i.z.toArray()],n=new Date().toISOString(),{ciphertext:s}=await this.encrypt({plaintext:r,protocolID:[2,"counterparty linkage revelation"],keyID:n,counterparty:e.verifier}),{ciphertext:o}=await this.encrypt({plaintext:a,protocolID:[2,"counterparty linkage revelation"],keyID:n,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,revelationTime:n,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 r=this.keyDeriver.revealSpecificSecret(e.counterparty,e.protocolID,e.keyID),{ciphertext:i}=await this.encrypt({plaintext:r,protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier}),{ciphertext:a}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,protocolID:e.protocolID,keyID:e.keyID,encryptedLinkage:i,encryptedLinkageProof:a,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:G(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=G(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data).toString()===e.hmac.toString();if(!t){let e=Error("HMAC is not valid");throw e.code="ERR_INVALID_HMAC",e}return{valid:t}}async createSignature(e){if(null==e.hashToDirectlySign&&null==e.data)throw Error("args.data or args.hashToDirectlySign must be valid");let t=e.hashToDirectlySign??$(e.data??[]),r=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePrivateKey(e.protocolID,e.keyID,e.counterparty??"anyone");return{signature:tw(new p(t),r,!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??$(e.data??[]),r=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf),i=tI(new p(t),tu.fromDER(e.signature),r);if(!i){let e=Error("Signature is not valid");throw e.code="ERR_INVALID_SIGNATURE",e}return{valid:i}}};class rY{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 rJ extends Error{code;isError=!0;constructor(e,t=1,r){super(e),this.code=t,this.name=this.constructor.name,null!=r&&""!==r?this.stack=r:Error.captureStackTrace(this,this.constructor)}}!function(e){e[e.unknownError=1]="unknownError",e[e.unsupportedAction=2]="unsupportedAction",e[e.invalidHmac=3]="invalidHmac",e[e.invalidSignature=4]="invalidSignature",e[e.reviewActions=5]="reviewActions"}(i||(i={}));let rZ=rJ;class rQ{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((r,i)=>{let a=eW(tx(12)),n=e=>{"CWI"===e.data.type&&e.isTrusted&&e.data.id===a&&!0!==e.data.isInvocation&&("function"==typeof window.removeEventListener&&window.removeEventListener("message",n),"error"===e.data.status?i(new rJ(e.data.description,e.data.code)):r(e.data.result))};window.addEventListener("message",n),window.parent.postMessage({type:"CWI",isInvocation:!0,id:a,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 r0{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(e,t,r,i,a,n,s){this.type=e,this.serialNumber=t,this.subject=r,this.certifier=i,this.revocationOutpoint=a,this.fields=n,this.signature=s}toBinary(e=!0){let t=new eZ,r=eF(this.type,"base64");t.write(r);let i=eF(this.serialNumber,"base64");t.write(i);let a=eF(this.subject,"hex");t.write(a);let n=eF(this.certifier,"hex");t.write(n);let[s,o]=this.revocationOutpoint.split("."),c=eF(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 r=this.fields[e],i=eF(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let a=eF(r,"utf8");t.writeVarIntNum(a.length),t.write(a)}if(e&&(this.signature??"").length>0){let e=eF(this.signature,"hex");t.write(e)}return t.toArray()}static fromBinary(e){let t,r=new eQ(e),i=eW(r.read(32)),a=eW(r.read(32)),n=eK(r.read(33)),s=eK(r.read(33)),o=eK(r.read(32)),c=r.readVarIntNum(),l=`${o}.${c}`,h=r.readVarIntNum(),d={};for(let e=0;e<h;e++){let e=r.readVarIntNum(),t=e$(r.read(e)),i=r.readVarIntNum(),a=e$(r.read(i));d[t]=a}if(!r.eof()){let e=r.read();t=tu.fromDER(e).toString("hex")}return new r0(i,a,n,s,l,d,t)}async verify(){let e=new rX("anyone"),t=this.toBinary(!1),r=this.signature??"",{valid:i}=await e.verifySignature({signature:eF(r,"hex"),data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`,counterparty:this.certifier});return i}async sign(e){if(null!=this.signature&&this.signature.length>0)throw Error(`Certificate has already been signed! Signature present: ${this.signature}`);this.certifier=(await e.getPublicKey({identityKey:!0})).publicKey;let t=this.toBinary(!1),{signature:r}=await e.createSignature({data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`});this.signature=eK(r)}static getCertificateFieldEncryptionDetails(e,t){return{protocolID:[2,"certificate field encryption"],keyID:t?`${t} ${e}`:e}}}!function(e){e[e.createAction=1]="createAction",e[e.signAction=2]="signAction",e[e.abortAction=3]="abortAction",e[e.listActions=4]="listActions",e[e.internalizeAction=5]="internalizeAction",e[e.listOutputs=6]="listOutputs",e[e.relinquishOutput=7]="relinquishOutput",e[e.getPublicKey=8]="getPublicKey",e[e.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",e[e.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",e[e.encrypt=11]="encrypt",e[e.decrypt=12]="decrypt",e[e.createHmac=13]="createHmac",e[e.verifyHmac=14]="verifyHmac",e[e.createSignature=15]="createSignature",e[e.verifySignature=16]="verifySignature",e[e.acquireCertificate=17]="acquireCertificate",e[e.listCertificates=18]="listCertificates",e[e.proveCertificate=19]="proveCertificate",e[e.relinquishCertificate=20]="relinquishCertificate",e[e.discoverByIdentityKey=21]="discoverByIdentityKey",e[e.discoverByAttributes=22]="discoverByAttributes",e[e.isAuthenticated=23]="isAuthenticated",e[e.waitForAuthentication=24]="waitForAuthentication",e[e.getHeight=25]="getHeight",e[e.getHeaderForHeight=26]="getHeaderForHeight",e[e.getNetwork=27]="getNetwork",e[e.getVersion=28]="getVersion"}(a||(a={}));let r1=a;class r2{wire;constructor(e){this.wire=e}async transmit(e,t="",r=[]){let i=new eZ;i.writeUInt8(r1[e]);let a=eF(t,"utf8");i.writeUInt8(a.length),i.write(a),r.length>0&&i.write(r);let n=i.toArray(),s=new eQ(await this.wire.transmitToWallet(n)),o=s.readUInt8();if(0===o)return s.read();{let e=s.readVarIntNum(),t=e$(s.read(e)),r=s.readVarIntNum();throw new rJ(t,o,e$(s.read(r)))}}async createAction(e,t){let r=new eZ,i=eF(e.description,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=e.inputBEEF?(r.writeVarIntNum(e.inputBEEF.length),r.write(e.inputBEEF)):r.writeVarIntNum(-1),null!=e.inputs)for(let t of(r.writeVarIntNum(e.inputs.length),e.inputs)){if(r.write(this.encodeOutpoint(t.outpoint)),null!=t.unlockingScript&&""!==t.unlockingScript){let e=eF(t.unlockingScript,"hex");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1),r.writeVarIntNum(t.unlockingScriptLength??0);let e=eF(t.inputDescription,"utf8");r.writeVarIntNum(e.length),r.write(e),"number"==typeof t.sequenceNumber?r.writeVarIntNum(t.sequenceNumber):r.writeVarIntNum(-1)}else r.writeVarIntNum(-1);if(null!=e.outputs)for(let t of(r.writeVarIntNum(e.outputs.length),e.outputs)){let e=eF(t.lockingScript,"hex");r.writeVarIntNum(e.length),r.write(e),r.writeVarIntNum(t.satoshis);let i=eF(t.outputDescription,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=t.basket&&""!==t.basket){let e=eF(t.basket,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=t.customInstructions&&""!==t.customInstructions){let e=eF(t.customInstructions,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=t.tags)for(let e of(r.writeVarIntNum(t.tags.length),t.tags)){let t=eF(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}else r.writeVarIntNum(-1)}else r.writeVarIntNum(-1);if("number"==typeof e.lockTime?r.writeVarIntNum(e.lockTime):r.writeVarIntNum(-1),"number"==typeof e.version?r.writeVarIntNum(e.version):r.writeVarIntNum(-1),null!=e.labels)for(let t of(r.writeVarIntNum(e.labels.length),e.labels)){let e=eF(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=e.options){if(r.writeInt8(1),"boolean"==typeof e.options.signAndProcess?r.writeInt8(+!!e.options.signAndProcess):r.writeInt8(-1),"boolean"==typeof e.options.acceptDelayedBroadcast?r.writeInt8(+!!e.options.acceptDelayedBroadcast):r.writeInt8(-1),"known"===e.options.trustSelf?r.writeInt8(1):r.writeInt8(-1),null!=e.options.knownTxids)for(let t of(r.writeVarIntNum(e.options.knownTxids.length),e.options.knownTxids)){let e=eF(t,"hex");r.write(e)}else r.writeVarIntNum(-1);if("boolean"==typeof e.options.returnTXIDOnly?r.writeInt8(+!!e.options.returnTXIDOnly):r.writeInt8(-1),"boolean"==typeof e.options.noSend?r.writeInt8(+!!e.options.noSend):r.writeInt8(-1),null!=e.options.noSendChange)for(let t of(r.writeVarIntNum(e.options.noSendChange.length),e.options.noSendChange))r.write(this.encodeOutpoint(t));else r.writeVarIntNum(-1);if(null!=e.options.sendWith)for(let t of(r.writeVarIntNum(e.options.sendWith.length),e.options.sendWith)){let e=eF(t,"hex");r.write(e)}else r.writeVarIntNum(-1);"boolean"==typeof e.options.randomizeOutputs?r.writeInt8(+!!e.options.randomizeOutputs):r.writeInt8(-1)}else r.writeInt8(0);let a=new eQ(await this.transmit("createAction",t,r.toArray())),n={};if(1===a.readInt8()&&(n.txid=eK(a.read(32))),1===a.readInt8()){let e=a.readVarIntNum();n.tx=a.read(e)}let s=a.readVarIntNum();if(s>=0){n.noSendChange=[];for(let e=0;e<s;e++){let e=this.readOutpoint(a);n.noSendChange.push(e)}}let o=a.readVarIntNum();if(o>=0){n.sendWithResults=[];for(let e=0;e<o;e++){let e=eK(a.read(32)),t=a.readInt8(),r="unproven";1===t?r="unproven":2===t?r="sending":3===t&&(r="failed"),n.sendWithResults.push({txid:e,status:r})}}if(1===a.readInt8()){let e=a.readVarIntNum(),t=a.read(e),r=a.readVarIntNum();n.signableTransaction={tx:t,reference:eW(a.read(r))}}return n}async signAction(e,t){let r=new eZ,i=Object.keys(e.spends);for(let t of(r.writeVarIntNum(i.length),i)){r.writeVarIntNum(Number(t));let i=e.spends[Number(t)],a=eF(i.unlockingScript,"hex");r.writeVarIntNum(a.length),r.write(a),"number"==typeof i.sequenceNumber?r.writeVarIntNum(i.sequenceNumber):r.writeVarIntNum(-1)}let a=eF(e.reference,"base64");if(r.writeVarIntNum(a.length),r.write(a),null!=e.options)if(r.writeInt8(1),"boolean"==typeof e.options.acceptDelayedBroadcast?r.writeInt8(+!!e.options.acceptDelayedBroadcast):r.writeInt8(-1),"boolean"==typeof e.options.returnTXIDOnly?r.writeInt8(+!!e.options.returnTXIDOnly):r.writeInt8(-1),"boolean"==typeof e.options.noSend?r.writeInt8(+!!e.options.noSend):r.writeInt8(-1),null!=e.options.sendWith)for(let t of(r.writeVarIntNum(e.options.sendWith.length),e.options.sendWith)){let e=eF(t,"hex");r.write(e)}else r.writeVarIntNum(-1);else r.writeInt8(0);let n=new eQ(await this.transmit("signAction",t,r.toArray())),s={};if(1===n.readInt8()&&(s.txid=eK(n.read(32))),1===n.readInt8()){let e=n.readVarIntNum();s.tx=n.read(e)}let o=n.readVarIntNum();if(o>=0){s.sendWithResults=[];for(let e=0;e<o;e++){let e=eK(n.read(32)),t=n.readInt8(),r="unproven";1===t?r="unproven":2===t?r="sending":3===t&&(r="failed"),s.sendWithResults.push({txid:e,status:r})}}return s}async abortAction(e,t){return await this.transmit("abortAction",t,eF(e.reference,"base64")),{aborted:!0}}async listActions(e,t){let r=new eZ;for(let t of(r.writeVarIntNum(e.labels.length),e.labels)){let e=eF(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}for(let t of("any"===e.labelQueryMode?r.writeInt8(1):"all"===e.labelQueryMode?r.writeInt8(2):r.writeInt8(-1),[e.includeLabels,e.includeInputs,e.includeInputSourceLockingScripts,e.includeInputUnlockingScripts,e.includeOutputs,e.includeOutputLockingScripts]))"boolean"==typeof t?r.writeInt8(+!!t):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 i=new eQ(await this.transmit("listActions",t,r.toArray())),a=i.readVarIntNum(),n=[];for(let e=0;e<a;e++){let e,t=eK(i.read(32)),r=i.readVarIntNum(),a=i.readInt8();switch(a){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: ${a}`)}let s=1===i.readInt8(),o=i.readVarIntNum(),c={txid:t,satoshis:r,status:e,isOutgoing:s,description:e$(i.read(o)),version:0,lockTime:0},l=i.readVarIntNum();if(l>=0){c.labels=[];for(let e=0;e<l;e++){let e=i.readVarIntNum(),t=i.read(e);c.labels.push(e$(t))}}c.version=i.readVarIntNum(),c.lockTime=i.readVarIntNum();let h=i.readVarIntNum();if(h>=0){c.inputs=[];for(let e=0;e<h;e++){let e,t,r=this.readOutpoint(i),a=i.readVarIntNum(),n=i.readVarIntNum();n>=0&&(e=eK(i.read(n)));let s=i.readVarIntNum();s>=0&&(t=eK(i.read(s)));let o=i.readVarIntNum(),l=e$(i.read(o)),h=i.readVarIntNum();c.inputs.push({sourceOutpoint:r,sourceSatoshis:a,sourceLockingScript:e,unlockingScript:t,inputDescription:l,sequenceNumber:h})}}let d=i.readVarIntNum();if(d>=0){c.outputs=[];for(let e=0;e<d;e++){let e,t,r,a=i.readVarIntNum(),n=i.readVarIntNum(),s=i.readVarIntNum();s>=0&&(e=eK(i.read(s)));let o=1===i.readInt8(),l=i.readVarIntNum(),h=e$(i.read(l)),d=i.readVarIntNum();d>=0&&(t=e$(i.read(d)));let u=i.readVarIntNum(),f=[];if(u>=0)for(let e=0;e<u;e++){let e=i.readVarIntNum(),t=i.read(e);f.push(e$(t))}let p=i.readVarIntNum();p>=0&&(r=e$(i.read(p))),c.outputs.push({outputIndex:a,satoshis:n,lockingScript:e,spendable:o,outputDescription:h,basket:t,tags:f,customInstructions:r})}}n.push(c)}return{totalActions:a,actions:n}}async internalizeAction(e,t){let r=new eZ;for(let t of(r.writeVarIntNum(e.tx.length),r.write(e.tx),r.writeVarIntNum(e.outputs.length),e.outputs))if(r.writeVarIntNum(t.outputIndex),"wallet payment"===t.protocol){if(null==t.paymentRemittance)throw Error("Payment remittance is required for wallet payment");r.writeUInt8(1),r.write(eF(t.paymentRemittance.senderIdentityKey,"hex"));let e=eF(t.paymentRemittance.derivationPrefix,"base64");r.writeVarIntNum(e.length),r.write(e);let i=eF(t.paymentRemittance.derivationSuffix,"base64");r.writeVarIntNum(i.length),r.write(i)}else{r.writeUInt8(2);let e=eF(t.insertionRemittance?.basket,"utf8");if(r.writeVarIntNum(e.length),r.write(e),"string"==typeof t.insertionRemittance?.customInstructions&&""!==t.insertionRemittance.customInstructions){let e=eF(t.insertionRemittance.customInstructions,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if("object"==typeof t.insertionRemittance?.tags)for(let e of(r.writeVarIntNum(t.insertionRemittance.tags.length),t.insertionRemittance.tags)){let t=eF(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}else r.writeVarIntNum(0)}if("object"==typeof e.labels)for(let t of(r.writeVarIntNum(e.labels.length),e.labels)){let e=eF(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);let i=eF(e.description);return r.writeVarIntNum(i.length),r.write(i),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),await this.transmit("internalizeAction",t,r.toArray()),{accepted:!0}}async listOutputs(e,t){let r,i=new eZ,a=eF(e.basket,"utf8");if(i.writeVarIntNum(a.length),i.write(a),"object"==typeof e.tags)for(let t of(i.writeVarIntNum(e.tags.length),e.tags)){let e=eF(t,"utf8");i.writeVarIntNum(e.length),i.write(e)}else i.writeVarIntNum(0);"all"===e.tagQueryMode?i.writeInt8(1):"any"===e.tagQueryMode?i.writeInt8(2):i.writeInt8(-1),"locking scripts"===e.include?i.writeInt8(1):"entire transactions"===e.include?i.writeInt8(2):i.writeInt8(-1),"boolean"==typeof e.includeCustomInstructions?i.writeInt8(+!!e.includeCustomInstructions):i.writeInt8(-1),"boolean"==typeof e.includeTags?i.writeInt8(+!!e.includeTags):i.writeInt8(-1),"boolean"==typeof e.includeLabels?i.writeInt8(+!!e.includeLabels):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 n=new eQ(await this.transmit("listOutputs",t,i.toArray())),s=n.readVarIntNum(),o=n.readVarIntNum();o>=0&&(r=n.read(o));let c=[];for(let e=0;e<s;e++){let e={spendable:!0,outpoint:this.readOutpoint(n),satoshis:n.readVarIntNum()},t=n.readVarIntNum();t>=0&&(e.lockingScript=eK(n.read(t)));let r=n.readVarIntNum();r>=0&&(e.customInstructions=e$(n.read(r)));let i=n.readVarIntNum();if(-1!==i){let t=[];for(let e=0;e<i;e++){let e=n.readVarIntNum();t.push(e$(n.read(e)))}e.tags=t}let a=n.readVarIntNum();if(-1!==a){let t=[];for(let e=0;e<a;e++){let e=n.readVarIntNum();t.push(e$(n.read(e)))}e.labels=t}c.push(e)}return{totalOutputs:s,BEEF:r,outputs:c}}async relinquishOutput(e,t){let r=new eZ,i=eF(e.basket,"utf8");return r.writeVarIntNum(i.length),r.write(i),r.write(this.encodeOutpoint(e.output)),await this.transmit("relinquishOutput",t,r.toArray()),{relinquished:!0}}encodeOutpoint(e){let t=new eZ,[r,i]=e.split(".");return t.write(eF(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}readOutpoint(e){let t=eK(e.read(32)),r=e.readVarIntNum();return`${t}.${r}`}async getPublicKey(e,t){let i=new eZ;return i.writeUInt8(+!!e.identityKey),e.identityKey?i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)):(i.write(this.encodeKeyRelatedParams(e.protocolID??=[r.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:eK(await this.transmit("getPublicKey",t,i.toArray()))}}async revealCounterpartyKeyLinkage(e,t){let r=new eZ;r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),r.write(eF(e.counterparty,"hex")),r.write(eF(e.verifier,"hex"));let i=new eQ(await this.transmit("revealCounterpartyKeyLinkage",t,r.toArray())),a=eK(i.read(33)),n=eK(i.read(33)),s=eK(i.read(33)),o=i.readVarIntNum(),c=e$(i.read(o)),l=i.readVarIntNum(),h=i.read(l),d=i.readVarIntNum();return{prover:a,verifier:n,counterparty:s,revelationTime:c,encryptedLinkage:h,encryptedLinkageProof:i.read(d)}}async revealSpecificKeyLinkage(e,t){let r=new eZ;r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.write(eF(e.verifier,"hex"));let i=new eQ(await this.transmit("revealSpecificKeyLinkage",t,r.toArray())),a=eK(i.read(33)),n=eK(i.read(33)),s=eK(i.read(33)),o=i.readUInt8(),c=i.readVarIntNum(),l=e$(i.read(c)),h=i.readVarIntNum(),d=e$(i.read(h)),u=i.readVarIntNum(),f=i.read(u),p=i.readVarIntNum();return{prover:a,verifier:n,counterparty:s,protocolID:[o,l],keyID:d,encryptedLinkage:f,encryptedLinkageProof:i.read(p),proofType:i.readUInt8()}}async encrypt(e,t){let r=new eZ;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.writeVarIntNum(e.plaintext.length),r.write(e.plaintext),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{ciphertext:await this.transmit("encrypt",t,r.toArray())}}async decrypt(e,t){let r=new eZ;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.writeVarIntNum(e.ciphertext.length),r.write(e.ciphertext),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{plaintext:await this.transmit("decrypt",t,r.toArray())}}async createHmac(e,t){let r=new eZ;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.writeVarIntNum(e.data.length),r.write(e.data),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{hmac:await this.transmit("createHmac",t,r.toArray())}}async verifyHmac(e,t){let r=new eZ;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.write(e.hmac),r.writeVarIntNum(e.data.length),r.write(e.data),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),await this.transmit("verifyHmac",t,r.toArray()),{valid:!0}}async createSignature(e,t){let r=new eZ;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"object"==typeof e.data?(r.writeUInt8(1),r.writeVarIntNum(e.data.length),r.write(e.data)):(r.writeUInt8(2),r.write(e.hashToDirectlySign??=[])),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{signature:await this.transmit("createSignature",t,r.toArray())}}async verifySignature(e,t){let r=new eZ;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?r.writeInt8(+!!e.forSelf):r.writeInt8(-1),r.writeVarIntNum(e.signature.length),r.write(e.signature),"object"==typeof e.data?(r.writeUInt8(1),r.writeVarIntNum(e.data.length),r.write(e.data)):(r.writeUInt8(2),r.write(e.hashToDirectlyVerify??[])),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),await this.transmit("verifySignature",t,r.toArray()),{valid:!0}}encodeKeyRelatedParams(e,t,r,i,a){let n=new eZ;n.writeUInt8(e[0]);let s=eF(e[1],"utf8");n.writeVarIntNum(s.length),n.write(s);let o=eF(t,"utf8");return n.writeVarIntNum(o.length),n.write(o),"string"!=typeof r?n.writeUInt8(0):"self"===r?n.writeUInt8(11):"anyone"===r?n.writeUInt8(12):n.write(eF(r,"hex")),n.write(this.encodePrivilegedParams(i,a)),n.toArray()}async acquireCertificate(e,t){let r=new eZ;r.write(eF(e.type,"base64")),r.write(eF(e.certifier,"hex"));let i=Object.entries(e.fields);for(let[e,t]of(r.writeVarIntNum(i.length),i)){let i=eF(e,"utf8"),a=eF(t,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(a.length),r.write(a)}if(r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),r.writeUInt8("direct"===e.acquisitionProtocol?1:2),"direct"===e.acquisitionProtocol){r.write(eF(e.serialNumber,"base64")),r.write(this.encodeOutpoint(e.revocationOutpoint??""));let t=eF(e.signature,"hex");r.writeVarIntNum(t.length),r.write(t);let i="certifier"!==e.keyringRevealer?eF(e.keyringRevealer,"hex"):[11];r.write(i);let a=Object.keys(e.keyringForSubject??{});r.writeVarIntNum(a.length);for(let t=0;t<a.length;t++){let i=eF(a[t],"utf8");r.writeVarIntNum(i.length),r.write(i);let n=eF(e.keyringForSubject?.[a[t]],"base64");r.writeVarIntNum(n.length),r.write(n)}}else{let t=eF(e.certifierUrl,"utf8");r.writeVarIntNum(t.length),r.write(t)}let a=await this.transmit("acquireCertificate",t,r.toArray()),n=r0.fromBinary(a);return{...n,signature:n.signature}}encodePrivilegedParams(e,t){let r=new eZ;if("boolean"==typeof e?r.writeInt8(+!!e):r.writeInt8(-1),"string"==typeof t){let e=eF(t,"utf8");r.writeInt8(e.length),r.write(e)}else r.writeInt8(-1);return r.toArray()}async listCertificates(e,t){let r=new eZ;r.writeVarIntNum(e.certifiers.length);for(let t=0;t<e.certifiers.length;t++)r.write(eF(e.certifiers[t],"hex"));r.writeVarIntNum(e.types.length);for(let t=0;t<e.types.length;t++)r.write(eF(e.types[t],"base64"));"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let i=new eQ(await this.transmit("listCertificates",t,r.toArray())),a=i.readVarIntNum(),n=[];for(let e=0;e<a;e++){let e,t=i.readVarIntNum(),r=i.read(t),a=r0.fromBinary(r),s={};if(1===i.readInt8()){let e=i.readVarIntNum();for(let t=0;t<e;t++){let e=i.readVarIntNum(),t=e$(i.read(e)),r=i.readVarIntNum();s[t]=eW(i.read(r))}}let o=i.readVarIntNum();o>0&&(e=e$(i.read(o))),n.push({...a,signature:a.signature,keyring:s,verifier:e})}return{totalCertificates:a,certificates:n}}async proveCertificate(e,t){let r=new eZ,i=eF(e.certificate.type,"base64");r.write(i);let a=eF(e.certificate.subject,"hex");r.write(a);let n=eF(e.certificate.serialNumber,"base64");r.write(n);let s=eF(e.certificate.certifier,"hex");r.write(s);let o=this.encodeOutpoint(e.certificate.revocationOutpoint??"");r.write(o);let c=eF(e.certificate.signature,"hex");r.writeVarIntNum(c.length),r.write(c);let l=Object.entries(e.certificate.fields??{});for(let[e,t]of(r.writeVarIntNum(l.length),l)){let i=eF(e,"utf8"),a=eF(t,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(a.length),r.write(a)}for(let t of(r.writeVarIntNum(e.fieldsToReveal.length),e.fieldsToReveal)){let e=eF(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}r.write(eF(e.verifier,"hex")),r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let h=new eQ(await this.transmit("proveCertificate",t,r.toArray())),d=h.readVarIntNum(),u={};for(let e=0;e<d;e++){let e=h.readVarIntNum(),t=e$(h.read(e)),r=h.readVarIntNum();u[t]=eW(h.read(r))}return{keyringForVerifier:u}}async relinquishCertificate(e,t){let r=new eZ,i=eF(e.type,"base64");r.write(i);let a=eF(e.serialNumber,"base64");r.write(a);let n=eF(e.certifier,"hex");return r.write(n),await this.transmit("relinquishCertificate",t,r.toArray()),{relinquished:!0}}parseDiscoveryResult(e){let t=new eQ(e),r=t.readVarIntNum(),i=[];for(let e=0;e<r;e++){let e=t.readVarIntNum(),r=t.read(e),a=r0.fromBinary(r),n=t.readVarIntNum(),s=e$(t.read(n)),o=t.readVarIntNum(),c=e$(t.read(o)),l=t.readVarIntNum(),h=e$(t.read(l)),d=t.readUInt8(),u={},f=t.readVarIntNum();for(let e=0;e<f;e++){let e=t.readVarIntNum(),r=e$(t.read(e)),i=t.readVarIntNum();u[r]=t.read(i)}let p={},b=t.readVarIntNum();for(let e=0;e<b;e++){let e=t.readVarIntNum(),r=e$(t.read(e)),i=t.readVarIntNum();p[r]=e$(t.read(i))}i.push({...a,signature:a.signature,certifierInfo:{iconUrl:c,name:s,description:h,trust:d},publiclyRevealedKeyring:u,decryptedFields:p})}return{totalCertificates:r,certificates:i}}async discoverByIdentityKey(e,t){let r=new eZ;r.write(eF(e.identityKey,"hex")),"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1);let i=await this.transmit("discoverByIdentityKey",t,r.toArray());return this.parseDiscoveryResult(i)}async discoverByAttributes(e,t){let r=new eZ,i=Object.keys(e.attributes);r.writeVarIntNum(i.length);for(let t=0;t<i.length;t++)r.writeVarIntNum(i[t].length),r.write(eF(i[t],"utf8")),r.writeVarIntNum(e.attributes[i[t]].length),r.write(eF(e.attributes[i[t]],"utf8"));"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1);let a=await this.transmit("discoverByAttributes",t,r.toArray());return this.parseDiscoveryResult(a)}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 eQ(await this.transmit("getHeight",t)).readVarIntNum()}}async getHeaderForHeight(e,t){let r=new eZ;return r.writeVarIntNum(e.height),{header:eK(await this.transmit("getHeaderForHeight",t,r.toArray()))}}async getNetwork(e,t){return{network:0===(await this.transmit("getNetwork",t))[0]?"mainnet":"testnet"}}async getVersion(e,t){return{version:e$(await this.transmit("getVersion",t))}}}class r8{baseUrl;httpClient;originator;constructor(e,t="http://localhost:3301",r=fetch){this.baseUrl=t,this.httpClient=r,this.originator=e}async transmitToWallet(e){let t,r=new eQ(e),i=r.readUInt8(),a=r1[i];if(void 0===a||""===a)throw Error(`Invalid call code: ${i}`);let n=r.readUInt8();n>0&&(t=e$(r.read(n)));let s=r.read(),o=await fetch(`${this.baseUrl}/${a}`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Origin:t??""},body:new Uint8Array(s)});return Array.from(new Uint8Array(await o.arrayBuffer()))}}class r3 extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(e,t,r,i,a){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=e,this.sendWithResults=t,this.txid=r,this.tx=i,this.noSendChange=a,this.code=5,this.name=this.constructor.name}}let r6=r3;class r4{baseUrl;httpClient;originator;api;constructor(e,t="http://localhost:3321",r=fetch){this.baseUrl=t,this.originator=e,this.httpClient=r;let i="undefined"!=typeof window&&"undefined"!=typeof document&&window?.origin!=="file://";this.api=async(e,t)=>{let a=!i&&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;i||void 0!==a||console.error("Originator is required in Node.js environments");let n=await await r(`${this.baseUrl}/${e}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...a?{Origin:a}:{},...a?{Originator:a}:{}},body:JSON.stringify(t)}),s=await n.json();if(!n.ok)if(400===n.status&&s.isError&&5===s.code)throw new r3(s.reviewActionResults,s.sendWithResults,s.txid,s.tx,s.noSendChange);else throw Error(JSON.stringify({call:e,args:t,message:s.message??`HTTP Client error ${n.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 r5{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((r,i)=>{let a=eW(tx(12)),n=e=>{let t=JSON.parse(e.data);"CWI"===t.type&&t.id===a&&!0!==t.isInvocation&&("function"==typeof window.removeEventListener&&window.removeEventListener("message",n),"error"===t.status?i(new rJ(t.description,t.code)):r(t.result))};window.addEventListener("message",n),window.ReactNativeWebView.postMessage(JSON.stringify({type:"CWI",isInvocation:!0,id:a,call:e,args:t}))})}async createAction(e){return await this.invoke("createAction",e)}async signAction(e){return await this.invoke("signAction",e)}async abortAction(e){return await this.invoke("abortAction",e)}async listActions(e){return await this.invoke("listActions",e)}async internalizeAction(e){return await this.invoke("internalizeAction",e)}async listOutputs(e){return await this.invoke("listOutputs",e)}async relinquishOutput(e){return await this.invoke("relinquishOutput",e)}async getPublicKey(e){return await this.invoke("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.invoke("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.invoke("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.invoke("encrypt",e)}async decrypt(e){return await this.invoke("decrypt",e)}async createHmac(e){return await this.invoke("createHmac",e)}async verifyHmac(e){return await this.invoke("verifyHmac",e)}async createSignature(e){return await this.invoke("createSignature",e)}async verifySignature(e){return await this.invoke("verifySignature",e)}async acquireCertificate(e){return await this.invoke("acquireCertificate",e)}async listCertificates(e){return await this.invoke("listCertificates",e)}async proveCertificate(e){return await this.invoke("proveCertificate",e)}async relinquishCertificate(e){return await this.invoke("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.invoke("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.invoke("discoverByAttributes",e)}async isAuthenticated(e){return await this.invoke("isAuthenticated",e)}async waitForAuthentication(e){return await this.invoke("waitForAuthentication",e)}async getHeight(e){return await this.invoke("getHeight",e)}async getHeaderForHeight(e){return await this.invoke("getHeaderForHeight",e)}async getNetwork(e){return await this.invoke("getNetwork",e)}async getVersion(e){return await this.invoke("getVersion",e)}}class r7{substrate;originator;constructor(e="auto",t){"Cicada"===e&&(e=new r2(new r8(t))),"window.CWI"===e&&(e=new rY),"XDM"===e&&(e=new rQ),"json-api"===e&&(e=new r4(t)),"react-native"===e&&(e=new r5(t)),"secure-json-api"===e&&(e=new r4(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 r,i=e();if(r="number"==typeof t?await Promise.race([i.getVersion({}),new Promise((e,r)=>setTimeout(()=>r(Error("Timed out.")),t))]):await i.getVersion({}),"object"!=typeof r||"string"!=typeof r.version)return{success:!1};return{success:!0,sub:i}}catch{return{success:!1}}},t=[e(()=>new rY),e(()=>new r4(this.originator,"https://localhost:2121")),e(()=>new r4(this.originator)),e(()=>new r5(this.originator)),e(()=>new r2(new r8(this.originator)))],r=(await Promise.allSettled(t)).filter(e=>"fulfilled"===e.status&&e.value.success&&void 0!==e.value.sub).map(e=>e.value.sub);if(r.length>0){this.substrate=r[0];return}let i=await e(()=>new rQ,200);if(i.success&&void 0!==i.sub)this.substrate=i.sub;else throw Error("No wallet available over any communication substrate. Install a BSV wallet today!")}async createAction(e){return await this.connectToSubstrate(),await this.substrate.createAction(e,this.originator)}async signAction(e){return await this.connectToSubstrate(),await this.substrate.signAction(e,this.originator)}async abortAction(e){return await this.connectToSubstrate(),await this.substrate.abortAction(e,this.originator)}async listActions(e){return await this.connectToSubstrate(),await this.substrate.listActions(e,this.originator)}async internalizeAction(e){return await this.connectToSubstrate(),await this.substrate.internalizeAction(e,this.originator)}async listOutputs(e){return await this.connectToSubstrate(),await this.substrate.listOutputs(e,this.originator)}async relinquishOutput(e){return await this.connectToSubstrate(),await this.substrate.relinquishOutput(e,this.originator)}async getPublicKey(e){return await this.connectToSubstrate(),await this.substrate.getPublicKey(e,this.originator)}async revealCounterpartyKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealCounterpartyKeyLinkage(e,this.originator)}async revealSpecificKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealSpecificKeyLinkage(e,this.originator)}async encrypt(e){return await this.connectToSubstrate(),await this.substrate.encrypt(e,this.originator)}async decrypt(e){return await this.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){return await this.connectToSubstrate(),await this.substrate.acquireCertificate(e,this.originator)}async listCertificates(e){return await this.connectToSubstrate(),await this.substrate.listCertificates(e,this.originator)}async proveCertificate(e){return await this.connectToSubstrate(),await this.substrate.proveCertificate(e,this.originator)}async relinquishCertificate(e){return await this.connectToSubstrate(),await this.substrate.relinquishCertificate(e,this.originator)}async discoverByIdentityKey(e){return await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(e,this.originator)}async discoverByAttributes(e){return await this.connectToSubstrate(),await this.substrate.discoverByAttributes(e,this.originator)}async isAuthenticated(e={}){return await this.connectToSubstrate(),await this.substrate.isAuthenticated(e,this.originator)}async waitForAuthentication(e={}){return await this.connectToSubstrate(),await this.substrate.waitForAuthentication(e,this.originator)}async getHeight(e={}){return await this.connectToSubstrate(),await this.substrate.getHeight(e,this.originator)}async getHeaderForHeight(e){return await this.connectToSubstrate(),await this.substrate.getHeaderForHeight(e,this.originator)}async getNetwork(e={}){return await this.connectToSubstrate(),await this.substrate.getNetwork(e,this.originator)}async getVersion(e={}){return await this.connectToSubstrate(),await this.substrate.getVersion(e,this.originator)}}class r9{wallet;constructor(e){this.wallet=e}decodeOutpoint(e){let t=eK(e.read(32)),r=e.readVarIntNum();return`${t}.${r}`}encodeOutpoint(e){let t=new eZ,[r,i]=e.split(".");return t.write(eF(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}async transmitToWallet(e){let t=new eQ(e);try{let e=t.readUInt8(),r=r1[e];if(void 0===r||""===r)throw Error(`Invalid call code: ${e}`);let i=t.readUInt8(),a=t.read(i),n=e$(a);switch(r){case"createAction":{let e={},r=t.readVarIntNum(),i=t.read(r);e.description=e$(i);let a=t.readVarIntNum();a>=0?e.inputBEEF=t.read(a):e.inputBEEF=void 0;let s=t.readVarIntNum();if(s>=0){e.inputs=[];for(let r=0;r<s;r++){let r={};r.outpoint=this.decodeOutpoint(t);let i=t.readVarIntNum();if(i>=0){let e=t.read(i);r.unlockingScript=eK(e)}else r.unlockingScript=void 0,r.unlockingScriptLength=t.readVarIntNum();let a=t.readVarIntNum(),n=t.read(a);r.inputDescription=e$(n);let s=t.readVarIntNum();s>=0?r.sequenceNumber=s:r.sequenceNumber=void 0,e.inputs.push(r)}}else e.inputs=void 0;let o=t.readVarIntNum();if(o>=0){e.outputs=[];for(let r=0;r<o;r++){let r={},i=t.readVarIntNum(),a=t.read(i);r.lockingScript=eK(a),r.satoshis=t.readVarIntNum();let n=t.readVarIntNum(),s=t.read(n);r.outputDescription=e$(s);let o=t.readVarIntNum();if(o>=0){let e=t.read(o);r.basket=e$(e)}else r.basket=void 0;let c=t.readVarIntNum();if(c>=0){let e=t.read(c);r.customInstructions=e$(e)}else r.customInstructions=void 0;let l=t.readVarIntNum();if(l>=0){r.tags=[];for(let e=0;e<l;e++){let e=t.readVarIntNum(),i=t.read(e),a=e$(i);r.tags.push(a)}}else r.tags=void 0;e.outputs.push(r)}}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 r=0;r<h;r++){let r=t.readVarIntNum(),i=t.read(r),a=e$(i);e.labels.push(a)}}else e.labels=void 0;let d=t.readInt8();if(1===d){e.options={};let r=t.readInt8();-1===r?e.options.signAndProcess=void 0:e.options.signAndProcess=1===r;let i=t.readInt8();-1===i?e.options.acceptDelayedBroadcast=void 0:e.options.acceptDelayedBroadcast=1===i;let a=t.readInt8();-1===a?e.options.trustSelf=void 0:1===a&&(e.options.trustSelf="known");let n=t.readVarIntNum();if(n>=0){e.options.knownTxids=[];for(let r=0;r<n;r++){let r=t.read(32),i=eK(r);e.options.knownTxids.push(i)}}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 r=0;r<c;r++){let r=this.decodeOutpoint(t);e.options.noSendChange.push(r)}}else e.options.noSendChange=void 0;let l=t.readVarIntNum();if(l>=0){e.options.sendWith=[];for(let r=0;r<l;r++){let r=t.read(32),i=eK(r);e.options.sendWith.push(i)}}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,n),f=new eZ;if(null!=u.txid&&""!==u.txid?(f.writeInt8(1),f.write(eF(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(eF(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=eF(u.signableTransaction.reference,"base64");f.writeVarIntNum(e.length),f.write(e)}else f.writeInt8(0);let p=new eZ;return p.writeUInt8(0),p.write(f.toArray()),p.toArray()}case"signAction":{let e={},r=t.readVarIntNum();e.spends={};for(let i=0;i<r;i++){let r=t.readVarIntNum(),i={},a=t.readVarIntNum(),n=t.read(a);i.unlockingScript=eK(n);let s=t.readVarIntNum();s>=0?i.sequenceNumber=s:i.sequenceNumber=void 0,e.spends[r]=i}let i=t.readVarIntNum(),a=t.read(i);e.reference=eW(a);let s=t.readInt8();if(1===s){e.options={};let r=t.readInt8();-1===r?e.options.acceptDelayedBroadcast=void 0:e.options.acceptDelayedBroadcast=1===r;let i=t.readInt8();-1===i?e.options.returnTXIDOnly=void 0:e.options.returnTXIDOnly=1===i;let a=t.readInt8();-1===a?e.options.noSend=void 0:e.options.noSend=1===a;let n=t.readVarIntNum();if(n>=0){e.options.sendWith=[];for(let r=0;r<n;r++){let r=t.read(32),i=eK(r);e.options.sendWith.push(i)}}else e.options.sendWith=void 0}else e.options=void 0;let o=await this.wallet.signAction(e,n),c=new eZ;if(null!=o.txid&&""!==o.txid?(c.writeInt8(1),c.write(eF(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(eF(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 eZ;return l.writeUInt8(0),l.write(c.toArray()),l.toArray()}case"abortAction":{let e=t.read(),r=eW(e);await this.wallet.abortAction({reference:r},n);let i=new eZ;return i.writeUInt8(0),i.toArray()}case"listActions":{let e={},r=t.readVarIntNum();e.labels=[];for(let i=0;i<r;i++){let r=t.readVarIntNum(),i=t.read(r);e.labels.push(e$(i))}let i=t.readInt8();for(let r of(-1===i?e.labelQueryMode=void 0:1===i?e.labelQueryMode="any":2===i&&(e.labelQueryMode="all"),["includeLabels","includeInputs","includeInputSourceLockingScripts","includeInputUnlockingScripts","includeOutputs","includeOutputLockingScripts"])){let i=t.readInt8();-1===i?e[r]=void 0:e[r]=1===i}let a=t.readVarIntNum();a>=0?e.limit=a: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,n),l=new eZ;for(let e of(l.writeVarIntNum(c.totalActions),c.actions)){let t;switch(l.write(eF(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 r=eF(e.description,"utf8");if(l.writeVarIntNum(r.length),l.write(r),void 0!==e.labels)for(let t of(l.writeVarIntNum(e.labels.length),e.labels)){let e=eF(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=eF(t.sourceLockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);if(void 0!==t.unlockingScript){let e=eF(t.unlockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);let e=eF(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=eF(t.lockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);l.writeInt8(+!!t.spendable);let e=eF(t.outputDescription,"utf8");if(l.writeVarIntNum(e.length),l.write(e),void 0!==t.basket){let e=eF(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=eF(e,"utf8");l.writeVarIntNum(t.length),l.write(t)}else l.writeVarIntNum(-1);if(void 0!==t.customInstructions){let e=eF(t.customInstructions,"utf8");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1)}else l.writeVarIntNum(-1)}let h=new eZ;return h.writeUInt8(0),h.write(l.toArray()),h.toArray()}case"internalizeAction":{let e={},r=t.readVarIntNum();e.tx=t.read(r);let i=t.readVarIntNum();e.outputs=[];for(let r=0;r<i;r++){let r={};r.outputIndex=t.readVarIntNum();let i=t.readUInt8();if(1===i){r.protocol="wallet payment",r.paymentRemittance={};let e=t.read(33);r.paymentRemittance.senderIdentityKey=eK(e);let i=t.readVarIntNum(),a=t.read(i);r.paymentRemittance.derivationPrefix=eW(a);let n=t.readVarIntNum(),s=t.read(n);r.paymentRemittance.derivationSuffix=eW(s)}else if(2===i){r.protocol="basket insertion",r.insertionRemittance={};let e=t.readVarIntNum(),i=t.read(e);r.insertionRemittance.basket=e$(i);let a=t.readVarIntNum();if(a>=0){let e=t.read(a);r.insertionRemittance.customInstructions=e$(e)}let n=t.readVarIntNum();if(n>0){r.insertionRemittance.tags=[];for(let e=0;e<n;e++){let e=t.readVarIntNum(),i=t.read(e);r.insertionRemittance.tags.push(e$(i))}}else r.insertionRemittance.tags=[]}e.outputs.push(r)}let a=t.readVarIntNum();if(a>=0){e.labels=[];for(let r=0;r<a;r++){let r=t.readVarIntNum();e.labels.push(e$(t.read(r)))}}let s=t.readVarIntNum();e.description=e$(t.read(s));let o=t.readInt8();o>=0?e.seekPermission=1===o:e.seekPermission=void 0,await this.wallet.internalizeAction(e,n);let c=new eZ;return c.writeUInt8(0),c.toArray()}case"listOutputs":{let e={},r=t.readVarIntNum(),i=t.read(r);e.basket=e$(i);let a=t.readVarIntNum();if(a>0){e.tags=[];for(let r=0;r<a;r++){let r=t.readVarIntNum(),i=t.read(r);e.tags.push(e$(i))}}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,n),b=new eZ;for(let e of(b.writeVarIntNum(p.totalOutputs),null!=p.BEEF?(b.writeVarIntNum(p.BEEF.length),b.write(p.BEEF)):b.writeVarIntNum(-1),p.outputs)){if(b.write(this.encodeOutpoint(e.outpoint)),b.writeVarIntNum(e.satoshis),void 0!==e.lockingScript){let t=eF(e.lockingScript,"hex");b.writeVarIntNum(t.length),b.write(t)}else b.writeVarIntNum(-1);if(void 0!==e.customInstructions){let t=eF(e.customInstructions,"utf8");b.writeVarIntNum(t.length),b.write(t)}else b.writeVarIntNum(-1);if(void 0!==e.tags)for(let t of(b.writeVarIntNum(e.tags.length),e.tags)){let e=eF(t,"utf8");b.writeVarIntNum(e.length),b.write(e)}else b.writeVarIntNum(-1);if(void 0!==e.labels)for(let t of(b.writeVarIntNum(e.labels.length),e.labels)){let e=eF(t,"utf8");b.writeVarIntNum(e.length),b.write(e)}else b.writeVarIntNum(-1)}let g=new eZ;return g.writeUInt8(0),g.write(b.toArray()),g.toArray()}case"relinquishOutput":{let e={},r=t.readVarIntNum(),i=t.read(r);e.basket=e$(i),e.output=this.decodeOutpoint(t),await this.wallet.relinquishOutput(e,n);let a=new eZ;return a.writeUInt8(0),a.toArray()}case"getPublicKey":{let e={},r=t.readUInt8();if(e.identityKey=1===r,!0!==e.identityKey){e.protocolID=this.decodeProtocolID(t),e.keyID=this.decodeString(t),e.counterparty=this.decodeCounterparty(t);let r=t.readInt8();-1===r?e.privileged=void 0:e.privileged=1===r;let i=t.readInt8();if(-1!==i){let r=t.read(i);e.privilegedReason=e$(r)}else e.privilegedReason=void 0;let a=t.readInt8();-1===a?e.forSelf=void 0:e.forSelf=1===a}else{let r=t.readInt8();-1===r?e.privileged=void 0:e.privileged=1===r;let i=t.readInt8();if(-1!==i){let r=t.read(i);e.privilegedReason=e$(r)}else e.privilegedReason=void 0}let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let a=await this.wallet.getPublicKey(e,n),s=new eZ;s.writeUInt8(0);let o=eF(a.publicKey,"hex");return s.write(o),s.toArray()}case"encrypt":{let e=this.decodeKeyRelatedParams(t),r=t.readVarIntNum();e.plaintext=t.read(r);let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let a=await this.wallet.encrypt(e,n),s=new eZ;return s.writeUInt8(0),s.write(a.ciphertext),s.toArray()}case"decrypt":{let e=this.decodeKeyRelatedParams(t),r=t.readVarIntNum();e.ciphertext=t.read(r);let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let a=await this.wallet.decrypt(e,n),s=new eZ;return s.writeUInt8(0),s.write(a.plaintext),s.toArray()}case"createHmac":{let e=this.decodeKeyRelatedParams(t),r=t.readVarIntNum();e.data=t.read(r);let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let a=await this.wallet.createHmac(e,n),s=new eZ;return s.writeUInt8(0),s.write(a.hmac),s.toArray()}case"verifyHmac":{let e=this.decodeKeyRelatedParams(t);e.hmac=t.read(32);let r=t.readVarIntNum();e.data=t.read(r);let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0,await this.wallet.verifyHmac(e,n);let a=new eZ;return a.writeUInt8(0),a.toArray()}case"createSignature":{let e=this.decodeKeyRelatedParams(t),r=t.readUInt8();if(1===r){let r=t.readVarIntNum();e.data=t.read(r)}else 2===r&&(e.hashToDirectlySign=t.read(32));let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let a=await this.wallet.createSignature(e,n),s=new eZ;return s.writeUInt8(0),s.write(a.signature),s.toArray()}case"verifySignature":{let e=this.decodeKeyRelatedParams(t),r=t.readInt8();-1===r?e.forSelf=void 0:e.forSelf=1===r;let i=t.readVarIntNum();e.signature=t.read(i);let a=t.readUInt8();if(1===a){let r=t.readVarIntNum();e.data=t.read(r)}else 2===a&&(e.hashToDirectlyVerify=t.read(32));let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0,await this.wallet.verifySignature(e,n);let o=new eZ;return o.writeUInt8(0),o.toArray()}case"isAuthenticated":{let e=await this.wallet.isAuthenticated({},n),t=new eZ;return t.writeUInt8(0),t.writeUInt8(+!!e.authenticated),t.toArray()}case"waitForAuthentication":{await this.wallet.waitForAuthentication({},n);let e=new eZ;return e.writeUInt8(0),e.toArray()}case"getHeight":{let e=await this.wallet.getHeight({},n),t=new eZ;return t.writeUInt8(0),t.writeVarIntNum(e.height),t.toArray()}case"getHeaderForHeight":{let e={};e.height=t.readVarIntNum();let r=await this.wallet.getHeaderForHeight(e,n),i=new eZ;i.writeUInt8(0);let a=eF(r.header,"hex");return i.write(a),i.toArray()}case"getNetwork":{let e=await this.wallet.getNetwork({},n),t=new eZ;return t.writeUInt8(0),t.writeUInt8(+("mainnet"!==e.network)),t.toArray()}case"getVersion":{let e=await this.wallet.getVersion({},n),t=new eZ;t.writeUInt8(0);let r=eF(e.version,"utf8");return t.write(r),t.toArray()}case"revealCounterpartyKeyLinkage":{let e={},r=t.readInt8();-1===r?e.privileged=void 0:e.privileged=1===r;let i=t.readInt8();if(-1===i)e.privilegedReason=void 0;else{let r=t.read(i);e.privilegedReason=e$(r)}let a=t.read(33);e.counterparty=eK(a);let s=t.read(33);e.verifier=eK(s);let o=await this.wallet.revealCounterpartyKeyLinkage(e,n),c=new eZ;c.write(eF(o.prover,"hex")),c.write(eF(o.verifier,"hex")),c.write(eF(o.counterparty,"hex"));let l=eF(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 eZ;return h.writeUInt8(0),h.write(c.toArray()),h.toArray()}case"revealSpecificKeyLinkage":{let e=this.decodeKeyRelatedParams(t),r=t.read(33);e.verifier=eK(r);let i=await this.wallet.revealSpecificKeyLinkage(e,n),a=new eZ;a.write(eF(i.prover,"hex")),a.write(eF(i.verifier,"hex")),a.write(eF(i.counterparty,"hex")),a.writeUInt8(i.protocolID[0]);let s=eF(i.protocolID[1],"utf8");a.writeVarIntNum(s.length),a.write(s);let o=eF(i.keyID,"utf8");a.writeVarIntNum(o.length),a.write(o),a.writeVarIntNum(i.encryptedLinkage.length),a.write(i.encryptedLinkage),a.writeVarIntNum(i.encryptedLinkageProof.length),a.write(i.encryptedLinkageProof),a.writeUInt8(i.proofType);let c=new eZ;return c.writeUInt8(0),c.write(a.toArray()),c.toArray()}case"acquireCertificate":{let e={},r=t.read(32);e.type=eW(r);let i=t.read(33);e.certifier=eK(i);let a=t.readVarIntNum();e.fields={};for(let r=0;r<a;r++){let r=t.readVarIntNum(),i=t.read(r),a=e$(i),n=t.readVarIntNum(),s=t.read(n),o=e$(s);e.fields[a]=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 r=t.read(o);e.privilegedReason=e$(r)}let c=t.readUInt8();if(e.acquisitionProtocol=1===c?"direct":"issuance","direct"===e.acquisitionProtocol){let r=t.read(32);e.serialNumber=eW(r),e.revocationOutpoint=this.decodeOutpoint(t);let i=t.readVarIntNum(),a=t.read(i);e.signature=eK(a);let n=t.readUInt8();if(11===n)e.keyringRevealer="certifier";else{let r=[n].concat(t.read(32));e.keyringRevealer=eK(r)}let s=t.readVarIntNum();e.keyringForSubject={};for(let r=0;r<s;r++){let r=t.readVarIntNum(),i=t.read(r),a=e$(i),n=t.readVarIntNum(),s=t.read(n),o=eW(s);e.keyringForSubject[a]=o}}else{let r=t.readVarIntNum(),i=t.read(r);e.certifierUrl=e$(i)}let l=await this.wallet.acquireCertificate(e,n),h=new r0(l.type,l.serialNumber,l.subject,l.certifier,l.revocationOutpoint,l.fields,l.signature).toBinary(),d=new eZ;return d.writeUInt8(0),d.write(h),d.toArray()}case"listCertificates":{let e={},r=t.readVarIntNum();e.certifiers=[];for(let i=0;i<r;i++){let r=t.read(33);e.certifiers.push(eK(r))}let i=t.readVarIntNum();e.types=[];for(let r=0;r<i;r++){let r=t.read(32);e.types.push(eW(r))}let a=t.readVarIntNum();a>=0?e.limit=a: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 r=t.read(c);e.privilegedReason=e$(r)}let l=await this.wallet.listCertificates(e,n),h=new eZ;for(let e of(h.writeVarIntNum(l.totalCertificates),l.certificates)){let t=new r0(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,r]of(h.writeVarIntNum(t.length),t)){let t=eF(e,"utf8");h.writeVarIntNum(t.length),h.write(t);let i=eF(r,"base64");h.writeVarIntNum(i.length),h.write(i)}}else h.writeInt8(0);let r=eF(e.verifier,"hex");h.writeVarIntNum(r.length),h.write(r)}let d=new eZ;return d.writeUInt8(0),d.write(h.toArray()),d.toArray()}case"proveCertificate":{let e={},r={},i=t.read(32);r.type=eW(i);let a=t.read(33);r.subject=eK(a);let s=t.read(32);r.serialNumber=eW(s);let o=t.read(33);r.certifier=eK(o),r.revocationOutpoint=this.decodeOutpoint(t);let c=t.readVarIntNum(),l=t.read(c);r.signature=eK(l);let h=t.readVarIntNum();r.fields={};for(let e=0;e<h;e++){let e=t.readVarIntNum(),i=t.read(e),a=e$(i),n=t.readVarIntNum(),s=t.read(n),o=e$(s);r.fields[a]=o}e.certificate=r;let d=t.readVarIntNum();e.fieldsToReveal=[];for(let r=0;r<d;r++){let r=t.readVarIntNum(),i=t.read(r),a=e$(i);e.fieldsToReveal.push(a)}let u=t.read(33);e.verifier=eK(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 r=t.read(p);e.privilegedReason=e$(r)}let b=await this.wallet.proveCertificate(e,n),g=new eZ,m=Object.entries(b.keyringForVerifier);for(let[e,t]of(g.writeVarIntNum(m.length),m)){let r=eF(e,"utf8");g.writeVarIntNum(r.length),g.write(r);let i=eF(t,"base64");g.writeVarIntNum(i.length),g.write(i)}let y=new eZ;return y.writeUInt8(0),y.write(g.toArray()),y.toArray()}case"relinquishCertificate":{let e={},r=t.read(32);e.type=eW(r);let i=t.read(32);e.serialNumber=eW(i);let a=t.read(33);e.certifier=eK(a),await this.wallet.relinquishCertificate(e,n);let s=new eZ;return s.writeUInt8(0),s.toArray()}case"discoverByIdentityKey":{let e={},r=t.read(33);e.identityKey=eK(r);let i=t.readVarIntNum();i>=0?e.limit=i:e.limit=void 0;let a=t.readVarIntNum();a>=0?e.offset=a: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,n),c=this.serializeDiscoveryResult(o),l=new eZ;return l.writeUInt8(0),l.write(c),l.toArray()}case"discoverByAttributes":{let e={},r=t.readVarIntNum();e.attributes={};for(let i=0;i<r;i++){let r=t.readVarIntNum(),i=t.read(r),a=e$(i),n=t.readVarIntNum(),s=t.read(n),o=e$(s);e.attributes[a]=o}let i=t.readVarIntNum();i>=0?e.limit=i:e.limit=void 0;let a=t.readVarIntNum();a>=0?e.offset=a: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,n),c=this.serializeDiscoveryResult(o),l=new eZ;return l.writeUInt8(0),l.write(c),l.toArray()}default:throw Error(`Method ${r} not implemented`)}}catch(i){let e=new eZ;e.writeUInt8("number"==typeof i.code?i.code:1);let t=eF("string"==typeof i.message?i.message:"Unknown error","utf8");e.writeVarIntNum(t.length),e.write(t);let r=eF("string"==typeof i.stack?i.stack:"","utf8");return e.writeVarIntNum(r.length),e.write(r),e.toArray()}}decodeProtocolID(e){let t=e.readUInt8(),r=e.readVarIntNum();return[t,e$(e.read(r))]}decodeString(e){let t=e.readVarIntNum();return e$(e.read(t))}decodeCounterparty(e){let t=e.readUInt8();return 11===t?"self":12===t?"anyone":0!==t?eK([t,...e.read(32)]):void 0}serializeDiscoveryResult(e){let t=new eZ;for(let r of(t.writeVarIntNum(e.totalCertificates),e.certificates)){let e=new r0(r.type,r.serialNumber,r.subject,r.certifier,r.revocationOutpoint,r.fields,r.signature).toBinary();t.writeVarIntNum(e.length),t.write(e);let i=eF(r.certifierInfo.name,"utf8");t.writeVarIntNum(i.length),t.write(i);let a=eF(r.certifierInfo.iconUrl,"utf8");t.writeVarIntNum(a.length),t.write(a);let n=eF(r.certifierInfo.description,"utf8");t.writeVarIntNum(n.length),t.write(n),t.writeUInt8(r.certifierInfo.trust);let s=Object.entries(r.publiclyRevealedKeyring);for(let[e,r]of(t.writeVarIntNum(s.length),s)){let i=eF(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let a=eF(r,"base64");t.writeVarIntNum(a.length),t.write(a)}let o=Object.entries(r.decryptedFields);for(let[e,r]of(t.writeVarIntNum(o.length),o)){let i=eF(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let a=eF(r,"utf8");t.writeVarIntNum(a.length),t.write(a)}}return t.toArray()}decodeKeyRelatedParams(e){let t={};t.protocolID=this.decodeProtocolID(e);let r=e.readVarIntNum();t.keyID=e$(e.read(r)),t.counterparty=this.decodeCounterparty(e);let i=e.readInt8();-1===i?t.privileged=void 0:t.privileged=1===i;let a=e.readInt8();return -1===a?t.privilegedReason=void 0:t.privilegedReason=e$(e.read(a)),t}}class ie extends r0{masterKeyring;constructor(e,t,r,i,a,n,s,o){for(let c of(super(e,t,r,i,a,n,o),Object.keys(n)))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,r,i,a){let n={},s={};for(let[o,c]of Object.entries(r)){let r=tz.fromRandom(),l=r.encrypt(eF(c,"utf8"));n[o]=eW(l);let{ciphertext:h}=await e.encrypt({plaintext:r.toArray(),...r0.getCertificateFieldEncryptionDetails(o),counterparty:t,privileged:i,privilegedReason:a});s[o]=eW(h)}return{certificateFields:n,masterKeyring:s}}static async createKeyringForVerifier(e,t,r,i,a,n,s,o,c){if(!Array.isArray(a))throw Error("fieldsToReveal must be an array of strings");let l={};for(let h of a){if(void 0===i[h]||null===i[h]||""===i[h])throw Error(`Fields to reveal must be a subset of the certificate fields. Missing the "${h}" field.`);let a=(await this.decryptField(e,n,h,i[h],t,o,c)).fieldRevelationKey,{ciphertext:d}=await e.encrypt({plaintext:a,...r0.getCertificateFieldEncryptionDetails(h,s),counterparty:r,privileged:o,privilegedReason:c});l[h]=eW(d)}return l}static async issueCertificateForSubject(e,t,r,i,a=async e=>"Certificate revocation not tracked.",n){let s=n??eW(tx(32)),{certificateFields:o,masterKeyring:c}=await this.createCertificateFields(e,t,r),l=await a(s),h=new ie(i,s,t,(await e.getPublicKey({identityKey:!0})).publicKey,l,o,c);return await h.sign(e),h}static async decryptFields(e,t,r,i,a,n){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(r))s[o]=(await this.decryptField(e,t,o,r[o],i,a,n)).decryptedFieldValue;return s}catch{throw Error("Failed to decrypt all master certificate fields.")}}static async decryptField(e,t,r,i,a,n,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:eF(t[r],"base64"),...r0.getCertificateFieldEncryptionDetails(r),counterparty:a,privileged:n,privilegedReason:s}),c=new tz(o).decrypt(eF(i,"base64"));return{fieldRevelationKey:o,decryptedFieldValue:e$(c)}}catch{throw Error("Failed to decrypt certificate field!")}}}class it extends r0{keyring;decryptedFields;constructor(e,t,r,i,a,n,s,o,c){super(e,t,r,i,a,n,o),this.keyring=s,this.decryptedFields=c}static fromCertificate(e,t){return new it(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,t,e.signature)}async decryptFields(e,t,r,i){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 a={};for(let n in this.keyring){let{plaintext:s}=await e.decrypt({ciphertext:eF(this.keyring[n],"base64"),...r0.getCertificateFieldEncryptionDetails(n,this.serialNumber),counterparty:this.subject,privileged:t,privilegedReason:r},i),o=new tz(s).decrypt(eF(this.fields[n],"base64"));a[n]=e$(o)}return a}catch(e){throw Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(e instanceof Error?e.message:e)}`)}}}class ir extends rX{keyDeriver;constructor(e){if(super(e),e instanceof rj)this.keyDeriver=e;else if("string"==typeof e||e instanceof tO)this.keyDeriver=new rG(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 ii{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,r=this.sessionNonceToSession.get(e);if(null!=r)return r;let i=this.identityKeyToNonces.get(e);if(null!=i&&0!==i.size){for(let e of i){let r=this.sessionNonceToSession.get(e);null!=r&&(null==t?t=r:(r.lastUpdate??0)>(t.lastUpdate??0)&&(t=r))}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 ia(e,t,r="self",i){let a=eF(e,"base64"),n=a.slice(0,16),s=a.slice(16),{valid:o}=await t.verifyHmac({data:n,hmac:s,protocolID:[2,"server hmac"],keyID:e$(n),counterparty:r},i);return o}async function is(e,t="self",r){let i=tx(16),{hmac:a}=await e.createHmac({protocolID:[2,"server hmac"],keyID:e$(i),data:i,counterparty:t},r);return eW([...i,...a])}let io=async(e,t,r,i)=>{let a=await e.listCertificates({certifiers:t.certifiers,types:Object.keys(t.types)},i);return await Promise.all(a.certificates.map(async a=>{let{keyringForVerifier:n}=await e.proveCertificate({certificate:a,fieldsToReveal:t.types[a.type],verifier:r},i);return new it(a.type,a.serialNumber,a.subject,a.certifier,a.revocationOutpoint,a.fields,n,a.signature)}))},ic=async(e,t,r,i)=>{if(null==t.certificates||0===t.certificates.length)throw Error("No certificates were provided in the AuthMessage.");await Promise.all(t.certificates.map(async a=>{if(a.subject!==t.identityKey)throw Error(`The subject of one of your certificates ("${a.subject}") is not the same as the request sender ("${t.identityKey}").`);let n=new it(a.type,a.serialNumber,a.subject,a.certifier,a.revocationOutpoint,a.fields,a.keyring,a.signature);if(!await n.verify())throw Error(`The signature for the certificate with serial number ${n.serialNumber} is invalid!`);if(null!=r){let{certifiers:e,types:t}=r;if(!e.includes(n.certifier))throw Error(`Certificate with serial number ${n.serialNumber} has an unrequested certifier: ${n.certifier}`);if(null==t[n.type])throw Error(`Certificate with type ${n.type} was not requested`)}await n.decryptFields(e,void 0,void 0,i)}))};class il{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;originator;constructor(e,t,r,i,a,n){this.wallet=e,this.originator=n,this.transport=t,this.certificatesToRequest=r??{certifiers:[],types:{}},this.transport.onData(this.handleIncomingMessage.bind(this)).catch(e=>{throw e}),this.sessionManager=null!=i?i:new ii,!1===a?this.autoPersistLastSession=!1:this.autoPersistLastSession=!0}async toPeer(e,t,r){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);let i=await this.getAuthenticatedSession(t,r),a=eW(tx(32)),{signature:n}=await this.wallet.createSignature({data:e,protocolID:[2,"auth message signature"],keyID:`${a} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),s={version:"0.1",messageType:"general",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,nonce:a,yourNonce:i.peerNonce,payload:e,signature:n};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(t){let e=Error(`Failed to send message to peer ${i.peerIdentityKey??"unknown"}: ${String(t.message)}`);throw e.stack=t.stack,e}}async requestCertificates(e,t,r=1e4){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);let i=await this.getAuthenticatedSession(t,r),a=eW(tx(32)),{signature:n}=await this.wallet.createSignature({data:eF(JSON.stringify(e),"utf8"),protocolID:[2,"auth message signature"],keyID:`${a} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),s={version:"0.1",messageType:"certificateRequest",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,nonce:a,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,requestedCertificates:e,signature:n};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(e){throw Error(`Failed to send certificate request message to peer ${i.peerIdentityKey??"unknown"}: ${String(e.message)}`)}}async getAuthenticatedSession(e,t){let r;if(void 0===this.transport)throw Error("Peer transport is not connected!");if("string"==typeof e&&(r=this.sessionManager.getSession(e)),null==r||!r.isAuthenticated){let i=await this.initiateHandshake(e,t);if(null==(r=this.sessionManager.getSession(i))||!r.isAuthenticated)throw Error("Unable to establish mutual authentication with peer!")}return r}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,t=1e4){let r=await is(this.wallet,void 0,this.originator),i=Date.now();this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:r,peerIdentityKey:e,lastUpdate:i});let a={version:"0.1",messageType:"initialRequest",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,initialNonce:r,requestedCertificates:this.certificatesToRequest};return await this.transport.send(a),await this.waitForInitialResponse(r,t)}async waitForInitialResponse(e,t=1e4){return await new Promise((r,i)=>{let a=this.listenForInitialResponse(e,e=>{clearTimeout(n),this.stopListeningForInitialResponses(a),r(e)}),n=setTimeout(()=>{this.stopListeningForInitialResponses(a),i(Error("Initial response timed out."))},t)})}listenForInitialResponse(e,t){let r=this.callbackIdCounter++;return this.onInitialResponseReceivedCallbacks.set(r,{callback:t,sessionNonce:e}),r}stopListeningForInitialResponses(e){this.onInitialResponseReceivedCallbacks.delete(e)}async handleIncomingMessage(e){if("string"!=typeof e.version||"0.1"!==e.version)throw Error(`Invalid or unsupported message auth version! Received: ${e.version}, expected: 0.1`);switch(e.messageType){case"initialRequest":await this.processInitialRequest(e);break;case"initialResponse":await this.processInitialResponse(e);break;case"certificateRequest":await this.processCertificateRequest(e);break;case"certificateResponse":await this.processCertificateResponse(e);break;case"general":await this.processGeneralMessage(e);break;default:throw Error(`Unknown message type of ${String(e.messageType)} from ${String(e.identityKey)}`)}}async processInitialRequest(e){let t;if("string"!=typeof e.identityKey||"string"!=typeof e.initialNonce||""===e.initialNonce)throw Error("Missing required fields in initialRequest message.");let r=await is(this.wallet,void 0,this.originator),i=Date.now();this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:r,peerNonce:e.initialNonce,peerIdentityKey:e.identityKey,lastUpdate:i}),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)}):t=await io(this.wallet,e.requestedCertificates,e.identityKey,this.originator));let{signature:a}=await this.wallet.createSignature({data:eF(e.initialNonce+r,"base64"),protocolID:[2,"auth message signature"],keyID:`${e.initialNonce} ${r}`,counterparty:e.identityKey},this.originator),n={version:"0.1",messageType:"initialResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,initialNonce:r,yourNonce:e.initialNonce,certificates:t,requestedCertificates:this.certificatesToRequest,signature:a};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=e.identityKey),await this.transport.send(n)}async processInitialResponse(e){if(!await ia(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 r=eF((t.sessionNonce??"")+(e.initialNonce??""),"base64"),{valid:i}=await this.wallet.verifySignature({data:r,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${t.sessionNonce??""} ${e.initialNonce??""}`,counterparty:e.identityKey},this.originator);if(!i)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.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.certificatesToRequest?.certifiers?.length>0&&e.certificates?.length>0&&(await ic(this.wallet,e,this.certificatesToRequest,this.originator),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 io(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async processCertificateRequest(e){if(!await ia(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:r}=await this.wallet.verifySignature({data:eF(JSON.stringify(e.requestedCertificates),"utf8"),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!r)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 io(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async sendCertificateResponse(e,t){let r=await this.getAuthenticatedSession(e),i=eW(tx(32)),{signature:a}=await this.wallet.createSignature({data:eF(JSON.stringify(t),"utf8"),protocolID:[2,"auth message signature"],keyID:`${i} ${r.peerNonce??""}`,counterparty:r.peerIdentityKey},this.originator),n={version:"0.1",messageType:"certificateResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,nonce:i,initialNonce:r.sessionNonce,yourNonce:r.peerNonce,certificates:t,signature:a};r.lastUpdate=Date.now(),this.sessionManager.updateSession(r);try{await this.transport.send(n)}catch(t){let e=t instanceof Error?t.message:String(t);throw Error(`Failed to send certificate response message to peer ${r.peerIdentityKey??"unknown"}: ${e}`)}}async processCertificateResponse(e){if(!await ia(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:r}=await this.wallet.verifySignature({data:eF(JSON.stringify(e.certificates),"utf8"),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:e.identityKey},this.originator);if(!r)throw Error(`Unable to verify certificate response signature for peer: ${e.identityKey}`);await ic(this.wallet,e,e.requestedCertificates,this.originator),this.onCertificatesReceivedCallbacks.forEach(t=>{t(e.identityKey,e.certificates??[])}),t.lastUpdate=Date.now(),this.sessionManager.updateSession(t)}async processGeneralMessage(e){if(!await ia(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{valid:r}=await this.wallet.verifySignature({data:e.payload,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!r)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??[])})}}let ih="undefined"!=typeof window?fetch.bind(window):fetch;class id{onDataCallback;fetchClient;baseUrl;constructor(e,t=ih){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,r)=>{(async()=>{try{let r=this.fetchClient(`${this.baseUrl}/.well-known/auth`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});"initialRequest"!==e.messageType&&t();let i=await r;if(i.ok&&null!=this.onDataCallback){let e=await i.json();this.onDataCallback(e)}else throw Error("HTTP server failed to authenticate");"initialRequest"===e.messageType&&t()}catch(e){r(e)}})()});{let t=this.deserializeRequestPayload(e.payload),r=`${this.baseUrl}${t.urlPostfix}`;if("object"!=typeof t.headers&&(t.headers={}),t.headers["x-bsv-auth-version"]=e.version,t.headers["x-bsv-auth-identity-key"]=e.identityKey,t.headers["x-bsv-auth-nonce"]=e.nonce,t.headers["x-bsv-auth-your-nonce"]=e.yourNonce,t.headers["x-bsv-auth-signature"]=eK(e.signature),t.headers["x-bsv-auth-request-id"]=t.requestId,null!=t.body){let e=t.headers;if(null==e["content-type"])throw Error("Content-Type header is required for requests with a body.");let r=String(e["content-type"]??"");r.includes("application/json")||r.includes("application/x-www-form-urlencoded")||r.includes("text/plain")?t.body=e$(t.body):t.body=new Uint8Array(t.body)}let i=await this.fetchClient(r,{method:t.method,headers:t.headers,body:t.body});if(500===i.status&&null==i.headers.get("x-bsv-auth-request-id")&&null==i.headers.get("x-bsv-auth-requested-certificates")){let e=await i.json();throw Error(`HTTP ${i.status} - ${JSON.stringify(e)}`)}let a=await i.arrayBuffer(),n=new eZ;null!=i.headers.get("x-bsv-auth-request-id")&&n.write(eF(i.headers.get("x-bsv-auth-request-id"),"base64")),n.writeVarIntNum(i.status);let s=[];i.headers.forEach((e,t)=>{let r=t.toLowerCase();(r.startsWith("x-bsv-")||"authorization"===r)&&!r.startsWith("x-bsv-auth")&&s.push([r,e])}),s.sort(([e],[t])=>e.localeCompare(t)),n.writeVarIntNum(s.length);for(let e=0;e<s.length;e++){let t=eF(s[e][0],"utf8");n.writeVarIntNum(t.length),n.write(t);let r=eF(s[e][1],"utf8");n.writeVarIntNum(r.length),n.write(r)}if(null!=a){let e=Array.from(new Uint8Array(a));n.writeVarIntNum(e.length),n.write(e)}else n.writeVarIntNum(-1);let o={version:i.headers.get("x-bsv-auth-version"),messageType:"certificateRequest"===i.headers.get("x-bsv-auth-message-type")?"certificateRequest":"general",identityKey:i.headers.get("x-bsv-auth-identity-key"),nonce:i.headers.get("x-bsv-auth-nonce"),yourNonce:i.headers.get("x-bsv-auth-your-nonce"),requestedCertificates:JSON.parse(i.headers.get("x-bsv-auth-requested-certificates")),payload:n.toArray(),signature:eF(i.headers.get("x-bsv-auth-signature"),"hex")};if(null==o.version)throw Error("HTTP server failed to authenticate");this.onDataCallback(o)}}async onData(e){this.onDataCallback=t=>{e(t)}}deserializeRequestPayload(e){let t,r=new eQ(e),i=eW(r.read(32)),a=r.readVarIntNum(),n="GET";a>0&&(n=e$(r.read(a)));let s=r.readVarIntNum(),o="";s>0&&(o=e$(r.read(s)));let c=r.readVarIntNum(),l="";c>0&&(l=e$(r.read(c)));let h={},d=r.readVarIntNum();if(d>0)for(let e=0;e<d;e++){let e=r.readVarIntNum(),t=e$(r.read(e)),i=r.readVarIntNum(),a=e$(r.read(i));h[t]=a}let u=r.readVarIntNum();return u>0&&(t=r.read(u)),{urlPostfix:o+l,method:n,headers:h,body:t,requestId:i}}}class iu{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;originator;peers={};constructor(e,t,r,i){this.wallet=e,this.requestedCertificates=t,this.sessionManager=r??new ii,this.originator=i}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 r=await new Promise(async(r,i)=>{try{let a,{method:n="GET",headers:s={},body:o}=t,c=new URL(e),l=c.origin;if(void 0===this.peers[l]){let e=new id(l);a={peer:new il(this.wallet,e,this.requestedCertificates,this.sessionManager,void 0,this.originator),pendingCertificateRequests:[]},this.peers[l]=a,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 r=await io(this.wallet,t,e,this.originator);await this.peers[l].peer.sendCertificateResponse(e,r)}finally{await new Promise(e=>setTimeout(e,500)),this.peers[l].pendingCertificateRequests.shift()}})}else{if(!1===this.peers[l].supportsMutualAuth){try{let i=await this.handleFetchAndValidate(e,t,this.peers[l]);r(i)}catch(e){i(e)}return}a=this.peers[l]}let h=tx(32),d=eW(h),u=await this.serializeRequest(n,s,o,c,h);this.callbacks[d]={resolve:r,reject:i};let f=a.peer.listenForGeneralMessages((e,t)=>{let r,i=new eQ(t);if(eW(i.read(32))!==d)return;a.peer.stopListeningForGeneralMessages(f),this.peers[l].identityKey=e,this.peers[l].supportsMutualAuth=!0;let n=i.readVarIntNum(),s={},o=i.readVarIntNum();if(o>0)for(let e=0;e<o;e++){let e=i.readVarIntNum(),t=i.read(e),r=e$(t),a=i.readVarIntNum(),n=i.read(a),o=e$(n);s[r]=o}s["x-bsv-auth-identity-key"]=e;let c=i.readVarIntNum();c>0&&(r=i.read(c));let h=new Response(r?new Uint8Array(r):null,{status:n,statusText:`${n}`,headers:new Headers(s)});this.callbacks[d].resolve(h),delete this.callbacks[d]});a.pendingCertificateRequests.length>0&&await new Promise(e=>{setInterval(()=>{0===a.pendingCertificateRequests.length&&e()},100)}),await a.peer.toPeer(u.toArray(),a.identityKey).catch(async n=>{if(n.message.includes("Session not found for nonce")){delete this.peers[l],t.retryCounter??=3;let i=await this.fetch(e,t);r(i);return}if(n.message.includes("HTTP server failed to authenticate"))try{let i=await this.handleFetchAndValidate(e,t,a);r(i);return}catch(e){i(e)}else i(n)})}catch(e){i(e)}});return 402===r.status?await this.handlePaymentAndRetry(e,t,r):r}async sendCertificateRequest(e,t){let r,i=new URL(e).origin;if(void 0!==this.peers[i])r={peer:this.peers[i].peer};else{let e=new id(i);r={peer:new il(this.wallet,e,this.requestedCertificates,this.sessionManager,this.originator)},this.peers[i]=r}return await new Promise(async(e,i)=>{let a=r.peer.listenForCertificatesReceived((t,i)=>{r.peer.stopListeningForCertificatesReceived(a),this.certificatesReceived.push(...i),e(i)});try{await r.peer.requestCertificates(t,r.identityKey)}catch(e){r.peer.stopListeningForCertificatesReceived(a),i(e)}})}consumeReceivedCertificates(){return this.certificatesReceived.splice(0)}async serializeRequest(e,t,r,i,a){let n=new eZ;if(n.write(a),n.writeVarIntNum(e.length),n.write(eF(e)),i.pathname.length>0){let e=eF(i.pathname);n.writeVarIntNum(e.length),n.write(e)}else n.writeVarIntNum(-1);if(i.search.length>0){let e=eF(i.search);n.writeVarIntNum(e.length),n.write(e)}else n.writeVarIntNum(-1);let s=[];for(let[e,r]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,r])}else if(e.startsWith("content-type"))r=r.split(";")[0].trim(),s.push([e,r]);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)),n.writeVarIntNum(s.length);for(let e=0;e<s.length;e++){let t=eF(s[e][0],"utf8");n.writeVarIntNum(t.length),n.write(t);let r=eF(s[e][1],"utf8");n.writeVarIntNum(r.length),n.write(r)}if(["POST","PUT","PATCH","DELETE"].includes(e.toUpperCase())&&void 0===r){let e=s.find(([e])=>"content-type"===e);r=e&&e[1].includes("application/json")?"{}":""}if(r){let e=await this.normalizeBodyToNumberArray(r);n.writeVarIntNum(e.length),n.write(e)}else n.writeVarIntNum(-1);return n}async handleFetchAndValidate(e,t,r){let i=await fetch(e,t);if(i.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!")}),i.ok)return r.supportsMutualAuth=!1,i;throw Error(`Request failed with status: ${i.status}`)}async handlePaymentAndRetry(e,t={},r){let i=r.headers.get("x-bsv-payment-version");if(!i||"1.0"!==i)throw Error(`Unsupported x-bsv-payment-version response header. Client version: 1.0, Server version: ${i}`);let a=r.headers.get("x-bsv-payment-satoshis-required");if(!a)throw Error("Missing x-bsv-payment-satoshis-required response header.");let n=parseInt(a);if(isNaN(n)||n<=0)throw Error("Invalid x-bsv-payment-satoshis-required response header value.");let s=r.headers.get("x-bsv-auth-identity-key");if("string"!=typeof s)throw Error("Missing x-bsv-auth-identity-key response header.");let o=r.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=await is(this.wallet,void 0,this.originator),{publicKey:l}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${o} ${c}`,counterparty:s},this.originator),h=new t3().lock(tv.fromString(l).toAddress()).toHex(),{tx:d}=await this.wallet.createAction({description:`Payment for request to ${new URL(e).origin}`,outputs:[{satoshis:n,lockingScript:h,customInstructions:JSON.stringify({derivationPrefix:o,derivationSuffix:c,payee:s}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}},this.originator);return t.headers=t.headers||{},t.headers["x-bsv-payment"]=JSON.stringify({derivationPrefix:o,derivationSuffix:c,transaction:eW(d)}),t.retryCounter??=3,this.fetch(e,t)}async normalizeBodyToNumberArray(e){if(null==e)return[];if("object"==typeof e)return eF(JSON.stringify(e,"utf8"));if(Array.isArray(e)&&e.every(e=>"number"==typeof e))return e;if("string"==typeof e)return eF(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,r)=>{t.push([r,e.toString()])}),eF(new URLSearchParams(t).toString(),"utf8")}if(e instanceof URLSearchParams)return eF(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 ip{pushDrop;static decode(e){let t=t7.decode(e);if(t.fields.length<4)throw Error("Invalid SHIP/SLAP advertisement!");let r=e$(t.fields[0]);if("SHIP"!==r&&"SLAP"!==r)throw Error("Invalid protocol type!");let i=eK(t.fields[1]);return{protocol:r,identityKey:i,domain:e$(t.fields[2]),topicOrService:e$(t.fields[3])}}constructor(e){this.pushDrop=new t7(e)}async lock(e,t,r){let{publicKey:i}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([eF(e,"utf8"),eF(i,"hex"),eF(t,"utf8"),eF(r,"utf8")],[2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}unlock(e){return this.pushDrop.unlock([2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}}let ib="undefined"!=typeof window?fetch.bind(window):fetch,ig=["https://overlay-us-1.bsvb.tech","https://overlay-eu-1.bsvb.tech","https://overlay-ap-1.bsvb.tech","https://users.bapp.dev"],im=["https://testnet-users.bapp.dev"];class iy{fetchClient;allowHTTP;constructor(e=ib,t=!1){this.fetchClient=e,this.allowHTTP=t}async lookup(e,t,r=5e3){if(!e.startsWith("https:")&&!this.allowHTTP)throw Error('HTTPS facilitator can only use URLs that start with "https:"');let i="undefined"!=typeof AbortController?new AbortController:void 0,a=setTimeout(()=>{try{i?.abort()}catch{}},r);try{let r={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:t.service,query:t.query}),signal:i?.signal},a=await this.fetchClient(`${e}/lookup`,r);if(!a.ok)throw Error(`Failed to facilitate lookup (HTTP ${a.status})`);return await a.json()}catch(e){if(e?.name==="AbortError")throw Error("Request timed out");throw e}finally{clearTimeout(a)}}}class iw{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;hostsCache;hostsInFlight;hostsTtlMs;hostsMaxEntries;txMemo;txMemoTtlMs;constructor(e={}){this.networkPreset=e.networkPreset??"mainnet",this.facilitator=e.facilitator??new iy(void 0,"local"===this.networkPreset),this.slapTrackers=e.slapTrackers??("mainnet"===this.networkPreset?ig:im),this.hostOverrides=e.hostOverrides??{},this.additionalHosts=e.additionalHosts??{},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 r=[];if(r="ls_slap"===e.service?"local"===this.networkPreset?["http://localhost:8080"]:this.slapTrackers:null!=this.hostOverrides[e.service]?this.hostOverrides[e.service]:"local"===this.networkPreset?["http://localhost:8080"]:await this.getCompetentHostsCached(e.service),this.additionalHosts[e.service]?.length>0){let t=this.additionalHosts[e.service],i=new Set(r);for(let e of t)i.has(e)||r.push(e)}if(r.length<1)throw Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${e.service}`);let i=await Promise.allSettled(r.map(async r=>await this.facilitator.lookup(r,e,t))),a=new Map,n=e=>"object"!=typeof e?"":e.join(",");for(let e of i){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=n(e.beef),r=this.txMemo.get(t),i=Date.now();if("object"!=typeof r||null===r||r.expiresAt<=i)try{r={txId:rg.fromBEEF(e.beef).id("hex"),expiresAt:i+this.txMemoTtlMs},this.txMemo.size>4096&&this.evictOldest(this.txMemo),this.txMemo.set(t,r)}catch{continue}let s=`${r.txId}.${e.outputIndex}`;a.set(s,e)}}return{type:"output-list",outputs:Array.from(a.values())}}async getCompetentHostsCached(e){let t=Date.now(),r=this.hostsCache.get(e);if("object"==typeof r&&r.expiresAt>t)return r.hosts.slice();if("object"==typeof r&&r.expiresAt<=t)return this.hostsInFlight.has(e)||this.hostsInFlight.set(e,this.refreshHosts(e).finally(()=>{this.hostsInFlight.delete(e)})),r.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 i=this.refreshHosts(e).finally(()=>{this.hostsInFlight.delete(e)});return this.hostsInFlight.set(e,i),(await i).slice()}async refreshHosts(e){let t=await this.findCompetentHosts(e),r=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:r}),t}async findCompetentHosts(e){let t={service:"ls_slap",query:{service:e}},r=await Promise.allSettled(this.slapTrackers.map(async e=>await this.facilitator.lookup(e,t,5e3))),i=new Set;for(let t of r){if("fulfilled"!==t.status)continue;let r=t.value;if("output-list"===r.type)for(let t of r.outputs)try{let r=rg.fromBEEF(t.beef),a=r.outputs[t.outputIndex]?.lockingScript;if("object"!=typeof a||null===a)continue;let n=ip.decode(a);if(n.topicOrService!==e||"SLAP"!==n.protocol)continue;"string"==typeof n.domain&&n.domain.length>0&&i.add(n.domain)}catch{continue}}return[...i]}evictOldest(e){let t=e.keys().next().value;void 0!==t&&e.delete(t)}}class iI{httpClient;allowHTTP;constructor(e=fetch,t=!1){this.httpClient=e,this.allowHTTP=t}async send(e,t){let r;if(!e.startsWith("https:")&&!this.allowHTTP)throw Error('HTTPS facilitator can only use URLs that start with "https:"');let i={"Content-Type":"application/octet-stream","X-Topics":JSON.stringify(t.topics)};if(Array.isArray(t.offChainValues)){i["x-includes-off-chain-values"]="true";let e=new eZ;e.writeVarIntNum(t.beef.length),e.write(t.beef),e.write(t.offChainValues),r=new Uint8Array(e.toArray())}else r=new Uint8Array(t.beef);let a=await fetch(`${e}/submit`,{method:"POST",headers:i,body:r});if(a.ok)return await a.json();throw Error("Failed to facilitate broadcast")}}class iv{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 iI(void 0,"local"===this.networkPreset),this.resolver=t.resolver??new iw({networkPreset:this.networkPreset}),this.requireAcknowledgmentFromAllHostsForTopics=t.requireAcknowledgmentFromAllHostsForTopics??[],this.requireAcknowledgmentFromAnyHostForTopics=t.requireAcknowledgmentFromAnyHostForTopics??"all",this.requireAcknowledgmentFromSpecificHostsForTopics=t.requireAcknowledgmentFromSpecificHostsForTopics??{}}async broadcast(e){let t,r,i,a,n,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,r])=>{try{let i=await this.facilitator.send(e,{beef:t,offChainValues:s,topics:[...r]});if(null==i||0===Object.keys(i).length)throw Error("Steak has no topics.");return{host:e,success:!0,steak:i}}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,r=e.steak,i=new Set;for(let[e,t]of Object.entries(r)){let r=t.outputsToAdmit,a=t.coinsToRetain,n=t.coinsRemoved;(r?.length>0||a?.length>0||n?.length>0)&&i.add(e)}h[t]=i}return("all"===this.requireAcknowledgmentFromAllHostsForTopics?(r=this.topics,i="all"):"any"===this.requireAcknowledgmentFromAllHostsForTopics?(r=this.topics,i="any"):(r=Array.isArray(this.requireAcknowledgmentFromAllHostsForTopics)?this.requireAcknowledgmentFromAllHostsForTopics:this.topics,i="all"),r.length>0&&!this.checkAcknowledgmentFromAllHosts(h,r,i))?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ALL_HOSTS_FAILED",description:"Not all hosts acknowledged the required topics."}:("all"===this.requireAcknowledgmentFromAnyHostForTopics?(a=this.topics,n="all"):"any"===this.requireAcknowledgmentFromAnyHostForTopics?(a=this.topics,n="any"):(a=Array.isArray(this.requireAcknowledgmentFromAnyHostForTopics)?this.requireAcknowledgmentFromAnyHostForTopics:[],n="all"),a.length>0&&!this.checkAcknowledgmentFromAnyHost(h,a,n))?{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,r){for(let i of Object.values(e))if("all"===r){for(let e of t)if(!i.has(e))return!1}else if("any"===r){let e=!1;for(let r of t)if(i.has(r)){e=!0;break}if(!e)return!1}return!0}checkAcknowledgmentFromAnyHost(e,t,r){if("all"===r){for(let r of Object.values(e)){let e=!0;for(let i of t)if(!r.has(i)){e=!1;break}if(e)return!0}return!1}for(let r of Object.values(e))for(let e of t)if(r.has(e))return!0;return!1}checkAcknowledgmentFromSpecificHosts(e,t){for(let[r,i]of Object.entries(t)){let t,a,n=e[r];if(null==n)return!1;if("all"===i||"any"===i)a=i,t=this.topics;else{if(!Array.isArray(i))continue;t=i,a="all"}if("all"===a){for(let e of t)if(!n.has(e))return!1}else if("any"===a){let e=!1;for(let r of t)if(n.has(r)){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 r of t.outputs)try{let t=rg.fromBEEF(r.beef).outputs[r.outputIndex].lockingScript,i=ip.decode(t);if(!this.topics.includes(i.topicOrService)||"SHIP"!==i.protocol)continue;void 0===e[i.domain]&&(e[i.domain]=new Set),e[i.domain].add(i.topicOrService)}catch(e){continue}return e}}let ik=e=>(e.toLowerCase().startsWith("uhrp:")&&(e=e.slice(5)),e.startsWith("//")&&(e=e.slice(2)),e),iS=e=>{if(32!==e.length)throw Error("Hash length must be 32 bytes (sha256)");return eY(e,eF("ce00","hex"))},ix=e=>{let t=e instanceof Uint8Array?e:Uint8Array.from(e),r=new D;for(let e=0;e<t.length;e+=1048576){let i=t.subarray(e,e+1048576);r.update(Array.from(i))}return iS(r.digest())},iE=e=>{let{data:t,prefix:r}=eJ(e=ik(e),void 0,2);if(32!==t.length)throw Error("Invalid length!");if("ce00"!==eK(r))throw Error("Bad prefix");return t},iN=e=>{try{return iE(e),!0}catch(e){return!1}};class iP{authFetch;baseURL;constructor(e){this.baseURL=e.storageURL,this.authFetch=new iu(e.wallet)}async getUploadInfo(e,t){let r=`${this.baseURL}/upload`,i=await this.authFetch.fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileSize:e,retentionPeriod:t})});if(!i.ok)throw Error(`Upload info request failed: HTTP ${i.status}`);let a=await i.json();if("error"===a.status)throw Error("Upload route returned an error.");return{uploadURL:a.uploadURL,requiredHeaders:a.requiredHeaders,amount:a.amount}}async uploadFile(e,t,r){let i=t.data instanceof Uint8Array?t.data:Uint8Array.from(t.data),a=await fetch(e,{method:"PUT",body:i,headers:{"Content-Type":t.type,...r}});if(!a.ok)throw Error(`File upload failed: HTTP ${a.status}`);return{published:!0,uhrpURL:ix(i)}}async publishFile(e){let{file:t,retentionPeriod:r}=e,i=t.data instanceof Uint8Array?t.data:Uint8Array.from(t.data),a=i.byteLength,{uploadURL:n,requiredHeaders:s}=await this.getUploadInfo(a,r);return await this.uploadFile(n,{data:i,type:t.type},s)}async findFile(e){let t=new URL(`${this.baseURL}/find`);t.searchParams.set("uhrpUrl",e);let r=await this.authFetch.fetch(t.toString(),{method:"GET"});if(!r.ok)throw Error(`findFile request failed: HTTP ${r.status}`);let i=await r.json();if("error"===i.status){let e=i.code??"unknown-code",t=i.description??"no-description";throw Error(`findFile returned an error: ${e} - ${t}`)}return i.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 r=await t.json();if("error"===r.status){let e=r.code??"unknown-code",t=r.description??"no-description";throw Error(`listUploads returned an error: ${e} - ${t}`)}return r.uploads}async renewFile(e,t){let r=`${this.baseURL}/renew`,i=await this.authFetch.fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({uhrpUrl:e,additionalMinutes:t})});if(!i.ok)throw Error(`renewFile request failed: HTTP ${i.status}`);let a=await i.json();if("error"===a.status){let e=a.code??"unknown-code",t=a.description??"no-description";throw Error(`renewFile returned an error: ${e} - ${t}`)}return{status:a.status,prevExpiryTime:a.prevExpiryTime,newExpiryTime:a.newExpiryTime,amount:a.amount}}}class iO{networkPreset="mainnet";lookupResolver;constructor(e){this.networkPreset=e?.networkPreset??"mainnet",this.lookupResolver=new iw({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 r=[],i=Math.floor(Date.now()/1e3);for(let e=0;e<t.outputs.length;e++){let a=rg.fromBEEF(t.outputs[e].beef),{fields:n}=t7.decode(a.outputs[t.outputs[e].outputIndex].lockingScript);new eQ(n[3]).readVarIntNum()<i||r.push(e$(n[2]))}return r}async download(e){if(!iN(e))throw Error("Invalid parameter UHRP url");let t=eK(iE(e)),r=await this.resolve(e);if(!Array.isArray(r)||0===r.length)throw Error("No one currently hosts this file!");for(let e=0;e<r.length;e++)try{let i=await fetch(r[e],{method:"GET"});if(!i.ok||i.status>=400||null==i.body)continue;let a=i.body.getReader(),n=new D,s=[],o=0;for(;;){let{done:e,value:t}=await a.read();if(e)break;n.update(Array.from(t)),s.push(t),o+=t.length}if(eK(n.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:i.headers.get("Content-Type")}}catch(e){continue}throw Error(`Unable to download content from ${e}`)}}let i_={name:"Unknown Identity",avatarURL:"XUUB8bbn9fEthk15Ge3zTQXypUShfC94vFjp65v7u5CQ8qkpxzst",identityKey:"",abbreviatedKey:"",badgeIconURL:"XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",badgeLabel:"Not verified by anyone you trust.",badgeClickURL:"https://projectbabbage.com/docs/unknown-identity"},iA={protocolID:[1,"identity"],keyID:"1",tokenAmount:1,outputIndex:0},iT={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="},iC=[2,"contact"];class iR{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 iV{wallet;cache=new iR;CONTACTS_CACHE_KEY="metanet-contacts";constructor(e){this.wallet=e??new r7}async getContacts(e,t=!1,r=1e3){if(!t){let t=this.cache.getItem(this.CONTACTS_CACHE_KEY);if(null!=t&&""!==t)try{let r=JSON.parse(t);return null!=e?r.filter(t=>t.identityKey===e):r}catch(e){console.warn("Invalid cached contacts JSON; will reload from chain",e)}}let i=[];if(null!=e){let{hmac:t}=await this.wallet.createHmac({protocolID:iC,keyID:e,counterparty:"self",data:eF(e,"utf8")});i.push(`identityKey ${eK(t)}`)}let a=await this.wallet.listOutputs({basket:"contacts",include:"locking scripts",includeCustomInstructions:!0,tags:i,limit:r});if(null==a.outputs||0===a.outputs.length)return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify([])),[];let n=[];for(let e of a.outputs)try{if(null==e.lockingScript)continue;let t=t7.decode(tJ.fromHex(e.lockingScript));if(null==e.customInstructions)continue;let r=JSON.parse(e.customInstructions).keyID,{plaintext:i}=await this.wallet.decrypt({ciphertext:t.fields[0],protocolID:iC,keyID:r,counterparty:"self"}),a=JSON.parse(e$(i));n.push(a)}catch(e){console.warn("ContactsManager: Failed to decode contact output:",e)}return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(n)),null!=e?n.filter(t=>t.identityKey===e):n}async saveContact(e,t){let r,i=this.cache.getItem(this.CONTACTS_CACHE_KEY),a=(r=null!=i&&""!==i?JSON.parse(i):await this.getContacts()).findIndex(t=>t.identityKey===e.identityKey),n={...e,metadata:t};a>=0?r[a]=n:r.push(n);let{hmac:s}=await this.wallet.createHmac({protocolID:iC,keyID:e.identityKey,counterparty:"self",data:eF(e.identityKey,"utf8")}),o=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:[`identityKey ${eK(s)}`],limit:100}),c=null,l=eW(tx(32));if(null!=o.outputs)for(let t of o.outputs)try{let[r,i]=t.outpoint.split("."),a=rg.fromBEEF(o.BEEF,r),n=t7.decode(a.outputs[Number(i)].lockingScript);if(null==t.customInstructions)continue;l=JSON.parse(t.customInstructions).keyID;let{plaintext:s}=await this.wallet.decrypt({ciphertext:n.fields[0],protocolID:iC,keyID:l,counterparty:"self"});if(JSON.parse(e$(s)).identityKey===e.identityKey){c=t;break}}catch(e){}let h={...e,metadata:t},{ciphertext:d}=await this.wallet.encrypt({plaintext:eF(JSON.stringify(h),"utf8"),protocolID:iC,keyID:l,counterparty:"self"}),u=await new t7(this.wallet).lock([d],iC,l,"self");if(null!=c){let[t,r]=String(c.outpoint).split("."),i=`${t}.${r}`,a=new t7(this.wallet),{signableTransaction:n}=await this.wallet.createAction({description:"Update Contact",inputBEEF:o.BEEF,inputs:[{outpoint:i,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 ${eK(s)}`],customInstructions:JSON.stringify({keyID:l})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}});if(null==n)throw Error("Unable to update contact");let h=a.unlock(iC,l,"self"),d=await h.sign(rg.fromBEEF(n.tx),0),{tx:f}=await this.wallet.signAction({reference:n.reference,spends:{0:{unlockingScript:d.toHex()}}});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 ${eK(s)}`],customInstructions:JSON.stringify({keyID:l})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}});if(null==t)throw Error("Failed to create contact output")}this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(r))}async removeContact(e){let t=this.cache.getItem(this.CONTACTS_CACHE_KEY);if(null!=t&&""!==t)try{let r=JSON.parse(t).filter(t=>t.identityKey!==e);this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(r))}catch(e){console.warn("Failed to update cache after contact removal:",e)}let r=[],{hmac:i}=await this.wallet.createHmac({protocolID:iC,keyID:e,counterparty:"self",data:eF(e,"utf8")});r.push(`identityKey ${eK(i)}`);let a=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:r,limit:100});if(null!=a.outputs)for(let t of a.outputs)try{let[r,i]=String(t.outpoint).split("."),n=rg.fromBEEF(a.BEEF,r),s=t7.decode(n.outputs[Number(i)].lockingScript);if(null==t.customInstructions)continue;let o=JSON.parse(t.customInstructions).keyID,{plaintext:c}=await this.wallet.decrypt({ciphertext:s.fields[0],protocolID:iC,keyID:o,counterparty:"self"});if(JSON.parse(e$(c)).identityKey===e){let e=`${r}.${i}`,t=new t7(this.wallet),{signableTransaction:n}=await this.wallet.createAction({description:"Delete Contact",inputBEEF:a.BEEF,inputs:[{outpoint:e,unlockingScriptLength:74,inputDescription:"Spend contact output to delete"}],outputs:[],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}});if(null==n)throw Error("Unable to delete contact");let s=t.unlock(iC,o,"self"),c=await s.sign(rg.fromBEEF(n.tx),0),{tx:l}=await this.wallet.signAction({reference:n.reference,spends:{0:{unlockingScript:c.toHex()}}});if(null==l)throw Error("Failed to delete contact output");return}}catch(e){}}}class iU{options;originator;authClient;wallet;contactsManager;constructor(e,t=iA,r){this.options=t,this.originator=r,this.wallet=e??new r7,this.authClient=new iu(this.wallet),this.contactsManager=new iV(this.wallet)}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 r0(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:r}=await this.wallet.proveCertificate({certificate:e,fieldsToReveal:t,verifier:new tO(1).toPublicKey().toString()}),i=await new t7(this.wallet).lock([eF(JSON.stringify({...e,keyring:r}))],this.options.protocolID,this.options.keyID,"anyone",!0,!0),{tx:a}=await this.wallet.createAction({description:"Create a new Identity Token",outputs:[{satoshis:this.options.tokenAmount,lockingScript:i.toHex(),outputDescription:"Identity Token"}],options:{randomizeOutputs:!1}});if(void 0!==a){let e=new iv(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network});return await e.broadcast(rg.fromAtomicBEEF(a))}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:r}=await this.wallet.discoverByIdentityKey(e,this.originator);return r.map(e=>iU.parseIdentity(e))}async resolveByAttributes(e,t=!0){let[r,i]=await Promise.all([t?this.contactsManager.getContacts():Promise.resolve([]),this.wallet.discoverByAttributes(e,this.originator)]),a=new Map(r.map(e=>[e.identityKey,e]));return(i?.certificates??[]).map(e=>a.get(e.subject)??iU.parseIdentity(e))}async getContacts(e,t=!1,r=1e3){return await this.contactsManager.getContacts(e,t,r)}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,r,i,a,n,{type:s,decryptedFields:o,certifierInfo:c}=e;switch(s){case iT.xCert:t=o.userName,r=o.profilePhoto,i=`X account certified by ${c.name}`,a=c.iconUrl,n="https://socialcert.net";break;case iT.discordCert:t=o.userName,r=o.profilePhoto,i=`Discord account certified by ${c.name}`,a=c.iconUrl,n="https://socialcert.net";break;case iT.emailCert:t=o.email,r="XUTZxep7BBghAJbSBwTjNfmcsDdRFs5EaGEgkESGSgjJVYgMEizu",i=`Email certified by ${c.name}`,a=c.iconUrl,n="https://socialcert.net";break;case iT.phoneCert:t=o.phoneNumber,r="XUTLxtX3ELNUwRhLwL7kWNGbdnFM8WG2eSLv84J7654oH8HaJWrU",i=`Phone certified by ${c.name}`,a=c.iconUrl,n="https://socialcert.net";break;case iT.identiCert:t=`${o.firstName} ${o.lastName}`,r=o.profilePhoto,i=`Government ID certified by ${c.name}`,a=c.iconUrl,n="https://identicert.me";break;case iT.registrant:t=o.name,r=o.icon,i=`Entity certified by ${c.name}`,a=c.iconUrl,n="https://projectbabbage.com/docs/registrant";break;case iT.coolCert:t="true"===o.cool?"Cool Person!":"Not cool!";break;case iT.anyone:t="Anyone",r="XUT4bpQ6cpBaXi1oMzZsXfpkWGbtp2JTUYAoN7PzhStFJ6wLfoeR",i="Represents the ability for anyone to access this information.",a="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",n="https://projectbabbage.com/docs/anyone-identity";break;case iT.self:t="You",r="XUT9jHGk2qace148jeCX5rDsMftkSGYKmigLwU2PLLBc7Hm63VYR",i="Represents your ability to access this information.",a="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",n="https://projectbabbage.com/docs/self-identity";break;default:t=i_.name,r=o.profilePhoto,i=i_.badgeLabel,a=i_.badgeIconURL,n=i_.badgeClickURL}return{name:t,avatarURL:r,abbreviatedKey:e.subject.length>0?`${e.subject.substring(0,10)}...`:"",identityKey:e.subject,badgeIconURL:a,badgeLabel:i,badgeClickURL:n}}}class iD{wallet;network;constructor(e=new r7){this.wallet=e}async registerDefinition(e){let t=(await this.wallet.getPublicKey({identityKey:!0})).publicKey,r=new t7(this.wallet),i=this.buildPushDropFields(e,t),a=this.mapDefinitionTypeToWalletProtocol(e.definitionType),n=await r.lock(i,a,"1","anyone",!0),{tx:s}=await this.wallet.createAction({description:`Register a new ${e.definitionType} item`,outputs:[{satoshis:1,lockingScript:n.toHex(),outputDescription:`New ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{randomizeOutputs:!1}});if(void 0===s)throw Error(`Failed to create ${e.definitionType} registration transaction!`);let o=new iv([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:this.network??=(await this.wallet.getNetwork({})).network});return await o.broadcast(rg.fromAtomicBEEF(s))}async resolve(e,t){let r=new iw,i=this.mapDefinitionTypeToServiceName(e),a=await r.query({service:i,query:t});if("output-list"!==a.type)return[];let n=[];for(let t of a.outputs)try{let r=rg.fromBEEF(t.beef).outputs[t.outputIndex].lockingScript,i=await this.parseLockingScript(e,r);n.push(i)}catch{}return n}async listOwnRegistryEntries(e){let t=this.mapDefinitionTypeToBasketName(e),{outputs:r,BEEF:i}=await this.wallet.listOutputs({basket:t,include:"entire transactions"}),a=[];for(let t of r)if(t.spendable)try{let[r,n]=t.outpoint.split("."),s=rg.fromBEEF(i).outputs[n].lockingScript,o=await this.parseLockingScript(e,s);a.push({...o,txid:r,outputIndex:Number(n),satoshis:t.satoshis,lockingScript:s.toHex(),beef:i})}catch{}return a}async revokeOwnRegistryEntry(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.wallet.getPublicKey({identityKey:!0})).publicKey;if(e.registryOperator!==t)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",i=`${e.txid}.${e.outputIndex}`,{signableTransaction:a}=await this.wallet.createAction({description:`Revoke ${e.definitionType} item: ${r}`,inputBEEF:e.beef,inputs:[{outpoint:i,unlockingScriptLength:73,inputDescription:`Revoking ${e.definitionType} token`}]});if(void 0===a)throw Error("Failed to create signable transaction.");let n=rg.fromBEEF(a.tx),s=new t7(this.wallet),o=await s.unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone","all",!1,e.satoshis,tJ.fromHex(e.lockingScript)),c=await o.sign(n,e.outputIndex),{tx:l}=await this.wallet.signAction({reference:a.reference,spends:{[e.outputIndex]:{unlockingScript:c.toHex()}},options:{acceptDelayedBroadcast:!1}});if(void 0===l)throw Error("Failed to finalize the transaction signature.");let h=new iv([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:this.network??=(await this.wallet.getNetwork({})).network});return await h.broadcast(rg.fromAtomicBEEF(l))}buildPushDropFields(e,t){let r;switch(e.definitionType){case"basket":r=[e.basketID,e.name,e.iconURL,e.description,e.documentationURL];break;case"protocol":r=[JSON.stringify(e.protocolID),e.name,e.iconURL,e.description,e.documentationURL];break;case"certificate":r=[e.type,e.name,e.iconURL,e.description,e.documentationURL,JSON.stringify(e.fields)];break;default:throw Error("Unsupported definition type")}return r.push(t),r.map(e=>eF(e))}async parseLockingScript(e,t){let r,i,a=t7.decode(t);if(0===a.fields.length)throw Error("Not a valid registry pushdrop script.");switch(e){case"basket":{if(7!==a.fields.length)throw Error("Unexpected field count for basket type.");let[e,t,n,s,o,c]=a.fields;r=e$(c),i={definitionType:"basket",basketID:e$(e),name:e$(t),iconURL:e$(n),description:e$(s),documentationURL:e$(o)};break}case"protocol":{if(7!==a.fields.length)throw Error("Unexpected field count for protocol type.");let[e,t,n,s,o,c]=a.fields;r=e$(c),i={definitionType:"protocol",protocolID:iB(e$(e)),name:e$(t),iconURL:e$(n),description:e$(s),documentationURL:e$(o)};break}case"certificate":{if(8!==a.fields.length)throw Error("Unexpected field count for certificate type.");let[e,t,n,s,o,c,l]=a.fields;r=e$(l);let h={};try{h=JSON.parse(e$(c))}catch{}i={definitionType:"certificate",type:e$(e),name:e$(t),iconURL:e$(n),description:e$(s),documentationURL:e$(o),fields:h};break}default:throw Error(`Unsupported definition type: ${e}`)}return{...i,registryOperator:r}}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 iB(e){let t=JSON.parse(e);if(!Array.isArray(t)||2!==t.length)throw Error("Invalid wallet protocol format.");let[r,i]=t;if(![0,1,2].includes(r))throw Error("Invalid security level.");if("string"!=typeof i)throw Error("Invalid protocolID");return[r,i]}class iH{wallet;context;encrypt;originator;acceptDelayedBroadcast=!1;keyLocks=new Map;constructor(e=new r7,t="kvstore default",r=!0,i,a=!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=r,this.originator=i,this.acceptDelayedBroadcast=a}async queueOperationOnKey(e){let t=this.keyLocks.get(e);null==t&&(t=[],this.keyLocks.set(e,t));let r=()=>{},i=new Promise(e=>{r=e,null!=t&&t.push(e)});return 1===t.length&&r(),await i,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})}async get(e,t){let r=await this.queueOperationOnKey(e);try{return(await this.lookupValue(e,t,5)).value}finally{this.finishOperationOnKey(e,r)}}getLockingScript(e,t){let[r,i]=e.outpoint.split("."),a=t.findTxid(r)?.tx;if(null==a)throw Error(`beef must contain txid ${r}`);return a.outputs[Number(i)].lockingScript}async lookupValue(e,t,r){let i,a=await this.getOutputs(e,r),n={value:t,outpoint:void 0,lor:a},{outputs:s}=a;if(0===s.length)return n;let o=s.slice(-1)[0];n.outpoint=o.outpoint;try{if(void 0===a.BEEF)throw Error("entire transactions listOutputs option must return valid BEEF");let e=this.getLockingScript(o,rb.fromBinary(a.BEEF)),t=t7.decode(e);if(t.fields.length<1||t.fields.length>2)throw Error("Invalid token.");i=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.`)}if(this.encrypt){let{plaintext:t}=await this.wallet.decrypt({...this.getProtocol(e),ciphertext:i});n.value=e$(t)}else n.value=e$(i);return n}getInputs(e){let t=[];for(let r=0;r<e.length;r++)t.push({outpoint:e[r].outpoint,unlockingScriptLength:74,inputDescription:"Previous key-value token"});return t}async getSpends(e,t,r,i){let a=this.getProtocol(e),n=rg.fromAtomicBEEF(i),s={};for(let e=0;e<t.length;e++){let t=r.unlock(a.protocolID,a.keyID,"self"),i=await t.sign(n,e);s[e]={unlockingScript:i.toHex()}}return s}async set(e,t){let r=await this.queueOperationOnKey(e);try{let r,i=await this.lookupValue(e,void 0,10);if(i.value===t){if(void 0===i.outpoint)throw Error("outpoint must be valid when value is valid and unchanged");return i.outpoint}let a=this.getProtocol(e),n=eF(t,"utf8");if(this.encrypt){let{ciphertext:e}=await this.wallet.encrypt({...a,plaintext:n});n=e}let s=new t7(this.wallet,this.originator),o=await s.lock([n],a.protocolID,a.keyID,"self"),{outputs:c,BEEF:l}=i.lor;try{let t=this.getInputs(c),{txid:i,signableTransaction:a}=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}});if(c.length>0&&"object"!=typeof a)throw Error("Wallet did not return a signable transaction when expected.");if(null==a)r=`${i}.0`;else{let t=await this.getSpends(e,c,s,a.tx),{txid:i}=await this.wallet.signAction({reference:a.reference,spends:t});r=`${i}.0`}}catch(t){throw Error(`There are ${c.length} outputs with tag ${e} that cannot be unlocked.`)}return r}finally{this.finishOperationOnKey(e,r)}}async remove(e){let t=await this.queueOperationOnKey(e);try{let t=[];for(;;){let{outputs:r,BEEF:i,totalOutputs:a}=await this.getOutputs(e);if(r.length>0){let n=new t7(this.wallet,this.originator);try{let a=this.getInputs(r),{signableTransaction:s}=await this.wallet.createAction({description:`Remove ${e} in ${this.context}`,inputBEEF:i,inputs:a,options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}});if("object"!=typeof s)throw Error("Wallet did not return a signable transaction when expected.");let o=await this.getSpends(e,r,n,s.tx),{txid:c}=await this.wallet.signAction({reference:s.reference,spends:o});if(void 0===c)throw Error("signAction must return a valid txid");t.push(c)}catch(t){throw Error(`There are ${a} outputs with tag ${e} that cannot be unlocked.`)}}if(r.length===a)break}return t}finally{this.finishOperationOnKey(e,t)}}}return s})());
19
+ `);return e}addComputedLeaves(){let e=e=>eK(W(eF(e,"hex").reverse()).reverse());for(let t of this.bumps)for(let r=1;r<t.path.length;r++)for(let i of t.path[r-1])if("string"==typeof i.hash&&(1&i.offset)==0){let a=t.path[r-1].find(e=>e.offset===i.offset+1),n=i.offset>>1;void 0!==a&&"string"==typeof a.hash&&t.path[r].every(e=>e.offset!==n)&&t.path[r].push({offset:n,hash:e(a.hash+i.hash)})}}}class rg{version;inputs;outputs;lockTime;metadata;merklePath;cachedHash;static addPathOrInputs(e,t,r){if("number"==typeof e.pathIndex){let t=r[e.pathIndex];if("object"!=typeof t)throw Error("Invalid merkle path index found in BEEF!");e.tx.merklePath=t}else for(let i of e.tx.inputs){if(void 0===i.sourceTXID)throw Error("Input sourceTXID is undefined");let e=t[i.sourceTXID];if("object"!=typeof e)throw Error(`Reference to unknown TXID in BEEF: ${i.sourceTXID??"undefined"}`);i.sourceTransaction=e.tx,this.addPathOrInputs(e,t,r)}}static fromBEEF(e,t){let{tx:r}=rg.fromAnyBeef(e,t);return r}static fromAtomicBEEF(e){let{tx:t,txid:r,beef:i}=rg.fromAnyBeef(e);if(r!==i.atomicTxid)if(null!=i.atomicTxid)throw Error(`Transaction with TXID ${i.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 r=rb.fromBinary(e);if(r.txs.length<1)throw Error("beef must include at least one transaction.");let i=t??r.atomicTxid??r.txs.slice(-1)[0].txid,a=r.findAtomicTransaction(i);if(null==a)if(null!=t)throw Error(`Transaction with TXID ${i} not found in BEEF data.`);else throw Error("beef does not contain transaction for atomic txid.");return{tx:a,beef:r,txid:i}}static fromEF(e){let t=new eQ(e),r=t.readUInt32LE();if("0000000000ef"!==eK(t.read(6)))throw Error("Invalid EF marker");let i=t.readVarIntNum(),a=[];for(let e=0;e<i;e++){let e=eK(t.readReverse(32)),r=t.readUInt32LE(),i=t.readVarIntNum(),n=t.read(i),s=tZ.fromBinary(n),o=t.readUInt32LE(),c=t.readUInt64LEBn().toNumber(),l=t.readVarIntNum(),h=t.read(l),d=tJ.fromBinary(h),u=new rg(void 0,[],[],void 0);u.outputs=Array(r+1).fill(null),u.outputs[r]={satoshis:c,lockingScript:d},a.push({sourceTransaction:u,sourceTXID:e,sourceOutputIndex:r,unlockingScript:s,sequence:o})}let n=t.readVarIntNum(),s=[];for(let e=0;e<n;e++){let e=t.readUInt64LEBn().toNumber(),r=t.readVarIntNum(),i=t.read(r),a=tJ.fromBinary(i);s.push({satoshis:e,lockingScript:a})}return new rg(r,a,s,t.readUInt32LE())}static parseScriptOffsets(e){let t=new eQ(e),r=[],i=[];t.pos+=4;let a=t.readVarIntNum();for(let e=0;e<a;e++){t.pos+=36;let i=t.readVarIntNum();r.push({vin:e,offset:t.pos,length:i}),t.pos+=i+4}let n=t.readVarIntNum();for(let e=0;e<n;e++){t.pos+=8;let r=t.readVarIntNum();i.push({vout:e,offset:t.pos,length:r}),t.pos+=r}return{inputs:r,outputs:i}}static fromReader(e){let t=e.readUInt32LE(),r=e.readVarIntNum(),i=[];for(let t=0;t<r;t++){let t=eK(e.readReverse(32)),r=e.readUInt32LE(),a=e.readVarIntNum(),n=e.read(a),s=tZ.fromBinary(n),o=e.readUInt32LE();i.push({sourceTXID:t,sourceOutputIndex:r,unlockingScript:s,sequence:o})}let a=e.readVarIntNum(),n=[];for(let t=0;t<a;t++){let t=e.readUInt64LEBn().toNumber(),r=e.readVarIntNum(),i=e.read(r),a=tJ.fromBinary(i);n.push({satoshis:t,lockingScript:a})}return new rg(t,i,n,e.readUInt32LE())}static fromBinary(e){let t=new eQ(e);return rg.fromReader(t)}static fromHex(e){return rg.fromBinary(eF(e,"hex"))}static fromHexEF(e){return rg.fromEF(eF(e,"hex"))}static fromHexBEEF(e,t){return rg.fromBEEF(eF(e,"hex"),t)}constructor(e=1,t=[],r=[],i=0,a=new Map,n){this.version=e,this.inputs=t,this.outputs=r,this.lockTime=i,this.metadata=a,this.merklePath=n}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.cachedHash=void 0,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 r=new t3().lock(e);if(void 0===t)return this.addOutput({lockingScript:r,change:!0});this.addOutput({lockingScript:r,satoshis:t})}updateMetadata(e){this.metadata={...this.metadata,...e}}async fee(e=re.getInstance(),t="equal"){if(this.cachedHash=void 0,"number"==typeof e){let t=e;e={computeFee:async()=>t}}let r=await e.computeFee(this),i=this.calculateChange(r);if(i<=0){this.outputs=this.outputs.filter(e=>!0!==e.change);return}this.distributeChange(i,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 r of(t-=e,this.outputs))!0!==r.change&&void 0!==r.satoshis&&(t-=r.satoshis);return t}distributeChange(e,t){let r=0,i=this.outputs.filter(e=>e.change);if("random"===t?r=this.distributeRandomChange(e,i):"equal"===t&&(r=this.distributeEqualChange(e,i)),r<e){let t=this.outputs[this.outputs.length-1];void 0!==t.satoshis?t.satoshis+=e-r:t.satoshis=e-r}}distributeRandomChange(e,t){let r=0,i=e,a=Array(t.length).fill(1);i-=t.length,r+=t.length;for(let e=0;e<t.length-1;e++){let t=this.benfordNumber(0,i);a[e]=a[e]+t,r+=t,i-=t}for(let e of this.outputs)!0===e.change&&(e.satoshis=a.shift());return r}distributeEqualChange(e,t){let r=0,i=Math.floor(e/t.length);for(let e of t)r+=i,e.satoshis=i;return r}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.cachedHash=void 0,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,r=this.inputs.length;t<r;t++)"object"==typeof this.inputs[t].unlockingScriptTemplate&&(this.inputs[t].unlockingScript=e[t])}async broadcast(e=rs()){return await e.broadcast(this)}toBinary(){let e=new eZ;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(eF(t.sourceTXID,"hex"));if(e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw Error("unlockingScript is undefined");let r=t.unlockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r),e.writeUInt32LE(t.sequence??0)}for(let t of(e.writeVarIntNum(this.outputs.length),this.outputs)){e.writeUInt64LE(t.satoshis??0);let r=t.lockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r)}return e.writeUInt32LE(this.lockTime),e.toArray()}toEF(){let e=new eZ;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(eF(t.sourceTXID,"hex").reverse()),e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw Error("unlockingScript is undefined");let r=t.unlockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r),e.writeUInt32LE(t.sequence??0),e.writeUInt64LE(t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0);let i=t.sourceTransaction.outputs[t.sourceOutputIndex].lockingScript.toBinary();e.writeVarIntNum(i.length),e.write(i)}for(let t of(e.writeVarIntNum(this.outputs.length),this.outputs)){e.writeUInt64LE(t.satoshis??0);let r=t.lockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r)}return e.writeUInt32LE(this.lockTime),e.toArray()}toHexEF(){return eK(this.toEF())}toHex(){return eK(this.toBinary())}toHexBEEF(){return eK(this.toBEEF())}toHexAtomicBEEF(){return eK(this.toAtomicBEEF())}hash(e){let t;return(null!=this.cachedHash?t=this.cachedHash:(t=W(this.toBinary()),this.cachedHash=t),"hex"===e)?eK(t):t}id(e){let t=[...this.hash()];return(t.reverse(),"hex"===e)?eK(t):t}async verify(e=rc(),t,r){let i=new Set,a=[this];for(;a.length>0;){let n=a.shift(),s=n?.id("hex")??"";if(null!=s&&""!==s&&i.has(s))continue;if("object"==typeof n?.merklePath)if("scripts only"===e){null!=s&&i.add(s);continue}else{if(await n.merklePath.verify(s,e)){i.add(s);continue}throw Error(`Invalid merkle path for transaction ${s}`)}if(void 0!==t){if(void 0===n)throw Error("Transaction is undefined");let e=rg.fromEF(n.toEF());if(delete e.outputs[0].satoshis,e.outputs[0].change=!0,await e.fee(t),n.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===n)throw Error("Transaction is undefined");for(let e=0;e<n.inputs.length;e++){let t=n.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");i.has(l)||a.push(t.sourceTransaction);let h=n.inputs.filter((t,r)=>r!==e);if(void 0===t.sourceTXID&&(t.sourceTXID=l),!new t2({sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,lockingScript:c.lockingScript,sourceSatoshis:c.satoshis??0,transactionVersion:n.version,otherInputs:h,unlockingScript:t.unlockingScript,inputSequence:t.sequence??0,inputIndex:e,outputs:n.outputs,lockTime:n.lockTime,memoryLimit:r}).validate())return!1}let c=0;for(let e of n.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;i.add(s)}return!0}toBEEF(e){let t=new eZ;t.writeUInt32LE(ru);let r=[],i=new Map,a=new Map,n=[],s=new Set,o=t=>{let c=t.id("hex");if(s.has(c))return;let l={tx:t},h=t.merklePath,d="object"==typeof h;if(d&&null!=h&&(l.pathIndex=(e=>{let t=i.get(e);if(void 0!==t)return t;let n=`${e.blockHeight}:${e.computeRoot()}`,s=a.get(n);if(void 0!==s)return r[s].combine(e),i.set(e,s),s;let o=r.length;return r.push(e),i.set(e,o),a.set(n,o),o})(h)),!d)for(let r=t.inputs.length-1;r>=0;r--){let i=t.inputs[r];if("object"==typeof i.sourceTransaction)o(i.sourceTransaction);else if(!1===e)throw Error("A required source transaction is missing!")}s.add(c),n.push(l)};for(let e of(o(this),t.writeVarIntNum(r.length),r))t.write(e.toBinary());for(let e of(t.writeVarIntNum(n.length),n))t.write(e.tx.toBinary()),"number"==typeof e.pathIndex?(t.writeUInt8(1),t.writeVarIntNum(e.pathIndex)):t.writeUInt8(0);return t.toArray()}toAtomicBEEF(e){let t=new eZ;t.writeUInt32LE(0x1010101),t.write(this.hash());let r=this.toBEEF(e);return t.write(r),t.toArray()}}function rm(e){return"success"===e.status}function ry(e){return"error"===e.status}let rw=class extends rb{knownTo={};constructor(e){if(super(),null!=e)for(let 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),r=this.clone();return r.trimKnownTxids(t),r}addKnownTxidsForParty(e,t){this.isParty(e)||this.addParty(e);let r=this.knownTo[e];for(let e of t)r[e]=!0,this.mergeTxidOnly(e)}mergeBeefFromParty(e,t){let r=Array.isArray(t)?rb.fromBinary(t):t,i=r.getValidTxids();this.mergeBeef(r),this.addKnownTxidsForParty(e,i)}};class rI{network;URL;httpClient;constructor(e="main",t=ri()){this.network=e,this.URL=`https://api.whatsonchain.com/v1/bsv/${e}/tx/raw`,this.httpClient=t}async broadcast(e){let t=e.toHex();try{let e=await this.httpClient.request(this.URL,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/plain"},data:{txhex:t}});if(!e.ok)return{status:"error",code:e.status.toString()??"ERR_UNKNOWN",description:e.data??"Unknown error"};{let t=e.data;return{status:"success",txid:t,message:"broadcast successful"}}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class rv{https;constructor(e){this.https=e}async request(e,t){return await new Promise((r,i)=>{let a=this.https.request(e,t,e=>{let t="";e.on("data",e=>{t+=e}),e.on("end",()=>{let i=e.statusCode>=200&&e.statusCode<=299,a=e.headers["content-type"],n=""!==t&&"string"==typeof a&&a.startsWith("application/json")?JSON.parse(t):t;r({status:e.statusCode,statusText:e.statusMessage,ok:i,data:n})})});a.on("error",e=>{i(e)}),null!==t.data&&void 0!==t.data&&a.write(Buffer.from(t.data)),a.end()})}}class rk{fetch;constructor(e){this.fetch=e}async request(e,t){let r={method:t.method,headers:t.headers,body:t.data},i=await this.fetch(e,r),a=await i.text();return{ok:i.ok,status:i.status,statusText:i.statusText,data:a}}}function rS(){let e={async request(){throw Error("No method available to perform HTTP request")}};if("undefined"!=typeof window&&"function"==typeof window.fetch)return new rk(window.fetch.bind(window));if("undefined"==typeof require)return e;try{let e=require("https");return new rv(e)}catch(t){return e}}class rx{URL;httpClient;constructor(e,t=rS()){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 r=await this.httpClient.request(this.URL,t);if(!r.ok)return{status:"error",code:r.status.toString()??"ERR_UNKNOWN",description:r.data??"Unknown error"};{let t=e.id("hex");return{status:"success",txid:t,message:"broadcast successful"}}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class rE{baseUrl;httpClient;apiKey;constructor(e,t={}){let{httpClient:r,apiKey:i}=t;this.baseUrl=e,this.httpClient=r??ri(),this.apiKey=i??""}async isValidRootForHeight(e,t){let r={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`,r);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",rP=(e,t,r)=>{let i="object"!=typeof r;if(i){let e=new td,t=new tO(1),i=e.g.mul(t);r=new tv(i.x,i.y)}let a=tx(32),n=eW(a),s=`2-message signing-${n}`,o=t.deriveChild(r,s).sign(e).toDER(),c=t.toPublicKey().encode(!0);return[...eF(rN,"hex"),...c,...i?[0]:r.encode(!0),...a,...o]},rO=(e,t,r)=>{let i=new eQ(t),a=eK(i.read(4));if(a!==rN)throw Error(`Message version mismatch: Expected ${rN}, received ${a}`);let n=tv.fromString(eK(i.read(33))),[s]=i.read(1);if(0===s)r=new tO(1);else{let e=eK([s,...i.read(32)]);if("object"!=typeof r)throw Error(`This signature can only be verified with knowledge of a specific private key. The associated public key is: ${e}`);let t=r.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=eW(i.read(32)),c=eK(i.read(i.bin.length-i.pos)),l=tu.fromDER(c,"hex"),h=`2-message signing-${o}`;return n.deriveChild(r,h).verify(e,l)},r_="42421033",rA=(e,t,r)=>{let i=tx(32),a=eW(i),n=`2-message encryption-${a}`,s=t.deriveChild(r,n),o=r.deriveChild(t,n),c=new tz(s.deriveSharedSecret(o).encode(!0).slice(1)).encrypt(e),l=t.toPublicKey().encode(!0);return[...eF(r_,"hex"),...l,...r.encode(!0),...i,...c]},rT=(e,t)=>{let r=new eQ(e),i=eK(r.read(4));if(i!==r_)throw Error(`Message version mismatch: Expected ${r_}, received ${i}`);let a=tv.fromString(eK(r.read(33))),n=eK(r.read(33)),s=t.toPublicKey().encode(!0,"hex");if(n!==s)throw Error(`The encrypted message expects a recipient public key of ${n}, but the provided key is ${s}`);let o=eW(r.read(32)),c=r.read(r.bin.length-r.pos),l=`2-message encryption-${o}`,h=a.deriveChild(t,l),d=t.deriveChild(a,l);return new tz(h.deriveSharedSecret(d).encode(!0).slice(1)).decrypt(c)},rC="Bitcoin Signed Message:\n",rR=e=>{let t=new eZ;return t.writeVarIntNum(rC.length),t.write(eF(rC,"utf8")),t.writeVarIntNum(e.length),t.write(e),W(t.toArray())},rV=(e,t,r="base64")=>{let i=rR(e),a=tw(new p(i),t,!0);if("raw"===r)return a;let n=new p(i),s=a.CalculateRecoveryFactor(t.toPublicKey(),n);return a.toCompact(s,!0,"base64")},rU=(e,t,r)=>tI(new p(rR(e)),t,r);class rD{versionBytesNum;depth;parentFingerPrint;childIndex;chainCode;privKey;pubKey;constants={pubKey:0x488b21e,privKey:0x488ade4};constructor(e,t,r,i,a,n,s){this.versionBytesNum=e,this.depth=t,this.parentFingerPrint=r,this.childIndex=i,this.chainCode=a,this.privKey=n,this.pubKey=s}fromRandom(){return this.versionBytesNum=this.constants.privKey,this.depth=0,this.parentFingerPrint=[0,0,0,0],this.childIndex=0,this.chainCode=tx(32),this.privKey=tO.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=eJ(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=X(eF("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 tO(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 eQ(e);this.versionBytesNum=t.readUInt32BE(),this.depth=t.readUInt8(),this.parentFingerPrint=t.read(4),this.childIndex=t.readUInt32BE(),this.chainCode=t.read(32);let r=t.read(33),i=this.versionBytesNum===this.constants.privKey,a=this.versionBytesNum===this.constants.pubKey;if(i&&0===r[0])this.privKey=new tO(r.slice(1,33)),this.pubKey=this.privKey.toPublicKey();else if(a&&(2===r[0]||3===r[0]))this.pubKey=tv.fromString(eK(r));else throw Error("Invalid key");return this}toString(){return eY(this.toBinary(),[])}derive(e){if("m"===e)return this;let t=e.split("/"),r=this;for(let[e,i]of t.entries()){if(0===e){if("m"!==i)throw Error("invalid path");continue}if(parseInt(i.replace("'",""),10).toString()!==i.replace("'",""))throw Error("invalid path");let t=i.length>1&&"'"===i[i.length-1],a=0x7fffffff&parseInt(t?i.slice(0,i.length-1):i,10);t&&(a+=0x80000000),r=r.deriveChild(a)}return r}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 r=[...t],i=(0x80000000&e)!=0,a=this.versionBytesNum===this.constants.privKey;if(i&&(null===this.privKey||void 0===this.privKey||!a))throw Error("Cannot do private key derivation without private key");let n=null;if(null!==this.privKey&&void 0!==this.privKey){let e=null;e=i?[0,...this.privKey.toArray("be",32),...r]:[...this.pubKey.encode(!0),...r];let t=X(this.chainCode,e),a=new p(t.slice(0,32)),s=t.slice(32,64),o=a.add(this.privKey).mod(new td().n);(n=new rD).chainCode=s,n.privKey=new tO(o.toArray()),n.pubKey=n.privKey.toPublicKey()}else{let e=[...this.pubKey.encode(!0),...r],t=X(this.chainCode,e),i=new p(t.slice(0,32)),a=t.slice(32,64),s=new td().g.mul(i),o=this.pubKey,c=s.add(o),l=new tv(c.x,c.y);(n=new rD).chainCode=a,n.pubKey=l}n.childIndex=e;let s=j(this.pubKey.encode(!0));return n.parentFingerPrint=s.slice(0,4),n.versionBytesNum=this.versionBytesNum,n.depth=this.depth+1,n}toPublic(){let e=new rD(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 eZ().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 eZ().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 rB={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 rH{mnemonic;seed;Wordlist;constructor(e,t,r=rB){this.mnemonic=e??"",this.seed=t??[],this.Wordlist=r}toBinary(){let e=new eZ;if(""!==this.mnemonic){let t=eF(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 eQ(e),r=t.readVarIntNum();r>0&&(this.mnemonic=ez(t.read(r),"utf8"));let i=t.readVarIntNum();return i>0&&(this.seed=t.read(i)),this}fromRandom(e){if((null==e||isNaN(e)||0===e)&&(e=128),e%32!=0)throw Error("bits must be multiple of 32");if(e<128)throw Error("bits must be at least 128");let t=tx(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=$(e),r="",i=8*e.length;for(let t=0;t<e.length;t++)r+=("00000000"+e[t].toString(2)).slice(-8);let a=t[0].toString(2);if((r+=a=("00000000"+a).slice(-8).slice(0,i/32)).length%11!=0)throw Error("internal error - entropy not an even multiple of 11 bits - "+r.length.toString());let n="";for(let e=0;e<r.length/11;e++){""!==n&&(n+=this.Wordlist.space);let t=parseInt(r.slice(11*e,(e+1)*11),2);n+=this.Wordlist.value[t]}return this.mnemonic=n,this}check(){let e=this.mnemonic.split(this.Wordlist.space),t="";for(let r=0;r<e.length;r++){let i=this.Wordlist.value.indexOf(e[r]);if(i<0)return!1;t+=("00000000000"+i.toString(2)).slice(-11)}if(t.length%11!=0)throw Error("internal error - entropy not an even multiple of 11 bits - "+t.length.toString());let r=t.length/33,i=t.slice(-r),a=t.slice(0,t.length-r),n=[];for(let e=0;e<a.length/8;e++)n.push(parseInt(t.slice(8*e,(e+1)*8),2));let s=$(n.slice(0,a.length/8))[0].toString(2);return(s=("00000000"+s).slice(-8).slice(0,r))===i}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 r=eF(t,"utf8"),i=[...eF("mnemonic","utf8"),...eF(e,"utf8")];return this.seed=eH(r,i,2048,64,"sha512"),this}isValid(e=""){let t;try{this.mnemonic2Seed(e),t=!0}catch{t=!1}return t}static isValid(e,t=""){return new rH(e).isValid(t)}}function rL(e){let t,r,i,a;0===this._tables[0][0][0]&&this._precompute();let n=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=[r=e.slice(0),i=[]],a=o;a<4*o+28;a++)t=r[a-1],(a%o==0||8===o&&a%o==4)&&(t=n[t>>>24]<<24^n[t>>16&255]<<16^n[t>>8&255]<<8^n[255&t],a%o==0&&(t=t<<8^t>>>24^c<<24,c=c<<1^(c>>7)*283)),r[a]=r[a-o]^t;for(let e=0;a>0;e++,a--)t=r[(3&e)!=0?a:a-4],a<=4||e<4?i[e]=t:i[e]=s[0][n[t>>>24]]^s[1][n[t>>16&255]]^s[2][n[t>>8&255]]^s[3][n[255&t]]}rL.prototype={encrypt:function(e){return this._crypt(e,0)},decrypt:function(e){return this._crypt(e,1)},_tables:[[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)]],_precompute:function(){let e,t,r,i,a,n,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=r=0;0===h[t];t^=0!==i?i:1,r=0!==f[r]?f[r]:1)for(e=0,n=(n=r^r<<1^r<<2^r<<3^r<<4)>>8^255&n^99,h[t]=n,d[n]=t,o=0x1010101*u[a=u[i=u[t]]]^65537*a^257*i^0x1010100*t,s=257*u[n]^0x1010100*n;e<4;e++)c[e][t]=s=s<<24^s>>>8,l[e][n]=o=o<<24^o>>>8},_crypt:function(e,t){let r,i,a,n;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],b=p[0],g=p[1],m=p[2],y=p[3],w=p[4];for(n=0;n<d;n++)r=b[o>>>24]^g[c>>16&255]^m[l>>8&255]^y[255&h]^s[u],i=b[c>>>24]^g[l>>16&255]^m[h>>8&255]^y[255&o]^s[u+1],a=b[l>>>24]^g[h>>16&255]^m[o>>8&255]^y[255&c]^s[u+2],h=b[h>>>24]^g[o>>16&255]^m[c>>8&255]^y[255&l]^s[u+3],u+=4,o=r,c=i,l=a;for(n=0;n<4;n++)f[1===t?3&-n:n]=w[o>>>24]<<24^w[c>>16&255]<<16^w[l>>8&255]<<8^w[255&h]^s[u++],r=o,o=c,c=l,l=h,h=r;return f}};class rK{static encrypt(e,t){let r=rK.buf2Words(t),i=rK.buf2Words(e),a=new rL(r).encrypt(i);return rK.words2Buf(a)}static decrypt(e,t){let r=rK.buf2Words(e),i=new rL(rK.buf2Words(t)).decrypt(r);return rK.words2Buf(i)}static buf2Words(e){if(e.length%4!=0)throw Error("buf length must be a multiple of 4");let t=[];for(let r=0;r<e.length/4;r++){let i=0x1000000*e[4*r]+(e[4*r+1]<<16|e[4*r+2]<<8|e[4*r+3]);t.push(i)}return t}static words2Buf(e){let t=Array(4*e.length);for(let r=0;r<e.length;r++){let i=e[r];t[4*r]=i>>>24&255,t[4*r+1]=i>>>16&255,t[4*r+2]=i>>>8&255,t[4*r+3]=255&i}return t}}class rF{static buf2BlocksBuf(e,t){let r=t/8,i=[];for(let a=0;a<=e.length/r;a++){let n=e.slice(a*r,a*r+r);n.length<t&&(n=rF.pkcs7Pad(n,t)),i.push(n)}return i}static blockBufs2Buf(e){let t=e[e.length-1];return t=rF.pkcs7Unpad(t),e[e.length-1]=t,e.flat()}static encrypt(e,t,r,i){let a=8*t.length,n=rF.buf2BlocksBuf(e,a);return rF.encryptBlocks(n,t,r,i).flat()}static decrypt(e,t,r,i){let a=t.length,n=[];for(let t=0;t<e.length/a;t++)n.push(e.slice(t*a,t*a+a));let s=rF.decryptBlocks(n,t,r,i);return rF.blockBufs2Buf(s)}static encryptBlock(e,t,r,i){let a=rF.xorBufs(e,t);return r.encrypt(a,i)}static decryptBlock(e,t,r,i){let a=r.decrypt(e,i);return rF.xorBufs(a,t)}static encryptBlocks(e,t,r,i){let a=[];for(let n=0;n<e.length;n++){let s=e[n],o=rF.encryptBlock(s,t,r,i);a.push(o),t=o}return a}static decryptBlocks(e,t,r,i){let a=[];for(let n=0;n<e.length;n++){let s=e[n],o=rF.decryptBlock(s,t,r,i);a.push(o),t=s}return a}static pkcs7Pad(e,t){let r=t/8-e.length,i=Array(r);return i.fill(r),[...e,...i]}static pkcs7Unpad(e){let t=e[e.length-1],r=e.slice(e.length-t,e.length),i=Array(t);if(i.fill(t),eK(r)!==eK(i))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 r=Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}}class rq{static encrypt(e,t,r,i=!0){r=r??tx(16);let a=rF.encrypt(e,r,rK,t);return i?[...r,...a]:[...a]}static decrypt(e,t,r){if(null!=r)return rF.decrypt(e,r,rK,t);{r=e.slice(0,16);let i=e.slice(16);return rF.decrypt(i,r,rK,t)}}}class rM{static ivkEkM(e,t){let r=t.mul(e),i=z(new tv(r.x,r.y).encode(!0));return{iv:i.slice(0,16),kE:i.slice(16,32),kM:i.slice(32,64)}}static electrumEncrypt(e,t,r,i=!1){let a,n=null;null==r&&(r=tO.fromRandom()),i||(n=r.toPublicKey().encode(!0));let{iv:s,kE:o,kM:c}=rM.ivkEkM(r,t),l=rq.encrypt(e,o,s,!1),h=eF("BIE1","utf8"),d=G(c,a=null!=n&&n.length>0?[...h,...n,...l]:[...h,...l]);return[...a,...d]}static electrumDecrypt(e,t,r){if("BIE1"!==ez(e.slice(0,4),"utf8"))throw Error("Invalid Magic");let i=4,a=null;if(e.length-i-32>=33){let t=e[i];2===t||3===t?(a=e.slice(i,i+33),i+=33):4===t&&(a=e.slice(i,i+65),i+=65)}if(null!==a)null==r&&(r=tv.fromString(eK(a)));else if(null==r)throw Error("Sender public key is required");let{iv:n,kE:s,kM:o}=rM.ivkEkM(t,r),c=e.slice(i,e.length-32),l=e.slice(e.length-32,e.length),h=G(o,e.slice(0,e.length-32));if(eK(l)!==eK(h))throw Error("Invalid checksum");return rq.decrypt(c,s,n)}static bitcoreEncrypt(e,t,r,i){null==r&&(r=tO.fromRandom()),null==i&&(i=tx(16));let a=r,n=r.toPublicKey().encode(!0),s=z(t.mul(a).getX().toArray("be",32)),o=s.slice(0,32),c=s.slice(32,64),l=rq.encrypt(e,o,i),h=G(c,[...l]);return[...n,...l,...h]}static bitcoreDecrypt(e,t){let r=tv.fromString(eK(e.slice(0,33))).mul(t);if(r.eq(new th(0,0)))throw Error("P equals 0");let i=z(r.getX().toArray("be",32)),a=i.slice(0,32),n=i.slice(32,64),s=e.slice(33,e.length-32),o=e.slice(e.length-32,e.length),c=G(n,s);if(eK(o)!==eK(c))throw Error("Invalid checksum");return[...rq.decrypt(s,a)]}}function r$(e,t){let r=new rg(0,[],[],0);return r.outputs=Array(e.vout+1).fill(null),r.outputs[e.vout]={satoshis:e.satoshis,lockingScript:tJ.fromHex(e.script)},{sourceTransaction:r,sourceTXID:e.txid,sourceOutputIndex:e.vout,unlockingScriptTemplate:t,sequence:0xffffffff}}class rz{static generate(e,t){let r=this.withDefaultOptions(t);return rW(e,this.getCounter(r.timestamp,r.period),r)}static validate(e,t,r){let i=this.withDefaultValidateOptions(r);if((t=t.trim()).length!==i.digits)return!1;let a=this.getCounter(i.timestamp,i.period),n=[a];for(let e=1;e<=i.skew;e++)n.push(a+e),n.push(a-e);for(let r of n)if(t===rW(e,r,i))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 rW(e,t,r){let i=(function(e,t,r){switch(r){case"SHA-1":return new K(e).update(t);case"SHA-256":return new L(e).update(t);case"SHA-512":return new F(e).update(t);default:throw Error("unsupported HMAC algorithm")}})(e,new p(t).toArray("be",8),r.algorithm).digest(),a=15&i[i.length-1];return(0x7fffffff&new p(i.slice(a,a+4)).toNumber()).toString().slice(-r.digits)}!function(e){e[e.Silent=0]="Silent",e[e.App=1]="App",e[e.Counterparty=2]="Counterparty"}(r||(r={}));class rj{cacheSharedSecret;retrieveCachedSharedSecret;rootKey;identityKey;anyone;constructor(e,t,r){this.cacheSharedSecret=t,this.retrieveCachedSharedSecret=r,this.anyone=new tO(1).toPublicKey(),"anyone"===e?this.rootKey=new tO(1):this.rootKey=e,this.identityKey=this.rootKey.toPublicKey().toString()}derivePublicKey(e,t,r,i=!1){return(r=this.normalizeCounterparty(r),i)?this.rootKey.deriveChild(r,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret).toPublicKey():r.deriveChild(this.rootKey,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}derivePrivateKey(e,t,r){return r=this.normalizeCounterparty(r),this.rootKey.deriveChild(r,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}deriveSymmetricKey(e,t,r){r="anyone"===r?this.anyone:this.normalizeCounterparty(r);let i=this.derivePublicKey(e,t,r),a=this.derivePrivateKey(e,t,r);return new tz(a.deriveSharedSecret(i)?.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,r){e=this.normalizeCounterparty(e);let i=this.rootKey.deriveSharedSecret(e),a=eF(this.computeInvoiceNumber(t,r),"utf8");return G(i.encode(!0),a)}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 tO(1).toPublicKey():"string"==typeof e?tv.fromString(e):e}computeInvoiceNumber(e,t){let r=e[0];if(!Number.isInteger(r)||r<0||r>2)throw Error("Protocol security level must be 0, 1, or 2");let i=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(i.length>400)if(i.startsWith("specific linkage revelation ")){if(i.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(i.length<5)throw Error("Protocol names must be 5 characters or more");if(i.includes(" "))throw Error('Protocol names cannot contain multiple consecutive spaces (" ")');if(!/^[a-z0-9 ]+$/g.test(i))throw Error("Protocol names can only contain letters, numbers and spaces");if(i.endsWith(" protocol"))throw Error('No need to end your protocol name with " protocol"');return`${r}-${i}-${t}`}}class rG{keyDeriver;cache;maxCacheSize;rootKey;identityKey;constructor(e,t){"anyone"===e?this.rootKey=new tO(1):this.rootKey=e,this.keyDeriver=new rj(this.rootKey,(e,t,r)=>{this.cacheSet(`${e.toString()}-${t.toString()}`,r)},(e,t)=>this.cacheGet(`${e.toString()}-${t.toString()}`)),this.identityKey=this.rootKey.toPublicKey().toString(),this.cache=new Map;let r=t?.maxCacheSize;this.maxCacheSize=null!=r&&!isNaN(r)&&r>0?r:1e3}derivePublicKey(e,t,r,i=!1){let a=this.generateCacheKey("derivePublicKey",e,t,r,i);if(this.cache.has(a)){let e=this.cacheGet(a);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.derivePublicKey(e,t,r,i);return this.cacheSet(a,n),n}}derivePrivateKey(e,t,r){let i=this.generateCacheKey("derivePrivateKey",e,t,r);if(this.cache.has(i)){let e=this.cacheGet(i);if(void 0===e)throw Error("Cached value is undefined");return e}{let a=this.keyDeriver.derivePrivateKey(e,t,r);return this.cacheSet(i,a),a}}deriveSymmetricKey(e,t,r){let i=this.generateCacheKey("deriveSymmetricKey",e,t,r);if(this.cache.has(i)){let e=this.cacheGet(i);if(void 0===e)throw Error("Cached value is undefined");return e}{let a=this.keyDeriver.deriveSymmetricKey(e,t,r);return this.cacheSet(i,a),a}}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 r=this.keyDeriver.revealCounterpartySecret(e);return this.cacheSet(t,r),r}}revealSpecificSecret(e,t,r){let i=this.generateCacheKey("revealSpecificSecret",e,t,r);if(this.cache.has(i)){let e=this.cacheGet(i);if(void 0===e)throw Error("Cached value is undefined");return e}{let a=this.keyDeriver.revealSpecificSecret(e,t,r);return this.cacheSet(i,a),a}}generateCacheKey(e,...t){let r=t.map(e=>this.serializeArgument(e)).join("|");return`${e}|${r}`}serializeArgument(e){return e instanceof tv||e instanceof tO?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)}}let rX=class{keyDeriver;constructor(e){"string"!=typeof e.identityKey&&(e=new rG(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 r=this.keyDeriver.revealCounterpartySecret(e.counterparty),i=new tj().generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),tv.fromString(e.counterparty),th.fromDER(r)),a=[...i.R.encode(!0),...i.SPrime.encode(!0),...i.z.toArray()],n=new Date().toISOString(),{ciphertext:s}=await this.encrypt({plaintext:r,protocolID:[2,"counterparty linkage revelation"],keyID:n,counterparty:e.verifier}),{ciphertext:o}=await this.encrypt({plaintext:a,protocolID:[2,"counterparty linkage revelation"],keyID:n,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,revelationTime:n,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 r=this.keyDeriver.revealSpecificSecret(e.counterparty,e.protocolID,e.keyID),{ciphertext:i}=await this.encrypt({plaintext:r,protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier}),{ciphertext:a}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,protocolID:e.protocolID,keyID:e.keyID,encryptedLinkage:i,encryptedLinkageProof:a,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:G(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=G(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data).toString()===e.hmac.toString();if(!t){let e=Error("HMAC is not valid");throw e.code="ERR_INVALID_HMAC",e}return{valid:t}}async createSignature(e){if(null==e.hashToDirectlySign&&null==e.data)throw Error("args.data or args.hashToDirectlySign must be valid");let t=e.hashToDirectlySign??$(e.data??[]),r=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePrivateKey(e.protocolID,e.keyID,e.counterparty??"anyone");return{signature:tw(new p(t),r,!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??$(e.data??[]),r=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf),i=tI(new p(t),tu.fromDER(e.signature),r);if(!i){let e=Error("Signature is not valid");throw e.code="ERR_INVALID_SIGNATURE",e}return{valid:i}}};class rY{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 rJ extends Error{code;isError=!0;constructor(e,t=1,r){super(e),this.code=t,this.name=this.constructor.name,null!=r&&""!==r?this.stack=r:Error.captureStackTrace(this,this.constructor)}}!function(e){e[e.unknownError=1]="unknownError",e[e.unsupportedAction=2]="unsupportedAction",e[e.invalidHmac=3]="invalidHmac",e[e.invalidSignature=4]="invalidSignature",e[e.reviewActions=5]="reviewActions"}(i||(i={}));let rZ=rJ;class rQ{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((r,i)=>{let a=eW(tx(12)),n=e=>{"CWI"===e.data.type&&e.isTrusted&&e.data.id===a&&!0!==e.data.isInvocation&&("function"==typeof window.removeEventListener&&window.removeEventListener("message",n),"error"===e.data.status?i(new rJ(e.data.description,e.data.code)):r(e.data.result))};window.addEventListener("message",n),window.parent.postMessage({type:"CWI",isInvocation:!0,id:a,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 r0{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(e,t,r,i,a,n,s){this.type=e,this.serialNumber=t,this.subject=r,this.certifier=i,this.revocationOutpoint=a,this.fields=n,this.signature=s}toBinary(e=!0){let t=new eZ,r=eF(this.type,"base64");t.write(r);let i=eF(this.serialNumber,"base64");t.write(i);let a=eF(this.subject,"hex");t.write(a);let n=eF(this.certifier,"hex");t.write(n);let[s,o]=this.revocationOutpoint.split("."),c=eF(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 r=this.fields[e],i=eF(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let a=eF(r,"utf8");t.writeVarIntNum(a.length),t.write(a)}if(e&&(this.signature??"").length>0){let e=eF(this.signature,"hex");t.write(e)}return t.toArray()}static fromBinary(e){let t,r=new eQ(e),i=eW(r.read(32)),a=eW(r.read(32)),n=eK(r.read(33)),s=eK(r.read(33)),o=eK(r.read(32)),c=r.readVarIntNum(),l=`${o}.${c}`,h=r.readVarIntNum(),d={};for(let e=0;e<h;e++){let e=r.readVarIntNum(),t=e$(r.read(e)),i=r.readVarIntNum(),a=e$(r.read(i));d[t]=a}if(!r.eof()){let e=r.read();t=tu.fromDER(e).toString("hex")}return new r0(i,a,n,s,l,d,t)}async verify(){let e=new rX("anyone"),t=this.toBinary(!1),r=this.signature??"",{valid:i}=await e.verifySignature({signature:eF(r,"hex"),data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`,counterparty:this.certifier});return i}async sign(e){if(null!=this.signature&&this.signature.length>0)throw Error(`Certificate has already been signed! Signature present: ${this.signature}`);this.certifier=(await e.getPublicKey({identityKey:!0})).publicKey;let t=this.toBinary(!1),{signature:r}=await e.createSignature({data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`});this.signature=eK(r)}static getCertificateFieldEncryptionDetails(e,t){return{protocolID:[2,"certificate field encryption"],keyID:t?`${t} ${e}`:e}}}!function(e){e[e.createAction=1]="createAction",e[e.signAction=2]="signAction",e[e.abortAction=3]="abortAction",e[e.listActions=4]="listActions",e[e.internalizeAction=5]="internalizeAction",e[e.listOutputs=6]="listOutputs",e[e.relinquishOutput=7]="relinquishOutput",e[e.getPublicKey=8]="getPublicKey",e[e.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",e[e.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",e[e.encrypt=11]="encrypt",e[e.decrypt=12]="decrypt",e[e.createHmac=13]="createHmac",e[e.verifyHmac=14]="verifyHmac",e[e.createSignature=15]="createSignature",e[e.verifySignature=16]="verifySignature",e[e.acquireCertificate=17]="acquireCertificate",e[e.listCertificates=18]="listCertificates",e[e.proveCertificate=19]="proveCertificate",e[e.relinquishCertificate=20]="relinquishCertificate",e[e.discoverByIdentityKey=21]="discoverByIdentityKey",e[e.discoverByAttributes=22]="discoverByAttributes",e[e.isAuthenticated=23]="isAuthenticated",e[e.waitForAuthentication=24]="waitForAuthentication",e[e.getHeight=25]="getHeight",e[e.getHeaderForHeight=26]="getHeaderForHeight",e[e.getNetwork=27]="getNetwork",e[e.getVersion=28]="getVersion"}(a||(a={}));let r1=a;class r2{wire;constructor(e){this.wire=e}async transmit(e,t="",r=[]){let i=new eZ;i.writeUInt8(r1[e]);let a=eF(t,"utf8");i.writeUInt8(a.length),i.write(a),r.length>0&&i.write(r);let n=i.toArray(),s=new eQ(await this.wire.transmitToWallet(n)),o=s.readUInt8();if(0===o)return s.read();{let e=s.readVarIntNum(),t=e$(s.read(e)),r=s.readVarIntNum();throw new rJ(t,o,e$(s.read(r)))}}async createAction(e,t){let r=new eZ,i=eF(e.description,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=e.inputBEEF?(r.writeVarIntNum(e.inputBEEF.length),r.write(e.inputBEEF)):r.writeVarIntNum(-1),null!=e.inputs)for(let t of(r.writeVarIntNum(e.inputs.length),e.inputs)){if(r.write(this.encodeOutpoint(t.outpoint)),null!=t.unlockingScript&&""!==t.unlockingScript){let e=eF(t.unlockingScript,"hex");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1),r.writeVarIntNum(t.unlockingScriptLength??0);let e=eF(t.inputDescription,"utf8");r.writeVarIntNum(e.length),r.write(e),"number"==typeof t.sequenceNumber?r.writeVarIntNum(t.sequenceNumber):r.writeVarIntNum(-1)}else r.writeVarIntNum(-1);if(null!=e.outputs)for(let t of(r.writeVarIntNum(e.outputs.length),e.outputs)){let e=eF(t.lockingScript,"hex");r.writeVarIntNum(e.length),r.write(e),r.writeVarIntNum(t.satoshis);let i=eF(t.outputDescription,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=t.basket&&""!==t.basket){let e=eF(t.basket,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=t.customInstructions&&""!==t.customInstructions){let e=eF(t.customInstructions,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=t.tags)for(let e of(r.writeVarIntNum(t.tags.length),t.tags)){let t=eF(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}else r.writeVarIntNum(-1)}else r.writeVarIntNum(-1);if("number"==typeof e.lockTime?r.writeVarIntNum(e.lockTime):r.writeVarIntNum(-1),"number"==typeof e.version?r.writeVarIntNum(e.version):r.writeVarIntNum(-1),null!=e.labels)for(let t of(r.writeVarIntNum(e.labels.length),e.labels)){let e=eF(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=e.options){if(r.writeInt8(1),"boolean"==typeof e.options.signAndProcess?r.writeInt8(+!!e.options.signAndProcess):r.writeInt8(-1),"boolean"==typeof e.options.acceptDelayedBroadcast?r.writeInt8(+!!e.options.acceptDelayedBroadcast):r.writeInt8(-1),"known"===e.options.trustSelf?r.writeInt8(1):r.writeInt8(-1),null!=e.options.knownTxids)for(let t of(r.writeVarIntNum(e.options.knownTxids.length),e.options.knownTxids)){let e=eF(t,"hex");r.write(e)}else r.writeVarIntNum(-1);if("boolean"==typeof e.options.returnTXIDOnly?r.writeInt8(+!!e.options.returnTXIDOnly):r.writeInt8(-1),"boolean"==typeof e.options.noSend?r.writeInt8(+!!e.options.noSend):r.writeInt8(-1),null!=e.options.noSendChange)for(let t of(r.writeVarIntNum(e.options.noSendChange.length),e.options.noSendChange))r.write(this.encodeOutpoint(t));else r.writeVarIntNum(-1);if(null!=e.options.sendWith)for(let t of(r.writeVarIntNum(e.options.sendWith.length),e.options.sendWith)){let e=eF(t,"hex");r.write(e)}else r.writeVarIntNum(-1);"boolean"==typeof e.options.randomizeOutputs?r.writeInt8(+!!e.options.randomizeOutputs):r.writeInt8(-1)}else r.writeInt8(0);let a=new eQ(await this.transmit("createAction",t,r.toArray())),n={};if(1===a.readInt8()&&(n.txid=eK(a.read(32))),1===a.readInt8()){let e=a.readVarIntNum();n.tx=a.read(e)}let s=a.readVarIntNum();if(s>=0){n.noSendChange=[];for(let e=0;e<s;e++){let e=this.readOutpoint(a);n.noSendChange.push(e)}}let o=a.readVarIntNum();if(o>=0){n.sendWithResults=[];for(let e=0;e<o;e++){let e=eK(a.read(32)),t=a.readInt8(),r="unproven";1===t?r="unproven":2===t?r="sending":3===t&&(r="failed"),n.sendWithResults.push({txid:e,status:r})}}if(1===a.readInt8()){let e=a.readVarIntNum(),t=a.read(e),r=a.readVarIntNum();n.signableTransaction={tx:t,reference:eW(a.read(r))}}return n}async signAction(e,t){let r=new eZ,i=Object.keys(e.spends);for(let t of(r.writeVarIntNum(i.length),i)){r.writeVarIntNum(Number(t));let i=e.spends[Number(t)],a=eF(i.unlockingScript,"hex");r.writeVarIntNum(a.length),r.write(a),"number"==typeof i.sequenceNumber?r.writeVarIntNum(i.sequenceNumber):r.writeVarIntNum(-1)}let a=eF(e.reference,"base64");if(r.writeVarIntNum(a.length),r.write(a),null!=e.options)if(r.writeInt8(1),"boolean"==typeof e.options.acceptDelayedBroadcast?r.writeInt8(+!!e.options.acceptDelayedBroadcast):r.writeInt8(-1),"boolean"==typeof e.options.returnTXIDOnly?r.writeInt8(+!!e.options.returnTXIDOnly):r.writeInt8(-1),"boolean"==typeof e.options.noSend?r.writeInt8(+!!e.options.noSend):r.writeInt8(-1),null!=e.options.sendWith)for(let t of(r.writeVarIntNum(e.options.sendWith.length),e.options.sendWith)){let e=eF(t,"hex");r.write(e)}else r.writeVarIntNum(-1);else r.writeInt8(0);let n=new eQ(await this.transmit("signAction",t,r.toArray())),s={};if(1===n.readInt8()&&(s.txid=eK(n.read(32))),1===n.readInt8()){let e=n.readVarIntNum();s.tx=n.read(e)}let o=n.readVarIntNum();if(o>=0){s.sendWithResults=[];for(let e=0;e<o;e++){let e=eK(n.read(32)),t=n.readInt8(),r="unproven";1===t?r="unproven":2===t?r="sending":3===t&&(r="failed"),s.sendWithResults.push({txid:e,status:r})}}return s}async abortAction(e,t){return await this.transmit("abortAction",t,eF(e.reference,"base64")),{aborted:!0}}async listActions(e,t){let r=new eZ;for(let t of(r.writeVarIntNum(e.labels.length),e.labels)){let e=eF(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}for(let t of("any"===e.labelQueryMode?r.writeInt8(1):"all"===e.labelQueryMode?r.writeInt8(2):r.writeInt8(-1),[e.includeLabels,e.includeInputs,e.includeInputSourceLockingScripts,e.includeInputUnlockingScripts,e.includeOutputs,e.includeOutputLockingScripts]))"boolean"==typeof t?r.writeInt8(+!!t):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 i=new eQ(await this.transmit("listActions",t,r.toArray())),a=i.readVarIntNum(),n=[];for(let e=0;e<a;e++){let e,t=eK(i.read(32)),r=i.readVarIntNum(),a=i.readInt8();switch(a){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: ${a}`)}let s=1===i.readInt8(),o=i.readVarIntNum(),c={txid:t,satoshis:r,status:e,isOutgoing:s,description:e$(i.read(o)),version:0,lockTime:0},l=i.readVarIntNum();if(l>=0){c.labels=[];for(let e=0;e<l;e++){let e=i.readVarIntNum(),t=i.read(e);c.labels.push(e$(t))}}c.version=i.readVarIntNum(),c.lockTime=i.readVarIntNum();let h=i.readVarIntNum();if(h>=0){c.inputs=[];for(let e=0;e<h;e++){let e,t,r=this.readOutpoint(i),a=i.readVarIntNum(),n=i.readVarIntNum();n>=0&&(e=eK(i.read(n)));let s=i.readVarIntNum();s>=0&&(t=eK(i.read(s)));let o=i.readVarIntNum(),l=e$(i.read(o)),h=i.readVarIntNum();c.inputs.push({sourceOutpoint:r,sourceSatoshis:a,sourceLockingScript:e,unlockingScript:t,inputDescription:l,sequenceNumber:h})}}let d=i.readVarIntNum();if(d>=0){c.outputs=[];for(let e=0;e<d;e++){let e,t,r,a=i.readVarIntNum(),n=i.readVarIntNum(),s=i.readVarIntNum();s>=0&&(e=eK(i.read(s)));let o=1===i.readInt8(),l=i.readVarIntNum(),h=e$(i.read(l)),d=i.readVarIntNum();d>=0&&(t=e$(i.read(d)));let u=i.readVarIntNum(),f=[];if(u>=0)for(let e=0;e<u;e++){let e=i.readVarIntNum(),t=i.read(e);f.push(e$(t))}let p=i.readVarIntNum();p>=0&&(r=e$(i.read(p))),c.outputs.push({outputIndex:a,satoshis:n,lockingScript:e,spendable:o,outputDescription:h,basket:t,tags:f,customInstructions:r})}}n.push(c)}return{totalActions:a,actions:n}}async internalizeAction(e,t){let r=new eZ;for(let t of(r.writeVarIntNum(e.tx.length),r.write(e.tx),r.writeVarIntNum(e.outputs.length),e.outputs))if(r.writeVarIntNum(t.outputIndex),"wallet payment"===t.protocol){if(null==t.paymentRemittance)throw Error("Payment remittance is required for wallet payment");r.writeUInt8(1),r.write(eF(t.paymentRemittance.senderIdentityKey,"hex"));let e=eF(t.paymentRemittance.derivationPrefix,"base64");r.writeVarIntNum(e.length),r.write(e);let i=eF(t.paymentRemittance.derivationSuffix,"base64");r.writeVarIntNum(i.length),r.write(i)}else{r.writeUInt8(2);let e=eF(t.insertionRemittance?.basket,"utf8");if(r.writeVarIntNum(e.length),r.write(e),"string"==typeof t.insertionRemittance?.customInstructions&&""!==t.insertionRemittance.customInstructions){let e=eF(t.insertionRemittance.customInstructions,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if("object"==typeof t.insertionRemittance?.tags)for(let e of(r.writeVarIntNum(t.insertionRemittance.tags.length),t.insertionRemittance.tags)){let t=eF(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}else r.writeVarIntNum(0)}if("object"==typeof e.labels)for(let t of(r.writeVarIntNum(e.labels.length),e.labels)){let e=eF(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);let i=eF(e.description);return r.writeVarIntNum(i.length),r.write(i),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),await this.transmit("internalizeAction",t,r.toArray()),{accepted:!0}}async listOutputs(e,t){let r,i=new eZ,a=eF(e.basket,"utf8");if(i.writeVarIntNum(a.length),i.write(a),"object"==typeof e.tags)for(let t of(i.writeVarIntNum(e.tags.length),e.tags)){let e=eF(t,"utf8");i.writeVarIntNum(e.length),i.write(e)}else i.writeVarIntNum(0);"all"===e.tagQueryMode?i.writeInt8(1):"any"===e.tagQueryMode?i.writeInt8(2):i.writeInt8(-1),"locking scripts"===e.include?i.writeInt8(1):"entire transactions"===e.include?i.writeInt8(2):i.writeInt8(-1),"boolean"==typeof e.includeCustomInstructions?i.writeInt8(+!!e.includeCustomInstructions):i.writeInt8(-1),"boolean"==typeof e.includeTags?i.writeInt8(+!!e.includeTags):i.writeInt8(-1),"boolean"==typeof e.includeLabels?i.writeInt8(+!!e.includeLabels):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 n=new eQ(await this.transmit("listOutputs",t,i.toArray())),s=n.readVarIntNum(),o=n.readVarIntNum();o>=0&&(r=n.read(o));let c=[];for(let e=0;e<s;e++){let e={spendable:!0,outpoint:this.readOutpoint(n),satoshis:n.readVarIntNum()},t=n.readVarIntNum();t>=0&&(e.lockingScript=eK(n.read(t)));let r=n.readVarIntNum();r>=0&&(e.customInstructions=e$(n.read(r)));let i=n.readVarIntNum();if(-1!==i){let t=[];for(let e=0;e<i;e++){let e=n.readVarIntNum();t.push(e$(n.read(e)))}e.tags=t}let a=n.readVarIntNum();if(-1!==a){let t=[];for(let e=0;e<a;e++){let e=n.readVarIntNum();t.push(e$(n.read(e)))}e.labels=t}c.push(e)}return{totalOutputs:s,BEEF:r,outputs:c}}async relinquishOutput(e,t){let r=new eZ,i=eF(e.basket,"utf8");return r.writeVarIntNum(i.length),r.write(i),r.write(this.encodeOutpoint(e.output)),await this.transmit("relinquishOutput",t,r.toArray()),{relinquished:!0}}encodeOutpoint(e){let t=new eZ,[r,i]=e.split(".");return t.write(eF(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}readOutpoint(e){let t=eK(e.read(32)),r=e.readVarIntNum();return`${t}.${r}`}async getPublicKey(e,t){let i=new eZ;return i.writeUInt8(+!!e.identityKey),e.identityKey?i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)):(i.write(this.encodeKeyRelatedParams(e.protocolID??=[r.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:eK(await this.transmit("getPublicKey",t,i.toArray()))}}async revealCounterpartyKeyLinkage(e,t){let r=new eZ;r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),r.write(eF(e.counterparty,"hex")),r.write(eF(e.verifier,"hex"));let i=new eQ(await this.transmit("revealCounterpartyKeyLinkage",t,r.toArray())),a=eK(i.read(33)),n=eK(i.read(33)),s=eK(i.read(33)),o=i.readVarIntNum(),c=e$(i.read(o)),l=i.readVarIntNum(),h=i.read(l),d=i.readVarIntNum();return{prover:a,verifier:n,counterparty:s,revelationTime:c,encryptedLinkage:h,encryptedLinkageProof:i.read(d)}}async revealSpecificKeyLinkage(e,t){let r=new eZ;r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.write(eF(e.verifier,"hex"));let i=new eQ(await this.transmit("revealSpecificKeyLinkage",t,r.toArray())),a=eK(i.read(33)),n=eK(i.read(33)),s=eK(i.read(33)),o=i.readUInt8(),c=i.readVarIntNum(),l=e$(i.read(c)),h=i.readVarIntNum(),d=e$(i.read(h)),u=i.readVarIntNum(),f=i.read(u),p=i.readVarIntNum();return{prover:a,verifier:n,counterparty:s,protocolID:[o,l],keyID:d,encryptedLinkage:f,encryptedLinkageProof:i.read(p),proofType:i.readUInt8()}}async encrypt(e,t){let r=new eZ;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.writeVarIntNum(e.plaintext.length),r.write(e.plaintext),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{ciphertext:await this.transmit("encrypt",t,r.toArray())}}async decrypt(e,t){let r=new eZ;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.writeVarIntNum(e.ciphertext.length),r.write(e.ciphertext),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{plaintext:await this.transmit("decrypt",t,r.toArray())}}async createHmac(e,t){let r=new eZ;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.writeVarIntNum(e.data.length),r.write(e.data),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{hmac:await this.transmit("createHmac",t,r.toArray())}}async verifyHmac(e,t){let r=new eZ;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.write(e.hmac),r.writeVarIntNum(e.data.length),r.write(e.data),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),await this.transmit("verifyHmac",t,r.toArray()),{valid:!0}}async createSignature(e,t){let r=new eZ;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"object"==typeof e.data?(r.writeUInt8(1),r.writeVarIntNum(e.data.length),r.write(e.data)):(r.writeUInt8(2),r.write(e.hashToDirectlySign??=[])),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{signature:await this.transmit("createSignature",t,r.toArray())}}async verifySignature(e,t){let r=new eZ;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?r.writeInt8(+!!e.forSelf):r.writeInt8(-1),r.writeVarIntNum(e.signature.length),r.write(e.signature),"object"==typeof e.data?(r.writeUInt8(1),r.writeVarIntNum(e.data.length),r.write(e.data)):(r.writeUInt8(2),r.write(e.hashToDirectlyVerify??[])),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),await this.transmit("verifySignature",t,r.toArray()),{valid:!0}}encodeKeyRelatedParams(e,t,r,i,a){let n=new eZ;n.writeUInt8(e[0]);let s=eF(e[1],"utf8");n.writeVarIntNum(s.length),n.write(s);let o=eF(t,"utf8");return n.writeVarIntNum(o.length),n.write(o),"string"!=typeof r?n.writeUInt8(0):"self"===r?n.writeUInt8(11):"anyone"===r?n.writeUInt8(12):n.write(eF(r,"hex")),n.write(this.encodePrivilegedParams(i,a)),n.toArray()}async acquireCertificate(e,t){let r=new eZ;r.write(eF(e.type,"base64")),r.write(eF(e.certifier,"hex"));let i=Object.entries(e.fields);for(let[e,t]of(r.writeVarIntNum(i.length),i)){let i=eF(e,"utf8"),a=eF(t,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(a.length),r.write(a)}if(r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),r.writeUInt8("direct"===e.acquisitionProtocol?1:2),"direct"===e.acquisitionProtocol){r.write(eF(e.serialNumber,"base64")),r.write(this.encodeOutpoint(e.revocationOutpoint??""));let t=eF(e.signature,"hex");r.writeVarIntNum(t.length),r.write(t);let i="certifier"!==e.keyringRevealer?eF(e.keyringRevealer,"hex"):[11];r.write(i);let a=Object.keys(e.keyringForSubject??{});r.writeVarIntNum(a.length);for(let t=0;t<a.length;t++){let i=eF(a[t],"utf8");r.writeVarIntNum(i.length),r.write(i);let n=eF(e.keyringForSubject?.[a[t]],"base64");r.writeVarIntNum(n.length),r.write(n)}}else{let t=eF(e.certifierUrl,"utf8");r.writeVarIntNum(t.length),r.write(t)}let a=await this.transmit("acquireCertificate",t,r.toArray()),n=r0.fromBinary(a);return{...n,signature:n.signature}}encodePrivilegedParams(e,t){let r=new eZ;if("boolean"==typeof e?r.writeInt8(+!!e):r.writeInt8(-1),"string"==typeof t){let e=eF(t,"utf8");r.writeInt8(e.length),r.write(e)}else r.writeInt8(-1);return r.toArray()}async listCertificates(e,t){let r=new eZ;r.writeVarIntNum(e.certifiers.length);for(let t=0;t<e.certifiers.length;t++)r.write(eF(e.certifiers[t],"hex"));r.writeVarIntNum(e.types.length);for(let t=0;t<e.types.length;t++)r.write(eF(e.types[t],"base64"));"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let i=new eQ(await this.transmit("listCertificates",t,r.toArray())),a=i.readVarIntNum(),n=[];for(let e=0;e<a;e++){let e,t=i.readVarIntNum(),r=i.read(t),a=r0.fromBinary(r),s={};if(1===i.readInt8()){let e=i.readVarIntNum();for(let t=0;t<e;t++){let e=i.readVarIntNum(),t=e$(i.read(e)),r=i.readVarIntNum();s[t]=eW(i.read(r))}}let o=i.readVarIntNum();o>0&&(e=e$(i.read(o))),n.push({...a,signature:a.signature,keyring:s,verifier:e})}return{totalCertificates:a,certificates:n}}async proveCertificate(e,t){let r=new eZ,i=eF(e.certificate.type,"base64");r.write(i);let a=eF(e.certificate.subject,"hex");r.write(a);let n=eF(e.certificate.serialNumber,"base64");r.write(n);let s=eF(e.certificate.certifier,"hex");r.write(s);let o=this.encodeOutpoint(e.certificate.revocationOutpoint??"");r.write(o);let c=eF(e.certificate.signature,"hex");r.writeVarIntNum(c.length),r.write(c);let l=Object.entries(e.certificate.fields??{});for(let[e,t]of(r.writeVarIntNum(l.length),l)){let i=eF(e,"utf8"),a=eF(t,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(a.length),r.write(a)}for(let t of(r.writeVarIntNum(e.fieldsToReveal.length),e.fieldsToReveal)){let e=eF(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}r.write(eF(e.verifier,"hex")),r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let h=new eQ(await this.transmit("proveCertificate",t,r.toArray())),d=h.readVarIntNum(),u={};for(let e=0;e<d;e++){let e=h.readVarIntNum(),t=e$(h.read(e)),r=h.readVarIntNum();u[t]=eW(h.read(r))}return{keyringForVerifier:u}}async relinquishCertificate(e,t){let r=new eZ,i=eF(e.type,"base64");r.write(i);let a=eF(e.serialNumber,"base64");r.write(a);let n=eF(e.certifier,"hex");return r.write(n),await this.transmit("relinquishCertificate",t,r.toArray()),{relinquished:!0}}parseDiscoveryResult(e){let t=new eQ(e),r=t.readVarIntNum(),i=[];for(let e=0;e<r;e++){let e=t.readVarIntNum(),r=t.read(e),a=r0.fromBinary(r),n=t.readVarIntNum(),s=e$(t.read(n)),o=t.readVarIntNum(),c=e$(t.read(o)),l=t.readVarIntNum(),h=e$(t.read(l)),d=t.readUInt8(),u={},f=t.readVarIntNum();for(let e=0;e<f;e++){let e=t.readVarIntNum(),r=e$(t.read(e)),i=t.readVarIntNum();u[r]=t.read(i)}let p={},b=t.readVarIntNum();for(let e=0;e<b;e++){let e=t.readVarIntNum(),r=e$(t.read(e)),i=t.readVarIntNum();p[r]=e$(t.read(i))}i.push({...a,signature:a.signature,certifierInfo:{iconUrl:c,name:s,description:h,trust:d},publiclyRevealedKeyring:u,decryptedFields:p})}return{totalCertificates:r,certificates:i}}async discoverByIdentityKey(e,t){let r=new eZ;r.write(eF(e.identityKey,"hex")),"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1);let i=await this.transmit("discoverByIdentityKey",t,r.toArray());return this.parseDiscoveryResult(i)}async discoverByAttributes(e,t){let r=new eZ,i=Object.keys(e.attributes);r.writeVarIntNum(i.length);for(let t=0;t<i.length;t++)r.writeVarIntNum(i[t].length),r.write(eF(i[t],"utf8")),r.writeVarIntNum(e.attributes[i[t]].length),r.write(eF(e.attributes[i[t]],"utf8"));"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1);let a=await this.transmit("discoverByAttributes",t,r.toArray());return this.parseDiscoveryResult(a)}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 eQ(await this.transmit("getHeight",t)).readVarIntNum()}}async getHeaderForHeight(e,t){let r=new eZ;return r.writeVarIntNum(e.height),{header:eK(await this.transmit("getHeaderForHeight",t,r.toArray()))}}async getNetwork(e,t){return{network:0===(await this.transmit("getNetwork",t))[0]?"mainnet":"testnet"}}async getVersion(e,t){return{version:e$(await this.transmit("getVersion",t))}}}class r8{baseUrl;httpClient;originator;constructor(e,t="http://localhost:3301",r=fetch){this.baseUrl=t,this.httpClient=r,this.originator=e}async transmitToWallet(e){let t,r=new eQ(e),i=r.readUInt8(),a=r1[i];if(void 0===a||""===a)throw Error(`Invalid call code: ${i}`);let n=r.readUInt8();n>0&&(t=e$(r.read(n)));let s=r.read(),o=await fetch(`${this.baseUrl}/${a}`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Origin:t??""},body:new Uint8Array(s)});return Array.from(new Uint8Array(await o.arrayBuffer()))}}class r3 extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(e,t,r,i,a){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=e,this.sendWithResults=t,this.txid=r,this.tx=i,this.noSendChange=a,this.code=5,this.name=this.constructor.name}}let r6=r3;class r4{baseUrl;httpClient;originator;api;constructor(e,t="http://localhost:3321",r=fetch){this.baseUrl=t,this.originator=e,this.httpClient=r;let i="undefined"!=typeof window&&"undefined"!=typeof document&&window?.origin!=="file://";this.api=async(e,t)=>{let a=!i&&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;i||void 0!==a||console.error("Originator is required in Node.js environments");let n=await await r(`${this.baseUrl}/${e}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...a?{Origin:a}:{},...a?{Originator:a}:{}},body:JSON.stringify(t)}),s=await n.json();if(!n.ok)if(400===n.status&&s.isError&&5===s.code)throw new r3(s.reviewActionResults,s.sendWithResults,s.txid,s.tx,s.noSendChange);else throw Error(JSON.stringify({call:e,args:t,message:s.message??`HTTP Client error ${n.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 r5{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((r,i)=>{let a=eW(tx(12)),n=e=>{let t=JSON.parse(e.data);"CWI"===t.type&&t.id===a&&!0!==t.isInvocation&&("function"==typeof window.removeEventListener&&window.removeEventListener("message",n),"error"===t.status?i(new rJ(t.description,t.code)):r(t.result))};window.addEventListener("message",n),window.ReactNativeWebView.postMessage(JSON.stringify({type:"CWI",isInvocation:!0,id:a,call:e,args:t}))})}async createAction(e){return await this.invoke("createAction",e)}async signAction(e){return await this.invoke("signAction",e)}async abortAction(e){return await this.invoke("abortAction",e)}async listActions(e){return await this.invoke("listActions",e)}async internalizeAction(e){return await this.invoke("internalizeAction",e)}async listOutputs(e){return await this.invoke("listOutputs",e)}async relinquishOutput(e){return await this.invoke("relinquishOutput",e)}async getPublicKey(e){return await this.invoke("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.invoke("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.invoke("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.invoke("encrypt",e)}async decrypt(e){return await this.invoke("decrypt",e)}async createHmac(e){return await this.invoke("createHmac",e)}async verifyHmac(e){return await this.invoke("verifyHmac",e)}async createSignature(e){return await this.invoke("createSignature",e)}async verifySignature(e){return await this.invoke("verifySignature",e)}async acquireCertificate(e){return await this.invoke("acquireCertificate",e)}async listCertificates(e){return await this.invoke("listCertificates",e)}async proveCertificate(e){return await this.invoke("proveCertificate",e)}async relinquishCertificate(e){return await this.invoke("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.invoke("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.invoke("discoverByAttributes",e)}async isAuthenticated(e){return await this.invoke("isAuthenticated",e)}async waitForAuthentication(e){return await this.invoke("waitForAuthentication",e)}async getHeight(e){return await this.invoke("getHeight",e)}async getHeaderForHeight(e){return await this.invoke("getHeaderForHeight",e)}async getNetwork(e){return await this.invoke("getNetwork",e)}async getVersion(e){return await this.invoke("getVersion",e)}}class r7{substrate;originator;constructor(e="auto",t){"Cicada"===e&&(e=new r2(new r8(t))),"window.CWI"===e&&(e=new rY),"XDM"===e&&(e=new rQ),"json-api"===e&&(e=new r4(t)),"react-native"===e&&(e=new r5(t)),"secure-json-api"===e&&(e=new r4(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 r,i=e();if(r="number"==typeof t?await Promise.race([i.getVersion({}),new Promise((e,r)=>setTimeout(()=>r(Error("Timed out.")),t))]):await i.getVersion({}),"object"!=typeof r||"string"!=typeof r.version)return{success:!1};return{success:!0,sub:i}}catch{return{success:!1}}},t=[e(()=>new rY),e(()=>new r4(this.originator,"https://localhost:2121")),e(()=>new r4(this.originator)),e(()=>new r5(this.originator)),e(()=>new r2(new r8(this.originator)))],r=(await Promise.allSettled(t)).filter(e=>"fulfilled"===e.status&&e.value.success&&void 0!==e.value.sub).map(e=>e.value.sub);if(r.length>0){this.substrate=r[0];return}let i=await e(()=>new rQ,200);if(i.success&&void 0!==i.sub)this.substrate=i.sub;else throw Error("No wallet available over any communication substrate. Install a BSV wallet today!")}async createAction(e){return await this.connectToSubstrate(),await this.substrate.createAction(e,this.originator)}async signAction(e){return await this.connectToSubstrate(),await this.substrate.signAction(e,this.originator)}async abortAction(e){return await this.connectToSubstrate(),await this.substrate.abortAction(e,this.originator)}async listActions(e){return await this.connectToSubstrate(),await this.substrate.listActions(e,this.originator)}async internalizeAction(e){return await this.connectToSubstrate(),await this.substrate.internalizeAction(e,this.originator)}async listOutputs(e){return await this.connectToSubstrate(),await this.substrate.listOutputs(e,this.originator)}async relinquishOutput(e){return await this.connectToSubstrate(),await this.substrate.relinquishOutput(e,this.originator)}async getPublicKey(e){return await this.connectToSubstrate(),await this.substrate.getPublicKey(e,this.originator)}async revealCounterpartyKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealCounterpartyKeyLinkage(e,this.originator)}async revealSpecificKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealSpecificKeyLinkage(e,this.originator)}async encrypt(e){return await this.connectToSubstrate(),await this.substrate.encrypt(e,this.originator)}async decrypt(e){return await this.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){return await this.connectToSubstrate(),await this.substrate.acquireCertificate(e,this.originator)}async listCertificates(e){return await this.connectToSubstrate(),await this.substrate.listCertificates(e,this.originator)}async proveCertificate(e){return await this.connectToSubstrate(),await this.substrate.proveCertificate(e,this.originator)}async relinquishCertificate(e){return await this.connectToSubstrate(),await this.substrate.relinquishCertificate(e,this.originator)}async discoverByIdentityKey(e){return await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(e,this.originator)}async discoverByAttributes(e){return await this.connectToSubstrate(),await this.substrate.discoverByAttributes(e,this.originator)}async isAuthenticated(e={}){return await this.connectToSubstrate(),await this.substrate.isAuthenticated(e,this.originator)}async waitForAuthentication(e={}){return await this.connectToSubstrate(),await this.substrate.waitForAuthentication(e,this.originator)}async getHeight(e={}){return await this.connectToSubstrate(),await this.substrate.getHeight(e,this.originator)}async getHeaderForHeight(e){return await this.connectToSubstrate(),await this.substrate.getHeaderForHeight(e,this.originator)}async getNetwork(e={}){return await this.connectToSubstrate(),await this.substrate.getNetwork(e,this.originator)}async getVersion(e={}){return await this.connectToSubstrate(),await this.substrate.getVersion(e,this.originator)}}class r9{wallet;constructor(e){this.wallet=e}decodeOutpoint(e){let t=eK(e.read(32)),r=e.readVarIntNum();return`${t}.${r}`}encodeOutpoint(e){let t=new eZ,[r,i]=e.split(".");return t.write(eF(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}async transmitToWallet(e){let t=new eQ(e);try{let e=t.readUInt8(),r=r1[e];if(void 0===r||""===r)throw Error(`Invalid call code: ${e}`);let i=t.readUInt8(),a=t.read(i),n=e$(a);switch(r){case"createAction":{let e={},r=t.readVarIntNum(),i=t.read(r);e.description=e$(i);let a=t.readVarIntNum();a>=0?e.inputBEEF=t.read(a):e.inputBEEF=void 0;let s=t.readVarIntNum();if(s>=0){e.inputs=[];for(let r=0;r<s;r++){let r={};r.outpoint=this.decodeOutpoint(t);let i=t.readVarIntNum();if(i>=0){let e=t.read(i);r.unlockingScript=eK(e)}else r.unlockingScript=void 0,r.unlockingScriptLength=t.readVarIntNum();let a=t.readVarIntNum(),n=t.read(a);r.inputDescription=e$(n);let s=t.readVarIntNum();s>=0?r.sequenceNumber=s:r.sequenceNumber=void 0,e.inputs.push(r)}}else e.inputs=void 0;let o=t.readVarIntNum();if(o>=0){e.outputs=[];for(let r=0;r<o;r++){let r={},i=t.readVarIntNum(),a=t.read(i);r.lockingScript=eK(a),r.satoshis=t.readVarIntNum();let n=t.readVarIntNum(),s=t.read(n);r.outputDescription=e$(s);let o=t.readVarIntNum();if(o>=0){let e=t.read(o);r.basket=e$(e)}else r.basket=void 0;let c=t.readVarIntNum();if(c>=0){let e=t.read(c);r.customInstructions=e$(e)}else r.customInstructions=void 0;let l=t.readVarIntNum();if(l>=0){r.tags=[];for(let e=0;e<l;e++){let e=t.readVarIntNum(),i=t.read(e),a=e$(i);r.tags.push(a)}}else r.tags=void 0;e.outputs.push(r)}}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 r=0;r<h;r++){let r=t.readVarIntNum(),i=t.read(r),a=e$(i);e.labels.push(a)}}else e.labels=void 0;let d=t.readInt8();if(1===d){e.options={};let r=t.readInt8();-1===r?e.options.signAndProcess=void 0:e.options.signAndProcess=1===r;let i=t.readInt8();-1===i?e.options.acceptDelayedBroadcast=void 0:e.options.acceptDelayedBroadcast=1===i;let a=t.readInt8();-1===a?e.options.trustSelf=void 0:1===a&&(e.options.trustSelf="known");let n=t.readVarIntNum();if(n>=0){e.options.knownTxids=[];for(let r=0;r<n;r++){let r=t.read(32),i=eK(r);e.options.knownTxids.push(i)}}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 r=0;r<c;r++){let r=this.decodeOutpoint(t);e.options.noSendChange.push(r)}}else e.options.noSendChange=void 0;let l=t.readVarIntNum();if(l>=0){e.options.sendWith=[];for(let r=0;r<l;r++){let r=t.read(32),i=eK(r);e.options.sendWith.push(i)}}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,n),f=new eZ;if(null!=u.txid&&""!==u.txid?(f.writeInt8(1),f.write(eF(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(eF(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=eF(u.signableTransaction.reference,"base64");f.writeVarIntNum(e.length),f.write(e)}else f.writeInt8(0);let p=new eZ;return p.writeUInt8(0),p.write(f.toArray()),p.toArray()}case"signAction":{let e={},r=t.readVarIntNum();e.spends={};for(let i=0;i<r;i++){let r=t.readVarIntNum(),i={},a=t.readVarIntNum(),n=t.read(a);i.unlockingScript=eK(n);let s=t.readVarIntNum();s>=0?i.sequenceNumber=s:i.sequenceNumber=void 0,e.spends[r]=i}let i=t.readVarIntNum(),a=t.read(i);e.reference=eW(a);let s=t.readInt8();if(1===s){e.options={};let r=t.readInt8();-1===r?e.options.acceptDelayedBroadcast=void 0:e.options.acceptDelayedBroadcast=1===r;let i=t.readInt8();-1===i?e.options.returnTXIDOnly=void 0:e.options.returnTXIDOnly=1===i;let a=t.readInt8();-1===a?e.options.noSend=void 0:e.options.noSend=1===a;let n=t.readVarIntNum();if(n>=0){e.options.sendWith=[];for(let r=0;r<n;r++){let r=t.read(32),i=eK(r);e.options.sendWith.push(i)}}else e.options.sendWith=void 0}else e.options=void 0;let o=await this.wallet.signAction(e,n),c=new eZ;if(null!=o.txid&&""!==o.txid?(c.writeInt8(1),c.write(eF(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(eF(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 eZ;return l.writeUInt8(0),l.write(c.toArray()),l.toArray()}case"abortAction":{let e=t.read(),r=eW(e);await this.wallet.abortAction({reference:r},n);let i=new eZ;return i.writeUInt8(0),i.toArray()}case"listActions":{let e={},r=t.readVarIntNum();e.labels=[];for(let i=0;i<r;i++){let r=t.readVarIntNum(),i=t.read(r);e.labels.push(e$(i))}let i=t.readInt8();for(let r of(-1===i?e.labelQueryMode=void 0:1===i?e.labelQueryMode="any":2===i&&(e.labelQueryMode="all"),["includeLabels","includeInputs","includeInputSourceLockingScripts","includeInputUnlockingScripts","includeOutputs","includeOutputLockingScripts"])){let i=t.readInt8();-1===i?e[r]=void 0:e[r]=1===i}let a=t.readVarIntNum();a>=0?e.limit=a: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,n),l=new eZ;for(let e of(l.writeVarIntNum(c.totalActions),c.actions)){let t;switch(l.write(eF(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 r=eF(e.description,"utf8");if(l.writeVarIntNum(r.length),l.write(r),void 0!==e.labels)for(let t of(l.writeVarIntNum(e.labels.length),e.labels)){let e=eF(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=eF(t.sourceLockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);if(void 0!==t.unlockingScript){let e=eF(t.unlockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);let e=eF(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=eF(t.lockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);l.writeInt8(+!!t.spendable);let e=eF(t.outputDescription,"utf8");if(l.writeVarIntNum(e.length),l.write(e),void 0!==t.basket){let e=eF(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=eF(e,"utf8");l.writeVarIntNum(t.length),l.write(t)}else l.writeVarIntNum(-1);if(void 0!==t.customInstructions){let e=eF(t.customInstructions,"utf8");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1)}else l.writeVarIntNum(-1)}let h=new eZ;return h.writeUInt8(0),h.write(l.toArray()),h.toArray()}case"internalizeAction":{let e={},r=t.readVarIntNum();e.tx=t.read(r);let i=t.readVarIntNum();e.outputs=[];for(let r=0;r<i;r++){let r={};r.outputIndex=t.readVarIntNum();let i=t.readUInt8();if(1===i){r.protocol="wallet payment",r.paymentRemittance={};let e=t.read(33);r.paymentRemittance.senderIdentityKey=eK(e);let i=t.readVarIntNum(),a=t.read(i);r.paymentRemittance.derivationPrefix=eW(a);let n=t.readVarIntNum(),s=t.read(n);r.paymentRemittance.derivationSuffix=eW(s)}else if(2===i){r.protocol="basket insertion",r.insertionRemittance={};let e=t.readVarIntNum(),i=t.read(e);r.insertionRemittance.basket=e$(i);let a=t.readVarIntNum();if(a>=0){let e=t.read(a);r.insertionRemittance.customInstructions=e$(e)}let n=t.readVarIntNum();if(n>0){r.insertionRemittance.tags=[];for(let e=0;e<n;e++){let e=t.readVarIntNum(),i=t.read(e);r.insertionRemittance.tags.push(e$(i))}}else r.insertionRemittance.tags=[]}e.outputs.push(r)}let a=t.readVarIntNum();if(a>=0){e.labels=[];for(let r=0;r<a;r++){let r=t.readVarIntNum();e.labels.push(e$(t.read(r)))}}let s=t.readVarIntNum();e.description=e$(t.read(s));let o=t.readInt8();o>=0?e.seekPermission=1===o:e.seekPermission=void 0,await this.wallet.internalizeAction(e,n);let c=new eZ;return c.writeUInt8(0),c.toArray()}case"listOutputs":{let e={},r=t.readVarIntNum(),i=t.read(r);e.basket=e$(i);let a=t.readVarIntNum();if(a>0){e.tags=[];for(let r=0;r<a;r++){let r=t.readVarIntNum(),i=t.read(r);e.tags.push(e$(i))}}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,n),b=new eZ;for(let e of(b.writeVarIntNum(p.totalOutputs),null!=p.BEEF?(b.writeVarIntNum(p.BEEF.length),b.write(p.BEEF)):b.writeVarIntNum(-1),p.outputs)){if(b.write(this.encodeOutpoint(e.outpoint)),b.writeVarIntNum(e.satoshis),void 0!==e.lockingScript){let t=eF(e.lockingScript,"hex");b.writeVarIntNum(t.length),b.write(t)}else b.writeVarIntNum(-1);if(void 0!==e.customInstructions){let t=eF(e.customInstructions,"utf8");b.writeVarIntNum(t.length),b.write(t)}else b.writeVarIntNum(-1);if(void 0!==e.tags)for(let t of(b.writeVarIntNum(e.tags.length),e.tags)){let e=eF(t,"utf8");b.writeVarIntNum(e.length),b.write(e)}else b.writeVarIntNum(-1);if(void 0!==e.labels)for(let t of(b.writeVarIntNum(e.labels.length),e.labels)){let e=eF(t,"utf8");b.writeVarIntNum(e.length),b.write(e)}else b.writeVarIntNum(-1)}let g=new eZ;return g.writeUInt8(0),g.write(b.toArray()),g.toArray()}case"relinquishOutput":{let e={},r=t.readVarIntNum(),i=t.read(r);e.basket=e$(i),e.output=this.decodeOutpoint(t),await this.wallet.relinquishOutput(e,n);let a=new eZ;return a.writeUInt8(0),a.toArray()}case"getPublicKey":{let e={},r=t.readUInt8();if(e.identityKey=1===r,!0!==e.identityKey){e.protocolID=this.decodeProtocolID(t),e.keyID=this.decodeString(t),e.counterparty=this.decodeCounterparty(t);let r=t.readInt8();-1===r?e.privileged=void 0:e.privileged=1===r;let i=t.readInt8();if(-1!==i){let r=t.read(i);e.privilegedReason=e$(r)}else e.privilegedReason=void 0;let a=t.readInt8();-1===a?e.forSelf=void 0:e.forSelf=1===a}else{let r=t.readInt8();-1===r?e.privileged=void 0:e.privileged=1===r;let i=t.readInt8();if(-1!==i){let r=t.read(i);e.privilegedReason=e$(r)}else e.privilegedReason=void 0}let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let a=await this.wallet.getPublicKey(e,n),s=new eZ;s.writeUInt8(0);let o=eF(a.publicKey,"hex");return s.write(o),s.toArray()}case"encrypt":{let e=this.decodeKeyRelatedParams(t),r=t.readVarIntNum();e.plaintext=t.read(r);let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let a=await this.wallet.encrypt(e,n),s=new eZ;return s.writeUInt8(0),s.write(a.ciphertext),s.toArray()}case"decrypt":{let e=this.decodeKeyRelatedParams(t),r=t.readVarIntNum();e.ciphertext=t.read(r);let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let a=await this.wallet.decrypt(e,n),s=new eZ;return s.writeUInt8(0),s.write(a.plaintext),s.toArray()}case"createHmac":{let e=this.decodeKeyRelatedParams(t),r=t.readVarIntNum();e.data=t.read(r);let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let a=await this.wallet.createHmac(e,n),s=new eZ;return s.writeUInt8(0),s.write(a.hmac),s.toArray()}case"verifyHmac":{let e=this.decodeKeyRelatedParams(t);e.hmac=t.read(32);let r=t.readVarIntNum();e.data=t.read(r);let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0,await this.wallet.verifyHmac(e,n);let a=new eZ;return a.writeUInt8(0),a.toArray()}case"createSignature":{let e=this.decodeKeyRelatedParams(t),r=t.readUInt8();if(1===r){let r=t.readVarIntNum();e.data=t.read(r)}else 2===r&&(e.hashToDirectlySign=t.read(32));let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let a=await this.wallet.createSignature(e,n),s=new eZ;return s.writeUInt8(0),s.write(a.signature),s.toArray()}case"verifySignature":{let e=this.decodeKeyRelatedParams(t),r=t.readInt8();-1===r?e.forSelf=void 0:e.forSelf=1===r;let i=t.readVarIntNum();e.signature=t.read(i);let a=t.readUInt8();if(1===a){let r=t.readVarIntNum();e.data=t.read(r)}else 2===a&&(e.hashToDirectlyVerify=t.read(32));let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0,await this.wallet.verifySignature(e,n);let o=new eZ;return o.writeUInt8(0),o.toArray()}case"isAuthenticated":{let e=await this.wallet.isAuthenticated({},n),t=new eZ;return t.writeUInt8(0),t.writeUInt8(+!!e.authenticated),t.toArray()}case"waitForAuthentication":{await this.wallet.waitForAuthentication({},n);let e=new eZ;return e.writeUInt8(0),e.toArray()}case"getHeight":{let e=await this.wallet.getHeight({},n),t=new eZ;return t.writeUInt8(0),t.writeVarIntNum(e.height),t.toArray()}case"getHeaderForHeight":{let e={};e.height=t.readVarIntNum();let r=await this.wallet.getHeaderForHeight(e,n),i=new eZ;i.writeUInt8(0);let a=eF(r.header,"hex");return i.write(a),i.toArray()}case"getNetwork":{let e=await this.wallet.getNetwork({},n),t=new eZ;return t.writeUInt8(0),t.writeUInt8(+("mainnet"!==e.network)),t.toArray()}case"getVersion":{let e=await this.wallet.getVersion({},n),t=new eZ;t.writeUInt8(0);let r=eF(e.version,"utf8");return t.write(r),t.toArray()}case"revealCounterpartyKeyLinkage":{let e={},r=t.readInt8();-1===r?e.privileged=void 0:e.privileged=1===r;let i=t.readInt8();if(-1===i)e.privilegedReason=void 0;else{let r=t.read(i);e.privilegedReason=e$(r)}let a=t.read(33);e.counterparty=eK(a);let s=t.read(33);e.verifier=eK(s);let o=await this.wallet.revealCounterpartyKeyLinkage(e,n),c=new eZ;c.write(eF(o.prover,"hex")),c.write(eF(o.verifier,"hex")),c.write(eF(o.counterparty,"hex"));let l=eF(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 eZ;return h.writeUInt8(0),h.write(c.toArray()),h.toArray()}case"revealSpecificKeyLinkage":{let e=this.decodeKeyRelatedParams(t),r=t.read(33);e.verifier=eK(r);let i=await this.wallet.revealSpecificKeyLinkage(e,n),a=new eZ;a.write(eF(i.prover,"hex")),a.write(eF(i.verifier,"hex")),a.write(eF(i.counterparty,"hex")),a.writeUInt8(i.protocolID[0]);let s=eF(i.protocolID[1],"utf8");a.writeVarIntNum(s.length),a.write(s);let o=eF(i.keyID,"utf8");a.writeVarIntNum(o.length),a.write(o),a.writeVarIntNum(i.encryptedLinkage.length),a.write(i.encryptedLinkage),a.writeVarIntNum(i.encryptedLinkageProof.length),a.write(i.encryptedLinkageProof),a.writeUInt8(i.proofType);let c=new eZ;return c.writeUInt8(0),c.write(a.toArray()),c.toArray()}case"acquireCertificate":{let e={},r=t.read(32);e.type=eW(r);let i=t.read(33);e.certifier=eK(i);let a=t.readVarIntNum();e.fields={};for(let r=0;r<a;r++){let r=t.readVarIntNum(),i=t.read(r),a=e$(i),n=t.readVarIntNum(),s=t.read(n),o=e$(s);e.fields[a]=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 r=t.read(o);e.privilegedReason=e$(r)}let c=t.readUInt8();if(e.acquisitionProtocol=1===c?"direct":"issuance","direct"===e.acquisitionProtocol){let r=t.read(32);e.serialNumber=eW(r),e.revocationOutpoint=this.decodeOutpoint(t);let i=t.readVarIntNum(),a=t.read(i);e.signature=eK(a);let n=t.readUInt8();if(11===n)e.keyringRevealer="certifier";else{let r=[n].concat(t.read(32));e.keyringRevealer=eK(r)}let s=t.readVarIntNum();e.keyringForSubject={};for(let r=0;r<s;r++){let r=t.readVarIntNum(),i=t.read(r),a=e$(i),n=t.readVarIntNum(),s=t.read(n),o=eW(s);e.keyringForSubject[a]=o}}else{let r=t.readVarIntNum(),i=t.read(r);e.certifierUrl=e$(i)}let l=await this.wallet.acquireCertificate(e,n),h=new r0(l.type,l.serialNumber,l.subject,l.certifier,l.revocationOutpoint,l.fields,l.signature).toBinary(),d=new eZ;return d.writeUInt8(0),d.write(h),d.toArray()}case"listCertificates":{let e={},r=t.readVarIntNum();e.certifiers=[];for(let i=0;i<r;i++){let r=t.read(33);e.certifiers.push(eK(r))}let i=t.readVarIntNum();e.types=[];for(let r=0;r<i;r++){let r=t.read(32);e.types.push(eW(r))}let a=t.readVarIntNum();a>=0?e.limit=a: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 r=t.read(c);e.privilegedReason=e$(r)}let l=await this.wallet.listCertificates(e,n),h=new eZ;for(let e of(h.writeVarIntNum(l.totalCertificates),l.certificates)){let t=new r0(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,r]of(h.writeVarIntNum(t.length),t)){let t=eF(e,"utf8");h.writeVarIntNum(t.length),h.write(t);let i=eF(r,"base64");h.writeVarIntNum(i.length),h.write(i)}}else h.writeInt8(0);let r=eF(e.verifier,"hex");h.writeVarIntNum(r.length),h.write(r)}let d=new eZ;return d.writeUInt8(0),d.write(h.toArray()),d.toArray()}case"proveCertificate":{let e={},r={},i=t.read(32);r.type=eW(i);let a=t.read(33);r.subject=eK(a);let s=t.read(32);r.serialNumber=eW(s);let o=t.read(33);r.certifier=eK(o),r.revocationOutpoint=this.decodeOutpoint(t);let c=t.readVarIntNum(),l=t.read(c);r.signature=eK(l);let h=t.readVarIntNum();r.fields={};for(let e=0;e<h;e++){let e=t.readVarIntNum(),i=t.read(e),a=e$(i),n=t.readVarIntNum(),s=t.read(n),o=e$(s);r.fields[a]=o}e.certificate=r;let d=t.readVarIntNum();e.fieldsToReveal=[];for(let r=0;r<d;r++){let r=t.readVarIntNum(),i=t.read(r),a=e$(i);e.fieldsToReveal.push(a)}let u=t.read(33);e.verifier=eK(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 r=t.read(p);e.privilegedReason=e$(r)}let b=await this.wallet.proveCertificate(e,n),g=new eZ,m=Object.entries(b.keyringForVerifier);for(let[e,t]of(g.writeVarIntNum(m.length),m)){let r=eF(e,"utf8");g.writeVarIntNum(r.length),g.write(r);let i=eF(t,"base64");g.writeVarIntNum(i.length),g.write(i)}let y=new eZ;return y.writeUInt8(0),y.write(g.toArray()),y.toArray()}case"relinquishCertificate":{let e={},r=t.read(32);e.type=eW(r);let i=t.read(32);e.serialNumber=eW(i);let a=t.read(33);e.certifier=eK(a),await this.wallet.relinquishCertificate(e,n);let s=new eZ;return s.writeUInt8(0),s.toArray()}case"discoverByIdentityKey":{let e={},r=t.read(33);e.identityKey=eK(r);let i=t.readVarIntNum();i>=0?e.limit=i:e.limit=void 0;let a=t.readVarIntNum();a>=0?e.offset=a: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,n),c=this.serializeDiscoveryResult(o),l=new eZ;return l.writeUInt8(0),l.write(c),l.toArray()}case"discoverByAttributes":{let e={},r=t.readVarIntNum();e.attributes={};for(let i=0;i<r;i++){let r=t.readVarIntNum(),i=t.read(r),a=e$(i),n=t.readVarIntNum(),s=t.read(n),o=e$(s);e.attributes[a]=o}let i=t.readVarIntNum();i>=0?e.limit=i:e.limit=void 0;let a=t.readVarIntNum();a>=0?e.offset=a: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,n),c=this.serializeDiscoveryResult(o),l=new eZ;return l.writeUInt8(0),l.write(c),l.toArray()}default:throw Error(`Method ${r} not implemented`)}}catch(i){let e=new eZ;e.writeUInt8("number"==typeof i.code?i.code:1);let t=eF("string"==typeof i.message?i.message:"Unknown error","utf8");e.writeVarIntNum(t.length),e.write(t);let r=eF("string"==typeof i.stack?i.stack:"","utf8");return e.writeVarIntNum(r.length),e.write(r),e.toArray()}}decodeProtocolID(e){let t=e.readUInt8(),r=e.readVarIntNum();return[t,e$(e.read(r))]}decodeString(e){let t=e.readVarIntNum();return e$(e.read(t))}decodeCounterparty(e){let t=e.readUInt8();return 11===t?"self":12===t?"anyone":0!==t?eK([t,...e.read(32)]):void 0}serializeDiscoveryResult(e){let t=new eZ;for(let r of(t.writeVarIntNum(e.totalCertificates),e.certificates)){let e=new r0(r.type,r.serialNumber,r.subject,r.certifier,r.revocationOutpoint,r.fields,r.signature).toBinary();t.writeVarIntNum(e.length),t.write(e);let i=eF(r.certifierInfo.name,"utf8");t.writeVarIntNum(i.length),t.write(i);let a=eF(r.certifierInfo.iconUrl,"utf8");t.writeVarIntNum(a.length),t.write(a);let n=eF(r.certifierInfo.description,"utf8");t.writeVarIntNum(n.length),t.write(n),t.writeUInt8(r.certifierInfo.trust);let s=Object.entries(r.publiclyRevealedKeyring);for(let[e,r]of(t.writeVarIntNum(s.length),s)){let i=eF(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let a=eF(r,"base64");t.writeVarIntNum(a.length),t.write(a)}let o=Object.entries(r.decryptedFields);for(let[e,r]of(t.writeVarIntNum(o.length),o)){let i=eF(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let a=eF(r,"utf8");t.writeVarIntNum(a.length),t.write(a)}}return t.toArray()}decodeKeyRelatedParams(e){let t={};t.protocolID=this.decodeProtocolID(e);let r=e.readVarIntNum();t.keyID=e$(e.read(r)),t.counterparty=this.decodeCounterparty(e);let i=e.readInt8();-1===i?t.privileged=void 0:t.privileged=1===i;let a=e.readInt8();return -1===a?t.privilegedReason=void 0:t.privilegedReason=e$(e.read(a)),t}}class ie extends r0{masterKeyring;constructor(e,t,r,i,a,n,s,o){for(let c of(super(e,t,r,i,a,n,o),Object.keys(n)))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,r,i,a){let n={},s={};for(let[o,c]of Object.entries(r)){let r=tz.fromRandom(),l=r.encrypt(eF(c,"utf8"));n[o]=eW(l);let{ciphertext:h}=await e.encrypt({plaintext:r.toArray(),...r0.getCertificateFieldEncryptionDetails(o),counterparty:t,privileged:i,privilegedReason:a});s[o]=eW(h)}return{certificateFields:n,masterKeyring:s}}static async createKeyringForVerifier(e,t,r,i,a,n,s,o,c){if(!Array.isArray(a))throw Error("fieldsToReveal must be an array of strings");let l={};for(let h of a){if(void 0===i[h]||null===i[h]||""===i[h])throw Error(`Fields to reveal must be a subset of the certificate fields. Missing the "${h}" field.`);let a=(await this.decryptField(e,n,h,i[h],t,o,c)).fieldRevelationKey,{ciphertext:d}=await e.encrypt({plaintext:a,...r0.getCertificateFieldEncryptionDetails(h,s),counterparty:r,privileged:o,privilegedReason:c});l[h]=eW(d)}return l}static async issueCertificateForSubject(e,t,r,i,a=async e=>"Certificate revocation not tracked.",n){let s=n??eW(tx(32)),{certificateFields:o,masterKeyring:c}=await this.createCertificateFields(e,t,r),l=await a(s),h=new ie(i,s,t,(await e.getPublicKey({identityKey:!0})).publicKey,l,o,c);return await h.sign(e),h}static async decryptFields(e,t,r,i,a,n){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(r))s[o]=(await this.decryptField(e,t,o,r[o],i,a,n)).decryptedFieldValue;return s}catch{throw Error("Failed to decrypt all master certificate fields.")}}static async decryptField(e,t,r,i,a,n,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:eF(t[r],"base64"),...r0.getCertificateFieldEncryptionDetails(r),counterparty:a,privileged:n,privilegedReason:s}),c=new tz(o).decrypt(eF(i,"base64"));return{fieldRevelationKey:o,decryptedFieldValue:e$(c)}}catch{throw Error("Failed to decrypt certificate field!")}}}class it extends r0{keyring;decryptedFields;constructor(e,t,r,i,a,n,s,o,c){super(e,t,r,i,a,n,o),this.keyring=s,this.decryptedFields=c}static fromCertificate(e,t){return new it(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,t,e.signature)}async decryptFields(e,t,r,i){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 a={};for(let n in this.keyring){let{plaintext:s}=await e.decrypt({ciphertext:eF(this.keyring[n],"base64"),...r0.getCertificateFieldEncryptionDetails(n,this.serialNumber),counterparty:this.subject,privileged:t,privilegedReason:r},i),o=new tz(s).decrypt(eF(this.fields[n],"base64"));a[n]=e$(o)}return a}catch(e){throw Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(e instanceof Error?e.message:e)}`)}}}class ir extends rX{keyDeriver;constructor(e){if(super(e),e instanceof rj)this.keyDeriver=e;else if("string"==typeof e||e instanceof tO)this.keyDeriver=new rG(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 ii{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,r=this.sessionNonceToSession.get(e);if(null!=r)return r;let i=this.identityKeyToNonces.get(e);if(null!=i&&0!==i.size){for(let e of i){let r=this.sessionNonceToSession.get(e);null!=r&&(null==t?t=r:(r.lastUpdate??0)>(t.lastUpdate??0)&&(t=r))}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 ia(e,t,r="self",i){let a=eF(e,"base64"),n=a.slice(0,16),s=a.slice(16),{valid:o}=await t.verifyHmac({data:n,hmac:s,protocolID:[2,"server hmac"],keyID:e$(n),counterparty:r},i);return o}async function is(e,t="self",r){let i=tx(16),{hmac:a}=await e.createHmac({protocolID:[2,"server hmac"],keyID:e$(i),data:i,counterparty:t},r);return eW([...i,...a])}let io=async(e,t,r,i)=>{let a=await e.listCertificates({certifiers:t.certifiers,types:Object.keys(t.types)},i);return await Promise.all(a.certificates.map(async a=>{let{keyringForVerifier:n}=await e.proveCertificate({certificate:a,fieldsToReveal:t.types[a.type],verifier:r},i);return new it(a.type,a.serialNumber,a.subject,a.certifier,a.revocationOutpoint,a.fields,n,a.signature)}))},ic=async(e,t,r,i)=>{if(null==t.certificates||0===t.certificates.length)throw Error("No certificates were provided in the AuthMessage.");await Promise.all(t.certificates.map(async a=>{if(a.subject!==t.identityKey)throw Error(`The subject of one of your certificates ("${a.subject}") is not the same as the request sender ("${t.identityKey}").`);let n=new it(a.type,a.serialNumber,a.subject,a.certifier,a.revocationOutpoint,a.fields,a.keyring,a.signature);if(!await n.verify())throw Error(`The signature for the certificate with serial number ${n.serialNumber} is invalid!`);if(null!=r){let{certifiers:e,types:t}=r;if(!e.includes(n.certifier))throw Error(`Certificate with serial number ${n.serialNumber} has an unrequested certifier: ${n.certifier}`);if(null==t[n.type])throw Error(`Certificate with type ${n.type} was not requested`)}await n.decryptFields(e,void 0,void 0,i)}))};class il{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;originator;constructor(e,t,r,i,a,n){this.wallet=e,this.originator=n,this.transport=t,this.certificatesToRequest=r??{certifiers:[],types:{}},this.transport.onData(this.handleIncomingMessage.bind(this)).catch(e=>{throw e}),this.sessionManager=null!=i?i:new ii,!1===a?this.autoPersistLastSession=!1:this.autoPersistLastSession=!0}async toPeer(e,t,r){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);let i=await this.getAuthenticatedSession(t,r),a=eW(tx(32)),{signature:n}=await this.wallet.createSignature({data:e,protocolID:[2,"auth message signature"],keyID:`${a} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),s={version:"0.1",messageType:"general",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,nonce:a,yourNonce:i.peerNonce,payload:e,signature:n};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(t){let e=Error(`Failed to send message to peer ${i.peerIdentityKey??"unknown"}: ${String(t.message)}`);throw e.stack=t.stack,e}}async requestCertificates(e,t,r=1e4){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);let i=await this.getAuthenticatedSession(t,r),a=eW(tx(32)),{signature:n}=await this.wallet.createSignature({data:eF(JSON.stringify(e),"utf8"),protocolID:[2,"auth message signature"],keyID:`${a} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),s={version:"0.1",messageType:"certificateRequest",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,nonce:a,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,requestedCertificates:e,signature:n};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(e){throw Error(`Failed to send certificate request message to peer ${i.peerIdentityKey??"unknown"}: ${String(e.message)}`)}}async getAuthenticatedSession(e,t){let r;if(void 0===this.transport)throw Error("Peer transport is not connected!");if("string"==typeof e&&(r=this.sessionManager.getSession(e)),null==r||!r.isAuthenticated){let i=await this.initiateHandshake(e,t);if(null==(r=this.sessionManager.getSession(i))||!r.isAuthenticated)throw Error("Unable to establish mutual authentication with peer!")}return r}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,t=1e4){let r=await is(this.wallet,void 0,this.originator),i=Date.now();this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:r,peerIdentityKey:e,lastUpdate:i});let a={version:"0.1",messageType:"initialRequest",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,initialNonce:r,requestedCertificates:this.certificatesToRequest};return await this.transport.send(a),await this.waitForInitialResponse(r,t)}async waitForInitialResponse(e,t=1e4){return await new Promise((r,i)=>{let a=this.listenForInitialResponse(e,e=>{clearTimeout(n),this.stopListeningForInitialResponses(a),r(e)}),n=setTimeout(()=>{this.stopListeningForInitialResponses(a),i(Error("Initial response timed out."))},t)})}listenForInitialResponse(e,t){let r=this.callbackIdCounter++;return this.onInitialResponseReceivedCallbacks.set(r,{callback:t,sessionNonce:e}),r}stopListeningForInitialResponses(e){this.onInitialResponseReceivedCallbacks.delete(e)}async handleIncomingMessage(e){if("string"!=typeof e.version||"0.1"!==e.version)throw Error(`Invalid or unsupported message auth version! Received: ${e.version}, expected: 0.1`);switch(e.messageType){case"initialRequest":await this.processInitialRequest(e);break;case"initialResponse":await this.processInitialResponse(e);break;case"certificateRequest":await this.processCertificateRequest(e);break;case"certificateResponse":await this.processCertificateResponse(e);break;case"general":await this.processGeneralMessage(e);break;default:throw Error(`Unknown message type of ${String(e.messageType)} from ${String(e.identityKey)}`)}}async processInitialRequest(e){let t;if("string"!=typeof e.identityKey||"string"!=typeof e.initialNonce||""===e.initialNonce)throw Error("Missing required fields in initialRequest message.");let r=await is(this.wallet,void 0,this.originator),i=Date.now();this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:r,peerNonce:e.initialNonce,peerIdentityKey:e.identityKey,lastUpdate:i}),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)}):t=await io(this.wallet,e.requestedCertificates,e.identityKey,this.originator));let{signature:a}=await this.wallet.createSignature({data:eF(e.initialNonce+r,"base64"),protocolID:[2,"auth message signature"],keyID:`${e.initialNonce} ${r}`,counterparty:e.identityKey},this.originator),n={version:"0.1",messageType:"initialResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,initialNonce:r,yourNonce:e.initialNonce,certificates:t,requestedCertificates:this.certificatesToRequest,signature:a};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=e.identityKey),await this.transport.send(n)}async processInitialResponse(e){if(!await ia(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 r=eF((t.sessionNonce??"")+(e.initialNonce??""),"base64"),{valid:i}=await this.wallet.verifySignature({data:r,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${t.sessionNonce??""} ${e.initialNonce??""}`,counterparty:e.identityKey},this.originator);if(!i)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.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.certificatesToRequest?.certifiers?.length>0&&e.certificates?.length>0&&(await ic(this.wallet,e,this.certificatesToRequest,this.originator),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 io(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async processCertificateRequest(e){if(!await ia(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:r}=await this.wallet.verifySignature({data:eF(JSON.stringify(e.requestedCertificates),"utf8"),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!r)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 io(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async sendCertificateResponse(e,t){let r=await this.getAuthenticatedSession(e),i=eW(tx(32)),{signature:a}=await this.wallet.createSignature({data:eF(JSON.stringify(t),"utf8"),protocolID:[2,"auth message signature"],keyID:`${i} ${r.peerNonce??""}`,counterparty:r.peerIdentityKey},this.originator),n={version:"0.1",messageType:"certificateResponse",identityKey:(await this.wallet.getPublicKey({identityKey:!0},this.originator)).publicKey,nonce:i,initialNonce:r.sessionNonce,yourNonce:r.peerNonce,certificates:t,signature:a};r.lastUpdate=Date.now(),this.sessionManager.updateSession(r);try{await this.transport.send(n)}catch(t){let e=t instanceof Error?t.message:String(t);throw Error(`Failed to send certificate response message to peer ${r.peerIdentityKey??"unknown"}: ${e}`)}}async processCertificateResponse(e){if(!await ia(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:r}=await this.wallet.verifySignature({data:eF(JSON.stringify(e.certificates),"utf8"),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:e.identityKey},this.originator);if(!r)throw Error(`Unable to verify certificate response signature for peer: ${e.identityKey}`);await ic(this.wallet,e,e.requestedCertificates,this.originator),this.onCertificatesReceivedCallbacks.forEach(t=>{t(e.identityKey,e.certificates??[])}),t.lastUpdate=Date.now(),this.sessionManager.updateSession(t)}async processGeneralMessage(e){if(!await ia(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{valid:r}=await this.wallet.verifySignature({data:e.payload,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!r)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??[])})}}let ih="undefined"!=typeof window?fetch.bind(window):fetch;class id{onDataCallback;fetchClient;baseUrl;constructor(e,t=ih){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,r)=>{(async()=>{try{let r=this.fetchClient(`${this.baseUrl}/.well-known/auth`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});"initialRequest"!==e.messageType&&t();let i=await r;if(i.ok&&null!=this.onDataCallback){let e=await i.json();this.onDataCallback(e)}else throw Error("HTTP server failed to authenticate");"initialRequest"===e.messageType&&t()}catch(e){r(e)}})()});{let t=this.deserializeRequestPayload(e.payload),r=`${this.baseUrl}${t.urlPostfix}`;if("object"!=typeof t.headers&&(t.headers={}),t.headers["x-bsv-auth-version"]=e.version,t.headers["x-bsv-auth-identity-key"]=e.identityKey,t.headers["x-bsv-auth-nonce"]=e.nonce,t.headers["x-bsv-auth-your-nonce"]=e.yourNonce,t.headers["x-bsv-auth-signature"]=eK(e.signature),t.headers["x-bsv-auth-request-id"]=t.requestId,null!=t.body){let e=t.headers;if(null==e["content-type"])throw Error("Content-Type header is required for requests with a body.");let r=String(e["content-type"]??"");r.includes("application/json")||r.includes("application/x-www-form-urlencoded")||r.includes("text/plain")?t.body=e$(t.body):t.body=new Uint8Array(t.body)}let i=await this.fetchClient(r,{method:t.method,headers:t.headers,body:t.body});if(500===i.status&&null==i.headers.get("x-bsv-auth-request-id")&&null==i.headers.get("x-bsv-auth-requested-certificates")){let e=await i.json();throw Error(`HTTP ${i.status} - ${JSON.stringify(e)}`)}let a=await i.arrayBuffer(),n=new eZ;null!=i.headers.get("x-bsv-auth-request-id")&&n.write(eF(i.headers.get("x-bsv-auth-request-id"),"base64")),n.writeVarIntNum(i.status);let s=[];i.headers.forEach((e,t)=>{let r=t.toLowerCase();(r.startsWith("x-bsv-")||"authorization"===r)&&!r.startsWith("x-bsv-auth")&&s.push([r,e])}),s.sort(([e],[t])=>e.localeCompare(t)),n.writeVarIntNum(s.length);for(let e=0;e<s.length;e++){let t=eF(s[e][0],"utf8");n.writeVarIntNum(t.length),n.write(t);let r=eF(s[e][1],"utf8");n.writeVarIntNum(r.length),n.write(r)}if(null!=a){let e=Array.from(new Uint8Array(a));n.writeVarIntNum(e.length),n.write(e)}else n.writeVarIntNum(-1);let o={version:i.headers.get("x-bsv-auth-version"),messageType:"certificateRequest"===i.headers.get("x-bsv-auth-message-type")?"certificateRequest":"general",identityKey:i.headers.get("x-bsv-auth-identity-key"),nonce:i.headers.get("x-bsv-auth-nonce"),yourNonce:i.headers.get("x-bsv-auth-your-nonce"),requestedCertificates:JSON.parse(i.headers.get("x-bsv-auth-requested-certificates")),payload:n.toArray(),signature:eF(i.headers.get("x-bsv-auth-signature"),"hex")};if(null==o.version)throw Error("HTTP server failed to authenticate");this.onDataCallback(o)}}async onData(e){this.onDataCallback=t=>{e(t)}}deserializeRequestPayload(e){let t,r=new eQ(e),i=eW(r.read(32)),a=r.readVarIntNum(),n="GET";a>0&&(n=e$(r.read(a)));let s=r.readVarIntNum(),o="";s>0&&(o=e$(r.read(s)));let c=r.readVarIntNum(),l="";c>0&&(l=e$(r.read(c)));let h={},d=r.readVarIntNum();if(d>0)for(let e=0;e<d;e++){let e=r.readVarIntNum(),t=e$(r.read(e)),i=r.readVarIntNum(),a=e$(r.read(i));h[t]=a}let u=r.readVarIntNum();return u>0&&(t=r.read(u)),{urlPostfix:o+l,method:n,headers:h,body:t,requestId:i}}}class iu{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;originator;peers={};constructor(e,t,r,i){this.wallet=e,this.requestedCertificates=t,this.sessionManager=r??new ii,this.originator=i}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 r=await new Promise(async(r,i)=>{try{let a,{method:n="GET",headers:s={},body:o}=t,c=new URL(e),l=c.origin;if(void 0===this.peers[l]){let e=new id(l);a={peer:new il(this.wallet,e,this.requestedCertificates,this.sessionManager,void 0,this.originator),pendingCertificateRequests:[]},this.peers[l]=a,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 r=await io(this.wallet,t,e,this.originator);await this.peers[l].peer.sendCertificateResponse(e,r)}finally{await new Promise(e=>setTimeout(e,500)),this.peers[l].pendingCertificateRequests.shift()}})}else{if(!1===this.peers[l].supportsMutualAuth){try{let i=await this.handleFetchAndValidate(e,t,this.peers[l]);r(i)}catch(e){i(e)}return}a=this.peers[l]}let h=tx(32),d=eW(h),u=await this.serializeRequest(n,s,o,c,h);this.callbacks[d]={resolve:r,reject:i};let f=a.peer.listenForGeneralMessages((e,t)=>{let r,i=new eQ(t);if(eW(i.read(32))!==d)return;a.peer.stopListeningForGeneralMessages(f),this.peers[l].identityKey=e,this.peers[l].supportsMutualAuth=!0;let n=i.readVarIntNum(),s={},o=i.readVarIntNum();if(o>0)for(let e=0;e<o;e++){let e=i.readVarIntNum(),t=i.read(e),r=e$(t),a=i.readVarIntNum(),n=i.read(a),o=e$(n);s[r]=o}s["x-bsv-auth-identity-key"]=e;let c=i.readVarIntNum();c>0&&(r=i.read(c));let h=new Response(r?new Uint8Array(r):null,{status:n,statusText:`${n}`,headers:new Headers(s)});this.callbacks[d].resolve(h),delete this.callbacks[d]});a.pendingCertificateRequests.length>0&&await new Promise(e=>{setInterval(()=>{0===a.pendingCertificateRequests.length&&e()},100)}),await a.peer.toPeer(u.toArray(),a.identityKey).catch(async n=>{if(n.message.includes("Session not found for nonce")){delete this.peers[l],t.retryCounter??=3;let i=await this.fetch(e,t);r(i);return}if(n.message.includes("HTTP server failed to authenticate"))try{let i=await this.handleFetchAndValidate(e,t,a);r(i);return}catch(e){i(e)}else i(n)})}catch(e){i(e)}});return 402===r.status?await this.handlePaymentAndRetry(e,t,r):r}async sendCertificateRequest(e,t){let r,i=new URL(e).origin;if(void 0!==this.peers[i])r={peer:this.peers[i].peer};else{let e=new id(i);r={peer:new il(this.wallet,e,this.requestedCertificates,this.sessionManager,this.originator)},this.peers[i]=r}return await new Promise(async(e,i)=>{let a=r.peer.listenForCertificatesReceived((t,i)=>{r.peer.stopListeningForCertificatesReceived(a),this.certificatesReceived.push(...i),e(i)});try{await r.peer.requestCertificates(t,r.identityKey)}catch(e){r.peer.stopListeningForCertificatesReceived(a),i(e)}})}consumeReceivedCertificates(){return this.certificatesReceived.splice(0)}async serializeRequest(e,t,r,i,a){let n=new eZ;if(n.write(a),n.writeVarIntNum(e.length),n.write(eF(e)),i.pathname.length>0){let e=eF(i.pathname);n.writeVarIntNum(e.length),n.write(e)}else n.writeVarIntNum(-1);if(i.search.length>0){let e=eF(i.search);n.writeVarIntNum(e.length),n.write(e)}else n.writeVarIntNum(-1);let s=[];for(let[e,r]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,r])}else if(e.startsWith("content-type"))r=r.split(";")[0].trim(),s.push([e,r]);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)),n.writeVarIntNum(s.length);for(let e=0;e<s.length;e++){let t=eF(s[e][0],"utf8");n.writeVarIntNum(t.length),n.write(t);let r=eF(s[e][1],"utf8");n.writeVarIntNum(r.length),n.write(r)}if(["POST","PUT","PATCH","DELETE"].includes(e.toUpperCase())&&void 0===r){let e=s.find(([e])=>"content-type"===e);r=e&&e[1].includes("application/json")?"{}":""}if(r){let e=await this.normalizeBodyToNumberArray(r);n.writeVarIntNum(e.length),n.write(e)}else n.writeVarIntNum(-1);return n}async handleFetchAndValidate(e,t,r){let i=await fetch(e,t);if(i.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!")}),i.ok)return r.supportsMutualAuth=!1,i;throw Error(`Request failed with status: ${i.status}`)}async handlePaymentAndRetry(e,t={},r){let i=r.headers.get("x-bsv-payment-version");if(!i||"1.0"!==i)throw Error(`Unsupported x-bsv-payment-version response header. Client version: 1.0, Server version: ${i}`);let a=r.headers.get("x-bsv-payment-satoshis-required");if(!a)throw Error("Missing x-bsv-payment-satoshis-required response header.");let n=parseInt(a);if(isNaN(n)||n<=0)throw Error("Invalid x-bsv-payment-satoshis-required response header value.");let s=r.headers.get("x-bsv-auth-identity-key");if("string"!=typeof s)throw Error("Missing x-bsv-auth-identity-key response header.");let o=r.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=await is(this.wallet,void 0,this.originator),{publicKey:l}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${o} ${c}`,counterparty:s},this.originator),h=new t3().lock(tv.fromString(l).toAddress()).toHex(),{tx:d}=await this.wallet.createAction({description:`Payment for request to ${new URL(e).origin}`,outputs:[{satoshis:n,lockingScript:h,customInstructions:JSON.stringify({derivationPrefix:o,derivationSuffix:c,payee:s}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}},this.originator);return t.headers=t.headers||{},t.headers["x-bsv-payment"]=JSON.stringify({derivationPrefix:o,derivationSuffix:c,transaction:eW(d)}),t.retryCounter??=3,this.fetch(e,t)}async normalizeBodyToNumberArray(e){if(null==e)return[];if("object"==typeof e)return eF(JSON.stringify(e,"utf8"));if(Array.isArray(e)&&e.every(e=>"number"==typeof e))return e;if("string"==typeof e)return eF(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,r)=>{t.push([r,e.toString()])}),eF(new URLSearchParams(t).toString(),"utf8")}if(e instanceof URLSearchParams)return eF(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 ip{pushDrop;static decode(e){let t=t7.decode(e);if(t.fields.length<4)throw Error("Invalid SHIP/SLAP advertisement!");let r=e$(t.fields[0]);if("SHIP"!==r&&"SLAP"!==r)throw Error("Invalid protocol type!");let i=eK(t.fields[1]);return{protocol:r,identityKey:i,domain:e$(t.fields[2]),topicOrService:e$(t.fields[3])}}constructor(e){this.pushDrop=new t7(e)}async lock(e,t,r){let{publicKey:i}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([eF(e,"utf8"),eF(i,"hex"),eF(t,"utf8"),eF(r,"utf8")],[2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}unlock(e){return this.pushDrop.unlock([2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}}let ib="undefined"!=typeof window?fetch.bind(window):fetch,ig=["https://overlay-us-1.bsvb.tech","https://overlay-eu-1.bsvb.tech","https://overlay-ap-1.bsvb.tech","https://users.bapp.dev"],im=["https://testnet-users.bapp.dev"];class iy{fetchClient;allowHTTP;constructor(e=ib,t=!1){this.fetchClient=e,this.allowHTTP=t}async lookup(e,t,r=5e3){if(!e.startsWith("https:")&&!this.allowHTTP)throw Error('HTTPS facilitator can only use URLs that start with "https:"');let i="undefined"!=typeof AbortController?new AbortController:void 0,a=setTimeout(()=>{try{i?.abort()}catch{}},r);try{let r={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:t.service,query:t.query}),signal:i?.signal},a=await this.fetchClient(`${e}/lookup`,r);if(!a.ok)throw Error(`Failed to facilitate lookup (HTTP ${a.status})`);return await a.json()}catch(e){if(e?.name==="AbortError")throw Error("Request timed out");throw e}finally{clearTimeout(a)}}}class iw{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;hostsCache;hostsInFlight;hostsTtlMs;hostsMaxEntries;txMemo;txMemoTtlMs;constructor(e={}){this.networkPreset=e.networkPreset??"mainnet",this.facilitator=e.facilitator??new iy(void 0,"local"===this.networkPreset),this.slapTrackers=e.slapTrackers??("mainnet"===this.networkPreset?ig:im),this.hostOverrides=e.hostOverrides??{},this.additionalHosts=e.additionalHosts??{},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 r=[];if(r="ls_slap"===e.service?"local"===this.networkPreset?["http://localhost:8080"]:this.slapTrackers:null!=this.hostOverrides[e.service]?this.hostOverrides[e.service]:"local"===this.networkPreset?["http://localhost:8080"]:await this.getCompetentHostsCached(e.service),this.additionalHosts[e.service]?.length>0){let t=this.additionalHosts[e.service],i=new Set(r);for(let e of t)i.has(e)||r.push(e)}if(r.length<1)throw Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${e.service}`);let i=await Promise.allSettled(r.map(async r=>await this.facilitator.lookup(r,e,t))),a=new Map,n=e=>"object"!=typeof e?"":e.join(",");for(let e of i){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=n(e.beef),r=this.txMemo.get(t),i=Date.now();if("object"!=typeof r||null===r||r.expiresAt<=i)try{r={txId:rg.fromBEEF(e.beef).id("hex"),expiresAt:i+this.txMemoTtlMs},this.txMemo.size>4096&&this.evictOldest(this.txMemo),this.txMemo.set(t,r)}catch{continue}let s=`${r.txId}.${e.outputIndex}`;a.set(s,e)}}return{type:"output-list",outputs:Array.from(a.values())}}async getCompetentHostsCached(e){let t=Date.now(),r=this.hostsCache.get(e);if("object"==typeof r&&r.expiresAt>t)return r.hosts.slice();if("object"==typeof r&&r.expiresAt<=t)return this.hostsInFlight.has(e)||this.hostsInFlight.set(e,this.refreshHosts(e).finally(()=>{this.hostsInFlight.delete(e)})),r.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 i=this.refreshHosts(e).finally(()=>{this.hostsInFlight.delete(e)});return this.hostsInFlight.set(e,i),(await i).slice()}async refreshHosts(e){let t=await this.findCompetentHosts(e),r=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:r}),t}async findCompetentHosts(e){let t={service:"ls_slap",query:{service:e}},r=await Promise.allSettled(this.slapTrackers.map(async e=>await this.facilitator.lookup(e,t,5e3))),i=new Set;for(let t of r){if("fulfilled"!==t.status)continue;let r=t.value;if("output-list"===r.type)for(let t of r.outputs)try{let r=rg.fromBEEF(t.beef),a=r.outputs[t.outputIndex]?.lockingScript;if("object"!=typeof a||null===a)continue;let n=ip.decode(a);if(n.topicOrService!==e||"SLAP"!==n.protocol)continue;"string"==typeof n.domain&&n.domain.length>0&&i.add(n.domain)}catch{continue}}return[...i]}evictOldest(e){let t=e.keys().next().value;void 0!==t&&e.delete(t)}}class iI{httpClient;allowHTTP;constructor(e=fetch,t=!1){this.httpClient=e,this.allowHTTP=t}async send(e,t){let r;if(!e.startsWith("https:")&&!this.allowHTTP)throw Error('HTTPS facilitator can only use URLs that start with "https:"');let i={"Content-Type":"application/octet-stream","X-Topics":JSON.stringify(t.topics)};if(Array.isArray(t.offChainValues)){i["x-includes-off-chain-values"]="true";let e=new eZ;e.writeVarIntNum(t.beef.length),e.write(t.beef),e.write(t.offChainValues),r=new Uint8Array(e.toArray())}else r=new Uint8Array(t.beef);let a=await fetch(`${e}/submit`,{method:"POST",headers:i,body:r});if(a.ok)return await a.json();throw Error("Failed to facilitate broadcast")}}class iv{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 iI(void 0,"local"===this.networkPreset),this.resolver=t.resolver??new iw({networkPreset:this.networkPreset}),this.requireAcknowledgmentFromAllHostsForTopics=t.requireAcknowledgmentFromAllHostsForTopics??[],this.requireAcknowledgmentFromAnyHostForTopics=t.requireAcknowledgmentFromAnyHostForTopics??"all",this.requireAcknowledgmentFromSpecificHostsForTopics=t.requireAcknowledgmentFromSpecificHostsForTopics??{}}async broadcast(e){let t,r,i,a,n,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,r])=>{try{let i=await this.facilitator.send(e,{beef:t,offChainValues:s,topics:[...r]});if(null==i||0===Object.keys(i).length)throw Error("Steak has no topics.");return{host:e,success:!0,steak:i}}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,r=e.steak,i=new Set;for(let[e,t]of Object.entries(r)){let r=t.outputsToAdmit,a=t.coinsToRetain,n=t.coinsRemoved;(r?.length>0||a?.length>0||n?.length>0)&&i.add(e)}h[t]=i}return("all"===this.requireAcknowledgmentFromAllHostsForTopics?(r=this.topics,i="all"):"any"===this.requireAcknowledgmentFromAllHostsForTopics?(r=this.topics,i="any"):(r=Array.isArray(this.requireAcknowledgmentFromAllHostsForTopics)?this.requireAcknowledgmentFromAllHostsForTopics:this.topics,i="all"),r.length>0&&!this.checkAcknowledgmentFromAllHosts(h,r,i))?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ALL_HOSTS_FAILED",description:"Not all hosts acknowledged the required topics."}:("all"===this.requireAcknowledgmentFromAnyHostForTopics?(a=this.topics,n="all"):"any"===this.requireAcknowledgmentFromAnyHostForTopics?(a=this.topics,n="any"):(a=Array.isArray(this.requireAcknowledgmentFromAnyHostForTopics)?this.requireAcknowledgmentFromAnyHostForTopics:[],n="all"),a.length>0&&!this.checkAcknowledgmentFromAnyHost(h,a,n))?{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,r){for(let i of Object.values(e))if("all"===r){for(let e of t)if(!i.has(e))return!1}else if("any"===r){let e=!1;for(let r of t)if(i.has(r)){e=!0;break}if(!e)return!1}return!0}checkAcknowledgmentFromAnyHost(e,t,r){if("all"===r){for(let r of Object.values(e)){let e=!0;for(let i of t)if(!r.has(i)){e=!1;break}if(e)return!0}return!1}for(let r of Object.values(e))for(let e of t)if(r.has(e))return!0;return!1}checkAcknowledgmentFromSpecificHosts(e,t){for(let[r,i]of Object.entries(t)){let t,a,n=e[r];if(null==n)return!1;if("all"===i||"any"===i)a=i,t=this.topics;else{if(!Array.isArray(i))continue;t=i,a="all"}if("all"===a){for(let e of t)if(!n.has(e))return!1}else if("any"===a){let e=!1;for(let r of t)if(n.has(r)){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 r of t.outputs)try{let t=rg.fromBEEF(r.beef).outputs[r.outputIndex].lockingScript,i=ip.decode(t);if(!this.topics.includes(i.topicOrService)||"SHIP"!==i.protocol)continue;void 0===e[i.domain]&&(e[i.domain]=new Set),e[i.domain].add(i.topicOrService)}catch(e){continue}return e}}let ik=e=>(e.toLowerCase().startsWith("uhrp:")&&(e=e.slice(5)),e.startsWith("//")&&(e=e.slice(2)),e),iS=e=>{if(32!==e.length)throw Error("Hash length must be 32 bytes (sha256)");return eY(e,eF("ce00","hex"))},ix=e=>{let t=e instanceof Uint8Array?e:Uint8Array.from(e),r=new D;for(let e=0;e<t.length;e+=1048576){let i=t.subarray(e,e+1048576);r.update(Array.from(i))}return iS(r.digest())},iE=e=>{let{data:t,prefix:r}=eJ(e=ik(e),void 0,2);if(32!==t.length)throw Error("Invalid length!");if("ce00"!==eK(r))throw Error("Bad prefix");return t},iN=e=>{try{return iE(e),!0}catch(e){return!1}};class iP{authFetch;baseURL;constructor(e){this.baseURL=e.storageURL,this.authFetch=new iu(e.wallet)}async getUploadInfo(e,t){let r=`${this.baseURL}/upload`,i=await this.authFetch.fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileSize:e,retentionPeriod:t})});if(!i.ok)throw Error(`Upload info request failed: HTTP ${i.status}`);let a=await i.json();if("error"===a.status)throw Error("Upload route returned an error.");return{uploadURL:a.uploadURL,requiredHeaders:a.requiredHeaders,amount:a.amount}}async uploadFile(e,t,r){let i=t.data instanceof Uint8Array?t.data:Uint8Array.from(t.data),a=await fetch(e,{method:"PUT",body:i,headers:{"Content-Type":t.type,...r}});if(!a.ok)throw Error(`File upload failed: HTTP ${a.status}`);return{published:!0,uhrpURL:ix(i)}}async publishFile(e){let{file:t,retentionPeriod:r}=e,i=t.data instanceof Uint8Array?t.data:Uint8Array.from(t.data),a=i.byteLength,{uploadURL:n,requiredHeaders:s}=await this.getUploadInfo(a,r);return await this.uploadFile(n,{data:i,type:t.type},s)}async findFile(e){let t=new URL(`${this.baseURL}/find`);t.searchParams.set("uhrpUrl",e);let r=await this.authFetch.fetch(t.toString(),{method:"GET"});if(!r.ok)throw Error(`findFile request failed: HTTP ${r.status}`);let i=await r.json();if("error"===i.status){let e=i.code??"unknown-code",t=i.description??"no-description";throw Error(`findFile returned an error: ${e} - ${t}`)}return i.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 r=await t.json();if("error"===r.status){let e=r.code??"unknown-code",t=r.description??"no-description";throw Error(`listUploads returned an error: ${e} - ${t}`)}return r.uploads}async renewFile(e,t){let r=`${this.baseURL}/renew`,i=await this.authFetch.fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({uhrpUrl:e,additionalMinutes:t})});if(!i.ok)throw Error(`renewFile request failed: HTTP ${i.status}`);let a=await i.json();if("error"===a.status){let e=a.code??"unknown-code",t=a.description??"no-description";throw Error(`renewFile returned an error: ${e} - ${t}`)}return{status:a.status,prevExpiryTime:a.prevExpiryTime,newExpiryTime:a.newExpiryTime,amount:a.amount}}}class iO{networkPreset="mainnet";lookupResolver;constructor(e){this.networkPreset=e?.networkPreset??"mainnet",this.lookupResolver=new iw({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 r=[],i=Math.floor(Date.now()/1e3);for(let e=0;e<t.outputs.length;e++){let a=rg.fromBEEF(t.outputs[e].beef),{fields:n}=t7.decode(a.outputs[t.outputs[e].outputIndex].lockingScript);new eQ(n[3]).readVarIntNum()<i||r.push(e$(n[2]))}return r}async download(e){if(!iN(e))throw Error("Invalid parameter UHRP url");let t=eK(iE(e)),r=await this.resolve(e);if(!Array.isArray(r)||0===r.length)throw Error("No one currently hosts this file!");for(let e=0;e<r.length;e++)try{let i=await fetch(r[e],{method:"GET"});if(!i.ok||i.status>=400||null==i.body)continue;let a=i.body.getReader(),n=new D,s=[],o=0;for(;;){let{done:e,value:t}=await a.read();if(e)break;n.update(Array.from(t)),s.push(t),o+=t.length}if(eK(n.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:i.headers.get("Content-Type")}}catch(e){continue}throw Error(`Unable to download content from ${e}`)}}let i_={name:"Unknown Identity",avatarURL:"XUUB8bbn9fEthk15Ge3zTQXypUShfC94vFjp65v7u5CQ8qkpxzst",identityKey:"",abbreviatedKey:"",badgeIconURL:"XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",badgeLabel:"Not verified by anyone you trust.",badgeClickURL:"https://projectbabbage.com/docs/unknown-identity"},iA={protocolID:[1,"identity"],keyID:"1",tokenAmount:1,outputIndex:0},iT={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="},iC=[2,"contact"];class iR{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 iV{wallet;cache=new iR;CONTACTS_CACHE_KEY="metanet-contacts";constructor(e){this.wallet=e??new r7}async getContacts(e,t=!1,r=1e3){if(!t){let t=this.cache.getItem(this.CONTACTS_CACHE_KEY);if(null!=t&&""!==t)try{let r=JSON.parse(t);return null!=e?r.filter(t=>t.identityKey===e):r}catch(e){console.warn("Invalid cached contacts JSON; will reload from chain",e)}}let i=[];if(null!=e){let{hmac:t}=await this.wallet.createHmac({protocolID:iC,keyID:e,counterparty:"self",data:eF(e,"utf8")});i.push(`identityKey ${eK(t)}`)}let a=await this.wallet.listOutputs({basket:"contacts",include:"locking scripts",includeCustomInstructions:!0,tags:i,limit:r});if(null==a.outputs||0===a.outputs.length)return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify([])),[];let n=[];for(let e of a.outputs)try{if(null==e.lockingScript)continue;let t=t7.decode(tJ.fromHex(e.lockingScript));if(null==e.customInstructions)continue;let r=JSON.parse(e.customInstructions).keyID,{plaintext:i}=await this.wallet.decrypt({ciphertext:t.fields[0],protocolID:iC,keyID:r,counterparty:"self"}),a=JSON.parse(e$(i));n.push(a)}catch(e){console.warn("ContactsManager: Failed to decode contact output:",e)}return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(n)),null!=e?n.filter(t=>t.identityKey===e):n}async saveContact(e,t){let r,i=this.cache.getItem(this.CONTACTS_CACHE_KEY),a=(r=null!=i&&""!==i?JSON.parse(i):await this.getContacts()).findIndex(t=>t.identityKey===e.identityKey),n={...e,metadata:t};a>=0?r[a]=n:r.push(n);let{hmac:s}=await this.wallet.createHmac({protocolID:iC,keyID:e.identityKey,counterparty:"self",data:eF(e.identityKey,"utf8")}),o=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:[`identityKey ${eK(s)}`],limit:100}),c=null,l=eW(tx(32));if(null!=o.outputs)for(let t of o.outputs)try{let[r,i]=t.outpoint.split("."),a=rg.fromBEEF(o.BEEF,r),n=t7.decode(a.outputs[Number(i)].lockingScript);if(null==t.customInstructions)continue;l=JSON.parse(t.customInstructions).keyID;let{plaintext:s}=await this.wallet.decrypt({ciphertext:n.fields[0],protocolID:iC,keyID:l,counterparty:"self"});if(JSON.parse(e$(s)).identityKey===e.identityKey){c=t;break}}catch(e){}let h={...e,metadata:t},{ciphertext:d}=await this.wallet.encrypt({plaintext:eF(JSON.stringify(h),"utf8"),protocolID:iC,keyID:l,counterparty:"self"}),u=await new t7(this.wallet).lock([d],iC,l,"self");if(null!=c){let[t,r]=String(c.outpoint).split("."),i=`${t}.${r}`,a=new t7(this.wallet),{signableTransaction:n}=await this.wallet.createAction({description:"Update Contact",inputBEEF:o.BEEF,inputs:[{outpoint:i,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 ${eK(s)}`],customInstructions:JSON.stringify({keyID:l})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}});if(null==n)throw Error("Unable to update contact");let h=a.unlock(iC,l,"self"),d=await h.sign(rg.fromBEEF(n.tx),0),{tx:f}=await this.wallet.signAction({reference:n.reference,spends:{0:{unlockingScript:d.toHex()}}});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 ${eK(s)}`],customInstructions:JSON.stringify({keyID:l})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}});if(null==t)throw Error("Failed to create contact output")}this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(r))}async removeContact(e){let t=this.cache.getItem(this.CONTACTS_CACHE_KEY);if(null!=t&&""!==t)try{let r=JSON.parse(t).filter(t=>t.identityKey!==e);this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(r))}catch(e){console.warn("Failed to update cache after contact removal:",e)}let r=[],{hmac:i}=await this.wallet.createHmac({protocolID:iC,keyID:e,counterparty:"self",data:eF(e,"utf8")});r.push(`identityKey ${eK(i)}`);let a=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:r,limit:100});if(null!=a.outputs)for(let t of a.outputs)try{let[r,i]=String(t.outpoint).split("."),n=rg.fromBEEF(a.BEEF,r),s=t7.decode(n.outputs[Number(i)].lockingScript);if(null==t.customInstructions)continue;let o=JSON.parse(t.customInstructions).keyID,{plaintext:c}=await this.wallet.decrypt({ciphertext:s.fields[0],protocolID:iC,keyID:o,counterparty:"self"});if(JSON.parse(e$(c)).identityKey===e){let e=`${r}.${i}`,t=new t7(this.wallet),{signableTransaction:n}=await this.wallet.createAction({description:"Delete Contact",inputBEEF:a.BEEF,inputs:[{outpoint:e,unlockingScriptLength:74,inputDescription:"Spend contact output to delete"}],outputs:[],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}});if(null==n)throw Error("Unable to delete contact");let s=t.unlock(iC,o,"self"),c=await s.sign(rg.fromBEEF(n.tx),0),{tx:l}=await this.wallet.signAction({reference:n.reference,spends:{0:{unlockingScript:c.toHex()}}});if(null==l)throw Error("Failed to delete contact output");return}}catch(e){}}}class iU{options;originator;authClient;wallet;contactsManager;constructor(e,t=iA,r){this.options=t,this.originator=r,this.wallet=e??new r7,this.authClient=new iu(this.wallet),this.contactsManager=new iV(this.wallet)}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 r0(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:r}=await this.wallet.proveCertificate({certificate:e,fieldsToReveal:t,verifier:new tO(1).toPublicKey().toString()}),i=await new t7(this.wallet).lock([eF(JSON.stringify({...e,keyring:r}))],this.options.protocolID,this.options.keyID,"anyone",!0,!0),{tx:a}=await this.wallet.createAction({description:"Create a new Identity Token",outputs:[{satoshis:this.options.tokenAmount,lockingScript:i.toHex(),outputDescription:"Identity Token"}],options:{randomizeOutputs:!1}});if(void 0!==a){let e=new iv(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network});return await e.broadcast(rg.fromAtomicBEEF(a))}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:r}=await this.wallet.discoverByIdentityKey(e,this.originator);return r.map(e=>iU.parseIdentity(e))}async resolveByAttributes(e,t=!0){let[r,i]=await Promise.all([t?this.contactsManager.getContacts():Promise.resolve([]),this.wallet.discoverByAttributes(e,this.originator)]),a=new Map(r.map(e=>[e.identityKey,e]));return(i?.certificates??[]).map(e=>a.get(e.subject)??iU.parseIdentity(e))}async getContacts(e,t=!1,r=1e3){return await this.contactsManager.getContacts(e,t,r)}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,r,i,a,n,{type:s,decryptedFields:o,certifierInfo:c}=e;switch(s){case iT.xCert:t=o.userName,r=o.profilePhoto,i=`X account certified by ${c.name}`,a=c.iconUrl,n="https://socialcert.net";break;case iT.discordCert:t=o.userName,r=o.profilePhoto,i=`Discord account certified by ${c.name}`,a=c.iconUrl,n="https://socialcert.net";break;case iT.emailCert:t=o.email,r="XUTZxep7BBghAJbSBwTjNfmcsDdRFs5EaGEgkESGSgjJVYgMEizu",i=`Email certified by ${c.name}`,a=c.iconUrl,n="https://socialcert.net";break;case iT.phoneCert:t=o.phoneNumber,r="XUTLxtX3ELNUwRhLwL7kWNGbdnFM8WG2eSLv84J7654oH8HaJWrU",i=`Phone certified by ${c.name}`,a=c.iconUrl,n="https://socialcert.net";break;case iT.identiCert:t=`${o.firstName} ${o.lastName}`,r=o.profilePhoto,i=`Government ID certified by ${c.name}`,a=c.iconUrl,n="https://identicert.me";break;case iT.registrant:t=o.name,r=o.icon,i=`Entity certified by ${c.name}`,a=c.iconUrl,n="https://projectbabbage.com/docs/registrant";break;case iT.coolCert:t="true"===o.cool?"Cool Person!":"Not cool!";break;case iT.anyone:t="Anyone",r="XUT4bpQ6cpBaXi1oMzZsXfpkWGbtp2JTUYAoN7PzhStFJ6wLfoeR",i="Represents the ability for anyone to access this information.",a="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",n="https://projectbabbage.com/docs/anyone-identity";break;case iT.self:t="You",r="XUT9jHGk2qace148jeCX5rDsMftkSGYKmigLwU2PLLBc7Hm63VYR",i="Represents your ability to access this information.",a="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",n="https://projectbabbage.com/docs/self-identity";break;default:t=i_.name,r=o.profilePhoto,i=i_.badgeLabel,a=i_.badgeIconURL,n=i_.badgeClickURL}return{name:t,avatarURL:r,abbreviatedKey:e.subject.length>0?`${e.subject.substring(0,10)}...`:"",identityKey:e.subject,badgeIconURL:a,badgeLabel:i,badgeClickURL:n}}}class iD{wallet;network;constructor(e=new r7){this.wallet=e}async registerDefinition(e){let t=(await this.wallet.getPublicKey({identityKey:!0})).publicKey,r=new t7(this.wallet),i=this.buildPushDropFields(e,t),a=this.mapDefinitionTypeToWalletProtocol(e.definitionType),n=await r.lock(i,a,"1","anyone",!0),{tx:s}=await this.wallet.createAction({description:`Register a new ${e.definitionType} item`,outputs:[{satoshis:1,lockingScript:n.toHex(),outputDescription:`New ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{randomizeOutputs:!1}});if(void 0===s)throw Error(`Failed to create ${e.definitionType} registration transaction!`);let o=new iv([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:this.network??=(await this.wallet.getNetwork({})).network});return await o.broadcast(rg.fromAtomicBEEF(s))}async resolve(e,t){let r=new iw,i=this.mapDefinitionTypeToServiceName(e),a=await r.query({service:i,query:t});if("output-list"!==a.type)return[];let n=[];for(let t of a.outputs)try{let r=rg.fromBEEF(t.beef).outputs[t.outputIndex].lockingScript,i=await this.parseLockingScript(e,r);n.push(i)}catch{}return n}async listOwnRegistryEntries(e){let t=this.mapDefinitionTypeToBasketName(e),{outputs:r,BEEF:i}=await this.wallet.listOutputs({basket:t,include:"entire transactions"}),a=[];for(let t of r)if(t.spendable)try{let[r,n]=t.outpoint.split("."),s=rg.fromBEEF(i).outputs[n].lockingScript,o=await this.parseLockingScript(e,s);a.push({...o,txid:r,outputIndex:Number(n),satoshis:t.satoshis,lockingScript:s.toHex(),beef:i})}catch{}return a}async revokeOwnRegistryEntry(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.wallet.getPublicKey({identityKey:!0})).publicKey;if(e.registryOperator!==t)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",i=`${e.txid}.${e.outputIndex}`,{signableTransaction:a}=await this.wallet.createAction({description:`Revoke ${e.definitionType} item: ${r}`,inputBEEF:e.beef,inputs:[{outpoint:i,unlockingScriptLength:73,inputDescription:`Revoking ${e.definitionType} token`}]});if(void 0===a)throw Error("Failed to create signable transaction.");let n=rg.fromBEEF(a.tx),s=new t7(this.wallet),o=await s.unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone","all",!1,e.satoshis,tJ.fromHex(e.lockingScript)),c=await o.sign(n,e.outputIndex),{tx:l}=await this.wallet.signAction({reference:a.reference,spends:{[e.outputIndex]:{unlockingScript:c.toHex()}},options:{acceptDelayedBroadcast:!1}});if(void 0===l)throw Error("Failed to finalize the transaction signature.");let h=new iv([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:this.network??=(await this.wallet.getNetwork({})).network});return await h.broadcast(rg.fromAtomicBEEF(l))}buildPushDropFields(e,t){let r;switch(e.definitionType){case"basket":r=[e.basketID,e.name,e.iconURL,e.description,e.documentationURL];break;case"protocol":r=[JSON.stringify(e.protocolID),e.name,e.iconURL,e.description,e.documentationURL];break;case"certificate":r=[e.type,e.name,e.iconURL,e.description,e.documentationURL,JSON.stringify(e.fields)];break;default:throw Error("Unsupported definition type")}return r.push(t),r.map(e=>eF(e))}async parseLockingScript(e,t){let r,i,a=t7.decode(t);if(0===a.fields.length)throw Error("Not a valid registry pushdrop script.");switch(e){case"basket":{if(7!==a.fields.length)throw Error("Unexpected field count for basket type.");let[e,t,n,s,o,c]=a.fields;r=e$(c),i={definitionType:"basket",basketID:e$(e),name:e$(t),iconURL:e$(n),description:e$(s),documentationURL:e$(o)};break}case"protocol":{if(7!==a.fields.length)throw Error("Unexpected field count for protocol type.");let[e,t,n,s,o,c]=a.fields;r=e$(c),i={definitionType:"protocol",protocolID:iB(e$(e)),name:e$(t),iconURL:e$(n),description:e$(s),documentationURL:e$(o)};break}case"certificate":{if(8!==a.fields.length)throw Error("Unexpected field count for certificate type.");let[e,t,n,s,o,c,l]=a.fields;r=e$(l);let h={};try{h=JSON.parse(e$(c))}catch{}i={definitionType:"certificate",type:e$(e),name:e$(t),iconURL:e$(n),description:e$(s),documentationURL:e$(o),fields:h};break}default:throw Error(`Unsupported definition type: ${e}`)}return{...i,registryOperator:r}}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 iB(e){let t=JSON.parse(e);if(!Array.isArray(t)||2!==t.length)throw Error("Invalid wallet protocol format.");let[r,i]=t;if(![0,1,2].includes(r))throw Error("Invalid security level.");if("string"!=typeof i)throw Error("Invalid protocolID");return[r,i]}class iH{wallet;context;encrypt;originator;acceptDelayedBroadcast=!1;keyLocks=new Map;constructor(e=new r7,t="kvstore default",r=!0,i,a=!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=r,this.originator=i,this.acceptDelayedBroadcast=a}async queueOperationOnKey(e){let t=this.keyLocks.get(e);null==t&&(t=[],this.keyLocks.set(e,t));let r=()=>{},i=new Promise(e=>{r=e,null!=t&&t.push(e)});return 1===t.length&&r(),await i,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})}async get(e,t){let r=await this.queueOperationOnKey(e);try{return(await this.lookupValue(e,t,5)).value}finally{this.finishOperationOnKey(e,r)}}getLockingScript(e,t){let[r,i]=e.outpoint.split("."),a=t.findTxid(r)?.tx;if(null==a)throw Error(`beef must contain txid ${r}`);return a.outputs[Number(i)].lockingScript}async lookupValue(e,t,r){let i,a=await this.getOutputs(e,r),n={value:t,outpoint:void 0,lor:a},{outputs:s}=a;if(0===s.length)return n;let o=s.slice(-1)[0];n.outpoint=o.outpoint;try{if(void 0===a.BEEF)throw Error("entire transactions listOutputs option must return valid BEEF");let e=this.getLockingScript(o,rb.fromBinary(a.BEEF)),t=t7.decode(e);if(t.fields.length<1||t.fields.length>2)throw Error("Invalid token.");i=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:i});n.value=e$(t)}else n.value=e$(i);return n}getInputs(e){let t=[];for(let r=0;r<e.length;r++)t.push({outpoint:e[r].outpoint,unlockingScriptLength:74,inputDescription:"Previous key-value token"});return t}async getSpends(e,t,r,i){let a=this.getProtocol(e),n=rg.fromAtomicBEEF(i),s={};for(let e=0;e<t.length;e++){let t=r.unlock(a.protocolID,a.keyID,"self"),i=await t.sign(n,e);s[e]={unlockingScript:i.toHex()}}return s}async set(e,t){let r=await this.queueOperationOnKey(e);try{let r,i=await this.lookupValue(e,void 0,10);if(i.value===t){if(void 0===i.outpoint)throw Error("outpoint must be valid when value is valid and unchanged");return i.outpoint}let a=this.getProtocol(e),n=eF(t,"utf8");if(this.encrypt){let{ciphertext:e}=await this.wallet.encrypt({...a,plaintext:n});n=e}let s=new t7(this.wallet,this.originator),o=await s.lock([n],a.protocolID,a.keyID,"self"),{outputs:c,BEEF:l}=i.lor;try{let t=this.getInputs(c),{txid:i,signableTransaction:a}=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}});if(c.length>0&&"object"!=typeof a)throw Error("Wallet did not return a signable transaction when expected.");if(null==a)r=`${i}.0`;else{let t=await this.getSpends(e,c,s,a.tx),{txid:i}=await this.wallet.signAction({reference:a.reference,spends:t});r=`${i}.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 r}finally{this.finishOperationOnKey(e,r)}}async remove(e){let t=await this.queueOperationOnKey(e);try{let t=[];for(;;){let{outputs:r,BEEF:i,totalOutputs:a}=await this.getOutputs(e);if(r.length>0){let n=new t7(this.wallet,this.originator);try{let a=this.getInputs(r),{signableTransaction:s}=await this.wallet.createAction({description:`Remove ${e} in ${this.context}`,inputBEEF:i,inputs:a,options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}});if("object"!=typeof s)throw Error("Wallet did not return a signable transaction when expected.");let o=await this.getSpends(e,r,n,s.tx),{txid:c}=await this.wallet.signAction({reference:s.reference,spends:o});if(void 0===c)throw Error("signAction must return a valid txid");t.push(c)}catch(t){throw Error(`There are ${a} outputs with tag ${e} that cannot be unlocked. Original error: ${t instanceof Error?t.message:String(t)}`)}}if(r.length===a)break}return t}finally{this.finishOperationOnKey(e,t)}}}return s})());
20
20
  //# sourceMappingURL=bundle.js.map