@babylonlabs-io/ts-sdk 2.0.2 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/dist/{PeginManager-CKf7Bjmj.js → PeginManager-D8WGB8eN.js} +2 -2
  2. package/dist/PeginManager-D8WGB8eN.js.map +1 -0
  3. package/dist/{PeginManager-Dt2Z5ljw.cjs → PeginManager-IgDHy_eU.cjs} +2 -2
  4. package/dist/PeginManager-IgDHy_eU.cjs.map +1 -0
  5. package/dist/{buildAndBroadcastReclaim-B19cyK69.js → buildAndBroadcastReclaim-C55KaRJF.js} +783 -791
  6. package/dist/buildAndBroadcastReclaim-C55KaRJF.js.map +1 -0
  7. package/dist/buildAndBroadcastReclaim-CefzR6i_.cjs +2 -0
  8. package/dist/buildAndBroadcastReclaim-CefzR6i_.cjs.map +1 -0
  9. package/dist/index-D2mybjXD.js +522 -0
  10. package/dist/index-D2mybjXD.js.map +1 -0
  11. package/dist/index-MRdle0fs.cjs +2 -0
  12. package/dist/index-MRdle0fs.cjs.map +1 -0
  13. package/dist/index.cjs +1 -1
  14. package/dist/index.js +215 -214
  15. package/dist/pegin-registration-client-B0j6ugt9.cjs +2 -0
  16. package/dist/pegin-registration-client-B0j6ugt9.cjs.map +1 -0
  17. package/dist/{pegin-registration-client-C5Hktrja.js → pegin-registration-client-ilkV1mLP.js} +103 -88
  18. package/dist/pegin-registration-client-ilkV1mLP.js.map +1 -0
  19. package/dist/primeVpAuth-BDWBKYhv.cjs +2 -0
  20. package/dist/primeVpAuth-BDWBKYhv.cjs.map +1 -0
  21. package/dist/primeVpAuth-D0ZnsjRi.js +805 -0
  22. package/dist/primeVpAuth-D0ZnsjRi.js.map +1 -0
  23. package/dist/state-C4WoNCy1.cjs +2 -0
  24. package/dist/state-C4WoNCy1.cjs.map +1 -0
  25. package/dist/{json-rpc-client-CQLbpuKK.js → state-CFn1rT74.js} +136 -88
  26. package/dist/state-CFn1rT74.js.map +1 -0
  27. package/dist/tbv/core/clients/eth/index.cjs +1 -1
  28. package/dist/tbv/core/clients/eth/index.js +2 -2
  29. package/dist/tbv/core/clients/eth/types.d.ts +12 -5
  30. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
  31. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts +12 -3
  32. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
  33. package/dist/tbv/core/clients/index.cjs +1 -1
  34. package/dist/tbv/core/clients/index.js +52 -51
  35. package/dist/tbv/core/clients/mempool/index.cjs +1 -1
  36. package/dist/tbv/core/clients/mempool/index.cjs.map +1 -1
  37. package/dist/tbv/core/clients/mempool/index.d.ts +1 -1
  38. package/dist/tbv/core/clients/mempool/index.d.ts.map +1 -1
  39. package/dist/tbv/core/clients/mempool/index.js +85 -71
  40. package/dist/tbv/core/clients/mempool/index.js.map +1 -1
  41. package/dist/tbv/core/clients/mempool/mempoolApi.d.ts +10 -0
  42. package/dist/tbv/core/clients/mempool/mempoolApi.d.ts.map +1 -1
  43. package/dist/tbv/core/clients/vault-provider/api.d.ts +17 -13
  44. package/dist/tbv/core/clients/vault-provider/api.d.ts.map +1 -1
  45. package/dist/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.d.ts +8 -0
  46. package/dist/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.d.ts.map +1 -1
  47. package/dist/tbv/core/clients/vault-provider/auth/index.d.ts +1 -1
  48. package/dist/tbv/core/clients/vault-provider/auth/index.d.ts.map +1 -1
  49. package/dist/tbv/core/clients/vault-provider/auth/primeVpAuth.d.ts +8 -0
  50. package/dist/tbv/core/clients/vault-provider/auth/primeVpAuth.d.ts.map +1 -1
  51. package/dist/tbv/core/clients/vault-provider/auth/tokenProvider.d.ts +18 -2
  52. package/dist/tbv/core/clients/vault-provider/auth/tokenProvider.d.ts.map +1 -1
  53. package/dist/tbv/core/clients/vault-provider/auth/tokenRegistry.d.ts +26 -6
  54. package/dist/tbv/core/clients/vault-provider/auth/tokenRegistry.d.ts.map +1 -1
  55. package/dist/tbv/core/clients/vault-provider/batchAttribution.d.ts +17 -15
  56. package/dist/tbv/core/clients/vault-provider/batchAttribution.d.ts.map +1 -1
  57. package/dist/tbv/core/clients/vault-provider/batchPoll.d.ts +15 -9
  58. package/dist/tbv/core/clients/vault-provider/batchPoll.d.ts.map +1 -1
  59. package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts +3 -2
  60. package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts.map +1 -1
  61. package/dist/tbv/core/clients/vault-provider/status/index.cjs +1 -1
  62. package/dist/tbv/core/clients/vault-provider/status/index.js +2 -2
  63. package/dist/tbv/core/clients/vault-provider/types.d.ts +36 -23
  64. package/dist/tbv/core/clients/vault-provider/types.d.ts.map +1 -1
  65. package/dist/tbv/core/clients/vault-provider/validators.d.ts +12 -4
  66. package/dist/tbv/core/clients/vault-provider/validators.d.ts.map +1 -1
  67. package/dist/tbv/core/index.cjs +1 -1
  68. package/dist/tbv/core/index.js +216 -215
  69. package/dist/tbv/core/managers/index.cjs +1 -1
  70. package/dist/tbv/core/managers/index.js +1 -1
  71. package/dist/tbv/core/services/deposit/interfaces.d.ts +2 -2
  72. package/dist/tbv/core/services/deposit/interfaces.d.ts.map +1 -1
  73. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts +3 -1
  74. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
  75. package/dist/tbv/core/services/deposit/submitWotsPublicKey.d.ts +3 -1
  76. package/dist/tbv/core/services/deposit/submitWotsPublicKey.d.ts.map +1 -1
  77. package/dist/tbv/core/services/deposit/waitForPeginStatus.d.ts +11 -2
  78. package/dist/tbv/core/services/deposit/waitForPeginStatus.d.ts.map +1 -1
  79. package/dist/tbv/core/services/index.cjs +1 -1
  80. package/dist/tbv/core/services/index.js +75 -74
  81. package/dist/tbv/core/services/index.js.map +1 -1
  82. package/dist/tbv/core/services/pegout/state.d.ts +10 -5
  83. package/dist/tbv/core/services/pegout/state.d.ts.map +1 -1
  84. package/dist/tbv/index.cjs +1 -1
  85. package/dist/tbv/index.js +216 -215
  86. package/dist/{toRefundInputs-DIIdhjvu.js → toRefundInputs-10RYIfh1.js} +2 -2
  87. package/dist/{toRefundInputs-DIIdhjvu.js.map → toRefundInputs-10RYIfh1.js.map} +1 -1
  88. package/dist/{toRefundInputs-B_GlIXjk.cjs → toRefundInputs-a-0HRyrl.cjs} +2 -2
  89. package/dist/{toRefundInputs-B_GlIXjk.cjs.map → toRefundInputs-a-0HRyrl.cjs.map} +1 -1
  90. package/dist/{types-DJxOEU3P.cjs → types-BueQoMjO.cjs} +2 -2
  91. package/dist/{types-DJxOEU3P.cjs.map → types-BueQoMjO.cjs.map} +1 -1
  92. package/dist/{types-Dz1kVqn6.js → types-DGkejGZH.js} +2 -2
  93. package/dist/{types-Dz1kVqn6.js.map → types-DGkejGZH.js.map} +1 -1
  94. package/package.json +1 -1
  95. package/dist/PeginManager-CKf7Bjmj.js.map +0 -1
  96. package/dist/PeginManager-Dt2Z5ljw.cjs.map +0 -1
  97. package/dist/buildAndBroadcastReclaim-B19cyK69.js.map +0 -1
  98. package/dist/buildAndBroadcastReclaim-DcbsjJdf.cjs +0 -2
  99. package/dist/buildAndBroadcastReclaim-DcbsjJdf.cjs.map +0 -1
  100. package/dist/index-Bnavi_r3.js +0 -521
  101. package/dist/index-Bnavi_r3.js.map +0 -1
  102. package/dist/index-CcdCNFLM.cjs +0 -2
  103. package/dist/index-CcdCNFLM.cjs.map +0 -1
  104. package/dist/json-rpc-client-CQLbpuKK.js.map +0 -1
  105. package/dist/json-rpc-client-DbpFfa_o.cjs +0 -2
  106. package/dist/json-rpc-client-DbpFfa_o.cjs.map +0 -1
  107. package/dist/pegin-registration-client-BdJ6c7si.cjs +0 -2
  108. package/dist/pegin-registration-client-BdJ6c7si.cjs.map +0 -1
  109. package/dist/pegin-registration-client-C5Hktrja.js.map +0 -1
  110. package/dist/primeVpAuth-D21PXgg2.cjs +0 -2
  111. package/dist/primeVpAuth-D21PXgg2.cjs.map +0 -1
  112. package/dist/primeVpAuth-PiUJksAq.js +0 -745
  113. package/dist/primeVpAuth-PiUJksAq.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"primeVpAuth-D0ZnsjRi.js","sources":["../src/tbv/core/clients/vault-provider/auth/cbor.ts","../src/tbv/core/clients/vault-provider/auth/serverIdentity.ts","../src/tbv/core/clients/vault-provider/auth/gatedMethods.ts","../src/tbv/core/clients/vault-provider/auth/innerTokenClient.ts","../src/tbv/core/clients/vault-provider/auth/cborDecode.ts","../src/tbv/core/clients/vault-provider/auth/verifyDepositorCwt.ts","../src/tbv/core/clients/vault-provider/auth/tokenProvider.ts","../src/tbv/core/clients/vault-provider/auth/tokenRegistry.ts","../src/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.ts","../src/tbv/core/clients/vault-provider/auth/primeVpAuth.ts"],"sourcesContent":["/**\n * Minimal CBOR encoder for the server-identity payload shape.\n *\n * We only need to encode one specific CBOR structure — the 3-tuple\n * `(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey_bytes, expires_at_u64)` —\n * byte-for-byte identical to what the Rust `ciborium` crate produces\n * for the corresponding tuple, because that's the exact message the\n * VP signs with BIP-322.\n *\n * IMPORTANT encoding quirk: the Rust side passes the domain and\n * pubkey as `&[u8]` / `Vec<u8>` without a `#[serde(with = \"serde_bytes\")]`\n * attribute, so serde/ciborium encodes them as **CBOR arrays of u8**\n * (major type 4, one item per byte) — NOT as CBOR byte strings (major\n * type 2). A naive byte-string encoding would produce the wrong bytes\n * and signature verification would fail.\n *\n * Rather than pull in a full CBOR dependency for this one shape, we\n * implement the exact subset inline (~40 LOC) and pin it with golden\n * vectors against the Rust reference output.\n *\n * @module tbv/core/clients/vault-provider/auth/cbor\n */\n\n/**\n * Encode a small CBOR unsigned-integer \"head\" byte for major type\n * `major` (0..7) with argument `arg` (0..2^64-1).\n *\n * Returns the header bytes; the caller concatenates any trailing data\n * (e.g. array elements). Encoding rules:\n * arg < 24 → single byte `(major << 5) | arg`\n * arg < 256 → `(major << 5) | 24` + 1-byte arg\n * arg < 65536 → `(major << 5) | 25` + 2-byte BE arg\n * arg < 2^32 → `(major << 5) | 26` + 4-byte BE arg\n * arg < 2^64 → `(major << 5) | 27` + 8-byte BE arg\n */\nfunction cborHead(major: number, arg: number | bigint): Uint8Array {\n const tag = (major & 0x07) << 5;\n const n = typeof arg === \"bigint\" ? arg : BigInt(arg);\n if (n < 0n) throw new Error(\"cborHead: negative argument\");\n\n if (n < 24n) return new Uint8Array([tag | Number(n)]);\n if (n < 0x100n) return new Uint8Array([tag | 24, Number(n)]);\n if (n < 0x10000n) {\n const v = Number(n);\n return new Uint8Array([tag | 25, (v >>> 8) & 0xff, v & 0xff]);\n }\n if (n < 0x1_0000_0000n) {\n const v = Number(n);\n return new Uint8Array([\n tag | 26,\n (v >>> 24) & 0xff,\n (v >>> 16) & 0xff,\n (v >>> 8) & 0xff,\n v & 0xff,\n ]);\n }\n // 8-byte BE for u64 range\n const out = new Uint8Array(9);\n out[0] = tag | 27;\n for (let i = 7; i >= 0; i--) {\n out[1 + i] = Number(n >> BigInt((7 - i) * 8)) & 0xff;\n }\n return out;\n}\n\nfunction concat(...parts: Uint8Array[]): Uint8Array {\n const total = parts.reduce((s, p) => s + p.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const p of parts) {\n out.set(p, offset);\n offset += p.length;\n }\n return out;\n}\n\n/**\n * Encode a `Vec<u8>` / `&[u8]` the way ciborium does by default — as a\n * CBOR array of u8 (major type 4), one element per byte.\n *\n * Each byte becomes a CBOR unsigned integer (major type 0): bytes\n * < 24 are encoded as single bytes, bytes 24..255 as `0x18 XX`.\n */\nfunction encodeBytesAsArrayOfU8(bytes: Uint8Array): Uint8Array {\n const header = cborHead(4, bytes.length);\n const items: Uint8Array[] = [header];\n for (const b of bytes) {\n items.push(cborHead(0, b));\n }\n return concat(...items);\n}\n\n/**\n * Encode the server-identity payload the Rust side signs:\n *\n * ciborium::into_writer(\n * &(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey.serialize().to_vec(), expires_at),\n * buf\n * )\n *\n * Output bytes are byte-for-byte identical to the Rust reference,\n * pinned by the golden vector in the corresponding test file.\n *\n * @internal Exposed only for the golden-vector test that pins this\n * encoding against ciborium's output. Production callers reach this\n * via `verifyServerIdentity` from `./serverIdentity`.\n *\n * @param domain - Must be `\"btc-auth.server-identity.v1\"` (27 bytes)\n * — the constant from btc-vault's `server_identity.rs`.\n * @param ephemeralPubkeyCompressed - 33-byte SEC1-compressed pubkey.\n * @param expiresAt - Unix timestamp (seconds). Must be a safe integer.\n */\nexport function encodeServerIdentityPayload(\n domain: Uint8Array,\n ephemeralPubkeyCompressed: Uint8Array,\n expiresAt: number,\n): Uint8Array {\n if (!Number.isSafeInteger(expiresAt) || expiresAt < 0) {\n throw new Error(\n `encodeServerIdentityPayload: expires_at must be a non-negative safe integer, got ${expiresAt}`,\n );\n }\n const arrayHeader = cborHead(4, 3); // 3-tuple encoded as array of 3\n const domainBytes = encodeBytesAsArrayOfU8(domain);\n const pubkeyBytes = encodeBytesAsArrayOfU8(ephemeralPubkeyCompressed);\n const expiresAtBytes = cborHead(0, expiresAt);\n return concat(arrayHeader, domainBytes, pubkeyBytes, expiresAtBytes);\n}\n","/**\n * Server-identity verification for the vault provider's\n * `auth_createDepositorToken` response.\n *\n * The VP returns a `ServerIdentityResponse` bundled with every issued\n * token:\n *\n * - `server_pubkey`: VP's persistent x-only pubkey (HEX, 32B)\n * - `ephemeral_pubkey`: VP's ephemeral token-signing key (HEX, 33B compressed)\n * - `expires_at`: Unix timestamp when the ephemeral key expires\n * - `signature`: BIP-322 signature by the persistent key over\n * `(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey, expires_at)`\n *\n * The FE pins `server_pubkey` against the on-chain `VaultProvider.btcPubKey`\n * it reads from the registry contract. A mismatch rejects the token.\n *\n * @module tbv/core/clients/vault-provider/auth/serverIdentity\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\n\nimport {\n SCHNORR_SIG_HEX_LEN,\n stripHexPrefix,\n} from \"../../../primitives/utils/bitcoin\";\nimport {\n COMPRESSED_PUBKEY_HEX_LEN,\n HEX_RE,\n X_ONLY_PUBKEY_HEX_LEN,\n} from \"../../../utils/validation\";\n\nimport { verifyBip322Simple } from \"./bip322Verify\";\nimport { encodeServerIdentityPayload } from \"./cbor\";\n\n/**\n * Byte-string domain the btc-vault Rust reference passes as the first\n * element of the CBOR tuple signed over for server-identity proofs.\n * Must match `SERVER_IDENTITY_DOMAIN` in\n * `btc-vault/crates/btc-auth/src/server_identity.rs`.\n */\nconst SERVER_IDENTITY_DOMAIN = new TextEncoder().encode(\n \"btc-auth.server-identity.v1\",\n);\n\n/**\n * Cap on `proof.expires_at - now`. Bounds how long a leaked VP\n * ephemeral key stays usable; the bearer token's own TTL does not\n * (different trust boundary). 2h = Rust ref VP's 1h rotation × 2 for\n * clock skew. Override per call via `maxLifetimeSecs`.\n */\nconst DEFAULT_MAX_PROOF_LIFETIME_SECS = 2 * 3600;\n\n/**\n * Wire representation from btc-vault's `ServerIdentityResponse`.\n */\nexport interface ServerIdentityResponse {\n /** Hex-encoded x-only (32-byte) persistent server pubkey. */\n server_pubkey: string;\n /** Hex-encoded compressed (33-byte) ephemeral token-signing pubkey. */\n ephemeral_pubkey: string;\n /** Unix timestamp at which the ephemeral key expires. */\n expires_at: number;\n /** Hex-encoded 64-byte BIP-322 Schnorr signature. */\n signature: string;\n}\n\nexport interface VerifyServerIdentityInput {\n /** The proof returned by `auth_createDepositorToken`. */\n proof: ServerIdentityResponse;\n /**\n * The x-only persistent server pubkey the FE expects (sourced from\n * the on-chain `VaultProvider.btcPubKey` via the vault registry\n * reader). 64-char lowercase hex, no `0x` prefix.\n */\n pinnedServerPubkey: string;\n /** Current Unix timestamp in seconds. Injected for testability. */\n now: number;\n /** Cap on `proof.expires_at - now` (seconds). Defaults to {@link DEFAULT_MAX_PROOF_LIFETIME_SECS}. */\n maxLifetimeSecs?: number;\n}\n\nexport class ServerIdentityError extends Error {\n constructor(\n message: string,\n public readonly reason:\n | \"pinned_pubkey_mismatch\"\n | \"expired\"\n | \"expires_too_far\"\n | \"invalid_expires_at\"\n | \"invalid_max_lifetime\"\n | \"invalid_pubkey_encoding\"\n | \"invalid_ephemeral_pubkey\"\n | \"invalid_signature_encoding\"\n | \"signature_verification_failed\",\n ) {\n super(message);\n this.name = \"ServerIdentityError\";\n }\n}\n\n/** Parse a lowercase-hex string to bytes. Expects even length, already validated. */\nfunction hexToBytes(hex: string): Uint8Array {\n const out = new Uint8Array(hex.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n\n/**\n * Verify a server identity proof against a pinned server pubkey.\n *\n * Checks:\n * 1. `server_pubkey` matches the pin.\n * 2. `now < expires_at <= now + maxLifetimeSecs` (with integer guards).\n * 3. `ephemeral_pubkey` is a well-formed 33-byte compressed pubkey.\n * 4. `signature` is a well-formed 64-byte Schnorr hex string.\n * 5. The BIP-322 Schnorr signature cryptographically verifies\n * against `server_pubkey` over the CBOR-encoded tuple\n * `(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey, expires_at)`.\n *\n * Step 5 is what actually binds the ephemeral key to the persistent\n * pubkey — without it, a TLS-MITM attacker who reads the pinned\n * pubkey from the on-chain registry could substitute an arbitrary\n * ephemeral pubkey paired with any lexically-valid signature.\n *\n * @throws ServerIdentityError on any validation failure.\n */\nexport function verifyServerIdentity(input: VerifyServerIdentityInput): void {\n const { proof, pinnedServerPubkey, now } = input;\n const maxLifetimeSecs =\n input.maxLifetimeSecs ?? DEFAULT_MAX_PROOF_LIFETIME_SECS;\n\n const pinned = stripHexPrefix(pinnedServerPubkey).toLowerCase();\n if (pinned.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(pinned)) {\n throw new ServerIdentityError(\n `pinnedServerPubkey must be 32-byte hex; got ${pinned.length} chars`,\n \"invalid_pubkey_encoding\",\n );\n }\n\n const actual = stripHexPrefix(proof.server_pubkey).toLowerCase();\n if (actual.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(actual)) {\n throw new ServerIdentityError(\n `server_pubkey must be 32-byte hex; got ${actual.length} chars`,\n \"invalid_pubkey_encoding\",\n );\n }\n\n if (actual !== pinned) {\n throw new ServerIdentityError(\n `server_pubkey does not match pinned value: expected ${pinned}, got ${actual}`,\n \"pinned_pubkey_mismatch\",\n );\n }\n\n // Validate both sides of the comparison are well-formed integers\n // BEFORE comparing — untrusted JSON-RPC input can supply\n // undefined/NaN/string values for `expires_at`, and relational\n // comparisons with those silently evaluate to `false` (accepting the\n // proof). Caller's `now` is injected but we still sanity-check it.\n // Garbage data and \"valid but past\" both render the proof unusable\n // but mean different things to a caller — keep the reasons distinct.\n if (!Number.isSafeInteger(proof.expires_at)) {\n throw new ServerIdentityError(\n `expires_at must be a finite integer; got ${JSON.stringify(proof.expires_at)}`,\n \"invalid_expires_at\",\n );\n }\n if (!Number.isSafeInteger(now)) {\n throw new ServerIdentityError(\n `now must be a finite integer; got ${JSON.stringify(now)}`,\n \"invalid_expires_at\",\n );\n }\n if (proof.expires_at <= now) {\n throw new ServerIdentityError(\n `server identity proof expired at ${proof.expires_at}, now ${now}`,\n \"expired\",\n );\n }\n if (!Number.isSafeInteger(maxLifetimeSecs) || maxLifetimeSecs <= 0) {\n throw new ServerIdentityError(\n `maxLifetimeSecs must be a positive safe integer; got ${JSON.stringify(maxLifetimeSecs)}`,\n \"invalid_max_lifetime\",\n );\n }\n if (proof.expires_at - now > maxLifetimeSecs) {\n throw new ServerIdentityError(\n `server identity proof expires too far in the future: ` +\n `expires_at=${proof.expires_at}, now=${now}, max lifetime=${maxLifetimeSecs}s`,\n \"expires_too_far\",\n );\n }\n\n const eph = stripHexPrefix(proof.ephemeral_pubkey).toLowerCase();\n if (eph.length !== COMPRESSED_PUBKEY_HEX_LEN || !HEX_RE.test(eph)) {\n throw new ServerIdentityError(\n `ephemeral_pubkey must be 33-byte compressed hex; got ${eph.length} chars`,\n \"invalid_ephemeral_pubkey\",\n );\n }\n const prefix = eph.slice(0, 2);\n if (prefix !== \"02\" && prefix !== \"03\") {\n throw new ServerIdentityError(\n `ephemeral_pubkey must be compressed (prefix 02/03); got ${prefix}`,\n \"invalid_ephemeral_pubkey\",\n );\n }\n // Curve validation. The BIP-322 signature attests to the byte string\n // of `ephemeral_pubkey` only, not to its curve validity. Without\n // this check, a server could sign a structurally-valid byte string\n // that doesn't decode to a secp256k1 point — passing verification\n // here and surfacing as an obscure crypto error later when the\n // depositor tries to use the key. Reject up front.\n const ephBytes = hexToBytes(eph);\n if (!ecc.isPoint(ephBytes)) {\n throw new ServerIdentityError(\n \"ephemeral_pubkey is not a valid secp256k1 point\",\n \"invalid_ephemeral_pubkey\",\n );\n }\n\n const sig = stripHexPrefix(proof.signature).toLowerCase();\n if (sig.length !== SCHNORR_SIG_HEX_LEN || !HEX_RE.test(sig)) {\n throw new ServerIdentityError(\n `signature must be 64-byte Schnorr hex; got ${sig.length} chars`,\n \"invalid_signature_encoding\",\n );\n }\n\n // Cryptographic verification of the BIP-322 signature over the\n // CBOR-encoded payload. Without this, the ephemeral-key binding is\n // unenforced and a TLS-MITM could substitute a fake ephemeral key\n // alongside the real (publicly-readable) pinned pubkey.\n const payload = encodeServerIdentityPayload(\n SERVER_IDENTITY_DOMAIN,\n hexToBytes(eph),\n proof.expires_at,\n );\n const verified = verifyBip322Simple(\n payload,\n hexToBytes(actual),\n hexToBytes(sig),\n );\n if (!verified) {\n throw new ServerIdentityError(\n \"BIP-322 signature verification failed — ephemeral key is not attested by pinned server pubkey\",\n \"signature_verification_failed\",\n );\n }\n}\n","/**\n * VP RPC methods that require `Authorization: Bearer <token>`.\n * Protocol invariant — must be kept in sync with the VP server.\n *\n * Split into two sets by the CWT subject the VP demands:\n *\n * - {@link AUTH_GATED_METHODS} — bearer minted by\n * `auth_createDepositorToken` (Subject::VaultdJsonRpc). These run\n * through the proxy's plain JSON-RPC forward path.\n * - {@link GRPC_AUTH_GATED_METHODS} — bearer minted by\n * `auth_createDepositorTokenGrpc` (Subject::VaultdGrpc). The proxy\n * translates these into gRPC calls to vaultd's daemon gRPC server,\n * so a JSON-RPC-subject token would be rejected by\n * `GrpcAuthInterceptor`.\n *\n * @stability frozen\n *\n * @module tbv/core/clients/vault-provider/auth/gatedMethods\n */\n\nexport const AUTH_GATED_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_submitDepositorWotsKey\",\n \"vaultProvider_submitDepositorPresignatures\",\n \"vaultProvider_requestDepositorPresignTransactions\",\n]);\n\nexport const GRPC_AUTH_GATED_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_requestDepositorClaimerArtifacts\",\n]);\n","/**\n * Shared internals for the unauthenticated token-issuing JSON-RPC\n * client. The \"inner\" client is dedicated to `auth_createDepositorToken`\n * — it MUST NOT carry a `tokenProvider`, else the JSON-RPC header\n * builder would recurse into token acquisition.\n *\n * @module tbv/core/clients/vault-provider/auth/innerTokenClient\n */\n\nimport { JsonRpcClient } from \"../json-rpc-client\";\n\nconst TOKEN_RPC_TIMEOUT_MS = 60_000;\n\nexport const TOKEN_ISSUE_METHOD = \"auth_createDepositorToken\";\n/**\n * gRPC-subject sibling of {@link TOKEN_ISSUE_METHOD}. The proxy bridges\n * this call to vaultd's `VaultProviderDepositorAuthService.CreateDepositorToken`\n * so the resulting CWT is bound to `Subject::VaultdGrpc` — required to\n * pass vaultd's `GrpcAuthInterceptor` on methods the proxy translates to\n * gRPC (currently just the artifact stream).\n */\nexport const GRPC_TOKEN_ISSUE_METHOD = \"auth_createDepositorTokenGrpc\";\n\nexport function buildInnerTokenClient(\n baseUrl: string,\n headers?: Record<string, string>,\n): JsonRpcClient {\n return new JsonRpcClient({\n baseUrl,\n timeout: TOKEN_RPC_TIMEOUT_MS,\n headers,\n retryableFor: (method) =>\n method === TOKEN_ISSUE_METHOD || method === GRPC_TOKEN_ISSUE_METHOD,\n });\n}\n","/**\n * Minimal CBOR decoder — the read-side counterpart to {@link ./cbor}.\n *\n * Decodes only the subset needed to verify a vault-provider CWT bearer\n * token (RFC 8392) wrapped in a COSE Sign1 envelope (RFC 8152): tagged\n * values, definite-length arrays and maps, byte/text strings, and\n * unsigned/negative integers. Indefinite-length items, floats, and\n * big-number tags are intentionally rejected — the issuer\n * (btc-vault's `coset`/`ciborium` stack) never emits them for this\n * shape, so accepting them would only widen the parser's attack\n * surface.\n *\n * The decoder is a cursor over a single buffer. {@link CborReader.pos}\n * is public so callers can slice the exact encoded byte range of an\n * item (head + content) — required to reconstruct the COSE\n * `Sig_structure` byte-for-byte from the token's own protected-header\n * and payload byte strings.\n *\n * @module tbv/core/clients/vault-provider/auth/cborDecode\n */\n\n/** CBOR major types (the high 3 bits of the initial byte). */\nconst MAJOR_UNSIGNED_INT = 0;\nconst MAJOR_NEGATIVE_INT = 1;\nconst MAJOR_BYTE_STRING = 2;\nconst MAJOR_TEXT_STRING = 3;\nconst MAJOR_ARRAY = 4;\nconst MAJOR_MAP = 5;\nconst MAJOR_TAG = 6;\nconst MAJOR_SIMPLE = 7;\n\n/**\n * Smallest additional-info value that introduces a multi-byte argument\n * (24 ⇒ 1 byte, 25 ⇒ 2, 26 ⇒ 4, 27 ⇒ 8 — i.e. `1 << (info - 24)`).\n */\nconst ARG_IN_NEXT_1_BYTE = 24;\n/** Additional-info ≥ this (28..31) is reserved/indefinite — unsupported. */\nconst ARG_RESERVED_MIN = 28;\n\n/** Major-7 simple values we accept. */\nconst SIMPLE_FALSE = 20;\nconst SIMPLE_TRUE = 21;\nconst SIMPLE_NULL = 22;\n\n/**\n * Maximum CBOR nesting depth. Mirrors the issuer's recursion cap (256 in\n * btc-vault's `ciborium` stack). The COSE protected header is decoded\n * *before* the signature is verified, so without this bound a\n * malicious/MITM'd VP could send a deeply-nested blob and crash token\n * acquisition with an uncatchable stack overflow. Far below the JS call\n * stack limit, so it converts that DoS into a catchable decode error.\n */\nconst MAX_NESTING_DEPTH = 256;\n\n/** A decoded CBOR data item. Maps preserve key insertion order. */\nexport type CborValue =\n | number\n | bigint\n | string\n | Uint8Array\n | boolean\n | null\n | CborValue[]\n | Map<CborValue, CborValue>\n | CborTagged;\n\n/** A CBOR tagged value (major type 6). */\nexport interface CborTagged {\n tag: number;\n value: CborValue;\n}\n\n/** Parsed initial-byte header: major type plus its decoded argument. */\nexport interface CborHead {\n major: number;\n /** The header argument (length, value, tag number, …) as a number. */\n arg: number;\n}\n\nexport class CborDecodeError extends Error {\n constructor(message: string) {\n super(`CBOR decode: ${message}`);\n this.name = \"CborDecodeError\";\n }\n}\n\n/**\n * Cursor-based reader over a CBOR buffer. Not reusable across buffers —\n * construct one per decode.\n */\nexport class CborReader {\n readonly buf: Uint8Array;\n /** Current read offset. Public so callers can slice encoded sub-ranges. */\n pos = 0;\n\n constructor(buf: Uint8Array) {\n this.buf = buf;\n }\n\n private nextByte(): number {\n if (this.pos >= this.buf.length) {\n throw new CborDecodeError(\"unexpected end of input\");\n }\n return this.buf[this.pos++];\n }\n\n /**\n * Read an initial byte and its argument. Rejects indefinite-length\n * and reserved additional-info encodings. Arguments wider than\n * {@link Number.MAX_SAFE_INTEGER} are rejected — none of the token's\n * lengths, tags, or timestamps approach that bound.\n */\n readHead(): CborHead {\n const initial = this.nextByte();\n const major = initial >> 5;\n const info = initial & 0x1f;\n\n if (info < ARG_IN_NEXT_1_BYTE) {\n return { major, arg: info };\n }\n if (info >= ARG_RESERVED_MIN) {\n throw new CborDecodeError(\n `unsupported additional info ${info} (indefinite-length or reserved)`,\n );\n }\n\n const byteCount = 1 << (info - ARG_IN_NEXT_1_BYTE);\n\n let value = 0n;\n for (let i = 0; i < byteCount; i++) {\n value = (value << 8n) | BigInt(this.nextByte());\n }\n if (value > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new CborDecodeError(`argument ${value} exceeds safe integer range`);\n }\n return { major, arg: Number(value) };\n }\n\n /** Read `length` raw bytes as a sub-array view into the backing buffer. */\n private readBytes(length: number): Uint8Array {\n if (this.pos + length > this.buf.length) {\n throw new CborDecodeError(\"length overruns end of input\");\n }\n const slice = this.buf.subarray(this.pos, this.pos + length);\n this.pos += length;\n return slice;\n }\n\n /**\n * Read a byte string (major type 2), returning its content bytes.\n * Throws if the next item is not a byte string.\n */\n readByteString(): Uint8Array {\n const head = this.readHead();\n if (head.major !== MAJOR_BYTE_STRING) {\n throw new CborDecodeError(\n `expected byte string (major ${MAJOR_BYTE_STRING}), got major ${head.major}`,\n );\n }\n return this.readBytes(head.arg);\n }\n\n /**\n * Read the next complete data item as a decoded {@link CborValue}.\n *\n * `depth` tracks the current nesting level so a deeply-nested blob is\n * rejected with a {@link CborDecodeError} rather than overflowing the\n * native call stack (see {@link MAX_NESTING_DEPTH}).\n */\n readValue(depth = 0): CborValue {\n if (depth > MAX_NESTING_DEPTH) {\n throw new CborDecodeError(\n `nesting exceeds maximum depth ${MAX_NESTING_DEPTH}`,\n );\n }\n const head = this.readHead();\n switch (head.major) {\n case MAJOR_UNSIGNED_INT:\n return head.arg;\n case MAJOR_NEGATIVE_INT:\n // RFC 8949 §3.1: the encoded argument n represents -1 - n.\n return -1 - head.arg;\n case MAJOR_BYTE_STRING:\n return this.readBytes(head.arg);\n case MAJOR_TEXT_STRING:\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(\n this.readBytes(head.arg),\n );\n case MAJOR_ARRAY: {\n const items: CborValue[] = [];\n for (let i = 0; i < head.arg; i++) {\n items.push(this.readValue(depth + 1));\n }\n return items;\n }\n case MAJOR_MAP: {\n const map = new Map<CborValue, CborValue>();\n for (let i = 0; i < head.arg; i++) {\n const key = this.readValue(depth + 1);\n const value = this.readValue(depth + 1);\n map.set(key, value);\n }\n return map;\n }\n case MAJOR_TAG:\n return { tag: head.arg, value: this.readValue(depth + 1) };\n case MAJOR_SIMPLE:\n if (head.arg === SIMPLE_FALSE) return false;\n if (head.arg === SIMPLE_TRUE) return true;\n if (head.arg === SIMPLE_NULL) return null;\n throw new CborDecodeError(\n `unsupported simple/float value ${head.arg}`,\n );\n default:\n throw new CborDecodeError(`unsupported major type ${head.major}`);\n }\n }\n}\n\n/**\n * Decode a single CBOR item from `bytes`, rejecting any trailing bytes.\n *\n * Used to parse the COSE protected header and CWT claims set — both are\n * exactly one top-level item, so a valid prefix followed by extra bytes\n * is a malformed structure, not a benign tail. Strict consumption keeps\n * the parser from silently accepting a token a stricter CWT/COSE\n * consumer would interpret differently.\n */\nexport function decodeCbor(bytes: Uint8Array): CborValue {\n const reader = new CborReader(bytes);\n const value = reader.readValue();\n if (reader.pos !== bytes.length) {\n throw new CborDecodeError(\"trailing bytes after top-level item\");\n }\n return value;\n}\n","/**\n * Verify a vault-provider CWT bearer (RFC 8392 / COSE Sign1, ES256K): checks the\n * signature against the VP's attested ephemeral key (see {@link ./serverIdentity})\n * and binds `iss`/`sub`/`aud` to the pinned VP, subject, and depositor. TS port\n * of btc-vault `client.rs::validate_token_with_public_key_at_time`.\n *\n * Divergence from that reference: the FE does NOT clock-gate `nbf`/`iat`. The VP\n * server is the temporal authority and re-checks `nbf`/`exp` on every gated call;\n * re-checking `nbf` against the browser clock only bricked freshly minted tokens\n * on benign skew. `exp` (wide window) and the structural `iat <= exp` are kept.\n *\n * @module tbv/core/clients/vault-provider/auth/verifyDepositorCwt\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\n\nimport {\n hexToUint8Array,\n stripHexPrefix,\n} from \"../../../primitives/utils/bitcoin\";\nimport {\n COMPRESSED_PUBKEY_HEX_LEN,\n HEX_RE,\n X_ONLY_PUBKEY_HEX_LEN,\n} from \"../../../utils/validation\";\n\nimport { CborReader, decodeCbor } from \"./cborDecode\";\n\n/** CWT `sub` value for JSON-RPC-subject tokens (`auth_createDepositorToken`). */\nexport const CWT_SUBJECT_JSONRPC = \"vaultd-jsonrpc\";\n/** CWT `sub` value for gRPC-subject tokens (`auth_createDepositorTokenGrpc`). */\nexport const CWT_SUBJECT_GRPC = \"vaultd-grpc\";\n\n/** CBOR tag wrapping a COSE_Sign1 structure (RFC 8152 §2). */\nconst COSE_SIGN1_TAG = 18;\n/** A COSE_Sign1 is a 4-element array: [protected, unprotected, payload, signature]. */\nconst COSE_SIGN1_ARRAY_LEN = 4;\n/** COSE algorithm id for ES256K (ECDSA w/ secp256k1 + SHA-256), RFC 8812. */\nconst COSE_ALG_ES256K = -47;\n/** COSE header label for the algorithm (RFC 8152 §3.1). */\nconst COSE_HEADER_LABEL_ALG = 1;\n/** ECDSA signature length in COSE compact (r‖s) form. */\nconst ECDSA_COMPACT_SIG_LEN = 64;\n\n/** CBOR major-type 4 (array) high bits, for the Sig_structure header. */\nconst CBOR_ARRAY_HEAD = 0x80;\n/** CBOR major-type 3 (text string) high bits, for the context string head. */\nconst CBOR_TEXT_STRING_HEAD = 0x60;\n/** CBOR encoding of an empty byte string (major type 2, length 0). */\nconst CBOR_EMPTY_BYTE_STRING = 0x40;\n\n/** CWT registered claim keys (RFC 8392 §4 / IANA CWT registry). */\nconst CWT_CLAIM_ISS = 1;\nconst CWT_CLAIM_SUB = 2;\nconst CWT_CLAIM_AUD = 3;\nconst CWT_CLAIM_EXP = 4;\nconst CWT_CLAIM_NBF = 5;\nconst CWT_CLAIM_IAT = 6;\nconst CWT_CLAIM_CTI = 7;\n\n/**\n * Context string for a COSE_Sign1 Sig_structure (RFC 8152 §4.4). 10\n * bytes, so it encodes with a single-byte CBOR text-string head.\n */\nconst SIG_STRUCTURE_CONTEXT = new TextEncoder().encode(\"Signature1\");\n\nexport type CwtVerificationReason =\n | \"invalid_input\"\n | \"invalid_token_structure\"\n | \"unexpected_algorithm\"\n | \"signature_verification_failed\"\n | \"invalid_claims\"\n | \"issuer_mismatch\"\n | \"subject_mismatch\"\n | \"audience_mismatch\"\n | \"token_expired\"\n | \"expiry_mismatch\"\n | \"server_identity_expires_before_token\";\n\nexport class CwtVerificationError extends Error {\n constructor(\n message: string,\n public readonly reason: CwtVerificationReason,\n ) {\n super(message);\n this.name = \"CwtVerificationError\";\n }\n}\n\nexport interface VerifyDepositorCwtInput {\n /** Base64url (no padding) COSE Sign1 token from `auth_createDepositorToken`. */\n token: string;\n /**\n * VP ephemeral token-signing pubkey (33-byte compressed hex) from the\n * bundled `server_identity` proof — MUST already be verified by\n * {@link verifyServerIdentity} before being passed here.\n */\n ephemeralPubkeyHex: string;\n /** Pinned VP persistent x-only pubkey (on-chain). Asserted against the token `iss`. */\n expectedIssuerXOnlyPubkey: string;\n /** Expected `sub` — {@link CWT_SUBJECT_JSONRPC} or {@link CWT_SUBJECT_GRPC}. */\n expectedSubject: string;\n /** Depositor x-only pubkey. Asserted against the token `aud`. */\n expectedAudienceXOnlyPubkey: string;\n /** Outer wire `expires_at`. Must equal the token's `exp` exactly. */\n responseExpiresAt: number;\n /** `server_identity.expires_at`. Must be ≥ the token's `exp`. */\n serverIdentityExpiresAt: number;\n /** Current Unix time (seconds). Injected for testability. */\n now: number;\n}\n\nexport interface VerifiedCwtClaims {\n issuer: string;\n subject: string;\n audience: string;\n expiresAt: number;\n notBefore: number;\n issuedAt: number;\n}\n\n/**\n * Verify a depositor CWT and return its claims, or throw\n * {@link CwtVerificationError}.\n *\n * Steps (mirroring the Rust reference; see the divergence note above):\n * 1. Decode the COSE Sign1 envelope and assert the protected header\n * pins ES256K.\n * 2. Verify the ECDSA signature over the reconstructed Sig_structure\n * against the (already server-identity-verified) ephemeral key.\n * 3. Decode the CWT claims and assert `iss`/`sub`/`aud` bindings, the\n * structural `iat <= exp`, `exp` validity, `cti` presence, and the\n * outer-vs-inner expiry cross-checks. `nbf`/`iat` are intentionally not\n * clock-gated here (see the module note above).\n */\nexport function verifyDepositorCwt(\n input: VerifyDepositorCwtInput,\n): VerifiedCwtClaims {\n const expectedIssuer = normalizeXOnly(\n input.expectedIssuerXOnlyPubkey,\n \"expectedIssuerXOnlyPubkey\",\n );\n const expectedAudience = normalizeXOnly(\n input.expectedAudienceXOnlyPubkey,\n \"expectedAudienceXOnlyPubkey\",\n );\n const ephemeral = decodeCompressedPubkey(input.ephemeralPubkeyHex);\n\n const tokenBytes = base64UrlToBytes(input.token);\n\n // --- 1. COSE Sign1 structural decode -------------------------------\n // Capture the exact encoded byte ranges of the protected header and\n // payload so the Sig_structure can be rebuilt byte-for-byte from the\n // token's own bytes (any re-encoding risks a non-canonical mismatch).\n const reader = new CborReader(tokenBytes);\n const tag = reader.readHead();\n if (tag.major !== 6 || tag.arg !== COSE_SIGN1_TAG) {\n throw new CwtVerificationError(\n `token is not a COSE Sign1 tagged value (tag ${COSE_SIGN1_TAG})`,\n \"invalid_token_structure\",\n );\n }\n const array = reader.readHead();\n if (array.major !== 4 || array.arg !== COSE_SIGN1_ARRAY_LEN) {\n throw new CwtVerificationError(\n `COSE Sign1 must be a ${COSE_SIGN1_ARRAY_LEN}-element array`,\n \"invalid_token_structure\",\n );\n }\n\n const protectedStart = reader.pos;\n const protectedContent = reader.readByteString();\n const protectedBstr = tokenBytes.subarray(protectedStart, reader.pos);\n\n // Unprotected header map: present in the envelope but unused here.\n reader.readValue();\n\n const payloadStart = reader.pos;\n const payloadContent = reader.readByteString();\n const payloadBstr = tokenBytes.subarray(payloadStart, reader.pos);\n\n const signature = reader.readByteString();\n if (signature.length !== ECDSA_COMPACT_SIG_LEN) {\n throw new CwtVerificationError(\n `COSE signature must be ${ECDSA_COMPACT_SIG_LEN} bytes, got ${signature.length}`,\n \"invalid_token_structure\",\n );\n }\n // Reject anything after the COSE_Sign1 structure. The bearer we verify\n // must be the exact bytes attached to authenticated calls; a stricter\n // CWT/COSE consumer could interpret trailing bytes differently.\n if (reader.pos !== tokenBytes.length) {\n throw new CwtVerificationError(\n \"COSE Sign1 token has trailing bytes after the signature\",\n \"invalid_token_structure\",\n );\n }\n\n // --- 2a. Algorithm pin --------------------------------------------\n const alg = readProtectedAlgorithm(protectedContent);\n if (alg !== COSE_ALG_ES256K) {\n throw new CwtVerificationError(\n `unexpected COSE algorithm ${alg} (expected ES256K ${COSE_ALG_ES256K})`,\n \"unexpected_algorithm\",\n );\n }\n\n // --- 2b. Signature verification -----------------------------------\n const sigStructure = buildSigStructure(protectedBstr, payloadBstr);\n const digest = sha256(sigStructure);\n // strict = true enforces low-S, matching libsecp256k1's `verify_ecdsa`.\n if (!ecc.verify(digest, ephemeral, signature, true)) {\n throw new CwtVerificationError(\n \"COSE signature does not verify against the server's ephemeral key\",\n \"signature_verification_failed\",\n );\n }\n\n // --- 3. Claims -----------------------------------------------------\n const claims = decodeClaims(payloadContent);\n\n const audience = claims.audience.toLowerCase();\n if (audience.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(audience)) {\n throw new CwtVerificationError(\n \"token `aud` is not a 32-byte x-only pubkey hex\",\n \"invalid_claims\",\n );\n }\n if (claims.issuedAt > claims.expiresAt) {\n throw new CwtVerificationError(\n `token iat (${claims.issuedAt}) is after exp (${claims.expiresAt})`,\n \"invalid_claims\",\n );\n }\n\n if (claims.issuer.toLowerCase() !== expectedIssuer) {\n throw new CwtVerificationError(\n `token issuer does not match pinned server pubkey: expected ${expectedIssuer}, got ${claims.issuer.toLowerCase()}`,\n \"issuer_mismatch\",\n );\n }\n if (claims.subject !== input.expectedSubject) {\n throw new CwtVerificationError(\n `token subject mismatch: expected ${input.expectedSubject}, got ${claims.subject}`,\n \"subject_mismatch\",\n );\n }\n if (audience !== expectedAudience) {\n throw new CwtVerificationError(\n `token audience does not match depositor pubkey: expected ${expectedAudience}, got ${audience}`,\n \"audience_mismatch\",\n );\n }\n // No nbf/iat clock-gate on purpose — the VP server is the temporal authority\n // (re-checks nbf/exp per call). See the module-level divergence note.\n if (claims.expiresAt <= input.now) {\n throw new CwtVerificationError(\n `token expired: exp ${claims.expiresAt} <= now ${input.now}`,\n \"token_expired\",\n );\n }\n if (input.responseExpiresAt !== claims.expiresAt) {\n throw new CwtVerificationError(\n `response expires_at (${input.responseExpiresAt}) does not equal token exp (${claims.expiresAt})`,\n \"expiry_mismatch\",\n );\n }\n if (input.serverIdentityExpiresAt < claims.expiresAt) {\n throw new CwtVerificationError(\n `server identity expires (${input.serverIdentityExpiresAt}) before token exp (${claims.expiresAt})`,\n \"server_identity_expires_before_token\",\n );\n }\n\n return {\n issuer: claims.issuer,\n subject: claims.subject,\n audience,\n expiresAt: claims.expiresAt,\n notBefore: claims.notBefore,\n issuedAt: claims.issuedAt,\n };\n}\n\n/** Read the algorithm label from the COSE protected-header byte string. */\nfunction readProtectedAlgorithm(protectedContent: Uint8Array): number {\n if (protectedContent.length === 0) {\n throw new CwtVerificationError(\n \"empty COSE protected header (no algorithm)\",\n \"unexpected_algorithm\",\n );\n }\n const header = decodeCbor(protectedContent);\n if (!(header instanceof Map)) {\n throw new CwtVerificationError(\n \"COSE protected header is not a map\",\n \"invalid_token_structure\",\n );\n }\n const alg = header.get(COSE_HEADER_LABEL_ALG);\n if (typeof alg !== \"number\") {\n throw new CwtVerificationError(\n \"COSE protected header missing integer algorithm label\",\n \"unexpected_algorithm\",\n );\n }\n return alg;\n}\n\n/**\n * Rebuild the COSE_Sign1 Sig_structure (RFC 8152 §4.4):\n *\n * [ \"Signature1\", body_protected (bstr), external_aad = h'' , payload (bstr) ]\n *\n * `body_protected` and `payload` are spliced verbatim from the token's\n * own encoded byte strings, so the result is byte-identical to what the\n * issuer signed regardless of CBOR canonicalization choices.\n */\nfunction buildSigStructure(\n protectedBstr: Uint8Array,\n payloadBstr: Uint8Array,\n): Uint8Array {\n return concatBytes(\n Uint8Array.of(CBOR_ARRAY_HEAD | COSE_SIGN1_ARRAY_LEN),\n Uint8Array.of(CBOR_TEXT_STRING_HEAD | SIG_STRUCTURE_CONTEXT.length),\n SIG_STRUCTURE_CONTEXT,\n protectedBstr,\n Uint8Array.of(CBOR_EMPTY_BYTE_STRING),\n payloadBstr,\n );\n}\n\ninterface DecodedClaims {\n issuer: string;\n subject: string;\n audience: string;\n expiresAt: number;\n notBefore: number;\n issuedAt: number;\n}\n\n/** Decode and type-check the CWT registered claims from the payload. */\nfunction decodeClaims(payloadContent: Uint8Array): DecodedClaims {\n const root = decodeCbor(payloadContent);\n if (!(root instanceof Map)) {\n throw new CwtVerificationError(\n \"CWT claims root is not a map\",\n \"invalid_claims\",\n );\n }\n const cti = requireBytes(root, CWT_CLAIM_CTI, \"cti\");\n if (cti.length === 0) {\n throw new CwtVerificationError(\"token cti is empty\", \"invalid_claims\");\n }\n return {\n issuer: requireString(root, CWT_CLAIM_ISS, \"iss\"),\n subject: requireString(root, CWT_CLAIM_SUB, \"sub\"),\n audience: requireString(root, CWT_CLAIM_AUD, \"aud\"),\n expiresAt: requireTimestamp(root, CWT_CLAIM_EXP, \"exp\"),\n notBefore: requireTimestamp(root, CWT_CLAIM_NBF, \"nbf\"),\n issuedAt: requireTimestamp(root, CWT_CLAIM_IAT, \"iat\"),\n };\n}\n\nfunction requireString(\n claims: Map<unknown, unknown>,\n key: number,\n name: string,\n): string {\n const value = claims.get(key);\n if (typeof value !== \"string\") {\n throw new CwtVerificationError(\n `token claim ${name} is missing or not a text string`,\n \"invalid_claims\",\n );\n }\n return value;\n}\n\nfunction requireBytes(\n claims: Map<unknown, unknown>,\n key: number,\n name: string,\n): Uint8Array {\n const value = claims.get(key);\n if (!(value instanceof Uint8Array)) {\n throw new CwtVerificationError(\n `token claim ${name} is missing or not a byte string`,\n \"invalid_claims\",\n );\n }\n return value;\n}\n\nfunction requireTimestamp(\n claims: Map<unknown, unknown>,\n key: number,\n name: string,\n): number {\n const value = claims.get(key);\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n throw new CwtVerificationError(\n `token claim ${name} is missing or not a non-negative integer timestamp`,\n \"invalid_claims\",\n );\n }\n return value;\n}\n\n/** Validate and normalize a 32-byte x-only pubkey to lowercase hex. */\nfunction normalizeXOnly(pubkey: string, label: string): string {\n const normalized = stripHexPrefix(pubkey).toLowerCase();\n if (normalized.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(normalized)) {\n throw new CwtVerificationError(\n `${label} must be 32-byte x-only hex; got ${normalized.length} chars`,\n \"invalid_input\",\n );\n }\n return normalized;\n}\n\n/** Validate a 33-byte compressed pubkey hex and return its bytes. */\nfunction decodeCompressedPubkey(pubkeyHex: string): Uint8Array {\n const normalized = stripHexPrefix(pubkeyHex).toLowerCase();\n const prefix = normalized.slice(0, 2);\n if (\n normalized.length !== COMPRESSED_PUBKEY_HEX_LEN ||\n !HEX_RE.test(normalized) ||\n (prefix !== \"02\" && prefix !== \"03\")\n ) {\n throw new CwtVerificationError(\n \"ephemeralPubkeyHex must be 33-byte compressed pubkey hex (prefix 02/03)\",\n \"invalid_input\",\n );\n }\n return hexToUint8Array(normalized);\n}\n\nconst B64URL_LOOKUP = (() => {\n const table = new Int16Array(128).fill(-1);\n const alphabet =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n for (let i = 0; i < alphabet.length; i++) {\n table[alphabet.charCodeAt(i)] = i;\n }\n return table;\n})();\n\n/** Decode a base64url (no-padding) string to bytes. */\nfunction base64UrlToBytes(input: string): Uint8Array {\n const len = input.length;\n const fullGroups = Math.floor(len / 4);\n const remainder = len % 4;\n if (remainder === 1) {\n throw new CwtVerificationError(\n \"invalid base64url length\",\n \"invalid_token_structure\",\n );\n }\n const outLen = fullGroups * 3 + (remainder === 0 ? 0 : remainder - 1);\n const out = new Uint8Array(outLen);\n\n const sextet = (charCode: number): number => {\n const value = charCode < 128 ? B64URL_LOOKUP[charCode] : -1;\n if (value < 0) {\n throw new CwtVerificationError(\n \"invalid base64url character\",\n \"invalid_token_structure\",\n );\n }\n return value;\n };\n\n let inPos = 0;\n let outPos = 0;\n for (let g = 0; g < fullGroups; g++) {\n const a = sextet(input.charCodeAt(inPos++));\n const b = sextet(input.charCodeAt(inPos++));\n const c = sextet(input.charCodeAt(inPos++));\n const d = sextet(input.charCodeAt(inPos++));\n out[outPos++] = (a << 2) | (b >> 4);\n out[outPos++] = ((b & 0x0f) << 4) | (c >> 2);\n out[outPos++] = ((c & 0x03) << 6) | d;\n }\n if (remainder === 2) {\n const a = sextet(input.charCodeAt(inPos++));\n const b = sextet(input.charCodeAt(inPos++));\n out[outPos++] = (a << 2) | (b >> 4);\n } else if (remainder === 3) {\n const a = sextet(input.charCodeAt(inPos++));\n const b = sextet(input.charCodeAt(inPos++));\n const c = sextet(input.charCodeAt(inPos++));\n out[outPos++] = (a << 2) | (b >> 4);\n out[outPos++] = ((b & 0x0f) << 4) | (c >> 2);\n }\n return out;\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n const total = parts.reduce((sum, part) => sum + part.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n","/**\n * `VpTokenProvider` — caches CWT bearer tokens issued by the vault\n * provider's `auth_createDepositorToken` RPC, with lazy expiry check\n * and single-flight concurrent acquire.\n *\n * Usage:\n *\n * ```ts\n * const provider = new VpTokenProvider({\n * client,\n * peginTxid,\n * authAnchorHex,\n * pinnedServerPubkey,\n * authGatedMethods,\n * });\n * const bearer = await provider.getToken(method); // null if not gated\n * ```\n *\n * The provider implements the `BearerTokenProvider` interface expected\n * by `JsonRpcClient`. Plug directly:\n *\n * ```ts\n * const client = new JsonRpcClient({ ..., tokenProvider: provider });\n * ```\n *\n * @module tbv/core/clients/vault-provider/auth/tokenProvider\n */\n\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\nimport type { BearerTokenProvider, JsonRpcClient } from \"../json-rpc-client\";\nimport {\n GRPC_TOKEN_ISSUE_METHOD,\n TOKEN_ISSUE_METHOD,\n} from \"./innerTokenClient\";\nimport {\n ServerIdentityError,\n type ServerIdentityResponse,\n verifyServerIdentity,\n} from \"./serverIdentity\";\nimport {\n CWT_SUBJECT_GRPC,\n CWT_SUBJECT_JSONRPC,\n CwtVerificationError,\n verifyDepositorCwt,\n} from \"./verifyDepositorCwt\";\n\n/**\n * Maximum reasonable `expires_at` value (seconds since epoch). Guards\n * against a bogus far-future timestamp that would lock the cache on a\n * bad token forever. Jan 1, 2100 in Unix seconds.\n */\nconst MAX_EXPIRES_AT_SECS = 4_102_444_800;\n\n/**\n * Default safety margin before `expires_at` — we treat a token as\n * expired this many seconds before its stated expiry so that in-flight\n * requests don't race the expiry boundary.\n */\nconst DEFAULT_REFRESH_SKEW_SECS = 30;\n\n/**\n * Wire response shape of `auth_createDepositorToken`.\n */\nexport interface CreateDepositorTokenResponse {\n /** Base64url-encoded COSE Sign1 CWT bearer token. */\n token: string;\n /** Unix timestamp at which the token expires. */\n expires_at: number;\n /** Server identity proof bundled with every token response. */\n server_identity: ServerIdentityResponse;\n}\n\nexport interface VpTokenProviderConfig {\n client: JsonRpcClient;\n /** Per-vault depositor-signed PegIn tx id. NOT shared across sibling vaults in a batch. */\n peginTxid: string;\n /** 64-char hex of the 32-byte OP_RETURN auth-anchor preimage. */\n authAnchorHex: string;\n /** Live JSON-RPC-subject VP pubkey from chain; branded so mirrors can't substitute it. */\n pinnedServerPubkey: OnChainBtcPubkey;\n /**\n * Pin for the gRPC-subject bootstrap. This must be the operation key at the\n * vault's frozen VP epoch: vaultd signs this subject with that key.\n */\n grpcPinnedServerPubkey: OnChainBtcPubkey;\n /**\n * Re-read the authoritative current operation key after a JSON-RPC-subject\n * identity mismatch. The provider retries at most once, and only when the\n * chain returns a key different from the stale pin.\n */\n refreshJsonRpcPinnedServerPubkey?: () => Promise<OnChainBtcPubkey>;\n /**\n * Depositor x-only pubkey (32-byte hex). Asserted against every\n * issued token's CWT `aud` claim so a token minted for a different\n * depositor — or mis-issued by a buggy/compromised VP — is rejected\n * before it can authenticate a mutation.\n */\n expectedAudienceXOnlyPubkey: string;\n /**\n * Methods that need a JSON-RPC-subject bearer (minted via\n * `auth_createDepositorToken`). Forwarded over plain HTTP JSON-RPC by\n * the proxy. `getToken` returns `null` for any method outside this and\n * {@link grpcGatedMethods}.\n */\n authGatedMethods: ReadonlySet<string>;\n /**\n * Methods that need a gRPC-subject bearer (minted via\n * `auth_createDepositorTokenGrpc`). The proxy translates these into\n * gRPC calls to vaultd; the JSON-RPC bearer is rejected with a\n * `Subject` mismatch.\n */\n grpcGatedMethods: ReadonlySet<string>;\n /** Default {@link DEFAULT_REFRESH_SKEW_SECS}. */\n refreshSkewSecs?: number;\n /** Clock source for testability. */\n now?: () => number;\n}\n\ninterface CachedToken {\n token: string;\n expiresAt: number;\n}\n\n/**\n * Acquire, cache, and refresh VP bearer tokens.\n *\n * Implements {@link BearerTokenProvider}. Safe to pass directly into\n * `JsonRpcClient` as `tokenProvider`.\n */\nexport class VpTokenProvider implements BearerTokenProvider {\n // Most identity-bearing fields remain readonly and are checked against\n // re-registration in the registry's `getOrCreate`. The JSON-RPC pin is the\n // one exception: RFC-006 explicitly permits it to move, but only to a value\n // re-read through the caller's authoritative chain resolver.\n private client: JsonRpcClient;\n private readonly peginTxid: string;\n private readonly authAnchorHex: string;\n private jsonRpcPinnedServerPubkey: OnChainBtcPubkey;\n private readonly grpcPinnedServerPubkey: OnChainBtcPubkey;\n private readonly refreshJsonRpcPinnedServerPubkey?: () => Promise<OnChainBtcPubkey>;\n private readonly expectedAudienceXOnlyPubkey: string;\n private readonly authGatedMethods: ReadonlySet<string>;\n private readonly grpcGatedMethods: ReadonlySet<string>;\n private readonly refreshSkewSecs: number;\n private readonly now: () => number;\n\n /** Cached JSON-RPC-subject bearer (auth_createDepositorToken). */\n private cachedJsonRpc: CachedToken | null = null;\n private inFlightJsonRpc: Promise<CachedToken> | null = null;\n /** Cached gRPC-subject bearer (auth_createDepositorTokenGrpc). */\n private cachedGrpc: CachedToken | null = null;\n private inFlightGrpc: Promise<CachedToken> | null = null;\n\n constructor(config: VpTokenProviderConfig) {\n this.client = config.client;\n this.peginTxid = config.peginTxid;\n this.authAnchorHex = config.authAnchorHex;\n this.jsonRpcPinnedServerPubkey = config.pinnedServerPubkey;\n this.grpcPinnedServerPubkey = config.grpcPinnedServerPubkey;\n this.refreshJsonRpcPinnedServerPubkey =\n config.refreshJsonRpcPinnedServerPubkey;\n this.expectedAudienceXOnlyPubkey = config.expectedAudienceXOnlyPubkey;\n this.authGatedMethods = config.authGatedMethods;\n this.grpcGatedMethods = config.grpcGatedMethods;\n this.refreshSkewSecs = config.refreshSkewSecs ?? DEFAULT_REFRESH_SKEW_SECS;\n this.now = config.now ?? (() => Math.floor(Date.now() / 1000));\n }\n\n /**\n * Return a bearer token for `method`, or `null` if `method` is not\n * auth-gated.\n *\n * Routes by subject: `authGatedMethods` → JSON-RPC bearer (issued via\n * `auth_createDepositorToken`); `grpcGatedMethods` → gRPC bearer\n * (`auth_createDepositorTokenGrpc`). Either path acquires lazily and\n * single-flights concurrent callers; the two cache slots are\n * independent.\n *\n * Both token-issuing methods are hard-exempted from the gate — if\n * either were ever included in the gated sets (caller misconfiguration)\n * the provider would recurse into `acquireSingleFlight` from inside the\n * JSON-RPC header builder before `inFlight` is assigned, defeating the\n * single-flight guard. Returning `null` here breaks that recursion\n * deterministically.\n */\n async getToken(method: string): Promise<string | null> {\n if (method === TOKEN_ISSUE_METHOD || method === GRPC_TOKEN_ISSUE_METHOD) {\n return null;\n }\n\n if (this.grpcGatedMethods.has(method)) {\n return this.getTokenForSubject(\"grpc\");\n }\n if (this.authGatedMethods.has(method)) {\n return this.getTokenForSubject(\"jsonrpc\");\n }\n return null;\n }\n\n /**\n * Drop both cached tokens. Next `getToken` call re-acquires the slot\n * that's actually needed. Called by `JsonRpcClient` on wire\n * `auth_expired` responses; the client doesn't tell us which subject\n * expired, so we evict both to stay correct under either.\n *\n * Worst case is one extra round-trip on the slot that was still fresh,\n * which is cheaper than carrying a `Subject` argument through\n * `BearerTokenProvider`.\n */\n invalidate(): void {\n this.cachedJsonRpc = null;\n this.cachedGrpc = null;\n // Do NOT clear `inFlight*` — a concurrent acquire is still valid;\n // the invalidator is saying \"the cached token is bad\", not \"any\n // in-flight acquire is bad\". The in-flight acquire will populate\n // a fresh `cached*` on completion.\n }\n\n private async getTokenForSubject(\n subject: \"jsonrpc\" | \"grpc\",\n ): Promise<string> {\n const cached = subject === \"grpc\" ? this.cachedGrpc : this.cachedJsonRpc;\n if (cached && this.now() + this.refreshSkewSecs < cached.expiresAt) {\n return cached.token;\n }\n const fresh = await this.acquireSingleFlight(subject);\n return fresh.token;\n }\n\n /**\n * Swap in a different transport for subsequent token-issuing calls.\n * Used by the registry when a later caller registers the same\n * `peginTxid` against a different `baseUrl` — the cached token\n * (bound to identity, not transport) stays valid, but future\n * refreshes hit the new URL. An in-flight acquire keeps using the\n * old client (it captured the reference); next call uses the new.\n */\n setClient(client: JsonRpcClient): void {\n this.client = client;\n }\n\n /** Current subject-specific pin, exposed for registry identity checks. */\n getPinnedServerPubkey(subject: \"jsonrpc\" | \"grpc\"): OnChainBtcPubkey {\n return subject === \"grpc\"\n ? this.grpcPinnedServerPubkey\n : this.jsonRpcPinnedServerPubkey;\n }\n\n private acquireSingleFlight(\n subject: \"jsonrpc\" | \"grpc\",\n ): Promise<CachedToken> {\n const existing =\n subject === \"grpc\" ? this.inFlightGrpc : this.inFlightJsonRpc;\n if (existing) return existing;\n\n const issueMethod =\n subject === \"grpc\" ? GRPC_TOKEN_ISSUE_METHOD : TOKEN_ISSUE_METHOD;\n\n const p = (async () => {\n try {\n const fresh = await this.acquireAndVerify(subject, issueMethod, true);\n if (subject === \"grpc\") {\n this.cachedGrpc = fresh;\n } else {\n this.cachedJsonRpc = fresh;\n }\n return fresh;\n } finally {\n if (subject === \"grpc\") {\n this.inFlightGrpc = null;\n } else {\n this.inFlightJsonRpc = null;\n }\n }\n })();\n\n if (subject === \"grpc\") {\n this.inFlightGrpc = p;\n } else {\n this.inFlightJsonRpc = p;\n }\n return p;\n }\n\n private async acquireAndVerify(\n subject: \"jsonrpc\" | \"grpc\",\n issueMethod: string,\n allowPinRefresh: boolean,\n ): Promise<CachedToken> {\n const response = await this.client.call<\n { pegin_txid: string; auth_anchor: string },\n CreateDepositorTokenResponse\n >(issueMethod, {\n pegin_txid: this.peginTxid,\n auth_anchor: this.authAnchorHex,\n });\n const pinnedServerPubkey = this.getPinnedServerPubkey(subject);\n\n try {\n verifyServerIdentity({\n proof: response.server_identity,\n pinnedServerPubkey,\n now: this.now(),\n });\n\n // Validate wire payload before caching so a malformed response\n // from a compromised VP or proxy can't poison the cache with\n // unusable values (non-string token, non-integer expiry, etc.).\n if (typeof response.token !== \"string\" || response.token.length === 0) {\n throw new Error(\n `VpTokenProvider: invalid token in acquire response (expected non-empty string, got ${typeof response.token})`,\n );\n }\n const now = this.now();\n if (\n !Number.isSafeInteger(response.expires_at) ||\n response.expires_at <= now ||\n response.expires_at > MAX_EXPIRES_AT_SECS\n ) {\n throw new Error(\n `VpTokenProvider: invalid expires_at in acquire response (got ${JSON.stringify(response.expires_at)}; must be a safe integer in (${now}, ${MAX_EXPIRES_AT_SECS}])`,\n );\n }\n\n // Cryptographically verify the token itself — not just the wire\n // envelope. The COSE Sign1 signature is checked against the\n // (server-identity-verified) ephemeral key, and the inner CWT\n // claims are bound to this depositor (`aud`), this VP (`iss`),\n // and this subject. Without this the bearer is an opaque blob the\n // FE would attach to mutations on the VP's word alone.\n verifyDepositorCwt({\n token: response.token,\n ephemeralPubkeyHex: response.server_identity.ephemeral_pubkey,\n expectedIssuerXOnlyPubkey: pinnedServerPubkey,\n expectedSubject:\n subject === \"grpc\" ? CWT_SUBJECT_GRPC : CWT_SUBJECT_JSONRPC,\n expectedAudienceXOnlyPubkey: this.expectedAudienceXOnlyPubkey,\n responseExpiresAt: response.expires_at,\n serverIdentityExpiresAt: response.server_identity.expires_at,\n now,\n });\n\n return {\n token: response.token,\n expiresAt: response.expires_at,\n };\n } catch (error) {\n if (\n allowPinRefresh &&\n subject === \"jsonrpc\" &&\n this.refreshJsonRpcPinnedServerPubkey &&\n isPinnedIdentityMismatch(error)\n ) {\n const refreshed = await this.refreshJsonRpcPinnedServerPubkey();\n if (refreshed !== this.jsonRpcPinnedServerPubkey) {\n this.jsonRpcPinnedServerPubkey = refreshed;\n return this.acquireAndVerify(subject, issueMethod, false);\n }\n }\n throw error;\n }\n }\n}\n\nfunction isPinnedIdentityMismatch(error: unknown): boolean {\n return (\n (error instanceof ServerIdentityError &&\n error.reason === \"pinned_pubkey_mismatch\") ||\n (error instanceof CwtVerificationError &&\n error.reason === \"issuer_mismatch\")\n );\n}\n","/**\n * In-memory registry of {@link VpTokenProvider} instances keyed by\n * the per-vault depositor-signed PegIn tx hash. Module-level\n * singleton, per-tab, never persisted.\n *\n * @module tbv/core/clients/vault-provider/auth/tokenRegistry\n */\n\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\nimport type { JsonRpcClient } from \"../json-rpc-client\";\n\nimport { AUTH_GATED_METHODS, GRPC_AUTH_GATED_METHODS } from \"./gatedMethods\";\nimport { VpTokenProvider } from \"./tokenProvider\";\n\nexport interface VpTokenRegistryInput {\n client: JsonRpcClient;\n peginTxid: string;\n authAnchorHex: string;\n /** Stable provider identity used to prevent cross-provider cache reuse. */\n providerAddress: string;\n pinnedServerPubkey: OnChainBtcPubkey;\n /** Frozen-epoch issuer used only by the gRPC token subject. */\n grpcPinnedServerPubkey: OnChainBtcPubkey;\n /** Frozen VP epoch that selected `grpcPinnedServerPubkey`. */\n grpcKeyEpoch: bigint;\n /** Authoritative live-key resolver for bounded JSON-RPC pin recovery. */\n refreshJsonRpcPinnedServerPubkey?: () => Promise<OnChainBtcPubkey>;\n /** Depositor x-only pubkey (32-byte hex), asserted against each token's CWT `aud`. */\n expectedAudienceXOnlyPubkey: string;\n}\n\nexport interface VpTokenRegistryLookup {\n peginTxid: string;\n providerAddress: string;\n expectedAudienceXOnlyPubkey: string;\n}\n\ninterface RegistryEntry {\n provider: VpTokenProvider;\n authAnchorHex: string;\n providerAddress: string;\n grpcKeyEpoch: bigint;\n expectedAudienceXOnlyPubkey: string;\n}\n\nexport class VpTokenRegistry {\n private readonly entries = new Map<string, RegistryEntry>();\n\n /**\n * Return the cached `VpTokenProvider` for `peginTxid` if one exists\n * with matching anchor, provider, audience, and subject-specific issuer\n * bindings, otherwise construct and cache a fresh provider. A mismatch\n * throws — silent overwrite would mask derivation drift or cross-provider\n * cache reuse. A legitimate live JSON-RPC key rotation is handled inside\n * `VpTokenProvider` through its chain-backed refresh callback.\n */\n getOrCreate(input: VpTokenRegistryInput): VpTokenProvider {\n const existing = this.entries.get(input.peginTxid);\n if (existing) {\n if (existing.authAnchorHex !== input.authAnchorHex) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to authAnchorHex ${existing.authAnchorHex.slice(0, 8)}…; got ${input.authAnchorHex.slice(0, 8)}…`,\n );\n }\n // Case-insensitive, as in `peek`: callers prime with the indexer's\n // lowercase address or the contract's checksummed one.\n if (\n existing.providerAddress.toLowerCase() !==\n input.providerAddress.toLowerCase()\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to providerAddress ${existing.providerAddress}; got ${input.providerAddress}`,\n );\n }\n if (\n existing.provider.getPinnedServerPubkey(\"jsonrpc\") !==\n input.pinnedServerPubkey\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to JSON-RPC pinnedServerPubkey ${existing.provider.getPinnedServerPubkey(\"jsonrpc\").slice(0, 8)}…; got ${input.pinnedServerPubkey.slice(0, 8)}…`,\n );\n }\n if (\n existing.provider.getPinnedServerPubkey(\"grpc\") !==\n input.grpcPinnedServerPubkey\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to gRPC pinnedServerPubkey ${existing.provider.getPinnedServerPubkey(\"grpc\").slice(0, 8)}…; got ${input.grpcPinnedServerPubkey.slice(0, 8)}…`,\n );\n }\n if (existing.grpcKeyEpoch !== input.grpcKeyEpoch) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to gRPC key epoch ${existing.grpcKeyEpoch.toString()}; got ${input.grpcKeyEpoch.toString()}`,\n );\n }\n if (\n existing.expectedAudienceXOnlyPubkey.toLowerCase() !==\n input.expectedAudienceXOnlyPubkey.toLowerCase()\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to expectedAudienceXOnlyPubkey ${existing.expectedAudienceXOnlyPubkey.slice(0, 8)}…; got ${input.expectedAudienceXOnlyPubkey.slice(0, 8)}…`,\n );\n }\n // Refresh the inner transport on every reuse so a VP URL\n // change between calls doesn't leave the cached provider\n // pinned to a dead URL for token refresh.\n existing.provider.setClient(input.client);\n return existing.provider;\n }\n\n const provider = new VpTokenProvider({\n client: input.client,\n peginTxid: input.peginTxid,\n authAnchorHex: input.authAnchorHex,\n pinnedServerPubkey: input.pinnedServerPubkey,\n grpcPinnedServerPubkey: input.grpcPinnedServerPubkey,\n refreshJsonRpcPinnedServerPubkey: input.refreshJsonRpcPinnedServerPubkey,\n expectedAudienceXOnlyPubkey: input.expectedAudienceXOnlyPubkey,\n authGatedMethods: AUTH_GATED_METHODS,\n grpcGatedMethods: GRPC_AUTH_GATED_METHODS,\n });\n this.entries.set(input.peginTxid, {\n provider,\n authAnchorHex: input.authAnchorHex,\n providerAddress: input.providerAddress,\n grpcKeyEpoch: input.grpcKeyEpoch,\n expectedAudienceXOnlyPubkey: input.expectedAudienceXOnlyPubkey,\n });\n return provider;\n }\n\n /**\n * Return the cached provider only when its request-facing identity matches.\n * A missing entry is a normal cold-cache result; a binding mismatch throws\n * so callers cannot attach one provider's bearer to another provider or\n * depositor request.\n */\n peek(input: VpTokenRegistryLookup): VpTokenProvider | undefined {\n const existing = this.entries.get(input.peginTxid);\n if (!existing) return undefined;\n\n if (\n existing.providerAddress.toLowerCase() !==\n input.providerAddress.toLowerCase()\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to providerAddress ${existing.providerAddress}; got ${input.providerAddress}`,\n );\n }\n if (\n existing.expectedAudienceXOnlyPubkey.toLowerCase() !==\n input.expectedAudienceXOnlyPubkey.toLowerCase()\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to expectedAudienceXOnlyPubkey ${existing.expectedAudienceXOnlyPubkey.slice(0, 8)}…; got ${input.expectedAudienceXOnlyPubkey.slice(0, 8)}…`,\n );\n }\n\n return existing.provider;\n }\n\n /**\n * Evict the entry for `peginTxid`. Idempotent. Called on terminal\n * paths — activation success, user-cancel, or component unmount —\n * so `authAnchorHex` doesn't outlive the deposit session.\n */\n release(peginTxid: string): void {\n this.entries.delete(peginTxid);\n }\n\n /**\n * Wipe every cached entry. Test-only escape hatch — not exposed on\n * the public {@link VpTokenRegistryPublic} singleton type.\n *\n * @internal\n */\n clear(): void {\n this.entries.clear();\n }\n\n get size(): number {\n return this.entries.size;\n }\n}\n\n/**\n * Public surface of the singleton — excludes the test-only `clear`\n * method.\n */\nexport interface VpTokenRegistryPublic {\n getOrCreate(input: VpTokenRegistryInput): VpTokenProvider;\n peek(input: VpTokenRegistryLookup): VpTokenProvider | undefined;\n release(peginTxid: string): void;\n readonly size: number;\n}\n\nexport const vpTokenRegistry: VpTokenRegistryPublic = new VpTokenRegistry();\n","/**\n * Build a {@link VaultProviderRpcClient} that auto-attaches CWT\n * bearer tokens on auth-gated methods. Caller pre-derives both the\n * `authAnchorHex` (from the wallet) and the `pinnedServerPubkey`\n * (from the on-chain registry) and hands them in — the SDK has no\n * notion of wallets here.\n *\n * @module tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient\n */\n\nimport { processPublicKeyToXOnly } from \"../../../primitives/utils/bitcoin\";\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\nimport {\n VaultProviderRpcClient,\n type VaultProviderRpcClientOptions,\n} from \"../api\";\n\nimport { buildInnerTokenClient } from \"./innerTokenClient\";\nimport { vpTokenRegistry } from \"./tokenRegistry\";\n\nexport interface AuthenticatedVpClientConfig {\n /** Base URL of the VP RPC endpoint (already proxied if applicable). */\n baseUrl: string;\n /** Per-vault depositor-signed PegIn tx id (registry cache key). */\n peginTxid: string;\n /** Already-derived 32-byte auth-anchor preimage (64-char hex, no `0x`). */\n authAnchorHex: string;\n /** Stable vault-provider address used to scope the registry entry. */\n providerAddress: string;\n /** On-chain VP pubkey, branded so it can only come from the registry reader. */\n pinnedServerPubkey: OnChainBtcPubkey;\n /** Frozen-epoch VP pubkey used by the gRPC-subject bootstrap. */\n grpcPinnedServerPubkey: OnChainBtcPubkey;\n /** Vault's frozen VP epoch, paired with `grpcPinnedServerPubkey`. */\n grpcKeyEpoch: bigint;\n /** Re-read the current operation key after a JSON-RPC identity mismatch. */\n refreshJsonRpcPinnedServerPubkey?: () => Promise<OnChainBtcPubkey>;\n /**\n * Depositor BTC pubkey (x-only or compressed hex). Normalized to\n * x-only and asserted against every issued token's CWT `aud` claim.\n */\n depositorBtcPubkey: string;\n /** Optional outer-client tunables (timeout, retries, headers, etc.). */\n options?: VaultProviderRpcClientOptions;\n}\n\nexport function createAuthenticatedVpClient(\n config: AuthenticatedVpClientConfig,\n): VaultProviderRpcClient {\n const innerTokenClient = buildInnerTokenClient(\n config.baseUrl,\n config.options?.headers,\n );\n\n const tokenProvider = vpTokenRegistry.getOrCreate({\n client: innerTokenClient,\n peginTxid: config.peginTxid,\n authAnchorHex: config.authAnchorHex,\n providerAddress: config.providerAddress,\n pinnedServerPubkey: config.pinnedServerPubkey,\n grpcPinnedServerPubkey: config.grpcPinnedServerPubkey,\n grpcKeyEpoch: config.grpcKeyEpoch,\n refreshJsonRpcPinnedServerPubkey: config.refreshJsonRpcPinnedServerPubkey,\n expectedAudienceXOnlyPubkey: processPublicKeyToXOnly(\n config.depositorBtcPubkey,\n ),\n });\n\n return new VaultProviderRpcClient(config.baseUrl, {\n ...config.options,\n tokenProvider,\n });\n}\n","/**\n * Pre-populate {@link vpTokenRegistry} when the caller already has\n * both the auth-anchor preimage and the on-chain VP pubkey. Seeds\n * the cache for a `peginTxid` so a later `createAuthenticatedVpClient`\n * call reuses the cached `VpTokenProvider` instead of rebuilding it.\n *\n * @module tbv/core/clients/vault-provider/auth/primeVpAuth\n */\n\nimport { processPublicKeyToXOnly } from \"../../../primitives/utils/bitcoin\";\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\n\nimport { buildInnerTokenClient } from \"./innerTokenClient\";\nimport { vpTokenRegistry } from \"./tokenRegistry\";\n\nexport interface PrimeVpAuthInput {\n baseUrl: string;\n peginTxid: string;\n authAnchorHex: string;\n /** Stable vault-provider address used to scope the registry entry. */\n providerAddress: string;\n pinnedServerPubkey: OnChainBtcPubkey;\n /** Frozen-epoch VP pubkey used by the gRPC-subject bootstrap. */\n grpcPinnedServerPubkey: OnChainBtcPubkey;\n /** Vault's frozen VP epoch, paired with `grpcPinnedServerPubkey`. */\n grpcKeyEpoch: bigint;\n /** Re-read the current operation key after a JSON-RPC identity mismatch. */\n refreshJsonRpcPinnedServerPubkey?: () => Promise<OnChainBtcPubkey>;\n /**\n * Depositor BTC pubkey (x-only or compressed hex). Normalized to\n * x-only and asserted against every issued token's CWT `aud` claim.\n */\n depositorBtcPubkey: string;\n /** Optional headers forwarded to the inner token client (e.g. gateway auth). */\n headers?: Record<string, string>;\n}\n\nexport function primeVpTokenRegistry(input: PrimeVpAuthInput): void {\n vpTokenRegistry.getOrCreate({\n client: buildInnerTokenClient(input.baseUrl, input.headers),\n peginTxid: input.peginTxid,\n authAnchorHex: input.authAnchorHex,\n providerAddress: input.providerAddress,\n pinnedServerPubkey: input.pinnedServerPubkey,\n grpcPinnedServerPubkey: input.grpcPinnedServerPubkey,\n grpcKeyEpoch: input.grpcKeyEpoch,\n refreshJsonRpcPinnedServerPubkey: input.refreshJsonRpcPinnedServerPubkey,\n expectedAudienceXOnlyPubkey: processPublicKeyToXOnly(\n input.depositorBtcPubkey,\n ),\n });\n}\n"],"names":["cborHead","major","arg","tag","v","out","concat","parts","total","p","offset","encodeBytesAsArrayOfU8","bytes","items","b","encodeServerIdentityPayload","domain","ephemeralPubkeyCompressed","expiresAt","arrayHeader","domainBytes","pubkeyBytes","expiresAtBytes","SERVER_IDENTITY_DOMAIN","DEFAULT_MAX_PROOF_LIFETIME_SECS","ServerIdentityError","message","reason","hexToBytes","hex","i","verifyServerIdentity","input","proof","pinnedServerPubkey","now","maxLifetimeSecs","pinned","stripHexPrefix","X_ONLY_PUBKEY_HEX_LEN","HEX_RE","actual","eph","COMPRESSED_PUBKEY_HEX_LEN","prefix","ephBytes","ecc","sig","SCHNORR_SIG_HEX_LEN","payload","verifyBip322Simple","AUTH_GATED_METHODS","GRPC_AUTH_GATED_METHODS","TOKEN_RPC_TIMEOUT_MS","TOKEN_ISSUE_METHOD","GRPC_TOKEN_ISSUE_METHOD","buildInnerTokenClient","baseUrl","headers","JsonRpcClient","method","MAJOR_UNSIGNED_INT","MAJOR_NEGATIVE_INT","MAJOR_BYTE_STRING","MAJOR_TEXT_STRING","MAJOR_ARRAY","MAJOR_MAP","MAJOR_TAG","MAJOR_SIMPLE","ARG_IN_NEXT_1_BYTE","ARG_RESERVED_MIN","SIMPLE_FALSE","SIMPLE_TRUE","SIMPLE_NULL","MAX_NESTING_DEPTH","CborDecodeError","CborReader","buf","__publicField","initial","info","byteCount","value","length","slice","head","depth","map","key","decodeCbor","reader","CWT_SUBJECT_JSONRPC","CWT_SUBJECT_GRPC","COSE_SIGN1_TAG","COSE_SIGN1_ARRAY_LEN","COSE_ALG_ES256K","COSE_HEADER_LABEL_ALG","ECDSA_COMPACT_SIG_LEN","CBOR_ARRAY_HEAD","CBOR_TEXT_STRING_HEAD","CBOR_EMPTY_BYTE_STRING","CWT_CLAIM_ISS","CWT_CLAIM_SUB","CWT_CLAIM_AUD","CWT_CLAIM_EXP","CWT_CLAIM_NBF","CWT_CLAIM_IAT","CWT_CLAIM_CTI","SIG_STRUCTURE_CONTEXT","CwtVerificationError","verifyDepositorCwt","expectedIssuer","normalizeXOnly","expectedAudience","ephemeral","decodeCompressedPubkey","tokenBytes","base64UrlToBytes","array","protectedStart","protectedContent","protectedBstr","payloadStart","payloadContent","payloadBstr","signature","alg","readProtectedAlgorithm","sigStructure","buildSigStructure","digest","sha256","claims","decodeClaims","audience","header","concatBytes","root","requireBytes","requireString","requireTimestamp","name","pubkey","label","normalized","pubkeyHex","hexToUint8Array","B64URL_LOOKUP","table","alphabet","len","fullGroups","remainder","outLen","sextet","charCode","inPos","outPos","g","a","c","d","sum","part","MAX_EXPIRES_AT_SECS","DEFAULT_REFRESH_SKEW_SECS","VpTokenProvider","config","subject","cached","client","existing","issueMethod","fresh","allowPinRefresh","response","error","isPinnedIdentityMismatch","refreshed","VpTokenRegistry","provider","peginTxid","vpTokenRegistry","createAuthenticatedVpClient","innerTokenClient","_a","tokenProvider","processPublicKeyToXOnly","VaultProviderRpcClient","primeVpTokenRegistry"],"mappings":";;;;;;;;;;AAmCA,SAASA,EAASC,GAAeC,GAAkC;AACjE,QAAMC,KAAOF,IAAQ,MAAS,GACxB,IAAI,OAAOC,KAAQ,WAAWA,IAAM,OAAOA,CAAG;AACpD,MAAI,IAAI,GAAI,OAAM,IAAI,MAAM,6BAA6B;AAEzD,MAAI,IAAI,IAAK,QAAO,IAAI,WAAW,CAACC,IAAM,OAAO,CAAC,CAAC,CAAC;AACpD,MAAI,IAAI,OAAQ,QAAO,IAAI,WAAW,CAACA,IAAM,IAAI,OAAO,CAAC,CAAC,CAAC;AAC3D,MAAI,IAAI,UAAU;AAChB,UAAMC,IAAI,OAAO,CAAC;AAClB,WAAO,IAAI,WAAW,CAACD,IAAM,IAAKC,MAAM,IAAK,KAAMA,IAAI,GAAI,CAAC;AAAA,EAC9D;AACA,MAAI,IAAI,cAAgB;AACtB,UAAMA,IAAI,OAAO,CAAC;AAClB,WAAO,IAAI,WAAW;AAAA,MACpBD,IAAM;AAAA,MACLC,MAAM,KAAM;AAAA,MACZA,MAAM,KAAM;AAAA,MACZA,MAAM,IAAK;AAAA,MACZA,IAAI;AAAA,IAAA,CACL;AAAA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);var O=(e=>(e.PENDING_INGESTION="PendingIngestion",e.PENDING_DEPOSITOR_WOTS_PK="PendingDepositorWotsPK",e.PENDING_BABE_SETUP="PendingBabeSetup",e.PENDING_CHALLENGER_PRESIGNING="PendingChallengerPresigning",e.PENDING_PEGIN_SIGS_AVAILABILITY="PendingPeginSigsAvailability",e.PENDING_PRE_PEGIN_CONFIRMATIONS="PendingPrePegInConfirmations",e.PENDING_DEPOSITOR_SIGNATURES="PendingDepositorSignatures",e.PENDING_ACKS="PendingACKs",e.PENDING_ACTIVATION="PendingActivation",e.ACTIVATED_PENDING_BROADCAST="ActivatedPendingBroadcast",e.ACTIVATED="Activated",e.EXPIRED="Expired",e.INGESTION_REJECTED="IngestionRejected",e.INVALID_SIG_IN_CONTRACT="InvalidSigInContract",e.AML_REJECTED="AmlRejected",e.EXPIRED_CLEANED_UP="ExpiredCleanedUp",e.EXPIRED_IN_CLAIM="ExpiredInClaim",e.BABE_SETUP_FAILED="BabeSetupFailed",e))(O||{});const D=["PendingIngestion","PendingBabeSetup","PendingChallengerPresigning","PendingPeginSigsAvailability","PendingPrePegInConfirmations"],L=["PendingACKs","PendingActivation","ActivatedPendingBroadcast","Activated"],p=new Set(["PendingBabeSetup","PendingChallengerPresigning","PendingPeginSigsAvailability","PendingPrePegInConfirmations",...L]),U=new Set(["IngestionRejected","InvalidSigInContract","AmlRejected","ExpiredCleanedUp","ExpiredInClaim","BabeSetupFailed"]),B=new Set([...p,"PendingDepositorSignatures"]),m=50;var y=(e=>(e[e.PEGIN_NOT_FOUND=4001]="PEGIN_NOT_FOUND",e))(y||{});function S(e){return(e.startsWith("0x")?e.slice(2):e).toLowerCase()}function G(e,t){const r=new Set;for(const s of e)r.add(S(s));const n=new Map,o=new Set,a=[],i=[];for(const s of t){const P=S(s.vault_id);if(!r.has(P)){i.push(P);continue}if(o.has(P)){a.push(P);continue}o.add(P),n.set(P,{result:s.result,error:s.error})}const c=[];for(const s of r)o.has(s)||c.push(s);return{byVaultId:n,missing:c,unexpected:i,duplicate:a}}class u extends Error{constructor(t,r,n="local",o){super(r),this.code=t,this.source=n,this.data=o,this.name="JsonRpcError"}}const A={TIMEOUT:-32e3,NETWORK:-32001,PROXY_TIMEOUT:-32002,PROXY_UNAVAILABLE:-32003,INVALID_RESPONSE:-32700,RESPONSE_TOO_LARGE:-32701},x="2.0",M=3,V=1e3,F=2*1024*1024,J=new Set(["vaultProvider_requestDepositorClaimerArtifacts"]),k=new Set([408,429,500,502,503,504]),Y=new Set(["vaultProvider_getPeginStatusByVaultId","vaultProvider_batchGetPeginStatusByVaultId","vaultProvider_batchGetPegoutStatusByVaultId","vaultProvider_requestDepositorPresignTransactions"]);function q(e){return Y.has(e)}const C=-32001;function f(e){return e instanceof u&&e.source==="wire"&&e.code===C}class j{constructor(t){d(this,"baseUrl");d(this,"timeout");d(this,"headers");d(this,"requestId",0);d(this,"retries");d(this,"retryDelay");d(this,"maxResponseBytes");d(this,"retryableFor");d(this,"tokenProvider");if(this.baseUrl=t.baseUrl.replace(/\/$/,""),this.timeout=t.timeout,this.headers={"Content-Type":"application/json",...t.headers},this.retries=t.retries??M,this.retryDelay=t.retryDelay??V,this.maxResponseBytes=t.maxResponseBytes??F,!Number.isFinite(this.maxResponseBytes)||this.maxResponseBytes<=0)throw new Error("maxResponseBytes must be a positive finite number");this.retryableFor=t.retryableFor??q,this.tokenProvider=t.tokenProvider}async buildHeaders(t,r){const n={...this.headers};if(this.tokenProvider){const o=await this.tokenProvider.getToken(t);o&&(n.Authorization=`Bearer ${o}`,r&&(r.bearerAttached=!0))}return n}async call(t,r,n){const o={bearerAttached:!1};try{return await this.callOnce(t,r,n,o)}catch(a){if(this.tokenProvider&&o.bearerAttached&&f(a))return this.tokenProvider.invalidate(),await this.callOnce(t,r,n);throw a}}async callOnce(t,r,n,o){const a=await this.fetchWithRetry(t,r,n,o);let i;try{const s=J.has(t)?await a.text():await W(a,this.maxResponseBytes);i=JSON.parse(s)}catch(s){throw s instanceof u?s:new u(A.INVALID_RESPONSE,"Invalid JSON-RPC response: body is not valid JSON","local")}if(i===null||typeof i!="object"||Array.isArray(i))throw new u(A.INVALID_RESPONSE,`Invalid JSON-RPC response: expected an object, got ${typeof i}`,"local");const c=i;if("error"in c&&c.error!=null){const s=c.error;throw new u(s.code??A.INVALID_RESPONSE,s.message??"Unknown RPC error","wire",s.data)}if(!("result"in c))throw new u(A.INVALID_RESPONSE,'Invalid JSON-RPC response: missing "result" field',"local");return c.result}async callRaw(t,r,n){return this.fetchWithRetry(t,r,n)}async fetchWithRetry(t,r,n,o){const a=++this.requestId,i=this.retryableFor(t)?this.retries:0,s=JSON.stringify({jsonrpc:x,method:t,params:[r],id:a});let P=null;for(let l=0;l<=i;l++){const R=new AbortController,h=setTimeout(()=>R.abort(),this.timeout),_=n?H(n,R.signal):null,w=_?_.signal:R.signal;try{const E=await this.buildHeaders(t,o),T=await fetch(this.baseUrl,{method:"POST",headers:E,body:s,signal:w});if(clearTimeout(h),_==null||_.cleanup(),!T.ok){if(l<i&&k.has(T.status)){const b=this.retryDelay*Math.pow(2,l);await this.sleep(b,n);continue}throw new Error(`HTTP error: ${T.status} ${T.statusText}`)}return T}catch(E){if(clearTimeout(h),_==null||_.cleanup(),P=E instanceof Error?E:new Error(String(E)),n!=null&&n.aborted)throw new Error("Request aborted");if(E instanceof Error&&E.name==="AbortError"){if(l<i){const T=this.retryDelay*Math.pow(2,l);await this.sleep(T,n);continue}throw new u(A.TIMEOUT,`Request timeout after ${this.timeout}ms (${i+1} attempts)`,"local")}if(E instanceof TypeError){if(l<i){const T=this.retryDelay*Math.pow(2,l);await this.sleep(T,n);continue}throw new u(A.NETWORK,`Network error: ${E.message} (${i+1} attempts)`,"local")}throw E}}throw P||new Error("Unknown error after retries")}sleep(t,r){return new Promise((n,o)=>{if(r!=null&&r.aborted){o(new Error("Request aborted"));return}const a=setTimeout(()=>{r==null||r.removeEventListener("abort",i),n()},t),i=()=>{clearTimeout(a),o(new Error("Request aborted"))};r==null||r.addEventListener("abort",i,{once:!0})})}getBaseUrl(){return this.baseUrl}}function H(e,t){if(e.aborted)return{signal:e,cleanup:()=>{}};if(t.aborted)return{signal:t,cleanup:()=>{}};const r=new AbortController,n=()=>{t.removeEventListener("abort",o),r.abort()},o=()=>{e.removeEventListener("abort",n),r.abort()};e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",o,{once:!0});const a=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o)};return{signal:r.signal,cleanup:a}}async function W(e,t){const r=e.headers.get("content-length");if(r!==null){const c=Number(r);if(Number.isFinite(c)&&c>t)throw N(t)}if(!e.body)return"";const n=e.body.getReader(),o=new TextDecoder;let a=0,i="";try{for(;;){const{done:c,value:s}=await n.read();if(c)break;if(s){if(a+=s.byteLength,a>t)throw await n.cancel(),N(t);i+=o.decode(s,{stream:!0})}}}finally{n.releaseLock()}return i+o.decode()}function N(e){return new u(A.RESPONSE_TOO_LARGE,`JSON-RPC response exceeds maximum size of ${e} bytes`,"local")}var I=(e=>(e.CLAIM_EVENT_RECEIVED="ClaimEventReceived",e.CLAIM_BROADCAST="ClaimBroadcast",e.ASSERT_BROADCAST="AssertBroadcast",e.PAYOUT_CONFIRMED="PayoutConfirmed",e.PAYOUT_BLOCKED="PayoutBlocked",e))(I||{});const K="PayoutBroadcast",$=new Set(["PayoutConfirmed","PayoutBlocked"]);function X(e){return e===K?"PayoutConfirmed":e}function z(e){return Object.values(I).includes(e)}function Z(e){return!!e&&$.has(e)}exports.AUTH_REJECTED_RPC_CODE=C;exports.ClaimerPegoutStatusValue=I;exports.DaemonStatus=O;exports.JSON_RPC_ERROR_CODES=A;exports.JsonRpcClient=j;exports.JsonRpcError=u;exports.POST_WOTS_STATUSES=B;exports.PRE_DEPOSITOR_SIGNATURES_STATES=D;exports.RpcErrorCode=y;exports.VP_BATCH_MAX_SIZE=m;exports.VP_TERMINAL_FAILURE_STATUSES=U;exports.VP_TRANSIENT_STATUSES=p;exports.attributeBatchResults=G;exports.isAuthRejectedError=f;exports.isPegoutTerminalStatus=Z;exports.isRecognizedPegoutStatus=z;exports.normalizeClaimerPegoutStatus=X;exports.vaultIdKey=S;
