var __defProp = Object.defineProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};

// ts/index.ts
import { Transaction as Transaction2, Address as Address2, p2wsh as p2wsh2, p2wpkh as p2wpkh2, p2sh as p2sh2, p2pk, p2pkh as p2pkh2 } from "@scure/btc-signer";

// ts/CosignScript.ts
import { p2pkh, p2sh, p2wpkh, p2wsh, Transaction } from "@scure/btc-signer";
import {
  hexToU8a as hexToU8a2,
  u8aEq,
  u8aToHex as u8aToHex2
} from "@argonprotocol/mainchain";

// wasm-module:/home/runner/work/mainchain/mainchain/bitcoin/nodejs/ts/wasm/bitcoin_bindings_bg.wasm
var bitcoin_bindings_bg_exports = {};
__export(bitcoin_bindings_bg_exports, {
  __externref_table_dealloc: () => __externref_table_dealloc,
  __wbindgen_externrefs: () => __wbindgen_externrefs,
  __wbindgen_free: () => __wbindgen_free,
  __wbindgen_malloc: () => __wbindgen_malloc,
  __wbindgen_realloc: () => __wbindgen_realloc,
  __wbindgen_start: () => __wbindgen_start,
  calculateFee: () => calculateFee2,
  createCosignPubkey: () => createCosignPubkey2,
  getCosignPsbt: () => getCosignPsbt2,
  instance: () => instance,
  memory: () => memory,
  module: () => module,
  rustsecp256k1_v0_10_0_context_create: () => rustsecp256k1_v0_10_0_context_create,
  rustsecp256k1_v0_10_0_context_destroy: () => rustsecp256k1_v0_10_0_context_destroy,
  rustsecp256k1_v0_10_0_default_error_callback_fn: () => rustsecp256k1_v0_10_0_default_error_callback_fn,
  rustsecp256k1_v0_10_0_default_illegal_callback_fn: () => rustsecp256k1_v0_10_0_default_illegal_callback_fn,
  signPsbt: () => signPsbt2,
  signPsbtDerived: () => signPsbtDerived2
});

// wasm-deferred:/home/runner/work/mainchain/mainchain/bitcoin/nodejs/ts/wasm/bitcoin_bindings_bg.wasm
var bitcoin_bindings_bg_default = "./bitcoin_bindings_bg-6TUA4LTN.wasm";

