"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.waitForBlockFinalization = exports.waitForBlockRelaying = exports.getTxProof = exports.decodeBtcAddress = exports.btcAddressFromParams = exports.encodeBtcAddress = exports.bitcoin = void 0;
const bitcoinjs = __importStar(require("bitcoinjs-lib"));
exports.bitcoin = bitcoinjs;
const utils_1 = require("../utils");
function encodeBtcAddress(address, network) {
    let btcAddress;
    try {
        if (address.isP2pkh) {
            const result = bitcoinjs.payments.p2pkh({
                hash: Buffer.from(address.asP2pkh.buffer),
                network,
            });
            btcAddress = result.address;
        }
        else if (address.isP2sh) {
            const result = bitcoinjs.payments.p2sh({
                hash: Buffer.from(address.asP2sh.buffer),
                network,
            });
            btcAddress = result.address;
        }
        else if (address.isP2wpkHv0) {
            const result = bitcoinjs.payments.p2wpkh({
                hash: Buffer.from(address.asP2wpkHv0.buffer),
                network,
            });
            btcAddress = result.address;
        }
        else {
            throw new Error("Invalid address format");
        }
    }
    catch (err) {
        throw new Error(`Error encoding BTC address ${address}: ${err}`);
    }
    if (btcAddress)
        return btcAddress;
    throw new Error("Unable to encode address");
}
exports.encodeBtcAddress = encodeBtcAddress;
function decode(p, f) {
    try {
        const pay = f(p);
        return pay.hash ? "0x" + pay.hash.toString("hex") : "";
    }
    catch (err) {
        return undefined;
    }
}
function btcAddressFromParams(registry, params) {
    registry.register;
    return registry.createType("BitcoinAddress", Object.assign({}, params));
}
exports.btcAddressFromParams = btcAddressFromParams;
function decodeBtcAddress(address, network) {
    const p2pkh = decode({ address, network }, bitcoinjs.payments.p2pkh);
    if (p2pkh)
        return { p2pkh };
    const p2sh = decode({ address, network }, bitcoinjs.payments.p2sh);
    if (p2sh)
        return { p2sh };
    const p2wpkhv0 = decode({ address, network }, bitcoinjs.payments.p2wpkh);
    if (p2wpkhv0)
        return { p2wpkhv0 };
    throw new Error("Unable to decode address");
}
exports.decodeBtcAddress = decodeBtcAddress;
function getTxProof(electrsAPI, btcTxId) {
    return __awaiter(this, void 0, void 0, function* () {
        const [merkleProof, rawTx] = yield electrsAPI.getParsedExecutionParameters(btcTxId);
        return {
            merkleProof,
            rawTx,
        };
    });
}
exports.getTxProof = getTxProof;
function waitForBlockRelaying(btcRelayAPI, blockHash, sleepMs = utils_1.SLEEP_TIME_MS) {
    return __awaiter(this, void 0, void 0, function* () {
        while (!(yield btcRelayAPI.isBlockInRelay(blockHash))) {
            console.log(`Blockhash ${blockHash} not yet relayed...`);
            yield (0, utils_1.sleep)(sleepMs);
        }
    });
}
exports.waitForBlockRelaying = waitForBlockRelaying;
function waitForBlockFinalization(bitcoinCoreClient, btcRelayAPI) {
    return __awaiter(this, void 0, void 0, function* () {
        const bestBlockHash = (0, utils_1.addHexPrefix)((0, utils_1.reverseEndiannessHex)(yield bitcoinCoreClient.getBestBlockHash()));
        // wait for block to be relayed
        yield waitForBlockRelaying(btcRelayAPI, bestBlockHash);
    });
}
exports.waitForBlockFinalization = waitForBlockFinalization;
//# sourceMappingURL=bitcoin.js.map