@babylonlabs-io/ts-sdk 0.68.0 → 0.68.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/dist/{PeginManager--2R3T2S8.js → PeginManager-Bsv6caG3.js} +371 -363
- package/dist/PeginManager-Bsv6caG3.js.map +1 -0
- package/dist/PeginManager-C5NWzGT7.cjs +2 -0
- package/dist/PeginManager-C5NWzGT7.cjs.map +1 -0
- package/dist/{batchPoll-Cjj1du0i.js → batchPoll-Bc_UKaTz.js} +2 -2
- package/dist/{batchPoll-Cjj1du0i.js.map → batchPoll-Bc_UKaTz.js.map} +1 -1
- package/dist/{batchPoll-REVZiE-M.cjs → batchPoll-C9cZ5usJ.cjs} +2 -2
- package/dist/{batchPoll-REVZiE-M.cjs.map → batchPoll-C9cZ5usJ.cjs.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +5 -5
- package/dist/{mempoolApi-_D-jvtj_.js → mempoolApi-71R_CNZa.js} +71 -69
- package/dist/mempoolApi-71R_CNZa.js.map +1 -0
- package/dist/mempoolApi-BJN9fGEd.cjs +2 -0
- package/dist/mempoolApi-BJN9fGEd.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/clients/vault-provider/auth/bip322Verify.d.ts +9 -0
- package/dist/tbv/core/clients/vault-provider/auth/bip322Verify.d.ts.map +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +5 -5
- package/dist/tbv/core/managers/index.cjs +1 -1
- package/dist/tbv/core/managers/index.js +1 -1
- package/dist/tbv/core/managers/pegin/verifyPopWitness.d.ts.map +1 -1
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.js +1 -1
- package/dist/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.d.ts +6 -5
- package/dist/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.d.ts.map +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +5 -5
- package/dist/testing/MockBitcoinWallet.d.ts +1 -1
- package/dist/testing/MockBitcoinWallet.d.ts.map +1 -1
- package/dist/testing/index.cjs +1 -1
- package/dist/testing/index.cjs.map +1 -1
- package/dist/testing/index.js +66 -62
- package/dist/testing/index.js.map +1 -1
- package/dist/testing/signBip322P2wpkhWitness.d.ts +5 -0
- package/dist/testing/signBip322P2wpkhWitness.d.ts.map +1 -1
- package/dist/{toRefundInputs-9hv_6k0E.js → toRefundInputs-4UJfSVEz.js} +2 -2
- package/dist/{toRefundInputs-9hv_6k0E.js.map → toRefundInputs-4UJfSVEz.js.map} +1 -1
- package/dist/{toRefundInputs-D8sFs44p.cjs → toRefundInputs-DgDhx_Ut.cjs} +2 -2
- package/dist/{toRefundInputs-D8sFs44p.cjs.map → toRefundInputs-DgDhx_Ut.cjs.map} +1 -1
- package/dist/{verifyKeyPathSchnorrSignature-oGCUbjjZ.js → verifyKeyPathSchnorrSignature-C6Cmk0R1.js} +137 -128
- package/dist/verifyKeyPathSchnorrSignature-C6Cmk0R1.js.map +1 -0
- package/dist/verifyKeyPathSchnorrSignature-Cr5T4Aym.cjs +2 -0
- package/dist/verifyKeyPathSchnorrSignature-Cr5T4Aym.cjs.map +1 -0
- package/package.json +1 -1
- package/dist/PeginManager--2R3T2S8.js.map +0 -1
- package/dist/PeginManager-CKWq8ouZ.cjs +0 -2
- package/dist/PeginManager-CKWq8ouZ.cjs.map +0 -1
- package/dist/mempoolApi-EU1La9wk.cjs +0 -2
- package/dist/mempoolApi-EU1La9wk.cjs.map +0 -1
- package/dist/mempoolApi-_D-jvtj_.js.map +0 -1
- package/dist/verifyKeyPathSchnorrSignature-DCOzQkDf.cjs +0 -2
- package/dist/verifyKeyPathSchnorrSignature-DCOzQkDf.cjs.map +0 -1
- package/dist/verifyKeyPathSchnorrSignature-oGCUbjjZ.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mempoolApi-71R_CNZa.js","sources":["../src/tbv/core/clients/vault-provider/auth/bip322Verify.ts","../src/tbv/core/clients/eth/protocol-params-validation.ts","../src/tbv/core/clients/eth/vault-registry-reader.ts","../src/tbv/core/clients/mempool/mempoolApi.ts"],"sourcesContent":["/**\n * BIP-322 \"simple\" signature verification for P2TR key-path and P2WPKH.\n *\n * Mirrors the Rust reference in\n * `btc-vault/crates/btc-signer/src/message.rs` (`verify_bip322_message`\n * and the P2WPKH arm of `verify_pop_witness`, both of which delegate to\n * the `bip322` crate 0.0.10's `verify_simple`).\n *\n * The algorithm:\n *\n * 1. Compute the BIP-322 tagged-hash of the message:\n * m_hash = SHA256( SHA256(tag) || SHA256(tag) || message )\n * where tag = \"BIP0322-signed-message\".\n *\n * 2. Build a virtual \"to_spend\" transaction with one input (prevout\n * all-zero txid + 0xFFFFFFFF vout, scriptSig = `OP_0 PUSH32 m_hash`,\n * sequence = 0) and one output (value 0, scriptPubKey = the signer's\n * address: P2TR key-path-only, or P2WPKH of the compressed pubkey).\n *\n * 3. Build a \"to_sign\" transaction that spends to_spend[0] and has a\n * single `OP_RETURN` output (value 0).\n *\n * 4. Compute the sighash of to_sign input 0: BIP-341 taproot for P2TR\n * (SIGHASH_DEFAULT 0x00 unless the witness item carried a trailing\n * SIGHASH_ALL 0x01 byte), BIP-143 with the standard P2WPKH\n * scriptCode for P2WPKH (SIGHASH_ALL only).\n *\n * 5. Verify the signature: Schnorr against the **tweaked** output key\n * `Q = P + tap_tweak(P) * G` for P2TR (no merkle root — key-path\n * only), ECDSA against the compressed pubkey for P2WPKH.\n *\n * `bitcoinjs-lib` handles (2)–(4); `tiny-secp256k1-asmjs` provides\n * the tweak and the Schnorr/ECDSA verifies. Pulling in a full BIP-322\n * library would add a peer dep for what amounts to ~40 lines of glue.\n *\n * @module tbv/core/clients/vault-provider/auth/bip322Verify\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { script as bscript, payments, Transaction } from \"bitcoinjs-lib\";\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { Buffer } from \"buffer\";\n\n/** BIP-322 message tag (BIP-340 tagged-hash style). */\nconst BIP322_TAG = \"BIP0322-signed-message\";\n\n/** BIP-341 taproot-tweak tag. */\nconst TAPTWEAK_TAG = \"TapTweak\";\n\nconst X_ONLY_PUBKEY_SIZE = 32;\nconst SCHNORR_SIG_SIZE = 64;\n/** SEC1 compressed pubkey: 0x02/0x03 prefix + 32-byte x coordinate. */\nconst COMPRESSED_PUBKEY_SIZE = 33;\n/**\n * vaultd's P2WPKH BIP-322 verifier accepts ONLY 71/72-byte encoded\n * signatures — DER (70/71B) + sighash byte (`bip322` crate 0.0.10\n * `verify.rs:141-153`). A shorter (short-DER) signature fails ingestion\n * permanently, so this gate must be exactly as strict. Exported so\n * `verifyPopWitness` can pre-screen with a cause-naming error.\n */\nexport const P2WPKH_ENCODED_SIG_MIN = 71;\nexport const P2WPKH_ENCODED_SIG_MAX = 72;\n\n// NOTE: bitcoinjs-lib v6.x's `Transaction.addOutput` and its sighash\n// methods are typed for `Satoshi` (a UInt53 number), not `bigint`.\n// Passing `BigInt(0)` triggers a typeforce assertion in `addOutput`\n// (\"Expected property '1' of type Satoshi, got BigInt 0\") which the\n// verifiers' try/catch silently turns into `verify -> false`. Use\n// plain `0` everywhere.\nconst ZERO_SATS = 0;\n\n// Wire fields of the virtual to_spend/to_sign transactions (`bip322`\n// crate 0.0.10 `util.rs:18-85`).\nconst BIP322_TX_VERSION = 0;\nconst BIP322_TX_LOCKTIME = 0;\nconst BIP322_INPUT_SEQUENCE = 0;\n/** to_spend prevout: all-zero 32-byte txid at index 0xFFFFFFFF (`util.rs:18-85`). */\nconst TO_SPEND_PREVOUT_TXID_BYTES = 32;\nconst TO_SPEND_PREVOUT_INDEX = 0xffffffff;\n/** to_sign spends to_spend's only output (`util.rs:18-85`). */\nconst TO_SPEND_OUTPUT_INDEX = 0;\nconst OP_0 = 0x00;\n/** Direct push of the 32-byte tagged message hash. */\nconst OP_PUSHBYTES_32 = 0x20;\nconst OP_RETURN = 0x6a;\n\n/**\n * BIP-340 tagged hash: `SHA256( SHA256(tag) || SHA256(tag) || data )`.\n * Used for both BIP-322 message hashing and BIP-341 tap-tweak.\n */\nfunction taggedHash(tag: string, data: Uint8Array): Uint8Array {\n const tagBytes = new TextEncoder().encode(tag);\n const tagHash = sha256(tagBytes);\n const preimage = new Uint8Array(tagHash.length * 2 + data.length);\n preimage.set(tagHash, 0);\n preimage.set(tagHash, tagHash.length);\n preimage.set(data, tagHash.length * 2);\n return sha256(preimage);\n}\n\n/**\n * Apply BIP-341 taproot tweak to an x-only pubkey with no merkle\n * root (key-path-only address).\n *\n * `tap_tweak = hash_TapTweak(P)`\n * `Q = P + tap_tweak * G` (x-only, even-Y parity)\n *\n * Returns the tweaked 32-byte x-only pubkey, or null if the tweak\n * produces a point-at-infinity or invalid result.\n */\nfunction tweakXOnlyKey(xOnly: Uint8Array): Uint8Array | null {\n if (xOnly.length !== X_ONLY_PUBKEY_SIZE) return null;\n const tweak = taggedHash(TAPTWEAK_TAG, xOnly);\n const tweaked = ecc.xOnlyPointAddTweak(xOnly, tweak);\n return tweaked ? tweaked.xOnlyPubkey : null;\n}\n\n/**\n * Build the BIP-322 virtual `to_sign` transaction for a signer\n * scriptPubKey (steps 1–3 above; `bip322` crate 0.0.10 `util.rs:18-85`:\n * both txs version 0, locktime 0, sequence 0, all values 0).\n */\nfunction buildToSignTransaction(\n messageBytes: Uint8Array,\n scriptPubKey: Buffer,\n): Transaction {\n const messageHash = taggedHash(BIP322_TAG, messageBytes);\n\n const toSpend = new Transaction();\n toSpend.version = BIP322_TX_VERSION;\n toSpend.locktime = BIP322_TX_LOCKTIME;\n const scriptSig = Buffer.concat([\n Buffer.from([OP_0, OP_PUSHBYTES_32]),\n Buffer.from(messageHash),\n ]);\n toSpend.addInput(\n Buffer.alloc(TO_SPEND_PREVOUT_TXID_BYTES, 0),\n TO_SPEND_PREVOUT_INDEX,\n BIP322_INPUT_SEQUENCE,\n scriptSig,\n );\n toSpend.addOutput(scriptPubKey, ZERO_SATS);\n\n const toSign = new Transaction();\n toSign.version = BIP322_TX_VERSION;\n toSign.locktime = BIP322_TX_LOCKTIME;\n // Bitcoin txid in natural-byte (little-endian) form.\n toSign.addInput(\n toSpend.getHash(),\n TO_SPEND_OUTPUT_INDEX,\n BIP322_INPUT_SEQUENCE,\n );\n toSign.addOutput(Buffer.from([OP_RETURN]), ZERO_SATS);\n\n return toSign;\n}\n\n/**\n * Verify a BIP-322 \"simple\" P2TR key-path signature over an arbitrary\n * byte message.\n *\n * @internal Consumed by `verifyServerIdentity` (VP auth) and\n * `verifyPopWitness` (PoP pre-registration check), and exposed so the\n * golden-vector test suite can pin the verifier independently.\n *\n * @param messageBytes - The bytes that were signed (e.g. a CBOR-encoded\n * payload). Not pre-hashed; this function applies\n * the BIP-322 tagged hash internally.\n * @param xOnlyPubkey - 32-byte x-only pubkey of the signer (pre-tweak).\n * @param signature - 64-byte raw Schnorr signature (BIP-340), as\n * emitted by a key-path witness. The trailing\n * sighash byte of a 65-byte witness item is not\n * part of it — pass it as `hashType` instead.\n * @param hashType - BIP-341 sighash type the signature commits to.\n * `SIGHASH_DEFAULT` (0x00) for a 64-byte witness\n * item, `SIGHASH_ALL` (0x01) for a 65-byte one.\n * @returns `true` if the signature verifies against the address\n * derived from `xOnlyPubkey`; `false` otherwise.\n */\nexport function verifyBip322Simple(\n messageBytes: Uint8Array,\n xOnlyPubkey: Uint8Array,\n signature: Uint8Array,\n hashType: number = Transaction.SIGHASH_DEFAULT,\n): boolean {\n if (xOnlyPubkey.length !== X_ONLY_PUBKEY_SIZE) return false;\n if (signature.length !== SCHNORR_SIG_SIZE) return false;\n // Only the two types a BIP-322 witness may carry. SIGHASH_NONE/SINGLE and the\n // ANYONECANPAY variants would verify here but are rejected downstream.\n if (\n hashType !== Transaction.SIGHASH_DEFAULT &&\n hashType !== Transaction.SIGHASH_ALL\n ) {\n return false;\n }\n\n // Any exception from the underlying crypto libraries (e.g. the\n // `Expected Point` error `tiny-secp256k1` throws when the supplied\n // 32 bytes don't represent a valid x-coordinate on secp256k1) is\n // treated as a verification failure rather than propagated — a\n // verifier MUST return a boolean, not raise.\n try {\n // scriptPubKey for the signer's P2TR key-path-only address.\n // bitcoinjs-lib's `payments.p2tr({ internalPubkey })` computes the\n // tweak and produces the `OP_1 <tweaked_xonly>` output script.\n const p2tr = payments.p2tr({\n internalPubkey: Buffer.from(xOnlyPubkey),\n });\n if (!p2tr.output) return false;\n const scriptPubKey = p2tr.output;\n\n const toSign = buildToSignTransaction(messageBytes, scriptPubKey);\n\n // Taproot sighash for to_sign input 0.\n const sighash = toSign.hashForWitnessV1(\n 0,\n [scriptPubKey],\n [ZERO_SATS],\n hashType,\n );\n\n // Tweak the x-only pubkey (no merkle root) and verify Schnorr.\n const tweakedXOnly = tweakXOnlyKey(xOnlyPubkey);\n if (!tweakedXOnly) return false;\n\n return ecc.verifySchnorr(sighash, tweakedXOnly, signature);\n } catch {\n return false;\n }\n}\n\n/**\n * Verify a BIP-322 \"simple\" P2WPKH signature over an arbitrary byte\n * message, mirroring the verifier vaultd runs on a two-item PoP witness\n * (`bip322` crate 0.0.10 `verify.rs:102-186 verify_full_p2wpkh`).\n *\n * @internal Consumed by `verifyPopWitness` for Native SegWit software\n * wallets, and exposed so the BIP-322 official-vector test suite can pin\n * the verifier independently.\n *\n * @param compressedPubkey - 33-byte SEC1 compressed pubkey of the signer\n * (witness item 1). The address is derived from\n * it; network affects only bech32 encoding, not\n * script or sighash (`message.rs:125-127`).\n * @param encodedSignature - Witness item 0: DER signature with trailing\n * sighash byte, 71 or 72 bytes, SIGHASH_ALL only\n * (`verify.rs:141-161`).\n * @returns `true` if the signature verifies against the P2WPKH address of\n * `compressedPubkey`; `false` otherwise.\n */\nexport function verifyBip322P2wpkhSimple(\n messageBytes: Uint8Array,\n compressedPubkey: Uint8Array,\n encodedSignature: Uint8Array,\n): boolean {\n if (compressedPubkey.length !== COMPRESSED_PUBKEY_SIZE) return false;\n if (\n encodedSignature.length < P2WPKH_ENCODED_SIG_MIN ||\n encodedSignature.length > P2WPKH_ENCODED_SIG_MAX\n ) {\n return false;\n }\n // Any exception below (strict-DER decode, malformed pubkey) is a\n // verification failure, not an error — a verifier returns a boolean.\n try {\n // Full curve-point parse, as `PublicKey::from_slice` (`verify.rs:82-83`).\n if (!ecc.isPointCompressed(compressedPubkey)) return false;\n\n // Strict DER decode, then SIGHASH_ALL only — deliberately NARROWER than\n // `verify.rs:156-161` (its from_consensus maps more bytes to All); host-stricter is safe.\n const { signature, hashType } = bscript.signature.decode(\n Buffer.from(encodedSignature),\n );\n // decode tolerates non-minimal integers (bip66.js never bounds lenR/lenS at 33;\n // fromDER truncates, script_signature.js:29-35) that vaultd's strict libsecp\n // parse rejects (secp256k1-sys ecdsa_impl.h:127-136) — require the unique\n // minimal encoding by re-encoding and byte-comparing.\n if (\n !bscript.signature\n .encode(signature, hashType)\n .equals(Buffer.from(encodedSignature))\n ) {\n return false;\n }\n if (hashType !== Transaction.SIGHASH_ALL) return false;\n\n // scriptPubKey = OP_0 PUSH20 hash160(pubkey) (`message.rs:127 Address::p2wpkh`).\n const p2wpkh = payments.p2wpkh({ pubkey: Buffer.from(compressedPubkey) });\n if (!p2wpkh.output || !p2wpkh.hash) return false;\n\n const toSign = buildToSignTransaction(messageBytes, p2wpkh.output);\n\n // BIP-143 sighash with the standard P2WPKH scriptCode\n // `OP_DUP OP_HASH160 <20B> OP_EQUALVERIFY OP_CHECKSIG` and value 0\n // (`verify.rs:163-173 p2wpkh_signature_hash`; scriptCode template per\n // bitcoinjs-lib's own P2WPKH signer, `src/psbt.js:1245-1255`).\n const scriptCode = payments.p2pkh({ hash: p2wpkh.hash }).output;\n if (!scriptCode) return false;\n const sighash = toSign.hashForWitnessV0(0, scriptCode, ZERO_SATS, hashType);\n\n // strict=true rejects high-S, as libsecp256k1's verify does\n // (`verify.rs:180-182`; secp256k1 crate `ecdsa/mod.rs:194`).\n return ecc.verify(sighash, compressedPubkey, signature, true);\n } catch {\n return false;\n }\n}\n","/**\n * Validation for protocol parameters fetched from the ProtocolParams contract.\n *\n * These values feed Bitcoin script construction and deposit validation.\n * Invalid params must be caught before they reach transaction-building code,\n * since errors after wallet signing prompts are unrecoverable.\n *\n * The {@link ViemProtocolParamsReader} runs these on every read; consumers\n * implementing their own reader against the same `ProtocolParamsReader`\n * interface should call them too.\n */\n\nimport { assertValidVaultCoreVersion } from \"../../primitives/vaultCoreVersion\";\n\nimport type {\n PegInConfiguration,\n TBVProtocolParams,\n VersionedOffchainParams,\n} from \"./types\";\n\n/**\n * Maximum value for a Solidity uint16.\n * PeginLogic.sol casts timelockAssert to uint16, so values above this are invalid.\n */\nconst UINT16_MAX = 65535;\n\n/** Maximum valid value for basis points (100%) */\nconst MAX_BASIS_POINTS = 10000;\n\n/** Maximum value for a Solidity uint32. */\nconst UINT32_MAX = 4_294_967_295;\n\n/** Maximum valid value for a uint8 (e.g. maxHtlcOutputCount). */\nconst UINT8_MAX = 255;\n\n/**\n * Validate an `offchainParamsVersion` value sourced from a contract read.\n * `Number()` on a malformed payload yields `NaN` or a non-integer; both\n * silently break consumers that loop `1..version` or use the value as a\n * map key. Used by reader entry points that surface the version to JS.\n */\nexport function assertValidOffchainParamsVersion(version: number): void {\n if (\n !Number.isInteger(version) ||\n version < 0 ||\n version > UINT32_MAX\n ) {\n throw new Error(\n `Invalid offchainParamsVersion from contract: must be a uint32, got ${version}`,\n );\n }\n}\n\n/**\n * Validate offchain params consistency and bounds.\n * @throws Error on invalid values to prevent constructing invalid Bitcoin scripts.\n */\nexport function validateOffchainParams(params: VersionedOffchainParams): void {\n const errors: string[] = [];\n\n if (params.timelockAssert <= 0n) {\n errors.push(\n `timelockAssert must be positive, got ${params.timelockAssert}`,\n );\n }\n if (params.timelockAssert > BigInt(UINT16_MAX)) {\n errors.push(\n `timelockAssert ${params.timelockAssert} exceeds uint16 max (${UINT16_MAX})`,\n );\n }\n\n if (params.timelockChallengeAssert <= 0n) {\n errors.push(\n `timelockChallengeAssert must be positive, got ${params.timelockChallengeAssert}`,\n );\n }\n\n if (params.tRefund <= 0) {\n errors.push(`tRefund must be positive, got ${params.tRefund}`);\n }\n\n if (params.tStale <= 0) {\n errors.push(`tStale must be positive, got ${params.tStale}`);\n }\n\n if (params.securityCouncilKeys.length === 0) {\n errors.push(\"securityCouncilKeys must not be empty\");\n }\n\n if (params.councilQuorum <= 0) {\n errors.push(`councilQuorum must be positive, got ${params.councilQuorum}`);\n }\n if (params.councilQuorum > params.securityCouncilKeys.length) {\n errors.push(\n `councilQuorum (${params.councilQuorum}) exceeds securityCouncilKeys count (${params.securityCouncilKeys.length})`,\n );\n }\n\n if (params.feeRate <= 0n) {\n errors.push(`feeRate must be positive, got ${params.feeRate}`);\n }\n\n if (params.minPeginFeeRate <= 0n) {\n errors.push(\n `minPeginFeeRate must be positive, got ${params.minPeginFeeRate}`,\n );\n }\n\n if (\n !Number.isInteger(params.proverCircuitVersion) ||\n params.proverCircuitVersion < 0 ||\n params.proverCircuitVersion > UINT16_MAX\n ) {\n errors.push(\n `proverCircuitVersion must be a uint16, got ${params.proverCircuitVersion}`,\n );\n }\n\n if (\n !Number.isInteger(params.minPrepeginDepth) ||\n params.minPrepeginDepth <= 0 ||\n params.minPrepeginDepth > UINT32_MAX\n ) {\n errors.push(\n `minPrepeginDepth must be a uint32 in [1, ${UINT32_MAX}], got ${params.minPrepeginDepth}`,\n );\n }\n\n if (params.babeTotalInstances <= 0) {\n errors.push(\n `babeTotalInstances must be positive, got ${params.babeTotalInstances}`,\n );\n }\n if (params.babeInstancesToFinalize <= 0) {\n errors.push(\n `babeInstancesToFinalize must be positive, got ${params.babeInstancesToFinalize}`,\n );\n }\n if (params.babeInstancesToFinalize > params.babeTotalInstances) {\n errors.push(\n `babeInstancesToFinalize (${params.babeInstancesToFinalize}) exceeds babeTotalInstances (${params.babeTotalInstances})`,\n );\n }\n\n if (\n params.minVpCommissionBps < 0 ||\n params.minVpCommissionBps > MAX_BASIS_POINTS\n ) {\n errors.push(\n `minVpCommissionBps must be in [0, ${MAX_BASIS_POINTS}], got ${params.minVpCommissionBps}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(\n `Invalid offchain protocol parameters: ${errors.join(\"; \")}`,\n );\n }\n}\n\n/**\n * Validate TBV protocol params returned from the contract.\n * @throws Error on invalid amounts or out-of-range bounded fields.\n */\nexport function validateTBVProtocolParams(params: TBVProtocolParams): void {\n const errors: string[] = [];\n\n if (params.minimumPegInAmount <= 0n) {\n errors.push(\n `minimumPegInAmount must be positive, got ${params.minimumPegInAmount}`,\n );\n }\n\n if (params.maxPegInAmount < params.minimumPegInAmount) {\n errors.push(\n `maxPegInAmount (${params.maxPegInAmount}) must be >= minimumPegInAmount (${params.minimumPegInAmount})`,\n );\n }\n\n if (params.pegInAckTimeout <= 0n) {\n errors.push(\n `pegInAckTimeout must be positive, got ${params.pegInAckTimeout}`,\n );\n }\n\n if (params.pegInActivationTimeout <= 0n) {\n errors.push(\n `pegInActivationTimeout must be positive, got ${params.pegInActivationTimeout}`,\n );\n }\n\n if (\n !Number.isInteger(params.maxHtlcOutputCount) ||\n params.maxHtlcOutputCount <= 0 ||\n params.maxHtlcOutputCount > UINT8_MAX\n ) {\n errors.push(\n `maxHtlcOutputCount must be an integer in [1, ${UINT8_MAX}], got ${params.maxHtlcOutputCount}`,\n );\n }\n\n if (\n typeof params.expiredPegInGraceBlocks !== \"bigint\" ||\n params.expiredPegInGraceBlocks <= 0n\n ) {\n errors.push(\n `expiredPegInGraceBlocks must be a positive bigint, got ${params.expiredPegInGraceBlocks}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(`Invalid TBV protocol parameters: ${errors.join(\"; \")}`);\n }\n}\n\n/**\n * Validate the full peg-in configuration after assembly.\n * Checks both TBV params and offchain params consistency, and the\n * top-level `offchainParamsVersion` (which originates from a separate\n * multicall result and so must be range-checked alongside the params it\n * names).\n */\nexport function validatePegInConfiguration(config: PegInConfiguration): void {\n validateTBVProtocolParams(config);\n validateOffchainParams(config.offchainParams);\n\n if (\n !Number.isInteger(config.offchainParamsVersion) ||\n config.offchainParamsVersion < 0 ||\n config.offchainParamsVersion > UINT32_MAX\n ) {\n throw new Error(\n `Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${config.offchainParamsVersion}`,\n );\n }\n\n // The contract enforces ≥ 1 (setter rejects 0); a 0 here means a\n // mis-decoded read or a pre-vaultCoreVersion contract — fail closed.\n assertValidVaultCoreVersion(\n config.activeVaultCoreVersion,\n \"ProtocolParams.activeVaultCoreVersion()\",\n );\n}\n","/**\n * Concrete BTCVaultRegistry reader using viem's readContract.\n *\n * This is an optional utility — callers can use their own implementation\n * of the VaultRegistryReader interface.\n */\n\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\n\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport { BTCVaultRegistryKeyEpochsABI } from \"../../contracts/abis/BTCVaultRegistryKeyEpochs.abi\";\nimport { assertOnChainBtcPubkey } from \"./onChainBtcPubkey\";\nimport { assertValidOffchainParamsVersion } from \"./protocol-params-validation\";\nimport type {\n KeyEpochs,\n OnChainBtcPubkey,\n VaultBasicInfo,\n VaultData,\n VaultProtocolInfo,\n VaultRegistryReader,\n} from \"./types\";\n\n/**\n * Inclusive upper bound the BTCVaultRegistry contract enforces on a vault\n * provider's commission (the contract check is `< 10000`).\n */\nconst MAX_VP_COMMISSION_BPS = 9999;\n\n/** Raw `getBtcVaultBasicInfo` tuple as decoded by viem. */\ntype RawVaultBasicInfo = {\n depositor: Address;\n depositorBtcPubKey: Hex;\n amount: bigint;\n vaultProvider: Address;\n status: number;\n applicationEntryPoint: Address;\n createdAt: bigint;\n};\n\n/** Raw `getBtcVaultProtocolInfo` tuple as decoded by viem. */\ntype RawVaultProtocolInfo = {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n claimExpiredUntil: bigint;\n vaultCoreVersion: number;\n};\n\nfunction mapVaultBasicInfo(result: RawVaultBasicInfo): VaultBasicInfo {\n return {\n depositor: result.depositor,\n depositorBtcPubKey: result.depositorBtcPubKey,\n amount: result.amount,\n vaultProvider: result.vaultProvider,\n status: result.status,\n applicationEntryPoint: result.applicationEntryPoint,\n createdAt: result.createdAt,\n };\n}\n\nfunction mapVaultProtocolInfo(result: RawVaultProtocolInfo): VaultProtocolInfo {\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n return {\n depositorSignedPeginTx: result.depositorSignedPeginTx,\n universalChallengersVersion: result.universalChallengersVersion,\n appVaultKeepersVersion: result.appVaultKeepersVersion,\n offchainParamsVersion,\n verifiedAt: result.verifiedAt,\n depositorWotsPkHash: result.depositorWotsPkHash,\n hashlock: result.hashlock,\n htlcVout: result.htlcVout,\n depositorPopSignature: result.depositorPopSignature,\n prePeginTxHash: result.prePeginTxHash,\n vaultProviderCommissionBps: result.vaultProviderCommissionBps,\n claimExpiredUntil: result.claimExpiredUntil,\n vaultCoreVersion: result.vaultCoreVersion,\n };\n}\n\n/**\n * Exclusive upper bound for a `uint64` epoch.\n *\n * viem does not range-check a decoded `uint64`, so a misaligned decode can\n * hand back a value far larger than the field can hold. Rejecting those is\n * cheap defence in depth against a mis-decode of the extended ABI.\n *\n * The state this is load-bearing for is narrower than \"a registry that predates\n * RFC-006\". Against a *fully* pre-RFC-006 registry the path fails closed on its\n * own: `resolveParticipantKeysAtEpochs` goes on to call\n * `getOperationBtcKeyAtEpochOrGenesis` on ApplicationRegistry and\n * ProtocolParams, which do not exist there, so the multicall reverts and these\n * epochs are never used. The reachable gap is a registry that *has* the\n * operation-key getters but whose `BTCVaultProtocolInfo` struct is not\n * extended — there the tail-data epochs resolve with no error at all, and this\n * range check is the only thing looking at them.\n *\n * Even for that case it is only a backstop, and a weak one: a misaligned decode\n * can land on a small, plausible-looking integer this range accepts. Correctness\n * rests on only ever pointing at an RFC-006 registry, which is a deployment\n * precondition rather than something this call can establish — see\n * https://github.com/babylonlabs-io/babylon-toolkit/issues/2192 for where that\n * check is owned, and `BTCVaultRegistryKeyEpochs.abi.ts` for the decode hazard.\n */\nconst UINT64_EXCLUSIVE_UPPER_BOUND = 1n << 64n;\n\n/**\n * The epoch a vault provider's registration key is bonded at.\n *\n * A provider's operation-key history is append-only and every appended version\n * is stamped at epoch 1 or later, so epoch 0 always resolves to the key set at\n * registration. This is what lets `getOperationBtcKeyAtEpoch` stand in for the\n * removed `getVaultProviderBTCKey` getter.\n */\nconst VP_GENESIS_KEY_EPOCH = 0n;\n\nfunction assertEpochInRange(\n value: bigint,\n field: string,\n vaultId: Hex,\n): bigint {\n if (value < 0n || value >= UINT64_EXCLUSIVE_UPPER_BOUND) {\n throw new Error(\n `getBtcVaultProtocolInfo returned ${field}=${value} for vault ${vaultId}, ` +\n `outside the uint64 range — the registry may predate RFC-006`,\n );\n }\n return value;\n}\n\nfunction mapKeyEpochs(result: KeyEpochs, vaultId: Hex): KeyEpochs {\n return {\n vpKeyEpoch: assertEpochInRange(result.vpKeyEpoch, \"vpKeyEpoch\", vaultId),\n appKeeperKeyEpoch: assertEpochInRange(\n result.appKeeperKeyEpoch,\n \"appKeeperKeyEpoch\",\n vaultId,\n ),\n ucKeyEpoch: assertEpochInRange(result.ucKeyEpoch, \"ucKeyEpoch\", vaultId),\n };\n}\n\n/**\n * Concrete vault registry reader using viem.\n *\n * Usage:\n * ```ts\n * const reader = new ViemVaultRegistryReader(publicClient, registryAddress);\n * const data = await reader.getVaultData(vaultId);\n * ```\n */\nexport class ViemVaultRegistryReader implements VaultRegistryReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n /**\n * Read the VP's **genesis** (registration) x-only BTC pubkey — the key bonded\n * at version 0, which never moves when the operator rotates.\n *\n * Resolved as \"the operation key at epoch 0\" rather than through the\n * dedicated `getVaultProviderBTCKey` getter, which\n * https://github.com/babylonlabs-io/vault-contracts-aave-v4/pull/539 removes.\n * Epoch 0 predates any rotation — appended versions are stamped at epoch 1 or\n * later — so it resolves to the registration key, and the contracts team has\n * confirmed that is a property we can rely on rather than an implementation\n * detail. The devnet comparison behind that claim — both getters returning the\n * identical key for a provider that *has* rotated, while\n * `getCurrentOperationBtcKey` differed — is recorded in\n * https://github.com/babylonlabs-io/babylon-toolkit/issues/2188.\n *\n * This makes the read RFC-006-only, where the removed getter also existed on a\n * legacy registry. That costs nothing: every caller of this method already\n * resolves participant keys through `OperationKeyReader`, so all of them\n * require an RFC-006 registry regardless.\n *\n * Validates length, hex form, and secp256k1 curve membership before minting\n * the brand. Returns 64-char lowercase hex without the `0x` prefix.\n */\n async getVaultProviderGenesisBtcPubKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getOperationBtcKeyAtEpoch\",\n args: [vpAddress, VP_GENESIS_KEY_EPOCH],\n })) as Hex;\n return assertOnChainBtcPubkey(\n result,\n `getOperationBtcKeyAtEpoch (vp=${vpAddress}, epoch=${VP_GENESIS_KEY_EPOCH})`,\n );\n }\n\n /**\n * Read a vault provider's *current* RFC-006 operation BTC key.\n *\n * Falls back on-chain to the registration key when the provider has never\n * rotated, so this returns the same value as\n * `getVaultProviderGenesisBtcPubKey` until the first rotation.\n *\n * This is the key the VP's server signs its BIP-322 auth tokens with — a\n * live per-operator identity, not a per-vault binding, so the auth pin uses\n * the current key rather than any vault's frozen epoch.\n */\n async getCurrentVaultProviderOperationBtcKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getCurrentOperationBtcKey\",\n args: [vpAddress],\n })) as Hex;\n return assertOnChainBtcPubkey(\n result,\n `getCurrentOperationBtcKey (vp=${vpAddress})`,\n );\n }\n\n /**\n * Read a vault's frozen RFC-006 operation-key epochs.\n *\n * Reads `getBtcVaultProtocolInfo` through the **extended** ABI, which is only\n * valid against an RFC-006 registry: against one whose `BTCVaultProtocolInfo`\n * struct is not extended this call does not fail for a populated vault, it\n * silently returns three words of tail data as epochs. Nothing here can detect\n * that, so the guarantee is a deployment one — every network this ships to has\n * the RFC-006 getters, and mainnet is a fresh RFC-006 deploy.\n *\n * A registry missing the operation-key getters entirely is the *safer* of the\n * two cases: `resolveParticipantKeysAtEpochs` reverts downstream and these\n * epochs never reach key resolution. See {@link UINT64_EXCLUSIVE_UPPER_BOUND}\n * for which state the range check actually guards, and\n * `BTCVaultRegistryKeyEpochs.abi.ts` for the decode hazard.\n */\n async getVaultKeyEpochs(vaultId: Hex): Promise<KeyEpochs> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryKeyEpochsABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as unknown as KeyEpochs;\n\n return mapKeyEpochs(result, vaultId);\n }\n\n async getVaultKeyEpochsBatch(vaultIds: readonly Hex[]): Promise<KeyEpochs[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryKeyEpochsABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info, i) =>\n mapKeyEpochs(info as unknown as KeyEpochs, vaultIds[i]),\n );\n }\n\n async getVaultBasicInfo(vaultId: Hex): Promise<VaultBasicInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n })) as RawVaultBasicInfo;\n\n return mapVaultBasicInfo(result);\n }\n\n async getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as RawVaultProtocolInfo;\n\n return mapVaultProtocolInfo(result);\n }\n\n async getProtocolInfoBatch(\n vaultIds: readonly Hex[],\n ): Promise<VaultProtocolInfo[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info, i) => {\n const result = info as unknown as RawVaultProtocolInfo;\n if (\n !result.depositorSignedPeginTx ||\n result.depositorSignedPeginTx === \"0x\"\n ) {\n // An empty record is not proof the vault is absent: a lagging RPC\n // node returns HTTP 200 with a zero struct, so no retry below this\n // layer can see it. Single-shot is only safe because the finality\n // gate (`waitForPeginRegistrationDepth`) runs first on the deposit\n // path — move this ahead of it and the read-after-write race returns.\n // The vault app matches this message to render \"still confirming\".\n throw new Error(\n `Vault ${vaultIds[i]} not found on-chain or has no pegin transaction`,\n );\n }\n return mapVaultProtocolInfo(result);\n });\n }\n\n /**\n * Read the protocol pegin fee (in wei) for a given vault provider.\n * Mirrors the `getPegInFee(address)` view on BTCVaultRegistry.\n */\n async getPegInFee(vaultProvider: Address): Promise<bigint> {\n return (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getPegInFee\",\n args: [vaultProvider],\n })) as bigint;\n }\n\n /**\n * Read a vault provider's current commission in basis points from\n * BTCVaultRegistry. The contract enforces `commissionBps < 10000`, so the\n * legitimate range is `[0, 9999]`; anything outside indicates a wrong\n * contract address or ABI drift and is surfaced as an error rather than\n * trusted.\n */\n async getVaultProviderCommission(vaultProvider: Address): Promise<number> {\n // viem infers `number` from the `uint16` return in the `as const` ABI.\n const bps = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderCommission\",\n args: [vaultProvider],\n });\n\n if (!Number.isInteger(bps) || bps < 0 || bps > MAX_VP_COMMISSION_BPS) {\n throw new Error(\n `getVaultProviderCommission returned ${bps} bps for ${vaultProvider}, ` +\n `outside the protocol range [0, ${MAX_VP_COMMISSION_BPS}]`,\n );\n }\n\n return bps;\n }\n\n async getVaultData(vaultId: Hex): Promise<VaultData> {\n // One round-trip for both structs (hard-fail): they feed signing/refund/\n // broadcast rebinds, so reading them in a single multicall also pins both\n // to the same block — no basic/protocol skew across two `eth_call`s.\n const [basicRaw, protocolRaw] = await this.publicClient.multicall({\n contracts: [\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n },\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n },\n ],\n allowFailure: false,\n });\n\n const basic = mapVaultBasicInfo(basicRaw);\n const protocol = mapVaultProtocolInfo(protocolRaw);\n\n if (\n !protocol.depositorSignedPeginTx ||\n protocol.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultId} not found on-chain or has no pegin transaction`,\n );\n }\n\n return { basic, protocol };\n }\n\n}\n","/**\n * Mempool API Client\n *\n * Client for interacting with mempool.space API for Bitcoin network operations.\n * Used for broadcasting transactions and fetching UTXO data.\n *\n * @module clients/mempool/mempoolApi\n */\n\nimport { combineAbortSignals } from \"../../utils/abortSignals\";\nimport {\n BITCOIN_ADDRESS_RE,\n HEX_RE,\n KNOWN_SCRIPT_PREFIXES,\n TXID_RE,\n} from \"../../utils/validation\";\n\nimport type {\n MempoolUTXO,\n NetworkFees,\n OutspendStatus,\n TxInfo,\n UtxoInfo,\n} from \"./types\";\n\n/** Maximum valid satoshi value: 21 million BTC × 10^8 sats/BTC */\nconst MAX_SATOSHIS = 21_000_000 * 1e8;\n\n/** Timeout for mempool API requests — prevents indefinite hangs from stalled endpoints */\nconst MEMPOOL_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch wrapper with AbortController-based timeout.\n * Ensures all mempool API requests fail bounded rather than hanging indefinitely.\n */\nasync function fetchWithTimeout(\n url: string,\n options?: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n MEMPOOL_REQUEST_TIMEOUT_MS,\n );\n\n // Compose timeout signal with any caller-supplied signal so both can cancel\n const signals = [controller.signal, options?.signal].filter(\n Boolean,\n ) as AbortSignal[];\n const combined = combineAbortSignals(signals);\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers.\n // For the same reason the composed signal keeps its listeners attached on\n // the success path: detaching them would stop the timeout from aborting a\n // stalled body read.\n return await fetch(url, {\n ...options,\n signal: combined.signal,\n });\n } catch (error) {\n clearTimeout(timeoutId);\n combined.cleanup();\n if (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n error.name === \"AbortError\"\n ) {\n throw new Error(\n `Mempool API request timed out after ${MEMPOOL_REQUEST_TIMEOUT_MS}ms: ${url}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Maximum sane fee rate in sat/vByte.\n * The April 2024 Runes spike peaked around 1,805 sat/vB — 10,000 provides ample headroom.\n */\nconst MAX_FEE_RATE = 10_000;\n\nfunction isValidSatoshiValue(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_SATOSHIS;\n}\n\nfunction isValidFeeRate(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_FEE_RATE;\n}\n\nfunction isValidVout(vout: number, outputCount?: number): boolean {\n if (!Number.isInteger(vout) || vout < 0) return false;\n return outputCount === undefined || vout < outputCount;\n}\n\n\nfunction assertValidTxid(txid: string): void {\n if (!TXID_RE.test(txid)) {\n throw new Error(`Invalid transaction ID format: ${txid}`);\n }\n}\n\nfunction assertValidAddress(address: string): void {\n if (!BITCOIN_ADDRESS_RE.test(address)) {\n throw new Error(`Invalid Bitcoin address format: ${address}`);\n }\n}\n\nfunction assertValidScriptPubKey(scriptPubKey: string, context: string): void {\n if (!HEX_RE.test(scriptPubKey)) {\n throw new Error(\n `Invalid scriptPubKey: not valid hex for ${context}`,\n );\n }\n const matchesKnownType = KNOWN_SCRIPT_PREFIXES.some((prefix) =>\n scriptPubKey.toLowerCase().startsWith(prefix),\n );\n if (!matchesKnownType) {\n throw new Error(\n `Unrecognized scriptPubKey type for ${context}: ` +\n `prefix ${scriptPubKey.slice(0, 6)} does not match any known Bitcoin script type`,\n );\n }\n}\n\n/**\n * Default mempool API URLs by network.\n */\nexport const MEMPOOL_API_URLS = {\n mainnet: \"https://mempool.space/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.space/signet/api\",\n} as const;\n\n/**\n * Fetch wrapper with error handling.\n */\nasync function fetchApi<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n try {\n const response = await fetchWithTimeout(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else {\n return (await response.text()) as T;\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to fetch from mempool API: ${error.message}`);\n }\n throw new Error(\"Failed to fetch from mempool API: Unknown error\");\n }\n}\n\n/**\n * Push a signed transaction to the Bitcoin network.\n *\n * @param txHex - The signed transaction hex string\n * @param apiUrl - Mempool API base URL\n * @returns The transaction ID\n * @throws Error if broadcasting fails\n */\nexport async function pushTx(txHex: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx`, {\n method: \"POST\",\n body: txHex,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // Try to extract error message from response using robust JSON parsing\n let message: string | undefined;\n try {\n const errorJson = JSON.parse(errorText);\n message = errorJson.message ?? errorJson.error;\n } catch {\n // Not JSON, use raw text\n message = errorText;\n }\n throw new Error(\n message || `Failed to broadcast transaction: ${response.statusText}`,\n );\n }\n\n // Response is the transaction ID (plain text)\n const txId = await response.text();\n return txId;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to broadcast BTC transaction: ${error.message}`);\n }\n throw new Error(\"Failed to broadcast BTC transaction: Unknown error\");\n }\n}\n\n/**\n * Get transaction information from mempool.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns Transaction information\n */\nexport async function getTxInfo(txid: string, apiUrl: string): Promise<TxInfo> {\n assertValidTxid(txid);\n return fetchApi<TxInfo>(`${apiUrl}/tx/${txid}`);\n}\n\n/**\n * Get the current block tip height.\n *\n * Source: mempool.space API — `GET /api/blocks/tip/height` returns the height\n * of the most recent block as a plain-text integer.\n *\n * @param apiUrl - Mempool API base URL\n * @returns The height of the most recent block\n * @throws Error if the response is not a whole number\n */\nexport async function getTipHeight(apiUrl: string): Promise<number> {\n const raw = await fetchApi<string>(`${apiUrl}/blocks/tip/height`);\n const trimmed = raw.trim();\n if (!/^\\d+$/.test(trimmed)) {\n throw new Error(\n `Mempool API returned an invalid block tip height: \"${raw}\"`,\n );\n }\n return Number.parseInt(trimmed, 10);\n}\n\n/**\n * Get the spend status of a specific transaction output.\n *\n * Calls the esplora-compatible `GET /tx/{txid}/outspend/{vout}` endpoint\n * (mempool.space backend, mempool/electrs `rest.rs`). Returns\n * `{ spent: false }` for an unspent output, or\n * `{ spent: true, txid, vin, status }` when the output has been spent.\n *\n * @param txid - The transaction id whose output is being checked (no 0x prefix)\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns The output's spend status\n */\nexport async function getOutspend(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<OutspendStatus> {\n assertValidTxid(txid);\n if (!isValidVout(vout)) {\n throw new Error(`Invalid vout ${vout} for transaction ${txid}`);\n }\n return fetchApi<OutspendStatus>(`${apiUrl}/tx/${txid}/outspend/${vout}`);\n}\n\n/**\n * Get the hex representation of a transaction.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns The transaction hex string\n * @throws Error if the request fails or transaction is not found\n */\nexport async function getTxHex(txid: string, apiUrl: string): Promise<string> {\n assertValidTxid(txid);\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx/${txid}/hex`);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n return await response.text();\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to get transaction hex for ${txid}: ${error.message}`);\n }\n throw new Error(`Failed to get transaction hex for ${txid}: Unknown error`);\n }\n}\n\n/**\n * Get UTXO information for a specific transaction output.\n *\n * This is used for constructing PSBTs where we need the witnessUtxo data.\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param txid - The transaction ID containing the UTXO\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns UTXO information with value and scriptPubKey\n */\nexport async function getUtxoInfo(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<UtxoInfo> {\n assertValidTxid(txid);\n const txInfo = await getTxInfo(txid, apiUrl);\n\n if (!isValidVout(vout, txInfo.vout.length)) {\n throw new Error(\n `Invalid vout ${vout} for transaction ${txid} (has ${txInfo.vout.length} outputs)`,\n );\n }\n\n const output = txInfo.vout[vout];\n if (!isValidSatoshiValue(output.value)) {\n throw new Error(`Invalid UTXO value ${output.value} for ${txid}:${vout}`);\n }\n assertValidScriptPubKey(output.scriptpubkey, `${txid}:${vout}`);\n\n return {\n txid,\n vout,\n value: output.value,\n scriptPubKey: output.scriptpubkey,\n };\n}\n\n/**\n * Get all UTXOs for a Bitcoin address.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of UTXOs sorted by value (largest first)\n */\nexport async function getAddressUtxos(\n address: string,\n apiUrl: string,\n): Promise<MempoolUTXO[]> {\n assertValidAddress(address);\n try {\n // Fetch UTXOs for the address\n const utxos = await fetchApi<\n {\n txid: string;\n vout: number;\n value: number;\n status: {\n confirmed: boolean;\n };\n }[]\n >(`${apiUrl}/address/${address}/utxo`);\n\n // Fetch scriptPubKey for the address\n const addressInfo = await fetchApi<{\n isvalid: boolean;\n scriptPubKey: string;\n }>(`${apiUrl}/v1/validate-address/${address}`);\n\n if (!addressInfo.isvalid) {\n throw new Error(\n `Invalid Bitcoin address: ${address}. Mempool API validation failed.`,\n );\n }\n assertValidScriptPubKey(addressInfo.scriptPubKey, address);\n\n // Validate UTXO fields from the listing endpoint.\n // Per-UTXO cross-verification against /tx/{txid} is intentionally NOT done\n // here — it would be expensive (N API calls) and redundant: the broadcast\n // path already verifies each selected input via getUtxoInfo before signing.\n // Both endpoints come from the same mempool API, so cross-checking one\n // against the other on the same server does not add real security.\n for (const utxo of utxos) {\n assertValidTxid(utxo.txid);\n if (!isValidVout(utxo.vout)) {\n throw new Error(`Invalid vout ${utxo.vout} for ${utxo.txid}`);\n }\n if (!isValidSatoshiValue(utxo.value)) {\n throw new Error(\n `Invalid UTXO value ${utxo.value} for ${utxo.txid}:${utxo.vout}`,\n );\n }\n }\n\n // Sort by value (largest first) and map to our UTXO format\n const sortedUTXOs = utxos.sort((a, b) => b.value - a.value);\n\n return sortedUTXOs.map((utxo) => ({\n txid: utxo.txid,\n vout: utxo.vout,\n value: utxo.value,\n scriptPubKey: addressInfo.scriptPubKey,\n confirmed: utxo.status.confirmed,\n }));\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(\n `Failed to get UTXOs for address ${address}: ${error.message}`,\n );\n }\n throw new Error(\n `Failed to get UTXOs for address ${address}: Unknown error`,\n );\n }\n}\n\n/**\n * Get the mempool API URL for a given network.\n *\n * @param network - Bitcoin network (mainnet, testnet, signet)\n * @returns The mempool API URL\n */\nexport function getMempoolApiUrl(\n network: \"mainnet\" | \"testnet\" | \"signet\",\n): string {\n return MEMPOOL_API_URLS[network];\n}\n\n/**\n * Transaction summary from address transactions endpoint.\n */\nexport interface AddressTx {\n txid: string;\n status: {\n confirmed: boolean;\n block_height?: number;\n };\n}\n\n/**\n * Get recent transactions for a Bitcoin address.\n *\n * Returns the last 25 confirmed transactions plus any unconfirmed (mempool) transactions.\n * This is useful for checking if a specific transaction has been broadcast.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of recent transactions\n */\nexport async function getAddressTxs(\n address: string,\n apiUrl: string,\n): Promise<AddressTx[]> {\n assertValidAddress(address);\n return fetchApi<AddressTx[]>(`${apiUrl}/address/${address}/txs`);\n}\n\n/**\n * Fetches Bitcoin network fee recommendations from mempool.space API.\n *\n * @param apiUrl - Mempool API base URL\n * @returns Fee rates in sat/vbyte for different confirmation times\n * @throws Error if request fails or returns invalid data\n *\n * @see https://mempool.space/docs/api/rest#get-recommended-fees\n */\nexport async function getNetworkFees(apiUrl: string): Promise<NetworkFees> {\n const response = await fetchWithTimeout(`${apiUrl}/v1/fees/recommended`);\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch network fees: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n\n const feeFields = [\n \"fastestFee\",\n \"halfHourFee\",\n \"hourFee\",\n \"economyFee\",\n \"minimumFee\",\n ] as const;\n\n for (const field of feeFields) {\n if (!isValidFeeRate(data[field])) {\n throw new Error(\n `Invalid fee rate ${field}=${data[field]} from mempool API: expected a positive number ≤ ${MAX_FEE_RATE}`,\n );\n }\n }\n\n if (\n data.minimumFee > data.economyFee ||\n data.economyFee > data.hourFee ||\n data.hourFee > data.halfHourFee ||\n data.halfHourFee > data.fastestFee\n ) {\n throw new Error(\n `Fee rate ordering violation from mempool API: expected ` +\n `minimumFee (${data.minimumFee}) <= economyFee (${data.economyFee}) <= ` +\n `hourFee (${data.hourFee}) <= halfHourFee (${data.halfHourFee}) <= ` +\n `fastestFee (${data.fastestFee}).`,\n );\n }\n\n return data as NetworkFees;\n}\n\n"],"names":["BIP322_TAG","TAPTWEAK_TAG","X_ONLY_PUBKEY_SIZE","SCHNORR_SIG_SIZE","COMPRESSED_PUBKEY_SIZE","P2WPKH_ENCODED_SIG_MIN","P2WPKH_ENCODED_SIG_MAX","ZERO_SATS","BIP322_TX_VERSION","BIP322_TX_LOCKTIME","BIP322_INPUT_SEQUENCE","TO_SPEND_PREVOUT_TXID_BYTES","TO_SPEND_PREVOUT_INDEX","TO_SPEND_OUTPUT_INDEX","OP_0","OP_PUSHBYTES_32","OP_RETURN","taggedHash","tag","data","tagBytes","tagHash","sha256","preimage","tweakXOnlyKey","xOnly","tweak","tweaked","ecc","buildToSignTransaction","messageBytes","scriptPubKey","messageHash","toSpend","Transaction","scriptSig","Buffer","toSign","verifyBip322Simple","xOnlyPubkey","signature","hashType","p2tr","payments","sighash","tweakedXOnly","verifyBip322P2wpkhSimple","compressedPubkey","encodedSignature","bscript","p2wpkh","scriptCode","UINT16_MAX","MAX_BASIS_POINTS","UINT32_MAX","UINT8_MAX","assertValidOffchainParamsVersion","version","validateOffchainParams","params","errors","validateTBVProtocolParams","validatePegInConfiguration","config","assertValidVaultCoreVersion","MAX_VP_COMMISSION_BPS","mapVaultBasicInfo","result","mapVaultProtocolInfo","offchainParamsVersion","UINT64_EXCLUSIVE_UPPER_BOUND","VP_GENESIS_KEY_EPOCH","assertEpochInRange","value","field","vaultId","mapKeyEpochs","ViemVaultRegistryReader","publicClient","contractAddress","vpAddress","BTCVaultRegistryABI","assertOnChainBtcPubkey","BTCVaultRegistryKeyEpochsABI","vaultIds","info","vaultProvider","bps","basicRaw","protocolRaw","basic","protocol","MAX_SATOSHIS","MEMPOOL_REQUEST_TIMEOUT_MS","fetchWithTimeout","url","options","controller","timeoutId","signals","combined","combineAbortSignals","error","MAX_FEE_RATE","isValidSatoshiValue","isValidFeeRate","isValidVout","vout","outputCount","assertValidTxid","txid","TXID_RE","assertValidAddress","address","BITCOIN_ADDRESS_RE","assertValidScriptPubKey","context","HEX_RE","KNOWN_SCRIPT_PREFIXES","prefix","MEMPOOL_API_URLS","fetchApi","response","errorText","contentType","pushTx","txHex","apiUrl","message","errorJson","getTxInfo","getTipHeight","raw","trimmed","getOutspend","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","feeFields"],"mappings":";;;;;;;;;AA6CA,MAAMA,IAAa,0BAGbC,IAAe,YAEfC,IAAqB,IACrBC,IAAmB,IAEnBC,IAAyB,IAQlBC,KAAyB,IACzBC,KAAyB,IAQhCC,IAAY,GAIZC,IAAoB,GACpBC,IAAqB,GACrBC,IAAwB,GAExBC,KAA8B,IAC9BC,KAAyB,YAEzBC,KAAwB,GACxBC,KAAO,GAEPC,KAAkB,IAClBC,KAAY;AAMlB,SAASC,EAAWC,GAAaC,GAA8B;AAC7D,QAAMC,IAAW,IAAI,cAAc,OAAOF,CAAG,GACvCG,IAAUC,EAAOF,CAAQ,GACzBG,IAAW,IAAI,WAAWF,EAAQ,SAAS,IAAIF,EAAK,MAAM;AAChE,SAAAI,EAAS,IAAIF,GAAS,CAAC,GACvBE,EAAS,IAAIF,GAASA,EAAQ,MAAM,GACpCE,EAAS,IAAIJ,GAAME,EAAQ,SAAS,CAAC,GAC9BC,EAAOC,CAAQ;AACxB;AAYA,SAASC,GAAcC,GAAsC;AAC3D,MAAIA,EAAM,WAAWvB,EAAoB,QAAO;AAChD,QAAMwB,IAAQT,EAAWhB,GAAcwB,CAAK,GACtCE,IAAUC,EAAI,mBAAmBH,GAAOC,CAAK;AACnD,SAAOC,IAAUA,EAAQ,cAAc;AACzC;AAOA,SAASE,EACPC,GACAC,GACa;AACb,QAAMC,IAAcf,EAAWjB,GAAY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AAA,MACR,iCAAiCA,EAAS,MAAM,IAAIA,EAAS,UAAU;AAAA,IAAA;AAI3E,QAAMvG,IAAO,MAAMuG,EAAS,KAAA,GAEtB2B,IAAY;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,aAAW3E,KAAS2E;AAClB,QAAI,CAAC5C,GAAetF,EAAKuD,CAAK,CAAC;AAC7B,YAAM,IAAI;AAAA,QACR,oBAAoBA,CAAK,IAAIvD,EAAKuD,CAAK,CAAC,mDAAmD6B,CAAY;AAAA,MAAA;AAK7G,MACEpF,EAAK,aAAaA,EAAK,cACvBA,EAAK,aAAaA,EAAK,WACvBA,EAAK,UAAUA,EAAK,eACpBA,EAAK,cAAcA,EAAK;AAExB,UAAM,IAAI;AAAA,MACR,sEACiBA,EAAK,UAAU,oBAAoBA,EAAK,UAAU,iBACrDA,EAAK,OAAO,qBAAqBA,EAAK,WAAW,oBAC9CA,EAAK,UAAU;AAAA,IAAA;AAIpC,SAAOA;AACT;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const Q=require("@bitcoin-js/tiny-secp256k1-asmjs"),a=require("bitcoinjs-lib"),E=require("./sha2-DsrLC4NM.cjs"),u=require("buffer"),c=require("./BTCVaultRegistry.abi-z7d_eP22.cjs"),$=require("./BTCVaultRegistryKeyEpochs.abi-_NERAdc5.cjs"),A=require("./onChainBtcPubkey-C_a2L3kL.cjs"),Y=require("./constants-DU5CGcqO.cjs"),f=require("./validation-CDbOaDj7.cjs");function Z(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const o=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,o.get?o:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const m=Z(Q),J="BIP0322-signed-message",tt="TapTweak",K=32,et=64,nt=33,k=71,R=72,d=0,B=0,V=0,C=0,ot=32,rt=4294967295,it=0,st=0,at=32,ct=106;function U(t,e){const n=new TextEncoder().encode(t),o=E.sha256(n),i=new Uint8Array(o.length*2+e.length);return i.set(o,0),i.set(o,o.length),i.set(e,o.length*2),E.sha256(i)}function ut(t){if(t.length!==K)return null;const e=U(tt,t),n=m.xOnlyPointAddTweak(t,e);return n?n.xOnlyPubkey:null}function H(t,e){const n=U(J,t),o=new a.Transaction;o.version=B,o.locktime=V;const i=u.Buffer.concat([u.Buffer.from([st,at]),u.Buffer.from(n)]);o.addInput(u.Buffer.alloc(ot,0),rt,C,i),o.addOutput(e,d);const r=new a.Transaction;return r.version=B,r.locktime=V,r.addInput(o.getHash(),it,C),r.addOutput(u.Buffer.from([ct]),d),r}function lt(t,e,n,o=a.Transaction.SIGHASH_DEFAULT){if(e.length!==K||n.length!==et||o!==a.Transaction.SIGHASH_DEFAULT&&o!==a.Transaction.SIGHASH_ALL)return!1;try{const i=a.payments.p2tr({internalPubkey:u.Buffer.from(e)});if(!i.output)return!1;const r=i.output,g=H(t,r).hashForWitnessV1(0,[r],[d],o),p=ut(e);return p?m.verifySchnorr(g,p,n):!1}catch{return!1}}function ft(t,e,n){if(e.length!==nt||n.length<k||n.length>R)return!1;try{if(!m.isPointCompressed(e))return!1;const{signature:o,hashType:i}=a.script.signature.decode(u.Buffer.from(n));if(!a.script.signature.encode(o,i).equals(u.Buffer.from(n))||i!==a.Transaction.SIGHASH_ALL)return!1;const r=a.payments.p2wpkh({pubkey:u.Buffer.from(e)});if(!r.output||!r.hash)return!1;const s=H(t,r.output),g=a.payments.p2pkh({hash:r.hash}).output;if(!g)return!1;const p=s.hashForWitnessV0(0,g,d,i);return m.verify(p,e,o,!0)}catch{return!1}}const w=65535,_=1e4,P=4294967295,v=255;function M(t){if(!Number.isInteger(t)||t<0||t>P)throw new Error(`Invalid offchainParamsVersion from contract: must be a uint32, got ${t}`)}function D(t){const e=[];if(t.timelockAssert<=0n&&e.push(`timelockAssert must be positive, got ${t.timelockAssert}`),t.timelockAssert>BigInt(w)&&e.push(`timelockAssert ${t.timelockAssert} exceeds uint16 max (${w})`),t.timelockChallengeAssert<=0n&&e.push(`timelockChallengeAssert must be positive, got ${t.timelockChallengeAssert}`),t.tRefund<=0&&e.push(`tRefund must be positive, got ${t.tRefund}`),t.tStale<=0&&e.push(`tStale must be positive, got ${t.tStale}`),t.securityCouncilKeys.length===0&&e.push("securityCouncilKeys must not be empty"),t.councilQuorum<=0&&e.push(`councilQuorum must be positive, got ${t.councilQuorum}`),t.councilQuorum>t.securityCouncilKeys.length&&e.push(`councilQuorum (${t.councilQuorum}) exceeds securityCouncilKeys count (${t.securityCouncilKeys.length})`),t.feeRate<=0n&&e.push(`feeRate must be positive, got ${t.feeRate}`),t.minPeginFeeRate<=0n&&e.push(`minPeginFeeRate must be positive, got ${t.minPeginFeeRate}`),(!Number.isInteger(t.proverCircuitVersion)||t.proverCircuitVersion<0||t.proverCircuitVersion>w)&&e.push(`proverCircuitVersion must be a uint16, got ${t.proverCircuitVersion}`),(!Number.isInteger(t.minPrepeginDepth)||t.minPrepeginDepth<=0||t.minPrepeginDepth>P)&&e.push(`minPrepeginDepth must be a uint32 in [1, ${P}], got ${t.minPrepeginDepth}`),t.babeTotalInstances<=0&&e.push(`babeTotalInstances must be positive, got ${t.babeTotalInstances}`),t.babeInstancesToFinalize<=0&&e.push(`babeInstancesToFinalize must be positive, got ${t.babeInstancesToFinalize}`),t.babeInstancesToFinalize>t.babeTotalInstances&&e.push(`babeInstancesToFinalize (${t.babeInstancesToFinalize}) exceeds babeTotalInstances (${t.babeTotalInstances})`),(t.minVpCommissionBps<0||t.minVpCommissionBps>_)&&e.push(`minVpCommissionBps must be in [0, ${_}], got ${t.minVpCommissionBps}`),e.length>0)throw new Error(`Invalid offchain protocol parameters: ${e.join("; ")}`)}function X(t){const e=[];if(t.minimumPegInAmount<=0n&&e.push(`minimumPegInAmount must be positive, got ${t.minimumPegInAmount}`),t.maxPegInAmount<t.minimumPegInAmount&&e.push(`maxPegInAmount (${t.maxPegInAmount}) must be >= minimumPegInAmount (${t.minimumPegInAmount})`),t.pegInAckTimeout<=0n&&e.push(`pegInAckTimeout must be positive, got ${t.pegInAckTimeout}`),t.pegInActivationTimeout<=0n&&e.push(`pegInActivationTimeout must be positive, got ${t.pegInActivationTimeout}`),(!Number.isInteger(t.maxHtlcOutputCount)||t.maxHtlcOutputCount<=0||t.maxHtlcOutputCount>v)&&e.push(`maxHtlcOutputCount must be an integer in [1, ${v}], got ${t.maxHtlcOutputCount}`),(typeof t.expiredPegInGraceBlocks!="bigint"||t.expiredPegInGraceBlocks<=0n)&&e.push(`expiredPegInGraceBlocks must be a positive bigint, got ${t.expiredPegInGraceBlocks}`),e.length>0)throw new Error(`Invalid TBV protocol parameters: ${e.join("; ")}`)}function ht(t){if(X(t),D(t.offchainParams),!Number.isInteger(t.offchainParamsVersion)||t.offchainParamsVersion<0||t.offchainParamsVersion>P)throw new Error(`Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${t.offchainParamsVersion}`);Y.assertValidVaultCoreVersion(t.activeVaultCoreVersion,"ProtocolParams.activeVaultCoreVersion()")}const S=9999;function O(t){return{depositor:t.depositor,depositorBtcPubKey:t.depositorBtcPubKey,amount:t.amount,vaultProvider:t.vaultProvider,status:t.status,applicationEntryPoint:t.applicationEntryPoint,createdAt:t.createdAt}}function b(t){const e=Number(t.offchainParamsVersion);return M(e),{depositorSignedPeginTx:t.depositorSignedPeginTx,universalChallengersVersion:t.universalChallengersVersion,appVaultKeepersVersion:t.appVaultKeepersVersion,offchainParamsVersion:e,verifiedAt:t.verifiedAt,depositorWotsPkHash:t.depositorWotsPkHash,hashlock:t.hashlock,htlcVout:t.htlcVout,depositorPopSignature:t.depositorPopSignature,prePeginTxHash:t.prePeginTxHash,vaultProviderCommissionBps:t.vaultProviderCommissionBps,claimExpiredUntil:t.claimExpiredUntil,vaultCoreVersion:t.vaultCoreVersion}}const gt=1n<<64n,x=0n;function T(t,e,n){if(t<0n||t>=gt)throw new Error(`getBtcVaultProtocolInfo returned ${e}=${t} for vault ${n}, outside the uint64 range — the registry may predate RFC-006`);return t}function F(t,e){return{vpKeyEpoch:T(t.vpKeyEpoch,"vpKeyEpoch",e),appKeeperKeyEpoch:T(t.appKeeperKeyEpoch,"appKeeperKeyEpoch",e),ucKeyEpoch:T(t.ucKeyEpoch,"ucKeyEpoch",e)}}class pt{constructor(e,n){this.publicClient=e,this.contractAddress=n}async getVaultProviderGenesisBtcPubKey(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getOperationBtcKeyAtEpoch",args:[e,x]});return A.assertOnChainBtcPubkey(n,`getOperationBtcKeyAtEpoch (vp=${e}, epoch=${x})`)}async getCurrentVaultProviderOperationBtcKey(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getCurrentOperationBtcKey",args:[e]});return A.assertOnChainBtcPubkey(n,`getCurrentOperationBtcKey (vp=${e})`)}async getVaultKeyEpochs(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:$.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[e]});return F(n,e)}async getVaultKeyEpochsBatch(e){return e.length===0?[]:(await this.publicClient.multicall({contracts:e.map(o=>({address:this.contractAddress,abi:$.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[o]})),allowFailure:!1})).map((o,i)=>F(o,e[i]))}async getVaultBasicInfo(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]});return O(n)}async getVaultProtocolInfo(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[e]});return b(n)}async getProtocolInfoBatch(e){return e.length===0?[]:(await this.publicClient.multicall({contracts:e.map(o=>({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[o]})),allowFailure:!1})).map((o,i)=>{const r=o;if(!r.depositorSignedPeginTx||r.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e[i]} not found on-chain or has no pegin transaction`);return b(r)})}async getPegInFee(e){return await this.publicClient.readContract({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getPegInFee",args:[e]})}async getVaultProviderCommission(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getVaultProviderCommission",args:[e]});if(!Number.isInteger(n)||n<0||n>S)throw new Error(`getVaultProviderCommission returned ${n} bps for ${e}, outside the protocol range [0, ${S}]`);return n}async getVaultData(e){const[n,o]=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]},{address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[e]}],allowFailure:!1}),i=O(n),r=b(o);if(!r.depositorSignedPeginTx||r.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e} not found on-chain or has no pegin transaction`);return{basic:i,protocol:r}}}const mt=21e6*1e8,N=3e4;async function I(t,e){const n=new AbortController,o=setTimeout(()=>n.abort(),N),i=[n.signal,e==null?void 0:e.signal].filter(Boolean),r=f.combineAbortSignals(i);try{return await fetch(t,{...e,signal:r.signal})}catch(s){throw clearTimeout(o),r.cleanup(),s!=null&&typeof s=="object"&&"name"in s&&s.name==="AbortError"?new Error(`Mempool API request timed out after ${N}ms: ${t}`):s}}const G=1e4;function L(t){return Number.isInteger(t)&&t>0&&t<=mt}function dt(t){return Number.isInteger(t)&&t>0&&t<=G}function y(t,e){return!Number.isInteger(t)||t<0?!1:e===void 0||t<e}function h(t){if(!f.TXID_RE.test(t))throw new Error(`Invalid transaction ID format: ${t}`)}function W(t){if(!f.BITCOIN_ADDRESS_RE.test(t))throw new Error(`Invalid Bitcoin address format: ${t}`)}function q(t,e){if(!f.HEX_RE.test(t))throw new Error(`Invalid scriptPubKey: not valid hex for ${e}`);if(!f.KNOWN_SCRIPT_PREFIXES.some(o=>t.toLowerCase().startsWith(o)))throw new Error(`Unrecognized scriptPubKey type for ${e}: prefix ${t.slice(0,6)} does not match any known Bitcoin script type`)}const j={mainnet:"https://mempool.space/api",testnet:"https://mempool.space/testnet/api",signet:"https://mempool.space/signet/api"};async function l(t,e){try{const n=await I(t,e);if(!n.ok){const i=await n.text();throw new Error(`Mempool API error (${n.status}): ${i||n.statusText}`)}const o=n.headers.get("content-type");return o!=null&&o.includes("application/json")?await n.json():await n.text()}catch(n){throw n instanceof Error?new Error(`Failed to fetch from mempool API: ${n.message}`):new Error("Failed to fetch from mempool API: Unknown error")}}async function Pt(t,e){try{const n=await I(`${e}/tx`,{method:"POST",body:t,headers:{"Content-Type":"text/plain"}});if(!n.ok){const i=await n.text();let r;try{const s=JSON.parse(i);r=s.message??s.error}catch{r=i}throw new Error(r||`Failed to broadcast transaction: ${n.statusText}`)}return await n.text()}catch(n){throw n instanceof Error?new Error(`Failed to broadcast BTC transaction: ${n.message}`):new Error("Failed to broadcast BTC transaction: Unknown error")}}async function z(t,e){return h(t),l(`${e}/tx/${t}`)}async function It(t){const e=await l(`${t}/blocks/tip/height`),n=e.trim();if(!/^\d+$/.test(n))throw new Error(`Mempool API returned an invalid block tip height: "${e}"`);return Number.parseInt(n,10)}async function wt(t,e,n){if(h(t),!y(e))throw new Error(`Invalid vout ${e} for transaction ${t}`);return l(`${n}/tx/${t}/outspend/${e}`)}async function bt(t,e){h(t);try{const n=await I(`${e}/tx/${t}/hex`);if(!n.ok){const o=await n.text();throw new Error(`Mempool API error (${n.status}): ${o||n.statusText}`)}return await n.text()}catch(n){throw n instanceof Error?new Error(`Failed to get transaction hex for ${t}: ${n.message}`):new Error(`Failed to get transaction hex for ${t}: Unknown error`)}}async function Tt(t,e,n){h(t);const o=await z(t,n);if(!y(e,o.vout.length))throw new Error(`Invalid vout ${e} for transaction ${t} (has ${o.vout.length} outputs)`);const i=o.vout[e];if(!L(i.value))throw new Error(`Invalid UTXO value ${i.value} for ${t}:${e}`);return q(i.scriptpubkey,`${t}:${e}`),{txid:t,vout:e,value:i.value,scriptPubKey:i.scriptpubkey}}async function yt(t,e){W(t);try{const n=await l(`${e}/address/${t}/utxo`),o=await l(`${e}/v1/validate-address/${t}`);if(!o.isvalid)throw new Error(`Invalid Bitcoin address: ${t}. Mempool API validation failed.`);q(o.scriptPubKey,t);for(const r of n){if(h(r.txid),!y(r.vout))throw new Error(`Invalid vout ${r.vout} for ${r.txid}`);if(!L(r.value))throw new Error(`Invalid UTXO value ${r.value} for ${r.txid}:${r.vout}`)}return n.sort((r,s)=>s.value-r.value).map(r=>({txid:r.txid,vout:r.vout,value:r.value,scriptPubKey:o.scriptPubKey,confirmed:r.status.confirmed}))}catch(n){throw n instanceof Error?new Error(`Failed to get UTXOs for address ${t}: ${n.message}`):new Error(`Failed to get UTXOs for address ${t}: Unknown error`)}}function Et(t){return j[t]}async function $t(t,e){return W(t),l(`${e}/address/${t}/txs`)}async function At(t){const e=await I(`${t}/v1/fees/recommended`);if(!e.ok)throw new Error(`Failed to fetch network fees: ${e.status} ${e.statusText}`);const n=await e.json(),o=["fastestFee","halfHourFee","hourFee","economyFee","minimumFee"];for(const i of o)if(!dt(n[i]))throw new Error(`Invalid fee rate ${i}=${n[i]} from mempool API: expected a positive number ≤ ${G}`);if(n.minimumFee>n.economyFee||n.economyFee>n.hourFee||n.hourFee>n.halfHourFee||n.halfHourFee>n.fastestFee)throw new Error(`Fee rate ordering violation from mempool API: expected minimumFee (${n.minimumFee}) <= economyFee (${n.economyFee}) <= hourFee (${n.hourFee}) <= halfHourFee (${n.halfHourFee}) <= fastestFee (${n.fastestFee}).`);return n}exports.MEMPOOL_API_URLS=j;exports.P2WPKH_ENCODED_SIG_MAX=R;exports.P2WPKH_ENCODED_SIG_MIN=k;exports.ViemVaultRegistryReader=pt;exports.assertValidOffchainParamsVersion=M;exports.getAddressTxs=$t;exports.getAddressUtxos=yt;exports.getMempoolApiUrl=Et;exports.getNetworkFees=At;exports.getOutspend=wt;exports.getTipHeight=It;exports.getTxHex=bt;exports.getTxInfo=z;exports.getUtxoInfo=Tt;exports.pushTx=Pt;exports.validateOffchainParams=D;exports.validatePegInConfiguration=ht;exports.validateTBVProtocolParams=X;exports.verifyBip322P2wpkhSimple=ft;exports.verifyBip322Simple=lt;
|
|
2
|
+
//# sourceMappingURL=mempoolApi-BJN9fGEd.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mempoolApi-BJN9fGEd.cjs","sources":["../src/tbv/core/clients/vault-provider/auth/bip322Verify.ts","../src/tbv/core/clients/eth/protocol-params-validation.ts","../src/tbv/core/clients/eth/vault-registry-reader.ts","../src/tbv/core/clients/mempool/mempoolApi.ts"],"sourcesContent":["/**\n * BIP-322 \"simple\" signature verification for P2TR key-path and P2WPKH.\n *\n * Mirrors the Rust reference in\n * `btc-vault/crates/btc-signer/src/message.rs` (`verify_bip322_message`\n * and the P2WPKH arm of `verify_pop_witness`, both of which delegate to\n * the `bip322` crate 0.0.10's `verify_simple`).\n *\n * The algorithm:\n *\n * 1. Compute the BIP-322 tagged-hash of the message:\n * m_hash = SHA256( SHA256(tag) || SHA256(tag) || message )\n * where tag = \"BIP0322-signed-message\".\n *\n * 2. Build a virtual \"to_spend\" transaction with one input (prevout\n * all-zero txid + 0xFFFFFFFF vout, scriptSig = `OP_0 PUSH32 m_hash`,\n * sequence = 0) and one output (value 0, scriptPubKey = the signer's\n * address: P2TR key-path-only, or P2WPKH of the compressed pubkey).\n *\n * 3. Build a \"to_sign\" transaction that spends to_spend[0] and has a\n * single `OP_RETURN` output (value 0).\n *\n * 4. Compute the sighash of to_sign input 0: BIP-341 taproot for P2TR\n * (SIGHASH_DEFAULT 0x00 unless the witness item carried a trailing\n * SIGHASH_ALL 0x01 byte), BIP-143 with the standard P2WPKH\n * scriptCode for P2WPKH (SIGHASH_ALL only).\n *\n * 5. Verify the signature: Schnorr against the **tweaked** output key\n * `Q = P + tap_tweak(P) * G` for P2TR (no merkle root — key-path\n * only), ECDSA against the compressed pubkey for P2WPKH.\n *\n * `bitcoinjs-lib` handles (2)–(4); `tiny-secp256k1-asmjs` provides\n * the tweak and the Schnorr/ECDSA verifies. Pulling in a full BIP-322\n * library would add a peer dep for what amounts to ~40 lines of glue.\n *\n * @module tbv/core/clients/vault-provider/auth/bip322Verify\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { script as bscript, payments, Transaction } from \"bitcoinjs-lib\";\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { Buffer } from \"buffer\";\n\n/** BIP-322 message tag (BIP-340 tagged-hash style). */\nconst BIP322_TAG = \"BIP0322-signed-message\";\n\n/** BIP-341 taproot-tweak tag. */\nconst TAPTWEAK_TAG = \"TapTweak\";\n\nconst X_ONLY_PUBKEY_SIZE = 32;\nconst SCHNORR_SIG_SIZE = 64;\n/** SEC1 compressed pubkey: 0x02/0x03 prefix + 32-byte x coordinate. */\nconst COMPRESSED_PUBKEY_SIZE = 33;\n/**\n * vaultd's P2WPKH BIP-322 verifier accepts ONLY 71/72-byte encoded\n * signatures — DER (70/71B) + sighash byte (`bip322` crate 0.0.10\n * `verify.rs:141-153`). A shorter (short-DER) signature fails ingestion\n * permanently, so this gate must be exactly as strict. Exported so\n * `verifyPopWitness` can pre-screen with a cause-naming error.\n */\nexport const P2WPKH_ENCODED_SIG_MIN = 71;\nexport const P2WPKH_ENCODED_SIG_MAX = 72;\n\n// NOTE: bitcoinjs-lib v6.x's `Transaction.addOutput` and its sighash\n// methods are typed for `Satoshi` (a UInt53 number), not `bigint`.\n// Passing `BigInt(0)` triggers a typeforce assertion in `addOutput`\n// (\"Expected property '1' of type Satoshi, got BigInt 0\") which the\n// verifiers' try/catch silently turns into `verify -> false`. Use\n// plain `0` everywhere.\nconst ZERO_SATS = 0;\n\n// Wire fields of the virtual to_spend/to_sign transactions (`bip322`\n// crate 0.0.10 `util.rs:18-85`).\nconst BIP322_TX_VERSION = 0;\nconst BIP322_TX_LOCKTIME = 0;\nconst BIP322_INPUT_SEQUENCE = 0;\n/** to_spend prevout: all-zero 32-byte txid at index 0xFFFFFFFF (`util.rs:18-85`). */\nconst TO_SPEND_PREVOUT_TXID_BYTES = 32;\nconst TO_SPEND_PREVOUT_INDEX = 0xffffffff;\n/** to_sign spends to_spend's only output (`util.rs:18-85`). */\nconst TO_SPEND_OUTPUT_INDEX = 0;\nconst OP_0 = 0x00;\n/** Direct push of the 32-byte tagged message hash. */\nconst OP_PUSHBYTES_32 = 0x20;\nconst OP_RETURN = 0x6a;\n\n/**\n * BIP-340 tagged hash: `SHA256( SHA256(tag) || SHA256(tag) || data )`.\n * Used for both BIP-322 message hashing and BIP-341 tap-tweak.\n */\nfunction taggedHash(tag: string, data: Uint8Array): Uint8Array {\n const tagBytes = new TextEncoder().encode(tag);\n const tagHash = sha256(tagBytes);\n const preimage = new Uint8Array(tagHash.length * 2 + data.length);\n preimage.set(tagHash, 0);\n preimage.set(tagHash, tagHash.length);\n preimage.set(data, tagHash.length * 2);\n return sha256(preimage);\n}\n\n/**\n * Apply BIP-341 taproot tweak to an x-only pubkey with no merkle\n * root (key-path-only address).\n *\n * `tap_tweak = hash_TapTweak(P)`\n * `Q = P + tap_tweak * G` (x-only, even-Y parity)\n *\n * Returns the tweaked 32-byte x-only pubkey, or null if the tweak\n * produces a point-at-infinity or invalid result.\n */\nfunction tweakXOnlyKey(xOnly: Uint8Array): Uint8Array | null {\n if (xOnly.length !== X_ONLY_PUBKEY_SIZE) return null;\n const tweak = taggedHash(TAPTWEAK_TAG, xOnly);\n const tweaked = ecc.xOnlyPointAddTweak(xOnly, tweak);\n return tweaked ? tweaked.xOnlyPubkey : null;\n}\n\n/**\n * Build the BIP-322 virtual `to_sign` transaction for a signer\n * scriptPubKey (steps 1–3 above; `bip322` crate 0.0.10 `util.rs:18-85`:\n * both txs version 0, locktime 0, sequence 0, all values 0).\n */\nfunction buildToSignTransaction(\n messageBytes: Uint8Array,\n scriptPubKey: Buffer,\n): Transaction {\n const messageHash = taggedHash(BIP322_TAG, messageBytes);\n\n const toSpend = new Transaction();\n toSpend.version = BIP322_TX_VERSION;\n toSpend.locktime = BIP322_TX_LOCKTIME;\n const scriptSig = Buffer.concat([\n Buffer.from([OP_0, OP_PUSHBYTES_32]),\n Buffer.from(messageHash),\n ]);\n toSpend.addInput(\n Buffer.alloc(TO_SPEND_PREVOUT_TXID_BYTES, 0),\n TO_SPEND_PREVOUT_INDEX,\n BIP322_INPUT_SEQUENCE,\n scriptSig,\n );\n toSpend.addOutput(scriptPubKey, ZERO_SATS);\n\n const toSign = new Transaction();\n toSign.version = BIP322_TX_VERSION;\n toSign.locktime = BIP322_TX_LOCKTIME;\n // Bitcoin txid in natural-byte (little-endian) form.\n toSign.addInput(\n toSpend.getHash(),\n TO_SPEND_OUTPUT_INDEX,\n BIP322_INPUT_SEQUENCE,\n );\n toSign.addOutput(Buffer.from([OP_RETURN]), ZERO_SATS);\n\n return toSign;\n}\n\n/**\n * Verify a BIP-322 \"simple\" P2TR key-path signature over an arbitrary\n * byte message.\n *\n * @internal Consumed by `verifyServerIdentity` (VP auth) and\n * `verifyPopWitness` (PoP pre-registration check), and exposed so the\n * golden-vector test suite can pin the verifier independently.\n *\n * @param messageBytes - The bytes that were signed (e.g. a CBOR-encoded\n * payload). Not pre-hashed; this function applies\n * the BIP-322 tagged hash internally.\n * @param xOnlyPubkey - 32-byte x-only pubkey of the signer (pre-tweak).\n * @param signature - 64-byte raw Schnorr signature (BIP-340), as\n * emitted by a key-path witness. The trailing\n * sighash byte of a 65-byte witness item is not\n * part of it — pass it as `hashType` instead.\n * @param hashType - BIP-341 sighash type the signature commits to.\n * `SIGHASH_DEFAULT` (0x00) for a 64-byte witness\n * item, `SIGHASH_ALL` (0x01) for a 65-byte one.\n * @returns `true` if the signature verifies against the address\n * derived from `xOnlyPubkey`; `false` otherwise.\n */\nexport function verifyBip322Simple(\n messageBytes: Uint8Array,\n xOnlyPubkey: Uint8Array,\n signature: Uint8Array,\n hashType: number = Transaction.SIGHASH_DEFAULT,\n): boolean {\n if (xOnlyPubkey.length !== X_ONLY_PUBKEY_SIZE) return false;\n if (signature.length !== SCHNORR_SIG_SIZE) return false;\n // Only the two types a BIP-322 witness may carry. SIGHASH_NONE/SINGLE and the\n // ANYONECANPAY variants would verify here but are rejected downstream.\n if (\n hashType !== Transaction.SIGHASH_DEFAULT &&\n hashType !== Transaction.SIGHASH_ALL\n ) {\n return false;\n }\n\n // Any exception from the underlying crypto libraries (e.g. the\n // `Expected Point` error `tiny-secp256k1` throws when the supplied\n // 32 bytes don't represent a valid x-coordinate on secp256k1) is\n // treated as a verification failure rather than propagated — a\n // verifier MUST return a boolean, not raise.\n try {\n // scriptPubKey for the signer's P2TR key-path-only address.\n // bitcoinjs-lib's `payments.p2tr({ internalPubkey })` computes the\n // tweak and produces the `OP_1 <tweaked_xonly>` output script.\n const p2tr = payments.p2tr({\n internalPubkey: Buffer.from(xOnlyPubkey),\n });\n if (!p2tr.output) return false;\n const scriptPubKey = p2tr.output;\n\n const toSign = buildToSignTransaction(messageBytes, scriptPubKey);\n\n // Taproot sighash for to_sign input 0.\n const sighash = toSign.hashForWitnessV1(\n 0,\n [scriptPubKey],\n [ZERO_SATS],\n hashType,\n );\n\n // Tweak the x-only pubkey (no merkle root) and verify Schnorr.\n const tweakedXOnly = tweakXOnlyKey(xOnlyPubkey);\n if (!tweakedXOnly) return false;\n\n return ecc.verifySchnorr(sighash, tweakedXOnly, signature);\n } catch {\n return false;\n }\n}\n\n/**\n * Verify a BIP-322 \"simple\" P2WPKH signature over an arbitrary byte\n * message, mirroring the verifier vaultd runs on a two-item PoP witness\n * (`bip322` crate 0.0.10 `verify.rs:102-186 verify_full_p2wpkh`).\n *\n * @internal Consumed by `verifyPopWitness` for Native SegWit software\n * wallets, and exposed so the BIP-322 official-vector test suite can pin\n * the verifier independently.\n *\n * @param compressedPubkey - 33-byte SEC1 compressed pubkey of the signer\n * (witness item 1). The address is derived from\n * it; network affects only bech32 encoding, not\n * script or sighash (`message.rs:125-127`).\n * @param encodedSignature - Witness item 0: DER signature with trailing\n * sighash byte, 71 or 72 bytes, SIGHASH_ALL only\n * (`verify.rs:141-161`).\n * @returns `true` if the signature verifies against the P2WPKH address of\n * `compressedPubkey`; `false` otherwise.\n */\nexport function verifyBip322P2wpkhSimple(\n messageBytes: Uint8Array,\n compressedPubkey: Uint8Array,\n encodedSignature: Uint8Array,\n): boolean {\n if (compressedPubkey.length !== COMPRESSED_PUBKEY_SIZE) return false;\n if (\n encodedSignature.length < P2WPKH_ENCODED_SIG_MIN ||\n encodedSignature.length > P2WPKH_ENCODED_SIG_MAX\n ) {\n return false;\n }\n // Any exception below (strict-DER decode, malformed pubkey) is a\n // verification failure, not an error — a verifier returns a boolean.\n try {\n // Full curve-point parse, as `PublicKey::from_slice` (`verify.rs:82-83`).\n if (!ecc.isPointCompressed(compressedPubkey)) return false;\n\n // Strict DER decode, then SIGHASH_ALL only — deliberately NARROWER than\n // `verify.rs:156-161` (its from_consensus maps more bytes to All); host-stricter is safe.\n const { signature, hashType } = bscript.signature.decode(\n Buffer.from(encodedSignature),\n );\n // decode tolerates non-minimal integers (bip66.js never bounds lenR/lenS at 33;\n // fromDER truncates, script_signature.js:29-35) that vaultd's strict libsecp\n // parse rejects (secp256k1-sys ecdsa_impl.h:127-136) — require the unique\n // minimal encoding by re-encoding and byte-comparing.\n if (\n !bscript.signature\n .encode(signature, hashType)\n .equals(Buffer.from(encodedSignature))\n ) {\n return false;\n }\n if (hashType !== Transaction.SIGHASH_ALL) return false;\n\n // scriptPubKey = OP_0 PUSH20 hash160(pubkey) (`message.rs:127 Address::p2wpkh`).\n const p2wpkh = payments.p2wpkh({ pubkey: Buffer.from(compressedPubkey) });\n if (!p2wpkh.output || !p2wpkh.hash) return false;\n\n const toSign = buildToSignTransaction(messageBytes, p2wpkh.output);\n\n // BIP-143 sighash with the standard P2WPKH scriptCode\n // `OP_DUP OP_HASH160 <20B> OP_EQUALVERIFY OP_CHECKSIG` and value 0\n // (`verify.rs:163-173 p2wpkh_signature_hash`; scriptCode template per\n // bitcoinjs-lib's own P2WPKH signer, `src/psbt.js:1245-1255`).\n const scriptCode = payments.p2pkh({ hash: p2wpkh.hash }).output;\n if (!scriptCode) return false;\n const sighash = toSign.hashForWitnessV0(0, scriptCode, ZERO_SATS, hashType);\n\n // strict=true rejects high-S, as libsecp256k1's verify does\n // (`verify.rs:180-182`; secp256k1 crate `ecdsa/mod.rs:194`).\n return ecc.verify(sighash, compressedPubkey, signature, true);\n } catch {\n return false;\n }\n}\n","/**\n * Validation for protocol parameters fetched from the ProtocolParams contract.\n *\n * These values feed Bitcoin script construction and deposit validation.\n * Invalid params must be caught before they reach transaction-building code,\n * since errors after wallet signing prompts are unrecoverable.\n *\n * The {@link ViemProtocolParamsReader} runs these on every read; consumers\n * implementing their own reader against the same `ProtocolParamsReader`\n * interface should call them too.\n */\n\nimport { assertValidVaultCoreVersion } from \"../../primitives/vaultCoreVersion\";\n\nimport type {\n PegInConfiguration,\n TBVProtocolParams,\n VersionedOffchainParams,\n} from \"./types\";\n\n/**\n * Maximum value for a Solidity uint16.\n * PeginLogic.sol casts timelockAssert to uint16, so values above this are invalid.\n */\nconst UINT16_MAX = 65535;\n\n/** Maximum valid value for basis points (100%) */\nconst MAX_BASIS_POINTS = 10000;\n\n/** Maximum value for a Solidity uint32. */\nconst UINT32_MAX = 4_294_967_295;\n\n/** Maximum valid value for a uint8 (e.g. maxHtlcOutputCount). */\nconst UINT8_MAX = 255;\n\n/**\n * Validate an `offchainParamsVersion` value sourced from a contract read.\n * `Number()` on a malformed payload yields `NaN` or a non-integer; both\n * silently break consumers that loop `1..version` or use the value as a\n * map key. Used by reader entry points that surface the version to JS.\n */\nexport function assertValidOffchainParamsVersion(version: number): void {\n if (\n !Number.isInteger(version) ||\n version < 0 ||\n version > UINT32_MAX\n ) {\n throw new Error(\n `Invalid offchainParamsVersion from contract: must be a uint32, got ${version}`,\n );\n }\n}\n\n/**\n * Validate offchain params consistency and bounds.\n * @throws Error on invalid values to prevent constructing invalid Bitcoin scripts.\n */\nexport function validateOffchainParams(params: VersionedOffchainParams): void {\n const errors: string[] = [];\n\n if (params.timelockAssert <= 0n) {\n errors.push(\n `timelockAssert must be positive, got ${params.timelockAssert}`,\n );\n }\n if (params.timelockAssert > BigInt(UINT16_MAX)) {\n errors.push(\n `timelockAssert ${params.timelockAssert} exceeds uint16 max (${UINT16_MAX})`,\n );\n }\n\n if (params.timelockChallengeAssert <= 0n) {\n errors.push(\n `timelockChallengeAssert must be positive, got ${params.timelockChallengeAssert}`,\n );\n }\n\n if (params.tRefund <= 0) {\n errors.push(`tRefund must be positive, got ${params.tRefund}`);\n }\n\n if (params.tStale <= 0) {\n errors.push(`tStale must be positive, got ${params.tStale}`);\n }\n\n if (params.securityCouncilKeys.length === 0) {\n errors.push(\"securityCouncilKeys must not be empty\");\n }\n\n if (params.councilQuorum <= 0) {\n errors.push(`councilQuorum must be positive, got ${params.councilQuorum}`);\n }\n if (params.councilQuorum > params.securityCouncilKeys.length) {\n errors.push(\n `councilQuorum (${params.councilQuorum}) exceeds securityCouncilKeys count (${params.securityCouncilKeys.length})`,\n );\n }\n\n if (params.feeRate <= 0n) {\n errors.push(`feeRate must be positive, got ${params.feeRate}`);\n }\n\n if (params.minPeginFeeRate <= 0n) {\n errors.push(\n `minPeginFeeRate must be positive, got ${params.minPeginFeeRate}`,\n );\n }\n\n if (\n !Number.isInteger(params.proverCircuitVersion) ||\n params.proverCircuitVersion < 0 ||\n params.proverCircuitVersion > UINT16_MAX\n ) {\n errors.push(\n `proverCircuitVersion must be a uint16, got ${params.proverCircuitVersion}`,\n );\n }\n\n if (\n !Number.isInteger(params.minPrepeginDepth) ||\n params.minPrepeginDepth <= 0 ||\n params.minPrepeginDepth > UINT32_MAX\n ) {\n errors.push(\n `minPrepeginDepth must be a uint32 in [1, ${UINT32_MAX}], got ${params.minPrepeginDepth}`,\n );\n }\n\n if (params.babeTotalInstances <= 0) {\n errors.push(\n `babeTotalInstances must be positive, got ${params.babeTotalInstances}`,\n );\n }\n if (params.babeInstancesToFinalize <= 0) {\n errors.push(\n `babeInstancesToFinalize must be positive, got ${params.babeInstancesToFinalize}`,\n );\n }\n if (params.babeInstancesToFinalize > params.babeTotalInstances) {\n errors.push(\n `babeInstancesToFinalize (${params.babeInstancesToFinalize}) exceeds babeTotalInstances (${params.babeTotalInstances})`,\n );\n }\n\n if (\n params.minVpCommissionBps < 0 ||\n params.minVpCommissionBps > MAX_BASIS_POINTS\n ) {\n errors.push(\n `minVpCommissionBps must be in [0, ${MAX_BASIS_POINTS}], got ${params.minVpCommissionBps}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(\n `Invalid offchain protocol parameters: ${errors.join(\"; \")}`,\n );\n }\n}\n\n/**\n * Validate TBV protocol params returned from the contract.\n * @throws Error on invalid amounts or out-of-range bounded fields.\n */\nexport function validateTBVProtocolParams(params: TBVProtocolParams): void {\n const errors: string[] = [];\n\n if (params.minimumPegInAmount <= 0n) {\n errors.push(\n `minimumPegInAmount must be positive, got ${params.minimumPegInAmount}`,\n );\n }\n\n if (params.maxPegInAmount < params.minimumPegInAmount) {\n errors.push(\n `maxPegInAmount (${params.maxPegInAmount}) must be >= minimumPegInAmount (${params.minimumPegInAmount})`,\n );\n }\n\n if (params.pegInAckTimeout <= 0n) {\n errors.push(\n `pegInAckTimeout must be positive, got ${params.pegInAckTimeout}`,\n );\n }\n\n if (params.pegInActivationTimeout <= 0n) {\n errors.push(\n `pegInActivationTimeout must be positive, got ${params.pegInActivationTimeout}`,\n );\n }\n\n if (\n !Number.isInteger(params.maxHtlcOutputCount) ||\n params.maxHtlcOutputCount <= 0 ||\n params.maxHtlcOutputCount > UINT8_MAX\n ) {\n errors.push(\n `maxHtlcOutputCount must be an integer in [1, ${UINT8_MAX}], got ${params.maxHtlcOutputCount}`,\n );\n }\n\n if (\n typeof params.expiredPegInGraceBlocks !== \"bigint\" ||\n params.expiredPegInGraceBlocks <= 0n\n ) {\n errors.push(\n `expiredPegInGraceBlocks must be a positive bigint, got ${params.expiredPegInGraceBlocks}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(`Invalid TBV protocol parameters: ${errors.join(\"; \")}`);\n }\n}\n\n/**\n * Validate the full peg-in configuration after assembly.\n * Checks both TBV params and offchain params consistency, and the\n * top-level `offchainParamsVersion` (which originates from a separate\n * multicall result and so must be range-checked alongside the params it\n * names).\n */\nexport function validatePegInConfiguration(config: PegInConfiguration): void {\n validateTBVProtocolParams(config);\n validateOffchainParams(config.offchainParams);\n\n if (\n !Number.isInteger(config.offchainParamsVersion) ||\n config.offchainParamsVersion < 0 ||\n config.offchainParamsVersion > UINT32_MAX\n ) {\n throw new Error(\n `Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${config.offchainParamsVersion}`,\n );\n }\n\n // The contract enforces ≥ 1 (setter rejects 0); a 0 here means a\n // mis-decoded read or a pre-vaultCoreVersion contract — fail closed.\n assertValidVaultCoreVersion(\n config.activeVaultCoreVersion,\n \"ProtocolParams.activeVaultCoreVersion()\",\n );\n}\n","/**\n * Concrete BTCVaultRegistry reader using viem's readContract.\n *\n * This is an optional utility — callers can use their own implementation\n * of the VaultRegistryReader interface.\n */\n\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\n\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport { BTCVaultRegistryKeyEpochsABI } from \"../../contracts/abis/BTCVaultRegistryKeyEpochs.abi\";\nimport { assertOnChainBtcPubkey } from \"./onChainBtcPubkey\";\nimport { assertValidOffchainParamsVersion } from \"./protocol-params-validation\";\nimport type {\n KeyEpochs,\n OnChainBtcPubkey,\n VaultBasicInfo,\n VaultData,\n VaultProtocolInfo,\n VaultRegistryReader,\n} from \"./types\";\n\n/**\n * Inclusive upper bound the BTCVaultRegistry contract enforces on a vault\n * provider's commission (the contract check is `< 10000`).\n */\nconst MAX_VP_COMMISSION_BPS = 9999;\n\n/** Raw `getBtcVaultBasicInfo` tuple as decoded by viem. */\ntype RawVaultBasicInfo = {\n depositor: Address;\n depositorBtcPubKey: Hex;\n amount: bigint;\n vaultProvider: Address;\n status: number;\n applicationEntryPoint: Address;\n createdAt: bigint;\n};\n\n/** Raw `getBtcVaultProtocolInfo` tuple as decoded by viem. */\ntype RawVaultProtocolInfo = {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n claimExpiredUntil: bigint;\n vaultCoreVersion: number;\n};\n\nfunction mapVaultBasicInfo(result: RawVaultBasicInfo): VaultBasicInfo {\n return {\n depositor: result.depositor,\n depositorBtcPubKey: result.depositorBtcPubKey,\n amount: result.amount,\n vaultProvider: result.vaultProvider,\n status: result.status,\n applicationEntryPoint: result.applicationEntryPoint,\n createdAt: result.createdAt,\n };\n}\n\nfunction mapVaultProtocolInfo(result: RawVaultProtocolInfo): VaultProtocolInfo {\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n return {\n depositorSignedPeginTx: result.depositorSignedPeginTx,\n universalChallengersVersion: result.universalChallengersVersion,\n appVaultKeepersVersion: result.appVaultKeepersVersion,\n offchainParamsVersion,\n verifiedAt: result.verifiedAt,\n depositorWotsPkHash: result.depositorWotsPkHash,\n hashlock: result.hashlock,\n htlcVout: result.htlcVout,\n depositorPopSignature: result.depositorPopSignature,\n prePeginTxHash: result.prePeginTxHash,\n vaultProviderCommissionBps: result.vaultProviderCommissionBps,\n claimExpiredUntil: result.claimExpiredUntil,\n vaultCoreVersion: result.vaultCoreVersion,\n };\n}\n\n/**\n * Exclusive upper bound for a `uint64` epoch.\n *\n * viem does not range-check a decoded `uint64`, so a misaligned decode can\n * hand back a value far larger than the field can hold. Rejecting those is\n * cheap defence in depth against a mis-decode of the extended ABI.\n *\n * The state this is load-bearing for is narrower than \"a registry that predates\n * RFC-006\". Against a *fully* pre-RFC-006 registry the path fails closed on its\n * own: `resolveParticipantKeysAtEpochs` goes on to call\n * `getOperationBtcKeyAtEpochOrGenesis` on ApplicationRegistry and\n * ProtocolParams, which do not exist there, so the multicall reverts and these\n * epochs are never used. The reachable gap is a registry that *has* the\n * operation-key getters but whose `BTCVaultProtocolInfo` struct is not\n * extended — there the tail-data epochs resolve with no error at all, and this\n * range check is the only thing looking at them.\n *\n * Even for that case it is only a backstop, and a weak one: a misaligned decode\n * can land on a small, plausible-looking integer this range accepts. Correctness\n * rests on only ever pointing at an RFC-006 registry, which is a deployment\n * precondition rather than something this call can establish — see\n * https://github.com/babylonlabs-io/babylon-toolkit/issues/2192 for where that\n * check is owned, and `BTCVaultRegistryKeyEpochs.abi.ts` for the decode hazard.\n */\nconst UINT64_EXCLUSIVE_UPPER_BOUND = 1n << 64n;\n\n/**\n * The epoch a vault provider's registration key is bonded at.\n *\n * A provider's operation-key history is append-only and every appended version\n * is stamped at epoch 1 or later, so epoch 0 always resolves to the key set at\n * registration. This is what lets `getOperationBtcKeyAtEpoch` stand in for the\n * removed `getVaultProviderBTCKey` getter.\n */\nconst VP_GENESIS_KEY_EPOCH = 0n;\n\nfunction assertEpochInRange(\n value: bigint,\n field: string,\n vaultId: Hex,\n): bigint {\n if (value < 0n || value >= UINT64_EXCLUSIVE_UPPER_BOUND) {\n throw new Error(\n `getBtcVaultProtocolInfo returned ${field}=${value} for vault ${vaultId}, ` +\n `outside the uint64 range — the registry may predate RFC-006`,\n );\n }\n return value;\n}\n\nfunction mapKeyEpochs(result: KeyEpochs, vaultId: Hex): KeyEpochs {\n return {\n vpKeyEpoch: assertEpochInRange(result.vpKeyEpoch, \"vpKeyEpoch\", vaultId),\n appKeeperKeyEpoch: assertEpochInRange(\n result.appKeeperKeyEpoch,\n \"appKeeperKeyEpoch\",\n vaultId,\n ),\n ucKeyEpoch: assertEpochInRange(result.ucKeyEpoch, \"ucKeyEpoch\", vaultId),\n };\n}\n\n/**\n * Concrete vault registry reader using viem.\n *\n * Usage:\n * ```ts\n * const reader = new ViemVaultRegistryReader(publicClient, registryAddress);\n * const data = await reader.getVaultData(vaultId);\n * ```\n */\nexport class ViemVaultRegistryReader implements VaultRegistryReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n /**\n * Read the VP's **genesis** (registration) x-only BTC pubkey — the key bonded\n * at version 0, which never moves when the operator rotates.\n *\n * Resolved as \"the operation key at epoch 0\" rather than through the\n * dedicated `getVaultProviderBTCKey` getter, which\n * https://github.com/babylonlabs-io/vault-contracts-aave-v4/pull/539 removes.\n * Epoch 0 predates any rotation — appended versions are stamped at epoch 1 or\n * later — so it resolves to the registration key, and the contracts team has\n * confirmed that is a property we can rely on rather than an implementation\n * detail. The devnet comparison behind that claim — both getters returning the\n * identical key for a provider that *has* rotated, while\n * `getCurrentOperationBtcKey` differed — is recorded in\n * https://github.com/babylonlabs-io/babylon-toolkit/issues/2188.\n *\n * This makes the read RFC-006-only, where the removed getter also existed on a\n * legacy registry. That costs nothing: every caller of this method already\n * resolves participant keys through `OperationKeyReader`, so all of them\n * require an RFC-006 registry regardless.\n *\n * Validates length, hex form, and secp256k1 curve membership before minting\n * the brand. Returns 64-char lowercase hex without the `0x` prefix.\n */\n async getVaultProviderGenesisBtcPubKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getOperationBtcKeyAtEpoch\",\n args: [vpAddress, VP_GENESIS_KEY_EPOCH],\n })) as Hex;\n return assertOnChainBtcPubkey(\n result,\n `getOperationBtcKeyAtEpoch (vp=${vpAddress}, epoch=${VP_GENESIS_KEY_EPOCH})`,\n );\n }\n\n /**\n * Read a vault provider's *current* RFC-006 operation BTC key.\n *\n * Falls back on-chain to the registration key when the provider has never\n * rotated, so this returns the same value as\n * `getVaultProviderGenesisBtcPubKey` until the first rotation.\n *\n * This is the key the VP's server signs its BIP-322 auth tokens with — a\n * live per-operator identity, not a per-vault binding, so the auth pin uses\n * the current key rather than any vault's frozen epoch.\n */\n async getCurrentVaultProviderOperationBtcKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getCurrentOperationBtcKey\",\n args: [vpAddress],\n })) as Hex;\n return assertOnChainBtcPubkey(\n result,\n `getCurrentOperationBtcKey (vp=${vpAddress})`,\n );\n }\n\n /**\n * Read a vault's frozen RFC-006 operation-key epochs.\n *\n * Reads `getBtcVaultProtocolInfo` through the **extended** ABI, which is only\n * valid against an RFC-006 registry: against one whose `BTCVaultProtocolInfo`\n * struct is not extended this call does not fail for a populated vault, it\n * silently returns three words of tail data as epochs. Nothing here can detect\n * that, so the guarantee is a deployment one — every network this ships to has\n * the RFC-006 getters, and mainnet is a fresh RFC-006 deploy.\n *\n * A registry missing the operation-key getters entirely is the *safer* of the\n * two cases: `resolveParticipantKeysAtEpochs` reverts downstream and these\n * epochs never reach key resolution. See {@link UINT64_EXCLUSIVE_UPPER_BOUND}\n * for which state the range check actually guards, and\n * `BTCVaultRegistryKeyEpochs.abi.ts` for the decode hazard.\n */\n async getVaultKeyEpochs(vaultId: Hex): Promise<KeyEpochs> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryKeyEpochsABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as unknown as KeyEpochs;\n\n return mapKeyEpochs(result, vaultId);\n }\n\n async getVaultKeyEpochsBatch(vaultIds: readonly Hex[]): Promise<KeyEpochs[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryKeyEpochsABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info, i) =>\n mapKeyEpochs(info as unknown as KeyEpochs, vaultIds[i]),\n );\n }\n\n async getVaultBasicInfo(vaultId: Hex): Promise<VaultBasicInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n })) as RawVaultBasicInfo;\n\n return mapVaultBasicInfo(result);\n }\n\n async getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as RawVaultProtocolInfo;\n\n return mapVaultProtocolInfo(result);\n }\n\n async getProtocolInfoBatch(\n vaultIds: readonly Hex[],\n ): Promise<VaultProtocolInfo[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info, i) => {\n const result = info as unknown as RawVaultProtocolInfo;\n if (\n !result.depositorSignedPeginTx ||\n result.depositorSignedPeginTx === \"0x\"\n ) {\n // An empty record is not proof the vault is absent: a lagging RPC\n // node returns HTTP 200 with a zero struct, so no retry below this\n // layer can see it. Single-shot is only safe because the finality\n // gate (`waitForPeginRegistrationDepth`) runs first on the deposit\n // path — move this ahead of it and the read-after-write race returns.\n // The vault app matches this message to render \"still confirming\".\n throw new Error(\n `Vault ${vaultIds[i]} not found on-chain or has no pegin transaction`,\n );\n }\n return mapVaultProtocolInfo(result);\n });\n }\n\n /**\n * Read the protocol pegin fee (in wei) for a given vault provider.\n * Mirrors the `getPegInFee(address)` view on BTCVaultRegistry.\n */\n async getPegInFee(vaultProvider: Address): Promise<bigint> {\n return (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getPegInFee\",\n args: [vaultProvider],\n })) as bigint;\n }\n\n /**\n * Read a vault provider's current commission in basis points from\n * BTCVaultRegistry. The contract enforces `commissionBps < 10000`, so the\n * legitimate range is `[0, 9999]`; anything outside indicates a wrong\n * contract address or ABI drift and is surfaced as an error rather than\n * trusted.\n */\n async getVaultProviderCommission(vaultProvider: Address): Promise<number> {\n // viem infers `number` from the `uint16` return in the `as const` ABI.\n const bps = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderCommission\",\n args: [vaultProvider],\n });\n\n if (!Number.isInteger(bps) || bps < 0 || bps > MAX_VP_COMMISSION_BPS) {\n throw new Error(\n `getVaultProviderCommission returned ${bps} bps for ${vaultProvider}, ` +\n `outside the protocol range [0, ${MAX_VP_COMMISSION_BPS}]`,\n );\n }\n\n return bps;\n }\n\n async getVaultData(vaultId: Hex): Promise<VaultData> {\n // One round-trip for both structs (hard-fail): they feed signing/refund/\n // broadcast rebinds, so reading them in a single multicall also pins both\n // to the same block — no basic/protocol skew across two `eth_call`s.\n const [basicRaw, protocolRaw] = await this.publicClient.multicall({\n contracts: [\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n },\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n },\n ],\n allowFailure: false,\n });\n\n const basic = mapVaultBasicInfo(basicRaw);\n const protocol = mapVaultProtocolInfo(protocolRaw);\n\n if (\n !protocol.depositorSignedPeginTx ||\n protocol.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultId} not found on-chain or has no pegin transaction`,\n );\n }\n\n return { basic, protocol };\n }\n\n}\n","/**\n * Mempool API Client\n *\n * Client for interacting with mempool.space API for Bitcoin network operations.\n * Used for broadcasting transactions and fetching UTXO data.\n *\n * @module clients/mempool/mempoolApi\n */\n\nimport { combineAbortSignals } from \"../../utils/abortSignals\";\nimport {\n BITCOIN_ADDRESS_RE,\n HEX_RE,\n KNOWN_SCRIPT_PREFIXES,\n TXID_RE,\n} from \"../../utils/validation\";\n\nimport type {\n MempoolUTXO,\n NetworkFees,\n OutspendStatus,\n TxInfo,\n UtxoInfo,\n} from \"./types\";\n\n/** Maximum valid satoshi value: 21 million BTC × 10^8 sats/BTC */\nconst MAX_SATOSHIS = 21_000_000 * 1e8;\n\n/** Timeout for mempool API requests — prevents indefinite hangs from stalled endpoints */\nconst MEMPOOL_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch wrapper with AbortController-based timeout.\n * Ensures all mempool API requests fail bounded rather than hanging indefinitely.\n */\nasync function fetchWithTimeout(\n url: string,\n options?: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n MEMPOOL_REQUEST_TIMEOUT_MS,\n );\n\n // Compose timeout signal with any caller-supplied signal so both can cancel\n const signals = [controller.signal, options?.signal].filter(\n Boolean,\n ) as AbortSignal[];\n const combined = combineAbortSignals(signals);\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers.\n // For the same reason the composed signal keeps its listeners attached on\n // the success path: detaching them would stop the timeout from aborting a\n // stalled body read.\n return await fetch(url, {\n ...options,\n signal: combined.signal,\n });\n } catch (error) {\n clearTimeout(timeoutId);\n combined.cleanup();\n if (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n error.name === \"AbortError\"\n ) {\n throw new Error(\n `Mempool API request timed out after ${MEMPOOL_REQUEST_TIMEOUT_MS}ms: ${url}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Maximum sane fee rate in sat/vByte.\n * The April 2024 Runes spike peaked around 1,805 sat/vB — 10,000 provides ample headroom.\n */\nconst MAX_FEE_RATE = 10_000;\n\nfunction isValidSatoshiValue(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_SATOSHIS;\n}\n\nfunction isValidFeeRate(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_FEE_RATE;\n}\n\nfunction isValidVout(vout: number, outputCount?: number): boolean {\n if (!Number.isInteger(vout) || vout < 0) return false;\n return outputCount === undefined || vout < outputCount;\n}\n\n\nfunction assertValidTxid(txid: string): void {\n if (!TXID_RE.test(txid)) {\n throw new Error(`Invalid transaction ID format: ${txid}`);\n }\n}\n\nfunction assertValidAddress(address: string): void {\n if (!BITCOIN_ADDRESS_RE.test(address)) {\n throw new Error(`Invalid Bitcoin address format: ${address}`);\n }\n}\n\nfunction assertValidScriptPubKey(scriptPubKey: string, context: string): void {\n if (!HEX_RE.test(scriptPubKey)) {\n throw new Error(\n `Invalid scriptPubKey: not valid hex for ${context}`,\n );\n }\n const matchesKnownType = KNOWN_SCRIPT_PREFIXES.some((prefix) =>\n scriptPubKey.toLowerCase().startsWith(prefix),\n );\n if (!matchesKnownType) {\n throw new Error(\n `Unrecognized scriptPubKey type for ${context}: ` +\n `prefix ${scriptPubKey.slice(0, 6)} does not match any known Bitcoin script type`,\n );\n }\n}\n\n/**\n * Default mempool API URLs by network.\n */\nexport const MEMPOOL_API_URLS = {\n mainnet: \"https://mempool.space/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.space/signet/api\",\n} as const;\n\n/**\n * Fetch wrapper with error handling.\n */\nasync function fetchApi<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n try {\n const response = await fetchWithTimeout(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else {\n return (await response.text()) as T;\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to fetch from mempool API: ${error.message}`);\n }\n throw new Error(\"Failed to fetch from mempool API: Unknown error\");\n }\n}\n\n/**\n * Push a signed transaction to the Bitcoin network.\n *\n * @param txHex - The signed transaction hex string\n * @param apiUrl - Mempool API base URL\n * @returns The transaction ID\n * @throws Error if broadcasting fails\n */\nexport async function pushTx(txHex: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx`, {\n method: \"POST\",\n body: txHex,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // Try to extract error message from response using robust JSON parsing\n let message: string | undefined;\n try {\n const errorJson = JSON.parse(errorText);\n message = errorJson.message ?? errorJson.error;\n } catch {\n // Not JSON, use raw text\n message = errorText;\n }\n throw new Error(\n message || `Failed to broadcast transaction: ${response.statusText}`,\n );\n }\n\n // Response is the transaction ID (plain text)\n const txId = await response.text();\n return txId;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to broadcast BTC transaction: ${error.message}`);\n }\n throw new Error(\"Failed to broadcast BTC transaction: Unknown error\");\n }\n}\n\n/**\n * Get transaction information from mempool.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns Transaction information\n */\nexport async function getTxInfo(txid: string, apiUrl: string): Promise<TxInfo> {\n assertValidTxid(txid);\n return fetchApi<TxInfo>(`${apiUrl}/tx/${txid}`);\n}\n\n/**\n * Get the current block tip height.\n *\n * Source: mempool.space API — `GET /api/blocks/tip/height` returns the height\n * of the most recent block as a plain-text integer.\n *\n * @param apiUrl - Mempool API base URL\n * @returns The height of the most recent block\n * @throws Error if the response is not a whole number\n */\nexport async function getTipHeight(apiUrl: string): Promise<number> {\n const raw = await fetchApi<string>(`${apiUrl}/blocks/tip/height`);\n const trimmed = raw.trim();\n if (!/^\\d+$/.test(trimmed)) {\n throw new Error(\n `Mempool API returned an invalid block tip height: \"${raw}\"`,\n );\n }\n return Number.parseInt(trimmed, 10);\n}\n\n/**\n * Get the spend status of a specific transaction output.\n *\n * Calls the esplora-compatible `GET /tx/{txid}/outspend/{vout}` endpoint\n * (mempool.space backend, mempool/electrs `rest.rs`). Returns\n * `{ spent: false }` for an unspent output, or\n * `{ spent: true, txid, vin, status }` when the output has been spent.\n *\n * @param txid - The transaction id whose output is being checked (no 0x prefix)\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns The output's spend status\n */\nexport async function getOutspend(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<OutspendStatus> {\n assertValidTxid(txid);\n if (!isValidVout(vout)) {\n throw new Error(`Invalid vout ${vout} for transaction ${txid}`);\n }\n return fetchApi<OutspendStatus>(`${apiUrl}/tx/${txid}/outspend/${vout}`);\n}\n\n/**\n * Get the hex representation of a transaction.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns The transaction hex string\n * @throws Error if the request fails or transaction is not found\n */\nexport async function getTxHex(txid: string, apiUrl: string): Promise<string> {\n assertValidTxid(txid);\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx/${txid}/hex`);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n return await response.text();\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to get transaction hex for ${txid}: ${error.message}`);\n }\n throw new Error(`Failed to get transaction hex for ${txid}: Unknown error`);\n }\n}\n\n/**\n * Get UTXO information for a specific transaction output.\n *\n * This is used for constructing PSBTs where we need the witnessUtxo data.\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param txid - The transaction ID containing the UTXO\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns UTXO information with value and scriptPubKey\n */\nexport async function getUtxoInfo(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<UtxoInfo> {\n assertValidTxid(txid);\n const txInfo = await getTxInfo(txid, apiUrl);\n\n if (!isValidVout(vout, txInfo.vout.length)) {\n throw new Error(\n `Invalid vout ${vout} for transaction ${txid} (has ${txInfo.vout.length} outputs)`,\n );\n }\n\n const output = txInfo.vout[vout];\n if (!isValidSatoshiValue(output.value)) {\n throw new Error(`Invalid UTXO value ${output.value} for ${txid}:${vout}`);\n }\n assertValidScriptPubKey(output.scriptpubkey, `${txid}:${vout}`);\n\n return {\n txid,\n vout,\n value: output.value,\n scriptPubKey: output.scriptpubkey,\n };\n}\n\n/**\n * Get all UTXOs for a Bitcoin address.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of UTXOs sorted by value (largest first)\n */\nexport async function getAddressUtxos(\n address: string,\n apiUrl: string,\n): Promise<MempoolUTXO[]> {\n assertValidAddress(address);\n try {\n // Fetch UTXOs for the address\n const utxos = await fetchApi<\n {\n txid: string;\n vout: number;\n value: number;\n status: {\n confirmed: boolean;\n };\n }[]\n >(`${apiUrl}/address/${address}/utxo`);\n\n // Fetch scriptPubKey for the address\n const addressInfo = await fetchApi<{\n isvalid: boolean;\n scriptPubKey: string;\n }>(`${apiUrl}/v1/validate-address/${address}`);\n\n if (!addressInfo.isvalid) {\n throw new Error(\n `Invalid Bitcoin address: ${address}. Mempool API validation failed.`,\n );\n }\n assertValidScriptPubKey(addressInfo.scriptPubKey, address);\n\n // Validate UTXO fields from the listing endpoint.\n // Per-UTXO cross-verification against /tx/{txid} is intentionally NOT done\n // here — it would be expensive (N API calls) and redundant: the broadcast\n // path already verifies each selected input via getUtxoInfo before signing.\n // Both endpoints come from the same mempool API, so cross-checking one\n // against the other on the same server does not add real security.\n for (const utxo of utxos) {\n assertValidTxid(utxo.txid);\n if (!isValidVout(utxo.vout)) {\n throw new Error(`Invalid vout ${utxo.vout} for ${utxo.txid}`);\n }\n if (!isValidSatoshiValue(utxo.value)) {\n throw new Error(\n `Invalid UTXO value ${utxo.value} for ${utxo.txid}:${utxo.vout}`,\n );\n }\n }\n\n // Sort by value (largest first) and map to our UTXO format\n const sortedUTXOs = utxos.sort((a, b) => b.value - a.value);\n\n return sortedUTXOs.map((utxo) => ({\n txid: utxo.txid,\n vout: utxo.vout,\n value: utxo.value,\n scriptPubKey: addressInfo.scriptPubKey,\n confirmed: utxo.status.confirmed,\n }));\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(\n `Failed to get UTXOs for address ${address}: ${error.message}`,\n );\n }\n throw new Error(\n `Failed to get UTXOs for address ${address}: Unknown error`,\n );\n }\n}\n\n/**\n * Get the mempool API URL for a given network.\n *\n * @param network - Bitcoin network (mainnet, testnet, signet)\n * @returns The mempool API URL\n */\nexport function getMempoolApiUrl(\n network: \"mainnet\" | \"testnet\" | \"signet\",\n): string {\n return MEMPOOL_API_URLS[network];\n}\n\n/**\n * Transaction summary from address transactions endpoint.\n */\nexport interface AddressTx {\n txid: string;\n status: {\n confirmed: boolean;\n block_height?: number;\n };\n}\n\n/**\n * Get recent transactions for a Bitcoin address.\n *\n * Returns the last 25 confirmed transactions plus any unconfirmed (mempool) transactions.\n * This is useful for checking if a specific transaction has been broadcast.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of recent transactions\n */\nexport async function getAddressTxs(\n address: string,\n apiUrl: string,\n): Promise<AddressTx[]> {\n assertValidAddress(address);\n return fetchApi<AddressTx[]>(`${apiUrl}/address/${address}/txs`);\n}\n\n/**\n * Fetches Bitcoin network fee recommendations from mempool.space API.\n *\n * @param apiUrl - Mempool API base URL\n * @returns Fee rates in sat/vbyte for different confirmation times\n * @throws Error if request fails or returns invalid data\n *\n * @see https://mempool.space/docs/api/rest#get-recommended-fees\n */\nexport async function getNetworkFees(apiUrl: string): Promise<NetworkFees> {\n const response = await fetchWithTimeout(`${apiUrl}/v1/fees/recommended`);\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch network fees: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n\n const feeFields = [\n \"fastestFee\",\n \"halfHourFee\",\n \"hourFee\",\n \"economyFee\",\n \"minimumFee\",\n ] as const;\n\n for (const field of feeFields) {\n if (!isValidFeeRate(data[field])) {\n throw new Error(\n `Invalid fee rate ${field}=${data[field]} from mempool API: expected a positive number ≤ ${MAX_FEE_RATE}`,\n );\n }\n }\n\n if (\n data.minimumFee > data.economyFee ||\n data.economyFee > data.hourFee ||\n data.hourFee > data.halfHourFee ||\n data.halfHourFee > data.fastestFee\n ) {\n throw new Error(\n `Fee rate ordering violation from mempool API: expected ` +\n `minimumFee (${data.minimumFee}) <= economyFee (${data.economyFee}) <= ` +\n `hourFee (${data.hourFee}) <= halfHourFee (${data.halfHourFee}) <= ` +\n `fastestFee (${data.fastestFee}).`,\n );\n }\n\n return data as NetworkFees;\n}\n\n"],"names":["BIP322_TAG","TAPTWEAK_TAG","X_ONLY_PUBKEY_SIZE","SCHNORR_SIG_SIZE","COMPRESSED_PUBKEY_SIZE","P2WPKH_ENCODED_SIG_MIN","P2WPKH_ENCODED_SIG_MAX","ZERO_SATS","BIP322_TX_VERSION","BIP322_TX_LOCKTIME","BIP322_INPUT_SEQUENCE","TO_SPEND_PREVOUT_TXID_BYTES","TO_SPEND_PREVOUT_INDEX","TO_SPEND_OUTPUT_INDEX","OP_0","OP_PUSHBYTES_32","OP_RETURN","taggedHash","tag","data","tagBytes","tagHash","sha256","preimage","tweakXOnlyKey","xOnly","tweak","tweaked","ecc","buildToSignTransaction","messageBytes","scriptPubKey","messageHash","toSpend","Transaction","scriptSig","Buffer","toSign","verifyBip322Simple","xOnlyPubkey","signature","hashType","p2tr","payments","sighash","tweakedXOnly","verifyBip322P2wpkhSimple","compressedPubkey","encodedSignature","bscript","p2wpkh","scriptCode","UINT16_MAX","MAX_BASIS_POINTS","UINT32_MAX","UINT8_MAX","assertValidOffchainParamsVersion","version","validateOffchainParams","params","errors","validateTBVProtocolParams","validatePegInConfiguration","config","assertValidVaultCoreVersion","MAX_VP_COMMISSION_BPS","mapVaultBasicInfo","result","mapVaultProtocolInfo","offchainParamsVersion","UINT64_EXCLUSIVE_UPPER_BOUND","VP_GENESIS_KEY_EPOCH","assertEpochInRange","value","field","vaultId","mapKeyEpochs","ViemVaultRegistryReader","publicClient","contractAddress","vpAddress","BTCVaultRegistryABI","assertOnChainBtcPubkey","BTCVaultRegistryKeyEpochsABI","vaultIds","info","vaultProvider","bps","basicRaw","protocolRaw","basic","protocol","MAX_SATOSHIS","MEMPOOL_REQUEST_TIMEOUT_MS","fetchWithTimeout","url","options","controller","timeoutId","signals","combined","combineAbortSignals","error","MAX_FEE_RATE","isValidSatoshiValue","isValidFeeRate","isValidVout","vout","outputCount","assertValidTxid","txid","TXID_RE","assertValidAddress","address","BITCOIN_ADDRESS_RE","assertValidScriptPubKey","context","HEX_RE","KNOWN_SCRIPT_PREFIXES","prefix","MEMPOOL_API_URLS","fetchApi","response","errorText","contentType","pushTx","txHex","apiUrl","message","errorJson","getTxInfo","getTipHeight","raw","trimmed","getOutspend","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","feeFields"],"mappings":"gpBA6CMA,EAAa,yBAGbC,GAAe,WAEfC,EAAqB,GACrBC,GAAmB,GAEnBC,GAAyB,GAQlBC,EAAyB,GACzBC,EAAyB,GAQhCC,EAAY,EAIZC,EAAoB,EACpBC,EAAqB,EACrBC,EAAwB,EAExBC,GAA8B,GAC9BC,GAAyB,WAEzBC,GAAwB,EACxBC,GAAO,EAEPC,GAAkB,GAClBC,GAAY,IAMlB,SAASC,EAAWC,EAAaC,EAA8B,CAC7D,MAAMC,EAAW,IAAI,cAAc,OAAOF,CAAG,EACvCG,EAAUC,EAAAA,OAAOF,CAAQ,EACzBG,EAAW,IAAI,WAAWF,EAAQ,OAAS,EAAIF,EAAK,MAAM,EAChE,OAAAI,EAAS,IAAIF,EAAS,CAAC,EACvBE,EAAS,IAAIF,EAASA,EAAQ,MAAM,EACpCE,EAAS,IAAIJ,EAAME,EAA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D,EAAKuD,CAAK,CAAC,mDAAmD6B,CAAY,EAAA,EAK7G,GACEpF,EAAK,WAAaA,EAAK,YACvBA,EAAK,WAAaA,EAAK,SACvBA,EAAK,QAAUA,EAAK,aACpBA,EAAK,YAAcA,EAAK,WAExB,MAAM,IAAI,MACR,sEACiBA,EAAK,UAAU,oBAAoBA,EAAK,UAAU,iBACrDA,EAAK,OAAO,qBAAqBA,EAAK,WAAW,oBAC9CA,EAAK,UAAU,IAAA,EAIpC,OAAOA,CACT"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("../../../mempoolApi-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("../../../mempoolApi-BJN9fGEd.cjs"),e=require("../../../batchPoll-C9cZ5usJ.cjs"),r=require("../../../json-rpc-client-BiAmg_ho.cjs"),o=require("../../../onChainBtcPubkey-C_a2L3kL.cjs");exports.MEMPOOL_API_URLS=t.MEMPOOL_API_URLS;exports.ViemVaultRegistryReader=t.ViemVaultRegistryReader;exports.getAddressTxs=t.getAddressTxs;exports.getAddressUtxos=t.getAddressUtxos;exports.getMempoolApiUrl=t.getMempoolApiUrl;exports.getNetworkFees=t.getNetworkFees;exports.getOutspend=t.getOutspend;exports.getTipHeight=t.getTipHeight;exports.getTxHex=t.getTxHex;exports.getTxInfo=t.getTxInfo;exports.getUtxoInfo=t.getUtxoInfo;exports.pushTx=t.pushTx;exports.validateOffchainParams=t.validateOffchainParams;exports.validatePegInConfiguration=t.validatePegInConfiguration;exports.validateTBVProtocolParams=t.validateTBVProtocolParams;exports.OnChainBtcVaultStatus=e.OnChainBtcVaultStatus;exports.ServerIdentityError=e.ServerIdentityError;exports.VaultProviderRpcClient=e.VaultProviderRpcClient;exports.ViemOperationKeyReader=e.ViemOperationKeyReader;exports.ViemProtocolParamsReader=e.ViemProtocolParamsReader;exports.ViemUniversalChallengerReader=e.ViemUniversalChallengerReader;exports.ViemVaultKeeperReader=e.ViemVaultKeeperReader;exports.VpResponseValidationError=e.VpResponseValidationError;exports.VpTokenRegistry=e.VpTokenRegistry;exports.batchPollByProvider=e.batchPollByProvider;exports.createAuthenticatedVpClient=e.createAuthenticatedVpClient;exports.primeVpTokenRegistry=e.primeVpTokenRegistry;exports.resolveProtocolAddresses=e.resolveProtocolAddresses;exports.validateRequestDepositorClaimerArtifactsResponse=e.validateRequestDepositorClaimerArtifactsResponse;exports.verifyServerIdentity=e.verifyServerIdentity;exports.vpTokenRegistry=e.vpTokenRegistry;exports.AUTH_REJECTED_RPC_CODE=r.AUTH_REJECTED_RPC_CODE;exports.DaemonStatus=r.DaemonStatus;exports.JSON_RPC_ERROR_CODES=r.JSON_RPC_ERROR_CODES;exports.JsonRpcClient=r.JsonRpcClient;exports.JsonRpcError=r.JsonRpcError;exports.POST_WOTS_STATUSES=r.POST_WOTS_STATUSES;exports.PRE_DEPOSITOR_SIGNATURES_STATES=r.PRE_DEPOSITOR_SIGNATURES_STATES;exports.RpcErrorCode=r.RpcErrorCode;exports.VP_BATCH_MAX_SIZE=r.VP_BATCH_MAX_SIZE;exports.VP_TERMINAL_FAILURE_STATUSES=r.VP_TERMINAL_FAILURE_STATUSES;exports.VP_TRANSIENT_STATUSES=r.VP_TRANSIENT_STATUSES;exports.isAuthRejectedError=r.isAuthRejectedError;exports.assertOnChainBtcPubkey=o.assertOnChainBtcPubkey;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { M as s, V as r, g as t, a as o, b as i, c as R, d as n, e as d, f as T, h as p, i as S, p as l, v as E, j as P, k as V } from "../../../mempoolApi-
|
|
2
|
-
import { O as A, S as g, V as c, g as m, h as O, i as C, j as v, a as f, d as u, b as I, f as h, p as x, r as U, v as y, c as D, e as k } from "../../../batchPoll-
|
|
1
|
+
import { M as s, V as r, g as t, a as o, b as i, c as R, d as n, e as d, f as T, h as p, i as S, p as l, v as E, j as P, k as V } from "../../../mempoolApi-71R_CNZa.js";
|
|
2
|
+
import { O as A, S as g, V as c, g as m, h as O, i as C, j as v, a as f, d as u, b as I, f as h, p as x, r as U, v as y, c as D, e as k } from "../../../batchPoll-Bc_UKaTz.js";
|
|
3
3
|
import { A as N, D as b, J as B, a as J, b as H, d as L, P as j, R as F, e as K, c as q, V as w, i as G } from "../../../json-rpc-client-DuUARJvV.js";
|
|
4
4
|
import { a as X } from "../../../onChainBtcPubkey-BAHZyKQL.js";
|
|
5
5
|
export {
|
|
@@ -35,6 +35,15 @@
|
|
|
35
35
|
*
|
|
36
36
|
* @module tbv/core/clients/vault-provider/auth/bip322Verify
|
|
37
37
|
*/
|
|
38
|
+
/**
|
|
39
|
+
* vaultd's P2WPKH BIP-322 verifier accepts ONLY 71/72-byte encoded
|
|
40
|
+
* signatures — DER (70/71B) + sighash byte (`bip322` crate 0.0.10
|
|
41
|
+
* `verify.rs:141-153`). A shorter (short-DER) signature fails ingestion
|
|
42
|
+
* permanently, so this gate must be exactly as strict. Exported so
|
|
43
|
+
* `verifyPopWitness` can pre-screen with a cause-naming error.
|
|
44
|
+
*/
|
|
45
|
+
export declare const P2WPKH_ENCODED_SIG_MIN = 71;
|
|
46
|
+
export declare const P2WPKH_ENCODED_SIG_MAX = 72;
|
|
38
47
|
/**
|
|
39
48
|
* Verify a BIP-322 "simple" P2TR key-path signature over an arbitrary
|
|
40
49
|
* byte message.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bip322Verify.d.ts","sourceRoot":"","sources":["../../../../../../src/tbv/core/clients/vault-provider/auth/bip322Verify.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;
|
|
1
|
+
{"version":3,"file":"bip322Verify.d.ts","sourceRoot":"","sources":["../../../../../../src/tbv/core/clients/vault-provider/auth/bip322Verify.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AAkBH;;;;;;GAMG;AACH,eAAO,MAAM,sBAAsB,KAAK,CAAC;AACzC,eAAO,MAAM,sBAAsB,KAAK,CAAC;AAgGzC;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,kBAAkB,CAChC,YAAY,EAAE,UAAU,EACxB,WAAW,EAAE,UAAU,EACvB,SAAS,EAAE,UAAU,EACrB,QAAQ,GAAE,MAAoC,GAC7C,OAAO,CA6CT;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,wBAAwB,CACtC,YAAY,EAAE,UAAU,EACxB,gBAAgB,EAAE,UAAU,EAC5B,gBAAgB,EAAE,UAAU,GAC3B,OAAO,CAoDT"}
|
package/dist/tbv/core/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("../../verifyScriptPathSchnorrSignature-la8XOAFm.cjs"),_=require("../../constants-DU5CGcqO.cjs"),P=require("@babylonlabs-io/babylon-tbv-rust-wasm"),E=require("../../verifyKeyPathSchnorrSignature-DCOzQkDf.cjs"),T=require("../../noPayout-Ox27Td9x.cjs"),m=require("../../challengeAssert-BrpC3-cQ.cjs"),r=require("../../bitcoin-m84N5a8o.cjs"),l=require("../../validation-CDbOaDj7.cjs"),O=require("../../signing-Bnsro0hE.cjs"),c=require("../../PeginManager-CKWq8ouZ.cjs"),d=require("../../signPsbtsWithFallback-DJ4kE9UI.cjs"),R=require("../../ProtocolParams.abi-CYZoV2EI.cjs"),C=require("../../BTCVaultRegistry.abi-z7d_eP22.cjs"),b=require("../../BTCVaultRegistryKeyEpochs.abi-_NERAdc5.cjs"),g=require("../../errors-CGcNP0rV.cjs"),p=require("../../parseFundingOutpoints-CIO9Ok1L.cjs"),s=require("../../waitForTransactionReceiptSmartAware-AgZ-3WV_.cjs"),a=require("../../fundPeginTransaction-BLD8FRL9.cjs"),S=require("../../reservation-CDbInVw0.cjs"),o=require("../../mempoolApi-EU1La9wk.cjs"),i=require("../../batchPoll-REVZiE-M.cjs"),n=require("../../json-rpc-client-BiAmg_ho.cjs"),y=require("../../onChainBtcPubkey-C_a2L3kL.cjs"),t=require("../../toRefundInputs-D8sFs44p.cjs"),e=require("../../buildAndBroadcastRefund-DrXwxrW1.cjs"),A=require("../../peginState-eaQ4IO_R.cjs");exports.PsbtSubstitutionError=u.PsbtSubstitutionError;exports.assertPsbtUnsignedTxMatches=u.assertPsbtUnsignedTxMatches;exports.assertScriptPathSchnorrSignature=u.assertScriptPathSchnorrSignature;exports.buildPayoutPsbt=u.buildPayoutPsbt;exports.buildPeginTxFromFundedPrePegin=u.buildPeginTxFromFundedPrePegin;exports.buildPrePeginPsbt=u.buildPrePeginPsbt;exports.computeNumLocalChallengers=u.computeNumLocalChallengers;exports.createPayoutScript=u.createPayoutScript;exports.extractPayoutSignature=u.extractPayoutSignature;exports.assertValidVaultCoreVersion=_.assertValidVaultCoreVersion;Object.defineProperty(exports,"computeMinClaimValue",{enumerable:!0,get:()=>P.computeMinClaimValue});Object.defineProperty(exports,"computeMinPeginFee",{enumerable:!0,get:()=>P.computeMinPeginFee});Object.defineProperty(exports,"deriveVaultId",{enumerable:!0,get:()=>P.deriveVaultId});Object.defineProperty(exports,"expandAuthAnchor",{enumerable:!0,get:()=>P.expandAuthAnchor});Object.defineProperty(exports,"expandHashlockSecret",{enumerable:!0,get:()=>P.expandHashlockSecret});Object.defineProperty(exports,"expandWotsSeed",{enumerable:!0,get:()=>P.expandWotsSeed});Object.defineProperty(exports,"peginP2aAnchorOutput",{enumerable:!0,get:()=>P.peginP2aAnchorOutput});Object.defineProperty(exports,"supportedTxGraphVersions",{enumerable:!0,get:()=>P.supportedTxGraphVersions});Object.defineProperty(exports,"validatePeginP2aAnchor",{enumerable:!0,get:()=>P.validatePeginP2aAnchor});exports.assertKeyPathSchnorrSignature=E.assertKeyPathSchnorrSignature;exports.assertReturnedKeyPathSignatures=E.assertReturnedKeyPathSignatures;exports.buildPeginInputPsbt=E.buildPeginInputPsbt;exports.extractPeginInputSignature=E.extractPeginInputSignature;exports.finalizePeginInputPsbt=E.finalizePeginInputPsbt;exports.buildNoPayoutPsbt=T.buildNoPayoutPsbt;exports.buildRefundPsbt=T.buildRefundPsbt;exports.buildChallengeAssertPsbt=m.buildChallengeAssertPsbt;exports.canonicalizeBtcPubkey=r.canonicalizeBtcPubkey;exports.deriveBip86ScriptPubKeyHex=r.deriveBip86ScriptPubKeyHex;exports.deriveNativeSegwitAddress=r.deriveNativeSegwitAddress;exports.deriveTaprootAddress=r.deriveTaprootAddress;exports.ensureHexPrefix=r.ensureHexPrefix;exports.formatSatoshisToBtc=r.formatSatoshisToBtc;exports.getNetwork=r.getNetwork;exports.getSortedXOnlyPubkeys=r.getSortedXOnlyPubkeys;exports.hexToUint8Array=r.hexToUint8Array;exports.isAddressFromPublicKey=r.isAddressFromPublicKey;exports.isValidHex=r.isValidHex;exports.processPublicKeyToXOnly=r.processPublicKeyToXOnly;exports.stripHexPrefix=r.stripHexPrefix;exports.toXOnly=r.toXOnly;exports.uint8ArrayToHex=r.uint8ArrayToHex;exports.validateWalletPubkey=r.validateWalletPubkey;exports.BITCOIN_ADDRESS_RE=l.BITCOIN_ADDRESS_RE;exports.HEX_RE=l.HEX_RE;exports.KNOWN_SCRIPT_PREFIXES=l.KNOWN_SCRIPT_PREFIXES;exports.MAX_REASONABLE_FEE_SATS=l.MAX_REASONABLE_FEE_SATS;exports.TXID_RE=l.TXID_RE;exports.combineAbortSignals=l.combineAbortSignals;exports.createTaprootScriptPathSignOptions=O.createTaprootScriptPathSignOptions;exports.COMMISSION_BPS_HEADROOM=c.COMMISSION_BPS_HEADROOM;exports.MAX_ACCEPTABLE_COMMISSION_BPS_CAP=c.MAX_ACCEPTABLE_COMMISSION_BPS_CAP;exports.PeginManager=c.PeginManager;exports.buildDepositTerms=c.buildDepositTerms;exports.capMaxAcceptableCommissionBps=c.capMaxAcceptableCommissionBps;exports.computeWotsBlockPublicKeysHash=c.computeWotsBlockPublicKeysHash;exports.deriveWotsBlocksFromSeed=c.deriveWotsBlocksFromSeed;exports.ensurePrePeginTermsApproval=c.ensurePrePeginTermsApproval;exports.estimateSubmitPeginRequestBatchGas=c.estimateSubmitPeginRequestBatchGas;exports.PayoutManager=d.PayoutManager;exports.computeHashlock=d.computeHashlock;exports.forwardDepositApproval=d.forwardDepositApproval;exports.requireChangeAddress=d.requireChangeAddress;exports.supportsDepositApproval=d.supportsDepositApproval;exports.validateSecretAgainstHashlock=d.validateSecretAgainstHashlock;exports.ApplicationRegistryABI=R.ApplicationRegistryABI;exports.ProtocolParamsABI=R.ProtocolParamsABI;exports.BTCVaultRegistryABI=C.BTCVaultRegistryABI;exports.BTCVaultRegistryKeyEpochsABI=b.BTCVaultRegistryKeyEpochsABI;exports.CONTRACT_ERRORS=g.CONTRACT_ERRORS;exports.extractErrorData=g.extractErrorData;exports.getContractErrorMessage=g.getContractErrorMessage;exports.handleContractError=g.handleContractError;exports.isKnownContractError=g.isKnownContractError;exports.VAULT_APP_NAME=p.VAULT_APP_NAME;exports.buildFundingOutpointsCommitment=p.buildFundingOutpointsCommitment;exports.buildVaultContext=p.buildVaultContext;exports.deriveVaultRoot=p.deriveVaultRoot;exports.forwardDeriveContextHash=p.forwardDeriveContextHash;exports.parseFundingOutpointsFromTx=p.parseFundingOutpointsFromTx;exports.BitcoinScriptType=s.BitcoinScriptType;exports.applyChangeOutputPolicy=s.applyChangeOutputPolicy;exports.calculateBtcTxHash=s.calculateBtcTxHash;exports.computeChangeOutputFeeSats=s.computeChangeOutputFeeSats;exports.computeMaxDeposit=s.computeMaxDeposit;exports.computePeginBaseFeeSats=s.computePeginBaseFeeSats;exports.getDustThreshold=s.getDustThreshold;exports.getPsbtInputFields=s.getPsbtInputFields;exports.getScriptType=s.getScriptType;exports.selectUtxosForPegin=s.selectUtxosForPegin;exports.shouldAddChangeOutput=s.shouldAddChangeOutput;exports.waitForTransactionReceiptSmartAware=s.waitForTransactionReceiptSmartAware;exports.BTC_DUST_SAT=a.BTC_DUST_SAT;exports.DUST_THRESHOLD=a.DUST_THRESHOLD;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=a.LOW_RATE_ESTIMATION_ACCURACY_BUFFER;exports.MAX_NON_LEGACY_OUTPUT_SIZE=a.MAX_NON_LEGACY_OUTPUT_SIZE;exports.MAX_REASONABLE_PEGIN_VBYTES=a.MAX_REASONABLE_PEGIN_VBYTES;exports.P2TR_INPUT_SIZE=a.P2TR_INPUT_SIZE;exports.PEGIN_AUTH_ANCHOR_OUTPUTS=a.PEGIN_AUTH_ANCHOR_OUTPUTS;exports.PEGIN_FIXED_OUTPUTS=a.PEGIN_FIXED_OUTPUTS;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=a.SPLIT_TX_FEE_SAFETY_MULTIPLIER;exports.TX_BUFFER_SIZE_OVERHEAD=a.TX_BUFFER_SIZE_OVERHEAD;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=a.WALLET_RELAY_FEE_RATE_THRESHOLD;exports.fundPeginTransaction=a.fundPeginTransaction;exports.parseUnfundedWasmTransaction=a.parseUnfundedWasmTransaction;exports.peginOutputCount=a.peginOutputCount;exports.rateBasedTxBufferFee=a.rateBasedTxBufferFee;exports.UtxoNotAvailableError=S.UtxoNotAvailableError;exports.assertUtxosAvailable=S.assertUtxosAvailable;exports.extractInputsFromTransaction=S.extractInputsFromTransaction;exports.findOverlappingPendingVaults=S.findOverlappingPendingVaults;exports.validateUtxosAvailable=S.validateUtxosAvailable;exports.MEMPOOL_API_URLS=o.MEMPOOL_API_URLS;exports.ViemVaultRegistryReader=o.ViemVaultRegistryReader;exports.getAddressTxs=o.getAddressTxs;exports.getAddressUtxos=o.getAddressUtxos;exports.getMempoolApiUrl=o.getMempoolApiUrl;exports.getNetworkFees=o.getNetworkFees;exports.getOutspend=o.getOutspend;exports.getTipHeight=o.getTipHeight;exports.getTxHex=o.getTxHex;exports.getTxInfo=o.getTxInfo;exports.getUtxoInfo=o.getUtxoInfo;exports.pushTx=o.pushTx;exports.validateOffchainParams=o.validateOffchainParams;exports.validatePegInConfiguration=o.validatePegInConfiguration;exports.validateTBVProtocolParams=o.validateTBVProtocolParams;exports.OnChainBtcVaultStatus=i.OnChainBtcVaultStatus;exports.ServerIdentityError=i.ServerIdentityError;exports.VaultProviderRpcClient=i.VaultProviderRpcClient;exports.ViemOperationKeyReader=i.ViemOperationKeyReader;exports.ViemProtocolParamsReader=i.ViemProtocolParamsReader;exports.ViemUniversalChallengerReader=i.ViemUniversalChallengerReader;exports.ViemVaultKeeperReader=i.ViemVaultKeeperReader;exports.VpResponseValidationError=i.VpResponseValidationError;exports.VpTokenRegistry=i.VpTokenRegistry;exports.batchPollByProvider=i.batchPollByProvider;exports.createAuthenticatedVpClient=i.createAuthenticatedVpClient;exports.primeVpTokenRegistry=i.primeVpTokenRegistry;exports.resolveProtocolAddresses=i.resolveProtocolAddresses;exports.validateRequestDepositorClaimerArtifactsResponse=i.validateRequestDepositorClaimerArtifactsResponse;exports.verifyServerIdentity=i.verifyServerIdentity;exports.vpTokenRegistry=i.vpTokenRegistry;exports.AUTH_REJECTED_RPC_CODE=n.AUTH_REJECTED_RPC_CODE;exports.DaemonStatus=n.DaemonStatus;exports.JSON_RPC_ERROR_CODES=n.JSON_RPC_ERROR_CODES;exports.JsonRpcClient=n.JsonRpcClient;exports.JsonRpcError=n.JsonRpcError;exports.POST_WOTS_STATUSES=n.POST_WOTS_STATUSES;exports.PRE_DEPOSITOR_SIGNATURES_STATES=n.PRE_DEPOSITOR_SIGNATURES_STATES;exports.RpcErrorCode=n.RpcErrorCode;exports.VP_BATCH_MAX_SIZE=n.VP_BATCH_MAX_SIZE;exports.VP_TERMINAL_FAILURE_STATUSES=n.VP_TERMINAL_FAILURE_STATUSES;exports.VP_TRANSIENT_STATUSES=n.VP_TRANSIENT_STATUSES;exports.isAuthRejectedError=n.isAuthRejectedError;exports.assertOnChainBtcPubkey=y.assertOnChainBtcPubkey;exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=t.DEPOSIT_TERMS_REJECTED_ERROR_NAME;exports.DepositTermsRejectedError=t.DepositTermsRejectedError;exports.PeginParamsAmbiguousError=t.PeginParamsAmbiguousError;exports.PeginParamsIncompleteSpaceError=t.PeginParamsIncompleteSpaceError;exports.PeginParamsNotFoundError=t.PeginParamsNotFoundError;exports.PeginSizingIntegrityError=t.PeginSizingIntegrityError;exports.UnanchoredPrePeginError=t.UnanchoredPrePeginError;exports.VaultRootMismatchError=t.VaultRootMismatchError;exports.buildPeginParamsCandidates=t.buildPeginParamsCandidates;exports.deriveHashlocksFromPrePegin=t.deriveHashlocksFromPrePegin;exports.describePeginParamsCandidate=t.describePeginParamsCandidate;exports.describeUnresolvedVersion=t.describeUnresolvedVersion;exports.isDepositTermsRejectedError=t.isDepositTermsRejectedError;exports.isWotsMismatchError=t.isWotsMismatchError;exports.rebuildDepositTermsCore=t.rebuildDepositTermsCore;exports.reconstructPeginParams=t.reconstructPeginParams;exports.toRefundInputs=t.toRefundInputs;exports.BIP68NotMatureError=e.BIP68NotMatureError;exports.ClaimerPegoutStatusValue=e.ClaimerPegoutStatusValue;exports.PEGIN_ETH_CONFIRMATIONS=e.PEGIN_ETH_CONFIRMATIONS;exports.ParticipantKeyDriftError=e.ParticipantKeyDriftError;exports.PeginRegistrationMissingError=e.PeginRegistrationMissingError;exports.PeginRegistrationNotFinalError=e.PeginRegistrationNotFinalError;exports.REFUND_MAX_FEE_FRACTION_DENOMINATOR=e.REFUND_MAX_FEE_FRACTION_DENOMINATOR;exports.REFUND_MAX_FEE_FRACTION_NUMERATOR=e.REFUND_MAX_FEE_FRACTION_NUMERATOR;exports.REFUND_MAX_FEE_RATE_SATS_VB=e.REFUND_MAX_FEE_RATE_SATS_VB;exports.REFUND_VSIZE=e.REFUND_VSIZE;exports.RegisteredVaultVersionMismatchError=e.RegisteredVaultVersionMismatchError;exports.activateVault=e.activateVault;exports.activateVaultAndRedeem=e.activateVaultAndRedeem;exports.assertVaultProviderHintAccepted=e.assertVaultProviderHintAccepted;exports.buildAndBroadcastRefund=e.buildAndBroadcastRefund;exports.estimateRefundFeeSats=e.estimateRefundFeeSats;exports.isDepositAmountValid=e.isDepositAmountValid;exports.isHintAccepted=e.isHintAccepted;exports.isParticipantKeyDriftError=e.isParticipantKeyDriftError;exports.isPeginRegistrationMissingError=e.isPeginRegistrationMissingError;exports.isPeginRegistrationNotFinalError=e.isPeginRegistrationNotFinalError;exports.isPegoutTerminalStatus=e.isPegoutTerminalStatus;exports.isRecognizedPegoutStatus=e.isRecognizedPegoutStatus;exports.isRegisteredVaultVersionMismatchError=e.isRegisteredVaultVersionMismatchError;exports.matchKeyHint=e.matchKeyHint;exports.matchKeySetHint=e.matchKeySetHint;exports.resolveCurrentParticipantKeys=e.resolveCurrentParticipantKeys;exports.resolveParticipantKeysAtEpochs=e.resolveParticipantKeysAtEpochs;exports.runDepositorPresignFlow=e.runDepositorPresignFlow;exports.signDepositorGraph=e.signDepositorGraph;exports.submitWotsPublicKey=e.submitWotsPublicKey;exports.validateDepositAmount=e.validateDepositAmount;exports.validateMultiVaultDepositInputs=e.validateMultiVaultDepositInputs;exports.validateOnChainParticipantKeys=e.validateOnChainParticipantKeys;exports.validateProviderSelection=e.validateProviderSelection;exports.validateRemainingCapacity=e.validateRemainingCapacity;exports.validateVaultAmounts=e.validateVaultAmounts;exports.validateVaultProviderPubkey=e.validateVaultProviderPubkey;exports.verifyRegisteredParticipantKeys=e.verifyRegisteredParticipantKeys;exports.verifyRegisteredVaultVersions=e.verifyRegisteredVaultVersions;exports.waitForPeginRegistrationDepth=e.waitForPeginRegistrationDepth;exports.waitForPeginStatus=e.waitForPeginStatus;exports.ContractStatus=A.ContractStatus;exports.PeginAction=A.PeginAction;exports.canPerformAction=A.canPerformAction;exports.getPeginProtocolState=A.getPeginProtocolState;exports.isActivationDeadlinePassedOnChain=A.isActivationDeadlinePassedOnChain;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("../../verifyScriptPathSchnorrSignature-la8XOAFm.cjs"),_=require("../../constants-DU5CGcqO.cjs"),P=require("@babylonlabs-io/babylon-tbv-rust-wasm"),E=require("../../verifyKeyPathSchnorrSignature-Cr5T4Aym.cjs"),T=require("../../noPayout-Ox27Td9x.cjs"),m=require("../../challengeAssert-BrpC3-cQ.cjs"),r=require("../../bitcoin-m84N5a8o.cjs"),l=require("../../validation-CDbOaDj7.cjs"),O=require("../../signing-Bnsro0hE.cjs"),c=require("../../PeginManager-C5NWzGT7.cjs"),d=require("../../signPsbtsWithFallback-DJ4kE9UI.cjs"),R=require("../../ProtocolParams.abi-CYZoV2EI.cjs"),C=require("../../BTCVaultRegistry.abi-z7d_eP22.cjs"),b=require("../../BTCVaultRegistryKeyEpochs.abi-_NERAdc5.cjs"),g=require("../../errors-CGcNP0rV.cjs"),p=require("../../parseFundingOutpoints-CIO9Ok1L.cjs"),s=require("../../waitForTransactionReceiptSmartAware-AgZ-3WV_.cjs"),a=require("../../fundPeginTransaction-BLD8FRL9.cjs"),S=require("../../reservation-CDbInVw0.cjs"),o=require("../../mempoolApi-BJN9fGEd.cjs"),i=require("../../batchPoll-C9cZ5usJ.cjs"),n=require("../../json-rpc-client-BiAmg_ho.cjs"),y=require("../../onChainBtcPubkey-C_a2L3kL.cjs"),t=require("../../toRefundInputs-DgDhx_Ut.cjs"),e=require("../../buildAndBroadcastRefund-DrXwxrW1.cjs"),A=require("../../peginState-eaQ4IO_R.cjs");exports.PsbtSubstitutionError=u.PsbtSubstitutionError;exports.assertPsbtUnsignedTxMatches=u.assertPsbtUnsignedTxMatches;exports.assertScriptPathSchnorrSignature=u.assertScriptPathSchnorrSignature;exports.buildPayoutPsbt=u.buildPayoutPsbt;exports.buildPeginTxFromFundedPrePegin=u.buildPeginTxFromFundedPrePegin;exports.buildPrePeginPsbt=u.buildPrePeginPsbt;exports.computeNumLocalChallengers=u.computeNumLocalChallengers;exports.createPayoutScript=u.createPayoutScript;exports.extractPayoutSignature=u.extractPayoutSignature;exports.assertValidVaultCoreVersion=_.assertValidVaultCoreVersion;Object.defineProperty(exports,"computeMinClaimValue",{enumerable:!0,get:()=>P.computeMinClaimValue});Object.defineProperty(exports,"computeMinPeginFee",{enumerable:!0,get:()=>P.computeMinPeginFee});Object.defineProperty(exports,"deriveVaultId",{enumerable:!0,get:()=>P.deriveVaultId});Object.defineProperty(exports,"expandAuthAnchor",{enumerable:!0,get:()=>P.expandAuthAnchor});Object.defineProperty(exports,"expandHashlockSecret",{enumerable:!0,get:()=>P.expandHashlockSecret});Object.defineProperty(exports,"expandWotsSeed",{enumerable:!0,get:()=>P.expandWotsSeed});Object.defineProperty(exports,"peginP2aAnchorOutput",{enumerable:!0,get:()=>P.peginP2aAnchorOutput});Object.defineProperty(exports,"supportedTxGraphVersions",{enumerable:!0,get:()=>P.supportedTxGraphVersions});Object.defineProperty(exports,"validatePeginP2aAnchor",{enumerable:!0,get:()=>P.validatePeginP2aAnchor});exports.assertKeyPathSchnorrSignature=E.assertKeyPathSchnorrSignature;exports.assertReturnedKeyPathSignatures=E.assertReturnedKeyPathSignatures;exports.buildPeginInputPsbt=E.buildPeginInputPsbt;exports.extractPeginInputSignature=E.extractPeginInputSignature;exports.finalizePeginInputPsbt=E.finalizePeginInputPsbt;exports.buildNoPayoutPsbt=T.buildNoPayoutPsbt;exports.buildRefundPsbt=T.buildRefundPsbt;exports.buildChallengeAssertPsbt=m.buildChallengeAssertPsbt;exports.canonicalizeBtcPubkey=r.canonicalizeBtcPubkey;exports.deriveBip86ScriptPubKeyHex=r.deriveBip86ScriptPubKeyHex;exports.deriveNativeSegwitAddress=r.deriveNativeSegwitAddress;exports.deriveTaprootAddress=r.deriveTaprootAddress;exports.ensureHexPrefix=r.ensureHexPrefix;exports.formatSatoshisToBtc=r.formatSatoshisToBtc;exports.getNetwork=r.getNetwork;exports.getSortedXOnlyPubkeys=r.getSortedXOnlyPubkeys;exports.hexToUint8Array=r.hexToUint8Array;exports.isAddressFromPublicKey=r.isAddressFromPublicKey;exports.isValidHex=r.isValidHex;exports.processPublicKeyToXOnly=r.processPublicKeyToXOnly;exports.stripHexPrefix=r.stripHexPrefix;exports.toXOnly=r.toXOnly;exports.uint8ArrayToHex=r.uint8ArrayToHex;exports.validateWalletPubkey=r.validateWalletPubkey;exports.BITCOIN_ADDRESS_RE=l.BITCOIN_ADDRESS_RE;exports.HEX_RE=l.HEX_RE;exports.KNOWN_SCRIPT_PREFIXES=l.KNOWN_SCRIPT_PREFIXES;exports.MAX_REASONABLE_FEE_SATS=l.MAX_REASONABLE_FEE_SATS;exports.TXID_RE=l.TXID_RE;exports.combineAbortSignals=l.combineAbortSignals;exports.createTaprootScriptPathSignOptions=O.createTaprootScriptPathSignOptions;exports.COMMISSION_BPS_HEADROOM=c.COMMISSION_BPS_HEADROOM;exports.MAX_ACCEPTABLE_COMMISSION_BPS_CAP=c.MAX_ACCEPTABLE_COMMISSION_BPS_CAP;exports.PeginManager=c.PeginManager;exports.buildDepositTerms=c.buildDepositTerms;exports.capMaxAcceptableCommissionBps=c.capMaxAcceptableCommissionBps;exports.computeWotsBlockPublicKeysHash=c.computeWotsBlockPublicKeysHash;exports.deriveWotsBlocksFromSeed=c.deriveWotsBlocksFromSeed;exports.ensurePrePeginTermsApproval=c.ensurePrePeginTermsApproval;exports.estimateSubmitPeginRequestBatchGas=c.estimateSubmitPeginRequestBatchGas;exports.PayoutManager=d.PayoutManager;exports.computeHashlock=d.computeHashlock;exports.forwardDepositApproval=d.forwardDepositApproval;exports.requireChangeAddress=d.requireChangeAddress;exports.supportsDepositApproval=d.supportsDepositApproval;exports.validateSecretAgainstHashlock=d.validateSecretAgainstHashlock;exports.ApplicationRegistryABI=R.ApplicationRegistryABI;exports.ProtocolParamsABI=R.ProtocolParamsABI;exports.BTCVaultRegistryABI=C.BTCVaultRegistryABI;exports.BTCVaultRegistryKeyEpochsABI=b.BTCVaultRegistryKeyEpochsABI;exports.CONTRACT_ERRORS=g.CONTRACT_ERRORS;exports.extractErrorData=g.extractErrorData;exports.getContractErrorMessage=g.getContractErrorMessage;exports.handleContractError=g.handleContractError;exports.isKnownContractError=g.isKnownContractError;exports.VAULT_APP_NAME=p.VAULT_APP_NAME;exports.buildFundingOutpointsCommitment=p.buildFundingOutpointsCommitment;exports.buildVaultContext=p.buildVaultContext;exports.deriveVaultRoot=p.deriveVaultRoot;exports.forwardDeriveContextHash=p.forwardDeriveContextHash;exports.parseFundingOutpointsFromTx=p.parseFundingOutpointsFromTx;exports.BitcoinScriptType=s.BitcoinScriptType;exports.applyChangeOutputPolicy=s.applyChangeOutputPolicy;exports.calculateBtcTxHash=s.calculateBtcTxHash;exports.computeChangeOutputFeeSats=s.computeChangeOutputFeeSats;exports.computeMaxDeposit=s.computeMaxDeposit;exports.computePeginBaseFeeSats=s.computePeginBaseFeeSats;exports.getDustThreshold=s.getDustThreshold;exports.getPsbtInputFields=s.getPsbtInputFields;exports.getScriptType=s.getScriptType;exports.selectUtxosForPegin=s.selectUtxosForPegin;exports.shouldAddChangeOutput=s.shouldAddChangeOutput;exports.waitForTransactionReceiptSmartAware=s.waitForTransactionReceiptSmartAware;exports.BTC_DUST_SAT=a.BTC_DUST_SAT;exports.DUST_THRESHOLD=a.DUST_THRESHOLD;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=a.LOW_RATE_ESTIMATION_ACCURACY_BUFFER;exports.MAX_NON_LEGACY_OUTPUT_SIZE=a.MAX_NON_LEGACY_OUTPUT_SIZE;exports.MAX_REASONABLE_PEGIN_VBYTES=a.MAX_REASONABLE_PEGIN_VBYTES;exports.P2TR_INPUT_SIZE=a.P2TR_INPUT_SIZE;exports.PEGIN_AUTH_ANCHOR_OUTPUTS=a.PEGIN_AUTH_ANCHOR_OUTPUTS;exports.PEGIN_FIXED_OUTPUTS=a.PEGIN_FIXED_OUTPUTS;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=a.SPLIT_TX_FEE_SAFETY_MULTIPLIER;exports.TX_BUFFER_SIZE_OVERHEAD=a.TX_BUFFER_SIZE_OVERHEAD;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=a.WALLET_RELAY_FEE_RATE_THRESHOLD;exports.fundPeginTransaction=a.fundPeginTransaction;exports.parseUnfundedWasmTransaction=a.parseUnfundedWasmTransaction;exports.peginOutputCount=a.peginOutputCount;exports.rateBasedTxBufferFee=a.rateBasedTxBufferFee;exports.UtxoNotAvailableError=S.UtxoNotAvailableError;exports.assertUtxosAvailable=S.assertUtxosAvailable;exports.extractInputsFromTransaction=S.extractInputsFromTransaction;exports.findOverlappingPendingVaults=S.findOverlappingPendingVaults;exports.validateUtxosAvailable=S.validateUtxosAvailable;exports.MEMPOOL_API_URLS=o.MEMPOOL_API_URLS;exports.ViemVaultRegistryReader=o.ViemVaultRegistryReader;exports.getAddressTxs=o.getAddressTxs;exports.getAddressUtxos=o.getAddressUtxos;exports.getMempoolApiUrl=o.getMempoolApiUrl;exports.getNetworkFees=o.getNetworkFees;exports.getOutspend=o.getOutspend;exports.getTipHeight=o.getTipHeight;exports.getTxHex=o.getTxHex;exports.getTxInfo=o.getTxInfo;exports.getUtxoInfo=o.getUtxoInfo;exports.pushTx=o.pushTx;exports.validateOffchainParams=o.validateOffchainParams;exports.validatePegInConfiguration=o.validatePegInConfiguration;exports.validateTBVProtocolParams=o.validateTBVProtocolParams;exports.OnChainBtcVaultStatus=i.OnChainBtcVaultStatus;exports.ServerIdentityError=i.ServerIdentityError;exports.VaultProviderRpcClient=i.VaultProviderRpcClient;exports.ViemOperationKeyReader=i.ViemOperationKeyReader;exports.ViemProtocolParamsReader=i.ViemProtocolParamsReader;exports.ViemUniversalChallengerReader=i.ViemUniversalChallengerReader;exports.ViemVaultKeeperReader=i.ViemVaultKeeperReader;exports.VpResponseValidationError=i.VpResponseValidationError;exports.VpTokenRegistry=i.VpTokenRegistry;exports.batchPollByProvider=i.batchPollByProvider;exports.createAuthenticatedVpClient=i.createAuthenticatedVpClient;exports.primeVpTokenRegistry=i.primeVpTokenRegistry;exports.resolveProtocolAddresses=i.resolveProtocolAddresses;exports.validateRequestDepositorClaimerArtifactsResponse=i.validateRequestDepositorClaimerArtifactsResponse;exports.verifyServerIdentity=i.verifyServerIdentity;exports.vpTokenRegistry=i.vpTokenRegistry;exports.AUTH_REJECTED_RPC_CODE=n.AUTH_REJECTED_RPC_CODE;exports.DaemonStatus=n.DaemonStatus;exports.JSON_RPC_ERROR_CODES=n.JSON_RPC_ERROR_CODES;exports.JsonRpcClient=n.JsonRpcClient;exports.JsonRpcError=n.JsonRpcError;exports.POST_WOTS_STATUSES=n.POST_WOTS_STATUSES;exports.PRE_DEPOSITOR_SIGNATURES_STATES=n.PRE_DEPOSITOR_SIGNATURES_STATES;exports.RpcErrorCode=n.RpcErrorCode;exports.VP_BATCH_MAX_SIZE=n.VP_BATCH_MAX_SIZE;exports.VP_TERMINAL_FAILURE_STATUSES=n.VP_TERMINAL_FAILURE_STATUSES;exports.VP_TRANSIENT_STATUSES=n.VP_TRANSIENT_STATUSES;exports.isAuthRejectedError=n.isAuthRejectedError;exports.assertOnChainBtcPubkey=y.assertOnChainBtcPubkey;exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=t.DEPOSIT_TERMS_REJECTED_ERROR_NAME;exports.DepositTermsRejectedError=t.DepositTermsRejectedError;exports.PeginParamsAmbiguousError=t.PeginParamsAmbiguousError;exports.PeginParamsIncompleteSpaceError=t.PeginParamsIncompleteSpaceError;exports.PeginParamsNotFoundError=t.PeginParamsNotFoundError;exports.PeginSizingIntegrityError=t.PeginSizingIntegrityError;exports.UnanchoredPrePeginError=t.UnanchoredPrePeginError;exports.VaultRootMismatchError=t.VaultRootMismatchError;exports.buildPeginParamsCandidates=t.buildPeginParamsCandidates;exports.deriveHashlocksFromPrePegin=t.deriveHashlocksFromPrePegin;exports.describePeginParamsCandidate=t.describePeginParamsCandidate;exports.describeUnresolvedVersion=t.describeUnresolvedVersion;exports.isDepositTermsRejectedError=t.isDepositTermsRejectedError;exports.isWotsMismatchError=t.isWotsMismatchError;exports.rebuildDepositTermsCore=t.rebuildDepositTermsCore;exports.reconstructPeginParams=t.reconstructPeginParams;exports.toRefundInputs=t.toRefundInputs;exports.BIP68NotMatureError=e.BIP68NotMatureError;exports.ClaimerPegoutStatusValue=e.ClaimerPegoutStatusValue;exports.PEGIN_ETH_CONFIRMATIONS=e.PEGIN_ETH_CONFIRMATIONS;exports.ParticipantKeyDriftError=e.ParticipantKeyDriftError;exports.PeginRegistrationMissingError=e.PeginRegistrationMissingError;exports.PeginRegistrationNotFinalError=e.PeginRegistrationNotFinalError;exports.REFUND_MAX_FEE_FRACTION_DENOMINATOR=e.REFUND_MAX_FEE_FRACTION_DENOMINATOR;exports.REFUND_MAX_FEE_FRACTION_NUMERATOR=e.REFUND_MAX_FEE_FRACTION_NUMERATOR;exports.REFUND_MAX_FEE_RATE_SATS_VB=e.REFUND_MAX_FEE_RATE_SATS_VB;exports.REFUND_VSIZE=e.REFUND_VSIZE;exports.RegisteredVaultVersionMismatchError=e.RegisteredVaultVersionMismatchError;exports.activateVault=e.activateVault;exports.activateVaultAndRedeem=e.activateVaultAndRedeem;exports.assertVaultProviderHintAccepted=e.assertVaultProviderHintAccepted;exports.buildAndBroadcastRefund=e.buildAndBroadcastRefund;exports.estimateRefundFeeSats=e.estimateRefundFeeSats;exports.isDepositAmountValid=e.isDepositAmountValid;exports.isHintAccepted=e.isHintAccepted;exports.isParticipantKeyDriftError=e.isParticipantKeyDriftError;exports.isPeginRegistrationMissingError=e.isPeginRegistrationMissingError;exports.isPeginRegistrationNotFinalError=e.isPeginRegistrationNotFinalError;exports.isPegoutTerminalStatus=e.isPegoutTerminalStatus;exports.isRecognizedPegoutStatus=e.isRecognizedPegoutStatus;exports.isRegisteredVaultVersionMismatchError=e.isRegisteredVaultVersionMismatchError;exports.matchKeyHint=e.matchKeyHint;exports.matchKeySetHint=e.matchKeySetHint;exports.resolveCurrentParticipantKeys=e.resolveCurrentParticipantKeys;exports.resolveParticipantKeysAtEpochs=e.resolveParticipantKeysAtEpochs;exports.runDepositorPresignFlow=e.runDepositorPresignFlow;exports.signDepositorGraph=e.signDepositorGraph;exports.submitWotsPublicKey=e.submitWotsPublicKey;exports.validateDepositAmount=e.validateDepositAmount;exports.validateMultiVaultDepositInputs=e.validateMultiVaultDepositInputs;exports.validateOnChainParticipantKeys=e.validateOnChainParticipantKeys;exports.validateProviderSelection=e.validateProviderSelection;exports.validateRemainingCapacity=e.validateRemainingCapacity;exports.validateVaultAmounts=e.validateVaultAmounts;exports.validateVaultProviderPubkey=e.validateVaultProviderPubkey;exports.verifyRegisteredParticipantKeys=e.verifyRegisteredParticipantKeys;exports.verifyRegisteredVaultVersions=e.verifyRegisteredVaultVersions;exports.waitForPeginRegistrationDepth=e.waitForPeginRegistrationDepth;exports.waitForPeginStatus=e.waitForPeginStatus;exports.ContractStatus=A.ContractStatus;exports.PeginAction=A.PeginAction;exports.canPerformAction=A.canPerformAction;exports.getPeginProtocolState=A.getPeginProtocolState;exports.isActivationDeadlinePassedOnChain=A.isActivationDeadlinePassedOnChain;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/tbv/core/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { P as s, f as t, g as r, d as i, b as o, a as n, c as P, h as p, e as u } from "../../verifyScriptPathSchnorrSignature-Dy9gF5RF.js";
|
|
2
2
|
import { a as c } from "../../constants-GjWXdaqV.js";
|
|
3
3
|
import { computeMinClaimValue as E, computeMinPeginFee as g, deriveVaultId as A, expandAuthAnchor as T, expandHashlockSecret as S, expandWotsSeed as R, peginP2aAnchorOutput as m, supportedTxGraphVersions as _, validatePeginP2aAnchor as f } from "@babylonlabs-io/babylon-tbv-rust-wasm";
|
|
4
|
-
import { a as x, c as h, b as O, e as b, f as I } from "../../verifyKeyPathSchnorrSignature-
|
|
4
|
+
import { a as x, c as h, b as O, e as b, f as I } from "../../verifyKeyPathSchnorrSignature-C6Cmk0R1.js";
|
|
5
5
|
import { a as V, b as y } from "../../noPayout-CXn-geIS.js";
|
|
6
6
|
import { b as F } from "../../challengeAssert-BNQ8sToz.js";
|
|
7
7
|
import { c as N, d as B, a as U, b as H, e as K, f as L, k, g as X, h as w, i as W, j as G, p as j, s as J, t as z, u as Y, v as Z } from "../../bitcoin-Ch_jxnDa.js";
|
|
8
8
|
import { B as Q, H as $, K as aa, M as ea, T as sa, c as ta } from "../../validation-Dj3dqYtl.js";
|
|
9
9
|
import { c as ia } from "../../signing-DaLvGwQe.js";
|
|
10
|
-
import { C as na, M as Pa, P as pa, b as ua, a as da, c as ca, d as la, f as Ea, e as ga } from "../../PeginManager
|
|
10
|
+
import { C as na, M as Pa, P as pa, b as ua, a as da, c as ca, d as la, f as Ea, e as ga } from "../../PeginManager-Bsv6caG3.js";
|
|
11
11
|
import { P as Ta, c as Sa, f as Ra, r as ma, s as _a, v as fa } from "../../signPsbtsWithFallback-Bv79gLFe.js";
|
|
12
12
|
import { A as xa, P as ha } from "../../ProtocolParams.abi-C0TSRaHV.js";
|
|
13
13
|
import { B as ba } from "../../BTCVaultRegistry.abi-CJwWI2EO.js";
|
|
@@ -17,11 +17,11 @@ import { V as Ua, b as Ha, a as Ka, d as La, f as ka, p as Xa } from "../../pars
|
|
|
17
17
|
import { B as Wa, a as Ga, f as ja, c as Ja, b as za, d as Ya, g as Za, i as qa, h as Qa, s as $a, e as ae, w as ee } from "../../waitForTransactionReceiptSmartAware-lobLm0q0.js";
|
|
18
18
|
import { B as te, D as re, L as ie, M as oe, c as ne, P as Pe, b as pe, a as ue, S as de, T as ce, W as le, f as Ee, d as ge, p as Ae, r as Te } from "../../fundPeginTransaction-B2wyjqp0.js";
|
|
19
19
|
import { U as Re, a as me, e as _e, f as fe, v as Ce } from "../../reservation-CBAvoF3U.js";
|
|
20
|
-
import { M as he, V as Oe, g as be, a as Ie, b as ve, c as Ve, d as ye, e as De, f as Fe, h as Me, i as Ne, p as Be, v as Ue, j as He, k as Ke } from "../../mempoolApi-
|
|
21
|
-
import { O as ke, S as Xe, V as we, g as We, h as Ge, i as je, j as Je, a as ze, d as Ye, b as Ze, f as qe, p as Qe, r as $e, v as as, c as es, e as ss } from "../../batchPoll-
|
|
20
|
+
import { M as he, V as Oe, g as be, a as Ie, b as ve, c as Ve, d as ye, e as De, f as Fe, h as Me, i as Ne, p as Be, v as Ue, j as He, k as Ke } from "../../mempoolApi-71R_CNZa.js";
|
|
21
|
+
import { O as ke, S as Xe, V as we, g as We, h as Ge, i as je, j as Je, a as ze, d as Ye, b as Ze, f as qe, p as Qe, r as $e, v as as, c as es, e as ss } from "../../batchPoll-Bc_UKaTz.js";
|
|
22
22
|
import { A as rs, D as is, J as os, a as ns, b as Ps, d as ps, P as us, R as ds, e as cs, c as ls, V as Es, i as gs } from "../../json-rpc-client-DuUARJvV.js";
|
|
23
23
|
import { a as Ts } from "../../onChainBtcPubkey-BAHZyKQL.js";
|
|
24
|
-
import { D as Rs, a as ms, h as _s, j as fs, P as Cs, k as xs, U as hs, V as Os, c as bs, d as Is, f as vs, e as Vs, b as ys, i as Ds, r as Fs, g as Ms, t as Ns } from "../../toRefundInputs-
|
|
24
|
+
import { D as Rs, a as ms, h as _s, j as fs, P as Cs, k as xs, U as hs, V as Os, c as bs, d as Is, f as vs, e as Vs, b as ys, i as Ds, r as Fs, g as Ms, t as Ns } from "../../toRefundInputs-4UJfSVEz.js";
|
|
25
25
|
import { H as Us, E as Hs, P as Ks, o as Ls, c as ks, d as Xs, K as ws, L as Ws, M as Gs, N as js, R as Js, a as zs, b as Ys, y as Zs, I as qs, J as Qs, g as $s, z as at, p as et, i as st, e as tt, G as rt, F as it, t as ot, A as nt, B as Pt, C as pt, D as ut, r as dt, s as ct, f as lt, h as Et, j as gt, v as At, k as Tt, l as St, m as Rt, n as mt, q as _t, u as ft, w as Ct, x as xt } from "../../buildAndBroadcastRefund-CpMDJ8up.js";
|
|
26
26
|
import { C as Ot, P as bt, c as It, g as vt, i as Vt } from "../../peginState-CxDiaKuk.js";
|
|
27
27
|
export {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../../PeginManager-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../../../PeginManager-C5NWzGT7.cjs"),a=require("../../../signPsbtsWithFallback-DJ4kE9UI.cjs");exports.PeginManager=e.PeginManager;exports.estimateSubmitPeginRequestBatchGas=e.estimateSubmitPeginRequestBatchGas;exports.PayoutManager=a.PayoutManager;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verifyPopWitness.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/core/managers/pegin/verifyPopWitness.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAIH,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"verifyPopWitness.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/core/managers/pegin/verifyPopWitness.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAIH,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AA2BhC,MAAM,MAAM,iBAAiB,GACzB;IAAE,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAA;CAAE,GAClC;IAAE,QAAQ,CAAC,IAAI,EAAE,iBAAiB,CAAA;CAAE,CAAC;AAgBzC;;;;;;;;;;;;GAYG;AACH,wBAAgB,gBAAgB,CAC9B,YAAY,EAAE,UAAU,EACxB,iBAAiB,EAAE,MAAM,EACzB,UAAU,EAAE,GAAG,GACd,iBAAiB,CAgHnB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("../../../verifyScriptPathSchnorrSignature-la8XOAFm.cjs"),a=require("../../../constants-DU5CGcqO.cjs"),r=require("@babylonlabs-io/babylon-tbv-rust-wasm"),i=require("../../../verifyKeyPathSchnorrSignature-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("../../../verifyScriptPathSchnorrSignature-la8XOAFm.cjs"),a=require("../../../constants-DU5CGcqO.cjs"),r=require("@babylonlabs-io/babylon-tbv-rust-wasm"),i=require("../../../verifyKeyPathSchnorrSignature-Cr5T4Aym.cjs"),n=require("../../../noPayout-Ox27Td9x.cjs"),u=require("../../../challengeAssert-BrpC3-cQ.cjs"),e=require("../../../bitcoin-m84N5a8o.cjs");exports.PsbtSubstitutionError=t.PsbtSubstitutionError;exports.assertPsbtUnsignedTxMatches=t.assertPsbtUnsignedTxMatches;exports.assertScriptPathSchnorrSignature=t.assertScriptPathSchnorrSignature;exports.buildPayoutPsbt=t.buildPayoutPsbt;exports.buildPeginTxFromFundedPrePegin=t.buildPeginTxFromFundedPrePegin;exports.buildPrePeginPsbt=t.buildPrePeginPsbt;exports.computeNumLocalChallengers=t.computeNumLocalChallengers;exports.createPayoutScript=t.createPayoutScript;exports.extractPayoutSignature=t.extractPayoutSignature;exports.assertValidVaultCoreVersion=a.assertValidVaultCoreVersion;Object.defineProperty(exports,"computeMinClaimValue",{enumerable:!0,get:()=>r.computeMinClaimValue});Object.defineProperty(exports,"computeMinPeginFee",{enumerable:!0,get:()=>r.computeMinPeginFee});Object.defineProperty(exports,"deriveVaultId",{enumerable:!0,get:()=>r.deriveVaultId});Object.defineProperty(exports,"peginP2aAnchorOutput",{enumerable:!0,get:()=>r.peginP2aAnchorOutput});Object.defineProperty(exports,"supportedTxGraphVersions",{enumerable:!0,get:()=>r.supportedTxGraphVersions});Object.defineProperty(exports,"validatePeginP2aAnchor",{enumerable:!0,get:()=>r.validatePeginP2aAnchor});exports.assertKeyPathSchnorrSignature=i.assertKeyPathSchnorrSignature;exports.assertReturnedKeyPathSignatures=i.assertReturnedKeyPathSignatures;exports.buildPeginInputPsbt=i.buildPeginInputPsbt;exports.extractPeginInputSignature=i.extractPeginInputSignature;exports.finalizePeginInputPsbt=i.finalizePeginInputPsbt;exports.buildNoPayoutPsbt=n.buildNoPayoutPsbt;exports.buildRefundPsbt=n.buildRefundPsbt;exports.buildChallengeAssertPsbt=u.buildChallengeAssertPsbt;exports.canonicalizeBtcPubkey=e.canonicalizeBtcPubkey;exports.deriveBip86ScriptPubKeyHex=e.deriveBip86ScriptPubKeyHex;exports.deriveNativeSegwitAddress=e.deriveNativeSegwitAddress;exports.deriveTaprootAddress=e.deriveTaprootAddress;exports.ensureHexPrefix=e.ensureHexPrefix;exports.formatSatoshisToBtc=e.formatSatoshisToBtc;exports.getSortedXOnlyPubkeys=e.getSortedXOnlyPubkeys;exports.hexToUint8Array=e.hexToUint8Array;exports.isAddressFromPublicKey=e.isAddressFromPublicKey;exports.isValidHex=e.isValidHex;exports.processPublicKeyToXOnly=e.processPublicKeyToXOnly;exports.stripHexPrefix=e.stripHexPrefix;exports.toXOnly=e.toXOnly;exports.uint8ArrayToHex=e.uint8ArrayToHex;exports.validateWalletPubkey=e.validateWalletPubkey;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { P as s, f as t, g as r, d as i, b as o, a as u, c as n, h as P, e as d } from "../../../verifyScriptPathSchnorrSignature-Dy9gF5RF.js";
|
|
2
2
|
import { a as b } from "../../../constants-GjWXdaqV.js";
|
|
3
3
|
import { computeMinClaimValue as c, computeMinPeginFee as g, deriveVaultId as x, peginP2aAnchorOutput as y, supportedTxGraphVersions as f, validatePeginP2aAnchor as h } from "@babylonlabs-io/babylon-tbv-rust-wasm";
|
|
4
|
-
import { a as S, c as v, b as A, e as T, f as V } from "../../../verifyKeyPathSchnorrSignature-
|
|
4
|
+
import { a as S, c as v, b as A, e as T, f as V } from "../../../verifyKeyPathSchnorrSignature-C6Cmk0R1.js";
|
|
5
5
|
import { a as K, b as C } from "../../../noPayout-CXn-geIS.js";
|
|
6
6
|
import { b as I } from "../../../challengeAssert-BNQ8sToz.js";
|
|
7
7
|
import { c as k, d as B, a as M, b as N, e as X, f as z, g as R, h as U, i as j, j as w, p as E, s as G, t as L, u as W, v as q } from "../../../bitcoin-Ch_jxnDa.js";
|