@babylonlabs-io/ts-sdk 0.19.0 → 0.20.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.
- package/README.md +56 -12
- package/dist/bitcoin-CNnPFU6Y.cjs +2 -0
- package/dist/bitcoin-CNnPFU6Y.cjs.map +1 -0
- package/dist/{constants-Q7v2O7Ps.js → bitcoin-nOOgeRyl.js} +64 -76
- package/dist/bitcoin-nOOgeRyl.js.map +1 -0
- package/dist/buildAndBroadcastRefund-DWEQvj9T.cjs +2 -0
- package/dist/buildAndBroadcastRefund-DWEQvj9T.cjs.map +1 -0
- package/dist/buildAndBroadcastRefund-DnTQkCgG.js +1331 -0
- package/dist/buildAndBroadcastRefund-DnTQkCgG.js.map +1 -0
- package/dist/challengeAssert-D1lpvuMv.js +283 -0
- package/dist/challengeAssert-D1lpvuMv.js.map +1 -0
- package/dist/challengeAssert-nYlgeAI8.cjs +2 -0
- package/dist/challengeAssert-nYlgeAI8.cjs.map +1 -0
- package/dist/errors-D9EtjJoD.cjs +2 -0
- package/dist/errors-D9EtjJoD.cjs.map +1 -0
- package/dist/{errors-aMocmFr-.js → errors-D_PI__IT.js} +98 -97
- package/dist/errors-D_PI__IT.js.map +1 -0
- package/dist/fundPeginTransaction-BLYXxLBv.js +70 -0
- package/dist/fundPeginTransaction-BLYXxLBv.js.map +1 -0
- package/dist/fundPeginTransaction-DxNOeyNI.cjs +2 -0
- package/dist/fundPeginTransaction-DxNOeyNI.cjs.map +1 -0
- package/dist/index-BpXpESWu.cjs +2 -0
- package/dist/index-BpXpESWu.cjs.map +1 -0
- package/dist/{index-BvFLf3vm.js → index-CFwoGJNQ.js} +146 -518
- package/dist/index-CFwoGJNQ.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +133 -109
- package/dist/payout-DzGsAnhf.js +261 -0
- package/dist/payout-DzGsAnhf.js.map +1 -0
- package/dist/payout-RFIh7GLN.cjs +2 -0
- package/dist/payout-RFIh7GLN.cjs.map +1 -0
- package/dist/psbtInputFields-05ZrwRzf.cjs +2 -0
- package/dist/psbtInputFields-05ZrwRzf.cjs.map +1 -0
- package/dist/psbtInputFields-r1ss6WLU.js +237 -0
- package/dist/psbtInputFields-r1ss6WLU.js.map +1 -0
- package/dist/signing-DeWVBl7m.js +64 -0
- package/dist/signing-DeWVBl7m.js.map +1 -0
- package/dist/signing-cl-lowxV.cjs +2 -0
- package/dist/signing-cl-lowxV.cjs.map +1 -0
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +2 -2
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.d.ts +3 -1
- package/dist/tbv/core/index.d.ts.map +1 -1
- package/dist/tbv/core/index.js +130 -106
- package/dist/tbv/core/managers/PeginManager.d.ts +1 -1
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.d.ts +3 -2
- package/dist/tbv/core/primitives/index.d.ts.map +1 -1
- package/dist/tbv/core/primitives/index.js +24 -23
- package/dist/tbv/core/primitives/psbt/__tests__/helpers.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/index.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/pegin.d.ts +2 -3
- package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts +4 -0
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -1
- package/dist/tbv/core/primitives/utils/index.d.ts +1 -1
- package/dist/tbv/core/primitives/utils/index.d.ts.map +1 -1
- package/dist/tbv/core/services/activation/__tests__/activateVault.test.d.ts +2 -0
- package/dist/tbv/core/services/activation/__tests__/activateVault.test.d.ts.map +1 -0
- package/dist/tbv/core/services/activation/activateVault.d.ts +77 -0
- package/dist/tbv/core/services/activation/activateVault.d.ts.map +1 -0
- package/dist/tbv/core/services/activation/index.d.ts +7 -0
- package/dist/tbv/core/services/activation/index.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/__tests__/peginState.test.d.ts +2 -0
- package/dist/tbv/core/services/deposit/__tests__/peginState.test.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/__tests__/validation.test.d.ts +5 -0
- package/dist/tbv/core/services/deposit/__tests__/validation.test.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/index.d.ts +4 -0
- package/dist/tbv/core/services/deposit/index.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/peginState.d.ts +93 -0
- package/dist/tbv/core/services/deposit/peginState.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/validation.d.ts +114 -0
- package/dist/tbv/core/services/deposit/validation.d.ts.map +1 -0
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.d.ts +3 -0
- package/dist/tbv/core/services/index.d.ts.map +1 -1
- package/dist/tbv/core/services/index.js +25 -7
- package/dist/tbv/core/services/index.js.map +1 -1
- package/dist/tbv/core/services/pegout/__tests__/state.test.d.ts +2 -0
- package/dist/tbv/core/services/pegout/__tests__/state.test.d.ts.map +1 -0
- package/dist/tbv/core/services/pegout/index.d.ts +2 -0
- package/dist/tbv/core/services/pegout/index.d.ts.map +1 -0
- package/dist/tbv/core/services/pegout/state.d.ts +30 -0
- package/dist/tbv/core/services/pegout/state.d.ts.map +1 -0
- package/dist/tbv/core/services/refund/__tests__/buildAndBroadcastRefund.test.d.ts +2 -0
- package/dist/tbv/core/services/refund/__tests__/buildAndBroadcastRefund.test.d.ts.map +1 -0
- package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts +103 -0
- package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts.map +1 -0
- package/dist/tbv/core/services/refund/errors.d.ts +13 -0
- package/dist/tbv/core/services/refund/errors.d.ts.map +1 -0
- package/dist/tbv/core/services/refund/index.d.ts +8 -0
- package/dist/tbv/core/services/refund/index.d.ts.map +1 -0
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +30 -24
- package/dist/tbv/core/utils/transaction/fundPeginTransaction.d.ts +1 -1
- package/dist/tbv/core/utils/utxo/__tests__/availability.test.d.ts +3 -0
- package/dist/tbv/core/utils/utxo/__tests__/availability.test.d.ts.map +1 -0
- package/dist/tbv/core/utils/utxo/__tests__/reservation.test.d.ts +3 -0
- package/dist/tbv/core/utils/utxo/__tests__/reservation.test.d.ts.map +1 -0
- package/dist/tbv/core/utils/utxo/availability.d.ts +62 -0
- package/dist/tbv/core/utils/utxo/availability.d.ts.map +1 -0
- package/dist/tbv/core/utils/utxo/index.d.ts +2 -0
- package/dist/tbv/core/utils/utxo/index.d.ts.map +1 -1
- package/dist/tbv/core/utils/utxo/reservation.d.ts +91 -0
- package/dist/tbv/core/utils/utxo/reservation.d.ts.map +1 -0
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +130 -106
- package/dist/tbv/integrations/aave/index.cjs +1 -1
- package/dist/tbv/integrations/aave/index.cjs.map +1 -1
- package/dist/tbv/integrations/aave/index.d.ts +3 -3
- package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/index.js +145 -169
- package/dist/tbv/integrations/aave/index.js.map +1 -1
- package/dist/tbv/integrations/aave/utils/healthFactor.d.ts +0 -30
- package/dist/tbv/integrations/aave/utils/healthFactor.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/utils/index.d.ts +2 -2
- package/dist/tbv/integrations/aave/utils/index.d.ts.map +1 -1
- package/dist/types-B-p4dhEH.cjs +2 -0
- package/dist/types-B-p4dhEH.cjs.map +1 -0
- package/dist/types-DWjaqVfP.js +608 -0
- package/dist/types-DWjaqVfP.js.map +1 -0
- package/package.json +5 -1
- package/dist/challengeAssert-D_k_ADgP.cjs +0 -2
- package/dist/challengeAssert-D_k_ADgP.cjs.map +0 -1
- package/dist/challengeAssert-k5_LWUtO.js +0 -362
- package/dist/challengeAssert-k5_LWUtO.js.map +0 -1
- package/dist/constants-EiyZkXce.cjs +0 -2
- package/dist/constants-EiyZkXce.cjs.map +0 -1
- package/dist/constants-Q7v2O7Ps.js.map +0 -1
- package/dist/errors-DVNYib5y.cjs +0 -2
- package/dist/errors-DVNYib5y.cjs.map +0 -1
- package/dist/errors-aMocmFr-.js.map +0 -1
- package/dist/fundPeginTransaction-DpwnDslW.js +0 -50
- package/dist/fundPeginTransaction-DpwnDslW.js.map +0 -1
- package/dist/fundPeginTransaction-EbrZzlrh.cjs +0 -2
- package/dist/fundPeginTransaction-EbrZzlrh.cjs.map +0 -1
- package/dist/index-BX-V3C9t.js +0 -995
- package/dist/index-BX-V3C9t.js.map +0 -1
- package/dist/index-BgnxXV5G.cjs +0 -2
- package/dist/index-BgnxXV5G.cjs.map +0 -1
- package/dist/index-BvFLf3vm.js.map +0 -1
- package/dist/index-DpKhuCta.cjs +0 -2
- package/dist/index-DpKhuCta.cjs.map +0 -1
- package/dist/payout-Ce9vSs9e.js +0 -164
- package/dist/payout-Ce9vSs9e.js.map +0 -1
- package/dist/payout-CfsDnjKI.cjs +0 -2
- package/dist/payout-CfsDnjKI.cjs.map +0 -1
- package/dist/psbtInputFields-C0nKn_GD.cjs +0 -2
- package/dist/psbtInputFields-C0nKn_GD.cjs.map +0 -1
- package/dist/psbtInputFields-DO0ELwiv.js +0 -116
- package/dist/psbtInputFields-DO0ELwiv.js.map +0 -1
- package/dist/signing-Deg5lCoC.cjs +0 -2
- package/dist/signing-Deg5lCoC.cjs.map +0 -1
- package/dist/signing-Drwr3bXB.js +0 -16
- package/dist/signing-Drwr3bXB.js.map +0 -1
- package/dist/types-D1rYwwCu.js +0 -235
- package/dist/types-D1rYwwCu.js.map +0 -1
- package/dist/types-DEWiqXYp.cjs +0 -2
- package/dist/types-DEWiqXYp.cjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"challengeAssert-k5_LWUtO.js","sources":["../src/tbv/core/primitives/challengers.ts","../src/tbv/core/primitives/psbt/pegin.ts","../src/tbv/core/primitives/psbt/peginInput.ts","../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/depositorPayout.ts","../src/tbv/core/primitives/psbt/noPayout.ts","../src/tbv/core/primitives/psbt/challengeAssert.ts"],"sourcesContent":["/**\n * Challenger counting utilities.\n *\n * Used for UI-level validation (e.g. computing minimum deposit amounts)\n * where the depositor's identity is known. The transaction builders use\n * `vaultKeeperBtcPubkeys.length` to match the VP's current validation.\n */\n\nimport { processPublicKeyToXOnly } from \"./utils/bitcoin\";\n\n/**\n * Normalize a public key to lowercase x-only hex for reliable comparison.\n *\n * Handles `0x` prefixes, compressed (33-byte), and uncompressed (65-byte) keys.\n */\nfunction normalizeKey(key: string): string {\n return processPublicKeyToXOnly(key).toLowerCase();\n}\n\n/**\n * Compute the number of local challengers for a vault.\n *\n * Mirrors the VP's `compute_num_challengers()` logic:\n * local challengers = {vault_provider} ∪ {vault_keepers} − {depositor}\n *\n * Keys are normalized to x-only lowercase hex before comparison, so\n * `0x`-prefixed, compressed, or mixed-case keys are handled correctly.\n *\n * @param vaultProviderPubkey - Vault provider BTC public key\n * @param vaultKeeperPubkeys - Vault keeper BTC public keys\n * @param depositorPubkey - Depositor (claimer) BTC public key\n * @returns Number of local challengers\n */\nexport function computeNumLocalChallengers(\n vaultProviderPubkey: string,\n vaultKeeperPubkeys: string[],\n depositorPubkey: string,\n): number {\n const localSet = new Set<string>();\n localSet.add(normalizeKey(vaultProviderPubkey));\n for (const vk of vaultKeeperPubkeys) {\n localSet.add(normalizeKey(vk));\n }\n localSet.delete(normalizeKey(depositorPubkey));\n return localSet.size;\n}\n","/**\n * Pre-PegIn PSBT Builder Primitive\n *\n * This module provides pure functions for building unfunded Pre-PegIn transactions\n * and deriving PegIn transactions from them, using the WASM implementation from\n * @babylonlabs-io/babylon-tbv-rust-wasm.\n *\n * Pre-PegIn Flow:\n * 1. buildPrePeginPsbt() — creates unfunded Pre-PegIn tx (HTLC output)\n * 2. [caller funds Pre-PegIn tx and computes txid]\n * 3. buildPeginTxFromFundedPrePegin() — derives PegIn tx spending the HTLC\n * 4. buildPeginInputPsbt() — PSBT for depositor to sign PegIn HTLC leaf 0 input\n *\n * @module primitives/psbt/pegin\n */\n\nimport {\n createPrePeginTransaction,\n buildPeginTxFromPrePegin,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\nimport { parseUnfundedWasmTransaction } from \"../../utils/transaction/fundPeginTransaction\";\n\n/**\n * Parameters for building an unfunded Pre-PegIn PSBT\n */\nexport interface PrePeginParams {\n /** Depositor's BTC public key (x-only, 64-char hex without 0x prefix) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Array of vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Array of universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment(s) (64 hex chars = 32 bytes each) */\n hashlocks: readonly string[];\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Amounts to peg in (satoshis), one per deposit */\n pegInAmounts: readonly bigint[];\n /** Fee rate in sat/vB from contract offchain params */\n feeRate: bigint;\n /** Number of local challengers (from contract params) */\n numLocalChallengers: number;\n /** M in M-of-N council multisig (from contract params) */\n councilQuorum: number;\n /** N in M-of-N council multisig (from contract params) */\n councilSize: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building an unfunded Pre-PegIn transaction\n */\nexport interface PrePeginPsbtResult {\n /**\n * Unfunded transaction hex (no inputs, HTLC output + CPFP anchor).\n *\n * The caller is responsible for:\n * - Selecting UTXOs covering totalOutputValue + network fees\n * - Funding the transaction (add inputs and change output)\n * - Computing the funded transaction's txid\n * - Calling buildPeginTxFromFundedPrePegin() with the funded txid\n */\n psbtHex: string;\n /** Sum of all unfunded outputs (HTLC + CPFP anchor) — use this for UTXO selection */\n totalOutputValue: bigint;\n /** HTLC output values in satoshis, one per deposit (each includes peginAmount + depositorClaimValue + minPeginFee) */\n htlcValues: readonly bigint[];\n /** HTLC output scriptPubKeys (hex encoded), one per deposit */\n htlcScriptPubKeys: readonly string[];\n /** HTLC Taproot addresses, one per deposit */\n htlcAddresses: readonly string[];\n /** Pegin amounts in satoshis, one per deposit */\n peginAmounts: readonly bigint[];\n /** Depositor claim value computed by WASM from contract parameters */\n depositorClaimValue: bigint;\n}\n\n/**\n * Parameters for building the PegIn transaction from a funded Pre-PegIn txid\n */\nexport interface BuildPeginTxParams {\n /** Same PrePeginParams used to create the Pre-PegIn transaction */\n prePeginParams: PrePeginParams;\n /** CSV timelock in blocks for the PegIn vault output */\n timelockPegin: number;\n /** Hex-encoded funded Pre-PegIn transaction */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output to spend */\n htlcVout: number;\n}\n\n/**\n * Result of building the PegIn transaction\n */\nexport interface PeginTxResult {\n /** PegIn transaction hex (1 input spending HTLC, 1 vault output) */\n txHex: string;\n /** PegIn transaction ID */\n txid: string;\n /** Vault output scriptPubKey (hex encoded) */\n vaultScriptPubKey: string;\n /** Vault output value in satoshis */\n vaultValue: bigint;\n}\n\n/**\n * Build unfunded Pre-PegIn transaction using WASM.\n *\n * Creates a Bitcoin transaction template with no inputs, an HTLC output, and a\n * CPFP anchor output. The HTLC value is computed internally from the contract\n * parameters — the caller does not need to compute depositorClaimValue separately.\n *\n * @param params - Pre-PegIn parameters\n * @returns Unfunded Pre-PegIn transaction details with HTLC output information\n * @throws If WASM initialization fails or parameters are invalid\n */\nexport async function buildPrePeginPsbt(\n params: PrePeginParams,\n): Promise<PrePeginPsbtResult> {\n const result = await createPrePeginTransaction({\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlocks: [...params.hashlocks],\n timelockRefund: params.timelockRefund,\n pegInAmounts: [...params.pegInAmounts],\n feeRate: params.feeRate,\n numLocalChallengers: params.numLocalChallengers,\n councilQuorum: params.councilQuorum,\n councilSize: params.councilSize,\n network: params.network,\n });\n\n // Parse the unfunded tx to sum all output values (HTLC + CPFP anchor).\n // This is the amount UTXOs must cover before adding network fees.\n const parsed = parseUnfundedWasmTransaction(result.txHex);\n const totalOutputValue = parsed.outputs.reduce(\n (sum, o) => sum + BigInt(o.value),\n 0n,\n );\n\n return {\n psbtHex: result.txHex,\n totalOutputValue,\n htlcValues: result.htlcValues,\n htlcScriptPubKeys: result.htlcScriptPubKeys,\n htlcAddresses: result.htlcAddresses,\n peginAmounts: result.peginAmounts,\n depositorClaimValue: result.depositorClaimValue,\n };\n}\n\n/**\n * Build the PegIn transaction from a funded Pre-PegIn transaction.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output at htlcVout via the\n * hashlock + all-party script (leaf 0).\n *\n * @param params - Build parameters including Pre-PegIn params and funded tx hex\n * @returns PegIn transaction details\n * @throws If WASM initialization fails or parameters are invalid\n */\nexport async function buildPeginTxFromFundedPrePegin(\n params: BuildPeginTxParams,\n): Promise<PeginTxResult> {\n const result = await buildPeginTxFromPrePegin(\n {\n depositorPubkey: params.prePeginParams.depositorPubkey,\n vaultProviderPubkey: params.prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: params.prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.prePeginParams.universalChallengerPubkeys,\n hashlocks: [...params.prePeginParams.hashlocks],\n timelockRefund: params.prePeginParams.timelockRefund,\n pegInAmounts: [...params.prePeginParams.pegInAmounts],\n feeRate: params.prePeginParams.feeRate,\n numLocalChallengers: params.prePeginParams.numLocalChallengers,\n councilQuorum: params.prePeginParams.councilQuorum,\n councilSize: params.prePeginParams.councilSize,\n network: params.prePeginParams.network,\n },\n params.timelockPegin,\n params.fundedPrePeginTxHex,\n params.htlcVout,\n );\n\n return {\n txHex: result.txHex,\n txid: result.txid,\n vaultScriptPubKey: result.vaultScriptPubKey,\n vaultValue: result.vaultValue,\n };\n}\n","/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, stripHexPrefix, uint8ArrayToHex } from \"../utils/bitcoin\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const hashlockScript = hexToUint8Array(htlcConnector.hashlockScript);\n const hashlockControlBlock = hexToUint8Array(htlcConnector.hashlockControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hashlockScript),\n controlBlock: Buffer.from(hashlockControlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports both non-finalized PSBTs (tapScriptSig) and finalized PSBTs (witness).\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(\n hexToUint8Array(depositorPubkey),\n );\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // Some wallets (UniSat, OKX) ignore autoFinalized: false and return\n // already-finalized PSBTs. finalizeAllInputs() throws in that case,\n // so fall back to verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n return psbt.extractTransaction().toHex();\n}\n\n/** Extract and validate a 64-byte Schnorr signature, stripping sighash flag if present. */\nfunction extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n return uint8ArrayToHex(new Uint8Array(sig.subarray(0, 64)));\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n\n","/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n initWasm,\n tapInternalPubkey,\n WasmPrePeginTx,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, uint8ArrayToHex } from \"../utils/bitcoin\";\nimport type { PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<timelockRefund> CSV DROP <depositorPubkey> CHECKSIG`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n await initWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(prePeginParams.pegInAmounts),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n );\n\n let fundedTx: WasmPrePeginTx | null = null;\n try {\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n depositorPubkey: prePeginParams.depositorPubkey,\n vaultProviderPubkey: prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys: prePeginParams.universalChallengerPubkeys,\n hashlock,\n timelockRefund: prePeginParams.timelockRefund,\n network: prePeginParams.network,\n });\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hexToUint8Array(htlcConnector.refundScript)),\n controlBlock: Buffer.from(\n hexToUint8Array(htlcConnector.refundControlBlock),\n ),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n for (const output of refundTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * Depositor Payout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's own Payout transaction\n * (depositor-as-claimer path). The depositor signs input 0 using the\n * payout taproot script from WasmPeginPayoutConnector (PegIn vault UTXO).\n *\n * Input 0 spends PegIn:0 (the vault UTXO) — the same connector used for\n * VP/VK payout signing. The VP verifies this signature using the\n * PeginPayoutConnector's payout script.\n *\n * @module primitives/psbt/depositorPayout\n * @see btc-vault crates/vault/src/sign.rs — verify_depositor_signature / get_payout_tap_leaf_hash\n */\n\nimport {\n type PayoutConnectorParams,\n getPeginPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a depositor Payout PSBT\n */\nexport interface DepositorPayoutParams {\n /** Payout transaction hex (unsigned) from VP */\n payoutTxHex: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the PeginPayout connector (depositor, VP, VKs, UCs, timelock) */\n connectorParams: PayoutConnectorParams;\n}\n\n/**\n * Build unsigned depositor Payout PSBT.\n *\n * The depositor's payout transaction has 2 inputs:\n * - Input 0: PegIn:0 (vault UTXO) — depositor signs using PeginPayoutConnector payout script\n * - Input 1: Assert:0 — NOT signed by depositor\n *\n * @param params - Depositor payout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildDepositorPayoutPsbt(\n params: DepositorPayoutParams,\n): Promise<string> {\n const payoutTxHex = stripHexPrefix(params.payoutTxHex);\n const payoutTx = Transaction.fromHex(payoutTxHex);\n\n // Get payout script and control block from WASM (PeginPayoutConnector)\n const { payoutScript, payoutControlBlock } = await getPeginPayoutScriptInfo(\n params.connectorParams,\n );\n const scriptBytes = hexToUint8Array(payoutScript);\n const controlBlock = hexToUint8Array(payoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(payoutTx.version);\n psbt.setLocktime(payoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < payoutTx.ins.length; i++) {\n const input = payoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of payoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n","/**\n * ChallengeAssert PSBT Builder\n *\n * Builds an unsigned PSBT for a ChallengeAssert transaction\n * (depositor-as-claimer path, per challenger). The ChallengeAssert tx has\n * NUM_UTXOS_FOR_CHALLENGE_ASSERT (3) inputs, each spending a different Assert\n * output segment. The depositor signs ALL inputs, each with its own taproot\n * script derived from the per-segment connector params.\n *\n * @module primitives/psbt/challengeAssert\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — ChallengeAssert connector (NUM_UTXOS_FOR_CHALLENGE_ASSERT=3)\n */\n\nimport {\n type ChallengeAssertConnectorParams,\n getChallengeAssertScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a ChallengeAssert PSBT\n */\nexport interface ChallengeAssertParams {\n /** ChallengeAssert transaction hex (unsigned) from VP */\n challengeAssertTxHex: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP (flat, one per input) */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Per-input connector params (one per input/segment, determines the taproot script) */\n connectorParamsPerInput: ChallengeAssertConnectorParams[];\n}\n\n/**\n * Build unsigned ChallengeAssert PSBT.\n *\n * The ChallengeAssert transaction has 3 inputs (one per Assert output segment).\n * Each input has its own taproot script derived from its connector params.\n * The depositor signs all inputs.\n *\n * @param params - ChallengeAssert parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildChallengeAssertPsbt(\n params: ChallengeAssertParams,\n): Promise<string> {\n const challengeAssertTxHex = stripHexPrefix(params.challengeAssertTxHex);\n const challengeAssertTx = Transaction.fromHex(challengeAssertTxHex);\n\n if (params.connectorParamsPerInput.length !== challengeAssertTx.ins.length) {\n throw new Error(\n `Expected ${challengeAssertTx.ins.length} connector params, got ${params.connectorParamsPerInput.length}`,\n );\n }\n\n // Get script and control block for each input from WASM\n const scriptInfos = await Promise.all(\n params.connectorParamsPerInput.map((cp) => getChallengeAssertScriptInfo(cp)),\n );\n\n const psbt = new Psbt();\n psbt.setVersion(challengeAssertTx.version);\n psbt.setLocktime(challengeAssertTx.locktime);\n\n // Add all inputs — depositor signs every input\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const { script, controlBlock } = scriptInfos[i];\n const scriptBytes = hexToUint8Array(script);\n const controlBlockBytes = hexToUint8Array(controlBlock);\n\n psbt.addInput({\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n }\n\n // Add outputs\n for (const output of challengeAssertTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n"],"names":["normalizeKey","key","processPublicKeyToXOnly","computeNumLocalChallengers","vaultProviderPubkey","vaultKeeperPubkeys","depositorPubkey","localSet","vk","buildPrePeginPsbt","params","result","createPrePeginTransaction","totalOutputValue","parseUnfundedWasmTransaction","sum","o","buildPeginTxFromFundedPrePegin","buildPeginTxFromPrePegin","buildPeginInputPsbt","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","hashlockScript","hexToUint8Array","hashlockControlBlock","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig","buildRefundPsbt","initWasm","prePeginParams","htlcVout","refundFee","hashlock","unfundedTx","WasmPrePeginTx","fundedTx","refundTxHex","cleanPrePeginHex","refundTx","refundInput","refundInputTxid","buildDepositorPayoutPsbt","payoutTxHex","payoutTx","payoutScript","payoutControlBlock","getPeginPayoutScriptInfo","scriptBytes","controlBlock","i","prevout","inputData","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","controlBlockBytes","buildChallengeAssertPsbt","challengeAssertTxHex","challengeAssertTx","scriptInfos","cp","getChallengeAssertScriptInfo","script"],"mappings":";;;;;AAeA,SAASA,EAAaC,GAAqB;AACzC,SAAOC,EAAwBD,CAAG,EAAE,YAAA;AACtC;AAgBO,SAASE,EACdC,GACAC,GACAC,GACQ;AACR,QAAMC,wBAAe,IAAA;AACrB,EAAAA,EAAS,IAAIP,EAAaI,CAAmB,CAAC;AAC9C,aAAWI,KAAMH;AACf,IAAAE,EAAS,IAAIP,EAAaQ,CAAE,CAAC;AAE/B,SAAAD,EAAS,OAAOP,EAAaM,CAAe,CAAC,GACtCC,EAAS;AAClB;AC4EA,eAAsBE,EACpBC,GAC6B;AAC7B,QAAMC,IAAS,MAAMC,EAA0B;AAAA,IAC7C,iBAAiBF,EAAO;AAAA,IACxB,qBAAqBA,EAAO;AAAA,IAC5B,oBAAoBA,EAAO;AAAA,IAC3B,4BAA4BA,EAAO;AAAA,IACnC,WAAW,CAAC,GAAGA,EAAO,SAAS;AAAA,IAC/B,gBAAgBA,EAAO;AAAA,IACvB,cAAc,CAAC,GAAGA,EAAO,YAAY;AAAA,IACrC,SAASA,EAAO;AAAA,IAChB,qBAAqBA,EAAO;AAAA,IAC5B,eAAeA,EAAO;AAAA,IACtB,aAAaA,EAAO;AAAA,IACpB,SAASA,EAAO;AAAA,EAAA,CACjB,GAKKG,IADSC,EAA6BH,EAAO,KAAK,EACxB,QAAQ;AAAA,IACtC,CAACI,GAAKC,MAAMD,IAAM,OAAOC,EAAE,KAAK;AAAA,IAChC;AAAA,EAAA;AAGF,SAAO;AAAA,IACL,SAASL,EAAO;AAAA,IAChB,kBAAAE;AAAA,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MACf,OAAOA,EAAO;AAAA,IAAA,CACf;AAGH,SAAOL,EAAK,MAAA;AACd;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const a=require("buffer"),o=require("bitcoinjs-lib"),w=192;function i(e){return e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e}function I(e){return e.startsWith("0x")?e:`0x${e}`}function s(e){const t=i(e);if(!u(t))throw new Error(`Invalid hex string: ${e}`);const n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=parseInt(t.slice(r,r+2),16);return n}function f(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function T(e){return e.length===32?e:e.slice(1,33)}function u(e){return/^[0-9a-fA-F]*$/.test(e)&&e.length%2===0}function E(e){const t=i(e);if(!u(t))throw new Error(`Invalid hex characters in public key: ${e}`);if(t.length===64)return t;if(t.length!==66&&t.length!==130)throw new Error(`Invalid public key length: ${t.length} (expected 64, 66, or 130 hex chars)`);const n=s(t);return f(T(n))}function P(e){const t=i(e);return u(t)}function g(e,t){const n=E(e),r=t??n;if(n.toLowerCase()!==r.toLowerCase())throw new Error(`Wallet public key does not match vault depositor. Expected: ${r}, Got: ${n}. Please connect the wallet that was used to create this vault.`);return{walletPubkeyRaw:e,walletPubkeyXOnly:n,depositorPubkey:r}}function F(){try{o.payments.p2tr({internalPubkey:a.Buffer.alloc(32,1)})}catch(e){if(e instanceof Error&&e.message.includes("No ECC Library provided"))throw new Error('ECC library not initialized. You must call initEccLib(ecc) from "bitcoinjs-lib" before using the SDK. See the ts-sdk README for setup instructions.')}}function l(e){switch(e){case"bitcoin":return o.networks.bitcoin;case"testnet":case"signet":return o.networks.testnet;case"regtest":return o.networks.regtest;default:throw new Error(`Unknown network: ${e}`)}}function _(e,t){F();const n=s(E(e)),{address:r}=o.payments.p2tr({internalPubkey:a.Buffer.from(n),network:l(t)});if(!r)throw new Error("Failed to derive taproot address from public key");return r}function d(e,t){const n=i(e);if(n.length!==66)throw new Error(`Native SegWit requires a compressed public key (66 hex chars), got ${n.length}`);const{address:r}=o.payments.p2wpkh({pubkey:a.Buffer.from(s(n)),network:l(t)});if(!r)throw new Error("Failed to derive native segwit address from public key");return r}function R(e,t,n){const r=i(t);try{if(e===_(r,n))return!0}catch{}const c=[];r.length===66?c.push(r):r.length===64&&c.push(`02${r}`,`03${r}`);for(const p of c)try{if(e===d(p,n))return!0}catch{}return!1}const L=58,O=43,U=11,A=546,b=BigInt(A),h=30,y=2,x=1.1;function k(e){return e<=y?h:0}const S=1;function H(e){return e+S}const C=5;exports.BTC_DUST_SAT=A;exports.DUST_THRESHOLD=b;exports.FEE_SAFETY_MARGIN=x;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=h;exports.MAX_NON_LEGACY_OUTPUT_SIZE=O;exports.P2TR_INPUT_SIZE=L;exports.PEGIN_FIXED_OUTPUTS=S;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=C;exports.TAPSCRIPT_LEAF_VERSION=w;exports.TX_BUFFER_SIZE_OVERHEAD=U;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=y;exports.deriveNativeSegwitAddress=d;exports.deriveTaprootAddress=_;exports.ensureHexPrefix=I;exports.getNetwork=l;exports.hexToUint8Array=s;exports.isAddressFromPublicKey=R;exports.isValidHex=P;exports.peginOutputCount=H;exports.processPublicKeyToXOnly=E;exports.rateBasedTxBufferFee=k;exports.stripHexPrefix=i;exports.toXOnly=T;exports.uint8ArrayToHex=f;exports.validateWalletPubkey=g;
|
|
2
|
-
//# sourceMappingURL=constants-EiyZkXce.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"constants-EiyZkXce.cjs","sources":["../src/tbv/core/primitives/utils/bitcoin.ts","../src/tbv/core/utils/fee/constants.ts"],"sourcesContent":["/**\n * Bitcoin Utilities\n *\n * Common pure utility functions for Bitcoin operations including:\n * - Public key conversions (x-only format)\n * - Hex string manipulation\n * - Uint8Array conversions and validation\n * - Address derivation and validation\n *\n * All functions are pure (no side effects) and work in Node.js, browsers,\n * and serverless environments.\n *\n * @module primitives/utils/bitcoin\n */\n\nimport { Buffer } from \"buffer\";\nimport { networks, payments } from \"bitcoinjs-lib\";\n\nimport type { Network } from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport type { Hex } from \"viem\";\n\n/**\n * BIP-341 Tapscript leaf version for script-path spends.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki\n * @see Rust: bitcoin::taproot::LeafVersion::TapScript\n */\nexport const TAPSCRIPT_LEAF_VERSION = 0xc0;\n\n/**\n * Strip \"0x\" prefix from hex string if present.\n *\n * Bitcoin expects plain hex (no \"0x\" prefix), but frontend often uses\n * Ethereum-style \"0x\"-prefixed hex.\n *\n * @param hex - Hex string with or without \"0x\" prefix\n * @returns Hex string without \"0x\" prefix\n */\nexport function stripHexPrefix(hex: string): string {\n return hex.startsWith(\"0x\") || hex.startsWith(\"0X\") ? hex.slice(2) : hex;\n}\n\n/**\n * Ensure \"0x\" prefix on a hex string, returning viem's Hex type.\n *\n * Ethereum/viem APIs expect `0x`-prefixed hex, but Bitcoin tooling\n * typically omits the prefix. This normalises either form.\n *\n * @param hex - Hex string with or without \"0x\" prefix\n * @returns `0x`-prefixed hex string typed as viem Hex\n */\nexport function ensureHexPrefix(hex: string): Hex {\n return hex.startsWith(\"0x\") ? (hex as Hex) : (`0x${hex}` as Hex);\n}\n\n/**\n * Convert hex string to Uint8Array.\n *\n * @param hex - Hex string (with or without 0x prefix)\n * @returns Uint8Array\n * @throws If hex is invalid\n */\nexport function hexToUint8Array(hex: string): Uint8Array {\n const cleanHex = stripHexPrefix(hex);\n if (!isValidHexRaw(cleanHex)) {\n throw new Error(`Invalid hex string: ${hex}`);\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Convert Uint8Array to hex string (without 0x prefix).\n *\n * @param bytes - Uint8Array to convert\n * @returns Hex string without 0x prefix\n */\nexport function uint8ArrayToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Convert a 33-byte public key to 32-byte x-only format (removes first byte).\n *\n * Used for Taproot/Schnorr signatures which only need the x-coordinate.\n * If the input is already 32 bytes, returns it unchanged.\n *\n * @param pubKey - 33-byte or 32-byte public key\n * @returns 32-byte x-only public key\n */\nexport function toXOnly(pubKey: Uint8Array): Uint8Array {\n return pubKey.length === 32 ? pubKey : pubKey.slice(1, 33);\n}\n\n/**\n * Internal helper: Validate hex string format without stripping prefix\n *\n * @internal\n * @param hex - Hex string (must already have prefix stripped)\n * @returns true if valid hex string\n */\nfunction isValidHexRaw(hex: string): boolean {\n return /^[0-9a-fA-F]*$/.test(hex) && hex.length % 2 === 0;\n}\n\n/**\n * Process and convert a public key to x-only format (32 bytes hex).\n *\n * Handles:\n * - 0x prefix removal\n * - Hex character validation\n * - Length validation\n * - Conversion to x-only format\n *\n * Accepts:\n * - 64 hex chars (32 bytes) - already x-only\n * - 66 hex chars (33 bytes) - compressed pubkey\n * - 130 hex chars (65 bytes) - uncompressed pubkey\n *\n * @param publicKeyHex - Public key in hex format (with or without 0x prefix)\n * @returns X-only public key as 32 bytes hex string (without 0x prefix)\n * @throws If public key format is invalid or contains invalid hex characters\n */\nexport function processPublicKeyToXOnly(publicKeyHex: string): string {\n // Remove '0x' prefix if present\n const cleanHex = stripHexPrefix(publicKeyHex);\n\n // Validate hex characters early to prevent silent failures\n if (!isValidHexRaw(cleanHex)) {\n throw new Error(`Invalid hex characters in public key: ${publicKeyHex}`);\n }\n\n // If already 64 chars (32 bytes), it's already x-only format\n if (cleanHex.length === 64) {\n return cleanHex;\n }\n\n // Validate public key length (should be 66 chars for compressed or 130 for uncompressed)\n if (cleanHex.length !== 66 && cleanHex.length !== 130) {\n throw new Error(\n `Invalid public key length: ${cleanHex.length} (expected 64, 66, or 130 hex chars)`,\n );\n }\n\n const pubkeyBytes = hexToUint8Array(cleanHex);\n return uint8ArrayToHex(toXOnly(pubkeyBytes));\n}\n\n/**\n * Validate hex string format.\n *\n * Checks that the string contains only valid hexadecimal characters (0-9, a-f, A-F)\n * and has an even length (since each byte is represented by 2 hex characters).\n *\n * @param hex - String to validate (with or without 0x prefix)\n * @returns true if valid hex string\n */\nexport function isValidHex(hex: string): boolean {\n const cleanHex = stripHexPrefix(hex);\n return isValidHexRaw(cleanHex);\n}\n\n/**\n * Result of validating a wallet public key against an expected depositor public key.\n */\nexport interface WalletPubkeyValidationResult {\n /** Wallet's raw public key (as returned by wallet, may be compressed) */\n walletPubkeyRaw: string;\n /** Wallet's public key in x-only format (32 bytes, 64 hex chars) */\n walletPubkeyXOnly: string;\n /** The validated depositor public key (x-only format) */\n depositorPubkey: string;\n}\n\n/**\n * Validate that a wallet's public key matches the expected depositor public key.\n *\n * This function:\n * 1. Converts the wallet pubkey to x-only format\n * 2. Uses the expected depositor pubkey if provided, otherwise falls back to wallet pubkey\n * 3. Validates they match (case-insensitive)\n *\n * @param walletPubkeyRaw - Raw public key from wallet (may be compressed 66 chars or x-only 64 chars)\n * @param expectedDepositorPubkey - Expected depositor public key (x-only, optional)\n * @returns Validation result with both pubkey formats\n * @throws If wallet pubkey doesn't match expected depositor pubkey\n */\nexport function validateWalletPubkey(\n walletPubkeyRaw: string,\n expectedDepositorPubkey?: string,\n): WalletPubkeyValidationResult {\n const walletPubkeyXOnly = processPublicKeyToXOnly(walletPubkeyRaw);\n const depositorPubkey = expectedDepositorPubkey ?? walletPubkeyXOnly;\n\n if (walletPubkeyXOnly.toLowerCase() !== depositorPubkey.toLowerCase()) {\n throw new Error(\n `Wallet public key does not match vault depositor. ` +\n `Expected: ${depositorPubkey}, Got: ${walletPubkeyXOnly}. ` +\n `Please connect the wallet that was used to create this vault.`\n );\n }\n\n return { walletPubkeyRaw, walletPubkeyXOnly, depositorPubkey };\n}\n\n// ============================================================================\n// Address derivation and validation\n// ============================================================================\n\n/**\n * Assert that the ECC library has been initialized via `initEccLib(ecc)`.\n *\n * The consuming application must call `initEccLib(ecc)` from `bitcoinjs-lib`\n * once at startup before using any SDK function that involves Taproot / P2TR\n * operations. This guard provides a clear error message when that step was\n * missed, instead of letting bitcoinjs-lib throw its generic\n * \"No ECC Library provided\" error deep in a call stack.\n */\nfunction assertEccInitialized(): void {\n try {\n payments.p2tr({ internalPubkey: Buffer.alloc(32, 1) });\n } catch (e) {\n if (e instanceof Error && e.message.includes(\"No ECC Library provided\")) {\n throw new Error(\n \"ECC library not initialized. \" +\n 'You must call initEccLib(ecc) from \"bitcoinjs-lib\" before using the SDK. ' +\n \"See the ts-sdk README for setup instructions.\",\n );\n }\n // Any other error means ECC is loaded (e.g. invalid key is fine — ECC worked).\n }\n}\n\n/**\n * Map SDK network type to bitcoinjs-lib Network object.\n *\n * @param network - Network type (\"bitcoin\", \"testnet\", \"signet\", \"regtest\")\n * @returns bitcoinjs-lib Network object\n */\nexport function getNetwork(network: Network): networks.Network {\n switch (network) {\n case \"bitcoin\":\n return networks.bitcoin;\n case \"testnet\":\n case \"signet\":\n return networks.testnet;\n case \"regtest\":\n return networks.regtest;\n default:\n throw new Error(`Unknown network: ${network}`);\n }\n}\n\n/**\n * Derive a Taproot (P2TR) address from a public key.\n *\n * @param publicKeyHex - Compressed (66 hex) or x-only (64 hex) public key\n * @param network - Bitcoin network\n * @returns Taproot address (bc1p... / tb1p... / bcrt1p...)\n */\nexport function deriveTaprootAddress(\n publicKeyHex: string,\n network: Network,\n): string {\n assertEccInitialized();\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(publicKeyHex));\n const { address } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!address) {\n throw new Error(\"Failed to derive taproot address from public key\");\n }\n return address;\n}\n\n/**\n * Derive a Native SegWit (P2WPKH) address from a compressed public key.\n *\n * @param publicKeyHex - Compressed public key (66 hex chars, with or without 0x prefix)\n * @param network - Bitcoin network\n * @returns Native SegWit address (bc1q... / tb1q... / bcrt1q...)\n * @throws If publicKeyHex is not a compressed public key (66 hex chars)\n */\nexport function deriveNativeSegwitAddress(\n publicKeyHex: string,\n network: Network,\n): string {\n const cleanHex = stripHexPrefix(publicKeyHex);\n if (cleanHex.length !== 66) {\n throw new Error(\n `Native SegWit requires a compressed public key (66 hex chars), got ${cleanHex.length}`,\n );\n }\n const { address } = payments.p2wpkh({\n pubkey: Buffer.from(hexToUint8Array(cleanHex)),\n network: getNetwork(network),\n });\n if (!address) {\n throw new Error(\n \"Failed to derive native segwit address from public key\",\n );\n }\n return address;\n}\n\n/**\n * Validate that a BTC address was derived from the given public key.\n *\n * Derives Taproot (P2TR) and Native SegWit (P2WPKH) addresses from the\n * public key and checks if the provided address matches any of them.\n *\n * When the input is an x-only key (64 hex chars), both possible compressed\n * keys (`02` + x and `03` + x) are tried for Native SegWit derivation,\n * since the y-parity is unknown.\n *\n * @param address - BTC address to validate\n * @param publicKeyHex - Public key from the wallet (x-only 64 or compressed 66 hex chars)\n * @param network - Bitcoin network\n * @returns true if the address matches the public key\n */\nexport function isAddressFromPublicKey(\n address: string,\n publicKeyHex: string,\n network: Network,\n): boolean {\n const cleanHex = stripHexPrefix(publicKeyHex);\n\n // P2TR — works with both x-only and compressed keys\n try {\n if (address === deriveTaprootAddress(cleanHex, network)) {\n return true;\n }\n } catch {\n // derivation failed, continue\n }\n\n // Build the list of compressed keys to try for P2WPKH\n const compressedKeys: string[] = [];\n if (cleanHex.length === 66) {\n compressedKeys.push(cleanHex);\n } else if (cleanHex.length === 64) {\n // x-only key — try both even (02) and odd (03) y-parity\n compressedKeys.push(`02${cleanHex}`, `03${cleanHex}`);\n }\n\n for (const key of compressedKeys) {\n try {\n if (address === deriveNativeSegwitAddress(key, network)) {\n return true;\n }\n } catch {\n // derivation failed, continue\n }\n }\n\n return false;\n}\n","/**\n * Fee calculation constants for Bitcoin transactions.\n * Based on btc-staking-ts values, adapted for vault peg-in transactions.\n */\n\n// P2TR input size in vbytes (42 vbytes non-witness + 16 vbytes witness)\nexport const P2TR_INPUT_SIZE = 58;\n\n// P2TR output size in bytes (largest non-legacy output type)\nexport const MAX_NON_LEGACY_OUTPUT_SIZE = 43;\n\n// Base transaction overhead (version, input/output counts, locktime, SegWit marker)\nexport const TX_BUFFER_SIZE_OVERHEAD = 11;\n\n// Dust threshold: outputs below this may not be relayed\nexport const BTC_DUST_SAT = 546;\n\n/** Pre-computed BigInt dust threshold to avoid repeated conversions in hot paths */\nexport const DUST_THRESHOLD = BigInt(BTC_DUST_SAT);\n\n// Buffer for low fee rate estimation accuracy (when feeRate <= 2 sat/vbyte)\nexport const LOW_RATE_ESTIMATION_ACCURACY_BUFFER = 30;\n\n// Wallet relay fee rate threshold - different buffer fees are used based on this\nexport const WALLET_RELAY_FEE_RATE_THRESHOLD = 2;\n\n// Safety margin: 10% buffer for size variations and fee market volatility\nexport const FEE_SAFETY_MARGIN = 1.1;\n\n/**\n * Adds a buffer to the transaction fee calculation if the fee rate is low.\n *\n * Some wallets have a relayer fee requirement. If the fee rate is <= 2 sat/vbyte,\n * there's a risk the fee might not be sufficient for transaction relay.\n * We add a buffer to ensure the transaction can be relayed.\n *\n * @param feeRate - Fee rate in satoshis per vbyte\n * @returns Buffer amount in satoshis to add to the transaction fee\n */\nexport function rateBasedTxBufferFee(feeRate: number): number {\n return feeRate <= WALLET_RELAY_FEE_RATE_THRESHOLD\n ? LOW_RATE_ESTIMATION_ACCURACY_BUFFER\n : 0;\n}\n\n/**\n * Number of fixed (non-HTLC) outputs in a Pre-PegIn transaction.\n * Currently this is 1 CPFP anchor output.\n */\nexport const PEGIN_FIXED_OUTPUTS = 1;\n\n/**\n * Compute the total number of outputs (before change) in a Pre-PegIn transaction.\n *\n * A Pre-PegIn tx has: N HTLC outputs (one per vault) + fixed outputs (CPFP anchor).\n * This count is used for fee estimation — the change output is handled separately\n * by selectUtxosForPegin when the change amount exceeds the dust threshold.\n *\n * @param vaultCount - Number of vaults in the batch (1 for single-vault)\n * @returns Total output count before change\n */\nexport function peginOutputCount(vaultCount: number): number {\n return vaultCount + PEGIN_FIXED_OUTPUTS;\n}\n\n/**\n * Safety multiplier for split transaction fee validation.\n * The signed PSBT's fee rate and absolute fee must not exceed this multiple\n * of the planned values. 5x accounts for witness estimation variance while\n * catching catastrophic wallet-side overpayment.\n */\nexport const SPLIT_TX_FEE_SAFETY_MULTIPLIER = 5;\n"],"names":["TAPSCRIPT_LEAF_VERSION","stripHexPrefix","hex","ensureHexPrefix","hexToUint8Array","cleanHex","isValidHexRaw","bytes","i","uint8ArrayToHex","b","toXOnly","pubKey","processPublicKeyToXOnly","publicKeyHex","pubkeyBytes","isValidHex","validateWalletPubkey","walletPubkeyRaw","expectedDepositorPubkey","walletPubkeyXOnly","depositorPubkey","assertEccInitialized","payments","Buffer","getNetwork","network","networks","deriveTaprootAddress","xOnly","address","deriveNativeSegwitAddress","isAddressFromPublicKey","compressedKeys","key","P2TR_INPUT_SIZE","MAX_NON_LEGACY_OUTPUT_SIZE","TX_BUFFER_SIZE_OVERHEAD","BTC_DUST_SAT","DUST_THRESHOLD","LOW_RATE_ESTIMATION_ACCURACY_BUFFER","WALLET_RELAY_FEE_RATE_THRESHOLD","FEE_SAFETY_MARGIN","rateBasedTxBufferFee","feeRate","PEGIN_FIXED_OUTPUTS","peginOutputCount","vaultCount","SPLIT_TX_FEE_SAFETY_MULTIPLIER"],"mappings":"kEA0BaA,EAAyB,IAW/B,SAASC,EAAeC,EAAqB,CAClD,OAAOA,EAAI,WAAW,IAAI,GAAKA,EAAI,WAAW,IAAI,EAAIA,EAAI,MAAM,CAAC,EAAIA,CACvE,CAWO,SAASC,EAAgBD,EAAkB,CAChD,OAAOA,EAAI,WAAW,IAAI,EAAKA,EAAe,KAAKA,CAAG,EACxD,CASO,SAASE,EAAgBF,EAAyB,CACvD,MAAMG,EAAWJ,EAAeC,CAAG,EACnC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AASE,EACdF,EACAhB,EACAY,EACS,CACT,MAAMrB,EAAWJ,EAAea,CAAY,EAG5C,GAAI,CACF,GAAIgB,IAAYF,EAAqBvB,EAAUqB,CAAO,EACpD,MAAO,EAEX,MAAQ,CAER,CAGA,MAAMO,EAA2B,CAAA,EAC7B5B,EAAS,SAAW,GACtB4B,EAAe,KAAK5B,CAAQ,EACnBA,EAAS,SAAW,IAE7B4B,EAAe,KAAK,KAAK5B,CAAQ,GAAI,KAAKA,CAAQ,EAAE,EAGtD,UAAW6B,KAAOD,EAChB,GAAI,CACF,GAAIH,IAAYC,EAA0BG,EAAKR,CAAO,EACpD,MAAO,EAEX,MAAQ,CAER,CAGF,MAAO,EACT,CCnWO,MAAMS,EAAkB,GAGlBC,EAA6B,GAG7BC,EAA0B,GAG1BC,EAAe,IAGfC,EAAiB,OAAOD,CAAY,EAGpCE,EAAsC,GAGtCC,EAAkC,EAGlCC,EAAoB,IAY1B,SAASC,EAAqBC,EAAyB,CAC5D,OAAOA,GAAWH,EACdD,EACA,CACN,CAMO,MAAMK,EAAsB,EAY5B,SAASC,EAAiBC,EAA4B,CAC3D,OAAOA,EAAaF,CACtB,CAQO,MAAMG,EAAiC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"constants-Q7v2O7Ps.js","sources":["../src/tbv/core/primitives/utils/bitcoin.ts","../src/tbv/core/utils/fee/constants.ts"],"sourcesContent":["/**\n * Bitcoin Utilities\n *\n * Common pure utility functions for Bitcoin operations including:\n * - Public key conversions (x-only format)\n * - Hex string manipulation\n * - Uint8Array conversions and validation\n * - Address derivation and validation\n *\n * All functions are pure (no side effects) and work in Node.js, browsers,\n * and serverless environments.\n *\n * @module primitives/utils/bitcoin\n */\n\nimport { Buffer } from \"buffer\";\nimport { networks, payments } from \"bitcoinjs-lib\";\n\nimport type { Network } from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport type { Hex } from \"viem\";\n\n/**\n * BIP-341 Tapscript leaf version for script-path spends.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki\n * @see Rust: bitcoin::taproot::LeafVersion::TapScript\n */\nexport const TAPSCRIPT_LEAF_VERSION = 0xc0;\n\n/**\n * Strip \"0x\" prefix from hex string if present.\n *\n * Bitcoin expects plain hex (no \"0x\" prefix), but frontend often uses\n * Ethereum-style \"0x\"-prefixed hex.\n *\n * @param hex - Hex string with or without \"0x\" prefix\n * @returns Hex string without \"0x\" prefix\n */\nexport function stripHexPrefix(hex: string): string {\n return hex.startsWith(\"0x\") || hex.startsWith(\"0X\") ? hex.slice(2) : hex;\n}\n\n/**\n * Ensure \"0x\" prefix on a hex string, returning viem's Hex type.\n *\n * Ethereum/viem APIs expect `0x`-prefixed hex, but Bitcoin tooling\n * typically omits the prefix. This normalises either form.\n *\n * @param hex - Hex string with or without \"0x\" prefix\n * @returns `0x`-prefixed hex string typed as viem Hex\n */\nexport function ensureHexPrefix(hex: string): Hex {\n return hex.startsWith(\"0x\") ? (hex as Hex) : (`0x${hex}` as Hex);\n}\n\n/**\n * Convert hex string to Uint8Array.\n *\n * @param hex - Hex string (with or without 0x prefix)\n * @returns Uint8Array\n * @throws If hex is invalid\n */\nexport function hexToUint8Array(hex: string): Uint8Array {\n const cleanHex = stripHexPrefix(hex);\n if (!isValidHexRaw(cleanHex)) {\n throw new Error(`Invalid hex string: ${hex}`);\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Convert Uint8Array to hex string (without 0x prefix).\n *\n * @param bytes - Uint8Array to convert\n * @returns Hex string without 0x prefix\n */\nexport function uint8ArrayToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Convert a 33-byte public key to 32-byte x-only format (removes first byte).\n *\n * Used for Taproot/Schnorr signatures which only need the x-coordinate.\n * If the input is already 32 bytes, returns it unchanged.\n *\n * @param pubKey - 33-byte or 32-byte public key\n * @returns 32-byte x-only public key\n */\nexport function toXOnly(pubKey: Uint8Array): Uint8Array {\n return pubKey.length === 32 ? pubKey : pubKey.slice(1, 33);\n}\n\n/**\n * Internal helper: Validate hex string format without stripping prefix\n *\n * @internal\n * @param hex - Hex string (must already have prefix stripped)\n * @returns true if valid hex string\n */\nfunction isValidHexRaw(hex: string): boolean {\n return /^[0-9a-fA-F]*$/.test(hex) && hex.length % 2 === 0;\n}\n\n/**\n * Process and convert a public key to x-only format (32 bytes hex).\n *\n * Handles:\n * - 0x prefix removal\n * - Hex character validation\n * - Length validation\n * - Conversion to x-only format\n *\n * Accepts:\n * - 64 hex chars (32 bytes) - already x-only\n * - 66 hex chars (33 bytes) - compressed pubkey\n * - 130 hex chars (65 bytes) - uncompressed pubkey\n *\n * @param publicKeyHex - Public key in hex format (with or without 0x prefix)\n * @returns X-only public key as 32 bytes hex string (without 0x prefix)\n * @throws If public key format is invalid or contains invalid hex characters\n */\nexport function processPublicKeyToXOnly(publicKeyHex: string): string {\n // Remove '0x' prefix if present\n const cleanHex = stripHexPrefix(publicKeyHex);\n\n // Validate hex characters early to prevent silent failures\n if (!isValidHexRaw(cleanHex)) {\n throw new Error(`Invalid hex characters in public key: ${publicKeyHex}`);\n }\n\n // If already 64 chars (32 bytes), it's already x-only format\n if (cleanHex.length === 64) {\n return cleanHex;\n }\n\n // Validate public key length (should be 66 chars for compressed or 130 for uncompressed)\n if (cleanHex.length !== 66 && cleanHex.length !== 130) {\n throw new Error(\n `Invalid public key length: ${cleanHex.length} (expected 64, 66, or 130 hex chars)`,\n );\n }\n\n const pubkeyBytes = hexToUint8Array(cleanHex);\n return uint8ArrayToHex(toXOnly(pubkeyBytes));\n}\n\n/**\n * Validate hex string format.\n *\n * Checks that the string contains only valid hexadecimal characters (0-9, a-f, A-F)\n * and has an even length (since each byte is represented by 2 hex characters).\n *\n * @param hex - String to validate (with or without 0x prefix)\n * @returns true if valid hex string\n */\nexport function isValidHex(hex: string): boolean {\n const cleanHex = stripHexPrefix(hex);\n return isValidHexRaw(cleanHex);\n}\n\n/**\n * Result of validating a wallet public key against an expected depositor public key.\n */\nexport interface WalletPubkeyValidationResult {\n /** Wallet's raw public key (as returned by wallet, may be compressed) */\n walletPubkeyRaw: string;\n /** Wallet's public key in x-only format (32 bytes, 64 hex chars) */\n walletPubkeyXOnly: string;\n /** The validated depositor public key (x-only format) */\n depositorPubkey: string;\n}\n\n/**\n * Validate that a wallet's public key matches the expected depositor public key.\n *\n * This function:\n * 1. Converts the wallet pubkey to x-only format\n * 2. Uses the expected depositor pubkey if provided, otherwise falls back to wallet pubkey\n * 3. Validates they match (case-insensitive)\n *\n * @param walletPubkeyRaw - Raw public key from wallet (may be compressed 66 chars or x-only 64 chars)\n * @param expectedDepositorPubkey - Expected depositor public key (x-only, optional)\n * @returns Validation result with both pubkey formats\n * @throws If wallet pubkey doesn't match expected depositor pubkey\n */\nexport function validateWalletPubkey(\n walletPubkeyRaw: string,\n expectedDepositorPubkey?: string,\n): WalletPubkeyValidationResult {\n const walletPubkeyXOnly = processPublicKeyToXOnly(walletPubkeyRaw);\n const depositorPubkey = expectedDepositorPubkey ?? walletPubkeyXOnly;\n\n if (walletPubkeyXOnly.toLowerCase() !== depositorPubkey.toLowerCase()) {\n throw new Error(\n `Wallet public key does not match vault depositor. ` +\n `Expected: ${depositorPubkey}, Got: ${walletPubkeyXOnly}. ` +\n `Please connect the wallet that was used to create this vault.`\n );\n }\n\n return { walletPubkeyRaw, walletPubkeyXOnly, depositorPubkey };\n}\n\n// ============================================================================\n// Address derivation and validation\n// ============================================================================\n\n/**\n * Assert that the ECC library has been initialized via `initEccLib(ecc)`.\n *\n * The consuming application must call `initEccLib(ecc)` from `bitcoinjs-lib`\n * once at startup before using any SDK function that involves Taproot / P2TR\n * operations. This guard provides a clear error message when that step was\n * missed, instead of letting bitcoinjs-lib throw its generic\n * \"No ECC Library provided\" error deep in a call stack.\n */\nfunction assertEccInitialized(): void {\n try {\n payments.p2tr({ internalPubkey: Buffer.alloc(32, 1) });\n } catch (e) {\n if (e instanceof Error && e.message.includes(\"No ECC Library provided\")) {\n throw new Error(\n \"ECC library not initialized. \" +\n 'You must call initEccLib(ecc) from \"bitcoinjs-lib\" before using the SDK. ' +\n \"See the ts-sdk README for setup instructions.\",\n );\n }\n // Any other error means ECC is loaded (e.g. invalid key is fine — ECC worked).\n }\n}\n\n/**\n * Map SDK network type to bitcoinjs-lib Network object.\n *\n * @param network - Network type (\"bitcoin\", \"testnet\", \"signet\", \"regtest\")\n * @returns bitcoinjs-lib Network object\n */\nexport function getNetwork(network: Network): networks.Network {\n switch (network) {\n case \"bitcoin\":\n return networks.bitcoin;\n case \"testnet\":\n case \"signet\":\n return networks.testnet;\n case \"regtest\":\n return networks.regtest;\n default:\n throw new Error(`Unknown network: ${network}`);\n }\n}\n\n/**\n * Derive a Taproot (P2TR) address from a public key.\n *\n * @param publicKeyHex - Compressed (66 hex) or x-only (64 hex) public key\n * @param network - Bitcoin network\n * @returns Taproot address (bc1p... / tb1p... / bcrt1p...)\n */\nexport function deriveTaprootAddress(\n publicKeyHex: string,\n network: Network,\n): string {\n assertEccInitialized();\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(publicKeyHex));\n const { address } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!address) {\n throw new Error(\"Failed to derive taproot address from public key\");\n }\n return address;\n}\n\n/**\n * Derive a Native SegWit (P2WPKH) address from a compressed public key.\n *\n * @param publicKeyHex - Compressed public key (66 hex chars, with or without 0x prefix)\n * @param network - Bitcoin network\n * @returns Native SegWit address (bc1q... / tb1q... / bcrt1q...)\n * @throws If publicKeyHex is not a compressed public key (66 hex chars)\n */\nexport function deriveNativeSegwitAddress(\n publicKeyHex: string,\n network: Network,\n): string {\n const cleanHex = stripHexPrefix(publicKeyHex);\n if (cleanHex.length !== 66) {\n throw new Error(\n `Native SegWit requires a compressed public key (66 hex chars), got ${cleanHex.length}`,\n );\n }\n const { address } = payments.p2wpkh({\n pubkey: Buffer.from(hexToUint8Array(cleanHex)),\n network: getNetwork(network),\n });\n if (!address) {\n throw new Error(\n \"Failed to derive native segwit address from public key\",\n );\n }\n return address;\n}\n\n/**\n * Validate that a BTC address was derived from the given public key.\n *\n * Derives Taproot (P2TR) and Native SegWit (P2WPKH) addresses from the\n * public key and checks if the provided address matches any of them.\n *\n * When the input is an x-only key (64 hex chars), both possible compressed\n * keys (`02` + x and `03` + x) are tried for Native SegWit derivation,\n * since the y-parity is unknown.\n *\n * @param address - BTC address to validate\n * @param publicKeyHex - Public key from the wallet (x-only 64 or compressed 66 hex chars)\n * @param network - Bitcoin network\n * @returns true if the address matches the public key\n */\nexport function isAddressFromPublicKey(\n address: string,\n publicKeyHex: string,\n network: Network,\n): boolean {\n const cleanHex = stripHexPrefix(publicKeyHex);\n\n // P2TR — works with both x-only and compressed keys\n try {\n if (address === deriveTaprootAddress(cleanHex, network)) {\n return true;\n }\n } catch {\n // derivation failed, continue\n }\n\n // Build the list of compressed keys to try for P2WPKH\n const compressedKeys: string[] = [];\n if (cleanHex.length === 66) {\n compressedKeys.push(cleanHex);\n } else if (cleanHex.length === 64) {\n // x-only key — try both even (02) and odd (03) y-parity\n compressedKeys.push(`02${cleanHex}`, `03${cleanHex}`);\n }\n\n for (const key of compressedKeys) {\n try {\n if (address === deriveNativeSegwitAddress(key, network)) {\n return true;\n }\n } catch {\n // derivation failed, continue\n }\n }\n\n return false;\n}\n","/**\n * Fee calculation constants for Bitcoin transactions.\n * Based on btc-staking-ts values, adapted for vault peg-in transactions.\n */\n\n// P2TR input size in vbytes (42 vbytes non-witness + 16 vbytes witness)\nexport const P2TR_INPUT_SIZE = 58;\n\n// P2TR output size in bytes (largest non-legacy output type)\nexport const MAX_NON_LEGACY_OUTPUT_SIZE = 43;\n\n// Base transaction overhead (version, input/output counts, locktime, SegWit marker)\nexport const TX_BUFFER_SIZE_OVERHEAD = 11;\n\n// Dust threshold: outputs below this may not be relayed\nexport const BTC_DUST_SAT = 546;\n\n/** Pre-computed BigInt dust threshold to avoid repeated conversions in hot paths */\nexport const DUST_THRESHOLD = BigInt(BTC_DUST_SAT);\n\n// Buffer for low fee rate estimation accuracy (when feeRate <= 2 sat/vbyte)\nexport const LOW_RATE_ESTIMATION_ACCURACY_BUFFER = 30;\n\n// Wallet relay fee rate threshold - different buffer fees are used based on this\nexport const WALLET_RELAY_FEE_RATE_THRESHOLD = 2;\n\n// Safety margin: 10% buffer for size variations and fee market volatility\nexport const FEE_SAFETY_MARGIN = 1.1;\n\n/**\n * Adds a buffer to the transaction fee calculation if the fee rate is low.\n *\n * Some wallets have a relayer fee requirement. If the fee rate is <= 2 sat/vbyte,\n * there's a risk the fee might not be sufficient for transaction relay.\n * We add a buffer to ensure the transaction can be relayed.\n *\n * @param feeRate - Fee rate in satoshis per vbyte\n * @returns Buffer amount in satoshis to add to the transaction fee\n */\nexport function rateBasedTxBufferFee(feeRate: number): number {\n return feeRate <= WALLET_RELAY_FEE_RATE_THRESHOLD\n ? LOW_RATE_ESTIMATION_ACCURACY_BUFFER\n : 0;\n}\n\n/**\n * Number of fixed (non-HTLC) outputs in a Pre-PegIn transaction.\n * Currently this is 1 CPFP anchor output.\n */\nexport const PEGIN_FIXED_OUTPUTS = 1;\n\n/**\n * Compute the total number of outputs (before change) in a Pre-PegIn transaction.\n *\n * A Pre-PegIn tx has: N HTLC outputs (one per vault) + fixed outputs (CPFP anchor).\n * This count is used for fee estimation — the change output is handled separately\n * by selectUtxosForPegin when the change amount exceeds the dust threshold.\n *\n * @param vaultCount - Number of vaults in the batch (1 for single-vault)\n * @returns Total output count before change\n */\nexport function peginOutputCount(vaultCount: number): number {\n return vaultCount + PEGIN_FIXED_OUTPUTS;\n}\n\n/**\n * Safety multiplier for split transaction fee validation.\n * The signed PSBT's fee rate and absolute fee must not exceed this multiple\n * of the planned values. 5x accounts for witness estimation variance while\n * catching catastrophic wallet-side overpayment.\n */\nexport const SPLIT_TX_FEE_SAFETY_MULTIPLIER = 5;\n"],"names":["TAPSCRIPT_LEAF_VERSION","stripHexPrefix","hex","ensureHexPrefix","hexToUint8Array","cleanHex","isValidHexRaw","bytes","i","uint8ArrayToHex","b","toXOnly","pubKey","processPublicKeyToXOnly","publicKeyHex","pubkeyBytes","isValidHex","validateWalletPubkey","walletPubkeyRaw","expectedDepositorPubkey","walletPubkeyXOnly","depositorPubkey","assertEccInitialized","payments","Buffer","e","getNetwork","network","networks","deriveTaprootAddress","xOnly","address","deriveNativeSegwitAddress","isAddressFromPublicKey","compressedKeys","key","P2TR_INPUT_SIZE","MAX_NON_LEGACY_OUTPUT_SIZE","TX_BUFFER_SIZE_OVERHEAD","BTC_DUST_SAT","DUST_THRESHOLD","LOW_RATE_ESTIMATION_ACCURACY_BUFFER","WALLET_RELAY_FEE_RATE_THRESHOLD","FEE_SAFETY_MARGIN","rateBasedTxBufferFee","feeRate","PEGIN_FIXED_OUTPUTS","peginOutputCount","vaultCount","SPLIT_TX_FEE_SAFETY_MULTIPLIER"],"mappings":";;AA0BO,MAAMA,IAAyB;AAW/B,SAASC,EAAeC,GAAqB;AAClD,SAAOA,EAAI,WAAW,IAAI,KAAKA,EAAI,WAAW,IAAI,IAAIA,EAAI,MAAM,CAAC,IAAIA;AACvE;AAWO,SAASC,EAAgBD,GAAkB;AAChD,SAAOA,EAAI,WAAW,IAAI,IAAKA,IAAe,KAAKA,CAAG;AACxD;AASO,SAASE,EAAgBF,GAAyB;AACvD,QAAMG,IAAWJ,EAAeC,CAAG;AACnC,MAAI,CAACI,EAAcD,CAAQ;AACzB,UAAM,IAAI,MAAM,uBAAuBH,CAAG,EAAE;AAE9C,QAAMK,IAAQ,IAAI,WAAWF,EAAS,SAAS,CAAC;AAChD,WAASG,IAAI,GAAGA,IAAIH,EAAS,QAAQG,KAAK;AACxC,IAAAD,EAAMC,IAAI,CAAC,IAAI,SAASH,EAAS,M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AACpD,aAAO;AAAA,EAEX,QAAQ;AAAA,EAER;AAGA,QAAMO,IAA2B,CAAA;AACjC,EAAI7B,EAAS,WAAW,KACtB6B,EAAe,KAAK7B,CAAQ,IACnBA,EAAS,WAAW,MAE7B6B,EAAe,KAAK,KAAK7B,CAAQ,IAAI,KAAKA,CAAQ,EAAE;AAGtD,aAAW8B,KAAOD;AAChB,QAAI;AACF,UAAIH,MAAYC,EAA0BG,GAAKR,CAAO;AACpD,eAAO;AAAA,IAEX,QAAQ;AAAA,IAER;AAGF,SAAO;AACT;ACnWO,MAAMS,IAAkB,IAGlBC,IAA6B,IAG7BC,IAA0B,IAG1BC,IAAe,KAGfC,IAAiB,OAAOD,CAAY,GAGpCE,IAAsC,IAGtCC,IAAkC,GAGlCC,IAAoB;AAY1B,SAASC,EAAqBC,GAAyB;AAC5D,SAAOA,KAAWH,IACdD,IACA;AACN;AAMO,MAAMK,IAAsB;AAY5B,SAASC,EAAiBC,GAA4B;AAC3D,SAAOA,IAAaF;AACtB;AAQO,MAAMG,IAAiC;"}
|
package/dist/errors-DVNYib5y.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var Lt=Object.defineProperty;var Wt=(e,t,n)=>t in e?Lt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var P=(e,t,n)=>Wt(e,typeof t!="symbol"?t+"":t,n);const K=require("bitcoinjs-lib"),X=require("buffer"),_=require("viem"),Vt=require("./signing-Deg5lCoC.cjs"),B=require("./index-DpKhuCta.cjs"),k=require("./constants-EiyZkXce.cjs"),ht=require("@babylonlabs-io/babylon-tbv-rust-wasm"),R=require("./challengeAssert-D_k_ADgP.cjs"),O=require("./psbtInputFields-C0nKn_GD.cjs"),Ft=require("./fundPeginTransaction-EbrZzlrh.cjs"),u=require("./index-BgnxXV5G.cjs");function Dt(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,s.get?s:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Kt=Dt(K),C={"0x04aabf33":"Vault already exists: This Bitcoin transaction has already been registered. Please select different UTXOs or use a different amount to create a unique transaction.","0x4fec082d":"Script mismatch: The Bitcoin transaction's taproot output does not match the expected vault script. This may be caused by incorrect vault participants or key configuration.","0x6cc363a5":"Invalid BTC proof of possession: The signature could not be verified. Please ensure you're signing with the correct Bitcoin wallet.","0x6c3f2bf6":"Invalid BTC public key: The Bitcoin public key format is invalid.","0x2c5211c6":"Invalid amount: The deposit amount is invalid or below the minimum required.","0x0405f772":"Application not registered: The application controller is not registered in the system.","0x24e165cc":"Invalid provider status: The vault provider is not in a valid state to accept deposits.","0xd92e233d":"Zero address: One of the required addresses is the zero address.","0x65aa7007":"BTC key mismatch: The Bitcoin public key does not match the expected key.","0x82b42900":"Unauthorized: You must be the depositor or vault provider to submit this transaction.","0x8baa579f":"Invalid signature: The BTC proof of possession signature could not be verified.","0x2f9d01e9":"Invalid BTC transaction: The Bitcoin transaction format is invalid.","0x5a3c6b3e":"Vault provider not registered: The selected vault provider is not registered.","0x979f4518":"Invalid pegin fee: The ETH fee sent does not match the required amount. This may indicate a fee rate change during the transaction."};function M(e){if(!e||typeof e!="object")return;const t=e;if(typeof t.data=="string"&&t.data.startsWith("0x"))return t.data;if(typeof t.details=="string"&&t.details.startsWith("0x"))return t.details;let n=t.cause,s=0;const o=5;for(;n&&typeof n=="object"&&s<o;){const a=n;if(typeof a.data=="string"&&a.data.startsWith("0x"))return a.data;n=a.cause,s++}const i=(typeof t.message=="string"?t.message:"").match(/\b(0x[a-fA-F0-9]{8})\b/);if(i)return i[1]}function Mt(e){const t=M(e);if(t){const n=t.substring(0,10);return C[t]??C[n]}}function Nt(e){const t=M(e);if(t===void 0)return!1;const n=t.substring(0,10);return t in C||n in C}function S(e){console.error("[Contract Error] Raw error:",e);const t=M(e);if(console.error("[Contract Error] Extracted error data:",t),t){const s=t.substring(0,10),o=C[t]??C[s];if(o)throw console.error("[Contract Error] Known error:",o),new Error(o)}const n=(e==null?void 0:e.message)||"";if(n.includes("gas limit too high")||n.includes("21000000")||n.includes("Internal JSON-RPC error")){const s=t?` (error code: ${t})`:"";throw console.error("[Contract Error] Transaction rejected. Error code:",t,"Message:",n),new Error(`Transaction failed: The contract rejected this transaction${s}. Possible causes: (1) Vault already exists for this transaction, (2) Invalid signature, (3) Unauthorized caller. Please check your transaction parameters and try again.`)}throw e instanceof Error?(console.error("[Contract Error] Unhandled error:",e.message),e):new Error(`Contract call failed: ${String(e)}`)}const jt=0;function qt(e,t,n,s){const o=n==null?void 0:n[`${e}:${t}`];return o?Promise.resolve({txid:e,vout:t,value:o.value,scriptPubKey:o.scriptPubKey}):B.getUtxoInfo(e,t,s)}const ft=12e4;class Xt{constructor(t){P(this,"config");this.config=t}async preparePegin(t){const n=await this.config.btcWallet.getPublicKeyHex(),s=n.length===66?n.slice(2):n,o=k.stripHexPrefix(t.vaultProviderBtcPubkey),r=t.vaultKeeperBtcPubkeys.map(k.stripHexPrefix),i=t.universalChallengerBtcPubkeys.map(k.stripHexPrefix);if(t.hashlocks.length!==t.amounts.length)throw new Error(`hashlocks.length (${t.hashlocks.length}) must equal amounts.length (${t.amounts.length})`);if(t.hashlocks.length===0)throw new Error("hashlocks must contain at least one entry");const a=r.length,g={depositorPubkey:s,vaultProviderPubkey:o,vaultKeeperPubkeys:r,universalChallengerPubkeys:i,hashlocks:t.hashlocks,timelockRefund:t.timelockRefund,pegInAmounts:t.amounts,feeRate:t.protocolFeeRate,numLocalChallengers:a,councilQuorum:t.councilQuorum,councilSize:t.councilSize,network:this.config.btcNetwork},f=await R.buildPrePeginPsbt(g),h=O.selectUtxosForPegin([...t.availableUTXOs],f.totalOutputValue,t.mempoolFeeRate,k.peginOutputCount(f.htlcValues.length)),x=k.getNetwork(this.config.btcNetwork),l=Ft.fundPeginTransaction({unfundedTxHex:f.psbtHex,selectedUTXOs:h.selectedUTXOs,changeAddress:t.changeAddress,changeAmount:h.changeAmount,network:x}),y=k.stripHexPrefix(O.calculateBtcTxHash(l)),m=[],b=[],T=[];for(let p=0;p<t.hashlocks.length;p++){const w=await R.buildPeginTxFromFundedPrePegin({prePeginParams:g,timelockPegin:t.timelockPegin,fundedPrePeginTxHex:l,htlcVout:p}),v=await R.buildPeginInputPsbt({peginTxHex:w.txHex,fundedPrePeginTxHex:l,depositorPubkey:s,vaultProviderPubkey:o,vaultKeeperPubkeys:r,universalChallengerPubkeys:i,hashlock:t.hashlocks[p],timelockRefund:t.timelockRefund,network:this.config.btcNetwork});m.push(w),b.push(v.psbtHex),T.push(Vt.createTaprootScriptPathSignOptions(n,1))}const d=await this.signPsbtsWithFallback(b,T),c=[];for(let p=0;p<d.length;p++){const w=R.extractPeginInputSignature(d[p],s),v=R.finalizePeginInputPsbt(d[p]);c.push({htlcVout:p,htlcValue:f.htlcValues[p],peginTxHex:v,peginTxid:m[p].txid,peginInputSignature:w,vaultScriptPubKey:m[p].vaultScriptPubKey})}return{fundedPrePeginTxHex:l,prePeginTxid:y,unsignedPrePeginTxHex:f.psbtHex,perVault:c,selectedUTXOs:h.selectedUTXOs,fee:h.fee,changeAmount:h.changeAmount}}async signPsbtsWithFallback(t,n){if(typeof this.config.btcWallet.signPsbts=="function"){const o=await this.config.btcWallet.signPsbts(t,n);if(o.length!==t.length)throw new Error(`Expected ${t.length} signed PSBTs but received ${o.length}`);return o}const s=[];for(let o=0;o<t.length;o++){const r=await this.config.btcWallet.signPsbt(t[o],n[o]);s.push(r)}return s}async signAndBroadcast(t){const{fundedPrePeginTxHex:n,depositorBtcPubkey:s}=t,o=n.startsWith("0x")?n.slice(2):n,r=K.Transaction.fromHex(o);if(r.ins.length===0)throw new Error("Transaction has no inputs");const i=new K.Psbt;i.setVersion(r.version),i.setLocktime(r.locktime);const a=s.startsWith("0x")?s.slice(2):s;if(a.length!==64||!/^[0-9a-fA-F]+$/.test(a))throw new Error("Invalid depositorBtcPubkey: expected 64 hex characters (x-only pubkey)");const g=X.Buffer.from(a,"hex");if(g.length!==32)throw new Error(`Invalid depositorBtcPubkey length: expected 32 bytes, got ${g.length}`);const f=this.config.mempoolApiUrl,h=r.ins.map(c=>{const p=X.Buffer.from(c.hash).reverse().toString("hex"),w=c.index;return qt(p,w,t.localPrevouts,f).then(v=>({input:c,utxoData:v,txid:p,vout:w}))}),x=await Promise.all(h),l=x.reduce((c,p)=>c+BigInt(p.utxoData.value),0n),y=r.outs.reduce((c,p)=>c+BigInt(p.value),0n);if(l<y)throw new Error(`UTXO value mismatch: total input value (${l} sat) is less than total output value (${y} sat). This may indicate the mempool API returned manipulated UTXO data.`);for(const{input:c,utxoData:p,txid:w,vout:v}of x){const I=O.getPsbtInputFields({value:p.value,scriptPubKey:p.scriptPubKey},g);i.addInput({hash:c.hash,index:c.index,sequence:c.sequence,...I})}for(const c of r.outs)i.addOutput({script:c.script,value:c.value});const m=await this.config.btcWallet.signPsbt(i.toHex()),b=K.Psbt.fromHex(m);try{b.finalizeAllInputs()}catch(c){if(!b.data.inputs.every(w=>w.finalScriptWitness||w.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${c}`)}const T=b.extractTransaction().toHex();return await B.pushTx(T,f)}async registerPeginOnChain(t){const{depositorBtcPubkey:n,unsignedPrePeginTx:s,depositorSignedPeginTx:o,vaultProvider:r,hashlock:i,htlcVout:a,onPopSigned:g,depositorPayoutBtcAddress:f,depositorWotsPkHash:h,preSignedBtcPopSignature:x}=t;if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const l=this.config.ethWallet.account.address,y=await this.resolvePopSignature(l,x);g&&await g();const m=k.ensureHexPrefix(n),b=k.ensureHexPrefix(s),T=k.ensureHexPrefix(o),d=await this.resolvePayoutScriptPubKey(f),c=O.calculateBtcTxHash(T),p=await ht.deriveVaultId(k.stripHexPrefix(c),k.stripHexPrefix(l)),w=k.ensureHexPrefix(p);if(await this.checkVaultExists(w))throw new Error(`Vault already exists (ID: ${w}, peginTxHash: ${c}). Vault IDs are derived from the pegin transaction hash and depositor address. To create a new vault, use different UTXOs or a different amount to generate a unique transaction.`);const I=_.createPublicClient({chain:this.config.ethChain,transport:_.http()});let E;try{E=await I.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:B.BTCVaultRegistryABI,functionName:"getPegInFee",args:[r]})}catch{throw new Error("Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.")}const A=_.encodeFunctionData({abi:B.BTCVaultRegistryABI,functionName:"submitPeginRequest",args:[l,m,y,b,T,r,i,a,d,h]});let $;try{$=await I.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:A,value:E,account:this.config.ethWallet.account.address})}catch(q){S(q)}let j;try{j=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:A,value:E,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:$})}catch(q){S(q)}const ut=await I.waitForTransactionReceipt({hash:j,timeout:ft});return ut.status==="reverted"&&S(new Error(`Transaction reverted. Hash: ${j}. Check the transaction on block explorer for details.`)),{ethTxHash:ut.transactionHash,vaultId:w,peginTxHash:c,btcPopSignature:y}}async registerPeginBatchOnChain(t){const{vaultProvider:n,requests:s,preSignedBtcPopSignature:o,onPopSigned:r}=t;if(s.length===0)throw new Error("Batch pegin requires at least one request");if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const i=this.config.ethWallet.account.address,a=await this.resolvePopSignature(i,o);r&&await r();const g=[];for(const c of s)g.push(await this.resolvePayoutScriptPubKey(c.depositorPayoutBtcAddress));const f=[];for(const c of s){const p=k.ensureHexPrefix(c.depositorSignedPeginTx),w=O.calculateBtcTxHash(p),v=await ht.deriveVaultId(k.stripHexPrefix(w),k.stripHexPrefix(i)),I=k.ensureHexPrefix(v);if(await this.checkVaultExists(I))throw new Error(`Vault already exists (ID: ${I}, peginTxHash: ${w}). To create a new vault, use different UTXOs or a different amount.`);f.push({vaultId:I,peginTxHash:w})}const h=_.createPublicClient({chain:this.config.ethChain,transport:_.http()});let x;try{x=await h.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:B.BTCVaultRegistryABI,functionName:"getPegInFee",args:[n]})}catch{throw new Error("Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.")}const l=x*BigInt(s.length),y=s.map((c,p)=>({depositorBtcPubKey:k.ensureHexPrefix(c.depositorBtcPubkey),btcPopSignature:a,unsignedPrePeginTx:k.ensureHexPrefix(c.unsignedPrePeginTx),depositorSignedPeginTx:k.ensureHexPrefix(c.depositorSignedPeginTx),hashlock:c.hashlock,htlcVout:c.htlcVout,referralCode:jt,depositorPayoutBtcAddress:g[p],depositorWotsPkHash:c.depositorWotsPkHash})),m=_.encodeFunctionData({abi:B.BTCVaultRegistryABI,functionName:"submitPeginRequestBatch",args:[i,n,y]});let b;try{b=await h.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:m,value:l,account:this.config.ethWallet.account.address})}catch(c){S(c)}let T;try{T=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:m,value:l,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:b})}catch(c){S(c)}const d=await h.waitForTransactionReceipt({hash:T,timeout:ft});return d.status==="reverted"&&S(new Error(`Batch transaction reverted. Hash: ${T}. Check the transaction on block explorer for details.`)),{ethTxHash:d.transactionHash,vaults:f,btcPopSignature:a}}async checkVaultExists(t){try{return(await _.createPublicClient({chain:this.config.ethChain,transport:_.http()}).readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:B.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[t]}))[0]!==_.zeroAddress}catch{return!1}}async resolvePayoutScriptPubKey(t){let n;if(t)n=t;else{n=await this.config.btcWallet.getAddress();const o=await this.config.btcWallet.getPublicKeyHex();if(!k.isAddressFromPublicKey(n,o,this.config.btcNetwork))throw new Error("The BTC address from your wallet does not match the wallet's public key. Please ensure your wallet is using a supported address type (Taproot or Native SegWit).")}const s=k.getNetwork(this.config.btcNetwork);try{return`0x${Kt.address.toOutputScript(n,s).toString("hex")}`}catch{throw new Error(`Invalid BTC payout address: "${n}". Please provide a valid Bitcoin address for the ${this.config.btcNetwork} network.`)}}async resolvePopSignature(t,n){if(n)return n;const s=this.config.vaultContracts.btcVaultRegistry,o=`${t.toLowerCase()}:${this.config.ethChain.id}:pegin:${s.toLowerCase()}`,r=await this.config.btcWallet.signMessage(o,"bip322-simple");return r.startsWith("0x")?r:`0x${X.Buffer.from(r,"base64").toString("hex")}`}getNetwork(){return this.config.btcNetwork}getVaultContractAddress(){return this.config.vaultContracts.btcVaultRegistry}}class bt{constructor(t,n){P(this,"oHash");P(this,"iHash");P(this,"blockLen");P(this,"outputLen");P(this,"finished",!1);P(this,"destroyed",!1);if(u.ahash(t),u.abytes(n,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,o=new Uint8Array(s);o.set(n.length>s?t.create().update(n).digest():n);for(let r=0;r<o.length;r++)o[r]^=54;this.iHash.update(o),this.oHash=t.create();for(let r=0;r<o.length;r++)o[r]^=106;this.oHash.update(o),u.clean(o)}update(t){return u.aexists(this),this.iHash.update(t),this}digestInto(t){u.aexists(this),u.abytes(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:s,finished:o,destroyed:r,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=r,t.blockLen=i,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=s._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const N=(e,t,n)=>new bt(e,t).update(n).digest();N.create=(e,t)=>new bt(e,t);const zt=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),wt=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),Gt=wt.map(e=>(9*e+5)%16),Pt=(()=>{const n=[[wt],[Gt]];for(let s=0;s<4;s++)for(let o of n)o.push(o[s].map(r=>zt[r]));return n})(),kt=Pt[0],Tt=Pt[1],It=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(e=>Uint8Array.from(e)),Zt=kt.map((e,t)=>e.map(n=>It[t][n])),Yt=Tt.map((e,t)=>e.map(n=>It[t][n])),Jt=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Qt=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function dt(e,t,n,s){return e===0?t^n^s:e===1?t&n|~t&s:e===2?(t|~n)^s:e===3?t&s|n&~s:t^(n|~s)}const W=new Uint32Array(16);class te extends u.HashMD{constructor(){super(64,20,8,!0);P(this,"h0",1732584193);P(this,"h1",-271733879);P(this,"h2",-1732584194);P(this,"h3",271733878);P(this,"h4",-1009589776)}get(){const{h0:n,h1:s,h2:o,h3:r,h4:i}=this;return[n,s,o,r,i]}set(n,s,o,r,i){this.h0=n|0,this.h1=s|0,this.h2=o|0,this.h3=r|0,this.h4=i|0}process(n,s){for(let m=0;m<16;m++,s+=4)W[m]=n.getUint32(s,!0);let o=this.h0|0,r=o,i=this.h1|0,a=i,g=this.h2|0,f=g,h=this.h3|0,x=h,l=this.h4|0,y=l;for(let m=0;m<5;m++){const b=4-m,T=Jt[m],d=Qt[m],c=kt[m],p=Tt[m],w=Zt[m],v=Yt[m];for(let I=0;I<16;I++){const E=u.rotl(o+dt(m,i,g,h)+W[c[I]]+T,w[I])+l|0;o=l,l=h,h=u.rotl(g,10)|0,g=i,i=E}for(let I=0;I<16;I++){const E=u.rotl(r+dt(b,a,f,x)+W[p[I]]+d,v[I])+y|0;r=y,y=x,x=u.rotl(f,10)|0,f=a,a=E}}this.set(this.h1+g+x|0,this.h2+h+y|0,this.h3+l+r|0,this.h4+o+a|0,this.h0+i+f|0)}roundClean(){u.clean(W)}destroy(){this.destroyed=!0,u.clean(this.buffer),this.set(0,0,0,0,0)}}const vt=u.createHasher(()=>new te),ee=BigInt(0),U=BigInt(1),ne=BigInt(2),se=BigInt(7),oe=BigInt(256),re=BigInt(113),Ht=[],Et=[],_t=[];for(let e=0,t=U,n=1,s=0;e<24;e++){[n,s]=[s,(2*n+3*s)%5],Ht.push(2*(5*s+n)),Et.push((e+1)*(e+2)/2%64);let o=ee;for(let r=0;r<7;r++)t=(t<<U^(t>>se)*re)%oe,t&ne&&(o^=U<<(U<<BigInt(r))-U);_t.push(o)}const Bt=u.split(_t,!0),ie=Bt[0],ae=Bt[1],gt=(e,t,n)=>n>32?u.rotlBH(e,t,n):u.rotlSH(e,t,n),pt=(e,t,n)=>n>32?u.rotlBL(e,t,n):u.rotlSL(e,t,n);function ce(e,t=24){const n=new Uint32Array(10);for(let s=24-t;s<24;s++){for(let i=0;i<10;i++)n[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,g=(i+2)%10,f=n[g],h=n[g+1],x=gt(f,h,1)^n[a],l=pt(f,h,1)^n[a+1];for(let y=0;y<50;y+=10)e[i+y]^=x,e[i+y+1]^=l}let o=e[2],r=e[3];for(let i=0;i<24;i++){const a=Et[i],g=gt(o,r,a),f=pt(o,r,a),h=Ht[i];o=e[h],r=e[h+1],e[h]=g,e[h+1]=f}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)n[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~n[(a+2)%10]&n[(a+4)%10]}e[0]^=ie[s],e[1]^=ae[s]}u.clean(n)}class ct{constructor(t,n,s,o=!1,r=24){P(this,"state");P(this,"pos",0);P(this,"posOut",0);P(this,"finished",!1);P(this,"state32");P(this,"destroyed",!1);P(this,"blockLen");P(this,"suffix");P(this,"outputLen");P(this,"enableXOF",!1);P(this,"rounds");if(this.blockLen=t,this.suffix=n,this.outputLen=s,this.enableXOF=o,this.rounds=r,u.anumber(s,"outputLen"),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=u.u32(this.state)}clone(){return this._cloneInto()}keccak(){u.swap32IfBE(this.state32),ce(this.state32,this.rounds),u.swap32IfBE(this.state32),this.posOut=0,this.pos=0}update(t){u.aexists(this),u.abytes(t);const{blockLen:n,state:s}=this,o=t.length;for(let r=0;r<o;){const i=Math.min(n-this.pos,o-r);for(let a=0;a<i;a++)s[this.pos++]^=t[r++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:n,pos:s,blockLen:o}=this;t[s]^=n,(n&128)!==0&&s===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){u.aexists(this,!1),u.abytes(t),this.finish();const n=this.state,{blockLen:s}=this;for(let o=0,r=t.length;o<r;){this.posOut>=s&&this.keccak();const i=Math.min(s-this.posOut,r-o);t.set(n.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return u.anumber(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(u.aoutput(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,u.clean(this.state)}_cloneInto(t){const{blockLen:n,suffix:s,outputLen:o,rounds:r,enableXOF:i}=this;return t||(t=new ct(n,s,o,i,r)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=r,t.suffix=s,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}}const le=(e,t,n,s={})=>u.createHasher(()=>new ct(t,e,n),s),St=le(1,136,32);function ue(e,t,n,s){u.ahash(e);const o=u.checkOpts({dkLen:32,asyncTick:10},s),{c:r,dkLen:i,asyncTick:a}=o;if(u.anumber(r,"c"),u.anumber(i,"dkLen"),u.anumber(a,"asyncTick"),r<1)throw new Error("iterations (c) must be >= 1");const g=u.kdfInputToBytes(t,"password"),f=u.kdfInputToBytes(n,"salt"),h=new Uint8Array(i),x=N.create(e,g),l=x._cloneInto().update(f);return{c:r,dkLen:i,asyncTick:a,DK:h,PRF:x,PRFSalt:l}}function he(e,t,n,s,o){return e.destroy(),t.destroy(),s&&s.destroy(),u.clean(o),n}function fe(e,t,n,s){const{c:o,dkLen:r,DK:i,PRF:a,PRFSalt:g}=ue(e,t,n,s);let f;const h=new Uint8Array(4),x=u.createView(h),l=new Uint8Array(a.outputLen);for(let y=1,m=0;m<r;y++,m+=a.outputLen){const b=i.subarray(m,m+a.outputLen);x.setInt32(0,y,!1),(f=g._cloneInto(f)).update(h).digestInto(l),b.set(l.subarray(0,b.length));for(let T=1;T<o;T++){a._cloneInto(f).update(l).digestInto(l);for(let d=0;d<b.length;d++)b[d]^=l[d]}}return he(a,g,i,f,l)}function Ct(e){if(typeof e!="string")throw new TypeError("invalid mnemonic type: "+typeof e);return e.normalize("NFKD")}function de(e){const t=Ct(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}const ge=e=>Ct("mnemonic"+e);function pe(e,t=""){return fe(u.sha512,de(e).nfkd,ge(t),{c:2048,dkLen:64})}const me=508,mt=16,V=32,F=64,xt=5,xe=4;function L(...e){const t=e.reduce((o,r)=>o+r.length,0),n=new Uint8Array(t);let s=0;for(const o of e)n.set(o,s),s+=o.length;return n}function z(e){return new TextEncoder().encode(e)}function G(e){const t=new Uint8Array(xe);return new DataView(t.buffer).setUint32(0,e.length,!1),L(t,e)}function Z(e,t){return N(u.sha512,e,t)}function yt(e){return vt(u.sha256(e))}const rt=e=>Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("");function At(e){const t=pe(e),n=new Uint8Array(t);return t.fill(0),n}async function $t(e,t,n,s){if(e.length!==F)throw new Error(`WOTS seed must be ${F} bytes, got ${e.length}`);t=k.stripHexPrefix(t),n=k.stripHexPrefix(n);const o=e.slice(V,F),r=e.slice(0,V),i=[o,r];try{const a=L(G(z(t)),G(z(n)),G(z(s))),g=L(r,a);i.push(g);const f=Z(o,g);i.push(f);const h=f.slice(0,V),x=f.slice(V,F);i.push(h,x);const l=[],y=[],m=[],b=[];let T=!1;try{for(let d=0;d<me;d++){const c=new Uint8Array(xt);c[0]=0,new DataView(c.buffer).setUint32(1,d,!1);const p=new Uint8Array(xt);p[0]=1,new DataView(p.buffer).setUint32(1,d,!1);const w=L(h,c),v=L(h,p),I=Z(x,w),E=Z(x,v);try{const A=I.slice(0,mt),$=E.slice(0,mt);l.push(A),y.push($),m.push(yt(A)),b.push(yt($))}finally{w.fill(0),v.fill(0),I.fill(0),E.fill(0)}}return T=!0,{falsePreimages:l,truePreimages:y,falseHashes:m,trueHashes:b}}finally{if(!T){for(const d of l)d.fill(0);for(const d of y)d.fill(0)}}}finally{for(const a of i)a.fill(0)}}function ye(e){return{false_list:e.falseHashes.map(rt),true_list:e.trueHashes.map(rt)}}function Rt(e){if(e.falseHashes.length===0||e.trueHashes.length===0)throw new Error("computeWotsPkHash: keypair hash arrays must not be empty");const t=e.falseHashes[0].length,n=(e.falseHashes.length+e.trueHashes.length)*t,s=new Uint8Array(n);let o=0;for(const i of e.falseHashes)s.set(i,o),o+=t;for(const i of e.trueHashes)s.set(i,o),o+=t;const r=St(s);return`0x${rt(r)}`}const Y=32,J=64,be=4,H=20,it=4,Ot=2,we=0,Pe=1,D=[64,64];function at(...e){const t=e.reduce((o,r)=>o+r.length,0),n=new Uint8Array(t);let s=0;for(const o of e)n.set(o,s),s+=o.length;return n}function Q(e){return new TextEncoder().encode(e)}function tt(e){const t=new Uint8Array(be);return new DataView(t.buffer).setUint32(0,e.length,!1),at(t,e)}function et(e){return e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e}const ke=e=>Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("");function Te(e,t){return N(u.sha512,e,t)}function lt(e){return vt(u.sha256(e))}function Ut(e){return(1<<e)-1}function Ie(e){let t=1;for(;t*t<e+1;)t++;return Math.max(t,2)}function ve(e){const t=it,n=Ut(t),s=e*n;return{d:t,n:e,checksum_radix:Ie(s)}}function nt(e,t){const n=[];let s=t;for(;s>0;)n.push(s&255),s>>>=8;const o=new Uint8Array(e.length+n.length);o.set(e);for(let r=0;r<n.length;r++)o[e.length+r]=n[r];return lt(o)}function st(e,t){let n=e;for(let s=0;s<t;s++)n=lt(n);return n}function He(e,t){const n=Ut(t.d),s=t.checksum_radix-1,o=Math.floor(t.n*n/t.checksum_radix),r=[];for(let h=0;h<t.n;h++){const x=nt(e,h+Ot),l=st(x,n);r.push(Array.from(l))}const i=nt(e,we),a=st(i,s),g=nt(e,Pe),f=st(g,o);return{config:t,message_terminals:r,checksum_major_terminal:Array.from(f),checksum_minor_terminal:Array.from(a)}}async function Ee(e,t,n,s){if(e.length!==J)throw new Error(`WOTS seed must be exactly ${J} bytes, got ${e.length}`);const o=et(t),r=et(n),i=e.slice(Y,J),a=e.slice(0,Y),g=at(a,at(tt(Q(o)),tt(Q(r)),tt(Q(et(s))))),f=Te(i,g),h=f.slice(0,Y);try{const x=[];for(let l=0;l<D.length;l++){const y=D[l],m=ve(y),b=new Uint8Array(h.length+1);b.set(h),b[h.length]=l;const T=lt(b);try{const d=He(T,m);if(d.config.d!==it)throw new Error(`Block ${l}: expected d=${it}, got d=${d.config.d}`);if(d.config.n!==y)throw new Error(`Block ${l}: expected n=${y}, got n=${d.config.n}`);if(d.message_terminals.length!==y)throw new Error(`Block ${l}: expected ${y} message terminals, got ${d.message_terminals.length}`);for(let c=0;c<d.message_terminals.length;c++)if(d.message_terminals[c].length!==H)throw new Error(`Block ${l} terminal ${c}: expected ${H} bytes, got ${d.message_terminals[c].length}`);if(d.checksum_minor_terminal.length!==H)throw new Error(`Block ${l} checksum_minor: expected ${H} bytes`);if(d.checksum_major_terminal.length!==H)throw new Error(`Block ${l} checksum_major: expected ${H} bytes`);x.push(d)}finally{b.fill(0),T.fill(0)}}if(x.length!==D.length)throw new Error(`Expected ${D.length} blocks, got ${x.length}`);return x}finally{g.fill(0),i.fill(0),a.fill(0),f.fill(0),h.fill(0),e.fill(0)}}function ot(e,t,n){if(e.length!==H)throw new Error(`Block ${t} ${n}: expected ${H} bytes, got ${e.length}`);for(let s=0;s<e.length;s++){const o=e[s];if(!Number.isInteger(o)||o<0||o>255)throw new Error(`Block ${t} ${n}[${s}]: invalid byte value ${o}`)}}function _e(e){if(e.length===0)throw new Error("Public keys array must not be empty");for(let r=0;r<e.length;r++){const i=e[r];ot(i.checksum_minor_terminal,r,"checksum_minor_terminal"),ot(i.checksum_major_terminal,r,"checksum_major_terminal");for(let a=0;a<i.message_terminals.length;a++)ot(i.message_terminals[a],r,`message_terminal[${a}]`)}let t=0;for(const r of e)t+=Ot+r.message_terminals.length;const n=new Uint8Array(t*H);let s=0;for(const r of e){n.set(r.checksum_minor_terminal,s),s+=H,n.set(r.checksum_major_terminal,s),s+=H;for(const i of r.message_terminals)n.set(i,s),s+=H}const o=St(n);return`0x${ke(o)}`}async function Be(e,t,n,s){const o=At(e);try{const r=await $t(o,t,n,s);try{return Rt(r)}finally{for(const i of r.falsePreimages)i.fill(0);for(const i of r.truePreimages)i.fill(0)}}finally{o.fill(0)}}function Se(e){const t=(e instanceof Error?e.message:typeof e=="string"?e:"").toLowerCase();return t.includes("wots")&&t.includes("hash")&&t.includes("does not match")}exports.CONTRACT_ERRORS=C;exports.PeginManager=Xt;exports.computeWotsBlockPublicKeysHash=_e;exports.computeWotsPkHash=Rt;exports.deriveWotsBlockPublicKeys=Ee;exports.deriveWotsKeypair=$t;exports.deriveWotsPkHash=Be;exports.extractErrorData=M;exports.getContractErrorMessage=Mt;exports.handleContractError=S;exports.isKnownContractError=Nt;exports.isWotsMismatchError=Se;exports.keypairToPublicKey=ye;exports.mnemonicToWotsSeed=At;
|
|
2
|
-
//# sourceMappingURL=errors-DVNYib5y.cjs.map
|