@babylonlabs-io/ts-sdk 0.74.0 → 0.74.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 (132) hide show
  1. package/dist/{PeginManager-E-UHA1un.cjs → PeginManager-DEByBX5R.cjs} +2 -2
  2. package/dist/{PeginManager-E-UHA1un.cjs.map → PeginManager-DEByBX5R.cjs.map} +1 -1
  3. package/dist/{PeginManager-C9RPOd0L.js → PeginManager-DNimKlmw.js} +11 -11
  4. package/dist/{PeginManager-C9RPOd0L.js.map → PeginManager-DNimKlmw.js.map} +1 -1
  5. package/dist/{bip322Verify-D6sBBUHE.js → bip322Verify-DSco3Yhl.js} +2 -2
  6. package/dist/{bip322Verify-D6sBBUHE.js.map → bip322Verify-DSco3Yhl.js.map} +1 -1
  7. package/dist/buildAndBroadcastReclaim-Cqc6Jiqk.cjs +2 -0
  8. package/dist/{buildAndBroadcastReclaim-U-PyFfDg.cjs.map → buildAndBroadcastReclaim-Cqc6Jiqk.cjs.map} +1 -1
  9. package/dist/{buildAndBroadcastReclaim-BXclIcu_.js → buildAndBroadcastReclaim-DCGcupg7.js} +6 -6
  10. package/dist/{buildAndBroadcastReclaim-BXclIcu_.js.map → buildAndBroadcastReclaim-DCGcupg7.js.map} +1 -1
  11. package/dist/constants-BTZdyOuk.cjs +2 -0
  12. package/dist/constants-BTZdyOuk.cjs.map +1 -0
  13. package/dist/constants-D5vORbQE.js +29 -0
  14. package/dist/constants-D5vORbQE.js.map +1 -0
  15. package/dist/fundPeginTransaction-54-Rwb2k.cjs +2 -0
  16. package/dist/fundPeginTransaction-54-Rwb2k.cjs.map +1 -0
  17. package/dist/fundPeginTransaction-CwhRbCQC.js +88 -0
  18. package/dist/fundPeginTransaction-CwhRbCQC.js.map +1 -0
  19. package/dist/{index-Cs7_Evtk.cjs → index-CK1Xvq4K.cjs} +2 -2
  20. package/dist/{index-Cs7_Evtk.cjs.map → index-CK1Xvq4K.cjs.map} +1 -1
  21. package/dist/{index-LgmJhdEN.js → index-DQ5bfoT3.js} +2 -2
  22. package/dist/{index-LgmJhdEN.js.map → index-DQ5bfoT3.js.map} +1 -1
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.js +15 -15
  25. package/dist/noPayout-4RZB2g1e.cjs +2 -0
  26. package/dist/noPayout-4RZB2g1e.cjs.map +1 -0
  27. package/dist/noPayout-DiGr4eas.js +361 -0
  28. package/dist/noPayout-DiGr4eas.js.map +1 -0
  29. package/dist/{parseFundingOutpoints-B67CoXpF.js → parseFundingOutpoints-BQWvINfm.js} +2 -2
  30. package/dist/{parseFundingOutpoints-B67CoXpF.js.map → parseFundingOutpoints-BQWvINfm.js.map} +1 -1
  31. package/dist/pegin-registration-client-CXK3B_D1.js +882 -0
  32. package/dist/pegin-registration-client-CXK3B_D1.js.map +1 -0
  33. package/dist/pegin-registration-client-DLsMNm8Z.cjs +2 -0
  34. package/dist/pegin-registration-client-DLsMNm8Z.cjs.map +1 -0
  35. package/dist/{primeVpAuth-DBHohVKM.cjs → primeVpAuth-BOGKniTl.cjs} +2 -2
  36. package/dist/{primeVpAuth-DBHohVKM.cjs.map → primeVpAuth-BOGKniTl.cjs.map} +1 -1
  37. package/dist/{primeVpAuth-DvaD45q_.js → primeVpAuth-DdfHSC53.js} +4 -4
  38. package/dist/{primeVpAuth-DvaD45q_.js.map → primeVpAuth-DdfHSC53.js.map} +1 -1
  39. package/dist/{psbtInputFields-BIxBpPj2.cjs → psbtInputFields-BrV_ZfL_.cjs} +2 -2
  40. package/dist/{psbtInputFields-BIxBpPj2.cjs.map → psbtInputFields-BrV_ZfL_.cjs.map} +1 -1
  41. package/dist/{psbtInputFields-B3e05Xe6.js → psbtInputFields-CCVyaQMi.js} +2 -2
  42. package/dist/{psbtInputFields-B3e05Xe6.js.map → psbtInputFields-CCVyaQMi.js.map} +1 -1
  43. package/dist/secp256k1-D-H9jmd7.js +1766 -0
  44. package/dist/secp256k1-D-H9jmd7.js.map +1 -0
  45. package/dist/secp256k1-DDHQ1_za.cjs +2 -0
  46. package/dist/secp256k1-DDHQ1_za.cjs.map +1 -0
  47. package/dist/{sha2-CrlWM5S8.js → sha2-CLpQd0Rd.js} +8 -8
  48. package/dist/{sha2-CrlWM5S8.js.map → sha2-CLpQd0Rd.js.map} +1 -1
  49. package/dist/{signPsbtsWithFallback-DMSpIQWH.cjs → signPsbtsWithFallback-DtwzL5AA.cjs} +2 -2
  50. package/dist/{signPsbtsWithFallback-DMSpIQWH.cjs.map → signPsbtsWithFallback-DtwzL5AA.cjs.map} +1 -1
  51. package/dist/{signPsbtsWithFallback-0VBALhjS.js → signPsbtsWithFallback-f7QLp0q8.js} +4 -4
  52. package/dist/{signPsbtsWithFallback-0VBALhjS.js.map → signPsbtsWithFallback-f7QLp0q8.js.map} +1 -1
  53. package/dist/tbv/core/clients/eth/index.cjs +1 -1
  54. package/dist/tbv/core/clients/eth/index.js +3 -3
  55. package/dist/tbv/core/clients/index.cjs +1 -1
  56. package/dist/tbv/core/clients/index.js +5 -5
  57. package/dist/tbv/core/clients/vault-provider/status/index.cjs +1 -1
  58. package/dist/tbv/core/clients/vault-provider/status/index.js +1 -1
  59. package/dist/tbv/core/index.cjs +1 -1
  60. package/dist/tbv/core/index.js +15 -15
  61. package/dist/tbv/core/managers/index.cjs +1 -1
  62. package/dist/tbv/core/managers/index.js +2 -2
  63. package/dist/tbv/core/primitives/index.cjs +1 -1
  64. package/dist/tbv/core/primitives/index.js +4 -4
  65. package/dist/tbv/core/primitives/psbt/__tests__/assertPeginTxShape.test.d.ts +5 -6
  66. package/dist/tbv/core/primitives/psbt/__tests__/assertPeginTxShape.test.d.ts.map +1 -1
  67. package/dist/tbv/core/primitives/psbt/__tests__/assertWasmPeginSizing.test.d.ts +2 -2
  68. package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts +36 -14
  69. package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts.map +1 -1
  70. package/dist/tbv/core/primitives/psbt/constants.d.ts +39 -0
  71. package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -1
  72. package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
  73. package/dist/tbv/core/primitives/psbt/peginInput.d.ts.map +1 -1
  74. package/dist/tbv/core/primitives/psbt/refund.d.ts.map +1 -1
  75. package/dist/tbv/core/services/index.cjs +1 -1
  76. package/dist/tbv/core/services/index.js +2 -2
  77. package/dist/tbv/core/utils/fee/constants.d.ts +4 -4
  78. package/dist/tbv/core/utils/index.cjs +1 -1
  79. package/dist/tbv/core/utils/index.js +2 -2
  80. package/dist/tbv/core/utils/transaction/fundPeginTransaction.d.ts.map +1 -1
  81. package/dist/tbv/core/vault-secrets/index.js +1 -1
  82. package/dist/tbv/index.cjs +1 -1
  83. package/dist/tbv/index.js +15 -15
  84. package/dist/test/setup.browser.d.ts +2 -0
  85. package/dist/test/setup.browser.d.ts.map +1 -0
  86. package/dist/testing/index.js +1 -1
  87. package/dist/{toRefundInputs-C3oIN0aW.js → toRefundInputs-BNSXIymn.js} +7 -7
  88. package/dist/{toRefundInputs-C3oIN0aW.js.map → toRefundInputs-BNSXIymn.js.map} +1 -1
  89. package/dist/{toRefundInputs-BwG6T0PP.cjs → toRefundInputs-meTyor7r.cjs} +2 -2
  90. package/dist/{toRefundInputs-BwG6T0PP.cjs.map → toRefundInputs-meTyor7r.cjs.map} +1 -1
  91. package/dist/{types-DSlcXtog.cjs → types-BzSOthHH.cjs} +2 -2
  92. package/dist/{types-DSlcXtog.cjs.map → types-BzSOthHH.cjs.map} +1 -1
  93. package/dist/{types-CPDLZm3l.js → types-C5DyrC8F.js} +2 -2
  94. package/dist/{types-CPDLZm3l.js.map → types-C5DyrC8F.js.map} +1 -1
  95. package/dist/verifyKeyPathSchnorrSignature-BVtNwgK6.js +360 -0
  96. package/dist/verifyKeyPathSchnorrSignature-BVtNwgK6.js.map +1 -0
  97. package/dist/verifyKeyPathSchnorrSignature-BjB8Znly.cjs +2 -0
  98. package/dist/verifyKeyPathSchnorrSignature-BjB8Znly.cjs.map +1 -0
  99. package/dist/verifyScriptPathSchnorrSignature-D_epga4j.js +1140 -0
  100. package/dist/verifyScriptPathSchnorrSignature-D_epga4j.js.map +1 -0
  101. package/dist/verifyScriptPathSchnorrSignature-DaRqvEgW.cjs +2 -0
  102. package/dist/verifyScriptPathSchnorrSignature-DaRqvEgW.cjs.map +1 -0
  103. package/package.json +4 -1
  104. package/dist/buildAndBroadcastReclaim-U-PyFfDg.cjs +0 -2
  105. package/dist/constants-Bh38W9mq.cjs +0 -2
  106. package/dist/constants-Bh38W9mq.cjs.map +0 -1
  107. package/dist/constants-CPzppOdq.js +0 -17
  108. package/dist/constants-CPzppOdq.js.map +0 -1
  109. package/dist/fundPeginTransaction-B2wyjqp0.js +0 -83
  110. package/dist/fundPeginTransaction-B2wyjqp0.js.map +0 -1
  111. package/dist/fundPeginTransaction-BLD8FRL9.cjs +0 -2
  112. package/dist/fundPeginTransaction-BLD8FRL9.cjs.map +0 -1
  113. package/dist/noPayout-DpGRzidi.js +0 -353
  114. package/dist/noPayout-DpGRzidi.js.map +0 -1
  115. package/dist/noPayout-zEifyecV.cjs +0 -2
  116. package/dist/noPayout-zEifyecV.cjs.map +0 -1
  117. package/dist/pegin-registration-client-6vLk2itL.cjs +0 -2
  118. package/dist/pegin-registration-client-6vLk2itL.cjs.map +0 -1
  119. package/dist/pegin-registration-client-BdRiR8br.js +0 -2635
  120. package/dist/pegin-registration-client-BdRiR8br.js.map +0 -1
  121. package/dist/vaultCoreVersion-DYfw3qed.cjs +0 -2
  122. package/dist/vaultCoreVersion-DYfw3qed.cjs.map +0 -1
  123. package/dist/vaultCoreVersion-D_fP9P3C.js +0 -10
  124. package/dist/vaultCoreVersion-D_fP9P3C.js.map +0 -1
  125. package/dist/verifyKeyPathSchnorrSignature-BedSbH2D.cjs +0 -2
  126. package/dist/verifyKeyPathSchnorrSignature-BedSbH2D.cjs.map +0 -1
  127. package/dist/verifyKeyPathSchnorrSignature-BrgUJmV0.js +0 -372
  128. package/dist/verifyKeyPathSchnorrSignature-BrgUJmV0.js.map +0 -1
  129. package/dist/verifyScriptPathSchnorrSignature-BfNUSgA7.cjs +0 -2
  130. package/dist/verifyScriptPathSchnorrSignature-BfNUSgA7.cjs.map +0 -1
  131. package/dist/verifyScriptPathSchnorrSignature-Ciq_xZhw.js +0 -951
  132. package/dist/verifyScriptPathSchnorrSignature-Ciq_xZhw.js.map +0 -1
