@bsv/sdk 1.10.1 → 1.10.2

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.
@@ -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=>e7(eo(e9(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 n=t.path[r-1].find(e=>e.offset===i.offset+1),a=i.offset>>1;void 0!==n&&"string"==typeof n.hash&&t.path[r].every(e=>e.offset!==a)&&t.path[r].push({offset:a,hash:e(n.hash+i.hash)})}}}let rQ="undefined"!=typeof globalThis?globalThis.Buffer:void 0;class r0{version;inputs;outputs;lockTime;metadata;merklePath;cachedHash;rawBytesCache;hexCache;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}=r0.fromAnyBeef(e,t);return r}static fromAtomicBEEF(e){let{tx:t,txid:r,beef:i}=r0.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=rZ.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,n=r.findAtomicTransaction(i);if(null==n)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:n,beef:r,txid:i}}static fromEF(e){let t=new td(e),r=t.readUInt32LE();if("0000000000ef"!==e7(t.read(6)))throw Error("Invalid EF marker");let i=t.readVarIntNum(),n=[];for(let e=0;e<i;e++){let e=e7(t.readReverse(32)),r=t.readUInt32LE(),i=t.readVarIntNum(),a=t.read(i),s=rP.fromBinary(a),o=t.readUInt32LE(),c=t.readUInt64LEBn().toNumber(),l=t.readVarIntNum(),h=t.read(l),u=rE.fromBinary(h),d=new r0(void 0,[],[],void 0);d.outputs=Array(r+1).fill(null),d.outputs[r]={satoshis:c,lockingScript:u},n.push({sourceTransaction:d,sourceTXID:e,sourceOutputIndex:r,unlockingScript:s,sequence:o})}let a=t.readVarIntNum(),s=[];for(let e=0;e<a;e++){let e=t.readUInt64LEBn().toNumber(),r=t.readVarIntNum(),i=t.read(r),n=rE.fromBinary(i);s.push({satoshis:e,lockingScript:n})}return new r0(r,n,s,t.readUInt32LE())}static parseScriptOffsets(e){let t=new td(e),r=[],i=[];t.pos+=4;let n=t.readVarIntNum();for(let e=0;e<n;e++){t.pos+=36;let i=t.readVarIntNum();r.push({vin:e,offset:t.pos,length:i}),t.pos+=i+4}let a=t.readVarIntNum();for(let e=0;e<a;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=e7(e.readReverse(32)),r=e.readUInt32LE(),n=e.readVarIntNum(),a=e.read(n),s=rP.fromBinary(a),o=e.readUInt32LE();i.push({sourceTXID:t,sourceOutputIndex:r,unlockingScript:s,sequence:o})}let n=e.readVarIntNum(),a=[];for(let t=0;t<n;t++){let t=e.readUInt64LEBn().toNumber(),r=e.readVarIntNum(),i=e.read(r),n=rE.fromBinary(i);a.push({satoshis:t,lockingScript:n})}return new r0(t,i,a,e.readUInt32LE())}static fromBinary(e){let t=e.slice(),r=Uint8Array.from(t),i=new td(t),n=r0.fromReader(i);return n.rawBytesCache=r,n}static fromHex(e){let t=e9(e,"hex"),r=Uint8Array.from(t),i=new td(t),n=r0.fromReader(i);return n.rawBytesCache=r,n.hexCache=null!=rQ?rQ.from(r).toString("hex"):e7(t),n}static fromHexEF(e){return r0.fromEF(e9(e,"hex"))}static fromHexBEEF(e,t){return r0.fromBEEF(e9(e,"hex"),t)}constructor(e=1,t=[],r=[],i=0,n=new Map,a){this.version=e,this.inputs=t,this.outputs=r,this.lockTime=i,this.metadata=n,this.merklePath=a}invalidateSerializationCaches(){this.cachedHash=void 0,this.rawBytesCache=void 0,this.hexCache=void 0}addInput(e){if(void 0===e.sourceTXID&&void 0===e.sourceTransaction)throw Error("A reference to an an input transaction is required. If the input transaction itself cannot be referenced, its TXID must still be provided.");void 0===e.sequence&&(e.sequence=0xffffffff),this.invalidateSerializationCaches(),this.inputs.push(e)}addOutput(e){if(this.cachedHash=void 0,!0!==e.change){if(void 0===e.satoshis)throw Error("either satoshis must be defined or change must be set to true");if(e.satoshis<0)throw Error("satoshis must be a positive integer or zero")}if(null==e.lockingScript)throw Error("lockingScript must be defined");this.outputs.push(e)}addP2PKHOutput(e,t){let r=new rC().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=rU.getInstance(),t="equal"){if(this.invalidateSerializationCaches(),"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,n=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);n[e]=n[e]+t,r+=t,i-=t}for(let e of this.outputs)!0===e.change&&(e.satoshis=n.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.invalidateSerializationCaches(),this.outputs))if(void 0===e.satoshis)if(!0===e.change)throw Error("There are still change outputs with uncomputed amounts. Use the fee() method to compute the change amounts and transaction fees prior to signing.");else throw Error("One or more transaction outputs is missing an amount. Ensure all output amounts are provided before signing.");let e=await Promise.all(this.inputs.map(async(e,t)=>"object"==typeof this.inputs[t].unlockingScriptTemplate?await this.inputs[t]?.unlockingScriptTemplate?.sign(this,t):await Promise.resolve(void 0)));for(let t=0,r=this.inputs.length;t<r;t++)"object"==typeof this.inputs[t].unlockingScriptTemplate&&(this.inputs[t].unlockingScript=e[t])}async broadcast(e=rM()){return await e.broadcast(this)}writeTransactionBody(e){for(let t of(e.writeUInt32LE(this.version),e.writeVarIntNum(this.inputs.length),this.inputs)){if(void 0===t.sourceTXID)if(null!=t.sourceTransaction)e.write(t.sourceTransaction.hash());else throw Error("sourceTransaction is undefined");else e.writeReverse(e9(t.sourceTXID,"hex"));if(e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw Error("unlockingScript is undefined");let r=t.unlockingScript.toUint8Array();e.writeVarIntNum(r.length),e.write(r),e.writeUInt32LE(t.sequence??0xffffffff)}for(let t of(e.writeVarIntNum(this.outputs.length),this.outputs)){e.writeUInt64LE(t.satoshis??0);let r=t.lockingScript.toUint8Array();e.writeVarIntNum(r.length),e.write(r)}e.writeUInt32LE(this.lockTime)}buildSerializedBytes(){let e=new tu;return this.writeTransactionBody(e),e.toUint8Array()}getSerializedBytes(){return null==this.rawBytesCache&&(this.rawBytesCache=this.buildSerializedBytes()),this.rawBytesCache}toBinary(){return Array.from(this.getSerializedBytes())}toUint8Array(){return this.getSerializedBytes()}toEF(){let e=new tu;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(e9(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??0xffffffff),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 e7(this.toEF())}toHex(){if(null!=this.hexCache)return this.hexCache;let e=this.getSerializedBytes(),t=null!=rQ?rQ.from(e).toString("hex"):e7(Array.from(e));return this.hexCache=t,t}toHexBEEF(){return e7(this.toBEEF())}toHexAtomicBEEF(){return e7(this.toAtomicBEEF())}hash(e){return(null==this.cachedHash&&(this.cachedHash=eo(this.getSerializedBytes())),"hex"===e)?e7(this.cachedHash):this.cachedHash}id(e){let t=[...this.hash()];return(t.reverse(),"hex"===e)?e7(t):t}async verify(e=rz(),t,r){let i=new Set,n=[this];for(;n.length>0;){let a=n.shift(),s=a?.id("hex")??"";if(null!=s&&""!==s&&i.has(s))continue;if("object"==typeof a?.merklePath)if("scripts only"===e){null!=s&&i.add(s);continue}else{if(await a.merklePath.verify(s,e)){i.add(s);continue}throw Error(`Invalid merkle path for transaction ${s}`)}if(void 0!==t){if(void 0===a)throw Error("Transaction is undefined");let e=r0.fromEF(a.toEF());if(delete e.outputs[0].satoshis,e.outputs[0].change=!0,await e.fee(t),a.getFee()<e.getFee())throw Error(`Verification failed because the transaction ${s} has an insufficient fee and has not been mined.`)}let o=0;if(void 0===a)throw Error("Transaction is undefined");for(let e=0;e<a.inputs.length;e++){let t=a.inputs[e];if("object"!=typeof t.sourceTransaction)throw Error(`Verification failed because the input at index ${e} of transaction ${s} is missing an associated source transaction. This source transaction is required for transaction verification because there is no merkle proof for the transaction spending a UTXO it contains.`);if("object"!=typeof t.unlockingScript)throw Error(`Verification failed because the input at index ${e} of transaction ${s} is missing an associated unlocking script. This script is required for transaction verification because there is no merkle proof for the transaction spending the UTXO.`);let c=t.sourceTransaction.outputs[t.sourceOutputIndex];o+=c.satoshis??0;let l=t.sourceTransaction.id("hex");i.has(l)||n.push(t.sourceTransaction);let h=a.inputs.filter((t,r)=>r!==e);if(void 0===t.sourceTXID&&(t.sourceTXID=l),!new rT({sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,lockingScript:c.lockingScript,sourceSatoshis:c.satoshis??0,transactionVersion:a.version,otherInputs:h,unlockingScript:t.unlockingScript,inputSequence:t.sequence??0xffffffff,inputIndex:e,outputs:a.outputs,lockTime:a.lockTime,memoryLimit:r}).validate())return!1}let c=0;for(let e of a.outputs){if("number"!=typeof e.satoshis)throw Error("Every output must have a defined amount during transaction verification.");c+=e.satoshis}if(c>o)return!1;i.add(s)}return!0}toBEEF(e){let t=new tu;t.writeUInt32LE(rG);let r=[],i=new Map,n=new Map,a=[],s=new Set,o=t=>{let c=t.id("hex");if(s.has(c))return;let l={tx:t},h=t.merklePath,u="object"==typeof h;if(u&&null!=h&&(l.pathIndex=(e=>{let t=i.get(e);if(void 0!==t)return t;let a=`${e.blockHeight}:${e.computeRoot()}`,s=n.get(a);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),n.set(a,o),o})(h)),!u)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),a.push(l)};for(let e of(o(this),t.writeVarIntNum(r.length),r))t.write(e.toBinary());for(let e of(t.writeVarIntNum(a.length),a))t.write(e.tx.toBinary()),"number"==typeof e.pathIndex?(t.writeUInt8(1),t.writeVarIntNum(e.pathIndex)):t.writeUInt8(0);return t.toArray()}toAtomicBEEF(e){return[1,1,1,1].concat(this.hash(),this.toBEEF(e))}}function r1(e){return"success"===e.status}function r2(e){return"error"===e.status}let r8=class extends rZ{knownTo={};constructor(e){if(super(),null!=e)for(const t of e)this.addParty(t)}isParty(e){return Object.keys(this.knownTo).includes(e)}addParty(e){if(this.isParty(e))throw Error(`Party ${e} already exists.`);this.knownTo[e]={}}getKnownTxidsForParty(e){let t=this.knownTo[e];if(void 0===t)throw Error(`Party ${e} is unknown.`);return Object.keys(t)}getTrimmedBeefForParty(e){let t=this.getKnownTxidsForParty(e),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)?rZ.fromBinary(t):t,i=r.getValidTxids();this.mergeBeef(r),this.addKnownTxidsForParty(e,i)}};class r3{network;URL;httpClient;constructor(e="main",t=rK()){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 r6{https;constructor(e){this.https=e}async request(e,t){return await new Promise((r,i)=>{let n=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,n=e.headers["content-type"],a=""!==t&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(t):t;r({status:e.statusCode,statusText:e.statusMessage,ok:i,data:a})})});n.on("error",e=>{i(e)}),null!==t.data&&void 0!==t.data&&n.write(Buffer.from(t.data)),n.end()})}}class r4{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),n=await i.text();return{ok:i.ok,status:i.status,statusText:i.statusText,data:n}}}function r5(){let e={async request(){throw Error("No method available to perform HTTP request")}};if("undefined"!=typeof window&&"function"==typeof window.fetch)return new r4(window.fetch.bind(window));if("undefined"==typeof require)return e;try{let e=require("https");return new r6(e)}catch(t){return e}}class r7{URL;httpClient;constructor(e,t=r5()){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 r9{baseUrl;httpClient;apiKey;constructor(e,t={}){const{httpClient:r,apiKey:i}=t;this.baseUrl=e,this.httpClient=r??rK(),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 ie="42423301",it=(e,t,r)=>{let i="object"!=typeof r;if(i){let e=new tU,t=new t1(1),i=e.g.mul(t);r=new tX(i.x,i.y)}let n=tJ(32),a=ta(n),s=`2-message signing-${a}`,o=t.deriveChild(r,s).sign(e).toDER(),c=t.toPublicKey().encode(!0);return[...e9(ie,"hex"),...c,...i?[0]:r.encode(!0),...n,...o]},ir=(e,t,r)=>{let i=new td(t),n=e7(i.read(4));if(n!==ie)throw Error(`Message version mismatch: Expected ${ie}, received ${n}`);let a=tX.fromString(e7(i.read(33))),[s]=i.read(1);if(0===s)r=new t1(1);else{let e=e7([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=ta(i.read(32)),c=e7(i.read(i.bin.length-i.pos)),l=tF.fromDER(c,"hex"),h=`2-message signing-${o}`;return a.deriveChild(r,h).verify(e,l)},ii="42421033",ia=(e,t,r)=>{let i=tJ(32),n=ta(i),a=`2-message encryption-${n}`,s=t.deriveChild(r,a),o=r.deriveChild(t,a),c=new rl(s.deriveSharedSecret(o).encode(!0).slice(1)).encrypt(e),l=t.toPublicKey().encode(!0);return[...e9(ii,"hex"),...l,...r.encode(!0),...i,...c]},is=(e,t)=>{let r=new td(e),i=e7(r.read(4));if(i!==ii)throw Error(`Message version mismatch: Expected ${ii}, received ${i}`);let n=tX.fromString(e7(r.read(33))),a=e7(r.read(33)),s=t.toPublicKey().encode(!0,"hex");if(a!==s)throw Error(`The encrypted message expects a recipient public key of ${a}, but the provided key is ${s}`);let o=ta(r.read(32)),c=r.read(r.bin.length-r.pos),l=`2-message encryption-${o}`,h=n.deriveChild(t,l),u=t.deriveChild(n,l);return new rl(h.deriveSharedSecret(u).encode(!0).slice(1)).decrypt(c)},io="Bitcoin Signed Message:\n",ic=e=>{let t=new tu;return t.writeVarIntNum(io.length),t.write(e9(io,"utf8")),t.writeVarIntNum(e.length),t.write(e),eo(t.toArray())},il=(e,t,r="base64")=>{let i=ic(e),n=tW(new P(i),t,!0);if("raw"===r)return n;let a=new P(i),s=n.CalculateRecoveryFactor(t.toPublicKey(),a);return n.toCompact(s,!0,"base64")},ih=(e,t,r)=>tj(new P(ic(e)),t,r);class iu{versionBytesNum;depth;parentFingerPrint;childIndex;chainCode;privKey;pubKey;constants={pubKey:0x488b21e,privKey:0x488ade4};constructor(e,t,r,i,n,a,s){this.versionBytesNum=e,this.depth=t,this.parentFingerPrint=r,this.childIndex=i,this.chainCode=n,this.privKey=a,this.pubKey=s}fromRandom(){return this.versionBytesNum=this.constants.privKey,this.depth=0,this.parentFingerPrint=[0,0,0,0],this.childIndex=0,this.chainCode=tJ(32),this.privKey=t1.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=th(e);return this.fromBinary([...t.prefix,...t.data])}static fromSeed(e){return new this().fromSeed(e)}fromSeed(e){if(e.length<16)throw Error("Need more than 128 bits of entropy");if(e.length>64)throw Error("More than 512 bits of entropy is nonstandard");let t=eh(e9("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 t1(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 td(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,n=this.versionBytesNum===this.constants.pubKey;if(i&&0===r[0])this.privKey=new t1(r.slice(1,33)),this.pubKey=this.privKey.toPublicKey();else if(n&&(2===r[0]||3===r[0]))this.pubKey=tX.fromString(e7(r));else throw Error("Invalid key");return this}toString(){return tl(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],n=0x7fffffff&parseInt(t?i.slice(0,i.length-1):i,10);t&&(n+=0x80000000),r=r.deriveChild(n)}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,n=this.versionBytesNum===this.constants.privKey;if(i&&(null===this.privKey||void 0===this.privKey||!n))throw Error("Cannot do private key derivation without private key");let a=null;if(null!==this.privKey&&void 0!==this.privKey){let e=null;e=i?[0,...this.privKey.toArray("be",32),...r]:[...this.pubKey.encode(!0),...r];let t=eh(this.chainCode,e),n=new P(t.slice(0,32)),s=t.slice(32,64),o=n.add(this.privKey).mod(new tU().n);(a=new iu).chainCode=s,a.privKey=new t1(o.toArray()),a.pubKey=a.privKey.toPublicKey()}else{let e=[...this.pubKey.encode(!0),...r],t=eh(this.chainCode,e),i=new P(t.slice(0,32)),n=t.slice(32,64),s=new tU().g.mul(i),o=this.pubKey,c=s.add(o),l=new tX(c.x,c.y);(a=new iu).chainCode=n,a.pubKey=l}a.childIndex=e;let s=ec(this.pubKey.encode(!0));return a.parentFingerPrint=s.slice(0,4),a.versionBytesNum=this.versionBytesNum,a.depth=this.depth+1,a}toPublic(){let e=new iu(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 tu().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 tu().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 id={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 ip{mnemonic;seed;Wordlist;constructor(e,t,r=id){this.mnemonic=e??"",this.seed=t??[],this.Wordlist=r}toBinary(){let e=new tu;if(""!==this.mnemonic){let t=e9(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 td(e),r=t.readVarIntNum();r>0&&(this.mnemonic=tn(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=tJ(e/8);return this.entropy2Mnemonic(t),this.mnemonic2Seed(),this}static fromRandom(e){return new this().fromRandom(e)}fromEntropy(e){return this.entropy2Mnemonic(e),this}static fromEntropy(e){return new this().fromEntropy(e)}fromString(e){return this.mnemonic=e,this}static fromString(e){return new this().fromString(e)}toString(){return this.mnemonic}toSeed(e){return this.mnemonic2Seed(e),this.seed}entropy2Mnemonic(e){if(e.length<16)throw Error("Entropy is less than 128 bits. It must be 128 bits or more.");let t=ea(e),r="",i=8*e.length;for(let t=0;t<e.length;t++)r+=("00000000"+e[t].toString(2)).slice(-8);let n=t[0].toString(2);if((r+=n=("00000000"+n).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 a="";for(let e=0;e<r.length/11;e++){""!==a&&(a+=this.Wordlist.space);let t=parseInt(r.slice(11*e,(e+1)*11),2);a+=this.Wordlist.value[t]}return this.mnemonic=a,this}check(){let e=this.mnemonic.split(this.Wordlist.space),t="";for(let 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),n=t.slice(0,t.length-r),a=[];for(let e=0;e<n.length/8;e++)a.push(parseInt(t.slice(8*e,(e+1)*8),2));let s=ea(a.slice(0,n.length/8))[0].toString(2);return(s=("00000000"+s).slice(-8).slice(0,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=e9(t,"utf8"),i=[...e9("mnemonic","utf8"),...e9(e,"utf8")];return this.seed=eQ(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 ip(e).isValid(t)}}function ig(e){let t,r,i,n;0===this._tables[0][0][0]&&this._precompute();let a=this._tables[0][4],s=this._tables[1],o=e.length,c=1;if(4!==o&&6!==o&&8!==o)throw Error("invalid aes key size");for(this._key=[r=e.slice(0),i=[]],n=o;n<4*o+28;n++)t=r[n-1],(n%o==0||8===o&&n%o==4)&&(t=a[t>>>24]<<24^a[t>>16&255]<<16^a[t>>8&255]<<8^a[255&t],n%o==0&&(t=t<<8^t>>>24^c<<24,c=c<<1^(c>>7)*283)),r[n]=r[n-o]^t;for(let e=0;n>0;e++,n--)t=r[(3&e)!=0?n:n-4],n<=4||e<4?i[e]=t:i[e]=s[0][a[t>>>24]]^s[1][a[t>>16&255]]^s[2][a[t>>8&255]]^s[3][a[255&t]]}ig.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,n,a,s,o,c=this._tables[0],l=this._tables[1],h=c[4],u=l[4],d=new Uint8Array(256),f=new Uint8Array(256);for(e=0;e<256;e++)f[(d[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,a=(a=r^r<<1^r<<2^r<<3^r<<4)>>8^255&a^99,h[t]=a,u[a]=t,o=0x1010101*d[n=d[i=d[t]]]^65537*n^257*i^0x1010100*t,s=257*d[a]^0x1010100*a;e<4;e++)c[e][t]=s=s<<24^s>>>8,l[e][a]=o=o<<24^o>>>8},_crypt:function(e,t){let r,i,n,a;if(4!==e.length)throw Error("invalid aes block size");let s=this._key[t],o=e[0]^s[0],c=e[1===t?3:1]^s[1],l=e[2]^s[2],h=e[1===t?1:3]^s[3],u=s.length/4-2,d=4,f=new Uint32Array(4),p=this._tables[t],g=p[0],b=p[1],y=p[2],m=p[3],w=p[4];for(a=0;a<u;a++)r=g[o>>>24]^b[c>>16&255]^y[l>>8&255]^m[255&h]^s[d],i=g[c>>>24]^b[l>>16&255]^y[h>>8&255]^m[255&o]^s[d+1],n=g[l>>>24]^b[h>>16&255]^y[o>>8&255]^m[255&c]^s[d+2],h=g[h>>>24]^b[o>>16&255]^y[c>>8&255]^m[255&l]^s[d+3],d+=4,o=r,c=i,l=n;for(a=0;a<4;a++)f[1===t?3&-a:a]=w[o>>>24]<<24^w[c>>16&255]<<16^w[l>>8&255]<<8^w[255&h]^s[d++],r=o,o=c,c=l,l=h,h=r;return f}};class ib{static encrypt(e,t){let r=ib.buf2Words(t),i=ib.buf2Words(e),n=new ig(r).encrypt(i);return ib.words2Buf(n)}static decrypt(e,t){let r=ib.buf2Words(e),i=new ig(ib.buf2Words(t)).decrypt(r);return ib.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 iy{static buf2BlocksBuf(e,t){let r=t/8,i=[];for(let n=0;n<=e.length/r;n++){let a=e.slice(n*r,n*r+r);a.length<t&&(a=iy.pkcs7Pad(a,t)),i.push(a)}return i}static blockBufs2Buf(e){let t=e[e.length-1];return t=iy.pkcs7Unpad(t),e[e.length-1]=t,e.flat()}static encrypt(e,t,r,i){let n=8*t.length,a=iy.buf2BlocksBuf(e,n);return iy.encryptBlocks(a,t,r,i).flat()}static decrypt(e,t,r,i){let n=t.length,a=[];for(let t=0;t<e.length/n;t++)a.push(e.slice(t*n,t*n+n));let s=iy.decryptBlocks(a,t,r,i);return iy.blockBufs2Buf(s)}static encryptBlock(e,t,r,i){let n=iy.xorBufs(e,t);return r.encrypt(n,i)}static decryptBlock(e,t,r,i){let n=r.decrypt(e,i);return iy.xorBufs(n,t)}static encryptBlocks(e,t,r,i){let n=[];for(let a=0;a<e.length;a++){let s=e[a],o=iy.encryptBlock(s,t,r,i);n.push(o),t=o}return n}static decryptBlocks(e,t,r,i){let n=[];for(let a=0;a<e.length;a++){let s=e[a],o=iy.decryptBlock(s,t,r,i);n.push(o),t=s}return n}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),e7(r)!==e7(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 im{static encrypt(e,t,r,i=!0){r=r??tJ(16);let n=iy.encrypt(e,r,ib,t);return i?[...r,...n]:[...n]}static decrypt(e,t,r){if(null!=r)return iy.decrypt(e,r,ib,t);{r=e.slice(0,16);let i=e.slice(16);return iy.decrypt(i,r,ib,t)}}}class iw{static ivkEkM(e,t){let r=t.mul(e),i=es(new tX(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 n,a=null;null==r&&(r=t1.fromRandom()),i||(a=r.toPublicKey().encode(!0));let{iv:s,kE:o,kM:c}=iw.ivkEkM(r,t),l=im.encrypt(e,o,s,!1),h=e9("BIE1","utf8"),u=el(c,n=null!=a&&a.length>0?[...h,...a,...l]:[...h,...l]);return[...n,...u]}static electrumDecrypt(e,t,r){if("BIE1"!==tn(e.slice(0,4),"utf8"))throw Error("Invalid Magic");let i=4,n=null;if(e.length-i-32>=33){let t=e[i];2===t||3===t?(n=e.slice(i,i+33),i+=33):4===t&&(n=e.slice(i,i+65),i+=65)}if(null!==n)null==r&&(r=tX.fromString(e7(n)));else if(null==r)throw Error("Sender public key is required");let{iv:a,kE:s,kM:o}=iw.ivkEkM(t,r),c=e.slice(i,e.length-32),l=e.slice(e.length-32,e.length),h=el(o,e.slice(0,e.length-32));if(e7(l)!==e7(h))throw Error("Invalid checksum");return im.decrypt(c,s,a)}static bitcoreEncrypt(e,t,r,i){null==r&&(r=t1.fromRandom()),null==i&&(i=tJ(16));let n=r,a=r.toPublicKey().encode(!0),s=es(t.mul(n).getX().toArray("be",32)),o=s.slice(0,32),c=s.slice(32,64),l=im.encrypt(e,o,i),h=el(c,[...l]);return[...a,...l,...h]}static bitcoreDecrypt(e,t){let r=tX.fromString(e7(e.slice(0,33))).mul(t);if(r.eq(new tD(0,0)))throw Error("P equals 0");let i=es(r.getX().toArray("be",32)),n=i.slice(0,32),a=i.slice(32,64),s=e.slice(33,e.length-32),o=e.slice(e.length-32,e.length),c=el(a,s);if(e7(o)!==e7(c))throw Error("Invalid checksum");return[...im.decrypt(s,n)]}}function iv(e,t){let r=new r0(0,[],[],0);return r.outputs=Array(e.vout+1).fill(null),r.outputs[e.vout]={satoshis:e.satoshis,lockingScript:rE.fromHex(e.script)},{sourceTransaction:r,sourceTXID:e.txid,sourceOutputIndex:e.vout,unlockingScriptTemplate:t,sequence:0xffffffff}}class iI{static generate(e,t){let r=this.withDefaultOptions(t);return ik(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 n=this.getCounter(i.timestamp,i.period),a=[n];for(let e=1;e<=i.skew;e++)a.push(n+e),a.push(n-e);for(let r of a){let n=ik(e,r,i);if(ty(e9(t,"utf8"),e9(n,"utf8")))return!0}return!1}static getCounter(e,t){return Math.floor(Math.floor(e/1e3)/t)}static withDefaultOptions(e){return{digits:2,algorithm:"SHA-1",period:30,timestamp:Date.now(),...e}}static withDefaultValidateOptions(e){return{skew:1,...this.withDefaultOptions(e)}}}function ik(e,t,r){let i=(function(e,t,r){switch(r){case"SHA-1":return new et(e).update(t);case"SHA-256":return new ee(e).update(t);case"SHA-512":return new er(e).update(t);default:throw Error("unsupported HMAC algorithm")}})(e,new P(t).toArray("be",8),r.algorithm).digest(),n=15&i[i.length-1];return(0x7fffffff&new P(i.slice(n,n+4)).toNumber()).toString().slice(-r.digits)}(s=h||(h={}))[s.Silent=0]="Silent",s[s.App=1]="App",s[s.Counterparty=2]="Counterparty";class iS{cacheSharedSecret;retrieveCachedSharedSecret;rootKey;identityKey;anyone;constructor(e,t,r){this.cacheSharedSecret=t,this.retrieveCachedSharedSecret=r,this.anyone=new t1(1).toPublicKey(),"anyone"===e?this.rootKey=new t1(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),n=this.derivePrivateKey(e,t,r);return new rl(n.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),n=e9(this.computeInvoiceNumber(t,r),"utf8");return el(i.encode(!0),n)}normalizeCounterparty(e){if(null==e)throw Error("counterparty must be self, anyone or a public key!");return"self"===e?this.rootKey.toPublicKey():"anyone"===e?new t1(1).toPublicKey():"string"==typeof e?tX.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 ix{keyDeriver;cache;maxCacheSize;rootKey;identityKey;constructor(e,t){"anyone"===e?this.rootKey=new t1(1):this.rootKey=e,this.keyDeriver=new iS(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;const r=t?.maxCacheSize;this.maxCacheSize=null!=r&&!isNaN(r)&&r>0?r:1e3}derivePublicKey(e,t,r,i=!1){let n=this.generateCacheKey("derivePublicKey",e,t,r,i);if(this.cache.has(n)){let e=this.cacheGet(n);if(void 0===e)throw Error("Cached value is undefined");return e}{let a=this.keyDeriver.derivePublicKey(e,t,r,i);return this.cacheSet(n,a),a}}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 n=this.keyDeriver.derivePrivateKey(e,t,r);return this.cacheSet(i,n),n}}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 n=this.keyDeriver.deriveSymmetricKey(e,t,r);return this.cacheSet(i,n),n}}revealCounterpartySecret(e){let t=this.generateCacheKey("revealCounterpartySecret",e);if(this.cache.has(t)){let e=this.cacheGet(t);if(void 0===e)throw Error("Cached value is undefined");return e}{let 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 n=this.keyDeriver.revealSpecificSecret(e,t,r);return this.cacheSet(i,n),n}}generateCacheKey(e,...t){let r=t.map(e=>this.serializeArgument(e)).join("|");return`${e}|${r}`}serializeArgument(e){return e instanceof tX||e instanceof t1?e.toString():Array.isArray(e)?e.map(e=>this.serializeArgument(e)).join(","):"object"==typeof e&&null!==e?JSON.stringify(e):String(e)}cacheGet(e){let t=this.cache.get(e);return this.cache.delete(e),void 0!==t&&this.cache.set(e,t),t}cacheSet(e,t){if(this.cache.size>=this.maxCacheSize){let e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(e,t)}}class iE{keyDeriver;constructor(e){"string"!=typeof e.identityKey&&(e=new ix(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 rd().generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),tX.fromString(e.counterparty),tD.fromDER(r)),n=[...i.R.encode(!0),...i.SPrime.encode(!0),...i.z.toArray()],a=new Date().toISOString(),{ciphertext:s}=await this.encrypt({plaintext:r,protocolID:[2,"counterparty linkage revelation"],keyID:a,counterparty:e.verifier}),{ciphertext:o}=await this.encrypt({plaintext:n,protocolID:[2,"counterparty linkage revelation"],keyID:a,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,revelationTime:a,encryptedLinkage:s,encryptedLinkageProof:o}}async revealSpecificKeyLinkage(e){let{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let r=this.keyDeriver.revealSpecificSecret(e.counterparty,e.protocolID,e.keyID),{ciphertext:i}=await this.encrypt({plaintext:r,protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier}),{ciphertext:n}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,protocolID:e.protocolID,keyID:e.keyID,encryptedLinkage:i,encryptedLinkageProof:n,proofType:0}}async encrypt(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{ciphertext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").encrypt(e.plaintext)}}async decrypt(e,t){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{plaintext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").decrypt(e.ciphertext)}}async createHmac(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{hmac:el(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data)}}async verifyHmac(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let t=el(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data),r=e.hmac,i=ty(e9(t),e9(r));if(!i){let e=Error("HMAC is not valid");throw e.code="ERR_INVALID_HMAC",e}return{valid:i}}async createSignature(e){if(null==e.hashToDirectlySign&&null==e.data)throw Error("args.data or args.hashToDirectlySign must be valid");let t=e.hashToDirectlySign??ea(e.data??[]),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??ea(e.data??[]),r=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf),i=tj(new P(t),tF.fromDER(e.signature),r);if(!i){let e=Error("Signature is not valid");throw e.code="ERR_INVALID_SIGNATURE",e}return{valid:i}}}let iP=iE;class iN{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 iO 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)}static unknownToJson(e){let t;return!0===e.isError&&String(e.name).startsWith("WERR_")?"WERR_REVIEW_ACTIONS"===(t={name:e.name,message:e.message,isError:!0}).name?(t.reviewActionResults=e.reviewActionResults,t.sendWithResults=e.sendWithResults,t.txid=e.txid,t.tx=e.tx,t.noSendChange=e.noSendChange,t.code=5):"WERR_INVALID_PARAMETER"===t.name?(t.parameter=e.parameter,t.code=6):"WERR_INSUFFICIENT_FUNDS"===t.name&&(t.totalSatoshisNeeded=e.totalSatoshisNeeded,t.moreSatoshisNeeded=e.moreSatoshisNeeded,t.code=7):t=e instanceof Error?{name:e.constructor.name,message:e.message,isError:!0}:{name:"WERR_UNKNOWN",message:String(e),isError:!0},JSON.stringify(t)}}(o=u||(u={}))[o.unknownError=1]="unknownError",o[o.unsupportedAction=2]="unsupportedAction",o[o.invalidHmac=3]="invalidHmac",o[o.invalidSignature=4]="invalidSignature",o[o.reviewActions=5]="reviewActions",o[o.invalidParameter=6]="invalidParameter",o[o.insufficientFunds=7]="insufficientFunds";let iA=iO;class i_{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 n=ta(tJ(12)),a=e=>{"CWI"===e.data.type&&e.isTrusted&&e.data.id===n&&!0!==e.data.isInvocation&&("function"==typeof window.removeEventListener&&window.removeEventListener("message",a),"error"===e.data.status?i(new iO(e.data.description,e.data.code)):r(e.data.result))};window.addEventListener("message",a),window.parent.postMessage({type:"CWI",isInvocation:!0,id:n,call:e,args:t},this.domain)})}async createAction(e){return await this.invoke("createAction",e)}async signAction(e){return await this.invoke("signAction",e)}async abortAction(e){return await this.invoke("abortAction",e)}async listActions(e){return await this.invoke("listActions",e)}async internalizeAction(e){return await this.invoke("internalizeAction",e)}async listOutputs(e){return await this.invoke("listOutputs",e)}async relinquishOutput(e){return await this.invoke("relinquishOutput",e)}async getPublicKey(e){return await this.invoke("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.invoke("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.invoke("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.invoke("encrypt",e)}async decrypt(e){return await this.invoke("decrypt",e)}async createHmac(e){return await this.invoke("createHmac",e)}async verifyHmac(e){return await this.invoke("verifyHmac",e)}async createSignature(e){return await this.invoke("createSignature",e)}async verifySignature(e){return await this.invoke("verifySignature",e)}async acquireCertificate(e){return await this.invoke("acquireCertificate",e)}async listCertificates(e){return await this.invoke("listCertificates",e)}async proveCertificate(e){return await this.invoke("proveCertificate",e)}async relinquishCertificate(e){return await this.invoke("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.invoke("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.invoke("discoverByAttributes",e)}async isAuthenticated(e){return await this.invoke("isAuthenticated",e)}async waitForAuthentication(e){return await this.invoke("waitForAuthentication",e)}async getHeight(e){return await this.invoke("getHeight",e)}async getHeaderForHeight(e){return await this.invoke("getHeaderForHeight",e)}async getNetwork(e){return await this.invoke("getNetwork",e)}async getVersion(e){return await this.invoke("getVersion",e)}}class iT{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(e,t,r,i,n,a,s){this.type=e,this.serialNumber=t,this.subject=r,this.certifier=i,this.revocationOutpoint=n,this.fields=a,this.signature=s}toBinary(e=!0){let t=new tu,r=e9(this.type,"base64");t.write(r);let i=e9(this.serialNumber,"base64");t.write(i);let n=e9(this.subject,"hex");t.write(n);let a=e9(this.certifier,"hex");t.write(a);let[s,o]=this.revocationOutpoint.split("."),c=e9(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=e9(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e9(r,"utf8");t.writeVarIntNum(n.length),t.write(n)}if(e&&(this.signature??"").length>0){let e=e9(this.signature,"hex");t.write(e)}return t.toArray()}static fromBinary(e){let t,r=new td(e),i=ta(r.read(32)),n=ta(r.read(32)),a=e7(r.read(33)),s=e7(r.read(33)),o=e7(r.read(32)),c=r.readVarIntNum(),l=`${o}.${c}`,h=r.readVarIntNum(),u={};for(let e=0;e<h;e++){let e=r.readVarIntNum(),t=ti(r.read(e)),i=r.readVarIntNum(),n=ti(r.read(i));u[t]=n}if(!r.eof()){let e=r.read();t=tF.fromDER(e).toString("hex")}return new iT(i,n,a,s,l,u,t)}async verify(){let e=new iP("anyone"),t=this.toBinary(!1),r=this.signature??"",{valid:i}=await e.verifySignature({signature:e9(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=e7(r)}static getCertificateFieldEncryptionDetails(e,t){return{protocolID:[2,"certificate field encryption"],keyID:t?`${t} ${e}`:e}}static fromObject(e){return new iT(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature)}}(c=d||(d={}))[c.createAction=1]="createAction",c[c.signAction=2]="signAction",c[c.abortAction=3]="abortAction",c[c.listActions=4]="listActions",c[c.internalizeAction=5]="internalizeAction",c[c.listOutputs=6]="listOutputs",c[c.relinquishOutput=7]="relinquishOutput",c[c.getPublicKey=8]="getPublicKey",c[c.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",c[c.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",c[c.encrypt=11]="encrypt",c[c.decrypt=12]="decrypt",c[c.createHmac=13]="createHmac",c[c.verifyHmac=14]="verifyHmac",c[c.createSignature=15]="createSignature",c[c.verifySignature=16]="verifySignature",c[c.acquireCertificate=17]="acquireCertificate",c[c.listCertificates=18]="listCertificates",c[c.proveCertificate=19]="proveCertificate",c[c.relinquishCertificate=20]="relinquishCertificate",c[c.discoverByIdentityKey=21]="discoverByIdentityKey",c[c.discoverByAttributes=22]="discoverByAttributes",c[c.isAuthenticated=23]="isAuthenticated",c[c.waitForAuthentication=24]="waitForAuthentication",c[c.getHeight=25]="getHeight",c[c.getHeaderForHeight=26]="getHeaderForHeight",c[c.getNetwork=27]="getNetwork",c[c.getVersion=28]="getVersion";let iC=d;class iR{wire;constructor(e){this.wire=e}async transmit(e,t="",r=[]){let i=new tu;i.writeUInt8(iC[e]);let n=e9(t,"utf8");i.writeUInt8(n.length),i.write(n),r.length>0&&i.write(r);let a=i.toArray(),s=new td(await this.wire.transmitToWallet(a)),o=s.readUInt8();if(0===o)return s.read();{let e=s.readVarIntNum(),t=ti(s.read(e)),r=s.readVarIntNum();throw new iO(t,o,ti(s.read(r)))}}async createAction(e,t){let r=new tu,i=e9(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=e9(t.unlockingScript,"hex");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1),r.writeVarIntNum(t.unlockingScriptLength??0);let e=e9(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=e9(t.lockingScript,"hex");r.writeVarIntNum(e.length),r.write(e),r.writeVarIntNum(t.satoshis);let i=e9(t.outputDescription,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=t.basket&&""!==t.basket){let e=e9(t.basket,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=t.customInstructions&&""!==t.customInstructions){let e=e9(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=e9(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=e9(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=e9(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=e9(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 n=new td(await this.transmit("createAction",t,r.toArray())),a={};if(1===n.readInt8()&&(a.txid=e7(n.read(32))),1===n.readInt8()){let e=n.readVarIntNum();a.tx=n.read(e)}let s=n.readVarIntNum();if(s>=0){a.noSendChange=[];for(let e=0;e<s;e++){let e=this.readOutpoint(n);a.noSendChange.push(e)}}let o=n.readVarIntNum();if(o>=0){a.sendWithResults=[];for(let e=0;e<o;e++){let e=e7(n.read(32)),t=n.readInt8(),r="unproven";1===t?r="unproven":2===t?r="sending":3===t&&(r="failed"),a.sendWithResults.push({txid:e,status:r})}}if(1===n.readInt8()){let e=n.readVarIntNum(),t=n.read(e),r=n.readVarIntNum();a.signableTransaction={tx:t,reference:ta(n.read(r))}}return a}async signAction(e,t){let r=new tu,i=Object.keys(e.spends);for(let t of(r.writeVarIntNum(i.length),i)){r.writeVarIntNum(Number(t));let i=e.spends[Number(t)],n=e9(i.unlockingScript,"hex");r.writeVarIntNum(n.length),r.write(n),"number"==typeof i.sequenceNumber?r.writeVarIntNum(i.sequenceNumber):r.writeVarIntNum(-1)}let n=e9(e.reference,"base64");if(r.writeVarIntNum(n.length),r.write(n),null!=e.options)if(r.writeInt8(1),"boolean"==typeof e.options.acceptDelayedBroadcast?r.writeInt8(+!!e.options.acceptDelayedBroadcast):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=e9(t,"hex");r.write(e)}else r.writeVarIntNum(-1);else r.writeInt8(0);let a=new td(await this.transmit("signAction",t,r.toArray())),s={};if(1===a.readInt8()&&(s.txid=e7(a.read(32))),1===a.readInt8()){let e=a.readVarIntNum();s.tx=a.read(e)}let o=a.readVarIntNum();if(o>=0){s.sendWithResults=[];for(let e=0;e<o;e++){let e=e7(a.read(32)),t=a.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,e9(e.reference,"base64")),{aborted:!0}}async listActions(e,t){let r=new tu;for(let t of(r.writeVarIntNum(e.labels.length),e.labels)){let e=e9(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 td(await this.transmit("listActions",t,r.toArray())),n=i.readVarIntNum(),a=[];for(let e=0;e<n;e++){let e,t=e7(i.read(32)),r=i.readVarIntNum(),n=i.readInt8();switch(n){case 1:e="completed";break;case 2:e="unprocessed";break;case 3:e="sending";break;case 4:e="unproven";break;case 5:e="unsigned";break;case 6:e="nosend";break;case 7:e="nonfinal";break;case 8:e="failed";break;default:throw Error(`Unknown status code: ${n}`)}let s=1===i.readInt8(),o=i.readVarIntNum(),c={txid:t,satoshis:r,status:e,isOutgoing:s,description:ti(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(ti(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),n=i.readVarIntNum(),a=i.readVarIntNum();a>=0&&(e=e7(i.read(a)));let s=i.readVarIntNum();s>=0&&(t=e7(i.read(s)));let o=i.readVarIntNum(),l=ti(i.read(o)),h=i.readVarIntNum();c.inputs.push({sourceOutpoint:r,sourceSatoshis:n,sourceLockingScript:e,unlockingScript:t,inputDescription:l,sequenceNumber:h})}}let u=i.readVarIntNum();if(u>=0){c.outputs=[];for(let e=0;e<u;e++){let e,t,r,n=i.readVarIntNum(),a=i.readVarIntNum(),s=i.readVarIntNum();s>=0&&(e=e7(i.read(s)));let o=1===i.readInt8(),l=i.readVarIntNum(),h=ti(i.read(l)),u=i.readVarIntNum();u>=0&&(t=ti(i.read(u)));let d=i.readVarIntNum(),f=[];if(d>=0)for(let e=0;e<d;e++){let e=i.readVarIntNum(),t=i.read(e);f.push(ti(t))}let p=i.readVarIntNum();p>=0&&(r=ti(i.read(p))),c.outputs.push({outputIndex:n,satoshis:a,lockingScript:e,spendable:o,outputDescription:h,basket:t,tags:f,customInstructions:r})}}a.push(c)}return{totalActions:n,actions:a}}async internalizeAction(e,t){let r=new tu;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(e9(t.paymentRemittance.senderIdentityKey,"hex"));let e=e9(t.paymentRemittance.derivationPrefix,"base64");r.writeVarIntNum(e.length),r.write(e);let i=e9(t.paymentRemittance.derivationSuffix,"base64");r.writeVarIntNum(i.length),r.write(i)}else{r.writeUInt8(2);let e=e9(t.insertionRemittance?.basket,"utf8");if(r.writeVarIntNum(e.length),r.write(e),"string"==typeof t.insertionRemittance?.customInstructions&&""!==t.insertionRemittance.customInstructions){let e=e9(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=e9(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=e9(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);let i=e9(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 tu,n=e9(e.basket,"utf8");if(i.writeVarIntNum(n.length),i.write(n),"object"==typeof e.tags)for(let t of(i.writeVarIntNum(e.tags.length),e.tags)){let e=e9(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 a=new td(await this.transmit("listOutputs",t,i.toArray())),s=a.readVarIntNum(),o=a.readVarIntNum();o>=0&&(r=a.read(o));let c=[];for(let e=0;e<s;e++){let e={spendable:!0,outpoint:this.readOutpoint(a),satoshis:a.readVarIntNum()},t=a.readVarIntNum();t>=0&&(e.lockingScript=e7(a.read(t)));let r=a.readVarIntNum();r>=0&&(e.customInstructions=ti(a.read(r)));let i=a.readVarIntNum();if(-1!==i){let t=[];for(let e=0;e<i;e++){let e=a.readVarIntNum();t.push(ti(a.read(e)))}e.tags=t}let n=a.readVarIntNum();if(-1!==n){let t=[];for(let e=0;e<n;e++){let e=a.readVarIntNum();t.push(ti(a.read(e)))}e.labels=t}c.push(e)}return{totalOutputs:s,BEEF:r,outputs:c}}async relinquishOutput(e,t){let r=new tu,i=e9(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 tu,[r,i]=e.split(".");return t.write(e9(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}readOutpoint(e){let t=e7(e.read(32)),r=e.readVarIntNum();return`${t}.${r}`}async getPublicKey(e,t){let r=new tu;return r.writeUInt8(+!!e.identityKey),e.identityKey?r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)):(r.write(this.encodeKeyRelatedParams(e.protocolID??=[h.Silent,"default"],e.keyID??="",e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?r.writeInt8(+!!e.forSelf):r.writeInt8(-1)),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{publicKey:e7(await this.transmit("getPublicKey",t,r.toArray()))}}async revealCounterpartyKeyLinkage(e,t){let r=new tu;r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),r.write(e9(e.counterparty,"hex")),r.write(e9(e.verifier,"hex"));let i=new td(await this.transmit("revealCounterpartyKeyLinkage",t,r.toArray())),n=e7(i.read(33)),a=e7(i.read(33)),s=e7(i.read(33)),o=i.readVarIntNum(),c=ti(i.read(o)),l=i.readVarIntNum(),h=i.read(l),u=i.readVarIntNum();return{prover:n,verifier:a,counterparty:s,revelationTime:c,encryptedLinkage:h,encryptedLinkageProof:i.read(u)}}async revealSpecificKeyLinkage(e,t){let r=new tu;r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.write(e9(e.verifier,"hex"));let i=new td(await this.transmit("revealSpecificKeyLinkage",t,r.toArray())),n=e7(i.read(33)),a=e7(i.read(33)),s=e7(i.read(33)),o=i.readUInt8(),c=i.readVarIntNum(),l=ti(i.read(c)),h=i.readVarIntNum(),u=ti(i.read(h)),d=i.readVarIntNum(),f=i.read(d),p=i.readVarIntNum();return{prover:n,verifier:a,counterparty:s,protocolID:[o,l],keyID:u,encryptedLinkage:f,encryptedLinkageProof:i.read(p),proofType:i.readUInt8()}}async encrypt(e,t){let r=new tu;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 tu;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 tu;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 tu;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 tu;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 tu;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,n){let a=new tu;a.writeUInt8(e[0]);let s=e9(e[1],"utf8");a.writeVarIntNum(s.length),a.write(s);let o=e9(t,"utf8");return a.writeVarIntNum(o.length),a.write(o),"string"!=typeof r?a.writeUInt8(0):"self"===r?a.writeUInt8(11):"anyone"===r?a.writeUInt8(12):a.write(e9(r,"hex")),a.write(this.encodePrivilegedParams(i,n)),a.toArray()}async acquireCertificate(e,t){let r=new tu;r.write(e9(e.type,"base64")),r.write(e9(e.certifier,"hex"));let i=Object.entries(e.fields);for(let[e,t]of(r.writeVarIntNum(i.length),i)){let i=e9(e,"utf8"),n=e9(t,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(n.length),r.write(n)}if(r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),r.writeUInt8("direct"===e.acquisitionProtocol?1:2),"direct"===e.acquisitionProtocol){r.write(e9(e.serialNumber,"base64")),r.write(this.encodeOutpoint(e.revocationOutpoint??""));let t=e9(e.signature,"hex");r.writeVarIntNum(t.length),r.write(t);let i="certifier"!==e.keyringRevealer?e9(e.keyringRevealer,"hex"):[11];r.write(i);let n=Object.keys(e.keyringForSubject??{});r.writeVarIntNum(n.length);for(let t=0;t<n.length;t++){let i=e9(n[t],"utf8");r.writeVarIntNum(i.length),r.write(i);let a=e9(e.keyringForSubject?.[n[t]],"base64");r.writeVarIntNum(a.length),r.write(a)}}else{let t=e9(e.certifierUrl,"utf8");r.writeVarIntNum(t.length),r.write(t)}let n=await this.transmit("acquireCertificate",t,r.toArray()),a=iT.fromBinary(n);return{...a,signature:a.signature}}encodePrivilegedParams(e,t){let r=new tu;if("boolean"==typeof e?r.writeInt8(+!!e):r.writeInt8(-1),"string"==typeof t){let e=e9(t,"utf8");r.writeInt8(e.length),r.write(e)}else r.writeInt8(-1);return r.toArray()}async listCertificates(e,t){let r=new tu;r.writeVarIntNum(e.certifiers.length);for(let t=0;t<e.certifiers.length;t++)r.write(e9(e.certifiers[t],"hex"));r.writeVarIntNum(e.types.length);for(let t=0;t<e.types.length;t++)r.write(e9(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 td(await this.transmit("listCertificates",t,r.toArray())),n=i.readVarIntNum(),a=[];for(let e=0;e<n;e++){let e,t=i.readVarIntNum(),r=i.read(t),n=iT.fromBinary(r),s={};if(1===i.readInt8()){let e=i.readVarIntNum();for(let t=0;t<e;t++){let e=i.readVarIntNum(),t=ti(i.read(e)),r=i.readVarIntNum();s[t]=ta(i.read(r))}}let o=i.readVarIntNum();o>0&&(e=ti(i.read(o))),a.push({...n,signature:n.signature,keyring:s,verifier:e})}return{totalCertificates:n,certificates:a}}async proveCertificate(e,t){let r=new tu,i=e9(e.certificate.type,"base64");r.write(i);let n=e9(e.certificate.subject,"hex");r.write(n);let a=e9(e.certificate.serialNumber,"base64");r.write(a);let s=e9(e.certificate.certifier,"hex");r.write(s);let o=this.encodeOutpoint(e.certificate.revocationOutpoint??"");r.write(o);let c=e9(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=e9(e,"utf8"),n=e9(t,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(n.length),r.write(n)}for(let t of(r.writeVarIntNum(e.fieldsToReveal.length),e.fieldsToReveal)){let e=e9(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}r.write(e9(e.verifier,"hex")),r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let h=new td(await this.transmit("proveCertificate",t,r.toArray())),u=h.readVarIntNum(),d={};for(let e=0;e<u;e++){let e=h.readVarIntNum(),t=ti(h.read(e)),r=h.readVarIntNum();d[t]=ta(h.read(r))}return{keyringForVerifier:d}}async relinquishCertificate(e,t){let r=new tu,i=e9(e.type,"base64");r.write(i);let n=e9(e.serialNumber,"base64");r.write(n);let a=e9(e.certifier,"hex");return r.write(a),await this.transmit("relinquishCertificate",t,r.toArray()),{relinquished:!0}}parseDiscoveryResult(e){let t=new td(e),r=t.readVarIntNum(),i=[];for(let e=0;e<r;e++){let e=t.readVarIntNum(),r=t.read(e),n=iT.fromBinary(r),a=t.readVarIntNum(),s=ti(t.read(a)),o=t.readVarIntNum(),c=ti(t.read(o)),l=t.readVarIntNum(),h=ti(t.read(l)),u=t.readUInt8(),d={},f=t.readVarIntNum();for(let e=0;e<f;e++){let e=t.readVarIntNum(),r=ti(t.read(e)),i=t.readVarIntNum();d[r]=t.read(i)}let p={},g=t.readVarIntNum();for(let e=0;e<g;e++){let e=t.readVarIntNum(),r=ti(t.read(e)),i=t.readVarIntNum();p[r]=ti(t.read(i))}i.push({...n,signature:n.signature,certifierInfo:{iconUrl:c,name:s,description:h,trust:u},publiclyRevealedKeyring:d,decryptedFields:p})}return{totalCertificates:r,certificates:i}}async discoverByIdentityKey(e,t){let r=new tu;r.write(e9(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 tu,i=Object.keys(e.attributes);r.writeVarIntNum(i.length);for(let t=0;t<i.length;t++)r.writeVarIntNum(i[t].length),r.write(e9(i[t],"utf8")),r.writeVarIntNum(e.attributes[i[t]].length),r.write(e9(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 n=await this.transmit("discoverByAttributes",t,r.toArray());return this.parseDiscoveryResult(n)}async isAuthenticated(e,t){return{authenticated:1===(await this.transmit("isAuthenticated",t))[0]}}async waitForAuthentication(e,t){return await this.transmit("waitForAuthentication",t),{authenticated:!0}}async getHeight(e,t){return{height:new td(await this.transmit("getHeight",t)).readVarIntNum()}}async getHeaderForHeight(e,t){let r=new tu;return r.writeVarIntNum(e.height),{header:e7(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:ti(await this.transmit("getVersion",t))}}}class iV{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 td(e),i=r.readUInt8(),n=iC[i];if(void 0===n||""===n)throw Error(`Invalid call code: ${i}`);let a=r.readUInt8();a>0&&(t=ti(r.read(a)));let s=r.read(),o=await fetch(`${this.baseUrl}/${n}`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Origin:t??""},body:new Uint8Array(s)});return Array.from(new Uint8Array(await o.arrayBuffer()))}}class iB extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(e,t,r,i,n){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=e,this.sendWithResults=t,this.txid=r,this.tx=i,this.noSendChange=n,this.code=5,this.name=this.constructor.name}}let iD=iB;class iU extends Error{parameter;code;isError=!0;constructor(e,t){super(`The ${e} parameter must be ${t??"valid."}`),this.parameter=e,this.code=6,this.name=this.constructor.name}}let iF=iU,iL=class extends Error{totalSatoshisNeeded;moreSatoshisNeeded;code;isError=!0;constructor(e,t){super(`Insufficient funds in the available inputs to cover the cost of the required outputs and the transaction fee (${t} more satoshis are needed, for a total of ${e}), plus whatever would be required in order to pay the fee to unlock and spend the outputs used to provide the additional satoshis.`),this.totalSatoshisNeeded=e,this.moreSatoshisNeeded=t,this.code=7,this.name=this.constructor.name}};class iK{baseUrl;httpClient;originator;api;constructor(e,t="http://localhost:3321",r=fetch){this.baseUrl=t,this.originator=e,this.httpClient=r;const i="undefined"!=typeof window&&"undefined"!=typeof document&&window?.origin!=="file://";this.api=async(e,t)=>{let n=!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!==n||console.error("Originator is required in Node.js environments");let a=await await r(`${this.baseUrl}/${e}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...n?{Origin:n}:{},...n?{Originator:n}:{}},body:JSON.stringify(t)}),s=await a.json();if(!a.ok){if(400===a.status&&s.isError){let e;switch(s.code){case 5:e=new iB(s.reviewActionResults,s.sendWithResults,s.txid,s.tx,s.noSendChange);break;case 6:(e=new iU(s.parameter)).message=s.message;break;case 7:e=new iL(s.totalSatoshisNeeded,s.moreSatoshisNeeded)}if(e)throw e}throw Error(JSON.stringify({call:e,args:t,message:s.message??`HTTP Client error ${a.status}`}))}return s}}async createAction(e){return await this.api("createAction",e)}async signAction(e){return await this.api("signAction",e)}async abortAction(e){return await this.api("abortAction",e)}async listActions(e){return await this.api("listActions",e)}async internalizeAction(e){return await this.api("internalizeAction",e)}async listOutputs(e){return await this.api("listOutputs",e)}async relinquishOutput(e){return await this.api("relinquishOutput",e)}async getPublicKey(e){return await this.api("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.api("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.api("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.api("encrypt",e)}async decrypt(e){return await this.api("decrypt",e)}async createHmac(e){return await this.api("createHmac",e)}async verifyHmac(e){return await this.api("verifyHmac",e)}async createSignature(e){return await this.api("createSignature",e)}async verifySignature(e){return await this.api("verifySignature",e)}async acquireCertificate(e){return await this.api("acquireCertificate",e)}async listCertificates(e){return await this.api("listCertificates",e)}async proveCertificate(e){return await this.api("proveCertificate",e)}async relinquishCertificate(e){return await this.api("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.api("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.api("discoverByAttributes",e)}async isAuthenticated(e){return await this.api("isAuthenticated",e)}async waitForAuthentication(e){return await this.api("waitForAuthentication",e)}async getHeight(e){return await this.api("getHeight",e)}async getHeaderForHeight(e){return await this.api("getHeaderForHeight",e)}async getNetwork(e){return await this.api("getNetwork",e)}async getVersion(e){return await this.api("getVersion",e)}}class iH{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 n=ta(tJ(12)),a=e=>{let t=JSON.parse(e.data);"CWI"===t.type&&t.id===n&&!0!==t.isInvocation&&("function"==typeof window.removeEventListener&&window.removeEventListener("message",a),"error"===t.status?i(new iO(t.description,t.code)):r(t.result))};window.addEventListener("message",a),window.ReactNativeWebView.postMessage(JSON.stringify({type:"CWI",isInvocation:!0,id:n,call:e,args:t}))})}async createAction(e){return await this.invoke("createAction",e)}async signAction(e){return await this.invoke("signAction",e)}async abortAction(e){return await this.invoke("abortAction",e)}async listActions(e){return await this.invoke("listActions",e)}async internalizeAction(e){return await this.invoke("internalizeAction",e)}async listOutputs(e){return await this.invoke("listOutputs",e)}async relinquishOutput(e){return await this.invoke("relinquishOutput",e)}async getPublicKey(e){return await this.invoke("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.invoke("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.invoke("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.invoke("encrypt",e)}async decrypt(e){return await this.invoke("decrypt",e)}async createHmac(e){return await this.invoke("createHmac",e)}async verifyHmac(e){return await this.invoke("verifyHmac",e)}async createSignature(e){return await this.invoke("createSignature",e)}async verifySignature(e){return await this.invoke("verifySignature",e)}async acquireCertificate(e){return await this.invoke("acquireCertificate",e)}async listCertificates(e){return await this.invoke("listCertificates",e)}async proveCertificate(e){return await this.invoke("proveCertificate",e)}async relinquishCertificate(e){return await this.invoke("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.invoke("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.invoke("discoverByAttributes",e)}async isAuthenticated(e){return await this.invoke("isAuthenticated",e)}async waitForAuthentication(e){return await this.invoke("waitForAuthentication",e)}async getHeight(e){return await this.invoke("getHeight",e)}async getHeaderForHeight(e){return await this.invoke("getHeaderForHeight",e)}async getNetwork(e){return await this.invoke("getNetwork",e)}async getVersion(e){return await this.invoke("getVersion",e)}}function iq(e){let[t,r]=e.split(".");return{txid:t,vout:Number(r)}}function iM(e){return e??!1}function i$(e,t,r,i){if(void 0!==e)return iG(e,t,r,i)}function iz(e,t,r){if(void 0===e||!Number.isInteger(e)||e<0||e>21e14)throw new iF(t,"a valid number of satoshis");if(void 0!==r&&e<r)throw new iF(t,`at least ${r} satoshis.`);return e}function iW(e,t,r,i){if(void 0!==e)return ij(e,t,void 0,r,i)}function ij(e,t,r,i,n){if(void 0===e){if(void 0!==r)return r;throw new iF(t,"a valid integer")}if(!Number.isInteger(e))throw new iF(t,"an integer");if(e=Number(e),void 0!==i&&e<i)throw new iF(t,`at least ${i} length.`);if(void 0!==n&&e>n)throw new iF(t,`no more than ${n} length.`);return e}function iX(e,t){return ij(e,t,0,0)}function iG(e,t,r,i){let n=e9(e,"utf8").length;if(void 0!==r&&n<r)throw new iF(t,`at least ${r} length.`);if(void 0!==i&&n>i)throw new iF(t,`no more than ${i} length.`);return e}function iY(e){return iQ(e,"basket",1,300)}function iJ(e){return iQ(e,"label",1,300)}function iZ(e){return iQ(e,"tag",1,300)}function iQ(e,t,r,i){let n=e9(e=e.trim().toLowerCase(),"utf8").length;if(void 0!==r&&n<r)throw new iF(t,`at least ${r} length.`);if(void 0!==i&&n>i)throw new iF(t,`no more than ${i} length.`);return e}function i0(e,t,r,i){if(void 0!==e)return i1(e,t,r,i)}function i1(e,t,r,i){if(0===(e=e.trim()).length)throw new iF(t,"valid base64 string");let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if((!(i>=65)||!(i<=90))&&(!(i>=97)||!(i<=122))&&(!(i>=48)||!(i<=57))&&43!==i&&47!==i){if(61===i){if(r<e.length-2)throw new iF(t,"valid base64 string");n++;continue}throw new iF(t,"valid base64 string")}}if(n>2||n>0&&e.length%4!=0)throw new iF(t,"valid base64 string");let a=e.length%4;if(0!==a&&a!==4-n)throw new iF(t,"valid base64 string");let s=Math.floor(3*(e.length-n)/4);if(void 0!==r&&s<r)throw new iF(t,`at least ${r} bytes`);if(void 0!==i&&s>i)throw new iF(t,`no more than ${i} bytes`);return e}function i2(e,t,r,i){if(void 0!==e)return i8(e,t,r,i)}function i8(e,t,r,i){if((e=e.trim().toLowerCase()).length%2==1)throw new iF(t,`even length, not ${e.length}.`);if(!/^[0-9A-Fa-f]+$/.test(e))throw new iF(t,"hexadecimal string.");if(void 0!==r&&e.length<r)throw new iF(t,`at least ${r} length.`);if(void 0!==i&&e.length>i)throw new iF(t,`no more than ${i} length.`);return e}function i3(e){return(e=e.trim()).length%2!=1&&!!/^[0-9A-Fa-f]+$/.test(e)}function i6(e){if(void 0===e.unlockingScript&&void 0===e.unlockingScriptLength)throw new iF("unlockingScript, unlockingScriptLength","at least one valid value.");let t=i2(e.unlockingScript,"unlockingScript"),r=e.unlockingScriptLength??(null!=t?t.length/2:0);if(t&&r!==t.length/2)throw new iF("unlockingScriptLength","length unlockingScript if both valid.");return{outpoint:iq(e.outpoint),inputDescription:iG(e.inputDescription,"inputDescription",5,2e3),unlockingScript:t,unlockingScriptLength:r,sequenceNumber:e.sequenceNumber??0xffffffff}}function i4(e){return{lockingScript:i8(e.lockingScript,"lockingScript"),satoshis:iz(e.satoshis,"satoshis"),outputDescription:iG(e.outputDescription,"outputDescription",5,2e3),basket:function(e){if(void 0!==e)return iY(e)}(e.basket),customInstructions:e.customInstructions,tags:(e.tags??[]).map(e=>iZ(e))}}function i5(e){let t=null!=e?e:{};return{signAndProcess:t.signAndProcess??!0,acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,knownTxids:t.knownTxids??[],returnTXIDOnly:iM(t.returnTXIDOnly),noSend:iM(t.noSend),noSendChange:(t.noSendChange??[]).map(e=>iq(e)),sendWith:t.sendWith??[],randomizeOutputs:t.randomizeOutputs??!0}}function i7(e,t){let r={description:iG(e.description,"description",5,2e3),inputBEEF:e.inputBEEF,inputs:(e.inputs??[]).map(e=>i6(e)),outputs:(e.outputs??[]).map(e=>i4(e)),lockTime:e.lockTime??0,version:e.version??1,labels:e.labels?.map(e=>iJ(e))??[],options:i5(e.options),logger:t,isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!1,isRemixChange:!1,isSignAction:!1,randomVals:void 0,includeAllSourceTransactions:!1,isTestWerrReviewActions:!1};return r.isTestWerrReviewActions=r.labels.includes(nv),r.isSendWith=r.options.sendWith.length>0,r.isRemixChange=!r.isSendWith&&0===r.inputs.length&&0===r.outputs.length,r.isNewTx=r.isRemixChange||r.inputs.length>0||r.outputs.length>0,r.isSignAction=r.isNewTx&&(!r.options.signAndProcess||r.inputs.some(e=>void 0===e.unlockingScript)),r.isDelayed=r.options.acceptDelayedBroadcast,r.isNoSend=r.options.noSend,r}function i9(e){let t=null!=e?e:{};return{acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,returnTXIDOnly:iM(t.returnTXIDOnly),noSend:iM(t.noSend),sendWith:t.sendWith??[]}}function ne(e){let t={spends:e.spends,reference:e.reference,options:i9(e.options),isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!0,isRemixChange:!1,isTestWerrReviewActions:!1};return t.isSendWith=t.options.sendWith.length>0,t.isDelayed=t.options.acceptDelayedBroadcast,t.isNoSend=t.options.noSend,t}function nt(e){return{reference:i1(e.reference,"reference")}}function nr(e){if(void 0!==e)return{derivationPrefix:i1(e.derivationPrefix,"derivationPrefix"),derivationSuffix:i1(e.derivationSuffix,"derivationSuffix"),senderIdentityKey:i8(e.senderIdentityKey,"senderIdentityKey")}}function ni(e){if(void 0!==e)return{basket:iY(e.basket),customInstructions:i$(e.customInstructions,"customInstructions",0,1e3),tags:(e.tags??[]).map(e=>iZ(e))}}function nn(e){if("basket insertion"!==e.protocol&&"wallet payment"!==e.protocol)throw new iF("protocol","'basket insertion' or 'wallet payment'");return{outputIndex:iX(e.outputIndex,"outputIndex"),protocol:e.protocol,paymentRemittance:nr(e.paymentRemittance),insertionRemittance:ni(e.insertionRemittance)}}function na(e){if(void 0!==e){for(let t of(iG(e=e.trim().toLowerCase(),"originator",1,250),e.split(".")))iG(t,"originator part",1,63);return e}}function ns(e){let t={tx:e.tx,outputs:e.outputs.map(e=>nn(e)),description:iG(e.description,"description",5,2e3),labels:(null!=e.labels?e.labels:[]).map(e=>iJ(e)),seekPermission:e.seekPermission??!0};try{if(rZ.fromBinary(t.tx).txs.length<1)throw new iF("tx","at least one transaction to internalize an output from")}catch{throw new iF("tx","valid with at least one transaction to internalize an output from")}if(t.outputs.length<1)throw new iF("outputs","at least one output to internalize from the transaction");return t}function no(e,t){if(void 0!==e)return nc(e,t)}function nc(e,t){let r=e.split(".");if(2!==r.length||!Number.isInteger(Number(r[1])))throw new iF(t,"txid as hex string and numeric output index joined with '.'");let i=i8(r[0],`${t} txid`,void 0,64),n=iX(Number(r[1]),`${t} vout`);return`${i}.${n}`}function nl(e){return{basket:iY(e.basket),output:nc(e.output,"output")}}function nh(e){return{type:i1(e.type,"type"),serialNumber:i1(e.serialNumber,"serialNumber"),certifier:i8(e.certifier,"certifier")}}function nu(e){return{certifiers:e.certifiers.map(e=>i8(e.trim(),"certifiers"))??[],types:e.types.map(e=>i1(e.trim(),"types"))??[],limit:ij(e.limit,"limit",10,1,1e4),offset:iX(e.offset??0,"offset"),privileged:iM(e.privileged),privilegedReason:i$(e.privilegedReason,"privilegedReason",5,50),partial:void 0}}function nd(e){for(let t of Object.keys(e))iG(t,"field name",1,50);return e}function nf(e){if("issuance"!==e.acquisitionProtocol)throw Error("Only acquire certificate via issuance requests allowed here.");if(e.serialNumber)throw new iF("serialNumber",'valid when acquisitionProtocol is "direct"');if(e.signature)throw new iF("signature",'valid when acquisitionProtocol is "direct"');if(e.revocationOutpoint)throw new iF("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(e.keyringRevealer)throw new iF("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null!=e.keyringForSubject)throw new iF("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(!e.certifierUrl)throw new iF("certifierUrl",'valid when acquisitionProtocol is "issuance"');if(e.privileged&&!e.privilegedReason)throw new iF("privilegedReason","valid when 'privileged' is true ");return{type:i1(e.type,"type"),certifier:i8(e.certifier,"certifier"),certifierUrl:e.certifierUrl,fields:nd(e.fields),privileged:iM(e.privileged),privilegedReason:i$(e.privilegedReason,"privilegedReason",5,50),subject:""}}function np(e){var t;if("direct"!==e.acquisitionProtocol)throw Error("Only acquire direct certificate requests allowed here.");if(!e.serialNumber)throw new iF("serialNumber",'valid when acquisitionProtocol is "direct"');if(!e.signature)throw new iF("signature",'valid when acquisitionProtocol is "direct"');if(!e.revocationOutpoint)throw new iF("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(!e.keyringRevealer)throw new iF("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null==e.keyringForSubject)throw new iF("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(e.privileged&&!e.privilegedReason)throw new iF("privilegedReason","valid when 'privileged' is true ");return{type:i1(e.type,"type"),serialNumber:i1(e.serialNumber,"serialNumber"),certifier:i8(e.certifier,"certifier"),revocationOutpoint:nc(e.revocationOutpoint,"revocationOutpoint"),fields:nd(e.fields),signature:i8(e.signature,"signature"),keyringRevealer:(t=e.keyringRevealer,"certifier"===t?t:i8(t,"keyringRevealer")),keyringForSubject:function(e,t){for(let r of Object.keys(e))iG(r,`${t} field name`,1,50),i1(e[r],`${t} field value`);return e}(e.keyringForSubject,"keyringForSubject"),privileged:iM(e.privileged),privilegedReason:i$(e.privilegedReason,"privilegedReason",5,50),subject:""}}function ng(e){if(e.privileged&&!e.privilegedReason)throw new iF("privilegedReason","valid when 'privileged' is true ");return{type:i0(e.certificate.type,"certificate.type"),serialNumber:i0(e.certificate.serialNumber,"certificate.serialNumber"),certifier:i2(e.certificate.certifier,"certificate.certifier"),subject:i2(e.certificate.subject,"certificate.subject"),revocationOutpoint:no(e.certificate.revocationOutpoint,"certificate.revocationOutpoint"),signature:i2(e.certificate.signature,"certificate.signature"),fieldsToReveal:(e.fieldsToReveal??[]).map(e=>iG(e,`fieldsToReveal ${e}`,1,50)),verifier:i8(e.verifier,"verifier"),privileged:iM(e.privileged),privilegedReason:i$(e.privilegedReason,"privilegedReason",5,50)}}function nb(e){return{identityKey:i8(e.identityKey,"identityKey",66,66),limit:ij(e.limit,"limit",10,1,1e4),offset:iX(e.offset??0,"offset"),seekPermission:iM(e.seekPermission)}}function ny(e){return{attributes:function(e){for(let t of Object.keys(e))iG(t,`field name ${t}`,1,50);return e}(e.attributes),limit:ij(e.limit,"limit",10,1,1e4),offset:iX(e.offset??0,"offset"),seekPermission:iM(e.seekPermission)}}function nm(e){let t;if(void 0===e.tagQueryMode||"any"===e.tagQueryMode)t="any";else if("all"===e.tagQueryMode)t="all";else throw new iF("tagQueryMode","undefined, 'any', or 'all'");return{basket:iG(e.basket,"basket",1,300),tags:(null!=e.tags?e.tags:[]).map(e=>iG(e,"tag",1,300)),tagQueryMode:t,includeLockingScripts:"locking scripts"===e.include,includeTransactions:"entire transactions"===e.include,includeCustomInstructions:iM(e.includeCustomInstructions),includeTags:iM(e.includeTags),includeLabels:iM(e.includeLabels),limit:ij(e.limit,"limit",10,1,1e4),offset:ij(e.offset,"offset",0,void 0,void 0),seekPermission:e.seekPermission??!0,knownTxids:[]}}function nw(e){let t;if(void 0===e.labelQueryMode||"any"===e.labelQueryMode)t="any";else if("all"===e.labelQueryMode)t="all";else throw new iF("labelQueryMode","undefined, 'any', or 'all'");return{labels:(null!=e.labels?e.labels:[]).map(e=>iJ(e)),labelQueryMode:t,includeLabels:iM(e.includeLabels),includeInputs:iM(e.includeInputs),includeInputSourceLockingScripts:iM(e.includeInputSourceLockingScripts),includeInputUnlockingScripts:iM(e.includeInputUnlockingScripts),includeOutputs:iM(e.includeOutputs),includeOutputLockingScripts:iM(e.includeOutputLockingScripts),limit:ij(e.limit,"limit",10,1,1e4),offset:ij(e.offset,"offset",0,0),seekPermission:e.seekPermission??!0}}let nv="a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a";class nI{substrate;originator;constructor(e="auto",t){"Cicada"===e&&(e=new iR(new iV(t))),"window.CWI"===e&&(e=new iN),"XDM"===e&&(e=new i_),"json-api"===e&&(e=new iK(t)),"react-native"===e&&(e=new iH(t)),"secure-json-api"===e&&(e=new iK(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 iN),e(()=>new iK(this.originator,"https://localhost:2121")),e(()=>new iK(this.originator)),e(()=>new iH(this.originator)),e(()=>new iR(new iV(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 i_,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 i7(e),await this.connectToSubstrate(),await this.substrate.createAction(e,this.originator)}async signAction(e){return ne(e),await this.connectToSubstrate(),await this.substrate.signAction(e,this.originator)}async abortAction(e){return nt(e),await this.connectToSubstrate(),await this.substrate.abortAction(e,this.originator)}async listActions(e){return nw(e),await this.connectToSubstrate(),await this.substrate.listActions(e,this.originator)}async internalizeAction(e){return ns(e),await this.connectToSubstrate(),await this.substrate.internalizeAction(e,this.originator)}async listOutputs(e){return nm(e),await this.connectToSubstrate(),await this.substrate.listOutputs(e,this.originator)}async relinquishOutput(e){return nl(e),await this.connectToSubstrate(),await this.substrate.relinquishOutput(e,this.originator)}async getPublicKey(e){return await this.connectToSubstrate(),await this.substrate.getPublicKey(e,this.originator)}async revealCounterpartyKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealCounterpartyKeyLinkage(e,this.originator)}async revealSpecificKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealSpecificKeyLinkage(e,this.originator)}async encrypt(e){return await this.connectToSubstrate(),await this.substrate.encrypt(e,this.originator)}async decrypt(e){return await this.connectToSubstrate(),await this.substrate.decrypt(e,this.originator)}async createHmac(e){return await this.connectToSubstrate(),await this.substrate.createHmac(e,this.originator)}async verifyHmac(e){return await this.connectToSubstrate(),await this.substrate.verifyHmac(e,this.originator)}async createSignature(e){return await this.connectToSubstrate(),await this.substrate.createSignature(e,this.originator)}async verifySignature(e){return await this.connectToSubstrate(),await this.substrate.verifySignature(e,this.originator)}async acquireCertificate(e){if("direct"===e.acquisitionProtocol)np(e);else if("issuance"===e.acquisitionProtocol)nf(e);else throw new iU("acquisitionProtocol",`valid. ${String(e.acquisitionProtocol)} is unrecognized.`);return await this.connectToSubstrate(),await this.substrate.acquireCertificate(e,this.originator)}async listCertificates(e){return nu(e),await this.connectToSubstrate(),await this.substrate.listCertificates(e,this.originator)}async proveCertificate(e){return ng(e),await this.connectToSubstrate(),await this.substrate.proveCertificate(e,this.originator)}async relinquishCertificate(e){return nh(e),await this.connectToSubstrate(),await this.substrate.relinquishCertificate(e,this.originator)}async discoverByIdentityKey(e){return nb(e),await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(e,this.originator)}async discoverByAttributes(e){return ny(e),await this.connectToSubstrate(),await this.substrate.discoverByAttributes(e,this.originator)}async isAuthenticated(e={}){return await this.connectToSubstrate(),await this.substrate.isAuthenticated(e,this.originator)}async waitForAuthentication(e={}){return await this.connectToSubstrate(),await this.substrate.waitForAuthentication(e,this.originator)}async getHeight(e={}){return await this.connectToSubstrate(),await this.substrate.getHeight(e,this.originator)}async getHeaderForHeight(e){return await this.connectToSubstrate(),await this.substrate.getHeaderForHeight(e,this.originator)}async getNetwork(e={}){return await this.connectToSubstrate(),await this.substrate.getNetwork(e,this.originator)}async getVersion(e={}){return await this.connectToSubstrate(),await this.substrate.getVersion(e,this.originator)}}class nk{wallet;constructor(e){this.wallet=e}decodeOutpoint(e){let t=e7(e.read(32)),r=e.readVarIntNum();return`${t}.${r}`}encodeOutpoint(e){let t=new tu,[r,i]=e.split(".");return t.write(e9(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}async transmitToWallet(e){let t=new td(e);try{let e=t.readUInt8(),r=iC[e];if(void 0===r||""===r)throw Error(`Invalid call code: ${e}`);let i=t.readUInt8(),n=t.read(i),a=ti(n);switch(r){case"createAction":{let e={},r=t.readVarIntNum(),i=t.read(r);e.description=ti(i);let n=t.readVarIntNum();n>=0?e.inputBEEF=t.read(n):e.inputBEEF=void 0;let s=t.readVarIntNum();if(s>=0){e.inputs=[];for(let 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=e7(e)}else r.unlockingScript=void 0,r.unlockingScriptLength=t.readVarIntNum();let n=t.readVarIntNum(),a=t.read(n);r.inputDescription=ti(a);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(),n=t.read(i);r.lockingScript=e7(n),r.satoshis=t.readVarIntNum();let a=t.readVarIntNum(),s=t.read(a);r.outputDescription=ti(s);let o=t.readVarIntNum();if(o>=0){let e=t.read(o);r.basket=ti(e)}else r.basket=void 0;let c=t.readVarIntNum();if(c>=0){let e=t.read(c);r.customInstructions=ti(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),n=ti(i);r.tags.push(n)}}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),n=ti(i);e.labels.push(n)}}else e.labels=void 0;let u=t.readInt8();if(1===u){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 n=t.readInt8();-1===n?e.options.trustSelf=void 0:1===n&&(e.options.trustSelf="known");let a=t.readVarIntNum();if(a>=0){e.options.knownTxids=[];for(let r=0;r<a;r++){let r=t.read(32),i=e7(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=e7(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 d=await this.wallet.createAction(e,a),f=new tu;if(null!=d.txid&&""!==d.txid?(f.writeInt8(1),f.write(e9(d.txid,"hex"))):f.writeInt8(0),null!=d.tx?(f.writeInt8(1),f.writeVarIntNum(d.tx.length),f.write(d.tx)):f.writeInt8(0),null!=d.noSendChange)for(let e of(f.writeVarIntNum(d.noSendChange.length),d.noSendChange))f.write(this.encodeOutpoint(e));else f.writeVarIntNum(-1);if(null!=d.sendWithResults)for(let e of(f.writeVarIntNum(d.sendWithResults.length),d.sendWithResults)){let t;f.write(e9(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!=d.signableTransaction){f.writeInt8(1),f.writeVarIntNum(d.signableTransaction.tx.length),f.write(d.signableTransaction.tx);let e=e9(d.signableTransaction.reference,"base64");f.writeVarIntNum(e.length),f.write(e)}else f.writeInt8(0);let p=new tu;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={},n=t.readVarIntNum(),a=t.read(n);i.unlockingScript=e7(a);let s=t.readVarIntNum();s>=0?i.sequenceNumber=s:i.sequenceNumber=void 0,e.spends[r]=i}let i=t.readVarIntNum(),n=t.read(i);e.reference=ta(n);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 n=t.readInt8();-1===n?e.options.noSend=void 0:e.options.noSend=1===n;let a=t.readVarIntNum();if(a>=0){e.options.sendWith=[];for(let r=0;r<a;r++){let r=t.read(32),i=e7(r);e.options.sendWith.push(i)}}else e.options.sendWith=void 0}else e.options=void 0;let o=await this.wallet.signAction(e,a),c=new tu;if(null!=o.txid&&""!==o.txid?(c.writeInt8(1),c.write(e9(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(e9(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 tu;return l.writeUInt8(0),l.write(c.toArray()),l.toArray()}case"abortAction":{let e=t.read(),r=ta(e);await this.wallet.abortAction({reference:r},a);let i=new tu;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(ti(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 n=t.readVarIntNum();n>=0?e.limit=n:e.limit=void 0;let s=t.readVarIntNum();s>=0?e.offset=s:e.offset=void 0;let o=t.readInt8();o>=0?e.seekPermission=1===o:e.seekPermission=void 0;let c=await this.wallet.listActions(e,a),l=new tu;for(let e of(l.writeVarIntNum(c.totalActions),c.actions)){let t;switch(l.write(e9(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=e9(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=e9(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=e9(t.sourceLockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);if(void 0!==t.unlockingScript){let e=e9(t.unlockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);let e=e9(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=e9(t.lockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);l.writeInt8(+!!t.spendable);let e=e9(t.outputDescription,"utf8");if(l.writeVarIntNum(e.length),l.write(e),void 0!==t.basket){let e=e9(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=e9(e,"utf8");l.writeVarIntNum(t.length),l.write(t)}else l.writeVarIntNum(-1);if(void 0!==t.customInstructions){let e=e9(t.customInstructions,"utf8");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1)}else l.writeVarIntNum(-1)}let h=new tu;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=e7(e);let i=t.readVarIntNum(),n=t.read(i);r.paymentRemittance.derivationPrefix=ta(n);let a=t.readVarIntNum(),s=t.read(a);r.paymentRemittance.derivationSuffix=ta(s)}else if(2===i){r.protocol="basket insertion",r.insertionRemittance={};let e=t.readVarIntNum(),i=t.read(e);r.insertionRemittance.basket=ti(i);let n=t.readVarIntNum();if(n>=0){let e=t.read(n);r.insertionRemittance.customInstructions=ti(e)}let a=t.readVarIntNum();if(a>0){r.insertionRemittance.tags=[];for(let e=0;e<a;e++){let e=t.readVarIntNum(),i=t.read(e);r.insertionRemittance.tags.push(ti(i))}}else r.insertionRemittance.tags=[]}e.outputs.push(r)}let n=t.readVarIntNum();if(n>=0){e.labels=[];for(let r=0;r<n;r++){let r=t.readVarIntNum();e.labels.push(ti(t.read(r)))}}let s=t.readVarIntNum();e.description=ti(t.read(s));let o=t.readInt8();o>=0?e.seekPermission=1===o:e.seekPermission=void 0,await this.wallet.internalizeAction(e,a);let c=new tu;return c.writeUInt8(0),c.toArray()}case"listOutputs":{let e={},r=t.readVarIntNum(),i=t.read(r);e.basket=ti(i);let n=t.readVarIntNum();if(n>0){e.tags=[];for(let r=0;r<n;r++){let r=t.readVarIntNum(),i=t.read(r);e.tags.push(ti(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 u=t.readVarIntNum();u>=0?e.limit=u:e.limit=void 0;let d=t.readVarIntNum();d>=0?e.offset=d:e.offset=void 0;let f=t.readInt8();f>=0?e.seekPermission=1===f:e.seekPermission=void 0;let p=await this.wallet.listOutputs(e,a),g=new tu;for(let e of(g.writeVarIntNum(p.totalOutputs),null!=p.BEEF?(g.writeVarIntNum(p.BEEF.length),g.write(p.BEEF)):g.writeVarIntNum(-1),p.outputs)){if(g.write(this.encodeOutpoint(e.outpoint)),g.writeVarIntNum(e.satoshis),void 0!==e.lockingScript){let t=e9(e.lockingScript,"hex");g.writeVarIntNum(t.length),g.write(t)}else g.writeVarIntNum(-1);if(void 0!==e.customInstructions){let t=e9(e.customInstructions,"utf8");g.writeVarIntNum(t.length),g.write(t)}else g.writeVarIntNum(-1);if(void 0!==e.tags)for(let t of(g.writeVarIntNum(e.tags.length),e.tags)){let e=e9(t,"utf8");g.writeVarIntNum(e.length),g.write(e)}else g.writeVarIntNum(-1);if(void 0!==e.labels)for(let t of(g.writeVarIntNum(e.labels.length),e.labels)){let e=e9(t,"utf8");g.writeVarIntNum(e.length),g.write(e)}else g.writeVarIntNum(-1)}let b=new tu;return b.writeUInt8(0),b.write(g.toArray()),b.toArray()}case"relinquishOutput":{let e={},r=t.readVarIntNum(),i=t.read(r);e.basket=ti(i),e.output=this.decodeOutpoint(t),await this.wallet.relinquishOutput(e,a);let n=new tu;return n.writeUInt8(0),n.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=ti(r)}else e.privilegedReason=void 0;let n=t.readInt8();-1===n?e.forSelf=void 0:e.forSelf=1===n}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=ti(r)}else e.privilegedReason=void 0}let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let n=await this.wallet.getPublicKey(e,a),s=new tu;s.writeUInt8(0);let o=e9(n.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 n=await this.wallet.encrypt(e,a),s=new tu;return s.writeUInt8(0),s.write(n.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 n=await this.wallet.decrypt(e,a),s=new tu;return s.writeUInt8(0),s.write(n.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 n=await this.wallet.createHmac(e,a),s=new tu;return s.writeUInt8(0),s.write(n.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,a);let n=new tu;return n.writeUInt8(0),n.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 n=await this.wallet.createSignature(e,a),s=new tu;return s.writeUInt8(0),s.write(n.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 n=t.readUInt8();if(1===n){let r=t.readVarIntNum();e.data=t.read(r)}else 2===n&&(e.hashToDirectlyVerify=t.read(32));let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0,await this.wallet.verifySignature(e,a);let o=new tu;return o.writeUInt8(0),o.toArray()}case"isAuthenticated":{let e=await this.wallet.isAuthenticated({},a),t=new tu;return t.writeUInt8(0),t.writeUInt8(+!!e.authenticated),t.toArray()}case"waitForAuthentication":{await this.wallet.waitForAuthentication({},a);let e=new tu;return e.writeUInt8(0),e.toArray()}case"getHeight":{let e=await this.wallet.getHeight({},a),t=new tu;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,a),i=new tu;i.writeUInt8(0);let n=e9(r.header,"hex");return i.write(n),i.toArray()}case"getNetwork":{let e=await this.wallet.getNetwork({},a),t=new tu;return t.writeUInt8(0),t.writeUInt8(+("mainnet"!==e.network)),t.toArray()}case"getVersion":{let e=await this.wallet.getVersion({},a),t=new tu;t.writeUInt8(0);let r=e9(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=ti(r)}let n=t.read(33);e.counterparty=e7(n);let s=t.read(33);e.verifier=e7(s);let o=await this.wallet.revealCounterpartyKeyLinkage(e,a),c=new tu;c.write(e9(o.prover,"hex")),c.write(e9(o.verifier,"hex")),c.write(e9(o.counterparty,"hex"));let l=e9(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 tu;return h.writeUInt8(0),h.write(c.toArray()),h.toArray()}case"revealSpecificKeyLinkage":{let e=this.decodeKeyRelatedParams(t),r=t.read(33);e.verifier=e7(r);let i=await this.wallet.revealSpecificKeyLinkage(e,a),n=new tu;n.write(e9(i.prover,"hex")),n.write(e9(i.verifier,"hex")),n.write(e9(i.counterparty,"hex")),n.writeUInt8(i.protocolID[0]);let s=e9(i.protocolID[1],"utf8");n.writeVarIntNum(s.length),n.write(s);let o=e9(i.keyID,"utf8");n.writeVarIntNum(o.length),n.write(o),n.writeVarIntNum(i.encryptedLinkage.length),n.write(i.encryptedLinkage),n.writeVarIntNum(i.encryptedLinkageProof.length),n.write(i.encryptedLinkageProof),n.writeUInt8(i.proofType);let c=new tu;return c.writeUInt8(0),c.write(n.toArray()),c.toArray()}case"acquireCertificate":{let e={},r=t.read(32);e.type=ta(r);let i=t.read(33);e.certifier=e7(i);let n=t.readVarIntNum();e.fields={};for(let r=0;r<n;r++){let r=t.readVarIntNum(),i=t.read(r),n=ti(i),a=t.readVarIntNum(),s=t.read(a),o=ti(s);e.fields[n]=o}let s=t.readInt8();-1===s?e.privileged=void 0:e.privileged=1===s;let o=t.readInt8();if(-1===o)e.privilegedReason=void 0;else{let r=t.read(o);e.privilegedReason=ti(r)}let c=t.readUInt8();if(e.acquisitionProtocol=1===c?"direct":"issuance","direct"===e.acquisitionProtocol){let r=t.read(32);e.serialNumber=ta(r),e.revocationOutpoint=this.decodeOutpoint(t);let i=t.readVarIntNum(),n=t.read(i);e.signature=e7(n);let a=t.readUInt8();if(11===a)e.keyringRevealer="certifier";else{let r=[a].concat(t.read(32));e.keyringRevealer=e7(r)}let s=t.readVarIntNum();e.keyringForSubject={};for(let r=0;r<s;r++){let r=t.readVarIntNum(),i=t.read(r),n=ti(i),a=t.readVarIntNum(),s=t.read(a),o=ta(s);e.keyringForSubject[n]=o}}else{let r=t.readVarIntNum(),i=t.read(r);e.certifierUrl=ti(i)}let l=await this.wallet.acquireCertificate(e,a),h=new iT(l.type,l.serialNumber,l.subject,l.certifier,l.revocationOutpoint,l.fields,l.signature).toBinary(),u=new tu;return u.writeUInt8(0),u.write(h),u.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(e7(r))}let i=t.readVarIntNum();e.types=[];for(let r=0;r<i;r++){let r=t.read(32);e.types.push(ta(r))}let n=t.readVarIntNum();n>=0?e.limit=n:e.limit=void 0;let s=t.readVarIntNum();s>=0?e.offset=s:e.offset=void 0;let o=t.readInt8();-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=ti(r)}let l=await this.wallet.listCertificates(e,a),h=new tu;for(let e of(h.writeVarIntNum(l.totalCertificates),l.certificates)){let t=new iT(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=e9(e,"utf8");h.writeVarIntNum(t.length),h.write(t);let i=e9(r,"base64");h.writeVarIntNum(i.length),h.write(i)}}else h.writeInt8(0);let r=e9(e.verifier,"hex");h.writeVarIntNum(r.length),h.write(r)}let u=new tu;return u.writeUInt8(0),u.write(h.toArray()),u.toArray()}case"proveCertificate":{let e={},r={},i=t.read(32);r.type=ta(i);let n=t.read(33);r.subject=e7(n);let s=t.read(32);r.serialNumber=ta(s);let o=t.read(33);r.certifier=e7(o),r.revocationOutpoint=this.decodeOutpoint(t);let c=t.readVarIntNum(),l=t.read(c);r.signature=e7(l);let h=t.readVarIntNum();r.fields={};for(let e=0;e<h;e++){let e=t.readVarIntNum(),i=t.read(e),n=ti(i),a=t.readVarIntNum(),s=t.read(a),o=ti(s);r.fields[n]=o}e.certificate=r;let u=t.readVarIntNum();e.fieldsToReveal=[];for(let r=0;r<u;r++){let r=t.readVarIntNum(),i=t.read(r),n=ti(i);e.fieldsToReveal.push(n)}let d=t.read(33);e.verifier=e7(d);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=ti(r)}let g=await this.wallet.proveCertificate(e,a),b=new tu,y=Object.entries(g.keyringForVerifier);for(let[e,t]of(b.writeVarIntNum(y.length),y)){let r=e9(e,"utf8");b.writeVarIntNum(r.length),b.write(r);let i=e9(t,"base64");b.writeVarIntNum(i.length),b.write(i)}let m=new tu;return m.writeUInt8(0),m.write(b.toArray()),m.toArray()}case"relinquishCertificate":{let e={},r=t.read(32);e.type=ta(r);let i=t.read(32);e.serialNumber=ta(i);let n=t.read(33);e.certifier=e7(n),await this.wallet.relinquishCertificate(e,a);let s=new tu;return s.writeUInt8(0),s.toArray()}case"discoverByIdentityKey":{let e={},r=t.read(33);e.identityKey=e7(r);let i=t.readVarIntNum();i>=0?e.limit=i:e.limit=void 0;let n=t.readVarIntNum();n>=0?e.offset=n:e.offset=void 0;let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0;let o=await this.wallet.discoverByIdentityKey(e,a),c=this.serializeDiscoveryResult(o),l=new tu;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),n=ti(i),a=t.readVarIntNum(),s=t.read(a),o=ti(s);e.attributes[n]=o}let i=t.readVarIntNum();i>=0?e.limit=i:e.limit=void 0;let n=t.readVarIntNum();n>=0?e.offset=n:e.offset=void 0;let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0;let o=await this.wallet.discoverByAttributes(e,a),c=this.serializeDiscoveryResult(o),l=new tu;return l.writeUInt8(0),l.write(c),l.toArray()}default:throw Error(`Method ${r} not implemented`)}}catch(i){let e=new tu;e.writeUInt8("number"==typeof i.code?i.code:1);let t=e9("string"==typeof i.message?i.message:"Unknown error","utf8");e.writeVarIntNum(t.length),e.write(t);let r=e9("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,ti(e.read(r))]}decodeString(e){let t=e.readVarIntNum();return ti(e.read(t))}decodeCounterparty(e){let t=e.readUInt8();return 11===t?"self":12===t?"anyone":0!==t?e7([t,...e.read(32)]):void 0}serializeDiscoveryResult(e){let t=new tu;for(let r of(t.writeVarIntNum(e.totalCertificates),e.certificates)){let e=new iT(r.type,r.serialNumber,r.subject,r.certifier,r.revocationOutpoint,r.fields,r.signature).toBinary();t.writeVarIntNum(e.length),t.write(e);let i=e9(r.certifierInfo.name,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e9(r.certifierInfo.iconUrl,"utf8");t.writeVarIntNum(n.length),t.write(n);let a=e9(r.certifierInfo.description,"utf8");t.writeVarIntNum(a.length),t.write(a),t.writeUInt8(r.certifierInfo.trust);let s=Object.entries(r.publiclyRevealedKeyring);for(let[e,r]of(t.writeVarIntNum(s.length),s)){let i=e9(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e9(r,"base64");t.writeVarIntNum(n.length),t.write(n)}let o=Object.entries(r.decryptedFields);for(let[e,r]of(t.writeVarIntNum(o.length),o)){let i=e9(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e9(r,"utf8");t.writeVarIntNum(n.length),t.write(n)}}return t.toArray()}decodeKeyRelatedParams(e){let t={};t.protocolID=this.decodeProtocolID(e);let r=e.readVarIntNum();t.keyID=ti(e.read(r)),t.counterparty=this.decodeCounterparty(e);let i=e.readInt8();-1===i?t.privileged=void 0:t.privileged=1===i;let n=e.readInt8();return -1===n?t.privilegedReason=void 0:t.privilegedReason=ti(e.read(n)),t}}class nS extends iT{masterKeyring;constructor(e,t,r,i,n,a,s,o){for(const c of(super(e,t,r,i,n,a,o),Object.keys(a)))if(void 0===s[c]||""===s[c])throw Error(`Master keyring must contain a value for every field. Missing or empty key for field: "${c}".`);this.masterKeyring=s}static async createCertificateFields(e,t,r,i,n){let a={},s={};for(let[o,c]of Object.entries(r)){let r=rl.fromRandom(),l=r.encrypt(e9(c,"utf8"));a[o]=ta(l);let{ciphertext:h}=await e.encrypt({plaintext:r.toArray(),...iT.getCertificateFieldEncryptionDetails(o),counterparty:t,privileged:i,privilegedReason:n});s[o]=ta(h)}return{certificateFields:a,masterKeyring:s}}static async createKeyringForVerifier(e,t,r,i,n,a,s,o,c){if(!Array.isArray(n))throw Error("fieldsToReveal must be an array of strings");let l={};for(let h of n){if(void 0===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 n=(await this.decryptField(e,a,h,i[h],t,o,c)).fieldRevelationKey,{ciphertext:u}=await e.encrypt({plaintext:n,...iT.getCertificateFieldEncryptionDetails(h,s),counterparty:r,privileged:o,privilegedReason:c});l[h]=ta(u)}return l}static async issueCertificateForSubject(e,t,r,i,n=async e=>"00".repeat(32),a){let s=a??ta(tJ(32)),{certificateFields:o,masterKeyring:c}=await this.createCertificateFields(e,t,r),l=await n(s),h=new nS(i,s,"self"===t?(await e.getPublicKey({identityKey:!0})).publicKey:t,(await e.getPublicKey({identityKey:!0})).publicKey,l,o,c);return await h.sign(e),h}static async decryptFields(e,t,r,i,n,a){if(null==t||0===Object.keys(t).length)throw Error("A MasterCertificate must have a valid masterKeyring!");try{let s={};for(let o of Object.keys(r))s[o]=(await this.decryptField(e,t,o,r[o],i,n,a)).decryptedFieldValue;return s}catch{throw Error("Failed to decrypt all master certificate fields.")}}static async decryptField(e,t,r,i,n,a,s){if(null==t||0===Object.keys(t).length)throw Error("A MasterCertificate must have a valid masterKeyring!");try{let{plaintext:o}=await e.decrypt({ciphertext:e9(t[r],"base64"),...iT.getCertificateFieldEncryptionDetails(r),counterparty:n,privileged:a,privilegedReason:s}),c=new rl(o).decrypt(e9(i,"base64"));return{fieldRevelationKey:o,decryptedFieldValue:ti(c)}}catch{throw Error("Failed to decrypt certificate field!")}}}class nx extends iT{keyring;decryptedFields;constructor(e,t,r,i,n,a,s,o,c){super(e,t,r,i,n,a,o),this.keyring=s,this.decryptedFields=c}static fromCertificate(e,t){return new nx(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,t,e.signature)}async decryptFields(e,t,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 n={};for(let a in this.keyring){let{plaintext:s}=await e.decrypt({ciphertext:e9(this.keyring[a],"base64"),...iT.getCertificateFieldEncryptionDetails(a,this.serialNumber),counterparty:this.subject,privileged:t,privilegedReason:r},i),o=new rl(s).decrypt(e9(this.fields[a],"base64"));n[a]=ti(o)}return n}catch(e){throw Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(e instanceof Error?e.message:e)}`)}}}class nE extends iP{keyDeriver;constructor(e){if(super(e),e instanceof iS)this.keyDeriver=e;else if("string"==typeof e||e instanceof t1)this.keyDeriver=new ix(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 nP{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 nN(e,t,r="self",i){let n=e9(e,"base64"),a=n.slice(0,16),s=n.slice(16),{valid:o}=await t.verifyHmac({data:a,hmac:s,protocolID:[2,"server hmac"],keyID:ti(a),counterparty:r},i);return o}async function nO(e,t="self",r){let i=tJ(16),{hmac:n}=await e.createHmac({protocolID:[2,"server hmac"],keyID:ti(i),data:i,counterparty:t},r);return ta([...i,...n])}let nA=async(e,t,r,i)=>{let n=await e.listCertificates({certifiers:t.certifiers,types:Object.keys(t.types)},i);return await Promise.all(n.certificates.map(async n=>{let{keyringForVerifier:a}=await e.proveCertificate({certificate:n,fieldsToReveal:t.types[n.type],verifier:r},i);return new nx(n.type,n.serialNumber,n.subject,n.certifier,n.revocationOutpoint,n.fields,a,n.signature)}))},n_=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 n=>{if(n.subject!==t.identityKey)throw Error(`The subject of one of your certificates ("${n.subject}") is not the same as the request sender ("${t.identityKey}").`);let a=new nx(n.type,n.serialNumber,n.subject,n.certifier,n.revocationOutpoint,n.fields,n.keyring,n.signature);if(!await a.verify())throw Error(`The signature for the certificate with serial number ${a.serialNumber} is invalid!`);if(null!=r){let{certifiers:e,types:t}=r;if(!e.includes(a.certifier))throw Error(`Certificate with serial number ${a.serialNumber} has an unrequested certifier: ${a.certifier}`);if(null==t[a.type])throw Error(`Certificate with type ${a.type} was not requested`)}await a.decryptFields(e,void 0,void 0,i)}))},nT="undefined"!=typeof globalThis?globalThis.Buffer:void 0;class nC{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;originator;identityPublicKey;constructor(e,t,r,i,n,a){this.wallet=e,this.originator=a,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 nP,!1===n?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);if(null==i.peerIdentityKey)throw Error("Peer identity is not established");if(!0===i.certificatesRequired&&!0!==i.certificatesValidated)throw Error("Cannot send general message before certificate validation is complete");let n=ta(tJ(32)),{signature:a}=await this.wallet.createSignature({data:e,protocolID:[2,"auth message signature"],keyID:`${n} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),s={version:"0.1",messageType:"general",identityKey:await this.getIdentityPublicKey(),nonce:n,yourNonce:i.peerNonce,payload:e,signature:a};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}async requestCertificates(e,t,r=1e4){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);let i=await this.getAuthenticatedSession(t,r),n=ta(tJ(32)),{signature:a}=await this.wallet.createSignature({data:nC.utf8ToBytes(JSON.stringify(e)),protocolID:[2,"auth message signature"],keyID:`${n} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),s={version:"0.1",messageType:"certificateRequest",identityKey:await this.getIdentityPublicKey(),nonce:n,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,requestedCertificates:e,signature:a};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}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 nO(this.wallet,void 0,this.originator),i=Date.now(),n=this.certificatesToRequest.certifiers.length>0;this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:r,peerIdentityKey:e,lastUpdate:i,certificatesRequired:n,certificatesValidated:!n});let a={version:"0.1",messageType:"initialRequest",identityKey:await this.getIdentityPublicKey(),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 n=this.listenForInitialResponse(e,e=>{clearTimeout(a),this.stopListeningForInitialResponses(n),r(e)}),a=setTimeout(()=>{this.stopListeningForInitialResponses(n),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)}propagateTransportError(e,t){if(t instanceof Error){if(null!=e){let r=t.details;null!=r&&"object"==typeof r?null==r.peerIdentityKey&&(r.peerIdentityKey=e):t.details={peerIdentityKey:e}}throw t}throw Error(`Failed to send message to peer ${e??"unknown"}: ${String(t)}`)}async handleIncomingMessage(e){if("string"!=typeof e.version||"0.1"!==e.version)throw Error(`Invalid or unsupported message auth version! Received: ${e.version}, expected: 0.1`);try{switch(e.messageType){case"initialRequest":await this.processInitialRequest(e);break;case"initialResponse":await this.processInitialResponse(e);break;case"certificateRequest":await this.processCertificateRequest(e);break;case"certificateResponse":await this.processCertificateResponse(e);break;case"general":await this.processGeneralMessage(e);break;default:throw Error(`Unknown message type of ${String(e.messageType)} from ${String(e.identityKey)}`)}}catch(e){}}async processInitialRequest(e){let t;if("string"!=typeof e.identityKey||"string"!=typeof e.initialNonce||""===e.initialNonce)throw Error("Missing required fields in initialRequest message.");let r=await nO(this.wallet,void 0,this.originator),i=Date.now(),n=Array.isArray(this.certificatesToRequest?.certifiers)&&this.certificatesToRequest.certifiers.length>0;this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:r,peerNonce:e.initialNonce,peerIdentityKey:e.identityKey,lastUpdate:i,certificatesRequired:n,certificatesValidated:!n}),Array.isArray(e.requestedCertificates?.certifiers)&&e.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)}):t=await nA(this.wallet,e.requestedCertificates,e.identityKey,this.originator));let{signature:a}=await this.wallet.createSignature({data:nC.base64ToBytes(e.initialNonce+r),protocolID:[2,"auth message signature"],keyID:`${e.initialNonce} ${r}`,counterparty:e.identityKey},this.originator),s={version:"0.1",messageType:"initialResponse",identityKey:await this.getIdentityPublicKey(),initialNonce:r,yourNonce:e.initialNonce,certificates:t,requestedCertificates:this.certificatesToRequest,signature:a};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=e.identityKey),await this.transport.send(s)}async processInitialResponse(e){if(!await nN(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=nC.base64ToBytes((t.sessionNonce??"")+(e.initialNonce??"")),{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.certificatesRequired=Array.isArray(this.certificatesToRequest?.certifiers)&&this.certificatesToRequest.certifiers.length>0,t.certificatesValidated=!t.certificatesRequired,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),t.certificatesRequired&&Array.isArray(e.certificates)&&e.certificates.length>0&&(await n_(this.wallet,e,this.certificatesToRequest,this.originator),t.certificatesValidated=!0,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),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 nA(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async processCertificateRequest(e){if(!await nN(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:nC.utf8ToBytes(JSON.stringify(e.requestedCertificates)),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 nA(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=ta(tJ(32)),{signature:n}=await this.wallet.createSignature({data:nC.utf8ToBytes(JSON.stringify(t)),protocolID:[2,"auth message signature"],keyID:`${i} ${r.peerNonce??""}`,counterparty:r.peerIdentityKey},this.originator),a={version:"0.1",messageType:"certificateResponse",identityKey:await this.getIdentityPublicKey(),nonce:i,initialNonce:r.sessionNonce,yourNonce:r.peerNonce,certificates:t,signature:n};r.lastUpdate=Date.now(),this.sessionManager.updateSession(r);try{await this.transport.send(a)}catch(e){this.propagateTransportError(r.peerIdentityKey,e)}}async processCertificateResponse(e){if(!await nN(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:nC.utf8ToBytes(JSON.stringify(e.certificates)),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 n_(this.wallet,e,e.requestedCertificates,this.originator),t.certificatesValidated=!0,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.onCertificatesReceivedCallbacks.forEach(t=>{t(e.identityKey,e.certificates??[])})}async processGeneralMessage(e){if(!await nN(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 r=!0===t.certificatesRequired,i=!0===t.certificatesValidated;if(r&&!i)throw Error(`Received general message before certificate validation from peer ${t.peerIdentityKey??"unknown"}`);let{valid:n}=await this.wallet.verifySignature({data:e.payload,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!n)throw Error(`Invalid signature in generalMessage from ${t.peerIdentityKey}`);t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.lastInteractedWithPeer=e.identityKey,this.onGeneralMessageReceivedCallbacks.forEach(t=>{t(e.identityKey,e.payload??[])})}async getIdentityPublicKey(){if(null!=this.identityPublicKey)return this.identityPublicKey;let{publicKey:e}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return this.identityPublicKey=e,e}static utf8ToBytes(e){return null!=nT?Array.from(nT.from(e,"utf8")):"undefined"!=typeof TextEncoder?Array.from(new TextEncoder().encode(e)):e9(e,"utf8")}static base64ToBytes(e){return null!=nT?Array.from(nT.from(e,"base64")):e9(e,"base64")}}let nR="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch;class nV{onDataCallback;fetchClient;baseUrl;constructor(e,t=nR){if("function"!=typeof t)throw Error("SimplifiedFetchTransport requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=t,this.baseUrl=e}async send(e){if(null==this.onDataCallback)throw Error("Listen before you start speaking. God gave you two ears and one mouth for a reason.");if("general"!==e.messageType)return await new Promise((t,r)=>{(async()=>{try{let r=`${this.baseUrl}/.well-known/auth`,i=(async()=>{try{return await this.fetchClient(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(e){throw this.createNetworkError(r,e)}})();"initialRequest"!==e.messageType&&t();let n=await i;if(!n.ok){let e=Array.from(new Uint8Array(await n.arrayBuffer()));throw this.createUnauthenticatedResponseError(r,n,e)}if(null!=this.onDataCallback){let e=await n.json();this.onDataCallback(e)}"initialRequest"===e.messageType&&t()}catch(e){r(e)}})()});{let t,r,i=this.deserializeRequestPayload(e.payload),n=`${this.baseUrl}${i.urlPostfix}`;if("object"!=typeof i.headers&&(i.headers={}),i.headers["x-bsv-auth-version"]=e.version,i.headers["x-bsv-auth-identity-key"]=e.identityKey,i.headers["x-bsv-auth-nonce"]=e.nonce,i.headers["x-bsv-auth-your-nonce"]=e.yourNonce,i.headers["x-bsv-auth-signature"]=e7(e.signature),i.headers["x-bsv-auth-request-id"]=i.requestId,null!=i.body){let e=i.headers;if(null==e["content-type"])throw Error("Content-Type header is required for requests with a body.");let t=String(e["content-type"]??"");t.includes("application/json")||t.includes("application/x-www-form-urlencoded")||t.includes("text/plain")?i.body=ti(i.body):i.body=new Uint8Array(i.body)}try{t=await this.fetchClient(n,{method:i.method,headers:i.headers,body:i.body})}catch(e){throw this.createNetworkError(n,e)}let a=Array.from(new Uint8Array(await t.arrayBuffer())),s=["x-bsv-auth-version","x-bsv-auth-identity-key","x-bsv-auth-signature"].filter(e=>{let r=t.headers.get(e);return null==r||0===r.trim().length});if(s.length>0)throw this.createUnauthenticatedResponseError(n,t,a,s);let o=t.headers.get("x-bsv-auth-requested-certificates");if(null!=o)try{r=JSON.parse(o)}catch(e){throw this.createMalformedHeaderError(n,"x-bsv-auth-requested-certificates",o,e)}let c=new tu;null!=t.headers.get("x-bsv-auth-request-id")&&c.write(e9(t.headers.get("x-bsv-auth-request-id"),"base64")),c.writeVarIntNum(t.status);let l=[];t.headers.forEach((e,t)=>{let r=t.toLowerCase();(r.startsWith("x-bsv-")||"authorization"===r)&&!r.startsWith("x-bsv-auth")&&l.push([r,e])}),l.sort(([e],[t])=>e.localeCompare(t)),c.writeVarIntNum(l.length);for(let e=0;e<l.length;e++){let t=e9(l[e][0],"utf8");c.writeVarIntNum(t.length),c.write(t);let r=e9(l[e][1],"utf8");c.writeVarIntNum(r.length),c.write(r)}c.writeVarIntNum(a.length),a.length>0&&c.write(a);let h={version:t.headers.get("x-bsv-auth-version"),messageType:"certificateRequest"===t.headers.get("x-bsv-auth-message-type")?"certificateRequest":"general",identityKey:t.headers.get("x-bsv-auth-identity-key"),nonce:t.headers.get("x-bsv-auth-nonce")??void 0,yourNonce:t.headers.get("x-bsv-auth-your-nonce")??void 0,requestedCertificates:r,payload:c.toArray(),signature:e9(t.headers.get("x-bsv-auth-signature"),"hex")};if(null==h.version)throw this.createUnauthenticatedResponseError(n,t,a);this.onDataCallback(h)}}async onData(e){this.onDataCallback=t=>{e(t)}}createNetworkError(e,t){let r=`Network error while sending authenticated request to ${e}`;if(t instanceof Error){let e=Error(`${r}: ${t.message}`);return e.stack=t.stack,e.cause=t,e}return Error(`${r}: ${String(t)}`)}createUnauthenticatedResponseError(e,t,r,i=[]){let n=(t.statusText??"").trim(),a=n.length>0?`${t.status} ${n}`:`${t.status}`,s=i.length>0?`missing headers: ${i.join(", ")}`:"response lacked required BSV auth headers",o=this.getBodyPreview(r,t.headers.get("content-type")),c=[`Received HTTP ${a} from ${e} without valid BSV authentication (${s})`];null!=o&&c.push(`body preview: ${o}`);let l=Error(c.join(" - "));return l.details={url:e,status:t.status,statusText:t.statusText,missingHeaders:i,bodyPreview:o},l}createMalformedHeaderError(e,t,r,i){let n=`Failed to parse ${t} returned by ${e}: ${r}`;if(i instanceof Error){let e=Error(`${n}. ${i.message}`);return e.stack=i.stack,e.cause=i,e}return Error(`${n}. ${String(i)}`)}getBodyPreview(e,t){let r;if(0===e.length)return;let i=e.length>1024,n=i?e.slice(0,1024):e;if(this.isTextualContent(t,n))try{r=ti(n)}catch{r=this.formatBinaryPreview(n,i)}else r=this.formatBinaryPreview(n,i);return r.length>512&&(r=`${r.slice(0,512)}…`),i&&(r=`${r} (truncated)`),r}isTextualContent(e,t){if(0===t.length)return!1;if(null!=e){let t=e.toLowerCase();if(["application/json","application/problem+json","application/xml","application/xhtml+xml","application/javascript","application/ecmascript","application/x-www-form-urlencoded","text/"].some(e=>t.includes(e))||t.includes("charset="))return!0}return t.reduce((e,t)=>9===t||10===t||13===t||t>=32&&t<=126?e+1:e,0)/t.length>.8}formatBinaryPreview(e,t){let r=e.map(e=>e.toString(16).padStart(2,"0")).join("");return`0x${r}${t?"…":""}`}deserializeRequestPayload(e){let t,r=new td(e),i=ta(r.read(32)),n=r.readVarIntNum(),a="GET";n>0&&(a=ti(r.read(n)));let s=r.readVarIntNum(),o="";s>0&&(o=ti(r.read(s)));let c=r.readVarIntNum(),l="";c>0&&(l=ti(r.read(c)));let h={},u=r.readVarIntNum();if(u>0)for(let e=0;e<u;e++){let e=r.readVarIntNum(),t=ti(r.read(e)),i=r.readVarIntNum(),n=ti(r.read(i));h[t]=n}let d=r.readVarIntNum();return d>0&&(t=r.read(d)),{urlPostfix:o+l,method:a,headers:h,body:t,requestId:i}}}class nB{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;originator;peers={};constructor(e,t,r,i){this.wallet=e,this.requestedCertificates=t,this.sessionManager=r??new nP,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 n,{method:a="GET",headers:s={},body:o}=t,c=new URL(e),l=c.origin;if(void 0===this.peers[l]){let e=new nV(l);n={peer:new nC(this.wallet,e,this.requestedCertificates,this.sessionManager,void 0,this.originator),pendingCertificateRequests:[]},this.peers[l]=n,this.peers[l].peer.listenForCertificatesReceived((e,t)=>{this.certificatesReceived.push(...t)}),this.peers[l].peer.listenForCertificatesRequested(async(e,t)=>{try{this.peers[l].pendingCertificateRequests.push(!0);let r=await nA(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}n=this.peers[l]}let h=tJ(32),u=ta(h),d=await this.serializeRequest(a,s,o,c,h);this.callbacks[u]={resolve:r,reject:i};let f=n.peer.listenForGeneralMessages((e,t)=>{let r,i=new td(t);if(ta(i.read(32))!==u)return;n.peer.stopListeningForGeneralMessages(f),this.peers[l].identityKey=e,this.peers[l].supportsMutualAuth=!0;let a=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=ti(t),n=i.readVarIntNum(),a=i.read(n),o=ti(a);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:a,statusText:`${a}`,headers:new Headers(s)});this.callbacks[u].resolve(h),delete this.callbacks[u]});n.pendingCertificateRequests.length>0&&await new Promise(e=>{setInterval(()=>{0===n.pendingCertificateRequests.length&&e()},100)}),await n.peer.toPeer(d.toArray(),n.identityKey).catch(async a=>{if(a.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(a.message.includes("HTTP server failed to authenticate"))try{let i=await this.handleFetchAndValidate(e,t,n);r(i);return}catch(e){i(e)}else i(a)})}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 nV(i);r={peer:new nC(this.wallet,e,this.requestedCertificates,this.sessionManager,this.originator)},this.peers[i]=r}return await new Promise(async(e,i)=>{let n=r.peer.listenForCertificatesReceived((t,i)=>{r.peer.stopListeningForCertificatesReceived(n),this.certificatesReceived.push(...i),e(i)});try{await r.peer.requestCertificates(t,r.identityKey)}catch(e){r.peer.stopListeningForCertificatesReceived(n),i(e)}})}consumeReceivedCertificates(){return this.certificatesReceived.splice(0)}async serializeRequest(e,t,r,i,n){let a=new tu;if(a.write(n),a.writeVarIntNum(e.length),a.write(e9(e)),i.pathname.length>0){let e=e9(i.pathname);a.writeVarIntNum(e.length),a.write(e)}else a.writeVarIntNum(-1);if(i.search.length>0){let e=e9(i.search);a.writeVarIntNum(e.length),a.write(e)}else a.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)),a.writeVarIntNum(s.length);for(let e=0;e<s.length;e++){let t=e9(s[e][0],"utf8");a.writeVarIntNum(t.length),a.write(t);let r=e9(s[e][1],"utf8");a.writeVarIntNum(r.length),a.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);a.writeVarIntNum(e.length),a.write(e)}else a.writeVarIntNum(-1);return a}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 n=r.headers.get("x-bsv-payment-satoshis-required");if(!n)throw Error("Missing x-bsv-payment-satoshis-required response header.");let a=parseInt(n);if(isNaN(a)||a<=0)throw Error("Invalid x-bsv-payment-satoshis-required response header value.");let s=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=t.paymentContext;if(null!=c?this.isPaymentContextCompatible(c,a,s,o)||(this.logPaymentAttempt("warn","Server adjusted payment requirements; regenerating transaction",this.composePaymentLogDetails(e,c)),c=await this.createPaymentContext(e,t,a,s,o)):c=await this.createPaymentContext(e,t,a,s,o),c.attempts>=c.maxAttempts)throw this.buildPaymentFailureError(e,c,Error("Maximum payment attempts exceeded before retrying"));let l={...t.headers??{}};l["x-bsv-payment"]=JSON.stringify({derivationPrefix:c.derivationPrefix,derivationSuffix:c.derivationSuffix,transaction:c.transactionBase64});let h={...t,headers:l,paymentContext:c};"number"!=typeof h.retryCounter&&(h.retryCounter=3);let u=c.attempts+1,d=c.maxAttempts;c.attempts=u;let f=this.composePaymentLogDetails(e,c);this.logPaymentAttempt("warn",`Attempting paid request (${u}/${d})`,f);try{let t=await this.fetch(e,h);return this.logPaymentAttempt("info",`Paid request attempt ${u} succeeded`,f),t}catch(n){let t=this.createPaymentErrorEntry(c.attempts,n);if(c.errors.push(t),this.logPaymentAttempt("error",`Paid request attempt ${u} failed`,{...f,error:{message:t.message,stack:t.stack}}),c.attempts>=c.maxAttempts)throw this.buildPaymentFailureError(e,c,n);let i=this.getPaymentRetryDelay(c.attempts);return await this.wait(i),this.handlePaymentAndRetry(e,h,r)}}isPaymentContextCompatible(e,t,r,i){return e.satoshisRequired===t&&e.serverIdentityKey===r&&e.derivationPrefix===i}async createPaymentContext(e,t,r,i,n){let a=await nO(this.wallet,void 0,this.originator),{publicKey:s}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${n} ${a}`,counterparty:i},this.originator),o=new rC().lock(tX.fromString(s).toAddress()).toHex(),{tx:c}=await this.wallet.createAction({description:`Payment for request to ${new URL(e).origin}`,outputs:[{satoshis:r,lockingScript:o,customInstructions:JSON.stringify({derivationPrefix:n,derivationSuffix:a,payee:i}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}},this.originator),{publicKey:l}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return{satoshisRequired:r,transactionBase64:ta(c),derivationPrefix:n,derivationSuffix:a,serverIdentityKey:i,clientIdentityKey:l,attempts:0,maxAttempts:this.getMaxPaymentAttempts(t),errors:[],requestSummary:this.buildPaymentRequestSummary(e,t)}}getMaxPaymentAttempts(e){let t="number"==typeof e.paymentRetryAttempts?e.paymentRetryAttempts:void 0;return"number"==typeof t&&t>0?Math.floor(t):3}buildPaymentRequestSummary(e,t){let r={...t.headers??{}},i="string"==typeof t.method?t.method.toUpperCase():"GET",n=this.describeRequestBodyForLogging(t.body);return{url:e,method:i,headers:r,bodyType:n.type,bodyByteLength:n.byteLength}}describeRequestBodyForLogging(e){if(null==e)return{type:"none",byteLength:0};if("string"==typeof e)return{type:"string",byteLength:e9(e,"utf8").length};if(Array.isArray(e))return e.every(e=>"number"==typeof e)?{type:"number[]",byteLength:e.length}:{type:"array",byteLength:e.length};if("undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer)return{type:"ArrayBuffer",byteLength:e.byteLength};if("undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e))return{type:null!=e.constructor?e.constructor.name:"TypedArray",byteLength:e.byteLength};if("undefined"!=typeof Blob&&e instanceof Blob)return{type:"Blob",byteLength:e.size};if("undefined"!=typeof FormData&&e instanceof FormData)return{type:"FormData",byteLength:0};if("undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams)return{type:"URLSearchParams",byteLength:e9(e.toString(),"utf8").length};if("undefined"!=typeof ReadableStream&&e instanceof ReadableStream)return{type:"ReadableStream",byteLength:0};try{let t=JSON.stringify(e);if("string"==typeof t)return{type:"object",byteLength:e9(t,"utf8").length}}catch(e){}return{type:typeof e,byteLength:0}}composePaymentLogDetails(e,t){return{url:e,request:t.requestSummary,payment:{satoshis:t.satoshisRequired,transactionBase64:t.transactionBase64,derivationPrefix:t.derivationPrefix,derivationSuffix:t.derivationSuffix,serverIdentityKey:t.serverIdentityKey,clientIdentityKey:t.clientIdentityKey},attempts:{used:t.attempts,max:t.maxAttempts},errors:t.errors}}logPaymentAttempt(e,t,r){let i="[AuthFetch][Payment]";"error"===e?console.error(`${i} ${t}`,r):"warn"===e?console.warn(`${i} ${t}`,r):"function"==typeof console.info?console.info(`${i} ${t}`,r):console.log(`${i} ${t}`,r)}createPaymentErrorEntry(e,t){let r={attempt:e,timestamp:new Date().toISOString(),message:"",stack:void 0};return t instanceof Error?(r.message=t.message,r.stack=t.stack??void 0):r.message=String(t),r}getPaymentRetryDelay(e){return 250*Math.min(e,5)}async wait(e){e<=0||await new Promise(t=>setTimeout(t,e))}buildPaymentFailureError(e,t,r){let i=Error(`Paid request to ${e} failed after ${t.attempts}/${t.maxAttempts} attempts. Sent ${t.satoshisRequired} satoshis to ${t.serverIdentityKey}.`);return i.details={request:t.requestSummary,payment:{satoshis:t.satoshisRequired,transactionBase64:t.transactionBase64,derivationPrefix:t.derivationPrefix,derivationSuffix:t.derivationSuffix,serverIdentityKey:t.serverIdentityKey,clientIdentityKey:t.clientIdentityKey},attempts:{used:t.attempts,max:t.maxAttempts},errors:t.errors},r instanceof Error&&(i.cause=r),i}async normalizeBodyToNumberArray(e){if(null==e)return[];if("object"==typeof e)return e9(JSON.stringify(e,"utf8"));if(Array.isArray(e)&&e.every(e=>"number"==typeof e))return e;if("string"==typeof e)return e9(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()])}),e9(new URLSearchParams(t).toString(),"utf8")}if(e instanceof URLSearchParams)return e9(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 nD{pushDrop;static decode(e){let t=rB.decode(e);if(t.fields.length<4)throw Error("Invalid SHIP/SLAP advertisement!");let r=ti(t.fields[0]);if("SHIP"!==r&&"SLAP"!==r)throw Error("Invalid protocol type!");let i=e7(t.fields[1]);return{protocol:r,identityKey:i,domain:ti(t.fields[2]),topicOrService:ti(t.fields[3])}}constructor(e,t){this.pushDrop=new rB(e,t)}async lock(e,t,r){let{publicKey:i}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([e9(e,"utf8"),e9(i,"hex"),e9(t,"utf8"),e9(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 nU="bsvsdk_overlay_host_reputation_v1";class nF{stats;store;constructor(e){this.stats=new Map,this.store=e??this.getLocalStorageAdapter(),this.loadFromStorage()}reset(){this.stats.clear()}recordSuccess(e,t){let r=this.getOrCreate(e),i=Date.now(),n=Number.isFinite(t)&&t>=0?t:1500;null===r.avgLatencyMs?r.avgLatencyMs=n:r.avgLatencyMs=.75*r.avgLatencyMs+.25*n,r.lastLatencyMs=n,r.totalSuccesses+=1,r.consecutiveFailures=0,r.backoffUntil=0,r.lastUpdatedAt=i,r.lastError=void 0,this.saveToStorage()}recordFailure(e,t){let r=this.getOrCreate(e),i=Date.now();r.totalFailures+=1,r.consecutiveFailures+=1;let n="string"==typeof t?t:t instanceof Error?t.message:void 0;"string"==typeof n&&(n.includes("ERR_NAME_NOT_RESOLVED")||n.includes("ENOTFOUND")||n.includes("getaddrinfo")||n.includes("Failed to fetch"))&&r.consecutiveFailures<3&&(r.consecutiveFailures=3);let a=Math.max(r.consecutiveFailures-2,0);0===a?r.backoffUntil=0:r.backoffUntil=i+Math.min(6e4,1e3*Math.pow(2,a-1)),r.lastUpdatedAt=i,r.lastError="string"==typeof t?t:t instanceof Error?t.message:void 0,this.saveToStorage()}rankHosts(e,t=Date.now()){let r=new Map;e.forEach((e,t)=>{"string"==typeof e&&0!==e.length&&(r.has(e)||r.set(e,t))});let i=Array.from(r.keys()).map(e=>{let i=this.getOrCreate(e);return{...i,score:this.computeScore(i,t),originalOrder:r.get(e)??0}});return i.sort((e,r)=>{let i=e.backoffUntil>t;return i!==r.backoffUntil>t?i?1:-1:e.score!==r.score?e.score-r.score:e.totalSuccesses!==r.totalSuccesses?r.totalSuccesses-e.totalSuccesses:e.originalOrder-r.originalOrder}),i.map(({originalOrder:e,...t})=>t)}snapshot(e){let t=this.stats.get(e);return null!=t?{...t}:void 0}getStorage(){try{let e="object"==typeof globalThis?globalThis:void 0;if(null==e||null==e.localStorage)return;return e.localStorage}catch{return}}getLocalStorageAdapter(){let e=this.getStorage();if(null!=e)return{get:t=>{try{return e.getItem(t)}catch{return null}},set:(t,r)=>{try{e.setItem(t,r)}catch{}}}}loadFromStorage(){let e=this.store;if(null!=e)try{let t=e.get(nU);if("string"!=typeof t||0===t.length)return;let r=JSON.parse(t);if("object"!=typeof r||null===r)return;for(let e of(this.stats.clear(),Object.keys(r))){let t=r[e];if(null!=t&&"object"==typeof t){let r={host:String(t.host??e),totalSuccesses:Number(t.totalSuccesses??0),totalFailures:Number(t.totalFailures??0),consecutiveFailures:Number(t.consecutiveFailures??0),avgLatencyMs:null==t.avgLatencyMs?null:Number(t.avgLatencyMs),lastLatencyMs:null==t.lastLatencyMs?null:Number(t.lastLatencyMs),backoffUntil:Number(t.backoffUntil??0),lastUpdatedAt:Number(t.lastUpdatedAt??0),lastError:"string"==typeof t.lastError?t.lastError:void 0};this.stats.set(r.host,r)}}}catch{}}saveToStorage(){let e=this.store;if(null!=e)try{let t={};for(let[e,r]of this.stats.entries())t[e]=r;e.set(nU,JSON.stringify(t))}catch{}}computeScore(e,t){let r=e.avgLatencyMs??1500,i=400*e.consecutiveFailures,n=Math.min(30*e.totalSuccesses,r/2);return r+i+(e.backoffUntil>t?e.backoffUntil-t:0)-n}getOrCreate(e){let t=this.stats.get(e);return null==t&&(t={host:e,totalSuccesses:0,totalFailures:0,consecutiveFailures:0,avgLatencyMs:null,lastLatencyMs:null,backoffUntil:0,lastUpdatedAt:0},this.stats.set(e,t)),t}}let nL=new nF,nK="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch,nH=["https://overlay-us-1.bsvb.tech","https://overlay-eu-1.bsvb.tech","https://overlay-ap-1.bsvb.tech","https://users.bapp.dev"],nq=["https://testnet-users.bapp.dev"];class nM{fetchClient;allowHTTP;constructor(e=nK,t=!1){if("function"!=typeof e)throw Error("HTTPSOverlayLookupFacilitator requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=e,this.allowHTTP=t}async lookup(e,t,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,n=setTimeout(()=>{try{i?.abort()}catch{}},r);try{let r={method:"POST",headers:{"Content-Type":"application/json","X-Aggregation":"yes"},body:JSON.stringify({service:t.service,query:t.query}),signal:i?.signal},n=await this.fetchClient(`${e}/lookup`,r);if(!n.ok)throw Error(`Failed to facilitate lookup (HTTP ${n.status})`);if("application/octet-stream"!==n.headers.get("content-type"))return await n.json();{let e=await n.arrayBuffer(),t=new td([...new Uint8Array(e)]),r=t.readVarIntNum(),i=[];for(let e=0;e<r;e++){let e,r=e7(t.read(32)),n=t.readVarIntNum(),a=t.readVarIntNum();a>0&&(e=t.read(a)),i.push({txid:r,outputIndex:n,context:e})}let a=t.read();return{type:"output-list",outputs:i.map(e=>({outputIndex:e.outputIndex,context:e.context,beef:r0.fromBEEF(a,e.txid).toBEEF()}))}}}catch(e){if(e?.name==="AbortError")throw Error("Request timed out");throw e}finally{clearTimeout(n)}}}class n${facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;hostReputation;hostsCache;hostsInFlight;hostsTtlMs;hostsMaxEntries;txMemo;txMemoTtlMs;constructor(e={}){this.networkPreset=e.networkPreset??"mainnet",this.facilitator=e.facilitator??new nM(void 0,"local"===this.networkPreset),this.slapTrackers=e.slapTrackers??("mainnet"===this.networkPreset?nH:nq);const t=e.hostOverrides??{};this.assertValidOverrideServices(t),this.hostOverrides=t,this.additionalHosts=e.additionalHosts??{};const r=e.reputationStorage;"localStorage"===r?this.hostReputation=new nF:"object"==typeof r&&null!==r&&"function"==typeof r.get&&"function"==typeof r.set?this.hostReputation=new nF(r):this.hostReputation=nL,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=this.prepareHostsForQuery(r,`lookup service ${e.service}`);if(i.length<1)throw Error(`All competent hosts for ${e.service} are temporarily unavailable due to backoff.`);let n=await Promise.allSettled(i.map(async r=>await this.lookupHostWithTracking(r,e,t))),a=new Map,s=e=>"object"!=typeof e?"":e.join(",");for(let e of n){if("fulfilled"!==e.status)continue;let t=e.value;if(t?.type==="output-list"&&Array.isArray(t.outputs))for(let e of t.outputs){let t=s(e.beef),r=this.txMemo.get(t),i=Date.now();if("object"!=typeof r||null===r||r.expiresAt<=i)try{r={txId:r0.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 n=`${r.txId}.${e.outputIndex}`;a.set(n,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=this.prepareHostsForQuery(this.slapTrackers,"SLAP trackers");if(0===r.length)return[];let i=await Promise.allSettled(r.map(async e=>await this.lookupHostWithTracking(e,t,5e3))),n=new Set;for(let t of i){if("fulfilled"!==t.status)continue;let r=t.value;if("output-list"===r.type)for(let t of r.outputs)try{let r=r0.fromBEEF(t.beef),i=r.outputs[t.outputIndex]?.lockingScript;if("object"!=typeof i||null===i)continue;let a=nD.decode(i);if(a.topicOrService!==e||"SLAP"!==a.protocol)continue;"string"==typeof a.domain&&a.domain.length>0&&n.add(a.domain)}catch{continue}}return[...n]}evictOldest(e){let t=e.keys().next().value;void 0!==t&&e.delete(t)}assertValidOverrideServices(e){for(let t of Object.keys(e))if(!t.startsWith("ls_"))throw Error(`Host override service names must start with "ls_": ${t}`)}prepareHostsForQuery(e,t){if(0===e.length)return[];let r=Date.now(),i=this.hostReputation.rankHosts(e,r),n=i.filter(e=>e.backoffUntil<=r).map(e=>e.host);if(n.length>0)return n;let a=Math.max(Math.min(...i.map(e=>e.backoffUntil))-r,0);throw Error(`All ${t} hosts are backing off for approximately ${a}ms due to repeated failures.`)}async lookupHostWithTracking(e,t,r){let i=Date.now();try{let n=await this.facilitator.lookup(e,t,r),a=Date.now()-i;return"object"==typeof n&&null!==n&&"output-list"===n.type&&Array.isArray(n.outputs)?this.hostReputation.recordSuccess(e,a):this.hostReputation.recordFailure(e,"Invalid lookup response"),n}catch(t){throw this.hostReputation.recordFailure(e,t),t}}}class nz{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 tu;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 n=await fetch(`${e}/submit`,{method:"POST",headers:i,body:r});if(n.ok)return await n.json();throw Error("Failed to facilitate broadcast")}}class nW{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 nz(void 0,"local"===this.networkPreset),this.resolver=t.resolver??new n$({networkPreset:this.networkPreset}),this.requireAcknowledgmentFromAllHostsForTopics=t.requireAcknowledgmentFromAllHostsForTopics??[],this.requireAcknowledgmentFromAnyHostForTopics=t.requireAcknowledgmentFromAnyHostForTopics??"all",this.requireAcknowledgmentFromSpecificHostsForTopics=t.requireAcknowledgmentFromSpecificHostsForTopics??{}}async broadcast(e){let t,r,i,n,a,s=e.metadata.get("OffChainValues");try{t=e.toBEEF()}catch(e){throw Error("Transactions sent via SHIP to Overlay Services must be serializable to BEEF format.")}let o=await this.findInterestedHosts();if(0===Object.keys(o).length)return{status:"error",code:"ERR_NO_HOSTS_INTERESTED",description:`No ${this.networkPreset} hosts are interested in receiving this transaction.`};let c=Object.entries(o).map(async([e,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,n=t.coinsToRetain,a=t.coinsRemoved;(r?.length>0||n?.length>0||a?.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?(n=this.topics,a="all"):"any"===this.requireAcknowledgmentFromAnyHostForTopics?(n=this.topics,a="any"):(n=Array.isArray(this.requireAcknowledgmentFromAnyHostForTopics)?this.requireAcknowledgmentFromAnyHostForTopics:[],a="all"),n.length>0&&!this.checkAcknowledgmentFromAnyHost(h,n,a))?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ANY_HOST_FAILED",description:"No host acknowledged the required topics."}:Object.keys(this.requireAcknowledgmentFromSpecificHostsForTopics).length>0&&!this.checkAcknowledgmentFromSpecificHosts(h,this.requireAcknowledgmentFromSpecificHostsForTopics)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_SPECIFIC_HOSTS_FAILED",description:"Specific hosts did not acknowledge the required topics."}:{status:"success",txid:e.id("hex"),message:`Sent to ${l.length} Overlay Services ${1===l.length?"host":"hosts"}.`}}checkAcknowledgmentFromAllHosts(e,t,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,n,a=e[r];if(null==a)return!1;if("all"===i||"any"===i)n=i,t=this.topics;else{if(!Array.isArray(i))continue;t=i,n="all"}if("all"===n){for(let e of t)if(!a.has(e))return!1}else if("any"===n){let e=!1;for(let r of t)if(a.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=r0.fromBEEF(r.beef).outputs[r.outputIndex].lockingScript,i=nD.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}}async function nj(e,t,r=5){let i=0;for(;i<r;){i++;try{return await e()}catch(e){if(i<r&&"WERR_REVIEW_ACTIONS"===e.name){let n=e.reviewActionResults.find(e=>"doubleSpend"===e.status);if(n?.competingBeef!=null&&n?.competingTxs!=null&&n?.competingTxs.length>0){let e=r0.fromBEEF(n.competingBeef,n.competingTxs[0]);await nj(async()=>await t.broadcast(e),t,r-i);continue}}throw e}}throw Error("Unexpected end of retry loop")}let nX=e=>(e.toLowerCase().startsWith("uhrp:")&&(e=e.slice(5)),e.startsWith("//")&&(e=e.slice(2)),e),nG=e=>{if(32!==e.length)throw Error("Hash length must be 32 bytes (sha256)");return tl(e,e9("ce00","hex"))},nY=e=>{let t=e instanceof Uint8Array?e:Uint8Array.from(e),r=new J;for(let e=0;e<t.length;e+=1048576){let i=t.subarray(e,e+1048576);r.update(Array.from(i))}return nG(r.digest())},nJ=e=>{let{data:t,prefix:r}=th(e=nX(e),void 0,2);if(32!==t.length)throw Error("Invalid length!");if("ce00"!==e7(r))throw Error("Bad prefix");return t},nZ=e=>{try{return nJ(e),!0}catch(e){return!1}};class nQ{authFetch;baseURL;constructor(e){this.baseURL=e.storageURL,this.authFetch=new nB(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 n=await i.json();if("error"===n.status)throw Error("Upload route returned an error.");return{uploadURL:n.uploadURL,requiredHeaders:n.requiredHeaders,amount:n.amount}}async uploadFile(e,t,r){let i=t.data instanceof Uint8Array?t.data:Uint8Array.from(t.data),n=await fetch(e,{method:"PUT",body:i,headers:{"Content-Type":t.type,...r}});if(!n.ok)throw Error(`File upload failed: HTTP ${n.status}`);return{published:!0,uhrpURL:nY(i)}}async publishFile(e){let{file:t,retentionPeriod:r}=e,i=t.data instanceof Uint8Array?t.data:Uint8Array.from(t.data),n=i.byteLength,{uploadURL:a,requiredHeaders:s}=await this.getUploadInfo(n,r);return await this.uploadFile(a,{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 n=await i.json();if("error"===n.status){let e=n.code??"unknown-code",t=n.description??"no-description";throw Error(`renewFile returned an error: ${e} - ${t}`)}return{status:n.status,prevExpiryTime:n.prevExpiryTime,newExpiryTime:n.newExpiryTime,amount:n.amount}}}class n0{networkPreset="mainnet";lookupResolver;constructor(e){this.networkPreset=e?.networkPreset??"mainnet",this.lookupResolver=new n$({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 n=r0.fromBEEF(t.outputs[e].beef),{fields:a}=rB.decode(n.outputs[t.outputs[e].outputIndex].lockingScript);new td(a[3]).readVarIntNum()<i||r.push(ti(a[2]))}return r}async download(e){if(!nZ(e))throw Error("Invalid parameter UHRP url");let t=e7(nJ(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 n=i.body.getReader(),a=new J,s=[],o=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;a.update(Array.from(t)),s.push(t),o+=t.length}if(e7(a.digest())!==t)throw Error("Data integrity error: value of content does not match hash of the url given");let c=new Uint8Array(o),l=0;for(let e of s)c.set(e,l),l+=e.length;return{data:c,mimeType:i.headers.get("Content-Type")}}catch(e){continue}throw Error(`Unable to download content from ${e}`)}}let n1={name:"Unknown Identity",avatarURL:"XUUB8bbn9fEthk15Ge3zTQXypUShfC94vFjp65v7u5CQ8qkpxzst",identityKey:"",abbreviatedKey:"",badgeIconURL:"XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",badgeLabel:"Not verified by anyone you trust.",badgeClickURL:"https://projectbabbage.com/docs/unknown-identity"},n2={protocolID:[1,"identity"],keyID:"1",tokenAmount:1,outputIndex:0},n8={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="},n3=[2,"contact"];class n6{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 n4{wallet;cache=new n6;CONTACTS_CACHE_KEY="metanet-contacts";originator;constructor(e,t){this.wallet=e??new nI,this.originator=t}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:n3,keyID:e,counterparty:"self",data:e9(e,"utf8")},this.originator);i.push(`identityKey ${e7(t)}`)}let n=await this.wallet.listOutputs({basket:"contacts",include:"locking scripts",includeCustomInstructions:!0,tags:i,limit:r},this.originator);if(null==n.outputs||0===n.outputs.length)return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify([])),[];let a=[];for(let e of n.outputs)try{if(null==e.lockingScript)continue;let t=rB.decode(rE.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:n3,keyID:r,counterparty:"self"},this.originator),n=JSON.parse(ti(i));a.push(n)}catch(e){console.warn("ContactsManager: Failed to decode contact output:",e)}return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(a)),null!=e?a.filter(t=>t.identityKey===e):a}async saveContact(e,t){let r,i=this.cache.getItem(this.CONTACTS_CACHE_KEY),n=(r=null!=i&&""!==i?JSON.parse(i):await this.getContacts()).findIndex(t=>t.identityKey===e.identityKey),a={...e,metadata:t};n>=0?r[n]=a:r.push(a);let{hmac:s}=await this.wallet.createHmac({protocolID:n3,keyID:e.identityKey,counterparty:"self",data:e9(e.identityKey,"utf8")},this.originator),o=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:[`identityKey ${e7(s)}`],limit:100},this.originator),c=null,l=ta(tJ(32));if(null!=o.outputs)for(let t of o.outputs)try{let[r,i]=t.outpoint.split("."),n=r0.fromBEEF(o.BEEF,r),a=rB.decode(n.outputs[Number(i)].lockingScript);if(null==t.customInstructions)continue;l=JSON.parse(t.customInstructions).keyID;let{plaintext:s}=await this.wallet.decrypt({ciphertext:a.fields[0],protocolID:n3,keyID:l,counterparty:"self"},this.originator);if(JSON.parse(ti(s)).identityKey===e.identityKey){c=t;break}}catch(e){}let h={...e,metadata:t},{ciphertext:u}=await this.wallet.encrypt({plaintext:e9(JSON.stringify(h),"utf8"),protocolID:n3,keyID:l,counterparty:"self"},this.originator),d=await new rB(this.wallet,this.originator).lock([u],n3,l,"self");if(null!=c){let[t,r]=String(c.outpoint).split("."),i=`${t}.${r}`,n=new rB(this.wallet,this.originator),{signableTransaction:a}=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:d.toHex(),outputDescription:`Updated Contact: ${e.name??e.identityKey.slice(0,10)}`,tags:[`identityKey ${e7(s)}`],customInstructions:JSON.stringify({keyID:l})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==a)throw Error("Unable to update contact");let h=n.unlock(n3,l,"self"),u=await h.sign(r0.fromBEEF(a.tx),0),{tx:f}=await this.wallet.signAction({reference:a.reference,spends:{0:{unlockingScript:u.toHex()}}},this.originator);if(null==f)throw Error("Failed to update contact output")}else{let{tx:t}=await this.wallet.createAction({description:"Add Contact",outputs:[{basket:"contacts",satoshis:1,lockingScript:d.toHex(),outputDescription:`Contact: ${e.name??e.identityKey.slice(0,10)}`,tags:[`identityKey ${e7(s)}`],customInstructions:JSON.stringify({keyID:l})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==t)throw Error("Failed to create contact output")}this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(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:n3,keyID:e,counterparty:"self",data:e9(e,"utf8")},this.originator);r.push(`identityKey ${e7(i)}`);let n=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:r,limit:100},this.originator);if(null!=n.outputs)for(let t of n.outputs)try{let[r,i]=String(t.outpoint).split("."),a=r0.fromBEEF(n.BEEF,r),s=rB.decode(a.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:n3,keyID:o,counterparty:"self"},this.originator);if(JSON.parse(ti(c)).identityKey===e){let e=`${r}.${i}`,t=new rB(this.wallet,this.originator),{signableTransaction:a}=await this.wallet.createAction({description:"Delete Contact",inputBEEF:n.BEEF,inputs:[{outpoint:e,unlockingScriptLength:74,inputDescription:"Spend contact output to delete"}],outputs:[],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==a)throw Error("Unable to delete contact");let s=t.unlock(n3,o,"self"),c=await s.sign(r0.fromBEEF(a.tx),0),{tx:l}=await this.wallet.signAction({reference:a.reference,spends:{0:{unlockingScript:c.toHex()}}},this.originator);if(null==l)throw Error("Failed to delete contact output");return}}catch(e){}}}class n5{options;originator;wallet;contactsManager;constructor(e,t=n2,r){this.options=t,this.originator=r,this.originator=r,this.wallet=e??new nI,this.contactsManager=new n4(this.wallet,this.originator)}async publiclyRevealAttributes(e,t){if(0===Object.keys(e.fields).length)throw Error("Public reveal failed: Certificate has no fields to reveal!");if(0===t.length)throw Error("Public reveal failed: You must reveal at least one field!");try{let t=new iT(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 t1(1).toPublicKey().toString()},this.originator),i=await new rB(this.wallet,this.originator).lock([e9(JSON.stringify({...e,keyring:r}))],this.options.protocolID,this.options.keyID,"anyone",!0,!0),{tx:n}=await this.wallet.createAction({description:"Create a new Identity Token",outputs:[{satoshis:this.options.tokenAmount,lockingScript:i.toHex(),outputDescription:"Identity Token"}],options:{randomizeOutputs:!1}},this.originator);if(void 0!==n){let e=new nW(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network});return await e.broadcast(r0.fromAtomicBEEF(n))}throw Error("Public reveal failed: failed to create action!")}async resolveByIdentityKey(e,t=!0){if(t){let t=await this.contactsManager.getContacts(e.identityKey);if(t.length>0)return t}let{certificates:r}=await this.wallet.discoverByIdentityKey(e,this.originator);return r.map(e=>n5.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)]),n=new Map(r.map(e=>[e.identityKey,e]));return(i?.certificates??[]).map(e=>n.get(e.subject)??n5.parseIdentity(e))}async revokeCertificateRevelation(e){let t=new n$({networkPreset:(await this.wallet.getNetwork({})).network}),r=await t.query({service:"ls_identity",query:{serialNumber:e}});if("output-list"!==r.type)throw Error("Failed to get lookup result");let i=new nW(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network,requireAcknowledgmentFromAllHostsForTopics:[],requireAcknowledgmentFromAnyHostForTopics:[],requireAcknowledgmentFromSpecificHostsForTopics:{tm_identity:[]}});await nj(async()=>{let e=r0.fromBEEF(r.outputs[0].beef),t=`${e.id("hex")}.${this.options.outputIndex}`;if(void 0===e.outputs[this.options.outputIndex].lockingScript||void 0===t)throw Error("Failed to get locking script for revelation output!");let{signableTransaction:n}=await this.wallet.createAction({description:"Spend certificate revelation token",inputBEEF:r.outputs[0].beef,inputs:[{inputDescription:"Revelation token",outpoint:t,unlockingScriptLength:74}],options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1,noSend:!0}},this.originator);if(void 0===n)throw Error("Failed to create signable transaction");let a=r0.fromBEEF(n.tx),s=new rB(this.wallet,this.originator).unlock(this.options.protocolID,this.options.keyID,"anyone"),o=await s.sign(a,this.options.outputIndex),{tx:c}=await this.wallet.signAction({reference:n.reference,spends:{[this.options.outputIndex]:{unlockingScript:o.toHex()}},options:{acceptDelayedBroadcast:!1,noSend:!0}},this.originator);if(void 0===c)throw Error("Failed to sign transaction");await i.broadcast(r0.fromAtomicBEEF(c))},i)}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,n,a,{type:s,decryptedFields:o,certifierInfo:c}=e;switch(s){case n8.xCert:t=o.userName,r=o.profilePhoto,i=`X account certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n8.discordCert:t=o.userName,r=o.profilePhoto,i=`Discord account certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n8.emailCert:t=o.email,r="XUTZxep7BBghAJbSBwTjNfmcsDdRFs5EaGEgkESGSgjJVYgMEizu",i=`Email certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n8.phoneCert:t=o.phoneNumber,r="XUTLxtX3ELNUwRhLwL7kWNGbdnFM8WG2eSLv84J7654oH8HaJWrU",i=`Phone certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n8.identiCert:t=`${o.firstName} ${o.lastName}`,r=o.profilePhoto,i=`Government ID certified by ${c.name}`,n=c.iconUrl,a="https://identicert.me";break;case n8.registrant:t=o.name,r=o.icon,i=`Entity certified by ${c.name}`,n=c.iconUrl,a="https://projectbabbage.com/docs/registrant";break;case n8.coolCert:t="true"===o.cool?"Cool Person!":"Not cool!";break;case n8.anyone:t="Anyone",r="XUT4bpQ6cpBaXi1oMzZsXfpkWGbtp2JTUYAoN7PzhStFJ6wLfoeR",i="Represents the ability for anyone to access this information.",n="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",a="https://projectbabbage.com/docs/anyone-identity";break;case n8.self:t="You",r="XUT9jHGk2qace148jeCX5rDsMftkSGYKmigLwU2PLLBc7Hm63VYR",i="Represents your ability to access this information.",n="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",a="https://projectbabbage.com/docs/self-identity";break;default:{let e=n5.tryToParseGenericIdentity(s,o,c);t=e.name,r=e.avatarURL,i=e.badgeLabel,n=e.badgeIconURL,a=e.badgeClickURL}}return{name:t,avatarURL:r,abbreviatedKey:e.subject.length>0?`${e.subject.substring(0,10)}...`:"",identityKey:e.subject,badgeIconURL:n,badgeLabel:i,badgeClickURL:a}}static hasValue(e){return null!=e&&""!==e}static tryToParseGenericIdentity(e,t,r){let i=t.firstName,n=t.lastName,a=n5.hasValue(i)&&n5.hasValue(n)?`${i} ${n}`:n5.hasValue(i)?i:n5.hasValue(n)?n:void 0,s=n5.hasValue(t.name)?t.name:n5.hasValue(t.userName)?t.userName:a??(n5.hasValue(t.email)?t.email:n1.name),o=n5.hasValue(t.profilePhoto)?t.profilePhoto:n5.hasValue(t.avatar)?t.avatar:n5.hasValue(t.icon)?t.icon:n5.hasValue(t.photo)?t.photo:n1.avatarURL,c=n5.hasValue(r?.name)?`${e} certified by ${String(r.name)}`:n1.badgeLabel;return{name:s,avatarURL:o,badgeLabel:c,badgeIconURL:n5.hasValue(r?.iconUrl)?r.iconUrl:n1.badgeIconURL,badgeClickURL:n1.badgeClickURL}}}class n7{wallet;originator;network;resolver;cachedIdentityKey;acceptDelayedBroadcast;constructor(e=new nI,t={},r){this.wallet=e,this.originator=r,this.acceptDelayedBroadcast=t.acceptDelayedBroadcast??!1,this.resolver=t.resolver??new n$}async getIdentityKey(){return void 0===this.cachedIdentityKey&&(this.cachedIdentityKey=(await this.wallet.getPublicKey({identityKey:!0})).publicKey),this.cachedIdentityKey}async getNetwork(){return void 0===this.network&&(this.network=(await this.wallet.getNetwork({})).network),this.network}async registerDefinition(e){let t=await this.getIdentityKey(),r=new rB(this.wallet,this.originator),i=this.buildPushDropFields(e,t),n=this.mapDefinitionTypeToWalletProtocol(e.definitionType),a=await r.lock(i,n,"1","anyone",!0),{tx:s}=await this.wallet.createAction({description:`Register a new ${e.definitionType} item`,outputs:[{satoshis:1,lockingScript:a.toHex(),outputDescription:`New ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===s)throw Error(`Failed to create ${e.definitionType} registration transaction!`);let o=new nW([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await o.broadcast(r0.fromAtomicBEEF(s))}async resolve(e,t){let r=this.mapDefinitionTypeToServiceName(e),i=await this.resolver.query({service:r,query:t});if("output-list"!==i.type)return[];let n=[];for(let t of i.outputs)try{let r=r0.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"}),n=[];for(let t of r)if(t.spendable)try{let[r,a]=t.outpoint.split("."),s=r0.fromBEEF(i,r).outputs[Number(a)].lockingScript,o=await this.parseLockingScript(e,s);n.push({...o,txid:r,outputIndex:Number(a),satoshis:t.satoshis,lockingScript:s.toHex(),beef:i})}catch{}return n}async removeDefinition(e){if(void 0===e.txid||void 0===e.outputIndex||void 0===e.lockingScript)throw Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");let t=await this.getIdentityKey();if(e.registryOperator!==t)throw Error("This registry token does not belong to the current wallet.");let r="basket"===e.definitionType?e.basketID:"protocol"===e.definitionType?e.name:"certificate"===e.definitionType?void 0!==e.name?e.name:e.type:"unknown",i=`${e.txid}.${e.outputIndex}`,{signableTransaction:n}=await this.wallet.createAction({description:`Remove ${e.definitionType} item: ${r}`,inputBEEF:e.beef,inputs:[{outpoint:i,unlockingScriptLength:74,inputDescription:`Removing ${e.definitionType} token`}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===n)throw Error("Failed to create signable transaction.");let a=r0.fromAtomicBEEF(n.tx),s=new rB(this.wallet,this.originator).unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone"),o=await s.sign(a,0),{tx:c}=await this.wallet.signAction({reference:n.reference,spends:{0:{unlockingScript:o.toHex()}},options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if(void 0===c)throw Error("Failed to finalize the transaction signature.");let l=new nW([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await l.broadcast(r0.fromAtomicBEEF(c))}async updateDefinition(e,t){if(void 0===e.txid||void 0===e.outputIndex||void 0===e.lockingScript)throw Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");if(e.definitionType!==t.definitionType)throw Error(`Cannot change definition type from ${e.definitionType} to ${t.definitionType}`);let r=await this.getIdentityKey();if(e.registryOperator!==r)throw Error("This registry token does not belong to the current wallet.");let i="basket"===e.definitionType?e.basketID:"protocol"===e.definitionType?e.name:"certificate"===e.definitionType?void 0!==e.name?e.name:e.type:"unknown",n=new rB(this.wallet,this.originator),a=this.buildPushDropFields(t,r),s=this.mapDefinitionTypeToWalletProtocol(t.definitionType),o=await n.lock(a,s,"1","anyone",!0),c=`${e.txid}.${e.outputIndex}`,{signableTransaction:l}=await this.wallet.createAction({description:`Update ${e.definitionType} item: ${i}`,inputBEEF:e.beef,inputs:[{outpoint:c,unlockingScriptLength:74,inputDescription:`Updating ${e.definitionType} token`}],outputs:[{satoshis:1,lockingScript:o.toHex(),outputDescription:`Updated ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===l)throw Error("Failed to create signable transaction.");let h=r0.fromAtomicBEEF(l.tx),u=n.unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone"),d=await u.sign(h,0),{tx:f}=await this.wallet.signAction({reference:l.reference,spends:{0:{unlockingScript:d.toHex()}},options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if(void 0===f)throw Error("Failed to finalize the transaction signature.");let p=new nW([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await p.broadcast(r0.fromAtomicBEEF(f))}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=>e9(e))}async parseLockingScript(e,t){let r,i,n=rB.decode(t);if(0===n.fields.length)throw Error("Not a valid registry pushdrop script.");switch(e){case"basket":{if(7!==n.fields.length)throw Error("Unexpected field count for basket type.");let[e,t,a,s,o,c]=n.fields;r=ti(c),i={definitionType:"basket",basketID:ti(e),name:ti(t),iconURL:ti(a),description:ti(s),documentationURL:ti(o)};break}case"protocol":{if(7!==n.fields.length)throw Error("Unexpected field count for protocol type.");let[e,t,a,s,o,c]=n.fields;r=ti(c),i={definitionType:"protocol",protocolID:n9(ti(e)),name:ti(t),iconURL:ti(a),description:ti(s),documentationURL:ti(o)};break}case"certificate":{if(8!==n.fields.length)throw Error("Unexpected field count for certificate type.");let[e,t,a,s,o,c,l]=n.fields;r=ti(l);let h={};try{h=JSON.parse(ti(c))}catch{}i={definitionType:"certificate",type:ti(e),name:ti(t),iconURL:ti(a),description:ti(s),documentationURL:ti(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 n9(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 ae{wallet;context;encrypt;originator;acceptDelayedBroadcast=!1;keyLocks=new Map;constructor(e=new nI,t="kvstore default",r=!0,i,n=!1){if("string"!=typeof t||t.length<1)throw Error("A context in which to operate is required.");this.wallet=e,this.context=t,this.encrypt=r,this.originator=i,this.acceptDelayedBroadcast=n}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},this.originator)}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("."),n=t.findTxid(r)?.tx;if(null==n)throw Error(`beef must contain txid ${r}`);return n.outputs[Number(i)].lockingScript}async lookupValue(e,t,r){let i,n=await this.getOutputs(e,r),a={value:t,outpoint:void 0,lor:n},{outputs:s}=n;if(0===s.length)return a;let o=s.slice(-1)[0];a.outpoint=o.outpoint;try{if(void 0===n.BEEF)throw Error("entire transactions listOutputs option must return valid BEEF");let e=this.getLockingScript(o,rZ.fromBinary(n.BEEF)),t=rB.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},this.originator);a.value=ti(t)}else a.value=ti(i);return a}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 n=this.getProtocol(e),a=r0.fromAtomicBEEF(i),s={};for(let e=0;e<t.length;e++){let t=r.unlock(n.protocolID,n.keyID,"self"),i=await t.sign(a,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 n=this.getProtocol(e),a=e9(t,"utf8");if(this.encrypt){let{ciphertext:e}=await this.wallet.encrypt({...n,plaintext:a},this.originator);a=e}let s=new rB(this.wallet,this.originator),o=await s.lock([a],n.protocolID,n.keyID,"self"),{outputs:c,BEEF:l}=i.lor;try{let t=this.getInputs(c),{txid:i,signableTransaction:n}=await this.wallet.createAction({description:`Update ${e} in ${this.context}`,inputBEEF:l,inputs:t,outputs:[{basket:this.context,tags:[e],lockingScript:o.toHex(),satoshis:1,outputDescription:"Key-value token"}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(c.length>0&&"object"!=typeof n)throw Error("Wallet did not return a signable transaction when expected.");if(null==n)r=`${i}.0`;else{let t=await this.getSpends(e,c,s,n.tx),{txid:i}=await this.wallet.signAction({reference:n.reference,spends:t},this.originator);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:n}=await this.getOutputs(e);if(r.length>0){let a=new rB(this.wallet,this.originator);try{let n=this.getInputs(r),{signableTransaction:s}=await this.wallet.createAction({description:`Remove ${e} in ${this.context}`,inputBEEF:i,inputs:n,options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if("object"!=typeof s)throw Error("Wallet did not return a signable transaction when expected.");let o=await this.getSpends(e,r,a,s.tx),{txid:c}=await this.wallet.signAction({reference:s.reference,spends:o},this.originator);if(void 0===c)throw Error("signAction must return a valid txid");t.push(c)}catch(t){throw Error(`There are ${n} outputs with tag ${e} that cannot be unlocked. Original error: ${t instanceof Error?t.message:String(t)}`)}}if(r.length===n)break}return t}finally{this.finishOperationOnKey(e,t)}}}class at{interpreter;debug;historyCache;interpreterVersion;ctxKeyFn;constructor(e,t){this.interpreter=e,this.debug=t?.debug??!1,this.historyCache=t?.historyCache,this.interpreterVersion=t?.interpreterVersion??"v1",this.ctxKeyFn=t?.ctxKeyFn??(e=>{try{return JSON.stringify(e??null)}catch{return""}})}historyKey(e,t){let r=e.id("hex"),i=this.ctxKeyFn(t);return`${this.interpreterVersion}|${r}|${i}`}async buildHistory(e,t){if(null!=this.historyCache){let r=this.historyKey(e,t);if(this.historyCache.has(r)){let e=this.historyCache.get(r);if(null!=e)return this.debug&&console.log("[Historian] History cache hit:",r),e.slice()}}let r=[],i=new Set,n=async e=>{let a=e.id("hex");if(i.has(a)){this.debug&&console.log(`[Historian] Skipping already visited transaction: ${a}`);return}i.add(a),this.debug&&console.log(`[Historian] Processing transaction: ${a}`);for(let i=0;i<e.outputs.length;i++)try{let n=await Promise.resolve(this.interpreter(e,i,t));void 0!==n&&(r.push(n),this.debug&&console.log("[Historian] Added value to history:",n))}catch(e){this.debug&&console.log(`[Historian] Failed to interpret output ${i}:`,e)}for(let t of e.inputs)null!=t.sourceTransaction?await n(t.sourceTransaction):this.debug&&console.log("[Historian] Input missing sourceTransaction, skipping")};await n(e);let a=r.reverse();if(null!=this.historyCache){let r=this.historyKey(e,t);this.historyCache.set(r,Object.freeze(a.slice())),this.debug&&console.log("[Historian] History cached:",r)}return a}}let ar={protocolID:0,key:1,value:2,controller:3,tags:4,signature:5},ai=async(e,t,r)=>{try{let i=e.outputs[t];if(null==i||null==i.lockingScript||null==r||null==r.key)return;let n=rB.decode(i.lockingScript),a=Object.keys(ar).length,s=n.fields.length===a;if(n.fields.length!==a-1&&!s)return;let o=ti(n.fields[ar.key]),c=ti(n.fields[ar.protocolID]);if(o!==r.key||c!==JSON.stringify(r.protocolID))return;try{return ti(n.fields[ar.value])}catch{return}}catch{return}},an={protocolID:[1,"kvstore"],serviceName:"ls_kvstore",tokenAmount:1,topics:["tm_kvstore"],networkPreset:"mainnet",acceptDelayedBroadcast:!1,overlayBroadcast:!1,tokenSetDescription:"",tokenUpdateDescription:"",tokenRemovalDescription:""};class aa{wallet;config;historian;lookupResolver;topicBroadcaster;keyLocks=new Map;cachedIdentityKey=null;constructor(e={}){this.config={...an,...e},this.wallet=e.wallet??new nI,this.historian=new at(ai),this.lookupResolver=new n$({networkPreset:this.config.networkPreset}),this.topicBroadcaster=new nW(this.config.topics,{networkPreset:this.config.networkPreset})}async get(e,t={}){if(0===Object.keys(e).length)throw Error("Must specify either key, controller, or protocolID");if(null!=e.key&&null!=e.controller){let r=await this.queryOverlay(e,t);return r.length>0?r[0]:void 0}return await this.queryOverlay(e,t)}async set(e,t,r={}){if("string"!=typeof e||0===e.length)throw Error("Key must be a non-empty string.");if("string"!=typeof t)throw Error("Value must be a string.");let i=await this.getIdentityKey(),n=await this.queueOperationOnKey(e),a=r.protocolID??this.config.protocolID,s=null!=r.tokenSetDescription&&""!==r.tokenSetDescription?r.tokenSetDescription:`Create KVStore value for ${e}`,o=null!=r.tokenUpdateDescription&&""!==r.tokenUpdateDescription?r.tokenUpdateDescription:`Update KVStore value for ${e}`,c=r.tokenAmount??this.config.tokenAmount,l=r.tags??[];try{let r=new rB(this.wallet,this.config.originator),n=[e9(JSON.stringify(a),"utf8"),e9(e,"utf8"),e9(t,"utf8"),e9(i,"hex")];l.length>0&&n.push(e9(JSON.stringify(l),"utf8"));let h=await r.lock(n,a??this.config.protocolID,ti(e9(e,"utf8")),"anyone",!0);return await nj(async()=>{let t=await this.queryOverlay({key:e,controller:i},{includeToken:!0}),n=t.length>0?t[0].token:void 0;if(null!=n){let t=[{outpoint:`${n.txid}.${n.outputIndex}`,unlockingScriptLength:74,inputDescription:"Previous KVStore token"}],i=n.beef,{signableTransaction:a}=await this.wallet.createAction({description:o,inputBEEF:i.toBinary(),inputs:t,outputs:[{satoshis:c??this.config.tokenAmount,lockingScript:h.toHex(),outputDescription:"KVStore token"}],options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast,randomizeOutputs:!1}},this.config.originator);if(null==a)throw Error("Unable to create update transaction");let s=r0.fromAtomicBEEF(a.tx),l=r.unlock(this.config.protocolID,e,"anyone"),u=await l.sign(s,0),{tx:d}=await this.wallet.signAction({reference:a.reference,spends:{0:{unlockingScript:u.toHex()}},options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==d)throw Error("Unable to finalize update transaction");let f=r0.fromAtomicBEEF(d);return await this.submitToOverlay(f),`${f.id("hex")}.0`}{let{tx:e}=await this.wallet.createAction({description:s,outputs:[{satoshis:c??this.config.tokenAmount,lockingScript:h.toHex(),outputDescription:"KVStore token"}],options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast,randomizeOutputs:!1}},this.config.originator);if(null==e)throw Error("Failed to create transaction");let t=r0.fromAtomicBEEF(e);return await this.submitToOverlay(t),`${t.id("hex")}.0`}},this.topicBroadcaster)}finally{n.length>0&&this.finishOperationOnKey(e,n)}}async remove(e,t,r={}){if("string"!=typeof e||0===e.length)throw Error("Key must be a non-empty string.");let i=await this.getIdentityKey(),n=await this.queueOperationOnKey(e),a=r.protocolID??this.config.protocolID,s=null!=r.tokenRemovalDescription&&""!==r.tokenRemovalDescription?r.tokenRemovalDescription:`Remove KVStore value for ${e}`;try{let r=new rB(this.wallet,this.config.originator);return await nj(async()=>{let n=await this.queryOverlay({key:e,controller:i},{includeToken:!0});if(0===n.length||null==n[0].token)throw Error("The item did not exist, no item was deleted.");let o=n[0].token,c=[{outpoint:`${o.txid}.${o.outputIndex}`,unlockingScriptLength:74,inputDescription:"KVStore token to remove"}],{signableTransaction:l}=await this.wallet.createAction({description:s,inputBEEF:o.beef.toBinary(),inputs:c,outputs:t,options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,randomizeOutputs:!1,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==l)throw Error("Unable to create removal transaction");let h=r0.fromAtomicBEEF(l.tx),u=r.unlock(a??this.config.protocolID,e,"anyone"),d=await u.sign(h,0),{tx:f}=await this.wallet.signAction({reference:l.reference,spends:{0:{unlockingScript:d.toHex()}},options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==f)throw Error("Unable to finalize removal transaction");let p=r0.fromAtomicBEEF(f);return await this.submitToOverlay(p),p.id("hex")},this.topicBroadcaster)}finally{n.length>0&&this.finishOperationOnKey(e,n)}}async queueOperationOnKey(e){let t=this.keyLocks.get(e);null==t&&(t=[],this.keyLocks.set(e,t));let 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]():this.keyLocks.delete(e)}async getIdentityKey(){return null==this.cachedIdentityKey&&(this.cachedIdentityKey=(await this.wallet.getPublicKey({identityKey:!0},this.config.originator)).publicKey),this.cachedIdentityKey}async queryOverlay(e,t={}){let r=await this.lookupResolver.query({service:t.serviceName??this.config.serviceName,query:e});if("output-list"!==r.type||0===r.outputs.length)return[];let i=[];for(let e of r.outputs)try{let r,n=r0.fromBEEF(e.beef),a=n.outputs[e.outputIndex],s=rB.decode(a.lockingScript),o=Object.keys(ar).length,c=s.fields.length===o;if(s.fields.length!==o-1&&!c)continue;let l=new iE("anyone"),h=s.fields.pop();try{await l.verifySignature({data:s.fields.reduce((e,t)=>[...e,...t],[]),signature:h,counterparty:e7(s.fields[ar.controller]),protocolID:JSON.parse(ti(s.fields[ar.protocolID])),keyID:ti(s.fields[ar.key])})}catch(e){continue}if(c&&null!=s.fields[ar.tags])try{r=JSON.parse(ti(s.fields[ar.tags]))}catch(e){r=void 0}let u={key:ti(s.fields[ar.key]),value:ti(s.fields[ar.value]),controller:e7(s.fields[ar.controller]),protocolID:JSON.parse(ti(s.fields[ar.protocolID])),tags:r};!0===t.includeToken&&(u.token={txid:n.id("hex"),outputIndex:e.outputIndex,beef:rZ.fromBinary(e.beef),satoshis:a.satoshis??1}),!0===t.history&&(u.history=await this.historian.buildHistory(n,{key:u.key,protocolID:u.protocolID})),i.push(u)}catch(e){continue}return i}async submitToOverlay(e){return await this.topicBroadcaster.broadcast(e)}}let as=aa;return p})());
19
+ `);return e}addComputedLeaves(){let e=e=>e7(eo(e9(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 n=t.path[r-1].find(e=>e.offset===i.offset+1),a=i.offset>>1;void 0!==n&&"string"==typeof n.hash&&t.path[r].every(e=>e.offset!==a)&&t.path[r].push({offset:a,hash:e(n.hash+i.hash)})}}}let rQ="undefined"!=typeof globalThis?globalThis.Buffer:void 0;class r0{version;inputs;outputs;lockTime;metadata;merklePath;cachedHash;rawBytesCache;hexCache;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}=r0.fromAnyBeef(e,t);return r}static fromAtomicBEEF(e){let{tx:t,txid:r,beef:i}=r0.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=rZ.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,n=r.findAtomicTransaction(i);if(null==n)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:n,beef:r,txid:i}}static fromEF(e){let t=new td(e),r=t.readUInt32LE();if("0000000000ef"!==e7(t.read(6)))throw Error("Invalid EF marker");let i=t.readVarIntNum(),n=[];for(let e=0;e<i;e++){let e=e7(t.readReverse(32)),r=t.readUInt32LE(),i=t.readVarIntNum(),a=t.read(i),s=rP.fromBinary(a),o=t.readUInt32LE(),c=t.readUInt64LEBn().toNumber(),l=t.readVarIntNum(),h=t.read(l),u=rE.fromBinary(h),d=new r0(void 0,[],[],void 0);d.outputs=Array(r+1).fill(null),d.outputs[r]={satoshis:c,lockingScript:u},n.push({sourceTransaction:d,sourceTXID:e,sourceOutputIndex:r,unlockingScript:s,sequence:o})}let a=t.readVarIntNum(),s=[];for(let e=0;e<a;e++){let e=t.readUInt64LEBn().toNumber(),r=t.readVarIntNum(),i=t.read(r),n=rE.fromBinary(i);s.push({satoshis:e,lockingScript:n})}return new r0(r,n,s,t.readUInt32LE())}static parseScriptOffsets(e){let t=new td(e),r=[],i=[];t.pos+=4;let n=t.readVarIntNum();for(let e=0;e<n;e++){t.pos+=36;let i=t.readVarIntNum();r.push({vin:e,offset:t.pos,length:i}),t.pos+=i+4}let a=t.readVarIntNum();for(let e=0;e<a;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=e7(e.readReverse(32)),r=e.readUInt32LE(),n=e.readVarIntNum(),a=e.read(n),s=rP.fromBinary(a),o=e.readUInt32LE();i.push({sourceTXID:t,sourceOutputIndex:r,unlockingScript:s,sequence:o})}let n=e.readVarIntNum(),a=[];for(let t=0;t<n;t++){let t=e.readUInt64LEBn().toNumber(),r=e.readVarIntNum(),i=e.read(r),n=rE.fromBinary(i);a.push({satoshis:t,lockingScript:n})}return new r0(t,i,a,e.readUInt32LE())}static fromBinary(e){let t=e.slice(),r=Uint8Array.from(t),i=new td(t),n=r0.fromReader(i);return n.rawBytesCache=r,n}static fromHex(e){let t=e9(e,"hex"),r=Uint8Array.from(t),i=new td(t),n=r0.fromReader(i);return n.rawBytesCache=r,n.hexCache=null!=rQ?rQ.from(r).toString("hex"):e7(t),n}static fromHexEF(e){return r0.fromEF(e9(e,"hex"))}static fromHexBEEF(e,t){return r0.fromBEEF(e9(e,"hex"),t)}constructor(e=1,t=[],r=[],i=0,n=new Map,a){this.version=e,this.inputs=t,this.outputs=r,this.lockTime=i,this.metadata=n,this.merklePath=a}invalidateSerializationCaches(){this.cachedHash=void 0,this.rawBytesCache=void 0,this.hexCache=void 0}addInput(e){if(void 0===e.sourceTXID&&void 0===e.sourceTransaction)throw Error("A reference to an an input transaction is required. If the input transaction itself cannot be referenced, its TXID must still be provided.");void 0===e.sequence&&(e.sequence=0xffffffff),this.invalidateSerializationCaches(),this.inputs.push(e)}addOutput(e){if(this.cachedHash=void 0,!0!==e.change){if(void 0===e.satoshis)throw Error("either satoshis must be defined or change must be set to true");if(e.satoshis<0)throw Error("satoshis must be a positive integer or zero")}if(null==e.lockingScript)throw Error("lockingScript must be defined");this.outputs.push(e)}addP2PKHOutput(e,t){let r=new rC().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=rU.getInstance(),t="equal"){if(this.invalidateSerializationCaches(),"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,n=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);n[e]=n[e]+t,r+=t,i-=t}for(let e of this.outputs)!0===e.change&&(e.satoshis=n.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.invalidateSerializationCaches(),this.outputs))if(void 0===e.satoshis)if(!0===e.change)throw Error("There are still change outputs with uncomputed amounts. Use the fee() method to compute the change amounts and transaction fees prior to signing.");else throw Error("One or more transaction outputs is missing an amount. Ensure all output amounts are provided before signing.");let e=await Promise.all(this.inputs.map(async(e,t)=>"object"==typeof this.inputs[t].unlockingScriptTemplate?await this.inputs[t]?.unlockingScriptTemplate?.sign(this,t):await Promise.resolve(void 0)));for(let t=0,r=this.inputs.length;t<r;t++)"object"==typeof this.inputs[t].unlockingScriptTemplate&&(this.inputs[t].unlockingScript=e[t])}async broadcast(e=rM()){return await e.broadcast(this)}writeTransactionBody(e){for(let t of(e.writeUInt32LE(this.version),e.writeVarIntNum(this.inputs.length),this.inputs)){if(void 0===t.sourceTXID)if(null!=t.sourceTransaction)e.write(t.sourceTransaction.hash());else throw Error("sourceTransaction is undefined");else e.writeReverse(e9(t.sourceTXID,"hex"));if(e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw Error("unlockingScript is undefined");let r=t.unlockingScript.toUint8Array();e.writeVarIntNum(r.length),e.write(r),e.writeUInt32LE(t.sequence??0xffffffff)}for(let t of(e.writeVarIntNum(this.outputs.length),this.outputs)){e.writeUInt64LE(t.satoshis??0);let r=t.lockingScript.toUint8Array();e.writeVarIntNum(r.length),e.write(r)}e.writeUInt32LE(this.lockTime)}buildSerializedBytes(){let e=new tu;return this.writeTransactionBody(e),e.toUint8Array()}getSerializedBytes(){return null==this.rawBytesCache&&(this.rawBytesCache=this.buildSerializedBytes()),this.rawBytesCache}toBinary(){return Array.from(this.getSerializedBytes())}toUint8Array(){return this.getSerializedBytes()}toEF(){let e=new tu;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(e9(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??0xffffffff),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 e7(this.toEF())}toHex(){if(null!=this.hexCache)return this.hexCache;let e=this.getSerializedBytes(),t=null!=rQ?rQ.from(e).toString("hex"):e7(Array.from(e));return this.hexCache=t,t}toHexBEEF(){return e7(this.toBEEF())}toHexAtomicBEEF(){return e7(this.toAtomicBEEF())}hash(e){return(null==this.cachedHash&&(this.cachedHash=eo(this.getSerializedBytes())),"hex"===e)?e7(this.cachedHash):this.cachedHash}id(e){let t=[...this.hash()];return(t.reverse(),"hex"===e)?e7(t):t}async verify(e=rz(),t,r){let i=new Set,n=[this];for(;n.length>0;){let a=n.shift(),s=a?.id("hex")??"";if(null!=s&&""!==s&&i.has(s))continue;if("object"==typeof a?.merklePath)if("scripts only"===e){null!=s&&i.add(s);continue}else{if(await a.merklePath.verify(s,e)){i.add(s);continue}throw Error(`Invalid merkle path for transaction ${s}`)}if(void 0!==t){if(void 0===a)throw Error("Transaction is undefined");let e=r0.fromEF(a.toEF());if(delete e.outputs[0].satoshis,e.outputs[0].change=!0,await e.fee(t),a.getFee()<e.getFee())throw Error(`Verification failed because the transaction ${s} has an insufficient fee and has not been mined.`)}let o=0;if(void 0===a)throw Error("Transaction is undefined");for(let e=0;e<a.inputs.length;e++){let t=a.inputs[e];if("object"!=typeof t.sourceTransaction)throw Error(`Verification failed because the input at index ${e} of transaction ${s} is missing an associated source transaction. This source transaction is required for transaction verification because there is no merkle proof for the transaction spending a UTXO it contains.`);if("object"!=typeof t.unlockingScript)throw Error(`Verification failed because the input at index ${e} of transaction ${s} is missing an associated unlocking script. This script is required for transaction verification because there is no merkle proof for the transaction spending the UTXO.`);let c=t.sourceTransaction.outputs[t.sourceOutputIndex];o+=c.satoshis??0;let l=t.sourceTransaction.id("hex");i.has(l)||n.push(t.sourceTransaction);let h=a.inputs.filter((t,r)=>r!==e);if(void 0===t.sourceTXID&&(t.sourceTXID=l),!new rT({sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,lockingScript:c.lockingScript,sourceSatoshis:c.satoshis??0,transactionVersion:a.version,otherInputs:h,unlockingScript:t.unlockingScript,inputSequence:t.sequence??0xffffffff,inputIndex:e,outputs:a.outputs,lockTime:a.lockTime,memoryLimit:r}).validate())return!1}let c=0;for(let e of a.outputs){if("number"!=typeof e.satoshis)throw Error("Every output must have a defined amount during transaction verification.");c+=e.satoshis}if(c>o)return!1;i.add(s)}return!0}toBEEF(e){let t=new tu;t.writeUInt32LE(rG);let r=[],i=new Map,n=new Map,a=[],s=new Set,o=t=>{let c=t.id("hex");if(s.has(c))return;let l={tx:t},h=t.merklePath,u="object"==typeof h;if(u&&null!=h&&(l.pathIndex=(e=>{let t=i.get(e);if(void 0!==t)return t;let a=`${e.blockHeight}:${e.computeRoot()}`,s=n.get(a);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),n.set(a,o),o})(h)),!u)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),a.push(l)};for(let e of(o(this),t.writeVarIntNum(r.length),r))t.write(e.toBinary());for(let e of(t.writeVarIntNum(a.length),a))t.write(e.tx.toBinary()),"number"==typeof e.pathIndex?(t.writeUInt8(1),t.writeVarIntNum(e.pathIndex)):t.writeUInt8(0);return t.toArray()}toAtomicBEEF(e){return[1,1,1,1].concat(this.hash(),this.toBEEF(e))}}function r1(e){return"success"===e.status}function r2(e){return"error"===e.status}let r8=class extends rZ{knownTo={};constructor(e){if(super(),null!=e)for(const t of e)this.addParty(t)}isParty(e){return Object.keys(this.knownTo).includes(e)}addParty(e){if(this.isParty(e))throw Error(`Party ${e} already exists.`);this.knownTo[e]={}}getKnownTxidsForParty(e){let t=this.knownTo[e];if(void 0===t)throw Error(`Party ${e} is unknown.`);return Object.keys(t)}getTrimmedBeefForParty(e){let t=this.getKnownTxidsForParty(e),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)?rZ.fromBinary(t):t,i=r.getValidTxids();this.mergeBeef(r),this.addKnownTxidsForParty(e,i)}};class r3{network;URL;httpClient;constructor(e="main",t=rK()){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 r6{https;constructor(e){this.https=e}async request(e,t){return await new Promise((r,i)=>{let n=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,n=e.headers["content-type"],a=""!==t&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(t):t;r({status:e.statusCode,statusText:e.statusMessage,ok:i,data:a})})});n.on("error",e=>{i(e)}),null!==t.data&&void 0!==t.data&&n.write(Buffer.from(t.data)),n.end()})}}class r4{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),n=await i.text();return{ok:i.ok,status:i.status,statusText:i.statusText,data:n}}}function r5(){let e={async request(){throw Error("No method available to perform HTTP request")}};if("undefined"!=typeof window&&"function"==typeof window.fetch)return new r4(window.fetch.bind(window));if("undefined"==typeof require)return e;try{let e=require("https");return new r6(e)}catch(t){return e}}class r7{URL;httpClient;constructor(e,t=r5()){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 r9{baseUrl;httpClient;apiKey;constructor(e,t={}){const{httpClient:r,apiKey:i}=t;this.baseUrl=e,this.httpClient=r??rK(),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 ie="42423301",it=(e,t,r)=>{let i="object"!=typeof r;if(i){let e=new tU,t=new t1(1),i=e.g.mul(t);r=new tX(i.x,i.y)}let n=tJ(32),a=ta(n),s=`2-message signing-${a}`,o=t.deriveChild(r,s).sign(e).toDER(),c=t.toPublicKey().encode(!0);return[...e9(ie,"hex"),...c,...i?[0]:r.encode(!0),...n,...o]},ir=(e,t,r)=>{let i=new td(t),n=e7(i.read(4));if(n!==ie)throw Error(`Message version mismatch: Expected ${ie}, received ${n}`);let a=tX.fromString(e7(i.read(33))),[s]=i.read(1);if(0===s)r=new t1(1);else{let e=e7([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=ta(i.read(32)),c=e7(i.read(i.bin.length-i.pos)),l=tF.fromDER(c,"hex"),h=`2-message signing-${o}`;return a.deriveChild(r,h).verify(e,l)},ii="42421033",ia=(e,t,r)=>{let i=tJ(32),n=ta(i),a=`2-message encryption-${n}`,s=t.deriveChild(r,a),o=r.deriveChild(t,a),c=new rl(s.deriveSharedSecret(o).encode(!0).slice(1)).encrypt(e),l=t.toPublicKey().encode(!0);return[...e9(ii,"hex"),...l,...r.encode(!0),...i,...c]},is=(e,t)=>{let r=new td(e),i=e7(r.read(4));if(i!==ii)throw Error(`Message version mismatch: Expected ${ii}, received ${i}`);let n=tX.fromString(e7(r.read(33))),a=e7(r.read(33)),s=t.toPublicKey().encode(!0,"hex");if(a!==s)throw Error(`The encrypted message expects a recipient public key of ${a}, but the provided key is ${s}`);let o=ta(r.read(32)),c=r.read(r.bin.length-r.pos),l=`2-message encryption-${o}`,h=n.deriveChild(t,l),u=t.deriveChild(n,l);return new rl(h.deriveSharedSecret(u).encode(!0).slice(1)).decrypt(c)},io="Bitcoin Signed Message:\n",ic=e=>{let t=new tu;return t.writeVarIntNum(io.length),t.write(e9(io,"utf8")),t.writeVarIntNum(e.length),t.write(e),eo(t.toArray())},il=(e,t,r="base64")=>{let i=ic(e),n=tW(new P(i),t,!0);if("raw"===r)return n;let a=new P(i),s=n.CalculateRecoveryFactor(t.toPublicKey(),a);return n.toCompact(s,!0,"base64")},ih=(e,t,r)=>tj(new P(ic(e)),t,r);class iu{versionBytesNum;depth;parentFingerPrint;childIndex;chainCode;privKey;pubKey;constants={pubKey:0x488b21e,privKey:0x488ade4};constructor(e,t,r,i,n,a,s){this.versionBytesNum=e,this.depth=t,this.parentFingerPrint=r,this.childIndex=i,this.chainCode=n,this.privKey=a,this.pubKey=s}fromRandom(){return this.versionBytesNum=this.constants.privKey,this.depth=0,this.parentFingerPrint=[0,0,0,0],this.childIndex=0,this.chainCode=tJ(32),this.privKey=t1.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=th(e);return this.fromBinary([...t.prefix,...t.data])}static fromSeed(e){return new this().fromSeed(e)}fromSeed(e){if(e.length<16)throw Error("Need more than 128 bits of entropy");if(e.length>64)throw Error("More than 512 bits of entropy is nonstandard");let t=eh(e9("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 t1(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 td(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,n=this.versionBytesNum===this.constants.pubKey;if(i&&0===r[0])this.privKey=new t1(r.slice(1,33)),this.pubKey=this.privKey.toPublicKey();else if(n&&(2===r[0]||3===r[0]))this.pubKey=tX.fromString(e7(r));else throw Error("Invalid key");return this}toString(){return tl(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],n=0x7fffffff&parseInt(t?i.slice(0,i.length-1):i,10);t&&(n+=0x80000000),r=r.deriveChild(n)}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,n=this.versionBytesNum===this.constants.privKey;if(i&&(null===this.privKey||void 0===this.privKey||!n))throw Error("Cannot do private key derivation without private key");let a=null;if(null!==this.privKey&&void 0!==this.privKey){let e=null;e=i?[0,...this.privKey.toArray("be",32),...r]:[...this.pubKey.encode(!0),...r];let t=eh(this.chainCode,e),n=new P(t.slice(0,32)),s=t.slice(32,64),o=n.add(this.privKey).mod(new tU().n);(a=new iu).chainCode=s,a.privKey=new t1(o.toArray()),a.pubKey=a.privKey.toPublicKey()}else{let e=[...this.pubKey.encode(!0),...r],t=eh(this.chainCode,e),i=new P(t.slice(0,32)),n=t.slice(32,64),s=new tU().g.mul(i),o=this.pubKey,c=s.add(o),l=new tX(c.x,c.y);(a=new iu).chainCode=n,a.pubKey=l}a.childIndex=e;let s=ec(this.pubKey.encode(!0));return a.parentFingerPrint=s.slice(0,4),a.versionBytesNum=this.versionBytesNum,a.depth=this.depth+1,a}toPublic(){let e=new iu(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 tu().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 tu().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 id={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 ip{mnemonic;seed;Wordlist;constructor(e,t,r=id){this.mnemonic=e??"",this.seed=t??[],this.Wordlist=r}toBinary(){let e=new tu;if(""!==this.mnemonic){let t=e9(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 td(e),r=t.readVarIntNum();r>0&&(this.mnemonic=tn(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=tJ(e/8);return this.entropy2Mnemonic(t),this.mnemonic2Seed(),this}static fromRandom(e){return new this().fromRandom(e)}fromEntropy(e){return this.entropy2Mnemonic(e),this}static fromEntropy(e){return new this().fromEntropy(e)}fromString(e){return this.mnemonic=e,this}static fromString(e){return new this().fromString(e)}toString(){return this.mnemonic}toSeed(e){return this.mnemonic2Seed(e),this.seed}entropy2Mnemonic(e){if(e.length<16)throw Error("Entropy is less than 128 bits. It must be 128 bits or more.");let t=ea(e),r="",i=8*e.length;for(let t=0;t<e.length;t++)r+=("00000000"+e[t].toString(2)).slice(-8);let n=t[0].toString(2);if((r+=n=("00000000"+n).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 a="";for(let e=0;e<r.length/11;e++){""!==a&&(a+=this.Wordlist.space);let t=parseInt(r.slice(11*e,(e+1)*11),2);a+=this.Wordlist.value[t]}return this.mnemonic=a,this}check(){let e=this.mnemonic.split(this.Wordlist.space),t="";for(let 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),n=t.slice(0,t.length-r),a=[];for(let e=0;e<n.length/8;e++)a.push(parseInt(t.slice(8*e,(e+1)*8),2));let s=ea(a.slice(0,n.length/8))[0].toString(2);return(s=("00000000"+s).slice(-8).slice(0,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=e9(t,"utf8"),i=[...e9("mnemonic","utf8"),...e9(e,"utf8")];return this.seed=eQ(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 ip(e).isValid(t)}}function ig(e){let t,r,i,n;0===this._tables[0][0][0]&&this._precompute();let a=this._tables[0][4],s=this._tables[1],o=e.length,c=1;if(4!==o&&6!==o&&8!==o)throw Error("invalid aes key size");for(this._key=[r=e.slice(0),i=[]],n=o;n<4*o+28;n++)t=r[n-1],(n%o==0||8===o&&n%o==4)&&(t=a[t>>>24]<<24^a[t>>16&255]<<16^a[t>>8&255]<<8^a[255&t],n%o==0&&(t=t<<8^t>>>24^c<<24,c=c<<1^(c>>7)*283)),r[n]=r[n-o]^t;for(let e=0;n>0;e++,n--)t=r[(3&e)!=0?n:n-4],n<=4||e<4?i[e]=t:i[e]=s[0][a[t>>>24]]^s[1][a[t>>16&255]]^s[2][a[t>>8&255]]^s[3][a[255&t]]}ig.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,n,a,s,o,c=this._tables[0],l=this._tables[1],h=c[4],u=l[4],d=new Uint8Array(256),f=new Uint8Array(256);for(e=0;e<256;e++)f[(d[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,a=(a=r^r<<1^r<<2^r<<3^r<<4)>>8^255&a^99,h[t]=a,u[a]=t,o=0x1010101*d[n=d[i=d[t]]]^65537*n^257*i^0x1010100*t,s=257*d[a]^0x1010100*a;e<4;e++)c[e][t]=s=s<<24^s>>>8,l[e][a]=o=o<<24^o>>>8},_crypt:function(e,t){let r,i,n,a;if(4!==e.length)throw Error("invalid aes block size");let s=this._key[t],o=e[0]^s[0],c=e[1===t?3:1]^s[1],l=e[2]^s[2],h=e[1===t?1:3]^s[3],u=s.length/4-2,d=4,f=new Uint32Array(4),p=this._tables[t],g=p[0],b=p[1],y=p[2],m=p[3],w=p[4];for(a=0;a<u;a++)r=g[o>>>24]^b[c>>16&255]^y[l>>8&255]^m[255&h]^s[d],i=g[c>>>24]^b[l>>16&255]^y[h>>8&255]^m[255&o]^s[d+1],n=g[l>>>24]^b[h>>16&255]^y[o>>8&255]^m[255&c]^s[d+2],h=g[h>>>24]^b[o>>16&255]^y[c>>8&255]^m[255&l]^s[d+3],d+=4,o=r,c=i,l=n;for(a=0;a<4;a++)f[1===t?3&-a:a]=w[o>>>24]<<24^w[c>>16&255]<<16^w[l>>8&255]<<8^w[255&h]^s[d++],r=o,o=c,c=l,l=h,h=r;return f}};class ib{static encrypt(e,t){let r=ib.buf2Words(t),i=ib.buf2Words(e),n=new ig(r).encrypt(i);return ib.words2Buf(n)}static decrypt(e,t){let r=ib.buf2Words(e),i=new ig(ib.buf2Words(t)).decrypt(r);return ib.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 iy{static buf2BlocksBuf(e,t){let r=t/8,i=[];for(let n=0;n<=e.length/r;n++){let a=e.slice(n*r,n*r+r);a.length<t&&(a=iy.pkcs7Pad(a,t)),i.push(a)}return i}static blockBufs2Buf(e){let t=e[e.length-1];return t=iy.pkcs7Unpad(t),e[e.length-1]=t,e.flat()}static encrypt(e,t,r,i){let n=8*t.length,a=iy.buf2BlocksBuf(e,n);return iy.encryptBlocks(a,t,r,i).flat()}static decrypt(e,t,r,i){let n=t.length,a=[];for(let t=0;t<e.length/n;t++)a.push(e.slice(t*n,t*n+n));let s=iy.decryptBlocks(a,t,r,i);return iy.blockBufs2Buf(s)}static encryptBlock(e,t,r,i){let n=iy.xorBufs(e,t);return r.encrypt(n,i)}static decryptBlock(e,t,r,i){let n=r.decrypt(e,i);return iy.xorBufs(n,t)}static encryptBlocks(e,t,r,i){let n=[];for(let a=0;a<e.length;a++){let s=e[a],o=iy.encryptBlock(s,t,r,i);n.push(o),t=o}return n}static decryptBlocks(e,t,r,i){let n=[];for(let a=0;a<e.length;a++){let s=e[a],o=iy.decryptBlock(s,t,r,i);n.push(o),t=s}return n}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),e7(r)!==e7(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 im{static encrypt(e,t,r,i=!0){r=r??tJ(16);let n=iy.encrypt(e,r,ib,t);return i?[...r,...n]:[...n]}static decrypt(e,t,r){if(null!=r)return iy.decrypt(e,r,ib,t);{r=e.slice(0,16);let i=e.slice(16);return iy.decrypt(i,r,ib,t)}}}class iw{static ivkEkM(e,t){let r=t.mul(e),i=es(new tX(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 n,a=null;null==r&&(r=t1.fromRandom()),i||(a=r.toPublicKey().encode(!0));let{iv:s,kE:o,kM:c}=iw.ivkEkM(r,t),l=im.encrypt(e,o,s,!1),h=e9("BIE1","utf8"),u=el(c,n=null!=a&&a.length>0?[...h,...a,...l]:[...h,...l]);return[...n,...u]}static electrumDecrypt(e,t,r){if("BIE1"!==tn(e.slice(0,4),"utf8"))throw Error("Invalid Magic");let i=4,n=null;if(e.length-i-32>=33){let t=e[i];2===t||3===t?(n=e.slice(i,i+33),i+=33):4===t&&(n=e.slice(i,i+65),i+=65)}if(null!==n)null==r&&(r=tX.fromString(e7(n)));else if(null==r)throw Error("Sender public key is required");let{iv:a,kE:s,kM:o}=iw.ivkEkM(t,r),c=e.slice(i,e.length-32),l=e.slice(e.length-32,e.length),h=el(o,e.slice(0,e.length-32));if(e7(l)!==e7(h))throw Error("Invalid checksum");return im.decrypt(c,s,a)}static bitcoreEncrypt(e,t,r,i){null==r&&(r=t1.fromRandom()),null==i&&(i=tJ(16));let n=r,a=r.toPublicKey().encode(!0),s=es(t.mul(n).getX().toArray("be",32)),o=s.slice(0,32),c=s.slice(32,64),l=im.encrypt(e,o,i),h=el(c,[...l]);return[...a,...l,...h]}static bitcoreDecrypt(e,t){let r=tX.fromString(e7(e.slice(0,33))).mul(t);if(r.eq(new tD(0,0)))throw Error("P equals 0");let i=es(r.getX().toArray("be",32)),n=i.slice(0,32),a=i.slice(32,64),s=e.slice(33,e.length-32),o=e.slice(e.length-32,e.length),c=el(a,s);if(e7(o)!==e7(c))throw Error("Invalid checksum");return[...im.decrypt(s,n)]}}function iv(e,t){let r=new r0(0,[],[],0);return r.outputs=Array(e.vout+1).fill(null),r.outputs[e.vout]={satoshis:e.satoshis,lockingScript:rE.fromHex(e.script)},{sourceTransaction:r,sourceTXID:e.txid,sourceOutputIndex:e.vout,unlockingScriptTemplate:t,sequence:0xffffffff}}class iI{static generate(e,t){let r=this.withDefaultOptions(t);return ik(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 n=this.getCounter(i.timestamp,i.period),a=[n];for(let e=1;e<=i.skew;e++)a.push(n+e),a.push(n-e);for(let r of a){let n=ik(e,r,i);if(ty(e9(t,"utf8"),e9(n,"utf8")))return!0}return!1}static getCounter(e,t){return Math.floor(Math.floor(e/1e3)/t)}static withDefaultOptions(e){return{digits:2,algorithm:"SHA-1",period:30,timestamp:Date.now(),...e}}static withDefaultValidateOptions(e){return{skew:1,...this.withDefaultOptions(e)}}}function ik(e,t,r){let i=(function(e,t,r){switch(r){case"SHA-1":return new et(e).update(t);case"SHA-256":return new ee(e).update(t);case"SHA-512":return new er(e).update(t);default:throw Error("unsupported HMAC algorithm")}})(e,new P(t).toArray("be",8),r.algorithm).digest(),n=15&i[i.length-1];return(0x7fffffff&new P(i.slice(n,n+4)).toNumber()).toString().slice(-r.digits)}(s=h||(h={}))[s.Silent=0]="Silent",s[s.App=1]="App",s[s.Counterparty=2]="Counterparty";class iS{cacheSharedSecret;retrieveCachedSharedSecret;rootKey;identityKey;anyone;constructor(e,t,r){this.cacheSharedSecret=t,this.retrieveCachedSharedSecret=r,this.anyone=new t1(1).toPublicKey(),"anyone"===e?this.rootKey=new t1(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),n=this.derivePrivateKey(e,t,r);return new rl(n.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),n=e9(this.computeInvoiceNumber(t,r),"utf8");return el(i.encode(!0),n)}normalizeCounterparty(e){if(null==e)throw Error("counterparty must be self, anyone or a public key!");return"self"===e?this.rootKey.toPublicKey():"anyone"===e?new t1(1).toPublicKey():"string"==typeof e?tX.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 ix{keyDeriver;cache;maxCacheSize;rootKey;identityKey;constructor(e,t){"anyone"===e?this.rootKey=new t1(1):this.rootKey=e,this.keyDeriver=new iS(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;const r=t?.maxCacheSize;this.maxCacheSize=null!=r&&!isNaN(r)&&r>0?r:1e3}derivePublicKey(e,t,r,i=!1){let n=this.generateCacheKey("derivePublicKey",e,t,r,i);if(this.cache.has(n)){let e=this.cacheGet(n);if(void 0===e)throw Error("Cached value is undefined");return e}{let a=this.keyDeriver.derivePublicKey(e,t,r,i);return this.cacheSet(n,a),a}}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 n=this.keyDeriver.derivePrivateKey(e,t,r);return this.cacheSet(i,n),n}}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 n=this.keyDeriver.deriveSymmetricKey(e,t,r);return this.cacheSet(i,n),n}}revealCounterpartySecret(e){let t=this.generateCacheKey("revealCounterpartySecret",e);if(this.cache.has(t)){let e=this.cacheGet(t);if(void 0===e)throw Error("Cached value is undefined");return e}{let 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 n=this.keyDeriver.revealSpecificSecret(e,t,r);return this.cacheSet(i,n),n}}generateCacheKey(e,...t){let r=t.map(e=>this.serializeArgument(e)).join("|");return`${e}|${r}`}serializeArgument(e){return e instanceof tX||e instanceof t1?e.toString():Array.isArray(e)?e.map(e=>this.serializeArgument(e)).join(","):"object"==typeof e&&null!==e?JSON.stringify(e):String(e)}cacheGet(e){let t=this.cache.get(e);return this.cache.delete(e),void 0!==t&&this.cache.set(e,t),t}cacheSet(e,t){if(this.cache.size>=this.maxCacheSize){let e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(e,t)}}class iE{keyDeriver;constructor(e){"string"!=typeof e.identityKey&&(e=new ix(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 rd().generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),tX.fromString(e.counterparty),tD.fromDER(r)),n=[...i.R.encode(!0),...i.SPrime.encode(!0),...i.z.toArray()],a=new Date().toISOString(),{ciphertext:s}=await this.encrypt({plaintext:r,protocolID:[2,"counterparty linkage revelation"],keyID:a,counterparty:e.verifier}),{ciphertext:o}=await this.encrypt({plaintext:n,protocolID:[2,"counterparty linkage revelation"],keyID:a,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,revelationTime:a,encryptedLinkage:s,encryptedLinkageProof:o}}async revealSpecificKeyLinkage(e){let{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let r=this.keyDeriver.revealSpecificSecret(e.counterparty,e.protocolID,e.keyID),{ciphertext:i}=await this.encrypt({plaintext:r,protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier}),{ciphertext:n}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,protocolID:e.protocolID,keyID:e.keyID,encryptedLinkage:i,encryptedLinkageProof:n,proofType:0}}async encrypt(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{ciphertext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").encrypt(e.plaintext)}}async decrypt(e,t){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{plaintext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").decrypt(e.ciphertext)}}async createHmac(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{hmac:el(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data)}}async verifyHmac(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let t=el(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data),r=e.hmac,i=ty(e9(t),e9(r));if(!i){let e=Error("HMAC is not valid");throw e.code="ERR_INVALID_HMAC",e}return{valid:i}}async createSignature(e){if(null==e.hashToDirectlySign&&null==e.data)throw Error("args.data or args.hashToDirectlySign must be valid");let t=e.hashToDirectlySign??ea(e.data??[]),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??ea(e.data??[]),r=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf),i=tj(new P(t),tF.fromDER(e.signature),r);if(!i){let e=Error("Signature is not valid");throw e.code="ERR_INVALID_SIGNATURE",e}return{valid:i}}}let iP=iE;class iN{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 iO 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)}static unknownToJson(e){let t;return!0===e.isError&&String(e.name).startsWith("WERR_")?"WERR_REVIEW_ACTIONS"===(t={name:e.name,message:e.message,isError:!0}).name?(t.reviewActionResults=e.reviewActionResults,t.sendWithResults=e.sendWithResults,t.txid=e.txid,t.tx=e.tx,t.noSendChange=e.noSendChange,t.code=5):"WERR_INVALID_PARAMETER"===t.name?(t.parameter=e.parameter,t.code=6):"WERR_INSUFFICIENT_FUNDS"===t.name&&(t.totalSatoshisNeeded=e.totalSatoshisNeeded,t.moreSatoshisNeeded=e.moreSatoshisNeeded,t.code=7):t=e instanceof Error?{name:e.constructor.name,message:e.message,isError:!0}:{name:"WERR_UNKNOWN",message:String(e),isError:!0},JSON.stringify(t)}}(o=u||(u={}))[o.unknownError=1]="unknownError",o[o.unsupportedAction=2]="unsupportedAction",o[o.invalidHmac=3]="invalidHmac",o[o.invalidSignature=4]="invalidSignature",o[o.reviewActions=5]="reviewActions",o[o.invalidParameter=6]="invalidParameter",o[o.insufficientFunds=7]="insufficientFunds";let iA=iO;class i_{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 n=ta(tJ(12)),a=e=>{"CWI"===e.data.type&&e.isTrusted&&e.data.id===n&&!0!==e.data.isInvocation&&("function"==typeof window.removeEventListener&&window.removeEventListener("message",a),"error"===e.data.status?i(new iO(e.data.description,e.data.code)):r(e.data.result))};window.addEventListener("message",a),window.parent.postMessage({type:"CWI",isInvocation:!0,id:n,call:e,args:t},this.domain)})}async createAction(e){return await this.invoke("createAction",e)}async signAction(e){return await this.invoke("signAction",e)}async abortAction(e){return await this.invoke("abortAction",e)}async listActions(e){return await this.invoke("listActions",e)}async internalizeAction(e){return await this.invoke("internalizeAction",e)}async listOutputs(e){return await this.invoke("listOutputs",e)}async relinquishOutput(e){return await this.invoke("relinquishOutput",e)}async getPublicKey(e){return await this.invoke("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.invoke("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.invoke("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.invoke("encrypt",e)}async decrypt(e){return await this.invoke("decrypt",e)}async createHmac(e){return await this.invoke("createHmac",e)}async verifyHmac(e){return await this.invoke("verifyHmac",e)}async createSignature(e){return await this.invoke("createSignature",e)}async verifySignature(e){return await this.invoke("verifySignature",e)}async acquireCertificate(e){return await this.invoke("acquireCertificate",e)}async listCertificates(e){return await this.invoke("listCertificates",e)}async proveCertificate(e){return await this.invoke("proveCertificate",e)}async relinquishCertificate(e){return await this.invoke("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.invoke("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.invoke("discoverByAttributes",e)}async isAuthenticated(e){return await this.invoke("isAuthenticated",e)}async waitForAuthentication(e){return await this.invoke("waitForAuthentication",e)}async getHeight(e){return await this.invoke("getHeight",e)}async getHeaderForHeight(e){return await this.invoke("getHeaderForHeight",e)}async getNetwork(e){return await this.invoke("getNetwork",e)}async getVersion(e){return await this.invoke("getVersion",e)}}class iT{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(e,t,r,i,n,a,s){this.type=e,this.serialNumber=t,this.subject=r,this.certifier=i,this.revocationOutpoint=n,this.fields=a,this.signature=s}toBinary(e=!0){let t=new tu,r=e9(this.type,"base64");t.write(r);let i=e9(this.serialNumber,"base64");t.write(i);let n=e9(this.subject,"hex");t.write(n);let a=e9(this.certifier,"hex");t.write(a);let[s,o]=this.revocationOutpoint.split("."),c=e9(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=e9(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e9(r,"utf8");t.writeVarIntNum(n.length),t.write(n)}if(e&&(this.signature??"").length>0){let e=e9(this.signature,"hex");t.write(e)}return t.toArray()}static fromBinary(e){let t,r=new td(e),i=ta(r.read(32)),n=ta(r.read(32)),a=e7(r.read(33)),s=e7(r.read(33)),o=e7(r.read(32)),c=r.readVarIntNum(),l=`${o}.${c}`,h=r.readVarIntNum(),u={};for(let e=0;e<h;e++){let e=r.readVarIntNum(),t=ti(r.read(e)),i=r.readVarIntNum(),n=ti(r.read(i));u[t]=n}if(!r.eof()){let e=r.read();t=tF.fromDER(e).toString("hex")}return new iT(i,n,a,s,l,u,t)}async verify(){let e=new iP("anyone"),t=this.toBinary(!1),r=this.signature??"",{valid:i}=await e.verifySignature({signature:e9(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=e7(r)}static getCertificateFieldEncryptionDetails(e,t){return{protocolID:[2,"certificate field encryption"],keyID:t?`${t} ${e}`:e}}static fromObject(e){return new iT(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature)}}(c=d||(d={}))[c.createAction=1]="createAction",c[c.signAction=2]="signAction",c[c.abortAction=3]="abortAction",c[c.listActions=4]="listActions",c[c.internalizeAction=5]="internalizeAction",c[c.listOutputs=6]="listOutputs",c[c.relinquishOutput=7]="relinquishOutput",c[c.getPublicKey=8]="getPublicKey",c[c.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",c[c.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",c[c.encrypt=11]="encrypt",c[c.decrypt=12]="decrypt",c[c.createHmac=13]="createHmac",c[c.verifyHmac=14]="verifyHmac",c[c.createSignature=15]="createSignature",c[c.verifySignature=16]="verifySignature",c[c.acquireCertificate=17]="acquireCertificate",c[c.listCertificates=18]="listCertificates",c[c.proveCertificate=19]="proveCertificate",c[c.relinquishCertificate=20]="relinquishCertificate",c[c.discoverByIdentityKey=21]="discoverByIdentityKey",c[c.discoverByAttributes=22]="discoverByAttributes",c[c.isAuthenticated=23]="isAuthenticated",c[c.waitForAuthentication=24]="waitForAuthentication",c[c.getHeight=25]="getHeight",c[c.getHeaderForHeight=26]="getHeaderForHeight",c[c.getNetwork=27]="getNetwork",c[c.getVersion=28]="getVersion";let iC=d;class iR{wire;constructor(e){this.wire=e}async transmit(e,t="",r=[]){let i=new tu;i.writeUInt8(iC[e]);let n=e9(t,"utf8");i.writeUInt8(n.length),i.write(n),r.length>0&&i.write(r);let a=i.toArray(),s=new td(await this.wire.transmitToWallet(a)),o=s.readUInt8();if(0===o)return s.read();{let e=s.readVarIntNum(),t=ti(s.read(e)),r=s.readVarIntNum();throw new iO(t,o,ti(s.read(r)))}}async createAction(e,t){let r=new tu,i=e9(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=e9(t.unlockingScript,"hex");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1),r.writeVarIntNum(t.unlockingScriptLength??0);let e=e9(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=e9(t.lockingScript,"hex");r.writeVarIntNum(e.length),r.write(e),r.writeVarIntNum(t.satoshis);let i=e9(t.outputDescription,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=t.basket&&""!==t.basket){let e=e9(t.basket,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=t.customInstructions&&""!==t.customInstructions){let e=e9(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=e9(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=e9(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=e9(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=e9(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 n=new td(await this.transmit("createAction",t,r.toArray())),a={};if(1===n.readInt8()&&(a.txid=e7(n.read(32))),1===n.readInt8()){let e=n.readVarIntNum();a.tx=n.read(e)}let s=n.readVarIntNum();if(s>=0){a.noSendChange=[];for(let e=0;e<s;e++){let e=this.readOutpoint(n);a.noSendChange.push(e)}}let o=n.readVarIntNum();if(o>=0){a.sendWithResults=[];for(let e=0;e<o;e++){let e=e7(n.read(32)),t=n.readInt8(),r="unproven";1===t?r="unproven":2===t?r="sending":3===t&&(r="failed"),a.sendWithResults.push({txid:e,status:r})}}if(1===n.readInt8()){let e=n.readVarIntNum(),t=n.read(e),r=n.readVarIntNum();a.signableTransaction={tx:t,reference:ta(n.read(r))}}return a}async signAction(e,t){let r=new tu,i=Object.keys(e.spends);for(let t of(r.writeVarIntNum(i.length),i)){r.writeVarIntNum(Number(t));let i=e.spends[Number(t)],n=e9(i.unlockingScript,"hex");r.writeVarIntNum(n.length),r.write(n),"number"==typeof i.sequenceNumber?r.writeVarIntNum(i.sequenceNumber):r.writeVarIntNum(-1)}let n=e9(e.reference,"base64");if(r.writeVarIntNum(n.length),r.write(n),null!=e.options)if(r.writeInt8(1),"boolean"==typeof e.options.acceptDelayedBroadcast?r.writeInt8(+!!e.options.acceptDelayedBroadcast):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=e9(t,"hex");r.write(e)}else r.writeVarIntNum(-1);else r.writeInt8(0);let a=new td(await this.transmit("signAction",t,r.toArray())),s={};if(1===a.readInt8()&&(s.txid=e7(a.read(32))),1===a.readInt8()){let e=a.readVarIntNum();s.tx=a.read(e)}let o=a.readVarIntNum();if(o>=0){s.sendWithResults=[];for(let e=0;e<o;e++){let e=e7(a.read(32)),t=a.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,e9(e.reference,"base64")),{aborted:!0}}async listActions(e,t){let r=new tu;for(let t of(r.writeVarIntNum(e.labels.length),e.labels)){let e=e9(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 td(await this.transmit("listActions",t,r.toArray())),n=i.readVarIntNum(),a=[];for(let e=0;e<n;e++){let e,t=e7(i.read(32)),r=i.readVarIntNum(),n=i.readInt8();switch(n){case 1:e="completed";break;case 2:e="unprocessed";break;case 3:e="sending";break;case 4:e="unproven";break;case 5:e="unsigned";break;case 6:e="nosend";break;case 7:e="nonfinal";break;case 8:e="failed";break;default:throw Error(`Unknown status code: ${n}`)}let s=1===i.readInt8(),o=i.readVarIntNum(),c={txid:t,satoshis:r,status:e,isOutgoing:s,description:ti(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(ti(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),n=i.readVarIntNum(),a=i.readVarIntNum();a>=0&&(e=e7(i.read(a)));let s=i.readVarIntNum();s>=0&&(t=e7(i.read(s)));let o=i.readVarIntNum(),l=ti(i.read(o)),h=i.readVarIntNum();c.inputs.push({sourceOutpoint:r,sourceSatoshis:n,sourceLockingScript:e,unlockingScript:t,inputDescription:l,sequenceNumber:h})}}let u=i.readVarIntNum();if(u>=0){c.outputs=[];for(let e=0;e<u;e++){let e,t,r,n=i.readVarIntNum(),a=i.readVarIntNum(),s=i.readVarIntNum();s>=0&&(e=e7(i.read(s)));let o=1===i.readInt8(),l=i.readVarIntNum(),h=ti(i.read(l)),u=i.readVarIntNum();u>=0&&(t=ti(i.read(u)));let d=i.readVarIntNum(),f=[];if(d>=0)for(let e=0;e<d;e++){let e=i.readVarIntNum(),t=i.read(e);f.push(ti(t))}let p=i.readVarIntNum();p>=0&&(r=ti(i.read(p))),c.outputs.push({outputIndex:n,satoshis:a,lockingScript:e,spendable:o,outputDescription:h,basket:t,tags:f,customInstructions:r})}}a.push(c)}return{totalActions:n,actions:a}}async internalizeAction(e,t){let r=new tu;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(e9(t.paymentRemittance.senderIdentityKey,"hex"));let e=e9(t.paymentRemittance.derivationPrefix,"base64");r.writeVarIntNum(e.length),r.write(e);let i=e9(t.paymentRemittance.derivationSuffix,"base64");r.writeVarIntNum(i.length),r.write(i)}else{r.writeUInt8(2);let e=e9(t.insertionRemittance?.basket,"utf8");if(r.writeVarIntNum(e.length),r.write(e),"string"==typeof t.insertionRemittance?.customInstructions&&""!==t.insertionRemittance.customInstructions){let e=e9(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=e9(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=e9(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);let i=e9(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 tu,n=e9(e.basket,"utf8");if(i.writeVarIntNum(n.length),i.write(n),"object"==typeof e.tags)for(let t of(i.writeVarIntNum(e.tags.length),e.tags)){let e=e9(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 a=new td(await this.transmit("listOutputs",t,i.toArray())),s=a.readVarIntNum(),o=a.readVarIntNum();o>=0&&(r=a.read(o));let c=[];for(let e=0;e<s;e++){let e={spendable:!0,outpoint:this.readOutpoint(a),satoshis:a.readVarIntNum()},t=a.readVarIntNum();t>=0&&(e.lockingScript=e7(a.read(t)));let r=a.readVarIntNum();r>=0&&(e.customInstructions=ti(a.read(r)));let i=a.readVarIntNum();if(-1!==i){let t=[];for(let e=0;e<i;e++){let e=a.readVarIntNum();t.push(ti(a.read(e)))}e.tags=t}let n=a.readVarIntNum();if(-1!==n){let t=[];for(let e=0;e<n;e++){let e=a.readVarIntNum();t.push(ti(a.read(e)))}e.labels=t}c.push(e)}return{totalOutputs:s,BEEF:r,outputs:c}}async relinquishOutput(e,t){let r=new tu,i=e9(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 tu,[r,i]=e.split(".");return t.write(e9(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}readOutpoint(e){let t=e7(e.read(32)),r=e.readVarIntNum();return`${t}.${r}`}async getPublicKey(e,t){let r=new tu;return r.writeUInt8(+!!e.identityKey),e.identityKey?r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)):(r.write(this.encodeKeyRelatedParams(e.protocolID??=[h.Silent,"default"],e.keyID??="",e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?r.writeInt8(+!!e.forSelf):r.writeInt8(-1)),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{publicKey:e7(await this.transmit("getPublicKey",t,r.toArray()))}}async revealCounterpartyKeyLinkage(e,t){let r=new tu;r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),r.write(e9(e.counterparty,"hex")),r.write(e9(e.verifier,"hex"));let i=new td(await this.transmit("revealCounterpartyKeyLinkage",t,r.toArray())),n=e7(i.read(33)),a=e7(i.read(33)),s=e7(i.read(33)),o=i.readVarIntNum(),c=ti(i.read(o)),l=i.readVarIntNum(),h=i.read(l),u=i.readVarIntNum();return{prover:n,verifier:a,counterparty:s,revelationTime:c,encryptedLinkage:h,encryptedLinkageProof:i.read(u)}}async revealSpecificKeyLinkage(e,t){let r=new tu;r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.write(e9(e.verifier,"hex"));let i=new td(await this.transmit("revealSpecificKeyLinkage",t,r.toArray())),n=e7(i.read(33)),a=e7(i.read(33)),s=e7(i.read(33)),o=i.readUInt8(),c=i.readVarIntNum(),l=ti(i.read(c)),h=i.readVarIntNum(),u=ti(i.read(h)),d=i.readVarIntNum(),f=i.read(d),p=i.readVarIntNum();return{prover:n,verifier:a,counterparty:s,protocolID:[o,l],keyID:u,encryptedLinkage:f,encryptedLinkageProof:i.read(p),proofType:i.readUInt8()}}async encrypt(e,t){let r=new tu;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 tu;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 tu;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 tu;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 tu;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 tu;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,n){let a=new tu;a.writeUInt8(e[0]);let s=e9(e[1],"utf8");a.writeVarIntNum(s.length),a.write(s);let o=e9(t,"utf8");return a.writeVarIntNum(o.length),a.write(o),"string"!=typeof r?a.writeUInt8(0):"self"===r?a.writeUInt8(11):"anyone"===r?a.writeUInt8(12):a.write(e9(r,"hex")),a.write(this.encodePrivilegedParams(i,n)),a.toArray()}async acquireCertificate(e,t){let r=new tu;r.write(e9(e.type,"base64")),r.write(e9(e.certifier,"hex"));let i=Object.entries(e.fields);for(let[e,t]of(r.writeVarIntNum(i.length),i)){let i=e9(e,"utf8"),n=e9(t,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(n.length),r.write(n)}if(r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),r.writeUInt8("direct"===e.acquisitionProtocol?1:2),"direct"===e.acquisitionProtocol){r.write(e9(e.serialNumber,"base64")),r.write(this.encodeOutpoint(e.revocationOutpoint??""));let t=e9(e.signature,"hex");r.writeVarIntNum(t.length),r.write(t);let i="certifier"!==e.keyringRevealer?e9(e.keyringRevealer,"hex"):[11];r.write(i);let n=Object.keys(e.keyringForSubject??{});r.writeVarIntNum(n.length);for(let t=0;t<n.length;t++){let i=e9(n[t],"utf8");r.writeVarIntNum(i.length),r.write(i);let a=e9(e.keyringForSubject?.[n[t]],"base64");r.writeVarIntNum(a.length),r.write(a)}}else{let t=e9(e.certifierUrl,"utf8");r.writeVarIntNum(t.length),r.write(t)}let n=await this.transmit("acquireCertificate",t,r.toArray()),a=iT.fromBinary(n);return{...a,signature:a.signature}}encodePrivilegedParams(e,t){let r=new tu;if("boolean"==typeof e?r.writeInt8(+!!e):r.writeInt8(-1),"string"==typeof t){let e=e9(t,"utf8");r.writeInt8(e.length),r.write(e)}else r.writeInt8(-1);return r.toArray()}async listCertificates(e,t){let r=new tu;r.writeVarIntNum(e.certifiers.length);for(let t=0;t<e.certifiers.length;t++)r.write(e9(e.certifiers[t],"hex"));r.writeVarIntNum(e.types.length);for(let t=0;t<e.types.length;t++)r.write(e9(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 td(await this.transmit("listCertificates",t,r.toArray())),n=i.readVarIntNum(),a=[];for(let e=0;e<n;e++){let e,t=i.readVarIntNum(),r=i.read(t),n=iT.fromBinary(r),s={};if(1===i.readInt8()){let e=i.readVarIntNum();for(let t=0;t<e;t++){let e=i.readVarIntNum(),t=ti(i.read(e)),r=i.readVarIntNum();s[t]=ta(i.read(r))}}let o=i.readVarIntNum();o>0&&(e=ti(i.read(o))),a.push({...n,signature:n.signature,keyring:s,verifier:e})}return{totalCertificates:n,certificates:a}}async proveCertificate(e,t){let r=new tu,i=e9(e.certificate.type,"base64");r.write(i);let n=e9(e.certificate.subject,"hex");r.write(n);let a=e9(e.certificate.serialNumber,"base64");r.write(a);let s=e9(e.certificate.certifier,"hex");r.write(s);let o=this.encodeOutpoint(e.certificate.revocationOutpoint??"");r.write(o);let c=e9(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=e9(e,"utf8"),n=e9(t,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(n.length),r.write(n)}for(let t of(r.writeVarIntNum(e.fieldsToReveal.length),e.fieldsToReveal)){let e=e9(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}r.write(e9(e.verifier,"hex")),r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let h=new td(await this.transmit("proveCertificate",t,r.toArray())),u=h.readVarIntNum(),d={};for(let e=0;e<u;e++){let e=h.readVarIntNum(),t=ti(h.read(e)),r=h.readVarIntNum();d[t]=ta(h.read(r))}return{keyringForVerifier:d}}async relinquishCertificate(e,t){let r=new tu,i=e9(e.type,"base64");r.write(i);let n=e9(e.serialNumber,"base64");r.write(n);let a=e9(e.certifier,"hex");return r.write(a),await this.transmit("relinquishCertificate",t,r.toArray()),{relinquished:!0}}parseDiscoveryResult(e){let t=new td(e),r=t.readVarIntNum(),i=[];for(let e=0;e<r;e++){let e=t.readVarIntNum(),r=t.read(e),n=iT.fromBinary(r),a=t.readVarIntNum(),s=ti(t.read(a)),o=t.readVarIntNum(),c=ti(t.read(o)),l=t.readVarIntNum(),h=ti(t.read(l)),u=t.readUInt8(),d={},f=t.readVarIntNum();for(let e=0;e<f;e++){let e=t.readVarIntNum(),r=ti(t.read(e)),i=t.readVarIntNum();d[r]=t.read(i)}let p={},g=t.readVarIntNum();for(let e=0;e<g;e++){let e=t.readVarIntNum(),r=ti(t.read(e)),i=t.readVarIntNum();p[r]=ti(t.read(i))}i.push({...n,signature:n.signature,certifierInfo:{iconUrl:c,name:s,description:h,trust:u},publiclyRevealedKeyring:d,decryptedFields:p})}return{totalCertificates:r,certificates:i}}async discoverByIdentityKey(e,t){let r=new tu;r.write(e9(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 tu,i=Object.keys(e.attributes);r.writeVarIntNum(i.length);for(let t=0;t<i.length;t++)r.writeVarIntNum(i[t].length),r.write(e9(i[t],"utf8")),r.writeVarIntNum(e.attributes[i[t]].length),r.write(e9(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 n=await this.transmit("discoverByAttributes",t,r.toArray());return this.parseDiscoveryResult(n)}async isAuthenticated(e,t){return{authenticated:1===(await this.transmit("isAuthenticated",t))[0]}}async waitForAuthentication(e,t){return await this.transmit("waitForAuthentication",t),{authenticated:!0}}async getHeight(e,t){return{height:new td(await this.transmit("getHeight",t)).readVarIntNum()}}async getHeaderForHeight(e,t){let r=new tu;return r.writeVarIntNum(e.height),{header:e7(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:ti(await this.transmit("getVersion",t))}}}class iV{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 td(e),i=r.readUInt8(),n=iC[i];if(void 0===n||""===n)throw Error(`Invalid call code: ${i}`);let a=r.readUInt8();a>0&&(t=ti(r.read(a)));let s=r.read(),o=await fetch(`${this.baseUrl}/${n}`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Origin:t??""},body:new Uint8Array(s)});return Array.from(new Uint8Array(await o.arrayBuffer()))}}class iB extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(e,t,r,i,n){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=e,this.sendWithResults=t,this.txid=r,this.tx=i,this.noSendChange=n,this.code=5,this.name=this.constructor.name}}let iD=iB;class iU extends Error{parameter;code;isError=!0;constructor(e,t){super(`The ${e} parameter must be ${t??"valid."}`),this.parameter=e,this.code=6,this.name=this.constructor.name}}let iF=iU,iL=class extends Error{totalSatoshisNeeded;moreSatoshisNeeded;code;isError=!0;constructor(e,t){super(`Insufficient funds in the available inputs to cover the cost of the required outputs and the transaction fee (${t} more satoshis are needed, for a total of ${e}), plus whatever would be required in order to pay the fee to unlock and spend the outputs used to provide the additional satoshis.`),this.totalSatoshisNeeded=e,this.moreSatoshisNeeded=t,this.code=7,this.name=this.constructor.name}};class iK{baseUrl;httpClient;originator;api;constructor(e,t="http://localhost:3321",r=fetch){this.baseUrl=t,this.originator=e,this.httpClient=r;const i="undefined"!=typeof window&&"undefined"!=typeof document&&window?.origin!=="file://";this.api=async(e,t)=>{let n=!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!==n||console.error("Originator is required in Node.js environments");let a=await await r(`${this.baseUrl}/${e}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...n?{Origin:n}:{},...n?{Originator:n}:{}},body:JSON.stringify(t)}),s=await a.json();if(!a.ok){if(400===a.status&&s.isError){let e;switch(s.code){case 5:e=new iB(s.reviewActionResults,s.sendWithResults,s.txid,s.tx,s.noSendChange);break;case 6:(e=new iU(s.parameter)).message=s.message;break;case 7:e=new iL(s.totalSatoshisNeeded,s.moreSatoshisNeeded)}if(e)throw e}throw Error(JSON.stringify({call:e,args:t,message:s.message??`HTTP Client error ${a.status}`}))}return s}}async createAction(e){return await this.api("createAction",e)}async signAction(e){return await this.api("signAction",e)}async abortAction(e){return await this.api("abortAction",e)}async listActions(e){return await this.api("listActions",e)}async internalizeAction(e){return await this.api("internalizeAction",e)}async listOutputs(e){return await this.api("listOutputs",e)}async relinquishOutput(e){return await this.api("relinquishOutput",e)}async getPublicKey(e){return await this.api("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.api("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.api("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.api("encrypt",e)}async decrypt(e){return await this.api("decrypt",e)}async createHmac(e){return await this.api("createHmac",e)}async verifyHmac(e){return await this.api("verifyHmac",e)}async createSignature(e){return await this.api("createSignature",e)}async verifySignature(e){return await this.api("verifySignature",e)}async acquireCertificate(e){return await this.api("acquireCertificate",e)}async listCertificates(e){return await this.api("listCertificates",e)}async proveCertificate(e){return await this.api("proveCertificate",e)}async relinquishCertificate(e){return await this.api("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.api("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.api("discoverByAttributes",e)}async isAuthenticated(e){return await this.api("isAuthenticated",e)}async waitForAuthentication(e){return await this.api("waitForAuthentication",e)}async getHeight(e){return await this.api("getHeight",e)}async getHeaderForHeight(e){return await this.api("getHeaderForHeight",e)}async getNetwork(e){return await this.api("getNetwork",e)}async getVersion(e){return await this.api("getVersion",e)}}class iH{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 n=ta(tJ(12)),a=e=>{let t=JSON.parse(e.data);"CWI"===t.type&&t.id===n&&!0!==t.isInvocation&&("function"==typeof window.removeEventListener&&window.removeEventListener("message",a),"error"===t.status?i(new iO(t.description,t.code)):r(t.result))};window.addEventListener("message",a),window.ReactNativeWebView.postMessage(JSON.stringify({type:"CWI",isInvocation:!0,id:n,call:e,args:t}))})}async createAction(e){return await this.invoke("createAction",e)}async signAction(e){return await this.invoke("signAction",e)}async abortAction(e){return await this.invoke("abortAction",e)}async listActions(e){return await this.invoke("listActions",e)}async internalizeAction(e){return await this.invoke("internalizeAction",e)}async listOutputs(e){return await this.invoke("listOutputs",e)}async relinquishOutput(e){return await this.invoke("relinquishOutput",e)}async getPublicKey(e){return await this.invoke("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.invoke("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.invoke("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.invoke("encrypt",e)}async decrypt(e){return await this.invoke("decrypt",e)}async createHmac(e){return await this.invoke("createHmac",e)}async verifyHmac(e){return await this.invoke("verifyHmac",e)}async createSignature(e){return await this.invoke("createSignature",e)}async verifySignature(e){return await this.invoke("verifySignature",e)}async acquireCertificate(e){return await this.invoke("acquireCertificate",e)}async listCertificates(e){return await this.invoke("listCertificates",e)}async proveCertificate(e){return await this.invoke("proveCertificate",e)}async relinquishCertificate(e){return await this.invoke("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.invoke("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.invoke("discoverByAttributes",e)}async isAuthenticated(e){return await this.invoke("isAuthenticated",e)}async waitForAuthentication(e){return await this.invoke("waitForAuthentication",e)}async getHeight(e){return await this.invoke("getHeight",e)}async getHeaderForHeight(e){return await this.invoke("getHeaderForHeight",e)}async getNetwork(e){return await this.invoke("getNetwork",e)}async getVersion(e){return await this.invoke("getVersion",e)}}function iq(e){let[t,r]=e.split(".");return{txid:t,vout:Number(r)}}function iM(e){return e??!1}function i$(e,t,r,i){if(void 0!==e)return iG(e,t,r,i)}function iz(e,t,r){if(void 0===e||!Number.isInteger(e)||e<0||e>21e14)throw new iF(t,"a valid number of satoshis");if(void 0!==r&&e<r)throw new iF(t,`at least ${r} satoshis.`);return e}function iW(e,t,r,i){if(void 0!==e)return ij(e,t,void 0,r,i)}function ij(e,t,r,i,n){if(void 0===e){if(void 0!==r)return r;throw new iF(t,"a valid integer")}if(!Number.isInteger(e))throw new iF(t,"an integer");if(e=Number(e),void 0!==i&&e<i)throw new iF(t,`at least ${i} length.`);if(void 0!==n&&e>n)throw new iF(t,`no more than ${n} length.`);return e}function iX(e,t){return ij(e,t,0,0)}function iG(e,t,r,i){let n=e9(e,"utf8").length;if(void 0!==r&&n<r)throw new iF(t,`at least ${r} length.`);if(void 0!==i&&n>i)throw new iF(t,`no more than ${i} length.`);return e}function iY(e){return iQ(e,"basket",1,300)}function iJ(e){return iQ(e,"label",1,300)}function iZ(e){return iQ(e,"tag",1,300)}function iQ(e,t,r,i){let n=e9(e=e.trim().toLowerCase(),"utf8").length;if(void 0!==r&&n<r)throw new iF(t,`at least ${r} length.`);if(void 0!==i&&n>i)throw new iF(t,`no more than ${i} length.`);return e}function i0(e,t,r,i){if(void 0!==e)return i1(e,t,r,i)}function i1(e,t,r,i){if(0===(e=e.trim()).length)throw new iF(t,"valid base64 string");let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if((!(i>=65)||!(i<=90))&&(!(i>=97)||!(i<=122))&&(!(i>=48)||!(i<=57))&&43!==i&&47!==i){if(61===i){if(r<e.length-2)throw new iF(t,"valid base64 string");n++;continue}throw new iF(t,"valid base64 string")}}if(n>2||n>0&&e.length%4!=0)throw new iF(t,"valid base64 string");let a=e.length%4;if(0!==a&&a!==4-n)throw new iF(t,"valid base64 string");let s=Math.floor(3*(e.length-n)/4);if(void 0!==r&&s<r)throw new iF(t,`at least ${r} bytes`);if(void 0!==i&&s>i)throw new iF(t,`no more than ${i} bytes`);return e}function i2(e,t,r,i){if(void 0!==e)return i8(e,t,r,i)}function i8(e,t,r,i){if((e=e.trim().toLowerCase()).length%2==1)throw new iF(t,`even length, not ${e.length}.`);if(!/^[0-9A-Fa-f]+$/.test(e))throw new iF(t,"hexadecimal string.");if(void 0!==r&&e.length<r)throw new iF(t,`at least ${r} length.`);if(void 0!==i&&e.length>i)throw new iF(t,`no more than ${i} length.`);return e}function i3(e){return(e=e.trim()).length%2!=1&&!!/^[0-9A-Fa-f]+$/.test(e)}function i6(e){if(void 0===e.unlockingScript&&void 0===e.unlockingScriptLength)throw new iF("unlockingScript, unlockingScriptLength","at least one valid value.");let t=i2(e.unlockingScript,"unlockingScript"),r=e.unlockingScriptLength??(null!=t?t.length/2:0);if(t&&r!==t.length/2)throw new iF("unlockingScriptLength","length unlockingScript if both valid.");return{outpoint:iq(e.outpoint),inputDescription:iG(e.inputDescription,"inputDescription",5,2e3),unlockingScript:t,unlockingScriptLength:r,sequenceNumber:e.sequenceNumber??0xffffffff}}function i4(e){return{lockingScript:i8(e.lockingScript,"lockingScript"),satoshis:iz(e.satoshis,"satoshis"),outputDescription:iG(e.outputDescription,"outputDescription",5,2e3),basket:function(e){if(void 0!==e)return iY(e)}(e.basket),customInstructions:e.customInstructions,tags:(e.tags??[]).map(e=>iZ(e))}}function i5(e){let t=null!=e?e:{};return{signAndProcess:t.signAndProcess??!0,acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,knownTxids:t.knownTxids??[],returnTXIDOnly:iM(t.returnTXIDOnly),noSend:iM(t.noSend),noSendChange:(t.noSendChange??[]).map(e=>iq(e)),sendWith:t.sendWith??[],randomizeOutputs:t.randomizeOutputs??!0}}function i7(e,t){let r={description:iG(e.description,"description",5,2e3),inputBEEF:e.inputBEEF,inputs:(e.inputs??[]).map(e=>i6(e)),outputs:(e.outputs??[]).map(e=>i4(e)),lockTime:e.lockTime??0,version:e.version??1,labels:e.labels?.map(e=>iJ(e))??[],options:i5(e.options),logger:t,isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!1,isRemixChange:!1,isSignAction:!1,randomVals:void 0,includeAllSourceTransactions:!1,isTestWerrReviewActions:!1};return r.isTestWerrReviewActions=r.labels.includes(nv),r.isSendWith=r.options.sendWith.length>0,r.isRemixChange=!r.isSendWith&&0===r.inputs.length&&0===r.outputs.length,r.isNewTx=r.isRemixChange||r.inputs.length>0||r.outputs.length>0,r.isSignAction=r.isNewTx&&(!r.options.signAndProcess||r.inputs.some(e=>void 0===e.unlockingScript)),r.isDelayed=r.options.acceptDelayedBroadcast,r.isNoSend=r.options.noSend,r}function i9(e){let t=null!=e?e:{};return{acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,returnTXIDOnly:iM(t.returnTXIDOnly),noSend:iM(t.noSend),sendWith:t.sendWith??[]}}function ne(e){let t={spends:e.spends,reference:e.reference,options:i9(e.options),isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!0,isRemixChange:!1,isTestWerrReviewActions:!1};return t.isSendWith=t.options.sendWith.length>0,t.isDelayed=t.options.acceptDelayedBroadcast,t.isNoSend=t.options.noSend,t}function nt(e){return{reference:i1(e.reference,"reference")}}function nr(e){if(void 0!==e)return{derivationPrefix:i1(e.derivationPrefix,"derivationPrefix"),derivationSuffix:i1(e.derivationSuffix,"derivationSuffix"),senderIdentityKey:i8(e.senderIdentityKey,"senderIdentityKey")}}function ni(e){if(void 0!==e)return{basket:iY(e.basket),customInstructions:i$(e.customInstructions,"customInstructions",0,1e3),tags:(e.tags??[]).map(e=>iZ(e))}}function nn(e){if("basket insertion"!==e.protocol&&"wallet payment"!==e.protocol)throw new iF("protocol","'basket insertion' or 'wallet payment'");return{outputIndex:iX(e.outputIndex,"outputIndex"),protocol:e.protocol,paymentRemittance:nr(e.paymentRemittance),insertionRemittance:ni(e.insertionRemittance)}}function na(e){if(void 0!==e){for(let t of(iG(e=e.trim().toLowerCase(),"originator",1,250),e.split(".")))iG(t,"originator part",1,63);return e}}function ns(e){let t={tx:e.tx,outputs:e.outputs.map(e=>nn(e)),description:iG(e.description,"description",5,2e3),labels:(null!=e.labels?e.labels:[]).map(e=>iJ(e)),seekPermission:e.seekPermission??!0};try{if(rZ.fromBinary(t.tx).txs.length<1)throw new iF("tx","at least one transaction to internalize an output from")}catch{throw new iF("tx","valid with at least one transaction to internalize an output from")}if(t.outputs.length<1)throw new iF("outputs","at least one output to internalize from the transaction");return t}function no(e,t){if(void 0!==e)return nc(e,t)}function nc(e,t){let r=e.split(".");if(2!==r.length||!Number.isInteger(Number(r[1])))throw new iF(t,"txid as hex string and numeric output index joined with '.'");let i=i8(r[0],`${t} txid`,void 0,64),n=iX(Number(r[1]),`${t} vout`);return`${i}.${n}`}function nl(e){return{basket:iY(e.basket),output:nc(e.output,"output")}}function nh(e){return{type:i1(e.type,"type"),serialNumber:i1(e.serialNumber,"serialNumber"),certifier:i8(e.certifier,"certifier")}}function nu(e){return{certifiers:e.certifiers.map(e=>i8(e.trim(),"certifiers"))??[],types:e.types.map(e=>i1(e.trim(),"types"))??[],limit:ij(e.limit,"limit",10,1,1e4),offset:iX(e.offset??0,"offset"),privileged:iM(e.privileged),privilegedReason:i$(e.privilegedReason,"privilegedReason",5,50),partial:void 0}}function nd(e){for(let t of Object.keys(e))iG(t,"field name",1,50);return e}function nf(e){if("issuance"!==e.acquisitionProtocol)throw Error("Only acquire certificate via issuance requests allowed here.");if(e.serialNumber)throw new iF("serialNumber",'valid when acquisitionProtocol is "direct"');if(e.signature)throw new iF("signature",'valid when acquisitionProtocol is "direct"');if(e.revocationOutpoint)throw new iF("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(e.keyringRevealer)throw new iF("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null!=e.keyringForSubject)throw new iF("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(!e.certifierUrl)throw new iF("certifierUrl",'valid when acquisitionProtocol is "issuance"');if(e.privileged&&!e.privilegedReason)throw new iF("privilegedReason","valid when 'privileged' is true ");return{type:i1(e.type,"type"),certifier:i8(e.certifier,"certifier"),certifierUrl:e.certifierUrl,fields:nd(e.fields),privileged:iM(e.privileged),privilegedReason:i$(e.privilegedReason,"privilegedReason",5,50),subject:""}}function np(e){var t;if("direct"!==e.acquisitionProtocol)throw Error("Only acquire direct certificate requests allowed here.");if(!e.serialNumber)throw new iF("serialNumber",'valid when acquisitionProtocol is "direct"');if(!e.signature)throw new iF("signature",'valid when acquisitionProtocol is "direct"');if(!e.revocationOutpoint)throw new iF("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(!e.keyringRevealer)throw new iF("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null==e.keyringForSubject)throw new iF("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(e.privileged&&!e.privilegedReason)throw new iF("privilegedReason","valid when 'privileged' is true ");return{type:i1(e.type,"type"),serialNumber:i1(e.serialNumber,"serialNumber"),certifier:i8(e.certifier,"certifier"),revocationOutpoint:nc(e.revocationOutpoint,"revocationOutpoint"),fields:nd(e.fields),signature:i8(e.signature,"signature"),keyringRevealer:(t=e.keyringRevealer,"certifier"===t?t:i8(t,"keyringRevealer")),keyringForSubject:function(e,t){for(let r of Object.keys(e))iG(r,`${t} field name`,1,50),i1(e[r],`${t} field value`);return e}(e.keyringForSubject,"keyringForSubject"),privileged:iM(e.privileged),privilegedReason:i$(e.privilegedReason,"privilegedReason",5,50),subject:""}}function ng(e){if(e.privileged&&!e.privilegedReason)throw new iF("privilegedReason","valid when 'privileged' is true ");return{type:i0(e.certificate.type,"certificate.type"),serialNumber:i0(e.certificate.serialNumber,"certificate.serialNumber"),certifier:i2(e.certificate.certifier,"certificate.certifier"),subject:i2(e.certificate.subject,"certificate.subject"),revocationOutpoint:no(e.certificate.revocationOutpoint,"certificate.revocationOutpoint"),signature:i2(e.certificate.signature,"certificate.signature"),fieldsToReveal:(e.fieldsToReveal??[]).map(e=>iG(e,`fieldsToReveal ${e}`,1,50)),verifier:i8(e.verifier,"verifier"),privileged:iM(e.privileged),privilegedReason:i$(e.privilegedReason,"privilegedReason",5,50)}}function nb(e){return{identityKey:i8(e.identityKey,"identityKey",66,66),limit:ij(e.limit,"limit",10,1,1e4),offset:iX(e.offset??0,"offset"),seekPermission:iM(e.seekPermission)}}function ny(e){return{attributes:function(e){for(let t of Object.keys(e))iG(t,`field name ${t}`,1,50);return e}(e.attributes),limit:ij(e.limit,"limit",10,1,1e4),offset:iX(e.offset??0,"offset"),seekPermission:iM(e.seekPermission)}}function nm(e){let t;if(void 0===e.tagQueryMode||"any"===e.tagQueryMode)t="any";else if("all"===e.tagQueryMode)t="all";else throw new iF("tagQueryMode","undefined, 'any', or 'all'");return{basket:iG(e.basket,"basket",1,300),tags:(null!=e.tags?e.tags:[]).map(e=>iG(e,"tag",1,300)),tagQueryMode:t,includeLockingScripts:"locking scripts"===e.include,includeTransactions:"entire transactions"===e.include,includeCustomInstructions:iM(e.includeCustomInstructions),includeTags:iM(e.includeTags),includeLabels:iM(e.includeLabels),limit:ij(e.limit,"limit",10,1,1e4),offset:ij(e.offset,"offset",0,void 0,void 0),seekPermission:e.seekPermission??!0,knownTxids:[]}}function nw(e){let t;if(void 0===e.labelQueryMode||"any"===e.labelQueryMode)t="any";else if("all"===e.labelQueryMode)t="all";else throw new iF("labelQueryMode","undefined, 'any', or 'all'");return{labels:(null!=e.labels?e.labels:[]).map(e=>iJ(e)),labelQueryMode:t,includeLabels:iM(e.includeLabels),includeInputs:iM(e.includeInputs),includeInputSourceLockingScripts:iM(e.includeInputSourceLockingScripts),includeInputUnlockingScripts:iM(e.includeInputUnlockingScripts),includeOutputs:iM(e.includeOutputs),includeOutputLockingScripts:iM(e.includeOutputLockingScripts),limit:ij(e.limit,"limit",10,1,1e4),offset:ij(e.offset,"offset",0,0),seekPermission:e.seekPermission??!0}}let nv="a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a";class nI{substrate;originator;constructor(e="auto",t){"Cicada"===e&&(e=new iR(new iV(t))),"window.CWI"===e&&(e=new iN),"XDM"===e&&(e=new i_),"json-api"===e&&(e=new iK(t)),"react-native"===e&&(e=new iH(t)),"secure-json-api"===e&&(e=new iK(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 iN),e(()=>new iK(this.originator,"https://localhost:2121")),e(()=>new iK(this.originator)),e(()=>new iH(this.originator)),e(()=>new iR(new iV(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 i_,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 i7(e),await this.connectToSubstrate(),await this.substrate.createAction(e,this.originator)}async signAction(e){return ne(e),await this.connectToSubstrate(),await this.substrate.signAction(e,this.originator)}async abortAction(e){return nt(e),await this.connectToSubstrate(),await this.substrate.abortAction(e,this.originator)}async listActions(e){return nw(e),await this.connectToSubstrate(),await this.substrate.listActions(e,this.originator)}async internalizeAction(e){return ns(e),await this.connectToSubstrate(),await this.substrate.internalizeAction(e,this.originator)}async listOutputs(e){return nm(e),await this.connectToSubstrate(),await this.substrate.listOutputs(e,this.originator)}async relinquishOutput(e){return nl(e),await this.connectToSubstrate(),await this.substrate.relinquishOutput(e,this.originator)}async getPublicKey(e){return await this.connectToSubstrate(),await this.substrate.getPublicKey(e,this.originator)}async revealCounterpartyKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealCounterpartyKeyLinkage(e,this.originator)}async revealSpecificKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealSpecificKeyLinkage(e,this.originator)}async encrypt(e){return await this.connectToSubstrate(),await this.substrate.encrypt(e,this.originator)}async decrypt(e){return await this.connectToSubstrate(),await this.substrate.decrypt(e,this.originator)}async createHmac(e){return await this.connectToSubstrate(),await this.substrate.createHmac(e,this.originator)}async verifyHmac(e){return await this.connectToSubstrate(),await this.substrate.verifyHmac(e,this.originator)}async createSignature(e){return await this.connectToSubstrate(),await this.substrate.createSignature(e,this.originator)}async verifySignature(e){return await this.connectToSubstrate(),await this.substrate.verifySignature(e,this.originator)}async acquireCertificate(e){if("direct"===e.acquisitionProtocol)np(e);else if("issuance"===e.acquisitionProtocol)nf(e);else throw new iU("acquisitionProtocol",`valid. ${String(e.acquisitionProtocol)} is unrecognized.`);return await this.connectToSubstrate(),await this.substrate.acquireCertificate(e,this.originator)}async listCertificates(e){return nu(e),await this.connectToSubstrate(),await this.substrate.listCertificates(e,this.originator)}async proveCertificate(e){return ng(e),await this.connectToSubstrate(),await this.substrate.proveCertificate(e,this.originator)}async relinquishCertificate(e){return nh(e),await this.connectToSubstrate(),await this.substrate.relinquishCertificate(e,this.originator)}async discoverByIdentityKey(e){return nb(e),await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(e,this.originator)}async discoverByAttributes(e){return ny(e),await this.connectToSubstrate(),await this.substrate.discoverByAttributes(e,this.originator)}async isAuthenticated(e={}){return await this.connectToSubstrate(),await this.substrate.isAuthenticated(e,this.originator)}async waitForAuthentication(e={}){return await this.connectToSubstrate(),await this.substrate.waitForAuthentication(e,this.originator)}async getHeight(e={}){return await this.connectToSubstrate(),await this.substrate.getHeight(e,this.originator)}async getHeaderForHeight(e){return await this.connectToSubstrate(),await this.substrate.getHeaderForHeight(e,this.originator)}async getNetwork(e={}){return await this.connectToSubstrate(),await this.substrate.getNetwork(e,this.originator)}async getVersion(e={}){return await this.connectToSubstrate(),await this.substrate.getVersion(e,this.originator)}}class nk{wallet;constructor(e){this.wallet=e}decodeOutpoint(e){let t=e7(e.read(32)),r=e.readVarIntNum();return`${t}.${r}`}encodeOutpoint(e){let t=new tu,[r,i]=e.split(".");return t.write(e9(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}async transmitToWallet(e){let t=new td(e);try{let e=t.readUInt8(),r=iC[e];if(void 0===r||""===r)throw Error(`Invalid call code: ${e}`);let i=t.readUInt8(),n=t.read(i),a=ti(n);switch(r){case"createAction":{let e={},r=t.readVarIntNum(),i=t.read(r);e.description=ti(i);let n=t.readVarIntNum();n>=0?e.inputBEEF=t.read(n):e.inputBEEF=void 0;let s=t.readVarIntNum();if(s>=0){e.inputs=[];for(let 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=e7(e)}else r.unlockingScript=void 0,r.unlockingScriptLength=t.readVarIntNum();let n=t.readVarIntNum(),a=t.read(n);r.inputDescription=ti(a);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(),n=t.read(i);r.lockingScript=e7(n),r.satoshis=t.readVarIntNum();let a=t.readVarIntNum(),s=t.read(a);r.outputDescription=ti(s);let o=t.readVarIntNum();if(o>=0){let e=t.read(o);r.basket=ti(e)}else r.basket=void 0;let c=t.readVarIntNum();if(c>=0){let e=t.read(c);r.customInstructions=ti(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),n=ti(i);r.tags.push(n)}}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),n=ti(i);e.labels.push(n)}}else e.labels=void 0;let u=t.readInt8();if(1===u){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 n=t.readInt8();-1===n?e.options.trustSelf=void 0:1===n&&(e.options.trustSelf="known");let a=t.readVarIntNum();if(a>=0){e.options.knownTxids=[];for(let r=0;r<a;r++){let r=t.read(32),i=e7(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=e7(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 d=await this.wallet.createAction(e,a),f=new tu;if(null!=d.txid&&""!==d.txid?(f.writeInt8(1),f.write(e9(d.txid,"hex"))):f.writeInt8(0),null!=d.tx?(f.writeInt8(1),f.writeVarIntNum(d.tx.length),f.write(d.tx)):f.writeInt8(0),null!=d.noSendChange)for(let e of(f.writeVarIntNum(d.noSendChange.length),d.noSendChange))f.write(this.encodeOutpoint(e));else f.writeVarIntNum(-1);if(null!=d.sendWithResults)for(let e of(f.writeVarIntNum(d.sendWithResults.length),d.sendWithResults)){let t;f.write(e9(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!=d.signableTransaction){f.writeInt8(1),f.writeVarIntNum(d.signableTransaction.tx.length),f.write(d.signableTransaction.tx);let e=e9(d.signableTransaction.reference,"base64");f.writeVarIntNum(e.length),f.write(e)}else f.writeInt8(0);let p=new tu;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={},n=t.readVarIntNum(),a=t.read(n);i.unlockingScript=e7(a);let s=t.readVarIntNum();s>=0?i.sequenceNumber=s:i.sequenceNumber=void 0,e.spends[r]=i}let i=t.readVarIntNum(),n=t.read(i);e.reference=ta(n);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 n=t.readInt8();-1===n?e.options.noSend=void 0:e.options.noSend=1===n;let a=t.readVarIntNum();if(a>=0){e.options.sendWith=[];for(let r=0;r<a;r++){let r=t.read(32),i=e7(r);e.options.sendWith.push(i)}}else e.options.sendWith=void 0}else e.options=void 0;let o=await this.wallet.signAction(e,a),c=new tu;if(null!=o.txid&&""!==o.txid?(c.writeInt8(1),c.write(e9(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(e9(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 tu;return l.writeUInt8(0),l.write(c.toArray()),l.toArray()}case"abortAction":{let e=t.read(),r=ta(e);await this.wallet.abortAction({reference:r},a);let i=new tu;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(ti(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 n=t.readVarIntNum();n>=0?e.limit=n:e.limit=void 0;let s=t.readVarIntNum();s>=0?e.offset=s:e.offset=void 0;let o=t.readInt8();o>=0?e.seekPermission=1===o:e.seekPermission=void 0;let c=await this.wallet.listActions(e,a),l=new tu;for(let e of(l.writeVarIntNum(c.totalActions),c.actions)){let t;switch(l.write(e9(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=e9(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=e9(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=e9(t.sourceLockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);if(void 0!==t.unlockingScript){let e=e9(t.unlockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);let e=e9(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=e9(t.lockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);l.writeInt8(+!!t.spendable);let e=e9(t.outputDescription,"utf8");if(l.writeVarIntNum(e.length),l.write(e),void 0!==t.basket){let e=e9(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=e9(e,"utf8");l.writeVarIntNum(t.length),l.write(t)}else l.writeVarIntNum(-1);if(void 0!==t.customInstructions){let e=e9(t.customInstructions,"utf8");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1)}else l.writeVarIntNum(-1)}let h=new tu;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=e7(e);let i=t.readVarIntNum(),n=t.read(i);r.paymentRemittance.derivationPrefix=ta(n);let a=t.readVarIntNum(),s=t.read(a);r.paymentRemittance.derivationSuffix=ta(s)}else if(2===i){r.protocol="basket insertion",r.insertionRemittance={};let e=t.readVarIntNum(),i=t.read(e);r.insertionRemittance.basket=ti(i);let n=t.readVarIntNum();if(n>=0){let e=t.read(n);r.insertionRemittance.customInstructions=ti(e)}let a=t.readVarIntNum();if(a>0){r.insertionRemittance.tags=[];for(let e=0;e<a;e++){let e=t.readVarIntNum(),i=t.read(e);r.insertionRemittance.tags.push(ti(i))}}else r.insertionRemittance.tags=[]}e.outputs.push(r)}let n=t.readVarIntNum();if(n>=0){e.labels=[];for(let r=0;r<n;r++){let r=t.readVarIntNum();e.labels.push(ti(t.read(r)))}}let s=t.readVarIntNum();e.description=ti(t.read(s));let o=t.readInt8();o>=0?e.seekPermission=1===o:e.seekPermission=void 0,await this.wallet.internalizeAction(e,a);let c=new tu;return c.writeUInt8(0),c.toArray()}case"listOutputs":{let e={},r=t.readVarIntNum(),i=t.read(r);e.basket=ti(i);let n=t.readVarIntNum();if(n>0){e.tags=[];for(let r=0;r<n;r++){let r=t.readVarIntNum(),i=t.read(r);e.tags.push(ti(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 u=t.readVarIntNum();u>=0?e.limit=u:e.limit=void 0;let d=t.readVarIntNum();d>=0?e.offset=d:e.offset=void 0;let f=t.readInt8();f>=0?e.seekPermission=1===f:e.seekPermission=void 0;let p=await this.wallet.listOutputs(e,a),g=new tu;for(let e of(g.writeVarIntNum(p.totalOutputs),null!=p.BEEF?(g.writeVarIntNum(p.BEEF.length),g.write(p.BEEF)):g.writeVarIntNum(-1),p.outputs)){if(g.write(this.encodeOutpoint(e.outpoint)),g.writeVarIntNum(e.satoshis),void 0!==e.lockingScript){let t=e9(e.lockingScript,"hex");g.writeVarIntNum(t.length),g.write(t)}else g.writeVarIntNum(-1);if(void 0!==e.customInstructions){let t=e9(e.customInstructions,"utf8");g.writeVarIntNum(t.length),g.write(t)}else g.writeVarIntNum(-1);if(void 0!==e.tags)for(let t of(g.writeVarIntNum(e.tags.length),e.tags)){let e=e9(t,"utf8");g.writeVarIntNum(e.length),g.write(e)}else g.writeVarIntNum(-1);if(void 0!==e.labels)for(let t of(g.writeVarIntNum(e.labels.length),e.labels)){let e=e9(t,"utf8");g.writeVarIntNum(e.length),g.write(e)}else g.writeVarIntNum(-1)}let b=new tu;return b.writeUInt8(0),b.write(g.toArray()),b.toArray()}case"relinquishOutput":{let e={},r=t.readVarIntNum(),i=t.read(r);e.basket=ti(i),e.output=this.decodeOutpoint(t),await this.wallet.relinquishOutput(e,a);let n=new tu;return n.writeUInt8(0),n.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=ti(r)}else e.privilegedReason=void 0;let n=t.readInt8();-1===n?e.forSelf=void 0:e.forSelf=1===n}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=ti(r)}else e.privilegedReason=void 0}let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let n=await this.wallet.getPublicKey(e,a),s=new tu;s.writeUInt8(0);let o=e9(n.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 n=await this.wallet.encrypt(e,a),s=new tu;return s.writeUInt8(0),s.write(n.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 n=await this.wallet.decrypt(e,a),s=new tu;return s.writeUInt8(0),s.write(n.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 n=await this.wallet.createHmac(e,a),s=new tu;return s.writeUInt8(0),s.write(n.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,a);let n=new tu;return n.writeUInt8(0),n.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 n=await this.wallet.createSignature(e,a),s=new tu;return s.writeUInt8(0),s.write(n.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 n=t.readUInt8();if(1===n){let r=t.readVarIntNum();e.data=t.read(r)}else 2===n&&(e.hashToDirectlyVerify=t.read(32));let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0,await this.wallet.verifySignature(e,a);let o=new tu;return o.writeUInt8(0),o.toArray()}case"isAuthenticated":{let e=await this.wallet.isAuthenticated({},a),t=new tu;return t.writeUInt8(0),t.writeUInt8(+!!e.authenticated),t.toArray()}case"waitForAuthentication":{await this.wallet.waitForAuthentication({},a);let e=new tu;return e.writeUInt8(0),e.toArray()}case"getHeight":{let e=await this.wallet.getHeight({},a),t=new tu;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,a),i=new tu;i.writeUInt8(0);let n=e9(r.header,"hex");return i.write(n),i.toArray()}case"getNetwork":{let e=await this.wallet.getNetwork({},a),t=new tu;return t.writeUInt8(0),t.writeUInt8(+("mainnet"!==e.network)),t.toArray()}case"getVersion":{let e=await this.wallet.getVersion({},a),t=new tu;t.writeUInt8(0);let r=e9(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=ti(r)}let n=t.read(33);e.counterparty=e7(n);let s=t.read(33);e.verifier=e7(s);let o=await this.wallet.revealCounterpartyKeyLinkage(e,a),c=new tu;c.write(e9(o.prover,"hex")),c.write(e9(o.verifier,"hex")),c.write(e9(o.counterparty,"hex"));let l=e9(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 tu;return h.writeUInt8(0),h.write(c.toArray()),h.toArray()}case"revealSpecificKeyLinkage":{let e=this.decodeKeyRelatedParams(t),r=t.read(33);e.verifier=e7(r);let i=await this.wallet.revealSpecificKeyLinkage(e,a),n=new tu;n.write(e9(i.prover,"hex")),n.write(e9(i.verifier,"hex")),n.write(e9(i.counterparty,"hex")),n.writeUInt8(i.protocolID[0]);let s=e9(i.protocolID[1],"utf8");n.writeVarIntNum(s.length),n.write(s);let o=e9(i.keyID,"utf8");n.writeVarIntNum(o.length),n.write(o),n.writeVarIntNum(i.encryptedLinkage.length),n.write(i.encryptedLinkage),n.writeVarIntNum(i.encryptedLinkageProof.length),n.write(i.encryptedLinkageProof),n.writeUInt8(i.proofType);let c=new tu;return c.writeUInt8(0),c.write(n.toArray()),c.toArray()}case"acquireCertificate":{let e={},r=t.read(32);e.type=ta(r);let i=t.read(33);e.certifier=e7(i);let n=t.readVarIntNum();e.fields={};for(let r=0;r<n;r++){let r=t.readVarIntNum(),i=t.read(r),n=ti(i),a=t.readVarIntNum(),s=t.read(a),o=ti(s);e.fields[n]=o}let s=t.readInt8();-1===s?e.privileged=void 0:e.privileged=1===s;let o=t.readInt8();if(-1===o)e.privilegedReason=void 0;else{let r=t.read(o);e.privilegedReason=ti(r)}let c=t.readUInt8();if(e.acquisitionProtocol=1===c?"direct":"issuance","direct"===e.acquisitionProtocol){let r=t.read(32);e.serialNumber=ta(r),e.revocationOutpoint=this.decodeOutpoint(t);let i=t.readVarIntNum(),n=t.read(i);e.signature=e7(n);let a=t.readUInt8();if(11===a)e.keyringRevealer="certifier";else{let r=[a].concat(t.read(32));e.keyringRevealer=e7(r)}let s=t.readVarIntNum();e.keyringForSubject={};for(let r=0;r<s;r++){let r=t.readVarIntNum(),i=t.read(r),n=ti(i),a=t.readVarIntNum(),s=t.read(a),o=ta(s);e.keyringForSubject[n]=o}}else{let r=t.readVarIntNum(),i=t.read(r);e.certifierUrl=ti(i)}let l=await this.wallet.acquireCertificate(e,a),h=new iT(l.type,l.serialNumber,l.subject,l.certifier,l.revocationOutpoint,l.fields,l.signature).toBinary(),u=new tu;return u.writeUInt8(0),u.write(h),u.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(e7(r))}let i=t.readVarIntNum();e.types=[];for(let r=0;r<i;r++){let r=t.read(32);e.types.push(ta(r))}let n=t.readVarIntNum();n>=0?e.limit=n:e.limit=void 0;let s=t.readVarIntNum();s>=0?e.offset=s:e.offset=void 0;let o=t.readInt8();-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=ti(r)}let l=await this.wallet.listCertificates(e,a),h=new tu;for(let e of(h.writeVarIntNum(l.totalCertificates),l.certificates)){let t=new iT(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=e9(e,"utf8");h.writeVarIntNum(t.length),h.write(t);let i=e9(r,"base64");h.writeVarIntNum(i.length),h.write(i)}}else h.writeInt8(0);let r=e9(e.verifier,"hex");h.writeVarIntNum(r.length),h.write(r)}let u=new tu;return u.writeUInt8(0),u.write(h.toArray()),u.toArray()}case"proveCertificate":{let e={},r={},i=t.read(32);r.type=ta(i);let n=t.read(33);r.subject=e7(n);let s=t.read(32);r.serialNumber=ta(s);let o=t.read(33);r.certifier=e7(o),r.revocationOutpoint=this.decodeOutpoint(t);let c=t.readVarIntNum(),l=t.read(c);r.signature=e7(l);let h=t.readVarIntNum();r.fields={};for(let e=0;e<h;e++){let e=t.readVarIntNum(),i=t.read(e),n=ti(i),a=t.readVarIntNum(),s=t.read(a),o=ti(s);r.fields[n]=o}e.certificate=r;let u=t.readVarIntNum();e.fieldsToReveal=[];for(let r=0;r<u;r++){let r=t.readVarIntNum(),i=t.read(r),n=ti(i);e.fieldsToReveal.push(n)}let d=t.read(33);e.verifier=e7(d);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=ti(r)}let g=await this.wallet.proveCertificate(e,a),b=new tu,y=Object.entries(g.keyringForVerifier);for(let[e,t]of(b.writeVarIntNum(y.length),y)){let r=e9(e,"utf8");b.writeVarIntNum(r.length),b.write(r);let i=e9(t,"base64");b.writeVarIntNum(i.length),b.write(i)}let m=new tu;return m.writeUInt8(0),m.write(b.toArray()),m.toArray()}case"relinquishCertificate":{let e={},r=t.read(32);e.type=ta(r);let i=t.read(32);e.serialNumber=ta(i);let n=t.read(33);e.certifier=e7(n),await this.wallet.relinquishCertificate(e,a);let s=new tu;return s.writeUInt8(0),s.toArray()}case"discoverByIdentityKey":{let e={},r=t.read(33);e.identityKey=e7(r);let i=t.readVarIntNum();i>=0?e.limit=i:e.limit=void 0;let n=t.readVarIntNum();n>=0?e.offset=n:e.offset=void 0;let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0;let o=await this.wallet.discoverByIdentityKey(e,a),c=this.serializeDiscoveryResult(o),l=new tu;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),n=ti(i),a=t.readVarIntNum(),s=t.read(a),o=ti(s);e.attributes[n]=o}let i=t.readVarIntNum();i>=0?e.limit=i:e.limit=void 0;let n=t.readVarIntNum();n>=0?e.offset=n:e.offset=void 0;let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0;let o=await this.wallet.discoverByAttributes(e,a),c=this.serializeDiscoveryResult(o),l=new tu;return l.writeUInt8(0),l.write(c),l.toArray()}default:throw Error(`Method ${r} not implemented`)}}catch(i){let e=new tu;e.writeUInt8("number"==typeof i.code?i.code:1);let t=e9("string"==typeof i.message?i.message:"Unknown error","utf8");e.writeVarIntNum(t.length),e.write(t);let r=e9("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,ti(e.read(r))]}decodeString(e){let t=e.readVarIntNum();return ti(e.read(t))}decodeCounterparty(e){let t=e.readUInt8();return 11===t?"self":12===t?"anyone":0!==t?e7([t,...e.read(32)]):void 0}serializeDiscoveryResult(e){let t=new tu;for(let r of(t.writeVarIntNum(e.totalCertificates),e.certificates)){let e=new iT(r.type,r.serialNumber,r.subject,r.certifier,r.revocationOutpoint,r.fields,r.signature).toBinary();t.writeVarIntNum(e.length),t.write(e);let i=e9(r.certifierInfo.name,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e9(r.certifierInfo.iconUrl,"utf8");t.writeVarIntNum(n.length),t.write(n);let a=e9(r.certifierInfo.description,"utf8");t.writeVarIntNum(a.length),t.write(a),t.writeUInt8(r.certifierInfo.trust);let s=Object.entries(r.publiclyRevealedKeyring);for(let[e,r]of(t.writeVarIntNum(s.length),s)){let i=e9(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e9(r,"base64");t.writeVarIntNum(n.length),t.write(n)}let o=Object.entries(r.decryptedFields);for(let[e,r]of(t.writeVarIntNum(o.length),o)){let i=e9(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e9(r,"utf8");t.writeVarIntNum(n.length),t.write(n)}}return t.toArray()}decodeKeyRelatedParams(e){let t={};t.protocolID=this.decodeProtocolID(e);let r=e.readVarIntNum();t.keyID=ti(e.read(r)),t.counterparty=this.decodeCounterparty(e);let i=e.readInt8();-1===i?t.privileged=void 0:t.privileged=1===i;let n=e.readInt8();return -1===n?t.privilegedReason=void 0:t.privilegedReason=ti(e.read(n)),t}}class nS extends iT{masterKeyring;constructor(e,t,r,i,n,a,s,o){for(const c of(super(e,t,r,i,n,a,o),Object.keys(a)))if(void 0===s[c]||""===s[c])throw Error(`Master keyring must contain a value for every field. Missing or empty key for field: "${c}".`);this.masterKeyring=s}static async createCertificateFields(e,t,r,i,n){let a={},s={};for(let[o,c]of Object.entries(r)){let r=rl.fromRandom(),l=r.encrypt(e9(c,"utf8"));a[o]=ta(l);let{ciphertext:h}=await e.encrypt({plaintext:r.toArray(),...iT.getCertificateFieldEncryptionDetails(o),counterparty:t,privileged:i,privilegedReason:n});s[o]=ta(h)}return{certificateFields:a,masterKeyring:s}}static async createKeyringForVerifier(e,t,r,i,n,a,s,o,c){if(!Array.isArray(n))throw Error("fieldsToReveal must be an array of strings");let l={};for(let h of n){if(void 0===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 n=(await this.decryptField(e,a,h,i[h],t,o,c)).fieldRevelationKey,{ciphertext:u}=await e.encrypt({plaintext:n,...iT.getCertificateFieldEncryptionDetails(h,s),counterparty:r,privileged:o,privilegedReason:c});l[h]=ta(u)}return l}static async issueCertificateForSubject(e,t,r,i,n=async e=>"00".repeat(32),a){let s=a??ta(tJ(32)),{certificateFields:o,masterKeyring:c}=await this.createCertificateFields(e,t,r),l=await n(s),h=new nS(i,s,"self"===t?(await e.getPublicKey({identityKey:!0})).publicKey:t,(await e.getPublicKey({identityKey:!0})).publicKey,l,o,c);return await h.sign(e),h}static async decryptFields(e,t,r,i,n,a){if(null==t||0===Object.keys(t).length)throw Error("A MasterCertificate must have a valid masterKeyring!");try{let s={};for(let o of Object.keys(r))s[o]=(await this.decryptField(e,t,o,r[o],i,n,a)).decryptedFieldValue;return s}catch{throw Error("Failed to decrypt all master certificate fields.")}}static async decryptField(e,t,r,i,n,a,s){if(null==t||0===Object.keys(t).length)throw Error("A MasterCertificate must have a valid masterKeyring!");try{let{plaintext:o}=await e.decrypt({ciphertext:e9(t[r],"base64"),...iT.getCertificateFieldEncryptionDetails(r),counterparty:n,privileged:a,privilegedReason:s}),c=new rl(o).decrypt(e9(i,"base64"));return{fieldRevelationKey:o,decryptedFieldValue:ti(c)}}catch{throw Error("Failed to decrypt certificate field!")}}}class nx extends iT{keyring;decryptedFields;constructor(e,t,r,i,n,a,s,o,c){super(e,t,r,i,n,a,o),this.keyring=s,this.decryptedFields=c}static fromCertificate(e,t){return new nx(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,t,e.signature)}async decryptFields(e,t,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 n={};for(let a in this.keyring){let{plaintext:s}=await e.decrypt({ciphertext:e9(this.keyring[a],"base64"),...iT.getCertificateFieldEncryptionDetails(a,this.serialNumber),counterparty:this.subject,privileged:t,privilegedReason:r},i),o=new rl(s).decrypt(e9(this.fields[a],"base64"));n[a]=ti(o)}return n}catch(e){throw Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(e instanceof Error?e.message:e)}`)}}}class nE extends iP{keyDeriver;constructor(e){if(super(e),e instanceof iS)this.keyDeriver=e;else if("string"==typeof e||e instanceof t1)this.keyDeriver=new ix(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 nP{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 nN(e,t,r="self",i){let n=e9(e,"base64"),a=n.slice(0,16),s=n.slice(16),{valid:o}=await t.verifyHmac({data:a,hmac:s,protocolID:[2,"server hmac"],keyID:ti(a),counterparty:r},i);return o}async function nO(e,t="self",r){let i=tJ(16),{hmac:n}=await e.createHmac({protocolID:[2,"server hmac"],keyID:ti(i),data:i,counterparty:t},r);return ta([...i,...n])}let nA=async(e,t,r,i)=>{let n=await e.listCertificates({certifiers:t.certifiers,types:Object.keys(t.types)},i);return await Promise.all(n.certificates.map(async n=>{let{keyringForVerifier:a}=await e.proveCertificate({certificate:n,fieldsToReveal:t.types[n.type],verifier:r},i);return new nx(n.type,n.serialNumber,n.subject,n.certifier,n.revocationOutpoint,n.fields,a,n.signature)}))},n_=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 n=>{if(n.subject!==t.identityKey)throw Error(`The subject of one of your certificates ("${n.subject}") is not the same as the request sender ("${t.identityKey}").`);let a=new nx(n.type,n.serialNumber,n.subject,n.certifier,n.revocationOutpoint,n.fields,n.keyring,n.signature);if(!await a.verify())throw Error(`The signature for the certificate with serial number ${a.serialNumber} is invalid!`);if(null!=r){let{certifiers:e,types:t}=r;if(!e.includes(a.certifier))throw Error(`Certificate with serial number ${a.serialNumber} has an unrequested certifier: ${a.certifier}`);if(null==t[a.type])throw Error(`Certificate with type ${a.type} was not requested`)}await a.decryptFields(e,void 0,void 0,i)}))},nT="undefined"!=typeof globalThis?globalThis.Buffer:void 0;class nC{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;originator;identityPublicKey;constructor(e,t,r,i,n,a){this.wallet=e,this.originator=a,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 nP,!1===n?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);if(null==i.peerIdentityKey)throw Error("Peer identity is not established");if(!0===i.certificatesRequired&&!0!==i.certificatesValidated)throw Error("Cannot send general message before certificate validation is complete");let n=ta(tJ(32)),{signature:a}=await this.wallet.createSignature({data:e,protocolID:[2,"auth message signature"],keyID:`${n} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),s={version:"0.1",messageType:"general",identityKey:await this.getIdentityPublicKey(),nonce:n,yourNonce:i.peerNonce,payload:e,signature:a};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}async requestCertificates(e,t,r=1e4){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);let i=await this.getAuthenticatedSession(t,r),n=ta(tJ(32)),{signature:a}=await this.wallet.createSignature({data:nC.utf8ToBytes(JSON.stringify(e)),protocolID:[2,"auth message signature"],keyID:`${n} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),s={version:"0.1",messageType:"certificateRequest",identityKey:await this.getIdentityPublicKey(),nonce:n,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,requestedCertificates:e,signature:a};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}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 nO(this.wallet,void 0,this.originator),i=Date.now(),n=this.certificatesToRequest.certifiers.length>0;this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:r,peerIdentityKey:e,lastUpdate:i,certificatesRequired:n,certificatesValidated:!n});let a={version:"0.1",messageType:"initialRequest",identityKey:await this.getIdentityPublicKey(),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 n=this.listenForInitialResponse(e,e=>{clearTimeout(a),this.stopListeningForInitialResponses(n),r(e)}),a=setTimeout(()=>{this.stopListeningForInitialResponses(n),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)}propagateTransportError(e,t){if(t instanceof Error){if(null!=e){let r=t.details;null!=r&&"object"==typeof r?null==r.peerIdentityKey&&(r.peerIdentityKey=e):t.details={peerIdentityKey:e}}throw t}throw Error(`Failed to send message to peer ${e??"unknown"}: ${String(t)}`)}async handleIncomingMessage(e){if("string"!=typeof e.version||"0.1"!==e.version)throw Error(`Invalid or unsupported message auth version! Received: ${e.version}, expected: 0.1`);try{switch(e.messageType){case"initialRequest":await this.processInitialRequest(e);break;case"initialResponse":await this.processInitialResponse(e);break;case"certificateRequest":await this.processCertificateRequest(e);break;case"certificateResponse":await this.processCertificateResponse(e);break;case"general":await this.processGeneralMessage(e);break;default:throw Error(`Unknown message type of ${String(e.messageType)} from ${String(e.identityKey)}`)}}catch(e){}}async processInitialRequest(e){let t;if("string"!=typeof e.identityKey||"string"!=typeof e.initialNonce||""===e.initialNonce)throw Error("Missing required fields in initialRequest message.");let r=await nO(this.wallet,void 0,this.originator),i=Date.now(),n=Array.isArray(this.certificatesToRequest?.certifiers)&&this.certificatesToRequest.certifiers.length>0;this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:r,peerNonce:e.initialNonce,peerIdentityKey:e.identityKey,lastUpdate:i,certificatesRequired:n,certificatesValidated:!n}),Array.isArray(e.requestedCertificates?.certifiers)&&e.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)}):t=await nA(this.wallet,e.requestedCertificates,e.identityKey,this.originator));let{signature:a}=await this.wallet.createSignature({data:nC.base64ToBytes(e.initialNonce+r),protocolID:[2,"auth message signature"],keyID:`${e.initialNonce} ${r}`,counterparty:e.identityKey},this.originator),s={version:"0.1",messageType:"initialResponse",identityKey:await this.getIdentityPublicKey(),initialNonce:r,yourNonce:e.initialNonce,certificates:t,requestedCertificates:this.certificatesToRequest,signature:a};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=e.identityKey),await this.transport.send(s)}async processInitialResponse(e){if(!await nN(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=nC.base64ToBytes((t.sessionNonce??"")+(e.initialNonce??"")),{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.certificatesRequired=Array.isArray(this.certificatesToRequest?.certifiers)&&this.certificatesToRequest.certifiers.length>0,t.certificatesValidated=!t.certificatesRequired,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),t.certificatesRequired&&Array.isArray(e.certificates)&&e.certificates.length>0&&(await n_(this.wallet,e,this.certificatesToRequest,this.originator),t.certificatesValidated=!0,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),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 nA(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async processCertificateRequest(e){if(!await nN(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:nC.utf8ToBytes(JSON.stringify(e.requestedCertificates)),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 nA(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=ta(tJ(32)),{signature:n}=await this.wallet.createSignature({data:nC.utf8ToBytes(JSON.stringify(t)),protocolID:[2,"auth message signature"],keyID:`${i} ${r.peerNonce??""}`,counterparty:r.peerIdentityKey},this.originator),a={version:"0.1",messageType:"certificateResponse",identityKey:await this.getIdentityPublicKey(),nonce:i,initialNonce:r.sessionNonce,yourNonce:r.peerNonce,certificates:t,signature:n};r.lastUpdate=Date.now(),this.sessionManager.updateSession(r);try{await this.transport.send(a)}catch(e){this.propagateTransportError(r.peerIdentityKey,e)}}async processCertificateResponse(e){if(!await nN(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:nC.utf8ToBytes(JSON.stringify(e.certificates)),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 n_(this.wallet,e,e.requestedCertificates,this.originator),t.certificatesValidated=!0,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.onCertificatesReceivedCallbacks.forEach(t=>{t(e.identityKey,e.certificates??[])})}async processGeneralMessage(e){if(!await nN(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 r=!0===t.certificatesRequired,i=!0===t.certificatesValidated;if(r&&!i)throw Error(`Received general message before certificate validation from peer ${t.peerIdentityKey??"unknown"}`);let{valid:n}=await this.wallet.verifySignature({data:e.payload,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!n)throw Error(`Invalid signature in generalMessage from ${t.peerIdentityKey}`);t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.lastInteractedWithPeer=e.identityKey,this.onGeneralMessageReceivedCallbacks.forEach(t=>{t(e.identityKey,e.payload??[])})}async getIdentityPublicKey(){if(null!=this.identityPublicKey)return this.identityPublicKey;let{publicKey:e}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return this.identityPublicKey=e,e}static utf8ToBytes(e){return null!=nT?Array.from(nT.from(e,"utf8")):"undefined"!=typeof TextEncoder?Array.from(new TextEncoder().encode(e)):e9(e,"utf8")}static base64ToBytes(e){return null!=nT?Array.from(nT.from(e,"base64")):e9(e,"base64")}}let nR="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch;class nV{onDataCallback;fetchClient;baseUrl;constructor(e,t=nR){if("function"!=typeof t)throw Error("SimplifiedFetchTransport requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=t,this.baseUrl=e}async send(e){if(null==this.onDataCallback)throw Error("Listen before you start speaking. God gave you two ears and one mouth for a reason.");if("general"!==e.messageType)return await new Promise((t,r)=>{(async()=>{try{let r=`${this.baseUrl}/.well-known/auth`,i=(async()=>{try{return await this.fetchClient(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(e){throw this.createNetworkError(r,e)}})();"initialRequest"!==e.messageType&&t();let n=await i;if(!n.ok){let e=Array.from(new Uint8Array(await n.arrayBuffer()));throw this.createUnauthenticatedResponseError(r,n,e)}if(null!=this.onDataCallback){let e=await n.json();this.onDataCallback(e)}"initialRequest"===e.messageType&&t()}catch(e){r(e)}})()});{let t,r,i=this.deserializeRequestPayload(e.payload),n=`${this.baseUrl}${i.urlPostfix}`;if("object"!=typeof i.headers&&(i.headers={}),i.headers["x-bsv-auth-version"]=e.version,i.headers["x-bsv-auth-identity-key"]=e.identityKey,i.headers["x-bsv-auth-nonce"]=e.nonce,i.headers["x-bsv-auth-your-nonce"]=e.yourNonce,i.headers["x-bsv-auth-signature"]=e7(e.signature),i.headers["x-bsv-auth-request-id"]=i.requestId,null!=i.body){let e=i.headers;if(null==e["content-type"])throw Error("Content-Type header is required for requests with a body.");let t=String(e["content-type"]??"");t.includes("application/json")||t.includes("application/x-www-form-urlencoded")||t.includes("text/plain")?i.body=ti(i.body):i.body=new Uint8Array(i.body)}try{t=await this.fetchClient(n,{method:i.method,headers:i.headers,body:i.body})}catch(e){throw this.createNetworkError(n,e)}let a=Array.from(new Uint8Array(await t.arrayBuffer())),s=["x-bsv-auth-version","x-bsv-auth-identity-key","x-bsv-auth-signature"].filter(e=>{let r=t.headers.get(e);return null==r||0===r.trim().length});if(s.length>0)throw this.createUnauthenticatedResponseError(n,t,a,s);let o=t.headers.get("x-bsv-auth-requested-certificates");if(null!=o)try{r=JSON.parse(o)}catch(e){throw this.createMalformedHeaderError(n,"x-bsv-auth-requested-certificates",o,e)}let c=new tu;null!=t.headers.get("x-bsv-auth-request-id")&&c.write(e9(t.headers.get("x-bsv-auth-request-id"),"base64")),c.writeVarIntNum(t.status);let l=[];t.headers.forEach((e,t)=>{let r=t.toLowerCase();(r.startsWith("x-bsv-")||"authorization"===r)&&!r.startsWith("x-bsv-auth")&&l.push([r,e])}),l.sort(([e],[t])=>e.localeCompare(t)),c.writeVarIntNum(l.length);for(let e=0;e<l.length;e++){let t=e9(l[e][0],"utf8");c.writeVarIntNum(t.length),c.write(t);let r=e9(l[e][1],"utf8");c.writeVarIntNum(r.length),c.write(r)}c.writeVarIntNum(a.length),a.length>0&&c.write(a);let h={version:t.headers.get("x-bsv-auth-version"),messageType:"certificateRequest"===t.headers.get("x-bsv-auth-message-type")?"certificateRequest":"general",identityKey:t.headers.get("x-bsv-auth-identity-key"),nonce:t.headers.get("x-bsv-auth-nonce")??void 0,yourNonce:t.headers.get("x-bsv-auth-your-nonce")??void 0,requestedCertificates:r,payload:c.toArray(),signature:e9(t.headers.get("x-bsv-auth-signature"),"hex")};if(null==h.version)throw this.createUnauthenticatedResponseError(n,t,a);this.onDataCallback(h)}}async onData(e){this.onDataCallback=t=>{e(t)}}createNetworkError(e,t){let r=`Network error while sending authenticated request to ${e}`;if(t instanceof Error){let e=Error(`${r}: ${t.message}`);return e.stack=t.stack,e.cause=t,e}return Error(`${r}: ${String(t)}`)}createUnauthenticatedResponseError(e,t,r,i=[]){let n=(t.statusText??"").trim(),a=n.length>0?`${t.status} ${n}`:`${t.status}`,s=i.length>0?`missing headers: ${i.join(", ")}`:"response lacked required BSV auth headers",o=this.getBodyPreview(r,t.headers.get("content-type")),c=[`Received HTTP ${a} from ${e} without valid BSV authentication (${s})`];null!=o&&c.push(`body preview: ${o}`);let l=Error(c.join(" - "));return l.details={url:e,status:t.status,statusText:t.statusText,missingHeaders:i,bodyPreview:o},l}createMalformedHeaderError(e,t,r,i){let n=`Failed to parse ${t} returned by ${e}: ${r}`;if(i instanceof Error){let e=Error(`${n}. ${i.message}`);return e.stack=i.stack,e.cause=i,e}return Error(`${n}. ${String(i)}`)}getBodyPreview(e,t){let r;if(0===e.length)return;let i=e.length>1024,n=i?e.slice(0,1024):e;if(this.isTextualContent(t,n))try{r=ti(n)}catch{r=this.formatBinaryPreview(n,i)}else r=this.formatBinaryPreview(n,i);return r.length>512&&(r=`${r.slice(0,512)}…`),i&&(r=`${r} (truncated)`),r}isTextualContent(e,t){if(0===t.length)return!1;if(null!=e){let t=e.toLowerCase();if(["application/json","application/problem+json","application/xml","application/xhtml+xml","application/javascript","application/ecmascript","application/x-www-form-urlencoded","text/"].some(e=>t.includes(e))||t.includes("charset="))return!0}return t.reduce((e,t)=>9===t||10===t||13===t||t>=32&&t<=126?e+1:e,0)/t.length>.8}formatBinaryPreview(e,t){let r=e.map(e=>e.toString(16).padStart(2,"0")).join("");return`0x${r}${t?"…":""}`}deserializeRequestPayload(e){let t,r=new td(e),i=ta(r.read(32)),n=r.readVarIntNum(),a="GET";n>0&&(a=ti(r.read(n)));let s=r.readVarIntNum(),o="";s>0&&(o=ti(r.read(s)));let c=r.readVarIntNum(),l="";c>0&&(l=ti(r.read(c)));let h={},u=r.readVarIntNum();if(u>0)for(let e=0;e<u;e++){let e=r.readVarIntNum(),t=ti(r.read(e)),i=r.readVarIntNum(),n=ti(r.read(i));h[t]=n}let d=r.readVarIntNum();return d>0&&(t=r.read(d)),{urlPostfix:o+l,method:a,headers:h,body:t,requestId:i}}}class nB{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;originator;peers={};constructor(e,t,r,i){this.wallet=e,this.requestedCertificates=t,this.sessionManager=r??new nP,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 n,{method:a="GET",headers:s={},body:o}=t,c=new URL(e),l=c.origin;if(void 0===this.peers[l]){let e=new nV(l);n={peer:new nC(this.wallet,e,this.requestedCertificates,this.sessionManager,void 0,this.originator),pendingCertificateRequests:[]},this.peers[l]=n,this.peers[l].peer.listenForCertificatesReceived((e,t)=>{this.certificatesReceived.push(...t)}),this.peers[l].peer.listenForCertificatesRequested(async(e,t)=>{try{this.peers[l].pendingCertificateRequests.push(!0);let r=await nA(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}n=this.peers[l]}let h=tJ(32),u=ta(h),d=await this.serializeRequest(a,s,o,c,h);this.callbacks[u]={resolve:r,reject:i};let f=n.peer.listenForGeneralMessages((e,t)=>{let r,i=new td(t);if(ta(i.read(32))!==u)return;n.peer.stopListeningForGeneralMessages(f),this.peers[l].identityKey=e,this.peers[l].supportsMutualAuth=!0;let a=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=ti(t),n=i.readVarIntNum(),a=i.read(n),o=ti(a);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:a,statusText:`${a}`,headers:new Headers(s)});this.callbacks[u].resolve(h),delete this.callbacks[u]});n.pendingCertificateRequests.length>0&&await new Promise(e=>{setInterval(()=>{0===n.pendingCertificateRequests.length&&e()},100)}),await n.peer.toPeer(d.toArray(),n.identityKey).catch(async a=>{if(a.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(a.message.includes("HTTP server failed to authenticate"))try{let i=await this.handleFetchAndValidate(e,t,n);r(i);return}catch(e){i(e)}else i(a)})}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 nV(i);r={peer:new nC(this.wallet,e,this.requestedCertificates,this.sessionManager,this.originator)},this.peers[i]=r}return await new Promise(async(e,i)=>{let n=r.peer.listenForCertificatesReceived((t,i)=>{r.peer.stopListeningForCertificatesReceived(n),this.certificatesReceived.push(...i),e(i)});try{await r.peer.requestCertificates(t,r.identityKey)}catch(e){r.peer.stopListeningForCertificatesReceived(n),i(e)}})}consumeReceivedCertificates(){return this.certificatesReceived.splice(0)}async serializeRequest(e,t,r,i,n){let a=new tu;if(a.write(n),a.writeVarIntNum(e.length),a.write(e9(e)),i.pathname.length>0){let e=e9(i.pathname);a.writeVarIntNum(e.length),a.write(e)}else a.writeVarIntNum(-1);if(i.search.length>0){let e=e9(i.search);a.writeVarIntNum(e.length),a.write(e)}else a.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)),a.writeVarIntNum(s.length);for(let e=0;e<s.length;e++){let t=e9(s[e][0],"utf8");a.writeVarIntNum(t.length),a.write(t);let r=e9(s[e][1],"utf8");a.writeVarIntNum(r.length),a.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);a.writeVarIntNum(e.length),a.write(e)}else a.writeVarIntNum(-1);return a}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 n=r.headers.get("x-bsv-payment-satoshis-required");if(!n)throw Error("Missing x-bsv-payment-satoshis-required response header.");let a=parseInt(n);if(isNaN(a)||a<=0)throw Error("Invalid x-bsv-payment-satoshis-required response header value.");let s=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=t.paymentContext;if(null!=c?this.isPaymentContextCompatible(c,a,s,o)||(this.logPaymentAttempt("warn","Server adjusted payment requirements; regenerating transaction",this.composePaymentLogDetails(e,c)),c=await this.createPaymentContext(e,t,a,s,o)):c=await this.createPaymentContext(e,t,a,s,o),c.attempts>=c.maxAttempts)throw this.buildPaymentFailureError(e,c,Error("Maximum payment attempts exceeded before retrying"));let l={...t.headers??{}};l["x-bsv-payment"]=JSON.stringify({derivationPrefix:c.derivationPrefix,derivationSuffix:c.derivationSuffix,transaction:c.transactionBase64});let h={...t,headers:l,paymentContext:c};"number"!=typeof h.retryCounter&&(h.retryCounter=3);let u=c.attempts+1,d=c.maxAttempts;c.attempts=u;let f=this.composePaymentLogDetails(e,c);this.logPaymentAttempt("warn",`Attempting paid request (${u}/${d})`,f);try{let t=await this.fetch(e,h);return this.logPaymentAttempt("info",`Paid request attempt ${u} succeeded`,f),t}catch(n){let t=this.createPaymentErrorEntry(c.attempts,n);if(c.errors.push(t),this.logPaymentAttempt("error",`Paid request attempt ${u} failed`,{...f,error:{message:t.message,stack:t.stack}}),c.attempts>=c.maxAttempts)throw this.buildPaymentFailureError(e,c,n);let i=this.getPaymentRetryDelay(c.attempts);return await this.wait(i),this.handlePaymentAndRetry(e,h,r)}}isPaymentContextCompatible(e,t,r,i){return e.satoshisRequired===t&&e.serverIdentityKey===r&&e.derivationPrefix===i}async createPaymentContext(e,t,r,i,n){let a=await nO(this.wallet,void 0,this.originator),{publicKey:s}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${n} ${a}`,counterparty:i},this.originator),o=new rC().lock(tX.fromString(s).toAddress()).toHex(),{tx:c}=await this.wallet.createAction({description:`Payment for request to ${new URL(e).origin}`,outputs:[{satoshis:r,lockingScript:o,customInstructions:JSON.stringify({derivationPrefix:n,derivationSuffix:a,payee:i}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}},this.originator),{publicKey:l}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return{satoshisRequired:r,transactionBase64:ta(c),derivationPrefix:n,derivationSuffix:a,serverIdentityKey:i,clientIdentityKey:l,attempts:0,maxAttempts:this.getMaxPaymentAttempts(t),errors:[],requestSummary:this.buildPaymentRequestSummary(e,t)}}getMaxPaymentAttempts(e){let t="number"==typeof e.paymentRetryAttempts?e.paymentRetryAttempts:void 0;return"number"==typeof t&&t>0?Math.floor(t):3}buildPaymentRequestSummary(e,t){let r={...t.headers??{}},i="string"==typeof t.method?t.method.toUpperCase():"GET",n=this.describeRequestBodyForLogging(t.body);return{url:e,method:i,headers:r,bodyType:n.type,bodyByteLength:n.byteLength}}describeRequestBodyForLogging(e){if(null==e)return{type:"none",byteLength:0};if("string"==typeof e)return{type:"string",byteLength:e9(e,"utf8").length};if(Array.isArray(e))return e.every(e=>"number"==typeof e)?{type:"number[]",byteLength:e.length}:{type:"array",byteLength:e.length};if("undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer)return{type:"ArrayBuffer",byteLength:e.byteLength};if("undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e))return{type:null!=e.constructor?e.constructor.name:"TypedArray",byteLength:e.byteLength};if("undefined"!=typeof Blob&&e instanceof Blob)return{type:"Blob",byteLength:e.size};if("undefined"!=typeof FormData&&e instanceof FormData)return{type:"FormData",byteLength:0};if("undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams)return{type:"URLSearchParams",byteLength:e9(e.toString(),"utf8").length};if("undefined"!=typeof ReadableStream&&e instanceof ReadableStream)return{type:"ReadableStream",byteLength:0};try{let t=JSON.stringify(e);if("string"==typeof t)return{type:"object",byteLength:e9(t,"utf8").length}}catch(e){}return{type:typeof e,byteLength:0}}composePaymentLogDetails(e,t){return{url:e,request:t.requestSummary,payment:{satoshis:t.satoshisRequired,transactionBase64:t.transactionBase64,derivationPrefix:t.derivationPrefix,derivationSuffix:t.derivationSuffix,serverIdentityKey:t.serverIdentityKey,clientIdentityKey:t.clientIdentityKey},attempts:{used:t.attempts,max:t.maxAttempts},errors:t.errors}}logPaymentAttempt(e,t,r){let i="[AuthFetch][Payment]";"error"===e?console.error(`${i} ${t}`,r):"warn"===e?console.warn(`${i} ${t}`,r):"function"==typeof console.info?console.info(`${i} ${t}`,r):console.log(`${i} ${t}`,r)}createPaymentErrorEntry(e,t){let r={attempt:e,timestamp:new Date().toISOString(),message:"",stack:void 0};return t instanceof Error?(r.message=t.message,r.stack=t.stack??void 0):r.message=String(t),r}getPaymentRetryDelay(e){return 250*Math.min(e,5)}async wait(e){e<=0||await new Promise(t=>setTimeout(t,e))}buildPaymentFailureError(e,t,r){let i=Error(`Paid request to ${e} failed after ${t.attempts}/${t.maxAttempts} attempts. Sent ${t.satoshisRequired} satoshis to ${t.serverIdentityKey}.`);return i.details={request:t.requestSummary,payment:{satoshis:t.satoshisRequired,transactionBase64:t.transactionBase64,derivationPrefix:t.derivationPrefix,derivationSuffix:t.derivationSuffix,serverIdentityKey:t.serverIdentityKey,clientIdentityKey:t.clientIdentityKey},attempts:{used:t.attempts,max:t.maxAttempts},errors:t.errors},r instanceof Error&&(i.cause=r),i}async normalizeBodyToNumberArray(e){if(null==e)return[];if("object"==typeof e)return e9(JSON.stringify(e,"utf8"));if(Array.isArray(e)&&e.every(e=>"number"==typeof e))return e;if("string"==typeof e)return e9(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()])}),e9(new URLSearchParams(t).toString(),"utf8")}if(e instanceof URLSearchParams)return e9(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 nD{pushDrop;static decode(e){let t=rB.decode(e);if(t.fields.length<4)throw Error("Invalid SHIP/SLAP advertisement!");let r=ti(t.fields[0]);if("SHIP"!==r&&"SLAP"!==r)throw Error("Invalid protocol type!");let i=e7(t.fields[1]);return{protocol:r,identityKey:i,domain:ti(t.fields[2]),topicOrService:ti(t.fields[3])}}constructor(e,t){this.pushDrop=new rB(e,t)}async lock(e,t,r){let{publicKey:i}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([e9(e,"utf8"),e9(i,"hex"),e9(t,"utf8"),e9(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 nU="bsvsdk_overlay_host_reputation_v1";class nF{stats;store;constructor(e){this.stats=new Map,this.store=e??this.getLocalStorageAdapter(),this.loadFromStorage()}reset(){this.stats.clear()}recordSuccess(e,t){let r=this.getOrCreate(e),i=Date.now(),n=Number.isFinite(t)&&t>=0?t:1500;null===r.avgLatencyMs?r.avgLatencyMs=n:r.avgLatencyMs=.75*r.avgLatencyMs+.25*n,r.lastLatencyMs=n,r.totalSuccesses+=1,r.consecutiveFailures=0,r.backoffUntil=0,r.lastUpdatedAt=i,r.lastError=void 0,this.saveToStorage()}recordFailure(e,t){let r=this.getOrCreate(e),i=Date.now();r.totalFailures+=1,r.consecutiveFailures+=1;let n="string"==typeof t?t:t instanceof Error?t.message:void 0;"string"==typeof n&&(n.includes("ERR_NAME_NOT_RESOLVED")||n.includes("ENOTFOUND")||n.includes("getaddrinfo")||n.includes("Failed to fetch"))&&r.consecutiveFailures<3&&(r.consecutiveFailures=3);let a=Math.max(r.consecutiveFailures-2,0);0===a?r.backoffUntil=0:r.backoffUntil=i+Math.min(6e4,1e3*Math.pow(2,a-1)),r.lastUpdatedAt=i,r.lastError="string"==typeof t?t:t instanceof Error?t.message:void 0,this.saveToStorage()}rankHosts(e,t=Date.now()){let r=new Map;e.forEach((e,t)=>{"string"==typeof e&&0!==e.length&&(r.has(e)||r.set(e,t))});let i=Array.from(r.keys()).map(e=>{let i=this.getOrCreate(e);return{...i,score:this.computeScore(i,t),originalOrder:r.get(e)??0}});return i.sort((e,r)=>{let i=e.backoffUntil>t;return i!==r.backoffUntil>t?i?1:-1:e.score!==r.score?e.score-r.score:e.totalSuccesses!==r.totalSuccesses?r.totalSuccesses-e.totalSuccesses:e.originalOrder-r.originalOrder}),i.map(({originalOrder:e,...t})=>t)}snapshot(e){let t=this.stats.get(e);return null!=t?{...t}:void 0}getStorage(){try{let e="object"==typeof globalThis?globalThis:void 0;if(null==e||null==e.localStorage)return;return e.localStorage}catch{return}}getLocalStorageAdapter(){let e=this.getStorage();if(null!=e)return{get:t=>{try{return e.getItem(t)}catch{return null}},set:(t,r)=>{try{e.setItem(t,r)}catch{}}}}loadFromStorage(){let e=this.store;if(null!=e)try{let t=e.get(nU);if("string"!=typeof t||0===t.length)return;let r=JSON.parse(t);if("object"!=typeof r||null===r)return;for(let e of(this.stats.clear(),Object.keys(r))){let t=r[e];if(null!=t&&"object"==typeof t){let r={host:String(t.host??e),totalSuccesses:Number(t.totalSuccesses??0),totalFailures:Number(t.totalFailures??0),consecutiveFailures:Number(t.consecutiveFailures??0),avgLatencyMs:null==t.avgLatencyMs?null:Number(t.avgLatencyMs),lastLatencyMs:null==t.lastLatencyMs?null:Number(t.lastLatencyMs),backoffUntil:Number(t.backoffUntil??0),lastUpdatedAt:Number(t.lastUpdatedAt??0),lastError:"string"==typeof t.lastError?t.lastError:void 0};this.stats.set(r.host,r)}}}catch{}}saveToStorage(){let e=this.store;if(null!=e)try{let t={};for(let[e,r]of this.stats.entries())t[e]=r;e.set(nU,JSON.stringify(t))}catch{}}computeScore(e,t){let r=e.avgLatencyMs??1500,i=400*e.consecutiveFailures,n=Math.min(30*e.totalSuccesses,r/2);return r+i+(e.backoffUntil>t?e.backoffUntil-t:0)-n}getOrCreate(e){let t=this.stats.get(e);return null==t&&(t={host:e,totalSuccesses:0,totalFailures:0,consecutiveFailures:0,avgLatencyMs:null,lastLatencyMs:null,backoffUntil:0,lastUpdatedAt:0},this.stats.set(e,t)),t}}let nL=new nF,nK="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch,nH=["https://overlay-us-1.bsvb.tech","https://overlay-eu-1.bsvb.tech","https://overlay-ap-1.bsvb.tech","https://users.bapp.dev"],nq=["https://testnet-users.bapp.dev"];class nM{fetchClient;allowHTTP;constructor(e=nK,t=!1){if("function"!=typeof e)throw Error("HTTPSOverlayLookupFacilitator requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=e,this.allowHTTP=t}async lookup(e,t,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,n=setTimeout(()=>{try{i?.abort()}catch{}},r);try{let r={method:"POST",headers:{"Content-Type":"application/json","X-Aggregation":"yes"},body:JSON.stringify({service:t.service,query:t.query}),signal:i?.signal},n=await this.fetchClient(`${e}/lookup`,r);if(!n.ok)throw Error(`Failed to facilitate lookup (HTTP ${n.status})`);if("application/octet-stream"!==n.headers.get("content-type"))return await n.json();{let e=await n.arrayBuffer(),t=new td([...new Uint8Array(e)]),r=t.readVarIntNum(),i=[];for(let e=0;e<r;e++){let e,r=e7(t.read(32)),n=t.readVarIntNum(),a=t.readVarIntNum();a>0&&(e=t.read(a)),i.push({txid:r,outputIndex:n,context:e})}let a=t.read();return{type:"output-list",outputs:i.map(e=>({outputIndex:e.outputIndex,context:e.context,beef:r0.fromBEEF(a,e.txid).toBEEF()}))}}}catch(e){if(e?.name==="AbortError")throw Error("Request timed out");throw e}finally{clearTimeout(n)}}}class n${facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;hostReputation;hostsCache;hostsInFlight;hostsTtlMs;hostsMaxEntries;txMemo;txMemoTtlMs;constructor(e={}){this.networkPreset=e.networkPreset??"mainnet",this.facilitator=e.facilitator??new nM(void 0,"local"===this.networkPreset),this.slapTrackers=e.slapTrackers??("mainnet"===this.networkPreset?nH:nq);const t=e.hostOverrides??{};this.assertValidOverrideServices(t),this.hostOverrides=t,this.additionalHosts=e.additionalHosts??{};const r=e.reputationStorage;"localStorage"===r?this.hostReputation=new nF:"object"==typeof r&&null!==r&&"function"==typeof r.get&&"function"==typeof r.set?this.hostReputation=new nF(r):this.hostReputation=nL,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=this.prepareHostsForQuery(r,`lookup service ${e.service}`);if(i.length<1)throw Error(`All competent hosts for ${e.service} are temporarily unavailable due to backoff.`);let n=await Promise.allSettled(i.map(async r=>await this.lookupHostWithTracking(r,e,t))),a=new Map,s=e=>"object"!=typeof e?"":e.join(",");for(let e of n){if("fulfilled"!==e.status)continue;let t=e.value;if(t?.type==="output-list"&&Array.isArray(t.outputs))for(let e of t.outputs){let t=s(e.beef),r=this.txMemo.get(t),i=Date.now();if("object"!=typeof r||null===r||r.expiresAt<=i)try{r={txId:r0.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 n=`${r.txId}.${e.outputIndex}`;a.set(n,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=this.prepareHostsForQuery(this.slapTrackers,"SLAP trackers");if(0===r.length)return[];let i=await Promise.allSettled(r.map(async e=>await this.lookupHostWithTracking(e,t,5e3))),n=new Set;for(let t of i){if("fulfilled"!==t.status)continue;let r=t.value;if("output-list"===r.type)for(let t of r.outputs)try{let r=r0.fromBEEF(t.beef),i=r.outputs[t.outputIndex]?.lockingScript;if("object"!=typeof i||null===i)continue;let a=nD.decode(i);if(a.topicOrService!==e||"SLAP"!==a.protocol)continue;"string"==typeof a.domain&&a.domain.length>0&&n.add(a.domain)}catch{continue}}return[...n]}evictOldest(e){let t=e.keys().next().value;void 0!==t&&e.delete(t)}assertValidOverrideServices(e){for(let t of Object.keys(e))if(!t.startsWith("ls_"))throw Error(`Host override service names must start with "ls_": ${t}`)}prepareHostsForQuery(e,t){if(0===e.length)return[];let r=Date.now(),i=this.hostReputation.rankHosts(e,r),n=i.filter(e=>e.backoffUntil<=r).map(e=>e.host);if(n.length>0)return n;let a=Math.max(Math.min(...i.map(e=>e.backoffUntil))-r,0);throw Error(`All ${t} hosts are backing off for approximately ${a}ms due to repeated failures.`)}async lookupHostWithTracking(e,t,r){let i=Date.now();try{let n=await this.facilitator.lookup(e,t,r),a=Date.now()-i;return"object"==typeof n&&null!==n&&"output-list"===n.type&&Array.isArray(n.outputs)?this.hostReputation.recordSuccess(e,a):this.hostReputation.recordFailure(e,"Invalid lookup response"),n}catch(t){throw this.hostReputation.recordFailure(e,t),t}}}class nz{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 tu;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 n=await fetch(`${e}/submit`,{method:"POST",headers:i,body:r});if(n.ok)return await n.json();throw Error("Failed to facilitate broadcast")}}class nW{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 nz(void 0,"local"===this.networkPreset),this.resolver=t.resolver??new n$({networkPreset:this.networkPreset}),this.requireAcknowledgmentFromAllHostsForTopics=t.requireAcknowledgmentFromAllHostsForTopics??[],this.requireAcknowledgmentFromAnyHostForTopics=t.requireAcknowledgmentFromAnyHostForTopics??"all",this.requireAcknowledgmentFromSpecificHostsForTopics=t.requireAcknowledgmentFromSpecificHostsForTopics??{}}async broadcast(e){let t,r,i,n,a,s=e.metadata.get("OffChainValues");try{t=e.toBEEF()}catch(e){throw Error("Transactions sent via SHIP to Overlay Services must be serializable to BEEF format.")}let o=await this.findInterestedHosts();if(0===Object.keys(o).length)return{status:"error",code:"ERR_NO_HOSTS_INTERESTED",description:`No ${this.networkPreset} hosts are interested in receiving this transaction.`};let c=Object.entries(o).map(async([e,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,n=t.coinsToRetain,a=t.coinsRemoved;(r?.length>0||n?.length>0||a?.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?(n=this.topics,a="all"):"any"===this.requireAcknowledgmentFromAnyHostForTopics?(n=this.topics,a="any"):(n=Array.isArray(this.requireAcknowledgmentFromAnyHostForTopics)?this.requireAcknowledgmentFromAnyHostForTopics:[],a="all"),n.length>0&&!this.checkAcknowledgmentFromAnyHost(h,n,a))?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ANY_HOST_FAILED",description:"No host acknowledged the required topics."}:Object.keys(this.requireAcknowledgmentFromSpecificHostsForTopics).length>0&&!this.checkAcknowledgmentFromSpecificHosts(h,this.requireAcknowledgmentFromSpecificHostsForTopics)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_SPECIFIC_HOSTS_FAILED",description:"Specific hosts did not acknowledge the required topics."}:{status:"success",txid:e.id("hex"),message:`Sent to ${l.length} Overlay Services ${1===l.length?"host":"hosts"}.`}}checkAcknowledgmentFromAllHosts(e,t,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,n,a=e[r];if(null==a)return!1;if("all"===i||"any"===i)n=i,t=this.topics;else{if(!Array.isArray(i))continue;t=i,n="all"}if("all"===n){for(let e of t)if(!a.has(e))return!1}else if("any"===n){let e=!1;for(let r of t)if(a.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=r0.fromBEEF(r.beef).outputs[r.outputIndex].lockingScript,i=nD.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}}async function nj(e,t,r=5){let i=0;for(;i<r;){i++;try{return await e()}catch(e){if(i<r&&"WERR_REVIEW_ACTIONS"===e.name){let n=e.reviewActionResults.find(e=>"doubleSpend"===e.status);if(n?.competingBeef!=null&&n?.competingTxs!=null&&n?.competingTxs.length>0){let e=r0.fromBEEF(n.competingBeef,n.competingTxs[0]);await nj(async()=>await t.broadcast(e),t,r-i);continue}}throw e}}throw Error("Unexpected end of retry loop")}let nX=e=>(e.toLowerCase().startsWith("uhrp:")&&(e=e.slice(5)),e.startsWith("//")&&(e=e.slice(2)),e),nG=e=>{if(32!==e.length)throw Error("Hash length must be 32 bytes (sha256)");return tl(e,e9("ce00","hex"))},nY=e=>{let t=e instanceof Uint8Array?e:Uint8Array.from(e),r=new J;for(let e=0;e<t.length;e+=1048576){let i=t.subarray(e,e+1048576);r.update(Array.from(i))}return nG(r.digest())},nJ=e=>{let{data:t,prefix:r}=th(e=nX(e),void 0,2);if(32!==t.length)throw Error("Invalid length!");if("ce00"!==e7(r))throw Error("Bad prefix");return t},nZ=e=>{try{return nJ(e),!0}catch(e){return!1}};class nQ{authFetch;baseURL;constructor(e){this.baseURL=e.storageURL,this.authFetch=new nB(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 n=await i.json();if("error"===n.status)throw Error("Upload route returned an error.");return{uploadURL:n.uploadURL,requiredHeaders:n.requiredHeaders,amount:n.amount}}async uploadFile(e,t,r){let i=t.data instanceof Uint8Array?t.data:Uint8Array.from(t.data),n=await fetch(e,{method:"PUT",body:i,headers:{"Content-Type":t.type,...r}});if(!n.ok)throw Error(`File upload failed: HTTP ${n.status}`);return{published:!0,uhrpURL:nY(i)}}async publishFile(e){let{file:t,retentionPeriod:r}=e,i=t.data instanceof Uint8Array?t.data:Uint8Array.from(t.data),n=i.byteLength,{uploadURL:a,requiredHeaders:s}=await this.getUploadInfo(n,r);return await this.uploadFile(a,{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 n=await i.json();if("error"===n.status){let e=n.code??"unknown-code",t=n.description??"no-description";throw Error(`renewFile returned an error: ${e} - ${t}`)}return{status:n.status,prevExpiryTime:n.prevExpiryTime,newExpiryTime:n.newExpiryTime,amount:n.amount}}}class n0{networkPreset="mainnet";lookupResolver;constructor(e){this.networkPreset=e?.networkPreset??"mainnet",this.lookupResolver=new n$({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 n=r0.fromBEEF(t.outputs[e].beef),{fields:a}=rB.decode(n.outputs[t.outputs[e].outputIndex].lockingScript);new td(a[3]).readVarIntNum()<i||r.push(ti(a[2]))}return r}async download(e){if(!nZ(e))throw Error("Invalid parameter UHRP url");let t=e7(nJ(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 n=i.body.getReader(),a=new J,s=[],o=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;a.update(Array.from(t)),s.push(t),o+=t.length}if(e7(a.digest())!==t)throw Error("Data integrity error: value of content does not match hash of the url given");let c=new Uint8Array(o),l=0;for(let e of s)c.set(e,l),l+=e.length;return{data:c,mimeType:i.headers.get("Content-Type")}}catch(e){continue}throw Error(`Unable to download content from ${e}`)}}let n1={name:"Unknown Identity",avatarURL:"XUUB8bbn9fEthk15Ge3zTQXypUShfC94vFjp65v7u5CQ8qkpxzst",identityKey:"",abbreviatedKey:"",badgeIconURL:"XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",badgeLabel:"Not verified by anyone you trust.",badgeClickURL:"https://projectbabbage.com/docs/unknown-identity"},n2={protocolID:[1,"identity"],keyID:"1",tokenAmount:1,outputIndex:0},n8={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="},n3=[2,"contact"];class n6{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 n4{wallet;cache=new n6;CONTACTS_CACHE_KEY="metanet-contacts";originator;constructor(e,t){this.wallet=e??new nI,this.originator=t}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:n3,keyID:e,counterparty:"self",data:e9(e,"utf8")},this.originator);i.push(`identityKey ${e7(t)}`)}let n=await this.wallet.listOutputs({basket:"contacts",include:"locking scripts",includeCustomInstructions:!0,tags:i,limit:r},this.originator);if(null==n.outputs||0===n.outputs.length)return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify([])),[];let a=[];for(let e of n.outputs)try{if(null==e.lockingScript)continue;let t=rB.decode(rE.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:n3,keyID:r,counterparty:"self"},this.originator),n=JSON.parse(ti(i));a.push(n)}catch(e){console.warn("ContactsManager: Failed to decode contact output:",e)}return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(a)),null!=e?a.filter(t=>t.identityKey===e):a}async saveContact(e,t){let r,i=this.cache.getItem(this.CONTACTS_CACHE_KEY),n=(r=null!=i&&""!==i?JSON.parse(i):await this.getContacts()).findIndex(t=>t.identityKey===e.identityKey),a={...e,metadata:t};n>=0?r[n]=a:r.push(a);let{hmac:s}=await this.wallet.createHmac({protocolID:n3,keyID:e.identityKey,counterparty:"self",data:e9(e.identityKey,"utf8")},this.originator),o=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:[`identityKey ${e7(s)}`],limit:100},this.originator),c=null,l=ta(tJ(32));if(null!=o.outputs)for(let t of o.outputs)try{let[r,i]=t.outpoint.split("."),n=r0.fromBEEF(o.BEEF,r),a=rB.decode(n.outputs[Number(i)].lockingScript);if(null==t.customInstructions)continue;l=JSON.parse(t.customInstructions).keyID;let{plaintext:s}=await this.wallet.decrypt({ciphertext:a.fields[0],protocolID:n3,keyID:l,counterparty:"self"},this.originator);if(JSON.parse(ti(s)).identityKey===e.identityKey){c=t;break}}catch(e){}let h={...e,metadata:t},{ciphertext:u}=await this.wallet.encrypt({plaintext:e9(JSON.stringify(h),"utf8"),protocolID:n3,keyID:l,counterparty:"self"},this.originator),d=await new rB(this.wallet,this.originator).lock([u],n3,l,"self");if(null!=c){let[t,r]=String(c.outpoint).split("."),i=`${t}.${r}`,n=new rB(this.wallet,this.originator),{signableTransaction:a}=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:d.toHex(),outputDescription:`Updated Contact: ${e.name??e.identityKey.slice(0,10)}`,tags:[`identityKey ${e7(s)}`],customInstructions:JSON.stringify({keyID:l})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==a)throw Error("Unable to update contact");let h=n.unlock(n3,l,"self"),u=await h.sign(r0.fromBEEF(a.tx),0),{tx:f}=await this.wallet.signAction({reference:a.reference,spends:{0:{unlockingScript:u.toHex()}}},this.originator);if(null==f)throw Error("Failed to update contact output")}else{let{tx:t}=await this.wallet.createAction({description:"Add Contact",outputs:[{basket:"contacts",satoshis:1,lockingScript:d.toHex(),outputDescription:`Contact: ${e.name??e.identityKey.slice(0,10)}`,tags:[`identityKey ${e7(s)}`],customInstructions:JSON.stringify({keyID:l})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==t)throw Error("Failed to create contact output")}this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(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:n3,keyID:e,counterparty:"self",data:e9(e,"utf8")},this.originator);r.push(`identityKey ${e7(i)}`);let n=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:r,limit:100},this.originator);if(null!=n.outputs)for(let t of n.outputs)try{let[r,i]=String(t.outpoint).split("."),a=r0.fromBEEF(n.BEEF,r),s=rB.decode(a.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:n3,keyID:o,counterparty:"self"},this.originator);if(JSON.parse(ti(c)).identityKey===e){let e=`${r}.${i}`,t=new rB(this.wallet,this.originator),{signableTransaction:a}=await this.wallet.createAction({description:"Delete Contact",inputBEEF:n.BEEF,inputs:[{outpoint:e,unlockingScriptLength:74,inputDescription:"Spend contact output to delete"}],outputs:[],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==a)throw Error("Unable to delete contact");let s=t.unlock(n3,o,"self"),c=await s.sign(r0.fromBEEF(a.tx),0),{tx:l}=await this.wallet.signAction({reference:a.reference,spends:{0:{unlockingScript:c.toHex()}}},this.originator);if(null==l)throw Error("Failed to delete contact output");return}}catch(e){}}}class n5{options;originator;wallet;contactsManager;constructor(e,t=n2,r){this.options=t,this.originator=r,this.originator=r,this.wallet=e??new nI("auto",this.originator),this.contactsManager=new n4(this.wallet,this.originator)}async publiclyRevealAttributes(e,t){if(0===Object.keys(e.fields).length)throw Error("Public reveal failed: Certificate has no fields to reveal!");if(0===t.length)throw Error("Public reveal failed: You must reveal at least one field!");try{let t=new iT(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 t1(1).toPublicKey().toString()},this.originator),i=await new rB(this.wallet,this.originator).lock([e9(JSON.stringify({...e,keyring:r}))],this.options.protocolID,this.options.keyID,"anyone",!0,!0),{tx:n}=await this.wallet.createAction({description:"Create a new Identity Token",outputs:[{satoshis:this.options.tokenAmount,lockingScript:i.toHex(),outputDescription:"Identity Token"}],options:{randomizeOutputs:!1}},this.originator);if(void 0!==n){let e=new nW(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network});return await e.broadcast(r0.fromAtomicBEEF(n))}throw Error("Public reveal failed: failed to create action!")}async resolveByIdentityKey(e,t=!0){if(t)try{let t=await this.contactsManager.getContacts(e.identityKey);if(t.length>0)return t}catch(e){}try{let{certificates:t}=await this.wallet.discoverByIdentityKey(e,this.originator);return t.map(e=>n5.parseIdentity(e))}catch(t){if((t instanceof Error?t.message:"").includes("No wallet available"))return(await this.resolveViaLookup({identityKey:e.identityKey})).map(e=>n5.parseIdentity(e));throw t}}async resolveByAttributes(e,t=!0){let r=t?this.contactsManager.getContacts().catch(()=>[]):Promise.resolve([]);try{let[t,i]=await Promise.all([r,this.wallet.discoverByAttributes(e,this.originator)]),n=new Map(t.map(e=>[e.identityKey,e]));return(i?.certificates??[]).map(e=>n.get(e.subject)??n5.parseIdentity(e))}catch(t){if((t instanceof Error?t.message:"").includes("No wallet available"))return(await this.resolveViaLookup({attributes:e.attributes})).map(e=>n5.parseIdentity(e));throw t}}async resolveViaLookup(e){let t=new n$({networkPreset:"mainnet"}),r={certifiers:["02cf6cdf466951d8dfc9e7c9367511d0007ed6fba35ed42d425cc412fd6cfd4a17"]};if(void 0!==e.identityKey)r.identityKey=e.identityKey;else if(void 0!==e.attributes){let t=Object.values(e.attributes);1===t.length?r.attributes={any:t[0]}:r.attributes=e.attributes}let i=await t.query({service:"ls_identity",query:r});if("output-list"!==i.type||0===i.outputs.length)return[];let n=[],a=new iP("anyone");for(let e of i.outputs)try{let t=r0.fromBEEF(e.beef),r=rB.decode(t.outputs[e.outputIndex].lockingScript),i=JSON.parse(ti(r.fields[0])),s=new nx(i.type,i.serialNumber,i.subject,i.certifier,i.revocationOutpoint,i.fields,i.keyring,i.signature),o=await s.decryptFields(a);await s.verify();let c={type:i.type,serialNumber:i.serialNumber,subject:i.subject,certifier:i.certifier,revocationOutpoint:i.revocationOutpoint,fields:i.fields,signature:i.signature,certifierInfo:{name:"SocialCert",iconUrl:"https://socialcert.net/favicon.ico",description:"Social identity verification",trust:5},publiclyRevealedKeyring:i.keyring,decryptedFields:o};n.push(c)}catch(e){continue}return n}async revokeCertificateRevelation(e){let t=new n$({networkPreset:(await this.wallet.getNetwork({})).network}),r=await t.query({service:"ls_identity",query:{serialNumber:e}});if("output-list"!==r.type)throw Error("Failed to get lookup result");let i=new nW(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network,requireAcknowledgmentFromAllHostsForTopics:[],requireAcknowledgmentFromAnyHostForTopics:[],requireAcknowledgmentFromSpecificHostsForTopics:{tm_identity:[]}});await nj(async()=>{let e=r0.fromBEEF(r.outputs[0].beef),t=`${e.id("hex")}.${this.options.outputIndex}`;if(void 0===e.outputs[this.options.outputIndex].lockingScript||void 0===t)throw Error("Failed to get locking script for revelation output!");let{signableTransaction:n}=await this.wallet.createAction({description:"Spend certificate revelation token",inputBEEF:r.outputs[0].beef,inputs:[{inputDescription:"Revelation token",outpoint:t,unlockingScriptLength:74}],options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1,noSend:!0}},this.originator);if(void 0===n)throw Error("Failed to create signable transaction");let a=r0.fromBEEF(n.tx),s=new rB(this.wallet,this.originator).unlock(this.options.protocolID,this.options.keyID,"anyone"),o=await s.sign(a,this.options.outputIndex),{tx:c}=await this.wallet.signAction({reference:n.reference,spends:{[this.options.outputIndex]:{unlockingScript:o.toHex()}},options:{acceptDelayedBroadcast:!1,noSend:!0}},this.originator);if(void 0===c)throw Error("Failed to sign transaction");await i.broadcast(r0.fromAtomicBEEF(c))},i)}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,n,a,{type:s,decryptedFields:o,certifierInfo:c}=e;switch(s){case n8.xCert:t=o.userName,r=o.profilePhoto,i=`X account certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n8.discordCert:t=o.userName,r=o.profilePhoto,i=`Discord account certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n8.emailCert:t=o.email,r="XUTZxep7BBghAJbSBwTjNfmcsDdRFs5EaGEgkESGSgjJVYgMEizu",i=`Email certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n8.phoneCert:t=o.phoneNumber,r="XUTLxtX3ELNUwRhLwL7kWNGbdnFM8WG2eSLv84J7654oH8HaJWrU",i=`Phone certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n8.identiCert:t=`${o.firstName} ${o.lastName}`,r=o.profilePhoto,i=`Government ID certified by ${c.name}`,n=c.iconUrl,a="https://identicert.me";break;case n8.registrant:t=o.name,r=o.icon,i=`Entity certified by ${c.name}`,n=c.iconUrl,a="https://projectbabbage.com/docs/registrant";break;case n8.coolCert:t="true"===o.cool?"Cool Person!":"Not cool!";break;case n8.anyone:t="Anyone",r="XUT4bpQ6cpBaXi1oMzZsXfpkWGbtp2JTUYAoN7PzhStFJ6wLfoeR",i="Represents the ability for anyone to access this information.",n="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",a="https://projectbabbage.com/docs/anyone-identity";break;case n8.self:t="You",r="XUT9jHGk2qace148jeCX5rDsMftkSGYKmigLwU2PLLBc7Hm63VYR",i="Represents your ability to access this information.",n="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",a="https://projectbabbage.com/docs/self-identity";break;default:{let e=n5.tryToParseGenericIdentity(s,o,c);t=e.name,r=e.avatarURL,i=e.badgeLabel,n=e.badgeIconURL,a=e.badgeClickURL}}return{name:t,avatarURL:r,abbreviatedKey:e.subject.length>0?`${e.subject.substring(0,10)}...`:"",identityKey:e.subject,badgeIconURL:n,badgeLabel:i,badgeClickURL:a}}static hasValue(e){return null!=e&&""!==e}static tryToParseGenericIdentity(e,t,r){let i=t.firstName,n=t.lastName,a=n5.hasValue(i)&&n5.hasValue(n)?`${i} ${n}`:n5.hasValue(i)?i:n5.hasValue(n)?n:void 0,s=n5.hasValue(t.name)?t.name:n5.hasValue(t.userName)?t.userName:a??(n5.hasValue(t.email)?t.email:n1.name),o=n5.hasValue(t.profilePhoto)?t.profilePhoto:n5.hasValue(t.avatar)?t.avatar:n5.hasValue(t.icon)?t.icon:n5.hasValue(t.photo)?t.photo:n1.avatarURL,c=n5.hasValue(r?.name)?`${e} certified by ${String(r.name)}`:n1.badgeLabel;return{name:s,avatarURL:o,badgeLabel:c,badgeIconURL:n5.hasValue(r?.iconUrl)?r.iconUrl:n1.badgeIconURL,badgeClickURL:n1.badgeClickURL}}}class n7{wallet;originator;network;resolver;cachedIdentityKey;acceptDelayedBroadcast;constructor(e=new nI,t={},r){this.wallet=e,this.originator=r,this.acceptDelayedBroadcast=t.acceptDelayedBroadcast??!1,this.resolver=t.resolver??new n$}async getIdentityKey(){return void 0===this.cachedIdentityKey&&(this.cachedIdentityKey=(await this.wallet.getPublicKey({identityKey:!0})).publicKey),this.cachedIdentityKey}async getNetwork(){return void 0===this.network&&(this.network=(await this.wallet.getNetwork({})).network),this.network}async registerDefinition(e){let t=await this.getIdentityKey(),r=new rB(this.wallet,this.originator),i=this.buildPushDropFields(e,t),n=this.mapDefinitionTypeToWalletProtocol(e.definitionType),a=await r.lock(i,n,"1","anyone",!0),{tx:s}=await this.wallet.createAction({description:`Register a new ${e.definitionType} item`,outputs:[{satoshis:1,lockingScript:a.toHex(),outputDescription:`New ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===s)throw Error(`Failed to create ${e.definitionType} registration transaction!`);let o=new nW([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await o.broadcast(r0.fromAtomicBEEF(s))}async resolve(e,t){let r=this.mapDefinitionTypeToServiceName(e),i=await this.resolver.query({service:r,query:t});if("output-list"!==i.type)return[];let n=[];for(let t of i.outputs)try{let r=r0.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"}),n=[];for(let t of r)if(t.spendable)try{let[r,a]=t.outpoint.split("."),s=r0.fromBEEF(i,r).outputs[Number(a)].lockingScript,o=await this.parseLockingScript(e,s);n.push({...o,txid:r,outputIndex:Number(a),satoshis:t.satoshis,lockingScript:s.toHex(),beef:i})}catch{}return n}async removeDefinition(e){if(void 0===e.txid||void 0===e.outputIndex||void 0===e.lockingScript)throw Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");let t=await this.getIdentityKey();if(e.registryOperator!==t)throw Error("This registry token does not belong to the current wallet.");let r="basket"===e.definitionType?e.basketID:"protocol"===e.definitionType?e.name:"certificate"===e.definitionType?void 0!==e.name?e.name:e.type:"unknown",i=`${e.txid}.${e.outputIndex}`,{signableTransaction:n}=await this.wallet.createAction({description:`Remove ${e.definitionType} item: ${r}`,inputBEEF:e.beef,inputs:[{outpoint:i,unlockingScriptLength:74,inputDescription:`Removing ${e.definitionType} token`}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===n)throw Error("Failed to create signable transaction.");let a=r0.fromAtomicBEEF(n.tx),s=new rB(this.wallet,this.originator).unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone"),o=await s.sign(a,0),{tx:c}=await this.wallet.signAction({reference:n.reference,spends:{0:{unlockingScript:o.toHex()}},options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if(void 0===c)throw Error("Failed to finalize the transaction signature.");let l=new nW([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await l.broadcast(r0.fromAtomicBEEF(c))}async updateDefinition(e,t){if(void 0===e.txid||void 0===e.outputIndex||void 0===e.lockingScript)throw Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");if(e.definitionType!==t.definitionType)throw Error(`Cannot change definition type from ${e.definitionType} to ${t.definitionType}`);let r=await this.getIdentityKey();if(e.registryOperator!==r)throw Error("This registry token does not belong to the current wallet.");let i="basket"===e.definitionType?e.basketID:"protocol"===e.definitionType?e.name:"certificate"===e.definitionType?void 0!==e.name?e.name:e.type:"unknown",n=new rB(this.wallet,this.originator),a=this.buildPushDropFields(t,r),s=this.mapDefinitionTypeToWalletProtocol(t.definitionType),o=await n.lock(a,s,"1","anyone",!0),c=`${e.txid}.${e.outputIndex}`,{signableTransaction:l}=await this.wallet.createAction({description:`Update ${e.definitionType} item: ${i}`,inputBEEF:e.beef,inputs:[{outpoint:c,unlockingScriptLength:74,inputDescription:`Updating ${e.definitionType} token`}],outputs:[{satoshis:1,lockingScript:o.toHex(),outputDescription:`Updated ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===l)throw Error("Failed to create signable transaction.");let h=r0.fromAtomicBEEF(l.tx),u=n.unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone"),d=await u.sign(h,0),{tx:f}=await this.wallet.signAction({reference:l.reference,spends:{0:{unlockingScript:d.toHex()}},options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if(void 0===f)throw Error("Failed to finalize the transaction signature.");let p=new nW([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await p.broadcast(r0.fromAtomicBEEF(f))}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=>e9(e))}async parseLockingScript(e,t){let r,i,n=rB.decode(t);if(0===n.fields.length)throw Error("Not a valid registry pushdrop script.");switch(e){case"basket":{if(7!==n.fields.length)throw Error("Unexpected field count for basket type.");let[e,t,a,s,o,c]=n.fields;r=ti(c),i={definitionType:"basket",basketID:ti(e),name:ti(t),iconURL:ti(a),description:ti(s),documentationURL:ti(o)};break}case"protocol":{if(7!==n.fields.length)throw Error("Unexpected field count for protocol type.");let[e,t,a,s,o,c]=n.fields;r=ti(c),i={definitionType:"protocol",protocolID:n9(ti(e)),name:ti(t),iconURL:ti(a),description:ti(s),documentationURL:ti(o)};break}case"certificate":{if(8!==n.fields.length)throw Error("Unexpected field count for certificate type.");let[e,t,a,s,o,c,l]=n.fields;r=ti(l);let h={};try{h=JSON.parse(ti(c))}catch{}i={definitionType:"certificate",type:ti(e),name:ti(t),iconURL:ti(a),description:ti(s),documentationURL:ti(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 n9(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 ae{wallet;context;encrypt;originator;acceptDelayedBroadcast=!1;keyLocks=new Map;constructor(e=new nI,t="kvstore default",r=!0,i,n=!1){if("string"!=typeof t||t.length<1)throw Error("A context in which to operate is required.");this.wallet=e,this.context=t,this.encrypt=r,this.originator=i,this.acceptDelayedBroadcast=n}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},this.originator)}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("."),n=t.findTxid(r)?.tx;if(null==n)throw Error(`beef must contain txid ${r}`);return n.outputs[Number(i)].lockingScript}async lookupValue(e,t,r){let i,n=await this.getOutputs(e,r),a={value:t,outpoint:void 0,lor:n},{outputs:s}=n;if(0===s.length)return a;let o=s.slice(-1)[0];a.outpoint=o.outpoint;try{if(void 0===n.BEEF)throw Error("entire transactions listOutputs option must return valid BEEF");let e=this.getLockingScript(o,rZ.fromBinary(n.BEEF)),t=rB.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},this.originator);a.value=ti(t)}else a.value=ti(i);return a}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 n=this.getProtocol(e),a=r0.fromAtomicBEEF(i),s={};for(let e=0;e<t.length;e++){let t=r.unlock(n.protocolID,n.keyID,"self"),i=await t.sign(a,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 n=this.getProtocol(e),a=e9(t,"utf8");if(this.encrypt){let{ciphertext:e}=await this.wallet.encrypt({...n,plaintext:a},this.originator);a=e}let s=new rB(this.wallet,this.originator),o=await s.lock([a],n.protocolID,n.keyID,"self"),{outputs:c,BEEF:l}=i.lor;try{let t=this.getInputs(c),{txid:i,signableTransaction:n}=await this.wallet.createAction({description:`Update ${e} in ${this.context}`,inputBEEF:l,inputs:t,outputs:[{basket:this.context,tags:[e],lockingScript:o.toHex(),satoshis:1,outputDescription:"Key-value token"}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(c.length>0&&"object"!=typeof n)throw Error("Wallet did not return a signable transaction when expected.");if(null==n)r=`${i}.0`;else{let t=await this.getSpends(e,c,s,n.tx),{txid:i}=await this.wallet.signAction({reference:n.reference,spends:t},this.originator);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:n}=await this.getOutputs(e);if(r.length>0){let a=new rB(this.wallet,this.originator);try{let n=this.getInputs(r),{signableTransaction:s}=await this.wallet.createAction({description:`Remove ${e} in ${this.context}`,inputBEEF:i,inputs:n,options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if("object"!=typeof s)throw Error("Wallet did not return a signable transaction when expected.");let o=await this.getSpends(e,r,a,s.tx),{txid:c}=await this.wallet.signAction({reference:s.reference,spends:o},this.originator);if(void 0===c)throw Error("signAction must return a valid txid");t.push(c)}catch(t){throw Error(`There are ${n} outputs with tag ${e} that cannot be unlocked. Original error: ${t instanceof Error?t.message:String(t)}`)}}if(r.length===n)break}return t}finally{this.finishOperationOnKey(e,t)}}}class at{interpreter;debug;historyCache;interpreterVersion;ctxKeyFn;constructor(e,t){this.interpreter=e,this.debug=t?.debug??!1,this.historyCache=t?.historyCache,this.interpreterVersion=t?.interpreterVersion??"v1",this.ctxKeyFn=t?.ctxKeyFn??(e=>{try{return JSON.stringify(e??null)}catch{return""}})}historyKey(e,t){let r=e.id("hex"),i=this.ctxKeyFn(t);return`${this.interpreterVersion}|${r}|${i}`}async buildHistory(e,t){if(null!=this.historyCache){let r=this.historyKey(e,t);if(this.historyCache.has(r)){let e=this.historyCache.get(r);if(null!=e)return this.debug&&console.log("[Historian] History cache hit:",r),e.slice()}}let r=[],i=new Set,n=async e=>{let a=e.id("hex");if(i.has(a)){this.debug&&console.log(`[Historian] Skipping already visited transaction: ${a}`);return}i.add(a),this.debug&&console.log(`[Historian] Processing transaction: ${a}`);for(let i=0;i<e.outputs.length;i++)try{let n=await Promise.resolve(this.interpreter(e,i,t));void 0!==n&&(r.push(n),this.debug&&console.log("[Historian] Added value to history:",n))}catch(e){this.debug&&console.log(`[Historian] Failed to interpret output ${i}:`,e)}for(let t of e.inputs)null!=t.sourceTransaction?await n(t.sourceTransaction):this.debug&&console.log("[Historian] Input missing sourceTransaction, skipping")};await n(e);let a=r.reverse();if(null!=this.historyCache){let r=this.historyKey(e,t);this.historyCache.set(r,Object.freeze(a.slice())),this.debug&&console.log("[Historian] History cached:",r)}return a}}let ar={protocolID:0,key:1,value:2,controller:3,tags:4,signature:5},ai=async(e,t,r)=>{try{let i=e.outputs[t];if(null==i||null==i.lockingScript||null==r||null==r.key)return;let n=rB.decode(i.lockingScript),a=Object.keys(ar).length,s=n.fields.length===a;if(n.fields.length!==a-1&&!s)return;let o=ti(n.fields[ar.key]),c=ti(n.fields[ar.protocolID]);if(o!==r.key||c!==JSON.stringify(r.protocolID))return;try{return ti(n.fields[ar.value])}catch{return}}catch{return}},an={protocolID:[1,"kvstore"],serviceName:"ls_kvstore",tokenAmount:1,topics:["tm_kvstore"],networkPreset:"mainnet",acceptDelayedBroadcast:!1,overlayBroadcast:!1,tokenSetDescription:"",tokenUpdateDescription:"",tokenRemovalDescription:""};class aa{wallet;config;historian;lookupResolver;topicBroadcaster;keyLocks=new Map;cachedIdentityKey=null;constructor(e={}){this.config={...an,...e},this.wallet=e.wallet??new nI,this.historian=new at(ai),this.lookupResolver=new n$({networkPreset:this.config.networkPreset}),this.topicBroadcaster=new nW(this.config.topics,{networkPreset:this.config.networkPreset})}async get(e,t={}){if(0===Object.keys(e).length)throw Error("Must specify either key, controller, or protocolID");if(null!=e.key&&null!=e.controller){let r=await this.queryOverlay(e,t);return r.length>0?r[0]:void 0}return await this.queryOverlay(e,t)}async set(e,t,r={}){if("string"!=typeof e||0===e.length)throw Error("Key must be a non-empty string.");if("string"!=typeof t)throw Error("Value must be a string.");let i=await this.getIdentityKey(),n=await this.queueOperationOnKey(e),a=r.protocolID??this.config.protocolID,s=null!=r.tokenSetDescription&&""!==r.tokenSetDescription?r.tokenSetDescription:`Create KVStore value for ${e}`,o=null!=r.tokenUpdateDescription&&""!==r.tokenUpdateDescription?r.tokenUpdateDescription:`Update KVStore value for ${e}`,c=r.tokenAmount??this.config.tokenAmount,l=r.tags??[];try{let r=new rB(this.wallet,this.config.originator),n=[e9(JSON.stringify(a),"utf8"),e9(e,"utf8"),e9(t,"utf8"),e9(i,"hex")];l.length>0&&n.push(e9(JSON.stringify(l),"utf8"));let h=await r.lock(n,a??this.config.protocolID,ti(e9(e,"utf8")),"anyone",!0);return await nj(async()=>{let t=await this.queryOverlay({key:e,controller:i},{includeToken:!0}),n=t.length>0?t[0].token:void 0;if(null!=n){let t=[{outpoint:`${n.txid}.${n.outputIndex}`,unlockingScriptLength:74,inputDescription:"Previous KVStore token"}],i=n.beef,{signableTransaction:a}=await this.wallet.createAction({description:o,inputBEEF:i.toBinary(),inputs:t,outputs:[{satoshis:c??this.config.tokenAmount,lockingScript:h.toHex(),outputDescription:"KVStore token"}],options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast,randomizeOutputs:!1}},this.config.originator);if(null==a)throw Error("Unable to create update transaction");let s=r0.fromAtomicBEEF(a.tx),l=r.unlock(this.config.protocolID,e,"anyone"),u=await l.sign(s,0),{tx:d}=await this.wallet.signAction({reference:a.reference,spends:{0:{unlockingScript:u.toHex()}},options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==d)throw Error("Unable to finalize update transaction");let f=r0.fromAtomicBEEF(d);return await this.submitToOverlay(f),`${f.id("hex")}.0`}{let{tx:e}=await this.wallet.createAction({description:s,outputs:[{satoshis:c??this.config.tokenAmount,lockingScript:h.toHex(),outputDescription:"KVStore token"}],options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast,randomizeOutputs:!1}},this.config.originator);if(null==e)throw Error("Failed to create transaction");let t=r0.fromAtomicBEEF(e);return await this.submitToOverlay(t),`${t.id("hex")}.0`}},this.topicBroadcaster)}finally{n.length>0&&this.finishOperationOnKey(e,n)}}async remove(e,t,r={}){if("string"!=typeof e||0===e.length)throw Error("Key must be a non-empty string.");let i=await this.getIdentityKey(),n=await this.queueOperationOnKey(e),a=r.protocolID??this.config.protocolID,s=null!=r.tokenRemovalDescription&&""!==r.tokenRemovalDescription?r.tokenRemovalDescription:`Remove KVStore value for ${e}`;try{let r=new rB(this.wallet,this.config.originator);return await nj(async()=>{let n=await this.queryOverlay({key:e,controller:i},{includeToken:!0});if(0===n.length||null==n[0].token)throw Error("The item did not exist, no item was deleted.");let o=n[0].token,c=[{outpoint:`${o.txid}.${o.outputIndex}`,unlockingScriptLength:74,inputDescription:"KVStore token to remove"}],{signableTransaction:l}=await this.wallet.createAction({description:s,inputBEEF:o.beef.toBinary(),inputs:c,outputs:t,options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,randomizeOutputs:!1,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==l)throw Error("Unable to create removal transaction");let h=r0.fromAtomicBEEF(l.tx),u=r.unlock(a??this.config.protocolID,e,"anyone"),d=await u.sign(h,0),{tx:f}=await this.wallet.signAction({reference:l.reference,spends:{0:{unlockingScript:d.toHex()}},options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==f)throw Error("Unable to finalize removal transaction");let p=r0.fromAtomicBEEF(f);return await this.submitToOverlay(p),p.id("hex")},this.topicBroadcaster)}finally{n.length>0&&this.finishOperationOnKey(e,n)}}async queueOperationOnKey(e){let t=this.keyLocks.get(e);null==t&&(t=[],this.keyLocks.set(e,t));let 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]():this.keyLocks.delete(e)}async getIdentityKey(){return null==this.cachedIdentityKey&&(this.cachedIdentityKey=(await this.wallet.getPublicKey({identityKey:!0},this.config.originator)).publicKey),this.cachedIdentityKey}async queryOverlay(e,t={}){let r=await this.lookupResolver.query({service:t.serviceName??this.config.serviceName,query:e});if("output-list"!==r.type||0===r.outputs.length)return[];let i=[];for(let e of r.outputs)try{let r,n=r0.fromBEEF(e.beef),a=n.outputs[e.outputIndex],s=rB.decode(a.lockingScript),o=Object.keys(ar).length,c=s.fields.length===o;if(s.fields.length!==o-1&&!c)continue;let l=new iE("anyone"),h=s.fields.pop();try{await l.verifySignature({data:s.fields.reduce((e,t)=>[...e,...t],[]),signature:h,counterparty:e7(s.fields[ar.controller]),protocolID:JSON.parse(ti(s.fields[ar.protocolID])),keyID:ti(s.fields[ar.key])})}catch(e){continue}if(c&&null!=s.fields[ar.tags])try{r=JSON.parse(ti(s.fields[ar.tags]))}catch(e){r=void 0}let u={key:ti(s.fields[ar.key]),value:ti(s.fields[ar.value]),controller:e7(s.fields[ar.controller]),protocolID:JSON.parse(ti(s.fields[ar.protocolID])),tags:r};!0===t.includeToken&&(u.token={txid:n.id("hex"),outputIndex:e.outputIndex,beef:rZ.fromBinary(e.beef),satoshis:a.satoshis??1}),!0===t.history&&(u.history=await this.historian.buildHistory(n,{key:u.key,protocolID:u.protocolID})),i.push(u)}catch(e){continue}return i}async submitToOverlay(e){return await this.topicBroadcaster.broadcast(e)}}let as=aa;return p})());
20
20
  //# sourceMappingURL=bundle.js.map