@bsv/sdk 1.9.9 → 1.9.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/package.json +1 -1
- package/dist/cjs/src/auth/certificates/Certificate.js +10 -0
- package/dist/cjs/src/auth/certificates/Certificate.js.map +1 -1
- package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
- package/dist/esm/src/auth/certificates/Certificate.js +10 -0
- package/dist/esm/src/auth/certificates/Certificate.js.map +1 -1
- package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
- package/dist/types/src/auth/certificates/Certificate.d.ts +15 -0
- package/dist/types/src/auth/certificates/Certificate.d.ts.map +1 -1
- package/dist/types/tsconfig.types.tsbuildinfo +1 -1
- package/dist/umd/bundle.js +1 -1
- package/dist/umd/bundle.js.map +1 -1
- package/docs/reference/auth.md +35 -0
- package/package.json +1 -1
- package/src/auth/certificates/Certificate.ts +28 -0
- package/src/auth/certificates/__tests/Certificate.test.ts +51 -0
package/dist/umd/bundle.js
CHANGED
|
@@ -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=>eQ(ee(e0(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 rC="undefined"!=typeof globalThis?globalThis.Buffer:void 0;class rR{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}=rR.fromAnyBeef(e,t);return r}static fromAtomicBEEF(e){let{tx:t,txid:r,beef:i}=rR.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=rT.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 ti(e),r=t.readUInt32LE();if("0000000000ef"!==eQ(t.read(6)))throw Error("Invalid EF marker");let i=t.readVarIntNum(),n=[];for(let e=0;e<i;e++){let e=eQ(t.readReverse(32)),r=t.readUInt32LE(),i=t.readVarIntNum(),a=t.read(i),s=ra.fromBinary(a),o=t.readUInt32LE(),c=t.readUInt64LEBn().toNumber(),l=t.readVarIntNum(),h=t.read(l),u=rn.fromBinary(h),d=new rR(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=rn.fromBinary(i);s.push({satoshis:e,lockingScript:n})}return new rR(r,n,s,t.readUInt32LE())}static parseScriptOffsets(e){let t=new ti(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=eQ(e.readReverse(32)),r=e.readUInt32LE(),n=e.readVarIntNum(),a=e.read(n),s=ra.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=rn.fromBinary(i);a.push({satoshis:t,lockingScript:n})}return new rR(t,i,a,e.readUInt32LE())}static fromBinary(e){let t=e.slice(),r=Uint8Array.from(t),i=new ti(t),n=rR.fromReader(i);return n.rawBytesCache=r,n}static fromHex(e){let t=e0(e,"hex"),r=Uint8Array.from(t),i=new ti(t),n=rR.fromReader(i);return n.rawBytesCache=r,n.hexCache=null!=rC?rC.from(r).toString("hex"):eQ(t),n}static fromHexEF(e){return rR.fromEF(e0(e,"hex"))}static fromHexBEEF(e,t){return rR.fromBEEF(e0(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 ru().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=rb.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=rk()){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(e0(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 tr;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 tr;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(e0(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 eQ(this.toEF())}toHex(){if(null!=this.hexCache)return this.hexCache;let e=this.getSerializedBytes(),t=null!=rC?rC.from(e).toString("hex"):eQ(Array.from(e));return this.hexCache=t,t}toHexBEEF(){return eQ(this.toBEEF())}toHexAtomicBEEF(){return eQ(this.toAtomicBEEF())}hash(e){return(null==this.cachedHash&&(this.cachedHash=ee(this.getSerializedBytes())),"hex"===e)?eQ(this.cachedHash):this.cachedHash}id(e){let t=[...this.hash()];return(t.reverse(),"hex"===e)?eQ(t):t}async verify(e=rx(),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=rR.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 rh({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 tr;t.writeUInt32LE(rO);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 rV(e){return"success"===e.status}function rB(e){return"error"===e.status}let rD=class extends rT{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)?rT.fromBinary(t):t,i=r.getValidTxids();this.mergeBeef(r),this.addKnownTxidsForParty(e,i)}};class rU{network;URL;httpClient;constructor(e="main",t=rw()){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 rF{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 rL{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 rK(){let e={async request(){throw Error("No method available to perform HTTP request")}};if("undefined"!=typeof window&&"function"==typeof window.fetch)return new rL(window.fetch.bind(window));if("undefined"==typeof require)return e;try{let e=require("https");return new rF(e)}catch(t){return e}}class rH{URL;httpClient;constructor(e,t=rK()){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 rq{baseUrl;httpClient;apiKey;constructor(e,t={}){const{httpClient:r,apiKey:i}=t;this.baseUrl=e,this.httpClient=r??rw(),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 rM="42423301",r$=(e,t,r)=>{let i="object"!=typeof r;if(i){let e=new tP,t=new tM(1),i=e.g.mul(t);r=new tD(i.x,i.y)}let n=tL(32),a=e4(n),s=`2-message signing-${a}`,o=t.deriveChild(r,s).sign(e).toDER(),c=t.toPublicKey().encode(!0);return[...e0(rM,"hex"),...c,...i?[0]:r.encode(!0),...n,...o]},rz=(e,t,r)=>{let i=new ti(t),n=eQ(i.read(4));if(n!==rM)throw Error(`Message version mismatch: Expected ${rM}, received ${n}`);let a=tD.fromString(eQ(i.read(33))),[s]=i.read(1);if(0===s)r=new tM(1);else{let e=eQ([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=e4(i.read(32)),c=eQ(i.read(i.bin.length-i.pos)),l=tN.fromDER(c,"hex"),h=`2-message signing-${o}`;return a.deriveChild(r,h).verify(e,l)},rW="42421033",rj=(e,t,r)=>{let i=tL(32),n=e4(i),a=`2-message encryption-${n}`,s=t.deriveChild(r,a),o=r.deriveChild(t,a),c=new t4(s.deriveSharedSecret(o).encode(!0).slice(1)).encrypt(e),l=t.toPublicKey().encode(!0);return[...e0(rW,"hex"),...l,...r.encode(!0),...i,...c]},rG=(e,t)=>{let r=new ti(e),i=eQ(r.read(4));if(i!==rW)throw Error(`Message version mismatch: Expected ${rW}, received ${i}`);let n=tD.fromString(eQ(r.read(33))),a=eQ(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=e4(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 t4(h.deriveSharedSecret(u).encode(!0).slice(1)).decrypt(c)},rX="Bitcoin Signed Message:\n",rJ=e=>{let t=new tr;return t.writeVarIntNum(rX.length),t.write(e0(rX,"utf8")),t.writeVarIntNum(e.length),t.write(e),ee(t.toArray())},rY=(e,t,r="base64")=>{let i=rJ(e),n=tV(new k(i),t,!0);if("raw"===r)return n;let a=new k(i),s=n.CalculateRecoveryFactor(t.toPublicKey(),a);return n.toCompact(s,!0,"base64")},rZ=(e,t,r)=>tB(new k(rJ(e)),t,r);class rQ{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=tL(32),this.privKey=tM.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=tt(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=ei(e0("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 tM(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 ti(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 tM(r.slice(1,33)),this.pubKey=this.privKey.toPublicKey();else if(n&&(2===r[0]||3===r[0]))this.pubKey=tD.fromString(eQ(r));else throw Error("Invalid key");return this}toString(){return te(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=ei(this.chainCode,e),n=new k(t.slice(0,32)),s=t.slice(32,64),o=n.add(this.privKey).mod(new tP().n);(a=new rQ).chainCode=s,a.privKey=new tM(o.toArray()),a.pubKey=a.privKey.toPublicKey()}else{let e=[...this.pubKey.encode(!0),...r],t=ei(this.chainCode,e),i=new k(t.slice(0,32)),n=t.slice(32,64),s=new tP().g.mul(i),o=this.pubKey,c=s.add(o),l=new tD(c.x,c.y);(a=new rQ).chainCode=n,a.pubKey=l}a.childIndex=e;let s=et(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 rQ(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 tr().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 tr().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 r0={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 r1{mnemonic;seed;Wordlist;constructor(e,t,r=r0){this.mnemonic=e??"",this.seed=t??[],this.Wordlist=r}toBinary(){let e=new tr;if(""!==this.mnemonic){let t=e0(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 ti(e),r=t.readVarIntNum();r>0&&(this.mnemonic=e6(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=tL(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=Z(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=Z(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=e0(t,"utf8"),i=[...e0("mnemonic","utf8"),...e0(e,"utf8")];return this.seed=eW(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 r1(e).isValid(t)}}function r2(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]]}r2.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],m=p[2],y=p[3],w=p[4];for(a=0;a<u;a++)r=g[o>>>24]^b[c>>16&255]^m[l>>8&255]^y[255&h]^s[d],i=g[c>>>24]^b[l>>16&255]^m[h>>8&255]^y[255&o]^s[d+1],n=g[l>>>24]^b[h>>16&255]^m[o>>8&255]^y[255&c]^s[d+2],h=g[h>>>24]^b[o>>16&255]^m[c>>8&255]^y[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 r8{static encrypt(e,t){let r=r8.buf2Words(t),i=r8.buf2Words(e),n=new r2(r).encrypt(i);return r8.words2Buf(n)}static decrypt(e,t){let r=r8.buf2Words(e),i=new r2(r8.buf2Words(t)).decrypt(r);return r8.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 r3{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=r3.pkcs7Pad(a,t)),i.push(a)}return i}static blockBufs2Buf(e){let t=e[e.length-1];return t=r3.pkcs7Unpad(t),e[e.length-1]=t,e.flat()}static encrypt(e,t,r,i){let n=8*t.length,a=r3.buf2BlocksBuf(e,n);return r3.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=r3.decryptBlocks(a,t,r,i);return r3.blockBufs2Buf(s)}static encryptBlock(e,t,r,i){let n=r3.xorBufs(e,t);return r.encrypt(n,i)}static decryptBlock(e,t,r,i){let n=r.decrypt(e,i);return r3.xorBufs(n,t)}static encryptBlocks(e,t,r,i){let n=[];for(let a=0;a<e.length;a++){let s=e[a],o=r3.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=r3.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),eQ(r)!==eQ(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 r6{static encrypt(e,t,r,i=!0){r=r??tL(16);let n=r3.encrypt(e,r,r8,t);return i?[...r,...n]:[...n]}static decrypt(e,t,r){if(null!=r)return r3.decrypt(e,r,r8,t);{r=e.slice(0,16);let i=e.slice(16);return r3.decrypt(i,r,r8,t)}}}class r4{static ivkEkM(e,t){let r=t.mul(e),i=Q(new tD(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=tM.fromRandom()),i||(a=r.toPublicKey().encode(!0));let{iv:s,kE:o,kM:c}=r4.ivkEkM(r,t),l=r6.encrypt(e,o,s,!1),h=e0("BIE1","utf8"),u=er(c,n=null!=a&&a.length>0?[...h,...a,...l]:[...h,...l]);return[...n,...u]}static electrumDecrypt(e,t,r){if("BIE1"!==e6(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=tD.fromString(eQ(n)));else if(null==r)throw Error("Sender public key is required");let{iv:a,kE:s,kM:o}=r4.ivkEkM(t,r),c=e.slice(i,e.length-32),l=e.slice(e.length-32,e.length),h=er(o,e.slice(0,e.length-32));if(eQ(l)!==eQ(h))throw Error("Invalid checksum");return r6.decrypt(c,s,a)}static bitcoreEncrypt(e,t,r,i){null==r&&(r=tM.fromRandom()),null==i&&(i=tL(16));let n=r,a=r.toPublicKey().encode(!0),s=Q(t.mul(n).getX().toArray("be",32)),o=s.slice(0,32),c=s.slice(32,64),l=r6.encrypt(e,o,i),h=er(c,[...l]);return[...a,...l,...h]}static bitcoreDecrypt(e,t){let r=tD.fromString(eQ(e.slice(0,33))).mul(t);if(r.eq(new tE(0,0)))throw Error("P equals 0");let i=Q(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=er(a,s);if(eQ(o)!==eQ(c))throw Error("Invalid checksum");return[...r6.decrypt(s,n)]}}function r5(e,t){let r=new rR(0,[],[],0);return r.outputs=Array(e.vout+1).fill(null),r.outputs[e.vout]={satoshis:e.satoshis,lockingScript:rn.fromHex(e.script)},{sourceTransaction:r,sourceTXID:e.txid,sourceOutputIndex:e.vout,unlockingScriptTemplate:t,sequence:0xffffffff}}class r7{static generate(e,t){let r=this.withDefaultOptions(t);return r9(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)if(t===r9(e,r,i))return!0;return!1}static getCounter(e,t){return Math.floor(Math.floor(e/1e3)/t)}static withDefaultOptions(e){return{digits:2,algorithm:"SHA-1",period:30,timestamp:Date.now(),...e}}static withDefaultValidateOptions(e){return{skew:1,...this.withDefaultOptions(e)}}}function r9(e,t,r){let i=(function(e,t,r){switch(r){case"SHA-1":return new G(e).update(t);case"SHA-256":return new j(e).update(t);case"SHA-512":return new X(e).update(t);default:throw Error("unsupported HMAC algorithm")}})(e,new k(t).toArray("be",8),r.algorithm).digest(),n=15&i[i.length-1];return(0x7fffffff&new k(i.slice(n,n+4)).toNumber()).toString().slice(-r.digits)}(r=s||(s={}))[r.Silent=0]="Silent",r[r.App=1]="App",r[r.Counterparty=2]="Counterparty";class ie{cacheSharedSecret;retrieveCachedSharedSecret;rootKey;identityKey;anyone;constructor(e,t,r){this.cacheSharedSecret=t,this.retrieveCachedSharedSecret=r,this.anyone=new tM(1).toPublicKey(),"anyone"===e?this.rootKey=new tM(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 t4(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=e0(this.computeInvoiceNumber(t,r),"utf8");return er(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 tM(1).toPublicKey():"string"==typeof e?tD.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 it{keyDeriver;cache;maxCacheSize;rootKey;identityKey;constructor(e,t){"anyone"===e?this.rootKey=new tM(1):this.rootKey=e,this.keyDeriver=new ie(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 tD||e instanceof tM?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 ir{keyDeriver;constructor(e){"string"!=typeof e.identityKey&&(e=new it(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 t9().generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),tD.fromString(e.counterparty),tE.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:er(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=er(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data).toString()===e.hmac.toString();if(!t){let e=Error("HMAC is not valid");throw e.code="ERR_INVALID_HMAC",e}return{valid:t}}async createSignature(e){if(null==e.hashToDirectlySign&&null==e.data)throw Error("args.data or args.hashToDirectlySign must be valid");let t=e.hashToDirectlySign??Z(e.data??[]),r=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePrivateKey(e.protocolID,e.keyID,e.counterparty??"anyone");return{signature:tV(new k(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??Z(e.data??[]),r=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf),i=tB(new k(t),tN.fromDER(e.signature),r);if(!i){let e=Error("Signature is not valid");throw e.code="ERR_INVALID_SIGNATURE",e}return{valid:i}}}let ii=ir;class ia{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 is 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)}}(i=o||(o={}))[i.unknownError=1]="unknownError",i[i.unsupportedAction=2]="unsupportedAction",i[i.invalidHmac=3]="invalidHmac",i[i.invalidSignature=4]="invalidSignature",i[i.reviewActions=5]="reviewActions",i[i.invalidParameter=6]="invalidParameter",i[i.insufficientFunds=7]="insufficientFunds";let io=is;class ic{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=e4(tL(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 is(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 il{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 tr,r=e0(this.type,"base64");t.write(r);let i=e0(this.serialNumber,"base64");t.write(i);let n=e0(this.subject,"hex");t.write(n);let a=e0(this.certifier,"hex");t.write(a);let[s,o]=this.revocationOutpoint.split("."),c=e0(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=e0(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e0(r,"utf8");t.writeVarIntNum(n.length),t.write(n)}if(e&&(this.signature??"").length>0){let e=e0(this.signature,"hex");t.write(e)}return t.toArray()}static fromBinary(e){let t,r=new ti(e),i=e4(r.read(32)),n=e4(r.read(32)),a=eQ(r.read(33)),s=eQ(r.read(33)),o=eQ(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=e3(r.read(e)),i=r.readVarIntNum(),n=e3(r.read(i));u[t]=n}if(!r.eof()){let e=r.read();t=tN.fromDER(e).toString("hex")}return new il(i,n,a,s,l,u,t)}async verify(){let e=new ii("anyone"),t=this.toBinary(!1),r=this.signature??"",{valid:i}=await e.verifySignature({signature:e0(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=eQ(r)}static getCertificateFieldEncryptionDetails(e,t){return{protocolID:[2,"certificate field encryption"],keyID:t?`${t} ${e}`:e}}}(n=c||(c={}))[n.createAction=1]="createAction",n[n.signAction=2]="signAction",n[n.abortAction=3]="abortAction",n[n.listActions=4]="listActions",n[n.internalizeAction=5]="internalizeAction",n[n.listOutputs=6]="listOutputs",n[n.relinquishOutput=7]="relinquishOutput",n[n.getPublicKey=8]="getPublicKey",n[n.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",n[n.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",n[n.encrypt=11]="encrypt",n[n.decrypt=12]="decrypt",n[n.createHmac=13]="createHmac",n[n.verifyHmac=14]="verifyHmac",n[n.createSignature=15]="createSignature",n[n.verifySignature=16]="verifySignature",n[n.acquireCertificate=17]="acquireCertificate",n[n.listCertificates=18]="listCertificates",n[n.proveCertificate=19]="proveCertificate",n[n.relinquishCertificate=20]="relinquishCertificate",n[n.discoverByIdentityKey=21]="discoverByIdentityKey",n[n.discoverByAttributes=22]="discoverByAttributes",n[n.isAuthenticated=23]="isAuthenticated",n[n.waitForAuthentication=24]="waitForAuthentication",n[n.getHeight=25]="getHeight",n[n.getHeaderForHeight=26]="getHeaderForHeight",n[n.getNetwork=27]="getNetwork",n[n.getVersion=28]="getVersion";let ih=c;class iu{wire;constructor(e){this.wire=e}async transmit(e,t="",r=[]){let i=new tr;i.writeUInt8(ih[e]);let n=e0(t,"utf8");i.writeUInt8(n.length),i.write(n),r.length>0&&i.write(r);let a=i.toArray(),s=new ti(await this.wire.transmitToWallet(a)),o=s.readUInt8();if(0===o)return s.read();{let e=s.readVarIntNum(),t=e3(s.read(e)),r=s.readVarIntNum();throw new is(t,o,e3(s.read(r)))}}async createAction(e,t){let r=new tr,i=e0(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=e0(t.unlockingScript,"hex");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1),r.writeVarIntNum(t.unlockingScriptLength??0);let e=e0(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=e0(t.lockingScript,"hex");r.writeVarIntNum(e.length),r.write(e),r.writeVarIntNum(t.satoshis);let i=e0(t.outputDescription,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=t.basket&&""!==t.basket){let e=e0(t.basket,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=t.customInstructions&&""!==t.customInstructions){let e=e0(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=e0(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=e0(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=e0(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=e0(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 ti(await this.transmit("createAction",t,r.toArray())),a={};if(1===n.readInt8()&&(a.txid=eQ(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=eQ(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:e4(n.read(r))}}return a}async signAction(e,t){let r=new tr,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=e0(i.unlockingScript,"hex");r.writeVarIntNum(n.length),r.write(n),"number"==typeof i.sequenceNumber?r.writeVarIntNum(i.sequenceNumber):r.writeVarIntNum(-1)}let n=e0(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=e0(t,"hex");r.write(e)}else r.writeVarIntNum(-1);else r.writeInt8(0);let a=new ti(await this.transmit("signAction",t,r.toArray())),s={};if(1===a.readInt8()&&(s.txid=eQ(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=eQ(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,e0(e.reference,"base64")),{aborted:!0}}async listActions(e,t){let r=new tr;for(let t of(r.writeVarIntNum(e.labels.length),e.labels)){let e=e0(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 ti(await this.transmit("listActions",t,r.toArray())),n=i.readVarIntNum(),a=[];for(let e=0;e<n;e++){let e,t=eQ(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:e3(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(e3(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=eQ(i.read(a)));let s=i.readVarIntNum();s>=0&&(t=eQ(i.read(s)));let o=i.readVarIntNum(),l=e3(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=eQ(i.read(s)));let o=1===i.readInt8(),l=i.readVarIntNum(),h=e3(i.read(l)),u=i.readVarIntNum();u>=0&&(t=e3(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(e3(t))}let p=i.readVarIntNum();p>=0&&(r=e3(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 tr;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(e0(t.paymentRemittance.senderIdentityKey,"hex"));let e=e0(t.paymentRemittance.derivationPrefix,"base64");r.writeVarIntNum(e.length),r.write(e);let i=e0(t.paymentRemittance.derivationSuffix,"base64");r.writeVarIntNum(i.length),r.write(i)}else{r.writeUInt8(2);let e=e0(t.insertionRemittance?.basket,"utf8");if(r.writeVarIntNum(e.length),r.write(e),"string"==typeof t.insertionRemittance?.customInstructions&&""!==t.insertionRemittance.customInstructions){let e=e0(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=e0(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=e0(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);let i=e0(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 tr,n=e0(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=e0(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 ti(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=eQ(a.read(t)));let r=a.readVarIntNum();r>=0&&(e.customInstructions=e3(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(e3(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(e3(a.read(e)))}e.labels=t}c.push(e)}return{totalOutputs:s,BEEF:r,outputs:c}}async relinquishOutput(e,t){let r=new tr,i=e0(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 tr,[r,i]=e.split(".");return t.write(e0(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}readOutpoint(e){let t=eQ(e.read(32)),r=e.readVarIntNum();return`${t}.${r}`}async getPublicKey(e,t){let r=new tr;return r.writeUInt8(+!!e.identityKey),e.identityKey?r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)):(r.write(this.encodeKeyRelatedParams(e.protocolID??=[s.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:eQ(await this.transmit("getPublicKey",t,r.toArray()))}}async revealCounterpartyKeyLinkage(e,t){let r=new tr;r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),r.write(e0(e.counterparty,"hex")),r.write(e0(e.verifier,"hex"));let i=new ti(await this.transmit("revealCounterpartyKeyLinkage",t,r.toArray())),n=eQ(i.read(33)),a=eQ(i.read(33)),s=eQ(i.read(33)),o=i.readVarIntNum(),c=e3(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 tr;r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.write(e0(e.verifier,"hex"));let i=new ti(await this.transmit("revealSpecificKeyLinkage",t,r.toArray())),n=eQ(i.read(33)),a=eQ(i.read(33)),s=eQ(i.read(33)),o=i.readUInt8(),c=i.readVarIntNum(),l=e3(i.read(c)),h=i.readVarIntNum(),u=e3(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 tr;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 tr;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 tr;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 tr;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 tr;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 tr;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 tr;a.writeUInt8(e[0]);let s=e0(e[1],"utf8");a.writeVarIntNum(s.length),a.write(s);let o=e0(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(e0(r,"hex")),a.write(this.encodePrivilegedParams(i,n)),a.toArray()}async acquireCertificate(e,t){let r=new tr;r.write(e0(e.type,"base64")),r.write(e0(e.certifier,"hex"));let i=Object.entries(e.fields);for(let[e,t]of(r.writeVarIntNum(i.length),i)){let i=e0(e,"utf8"),n=e0(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(e0(e.serialNumber,"base64")),r.write(this.encodeOutpoint(e.revocationOutpoint??""));let t=e0(e.signature,"hex");r.writeVarIntNum(t.length),r.write(t);let i="certifier"!==e.keyringRevealer?e0(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=e0(n[t],"utf8");r.writeVarIntNum(i.length),r.write(i);let a=e0(e.keyringForSubject?.[n[t]],"base64");r.writeVarIntNum(a.length),r.write(a)}}else{let t=e0(e.certifierUrl,"utf8");r.writeVarIntNum(t.length),r.write(t)}let n=await this.transmit("acquireCertificate",t,r.toArray()),a=il.fromBinary(n);return{...a,signature:a.signature}}encodePrivilegedParams(e,t){let r=new tr;if("boolean"==typeof e?r.writeInt8(+!!e):r.writeInt8(-1),"string"==typeof t){let e=e0(t,"utf8");r.writeInt8(e.length),r.write(e)}else r.writeInt8(-1);return r.toArray()}async listCertificates(e,t){let r=new tr;r.writeVarIntNum(e.certifiers.length);for(let t=0;t<e.certifiers.length;t++)r.write(e0(e.certifiers[t],"hex"));r.writeVarIntNum(e.types.length);for(let t=0;t<e.types.length;t++)r.write(e0(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 ti(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=il.fromBinary(r),s={};if(1===i.readInt8()){let e=i.readVarIntNum();for(let t=0;t<e;t++){let e=i.readVarIntNum(),t=e3(i.read(e)),r=i.readVarIntNum();s[t]=e4(i.read(r))}}let o=i.readVarIntNum();o>0&&(e=e3(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 tr,i=e0(e.certificate.type,"base64");r.write(i);let n=e0(e.certificate.subject,"hex");r.write(n);let a=e0(e.certificate.serialNumber,"base64");r.write(a);let s=e0(e.certificate.certifier,"hex");r.write(s);let o=this.encodeOutpoint(e.certificate.revocationOutpoint??"");r.write(o);let c=e0(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=e0(e,"utf8"),n=e0(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=e0(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}r.write(e0(e.verifier,"hex")),r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let h=new ti(await this.transmit("proveCertificate",t,r.toArray())),u=h.readVarIntNum(),d={};for(let e=0;e<u;e++){let e=h.readVarIntNum(),t=e3(h.read(e)),r=h.readVarIntNum();d[t]=e4(h.read(r))}return{keyringForVerifier:d}}async relinquishCertificate(e,t){let r=new tr,i=e0(e.type,"base64");r.write(i);let n=e0(e.serialNumber,"base64");r.write(n);let a=e0(e.certifier,"hex");return r.write(a),await this.transmit("relinquishCertificate",t,r.toArray()),{relinquished:!0}}parseDiscoveryResult(e){let t=new ti(e),r=t.readVarIntNum(),i=[];for(let e=0;e<r;e++){let e=t.readVarIntNum(),r=t.read(e),n=il.fromBinary(r),a=t.readVarIntNum(),s=e3(t.read(a)),o=t.readVarIntNum(),c=e3(t.read(o)),l=t.readVarIntNum(),h=e3(t.read(l)),u=t.readUInt8(),d={},f=t.readVarIntNum();for(let e=0;e<f;e++){let e=t.readVarIntNum(),r=e3(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=e3(t.read(e)),i=t.readVarIntNum();p[r]=e3(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 tr;r.write(e0(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 tr,i=Object.keys(e.attributes);r.writeVarIntNum(i.length);for(let t=0;t<i.length;t++)r.writeVarIntNum(i[t].length),r.write(e0(i[t],"utf8")),r.writeVarIntNum(e.attributes[i[t]].length),r.write(e0(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 ti(await this.transmit("getHeight",t)).readVarIntNum()}}async getHeaderForHeight(e,t){let r=new tr;return r.writeVarIntNum(e.height),{header:eQ(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:e3(await this.transmit("getVersion",t))}}}class id{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 ti(e),i=r.readUInt8(),n=ih[i];if(void 0===n||""===n)throw Error(`Invalid call code: ${i}`);let a=r.readUInt8();a>0&&(t=e3(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 ip 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 ig=ip;class ib 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 im=ib,iy=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 iw{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 ip(s.reviewActionResults,s.sendWithResults,s.txid,s.tx,s.noSendChange);break;case 6:(e=new ib(s.parameter)).message=s.message;break;case 7:e=new iy(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 iv{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=e4(tL(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 is(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 iI(e){let[t,r]=e.split(".");return{txid:t,vout:Number(r)}}function ik(e){return e??!1}function iS(e,t,r,i){if(void 0!==e)return iO(e,t,r,i)}function ix(e,t,r){if(void 0===e||!Number.isInteger(e)||e<0||e>21e14)throw new im(t,"a valid number of satoshis");if(void 0!==r&&e<r)throw new im(t,`at least ${r} satoshis.`);return e}function iE(e,t,r,i){if(void 0!==e)return iP(e,t,void 0,r,i)}function iP(e,t,r,i,n){if(void 0===e){if(void 0!==r)return r;throw new im(t,"a valid integer")}if(!Number.isInteger(e))throw new im(t,"an integer");if(e=Number(e),void 0!==i&&e<i)throw new im(t,`at least ${i} length.`);if(void 0!==n&&e>n)throw new im(t,`no more than ${n} length.`);return e}function iN(e,t){return iP(e,t,0,0)}function iO(e,t,r,i){let n=e0(e,"utf8").length;if(void 0!==r&&n<r)throw new im(t,`at least ${r} length.`);if(void 0!==i&&n>i)throw new im(t,`no more than ${i} length.`);return e}function iA(e){return iC(e,"basket",1,300)}function i_(e){return iC(e,"label",1,300)}function iT(e){return iC(e,"tag",1,300)}function iC(e,t,r,i){let n=e0(e=e.trim().toLowerCase(),"utf8").length;if(void 0!==r&&n<r)throw new im(t,`at least ${r} length.`);if(void 0!==i&&n>i)throw new im(t,`no more than ${i} length.`);return e}function iR(e,t,r,i){if(void 0!==e)return iV(e,t,r,i)}function iV(e,t,r,i){if(0===(e=e.trim()).length)throw new im(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 im(t,"valid base64 string");n++;continue}throw new im(t,"valid base64 string")}}if(n>2||n>0&&e.length%4!=0)throw new im(t,"valid base64 string");let a=e.length%4;if(0!==a&&a!==4-n)throw new im(t,"valid base64 string");let s=Math.floor(3*(e.length-n)/4);if(void 0!==r&&s<r)throw new im(t,`at least ${r} bytes`);if(void 0!==i&&s>i)throw new im(t,`no more than ${i} bytes`);return e}function iB(e,t,r,i){if(void 0!==e)return iD(e,t,r,i)}function iD(e,t,r,i){if((e=e.trim().toLowerCase()).length%2==1)throw new im(t,`even length, not ${e.length}.`);if(!/^[0-9A-Fa-f]+$/.test(e))throw new im(t,"hexadecimal string.");if(void 0!==r&&e.length<r)throw new im(t,`at least ${r} length.`);if(void 0!==i&&e.length>i)throw new im(t,`no more than ${i} length.`);return e}function iU(e){return(e=e.trim()).length%2!=1&&!!/^[0-9A-Fa-f]+$/.test(e)}function iF(e){if(void 0===e.unlockingScript&&void 0===e.unlockingScriptLength)throw new im("unlockingScript, unlockingScriptLength","at least one valid value.");let t=iB(e.unlockingScript,"unlockingScript"),r=e.unlockingScriptLength??(null!=t?t.length/2:0);if(t&&r!==t.length/2)throw new im("unlockingScriptLength","length unlockingScript if both valid.");return{outpoint:iI(e.outpoint),inputDescription:iO(e.inputDescription,"inputDescription",5,2e3),unlockingScript:t,unlockingScriptLength:r,sequenceNumber:e.sequenceNumber??0xffffffff}}function iL(e){return{lockingScript:iD(e.lockingScript,"lockingScript"),satoshis:ix(e.satoshis,"satoshis"),outputDescription:iO(e.outputDescription,"outputDescription",5,2e3),basket:function(e){if(void 0!==e)return iA(e)}(e.basket),customInstructions:e.customInstructions,tags:(e.tags??[]).map(e=>iT(e))}}function iK(e){let t=null!=e?e:{};return{signAndProcess:t.signAndProcess??!0,acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,knownTxids:t.knownTxids??[],returnTXIDOnly:ik(t.returnTXIDOnly),noSend:ik(t.noSend),noSendChange:(t.noSendChange??[]).map(e=>iI(e)),sendWith:t.sendWith??[],randomizeOutputs:t.randomizeOutputs??!0}}function iH(e,t){let r={description:iO(e.description,"description",5,2e3),inputBEEF:e.inputBEEF,inputs:(e.inputs??[]).map(e=>iF(e)),outputs:(e.outputs??[]).map(e=>iL(e)),lockTime:e.lockTime??0,version:e.version??1,labels:e.labels?.map(e=>i_(e))??[],options:iK(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(i9),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 iq(e){let t=null!=e?e:{};return{acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,returnTXIDOnly:ik(t.returnTXIDOnly),noSend:ik(t.noSend),sendWith:t.sendWith??[]}}function iM(e){let t={spends:e.spends,reference:e.reference,options:iq(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 i$(e){return{reference:iV(e.reference,"reference")}}function iz(e){if(void 0!==e)return{derivationPrefix:iV(e.derivationPrefix,"derivationPrefix"),derivationSuffix:iV(e.derivationSuffix,"derivationSuffix"),senderIdentityKey:iD(e.senderIdentityKey,"senderIdentityKey")}}function iW(e){if(void 0!==e)return{basket:iA(e.basket),customInstructions:iS(e.customInstructions,"customInstructions",0,1e3),tags:(e.tags??[]).map(e=>iT(e))}}function ij(e){if("basket insertion"!==e.protocol&&"wallet payment"!==e.protocol)throw new im("protocol","'basket insertion' or 'wallet payment'");return{outputIndex:iN(e.outputIndex,"outputIndex"),protocol:e.protocol,paymentRemittance:iz(e.paymentRemittance),insertionRemittance:iW(e.insertionRemittance)}}function iG(e){if(void 0!==e){for(let t of(iO(e=e.trim().toLowerCase(),"originator",1,250),e.split(".")))iO(t,"originator part",1,63);return e}}function iX(e){let t={tx:e.tx,outputs:e.outputs.map(e=>ij(e)),description:iO(e.description,"description",5,2e3),labels:(null!=e.labels?e.labels:[]).map(e=>i_(e)),seekPermission:e.seekPermission??!0};try{if(rT.fromBinary(t.tx).txs.length<1)throw new im("tx","at least one transaction to internalize an output from")}catch{throw new im("tx","valid with at least one transaction to internalize an output from")}if(t.outputs.length<1)throw new im("outputs","at least one output to internalize from the transaction");return t}function iJ(e,t){if(void 0!==e)return iY(e,t)}function iY(e,t){let r=e.split(".");if(2!==r.length||!Number.isInteger(Number(r[1])))throw new im(t,"txid as hex string and numeric output index joined with '.'");let i=iD(r[0],`${t} txid`,void 0,64),n=iN(Number(r[1]),`${t} vout`);return`${i}.${n}`}function iZ(e){return{basket:iA(e.basket),output:iY(e.output,"output")}}function iQ(e){return{type:iV(e.type,"type"),serialNumber:iV(e.serialNumber,"serialNumber"),certifier:iD(e.certifier,"certifier")}}function i0(e){return{certifiers:e.certifiers.map(e=>iD(e.trim(),"certifiers"))??[],types:e.types.map(e=>iV(e.trim(),"types"))??[],limit:iP(e.limit,"limit",10,1,1e4),offset:iN(e.offset??0,"offset"),privileged:ik(e.privileged),privilegedReason:iS(e.privilegedReason,"privilegedReason",5,50),partial:void 0}}function i1(e){for(let t of Object.keys(e))iO(t,"field name",1,50);return e}function i2(e){if("issuance"!==e.acquisitionProtocol)throw Error("Only acquire certificate via issuance requests allowed here.");if(e.serialNumber)throw new im("serialNumber",'valid when acquisitionProtocol is "direct"');if(e.signature)throw new im("signature",'valid when acquisitionProtocol is "direct"');if(e.revocationOutpoint)throw new im("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(e.keyringRevealer)throw new im("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null!=e.keyringForSubject)throw new im("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(!e.certifierUrl)throw new im("certifierUrl",'valid when acquisitionProtocol is "issuance"');if(e.privileged&&!e.privilegedReason)throw new im("privilegedReason","valid when 'privileged' is true ");return{type:iV(e.type,"type"),certifier:iD(e.certifier,"certifier"),certifierUrl:e.certifierUrl,fields:i1(e.fields),privileged:ik(e.privileged),privilegedReason:iS(e.privilegedReason,"privilegedReason",5,50),subject:""}}function i8(e){var t;if("direct"!==e.acquisitionProtocol)throw Error("Only acquire direct certificate requests allowed here.");if(!e.serialNumber)throw new im("serialNumber",'valid when acquisitionProtocol is "direct"');if(!e.signature)throw new im("signature",'valid when acquisitionProtocol is "direct"');if(!e.revocationOutpoint)throw new im("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(!e.keyringRevealer)throw new im("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null==e.keyringForSubject)throw new im("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(e.privileged&&!e.privilegedReason)throw new im("privilegedReason","valid when 'privileged' is true ");return{type:iV(e.type,"type"),serialNumber:iV(e.serialNumber,"serialNumber"),certifier:iD(e.certifier,"certifier"),revocationOutpoint:iY(e.revocationOutpoint,"revocationOutpoint"),fields:i1(e.fields),signature:iD(e.signature,"signature"),keyringRevealer:(t=e.keyringRevealer,"certifier"===t?t:iD(t,"keyringRevealer")),keyringForSubject:function(e,t){for(let r of Object.keys(e))iO(r,`${t} field name`,1,50),iV(e[r],`${t} field value`);return e}(e.keyringForSubject,"keyringForSubject"),privileged:ik(e.privileged),privilegedReason:iS(e.privilegedReason,"privilegedReason",5,50),subject:""}}function i3(e){if(e.privileged&&!e.privilegedReason)throw new im("privilegedReason","valid when 'privileged' is true ");return{type:iR(e.certificate.type,"certificate.type"),serialNumber:iR(e.certificate.serialNumber,"certificate.serialNumber"),certifier:iB(e.certificate.certifier,"certificate.certifier"),subject:iB(e.certificate.subject,"certificate.subject"),revocationOutpoint:iJ(e.certificate.revocationOutpoint,"certificate.revocationOutpoint"),signature:iB(e.certificate.signature,"certificate.signature"),fieldsToReveal:(e.fieldsToReveal??[]).map(e=>iO(e,`fieldsToReveal ${e}`,1,50)),verifier:iD(e.verifier,"verifier"),privileged:ik(e.privileged),privilegedReason:iS(e.privilegedReason,"privilegedReason",5,50)}}function i6(e){return{identityKey:iD(e.identityKey,"identityKey",66,66),limit:iP(e.limit,"limit",10,1,1e4),offset:iN(e.offset??0,"offset"),seekPermission:ik(e.seekPermission)}}function i4(e){return{attributes:function(e){for(let t of Object.keys(e))iO(t,`field name ${t}`,1,50);return e}(e.attributes),limit:iP(e.limit,"limit",10,1,1e4),offset:iN(e.offset??0,"offset"),seekPermission:ik(e.seekPermission)}}function i5(e){let t;if(void 0===e.tagQueryMode||"any"===e.tagQueryMode)t="any";else if("all"===e.tagQueryMode)t="all";else throw new im("tagQueryMode","undefined, 'any', or 'all'");return{basket:iO(e.basket,"basket",1,300),tags:(null!=e.tags?e.tags:[]).map(e=>iO(e,"tag",1,300)),tagQueryMode:t,includeLockingScripts:"locking scripts"===e.include,includeTransactions:"entire transactions"===e.include,includeCustomInstructions:ik(e.includeCustomInstructions),includeTags:ik(e.includeTags),includeLabels:ik(e.includeLabels),limit:iP(e.limit,"limit",10,1,1e4),offset:iP(e.offset,"offset",0,void 0,void 0),seekPermission:e.seekPermission??!0,knownTxids:[]}}function i7(e){let t;if(void 0===e.labelQueryMode||"any"===e.labelQueryMode)t="any";else if("all"===e.labelQueryMode)t="all";else throw new im("labelQueryMode","undefined, 'any', or 'all'");return{labels:(null!=e.labels?e.labels:[]).map(e=>i_(e)),labelQueryMode:t,includeLabels:ik(e.includeLabels),includeInputs:ik(e.includeInputs),includeInputSourceLockingScripts:ik(e.includeInputSourceLockingScripts),includeInputUnlockingScripts:ik(e.includeInputUnlockingScripts),includeOutputs:ik(e.includeOutputs),includeOutputLockingScripts:ik(e.includeOutputLockingScripts),limit:iP(e.limit,"limit",10,1,1e4),offset:iP(e.offset,"offset",0,0),seekPermission:e.seekPermission??!0}}let i9="a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a";class ne{substrate;originator;constructor(e="auto",t){"Cicada"===e&&(e=new iu(new id(t))),"window.CWI"===e&&(e=new ia),"XDM"===e&&(e=new ic),"json-api"===e&&(e=new iw(t)),"react-native"===e&&(e=new iv(t)),"secure-json-api"===e&&(e=new iw(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 ia),e(()=>new iw(this.originator,"https://localhost:2121")),e(()=>new iw(this.originator)),e(()=>new iv(this.originator)),e(()=>new iu(new id(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 ic,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 iH(e),await this.connectToSubstrate(),await this.substrate.createAction(e,this.originator)}async signAction(e){return iM(e),await this.connectToSubstrate(),await this.substrate.signAction(e,this.originator)}async abortAction(e){return i$(e),await this.connectToSubstrate(),await this.substrate.abortAction(e,this.originator)}async listActions(e){return i7(e),await this.connectToSubstrate(),await this.substrate.listActions(e,this.originator)}async internalizeAction(e){return iX(e),await this.connectToSubstrate(),await this.substrate.internalizeAction(e,this.originator)}async listOutputs(e){return i5(e),await this.connectToSubstrate(),await this.substrate.listOutputs(e,this.originator)}async relinquishOutput(e){return iZ(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)i8(e);else if("issuance"===e.acquisitionProtocol)i2(e);else throw new ib("acquisitionProtocol",`valid. ${String(e.acquisitionProtocol)} is unrecognized.`);return await this.connectToSubstrate(),await this.substrate.acquireCertificate(e,this.originator)}async listCertificates(e){return i0(e),await this.connectToSubstrate(),await this.substrate.listCertificates(e,this.originator)}async proveCertificate(e){return i3(e),await this.connectToSubstrate(),await this.substrate.proveCertificate(e,this.originator)}async relinquishCertificate(e){return iQ(e),await this.connectToSubstrate(),await this.substrate.relinquishCertificate(e,this.originator)}async discoverByIdentityKey(e){return i6(e),await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(e,this.originator)}async discoverByAttributes(e){return i4(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 nt{wallet;constructor(e){this.wallet=e}decodeOutpoint(e){let t=eQ(e.read(32)),r=e.readVarIntNum();return`${t}.${r}`}encodeOutpoint(e){let t=new tr,[r,i]=e.split(".");return t.write(e0(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}async transmitToWallet(e){let t=new ti(e);try{let e=t.readUInt8(),r=ih[e];if(void 0===r||""===r)throw Error(`Invalid call code: ${e}`);let i=t.readUInt8(),n=t.read(i),a=e3(n);switch(r){case"createAction":{let e={},r=t.readVarIntNum(),i=t.read(r);e.description=e3(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=eQ(e)}else r.unlockingScript=void 0,r.unlockingScriptLength=t.readVarIntNum();let n=t.readVarIntNum(),a=t.read(n);r.inputDescription=e3(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=eQ(n),r.satoshis=t.readVarIntNum();let a=t.readVarIntNum(),s=t.read(a);r.outputDescription=e3(s);let o=t.readVarIntNum();if(o>=0){let e=t.read(o);r.basket=e3(e)}else r.basket=void 0;let c=t.readVarIntNum();if(c>=0){let e=t.read(c);r.customInstructions=e3(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=e3(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=e3(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=eQ(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=eQ(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 tr;if(null!=d.txid&&""!==d.txid?(f.writeInt8(1),f.write(e0(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(e0(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=e0(d.signableTransaction.reference,"base64");f.writeVarIntNum(e.length),f.write(e)}else f.writeInt8(0);let p=new tr;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=eQ(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=e4(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=eQ(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 tr;if(null!=o.txid&&""!==o.txid?(c.writeInt8(1),c.write(e0(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(e0(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 tr;return l.writeUInt8(0),l.write(c.toArray()),l.toArray()}case"abortAction":{let e=t.read(),r=e4(e);await this.wallet.abortAction({reference:r},a);let i=new tr;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(e3(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 tr;for(let e of(l.writeVarIntNum(c.totalActions),c.actions)){let t;switch(l.write(e0(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=e0(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=e0(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=e0(t.sourceLockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);if(void 0!==t.unlockingScript){let e=e0(t.unlockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);let e=e0(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=e0(t.lockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);l.writeInt8(+!!t.spendable);let e=e0(t.outputDescription,"utf8");if(l.writeVarIntNum(e.length),l.write(e),void 0!==t.basket){let e=e0(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=e0(e,"utf8");l.writeVarIntNum(t.length),l.write(t)}else l.writeVarIntNum(-1);if(void 0!==t.customInstructions){let e=e0(t.customInstructions,"utf8");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1)}else l.writeVarIntNum(-1)}let h=new tr;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=eQ(e);let i=t.readVarIntNum(),n=t.read(i);r.paymentRemittance.derivationPrefix=e4(n);let a=t.readVarIntNum(),s=t.read(a);r.paymentRemittance.derivationSuffix=e4(s)}else if(2===i){r.protocol="basket insertion",r.insertionRemittance={};let e=t.readVarIntNum(),i=t.read(e);r.insertionRemittance.basket=e3(i);let n=t.readVarIntNum();if(n>=0){let e=t.read(n);r.insertionRemittance.customInstructions=e3(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(e3(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(e3(t.read(r)))}}let s=t.readVarIntNum();e.description=e3(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 tr;return c.writeUInt8(0),c.toArray()}case"listOutputs":{let e={},r=t.readVarIntNum(),i=t.read(r);e.basket=e3(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(e3(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 tr;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=e0(e.lockingScript,"hex");g.writeVarIntNum(t.length),g.write(t)}else g.writeVarIntNum(-1);if(void 0!==e.customInstructions){let t=e0(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=e0(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=e0(t,"utf8");g.writeVarIntNum(e.length),g.write(e)}else g.writeVarIntNum(-1)}let b=new tr;return b.writeUInt8(0),b.write(g.toArray()),b.toArray()}case"relinquishOutput":{let e={},r=t.readVarIntNum(),i=t.read(r);e.basket=e3(i),e.output=this.decodeOutpoint(t),await this.wallet.relinquishOutput(e,a);let n=new tr;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=e3(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=e3(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 tr;s.writeUInt8(0);let o=e0(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 tr;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 tr;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 tr;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 tr;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 tr;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 tr;return o.writeUInt8(0),o.toArray()}case"isAuthenticated":{let e=await this.wallet.isAuthenticated({},a),t=new tr;return t.writeUInt8(0),t.writeUInt8(+!!e.authenticated),t.toArray()}case"waitForAuthentication":{await this.wallet.waitForAuthentication({},a);let e=new tr;return e.writeUInt8(0),e.toArray()}case"getHeight":{let e=await this.wallet.getHeight({},a),t=new tr;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 tr;i.writeUInt8(0);let n=e0(r.header,"hex");return i.write(n),i.toArray()}case"getNetwork":{let e=await this.wallet.getNetwork({},a),t=new tr;return t.writeUInt8(0),t.writeUInt8(+("mainnet"!==e.network)),t.toArray()}case"getVersion":{let e=await this.wallet.getVersion({},a),t=new tr;t.writeUInt8(0);let r=e0(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=e3(r)}let n=t.read(33);e.counterparty=eQ(n);let s=t.read(33);e.verifier=eQ(s);let o=await this.wallet.revealCounterpartyKeyLinkage(e,a),c=new tr;c.write(e0(o.prover,"hex")),c.write(e0(o.verifier,"hex")),c.write(e0(o.counterparty,"hex"));let l=e0(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 tr;return h.writeUInt8(0),h.write(c.toArray()),h.toArray()}case"revealSpecificKeyLinkage":{let e=this.decodeKeyRelatedParams(t),r=t.read(33);e.verifier=eQ(r);let i=await this.wallet.revealSpecificKeyLinkage(e,a),n=new tr;n.write(e0(i.prover,"hex")),n.write(e0(i.verifier,"hex")),n.write(e0(i.counterparty,"hex")),n.writeUInt8(i.protocolID[0]);let s=e0(i.protocolID[1],"utf8");n.writeVarIntNum(s.length),n.write(s);let o=e0(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 tr;return c.writeUInt8(0),c.write(n.toArray()),c.toArray()}case"acquireCertificate":{let e={},r=t.read(32);e.type=e4(r);let i=t.read(33);e.certifier=eQ(i);let n=t.readVarIntNum();e.fields={};for(let r=0;r<n;r++){let r=t.readVarIntNum(),i=t.read(r),n=e3(i),a=t.readVarIntNum(),s=t.read(a),o=e3(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=e3(r)}let c=t.readUInt8();if(e.acquisitionProtocol=1===c?"direct":"issuance","direct"===e.acquisitionProtocol){let r=t.read(32);e.serialNumber=e4(r),e.revocationOutpoint=this.decodeOutpoint(t);let i=t.readVarIntNum(),n=t.read(i);e.signature=eQ(n);let a=t.readUInt8();if(11===a)e.keyringRevealer="certifier";else{let r=[a].concat(t.read(32));e.keyringRevealer=eQ(r)}let s=t.readVarIntNum();e.keyringForSubject={};for(let r=0;r<s;r++){let r=t.readVarIntNum(),i=t.read(r),n=e3(i),a=t.readVarIntNum(),s=t.read(a),o=e4(s);e.keyringForSubject[n]=o}}else{let r=t.readVarIntNum(),i=t.read(r);e.certifierUrl=e3(i)}let l=await this.wallet.acquireCertificate(e,a),h=new il(l.type,l.serialNumber,l.subject,l.certifier,l.revocationOutpoint,l.fields,l.signature).toBinary(),u=new tr;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(eQ(r))}let i=t.readVarIntNum();e.types=[];for(let r=0;r<i;r++){let r=t.read(32);e.types.push(e4(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=e3(r)}let l=await this.wallet.listCertificates(e,a),h=new tr;for(let e of(h.writeVarIntNum(l.totalCertificates),l.certificates)){let t=new il(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=e0(e,"utf8");h.writeVarIntNum(t.length),h.write(t);let i=e0(r,"base64");h.writeVarIntNum(i.length),h.write(i)}}else h.writeInt8(0);let r=e0(e.verifier,"hex");h.writeVarIntNum(r.length),h.write(r)}let u=new tr;return u.writeUInt8(0),u.write(h.toArray()),u.toArray()}case"proveCertificate":{let e={},r={},i=t.read(32);r.type=e4(i);let n=t.read(33);r.subject=eQ(n);let s=t.read(32);r.serialNumber=e4(s);let o=t.read(33);r.certifier=eQ(o),r.revocationOutpoint=this.decodeOutpoint(t);let c=t.readVarIntNum(),l=t.read(c);r.signature=eQ(l);let h=t.readVarIntNum();r.fields={};for(let e=0;e<h;e++){let e=t.readVarIntNum(),i=t.read(e),n=e3(i),a=t.readVarIntNum(),s=t.read(a),o=e3(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=e3(i);e.fieldsToReveal.push(n)}let d=t.read(33);e.verifier=eQ(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=e3(r)}let g=await this.wallet.proveCertificate(e,a),b=new tr,m=Object.entries(g.keyringForVerifier);for(let[e,t]of(b.writeVarIntNum(m.length),m)){let r=e0(e,"utf8");b.writeVarIntNum(r.length),b.write(r);let i=e0(t,"base64");b.writeVarIntNum(i.length),b.write(i)}let y=new tr;return y.writeUInt8(0),y.write(b.toArray()),y.toArray()}case"relinquishCertificate":{let e={},r=t.read(32);e.type=e4(r);let i=t.read(32);e.serialNumber=e4(i);let n=t.read(33);e.certifier=eQ(n),await this.wallet.relinquishCertificate(e,a);let s=new tr;return s.writeUInt8(0),s.toArray()}case"discoverByIdentityKey":{let e={},r=t.read(33);e.identityKey=eQ(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 tr;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=e3(i),a=t.readVarIntNum(),s=t.read(a),o=e3(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 tr;return l.writeUInt8(0),l.write(c),l.toArray()}default:throw Error(`Method ${r} not implemented`)}}catch(i){let e=new tr;e.writeUInt8("number"==typeof i.code?i.code:1);let t=e0("string"==typeof i.message?i.message:"Unknown error","utf8");e.writeVarIntNum(t.length),e.write(t);let r=e0("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,e3(e.read(r))]}decodeString(e){let t=e.readVarIntNum();return e3(e.read(t))}decodeCounterparty(e){let t=e.readUInt8();return 11===t?"self":12===t?"anyone":0!==t?eQ([t,...e.read(32)]):void 0}serializeDiscoveryResult(e){let t=new tr;for(let r of(t.writeVarIntNum(e.totalCertificates),e.certificates)){let e=new il(r.type,r.serialNumber,r.subject,r.certifier,r.revocationOutpoint,r.fields,r.signature).toBinary();t.writeVarIntNum(e.length),t.write(e);let i=e0(r.certifierInfo.name,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e0(r.certifierInfo.iconUrl,"utf8");t.writeVarIntNum(n.length),t.write(n);let a=e0(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=e0(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e0(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=e0(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e0(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=e3(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=e3(e.read(n)),t}}class nr extends il{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=t4.fromRandom(),l=r.encrypt(e0(c,"utf8"));a[o]=e4(l);let{ciphertext:h}=await e.encrypt({plaintext:r.toArray(),...il.getCertificateFieldEncryptionDetails(o),counterparty:t,privileged:i,privilegedReason:n});s[o]=e4(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,...il.getCertificateFieldEncryptionDetails(h,s),counterparty:r,privileged:o,privilegedReason:c});l[h]=e4(u)}return l}static async issueCertificateForSubject(e,t,r,i,n=async e=>"Certificate revocation not tracked.",a){let s=a??e4(tL(32)),{certificateFields:o,masterKeyring:c}=await this.createCertificateFields(e,t,r),l=await n(s),h=new nr(i,s,t,(await e.getPublicKey({identityKey:!0})).publicKey,l,o,c);return await h.sign(e),h}static async decryptFields(e,t,r,i,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:e0(t[r],"base64"),...il.getCertificateFieldEncryptionDetails(r),counterparty:n,privileged:a,privilegedReason:s}),c=new t4(o).decrypt(e0(i,"base64"));return{fieldRevelationKey:o,decryptedFieldValue:e3(c)}}catch{throw Error("Failed to decrypt certificate field!")}}}class ni extends il{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 ni(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:e0(this.keyring[a],"base64"),...il.getCertificateFieldEncryptionDetails(a,this.serialNumber),counterparty:this.subject,privileged:t,privilegedReason:r},i),o=new t4(s).decrypt(e0(this.fields[a],"base64"));n[a]=e3(o)}return n}catch(e){throw Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(e instanceof Error?e.message:e)}`)}}}class nn extends ii{keyDeriver;constructor(e){if(super(e),e instanceof ie)this.keyDeriver=e;else if("string"==typeof e||e instanceof tM)this.keyDeriver=new it(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 na{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 ns(e,t,r="self",i){let n=e0(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:e3(a),counterparty:r},i);return o}async function no(e,t="self",r){let i=tL(16),{hmac:n}=await e.createHmac({protocolID:[2,"server hmac"],keyID:e3(i),data:i,counterparty:t},r);return e4([...i,...n])}let nc=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 ni(n.type,n.serialNumber,n.subject,n.certifier,n.revocationOutpoint,n.fields,a,n.signature)}))},nl=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 ni(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)}))},nh="undefined"!=typeof globalThis?globalThis.Buffer:void 0;class nu{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 na,!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),n=e4(tL(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=e4(tL(32)),{signature:a}=await this.wallet.createSignature({data:nu.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();this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:r,peerIdentityKey:e,lastUpdate:i});let n={version:"0.1",messageType:"initialRequest",identityKey:await this.getIdentityPublicKey(),initialNonce:r,requestedCertificates:this.certificatesToRequest};return await this.transport.send(n),await this.waitForInitialResponse(r,t)}async waitForInitialResponse(e,t=1e4){return await new Promise((r,i)=>{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`);switch(e.messageType){case"initialRequest":await this.processInitialRequest(e);break;case"initialResponse":await this.processInitialResponse(e);break;case"certificateRequest":await this.processCertificateRequest(e);break;case"certificateResponse":await this.processCertificateResponse(e);break;case"general":await this.processGeneralMessage(e);break;default:throw Error(`Unknown message type of ${String(e.messageType)} from ${String(e.identityKey)}`)}}async processInitialRequest(e){let t;if("string"!=typeof e.identityKey||"string"!=typeof e.initialNonce||""===e.initialNonce)throw Error("Missing required fields in initialRequest message.");let r=await no(this.wallet,void 0,this.originator),i=Date.now();this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:r,peerNonce:e.initialNonce,peerIdentityKey:e.identityKey,lastUpdate:i}),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)}):t=await nc(this.wallet,e.requestedCertificates,e.identityKey,this.originator));let{signature:n}=await this.wallet.createSignature({data:nu.base64ToBytes(e.initialNonce+r),protocolID:[2,"auth message signature"],keyID:`${e.initialNonce} ${r}`,counterparty:e.identityKey},this.originator),a={version:"0.1",messageType:"initialResponse",identityKey:await this.getIdentityPublicKey(),initialNonce:r,yourNonce:e.initialNonce,certificates:t,requestedCertificates:this.certificatesToRequest,signature:n};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=e.identityKey),await this.transport.send(a)}async processInitialResponse(e){if(!await ns(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=nu.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.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.certificatesToRequest?.certifiers?.length>0&&e.certificates?.length>0&&(await nl(this.wallet,e,this.certificatesToRequest,this.originator),this.onCertificatesReceivedCallbacks.forEach(t=>t(e.identityKey,e.certificates))),this.lastInteractedWithPeer=e.identityKey,this.onInitialResponseReceivedCallbacks.forEach(e=>{e.sessionNonce===t.sessionNonce&&e.callback(t.sessionNonce)}),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)});else{let t=await nc(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async processCertificateRequest(e){if(!await ns(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:nu.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 nc(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=e4(tL(32)),{signature:n}=await this.wallet.createSignature({data:nu.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 ns(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:nu.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 nl(this.wallet,e,e.requestedCertificates,this.originator),this.onCertificatesReceivedCallbacks.forEach(t=>{t(e.identityKey,e.certificates??[])}),t.lastUpdate=Date.now(),this.sessionManager.updateSession(t)}async processGeneralMessage(e){if(!await ns(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for general message from: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let{valid:r}=await this.wallet.verifySignature({data:e.payload,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!r)throw Error(`Invalid signature in generalMessage from ${t.peerIdentityKey}`);t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.lastInteractedWithPeer=e.identityKey,this.onGeneralMessageReceivedCallbacks.forEach(t=>{t(e.identityKey,e.payload??[])})}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!=nh?Array.from(nh.from(e,"utf8")):"undefined"!=typeof TextEncoder?Array.from(new TextEncoder().encode(e)):e0(e,"utf8")}static base64ToBytes(e){return null!=nh?Array.from(nh.from(e,"base64")):e0(e,"base64")}}let nd="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch;class nf{onDataCallback;fetchClient;baseUrl;constructor(e,t=nd){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"]=eQ(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=e3(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 tr;null!=t.headers.get("x-bsv-auth-request-id")&&c.write(e0(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=e0(l[e][0],"utf8");c.writeVarIntNum(t.length),c.write(t);let r=e0(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:e0(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=e3(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 ti(e),i=e4(r.read(32)),n=r.readVarIntNum(),a="GET";n>0&&(a=e3(r.read(n)));let s=r.readVarIntNum(),o="";s>0&&(o=e3(r.read(s)));let c=r.readVarIntNum(),l="";c>0&&(l=e3(r.read(c)));let h={},u=r.readVarIntNum();if(u>0)for(let e=0;e<u;e++){let e=r.readVarIntNum(),t=e3(r.read(e)),i=r.readVarIntNum(),n=e3(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 np{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;originator;peers={};constructor(e,t,r,i){this.wallet=e,this.requestedCertificates=t,this.sessionManager=r??new na,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 nf(l);n={peer:new nu(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 nc(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=tL(32),u=e4(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 ti(t);if(e4(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=e3(t),n=i.readVarIntNum(),a=i.read(n),o=e3(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 nf(i);r={peer:new nu(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 tr;if(a.write(n),a.writeVarIntNum(e.length),a.write(e0(e)),i.pathname.length>0){let e=e0(i.pathname);a.writeVarIntNum(e.length),a.write(e)}else a.writeVarIntNum(-1);if(i.search.length>0){let e=e0(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=e0(s[e][0],"utf8");a.writeVarIntNum(t.length),a.write(t);let r=e0(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 ru().lock(tD.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:e4(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:e0(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:e0(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:e0(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 e0(JSON.stringify(e,"utf8"));if(Array.isArray(e)&&e.every(e=>"number"==typeof e))return e;if("string"==typeof e)return e0(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()])}),e0(new URLSearchParams(t).toString(),"utf8")}if(e instanceof URLSearchParams)return e0(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 ng{pushDrop;static decode(e){let t=rp.decode(e);if(t.fields.length<4)throw Error("Invalid SHIP/SLAP advertisement!");let r=e3(t.fields[0]);if("SHIP"!==r&&"SLAP"!==r)throw Error("Invalid protocol type!");let i=eQ(t.fields[1]);return{protocol:r,identityKey:i,domain:e3(t.fields[2]),topicOrService:e3(t.fields[3])}}constructor(e,t){this.pushDrop=new rp(e,t)}async lock(e,t,r){let{publicKey:i}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([e0(e,"utf8"),e0(i,"hex"),e0(t,"utf8"),e0(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 nb="bsvsdk_overlay_host_reputation_v1";class nm{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(nb);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(nb,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 ny=new nm,nw="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch,nv=["https://overlay-us-1.bsvb.tech","https://overlay-eu-1.bsvb.tech","https://overlay-ap-1.bsvb.tech","https://users.bapp.dev"],nI=["https://testnet-users.bapp.dev"];class nk{fetchClient;allowHTTP;constructor(e=nw,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 ti([...new Uint8Array(e)]),r=t.readVarIntNum(),i=[];for(let e=0;e<r;e++){let e,r=eQ(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:rR.fromBEEF(a,e.txid).toBEEF()}))}}}catch(e){if(e?.name==="AbortError")throw Error("Request timed out");throw e}finally{clearTimeout(n)}}}class nS{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;hostReputation;hostsCache;hostsInFlight;hostsTtlMs;hostsMaxEntries;txMemo;txMemoTtlMs;constructor(e={}){this.networkPreset=e.networkPreset??"mainnet",this.facilitator=e.facilitator??new nk(void 0,"local"===this.networkPreset),this.slapTrackers=e.slapTrackers??("mainnet"===this.networkPreset?nv:nI);const t=e.hostOverrides??{};this.assertValidOverrideServices(t),this.hostOverrides=t,this.additionalHosts=e.additionalHosts??{};const r=e.reputationStorage;"localStorage"===r?this.hostReputation=new nm:"object"==typeof r&&null!==r&&"function"==typeof r.get&&"function"==typeof r.set?this.hostReputation=new nm(r):this.hostReputation=ny,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:rR.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=rR.fromBEEF(t.beef),i=r.outputs[t.outputIndex]?.lockingScript;if("object"!=typeof i||null===i)continue;let a=ng.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 nx{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 tr;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 nE{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 nx(void 0,"local"===this.networkPreset),this.resolver=t.resolver??new nS({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=rR.fromBEEF(r.beef).outputs[r.outputIndex].lockingScript,i=ng.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 nP(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=rR.fromBEEF(n.competingBeef,n.competingTxs[0]);await nP(async()=>await t.broadcast(e),t,r-i);continue}}throw e}}throw Error("Unexpected end of retry loop")}let nN=e=>(e.toLowerCase().startsWith("uhrp:")&&(e=e.slice(5)),e.startsWith("//")&&(e=e.slice(2)),e),nO=e=>{if(32!==e.length)throw Error("Hash length must be 32 bytes (sha256)");return te(e,e0("ce00","hex"))},nA=e=>{let t=e instanceof Uint8Array?e:Uint8Array.from(e),r=new $;for(let e=0;e<t.length;e+=1048576){let i=t.subarray(e,e+1048576);r.update(Array.from(i))}return nO(r.digest())},n_=e=>{let{data:t,prefix:r}=tt(e=nN(e),void 0,2);if(32!==t.length)throw Error("Invalid length!");if("ce00"!==eQ(r))throw Error("Bad prefix");return t},nT=e=>{try{return n_(e),!0}catch(e){return!1}};class nC{authFetch;baseURL;constructor(e){this.baseURL=e.storageURL,this.authFetch=new np(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:nA(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 nR{networkPreset="mainnet";lookupResolver;constructor(e){this.networkPreset=e?.networkPreset??"mainnet",this.lookupResolver=new nS({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=rR.fromBEEF(t.outputs[e].beef),{fields:a}=rp.decode(n.outputs[t.outputs[e].outputIndex].lockingScript);new ti(a[3]).readVarIntNum()<i||r.push(e3(a[2]))}return r}async download(e){if(!nT(e))throw Error("Invalid parameter UHRP url");let t=eQ(n_(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 $,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(eQ(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 nV={name:"Unknown Identity",avatarURL:"XUUB8bbn9fEthk15Ge3zTQXypUShfC94vFjp65v7u5CQ8qkpxzst",identityKey:"",abbreviatedKey:"",badgeIconURL:"XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",badgeLabel:"Not verified by anyone you trust.",badgeClickURL:"https://projectbabbage.com/docs/unknown-identity"},nB={protocolID:[1,"identity"],keyID:"1",tokenAmount:1,outputIndex:0},nD={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="},nU=[2,"contact"];class nF{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 nL{wallet;cache=new nF;CONTACTS_CACHE_KEY="metanet-contacts";originator;constructor(e,t){this.wallet=e??new ne,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:nU,keyID:e,counterparty:"self",data:e0(e,"utf8")},this.originator);i.push(`identityKey ${eQ(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=rp.decode(rn.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:nU,keyID:r,counterparty:"self"},this.originator),n=JSON.parse(e3(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:nU,keyID:e.identityKey,counterparty:"self",data:e0(e.identityKey,"utf8")},this.originator),o=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:[`identityKey ${eQ(s)}`],limit:100},this.originator),c=null,l=e4(tL(32));if(null!=o.outputs)for(let t of o.outputs)try{let[r,i]=t.outpoint.split("."),n=rR.fromBEEF(o.BEEF,r),a=rp.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:nU,keyID:l,counterparty:"self"},this.originator);if(JSON.parse(e3(s)).identityKey===e.identityKey){c=t;break}}catch(e){}let h={...e,metadata:t},{ciphertext:u}=await this.wallet.encrypt({plaintext:e0(JSON.stringify(h),"utf8"),protocolID:nU,keyID:l,counterparty:"self"},this.originator),d=await new rp(this.wallet,this.originator).lock([u],nU,l,"self");if(null!=c){let[t,r]=String(c.outpoint).split("."),i=`${t}.${r}`,n=new rp(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 ${eQ(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(nU,l,"self"),u=await h.sign(rR.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 ${eQ(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:nU,keyID:e,counterparty:"self",data:e0(e,"utf8")},this.originator);r.push(`identityKey ${eQ(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=rR.fromBEEF(n.BEEF,r),s=rp.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:nU,keyID:o,counterparty:"self"},this.originator);if(JSON.parse(e3(c)).identityKey===e){let e=`${r}.${i}`,t=new rp(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(nU,o,"self"),c=await s.sign(rR.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 nK{options;originator;wallet;contactsManager;constructor(e,t=nB,r){this.options=t,this.originator=r,this.originator=r,this.wallet=e??new ne,this.contactsManager=new nL(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 il(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 tM(1).toPublicKey().toString()},this.originator),i=await new rp(this.wallet,this.originator).lock([e0(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 nE(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network});return await e.broadcast(rR.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=>nK.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)??nK.parseIdentity(e))}async revokeCertificateRevelation(e){let t=new nS({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 nE(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network,requireAcknowledgmentFromAllHostsForTopics:[],requireAcknowledgmentFromAnyHostForTopics:[],requireAcknowledgmentFromSpecificHostsForTopics:{tm_identity:[]}});await nP(async()=>{let e=rR.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=rR.fromBEEF(n.tx),s=new rp(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(rR.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 nD.xCert:t=o.userName,r=o.profilePhoto,i=`X account certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case nD.discordCert:t=o.userName,r=o.profilePhoto,i=`Discord account certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case nD.emailCert:t=o.email,r="XUTZxep7BBghAJbSBwTjNfmcsDdRFs5EaGEgkESGSgjJVYgMEizu",i=`Email certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case nD.phoneCert:t=o.phoneNumber,r="XUTLxtX3ELNUwRhLwL7kWNGbdnFM8WG2eSLv84J7654oH8HaJWrU",i=`Phone certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case nD.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 nD.registrant:t=o.name,r=o.icon,i=`Entity certified by ${c.name}`,n=c.iconUrl,a="https://projectbabbage.com/docs/registrant";break;case nD.coolCert:t="true"===o.cool?"Cool Person!":"Not cool!";break;case nD.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 nD.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=nK.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=nK.hasValue(i)&&nK.hasValue(n)?`${i} ${n}`:nK.hasValue(i)?i:nK.hasValue(n)?n:void 0,s=nK.hasValue(t.name)?t.name:nK.hasValue(t.userName)?t.userName:a??(nK.hasValue(t.email)?t.email:nV.name),o=nK.hasValue(t.profilePhoto)?t.profilePhoto:nK.hasValue(t.avatar)?t.avatar:nK.hasValue(t.icon)?t.icon:nK.hasValue(t.photo)?t.photo:nV.avatarURL,c=nK.hasValue(r?.name)?`${e} certified by ${String(r.name)}`:nV.badgeLabel;return{name:s,avatarURL:o,badgeLabel:c,badgeIconURL:nK.hasValue(r?.iconUrl)?r.iconUrl:nV.badgeIconURL,badgeClickURL:nV.badgeClickURL}}}class nH{wallet;originator;network;resolver;cachedIdentityKey;acceptDelayedBroadcast;constructor(e=new ne,t={},r){this.wallet=e,this.originator=r,this.acceptDelayedBroadcast=t.acceptDelayedBroadcast??!1,this.resolver=t.resolver??new nS}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 rp(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 nE([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await o.broadcast(rR.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=rR.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=rR.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=rR.fromAtomicBEEF(n.tx),s=new rp(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 nE([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await l.broadcast(rR.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 rp(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=rR.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 nE([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await p.broadcast(rR.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=>e0(e))}async parseLockingScript(e,t){let r,i,n=rp.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=e3(c),i={definitionType:"basket",basketID:e3(e),name:e3(t),iconURL:e3(a),description:e3(s),documentationURL:e3(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=e3(c),i={definitionType:"protocol",protocolID:nq(e3(e)),name:e3(t),iconURL:e3(a),description:e3(s),documentationURL:e3(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=e3(l);let h={};try{h=JSON.parse(e3(c))}catch{}i={definitionType:"certificate",type:e3(e),name:e3(t),iconURL:e3(a),description:e3(s),documentationURL:e3(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 nq(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 nM{wallet;context;encrypt;originator;acceptDelayedBroadcast=!1;keyLocks=new Map;constructor(e=new ne,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,rT.fromBinary(n.BEEF)),t=rp.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=e3(t)}else a.value=e3(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=rR.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=e0(t,"utf8");if(this.encrypt){let{ciphertext:e}=await this.wallet.encrypt({...n,plaintext:a},this.originator);a=e}let s=new rp(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 rp(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 n${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 nz={protocolID:0,key:1,value:2,controller:3,tags:4,signature:5},nW=async(e,t,r)=>{try{let i=e.outputs[t];if(null==i||null==i.lockingScript||null==r||null==r.key)return;let n=rp.decode(i.lockingScript),a=Object.keys(nz).length,s=n.fields.length===a;if(n.fields.length!==a-1&&!s)return;let o=e3(n.fields[nz.key]),c=e3(n.fields[nz.protocolID]);if(o!==r.key||c!==JSON.stringify(r.protocolID))return;try{return e3(n.fields[nz.value])}catch{return}}catch{return}},nj={protocolID:[1,"kvstore"],serviceName:"ls_kvstore",tokenAmount:1,topics:["tm_kvstore"],networkPreset:"mainnet",acceptDelayedBroadcast:!1,overlayBroadcast:!1,tokenSetDescription:"",tokenUpdateDescription:"",tokenRemovalDescription:""};class nG{wallet;config;historian;lookupResolver;topicBroadcaster;keyLocks=new Map;cachedIdentityKey=null;constructor(e={}){this.config={...nj,...e},this.wallet=e.wallet??new ne,this.historian=new n$(nW),this.lookupResolver=new nS({networkPreset:this.config.networkPreset}),this.topicBroadcaster=new nE(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 rp(this.wallet,this.config.originator),n=[e0(JSON.stringify(a),"utf8"),e0(e,"utf8"),e0(t,"utf8"),e0(i,"hex")];l.length>0&&n.push(e0(JSON.stringify(l),"utf8"));let h=await r.lock(n,a??this.config.protocolID,e3(e0(e,"utf8")),"anyone",!0);return await nP(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=rR.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=rR.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=rR.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 rp(this.wallet,this.config.originator);return await nP(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=rR.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=rR.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=rR.fromBEEF(e.beef),a=n.outputs[e.outputIndex],s=rp.decode(a.lockingScript),o=Object.keys(nz).length,c=s.fields.length===o;if(s.fields.length!==o-1&&!c)continue;let l=new ir("anyone"),h=s.fields.pop();try{await l.verifySignature({data:s.fields.reduce((e,t)=>[...e,...t],[]),signature:h,counterparty:eQ(s.fields[nz.controller]),protocolID:JSON.parse(e3(s.fields[nz.protocolID])),keyID:e3(s.fields[nz.key])})}catch(e){continue}if(c&&null!=s.fields[nz.tags])try{r=JSON.parse(e3(s.fields[nz.tags]))}catch(e){r=void 0}let u={key:e3(s.fields[nz.key]),value:e3(s.fields[nz.value]),controller:eQ(s.fields[nz.controller]),protocolID:JSON.parse(e3(s.fields[nz.protocolID])),tags:r};!0===t.includeToken&&(u.token={txid:n.id("hex"),outputIndex:e.outputIndex,beef:rT.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 nX=nG;return h})());
|
|
19
|
+
`);return e}addComputedLeaves(){let e=e=>eQ(ee(e0(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 rC="undefined"!=typeof globalThis?globalThis.Buffer:void 0;class rR{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}=rR.fromAnyBeef(e,t);return r}static fromAtomicBEEF(e){let{tx:t,txid:r,beef:i}=rR.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=rT.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 ti(e),r=t.readUInt32LE();if("0000000000ef"!==eQ(t.read(6)))throw Error("Invalid EF marker");let i=t.readVarIntNum(),n=[];for(let e=0;e<i;e++){let e=eQ(t.readReverse(32)),r=t.readUInt32LE(),i=t.readVarIntNum(),a=t.read(i),s=ra.fromBinary(a),o=t.readUInt32LE(),c=t.readUInt64LEBn().toNumber(),l=t.readVarIntNum(),h=t.read(l),u=rn.fromBinary(h),d=new rR(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=rn.fromBinary(i);s.push({satoshis:e,lockingScript:n})}return new rR(r,n,s,t.readUInt32LE())}static parseScriptOffsets(e){let t=new ti(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=eQ(e.readReverse(32)),r=e.readUInt32LE(),n=e.readVarIntNum(),a=e.read(n),s=ra.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=rn.fromBinary(i);a.push({satoshis:t,lockingScript:n})}return new rR(t,i,a,e.readUInt32LE())}static fromBinary(e){let t=e.slice(),r=Uint8Array.from(t),i=new ti(t),n=rR.fromReader(i);return n.rawBytesCache=r,n}static fromHex(e){let t=e0(e,"hex"),r=Uint8Array.from(t),i=new ti(t),n=rR.fromReader(i);return n.rawBytesCache=r,n.hexCache=null!=rC?rC.from(r).toString("hex"):eQ(t),n}static fromHexEF(e){return rR.fromEF(e0(e,"hex"))}static fromHexBEEF(e,t){return rR.fromBEEF(e0(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 ru().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=rb.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=rk()){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(e0(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 tr;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 tr;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(e0(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 eQ(this.toEF())}toHex(){if(null!=this.hexCache)return this.hexCache;let e=this.getSerializedBytes(),t=null!=rC?rC.from(e).toString("hex"):eQ(Array.from(e));return this.hexCache=t,t}toHexBEEF(){return eQ(this.toBEEF())}toHexAtomicBEEF(){return eQ(this.toAtomicBEEF())}hash(e){return(null==this.cachedHash&&(this.cachedHash=ee(this.getSerializedBytes())),"hex"===e)?eQ(this.cachedHash):this.cachedHash}id(e){let t=[...this.hash()];return(t.reverse(),"hex"===e)?eQ(t):t}async verify(e=rx(),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=rR.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 rh({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 tr;t.writeUInt32LE(rO);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 rV(e){return"success"===e.status}function rB(e){return"error"===e.status}let rD=class extends rT{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)?rT.fromBinary(t):t,i=r.getValidTxids();this.mergeBeef(r),this.addKnownTxidsForParty(e,i)}};class rU{network;URL;httpClient;constructor(e="main",t=rw()){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 rF{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 rL{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 rK(){let e={async request(){throw Error("No method available to perform HTTP request")}};if("undefined"!=typeof window&&"function"==typeof window.fetch)return new rL(window.fetch.bind(window));if("undefined"==typeof require)return e;try{let e=require("https");return new rF(e)}catch(t){return e}}class rH{URL;httpClient;constructor(e,t=rK()){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 rq{baseUrl;httpClient;apiKey;constructor(e,t={}){const{httpClient:r,apiKey:i}=t;this.baseUrl=e,this.httpClient=r??rw(),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 rM="42423301",r$=(e,t,r)=>{let i="object"!=typeof r;if(i){let e=new tP,t=new tM(1),i=e.g.mul(t);r=new tD(i.x,i.y)}let n=tL(32),a=e4(n),s=`2-message signing-${a}`,o=t.deriveChild(r,s).sign(e).toDER(),c=t.toPublicKey().encode(!0);return[...e0(rM,"hex"),...c,...i?[0]:r.encode(!0),...n,...o]},rz=(e,t,r)=>{let i=new ti(t),n=eQ(i.read(4));if(n!==rM)throw Error(`Message version mismatch: Expected ${rM}, received ${n}`);let a=tD.fromString(eQ(i.read(33))),[s]=i.read(1);if(0===s)r=new tM(1);else{let e=eQ([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=e4(i.read(32)),c=eQ(i.read(i.bin.length-i.pos)),l=tN.fromDER(c,"hex"),h=`2-message signing-${o}`;return a.deriveChild(r,h).verify(e,l)},rW="42421033",rj=(e,t,r)=>{let i=tL(32),n=e4(i),a=`2-message encryption-${n}`,s=t.deriveChild(r,a),o=r.deriveChild(t,a),c=new t4(s.deriveSharedSecret(o).encode(!0).slice(1)).encrypt(e),l=t.toPublicKey().encode(!0);return[...e0(rW,"hex"),...l,...r.encode(!0),...i,...c]},rG=(e,t)=>{let r=new ti(e),i=eQ(r.read(4));if(i!==rW)throw Error(`Message version mismatch: Expected ${rW}, received ${i}`);let n=tD.fromString(eQ(r.read(33))),a=eQ(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=e4(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 t4(h.deriveSharedSecret(u).encode(!0).slice(1)).decrypt(c)},rX="Bitcoin Signed Message:\n",rJ=e=>{let t=new tr;return t.writeVarIntNum(rX.length),t.write(e0(rX,"utf8")),t.writeVarIntNum(e.length),t.write(e),ee(t.toArray())},rY=(e,t,r="base64")=>{let i=rJ(e),n=tV(new k(i),t,!0);if("raw"===r)return n;let a=new k(i),s=n.CalculateRecoveryFactor(t.toPublicKey(),a);return n.toCompact(s,!0,"base64")},rZ=(e,t,r)=>tB(new k(rJ(e)),t,r);class rQ{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=tL(32),this.privKey=tM.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=tt(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=ei(e0("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 tM(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 ti(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 tM(r.slice(1,33)),this.pubKey=this.privKey.toPublicKey();else if(n&&(2===r[0]||3===r[0]))this.pubKey=tD.fromString(eQ(r));else throw Error("Invalid key");return this}toString(){return te(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=ei(this.chainCode,e),n=new k(t.slice(0,32)),s=t.slice(32,64),o=n.add(this.privKey).mod(new tP().n);(a=new rQ).chainCode=s,a.privKey=new tM(o.toArray()),a.pubKey=a.privKey.toPublicKey()}else{let e=[...this.pubKey.encode(!0),...r],t=ei(this.chainCode,e),i=new k(t.slice(0,32)),n=t.slice(32,64),s=new tP().g.mul(i),o=this.pubKey,c=s.add(o),l=new tD(c.x,c.y);(a=new rQ).chainCode=n,a.pubKey=l}a.childIndex=e;let s=et(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 rQ(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 tr().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 tr().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 r0={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 r1{mnemonic;seed;Wordlist;constructor(e,t,r=r0){this.mnemonic=e??"",this.seed=t??[],this.Wordlist=r}toBinary(){let e=new tr;if(""!==this.mnemonic){let t=e0(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 ti(e),r=t.readVarIntNum();r>0&&(this.mnemonic=e6(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=tL(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=Z(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=Z(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=e0(t,"utf8"),i=[...e0("mnemonic","utf8"),...e0(e,"utf8")];return this.seed=eW(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 r1(e).isValid(t)}}function r2(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]]}r2.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],m=p[2],y=p[3],w=p[4];for(a=0;a<u;a++)r=g[o>>>24]^b[c>>16&255]^m[l>>8&255]^y[255&h]^s[d],i=g[c>>>24]^b[l>>16&255]^m[h>>8&255]^y[255&o]^s[d+1],n=g[l>>>24]^b[h>>16&255]^m[o>>8&255]^y[255&c]^s[d+2],h=g[h>>>24]^b[o>>16&255]^m[c>>8&255]^y[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 r8{static encrypt(e,t){let r=r8.buf2Words(t),i=r8.buf2Words(e),n=new r2(r).encrypt(i);return r8.words2Buf(n)}static decrypt(e,t){let r=r8.buf2Words(e),i=new r2(r8.buf2Words(t)).decrypt(r);return r8.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 r3{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=r3.pkcs7Pad(a,t)),i.push(a)}return i}static blockBufs2Buf(e){let t=e[e.length-1];return t=r3.pkcs7Unpad(t),e[e.length-1]=t,e.flat()}static encrypt(e,t,r,i){let n=8*t.length,a=r3.buf2BlocksBuf(e,n);return r3.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=r3.decryptBlocks(a,t,r,i);return r3.blockBufs2Buf(s)}static encryptBlock(e,t,r,i){let n=r3.xorBufs(e,t);return r.encrypt(n,i)}static decryptBlock(e,t,r,i){let n=r.decrypt(e,i);return r3.xorBufs(n,t)}static encryptBlocks(e,t,r,i){let n=[];for(let a=0;a<e.length;a++){let s=e[a],o=r3.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=r3.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),eQ(r)!==eQ(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 r6{static encrypt(e,t,r,i=!0){r=r??tL(16);let n=r3.encrypt(e,r,r8,t);return i?[...r,...n]:[...n]}static decrypt(e,t,r){if(null!=r)return r3.decrypt(e,r,r8,t);{r=e.slice(0,16);let i=e.slice(16);return r3.decrypt(i,r,r8,t)}}}class r4{static ivkEkM(e,t){let r=t.mul(e),i=Q(new tD(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=tM.fromRandom()),i||(a=r.toPublicKey().encode(!0));let{iv:s,kE:o,kM:c}=r4.ivkEkM(r,t),l=r6.encrypt(e,o,s,!1),h=e0("BIE1","utf8"),u=er(c,n=null!=a&&a.length>0?[...h,...a,...l]:[...h,...l]);return[...n,...u]}static electrumDecrypt(e,t,r){if("BIE1"!==e6(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=tD.fromString(eQ(n)));else if(null==r)throw Error("Sender public key is required");let{iv:a,kE:s,kM:o}=r4.ivkEkM(t,r),c=e.slice(i,e.length-32),l=e.slice(e.length-32,e.length),h=er(o,e.slice(0,e.length-32));if(eQ(l)!==eQ(h))throw Error("Invalid checksum");return r6.decrypt(c,s,a)}static bitcoreEncrypt(e,t,r,i){null==r&&(r=tM.fromRandom()),null==i&&(i=tL(16));let n=r,a=r.toPublicKey().encode(!0),s=Q(t.mul(n).getX().toArray("be",32)),o=s.slice(0,32),c=s.slice(32,64),l=r6.encrypt(e,o,i),h=er(c,[...l]);return[...a,...l,...h]}static bitcoreDecrypt(e,t){let r=tD.fromString(eQ(e.slice(0,33))).mul(t);if(r.eq(new tE(0,0)))throw Error("P equals 0");let i=Q(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=er(a,s);if(eQ(o)!==eQ(c))throw Error("Invalid checksum");return[...r6.decrypt(s,n)]}}function r5(e,t){let r=new rR(0,[],[],0);return r.outputs=Array(e.vout+1).fill(null),r.outputs[e.vout]={satoshis:e.satoshis,lockingScript:rn.fromHex(e.script)},{sourceTransaction:r,sourceTXID:e.txid,sourceOutputIndex:e.vout,unlockingScriptTemplate:t,sequence:0xffffffff}}class r7{static generate(e,t){let r=this.withDefaultOptions(t);return r9(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)if(t===r9(e,r,i))return!0;return!1}static getCounter(e,t){return Math.floor(Math.floor(e/1e3)/t)}static withDefaultOptions(e){return{digits:2,algorithm:"SHA-1",period:30,timestamp:Date.now(),...e}}static withDefaultValidateOptions(e){return{skew:1,...this.withDefaultOptions(e)}}}function r9(e,t,r){let i=(function(e,t,r){switch(r){case"SHA-1":return new G(e).update(t);case"SHA-256":return new j(e).update(t);case"SHA-512":return new X(e).update(t);default:throw Error("unsupported HMAC algorithm")}})(e,new k(t).toArray("be",8),r.algorithm).digest(),n=15&i[i.length-1];return(0x7fffffff&new k(i.slice(n,n+4)).toNumber()).toString().slice(-r.digits)}(r=s||(s={}))[r.Silent=0]="Silent",r[r.App=1]="App",r[r.Counterparty=2]="Counterparty";class ie{cacheSharedSecret;retrieveCachedSharedSecret;rootKey;identityKey;anyone;constructor(e,t,r){this.cacheSharedSecret=t,this.retrieveCachedSharedSecret=r,this.anyone=new tM(1).toPublicKey(),"anyone"===e?this.rootKey=new tM(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 t4(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=e0(this.computeInvoiceNumber(t,r),"utf8");return er(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 tM(1).toPublicKey():"string"==typeof e?tD.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 it{keyDeriver;cache;maxCacheSize;rootKey;identityKey;constructor(e,t){"anyone"===e?this.rootKey=new tM(1):this.rootKey=e,this.keyDeriver=new ie(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 tD||e instanceof tM?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 ir{keyDeriver;constructor(e){"string"!=typeof e.identityKey&&(e=new it(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 t9().generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),tD.fromString(e.counterparty),tE.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:er(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=er(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data).toString()===e.hmac.toString();if(!t){let e=Error("HMAC is not valid");throw e.code="ERR_INVALID_HMAC",e}return{valid:t}}async createSignature(e){if(null==e.hashToDirectlySign&&null==e.data)throw Error("args.data or args.hashToDirectlySign must be valid");let t=e.hashToDirectlySign??Z(e.data??[]),r=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePrivateKey(e.protocolID,e.keyID,e.counterparty??"anyone");return{signature:tV(new k(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??Z(e.data??[]),r=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf),i=tB(new k(t),tN.fromDER(e.signature),r);if(!i){let e=Error("Signature is not valid");throw e.code="ERR_INVALID_SIGNATURE",e}return{valid:i}}}let ii=ir;class ia{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 is 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)}}(i=o||(o={}))[i.unknownError=1]="unknownError",i[i.unsupportedAction=2]="unsupportedAction",i[i.invalidHmac=3]="invalidHmac",i[i.invalidSignature=4]="invalidSignature",i[i.reviewActions=5]="reviewActions",i[i.invalidParameter=6]="invalidParameter",i[i.insufficientFunds=7]="insufficientFunds";let io=is;class ic{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=e4(tL(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 is(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 il{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 tr,r=e0(this.type,"base64");t.write(r);let i=e0(this.serialNumber,"base64");t.write(i);let n=e0(this.subject,"hex");t.write(n);let a=e0(this.certifier,"hex");t.write(a);let[s,o]=this.revocationOutpoint.split("."),c=e0(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=e0(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e0(r,"utf8");t.writeVarIntNum(n.length),t.write(n)}if(e&&(this.signature??"").length>0){let e=e0(this.signature,"hex");t.write(e)}return t.toArray()}static fromBinary(e){let t,r=new ti(e),i=e4(r.read(32)),n=e4(r.read(32)),a=eQ(r.read(33)),s=eQ(r.read(33)),o=eQ(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=e3(r.read(e)),i=r.readVarIntNum(),n=e3(r.read(i));u[t]=n}if(!r.eof()){let e=r.read();t=tN.fromDER(e).toString("hex")}return new il(i,n,a,s,l,u,t)}async verify(){let e=new ii("anyone"),t=this.toBinary(!1),r=this.signature??"",{valid:i}=await e.verifySignature({signature:e0(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=eQ(r)}static getCertificateFieldEncryptionDetails(e,t){return{protocolID:[2,"certificate field encryption"],keyID:t?`${t} ${e}`:e}}static fromObject(e){return new il(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature)}}(n=c||(c={}))[n.createAction=1]="createAction",n[n.signAction=2]="signAction",n[n.abortAction=3]="abortAction",n[n.listActions=4]="listActions",n[n.internalizeAction=5]="internalizeAction",n[n.listOutputs=6]="listOutputs",n[n.relinquishOutput=7]="relinquishOutput",n[n.getPublicKey=8]="getPublicKey",n[n.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",n[n.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",n[n.encrypt=11]="encrypt",n[n.decrypt=12]="decrypt",n[n.createHmac=13]="createHmac",n[n.verifyHmac=14]="verifyHmac",n[n.createSignature=15]="createSignature",n[n.verifySignature=16]="verifySignature",n[n.acquireCertificate=17]="acquireCertificate",n[n.listCertificates=18]="listCertificates",n[n.proveCertificate=19]="proveCertificate",n[n.relinquishCertificate=20]="relinquishCertificate",n[n.discoverByIdentityKey=21]="discoverByIdentityKey",n[n.discoverByAttributes=22]="discoverByAttributes",n[n.isAuthenticated=23]="isAuthenticated",n[n.waitForAuthentication=24]="waitForAuthentication",n[n.getHeight=25]="getHeight",n[n.getHeaderForHeight=26]="getHeaderForHeight",n[n.getNetwork=27]="getNetwork",n[n.getVersion=28]="getVersion";let ih=c;class iu{wire;constructor(e){this.wire=e}async transmit(e,t="",r=[]){let i=new tr;i.writeUInt8(ih[e]);let n=e0(t,"utf8");i.writeUInt8(n.length),i.write(n),r.length>0&&i.write(r);let a=i.toArray(),s=new ti(await this.wire.transmitToWallet(a)),o=s.readUInt8();if(0===o)return s.read();{let e=s.readVarIntNum(),t=e3(s.read(e)),r=s.readVarIntNum();throw new is(t,o,e3(s.read(r)))}}async createAction(e,t){let r=new tr,i=e0(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=e0(t.unlockingScript,"hex");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1),r.writeVarIntNum(t.unlockingScriptLength??0);let e=e0(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=e0(t.lockingScript,"hex");r.writeVarIntNum(e.length),r.write(e),r.writeVarIntNum(t.satoshis);let i=e0(t.outputDescription,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=t.basket&&""!==t.basket){let e=e0(t.basket,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=t.customInstructions&&""!==t.customInstructions){let e=e0(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=e0(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=e0(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=e0(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=e0(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 ti(await this.transmit("createAction",t,r.toArray())),a={};if(1===n.readInt8()&&(a.txid=eQ(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=eQ(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:e4(n.read(r))}}return a}async signAction(e,t){let r=new tr,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=e0(i.unlockingScript,"hex");r.writeVarIntNum(n.length),r.write(n),"number"==typeof i.sequenceNumber?r.writeVarIntNum(i.sequenceNumber):r.writeVarIntNum(-1)}let n=e0(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=e0(t,"hex");r.write(e)}else r.writeVarIntNum(-1);else r.writeInt8(0);let a=new ti(await this.transmit("signAction",t,r.toArray())),s={};if(1===a.readInt8()&&(s.txid=eQ(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=eQ(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,e0(e.reference,"base64")),{aborted:!0}}async listActions(e,t){let r=new tr;for(let t of(r.writeVarIntNum(e.labels.length),e.labels)){let e=e0(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 ti(await this.transmit("listActions",t,r.toArray())),n=i.readVarIntNum(),a=[];for(let e=0;e<n;e++){let e,t=eQ(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:e3(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(e3(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=eQ(i.read(a)));let s=i.readVarIntNum();s>=0&&(t=eQ(i.read(s)));let o=i.readVarIntNum(),l=e3(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=eQ(i.read(s)));let o=1===i.readInt8(),l=i.readVarIntNum(),h=e3(i.read(l)),u=i.readVarIntNum();u>=0&&(t=e3(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(e3(t))}let p=i.readVarIntNum();p>=0&&(r=e3(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 tr;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(e0(t.paymentRemittance.senderIdentityKey,"hex"));let e=e0(t.paymentRemittance.derivationPrefix,"base64");r.writeVarIntNum(e.length),r.write(e);let i=e0(t.paymentRemittance.derivationSuffix,"base64");r.writeVarIntNum(i.length),r.write(i)}else{r.writeUInt8(2);let e=e0(t.insertionRemittance?.basket,"utf8");if(r.writeVarIntNum(e.length),r.write(e),"string"==typeof t.insertionRemittance?.customInstructions&&""!==t.insertionRemittance.customInstructions){let e=e0(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=e0(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=e0(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);let i=e0(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 tr,n=e0(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=e0(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 ti(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=eQ(a.read(t)));let r=a.readVarIntNum();r>=0&&(e.customInstructions=e3(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(e3(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(e3(a.read(e)))}e.labels=t}c.push(e)}return{totalOutputs:s,BEEF:r,outputs:c}}async relinquishOutput(e,t){let r=new tr,i=e0(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 tr,[r,i]=e.split(".");return t.write(e0(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}readOutpoint(e){let t=eQ(e.read(32)),r=e.readVarIntNum();return`${t}.${r}`}async getPublicKey(e,t){let r=new tr;return r.writeUInt8(+!!e.identityKey),e.identityKey?r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)):(r.write(this.encodeKeyRelatedParams(e.protocolID??=[s.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:eQ(await this.transmit("getPublicKey",t,r.toArray()))}}async revealCounterpartyKeyLinkage(e,t){let r=new tr;r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),r.write(e0(e.counterparty,"hex")),r.write(e0(e.verifier,"hex"));let i=new ti(await this.transmit("revealCounterpartyKeyLinkage",t,r.toArray())),n=eQ(i.read(33)),a=eQ(i.read(33)),s=eQ(i.read(33)),o=i.readVarIntNum(),c=e3(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 tr;r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.write(e0(e.verifier,"hex"));let i=new ti(await this.transmit("revealSpecificKeyLinkage",t,r.toArray())),n=eQ(i.read(33)),a=eQ(i.read(33)),s=eQ(i.read(33)),o=i.readUInt8(),c=i.readVarIntNum(),l=e3(i.read(c)),h=i.readVarIntNum(),u=e3(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 tr;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 tr;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 tr;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 tr;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 tr;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 tr;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 tr;a.writeUInt8(e[0]);let s=e0(e[1],"utf8");a.writeVarIntNum(s.length),a.write(s);let o=e0(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(e0(r,"hex")),a.write(this.encodePrivilegedParams(i,n)),a.toArray()}async acquireCertificate(e,t){let r=new tr;r.write(e0(e.type,"base64")),r.write(e0(e.certifier,"hex"));let i=Object.entries(e.fields);for(let[e,t]of(r.writeVarIntNum(i.length),i)){let i=e0(e,"utf8"),n=e0(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(e0(e.serialNumber,"base64")),r.write(this.encodeOutpoint(e.revocationOutpoint??""));let t=e0(e.signature,"hex");r.writeVarIntNum(t.length),r.write(t);let i="certifier"!==e.keyringRevealer?e0(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=e0(n[t],"utf8");r.writeVarIntNum(i.length),r.write(i);let a=e0(e.keyringForSubject?.[n[t]],"base64");r.writeVarIntNum(a.length),r.write(a)}}else{let t=e0(e.certifierUrl,"utf8");r.writeVarIntNum(t.length),r.write(t)}let n=await this.transmit("acquireCertificate",t,r.toArray()),a=il.fromBinary(n);return{...a,signature:a.signature}}encodePrivilegedParams(e,t){let r=new tr;if("boolean"==typeof e?r.writeInt8(+!!e):r.writeInt8(-1),"string"==typeof t){let e=e0(t,"utf8");r.writeInt8(e.length),r.write(e)}else r.writeInt8(-1);return r.toArray()}async listCertificates(e,t){let r=new tr;r.writeVarIntNum(e.certifiers.length);for(let t=0;t<e.certifiers.length;t++)r.write(e0(e.certifiers[t],"hex"));r.writeVarIntNum(e.types.length);for(let t=0;t<e.types.length;t++)r.write(e0(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 ti(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=il.fromBinary(r),s={};if(1===i.readInt8()){let e=i.readVarIntNum();for(let t=0;t<e;t++){let e=i.readVarIntNum(),t=e3(i.read(e)),r=i.readVarIntNum();s[t]=e4(i.read(r))}}let o=i.readVarIntNum();o>0&&(e=e3(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 tr,i=e0(e.certificate.type,"base64");r.write(i);let n=e0(e.certificate.subject,"hex");r.write(n);let a=e0(e.certificate.serialNumber,"base64");r.write(a);let s=e0(e.certificate.certifier,"hex");r.write(s);let o=this.encodeOutpoint(e.certificate.revocationOutpoint??"");r.write(o);let c=e0(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=e0(e,"utf8"),n=e0(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=e0(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}r.write(e0(e.verifier,"hex")),r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let h=new ti(await this.transmit("proveCertificate",t,r.toArray())),u=h.readVarIntNum(),d={};for(let e=0;e<u;e++){let e=h.readVarIntNum(),t=e3(h.read(e)),r=h.readVarIntNum();d[t]=e4(h.read(r))}return{keyringForVerifier:d}}async relinquishCertificate(e,t){let r=new tr,i=e0(e.type,"base64");r.write(i);let n=e0(e.serialNumber,"base64");r.write(n);let a=e0(e.certifier,"hex");return r.write(a),await this.transmit("relinquishCertificate",t,r.toArray()),{relinquished:!0}}parseDiscoveryResult(e){let t=new ti(e),r=t.readVarIntNum(),i=[];for(let e=0;e<r;e++){let e=t.readVarIntNum(),r=t.read(e),n=il.fromBinary(r),a=t.readVarIntNum(),s=e3(t.read(a)),o=t.readVarIntNum(),c=e3(t.read(o)),l=t.readVarIntNum(),h=e3(t.read(l)),u=t.readUInt8(),d={},f=t.readVarIntNum();for(let e=0;e<f;e++){let e=t.readVarIntNum(),r=e3(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=e3(t.read(e)),i=t.readVarIntNum();p[r]=e3(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 tr;r.write(e0(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 tr,i=Object.keys(e.attributes);r.writeVarIntNum(i.length);for(let t=0;t<i.length;t++)r.writeVarIntNum(i[t].length),r.write(e0(i[t],"utf8")),r.writeVarIntNum(e.attributes[i[t]].length),r.write(e0(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 ti(await this.transmit("getHeight",t)).readVarIntNum()}}async getHeaderForHeight(e,t){let r=new tr;return r.writeVarIntNum(e.height),{header:eQ(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:e3(await this.transmit("getVersion",t))}}}class id{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 ti(e),i=r.readUInt8(),n=ih[i];if(void 0===n||""===n)throw Error(`Invalid call code: ${i}`);let a=r.readUInt8();a>0&&(t=e3(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 ip 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 ig=ip;class ib 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 im=ib,iy=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 iw{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 ip(s.reviewActionResults,s.sendWithResults,s.txid,s.tx,s.noSendChange);break;case 6:(e=new ib(s.parameter)).message=s.message;break;case 7:e=new iy(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 iv{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=e4(tL(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 is(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 iI(e){let[t,r]=e.split(".");return{txid:t,vout:Number(r)}}function ik(e){return e??!1}function iS(e,t,r,i){if(void 0!==e)return iO(e,t,r,i)}function ix(e,t,r){if(void 0===e||!Number.isInteger(e)||e<0||e>21e14)throw new im(t,"a valid number of satoshis");if(void 0!==r&&e<r)throw new im(t,`at least ${r} satoshis.`);return e}function iE(e,t,r,i){if(void 0!==e)return iP(e,t,void 0,r,i)}function iP(e,t,r,i,n){if(void 0===e){if(void 0!==r)return r;throw new im(t,"a valid integer")}if(!Number.isInteger(e))throw new im(t,"an integer");if(e=Number(e),void 0!==i&&e<i)throw new im(t,`at least ${i} length.`);if(void 0!==n&&e>n)throw new im(t,`no more than ${n} length.`);return e}function iN(e,t){return iP(e,t,0,0)}function iO(e,t,r,i){let n=e0(e,"utf8").length;if(void 0!==r&&n<r)throw new im(t,`at least ${r} length.`);if(void 0!==i&&n>i)throw new im(t,`no more than ${i} length.`);return e}function iA(e){return iC(e,"basket",1,300)}function i_(e){return iC(e,"label",1,300)}function iT(e){return iC(e,"tag",1,300)}function iC(e,t,r,i){let n=e0(e=e.trim().toLowerCase(),"utf8").length;if(void 0!==r&&n<r)throw new im(t,`at least ${r} length.`);if(void 0!==i&&n>i)throw new im(t,`no more than ${i} length.`);return e}function iR(e,t,r,i){if(void 0!==e)return iV(e,t,r,i)}function iV(e,t,r,i){if(0===(e=e.trim()).length)throw new im(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 im(t,"valid base64 string");n++;continue}throw new im(t,"valid base64 string")}}if(n>2||n>0&&e.length%4!=0)throw new im(t,"valid base64 string");let a=e.length%4;if(0!==a&&a!==4-n)throw new im(t,"valid base64 string");let s=Math.floor(3*(e.length-n)/4);if(void 0!==r&&s<r)throw new im(t,`at least ${r} bytes`);if(void 0!==i&&s>i)throw new im(t,`no more than ${i} bytes`);return e}function iB(e,t,r,i){if(void 0!==e)return iD(e,t,r,i)}function iD(e,t,r,i){if((e=e.trim().toLowerCase()).length%2==1)throw new im(t,`even length, not ${e.length}.`);if(!/^[0-9A-Fa-f]+$/.test(e))throw new im(t,"hexadecimal string.");if(void 0!==r&&e.length<r)throw new im(t,`at least ${r} length.`);if(void 0!==i&&e.length>i)throw new im(t,`no more than ${i} length.`);return e}function iU(e){return(e=e.trim()).length%2!=1&&!!/^[0-9A-Fa-f]+$/.test(e)}function iF(e){if(void 0===e.unlockingScript&&void 0===e.unlockingScriptLength)throw new im("unlockingScript, unlockingScriptLength","at least one valid value.");let t=iB(e.unlockingScript,"unlockingScript"),r=e.unlockingScriptLength??(null!=t?t.length/2:0);if(t&&r!==t.length/2)throw new im("unlockingScriptLength","length unlockingScript if both valid.");return{outpoint:iI(e.outpoint),inputDescription:iO(e.inputDescription,"inputDescription",5,2e3),unlockingScript:t,unlockingScriptLength:r,sequenceNumber:e.sequenceNumber??0xffffffff}}function iL(e){return{lockingScript:iD(e.lockingScript,"lockingScript"),satoshis:ix(e.satoshis,"satoshis"),outputDescription:iO(e.outputDescription,"outputDescription",5,2e3),basket:function(e){if(void 0!==e)return iA(e)}(e.basket),customInstructions:e.customInstructions,tags:(e.tags??[]).map(e=>iT(e))}}function iK(e){let t=null!=e?e:{};return{signAndProcess:t.signAndProcess??!0,acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,knownTxids:t.knownTxids??[],returnTXIDOnly:ik(t.returnTXIDOnly),noSend:ik(t.noSend),noSendChange:(t.noSendChange??[]).map(e=>iI(e)),sendWith:t.sendWith??[],randomizeOutputs:t.randomizeOutputs??!0}}function iH(e,t){let r={description:iO(e.description,"description",5,2e3),inputBEEF:e.inputBEEF,inputs:(e.inputs??[]).map(e=>iF(e)),outputs:(e.outputs??[]).map(e=>iL(e)),lockTime:e.lockTime??0,version:e.version??1,labels:e.labels?.map(e=>i_(e))??[],options:iK(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(i9),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 iq(e){let t=null!=e?e:{};return{acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,returnTXIDOnly:ik(t.returnTXIDOnly),noSend:ik(t.noSend),sendWith:t.sendWith??[]}}function iM(e){let t={spends:e.spends,reference:e.reference,options:iq(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 i$(e){return{reference:iV(e.reference,"reference")}}function iz(e){if(void 0!==e)return{derivationPrefix:iV(e.derivationPrefix,"derivationPrefix"),derivationSuffix:iV(e.derivationSuffix,"derivationSuffix"),senderIdentityKey:iD(e.senderIdentityKey,"senderIdentityKey")}}function iW(e){if(void 0!==e)return{basket:iA(e.basket),customInstructions:iS(e.customInstructions,"customInstructions",0,1e3),tags:(e.tags??[]).map(e=>iT(e))}}function ij(e){if("basket insertion"!==e.protocol&&"wallet payment"!==e.protocol)throw new im("protocol","'basket insertion' or 'wallet payment'");return{outputIndex:iN(e.outputIndex,"outputIndex"),protocol:e.protocol,paymentRemittance:iz(e.paymentRemittance),insertionRemittance:iW(e.insertionRemittance)}}function iG(e){if(void 0!==e){for(let t of(iO(e=e.trim().toLowerCase(),"originator",1,250),e.split(".")))iO(t,"originator part",1,63);return e}}function iX(e){let t={tx:e.tx,outputs:e.outputs.map(e=>ij(e)),description:iO(e.description,"description",5,2e3),labels:(null!=e.labels?e.labels:[]).map(e=>i_(e)),seekPermission:e.seekPermission??!0};try{if(rT.fromBinary(t.tx).txs.length<1)throw new im("tx","at least one transaction to internalize an output from")}catch{throw new im("tx","valid with at least one transaction to internalize an output from")}if(t.outputs.length<1)throw new im("outputs","at least one output to internalize from the transaction");return t}function iJ(e,t){if(void 0!==e)return iY(e,t)}function iY(e,t){let r=e.split(".");if(2!==r.length||!Number.isInteger(Number(r[1])))throw new im(t,"txid as hex string and numeric output index joined with '.'");let i=iD(r[0],`${t} txid`,void 0,64),n=iN(Number(r[1]),`${t} vout`);return`${i}.${n}`}function iZ(e){return{basket:iA(e.basket),output:iY(e.output,"output")}}function iQ(e){return{type:iV(e.type,"type"),serialNumber:iV(e.serialNumber,"serialNumber"),certifier:iD(e.certifier,"certifier")}}function i0(e){return{certifiers:e.certifiers.map(e=>iD(e.trim(),"certifiers"))??[],types:e.types.map(e=>iV(e.trim(),"types"))??[],limit:iP(e.limit,"limit",10,1,1e4),offset:iN(e.offset??0,"offset"),privileged:ik(e.privileged),privilegedReason:iS(e.privilegedReason,"privilegedReason",5,50),partial:void 0}}function i1(e){for(let t of Object.keys(e))iO(t,"field name",1,50);return e}function i2(e){if("issuance"!==e.acquisitionProtocol)throw Error("Only acquire certificate via issuance requests allowed here.");if(e.serialNumber)throw new im("serialNumber",'valid when acquisitionProtocol is "direct"');if(e.signature)throw new im("signature",'valid when acquisitionProtocol is "direct"');if(e.revocationOutpoint)throw new im("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(e.keyringRevealer)throw new im("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null!=e.keyringForSubject)throw new im("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(!e.certifierUrl)throw new im("certifierUrl",'valid when acquisitionProtocol is "issuance"');if(e.privileged&&!e.privilegedReason)throw new im("privilegedReason","valid when 'privileged' is true ");return{type:iV(e.type,"type"),certifier:iD(e.certifier,"certifier"),certifierUrl:e.certifierUrl,fields:i1(e.fields),privileged:ik(e.privileged),privilegedReason:iS(e.privilegedReason,"privilegedReason",5,50),subject:""}}function i8(e){var t;if("direct"!==e.acquisitionProtocol)throw Error("Only acquire direct certificate requests allowed here.");if(!e.serialNumber)throw new im("serialNumber",'valid when acquisitionProtocol is "direct"');if(!e.signature)throw new im("signature",'valid when acquisitionProtocol is "direct"');if(!e.revocationOutpoint)throw new im("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(!e.keyringRevealer)throw new im("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null==e.keyringForSubject)throw new im("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(e.privileged&&!e.privilegedReason)throw new im("privilegedReason","valid when 'privileged' is true ");return{type:iV(e.type,"type"),serialNumber:iV(e.serialNumber,"serialNumber"),certifier:iD(e.certifier,"certifier"),revocationOutpoint:iY(e.revocationOutpoint,"revocationOutpoint"),fields:i1(e.fields),signature:iD(e.signature,"signature"),keyringRevealer:(t=e.keyringRevealer,"certifier"===t?t:iD(t,"keyringRevealer")),keyringForSubject:function(e,t){for(let r of Object.keys(e))iO(r,`${t} field name`,1,50),iV(e[r],`${t} field value`);return e}(e.keyringForSubject,"keyringForSubject"),privileged:ik(e.privileged),privilegedReason:iS(e.privilegedReason,"privilegedReason",5,50),subject:""}}function i3(e){if(e.privileged&&!e.privilegedReason)throw new im("privilegedReason","valid when 'privileged' is true ");return{type:iR(e.certificate.type,"certificate.type"),serialNumber:iR(e.certificate.serialNumber,"certificate.serialNumber"),certifier:iB(e.certificate.certifier,"certificate.certifier"),subject:iB(e.certificate.subject,"certificate.subject"),revocationOutpoint:iJ(e.certificate.revocationOutpoint,"certificate.revocationOutpoint"),signature:iB(e.certificate.signature,"certificate.signature"),fieldsToReveal:(e.fieldsToReveal??[]).map(e=>iO(e,`fieldsToReveal ${e}`,1,50)),verifier:iD(e.verifier,"verifier"),privileged:ik(e.privileged),privilegedReason:iS(e.privilegedReason,"privilegedReason",5,50)}}function i6(e){return{identityKey:iD(e.identityKey,"identityKey",66,66),limit:iP(e.limit,"limit",10,1,1e4),offset:iN(e.offset??0,"offset"),seekPermission:ik(e.seekPermission)}}function i4(e){return{attributes:function(e){for(let t of Object.keys(e))iO(t,`field name ${t}`,1,50);return e}(e.attributes),limit:iP(e.limit,"limit",10,1,1e4),offset:iN(e.offset??0,"offset"),seekPermission:ik(e.seekPermission)}}function i5(e){let t;if(void 0===e.tagQueryMode||"any"===e.tagQueryMode)t="any";else if("all"===e.tagQueryMode)t="all";else throw new im("tagQueryMode","undefined, 'any', or 'all'");return{basket:iO(e.basket,"basket",1,300),tags:(null!=e.tags?e.tags:[]).map(e=>iO(e,"tag",1,300)),tagQueryMode:t,includeLockingScripts:"locking scripts"===e.include,includeTransactions:"entire transactions"===e.include,includeCustomInstructions:ik(e.includeCustomInstructions),includeTags:ik(e.includeTags),includeLabels:ik(e.includeLabels),limit:iP(e.limit,"limit",10,1,1e4),offset:iP(e.offset,"offset",0,void 0,void 0),seekPermission:e.seekPermission??!0,knownTxids:[]}}function i7(e){let t;if(void 0===e.labelQueryMode||"any"===e.labelQueryMode)t="any";else if("all"===e.labelQueryMode)t="all";else throw new im("labelQueryMode","undefined, 'any', or 'all'");return{labels:(null!=e.labels?e.labels:[]).map(e=>i_(e)),labelQueryMode:t,includeLabels:ik(e.includeLabels),includeInputs:ik(e.includeInputs),includeInputSourceLockingScripts:ik(e.includeInputSourceLockingScripts),includeInputUnlockingScripts:ik(e.includeInputUnlockingScripts),includeOutputs:ik(e.includeOutputs),includeOutputLockingScripts:ik(e.includeOutputLockingScripts),limit:iP(e.limit,"limit",10,1,1e4),offset:iP(e.offset,"offset",0,0),seekPermission:e.seekPermission??!0}}let i9="a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a";class ne{substrate;originator;constructor(e="auto",t){"Cicada"===e&&(e=new iu(new id(t))),"window.CWI"===e&&(e=new ia),"XDM"===e&&(e=new ic),"json-api"===e&&(e=new iw(t)),"react-native"===e&&(e=new iv(t)),"secure-json-api"===e&&(e=new iw(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 ia),e(()=>new iw(this.originator,"https://localhost:2121")),e(()=>new iw(this.originator)),e(()=>new iv(this.originator)),e(()=>new iu(new id(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 ic,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 iH(e),await this.connectToSubstrate(),await this.substrate.createAction(e,this.originator)}async signAction(e){return iM(e),await this.connectToSubstrate(),await this.substrate.signAction(e,this.originator)}async abortAction(e){return i$(e),await this.connectToSubstrate(),await this.substrate.abortAction(e,this.originator)}async listActions(e){return i7(e),await this.connectToSubstrate(),await this.substrate.listActions(e,this.originator)}async internalizeAction(e){return iX(e),await this.connectToSubstrate(),await this.substrate.internalizeAction(e,this.originator)}async listOutputs(e){return i5(e),await this.connectToSubstrate(),await this.substrate.listOutputs(e,this.originator)}async relinquishOutput(e){return iZ(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)i8(e);else if("issuance"===e.acquisitionProtocol)i2(e);else throw new ib("acquisitionProtocol",`valid. ${String(e.acquisitionProtocol)} is unrecognized.`);return await this.connectToSubstrate(),await this.substrate.acquireCertificate(e,this.originator)}async listCertificates(e){return i0(e),await this.connectToSubstrate(),await this.substrate.listCertificates(e,this.originator)}async proveCertificate(e){return i3(e),await this.connectToSubstrate(),await this.substrate.proveCertificate(e,this.originator)}async relinquishCertificate(e){return iQ(e),await this.connectToSubstrate(),await this.substrate.relinquishCertificate(e,this.originator)}async discoverByIdentityKey(e){return i6(e),await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(e,this.originator)}async discoverByAttributes(e){return i4(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 nt{wallet;constructor(e){this.wallet=e}decodeOutpoint(e){let t=eQ(e.read(32)),r=e.readVarIntNum();return`${t}.${r}`}encodeOutpoint(e){let t=new tr,[r,i]=e.split(".");return t.write(e0(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}async transmitToWallet(e){let t=new ti(e);try{let e=t.readUInt8(),r=ih[e];if(void 0===r||""===r)throw Error(`Invalid call code: ${e}`);let i=t.readUInt8(),n=t.read(i),a=e3(n);switch(r){case"createAction":{let e={},r=t.readVarIntNum(),i=t.read(r);e.description=e3(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=eQ(e)}else r.unlockingScript=void 0,r.unlockingScriptLength=t.readVarIntNum();let n=t.readVarIntNum(),a=t.read(n);r.inputDescription=e3(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=eQ(n),r.satoshis=t.readVarIntNum();let a=t.readVarIntNum(),s=t.read(a);r.outputDescription=e3(s);let o=t.readVarIntNum();if(o>=0){let e=t.read(o);r.basket=e3(e)}else r.basket=void 0;let c=t.readVarIntNum();if(c>=0){let e=t.read(c);r.customInstructions=e3(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=e3(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=e3(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=eQ(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=eQ(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 tr;if(null!=d.txid&&""!==d.txid?(f.writeInt8(1),f.write(e0(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(e0(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=e0(d.signableTransaction.reference,"base64");f.writeVarIntNum(e.length),f.write(e)}else f.writeInt8(0);let p=new tr;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=eQ(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=e4(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=eQ(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 tr;if(null!=o.txid&&""!==o.txid?(c.writeInt8(1),c.write(e0(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(e0(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 tr;return l.writeUInt8(0),l.write(c.toArray()),l.toArray()}case"abortAction":{let e=t.read(),r=e4(e);await this.wallet.abortAction({reference:r},a);let i=new tr;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(e3(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 tr;for(let e of(l.writeVarIntNum(c.totalActions),c.actions)){let t;switch(l.write(e0(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=e0(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=e0(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=e0(t.sourceLockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);if(void 0!==t.unlockingScript){let e=e0(t.unlockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);let e=e0(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=e0(t.lockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);l.writeInt8(+!!t.spendable);let e=e0(t.outputDescription,"utf8");if(l.writeVarIntNum(e.length),l.write(e),void 0!==t.basket){let e=e0(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=e0(e,"utf8");l.writeVarIntNum(t.length),l.write(t)}else l.writeVarIntNum(-1);if(void 0!==t.customInstructions){let e=e0(t.customInstructions,"utf8");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1)}else l.writeVarIntNum(-1)}let h=new tr;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=eQ(e);let i=t.readVarIntNum(),n=t.read(i);r.paymentRemittance.derivationPrefix=e4(n);let a=t.readVarIntNum(),s=t.read(a);r.paymentRemittance.derivationSuffix=e4(s)}else if(2===i){r.protocol="basket insertion",r.insertionRemittance={};let e=t.readVarIntNum(),i=t.read(e);r.insertionRemittance.basket=e3(i);let n=t.readVarIntNum();if(n>=0){let e=t.read(n);r.insertionRemittance.customInstructions=e3(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(e3(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(e3(t.read(r)))}}let s=t.readVarIntNum();e.description=e3(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 tr;return c.writeUInt8(0),c.toArray()}case"listOutputs":{let e={},r=t.readVarIntNum(),i=t.read(r);e.basket=e3(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(e3(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 tr;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=e0(e.lockingScript,"hex");g.writeVarIntNum(t.length),g.write(t)}else g.writeVarIntNum(-1);if(void 0!==e.customInstructions){let t=e0(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=e0(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=e0(t,"utf8");g.writeVarIntNum(e.length),g.write(e)}else g.writeVarIntNum(-1)}let b=new tr;return b.writeUInt8(0),b.write(g.toArray()),b.toArray()}case"relinquishOutput":{let e={},r=t.readVarIntNum(),i=t.read(r);e.basket=e3(i),e.output=this.decodeOutpoint(t),await this.wallet.relinquishOutput(e,a);let n=new tr;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=e3(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=e3(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 tr;s.writeUInt8(0);let o=e0(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 tr;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 tr;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 tr;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 tr;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 tr;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 tr;return o.writeUInt8(0),o.toArray()}case"isAuthenticated":{let e=await this.wallet.isAuthenticated({},a),t=new tr;return t.writeUInt8(0),t.writeUInt8(+!!e.authenticated),t.toArray()}case"waitForAuthentication":{await this.wallet.waitForAuthentication({},a);let e=new tr;return e.writeUInt8(0),e.toArray()}case"getHeight":{let e=await this.wallet.getHeight({},a),t=new tr;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 tr;i.writeUInt8(0);let n=e0(r.header,"hex");return i.write(n),i.toArray()}case"getNetwork":{let e=await this.wallet.getNetwork({},a),t=new tr;return t.writeUInt8(0),t.writeUInt8(+("mainnet"!==e.network)),t.toArray()}case"getVersion":{let e=await this.wallet.getVersion({},a),t=new tr;t.writeUInt8(0);let r=e0(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=e3(r)}let n=t.read(33);e.counterparty=eQ(n);let s=t.read(33);e.verifier=eQ(s);let o=await this.wallet.revealCounterpartyKeyLinkage(e,a),c=new tr;c.write(e0(o.prover,"hex")),c.write(e0(o.verifier,"hex")),c.write(e0(o.counterparty,"hex"));let l=e0(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 tr;return h.writeUInt8(0),h.write(c.toArray()),h.toArray()}case"revealSpecificKeyLinkage":{let e=this.decodeKeyRelatedParams(t),r=t.read(33);e.verifier=eQ(r);let i=await this.wallet.revealSpecificKeyLinkage(e,a),n=new tr;n.write(e0(i.prover,"hex")),n.write(e0(i.verifier,"hex")),n.write(e0(i.counterparty,"hex")),n.writeUInt8(i.protocolID[0]);let s=e0(i.protocolID[1],"utf8");n.writeVarIntNum(s.length),n.write(s);let o=e0(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 tr;return c.writeUInt8(0),c.write(n.toArray()),c.toArray()}case"acquireCertificate":{let e={},r=t.read(32);e.type=e4(r);let i=t.read(33);e.certifier=eQ(i);let n=t.readVarIntNum();e.fields={};for(let r=0;r<n;r++){let r=t.readVarIntNum(),i=t.read(r),n=e3(i),a=t.readVarIntNum(),s=t.read(a),o=e3(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=e3(r)}let c=t.readUInt8();if(e.acquisitionProtocol=1===c?"direct":"issuance","direct"===e.acquisitionProtocol){let r=t.read(32);e.serialNumber=e4(r),e.revocationOutpoint=this.decodeOutpoint(t);let i=t.readVarIntNum(),n=t.read(i);e.signature=eQ(n);let a=t.readUInt8();if(11===a)e.keyringRevealer="certifier";else{let r=[a].concat(t.read(32));e.keyringRevealer=eQ(r)}let s=t.readVarIntNum();e.keyringForSubject={};for(let r=0;r<s;r++){let r=t.readVarIntNum(),i=t.read(r),n=e3(i),a=t.readVarIntNum(),s=t.read(a),o=e4(s);e.keyringForSubject[n]=o}}else{let r=t.readVarIntNum(),i=t.read(r);e.certifierUrl=e3(i)}let l=await this.wallet.acquireCertificate(e,a),h=new il(l.type,l.serialNumber,l.subject,l.certifier,l.revocationOutpoint,l.fields,l.signature).toBinary(),u=new tr;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(eQ(r))}let i=t.readVarIntNum();e.types=[];for(let r=0;r<i;r++){let r=t.read(32);e.types.push(e4(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=e3(r)}let l=await this.wallet.listCertificates(e,a),h=new tr;for(let e of(h.writeVarIntNum(l.totalCertificates),l.certificates)){let t=new il(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=e0(e,"utf8");h.writeVarIntNum(t.length),h.write(t);let i=e0(r,"base64");h.writeVarIntNum(i.length),h.write(i)}}else h.writeInt8(0);let r=e0(e.verifier,"hex");h.writeVarIntNum(r.length),h.write(r)}let u=new tr;return u.writeUInt8(0),u.write(h.toArray()),u.toArray()}case"proveCertificate":{let e={},r={},i=t.read(32);r.type=e4(i);let n=t.read(33);r.subject=eQ(n);let s=t.read(32);r.serialNumber=e4(s);let o=t.read(33);r.certifier=eQ(o),r.revocationOutpoint=this.decodeOutpoint(t);let c=t.readVarIntNum(),l=t.read(c);r.signature=eQ(l);let h=t.readVarIntNum();r.fields={};for(let e=0;e<h;e++){let e=t.readVarIntNum(),i=t.read(e),n=e3(i),a=t.readVarIntNum(),s=t.read(a),o=e3(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=e3(i);e.fieldsToReveal.push(n)}let d=t.read(33);e.verifier=eQ(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=e3(r)}let g=await this.wallet.proveCertificate(e,a),b=new tr,m=Object.entries(g.keyringForVerifier);for(let[e,t]of(b.writeVarIntNum(m.length),m)){let r=e0(e,"utf8");b.writeVarIntNum(r.length),b.write(r);let i=e0(t,"base64");b.writeVarIntNum(i.length),b.write(i)}let y=new tr;return y.writeUInt8(0),y.write(b.toArray()),y.toArray()}case"relinquishCertificate":{let e={},r=t.read(32);e.type=e4(r);let i=t.read(32);e.serialNumber=e4(i);let n=t.read(33);e.certifier=eQ(n),await this.wallet.relinquishCertificate(e,a);let s=new tr;return s.writeUInt8(0),s.toArray()}case"discoverByIdentityKey":{let e={},r=t.read(33);e.identityKey=eQ(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 tr;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=e3(i),a=t.readVarIntNum(),s=t.read(a),o=e3(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 tr;return l.writeUInt8(0),l.write(c),l.toArray()}default:throw Error(`Method ${r} not implemented`)}}catch(i){let e=new tr;e.writeUInt8("number"==typeof i.code?i.code:1);let t=e0("string"==typeof i.message?i.message:"Unknown error","utf8");e.writeVarIntNum(t.length),e.write(t);let r=e0("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,e3(e.read(r))]}decodeString(e){let t=e.readVarIntNum();return e3(e.read(t))}decodeCounterparty(e){let t=e.readUInt8();return 11===t?"self":12===t?"anyone":0!==t?eQ([t,...e.read(32)]):void 0}serializeDiscoveryResult(e){let t=new tr;for(let r of(t.writeVarIntNum(e.totalCertificates),e.certificates)){let e=new il(r.type,r.serialNumber,r.subject,r.certifier,r.revocationOutpoint,r.fields,r.signature).toBinary();t.writeVarIntNum(e.length),t.write(e);let i=e0(r.certifierInfo.name,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e0(r.certifierInfo.iconUrl,"utf8");t.writeVarIntNum(n.length),t.write(n);let a=e0(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=e0(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e0(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=e0(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e0(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=e3(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=e3(e.read(n)),t}}class nr extends il{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=t4.fromRandom(),l=r.encrypt(e0(c,"utf8"));a[o]=e4(l);let{ciphertext:h}=await e.encrypt({plaintext:r.toArray(),...il.getCertificateFieldEncryptionDetails(o),counterparty:t,privileged:i,privilegedReason:n});s[o]=e4(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,...il.getCertificateFieldEncryptionDetails(h,s),counterparty:r,privileged:o,privilegedReason:c});l[h]=e4(u)}return l}static async issueCertificateForSubject(e,t,r,i,n=async e=>"Certificate revocation not tracked.",a){let s=a??e4(tL(32)),{certificateFields:o,masterKeyring:c}=await this.createCertificateFields(e,t,r),l=await n(s),h=new nr(i,s,t,(await e.getPublicKey({identityKey:!0})).publicKey,l,o,c);return await h.sign(e),h}static async decryptFields(e,t,r,i,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:e0(t[r],"base64"),...il.getCertificateFieldEncryptionDetails(r),counterparty:n,privileged:a,privilegedReason:s}),c=new t4(o).decrypt(e0(i,"base64"));return{fieldRevelationKey:o,decryptedFieldValue:e3(c)}}catch{throw Error("Failed to decrypt certificate field!")}}}class ni extends il{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 ni(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:e0(this.keyring[a],"base64"),...il.getCertificateFieldEncryptionDetails(a,this.serialNumber),counterparty:this.subject,privileged:t,privilegedReason:r},i),o=new t4(s).decrypt(e0(this.fields[a],"base64"));n[a]=e3(o)}return n}catch(e){throw Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(e instanceof Error?e.message:e)}`)}}}class nn extends ii{keyDeriver;constructor(e){if(super(e),e instanceof ie)this.keyDeriver=e;else if("string"==typeof e||e instanceof tM)this.keyDeriver=new it(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 na{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 ns(e,t,r="self",i){let n=e0(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:e3(a),counterparty:r},i);return o}async function no(e,t="self",r){let i=tL(16),{hmac:n}=await e.createHmac({protocolID:[2,"server hmac"],keyID:e3(i),data:i,counterparty:t},r);return e4([...i,...n])}let nc=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 ni(n.type,n.serialNumber,n.subject,n.certifier,n.revocationOutpoint,n.fields,a,n.signature)}))},nl=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 ni(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)}))},nh="undefined"!=typeof globalThis?globalThis.Buffer:void 0;class nu{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 na,!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),n=e4(tL(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=e4(tL(32)),{signature:a}=await this.wallet.createSignature({data:nu.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();this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:r,peerIdentityKey:e,lastUpdate:i});let n={version:"0.1",messageType:"initialRequest",identityKey:await this.getIdentityPublicKey(),initialNonce:r,requestedCertificates:this.certificatesToRequest};return await this.transport.send(n),await this.waitForInitialResponse(r,t)}async waitForInitialResponse(e,t=1e4){return await new Promise((r,i)=>{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`);switch(e.messageType){case"initialRequest":await this.processInitialRequest(e);break;case"initialResponse":await this.processInitialResponse(e);break;case"certificateRequest":await this.processCertificateRequest(e);break;case"certificateResponse":await this.processCertificateResponse(e);break;case"general":await this.processGeneralMessage(e);break;default:throw Error(`Unknown message type of ${String(e.messageType)} from ${String(e.identityKey)}`)}}async processInitialRequest(e){let t;if("string"!=typeof e.identityKey||"string"!=typeof e.initialNonce||""===e.initialNonce)throw Error("Missing required fields in initialRequest message.");let r=await no(this.wallet,void 0,this.originator),i=Date.now();this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:r,peerNonce:e.initialNonce,peerIdentityKey:e.identityKey,lastUpdate:i}),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)}):t=await nc(this.wallet,e.requestedCertificates,e.identityKey,this.originator));let{signature:n}=await this.wallet.createSignature({data:nu.base64ToBytes(e.initialNonce+r),protocolID:[2,"auth message signature"],keyID:`${e.initialNonce} ${r}`,counterparty:e.identityKey},this.originator),a={version:"0.1",messageType:"initialResponse",identityKey:await this.getIdentityPublicKey(),initialNonce:r,yourNonce:e.initialNonce,certificates:t,requestedCertificates:this.certificatesToRequest,signature:n};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=e.identityKey),await this.transport.send(a)}async processInitialResponse(e){if(!await ns(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=nu.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.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.certificatesToRequest?.certifiers?.length>0&&e.certificates?.length>0&&(await nl(this.wallet,e,this.certificatesToRequest,this.originator),this.onCertificatesReceivedCallbacks.forEach(t=>t(e.identityKey,e.certificates))),this.lastInteractedWithPeer=e.identityKey,this.onInitialResponseReceivedCallbacks.forEach(e=>{e.sessionNonce===t.sessionNonce&&e.callback(t.sessionNonce)}),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)});else{let t=await nc(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async processCertificateRequest(e){if(!await ns(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:nu.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 nc(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=e4(tL(32)),{signature:n}=await this.wallet.createSignature({data:nu.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 ns(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:nu.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 nl(this.wallet,e,e.requestedCertificates,this.originator),this.onCertificatesReceivedCallbacks.forEach(t=>{t(e.identityKey,e.certificates??[])}),t.lastUpdate=Date.now(),this.sessionManager.updateSession(t)}async processGeneralMessage(e){if(!await ns(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for general message from: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let{valid:r}=await this.wallet.verifySignature({data:e.payload,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!r)throw Error(`Invalid signature in generalMessage from ${t.peerIdentityKey}`);t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.lastInteractedWithPeer=e.identityKey,this.onGeneralMessageReceivedCallbacks.forEach(t=>{t(e.identityKey,e.payload??[])})}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!=nh?Array.from(nh.from(e,"utf8")):"undefined"!=typeof TextEncoder?Array.from(new TextEncoder().encode(e)):e0(e,"utf8")}static base64ToBytes(e){return null!=nh?Array.from(nh.from(e,"base64")):e0(e,"base64")}}let nd="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch;class nf{onDataCallback;fetchClient;baseUrl;constructor(e,t=nd){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"]=eQ(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=e3(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 tr;null!=t.headers.get("x-bsv-auth-request-id")&&c.write(e0(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=e0(l[e][0],"utf8");c.writeVarIntNum(t.length),c.write(t);let r=e0(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:e0(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=e3(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 ti(e),i=e4(r.read(32)),n=r.readVarIntNum(),a="GET";n>0&&(a=e3(r.read(n)));let s=r.readVarIntNum(),o="";s>0&&(o=e3(r.read(s)));let c=r.readVarIntNum(),l="";c>0&&(l=e3(r.read(c)));let h={},u=r.readVarIntNum();if(u>0)for(let e=0;e<u;e++){let e=r.readVarIntNum(),t=e3(r.read(e)),i=r.readVarIntNum(),n=e3(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 np{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;originator;peers={};constructor(e,t,r,i){this.wallet=e,this.requestedCertificates=t,this.sessionManager=r??new na,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 nf(l);n={peer:new nu(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 nc(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=tL(32),u=e4(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 ti(t);if(e4(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=e3(t),n=i.readVarIntNum(),a=i.read(n),o=e3(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 nf(i);r={peer:new nu(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 tr;if(a.write(n),a.writeVarIntNum(e.length),a.write(e0(e)),i.pathname.length>0){let e=e0(i.pathname);a.writeVarIntNum(e.length),a.write(e)}else a.writeVarIntNum(-1);if(i.search.length>0){let e=e0(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=e0(s[e][0],"utf8");a.writeVarIntNum(t.length),a.write(t);let r=e0(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 ru().lock(tD.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:e4(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:e0(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:e0(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:e0(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 e0(JSON.stringify(e,"utf8"));if(Array.isArray(e)&&e.every(e=>"number"==typeof e))return e;if("string"==typeof e)return e0(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()])}),e0(new URLSearchParams(t).toString(),"utf8")}if(e instanceof URLSearchParams)return e0(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 ng{pushDrop;static decode(e){let t=rp.decode(e);if(t.fields.length<4)throw Error("Invalid SHIP/SLAP advertisement!");let r=e3(t.fields[0]);if("SHIP"!==r&&"SLAP"!==r)throw Error("Invalid protocol type!");let i=eQ(t.fields[1]);return{protocol:r,identityKey:i,domain:e3(t.fields[2]),topicOrService:e3(t.fields[3])}}constructor(e,t){this.pushDrop=new rp(e,t)}async lock(e,t,r){let{publicKey:i}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([e0(e,"utf8"),e0(i,"hex"),e0(t,"utf8"),e0(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 nb="bsvsdk_overlay_host_reputation_v1";class nm{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(nb);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(nb,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 ny=new nm,nw="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch,nv=["https://overlay-us-1.bsvb.tech","https://overlay-eu-1.bsvb.tech","https://overlay-ap-1.bsvb.tech","https://users.bapp.dev"],nI=["https://testnet-users.bapp.dev"];class nk{fetchClient;allowHTTP;constructor(e=nw,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 ti([...new Uint8Array(e)]),r=t.readVarIntNum(),i=[];for(let e=0;e<r;e++){let e,r=eQ(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:rR.fromBEEF(a,e.txid).toBEEF()}))}}}catch(e){if(e?.name==="AbortError")throw Error("Request timed out");throw e}finally{clearTimeout(n)}}}class nS{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;hostReputation;hostsCache;hostsInFlight;hostsTtlMs;hostsMaxEntries;txMemo;txMemoTtlMs;constructor(e={}){this.networkPreset=e.networkPreset??"mainnet",this.facilitator=e.facilitator??new nk(void 0,"local"===this.networkPreset),this.slapTrackers=e.slapTrackers??("mainnet"===this.networkPreset?nv:nI);const t=e.hostOverrides??{};this.assertValidOverrideServices(t),this.hostOverrides=t,this.additionalHosts=e.additionalHosts??{};const r=e.reputationStorage;"localStorage"===r?this.hostReputation=new nm:"object"==typeof r&&null!==r&&"function"==typeof r.get&&"function"==typeof r.set?this.hostReputation=new nm(r):this.hostReputation=ny,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:rR.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=rR.fromBEEF(t.beef),i=r.outputs[t.outputIndex]?.lockingScript;if("object"!=typeof i||null===i)continue;let a=ng.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 nx{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 tr;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 nE{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 nx(void 0,"local"===this.networkPreset),this.resolver=t.resolver??new nS({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=rR.fromBEEF(r.beef).outputs[r.outputIndex].lockingScript,i=ng.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 nP(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=rR.fromBEEF(n.competingBeef,n.competingTxs[0]);await nP(async()=>await t.broadcast(e),t,r-i);continue}}throw e}}throw Error("Unexpected end of retry loop")}let nN=e=>(e.toLowerCase().startsWith("uhrp:")&&(e=e.slice(5)),e.startsWith("//")&&(e=e.slice(2)),e),nO=e=>{if(32!==e.length)throw Error("Hash length must be 32 bytes (sha256)");return te(e,e0("ce00","hex"))},nA=e=>{let t=e instanceof Uint8Array?e:Uint8Array.from(e),r=new $;for(let e=0;e<t.length;e+=1048576){let i=t.subarray(e,e+1048576);r.update(Array.from(i))}return nO(r.digest())},n_=e=>{let{data:t,prefix:r}=tt(e=nN(e),void 0,2);if(32!==t.length)throw Error("Invalid length!");if("ce00"!==eQ(r))throw Error("Bad prefix");return t},nT=e=>{try{return n_(e),!0}catch(e){return!1}};class nC{authFetch;baseURL;constructor(e){this.baseURL=e.storageURL,this.authFetch=new np(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:nA(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 nR{networkPreset="mainnet";lookupResolver;constructor(e){this.networkPreset=e?.networkPreset??"mainnet",this.lookupResolver=new nS({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=rR.fromBEEF(t.outputs[e].beef),{fields:a}=rp.decode(n.outputs[t.outputs[e].outputIndex].lockingScript);new ti(a[3]).readVarIntNum()<i||r.push(e3(a[2]))}return r}async download(e){if(!nT(e))throw Error("Invalid parameter UHRP url");let t=eQ(n_(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 $,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(eQ(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 nV={name:"Unknown Identity",avatarURL:"XUUB8bbn9fEthk15Ge3zTQXypUShfC94vFjp65v7u5CQ8qkpxzst",identityKey:"",abbreviatedKey:"",badgeIconURL:"XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",badgeLabel:"Not verified by anyone you trust.",badgeClickURL:"https://projectbabbage.com/docs/unknown-identity"},nB={protocolID:[1,"identity"],keyID:"1",tokenAmount:1,outputIndex:0},nD={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="},nU=[2,"contact"];class nF{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 nL{wallet;cache=new nF;CONTACTS_CACHE_KEY="metanet-contacts";originator;constructor(e,t){this.wallet=e??new ne,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:nU,keyID:e,counterparty:"self",data:e0(e,"utf8")},this.originator);i.push(`identityKey ${eQ(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=rp.decode(rn.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:nU,keyID:r,counterparty:"self"},this.originator),n=JSON.parse(e3(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:nU,keyID:e.identityKey,counterparty:"self",data:e0(e.identityKey,"utf8")},this.originator),o=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:[`identityKey ${eQ(s)}`],limit:100},this.originator),c=null,l=e4(tL(32));if(null!=o.outputs)for(let t of o.outputs)try{let[r,i]=t.outpoint.split("."),n=rR.fromBEEF(o.BEEF,r),a=rp.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:nU,keyID:l,counterparty:"self"},this.originator);if(JSON.parse(e3(s)).identityKey===e.identityKey){c=t;break}}catch(e){}let h={...e,metadata:t},{ciphertext:u}=await this.wallet.encrypt({plaintext:e0(JSON.stringify(h),"utf8"),protocolID:nU,keyID:l,counterparty:"self"},this.originator),d=await new rp(this.wallet,this.originator).lock([u],nU,l,"self");if(null!=c){let[t,r]=String(c.outpoint).split("."),i=`${t}.${r}`,n=new rp(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 ${eQ(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(nU,l,"self"),u=await h.sign(rR.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 ${eQ(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:nU,keyID:e,counterparty:"self",data:e0(e,"utf8")},this.originator);r.push(`identityKey ${eQ(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=rR.fromBEEF(n.BEEF,r),s=rp.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:nU,keyID:o,counterparty:"self"},this.originator);if(JSON.parse(e3(c)).identityKey===e){let e=`${r}.${i}`,t=new rp(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(nU,o,"self"),c=await s.sign(rR.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 nK{options;originator;wallet;contactsManager;constructor(e,t=nB,r){this.options=t,this.originator=r,this.originator=r,this.wallet=e??new ne,this.contactsManager=new nL(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 il(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 tM(1).toPublicKey().toString()},this.originator),i=await new rp(this.wallet,this.originator).lock([e0(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 nE(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network});return await e.broadcast(rR.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=>nK.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)??nK.parseIdentity(e))}async revokeCertificateRevelation(e){let t=new nS({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 nE(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network,requireAcknowledgmentFromAllHostsForTopics:[],requireAcknowledgmentFromAnyHostForTopics:[],requireAcknowledgmentFromSpecificHostsForTopics:{tm_identity:[]}});await nP(async()=>{let e=rR.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=rR.fromBEEF(n.tx),s=new rp(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(rR.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 nD.xCert:t=o.userName,r=o.profilePhoto,i=`X account certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case nD.discordCert:t=o.userName,r=o.profilePhoto,i=`Discord account certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case nD.emailCert:t=o.email,r="XUTZxep7BBghAJbSBwTjNfmcsDdRFs5EaGEgkESGSgjJVYgMEizu",i=`Email certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case nD.phoneCert:t=o.phoneNumber,r="XUTLxtX3ELNUwRhLwL7kWNGbdnFM8WG2eSLv84J7654oH8HaJWrU",i=`Phone certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case nD.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 nD.registrant:t=o.name,r=o.icon,i=`Entity certified by ${c.name}`,n=c.iconUrl,a="https://projectbabbage.com/docs/registrant";break;case nD.coolCert:t="true"===o.cool?"Cool Person!":"Not cool!";break;case nD.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 nD.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=nK.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=nK.hasValue(i)&&nK.hasValue(n)?`${i} ${n}`:nK.hasValue(i)?i:nK.hasValue(n)?n:void 0,s=nK.hasValue(t.name)?t.name:nK.hasValue(t.userName)?t.userName:a??(nK.hasValue(t.email)?t.email:nV.name),o=nK.hasValue(t.profilePhoto)?t.profilePhoto:nK.hasValue(t.avatar)?t.avatar:nK.hasValue(t.icon)?t.icon:nK.hasValue(t.photo)?t.photo:nV.avatarURL,c=nK.hasValue(r?.name)?`${e} certified by ${String(r.name)}`:nV.badgeLabel;return{name:s,avatarURL:o,badgeLabel:c,badgeIconURL:nK.hasValue(r?.iconUrl)?r.iconUrl:nV.badgeIconURL,badgeClickURL:nV.badgeClickURL}}}class nH{wallet;originator;network;resolver;cachedIdentityKey;acceptDelayedBroadcast;constructor(e=new ne,t={},r){this.wallet=e,this.originator=r,this.acceptDelayedBroadcast=t.acceptDelayedBroadcast??!1,this.resolver=t.resolver??new nS}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 rp(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 nE([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await o.broadcast(rR.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=rR.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=rR.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=rR.fromAtomicBEEF(n.tx),s=new rp(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 nE([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await l.broadcast(rR.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 rp(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=rR.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 nE([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await p.broadcast(rR.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=>e0(e))}async parseLockingScript(e,t){let r,i,n=rp.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=e3(c),i={definitionType:"basket",basketID:e3(e),name:e3(t),iconURL:e3(a),description:e3(s),documentationURL:e3(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=e3(c),i={definitionType:"protocol",protocolID:nq(e3(e)),name:e3(t),iconURL:e3(a),description:e3(s),documentationURL:e3(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=e3(l);let h={};try{h=JSON.parse(e3(c))}catch{}i={definitionType:"certificate",type:e3(e),name:e3(t),iconURL:e3(a),description:e3(s),documentationURL:e3(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 nq(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 nM{wallet;context;encrypt;originator;acceptDelayedBroadcast=!1;keyLocks=new Map;constructor(e=new ne,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,rT.fromBinary(n.BEEF)),t=rp.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=e3(t)}else a.value=e3(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=rR.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=e0(t,"utf8");if(this.encrypt){let{ciphertext:e}=await this.wallet.encrypt({...n,plaintext:a},this.originator);a=e}let s=new rp(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 rp(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 n${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 nz={protocolID:0,key:1,value:2,controller:3,tags:4,signature:5},nW=async(e,t,r)=>{try{let i=e.outputs[t];if(null==i||null==i.lockingScript||null==r||null==r.key)return;let n=rp.decode(i.lockingScript),a=Object.keys(nz).length,s=n.fields.length===a;if(n.fields.length!==a-1&&!s)return;let o=e3(n.fields[nz.key]),c=e3(n.fields[nz.protocolID]);if(o!==r.key||c!==JSON.stringify(r.protocolID))return;try{return e3(n.fields[nz.value])}catch{return}}catch{return}},nj={protocolID:[1,"kvstore"],serviceName:"ls_kvstore",tokenAmount:1,topics:["tm_kvstore"],networkPreset:"mainnet",acceptDelayedBroadcast:!1,overlayBroadcast:!1,tokenSetDescription:"",tokenUpdateDescription:"",tokenRemovalDescription:""};class nG{wallet;config;historian;lookupResolver;topicBroadcaster;keyLocks=new Map;cachedIdentityKey=null;constructor(e={}){this.config={...nj,...e},this.wallet=e.wallet??new ne,this.historian=new n$(nW),this.lookupResolver=new nS({networkPreset:this.config.networkPreset}),this.topicBroadcaster=new nE(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 rp(this.wallet,this.config.originator),n=[e0(JSON.stringify(a),"utf8"),e0(e,"utf8"),e0(t,"utf8"),e0(i,"hex")];l.length>0&&n.push(e0(JSON.stringify(l),"utf8"));let h=await r.lock(n,a??this.config.protocolID,e3(e0(e,"utf8")),"anyone",!0);return await nP(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=rR.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=rR.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=rR.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 rp(this.wallet,this.config.originator);return await nP(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=rR.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=rR.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=rR.fromBEEF(e.beef),a=n.outputs[e.outputIndex],s=rp.decode(a.lockingScript),o=Object.keys(nz).length,c=s.fields.length===o;if(s.fields.length!==o-1&&!c)continue;let l=new ir("anyone"),h=s.fields.pop();try{await l.verifySignature({data:s.fields.reduce((e,t)=>[...e,...t],[]),signature:h,counterparty:eQ(s.fields[nz.controller]),protocolID:JSON.parse(e3(s.fields[nz.protocolID])),keyID:e3(s.fields[nz.key])})}catch(e){continue}if(c&&null!=s.fields[nz.tags])try{r=JSON.parse(e3(s.fields[nz.tags]))}catch(e){r=void 0}let u={key:e3(s.fields[nz.key]),value:e3(s.fields[nz.value]),controller:eQ(s.fields[nz.controller]),protocolID:JSON.parse(e3(s.fields[nz.protocolID])),tags:r};!0===t.includeToken&&(u.token={txid:n.id("hex"),outputIndex:e.outputIndex,beef:rT.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 nX=nG;return h})());
|
|
20
20
|
//# sourceMappingURL=bundle.js.map
|