@@ -1,6 +1,6 @@
1
1
  import * as u from "@bitcoin-js/tiny-secp256k1-asmjs";
2
2
  import { Transaction as c, payments as l, script as S } from "bitcoinjs-lib";
3
- import { s as p } from "./sha2-CrlWM5S8.js";
3
+ import { s as p } from "./sha2-CLpQd0Rd.js";
4
4
  import { Buffer as a } from "buffer";
5
5
  const O = "BIP0322-signed-message", A = "TapTweak", P = 32, H = 64, N = 33, d = 71, w = 72, _ = 0, E = 0, T = 0, g = 0, B = 32, D = 4294967295, U = 0, k = 0, G = 32, R = 106;
6
6
  function I(r, n) {
@@ -76,4 +76,4 @@ export {
76
76
  v as b,
77
77
  L as v
78
78
  };
79
- //# sourceMappingURL=bip322Verify-D6sBBUHE.js.map
79
+ //# sourceMappingURL=bip322Verify-DSco3Yhl.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"bip322Verify-D6sBBUHE.js","sources":["../src/tbv/core/clients/vault-provider/auth/bip322Verify.ts"],"sourcesContent":["/**\n * BIP-322 \"simple\" signature verification for P2TR key-path and P2WPKH.\n *\n * Mirrors the Rust reference in\n * `btc-vault/crates/btc-signer/src/message.rs` (`verify_bip322_message`\n * and the P2WPKH arm of `verify_pop_witness`, both of which delegate to\n * the `bip322` crate 0.0.10's `verify_simple`).\n *\n * The algorithm:\n *\n * 1. Compute the BIP-322 tagged-hash of the message:\n * m_hash = SHA256( SHA256(tag) || SHA256(tag) || message )\n * where tag = \"BIP0322-signed-message\".\n *\n * 2. Build a virtual \"to_spend\" transaction with one input (prevout\n * all-zero txid + 0xFFFFFFFF vout, scriptSig = `OP_0 PUSH32 m_hash`,\n * sequence = 0) and one output (value 0, scriptPubKey = the signer's\n * address: P2TR key-path-only, or P2WPKH of the compressed pubkey).\n *\n * 3. Build a \"to_sign\" transaction that spends to_spend[0] and has a\n * single `OP_RETURN` output (value 0).\n *\n * 4. Compute the sighash of to_sign input 0: BIP-341 taproot for P2TR\n * (SIGHASH_DEFAULT 0x00 unless the witness item carried a trailing\n * SIGHASH_ALL 0x01 byte), BIP-143 with the standard P2WPKH\n * scriptCode for P2WPKH (SIGHASH_ALL only).\n *\n * 5. Verify the signature: Schnorr against the **tweaked** output key\n * `Q = P + tap_tweak(P) * G` for P2TR (no merkle root — key-path\n * only), ECDSA against the compressed pubkey for P2WPKH.\n *\n * `bitcoinjs-lib` handles (2)–(4); `tiny-secp256k1-asmjs` provides\n * the tweak and the Schnorr/ECDSA verifies. Pulling in a full BIP-322\n * library would add a peer dep for what amounts to ~40 lines of glue.\n *\n * @module tbv/core/clients/vault-provider/auth/bip322Verify\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { script as bscript, payments, Transaction } from \"bitcoinjs-lib\";\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { Buffer } from \"buffer\";\n\n/** BIP-322 message tag (BIP-340 tagged-hash style). */\nconst BIP322_TAG = \"BIP0322-signed-message\";\n\n/** BIP-341 taproot-tweak tag. */\nconst TAPTWEAK_TAG = \"TapTweak\";\n\nconst X_ONLY_PUBKEY_SIZE = 32;\nconst SCHNORR_SIG_SIZE = 64;\n/** SEC1 compressed pubkey: 0x02/0x03 prefix + 32-byte x coordinate. */\nconst COMPRESSED_PUBKEY_SIZE = 33;\n/**\n * vaultd's P2WPKH BIP-322 verifier accepts ONLY 71/72-byte encoded\n * signatures — DER (70/71B) + sighash byte (`bip322` crate 0.0.10\n * `verify.rs:141-153`). A shorter (short-DER) signature fails ingestion\n * permanently, so this gate must be exactly as strict. Exported so\n * `verifyPopWitness` can pre-screen with a cause-naming error.\n */\nexport const P2WPKH_ENCODED_SIG_MIN = 71;\nexport const P2WPKH_ENCODED_SIG_MAX = 72;\n\n// NOTE: bitcoinjs-lib v6.x's `Transaction.addOutput` and its sighash\n// methods are typed for `Satoshi` (a UInt53 number), not `bigint`.\n// Passing `BigInt(0)` triggers a typeforce assertion in `addOutput`\n// (\"Expected property '1' of type Satoshi, got BigInt 0\") which the\n// verifiers' try/catch silently turns into `verify -> false`. Use\n// plain `0` everywhere.\nconst ZERO_SATS = 0;\n\n// Wire fields of the virtual to_spend/to_sign transactions (`bip322`\n// crate 0.0.10 `util.rs:18-85`).\nconst BIP322_TX_VERSION = 0;\nconst BIP322_TX_LOCKTIME = 0;\nconst BIP322_INPUT_SEQUENCE = 0;\n/** to_spend prevout: all-zero 32-byte txid at index 0xFFFFFFFF (`util.rs:18-85`). */\nconst TO_SPEND_PREVOUT_TXID_BYTES = 32;\nconst TO_SPEND_PREVOUT_INDEX = 0xffffffff;\n/** to_sign spends to_spend's only output (`util.rs:18-85`). */\nconst TO_SPEND_OUTPUT_INDEX = 0;\nconst OP_0 = 0x00;\n/** Direct push of the 32-byte tagged message hash. */\nconst OP_PUSHBYTES_32 = 0x20;\nconst OP_RETURN = 0x6a;\n\n/**\n * BIP-340 tagged hash: `SHA256( SHA256(tag) || SHA256(tag) || data )`.\n * Used for both BIP-322 message hashing and BIP-341 tap-tweak.\n */\nfunction taggedHash(tag: string, data: Uint8Array): Uint8Array {\n const tagBytes = new TextEncoder().encode(tag);\n const tagHash = sha256(tagBytes);\n const preimage = new Uint8Array(tagHash.length * 2 + data.length);\n preimage.set(tagHash, 0);\n preimage.set(tagHash, tagHash.length);\n preimage.set(data, tagHash.length * 2);\n return sha256(preimage);\n}\n\n/**\n * Apply BIP-341 taproot tweak to an x-only pubkey with no merkle\n * root (key-path-only address).\n *\n * `tap_tweak = hash_TapTweak(P)`\n * `Q = P + tap_tweak * G` (x-only, even-Y parity)\n *\n * Returns the tweaked 32-byte x-only pubkey, or null if the tweak\n * produces a point-at-infinity or invalid result.\n */\nfunction tweakXOnlyKey(xOnly: Uint8Array): Uint8Array | null {\n if (xOnly.length !== X_ONLY_PUBKEY_SIZE) return null;\n const tweak = taggedHash(TAPTWEAK_TAG, xOnly);\n const tweaked = ecc.xOnlyPointAddTweak(xOnly, tweak);\n return tweaked ? tweaked.xOnlyPubkey : null;\n}\n\n/**\n * Build the BIP-322 virtual `to_sign` transaction for a signer\n * scriptPubKey (steps 1–3 above; `bip322` crate 0.0.10 `util.rs:18-85`:\n * both txs version 0, locktime 0, sequence 0, all values 0).\n */\nfunction buildToSignTransaction(\n messageBytes: Uint8Array,\n scriptPubKey: Buffer,\n): Transaction {\n const messageHash = taggedHash(BIP322_TAG, messageBytes);\n\n const toSpend = new Transaction();\n toSpend.version = BIP322_TX_VERSION;\n toSpend.locktime = BIP322_TX_LOCKTIME;\n const scriptSig = Buffer.concat([\n Buffer.from([OP_0, OP_PUSHBYTES_32]),\n Buffer.from(messageHash),\n ]);\n toSpend.addInput(\n Buffer.alloc(TO_SPEND_PREVOUT_TXID_BYTES, 0),\n TO_SPEND_PREVOUT_INDEX,\n BIP322_INPUT_SEQUENCE,\n scriptSig,\n );\n toSpend.addOutput(scriptPubKey, ZERO_SATS);\n\n const toSign = new Transaction();\n toSign.version = BIP322_TX_VERSION;\n toSign.locktime = BIP322_TX_LOCKTIME;\n // Bitcoin txid in natural-byte (little-endian) form.\n toSign.addInput(\n toSpend.getHash(),\n TO_SPEND_OUTPUT_INDEX,\n BIP322_INPUT_SEQUENCE,\n );\n toSign.addOutput(Buffer.from([OP_RETURN]), ZERO_SATS);\n\n return toSign;\n}\n\n/**\n * Verify a BIP-322 \"simple\" P2TR key-path signature over an arbitrary\n * byte message.\n *\n * @internal Consumed by `verifyServerIdentity` (VP auth) and\n * `verifyPopWitness` (PoP pre-registration check), and exposed so the\n * golden-vector test suite can pin the verifier independently.\n *\n * @param messageBytes - The bytes that were signed (e.g. a CBOR-encoded\n * payload). Not pre-hashed; this function applies\n * the BIP-322 tagged hash internally.\n * @param xOnlyPubkey - 32-byte x-only pubkey of the signer (pre-tweak).\n * @param signature - 64-byte raw Schnorr signature (BIP-340), as\n * emitted by a key-path witness. The trailing\n * sighash byte of a 65-byte witness item is not\n * part of it — pass it as `hashType` instead.\n * @param hashType - BIP-341 sighash type the signature commits to.\n * `SIGHASH_DEFAULT` (0x00) for a 64-byte witness\n * item, `SIGHASH_ALL` (0x01) for a 65-byte one.\n * @returns `true` if the signature verifies against the address\n * derived from `xOnlyPubkey`; `false` otherwise.\n */\nexport function verifyBip322Simple(\n messageBytes: Uint8Array,\n xOnlyPubkey: Uint8Array,\n signature: Uint8Array,\n hashType: number = Transaction.SIGHASH_DEFAULT,\n): boolean {\n if (xOnlyPubkey.length !== X_ONLY_PUBKEY_SIZE) return false;\n if (signature.length !== SCHNORR_SIG_SIZE) return false;\n // Only the two types a BIP-322 witness may carry. SIGHASH_NONE/SINGLE and the\n // ANYONECANPAY variants would verify here but are rejected downstream.\n if (\n hashType !== Transaction.SIGHASH_DEFAULT &&\n hashType !== Transaction.SIGHASH_ALL\n ) {\n return false;\n }\n\n // Any exception from the underlying crypto libraries (e.g. the\n // `Expected Point` error `tiny-secp256k1` throws when the supplied\n // 32 bytes don't represent a valid x-coordinate on secp256k1) is\n // treated as a verification failure rather than propagated — a\n // verifier MUST return a boolean, not raise.\n try {\n // scriptPubKey for the signer's P2TR key-path-only address.\n // bitcoinjs-lib's `payments.p2tr({ internalPubkey })` computes the\n // tweak and produces the `OP_1 <tweaked_xonly>` output script.\n const p2tr = payments.p2tr({\n internalPubkey: Buffer.from(xOnlyPubkey),\n });\n if (!p2tr.output) return false;\n const scriptPubKey = p2tr.output;\n\n const toSign = buildToSignTransaction(messageBytes, scriptPubKey);\n\n // Taproot sighash for to_sign input 0.\n const sighash = toSign.hashForWitnessV1(\n 0,\n [scriptPubKey],\n [ZERO_SATS],\n hashType,\n );\n\n // Tweak the x-only pubkey (no merkle root) and verify Schnorr.\n const tweakedXOnly = tweakXOnlyKey(xOnlyPubkey);\n if (!tweakedXOnly) return false;\n\n return ecc.verifySchnorr(sighash, tweakedXOnly, signature);\n } catch {\n return false;\n }\n}\n\n/**\n * Verify a BIP-322 \"simple\" P2WPKH signature over an arbitrary byte\n * message, mirroring the verifier vaultd runs on a two-item PoP witness\n * (`bip322` crate 0.0.10 `verify.rs:102-186 verify_full_p2wpkh`).\n *\n * @internal Consumed by `verifyPopWitness` for Native SegWit software\n * wallets, and exposed so the BIP-322 official-vector test suite can pin\n * the verifier independently.\n *\n * @param compressedPubkey - 33-byte SEC1 compressed pubkey of the signer\n * (witness item 1). The address is derived from\n * it; network affects only bech32 encoding, not\n * script or sighash (`message.rs:125-127`).\n * @param encodedSignature - Witness item 0: DER signature with trailing\n * sighash byte, 71 or 72 bytes, SIGHASH_ALL only\n * (`verify.rs:141-161`).\n * @returns `true` if the signature verifies against the P2WPKH address of\n * `compressedPubkey`; `false` otherwise.\n */\nexport function verifyBip322P2wpkhSimple(\n messageBytes: Uint8Array,\n compressedPubkey: Uint8Array,\n encodedSignature: Uint8Array,\n): boolean {\n if (compressedPubkey.length !== COMPRESSED_PUBKEY_SIZE) return false;\n if (\n encodedSignature.length < P2WPKH_ENCODED_SIG_MIN ||\n encodedSignature.length > P2WPKH_ENCODED_SIG_MAX\n ) {\n return false;\n }\n // Any exception below (strict-DER decode, malformed pubkey) is a\n // verification failure, not an error — a verifier returns a boolean.\n try {\n // Full curve-point parse, as `PublicKey::from_slice` (`verify.rs:82-83`).\n if (!ecc.isPointCompressed(compressedPubkey)) return false;\n\n // Strict DER decode, then SIGHASH_ALL only — deliberately NARROWER than\n // `verify.rs:156-161` (its from_consensus maps more bytes to All); host-stricter is safe.\n const { signature, hashType } = bscript.signature.decode(\n Buffer.from(encodedSignature),\n );\n // decode tolerates non-minimal integers (bip66.js never bounds lenR/lenS at 33;\n // fromDER truncates, script_signature.js:29-35) that vaultd's strict libsecp\n // parse rejects (secp256k1-sys ecdsa_impl.h:127-136) — require the unique\n // minimal encoding by re-encoding and byte-comparing.\n if (\n !bscript.signature\n .encode(signature, hashType)\n .equals(Buffer.from(encodedSignature))\n ) {\n return false;\n }\n if (hashType !== Transaction.SIGHASH_ALL) return false;\n\n // scriptPubKey = OP_0 PUSH20 hash160(pubkey) (`message.rs:127 Address::p2wpkh`).\n const p2wpkh = payments.p2wpkh({ pubkey: Buffer.from(compressedPubkey) });\n if (!p2wpkh.output || !p2wpkh.hash) return false;\n\n const toSign = buildToSignTransaction(messageBytes, p2wpkh.output);\n\n // BIP-143 sighash with the standard P2WPKH scriptCode\n // `OP_DUP OP_HASH160 <20B> OP_EQUALVERIFY OP_CHECKSIG` and value 0\n // (`verify.rs:163-173 p2wpkh_signature_hash`; scriptCode template per\n // bitcoinjs-lib's own P2WPKH signer, `src/psbt.js:1245-1255`).\n const scriptCode = payments.p2pkh({ hash: p2wpkh.hash }).output;\n if (!scriptCode) return false;\n const sighash = toSign.hashForWitnessV0(0, scriptCode, ZERO_SATS, hashType);\n\n // strict=true rejects high-S, as libsecp256k1's verify does\n // (`verify.rs:180-182`; secp256k1 crate `ecdsa/mod.rs:194`).\n return ecc.verify(sighash, compressedPubkey, signature, true);\n } catch {\n return false;\n }\n}\n"],"names":["BIP322_TAG","TAPTWEAK_TAG","X_ONLY_PUBKEY_SIZE","SCHNORR_SIG_SIZE","COMPRESSED_PUBKEY_SIZE","P2WPKH_ENCODED_SIG_MIN","P2WPKH_ENCODED_SIG_MAX","ZERO_SATS","BIP322_TX_VERSION","BIP322_TX_LOCKTIME","BIP322_INPUT_SEQUENCE","TO_SPEND_PREVOUT_TXID_BYTES","TO_SPEND_PREVOUT_INDEX","TO_SPEND_OUTPUT_INDEX","OP_0","OP_PUSHBYTES_32","OP_RETURN","taggedHash","tag","data","tagBytes","tagHash","sha256","preimage","tweakXOnlyKey","xOnly","tweak","tweaked","ecc","buildToSignTransaction","messageBytes","scriptPubKey","messageHash","toSpend","Transaction","scriptSig","Buffer","toSign","verifyBip322Simple","xOnlyPubkey","signature","hashType","p2tr","payments","sighash","tweakedXOnly","verifyBip322P2wpkhSimple","compressedPubkey","encodedSignature","bscript","p2wpkh","scriptCode"],"mappings":"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"}
1
+ {"version":3,"file":"bip322Verify-DSco3Yhl.js","sources":["../src/tbv/core/clients/vault-provider/auth/bip322Verify.ts"],"sourcesContent":["/**\n * BIP-322 \"simple\" signature verification for P2TR key-path and P2WPKH.\n *\n * Mirrors the Rust reference in\n * `btc-vault/crates/btc-signer/src/message.rs` (`verify_bip322_message`\n * and the P2WPKH arm of `verify_pop_witness`, both of which delegate to\n * the `bip322` crate 0.0.10's `verify_simple`).\n *\n * The algorithm:\n *\n * 1. Compute the BIP-322 tagged-hash of the message:\n * m_hash = SHA256( SHA256(tag) || SHA256(tag) || message )\n * where tag = \"BIP0322-signed-message\".\n *\n * 2. Build a virtual \"to_spend\" transaction with one input (prevout\n * all-zero txid + 0xFFFFFFFF vout, scriptSig = `OP_0 PUSH32 m_hash`,\n * sequence = 0) and one output (value 0, scriptPubKey = the signer's\n * address: P2TR key-path-only, or P2WPKH of the compressed pubkey).\n *\n * 3. Build a \"to_sign\" transaction that spends to_spend[0] and has a\n * single `OP_RETURN` output (value 0).\n *\n * 4. Compute the sighash of to_sign input 0: BIP-341 taproot for P2TR\n * (SIGHASH_DEFAULT 0x00 unless the witness item carried a trailing\n * SIGHASH_ALL 0x01 byte), BIP-143 with the standard P2WPKH\n * scriptCode for P2WPKH (SIGHASH_ALL only).\n *\n * 5. Verify the signature: Schnorr against the **tweaked** output key\n * `Q = P + tap_tweak(P) * G` for P2TR (no merkle root — key-path\n * only), ECDSA against the compressed pubkey for P2WPKH.\n *\n * `bitcoinjs-lib` handles (2)–(4); `tiny-secp256k1-asmjs` provides\n * the tweak and the Schnorr/ECDSA verifies. Pulling in a full BIP-322\n * library would add a peer dep for what amounts to ~40 lines of glue.\n *\n * @module tbv/core/clients/vault-provider/auth/bip322Verify\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { script as bscript, payments, Transaction } from \"bitcoinjs-lib\";\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { Buffer } from \"buffer\";\n\n/** BIP-322 message tag (BIP-340 tagged-hash style). */\nconst BIP322_TAG = \"BIP0322-signed-message\";\n\n/** BIP-341 taproot-tweak tag. */\nconst TAPTWEAK_TAG = \"TapTweak\";\n\nconst X_ONLY_PUBKEY_SIZE = 32;\nconst SCHNORR_SIG_SIZE = 64;\n/** SEC1 compressed pubkey: 0x02/0x03 prefix + 32-byte x coordinate. */\nconst COMPRESSED_PUBKEY_SIZE = 33;\n/**\n * vaultd's P2WPKH BIP-322 verifier accepts ONLY 71/72-byte encoded\n * signatures — DER (70/71B) + sighash byte (`bip322` crate 0.0.10\n * `verify.rs:141-153`). A shorter (short-DER) signature fails ingestion\n * permanently, so this gate must be exactly as strict. Exported so\n * `verifyPopWitness` can pre-screen with a cause-naming error.\n */\nexport const P2WPKH_ENCODED_SIG_MIN = 71;\nexport const P2WPKH_ENCODED_SIG_MAX = 72;\n\n// NOTE: bitcoinjs-lib v6.x's `Transaction.addOutput` and its sighash\n// methods are typed for `Satoshi` (a UInt53 number), not `bigint`.\n// Passing `BigInt(0)` triggers a typeforce assertion in `addOutput`\n// (\"Expected property '1' of type Satoshi, got BigInt 0\") which the\n// verifiers' try/catch silently turns into `verify -> false`. Use\n// plain `0` everywhere.\nconst ZERO_SATS = 0;\n\n// Wire fields of the virtual to_spend/to_sign transactions (`bip322`\n// crate 0.0.10 `util.rs:18-85`).\nconst BIP322_TX_VERSION = 0;\nconst BIP322_TX_LOCKTIME = 0;\nconst BIP322_INPUT_SEQUENCE = 0;\n/** to_spend prevout: all-zero 32-byte txid at index 0xFFFFFFFF (`util.rs:18-85`). */\nconst TO_SPEND_PREVOUT_TXID_BYTES = 32;\nconst TO_SPEND_PREVOUT_INDEX = 0xffffffff;\n/** to_sign spends to_spend's only output (`util.rs:18-85`). */\nconst TO_SPEND_OUTPUT_INDEX = 0;\nconst OP_0 = 0x00;\n/** Direct push of the 32-byte tagged message hash. */\nconst OP_PUSHBYTES_32 = 0x20;\nconst OP_RETURN = 0x6a;\n\n/**\n * BIP-340 tagged hash: `SHA256( SHA256(tag) || SHA256(tag) || data )`.\n * Used for both BIP-322 message hashing and BIP-341 tap-tweak.\n */\nfunction taggedHash(tag: string, data: Uint8Array): Uint8Array {\n const tagBytes = new TextEncoder().encode(tag);\n const tagHash = sha256(tagBytes);\n const preimage = new Uint8Array(tagHash.length * 2 + data.length);\n preimage.set(tagHash, 0);\n preimage.set(tagHash, tagHash.length);\n preimage.set(data, tagHash.length * 2);\n return sha256(preimage);\n}\n\n/**\n * Apply BIP-341 taproot tweak to an x-only pubkey with no merkle\n * root (key-path-only address).\n *\n * `tap_tweak = hash_TapTweak(P)`\n * `Q = P + tap_tweak * G` (x-only, even-Y parity)\n *\n * Returns the tweaked 32-byte x-only pubkey, or null if the tweak\n * produces a point-at-infinity or invalid result.\n */\nfunction tweakXOnlyKey(xOnly: Uint8Array): Uint8Array | null {\n if (xOnly.length !== X_ONLY_PUBKEY_SIZE) return null;\n const tweak = taggedHash(TAPTWEAK_TAG, xOnly);\n const tweaked = ecc.xOnlyPointAddTweak(xOnly, tweak);\n return tweaked ? tweaked.xOnlyPubkey : null;\n}\n\n/**\n * Build the BIP-322 virtual `to_sign` transaction for a signer\n * scriptPubKey (steps 1–3 above; `bip322` crate 0.0.10 `util.rs:18-85`:\n * both txs version 0, locktime 0, sequence 0, all values 0).\n */\nfunction buildToSignTransaction(\n messageBytes: Uint8Array,\n scriptPubKey: Buffer,\n): Transaction {\n const messageHash = taggedHash(BIP322_TAG, messageBytes);\n\n const toSpend = new Transaction();\n toSpend.version = BIP322_TX_VERSION;\n toSpend.locktime = BIP322_TX_LOCKTIME;\n const scriptSig = Buffer.concat([\n Buffer.from([OP_0, OP_PUSHBYTES_32]),\n Buffer.from(messageHash),\n ]);\n toSpend.addInput(\n Buffer.alloc(TO_SPEND_PREVOUT_TXID_BYTES, 0),\n TO_SPEND_PREVOUT_INDEX,\n BIP322_INPUT_SEQUENCE,\n scriptSig,\n );\n toSpend.addOutput(scriptPubKey, ZERO_SATS);\n\n const toSign = new Transaction();\n toSign.version = BIP322_TX_VERSION;\n toSign.locktime = BIP322_TX_LOCKTIME;\n // Bitcoin txid in natural-byte (little-endian) form.\n toSign.addInput(\n toSpend.getHash(),\n TO_SPEND_OUTPUT_INDEX,\n BIP322_INPUT_SEQUENCE,\n );\n toSign.addOutput(Buffer.from([OP_RETURN]), ZERO_SATS);\n\n return toSign;\n}\n\n/**\n * Verify a BIP-322 \"simple\" P2TR key-path signature over an arbitrary\n * byte message.\n *\n * @internal Consumed by `verifyServerIdentity` (VP auth) and\n * `verifyPopWitness` (PoP pre-registration check), and exposed so the\n * golden-vector test suite can pin the verifier independently.\n *\n * @param messageBytes - The bytes that were signed (e.g. a CBOR-encoded\n * payload). Not pre-hashed; this function applies\n * the BIP-322 tagged hash internally.\n * @param xOnlyPubkey - 32-byte x-only pubkey of the signer (pre-tweak).\n * @param signature - 64-byte raw Schnorr signature (BIP-340), as\n * emitted by a key-path witness. The trailing\n * sighash byte of a 65-byte witness item is not\n * part of it — pass it as `hashType` instead.\n * @param hashType - BIP-341 sighash type the signature commits to.\n * `SIGHASH_DEFAULT` (0x00) for a 64-byte witness\n * item, `SIGHASH_ALL` (0x01) for a 65-byte one.\n * @returns `true` if the signature verifies against the address\n * derived from `xOnlyPubkey`; `false` otherwise.\n */\nexport function verifyBip322Simple(\n messageBytes: Uint8Array,\n xOnlyPubkey: Uint8Array,\n signature: Uint8Array,\n hashType: number = Transaction.SIGHASH_DEFAULT,\n): boolean {\n if (xOnlyPubkey.length !== X_ONLY_PUBKEY_SIZE) return false;\n if (signature.length !== SCHNORR_SIG_SIZE) return false;\n // Only the two types a BIP-322 witness may carry. SIGHASH_NONE/SINGLE and the\n // ANYONECANPAY variants would verify here but are rejected downstream.\n if (\n hashType !== Transaction.SIGHASH_DEFAULT &&\n hashType !== Transaction.SIGHASH_ALL\n ) {\n return false;\n }\n\n // Any exception from the underlying crypto libraries (e.g. the\n // `Expected Point` error `tiny-secp256k1` throws when the supplied\n // 32 bytes don't represent a valid x-coordinate on secp256k1) is\n // treated as a verification failure rather than propagated — a\n // verifier MUST return a boolean, not raise.\n try {\n // scriptPubKey for the signer's P2TR key-path-only address.\n // bitcoinjs-lib's `payments.p2tr({ internalPubkey })` computes the\n // tweak and produces the `OP_1 <tweaked_xonly>` output script.\n const p2tr = payments.p2tr({\n internalPubkey: Buffer.from(xOnlyPubkey),\n });\n if (!p2tr.output) return false;\n const scriptPubKey = p2tr.output;\n\n const toSign = buildToSignTransaction(messageBytes, scriptPubKey);\n\n // Taproot sighash for to_sign input 0.\n const sighash = toSign.hashForWitnessV1(\n 0,\n [scriptPubKey],\n [ZERO_SATS],\n hashType,\n );\n\n // Tweak the x-only pubkey (no merkle root) and verify Schnorr.\n const tweakedXOnly = tweakXOnlyKey(xOnlyPubkey);\n if (!tweakedXOnly) return false;\n\n return ecc.verifySchnorr(sighash, tweakedXOnly, signature);\n } catch {\n return false;\n }\n}\n\n/**\n * Verify a BIP-322 \"simple\" P2WPKH signature over an arbitrary byte\n * message, mirroring the verifier vaultd runs on a two-item PoP witness\n * (`bip322` crate 0.0.10 `verify.rs:102-186 verify_full_p2wpkh`).\n *\n * @internal Consumed by `verifyPopWitness` for Native SegWit software\n * wallets, and exposed so the BIP-322 official-vector test suite can pin\n * the verifier independently.\n *\n * @param compressedPubkey - 33-byte SEC1 compressed pubkey of the signer\n * (witness item 1). The address is derived from\n * it; network affects only bech32 encoding, not\n * script or sighash (`message.rs:125-127`).\n * @param encodedSignature - Witness item 0: DER signature with trailing\n * sighash byte, 71 or 72 bytes, SIGHASH_ALL only\n * (`verify.rs:141-161`).\n * @returns `true` if the signature verifies against the P2WPKH address of\n * `compressedPubkey`; `false` otherwise.\n */\nexport function verifyBip322P2wpkhSimple(\n messageBytes: Uint8Array,\n compressedPubkey: Uint8Array,\n encodedSignature: Uint8Array,\n): boolean {\n if (compressedPubkey.length !== COMPRESSED_PUBKEY_SIZE) return false;\n if (\n encodedSignature.length < P2WPKH_ENCODED_SIG_MIN ||\n encodedSignature.length > P2WPKH_ENCODED_SIG_MAX\n ) {\n return false;\n }\n // Any exception below (strict-DER decode, malformed pubkey) is a\n // verification failure, not an error — a verifier returns a boolean.\n try {\n // Full curve-point parse, as `PublicKey::from_slice` (`verify.rs:82-83`).\n if (!ecc.isPointCompressed(compressedPubkey)) return false;\n\n // Strict DER decode, then SIGHASH_ALL only — deliberately NARROWER than\n // `verify.rs:156-161` (its from_consensus maps more bytes to All); host-stricter is safe.\n const { signature, hashType } = bscript.signature.decode(\n Buffer.from(encodedSignature),\n );\n // decode tolerates non-minimal integers (bip66.js never bounds lenR/lenS at 33;\n // fromDER truncates, script_signature.js:29-35) that vaultd's strict libsecp\n // parse rejects (secp256k1-sys ecdsa_impl.h:127-136) — require the unique\n // minimal encoding by re-encoding and byte-comparing.\n if (\n !bscript.signature\n .encode(signature, hashType)\n .equals(Buffer.from(encodedSignature))\n ) {\n return false;\n }\n if (hashType !== Transaction.SIGHASH_ALL) return false;\n\n // scriptPubKey = OP_0 PUSH20 hash160(pubkey) (`message.rs:127 Address::p2wpkh`).\n const p2wpkh = payments.p2wpkh({ pubkey: Buffer.from(compressedPubkey) });\n if (!p2wpkh.output || !p2wpkh.hash) return false;\n\n const toSign = buildToSignTransaction(messageBytes, p2wpkh.output);\n\n // BIP-143 sighash with the standard P2WPKH scriptCode\n // `OP_DUP OP_HASH160 <20B> OP_EQUALVERIFY OP_CHECKSIG` and value 0\n // (`verify.rs:163-173 p2wpkh_signature_hash`; scriptCode template per\n // bitcoinjs-lib's own P2WPKH signer, `src/psbt.js:1245-1255`).\n const scriptCode = payments.p2pkh({ hash: p2wpkh.hash }).output;\n if (!scriptCode) return false;\n const sighash = toSign.hashForWitnessV0(0, scriptCode, ZERO_SATS, hashType);\n\n // strict=true rejects high-S, as libsecp256k1's verify does\n // (`verify.rs:180-182`; secp256k1 crate `ecdsa/mod.rs:194`).\n return ecc.verify(sighash, compressedPubkey, signature, true);\n } catch {\n return false;\n }\n}\n"],"names":["BIP322_TAG","TAPTWEAK_TAG","X_ONLY_PUBKEY_SIZE","SCHNORR_SIG_SIZE","COMPRESSED_PUBKEY_SIZE","P2WPKH_ENCODED_SIG_MIN","P2WPKH_ENCODED_SIG_MAX","ZERO_SATS","BIP322_TX_VERSION","BIP322_TX_LOCKTIME","BIP322_INPUT_SEQUENCE","TO_SPEND_PREVOUT_TXID_BYTES","TO_SPEND_PREVOUT_INDEX","TO_SPEND_OUTPUT_INDEX","OP_0","OP_PUSHBYTES_32","OP_RETURN","taggedHash","tag","data","tagBytes","tagHash","sha256","preimage","tweakXOnlyKey","xOnly","tweak","tweaked","ecc","buildToSignTransaction","messageBytes","scriptPubKey","messageHash","toSpend","Transaction","scriptSig","Buffer","toSign","verifyBip322Simple","xOnlyPubkey","signature","hashType","p2tr","payments","sighash","tweakedXOnly","verifyBip322P2wpkhSimple","compressedPubkey","encodedSignature","bscript","p2wpkh","scriptCode"],"mappings":"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"}
@@ -0,0 +1,2 @@
1
+ "use strict";var Se=Object.defineProperty;var Re=(e,t,r)=>t in e?Se(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var C=(e,t,r)=>Re(e,typeof t!="symbol"?t+"":t,r);const he=require("./BTCVaultRegistry.abi-z7d_eP22.cjs"),p=require("./bitcoin-D-O2GjbC.cjs"),$=require("./signPsbtsWithFallback-DtwzL5AA.cjs"),Ae=require("viem"),k=require("./json-rpc-client-BiAmg_ho.cjs"),B=require("bitcoinjs-lib"),x=require("./verifyScriptPathSchnorrSignature-DaRqvEgW.cjs"),oe=require("./constants-BTZdyOuk.cjs"),_=require("./noPayout-4RZB2g1e.cjs"),I=require("./signing-BJ3X66b-.cjs"),ie=require("./onChainBtcPubkey-BbxRrbvg.cjs"),_e=require("./secp256k1-DDHQ1_za.cjs"),Ce=require("./tbv/core/wasm/index.cjs"),Be=/^0x[0-9a-fA-F]{64}$/,Ie=/^0x[0-9a-fA-F]{40}$/,$e=/^0x([0-9a-fA-F]{2})*$/;function O(e,t){if(e.length!==66)throw new Error(`${t} must be 32 bytes (66 hex chars with 0x prefix), got length ${e.length}`);if(!Be.test(e))throw new Error(`${t} must contain only hex characters after the 0x prefix`)}function Ve(e,t){if(!Ie.test(e))throw new Error(`${t} must be a 20-byte 0x-prefixed hex address (42 chars)`)}function Oe(e,t){if(!$e.test(e))throw new Error(`${t} must be a 0x-prefixed hex string with an even number of hex chars`)}function pe(e){Ve(e.btcVaultRegistryAddress,"btcVaultRegistryAddress"),O(e.vaultId,"vaultId");const t=p.ensureHexPrefix(e.secret);if(O(t,"secret"),e.hashlock!==void 0&&(O(e.hashlock,"hashlock"),!$.validateSecretAgainstHashlock(t,e.hashlock)))throw new Error("Invalid secret: SHA256(secret) does not match the provided hashlock");return t}async function Ne(e){const{btcVaultRegistryAddress:t,vaultId:r,hashlock:n,activationMetadata:s,writeContract:c,signal:i}=e;i==null||i.throwIfAborted();const a=pe({btcVaultRegistryAddress:t,vaultId:r,secret:e.secret,hashlock:n});return Oe(s,"activationMetadata"),c({address:t,abi:he.BTCVaultRegistryABI,functionName:"activateVaultWithSecret",args:[r,a,s]})}async function He(e){const{btcVaultRegistryAddress:t,vaultId:r,hashlock:n,writeContract:s,signal:c}=e;c==null||c.throwIfAborted();const i=pe({btcVaultRegistryAddress:t,vaultId:r,secret:e.secret,hashlock:n});return s({address:t,abi:he.BTCVaultRegistryABI,functionName:"activateVaultWithSecretAndRedeem",args:[r,i]})}const de=8,Ke=6e3,De=10*6e4,Fe=10;class W extends Error{constructor(t){super(t),this.name="PeginRegistrationMissingError"}}class Q extends Error{constructor(t){super(t),this.name="PeginRegistrationNotFinalError"}}function ge(e){return e instanceof W||e instanceof Error&&e.name==="PeginRegistrationMissingError"}function Me(e){return e instanceof Q||e instanceof Error&&e.name==="PeginRegistrationNotFinalError"}function se(e){const{currentBlock:t,createdAtBlock:r}=e,n=t-r+1n;return n<0n?0:Number(n)}async function Ue(e){const{vaultRegistryReader:t,getBlockNumber:r,vaultIds:n,required:s=de,pollIntervalMs:c=Ke,timeoutMs:i=De,signal:a,onProgress:o}=e;if(n.length===0)throw new Error("waitForPeginRegistrationDepth requires at least one vault ID");const u=Date.now();let h=!1,l=0,d;for(;;){if(a!=null&&a.aborted)throw new Error(`Aborted while waiting for peg-in registration depth (${n.length} vault(s))`);if(Date.now()-u>=i)throw new Q(`Peg-in registration did not reach ${s} Ethereum confirmations within ${i}ms. The registration transaction was submitted but is not yet final, so the Pre-PegIn Bitcoin transaction was never sent and no funds are at risk. Resume this deposit from the dashboard once the network settles.`+(d instanceof Error?` Last read error: ${d.message}`:""));try{const g=await r(),f=await Promise.all(n.map(P=>t.getVaultBasicInfo(P))),y=f.findIndex(P=>P.depositor===Ae.zeroAddress||P.createdAt===0n);if(y!==-1){if(l+=1,!h&&l>Fe)throw new W(`Vault ${n[y]} is still not visible on-chain after ${l} reads — the registration does not exist.`);console.warn(`Peg-in registration for vault ${n[y]} is not visible in chain state at block ${g} — a lagging RPC backend or an Ethereum reorg. Still polling.`),o==null||o({confirmations:0,required:s})}else{h=!0,l=0,d=void 0;let P=f[0],v=se({currentBlock:g,createdAtBlock:f[0].createdAt});for(const w of f.slice(1)){const E=se({currentBlock:g,createdAtBlock:w.createdAt});E<v&&(v=E,P=w)}if(o==null||o({confirmations:v,required:s}),v>=s)return{confirmations:v,basicInfo:P}}}catch(g){if(ge(g))throw g;console.warn(`Registration-depth read failed (retrying in ${c}ms): `+(g instanceof Error?g.message:String(g))),d=g}await new Promise((g,f)=>{const y=()=>{clearTimeout(P),f(new Error(`Aborted while waiting for peg-in registration depth (${n.length} vault(s))`))},P=setTimeout(()=>{a==null||a.removeEventListener("abort",y),g()},c);a==null||a.addEventListener("abort",y,{once:!0})})}}const Le=1;function Xe(e,t,r){const n=r.map(l=>p.stripHexPrefix(l).toLowerCase()),s=t.filter(l=>n.includes(l));if(s.length>0)throw new Error(`Cannot validate challenger set: vault keepers and universal challengers overlap (${s.join(", ")})`);const c=[...t,...n],i=e.map(l=>p.stripHexPrefix(l.challenger_pubkey).toLowerCase()),a=new Set(i);if(a.size!==i.length)throw new Error("Depositor graph contains duplicate challenger entries in challenger_presign_data");const o=new Set(c),u=c.filter(l=>!a.has(l)),h=i.filter(l=>!o.has(l));if(u.length>0||h.length>0)throw new Error("Depositor graph challenger set does not match expected (local ∪ universal)"+(u.length>0?` (missing: ${u.join(", ")})`:"")+(h.length>0?` (unexpected: ${h.join(", ")})`:""))}function qe(e,t){const r=e.ins[t];return p.uint8ArrayToHex(new Uint8Array(r.hash).slice().reverse())}function N(e,t,r,n,s){const c=e.ins[t];if(c.index!==0)throw new Error(`NoPayout (challenger ${s}) input ${t} expected to spend ${n} vout 0, got vout ${c.index}`);const i=r.getId(),a=qe(e,t);if(a!==i)throw new Error(`NoPayout (challenger ${s}) input ${t} does not reference ${n} (expected txid ${i}, got ${a})`)}async function ze(e,t,r){const n=[],s=[],c=[],i=x.deriveLocalChallengers({claimerBtcPubkey:r.depositorBtcPubkey,depositorBtcPubkey:r.depositorBtcPubkey,vaultProviderBtcPubkey:r.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:r.vaultKeeperBtcPubkeys});Xe(e.challenger_presign_data,i,r.universalChallengerBtcPubkeys);const a=await x.buildPayoutPsbt({vaultCoreVersion:r.vaultCoreVersion,vkClaimerPayoutScriptPubKeys:r.vkClaimerPayoutScriptPubKeys,vpCommissionScriptPubKey:r.vpCommissionScriptPubKey,payoutTxHex:e.payout_tx.tx_hex,peginTxHex:r.peginTxHex,assertTxHex:e.assert_tx.tx_hex,timelockAssert:r.timelockAssert,depositorBtcPubkey:r.depositorBtcPubkey,vaultProviderBtcPubkey:r.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:r.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:r.universalChallengerBtcPubkeys,timelockPegin:r.timelockPegin,network:r.network,claimerBtcPubkey:r.depositorBtcPubkey,registeredPayoutScriptPubKey:r.registeredPayoutScriptPubKey,commissionBps:Le,protocolFeeRate:r.protocolFeeRate,councilMembers:r.councilMembers,councilQuorum:r.councilQuorum});n.push(a.psbtHex),s.push(I.createTaprootScriptPathSignOptions(t,oe.DEPOSITOR_SIGNED_INPUT_COUNT));const o=p.stripHexPrefix(r.depositorBtcPubkey),u=B.Transaction.fromHex(p.stripHexPrefix(e.assert_tx.tx_hex));for(const h of e.challenger_presign_data){const l=p.stripHexPrefix(h.challenger_pubkey),d=n.length,g=await Ge({challenger:h,challengerPubkey:l,claimerPubkey:o,localChallengers:i,assertTxParsed:u,ctx:r});n.push(g),s.push(I.createTaprootScriptPathSignOptions(t,oe.DEPOSITOR_SIGNED_INPUT_COUNT)),c.push({challengerPubkey:l,noPayoutIdx:d})}return{psbtHexes:n,signOptions:s,challengerEntries:c}}async function Ge(e){const{challenger:t,challengerPubkey:r,claimerPubkey:n,localChallengers:s,assertTxParsed:c,ctx:i}=e;_.assertNoPayoutOutputMatchesChallenger(t.nopayout_tx.tx_hex,r,i.network);const a=B.Transaction.fromHex(p.stripHexPrefix(t.nopayout_tx.tx_hex)),o=B.Transaction.fromHex(p.stripHexPrefix(t.challenge_assert_x_tx.tx_hex)),u=B.Transaction.fromHex(p.stripHexPrefix(t.challenge_assert_y_tx.tx_hex));if(a.ins.length!==3)throw new Error(`NoPayout (challenger ${r}) must have exactly 3 inputs, got ${a.ins.length}`);N(a,0,c,"Assert",r),N(a,1,o,"ChallengeAssertX",r),N(a,2,u,"ChallengeAssertY",r);const h=[c.outs[0],o.outs[0],u.outs[0]].map(l=>({script_pubkey:p.uint8ArrayToHex(new Uint8Array(l.script)),value:l.value}));return _.buildNoPayoutPsbt({noPayoutTxHex:t.nopayout_tx.tx_hex,challengerPubkey:r,prevouts:h,connectorParams:{txGraphVersion:i.vaultCoreVersion,claimer:n,localChallengers:s,universalChallengers:i.universalChallengerBtcPubkeys,timelockAssert:i.timelockAssert,councilMembers:i.councilMembers,councilQuorum:i.councilQuorum}})}function je(e,t,r){x.assertPsbtUnsignedTxMatches(e[0]);const s=x.extractPayoutSignature(e[0].returnedPsbtHex,r);x.assertScriptPathSchnorrSignature({requestedPsbtHex:e[0].requestedPsbtHex,signatureHex:s,signerXOnlyPubkeyHex:r,inputIndex:0});const c={};for(const i of t){x.assertPsbtUnsignedTxMatches(e[i.noPayoutIdx]);const a=x.extractPayoutSignature(e[i.noPayoutIdx].returnedPsbtHex,r);x.assertScriptPathSchnorrSignature({requestedPsbtHex:e[i.noPayoutIdx].requestedPsbtHex,signatureHex:a,signerXOnlyPubkeyHex:r,inputIndex:0}),c[i.challengerPubkey]={nopayout_signature:a}}return{payout_signatures:{payout_signature:s},per_challenger:c}}async function fe(e){const{depositorGraph:t,btcWallet:r,signingContext:n}=e,s=await r.getPublicKeyHex(),{depositorPubkey:c}=p.validateWalletPubkey(s,p.stripHexPrefix(n.depositorBtcPubkey)),{psbtHexes:i,signOptions:a,challengerEntries:o}=await ze(t,s,n),u=await $.signPsbtsWithFallback(r,i,a),h=i.map((l,d)=>({requestedPsbtHex:l,returnedPsbtHex:u[d]}));return je(h,o,c)}const We=1e4;async function Y(e){const{statusReader:t,peginTxid:r,targetStatuses:n,timeoutMs:s,pollIntervalMs:c=We,signal:i}=e,a=Date.now();for(;;){if(i!=null&&i.aborted)throw new Error(`Polling aborted for pegin ${r.slice(0,8)}… (target: ${[...n].join(", ")})`);if(Date.now()-a>=s)throw new Error(`Polling timeout after ${s}ms for pegin ${r.slice(0,8)}… (target: ${[...n].join(", ")})`);try{const o=await t.getPeginStatus({pegin_txid:r},i);if(o.pegin_txid.toLowerCase()!==r.toLowerCase())throw new Error(`getPeginStatus returned status for pegin ${o.pegin_txid.slice(0,8)}…, requested ${r.slice(0,8)}…`);const u=o.status;if(n.has(u)||u===k.DaemonStatus.ACTIVATED)return u;if(u===k.DaemonStatus.EXPIRED||k.VP_TERMINAL_FAILURE_STATUSES.has(u))throw new Error(`Pegin ${r.slice(0,8)}… reached terminal status "${u}" while waiting for ${[...n].join(", ")}`)}catch(o){if(!(o instanceof k.JsonRpcError&&o.code===k.RpcErrorCode.PEGIN_NOT_FOUND))throw o}await new Promise((o,u)=>{const h=()=>{clearTimeout(l),u(new Error(`Polling aborted for pegin ${r.slice(0,8)}… (target: ${[...n].join(", ")})`))},l=setTimeout(()=>{i==null||i.removeEventListener("abort",h),o()},c);i==null||i.addEventListener("abort",h,{once:!0})})}}const Qe=1200*1e3,Pe=new Set([k.DaemonStatus.PENDING_ACKS,k.DaemonStatus.PENDING_ACTIVATION,k.DaemonStatus.ACTIVATED_PENDING_BROADCAST,k.DaemonStatus.ACTIVATED]),Ye=new Set([k.DaemonStatus.PENDING_DEPOSITOR_SIGNATURES,...Pe]);function Ze(e){return e.map(t=>({claimerPubkeyXOnly:p.processPublicKeyToXOnly(t.claimer_pubkey),payoutTxHex:t.payout_tx.tx_hex,assertTxHex:t.assert_tx.tx_hex}))}function R(e){return p.processPublicKeyToXOnly(e).toLowerCase()}function Je(e,t){const r=(o,u,h)=>{throw new Error(`Deposit terms ${o} (${String(u)}) does not match the vault's version-locked signing context (${String(h)}); refusing to sign payouts against terms that describe a different graph.`)},n=[["protocolFeeRate",e.protocolFeeRate,t.protocolFeeRate],["vaultCoreVersion",e.vaultCoreVersion,t.vaultCoreVersion],["timelockPegin",e.timelockPegin,t.timelockPegin],["timelockAssert",e.timelockAssert,t.timelockAssert]];for(const[o,u,h]of n)u!==h&&r(o,u,h);const s=o=>o.map(R).sort(),c=(o,u)=>{const h=s(o),l=s(u);return h.length===l.length&&h.every((d,g)=>d===l[g])};c(e.vaultKeeperBtcPubkeys,t.vaultKeeperBtcPubkeys)||r("vaultKeeperBtcPubkeys",e.vaultKeeperBtcPubkeys.join(","),t.vaultKeeperBtcPubkeys.join(",")),c(e.universalChallengerBtcPubkeys,t.universalChallengerBtcPubkeys)||r("universalChallengerBtcPubkeys",e.universalChallengerBtcPubkeys.join(","),t.universalChallengerBtcPubkeys.join(","));const i=R(t.vaultProviderBtcPubkey),a=e.vaults.map(o=>R(o.vaultProviderBtcPubkey));a.includes(i)||r("vaults[].vaultProviderBtcPubkey",a.join(",")||"<no vaults>",t.vaultProviderBtcPubkey)}function et(e,t,r,n){const s=R(n),c=[R(t),...r.map(R)],i=new Set(c);if(i.size!==c.length)throw new Error("Cannot validate claimer set: signing context contains duplicate vault provider or vault keeper key");if(i.has(s))throw new Error("Cannot validate claimer set: depositor key overlaps with vault provider or vault keeper set");const a=e.map(d=>R(d.claimer_pubkey));if(new Set(a).size!==a.length)throw new Error("Presign response contains duplicate claimer entries");const o=a.filter(d=>d!==s),u=new Set(o),h=c.filter(d=>!u.has(d)),l=o.filter(d=>!i.has(d));if(h.length>0||l.length>0)throw new Error("Presign response claimer set does not match expected (vault provider ∪ vault keepers)"+(h.length>0?` (missing: ${h.join(", ")})`:"")+(l.length>0?` (unexpected: ${l.join(", ")})`:""))}function ae(e,t){return{vaultCoreVersion:t.vaultCoreVersion,payoutTxHex:e.payoutTxHex,peginTxHex:t.peginTxHex,assertTxHex:e.assertTxHex,vaultProviderBtcPubkey:t.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:t.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:t.universalChallengerBtcPubkeys,depositorBtcPubkey:t.depositorBtcPubkey,timelockPegin:t.timelockPegin,timelockAssert:t.timelockAssert,registeredPayoutScriptPubKey:t.registeredPayoutScriptPubKey,claimerBtcPubkey:e.claimerPubkeyXOnly,commissionBps:t.commissionBps,protocolFeeRate:t.protocolFeeRate,councilMembers:t.councilMembers,councilQuorum:t.councilQuorum,vkClaimerPayoutScriptPubKeys:t.vkClaimerPayoutScriptPubKeys,vpCommissionScriptPubKey:t.vpCommissionScriptPubKey}}async function tt(e,t,r,n){const s=new $.PayoutManager({network:t.network,btcWallet:e}),c=r.length;n==null||n(0,c);let i;if(s.supportsBatchSigning())i=(await s.signPayoutTransactionsBatch(r.map(u=>ae(u,t)))).map(u=>u.payoutSignature);else{i=[];for(let o=0;o<r.length;o++){n==null||n(o,c);const u=await s.signPayoutTransaction(ae(r[o],t));i.push(u.signature)}}const a={};for(let o=0;o<r.length;o++)a[r[o].claimerPubkeyXOnly]={payout_signature:i[o]};return n==null||n(c,c),a}async function rt(e){const{statusReader:t,presignClient:r,btcWallet:n,peginTxid:s,depositorPk:c,signingContext:i,depositTerms:a,timeoutMs:o=Qe,signal:u,onProgress:h}=e,l=await Y({statusReader:t,peginTxid:s,targetStatuses:Ye,timeoutMs:o,signal:u});if(Pe.has(l))return;if(u==null||u.throwIfAborted(),a!==void 0&&Je(a,i),$.supportsDepositApproval(n)){if(!a)throw new Error("runDepositorPresignFlow: this wallet requires approved deposit terms but none were provided. Fresh deposits must pass PreparePeginResult.depositTerms; resume flows must rebuild them from on-chain state (the vault app's rebuildDepositTerms).");typeof n.validateDepositTerms=="function"&&await n.validateDepositTerms(a),await n.approveDepositTerms(a)}const d=await r.requestDepositorPresignTransactions({pegin_txid:s,depositor_pk:c},u);u==null||u.throwIfAborted();const g=R(c);et(d.txs,i.vaultProviderBtcPubkey,i.vaultKeeperBtcPubkeys,c);const f=d.txs.filter(E=>R(E.claimer_pubkey)!==g),y=Ze(f),P=await tt(n,i,y,h);u==null||u.throwIfAborted();const v=await fe({depositorGraph:d.depositor_graph,btcWallet:n,signingContext:{vaultCoreVersion:i.vaultCoreVersion,peginTxHex:i.peginTxHex,depositorBtcPubkey:c,vaultProviderBtcPubkey:i.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:i.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:i.universalChallengerBtcPubkeys,timelockPegin:i.timelockPegin,timelockAssert:i.timelockAssert,councilMembers:i.councilMembers,councilQuorum:i.councilQuorum,network:i.network,registeredPayoutScriptPubKey:i.registeredPayoutScriptPubKey,protocolFeeRate:i.protocolFeeRate,vkClaimerPayoutScriptPubKeys:i.vkClaimerPayoutScriptPubKeys,vpCommissionScriptPubKey:i.vpCommissionScriptPubKey}});u==null||u.throwIfAborted();const w={...P};w[p.stripHexPrefix(c)]=v.payout_signatures,await r.submitDepositorPresignatures({pegin_txid:s,depositor_pk:c,signatures:w,depositor_claimer_presignatures:v},u)}const nt=300*1e3,ot=new Set([k.DaemonStatus.PENDING_DEPOSITOR_WOTS_PK,...k.POST_WOTS_STATUSES]);async function it(e){const{statusReader:t,wotsSubmitter:r,peginTxid:n,depositorPk:s,wotsPublicKeys:c,timeoutMs:i=nt,signal:a}=e;a==null||a.throwIfAborted();const o=await Y({statusReader:t,peginTxid:n,targetStatuses:ot,timeoutMs:i,signal:a});k.POST_WOTS_STATUSES.has(o)||(a==null||a.throwIfAborted(),await r.submitDepositorWotsKey({pegin_txid:n,depositor_pk:s,wots_public_keys:c},a))}function V(e){return e.registration||e.operation}function ye(e,t,r){const n=p.canonicalizeBtcPubkey(e);return{registration:n===p.canonicalizeBtcPubkey(t),operation:n===p.canonicalizeBtcPubkey(r)}}function F(e,t,r){const n=H(e);return{registration:ue(n,H(t)),operation:ue(n,H(r))}}function H(e){return e.map(p.canonicalizeBtcPubkey).sort()}function ue(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}async function st(e){const{vaultProviderEthAddress:t,hintBtcPubkey:r,registrationBtcPubkey:n,readCurrentOperationBtcPubkey:s,context:c}=e;if(!r)return;const i=p.canonicalizeBtcPubkey(r);if(i===p.canonicalizeBtcPubkey(n))return;const a=p.canonicalizeBtcPubkey(await s());if(i!==a)throw new Error(`Vault provider BTC pubkey mismatch for ${t}: indexer hint matches neither the registration key nor the current operation key on-chain.${c?` ${c}`:""}`)}function K(e,t,r){const n=`${e} operation key (admin=${t.ethAddress})`,s=ie.assertOnChainBtcPubkey(t.btcPubKey,`${e} roster key (admin=${t.ethAddress})`),c=ie.assertOnChainBtcPubkey(r,n);return{adminAddress:t.ethAddress,genesisBtcPubkey:s,operationBtcPubkey:c,rotated:c!==s}}function at(e){const t=new Map;for(const r of e){const n=t.get(r.operationBtcPubkey);if(n)throw new Error(`Participant operation key collision: ${n} and ${r.adminAddress} both resolve to operation key ${r.operationBtcPubkey}`);t.set(r.operationBtcPubkey,r.adminAddress)}}function ve(e,t,r){if(t.vaultKeepers.length!==e.vaultKeepers.length||t.universalChallengers.length!==e.universalChallengers.length)throw new Error(`Operation-key resolution returned ${t.vaultKeepers.length} keeper and ${t.universalChallengers.length} challenger keys for a roster of ${e.vaultKeepers.length} keepers and ${e.universalChallengers.length} challengers`);const n=K("vault provider",{ethAddress:e.vaultProviderEthAddress,btcPubKey:e.vaultProviderGenesisBtcPubkey},t.vaultProvider),s=e.vaultKeepers.map((i,a)=>K("vault keeper",i,t.vaultKeepers[a])),c=e.universalChallengers.map((i,a)=>K("universal challenger",i,t.universalChallengers[a]));return at([n,...s,...c]),{vaultProvider:n,vaultKeepers:s,universalChallengers:c,vaultKeeperOperationKeysSorted:s.map(i=>i.operationBtcPubkey).sort(),universalChallengerOperationKeysSorted:c.map(i=>i.operationBtcPubkey).sort(),resolvedAt:r,query:e}}async function me(e){const t=await e.operationKeyReader.getCurrentOperationKeys(e.query,e.blockNumber);return ve(e.query,t,{mode:"current"})}async function be(e){const t=await e.operationKeyReader.getOperationKeysAtEpochs(e.query,e.epochs);return ve(e.query,t,{mode:"epochs",epochs:e.epochs})}const ce=e=>e.map(p.canonicalizeBtcPubkey).sort();async function ut(e){const{vaultRegistryReader:t,vaultKeeperReader:r,universalChallengerReader:n,vaultProviderEthAddress:s,applicationEntryPoint:c,expectedVaultProviderBtcPubkey:i,expectedVaultKeeperBtcPubkeys:a,expectedUniversalChallengerBtcPubkeys:o,operationKeyReader:u,onIndexerServingOperationKeys:h,onIndexerHintsInconsistent:l,blockNumber:d}=e,[g,f,y]=await Promise.all([t.getVaultProviderGenesisBtcPubKey(s,d),r.getCurrentVaultKeepersVersion(c,d),n.getLatestUniversalChallengersVersion(d)]),[P,v]=await Promise.all([r.getVaultKeepersByVersion(c,f,d),n.getUniversalChallengersByVersion(y,d)]),w={vaultProvider:p.canonicalizeBtcPubkey(g),vaultKeepers:ce(P.map(T=>T.btcPubKey)),universalChallengers:ce(v.map(T=>T.btcPubKey))},E=await me({operationKeyReader:u,query:{vaultProviderEthAddress:s,vaultProviderGenesisBtcPubkey:`0x${g}`,applicationEntryPoint:c,vaultKeepers:P,universalChallengers:v},blockNumber:d}),m={vaultProvider:E.vaultProvider.operationBtcPubkey,vaultKeepers:[...E.vaultKeeperOperationKeysSorted],universalChallengers:[...E.universalChallengerOperationKeysSorted]},S=ye(i,w.vaultProvider,m.vaultProvider),A=F(a,w.vaultKeepers,m.vaultKeepers),b=F(o,w.universalChallengers,m.universalChallengers);if(!V(S))throw new Error(`Vault provider BTC pubkey indexer hint does not match BTCVaultRegistry for ${s}. Refresh and try again.`);if(!V(A))throw new Error(`Vault keeper BTC pubkeys (v${f}) indexer set does not match ApplicationRegistry on-chain set. Refresh and try again.`);if(!V(b))throw new Error(`Universal challenger BTC pubkeys (v${y}) indexer set does not match ProtocolParams on-chain set. Refresh and try again.`);const re=[S,A,b],Te=re.some(T=>T.registration&&!T.operation),ne=re.some(T=>T.operation&&!T.registration);if(Te&&ne){const T=`Indexer participant hints are internally inconsistent for vault provider ${s}: some roles match the registration keys while others match the rotated operation keys.`;throw l==null||l(T),new Error(`${T} Refresh and try again.`)}return ne&&(h==null||h(`Indexer is serving rotated operation keys for vault provider ${s}`)),{vaultProviderBtcPubkeyXOnly:m.vaultProvider,vaultKeeperBtcPubkeysSorted:m.vaultKeepers,universalChallengerBtcPubkeysSorted:m.universalChallengers,expectedAppVaultKeepersVersion:f,expectedUniversalChallengersVersion:y,registrationKeys:w,participantKeys:E}}function ct(e){return/^[0-9a-fA-F]{64}$/.test(e)}function lt(e){const{amountSats:t,minDeposit:r,maxDeposit:n,btcBalance:s,estimatedFeeSats:c,depositorClaimValue:i}=e;return!(t<=0n||t<r||n&&n>0n&&t>n||c==null||i==null||t+c+i>s)}function ht(e,t,r){return e<=0n?{valid:!1,error:"Deposit amount must be greater than zero"}:e<t?{valid:!1,error:`Minimum deposit is ${p.formatSatoshisToBtc(t)} BTC`}:r&&r>0n&&e>r?{valid:!1,error:`Maximum deposit is ${p.formatSatoshisToBtc(r)} BTC`}:{valid:!0}}function pt(e){const{amount:t,effectiveRemaining:r}=e;return r===null?{valid:!0}:r===0n?{valid:!1,error:"Supply cap reached — deposits temporarily paused"}:t>r?{valid:!1,error:`Vault size exceeds remaining capacity (${p.formatSatoshisToBtc(r)} BTC)`}:{valid:!0}}function dt(e,t){if(!e||e.length===0)return{valid:!1,error:"At least one vault provider must be selected"};const r=t.map(s=>s.toLowerCase());return e.filter(s=>!r.includes(s.toLowerCase())).length>0?{valid:!1,error:"Invalid vault provider selected"}:{valid:!0}}function we(e,t,r){if(!e||e.length===0)return{valid:!1,error:"At least one vault amount required"};for(let n=0;n<e.length;n++){const s=e[n];if(s<=0n)return{valid:!1,error:`Vault ${n+1} amount must be positive`};if(t&&s<t)return{valid:!1,error:`Vault ${n+1} amount ${p.formatSatoshisToBtc(s)} BTC is below minimum deposit ${p.formatSatoshisToBtc(t)} BTC`};if(r&&s>r)return{valid:!1,error:`Vault ${n+1} amount ${p.formatSatoshisToBtc(s)} BTC exceeds maximum deposit ${p.formatSatoshisToBtc(r)} BTC`}}return{valid:!0}}function Ee(e){const t=p.stripHexPrefix(e);return ct(t)?{valid:!0}:{valid:!1,error:"Invalid pubkey format: must be 64 hex characters (32-byte x-only public key, no 0x prefix)"}}function gt(e){if(!e||e.length===0)throw new Error("No vault keepers available. The system requires at least one vault keeper to create a deposit.")}function ft(e){if(!e||e.length===0)throw new Error("No universal challengers available. The system requires at least one universal challenger to create a deposit.")}function Pt(e){if(e.length===0)throw new Error("No spendable UTXOs available")}function yt(e){const{vaultAmounts:t,confirmedUTXOs:r,vaultProviderBtcPubkey:n,vaultKeeperBtcPubkeys:s,universalChallengerBtcPubkeys:c,minDeposit:i,maxDeposit:a}=e,o=we(t,i,a);if(!o.valid)throw new Error(o.error);const u=Ee(n);if(!u.valid)throw new Error(u.error);gt(s),ft(c),Pt(r)}class Z extends Error{constructor(t){super(t),this.name="ParticipantKeyDriftError"}}function vt(e){return e instanceof Z||e instanceof Error&&e.name==="ParticipantKeyDriftError"}function le(e,t,r){return t.length===r.length&&t.every((n,s)=>n===r[s])?null:`${e} expected [${t.join(", ")}], got [${r.join(", ")}]`}async function mt(e){const{vaultRegistryReader:t,operationKeyReader:r,vaultIds:n,expected:s}=e,c=s.query;if(n.length===0)return;const i=await t.getVaultKeyEpochsBatch(n),a=[];for(const[o,u]of i.entries()){const h=n[o];let l;try{l=await be({operationKeyReader:r,query:c,epochs:u})}catch(f){a.push(`vault ${h}: could not resolve participants at frozen epochs (vp=${u.vpKeyEpoch}, keeper=${u.appKeeperKeyEpoch}, uc=${u.ucKeyEpoch}): ${f.message}`);continue}l.vaultProvider.operationBtcPubkey!==s.vaultProvider.operationBtcPubkey&&a.push(`vault ${h}: vault provider key expected ${s.vaultProvider.operationBtcPubkey}, got ${l.vaultProvider.operationBtcPubkey}`);const d=le(`vault ${h}: vault keeper keys`,s.vaultKeeperOperationKeysSorted,l.vaultKeeperOperationKeysSorted);d&&a.push(d);const g=le(`vault ${h}: universal challenger keys`,s.universalChallengerOperationKeysSorted,l.universalChallengerOperationKeysSorted);g&&a.push(g)}if(a.length>0)throw new Z(`Aborting BTC broadcast: participant operation keys changed during registration (${a.join("; ")}). The Pre-PegIn was not broadcast; the registered ETH vault will time out per protocol rules.`)}class J extends Error{constructor(t){super(t),this.name="RegisteredVaultVersionMismatchError"}}function bt(e){return e instanceof J||e instanceof Error&&e.name==="RegisteredVaultVersionMismatchError"}async function wt(e){const{vaultRegistryReader:t,vaultIds:r,expectedOffchainParamsVersion:n,expectedAppVaultKeepersVersion:s,expectedUniversalChallengersVersion:c,expectedVaultCoreVersion:i}=e,a=await t.getProtocolInfoBatch(r),o=[];if(a.forEach((u,h)=>{const l=r[h];u.offchainParamsVersion!==n&&o.push(`vault ${l}: offchainParams expected v${n}, got v${u.offchainParamsVersion}`),u.appVaultKeepersVersion!==s&&o.push(`vault ${l}: appVaultKeepers expected v${s}, got v${u.appVaultKeepersVersion}`),u.universalChallengersVersion!==c&&o.push(`vault ${l}: universalChallengers expected v${c}, got v${u.universalChallengersVersion}`),u.vaultCoreVersion!==i&&o.push(`vault ${l}: vaultCoreVersion expected v${i} (build-time active), got v${u.vaultCoreVersion}`)}),o.length>0)throw new J(`Aborting BTC broadcast: signer-set or offchain-params versions changed during registration (${o.join("; ")}). The Pre-PegIn was not broadcast; the registered ETH vault will time out per protocol rules.`)}var ee=(e=>(e.CLAIM_EVENT_RECEIVED="ClaimEventReceived",e.CLAIM_BROADCAST="ClaimBroadcast",e.ASSERT_BROADCAST="AssertBroadcast",e.PAYOUT_BROADCAST="PayoutBroadcast",e.PAYOUT_BLOCKED="PayoutBlocked",e))(ee||{});const Et=new Set(["PayoutBroadcast","PayoutBlocked"]);function xt(e){return Object.values(ee).includes(e)}function kt(e){return!!e&&Et.has(e)}class xe extends Error{constructor(r,n){super(`Refund not yet mature (BIP68 not final): ${n.message}`);C(this,"vaultId");C(this,"cause");this.name="BIP68NotMatureError",this.vaultId=r,this.cause=n}}const Tt=/^0x[0-9a-fA-F]{64}$/,St=/^(?:0x)?(?:[0-9a-fA-F]{2})+$/,ke=/^(?:0x)?(?:[0-9a-fA-F]{64}|[0-9a-fA-F]{66})$/,te=160,M=2e3,U=10n,L=100n;function Rt(e){if(!Number.isFinite(e)||e<=0)throw new Error(`feeRateSatsVb must be a positive finite number, got ${e}`);return BigInt(Math.ceil(e*te))}const At=1,_t=/non-BIP68-final/i;function X(e,t){if(e.length!==66)throw new Error(`${t} must be 32 bytes (66 hex chars with 0x prefix), got length ${e.length}`);if(!Tt.test(e))throw new Error(`${t} must contain only hex characters after the 0x prefix`)}function D(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer, got ${e}`)}function Ct(e){if(X(e.hashlock,"hashlock"),!Number.isInteger(e.htlcVout)||e.htlcVout<0)throw new Error(`htlcVout must be a non-negative integer, got ${e.htlcVout}`);if(!Array.isArray(e.batch)||e.batch.length===0)throw new Error("batch must be a non-empty array of HTLC entries");if(e.htlcVout>=e.batch.length)throw new Error(`htlcVout ${e.htlcVout} is out of range for batch of size ${e.batch.length}`);for(let r=0;r<e.batch.length;r++){const n=e.batch[r];if(X(n.hashlock,`batch[${r}].hashlock`),!Number.isInteger(n.htlcVout)||n.htlcVout!==r)throw new Error(`batch[${r}].htlcVout must equal ${r} (contiguous vout-ordered vector), got ${n.htlcVout}`);if(typeof n.amount!="bigint"||n.amount<=0n)throw new Error(`batch[${r}].amount must be a positive bigint, got ${n.amount}`)}const t=e.batch[e.htlcVout];if(t.hashlock.toLowerCase()!==e.hashlock.toLowerCase())throw new Error(`batch[${e.htlcVout}].hashlock (${t.hashlock}) does not match target hashlock (${e.hashlock})`);if(t.amount!==e.amount)throw new Error(`batch[${e.htlcVout}].amount (${t.amount}) does not match target amount (${e.amount})`);if(D(e.offchainParamsVersion,"offchainParamsVersion"),D(e.appVaultKeepersVersion,"appVaultKeepersVersion"),D(e.universalChallengersVersion,"universalChallengersVersion"),_e.assertValidVaultCoreVersion(e.vaultCoreVersion,"VaultRefundData.vaultCoreVersion"),typeof e.unsignedPrePeginTxHex!="string"||e.unsignedPrePeginTxHex.length===0)throw new Error("unsignedPrePeginTxHex must be a non-empty hex string");if(!St.test(e.unsignedPrePeginTxHex))throw new Error("unsignedPrePeginTxHex must be a hex byte string (optional 0x prefix, even length)");if(!e.depositorBtcPubkey||!ke.test(e.depositorBtcPubkey))throw new Error("depositorBtcPubkey must be 32 or 33 bytes of hex (optional 0x prefix)");if(typeof e.amount!="bigint"||e.amount<=0n)throw new Error(`amount must be a positive bigint, got ${e.amount}`)}function Bt(e){if(!e.vaultProviderPubkey||!ke.test(e.vaultProviderPubkey))throw new Error("vaultProviderPubkey must be 32 or 33 bytes of hex");if(e.vaultKeeperPubkeys.length===0)throw new Error("vaultKeeperPubkeys must be non-empty");if(e.universalChallengerPubkeys.length===0)throw new Error("universalChallengerPubkeys must be non-empty");if(!Number.isInteger(e.timelockRefund)||e.timelockRefund<=0)throw new Error(`timelockRefund must be a positive integer, got ${e.timelockRefund}`);if(typeof e.feeRate!="bigint"||e.feeRate<=0n)throw new Error(`protocol feeRate must be a positive bigint, got ${e.feeRate}`);if(typeof e.minPeginFeeRate!="bigint"||e.minPeginFeeRate<=0n)throw new Error(`minPeginFeeRate must be a positive bigint, got ${e.minPeginFeeRate}`);if(!Number.isInteger(e.numLocalChallengers)||e.numLocalChallengers<0)throw new Error("numLocalChallengers must be a non-negative integer");if(!Number.isInteger(e.councilQuorum)||!Number.isInteger(e.councilSize)||e.councilQuorum<=0||e.councilSize<=0||e.councilQuorum>e.councilSize)throw new Error(`councilQuorum (${e.councilQuorum}) must be in [1, councilSize=${e.councilSize}]`)}async function It(e){const{vaultId:t,readVault:r,readPrePeginContext:n,feeRate:s,signPsbt:c,broadcastTx:i,signal:a}=e;a==null||a.throwIfAborted(),X(t,"vaultId");const o=await r();Ct(o),a==null||a.throwIfAborted();const u=await n(o);if(Bt(u),a==null||a.throwIfAborted(),!Number.isFinite(s)||s<=0)throw new Error(`feeRate must be a positive number, got ${s}`);if(s>M)throw new Error(`feeRate ${s} sat/vB exceeds refund safety cap ${M} sat/vB; refusing to sign refund.`);const h=BigInt(Math.ceil(s*te)),l=o.amount*U/L;if(h>l)throw new Error(`Refund fee ${h} sats exceeds the per-vault safety cap of ${l} sats (${U}/${L} of vault.amount=${o.amount}); refusing to sign refund.`);a==null||a.throwIfAborted();const d=p.processPublicKeyToXOnly(o.depositorBtcPubkey),g=p.stripHexPrefix(o.unsignedPrePeginTxHex),f=$.findAuthAnchorOpReturn(g);if(f!==void 0&&f.vout!==o.batch.length)throw new Error(`Auth-anchor OP_RETURN at vout ${f.vout} does not match batch size (${o.batch.length} HTLC outputs expect the anchor at vout ${o.batch.length}). Refund refused — sibling HTLC vector is incomplete.`);const y=f==null?void 0:f.hash;let P;try{P=B.Transaction.fromHex(g)}catch(b){throw new Error(`Failed to parse funded Pre-PegIn transaction hex: ${b instanceof Error?b.message:String(b)}`)}if(P.outs.length<o.batch.length)throw new Error(`Funded Pre-PegIn tx has ${P.outs.length} outputs but batch requires at least ${o.batch.length} HTLC outputs. Refund refused — funded tx shape disagrees with sibling vector.`);const{psbtHex:v}=await _.buildRefundPsbt({prePeginParams:{vaultCoreVersion:o.vaultCoreVersion,depositorPubkey:d,vaultProviderPubkey:p.stripHexPrefix(u.vaultProviderPubkey),vaultKeeperPubkeys:u.vaultKeeperPubkeys.map(p.stripHexPrefix),universalChallengerPubkeys:u.universalChallengerPubkeys.map(p.stripHexPrefix),hashlocks:o.batch.map(b=>p.stripHexPrefix(b.hashlock)),timelockRefund:u.timelockRefund,pegInAmounts:o.batch.map(b=>b.amount),feeRate:u.feeRate,minPeginFeeRate:u.minPeginFeeRate,numLocalChallengers:u.numLocalChallengers,councilQuorum:u.councilQuorum,councilSize:u.councilSize,network:u.network,authAnchorHash:y},fundedPrePeginTxHex:g,htlcVout:o.htlcVout,refundFee:h,hashlock:p.stripHexPrefix(o.hashlock)});a==null||a.throwIfAborted();const w=I.createTaprootScriptPathSignOptions(o.depositorBtcPubkey,At),E=await c(v,w);x.assertPsbtUnsignedTxMatches({requestedPsbtHex:v,returnedPsbtHex:E});const m=0,S=x.extractPayoutSignature(E,d,m);x.assertScriptPathSchnorrSignature({requestedPsbtHex:v,signatureHex:S,signerXOnlyPubkeyHex:d,inputIndex:m});const A=_.finalizeScriptPathWithSignatures({requestedPsbtHex:v,signaturesHex:[S],signerXOnlyPubkeyHex:d});a==null||a.throwIfAborted();try{return await i(A)}catch(b){throw b instanceof Error&&_t.test(b.message)?new xe(t,b):b}}class q extends Error{constructor(r,n,s){super(r);C(this,"feeSats");C(this,"sweptTotalSats");this.name="ReclaimUneconomicalError",this.feeSats=n,this.sweptTotalSats=s}}const z=2e3,G=25n,j=100n,$t=10n;async function Vt(e,t,r){for(let n=0;n<e.length;n++){const s=I.calculateBtcTxHash(e[n].depositorSignedPeginTxHex),c=p.ensureHexPrefix(await Ce.deriveVaultId(p.stripHexPrefix(s),p.stripHexPrefix(r))).toLowerCase();if(c!==t[n].toLowerCase())throw new Error(`Reserve ${n} belongs to vault ${c}, not the requested ${t[n].toLowerCase()}. Refusing to sweep a reserve whose vault is not the one the caller asked for — the reserve funds that vault's claim transaction and cannot be replaced.`)}}async function Ot(e){const{vaultIds:t,depositorEthAddress:r,depositorBtcPubkey:n,readVaults:s,feeRate:c,signPsbt:i,broadcastTx:a,signal:o}=e;if(o==null||o.throwIfAborted(),t.length===0)throw new Error("Reclaim requires at least one vault id; got none.");if(!Number.isFinite(c)||c<=0)throw new Error(`feeRate must be a positive number, got ${c}`);if(c>z)throw new q(`Fee rate ${c} sat/vB exceeds the reclaim safety cap of ${z} sat/vB; refusing to sign.`,0n,0n);const u=await s();if(o==null||o.throwIfAborted(),u.length!==t.length)throw new Error(`readVaults returned ${u.length} reserves for ${t.length} vault id(s); refusing to sweep a set that does not match the request.`);await Vt(u,t,r),o==null||o.throwIfAborted();const h=p.processPublicKeyToXOnly(n),l=u.map(m=>({depositorSignedPeginTxHex:m.depositorSignedPeginTxHex,observed:m.observed,expectedValue:m.expectedClaimValue})),d=_.estimateReclaimFeeSats(c,l.length),g=l.reduce((m,S)=>m+S.expectedValue,0n),f=g*G/j;if(d>f)throw new q(`Reclaim fee ${d} sats exceeds ${G}/${j} of the swept total (${g} sats, cap ${f} sats). The reserve is not at risk — it stays where it is until fee rates fall.`,d,g);o==null||o.throwIfAborted();const{psbtHex:y}=_.buildReclaimPsbt({depositorPubkey:h,inputs:l,feeSats:d});o==null||o.throwIfAborted();const P=I.createTaprootScriptPathSignOptions(n,l.length),v=await i(y,P);x.assertPsbtUnsignedTxMatches({requestedPsbtHex:y,returnedPsbtHex:v});const w=l.map((m,S)=>{const A=x.extractPayoutSignature(v,h,S);return x.assertScriptPathSchnorrSignature({requestedPsbtHex:y,signatureHex:A,signerXOnlyPubkeyHex:h,inputIndex:S}),A}),E=_.finalizeScriptPathWithSignatures({requestedPsbtHex:y,signaturesHex:w,signerXOnlyPubkeyHex:h});return o==null||o.throwIfAborted(),a(E)}exports.BIP68NotMatureError=xe;exports.ClaimerPegoutStatusValue=ee;exports.PEGIN_ETH_CONFIRMATIONS=de;exports.ParticipantKeyDriftError=Z;exports.PeginRegistrationMissingError=W;exports.PeginRegistrationNotFinalError=Q;exports.RECLAIM_MAX_FEE_FRACTION_DENOMINATOR=j;exports.RECLAIM_MAX_FEE_FRACTION_NUMERATOR=G;exports.RECLAIM_MAX_FEE_RATE_SATS_VB=z;exports.RECLAIM_WARN_FEE_FRACTION_NUMERATOR=$t;exports.REFUND_MAX_FEE_FRACTION_DENOMINATOR=L;exports.REFUND_MAX_FEE_FRACTION_NUMERATOR=U;exports.REFUND_MAX_FEE_RATE_SATS_VB=M;exports.REFUND_VSIZE=te;exports.ReclaimUneconomicalError=q;exports.RegisteredVaultVersionMismatchError=J;exports.activateVault=Ne;exports.activateVaultAndRedeem=He;exports.assertVaultProviderHintAccepted=st;exports.buildAndBroadcastReclaim=Ot;exports.buildAndBroadcastRefund=It;exports.estimateRefundFeeSats=Rt;exports.isDepositAmountValid=lt;exports.isHintAccepted=V;exports.isParticipantKeyDriftError=vt;exports.isPeginRegistrationMissingError=ge;exports.isPeginRegistrationNotFinalError=Me;exports.isPegoutTerminalStatus=kt;exports.isRecognizedPegoutStatus=xt;exports.isRegisteredVaultVersionMismatchError=bt;exports.matchKeyHint=ye;exports.matchKeySetHint=F;exports.resolveCurrentParticipantKeys=me;exports.resolveParticipantKeysAtEpochs=be;exports.runDepositorPresignFlow=rt;exports.signDepositorGraph=fe;exports.submitWotsPublicKey=it;exports.validateDepositAmount=ht;exports.validateMultiVaultDepositInputs=yt;exports.validateOnChainParticipantKeys=ut;exports.validateProviderSelection=dt;exports.validateRemainingCapacity=pt;exports.validateVaultAmounts=we;exports.validateVaultProviderPubkey=Ee;exports.verifyRegisteredParticipantKeys=mt;exports.verifyRegisteredVaultVersions=wt;exports.waitForPeginRegistrationDepth=Ue;exports.waitForPeginStatus=Y;
2
+ //# sourceMappingURL=buildAndBroadcastReclaim-Cqc6Jiqk.cjs.map