@babylonlabs-io/ts-sdk 0.50.0 → 0.51.0
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/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/{primeVpAuth-BdrwraAe.js → primeVpAuth-DxMuWQCi.js} +228 -247
- package/dist/{primeVpAuth-BdrwraAe.js.map → primeVpAuth-DxMuWQCi.js.map} +1 -1
- package/dist/{primeVpAuth-Brl_bnBH.cjs → primeVpAuth-yTddDmGy.cjs} +2 -2
- package/dist/{primeVpAuth-Brl_bnBH.cjs.map → primeVpAuth-yTddDmGy.cjs.map} +1 -1
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +1 -1
- package/dist/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.d.ts +0 -6
- package/dist/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/auth/primeVpAuth.d.ts +0 -8
- package/dist/tbv/core/clients/vault-provider/auth/primeVpAuth.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/auth/tokenRegistry.d.ts +3 -14
- package/dist/tbv/core/clients/vault-provider/auth/tokenRegistry.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/auth/verifyDepositorCwt.d.ts +14 -26
- package/dist/tbv/core/clients/vault-provider/auth/verifyDepositorCwt.d.ts.map +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var $e=Object.defineProperty;var Re=(r,e,t)=>e in r?$e(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var _=(r,e,t)=>Re(r,typeof e!="symbol"?e+"":e,t);const Z=require("./BTCVaultRegistry.abi-JdeqLz4x.cjs"),w=require("./ApplicationRegistry.abi-BAPhJch3.cjs"),I=require("./mempoolApi-NMiYQAXI.cjs"),M=require("./types-WA0LrDk1.cjs"),f=require("./bitcoin-CHfKAhcI.cjs"),Q=require("./constants-CSG2XeD8.cjs"),T=require("./validation-u8W7Lp2x.cjs"),Ie=require("@bitcoin-js/tiny-secp256k1-asmjs"),B=require("bitcoinjs-lib"),V=require("buffer"),F=require("./sha2-DsrLC4NM.cjs");function Ve(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const X=Ve(Ie);async function Oe(r,e){const[t,n]=await r.multicall({contracts:[{address:e,abi:Z.BTCVaultRegistryABI,functionName:"protocolParams"},{address:e,abi:Z.BTCVaultRegistryABI,functionName:"applicationRegistry"}],allowFailure:!1});return{protocolParams:t,applicationRegistry:n}}const ee=65535;function N(r){return{timelockAssert:r.timelockAssert,timelockChallengeAssert:r.timelockChallengeAssert,securityCouncilKeys:[...r.securityCouncilKeys],councilQuorum:r.councilQuorum,feeRate:r.feeRate,babeTotalInstances:r.babeTotalInstances,babeInstancesToFinalize:r.babeInstancesToFinalize,minVpCommissionBps:r.minVpCommissionBps,tRefund:r.tRefund,tStale:r.tStale,minPeginFeeRate:r.minPeginFeeRate,proverCircuitVersion:r.proverCircuitVersion,minPrepeginDepth:r.minPrepeginDepth}}function te(r){return{minimumPegInAmount:r.minimumPegInAmount,maxPegInAmount:r.maxPegInAmount,pegInAckTimeout:r.pegInAckTimeout,pegInActivationTimeout:r.pegInActivationTimeout,maxHtlcOutputCount:r.maxHtlcOutputCount,expiredPegInGraceBlocks:r.expiredPegInGraceBlocks}}function re(r){if(r>BigInt(ee))throw new Error(`timelockAssert value ${r} exceeds uint16 max (${ee})`);return Number(r)}class Be{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getTBVProtocolParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"getTBVProtocolParams"}),t=te(e);return I.validateTBVProtocolParams(t),t}async getLatestOffchainParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"getLatestOffchainParams"}),t=N(e);return I.validateOffchainParams(t),t}async getOffchainParamsByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[e]}),n=N(t);return I.validateOffchainParams(n),n}async getLatestOffchainParamsVersion(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"latestOffchainParamsVersion"}),t=Number(e);return I.assertValidOffchainParamsVersion(t),t}async getTimelockPeginByVersion(e){const t=await this.getOffchainParamsByVersion(e);return re(t.timelockAssert)}async getPegInConfiguration(){const e=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"getTBVProtocolParams"},{address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"getLatestOffchainParams"},{address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"latestOffchainParamsVersion"}],allowFailure:!1}),t=te(e[0]),n=N(e[1]),i=Number(e[2]),s={minimumPegInAmount:t.minimumPegInAmount,maxPegInAmount:t.maxPegInAmount,pegInAckTimeout:t.pegInAckTimeout,pegInActivationTimeout:t.pegInActivationTimeout,maxHtlcOutputCount:t.maxHtlcOutputCount,expiredPegInGraceBlocks:t.expiredPegInGraceBlocks,timelockPegin:re(n.timelockAssert),timelockRefund:n.tRefund,minVpCommissionBps:n.minVpCommissionBps,offchainParams:n,offchainParamsVersion:i};return I.validatePegInConfiguration(s),s}async fetchAllOffchainParams(e){const t=await this.getLatestOffchainParamsVersion();if(t===0)return{byVersion:new Map,latestVersion:0};const n=Array.from({length:t},(c,d)=>d+1),i=n.map(c=>({address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[c]})),s=await this.publicClient.multicall({contracts:i,allowFailure:!1}),o=new Map;for(let c=0;c<n.length;c++){const d=N(s[c]);try{I.validateOffchainParams(d),o.set(n[c],d)}catch(u){e==null||e(n[c],u instanceof Error?u:new Error(String(u)))}}return{byVersion:o,latestVersion:t}}}function L(r){return r.map(e=>({ethAddress:e.ethAddress,btcPubKey:e.btcPubKey}))}class Ne{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getVaultKeepersByVersion(e,t){const n=await this.publicClient.readContract({address:this.contractAddress,abi:w.ApplicationRegistryABI,functionName:"getVaultKeepersByVersion",args:[e,t]});return L(n)}async getCurrentVaultKeepers(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:w.ApplicationRegistryABI,functionName:"getCurrentVaultKeepers",args:[e]});return L(t)}async getCurrentVaultKeepersVersion(e){return await this.publicClient.readContract({address:this.contractAddress,abi:w.ApplicationRegistryABI,functionName:"getCurrentVaultKeepersVersion",args:[e]})}}class He{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getUniversalChallengersByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"getUniversalChallengersByVersion",args:[e]});return L(t)}async getCurrentUniversalChallengers(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"getCurrentUniversalChallengers"});return L(e)}async getLatestUniversalChallengersVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"latestUniversalChallengersVersion"})}}var fe=(r=>(r[r.PENDING=0]="PENDING",r[r.VERIFIED=1]="VERIFIED",r[r.ACTIVE=2]="ACTIVE",r[r.REDEEMED=3]="REDEEMED",r[r.EXPIRED=4]="EXPIRED",r))(fe||{});const ne=new Set(Object.values(M.DaemonStatus)),Ge=200;function h(r){var e;return((e=JSON.stringify(r))==null?void 0:e.slice(0,Ge))??"undefined"}const Le="The vault provider returned an unexpected response. Please try again or contact support.";class a extends Error{constructor(t){super(Le);_(this,"detail");this.name="VpResponseValidationError",this.detail=t}}const O=64;function $(r){return typeof r=="string"&&r.length>0&&T.HEX_RE.test(r)}function _e(r){return typeof r=="string"&&r.length>0}function me(r,e){if(!$(r))throw new a(`VP response validation failed: "${e}" must be a non-empty hex string, got ${h(r)}`)}function P(r,e){if(!_e(r))throw new a(`VP response validation failed: "${e}" must be a non-empty string, got ${h(r)}`)}function W(r,e){if(!$(r)||r.length!==f.X_ONLY_PUBKEY_HEX_LEN&&r.length!==f.COMPRESSED_PUBKEY_HEX_LEN)throw new a(`VP response validation failed: "${e}" must be a ${f.X_ONLY_PUBKEY_HEX_LEN} or ${f.COMPRESSED_PUBKEY_HEX_LEN}-char hex string (BTC pubkey), got ${h(r)}`)}function De(r){const e=r.presigning;if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new a('VP response validation failed: "progress.presigning" must be an object if present');const t=e;if(t.depositor_graph_created!==void 0&&typeof t.depositor_graph_created!="boolean")throw new a(`VP response validation failed: "progress.presigning.depositor_graph_created" must be a boolean if present, got ${h(t.depositor_graph_created)}`);if(t.vk_challenger_presigning_completed!==void 0&&typeof t.vk_challenger_presigning_completed!="number")throw new a(`VP response validation failed: "progress.presigning.vk_challenger_presigning_completed" must be a number if present, got ${h(t.vk_challenger_presigning_completed)}`);if(t.vk_challenger_presigning_total!==void 0&&typeof t.vk_challenger_presigning_total!="number")throw new a(`VP response validation failed: "progress.presigning.vk_challenger_presigning_total" must be a number if present, got ${h(t.vk_challenger_presigning_total)}`)}function ye(r){if(r===null||typeof r!="object")throw new a("VP response validation failed: getPeginStatus response is not an object");const e=r;if(!$(e.pegin_txid)||e.pegin_txid.length!==O)throw new a(`VP response validation failed: "pegin_txid" must be a ${O}-char hex string (txid), got ${h(e.pegin_txid)}`);if(typeof e.status!="string")throw new a('VP response validation failed: "status" must be a string');if(!ne.has(e.status))throw new a(`VP response validation failed: unrecognized status "${e.status}". Expected one of: ${[...ne].join(", ")}`);if(e.progress===null||typeof e.progress!="object"||Array.isArray(e.progress))throw new a('VP response validation failed: "progress" must be an object');if(De(e.progress),typeof e.health_info!="string")throw new a('VP response validation failed: "health_info" must be a string');if(e.last_error!==void 0&&typeof e.last_error!="string")throw new a(`VP response validation failed: "last_error" must be a string if present, got ${h(e.last_error)}`)}function Me(r){if(r===null||typeof r!="object")throw new a("VP response validation failed: requestDepositorPresignTransactions response is not an object");const e=r;if(!Array.isArray(e.txs))throw new a('VP response validation failed: "txs" must be an array');for(let t=0;t<e.txs.length;t++)Xe(e.txs[t],`txs[${t}]`);if(e.depositor_graph===null||typeof e.depositor_graph!="object")throw new a('VP response validation failed: "depositor_graph" must be an object');We(e.depositor_graph)}function E(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "${e}" must be an object`);me(r.tx_hex,`${e}.tx_hex`)}function Xe(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=r;W(t.claimer_pubkey,`${e}.claimer_pubkey`),E(t.claim_tx,`${e}.claim_tx`),E(t.assert_tx,`${e}.assert_tx`),E(t.payout_tx,`${e}.payout_tx`),P(t.payout_psbt,`${e}.payout_psbt`)}function je(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=r;P(t.wots_pks_json,`${e}.wots_pks_json`),P(t.gc_wots_keys_json,`${e}.gc_wots_keys_json`)}function Ue(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=r;if(W(t.challenger_pubkey,`${e}.challenger_pubkey`),E(t.challenge_assert_x_tx,`${e}.challenge_assert_x_tx`),E(t.challenge_assert_y_tx,`${e}.challenge_assert_y_tx`),E(t.nopayout_tx,`${e}.nopayout_tx`),P(t.nopayout_psbt,`${e}.nopayout_psbt`),!Array.isArray(t.challenge_assert_connectors))throw new a(`VP response validation failed: "${e}.challenge_assert_connectors" must be an array`);if(t.challenge_assert_connectors.length!==Q.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER)throw new a(`VP response validation failed: "${e}.challenge_assert_connectors" must have exactly ${Q.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER} entries, got ${t.challenge_assert_connectors.length}`);for(let n=0;n<t.challenge_assert_connectors.length;n++)je(t.challenge_assert_connectors[n],`${e}.challenge_assert_connectors[${n}]`);if(!Array.isArray(t.output_label_hashes))throw new a(`VP response validation failed: "${e}.output_label_hashes" must be an array`);for(let n=0;n<t.output_label_hashes.length;n++)me(t.output_label_hashes[n],`${e}.output_label_hashes[${n}]`)}function be(r){if(r===null||typeof r!="object")throw new a("VP response validation failed: requestDepositorClaimerArtifacts response is not an object");const e=r;if(!_e(e.tx_graph_json))throw new a(`VP response validation failed: "tx_graph_json" must be a non-empty string, got ${h(e.tx_graph_json)}`);if(!$(e.verifying_key_hex))throw new a(`VP response validation failed: "verifying_key_hex" must be a non-empty hex string, got ${h(e.verifying_key_hex)}`);if(e.babe_sessions===null||typeof e.babe_sessions!="object"||Array.isArray(e.babe_sessions))throw new a('VP response validation failed: "babe_sessions" must be an object');const t=Object.entries(e.babe_sessions);if(t.length===0)throw new a('VP response validation failed: "babe_sessions" must contain at least one challenger entry');for(const[n,i]of t){if(W(n,`babe_sessions["${n}"]`),i===null||typeof i!="object")throw new a(`VP response validation failed: "babe_sessions.${n}" must be an object`);const s=i;if(!$(s.decryptor_artifacts_hex))throw new a(`VP response validation failed: "babe_sessions.${n}.decryptor_artifacts_hex" must be a non-empty hex string, got ${h(s.decryptor_artifacts_hex)}`)}}function Ke(r){if(r===null||typeof r!="object")throw new a("VP response validation failed: pegout status payload is not an object");const e=r;if(!$(e.pegin_txid)||e.pegin_txid.length!==O)throw new a(`VP response validation failed: "pegin_txid" must be a ${O}-char hex string (txid), got ${h(e.pegin_txid)}`);if(typeof e.found!="boolean")throw new a(`VP response validation failed: "found" must be a boolean, got ${h(e.found)}`);if(e.claimer!==null){if(typeof e.claimer!="object")throw new a(`VP response validation failed: "claimer" must be an object or null, got ${h(e.claimer)}`);Fe(e.claimer)}if(!Array.isArray(e.challengers))throw new a(`VP response validation failed: "challengers" must be an array, got ${h(e.challengers)}`);for(let t=0;t<e.challengers.length;t++)qe(e.challengers[t],t)}function Fe(r){if(P(r.status,"claimer.status"),typeof r.failed!="boolean")throw new a(`VP response validation failed: "claimer.failed" must be a boolean, got ${h(r.failed)}`);if(P(r.claim_txid,"claimer.claim_txid"),P(r.claimer_pubkey,"claimer.claimer_pubkey"),P(r.assert_txid,"claimer.assert_txid"),typeof r.created_at!="number")throw new a(`VP response validation failed: "claimer.created_at" must be a number, got ${h(r.created_at)}`);if(typeof r.updated_at!="number")throw new a(`VP response validation failed: "claimer.updated_at" must be a number, got ${h(r.updated_at)}`)}function qe(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "challengers[${e}]" must be an object, got ${h(r)}`);const t=r;if(P(t.status,`challengers[${e}].status`),P(t.claim_txid,`challengers[${e}].claim_txid`),P(t.claimer_pubkey,`challengers[${e}].claimer_pubkey`),H(t.assert_txid,`challengers[${e}].assert_txid`),H(t.challenge_assert_x_txid,`challengers[${e}].challenge_assert_x_txid`),H(t.challenge_assert_y_txid,`challengers[${e}].challenge_assert_y_txid`),H(t.nopayout_txid,`challengers[${e}].nopayout_txid`),typeof t.created_at!="number")throw new a(`VP response validation failed: "challengers[${e}].created_at" must be a number, got ${h(t.created_at)}`);if(typeof t.updated_at!="number")throw new a(`VP response validation failed: "challengers[${e}].updated_at" must be a number, got ${h(t.updated_at)}`)}function H(r,e){if(r!==null&&typeof r!="string")throw new a(`VP response validation failed: "${e}" must be a string or null, got ${h(r)}`)}function Je(r){we(r,"batchGetPeginStatus",e=>{e.result!==null&&ye(e.result)})}function Ye(r){we(r,"batchGetPegoutStatus",e=>{e.result!==null&&Ke(e.result)})}function we(r,e,t){if(r===null||typeof r!="object")throw new a(`VP response validation failed: ${e} response is not an object`);const n=r;if(!Array.isArray(n.results))throw new a(`VP response validation failed: "${e}.results" must be an array, got ${h(n.results)}`);for(let i=0;i<n.results.length;i++){const s=n.results[i];if(s===null||typeof s!="object")throw new a(`VP response validation failed: "${e}.results[${i}]" must be an object, got ${h(s)}`);const o=s;if(!$(o.pegin_txid)||o.pegin_txid.length!==O)throw new a(`VP response validation failed: "${e}.results[${i}].pegin_txid" must be a ${O}-char hex string, got ${h(o.pegin_txid)}`);if(o.error!==null&&typeof o.error!="string")throw new a(`VP response validation failed: "${e}.results[${i}].error" must be a string or null, got ${h(o.error)}`);if(o.result===null&&o.error===null)throw new a(`VP response validation failed: "${e}.results[${i}]" has neither "result" nor "error" populated`);if(o.result!==null&&o.error!==null)throw new a(`VP response validation failed: "${e}.results[${i}]" has both "result" and "error" populated`);t(o,i)}}function We(r){if(E(r.claim_tx,"depositor_graph.claim_tx"),E(r.assert_tx,"depositor_graph.assert_tx"),E(r.payout_tx,"depositor_graph.payout_tx"),P(r.payout_psbt,"depositor_graph.payout_psbt"),!Array.isArray(r.challenger_presign_data))throw new a('VP response validation failed: "depositor_graph.challenger_presign_data" must be an array');for(let e=0;e<r.challenger_presign_data.length;e++)Ue(r.challenger_presign_data[e],`depositor_graph.challenger_presign_data[${e}]`);if(typeof r.offchain_params_version!="number")throw new a('VP response validation failed: "depositor_graph.offchain_params_version" must be a number')}const ze=6e4;class Pe{constructor(e,t){_(this,"client");const n={baseUrl:e,timeout:(t==null?void 0:t.timeout)??ze,retries:t==null?void 0:t.retries,retryDelay:t==null?void 0:t.retryDelay,retryableFor:t==null?void 0:t.retryableFor,headers:t==null?void 0:t.headers,tokenProvider:t==null?void 0:t.tokenProvider,maxResponseBytes:t==null?void 0:t.maxResponseBytes};this.client=new M.JsonRpcClient(n)}async requestDepositorPresignTransactions(e,t){const n=await this.client.call("vaultProvider_requestDepositorPresignTransactions",e,t);return Me(n),n}async submitDepositorPresignatures(e,t){return this.client.call("vaultProvider_submitDepositorPresignatures",e,t)}async submitDepositorWotsKey(e,t){return this.client.call("vaultProvider_submitDepositorWotsKey",e,t)}async requestDepositorClaimerArtifacts(e,t){const n=await this.client.call("vaultProvider_requestDepositorClaimerArtifacts",e,t);return be(n),n}async getPeginStatus(e,t){const n=await this.client.call("vaultProvider_getPeginStatus",e,t);return ye(n),n}async batchGetPeginStatus(e,t){const n=await this.client.call("vaultProvider_batchGetPeginStatus",e,t);return Je(n),n}async batchGetPegoutStatus(e,t){const n=await this.client.call("vaultProvider_batchGetPegoutStatus",e,t);return Ye(n),n}}function Ze(r,e){const t=new Set;for(const d of r)t.add(d.toLowerCase());const n=new Map,i=new Set,s=[],o=[];for(const d of e){const u=d.pegin_txid.toLowerCase();if(!t.has(u)){o.push(u);continue}if(i.has(u)){s.push(u);continue}i.add(u),n.set(u,{result:d.result,error:d.error})}const c=[];for(const d of t)i.has(d)||c.push(d);return{byTxid:n,missing:c,unexpected:o,duplicate:s}}async function Qe(r){const{items:e,getTxid:t,batchCall:n,onItem:i,onMissing:s,onDuplicate:o,onDuplicateBatch:c,onWholeBatchError:d,onUnexpected:u,batchSize:g=M.VP_BATCH_MAX_SIZE}=r;if(!Number.isInteger(g)||g<=0)throw new Error(`batchPollByProvider: batchSize must be a positive integer, got ${g}`);for(let y=0;y<e.length;y+=g){const x=e.slice(y,y+g),S=new Map,C=[];for(const m of x){const l=t(m).toLowerCase();S.set(l,m),C.push(l)}let A;try{const m=await n(C);A=Ze(C,m.results)}catch(m){d(x,m);continue}u&&A.unexpected.length>0&&u(A.unexpected);const R=new Set(A.duplicate);for(const m of R){const l=S.get(m);l&&o(l)}c&&R.size>0&&c(R.size);for(const m of A.missing){const l=S.get(m);l&&s(l)}for(const[m,l]of A.byTxid){if(R.has(m))continue;const k=S.get(m);k&&i(k,{pegin_txid:m,result:l.result,error:l.error})}}}const et="BIP0322-signed-message",tt="TapTweak",xe=32,rt=64;function Ae(r,e){const t=new TextEncoder().encode(r),n=F.sha256(t),i=new Uint8Array(n.length*2+e.length);return i.set(n,0),i.set(n,n.length),i.set(e,n.length*2),F.sha256(i)}function nt(r){if(r.length!==xe)return null;const e=Ae(tt,r),t=X.xOnlyPointAddTweak(r,e);return t?t.xOnlyPubkey:null}function st(r,e,t){if(e.length!==xe||t.length!==rt)return!1;try{const n=Ae(et,r),i=B.payments.p2tr({internalPubkey:V.Buffer.from(e)});if(!i.output)return!1;const s=i.output,o=0,c=new B.Transaction;c.version=0,c.locktime=0;const d=V.Buffer.concat([V.Buffer.from([0,32]),V.Buffer.from(n)]);c.addInput(V.Buffer.alloc(32,0),4294967295,0,d),c.addOutput(s,o);const u=new B.Transaction;u.version=0,u.locktime=0;const g=c.getHash();u.addInput(g,0,0),u.addOutput(V.Buffer.from([106]),o);const y=u.hashForWitnessV1(0,[s],[o],B.Transaction.SIGHASH_DEFAULT),x=nt(e);return x?X.verifySchnorr(y,x,t):!1}catch{return!1}}function D(r,e){const t=(r&7)<<5,n=typeof e=="bigint"?e:BigInt(e);if(n<0n)throw new Error("cborHead: negative argument");if(n<24n)return new Uint8Array([t|Number(n)]);if(n<0x100n)return new Uint8Array([t|24,Number(n)]);if(n<0x10000n){const s=Number(n);return new Uint8Array([t|25,s>>>8&255,s&255])}if(n<0x100000000n){const s=Number(n);return new Uint8Array([t|26,s>>>24&255,s>>>16&255,s>>>8&255,s&255])}const i=new Uint8Array(9);i[0]=t|27;for(let s=7;s>=0;s--)i[1+s]=Number(n>>BigInt((7-s)*8))&255;return i}function ve(...r){const e=r.reduce((i,s)=>i+s.length,0),t=new Uint8Array(e);let n=0;for(const i of r)t.set(i,n),n+=i.length;return t}function se(r){const t=[D(4,r.length)];for(const n of r)t.push(D(0,n));return ve(...t)}function it(r,e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`encodeServerIdentityPayload: expires_at must be a non-negative safe integer, got ${t}`);const n=D(4,3),i=se(r),s=se(e),o=D(0,t);return ve(n,i,s,o)}const ot=new TextEncoder().encode("btc-auth.server-identity.v1"),at=2*3600;class b extends Error{constructor(e,t){super(e),this.reason=t,this.name="ServerIdentityError"}}function G(r){const e=new Uint8Array(r.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(r.slice(t*2,t*2+2),16);return e}function Ee(r){const{proof:e,pinnedServerPubkey:t,now:n}=r,i=r.maxLifetimeSecs??at,s=f.stripHexPrefix(t).toLowerCase();if(s.length!==f.X_ONLY_PUBKEY_HEX_LEN||!T.HEX_RE.test(s))throw new b(`pinnedServerPubkey must be 32-byte hex; got ${s.length} chars`,"invalid_pubkey_encoding");const o=f.stripHexPrefix(e.server_pubkey).toLowerCase();if(o.length!==f.X_ONLY_PUBKEY_HEX_LEN||!T.HEX_RE.test(o))throw new b(`server_pubkey must be 32-byte hex; got ${o.length} chars`,"invalid_pubkey_encoding");if(o!==s)throw new b(`server_pubkey does not match pinned value: expected ${s}, got ${o}`,"pinned_pubkey_mismatch");if(!Number.isSafeInteger(e.expires_at))throw new b(`expires_at must be a finite integer; got ${JSON.stringify(e.expires_at)}`,"invalid_expires_at");if(!Number.isSafeInteger(n))throw new b(`now must be a finite integer; got ${JSON.stringify(n)}`,"invalid_expires_at");if(e.expires_at<=n)throw new b(`server identity proof expired at ${e.expires_at}, now ${n}`,"expired");if(!Number.isSafeInteger(i)||i<=0)throw new b(`maxLifetimeSecs must be a positive safe integer; got ${JSON.stringify(i)}`,"invalid_max_lifetime");if(e.expires_at-n>i)throw new b(`server identity proof expires too far in the future: expires_at=${e.expires_at}, now=${n}, max lifetime=${i}s`,"expires_too_far");const c=f.stripHexPrefix(e.ephemeral_pubkey).toLowerCase();if(c.length!==f.COMPRESSED_PUBKEY_HEX_LEN||!T.HEX_RE.test(c))throw new b(`ephemeral_pubkey must be 33-byte compressed hex; got ${c.length} chars`,"invalid_ephemeral_pubkey");const d=c.slice(0,2);if(d!=="02"&&d!=="03")throw new b(`ephemeral_pubkey must be compressed (prefix 02/03); got ${d}`,"invalid_ephemeral_pubkey");const u=G(c);if(!X.isPoint(u))throw new b("ephemeral_pubkey is not a valid secp256k1 point","invalid_ephemeral_pubkey");const g=f.stripHexPrefix(e.signature).toLowerCase();if(g.length!==f.SCHNORR_SIG_HEX_LEN||!T.HEX_RE.test(g))throw new b(`signature must be 64-byte Schnorr hex; got ${g.length} chars`,"invalid_signature_encoding");const y=it(ot,G(c),e.expires_at);if(!st(y,G(o),G(g)))throw new b("BIP-322 signature verification failed — ephemeral key is not attested by pinned server pubkey","signature_verification_failed")}const ie=new Set(["vaultProvider_submitDepositorWotsKey","vaultProvider_submitDepositorPresignatures","vaultProvider_requestDepositorPresignTransactions"]),oe=new Set(["vaultProvider_requestDepositorClaimerArtifacts"]),ct=6e4,q="auth_createDepositorToken",J="auth_createDepositorTokenGrpc";function Se(r,e){return new M.JsonRpcClient({baseUrl:r,timeout:ct,headers:e,retryableFor:t=>t===q||t===J})}const lt=0,ut=1,j=2,dt=3,pt=4,ht=5,gt=6,ft=7,ae=24,_t=28,mt=20,yt=21,bt=22,ce=256;class v extends Error{constructor(e){super(`CBOR decode: ${e}`),this.name="CborDecodeError"}}class ke{constructor(e){_(this,"buf");_(this,"pos",0);this.buf=e}nextByte(){if(this.pos>=this.buf.length)throw new v("unexpected end of input");return this.buf[this.pos++]}readHead(){const e=this.nextByte(),t=e>>5,n=e&31;if(n<ae)return{major:t,arg:n};if(n>=_t)throw new v(`unsupported additional info ${n} (indefinite-length or reserved)`);const i=1<<n-ae;let s=0n;for(let o=0;o<i;o++)s=s<<8n|BigInt(this.nextByte());if(s>BigInt(Number.MAX_SAFE_INTEGER))throw new v(`argument ${s} exceeds safe integer range`);return{major:t,arg:Number(s)}}readBytes(e){if(this.pos+e>this.buf.length)throw new v("length overruns end of input");const t=this.buf.subarray(this.pos,this.pos+e);return this.pos+=e,t}readByteString(){const e=this.readHead();if(e.major!==j)throw new v(`expected byte string (major ${j}), got major ${e.major}`);return this.readBytes(e.arg)}readValue(e=0){if(e>ce)throw new v(`nesting exceeds maximum depth ${ce}`);const t=this.readHead();switch(t.major){case lt:return t.arg;case ut:return-1-t.arg;case j:return this.readBytes(t.arg);case dt:return new TextDecoder("utf-8",{fatal:!0}).decode(this.readBytes(t.arg));case pt:{const n=[];for(let i=0;i<t.arg;i++)n.push(this.readValue(e+1));return n}case ht:{const n=new Map;for(let i=0;i<t.arg;i++){const s=this.readValue(e+1),o=this.readValue(e+1);n.set(s,o)}return n}case gt:return{tag:t.arg,value:this.readValue(e+1)};case ft:if(t.arg===mt)return!1;if(t.arg===yt)return!0;if(t.arg===bt)return null;throw new v(`unsupported simple/float value ${t.arg}`);default:throw new v(`unsupported major type ${t.major}`)}}}function Te(r){const e=new ke(r),t=e.readValue();if(e.pos!==r.length)throw new v("trailing bytes after top-level item");return t}const wt="vaultd-jsonrpc",Pt="vaultd-grpc",le=18,Y=4,ue=-47,xt=1,de=64,At=128,vt=96,Et=64,St=1,kt=2,Tt=3,Ct=4,$t=5,Rt=6,It=7,pe=new TextEncoder().encode("Signature1");class p extends Error{constructor(e,t){super(e),this.reason=t,this.name="CwtVerificationError"}}function Vt(r){const e=he(r.expectedIssuerXOnlyPubkey,"expectedIssuerXOnlyPubkey"),t=he(r.expectedAudienceXOnlyPubkey,"expectedAudienceXOnlyPubkey"),n=Gt(r.ephemeralPubkeyHex),i=Dt(r.token),s=new ke(i),o=s.readHead();if(o.major!==6||o.arg!==le)throw new p(`token is not a COSE Sign1 tagged value (tag ${le})`,"invalid_token_structure");const c=s.readHead();if(c.major!==4||c.arg!==Y)throw new p(`COSE Sign1 must be a ${Y}-element array`,"invalid_token_structure");const d=s.pos,u=s.readByteString(),g=i.subarray(d,s.pos);s.readValue();const y=s.pos,x=s.readByteString(),S=i.subarray(y,s.pos),C=s.readByteString();if(C.length!==de)throw new p(`COSE signature must be ${de} bytes, got ${C.length}`,"invalid_token_structure");if(s.pos!==i.length)throw new p("COSE Sign1 token has trailing bytes after the signature","invalid_token_structure");const A=Ot(u);if(A!==ue)throw new p(`unexpected COSE algorithm ${A} (expected ES256K ${ue})`,"unexpected_algorithm");const R=Bt(g,S),m=F.sha256(R);if(!X.verify(m,n,C,!0))throw new p("COSE signature does not verify against the server's ephemeral key","signature_verification_failed");const l=Nt(x),k=l.audience.toLowerCase();if(k.length!==f.X_ONLY_PUBKEY_HEX_LEN||!T.HEX_RE.test(k))throw new p("token `aud` is not a 32-byte x-only pubkey hex","invalid_claims");if(l.issuedAt>l.expiresAt)throw new p(`token iat (${l.issuedAt}) is after exp (${l.expiresAt})`,"invalid_claims");if(l.issuer.toLowerCase()!==e)throw new p(`token issuer does not match pinned server pubkey: expected ${e}, got ${l.issuer.toLowerCase()}`,"issuer_mismatch");if(l.subject!==r.expectedSubject)throw new p(`token subject mismatch: expected ${r.expectedSubject}, got ${l.subject}`,"subject_mismatch");if(k!==t)throw new p(`token audience does not match depositor pubkey: expected ${t}, got ${k}`,"audience_mismatch");if(l.notBefore>r.now)throw new p(`token not yet valid: nbf ${l.notBefore} > now ${r.now}`,"token_not_yet_valid");if(l.issuedAt>r.now)throw new p(`token issued in the future: iat ${l.issuedAt} > now ${r.now}`,"invalid_claims");if(l.expiresAt<=r.now)throw new p(`token expired: exp ${l.expiresAt} <= now ${r.now}`,"token_expired");if(r.responseExpiresAt!==l.expiresAt)throw new p(`response expires_at (${r.responseExpiresAt}) does not equal token exp (${l.expiresAt})`,"expiry_mismatch");if(r.serverIdentityExpiresAt<l.expiresAt)throw new p(`server identity expires (${r.serverIdentityExpiresAt}) before token exp (${l.expiresAt})`,"server_identity_expires_before_token");return{issuer:l.issuer,subject:l.subject,audience:k,expiresAt:l.expiresAt,notBefore:l.notBefore,issuedAt:l.issuedAt}}function Ot(r){if(r.length===0)throw new p("empty COSE protected header (no algorithm)","unexpected_algorithm");const e=Te(r);if(!(e instanceof Map))throw new p("COSE protected header is not a map","invalid_token_structure");const t=e.get(xt);if(typeof t!="number")throw new p("COSE protected header missing integer algorithm label","unexpected_algorithm");return t}function Bt(r,e){return Mt(Uint8Array.of(At|Y),Uint8Array.of(vt|pe.length),pe,r,Uint8Array.of(Et),e)}function Nt(r){const e=Te(r);if(!(e instanceof Map))throw new p("CWT claims root is not a map","invalid_claims");if(Ht(e,It,"cti").length===0)throw new p("token cti is empty","invalid_claims");return{issuer:U(e,St,"iss"),subject:U(e,kt,"sub"),audience:U(e,Tt,"aud"),expiresAt:K(e,Ct,"exp"),notBefore:K(e,$t,"nbf"),issuedAt:K(e,Rt,"iat")}}function U(r,e,t){const n=r.get(e);if(typeof n!="string")throw new p(`token claim ${t} is missing or not a text string`,"invalid_claims");return n}function Ht(r,e,t){const n=r.get(e);if(!(n instanceof Uint8Array))throw new p(`token claim ${t} is missing or not a byte string`,"invalid_claims");return n}function K(r,e,t){const n=r.get(e);if(typeof n!="number"||!Number.isSafeInteger(n)||n<0)throw new p(`token claim ${t} is missing or not a non-negative integer timestamp`,"invalid_claims");return n}function he(r,e){const t=f.stripHexPrefix(r).toLowerCase();if(t.length!==f.X_ONLY_PUBKEY_HEX_LEN||!T.HEX_RE.test(t))throw new p(`${e} must be 32-byte x-only hex; got ${t.length} chars`,"invalid_input");return t}function Gt(r){const e=f.stripHexPrefix(r).toLowerCase(),t=e.slice(0,2);if(e.length!==f.COMPRESSED_PUBKEY_HEX_LEN||!T.HEX_RE.test(e)||t!=="02"&&t!=="03")throw new p("ephemeralPubkeyHex must be 33-byte compressed pubkey hex (prefix 02/03)","invalid_input");return f.hexToUint8Array(e)}const Lt=(()=>{const r=new Int16Array(128).fill(-1),e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";for(let t=0;t<e.length;t++)r[e.charCodeAt(t)]=t;return r})();function Dt(r){const e=r.length,t=Math.floor(e/4),n=e%4;if(n===1)throw new p("invalid base64url length","invalid_token_structure");const i=t*3+(n===0?0:n-1),s=new Uint8Array(i),o=u=>{const g=u<128?Lt[u]:-1;if(g<0)throw new p("invalid base64url character","invalid_token_structure");return g};let c=0,d=0;for(let u=0;u<t;u++){const g=o(r.charCodeAt(c++)),y=o(r.charCodeAt(c++)),x=o(r.charCodeAt(c++)),S=o(r.charCodeAt(c++));s[d++]=g<<2|y>>4,s[d++]=(y&15)<<4|x>>2,s[d++]=(x&3)<<6|S}if(n===2){const u=o(r.charCodeAt(c++)),g=o(r.charCodeAt(c++));s[d++]=u<<2|g>>4}else if(n===3){const u=o(r.charCodeAt(c++)),g=o(r.charCodeAt(c++)),y=o(r.charCodeAt(c++));s[d++]=u<<2|g>>4,s[d++]=(g&15)<<4|y>>2}return s}function Mt(...r){const e=r.reduce((i,s)=>i+s.length,0),t=new Uint8Array(e);let n=0;for(const i of r)t.set(i,n),n+=i.length;return t}const ge=4102444800,Xt=30;class jt{constructor(e){_(this,"client");_(this,"peginTxid");_(this,"authAnchorHex");_(this,"pinnedServerPubkey");_(this,"expectedAudienceXOnlyPubkey");_(this,"authGatedMethods");_(this,"grpcGatedMethods");_(this,"refreshSkewSecs");_(this,"now");_(this,"cachedJsonRpc",null);_(this,"inFlightJsonRpc",null);_(this,"cachedGrpc",null);_(this,"inFlightGrpc",null);this.client=e.client,this.peginTxid=e.peginTxid,this.authAnchorHex=e.authAnchorHex,this.pinnedServerPubkey=e.pinnedServerPubkey,this.expectedAudienceXOnlyPubkey=e.expectedAudienceXOnlyPubkey,this.authGatedMethods=e.authGatedMethods,this.grpcGatedMethods=e.grpcGatedMethods,this.refreshSkewSecs=e.refreshSkewSecs??Xt,this.now=e.now??(()=>Math.floor(Date.now()/1e3))}async getToken(e){return e===q||e===J?null:this.grpcGatedMethods.has(e)?this.getTokenForSubject("grpc"):this.authGatedMethods.has(e)?this.getTokenForSubject("jsonrpc"):null}invalidate(){this.cachedJsonRpc=null,this.cachedGrpc=null}async getTokenForSubject(e){const t=e==="grpc"?this.cachedGrpc:this.cachedJsonRpc;return t&&this.now()+this.refreshSkewSecs<t.expiresAt?t.token:(await this.acquireSingleFlight(e)).token}setClient(e){this.client=e}acquireSingleFlight(e){const t=e==="grpc"?this.inFlightGrpc:this.inFlightJsonRpc;if(t)return t;const n=e==="grpc"?J:q,i=(async()=>{try{const s=await this.client.call(n,{pegin_txid:this.peginTxid,auth_anchor:this.authAnchorHex});if(Ee({proof:s.server_identity,pinnedServerPubkey:this.pinnedServerPubkey,now:this.now()}),typeof s.token!="string"||s.token.length===0)throw new Error(`VpTokenProvider: invalid token in acquire response (expected non-empty string, got ${typeof s.token})`);const o=this.now();if(!Number.isSafeInteger(s.expires_at)||s.expires_at<=o||s.expires_at>ge)throw new Error(`VpTokenProvider: invalid expires_at in acquire response (got ${JSON.stringify(s.expires_at)}; must be a safe integer in (${o}, ${ge}])`);Vt({token:s.token,ephemeralPubkeyHex:s.server_identity.ephemeral_pubkey,expectedIssuerXOnlyPubkey:this.pinnedServerPubkey,expectedSubject:e==="grpc"?Pt:wt,expectedAudienceXOnlyPubkey:this.expectedAudienceXOnlyPubkey,responseExpiresAt:s.expires_at,serverIdentityExpiresAt:s.server_identity.expires_at,now:o});const c={token:s.token,expiresAt:s.expires_at};return e==="grpc"?this.cachedGrpc=c:this.cachedJsonRpc=c,c}finally{e==="grpc"?this.inFlightGrpc=null:this.inFlightJsonRpc=null}})();return e==="grpc"?this.inFlightGrpc=i:this.inFlightJsonRpc=i,i}}class Ce{constructor(){_(this,"entries",new Map)}getOrCreate(e){const t=e.enableGrpcArtifactAuth??!1,n=this.entries.get(e.peginTxid);if(n){if(n.authAnchorHex!==e.authAnchorHex)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to authAnchorHex ${n.authAnchorHex.slice(0,8)}…; got ${e.authAnchorHex.slice(0,8)}…`);if(n.pinnedServerPubkey!==e.pinnedServerPubkey)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to pinnedServerPubkey ${n.pinnedServerPubkey.slice(0,8)}…; got ${e.pinnedServerPubkey.slice(0,8)}…`);if(n.expectedAudienceXOnlyPubkey!==e.expectedAudienceXOnlyPubkey)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to expectedAudienceXOnlyPubkey ${n.expectedAudienceXOnlyPubkey.slice(0,8)}…; got ${e.expectedAudienceXOnlyPubkey.slice(0,8)}…`);if(n.enableGrpcArtifactAuth!==t)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to enableGrpcArtifactAuth=${n.enableGrpcArtifactAuth}; got ${t}`);return n.provider.setClient(e.client),n.provider}const i=new jt({client:e.client,peginTxid:e.peginTxid,authAnchorHex:e.authAnchorHex,pinnedServerPubkey:e.pinnedServerPubkey,expectedAudienceXOnlyPubkey:e.expectedAudienceXOnlyPubkey,authGatedMethods:t?ie:new Set([...ie,...oe]),grpcGatedMethods:t?oe:new Set});return this.entries.set(e.peginTxid,{provider:i,authAnchorHex:e.authAnchorHex,pinnedServerPubkey:e.pinnedServerPubkey,expectedAudienceXOnlyPubkey:e.expectedAudienceXOnlyPubkey,enableGrpcArtifactAuth:t}),i}peek(e){var t;return(t=this.entries.get(e))==null?void 0:t.provider}release(e){this.entries.delete(e)}clear(){this.entries.clear()}get size(){return this.entries.size}}const z=new Ce;function Ut(r){var n;const e=Se(r.baseUrl,(n=r.options)==null?void 0:n.headers),t=z.getOrCreate({client:e,peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey,expectedAudienceXOnlyPubkey:f.processPublicKeyToXOnly(r.depositorBtcPubkey),enableGrpcArtifactAuth:r.enableGrpcArtifactAuth});return new Pe(r.baseUrl,{...r.options,tokenProvider:t})}function Kt(r){z.getOrCreate({client:Se(r.baseUrl,r.headers),peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey,expectedAudienceXOnlyPubkey:f.processPublicKeyToXOnly(r.depositorBtcPubkey),enableGrpcArtifactAuth:r.enableGrpcArtifactAuth})}exports.OnChainBtcVaultStatus=fe;exports.ServerIdentityError=b;exports.VaultProviderRpcClient=Pe;exports.ViemProtocolParamsReader=Be;exports.ViemUniversalChallengerReader=He;exports.ViemVaultKeeperReader=Ne;exports.VpResponseValidationError=a;exports.VpTokenRegistry=Ce;exports.batchPollByProvider=Qe;exports.createAuthenticatedVpClient=Ut;exports.primeVpTokenRegistry=Kt;exports.resolveProtocolAddresses=Oe;exports.validateRequestDepositorClaimerArtifactsResponse=be;exports.verifyServerIdentity=Ee;exports.vpTokenRegistry=z;
|
|
2
|
-
//# sourceMappingURL=primeVpAuth-
|
|
1
|
+
"use strict";var Ce=Object.defineProperty;var Te=(r,e,t)=>e in r?Ce(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var _=(r,e,t)=>Te(r,typeof e!="symbol"?e+"":e,t);const Z=require("./BTCVaultRegistry.abi-JdeqLz4x.cjs"),w=require("./ApplicationRegistry.abi-BAPhJch3.cjs"),R=require("./mempoolApi-NMiYQAXI.cjs"),G=require("./types-WA0LrDk1.cjs"),f=require("./bitcoin-CHfKAhcI.cjs"),Q=require("./constants-CSG2XeD8.cjs"),C=require("./validation-u8W7Lp2x.cjs"),$e=require("@bitcoin-js/tiny-secp256k1-asmjs"),B=require("bitcoinjs-lib"),V=require("buffer"),F=require("./sha2-DsrLC4NM.cjs");function Ie(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const X=Ie($e);async function Re(r,e){const[t,n]=await r.multicall({contracts:[{address:e,abi:Z.BTCVaultRegistryABI,functionName:"protocolParams"},{address:e,abi:Z.BTCVaultRegistryABI,functionName:"applicationRegistry"}],allowFailure:!1});return{protocolParams:t,applicationRegistry:n}}const ee=65535;function N(r){return{timelockAssert:r.timelockAssert,timelockChallengeAssert:r.timelockChallengeAssert,securityCouncilKeys:[...r.securityCouncilKeys],councilQuorum:r.councilQuorum,feeRate:r.feeRate,babeTotalInstances:r.babeTotalInstances,babeInstancesToFinalize:r.babeInstancesToFinalize,minVpCommissionBps:r.minVpCommissionBps,tRefund:r.tRefund,tStale:r.tStale,minPeginFeeRate:r.minPeginFeeRate,proverCircuitVersion:r.proverCircuitVersion,minPrepeginDepth:r.minPrepeginDepth}}function te(r){return{minimumPegInAmount:r.minimumPegInAmount,maxPegInAmount:r.maxPegInAmount,pegInAckTimeout:r.pegInAckTimeout,pegInActivationTimeout:r.pegInActivationTimeout,maxHtlcOutputCount:r.maxHtlcOutputCount,expiredPegInGraceBlocks:r.expiredPegInGraceBlocks}}function re(r){if(r>BigInt(ee))throw new Error(`timelockAssert value ${r} exceeds uint16 max (${ee})`);return Number(r)}class Ve{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getTBVProtocolParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"getTBVProtocolParams"}),t=te(e);return R.validateTBVProtocolParams(t),t}async getLatestOffchainParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"getLatestOffchainParams"}),t=N(e);return R.validateOffchainParams(t),t}async getOffchainParamsByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[e]}),n=N(t);return R.validateOffchainParams(n),n}async getLatestOffchainParamsVersion(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"latestOffchainParamsVersion"}),t=Number(e);return R.assertValidOffchainParamsVersion(t),t}async getTimelockPeginByVersion(e){const t=await this.getOffchainParamsByVersion(e);return re(t.timelockAssert)}async getPegInConfiguration(){const e=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"getTBVProtocolParams"},{address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"getLatestOffchainParams"},{address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"latestOffchainParamsVersion"}],allowFailure:!1}),t=te(e[0]),n=N(e[1]),i=Number(e[2]),s={minimumPegInAmount:t.minimumPegInAmount,maxPegInAmount:t.maxPegInAmount,pegInAckTimeout:t.pegInAckTimeout,pegInActivationTimeout:t.pegInActivationTimeout,maxHtlcOutputCount:t.maxHtlcOutputCount,expiredPegInGraceBlocks:t.expiredPegInGraceBlocks,timelockPegin:re(n.timelockAssert),timelockRefund:n.tRefund,minVpCommissionBps:n.minVpCommissionBps,offchainParams:n,offchainParamsVersion:i};return R.validatePegInConfiguration(s),s}async fetchAllOffchainParams(e){const t=await this.getLatestOffchainParamsVersion();if(t===0)return{byVersion:new Map,latestVersion:0};const n=Array.from({length:t},(c,d)=>d+1),i=n.map(c=>({address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[c]})),s=await this.publicClient.multicall({contracts:i,allowFailure:!1}),o=new Map;for(let c=0;c<n.length;c++){const d=N(s[c]);try{R.validateOffchainParams(d),o.set(n[c],d)}catch(l){e==null||e(n[c],l instanceof Error?l:new Error(String(l)))}}return{byVersion:o,latestVersion:t}}}function D(r){return r.map(e=>({ethAddress:e.ethAddress,btcPubKey:e.btcPubKey}))}class Oe{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getVaultKeepersByVersion(e,t){const n=await this.publicClient.readContract({address:this.contractAddress,abi:w.ApplicationRegistryABI,functionName:"getVaultKeepersByVersion",args:[e,t]});return D(n)}async getCurrentVaultKeepers(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:w.ApplicationRegistryABI,functionName:"getCurrentVaultKeepers",args:[e]});return D(t)}async getCurrentVaultKeepersVersion(e){return await this.publicClient.readContract({address:this.contractAddress,abi:w.ApplicationRegistryABI,functionName:"getCurrentVaultKeepersVersion",args:[e]})}}class Be{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getUniversalChallengersByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"getUniversalChallengersByVersion",args:[e]});return D(t)}async getCurrentUniversalChallengers(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"getCurrentUniversalChallengers"});return D(e)}async getLatestUniversalChallengersVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:w.ProtocolParamsABI,functionName:"latestUniversalChallengersVersion"})}}var he=(r=>(r[r.PENDING=0]="PENDING",r[r.VERIFIED=1]="VERIFIED",r[r.ACTIVE=2]="ACTIVE",r[r.REDEEMED=3]="REDEEMED",r[r.EXPIRED=4]="EXPIRED",r))(he||{});const ne=new Set(Object.values(G.DaemonStatus)),Ne=200;function h(r){var e;return((e=JSON.stringify(r))==null?void 0:e.slice(0,Ne))??"undefined"}const He="The vault provider returned an unexpected response. Please try again or contact support.";class a extends Error{constructor(t){super(He);_(this,"detail");this.name="VpResponseValidationError",this.detail=t}}const O=64;function $(r){return typeof r=="string"&&r.length>0&&C.HEX_RE.test(r)}function ge(r){return typeof r=="string"&&r.length>0}function fe(r,e){if(!$(r))throw new a(`VP response validation failed: "${e}" must be a non-empty hex string, got ${h(r)}`)}function P(r,e){if(!ge(r))throw new a(`VP response validation failed: "${e}" must be a non-empty string, got ${h(r)}`)}function W(r,e){if(!$(r)||r.length!==f.X_ONLY_PUBKEY_HEX_LEN&&r.length!==f.COMPRESSED_PUBKEY_HEX_LEN)throw new a(`VP response validation failed: "${e}" must be a ${f.X_ONLY_PUBKEY_HEX_LEN} or ${f.COMPRESSED_PUBKEY_HEX_LEN}-char hex string (BTC pubkey), got ${h(r)}`)}function Le(r){const e=r.presigning;if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new a('VP response validation failed: "progress.presigning" must be an object if present');const t=e;if(t.depositor_graph_created!==void 0&&typeof t.depositor_graph_created!="boolean")throw new a(`VP response validation failed: "progress.presigning.depositor_graph_created" must be a boolean if present, got ${h(t.depositor_graph_created)}`);if(t.vk_challenger_presigning_completed!==void 0&&typeof t.vk_challenger_presigning_completed!="number")throw new a(`VP response validation failed: "progress.presigning.vk_challenger_presigning_completed" must be a number if present, got ${h(t.vk_challenger_presigning_completed)}`);if(t.vk_challenger_presigning_total!==void 0&&typeof t.vk_challenger_presigning_total!="number")throw new a(`VP response validation failed: "progress.presigning.vk_challenger_presigning_total" must be a number if present, got ${h(t.vk_challenger_presigning_total)}`)}function _e(r){if(r===null||typeof r!="object")throw new a("VP response validation failed: getPeginStatus response is not an object");const e=r;if(!$(e.pegin_txid)||e.pegin_txid.length!==O)throw new a(`VP response validation failed: "pegin_txid" must be a ${O}-char hex string (txid), got ${h(e.pegin_txid)}`);if(typeof e.status!="string")throw new a('VP response validation failed: "status" must be a string');if(!ne.has(e.status))throw new a(`VP response validation failed: unrecognized status "${e.status}". Expected one of: ${[...ne].join(", ")}`);if(e.progress===null||typeof e.progress!="object"||Array.isArray(e.progress))throw new a('VP response validation failed: "progress" must be an object');if(Le(e.progress),typeof e.health_info!="string")throw new a('VP response validation failed: "health_info" must be a string');if(e.last_error!==void 0&&typeof e.last_error!="string")throw new a(`VP response validation failed: "last_error" must be a string if present, got ${h(e.last_error)}`)}function De(r){if(r===null||typeof r!="object")throw new a("VP response validation failed: requestDepositorPresignTransactions response is not an object");const e=r;if(!Array.isArray(e.txs))throw new a('VP response validation failed: "txs" must be an array');for(let t=0;t<e.txs.length;t++)Me(e.txs[t],`txs[${t}]`);if(e.depositor_graph===null||typeof e.depositor_graph!="object")throw new a('VP response validation failed: "depositor_graph" must be an object');Je(e.depositor_graph)}function E(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "${e}" must be an object`);fe(r.tx_hex,`${e}.tx_hex`)}function Me(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=r;W(t.claimer_pubkey,`${e}.claimer_pubkey`),E(t.claim_tx,`${e}.claim_tx`),E(t.assert_tx,`${e}.assert_tx`),E(t.payout_tx,`${e}.payout_tx`),P(t.payout_psbt,`${e}.payout_psbt`)}function Ge(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=r;P(t.wots_pks_json,`${e}.wots_pks_json`),P(t.gc_wots_keys_json,`${e}.gc_wots_keys_json`)}function Xe(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=r;if(W(t.challenger_pubkey,`${e}.challenger_pubkey`),E(t.challenge_assert_x_tx,`${e}.challenge_assert_x_tx`),E(t.challenge_assert_y_tx,`${e}.challenge_assert_y_tx`),E(t.nopayout_tx,`${e}.nopayout_tx`),P(t.nopayout_psbt,`${e}.nopayout_psbt`),!Array.isArray(t.challenge_assert_connectors))throw new a(`VP response validation failed: "${e}.challenge_assert_connectors" must be an array`);if(t.challenge_assert_connectors.length!==Q.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER)throw new a(`VP response validation failed: "${e}.challenge_assert_connectors" must have exactly ${Q.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER} entries, got ${t.challenge_assert_connectors.length}`);for(let n=0;n<t.challenge_assert_connectors.length;n++)Ge(t.challenge_assert_connectors[n],`${e}.challenge_assert_connectors[${n}]`);if(!Array.isArray(t.output_label_hashes))throw new a(`VP response validation failed: "${e}.output_label_hashes" must be an array`);for(let n=0;n<t.output_label_hashes.length;n++)fe(t.output_label_hashes[n],`${e}.output_label_hashes[${n}]`)}function me(r){if(r===null||typeof r!="object")throw new a("VP response validation failed: requestDepositorClaimerArtifacts response is not an object");const e=r;if(!ge(e.tx_graph_json))throw new a(`VP response validation failed: "tx_graph_json" must be a non-empty string, got ${h(e.tx_graph_json)}`);if(!$(e.verifying_key_hex))throw new a(`VP response validation failed: "verifying_key_hex" must be a non-empty hex string, got ${h(e.verifying_key_hex)}`);if(e.babe_sessions===null||typeof e.babe_sessions!="object"||Array.isArray(e.babe_sessions))throw new a('VP response validation failed: "babe_sessions" must be an object');const t=Object.entries(e.babe_sessions);if(t.length===0)throw new a('VP response validation failed: "babe_sessions" must contain at least one challenger entry');for(const[n,i]of t){if(W(n,`babe_sessions["${n}"]`),i===null||typeof i!="object")throw new a(`VP response validation failed: "babe_sessions.${n}" must be an object`);const s=i;if(!$(s.decryptor_artifacts_hex))throw new a(`VP response validation failed: "babe_sessions.${n}.decryptor_artifacts_hex" must be a non-empty hex string, got ${h(s.decryptor_artifacts_hex)}`)}}function je(r){if(r===null||typeof r!="object")throw new a("VP response validation failed: pegout status payload is not an object");const e=r;if(!$(e.pegin_txid)||e.pegin_txid.length!==O)throw new a(`VP response validation failed: "pegin_txid" must be a ${O}-char hex string (txid), got ${h(e.pegin_txid)}`);if(typeof e.found!="boolean")throw new a(`VP response validation failed: "found" must be a boolean, got ${h(e.found)}`);if(e.claimer!==null){if(typeof e.claimer!="object")throw new a(`VP response validation failed: "claimer" must be an object or null, got ${h(e.claimer)}`);Ue(e.claimer)}if(!Array.isArray(e.challengers))throw new a(`VP response validation failed: "challengers" must be an array, got ${h(e.challengers)}`);for(let t=0;t<e.challengers.length;t++)Ke(e.challengers[t],t)}function Ue(r){if(P(r.status,"claimer.status"),typeof r.failed!="boolean")throw new a(`VP response validation failed: "claimer.failed" must be a boolean, got ${h(r.failed)}`);if(P(r.claim_txid,"claimer.claim_txid"),P(r.claimer_pubkey,"claimer.claimer_pubkey"),P(r.assert_txid,"claimer.assert_txid"),typeof r.created_at!="number")throw new a(`VP response validation failed: "claimer.created_at" must be a number, got ${h(r.created_at)}`);if(typeof r.updated_at!="number")throw new a(`VP response validation failed: "claimer.updated_at" must be a number, got ${h(r.updated_at)}`)}function Ke(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "challengers[${e}]" must be an object, got ${h(r)}`);const t=r;if(P(t.status,`challengers[${e}].status`),P(t.claim_txid,`challengers[${e}].claim_txid`),P(t.claimer_pubkey,`challengers[${e}].claimer_pubkey`),H(t.assert_txid,`challengers[${e}].assert_txid`),H(t.challenge_assert_x_txid,`challengers[${e}].challenge_assert_x_txid`),H(t.challenge_assert_y_txid,`challengers[${e}].challenge_assert_y_txid`),H(t.nopayout_txid,`challengers[${e}].nopayout_txid`),typeof t.created_at!="number")throw new a(`VP response validation failed: "challengers[${e}].created_at" must be a number, got ${h(t.created_at)}`);if(typeof t.updated_at!="number")throw new a(`VP response validation failed: "challengers[${e}].updated_at" must be a number, got ${h(t.updated_at)}`)}function H(r,e){if(r!==null&&typeof r!="string")throw new a(`VP response validation failed: "${e}" must be a string or null, got ${h(r)}`)}function Fe(r){ye(r,"batchGetPeginStatus",e=>{e.result!==null&&_e(e.result)})}function qe(r){ye(r,"batchGetPegoutStatus",e=>{e.result!==null&&je(e.result)})}function ye(r,e,t){if(r===null||typeof r!="object")throw new a(`VP response validation failed: ${e} response is not an object`);const n=r;if(!Array.isArray(n.results))throw new a(`VP response validation failed: "${e}.results" must be an array, got ${h(n.results)}`);for(let i=0;i<n.results.length;i++){const s=n.results[i];if(s===null||typeof s!="object")throw new a(`VP response validation failed: "${e}.results[${i}]" must be an object, got ${h(s)}`);const o=s;if(!$(o.pegin_txid)||o.pegin_txid.length!==O)throw new a(`VP response validation failed: "${e}.results[${i}].pegin_txid" must be a ${O}-char hex string, got ${h(o.pegin_txid)}`);if(o.error!==null&&typeof o.error!="string")throw new a(`VP response validation failed: "${e}.results[${i}].error" must be a string or null, got ${h(o.error)}`);if(o.result===null&&o.error===null)throw new a(`VP response validation failed: "${e}.results[${i}]" has neither "result" nor "error" populated`);if(o.result!==null&&o.error!==null)throw new a(`VP response validation failed: "${e}.results[${i}]" has both "result" and "error" populated`);t(o,i)}}function Je(r){if(E(r.claim_tx,"depositor_graph.claim_tx"),E(r.assert_tx,"depositor_graph.assert_tx"),E(r.payout_tx,"depositor_graph.payout_tx"),P(r.payout_psbt,"depositor_graph.payout_psbt"),!Array.isArray(r.challenger_presign_data))throw new a('VP response validation failed: "depositor_graph.challenger_presign_data" must be an array');for(let e=0;e<r.challenger_presign_data.length;e++)Xe(r.challenger_presign_data[e],`depositor_graph.challenger_presign_data[${e}]`);if(typeof r.offchain_params_version!="number")throw new a('VP response validation failed: "depositor_graph.offchain_params_version" must be a number')}const Ye=6e4;class be{constructor(e,t){_(this,"client");const n={baseUrl:e,timeout:(t==null?void 0:t.timeout)??Ye,retries:t==null?void 0:t.retries,retryDelay:t==null?void 0:t.retryDelay,retryableFor:t==null?void 0:t.retryableFor,headers:t==null?void 0:t.headers,tokenProvider:t==null?void 0:t.tokenProvider,maxResponseBytes:t==null?void 0:t.maxResponseBytes};this.client=new G.JsonRpcClient(n)}async requestDepositorPresignTransactions(e,t){const n=await this.client.call("vaultProvider_requestDepositorPresignTransactions",e,t);return De(n),n}async submitDepositorPresignatures(e,t){return this.client.call("vaultProvider_submitDepositorPresignatures",e,t)}async submitDepositorWotsKey(e,t){return this.client.call("vaultProvider_submitDepositorWotsKey",e,t)}async requestDepositorClaimerArtifacts(e,t){const n=await this.client.call("vaultProvider_requestDepositorClaimerArtifacts",e,t);return me(n),n}async getPeginStatus(e,t){const n=await this.client.call("vaultProvider_getPeginStatus",e,t);return _e(n),n}async batchGetPeginStatus(e,t){const n=await this.client.call("vaultProvider_batchGetPeginStatus",e,t);return Fe(n),n}async batchGetPegoutStatus(e,t){const n=await this.client.call("vaultProvider_batchGetPegoutStatus",e,t);return qe(n),n}}function We(r,e){const t=new Set;for(const d of r)t.add(d.toLowerCase());const n=new Map,i=new Set,s=[],o=[];for(const d of e){const l=d.pegin_txid.toLowerCase();if(!t.has(l)){o.push(l);continue}if(i.has(l)){s.push(l);continue}i.add(l),n.set(l,{result:d.result,error:d.error})}const c=[];for(const d of t)i.has(d)||c.push(d);return{byTxid:n,missing:c,unexpected:o,duplicate:s}}async function ze(r){const{items:e,getTxid:t,batchCall:n,onItem:i,onMissing:s,onDuplicate:o,onDuplicateBatch:c,onWholeBatchError:d,onUnexpected:l,batchSize:g=G.VP_BATCH_MAX_SIZE}=r;if(!Number.isInteger(g)||g<=0)throw new Error(`batchPollByProvider: batchSize must be a positive integer, got ${g}`);for(let y=0;y<e.length;y+=g){const x=e.slice(y,y+g),S=new Map,T=[];for(const m of x){const u=t(m).toLowerCase();S.set(u,m),T.push(u)}let A;try{const m=await n(T);A=We(T,m.results)}catch(m){d(x,m);continue}l&&A.unexpected.length>0&&l(A.unexpected);const I=new Set(A.duplicate);for(const m of I){const u=S.get(m);u&&o(u)}c&&I.size>0&&c(I.size);for(const m of A.missing){const u=S.get(m);u&&s(u)}for(const[m,u]of A.byTxid){if(I.has(m))continue;const k=S.get(m);k&&i(k,{pegin_txid:m,result:u.result,error:u.error})}}}const Ze="BIP0322-signed-message",Qe="TapTweak",we=32,et=64;function Pe(r,e){const t=new TextEncoder().encode(r),n=F.sha256(t),i=new Uint8Array(n.length*2+e.length);return i.set(n,0),i.set(n,n.length),i.set(e,n.length*2),F.sha256(i)}function tt(r){if(r.length!==we)return null;const e=Pe(Qe,r),t=X.xOnlyPointAddTweak(r,e);return t?t.xOnlyPubkey:null}function rt(r,e,t){if(e.length!==we||t.length!==et)return!1;try{const n=Pe(Ze,r),i=B.payments.p2tr({internalPubkey:V.Buffer.from(e)});if(!i.output)return!1;const s=i.output,o=0,c=new B.Transaction;c.version=0,c.locktime=0;const d=V.Buffer.concat([V.Buffer.from([0,32]),V.Buffer.from(n)]);c.addInput(V.Buffer.alloc(32,0),4294967295,0,d),c.addOutput(s,o);const l=new B.Transaction;l.version=0,l.locktime=0;const g=c.getHash();l.addInput(g,0,0),l.addOutput(V.Buffer.from([106]),o);const y=l.hashForWitnessV1(0,[s],[o],B.Transaction.SIGHASH_DEFAULT),x=tt(e);return x?X.verifySchnorr(y,x,t):!1}catch{return!1}}function M(r,e){const t=(r&7)<<5,n=typeof e=="bigint"?e:BigInt(e);if(n<0n)throw new Error("cborHead: negative argument");if(n<24n)return new Uint8Array([t|Number(n)]);if(n<0x100n)return new Uint8Array([t|24,Number(n)]);if(n<0x10000n){const s=Number(n);return new Uint8Array([t|25,s>>>8&255,s&255])}if(n<0x100000000n){const s=Number(n);return new Uint8Array([t|26,s>>>24&255,s>>>16&255,s>>>8&255,s&255])}const i=new Uint8Array(9);i[0]=t|27;for(let s=7;s>=0;s--)i[1+s]=Number(n>>BigInt((7-s)*8))&255;return i}function xe(...r){const e=r.reduce((i,s)=>i+s.length,0),t=new Uint8Array(e);let n=0;for(const i of r)t.set(i,n),n+=i.length;return t}function se(r){const t=[M(4,r.length)];for(const n of r)t.push(M(0,n));return xe(...t)}function nt(r,e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`encodeServerIdentityPayload: expires_at must be a non-negative safe integer, got ${t}`);const n=M(4,3),i=se(r),s=se(e),o=M(0,t);return xe(n,i,s,o)}const st=new TextEncoder().encode("btc-auth.server-identity.v1"),it=2*3600;class b extends Error{constructor(e,t){super(e),this.reason=t,this.name="ServerIdentityError"}}function L(r){const e=new Uint8Array(r.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(r.slice(t*2,t*2+2),16);return e}function Ae(r){const{proof:e,pinnedServerPubkey:t,now:n}=r,i=r.maxLifetimeSecs??it,s=f.stripHexPrefix(t).toLowerCase();if(s.length!==f.X_ONLY_PUBKEY_HEX_LEN||!C.HEX_RE.test(s))throw new b(`pinnedServerPubkey must be 32-byte hex; got ${s.length} chars`,"invalid_pubkey_encoding");const o=f.stripHexPrefix(e.server_pubkey).toLowerCase();if(o.length!==f.X_ONLY_PUBKEY_HEX_LEN||!C.HEX_RE.test(o))throw new b(`server_pubkey must be 32-byte hex; got ${o.length} chars`,"invalid_pubkey_encoding");if(o!==s)throw new b(`server_pubkey does not match pinned value: expected ${s}, got ${o}`,"pinned_pubkey_mismatch");if(!Number.isSafeInteger(e.expires_at))throw new b(`expires_at must be a finite integer; got ${JSON.stringify(e.expires_at)}`,"invalid_expires_at");if(!Number.isSafeInteger(n))throw new b(`now must be a finite integer; got ${JSON.stringify(n)}`,"invalid_expires_at");if(e.expires_at<=n)throw new b(`server identity proof expired at ${e.expires_at}, now ${n}`,"expired");if(!Number.isSafeInteger(i)||i<=0)throw new b(`maxLifetimeSecs must be a positive safe integer; got ${JSON.stringify(i)}`,"invalid_max_lifetime");if(e.expires_at-n>i)throw new b(`server identity proof expires too far in the future: expires_at=${e.expires_at}, now=${n}, max lifetime=${i}s`,"expires_too_far");const c=f.stripHexPrefix(e.ephemeral_pubkey).toLowerCase();if(c.length!==f.COMPRESSED_PUBKEY_HEX_LEN||!C.HEX_RE.test(c))throw new b(`ephemeral_pubkey must be 33-byte compressed hex; got ${c.length} chars`,"invalid_ephemeral_pubkey");const d=c.slice(0,2);if(d!=="02"&&d!=="03")throw new b(`ephemeral_pubkey must be compressed (prefix 02/03); got ${d}`,"invalid_ephemeral_pubkey");const l=L(c);if(!X.isPoint(l))throw new b("ephemeral_pubkey is not a valid secp256k1 point","invalid_ephemeral_pubkey");const g=f.stripHexPrefix(e.signature).toLowerCase();if(g.length!==f.SCHNORR_SIG_HEX_LEN||!C.HEX_RE.test(g))throw new b(`signature must be 64-byte Schnorr hex; got ${g.length} chars`,"invalid_signature_encoding");const y=nt(st,L(c),e.expires_at);if(!rt(y,L(o),L(g)))throw new b("BIP-322 signature verification failed — ephemeral key is not attested by pinned server pubkey","signature_verification_failed")}const ot=new Set(["vaultProvider_submitDepositorWotsKey","vaultProvider_submitDepositorPresignatures","vaultProvider_requestDepositorPresignTransactions"]),at=new Set(["vaultProvider_requestDepositorClaimerArtifacts"]),ct=6e4,q="auth_createDepositorToken",J="auth_createDepositorTokenGrpc";function ve(r,e){return new G.JsonRpcClient({baseUrl:r,timeout:ct,headers:e,retryableFor:t=>t===q||t===J})}const lt=0,ut=1,j=2,dt=3,pt=4,ht=5,gt=6,ft=7,ie=24,_t=28,mt=20,yt=21,bt=22,oe=256;class v extends Error{constructor(e){super(`CBOR decode: ${e}`),this.name="CborDecodeError"}}class Ee{constructor(e){_(this,"buf");_(this,"pos",0);this.buf=e}nextByte(){if(this.pos>=this.buf.length)throw new v("unexpected end of input");return this.buf[this.pos++]}readHead(){const e=this.nextByte(),t=e>>5,n=e&31;if(n<ie)return{major:t,arg:n};if(n>=_t)throw new v(`unsupported additional info ${n} (indefinite-length or reserved)`);const i=1<<n-ie;let s=0n;for(let o=0;o<i;o++)s=s<<8n|BigInt(this.nextByte());if(s>BigInt(Number.MAX_SAFE_INTEGER))throw new v(`argument ${s} exceeds safe integer range`);return{major:t,arg:Number(s)}}readBytes(e){if(this.pos+e>this.buf.length)throw new v("length overruns end of input");const t=this.buf.subarray(this.pos,this.pos+e);return this.pos+=e,t}readByteString(){const e=this.readHead();if(e.major!==j)throw new v(`expected byte string (major ${j}), got major ${e.major}`);return this.readBytes(e.arg)}readValue(e=0){if(e>oe)throw new v(`nesting exceeds maximum depth ${oe}`);const t=this.readHead();switch(t.major){case lt:return t.arg;case ut:return-1-t.arg;case j:return this.readBytes(t.arg);case dt:return new TextDecoder("utf-8",{fatal:!0}).decode(this.readBytes(t.arg));case pt:{const n=[];for(let i=0;i<t.arg;i++)n.push(this.readValue(e+1));return n}case ht:{const n=new Map;for(let i=0;i<t.arg;i++){const s=this.readValue(e+1),o=this.readValue(e+1);n.set(s,o)}return n}case gt:return{tag:t.arg,value:this.readValue(e+1)};case ft:if(t.arg===mt)return!1;if(t.arg===yt)return!0;if(t.arg===bt)return null;throw new v(`unsupported simple/float value ${t.arg}`);default:throw new v(`unsupported major type ${t.major}`)}}}function Se(r){const e=new Ee(r),t=e.readValue();if(e.pos!==r.length)throw new v("trailing bytes after top-level item");return t}const wt="vaultd-jsonrpc",Pt="vaultd-grpc",ae=18,Y=4,ce=-47,xt=1,le=64,At=128,vt=96,Et=64,St=1,kt=2,Ct=3,Tt=4,$t=5,It=6,Rt=7,ue=new TextEncoder().encode("Signature1");class p extends Error{constructor(e,t){super(e),this.reason=t,this.name="CwtVerificationError"}}function Vt(r){const e=de(r.expectedIssuerXOnlyPubkey,"expectedIssuerXOnlyPubkey"),t=de(r.expectedAudienceXOnlyPubkey,"expectedAudienceXOnlyPubkey"),n=Lt(r.ephemeralPubkeyHex),i=Mt(r.token),s=new Ee(i),o=s.readHead();if(o.major!==6||o.arg!==ae)throw new p(`token is not a COSE Sign1 tagged value (tag ${ae})`,"invalid_token_structure");const c=s.readHead();if(c.major!==4||c.arg!==Y)throw new p(`COSE Sign1 must be a ${Y}-element array`,"invalid_token_structure");const d=s.pos,l=s.readByteString(),g=i.subarray(d,s.pos);s.readValue();const y=s.pos,x=s.readByteString(),S=i.subarray(y,s.pos),T=s.readByteString();if(T.length!==le)throw new p(`COSE signature must be ${le} bytes, got ${T.length}`,"invalid_token_structure");if(s.pos!==i.length)throw new p("COSE Sign1 token has trailing bytes after the signature","invalid_token_structure");const A=Ot(l);if(A!==ce)throw new p(`unexpected COSE algorithm ${A} (expected ES256K ${ce})`,"unexpected_algorithm");const I=Bt(g,S),m=F.sha256(I);if(!X.verify(m,n,T,!0))throw new p("COSE signature does not verify against the server's ephemeral key","signature_verification_failed");const u=Nt(x),k=u.audience.toLowerCase();if(k.length!==f.X_ONLY_PUBKEY_HEX_LEN||!C.HEX_RE.test(k))throw new p("token `aud` is not a 32-byte x-only pubkey hex","invalid_claims");if(u.issuedAt>u.expiresAt)throw new p(`token iat (${u.issuedAt}) is after exp (${u.expiresAt})`,"invalid_claims");if(u.issuer.toLowerCase()!==e)throw new p(`token issuer does not match pinned server pubkey: expected ${e}, got ${u.issuer.toLowerCase()}`,"issuer_mismatch");if(u.subject!==r.expectedSubject)throw new p(`token subject mismatch: expected ${r.expectedSubject}, got ${u.subject}`,"subject_mismatch");if(k!==t)throw new p(`token audience does not match depositor pubkey: expected ${t}, got ${k}`,"audience_mismatch");if(u.expiresAt<=r.now)throw new p(`token expired: exp ${u.expiresAt} <= now ${r.now}`,"token_expired");if(r.responseExpiresAt!==u.expiresAt)throw new p(`response expires_at (${r.responseExpiresAt}) does not equal token exp (${u.expiresAt})`,"expiry_mismatch");if(r.serverIdentityExpiresAt<u.expiresAt)throw new p(`server identity expires (${r.serverIdentityExpiresAt}) before token exp (${u.expiresAt})`,"server_identity_expires_before_token");return{issuer:u.issuer,subject:u.subject,audience:k,expiresAt:u.expiresAt,notBefore:u.notBefore,issuedAt:u.issuedAt}}function Ot(r){if(r.length===0)throw new p("empty COSE protected header (no algorithm)","unexpected_algorithm");const e=Se(r);if(!(e instanceof Map))throw new p("COSE protected header is not a map","invalid_token_structure");const t=e.get(xt);if(typeof t!="number")throw new p("COSE protected header missing integer algorithm label","unexpected_algorithm");return t}function Bt(r,e){return Gt(Uint8Array.of(At|Y),Uint8Array.of(vt|ue.length),ue,r,Uint8Array.of(Et),e)}function Nt(r){const e=Se(r);if(!(e instanceof Map))throw new p("CWT claims root is not a map","invalid_claims");if(Ht(e,Rt,"cti").length===0)throw new p("token cti is empty","invalid_claims");return{issuer:U(e,St,"iss"),subject:U(e,kt,"sub"),audience:U(e,Ct,"aud"),expiresAt:K(e,Tt,"exp"),notBefore:K(e,$t,"nbf"),issuedAt:K(e,It,"iat")}}function U(r,e,t){const n=r.get(e);if(typeof n!="string")throw new p(`token claim ${t} is missing or not a text string`,"invalid_claims");return n}function Ht(r,e,t){const n=r.get(e);if(!(n instanceof Uint8Array))throw new p(`token claim ${t} is missing or not a byte string`,"invalid_claims");return n}function K(r,e,t){const n=r.get(e);if(typeof n!="number"||!Number.isSafeInteger(n)||n<0)throw new p(`token claim ${t} is missing or not a non-negative integer timestamp`,"invalid_claims");return n}function de(r,e){const t=f.stripHexPrefix(r).toLowerCase();if(t.length!==f.X_ONLY_PUBKEY_HEX_LEN||!C.HEX_RE.test(t))throw new p(`${e} must be 32-byte x-only hex; got ${t.length} chars`,"invalid_input");return t}function Lt(r){const e=f.stripHexPrefix(r).toLowerCase(),t=e.slice(0,2);if(e.length!==f.COMPRESSED_PUBKEY_HEX_LEN||!C.HEX_RE.test(e)||t!=="02"&&t!=="03")throw new p("ephemeralPubkeyHex must be 33-byte compressed pubkey hex (prefix 02/03)","invalid_input");return f.hexToUint8Array(e)}const Dt=(()=>{const r=new Int16Array(128).fill(-1),e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";for(let t=0;t<e.length;t++)r[e.charCodeAt(t)]=t;return r})();function Mt(r){const e=r.length,t=Math.floor(e/4),n=e%4;if(n===1)throw new p("invalid base64url length","invalid_token_structure");const i=t*3+(n===0?0:n-1),s=new Uint8Array(i),o=l=>{const g=l<128?Dt[l]:-1;if(g<0)throw new p("invalid base64url character","invalid_token_structure");return g};let c=0,d=0;for(let l=0;l<t;l++){const g=o(r.charCodeAt(c++)),y=o(r.charCodeAt(c++)),x=o(r.charCodeAt(c++)),S=o(r.charCodeAt(c++));s[d++]=g<<2|y>>4,s[d++]=(y&15)<<4|x>>2,s[d++]=(x&3)<<6|S}if(n===2){const l=o(r.charCodeAt(c++)),g=o(r.charCodeAt(c++));s[d++]=l<<2|g>>4}else if(n===3){const l=o(r.charCodeAt(c++)),g=o(r.charCodeAt(c++)),y=o(r.charCodeAt(c++));s[d++]=l<<2|g>>4,s[d++]=(g&15)<<4|y>>2}return s}function Gt(...r){const e=r.reduce((i,s)=>i+s.length,0),t=new Uint8Array(e);let n=0;for(const i of r)t.set(i,n),n+=i.length;return t}const pe=4102444800,Xt=30;class jt{constructor(e){_(this,"client");_(this,"peginTxid");_(this,"authAnchorHex");_(this,"pinnedServerPubkey");_(this,"expectedAudienceXOnlyPubkey");_(this,"authGatedMethods");_(this,"grpcGatedMethods");_(this,"refreshSkewSecs");_(this,"now");_(this,"cachedJsonRpc",null);_(this,"inFlightJsonRpc",null);_(this,"cachedGrpc",null);_(this,"inFlightGrpc",null);this.client=e.client,this.peginTxid=e.peginTxid,this.authAnchorHex=e.authAnchorHex,this.pinnedServerPubkey=e.pinnedServerPubkey,this.expectedAudienceXOnlyPubkey=e.expectedAudienceXOnlyPubkey,this.authGatedMethods=e.authGatedMethods,this.grpcGatedMethods=e.grpcGatedMethods,this.refreshSkewSecs=e.refreshSkewSecs??Xt,this.now=e.now??(()=>Math.floor(Date.now()/1e3))}async getToken(e){return e===q||e===J?null:this.grpcGatedMethods.has(e)?this.getTokenForSubject("grpc"):this.authGatedMethods.has(e)?this.getTokenForSubject("jsonrpc"):null}invalidate(){this.cachedJsonRpc=null,this.cachedGrpc=null}async getTokenForSubject(e){const t=e==="grpc"?this.cachedGrpc:this.cachedJsonRpc;return t&&this.now()+this.refreshSkewSecs<t.expiresAt?t.token:(await this.acquireSingleFlight(e)).token}setClient(e){this.client=e}acquireSingleFlight(e){const t=e==="grpc"?this.inFlightGrpc:this.inFlightJsonRpc;if(t)return t;const n=e==="grpc"?J:q,i=(async()=>{try{const s=await this.client.call(n,{pegin_txid:this.peginTxid,auth_anchor:this.authAnchorHex});if(Ae({proof:s.server_identity,pinnedServerPubkey:this.pinnedServerPubkey,now:this.now()}),typeof s.token!="string"||s.token.length===0)throw new Error(`VpTokenProvider: invalid token in acquire response (expected non-empty string, got ${typeof s.token})`);const o=this.now();if(!Number.isSafeInteger(s.expires_at)||s.expires_at<=o||s.expires_at>pe)throw new Error(`VpTokenProvider: invalid expires_at in acquire response (got ${JSON.stringify(s.expires_at)}; must be a safe integer in (${o}, ${pe}])`);Vt({token:s.token,ephemeralPubkeyHex:s.server_identity.ephemeral_pubkey,expectedIssuerXOnlyPubkey:this.pinnedServerPubkey,expectedSubject:e==="grpc"?Pt:wt,expectedAudienceXOnlyPubkey:this.expectedAudienceXOnlyPubkey,responseExpiresAt:s.expires_at,serverIdentityExpiresAt:s.server_identity.expires_at,now:o});const c={token:s.token,expiresAt:s.expires_at};return e==="grpc"?this.cachedGrpc=c:this.cachedJsonRpc=c,c}finally{e==="grpc"?this.inFlightGrpc=null:this.inFlightJsonRpc=null}})();return e==="grpc"?this.inFlightGrpc=i:this.inFlightJsonRpc=i,i}}class ke{constructor(){_(this,"entries",new Map)}getOrCreate(e){const t=this.entries.get(e.peginTxid);if(t){if(t.authAnchorHex!==e.authAnchorHex)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to authAnchorHex ${t.authAnchorHex.slice(0,8)}…; got ${e.authAnchorHex.slice(0,8)}…`);if(t.pinnedServerPubkey!==e.pinnedServerPubkey)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to pinnedServerPubkey ${t.pinnedServerPubkey.slice(0,8)}…; got ${e.pinnedServerPubkey.slice(0,8)}…`);if(t.expectedAudienceXOnlyPubkey!==e.expectedAudienceXOnlyPubkey)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to expectedAudienceXOnlyPubkey ${t.expectedAudienceXOnlyPubkey.slice(0,8)}…; got ${e.expectedAudienceXOnlyPubkey.slice(0,8)}…`);return t.provider.setClient(e.client),t.provider}const n=new jt({client:e.client,peginTxid:e.peginTxid,authAnchorHex:e.authAnchorHex,pinnedServerPubkey:e.pinnedServerPubkey,expectedAudienceXOnlyPubkey:e.expectedAudienceXOnlyPubkey,authGatedMethods:ot,grpcGatedMethods:at});return this.entries.set(e.peginTxid,{provider:n,authAnchorHex:e.authAnchorHex,pinnedServerPubkey:e.pinnedServerPubkey,expectedAudienceXOnlyPubkey:e.expectedAudienceXOnlyPubkey}),n}peek(e){var t;return(t=this.entries.get(e))==null?void 0:t.provider}release(e){this.entries.delete(e)}clear(){this.entries.clear()}get size(){return this.entries.size}}const z=new ke;function Ut(r){var n;const e=ve(r.baseUrl,(n=r.options)==null?void 0:n.headers),t=z.getOrCreate({client:e,peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey,expectedAudienceXOnlyPubkey:f.processPublicKeyToXOnly(r.depositorBtcPubkey)});return new be(r.baseUrl,{...r.options,tokenProvider:t})}function Kt(r){z.getOrCreate({client:ve(r.baseUrl,r.headers),peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey,expectedAudienceXOnlyPubkey:f.processPublicKeyToXOnly(r.depositorBtcPubkey)})}exports.OnChainBtcVaultStatus=he;exports.ServerIdentityError=b;exports.VaultProviderRpcClient=be;exports.ViemProtocolParamsReader=Ve;exports.ViemUniversalChallengerReader=Be;exports.ViemVaultKeeperReader=Oe;exports.VpResponseValidationError=a;exports.VpTokenRegistry=ke;exports.batchPollByProvider=ze;exports.createAuthenticatedVpClient=Ut;exports.primeVpTokenRegistry=Kt;exports.resolveProtocolAddresses=Re;exports.validateRequestDepositorClaimerArtifactsResponse=me;exports.verifyServerIdentity=Ae;exports.vpTokenRegistry=z;
|
|
2
|
+
//# sourceMappingURL=primeVpAuth-yTddDmGy.cjs.map
|