"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 crypto_wallet_core_1 = require("@bitpay-labs/crypto-wallet-core");
const config_1 = __importDefault(require("../../src/config"));
const storage_1 = require("../../src/services/storage");
const block_1 = require("../../src/models/block");
const index_js_1 = require("../helpers/index.js");
const crypto = __importStar(require("crypto"));
const { Transaction, PrivateKey } = crypto_wallet_core_1.BitcoreLib;
const UnspentOutput = Transaction.UnspentOutput;
function randomHash() {
    return crypto.randomBytes(32).toString('hex');
}
function* generateBlocks(blockCount, blockSizeMb) {
    let prevBlock = undefined;
    for (let i = 0; i < blockCount; i++) {
        const tempBlock = generateBlock(blockSizeMb, prevBlock);
        yield tempBlock;
        prevBlock = tempBlock;
    }
}
function preGenerateBlocks(blockCount, blockSizeMb) {
    const blocks = new Array();
    for (const block of generateBlocks(blockCount, blockSizeMb)) {
        blocks.push(block);
    }
    return blocks;
}
function generateBlock(blockSizeMb, previousBlock) {
    const txAmount = 100000;
    const prevHash = previousBlock ? previousBlock.hash : '';
    const block = {
        hash: randomHash(),
        transactions: [],
        toBuffer: () => {
            return { length: 264 };
        },
        header: {
            toObject: () => {
                return {
                    hash: randomHash(),
                    confirmations: 1,
                    strippedsize: 228,
                    size: 264,
                    weight: 948,
                    height: 1355,
                    version: 536870912,
                    versionHex: '20000000',
                    merkleRoot: randomHash(),
                    tx: [randomHash()],
                    time: 1526756523,
                    mediantime: 1526066375,
                    nonce: 2,
                    bits: parseInt('207fffff', 16),
                    difficulty: 4.656542373906925e-10,
                    chainwork: '0000000000000000000000000000000000000000000000000000000000000a98',
                    prevHash: prevHash
                };
            }
        }
    };
    const transactions = new Array();
    if (previousBlock) {
        for (const transaction of previousBlock.transactions) {
            // each transaction should have one input and one output
            const utxos = transaction.outputs.map(output => {
                return new UnspentOutput({
                    txid: transaction.hash,
                    vout: 0,
                    address: output.script.toAddress('mainnet').toString(false),
                    scriptPubKey: output.script.toBuffer().toString('hex'),
                    amount: Number(txAmount)
                });
            });
            const newTx = new Transaction().from(utxos);
            for (const _ of newTx.inputs) {
                newTx.to(newAddress(), txAmount);
            }
            transactions.push(newTx);
        }
        block.transactions = transactions;
    }
    else {
        const txPerMb = 2500;
        const blockSize = txPerMb * blockSizeMb;
        for (let i = 0; i < blockSize; i++) {
            const newTx = new Transaction().to(newAddress(), txAmount);
            block.transactions.push(newTx);
        }
    }
    return block;
}
const addresses = new Array();
for (let i = 0; i < 100; i++) {
    const privateKey = new PrivateKey();
    const publicKey = privateKey.toPublicKey();
    const address = publicKey.toAddress().toString();
    addresses.push(address);
}
function newAddress() {
    const index = Math.floor(Math.random() * 100);
    return addresses[index];
}
function startBenchmarkDatabase() {
    const storageArgs = {
        dbHost: config_1.default.dbHost,
        dbName: 'bitcore-benchmark'
    };
    return storage_1.Storage.start(storageArgs);
}
async function benchmark(blockCount, blockSizeMb) {
    await (0, index_js_1.resetDatabase)();
    console.log('Generating blocks');
    const blocks = preGenerateBlocks(blockCount, blockSizeMb);
    const startTime = new Date();
    console.log('Adding blocks');
    for (const block of blocks) {
        process.stdout.write('.');
        await block_1.BitcoinBlockStorage.addBlock({ block, chain: 'BENCH', network: 'MARK', initialSyncComplete: false });
    }
    process.stdout.write('\n');
    const endTime = new Date();
    const time = endTime.getTime() - startTime.getTime();
    const seconds = time / 1000;
    console.log(`Benchmark for ${blockCount} (${blockSizeMb} MB) blocks completed after ${seconds} s`);
    console.log(`${(blockSizeMb * blockCount) / seconds} MB/s`);
    console.log(`${seconds / blockCount} Seconds/Block`);
}
startBenchmarkDatabase()
    .then(() => benchmark(80, 1))
    .then(() => benchmark(5, 32))
    .then(() => benchmark(1, 64))
    .then(() => process.exit());
//# sourceMappingURL=benchmark.js.map