2
+ //# sourceMappingURL=state-C4WoNCy1.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state-C4WoNCy1.cjs","sources":["../src/tbv/core/clients/vault-provider/types.ts","../src/tbv/core/clients/vault-provider/batchAttribution.ts","../src/tbv/core/clients/vault-provider/json-rpc-client.ts","../src/tbv/core/services/pegout/state.ts"],"sourcesContent":["/**\n * Type definitions for Vault Provider JSON-RPC API.\n *\n * These types match the `vaultProvider_*` RPC namespace defined by the\n * btc-vault daemon. They are the SDK's canonical copy of the VP protocol\n * contract, independent of any frontend framework.\n *\n * @see https://github.com/babylonlabs-io/btc-vault/blob/main/docs/pegin.md\n */\n\n// ============================================================================\n// Daemon Status\n// ============================================================================\n\n/**\n * Backend daemon status (vault provider database).\n * Source: btc-vault crates/vaultd/src/workers/claimer/mod.rs PegInStatus enum\n *\n * State flow (happy path):\n * PendingIngestion -> PendingDepositorWotsPK -> PendingBabeSetup -> PendingChallengerPresigning\n * -> PendingPeginSigsAvailability -> PendingPrePegInConfirmations\n * -> PendingDepositorSignatures -> PendingACKs -> PendingActivation\n * -> ActivatedPendingBroadcast -> Activated\n *\n * Branching / terminal states:\n * - IngestionRejected: terminal — ingestion permanently failed (e.g. malformed\n * Pre-PegIn, invalid HTLC outputs); reachable directly from PendingIngestion.\n * - Expired: activation timed out; non-terminal during the grace window\n * (RFC 003) — transitions to ExpiredCleanedUp or ExpiredInClaim.\n * - InvalidSigInContract: terminal — pegin input signature posted on\n * chain failed verification.\n * - AmlRejected: terminal — AML address screening rejected the pegin.\n * - ExpiredCleanedUp: terminal — grace window expired, per-pegin\n * artifacts deleted.\n * - ExpiredInClaim: terminal at the pegin-state-machine level; pegout-side\n * work continues on the pegout_tracking row.\n * - BabeSetupFailed: terminal — a challenger's BaBe decryptor session\n * failed verification, so BaBe setup cannot complete; reachable from\n * PendingBabeSetup.\n */\nexport enum DaemonStatus {\n PENDING_INGESTION = \"PendingIngestion\",\n PENDING_DEPOSITOR_WOTS_PK = \"PendingDepositorWotsPK\",\n PENDING_BABE_SETUP = \"PendingBabeSetup\",\n PENDING_CHALLENGER_PRESIGNING = \"PendingChallengerPresigning\",\n PENDING_PEGIN_SIGS_AVAILABILITY = \"PendingPeginSigsAvailability\",\n PENDING_PRE_PEGIN_CONFIRMATIONS = \"PendingPrePegInConfirmations\",\n PENDING_DEPOSITOR_SIGNATURES = \"PendingDepositorSignatures\",\n PENDING_ACKS = \"PendingACKs\",\n PENDING_ACTIVATION = \"PendingActivation\",\n ACTIVATED_PENDING_BROADCAST = \"ActivatedPendingBroadcast\",\n ACTIVATED = \"Activated\",\n EXPIRED = \"Expired\",\n INGESTION_REJECTED = \"IngestionRejected\",\n INVALID_SIG_IN_CONTRACT = \"InvalidSigInContract\",\n AML_REJECTED = \"AmlRejected\",\n EXPIRED_CLEANED_UP = \"ExpiredCleanedUp\",\n EXPIRED_IN_CLAIM = \"ExpiredInClaim\",\n BABE_SETUP_FAILED = \"BabeSetupFailed\",\n}\n\n// ============================================================================\n// Status Groups\n// ============================================================================\n\n/**\n * States where the VP is still processing (no depositor action needed).\n * Excludes PENDING_DEPOSITOR_WOTS_PK (requires depositor action).\n */\nexport const PRE_DEPOSITOR_SIGNATURES_STATES: readonly DaemonStatus[] = [\n DaemonStatus.PENDING_INGESTION,\n DaemonStatus.PENDING_BABE_SETUP,\n DaemonStatus.PENDING_CHALLENGER_PRESIGNING,\n DaemonStatus.PENDING_PEGIN_SIGS_AVAILABILITY,\n DaemonStatus.PENDING_PRE_PEGIN_CONFIRMATIONS,\n];\n\n/** States after PendingDepositorSignatures where the depositor has no action. */\nconst POST_PAYOUT_SIGNATURE_STATUSES: readonly DaemonStatus[] = [\n DaemonStatus.PENDING_ACKS,\n DaemonStatus.PENDING_ACTIVATION,\n DaemonStatus.ACTIVATED_PENDING_BROADCAST,\n DaemonStatus.ACTIVATED,\n];\n\n/**\n * Statuses where no depositor action is needed (VP processing or already past\n * depositor interaction). Excludes PENDING_INGESTION and PENDING_DEPOSITOR_WOTS_PK.\n */\nexport const VP_TRANSIENT_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n DaemonStatus.PENDING_BABE_SETUP,\n DaemonStatus.PENDING_CHALLENGER_PRESIGNING,\n DaemonStatus.PENDING_PEGIN_SIGS_AVAILABILITY,\n DaemonStatus.PENDING_PRE_PEGIN_CONFIRMATIONS,\n ...POST_PAYOUT_SIGNATURE_STATUSES,\n]);\n\n/**\n * Terminal VP statuses that represent failure outcomes — polling should\n * stop immediately with an error rather than wait for timeout.\n *\n * Mirrors the failure subset of the server-side terminals\n * (`allowed_transitions()` empty, see `PegInStatus` in\n * `btc-vault/crates/vaultd/src/workers/claimer/mod.rs`).\n * `Activated` IS terminal on-chain but is the success outcome, so it is\n * intentionally excluded — a caller polling for an earlier state that\n * races straight to `Activated` should treat that as success-via-overshoot,\n * not failure. `Expired` is also excluded — under RFC 003 it is a\n * grace-window interim that transitions to `ExpiredCleanedUp` or\n * `ExpiredInClaim`. Callers that want to stop polling on any expiry\n * should check `status === DaemonStatus.EXPIRED ||\n * VP_TERMINAL_FAILURE_STATUSES.has(status)`.\n */\nexport const VP_TERMINAL_FAILURE_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n DaemonStatus.INGESTION_REJECTED,\n DaemonStatus.INVALID_SIG_IN_CONTRACT,\n DaemonStatus.AML_REJECTED,\n DaemonStatus.EXPIRED_CLEANED_UP,\n DaemonStatus.EXPIRED_IN_CLAIM,\n DaemonStatus.BABE_SETUP_FAILED,\n]);\n\n/**\n * Statuses that come after WOTS key submission.\n * If the VP is already in one of these states, the WOTS key was already\n * submitted and we can skip.\n */\nexport const POST_WOTS_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n ...VP_TRANSIENT_STATUSES,\n DaemonStatus.PENDING_DEPOSITOR_SIGNATURES,\n]);\n\n// ============================================================================\n// WOTS Types (needed by SubmitDepositorWotsKeyParams)\n// ============================================================================\n\n/**\n * WOTS configuration for a single block.\n * Matches Rust `babe::wots::Config` serde format.\n */\nexport interface WotsConfig {\n /** Digit bit-width (e.g. 4 → base-16 digits). */\n d: number;\n /** Number of message digits in this block. */\n n: number;\n /** Radix used for the checksum computation. */\n checksum_radix: number;\n}\n\n/**\n * A single block of WOTS public keys.\n * Chain values are arrays of byte values (matching Rust `[u8; 20]`).\n */\nexport interface WotsBlockPublicKey {\n config: WotsConfig;\n message_terminals: number[][];\n checksum_major_terminal: number[];\n checksum_minor_terminal: number[];\n}\n\n// ============================================================================\n// Request Parameter Types\n// ============================================================================\n\n/** Params for requesting the payout/claim/assert transactions to pre-sign. */\nexport interface RequestDepositorPresignTransactionsParams {\n pegin_txid: string;\n depositor_pk: string;\n}\n\n/** Params for submitting the depositor's WOTS public key to the VP. */\nexport interface SubmitDepositorWotsKeyParams {\n pegin_txid: string;\n depositor_pk: string;\n wots_public_keys: WotsBlockPublicKey[];\n}\n\n/** Per-challenger signatures for the depositor-as-claimer flow. */\nexport interface DepositorPreSigsPerChallenger {\n nopayout_signature: string;\n}\n\n/** Depositor-as-claimer pre-signatures (payout + per-challenger). */\nexport interface DepositorAsClaimerPresignatures {\n payout_signatures: ClaimerSignatures;\n per_challenger: Record<string, DepositorPreSigsPerChallenger>;\n}\n\n/** Params for submitting depositor pre-signatures including claimer presignatures. */\nexport interface SubmitDepositorPresignaturesParams {\n pegin_txid: string;\n depositor_pk: string;\n signatures: Record<string, ClaimerSignatures>;\n depositor_claimer_presignatures: DepositorAsClaimerPresignatures;\n}\n\n/** Payout signatures per claimer. */\nexport interface ClaimerSignatures {\n payout_signature: string;\n}\n\n/** Params for requesting BaBe DecryptorArtifacts from the VP. */\nexport interface RequestDepositorClaimerArtifactsParams {\n pegin_txid: string;\n depositor_pk: string;\n}\n\n/**\n * Params for `getPeginStatusByVaultId`. A vault is addressed by its\n * depositor-bound `vault_id` (`keccak256(abi.encode(peginTxHash, depositor))`),\n * hex-encoded with or without a `0x` prefix. A `pegin_txid` does not identify\n * a vault — several vaults can share one txid.\n */\nexport interface GetPeginStatusByVaultIdParams {\n vault_id: string;\n}\n\n// ============================================================================\n// Response Types\n// ============================================================================\n\n/** A raw Bitcoin transaction with its hex encoding. */\nexport interface TransactionData {\n tx_hex: string;\n}\n\n/** Set of transactions the depositor must pre-sign for a single claimer. */\nexport interface ClaimerTransactions {\n claimer_pubkey: string;\n claim_tx: TransactionData;\n assert_tx: TransactionData;\n payout_tx: TransactionData;\n payout_psbt: string;\n}\n\n/** Per-segment connector data for ChallengeAssert inputs. */\nexport interface ChallengeAssertConnectorData {\n wots_pks_json: string;\n gc_wots_keys_json: string;\n}\n\n/** Challenger-specific transactions and signing data for the depositor graph. */\nexport interface PresignDataPerChallenger {\n challenger_pubkey: string;\n challenge_assert_x_tx: TransactionData;\n challenge_assert_y_tx: TransactionData;\n nopayout_tx: TransactionData;\n nopayout_psbt: string;\n challenge_assert_connectors: ChallengeAssertConnectorData[];\n output_label_hashes: string[];\n}\n\n/** Depositor-as-claimer TxGraph transactions. */\nexport interface DepositorGraphTransactions {\n claim_tx: TransactionData;\n assert_tx: TransactionData;\n payout_tx: TransactionData;\n payout_psbt: string;\n challenger_presign_data: PresignDataPerChallenger[];\n offchain_params_version: number;\n}\n\n/** Response from `requestDepositorPresignTransactions`. */\nexport interface RequestDepositorPresignTransactionsResponse {\n txs: ClaimerTransactions[];\n depositor_graph: DepositorGraphTransactions;\n}\n\n/** BaBe garbled-circuit session data for a single challenger. */\nexport interface BaBeSessionData {\n decryptor_artifacts_hex: string;\n}\n\n/** Response from `requestDepositorClaimerArtifacts`. */\nexport interface RequestDepositorClaimerArtifactsResponse {\n tx_graph_json: string;\n verifying_key_hex: string;\n babe_sessions: Record<string, BaBeSessionData>;\n}\n\n/** Progress tracker for a multi-challenger operation. */\nexport interface ChallengerProgress {\n total_challengers: number;\n completed_challengers: number;\n completed_challenger_pubkeys: string[];\n pending_challenger_pubkeys: string[];\n}\n\nexport type GcDataProgress = ChallengerProgress;\nexport type AckCollectionProgress = ChallengerProgress;\n\n/** Extended presigning progress with all 3 concurrent phases. */\nexport interface PresigningProgress extends ChallengerProgress {\n depositor_graph_created?: boolean;\n vk_challenger_presigning_completed?: number;\n vk_challenger_presigning_total?: number;\n}\n\n/** Detailed progress breakdown for an in-progress pegin. */\nexport interface PeginProgressDetails {\n gc_data?: GcDataProgress;\n presigning?: PresigningProgress;\n ack_collection?: AckCollectionProgress;\n claimer_graphs?: ClaimerGraphStatus[];\n}\n\n/** Per-claimer graph status (challenger perspective). */\nexport interface ClaimerGraphStatus {\n claimer_pubkey: string;\n presigned: boolean;\n}\n\n/** Response from `getPeginStatusByVaultId`. */\nexport interface GetPeginStatusResponse {\n /**\n * The peg-in txid the server stores for this vault. A mismatch with the\n * caller's txid shows a status for a different peg-in; several vaults can\n * share one txid, so it does not identify a vault.\n */\n pegin_txid: string;\n /** The vault this response describes (`0x`-prefixed hex). */\n vault_id: string;\n status: string;\n progress: PeginProgressDetails;\n health_info: string;\n last_error?: string;\n}\n\n// ============================================================================\n// Pegout Types\n// ============================================================================\n\n/**\n * Claimer-side pegout progress.\n * Source: btc-vault crates/vaultd/src/rpc/server/pegout_status.rs ClaimerPegoutStatus.\n */\nexport interface ClaimerPegoutStatus {\n /** Wire string from PegoutStatus enum. */\n status: string;\n failed: boolean;\n claim_txid: string;\n claimer_pubkey: string;\n assert_txid: string;\n /** Unix epoch seconds. */\n created_at: number;\n /** Unix epoch seconds. */\n updated_at: number;\n}\n\n/**\n * Challenger-side pegout progress.\n * Source: btc-vault crates/vaultd/src/rpc/server/pegout_status.rs ChallengerStatus.\n */\nexport interface ChallengerStatus {\n status: string;\n claim_txid: string;\n claimer_pubkey: string;\n assert_txid: string | null;\n challenge_assert_x_txid: string | null;\n challenge_assert_y_txid: string | null;\n nopayout_txid: string | null;\n created_at: number;\n updated_at: number;\n}\n\n/**\n * Pegout status response. Embedded by `batchGetPegoutStatusByVaultId`\n * per-result envelopes. Mirrors btc-vault `GetPegoutStatusResponse`.\n */\nexport interface GetPegoutStatusResponse {\n pegin_txid: string;\n /** The vault this response describes (`0x`-prefixed hex). */\n vault_id: string;\n found: boolean;\n claimer: ClaimerPegoutStatus | null;\n challengers: ChallengerStatus[];\n}\n\n// ============================================================================\n// Batch Status Types (peginStatus + pegoutStatus)\n// ============================================================================\n\n/** Params for `batchGetPeginStatusByVaultId`. */\nexport interface BatchGetPeginStatusByVaultIdParams {\n /** Up to MAX_BATCH_SIZE (50) vault ids per call (hex, `0x` prefix optional). */\n vault_ids: string[];\n}\n\n/** Per-vault entry in a `batchGetPeginStatusByVaultId` response. */\nexport interface BatchPeginStatusResult {\n /** Echo of the requested vault id, verbatim. */\n vault_id: string;\n result: GetPeginStatusResponse | null;\n error: string | null;\n}\n\n/** Response from `batchGetPeginStatusByVaultId`. Results are returned in request order. */\nexport interface BatchGetPeginStatusResponse {\n results: BatchPeginStatusResult[];\n}\n\n/** Params for `batchGetPegoutStatusByVaultId`. */\nexport interface BatchGetPegoutStatusByVaultIdParams {\n /** Vault ids to query (hex, `0x` prefix optional). */\n vault_ids: string[];\n}\n\n/** Per-vault entry in a `batchGetPegoutStatusByVaultId` response. */\nexport interface BatchPegoutStatusResult {\n /** Echo of the requested vault id, verbatim. */\n vault_id: string;\n result: GetPegoutStatusResponse | null;\n error: string | null;\n}\n\n/** Response from `batchGetPegoutStatusByVaultId`. Results are returned in request order. */\nexport interface BatchGetPegoutStatusResponse {\n results: BatchPegoutStatusResult[];\n}\n\n/**\n * Maximum number of items per batch call. Mirrors the server-side\n * `MAX_BATCH_SIZE` in btc-vault (`crates/vaultd/src/rpc/server/vault_provider.rs:7`).\n * Callers must chunk requests larger than this.\n */\nexport const VP_BATCH_MAX_SIZE = 50;\n\n// ============================================================================\n// Error Codes\n// ============================================================================\n\n/**\n * JSON-RPC error codes returned by the vault provider.\n * Source: btc-vault `crates/vaultd/src/rpc/error.rs::RpcError::error_code`.\n */\nexport enum RpcErrorCode {\n PEGIN_NOT_FOUND = 4001,\n}\n","/**\n * Defensive helper for attributing per-item results in a VP batch RPC\n * response back to the requested vault ids. The server promises 1:1 ordered\n * results, but we don't trust that promise — a server bug could duplicate,\n * skip, or scramble items, and silent attribution-by-array-index would\n * mask the bug.\n *\n * Normalizes vault ids on both sides (strip `0x`, lowercase) to absorb\n * prefix and case mismatch — the server echoes the request string verbatim.\n *\n * @module tbv/core/clients/vault-provider/batchAttribution\n */\n\n/** Per-item entry in a VP batch response. */\nexport interface BatchResultEntry<T> {\n vault_id: string;\n result: T | null;\n error: string | null;\n}\n\n/** Output of {@link attributeBatchResults}. */\nexport interface BatchAttributionResult<T> {\n /** Normalized requested vault id -> per-item envelope. */\n byVaultId: Map<string, { result: T | null; error: string | null }>;\n /** Requested vault ids that did not appear in the response. */\n missing: string[];\n /** Echoed vault ids that were not in the request — logged + dropped. */\n unexpected: string[];\n /** Echoed vault ids that appeared more than once — first kept, rest dropped. */\n duplicate: string[];\n}\n\n/** Normalize a vault id for map keys: strip an optional `0x`, lowercase. */\nexport function vaultIdKey(vaultId: string): string {\n const unprefixed = vaultId.startsWith(\"0x\") ? vaultId.slice(2) : vaultId;\n return unprefixed.toLowerCase();\n}\n\n/**\n * Attribute batch results to requested vault ids defensively.\n *\n * Both `requestedVaultIds` and the echoed `vault_id` field on each result\n * are normalized before lookup. Duplicates and unexpected echoes are\n * surfaced so callers can flag the affected items as errored rather than\n * silently overwriting state.\n *\n * `requestedVaultIds` may contain duplicates; they are de-duplicated for the\n * purposes of map keys (each unique vault id becomes a single map entry).\n */\nexport function attributeBatchResults<T>(\n requestedVaultIds: string[],\n results: ReadonlyArray<BatchResultEntry<T>>,\n): BatchAttributionResult<T> {\n const requestedSet = new Set<string>();\n for (const vaultId of requestedVaultIds) {\n requestedSet.add(vaultIdKey(vaultId));\n }\n\n const byVaultId = new Map<\n string,\n { result: T | null; error: string | null }\n >();\n const seen = new Set<string>();\n const duplicate: string[] = [];\n const unexpected: string[] = [];\n\n for (const entry of results) {\n const normalized = vaultIdKey(entry.vault_id);\n if (!requestedSet.has(normalized)) {\n unexpected.push(normalized);\n continue;\n }\n if (seen.has(normalized)) {\n duplicate.push(normalized);\n continue;\n }\n seen.add(normalized);\n byVaultId.set(normalized, { result: entry.result, error: entry.error });\n }\n\n const missing: string[] = [];\n for (const vaultId of requestedSet) {\n if (!seen.has(vaultId)) missing.push(vaultId);\n }\n\n return { byVaultId, missing, unexpected, duplicate };\n}\n","/**\n * Generic JSON-RPC 2.0 HTTP Client\n *\n * Framework-agnostic client using `fetch()` — works in browsers and Node.js 18+.\n * Includes configurable retry policy and AbortSignal passthrough.\n */\n\nexport interface JsonRpcRequest<T = unknown> {\n jsonrpc: \"2.0\";\n method: string;\n params: T;\n id: number | string;\n}\n\nexport interface JsonRpcSuccessResponse<T = unknown> {\n jsonrpc: \"2.0\";\n result: T;\n id: number | string;\n}\n\nexport interface JsonRpcErrorResponse {\n jsonrpc: \"2.0\";\n error: {\n code: number;\n message: string;\n data?: unknown;\n };\n id: number | string;\n}\n\nexport type JsonRpcResponse<T = unknown> =\n | JsonRpcSuccessResponse<T>\n | JsonRpcErrorResponse;\n\n/**\n * Injects bearer tokens into requests for auth-gated methods, and is\n * notified when the server rejects a bearer so it can invalidate its cache.\n *\n * The `JsonRpcClient` is agnostic to which methods are auth-gated —\n * the provider's `getToken(method)` decides. Returning `null` means\n * \"no auth required for this method\"; the client then sends the\n * request with no `Authorization` header.\n */\nexport interface BearerTokenProvider {\n /**\n * Return the bearer token to inject for `method`, or `null` if the\n * method does not require auth.\n */\n getToken(method: string): Promise<string | null>;\n /**\n * Drop the cached token. Next call to `getToken` must re-acquire.\n * Called by the client on reactive-refresh-trigger responses.\n */\n invalidate(): void;\n}\n\nexport interface JsonRpcClientConfig {\n /** Base URL of the RPC service */\n baseUrl: string;\n /** Timeout in milliseconds per request attempt */\n timeout: number;\n /** Optional custom headers */\n headers?: Record<string, string>;\n /** Number of retry attempts for transient errors (default: 3) */\n retries?: number;\n /** Initial retry delay in milliseconds (default: 1000) */\n retryDelay?: number;\n /**\n * Maximum response body size, in bytes, for typed JSON-RPC calls.\n * `callRaw` intentionally returns the unparsed Response and is not capped here.\n * Default: 2 MiB.\n */\n maxResponseBytes?: number;\n /**\n * Predicate that decides which methods retry on transient errors.\n * Default retries only `getPeginStatusByVaultId`,\n * `batchGetPeginStatusByVaultId`, `batchGetPegoutStatusByVaultId`, and\n * `requestDepositorPresignTransactions`.\n * Write methods are not retried by default.\n */\n retryableFor?: (method: string) => boolean;\n /**\n * Per-request bearer-token source. A non-null return attaches\n * `Authorization: Bearer <token>`; `null` skips auth. `call`\n * additionally retries once when the server rejects the bearer\n * (invalidate + refetch + retry) — see {@link isAuthRejectedError}.\n * `callRaw` skips reactive refresh.\n */\n tokenProvider?: BearerTokenProvider;\n}\n\n// \"wire\" = parsed from a JSON-RPC error envelope; \"local\" = timeout/network/parse failure.\nexport type JsonRpcErrorSource = \"wire\" | \"local\";\n\nexport class JsonRpcError extends Error {\n constructor(\n public code: number,\n message: string,\n /** \"wire\" for server-returned envelopes; \"local\" for SDK-side failures. */\n public source: JsonRpcErrorSource = \"local\",\n /** Structured data from the server `error.data` field, if any. */\n public data?: unknown,\n ) {\n super(message);\n this.name = \"JsonRpcError\";\n }\n}\n\nexport const JSON_RPC_ERROR_CODES = {\n TIMEOUT: -32000,\n NETWORK: -32001,\n /** VP proxy: request timed out at proxy level */\n PROXY_TIMEOUT: -32002,\n /** VP proxy: VP unreachable / DNS failure / response too large */\n PROXY_UNAVAILABLE: -32003,\n /** SDK client: response missing \"result\" field (malformed JSON-RPC) */\n INVALID_RESPONSE: -32700,\n /** SDK client: response body exceeded the configured byte limit */\n RESPONSE_TOO_LARGE: -32701,\n} as const;\n\n/** JSON-RPC protocol version */\nconst JSON_RPC_VERSION = \"2.0\" as const;\n\n/** Default number of retry attempts for transient errors */\nconst DEFAULT_RETRY_ATTEMPTS = 3;\n\n/** Default initial retry delay in milliseconds */\nconst DEFAULT_RETRY_DELAY_MS = 1000;\n\n/** Default maximum JSON-RPC response size for typed calls (2 MiB) */\nconst DEFAULT_MAX_RESPONSE_BYTES = 2 * 1024 * 1024;\n\n/**\n * TODO: Temporary typed-call exceptions for methods that currently return large\n * artifact payloads as JSON-RPC results.\n */\nconst UNCAPPED_TYPED_RESPONSE_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_requestDepositorClaimerArtifacts\",\n]);\n\n/** HTTP status codes that indicate transient server errors and are safe to retry */\nconst RETRYABLE_HTTP_STATUS_CODES: ReadonlySet<number> = new Set([\n 408, // Request Timeout\n 429, // Too Many Requests\n 500, // Internal Server Error\n 502, // Bad Gateway\n 503, // Service Unavailable\n 504, // Gateway Timeout\n]);\n\n/** Default retry predicate: only retry read-only / idempotent methods */\nconst DEFAULT_RETRYABLE_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_getPeginStatusByVaultId\",\n \"vaultProvider_batchGetPeginStatusByVaultId\",\n \"vaultProvider_batchGetPegoutStatusByVaultId\",\n \"vaultProvider_requestDepositorPresignTransactions\",\n]);\n\nfunction defaultRetryableFor(method: string): boolean {\n return DEFAULT_RETRYABLE_METHODS.has(method);\n}\n\n/**\n * JSON-RPC error code the vault provider returns for every bearer-token\n * rejection: expired, not-yet-valid, missing bearer, invalid signature,\n * invalid claims, invalid structure, subject mismatch, issuer mismatch.\n * All eight variants collapse onto this one code, distinguished only by\n * message text — see btc-vault `crates/btc-auth/src/rpc.rs`\n * (`auth_error_to_rpc_error`). Operationally they all mean the same\n * thing: this bearer is dead, mint a new one.\n *\n * Numerically equal to {@link JSON_RPC_ERROR_CODES.NETWORK}, which this\n * client throws for local network failures. `source` is what separates\n * them — see {@link isAuthRejectedError}.\n */\nexport const AUTH_REJECTED_RPC_CODE = -32001;\n\n/**\n * True when `error` is the vault provider rejecting our bearer token.\n *\n * Classified on the error code, which is the only thing the server\n * guarantees: its auth errors carry `data: null` unconditionally\n * (`rpc_error` passes `None::<()>`), so any predicate keyed on an\n * `error.data` field can never match a real response.\n *\n * `source === \"wire\"` is load-bearing: this client reuses -32001\n * internally as {@link JSON_RPC_ERROR_CODES.NETWORK}, always with\n * source \"local\".\n *\n * Known, bounded collision: the vault-provider proxy reuses -32001 for\n * \"Provider not found\". A call to a deregistered provider therefore\n * costs one wasted token-mint round-trip, which fails against the same\n * registry check and surfaces the same message.\n */\nexport function isAuthRejectedError(error: unknown): boolean {\n return (\n error instanceof JsonRpcError &&\n error.source === \"wire\" &&\n error.code === AUTH_REJECTED_RPC_CODE\n );\n}\n\n/**\n * Per-`call` record of whether a bearer was actually attached to the\n * request. Scoped to one `call` (not client state) so concurrent\n * requests can't observe each other's auth state.\n */\ninterface AttemptAuthState {\n bearerAttached: boolean;\n}\n\n/**\n * Generic JSON-RPC 2.0 HTTP client with safe retry policy.\n */\nexport class JsonRpcClient {\n private baseUrl: string;\n private timeout: number;\n private headers: Record<string, string>;\n private requestId = 0;\n private retries: number;\n private retryDelay: number;\n private maxResponseBytes: number;\n private retryableFor: (method: string) => boolean;\n private tokenProvider?: BearerTokenProvider;\n\n constructor(config: JsonRpcClientConfig) {\n this.baseUrl = config.baseUrl.replace(/\\/$/, \"\");\n this.timeout = config.timeout;\n this.headers = {\n \"Content-Type\": \"application/json\",\n ...config.headers,\n };\n this.retries = config.retries ?? DEFAULT_RETRY_ATTEMPTS;\n this.retryDelay = config.retryDelay ?? DEFAULT_RETRY_DELAY_MS;\n this.maxResponseBytes =\n config.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;\n if (!Number.isFinite(this.maxResponseBytes) || this.maxResponseBytes <= 0) {\n throw new Error(\"maxResponseBytes must be a positive finite number\");\n }\n this.retryableFor = config.retryableFor ?? defaultRetryableFor;\n this.tokenProvider = config.tokenProvider;\n }\n\n private async buildHeaders(\n method: string,\n authState?: AttemptAuthState,\n ): Promise<Record<string, string>> {\n const headers: Record<string, string> = { ...this.headers };\n if (this.tokenProvider) {\n const token = await this.tokenProvider.getToken(method);\n if (token) {\n headers.Authorization = `Bearer ${token}`;\n if (authState) authState.bearerAttached = true;\n }\n }\n return headers;\n }\n\n /**\n * Make a JSON-RPC request with optional retry for safe methods.\n *\n * If the server rejects the bearer token and a `tokenProvider` is\n * configured, the client invalidates its cached token and retries the\n * request once with a freshly-acquired bearer.\n *\n * @param method - The RPC method name\n * @param params - The method parameters\n * @param signal - Optional AbortSignal for caller-controlled cancellation\n * @returns The result from the RPC method\n * @throws JsonRpcError if the RPC call fails\n */\n async call<TParams, TResult>(\n method: string,\n params: TParams,\n signal?: AbortSignal,\n ): Promise<TResult> {\n const authState: AttemptAuthState = { bearerAttached: false };\n try {\n return await this.callOnce<TParams, TResult>(\n method,\n params,\n signal,\n authState,\n );\n } catch (error) {\n // The re-auth retry fires for ALL methods, including mutating ones.\n // This is intentional and safe: the server's auth middleware rejects\n // the request BEFORE dispatching to the method handler, so a\n // rejected bearer means the handler never ran and no state was\n // mutated. Confirmed against btc-vault\n // `crates/btc-auth/src/middleware/jsonrpc.rs` — `unauthorized_response`\n // returns without ever calling `service.call(req)`, in both `call`\n // and `batch`. The `retryableFor` guard on HTTP-transient-error\n // retries doesn't apply here because that guard is about retrying\n // after a request the server may have started processing.\n //\n // `bearerAttached` keeps this off methods that sent no token — most\n // importantly the token-issuing calls themselves, which would\n // otherwise burn a round-trip re-minting against the proxy's\n // colliding -32001 \"Provider not found\".\n //\n // Bounded to one retry: the retried call is not wrapped in this\n // handler. If the freshly-minted token is rejected too, the problem\n // is the pinned server key rather than the token, and that surfaces\n // instead of looping.\n if (\n this.tokenProvider &&\n authState.bearerAttached &&\n isAuthRejectedError(error)\n ) {\n this.tokenProvider.invalidate();\n return await this.callOnce<TParams, TResult>(method, params, signal);\n }\n throw error;\n }\n }\n\n private async callOnce<TParams, TResult>(\n method: string,\n params: TParams,\n signal: AbortSignal | undefined,\n authState?: AttemptAuthState,\n ): Promise<TResult> {\n const response = await this.fetchWithRetry(\n method,\n params,\n signal,\n authState,\n );\n\n let jsonResponse: unknown;\n try {\n const responseText = UNCAPPED_TYPED_RESPONSE_METHODS.has(method)\n ? await response.text()\n : await readResponseTextWithLimit(response, this.maxResponseBytes);\n jsonResponse = JSON.parse(responseText);\n } catch (error) {\n if (error instanceof JsonRpcError) {\n throw error;\n }\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n \"Invalid JSON-RPC response: body is not valid JSON\",\n \"local\",\n );\n }\n\n if (\n jsonResponse === null ||\n typeof jsonResponse !== \"object\" ||\n Array.isArray(jsonResponse)\n ) {\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n `Invalid JSON-RPC response: expected an object, got ${typeof jsonResponse}`,\n \"local\",\n );\n }\n\n const rpcResponse = jsonResponse as Record<string, unknown>;\n\n if (\"error\" in rpcResponse && rpcResponse.error != null) {\n const err = rpcResponse.error as {\n code?: number;\n message?: string;\n data?: unknown;\n };\n throw new JsonRpcError(\n err.code ?? JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n err.message ?? \"Unknown RPC error\",\n \"wire\",\n err.data,\n );\n }\n\n if (!(\"result\" in rpcResponse)) {\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n `Invalid JSON-RPC response: missing \"result\" field`,\n \"local\",\n );\n }\n\n return rpcResponse.result as TResult;\n }\n\n /**\n * Make a JSON-RPC request returning the raw Response (unparsed body).\n *\n * Bearer tokens are injected identically to `call`. **Reactive refresh\n * is NOT performed here** — the response body may be unbounded (e.g.\n * claimer-artifact downloads), so the client refuses to parse it to\n * detect auth errors. Callers relying on token-expired retries for\n * large downloads must read the body themselves and re-invoke\n * `callRaw` after `tokenProvider.invalidate()`.\n */\n async callRaw<TParams>(\n method: string,\n params: TParams,\n signal?: AbortSignal,\n ): Promise<Response> {\n return this.fetchWithRetry(method, params, signal);\n }\n\n private async fetchWithRetry<TParams>(\n method: string,\n params: TParams,\n callerSignal?: AbortSignal,\n authState?: AttemptAuthState,\n ): Promise<Response> {\n const requestId = ++this.requestId;\n const maxRetries = this.retryableFor(method) ? this.retries : 0;\n\n // jsonrpsee (Rust backend) expects params as an array (positional parameters)\n const request: JsonRpcRequest<TParams[]> = {\n jsonrpc: JSON_RPC_VERSION,\n method,\n params: [params],\n id: requestId,\n };\n\n const body = JSON.stringify(request);\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n // Merge caller signal with per-request timeout signal\n const timeoutController = new AbortController();\n const timeoutId = setTimeout(\n () => timeoutController.abort(),\n this.timeout,\n );\n\n const merged = callerSignal\n ? mergeAbortSignals(callerSignal, timeoutController.signal)\n : null;\n const signal = merged ? merged.signal : timeoutController.signal;\n\n try {\n // Build headers per-attempt so the token provider can return a\n // freshly-acquired bearer after a prior invalidate() on this\n // request (retry loop path) without plumbing state through.\n const headers = await this.buildHeaders(method, authState);\n\n const response = await fetch(this.baseUrl, {\n method: \"POST\",\n headers,\n body,\n signal,\n });\n\n clearTimeout(timeoutId);\n merged?.cleanup();\n\n if (!response.ok) {\n const shouldRetry =\n attempt < maxRetries &&\n RETRYABLE_HTTP_STATUS_CODES.has(response.status);\n\n if (shouldRetry) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n await this.sleep(delay, callerSignal);\n continue;\n }\n\n throw new Error(\n `HTTP error: ${response.status} ${response.statusText}`,\n );\n }\n\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n merged?.cleanup();\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Check if caller aborted (not our timeout)\n if (callerSignal?.aborted) {\n throw new Error(\"Request aborted\");\n }\n\n if (error instanceof Error && error.name === \"AbortError\") {\n if (attempt < maxRetries) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n await this.sleep(delay, callerSignal);\n continue;\n }\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.TIMEOUT,\n `Request timeout after ${this.timeout}ms (${maxRetries + 1} attempts)`,\n \"local\",\n );\n }\n\n // Handle network errors (CORS, connection refused, etc.)\n if (error instanceof TypeError) {\n if (attempt < maxRetries) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n await this.sleep(delay, callerSignal);\n continue;\n }\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.NETWORK,\n `Network error: ${error.message} (${maxRetries + 1} attempts)`,\n \"local\",\n );\n }\n\n // Don't retry JSON-RPC errors (business logic errors)\n throw error;\n }\n }\n\n throw lastError || new Error(\"Unknown error after retries\");\n }\n\n private sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new Error(\"Request aborted\"));\n return;\n }\n const timeoutId = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timeoutId);\n reject(new Error(\"Request aborted\"));\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n }\n\n getBaseUrl(): string {\n return this.baseUrl;\n }\n}\n\ninterface MergedSignal {\n signal: AbortSignal;\n /** Remove listeners from the source signals. Call after the request completes. */\n cleanup: () => void;\n}\n\n/**\n * Merge two AbortSignals — the returned signal aborts if either input aborts.\n * Returns a cleanup function to remove listeners when the request completes\n * normally, preventing listener accumulation in long-lived polling flows.\n */\nfunction mergeAbortSignals(a: AbortSignal, b: AbortSignal): MergedSignal {\n if (a.aborted) return { signal: a, cleanup: () => {} };\n if (b.aborted) return { signal: b, cleanup: () => {} };\n\n const controller = new AbortController();\n const onAbortA = () => {\n b.removeEventListener(\"abort\", onAbortB);\n controller.abort();\n };\n const onAbortB = () => {\n a.removeEventListener(\"abort\", onAbortA);\n controller.abort();\n };\n a.addEventListener(\"abort\", onAbortA, { once: true });\n b.addEventListener(\"abort\", onAbortB, { once: true });\n\n const cleanup = () => {\n a.removeEventListener(\"abort\", onAbortA);\n b.removeEventListener(\"abort\", onAbortB);\n };\n\n return { signal: controller.signal, cleanup };\n}\n\nasync function readResponseTextWithLimit(\n response: Response,\n maxBytes: number,\n): Promise<string> {\n const contentLength = response.headers.get(\"content-length\");\n if (contentLength !== null) {\n const parsedContentLength = Number(contentLength);\n if (\n Number.isFinite(parsedContentLength) &&\n parsedContentLength > maxBytes\n ) {\n throw responseTooLargeError(maxBytes);\n }\n }\n\n if (!response.body) {\n return \"\";\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let totalBytes = 0;\n let responseText = \"\";\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!value) continue;\n\n totalBytes += value.byteLength;\n if (totalBytes > maxBytes) {\n await reader.cancel();\n throw responseTooLargeError(maxBytes);\n }\n responseText += decoder.decode(value, { stream: true });\n }\n } finally {\n reader.releaseLock();\n }\n\n return responseText + decoder.decode();\n}\n\nfunction responseTooLargeError(maxBytes: number): JsonRpcError {\n return new JsonRpcError(\n JSON_RPC_ERROR_CODES.RESPONSE_TOO_LARGE,\n `JSON-RPC response exceeds maximum size of ${maxBytes} bytes`,\n \"local\",\n );\n}\n","/**\n * Pegout state definitions and protocol-level terminal checks.\n *\n * Maps VP-reported pegout statuses from\n * `vaultProvider_batchGetPegoutStatusByVaultId` to protocol lifecycle states.\n *\n * Lifecycle (pegin-level, see btc-vault mod.rs PegoutStatus):\n * ClaimEventReceived -> ClaimBroadcast -> AssertBroadcast ->\n * PayoutConfirmed (success) | PayoutBlocked (NoPayout / CouncilNoPayout)\n */\n\n/** Claimer-side pegout statuses reported by the VP. */\nexport enum ClaimerPegoutStatusValue {\n CLAIM_EVENT_RECEIVED = \"ClaimEventReceived\",\n CLAIM_BROADCAST = \"ClaimBroadcast\",\n ASSERT_BROADCAST = \"AssertBroadcast\",\n PAYOUT_CONFIRMED = \"PayoutConfirmed\",\n PAYOUT_BLOCKED = \"PayoutBlocked\",\n}\n\n/**\n * Wire name of `PayoutConfirmed` before btc-vault v0.7.0 (btc-vault #2294).\n * Vault providers that run an older daemon still send it.\n */\nconst LEGACY_PAYOUT_BROADCAST = \"PayoutBroadcast\";\n\nconst PEGOUT_TERMINAL_STATUSES = new Set<string>([\n ClaimerPegoutStatusValue.PAYOUT_CONFIRMED,\n ClaimerPegoutStatusValue.PAYOUT_BLOCKED,\n]);\n\n/**\n * Replace the pre-v0.7.0 name `PayoutBroadcast` with `PayoutConfirmed`.\n * Other statuses pass through unchanged.\n */\nexport function normalizeClaimerPegoutStatus(status: string): string {\n return status === LEGACY_PAYOUT_BROADCAST\n ? ClaimerPegoutStatusValue.PAYOUT_CONFIRMED\n : status;\n}\n\n/** Whether a claimer status string maps to a known pegout state. */\nexport function isRecognizedPegoutStatus(status: string): boolean {\n return Object.values(ClaimerPegoutStatusValue).includes(\n status as ClaimerPegoutStatusValue,\n );\n}\n\n/**\n * Whether a claimer status is a hard-terminal pegout status\n * (PayoutConfirmed or PayoutBlocked). Soft-terminal conditions (polling\n * thresholds) are a consumer-side concern.\n */\nexport function isPegoutTerminalStatus(\n claimerStatus: string | undefined,\n): boolean {\n return !!claimerStatus && PEGOUT_TERMINAL_STATUSES.has(claimerStatus);\n}\n"],"names":["DaemonStatus","PRE_DEPOSITOR_SIGNATURES_STATES","POST_PAYOUT_SIGNATURE_STATUSES","VP_TRANSIENT_STATUSES","VP_TERMINAL_FAILURE_STATUSES","POST_WOTS_STATUSES","VP_BATCH_MAX_SIZE","RpcErrorCode","vaultIdKey","vaultId","attributeBatchResults","requestedVaultIds","results","requestedSet","byVaultId","seen","duplicate","unexpected","entry","normalized","missing","JsonRpcError","code","message","source","data","JSON_RPC_ERROR_CODES","JSON_RPC_VERSION","DEFAULT_RETRY_ATTEMPTS","DEFAULT_RETRY_DELAY_MS","DEFAULT_MAX_RESPONSE_BYTES","UNCAPPED_TYPED_RESPONSE_METHODS","RETRYABLE_HTTP_STATUS_CODES","DEFAULT_RETRYABLE_METHODS","defaultRetryableFor","method","AUTH_REJECTED_RPC_CODE","isAuthRejectedError","error","JsonRpcClient","config","__publicField","authState","headers","token","params","signal","response","jsonResponse","responseText","readResponseTextWithLimit","rpcResponse","err","callerSignal","requestId","maxRetries","body","lastError","attempt","timeoutController","timeoutId","merged","mergeAbortSignals","delay","ms","resolve","reject","onAbort","a","b","controller","onAbortA","onAbortB","cleanup","maxBytes","contentLength","parsedContentLength","responseTooLargeError","reader","decoder","totalBytes","done","value","ClaimerPegoutStatusValue","LEGACY_PAYOUT_BROADCAST","PEGOUT_TERMINAL_STATUSES","normalizeClaimerPegoutStatus","status","isRecognizedPegoutStatus","isPegoutTerminalStatus","claimerStatus"],"mappings":"iLAwCO,IAAKA,GAAAA,IACVA,EAAA,kBAAoB,mBACpBA,EAAA,0BAA4B,yBAC5BA,EAAA,mBAAqB,mBACrBA,EAAA,8BAAgC,8BAChCA,EAAA,gCAAkC,+BAClCA,EAAA,gCAAkC,+BAClCA,EAAA,6BAA+B,6BAC/BA,EAAA,aAAe,cACfA,EAAA,mBAAqB,oBACrBA,EAAA,4BAA8B,4BAC9BA,EAAA,UAAY,YACZA,EAAA,QAAU,UACVA,EAAA,mBAAqB,oBACrBA,EAAA,wBAA0B,uBAC1BA,EAAA,aAAe,cACfA,EAAA,mBAAqB,mBACrBA,EAAA,iBAAmB,iBACnBA,EAAA,kBAAoB,kBAlBVA,IAAAA,GAAA,CAAA,CAAA,EA6BL,MAAMC,EAA2D,CACtE,mBACA,mBACA,8BACA,+BACA,8BACF,EAGMC,EAA0D,CAC9D,cACA,oBACA,4BACA,WACF,EAMaC,MAAuD,IAAI,CACtE,mBACA,8BACA,+BACA,+BACA,GAAGD,CACL,CAAC,EAkBYE,MAA8D,IAAI,CAC7E,oBACA,uBACA,cACA,mBACA,iBACA,iBACF,CAAC,EAOYC,MAAoD,IAAI,CACnE,GAAGF,EACH,4BACF,CAAC,EAuSYG,EAAoB,GAU1B,IAAKC,GAAAA,IACVA,EAAAA,EAAA,gBAAkB,IAAA,EAAlB,kBADUA,IAAAA,GAAA,CAAA,CAAA,EClZL,SAASC,EAAWC,EAAyB,CAElD,OADmBA,EAAQ,WAAW,IAAI,EAAIA,EA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