#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const block_1 = require("../../src/models/block");
const coin_1 = require("../../src/models/coin");
const modules_1 = require("../../src/modules");
const config_1 = require("../../src/services/config");
const storage_1 = require("../../src/services/storage");
if (require.main === module) {
    (async () => {
        const { CHAIN = '', NETWORK = '', HEIGHT } = process.env;
        const chain = CHAIN || '';
        const network = NETWORK || '';
        const startHeight = Number(HEIGHT) || 0;
        const chainConfig = config_1.Config.chainConfig({ chain, network });
        const FORKHEIGHT = chainConfig.forkHeight;
        const FORKFROM = chainConfig.parentChain;
        const forkHeight = Number(FORKHEIGHT);
        if (!FORKFROM || !FORKHEIGHT) {
            console.log(`There is no forkHeight or parentChain on the config for ${chain} ${network}`);
        }
        if (!chain || !network) {
            console.log('Please provide a CHAIN and NETWORK environment variable');
            process.exit(1);
        }
        console.log('Searching for coins that can be removed from', chain, network, 'comparing against', FORKFROM, '<', forkHeight);
        modules_1.Modules.loadConfigured();
        await storage_1.Storage.start();
        const tip = await block_1.BitcoinBlockStorage.getLocalTip({ chain, network });
        if (tip) {
            for (let i = startHeight; i <= forkHeight; i++) {
                let success = true;
                const unspentForkCoinsForBlock = await coin_1.CoinStorage.collection
                    .find({ chain, network, mintHeight: i, spentHeight: -2 })
                    .toArray();
                for (const forkCoin of unspentForkCoinsForBlock) {
                    const toPrune = await coin_1.CoinStorage.collection.findOne({
                        chain: FORKFROM,
                        network,
                        mintTxid: forkCoin.mintTxid,
                        mintIndex: forkCoin.mintIndex
                    });
                    const shouldPrune = toPrune && toPrune.spentHeight <= forkHeight && toPrune.spentHeight > 0;
                    if (shouldPrune) {
                        success = false;
                        const error = {
                            model: 'coin',
                            err: true,
                            type: 'FORK_PRUNE_COIN',
                            payload: { coin: forkCoin, blockNum: i }
                        };
                        console.log(JSON.stringify(error));
                    }
                }
                console.log(JSON.stringify({ block: i, success, forkCoins: unspentForkCoinsForBlock.length }));
            }
        }
        process.exit(0);
    })();
}
//# sourceMappingURL=prune-fork.js.map