// ts/wasm/bitcoin_bindings_bg.js
var BitcoinNetwork = Object.freeze({
  /**
   * Mainnet Bitcoin.
   */
  Bitcoin: 0,
  "0": "Bitcoin",
  /**
   * Bitcoin's testnet network.
   */
  Testnet: 1,
  "1": "Testnet",
  /**
   * Bitcoin's signet network
   */
  Signet: 2,
  "2": "Signet",
  /**
   * Bitcoin's regtest network.
   */
  Regtest: 3,
  "3": "Regtest"
});
function calculateFee(vault_pubkey_hex, vault_claim_pubkey_hex, owner_pubkey_hex, vault_claim_height, open_claim_height, created_at_height, bitcoin_network, fee_rate_sats_per_vb, to_script_pubkey) {
  const ptr0 = passStringToWasm0(vault_pubkey_hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
  const len0 = WASM_VECTOR_LEN;
  const ptr1 = passStringToWasm0(vault_claim_pubkey_hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
  const len1 = WASM_VECTOR_LEN;
  const ptr2 = passStringToWasm0(owner_pubkey_hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
  const len2 = WASM_VECTOR_LEN;
  const ptr3 = passStringToWasm0(to_script_pubkey, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
  const len3 = WASM_VECTOR_LEN;
  const ret = wasm.calculateFee(ptr0, len0, ptr1, len1, ptr2, len2, vault_claim_height, open_claim_height, created_at_height, bitcoin_network, fee_rate_sats_per_vb, ptr3, len3);
  if (ret[2]) {
    throw takeFromExternrefTable0(ret[1]);
  }
  return BigInt.asUintN(64, ret[0]);
}
function createCosignPubkey(vault_pubkey_hex, vault_claim_pubkey_hex, owner_pubkey_hex, vault_claim_height, open_claim_height, created_at_height, bitcoin_network) {
  let deferred5_0;
  let deferred5_1;
  try {
    const ptr0 = passStringToWasm0(vault_pubkey_hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len0 = WASM_VECTOR_LEN;
    const ptr1 = passStringToWasm0(vault_claim_pubkey_hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len1 = WASM_VECTOR_LEN;
    const ptr2 = passStringToWasm0(owner_pubkey_hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len2 = WASM_VECTOR_LEN;
    const ret = wasm.createCosignPubkey(ptr0, len0, ptr1, len1, ptr2, len2, vault_claim_height, open_claim_height, created_at_height, bitcoin_network);
    var ptr4 = ret[0];
    var len4 = ret[1];
    if (ret[3]) {
      ptr4 = 0;
      len4 = 0;
      throw takeFromExternrefTable0(ret[2]);
    }
    deferred5_0 = ptr4;
    deferred5_1 = len4;
    return getStringFromWasm0(ptr4, len4);
  } finally {
    wasm.__wbindgen_free(deferred5_0, deferred5_1, 1);
  }
}
function getCosignPsbt(txid, vout, satoshis, vault_pubkey_hex, vault_claim_pubkey_hex, owner_pubkey_hex, vault_claim_height, open_claim_height, created_at_height, bitcoin_network, to_script_pubkey_hex, bitcoin_network_fee) {
  let deferred7_0;
  let deferred7_1;
  try {
    const ptr0 = passStringToWasm0(txid, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len0 = WASM_VECTOR_LEN;
    const ptr1 = passStringToWasm0(vault_pubkey_hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len1 = WASM_VECTOR_LEN;
    const ptr2 = passStringToWasm0(vault_claim_pubkey_hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len2 = WASM_VECTOR_LEN;
    const ptr3 = passStringToWasm0(owner_pubkey_hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len3 = WASM_VECTOR_LEN;
    const ptr4 = passStringToWasm0(to_script_pubkey_hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len4 = WASM_VECTOR_LEN;
    const ret = wasm.getCosignPsbt(ptr0, len0, vout, satoshis, ptr1, len1, ptr2, len2, ptr3, len3, vault_claim_height, open_claim_height, created_at_height, bitcoin_network, ptr4, len4, bitcoin_network_fee);
    var ptr6 = ret[0];
    var len6 = ret[1];
    if (ret[3]) {
      ptr6 = 0;
      len6 = 0;
      throw takeFromExternrefTable0(ret[2]);
    }
    deferred7_0 = ptr6;
    deferred7_1 = len6;
    return getStringFromWasm0(ptr6, len6);
  } finally {
    wasm.__wbindgen_free(deferred7_0, deferred7_1, 1);
  }
}
function signPsbt(psbt_hex, bitcoin_network, private_key_hex, finalize) {
  let deferred4_0;
  let deferred4_1;
  try {
    const ptr0 = passStringToWasm0(psbt_hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len0 = WASM_VECTOR_LEN;
    const ptr1 = passStringToWasm0(private_key_hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len1 = WASM_VECTOR_LEN;
    const ret = wasm.signPsbt(ptr0, len0, bitcoin_network, ptr1, len1, finalize);
    var ptr3 = ret[0];
    var len3 = ret[1];
    if (ret[3]) {
      ptr3 = 0;
      len3 = 0;
      throw takeFromExternrefTable0(ret[2]);
    }
    deferred4_0 = ptr3;
    deferred4_1 = len3;
    return getStringFromWasm0(ptr3, len3);
  } finally {
    wasm.__wbindgen_free(deferred4_0, deferred4_1, 1);
  }
}
function signPsbtDerived(psbt_hex, xpriv_b58, xpriv_hd_path, finalize) {
  let deferred5_0;
  let deferred5_1;
  try {
    const ptr0 = passStringToWasm0(psbt_hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len0 = WASM_VECTOR_LEN;
    const ptr1 = passStringToWasm0(xpriv_b58, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len1 = WASM_VECTOR_LEN;
    const ptr2 = passStringToWasm0(xpriv_hd_path, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len2 = WASM_VECTOR_LEN;
    const ret = wasm.signPsbtDerived(ptr0, len0, ptr1, len1, ptr2, len2, finalize);
    var ptr4 = ret[0];
    var len4 = ret[1];
    if (ret[3]) {
      ptr4 = 0;
      len4 = 0;
      throw takeFromExternrefTable0(ret[2]);
    }
    deferred5_0 = ptr4;
    deferred5_1 = len4;
    return getStringFromWasm0(ptr4, len4);
  } finally {
    wasm.__wbindgen_free(deferred5_0, deferred5_1, 1);
  }
}
function __wbg___wbindgen_throw_be289d5034ed271b(arg0, arg1) {
  throw new Error(getStringFromWasm0(arg0, arg1));
}
function __wbg_error_7534b8e9a36f1ab4(arg0, arg1) {
  let deferred0_0;
  let deferred0_1;
  try {
    deferred0_0 = arg0;
    deferred0_1 = arg1;
    console.error(getStringFromWasm0(arg0, arg1));
  } finally {
    wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);
  }
}
function __wbg_new_8a6f238a6ece86ea() {
  const ret = new Error();
  return ret;
}
function __wbg_stack_0ed75d68575b0f3c(arg0, arg1) {
  const ret = arg1.stack;
  const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
  const len1 = WASM_VECTOR_LEN;
  getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
  getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
}
function __wbindgen_cast_0000000000000001(arg0, arg1) {
  const ret = getStringFromWasm0(arg0, arg1);
  return ret;
}
function __wbindgen_init_externref_table() {
  const table = wasm.__wbindgen_externrefs;
  const offset = table.grow(4);
  table.set(0, void 0);
  table.set(offset + 0, void 0);
  table.set(offset + 1, null);
  table.set(offset + 2, true);
  table.set(offset + 3, false);
}
var cachedDataViewMemory0 = null;
function getDataViewMemory0() {
  if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || cachedDataViewMemory0.buffer.detached === void 0 && cachedDataViewMemory0.buffer !== wasm.memory.buffer) {
    cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
  }
  return cachedDataViewMemory0;
}
function getStringFromWasm0(ptr, len) {
  ptr = ptr >>> 0;
  return decodeText(ptr, len);
}
var cachedUint8ArrayMemory0 = null;
function getUint8ArrayMemory0() {
  if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
    cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
  }
  return cachedUint8ArrayMemory0;
}
function passStringToWasm0(arg, malloc, realloc) {
  if (realloc === void 0) {
    const buf = cachedTextEncoder.encode(arg);
    const ptr2 = malloc(buf.length, 1) >>> 0;
    getUint8ArrayMemory0().subarray(ptr2, ptr2 + buf.length).set(buf);
    WASM_VECTOR_LEN = buf.length;
    return ptr2;
  }
  let len = arg.length;
  let ptr = malloc(len, 1) >>> 0;
  const mem = getUint8ArrayMemory0();
  let offset = 0;
  for (; offset < len; offset++) {
    const code = arg.charCodeAt(offset);
    if (code > 127) break;
    mem[ptr + offset] = code;
  }
  if (offset !== len) {
    if (offset !== 0) {
      arg = arg.slice(offset);
    }
    ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
    const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
    const ret = cachedTextEncoder.encodeInto(arg, view);
    offset += ret.written;
    ptr = realloc(ptr, len, offset, 1) >>> 0;
  }
  WASM_VECTOR_LEN = offset;
  return ptr;
}
function takeFromExternrefTable0(idx) {
  const value = wasm.__wbindgen_externrefs.get(idx);
  wasm.__externref_table_dealloc(idx);
  return value;
}
var cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true });
cachedTextDecoder.decode();
var MAX_SAFARI_DECODE_BYTES = 2146435072;
var numBytesDecoded = 0;
function decodeText(ptr, len) {
  numBytesDecoded += len;
  if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
    cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true });
    cachedTextDecoder.decode();
    numBytesDecoded = len;
  }
  return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
}
var cachedTextEncoder = new TextEncoder();
if (!("encodeInto" in cachedTextEncoder)) {
  cachedTextEncoder.encodeInto = function(arg, view) {
    const buf = cachedTextEncoder.encode(arg);
    view.set(buf);
    return {
      read: arg.length,
      written: buf.length
    };
  };
}
var WASM_VECTOR_LEN = 0;
var wasm;
function __wbg_set_wasm(val) {
  wasm = val;
}

// wasm-module:/home/runner/work/mainchain/mainchain/bitcoin/nodejs/ts/wasm/bitcoin_bindings_bg.wasm
var imports = {
  ["./bitcoin_bindings_bg.js"]: {
    __wbg_new_8a6f238a6ece86ea,
    __wbg_stack_0ed75d68575b0f3c,
    __wbg_error_7534b8e9a36f1ab4,
    __wbg___wbindgen_throw_be289d5034ed271b,
    __wbindgen_init_externref_table,
    __wbindgen_cast_0000000000000001
  }
};
async function loadWasm(module2, imports2) {
  if (typeof module2 === "string") {
    if (module2.startsWith("./")) {
      module2 = new URL(module2, import.meta.url).href;
    }
    if (module2.startsWith("file://")) {
      const fs = await import("fs");
      module2 = await fs.promises.readFile(new URL(module2));
    } else {
      const moduleRequest = await fetch(module2);
      if (typeof WebAssembly.instantiateStreaming === "function") {
        try {
          return await WebAssembly.instantiateStreaming(moduleRequest, imports2);
        } catch (e) {
          if (moduleRequest.headers.get("Content-Type") != "application/wasm") {
            console.warn(e);
          } else {
            throw e;
          }
        }
      }
      module2 = await moduleRequest.arrayBuffer();
    }
  }
  return await WebAssembly.instantiate(module2, imports2);
}
var { instance, module } = await loadWasm(bitcoin_bindings_bg_default, imports);
var memory = instance.exports.memory;
var createCosignPubkey2 = instance.exports.createCosignPubkey;
var calculateFee2 = instance.exports.calculateFee;
var signPsbtDerived2 = instance.exports.signPsbtDerived;
var signPsbt2 = instance.exports.signPsbt;
var getCosignPsbt2 = instance.exports.getCosignPsbt;
var rustsecp256k1_v0_10_0_context_create = instance.exports.rustsecp256k1_v0_10_0_context_create;
var rustsecp256k1_v0_10_0_context_destroy = instance.exports.rustsecp256k1_v0_10_0_context_destroy;
var rustsecp256k1_v0_10_0_default_illegal_callback_fn = instance.exports.rustsecp256k1_v0_10_0_default_illegal_callback_fn;
var rustsecp256k1_v0_10_0_default_error_callback_fn = instance.exports.rustsecp256k1_v0_10_0_default_error_callback_fn;
var __wbindgen_free = instance.exports.__wbindgen_free;
var __wbindgen_malloc = instance.exports.__wbindgen_malloc;
var __wbindgen_realloc = instance.exports.__wbindgen_realloc;
var __wbindgen_externrefs = instance.exports.__wbindgen_externrefs;
var __externref_table_dealloc = instance.exports.__externref_table_dealloc;
var __wbindgen_start = instance.exports.__wbindgen_start;

// ts/wasm/bitcoin_bindings.js
__wbg_set_wasm(bitcoin_bindings_bg_exports);
__wbindgen_start();

// ts/KeysHelper.ts
import { Address, NETWORK, OutScript, TEST_NETWORK } from "@scure/btc-signer";
import { bech32 } from "@scure/base";
import { HDKey } from "@scure/bip32";
import { hexToU8a, u8aToHex } from "@argonprotocol/mainchain";
import * as secp256k1 from "@noble/secp256k1";
function getBip32Version(network) {
  if (!network) {
    return void 0;
  }
  if (network === BitcoinNetwork.Testnet || network === BitcoinNetwork.Signet) {
    return {
      private: 70615956,
      // tprv
      public: 70617039
      // tpub
    };
  }
  if (network === BitcoinNetwork.Regtest) {
    return {
      private: 70615956,
      // rprv
      public: 70617039
      // rpub
    };
  }
  return void 0;
}
function getChildXpriv(bip39Seed, hdPath, network) {
  const root = HDKey.fromMasterSeed(bip39Seed, getBip32Version(network));
  return root.derive(hdPath);
}
function getXpubFromXpriv(xpriv) {
  return xpriv.publicExtendedKey;
}
function getCompressedPubkey(pubkey) {
  const pubkeyUint8Array = keyToU8a(pubkey);
  if (pubkeyUint8Array.length === 33) {
    return pubkeyUint8Array;
  }
  const point = secp256k1.Point.fromHex(pubkeyUint8Array);
  return point.toRawBytes(true);
}
function getBech32Prefix(network) {
  return getScureNetwork(network).bech32;
}
function p2wshScriptHexToAddress(scriptPubKeyHex, network) {
  const script = hexToU8a(scriptPubKeyHex);
  if (script.byteLength !== 34 || script[0] !== 0 || script[1] !== 32) {
    throw new Error("Invalid P2WSH scriptPubKey");
  }
  const witnessProgram = script.slice(2);
  const version = 0;
  const prefix = getBech32Prefix(network);
  return bech32.encode(prefix, [version, ...bech32.toWords(witnessProgram)]);
}
function addressBytesHex(address, network) {
  if (address.startsWith("0x")) {
    return address;
  }
  const bech32Prefix = getBech32Prefix(network);
  if (/^[0-9a-fA-F]+$/.test(address) && !address.startsWith("bc") && !address.startsWith(bech32Prefix)) {
    return `0x${address}`;
  }
  const btcNetwork = getScureNetwork(network);
  const decoded = Address(btcNetwork).decode(address);
  const out = OutScript.encode(decoded);
  return u8aToHex(out);
}
function keyToU8a(pubkey) {
  return typeof pubkey === "string" ? hexToU8a(pubkey) : pubkey;
}
function getScureNetwork(network) {
  if (network === BitcoinNetwork.Bitcoin) {
    return NETWORK;
  } else if (network === BitcoinNetwork.Testnet || network === BitcoinNetwork.Signet) {
    return TEST_NETWORK;
  } else {
    return {
      bech32: "bcrt",
      pubKeyHash: 111,
      scriptHash: 196,
      wif: 239
    };
  }
}

// ts/CosignScript.ts
var CosignScript = class {
  constructor(lock, network) {
    this.lock = lock;
    this.network = network;
  }
  getFundingPsbt() {
    const { lock, network } = this;
    const tx = new Transaction();
    tx.addOutput({
      script: keyToU8a(lock.p2wshScriptHashHex),
      amount: lock.utxoSatoshis ?? lock.satoshis
    });
    return tx.toPSBT(0);
  }
  calculateFee(feeRatePerSatVb, toScriptPubkey) {
    toScriptPubkey = addressBytesHex(toScriptPubkey, this.network);
    const { lock, network } = this;
    return calculateFee(
      lock.vaultPubkey,
      lock.vaultClaimPubkey,
      lock.ownerPubkey,
      BigInt(lock.vaultClaimHeight),
      BigInt(lock.openClaimHeight),
      BigInt(lock.createdAtHeight),
      network,
      feeRatePerSatVb,
      toScriptPubkey
    );
  }
  calculateScriptPubkey() {
    const { lock, network } = this;
    return createCosignPubkey(
      lock.vaultPubkey,
      lock.vaultClaimPubkey,
      lock.ownerPubkey,
      BigInt(lock.vaultClaimHeight),
      BigInt(lock.openClaimHeight),
      BigInt(lock.createdAtHeight),
      network
    );
  }
  getCosignPsbt(args) {
    const { lock, network } = this;
    const { releaseRequest, utxoRef, utxoSatoshis } = args;
    releaseRequest.toScriptPubkey = addressBytesHex(releaseRequest.toScriptPubkey, network);
    const psbtStr = getCosignPsbt(
      utxoRef.txid,
      utxoRef.vout,
      utxoSatoshis ?? lock.utxoSatoshis ?? lock.satoshis,
      lock.vaultPubkey,
      lock.vaultClaimPubkey,
      lock.ownerPubkey,
      BigInt(lock.vaultClaimHeight),
      BigInt(lock.openClaimHeight),
      BigInt(lock.createdAtHeight),
      network,
      releaseRequest.toScriptPubkey,
      releaseRequest.bitcoinNetworkFee
    );
    return this.psbtFromHex(psbtStr);
  }
  psbtFromHex(psbtHex) {
    const psbtBytes = hexToU8a2(psbtHex);
    const tx = Transaction.fromPSBT(psbtBytes);
    if (tx.inputsLength === 0) {
      throw new Error("PSBT has no inputs");
    }
    if (tx.outputsLength === 0) {
      throw new Error("PSBT has no outputs");
    }
    return tx;
  }
  /**
   * Cosigns the PSBT with the vault xpub.
   * @param psbt - The PSBT to cosign.
   * @param lock - The Bitcoin lock containing the vault information.
   * @param vaultXpriv - The vault's extended private key of which the xpub was used to create the vault.
   */
  vaultCosignPsbt(psbt, lock, vaultXpriv) {
    const parentFingerprint = lock.vaultXpubSources.parentFingerprint;
    const vaultFingerprint = vaultXpriv.identifier?.slice(0, 4);
    if (!vaultFingerprint) {
      throw new Error("Could not get vault fingerprint from HDKey");
    }
    if (!u8aEq(parentFingerprint, vaultFingerprint)) {
      throw new Error(
        `Vault xpub fingerprint ${u8aToHex2(parentFingerprint)} does not match the vault xpriv fingerprint ${u8aToHex2(vaultFingerprint)}`
      );
    }
    const childPath = `${lock.vaultXpubSources.cosignHdIndex}`;
    const pubkey = vaultXpriv.deriveChild(lock.vaultXpubSources.cosignHdIndex).publicKey;
    if (!pubkey) {
      throw new Error(`Failed to derive public key for path ${childPath}`);
    }
    const vaultPubkey = keyToU8a(lock.vaultPubkey);
    if (!u8aEq(vaultPubkey, pubkey)) {
      throw new Error(
        `Vault pubkey ${u8aToHex2(vaultPubkey)} does not match the derived pubkey ${u8aToHex2(pubkey)} using path ${childPath}`
      );
    }
    const signedPsbt = signPsbtDerived(
      u8aToHex2(psbt.toPSBT()),
      vaultXpriv.privateExtendedKey,
      childPath,
      false
    );
    psbt = this.psbtFromHex(signedPsbt);
    return psbt;
  }
  /**
   * Cosigns the transaction.
   */
  cosignAndGenerateTx(args) {
    const { lock } = this;
    const psbt = this.getCosignPsbt(args);
    const { addTx, vaultCosignature, ownerXpriv, ownerXprivChildHdPath } = args;
    psbt.updateInput(0, {
      partialSig: [[keyToU8a(lock.vaultPubkey), vaultCosignature]]
    });
    const derivePubkey = ownerXprivChildHdPath ? ownerXpriv.derive(ownerXprivChildHdPath).publicKey : ownerXpriv.publicKey;
    if (!derivePubkey) {
      throw new Error("Failed to derive owner public key");
    }
    const ownerPubkey = keyToU8a(lock.ownerPubkey);
    if (!u8aEq(ownerPubkey, derivePubkey)) {
      throw new Error(
        `Owner pubkey ${u8aToHex2(ownerPubkey)} does not match the derived pubkey ${u8aToHex2(derivePubkey)}`
      );
    }
    if (addTx) {
      const addTxBytes = hexToU8a2(addTx);
      const tx = Transaction.fromPSBT(addTxBytes);
      for (let i = 0; i < tx.outputsLength; i++) {
        const output = tx.getOutput(i);
        const network = getScureNetwork(this.network);
        const scripts = [
          p2wpkh(ownerPubkey, network).script,
          p2wsh(p2wpkh(ownerPubkey, network), network).script,
          p2sh(p2pkh(ownerPubkey, network), network).script,
          p2pkh(ownerPubkey, network).script
        ];
        if (scripts.some((x) => x && output.script && u8aEq(output.script, x))) {
          psbt.addInput({
            txid: tx.id,
            index: i,
            witnessUtxo: {
              script: output.script,
              amount: output.amount
            }
          });
        }
      }
    }
    const psbtBytes = u8aToHex2(psbt.toPSBT());
    const signedPsbt = ownerXprivChildHdPath ? signPsbtDerived(psbtBytes, ownerXpriv.privateExtendedKey, ownerXprivChildHdPath, true) : signPsbt(psbtBytes, this.network, u8aToHex2(ownerXpriv.privateKey, void 0, false), true);
    return this.psbtFromHex(signedPsbt);
  }
};
function getBitcoinNetworkFromApi(network) {
  if (network.isBitcoin) {
    return BitcoinNetwork.Bitcoin;
  } else if (network.isTestnet) {
    return BitcoinNetwork.Testnet;
  } else if (network.isRegtest) {
    return BitcoinNetwork.Regtest;
  } else if (network.isSignet) {
    return BitcoinNetwork.Signet;
  }
  throw new Error("Unsupported network: " + network.toString());
}

// ts/index.ts
import * as bip39 from "@scure/bip39";
export {
  Address2 as Address,
  BitcoinNetwork,
  CosignScript,
  HDKey,
  Transaction2 as Transaction,
  addressBytesHex,
  bip39,
  getBech32Prefix,
  getBip32Version,
  getBitcoinNetworkFromApi,
  getChildXpriv,
  getCompressedPubkey,
  getScureNetwork,
  getXpubFromXpriv,
  keyToU8a,
  p2pk,
  p2pkh2 as p2pkh,
  p2sh2 as p2sh,
  p2wpkh2 as p2wpkh,
  p2wsh2 as p2wsh,
  p2wshScriptHexToAddress
};
