#!/usr/bin/env node
"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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const readline = __importStar(require("readline"));
const config_1 = __importDefault(require("../build/src/config"));
const block_1 = require("../build/src/models/block");
const p2p_1 = require("../build/src/modules/bitcoin/p2p");
const storage_1 = require("../build/src/services/storage");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
function usage(errMsg) {
    console.log('USAGE: ./addGenesisBlock.js [options]');
    console.log('OPTIONS:');
    console.log('  --chain <value>      BTC, BCH, DOGE, or LTC');
    console.log('  --network <value>    mainnet, testnet, or regtest');
    console.log('  --real               Write the change to the db. If not given, will only do a dry run');
    if (errMsg) {
        console.log('\nERROR: ' + errMsg);
    }
    process.exit();
}
const args = process.argv.slice(2);
if (args.includes('--help') || args.includes('-h')) {
    usage();
}
const chain = args[args.indexOf('--chain') + 1];
const network = args[args.indexOf('--network') + 1];
if (!['BTC', 'BCH', 'DOGE', 'LTC'].includes(chain) || !['mainnet', 'testnet', 'regtest'].includes(network)) {
    usage('Invalid chain and/or network param(s).');
}
const real = !!args.find(a => a === '--real');
console.log('Real:', real);
if (real)
    console.log('~~~~ REAL RUN ~~~~');
let p2pWorker;
console.log('Connecting to storage...');
storage_1.Storage.start()
    .then(async () => {
    const genesisExists = await block_1.BitcoinBlockStorage.collection.findOne({ chain, network, height: 0 });
    if (genesisExists) {
        console.log('Genesis block already exists.', genesisExists.hash);
        return;
    }
    const blockOne = await block_1.BitcoinBlockStorage.collection.findOne({ chain, network, height: 1 });
    if (!blockOne) {
        console.log('Block 1 not found.');
        return;
    }
    const chainConfig = config_1.default.default.chains[chain][network];
    p2pWorker = new p2p_1.BitcoinP2PWorker({ chain, network, chainConfig });
    await p2pWorker.connect();
    p2pWorker.pool.on('peerblock', async (peer, message) => {
        if (message.block?.hash === blockOne.previousBlockHash) {
            p2pWorker.events.emit(message.block.hash, message.block);
        }
    });
    const genesisBlock = await p2pWorker.getBlock(blockOne.previousBlockHash);
    console.log('\nGenesis block:', genesisBlock.hash);
    const ans = await new Promise(r => rl.question(`${real ? '' : 'DRY RUN: '}Do you want to continue? (y/N): `, r));
    if (ans?.toLowerCase() !== 'y') {
        console.log('Aborted.');
        return;
    }
    if (real) {
        await block_1.BitcoinBlockStorage.processBlock({
            block: genesisBlock,
            initialSyncComplete: true,
            chain,
            network
        });
        const cnt = await block_1.BitcoinBlockStorage.collection.countDocuments({ chain, network, height: 0 });
        if (cnt == 1)
            console.log('Genesis block added');
        else
            console.log(`Somethings wrong. There are ${cnt} genesis blocks in the db`);
    }
    else {
        console.log('Dry run. Genesis block not added.');
    }
})
    .catch(console.error)
    .finally(() => {
    rl.close();
    p2pWorker?.disconnect();
    storage_1.Storage.stop();
});
//# sourceMappingURL=addGenesisBlock.js.map