#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const block_1 = require("../../src/models/block");
const modules_1 = require("../../src/modules");
const storage_1 = require("../../src/services/storage");
if (require.main === module) {
    (async () => {
        const { CHAIN = '', NETWORK = '', HEIGHT } = process.env;
        const resumeHeight = Number(HEIGHT) || 1;
        const chain = CHAIN || '';
        const network = NETWORK || '';
        modules_1.Modules.loadConfigured();
        await storage_1.Storage.start();
        let prevMatch = true;
        let nextMatch = true;
        let previousBlock;
        let checkHeight = resumeHeight;
        console.log('Verifying headers for', chain, network, 'from height', resumeHeight);
        const blockStream = block_1.BitcoinBlockStorage.collection
            .find({ chain, network, processed: true, height: { $gte: checkHeight } })
            .project({ height: 1, nextBlockHash: 1, previousBlockHash: 1, hash: 1 })
            .sort({ height: 1 })
            .stream();
        for await (const locatorBlock of blockStream) {
            let success = true;
            if (checkHeight !== locatorBlock.height) {
                const error = {
                    model: 'block',
                    err: true,
                    type: 'MISSING_BLOCK',
                    payload: { blockNum: checkHeight }
                };
                console.log(JSON.stringify(error));
                success = false;
                checkHeight = locatorBlock.height;
            }
            else if (previousBlock) {
                prevMatch = prevMatch && locatorBlock.previousBlockHash === previousBlock.hash;
                nextMatch = nextMatch && locatorBlock.hash === previousBlock.nextBlockHash;
                if (!prevMatch || !nextMatch) {
                    const error = {
                        model: 'block',
                        err: true,
                        type: 'CORRUPTED_BLOCK',
                        payload: { blockNum: locatorBlock.height }
                    };
                    console.log(JSON.stringify(error));
                    success = false;
                }
            }
            previousBlock = locatorBlock;
            checkHeight++;
            if (success) {
                console.log({ block: checkHeight, success });
            }
        }
        process.exit(0);
    })();
}
//# sourceMappingURL=db-verify-headers.js.map