create-first-blocks.js
1 /*! 2 * scripts/createfirstblocks.js 3 * Copyright © 2019 – Katana Cryptographic Ltd. All Rights Reserved. 4 */ 5 6 7 import Logger from '../lib/logger.js' 8 import util from '../lib/util.js' 9 import db from '../lib/db/mysql-db-wrapper.js' 10 import { createRpcClient } from '../lib/bitcoind-rpc/rpc-client.js' 11 12 13 /** 14 * Script inserting first blocks into the database 15 * (without a scan of transactions) 16 */ 17 18 // RPC Client requests data from bitcoind 19 let client = createRpcClient() 20 21 // Database id of the previous block 22 let prevID = null 23 24 25 async function processBlock(height) { 26 Logger.info(`Start processing block ${height}`) 27 28 const blockHash = await client.getblockhash({ height }) 29 30 if (blockHash) { 31 const header = await client.getblockheader({ blockhash: blockHash, verbose: true }) 32 33 if (header) { 34 const dbBlock = { 35 blockHeight: header.height, 36 blockHash: header.hash, 37 blockTime: header.time, 38 blockParent: prevID 39 } 40 41 // eslint-disable-next-line require-atomic-updates 42 prevID = await db.addBlock(dbBlock) 43 Logger.info(`Successfully processed block ${height}`) 44 45 } else { 46 const error = `Unable to retrieve header of block ${height}` 47 48 Logger.error(null, error) 49 throw error 50 } 51 52 } else { 53 const error = `Unable to find hash of block ${height}` 54 55 Logger.error(null, error) 56 throw error 57 } 58 } 59 60 61 async function run(heights) { 62 return util.seriesCall(heights, processBlock) 63 } 64 65 66 /** 67 * Launch the script 68 */ 69 70 // Retrieves command line arguments 71 if (process.argv.length < 3) { 72 Logger.error(null, 'Missing arguments. Command = node create-first-blocks.js <number_of_blocks>') 73 process.exit(1) 74 } 75 76 // Create list of integers from 0 to index passed as parameter (included) 77 const n = Number.parseInt(process.argv[2], 10) 78 const heights = util.range(0, n) 79 80 Logger.info('Start processing') 81 82 setTimeout(async () => { 83 return run(heights).then(() => { 84 Logger.info('Processing completed') 85 }) 86 }, 1500)