headers.js
1 /*! 2 * lib/bitcoind-rpc/headers.js 3 * Copyright © 2019 – Katana Cryptographic Ltd. All Rights Reserved. 4 */ 5 6 7 import QuickLRU from 'quick-lru' 8 9 import errors from '../errors.js' 10 import { createRpcClient } from './rpc-client.js' 11 12 13 /** 14 * A singleton providing information about block headers 15 */ 16 class Headers { 17 18 constructor() { 19 // Cache 20 this.headers = new QuickLRU({ 21 // Maximum number of headers to store in cache 22 maxSize: 2016, 23 // Maximum age for items in the cache. Items do not expire 24 maxAge: Number.POSITIVE_INFINITY 25 }) 26 27 // Initialize the rpc client 28 this.rpcClient = createRpcClient() 29 } 30 31 /** 32 * Get the block header for a given hash 33 * @param {string} hash - block hash 34 * @returns {Promise} 35 */ 36 async getHeader(hash) { 37 if (this.headers.has(hash)) 38 return this.headers.get(hash) 39 40 try { 41 const header = await this.rpcClient.getblockheader({ blockhash: hash, verbose: true }) 42 const fmtHeader = JSON.stringify(header, null, 2) 43 this.headers.set(hash, fmtHeader) 44 return fmtHeader 45 } catch { 46 throw errors.generic.GEN 47 } 48 } 49 50 } 51 52 export default new Headers()