2020-12-20 22:36:36 +07:00
import config from '../config' ;
2023-03-03 13:59:17 +09:00
import bitcoinApi , { bitcoinCoreApi } from './bitcoin/bitcoin-api-factory' ;
2020-10-13 15:27:52 +07:00
import logger from '../logger' ;
2020-02-23 19:16:50 +07:00
import memPool from './mempool' ;
2024-07-10 13:13:53 +09:00
import { BlockExtended , BlockExtension , BlockSummary , PoolTag , TransactionExtended , TransactionMinerInfo , CpfpSummary , MempoolTransactionExtended , TransactionClassified , BlockAudit , TransactionAudit } from '../mempool.interfaces' ;
2020-05-24 16:29:30 +07:00
import { Common } from './common' ;
2020-10-27 00:05:06 +07:00
import diskCache from './disk-cache' ;
2020-12-21 23:08:34 +07:00
import transactionUtils from './transaction-utils' ;
2021-09-15 01:47:24 +04:00
import bitcoinClient from './bitcoin/bitcoin-client' ;
2022-06-15 19:53:37 +00:00
import { IBitcoinApi } from './bitcoin/bitcoin-api.interface' ;
2022-01-05 15:41:14 +09:00
import { IEsploraApi } from './bitcoin/esplora-api.interface' ;
import poolsRepository from '../repositories/PoolsRepository' ;
import blocksRepository from '../repositories/BlocksRepository' ;
2022-02-08 15:47:43 +09:00
import loadingIndicators from './loading-indicators' ;
2022-03-13 11:38:45 +01:00
import BitcoinApi from './bitcoin/bitcoin-api' ;
2022-04-18 17:49:22 +09:00
import BlocksRepository from '../repositories/BlocksRepository' ;
import HashratesRepository from '../repositories/HashratesRepository' ;
2022-05-19 16:40:38 +02:00
import indexer from '../indexer' ;
2022-06-07 11:28:39 +02:00
import poolsParser from './pools-parser' ;
2022-06-18 16:48:02 +02:00
import BlocksSummariesRepository from '../repositories/BlocksSummariesRepository' ;
2022-10-28 10:31:55 -06:00
import BlocksAuditsRepository from '../repositories/BlocksAuditsRepository' ;
2022-11-27 13:46:23 +09:00
import cpfpRepository from '../repositories/CpfpRepository' ;
2022-07-11 19:15:28 +02:00
import mining from './mining/mining' ;
2022-06-25 12:14:32 +02:00
import DifficultyAdjustmentsRepository from '../repositories/DifficultyAdjustmentsRepository' ;
2022-07-16 09:22:45 +02:00
import PricesRepository from '../repositories/PricesRepository' ;
import priceUpdater from '../tasks/price-updater' ;
2023-02-18 14:10:07 +09:00
import chainTips from './chain-tips' ;
2023-07-08 01:07:06 -04:00
import websocketHandler from './websocket-handler' ;
2023-05-12 16:29:45 -06:00
import redisCache from './redis-cache' ;
import rbfCache from './rbf-cache' ;
2023-07-31 18:22:13 -07:00
import { calcBitsDifference } from './difficulty-adjustment' ;
2024-04-04 08:18:34 +00:00
import AccelerationRepository from '../repositories/AccelerationRepository' ;
2024-04-04 04:28:57 +00:00
import { calculateFastBlockCpfp , calculateGoodBlockCpfp } from './cpfp' ;
2024-04-06 02:24:22 +00:00
import mempool from './mempool' ;
2024-07-20 11:59:18 +00:00
import CpfpRepository from '../repositories/CpfpRepository' ;
2019-07-21 17:59:47 +03:00
class Blocks {
2020-12-28 04:47:22 +07:00
private blocks : BlockExtended [] = [];
2022-06-15 19:53:37 +00:00
private blockSummaries : BlockSummary [] = [];
2019-08-29 01:17:31 +02:00
private currentBlockHeight = 0 ;
2023-07-31 18:22:13 -07:00
private currentBits = 0 ;
2020-09-21 19:41:12 +07:00
private lastDifficultyAdjustmentTime = 0 ;
2021-07-23 14:35:04 +03:00
private previousDifficultyRetarget = 0 ;
2024-02-11 22:50:34 +00:00
private quarterEpochBlockTime : number | null = null ;
2020-12-28 04:47:22 +07:00
private newBlockCallbacks : (( block : BlockExtended , txIds : string [], transactions : TransactionExtended []) => void )[] = [];
2023-06-25 20:37:42 -04:00
private newAsyncBlockCallbacks : (( block : BlockExtended , txIds : string [], transactions : MempoolTransactionExtended []) => Promise < void >)[] = [];
2024-02-19 02:43:19 +00:00
private classifyingBlocks : boolean = false ;
2019-08-29 01:17:31 +02:00
2023-04-27 10:19:12 +09:00
private mainLoopTimeout : number = 120000 ;
2020-02-16 22:15:07 +07:00
constructor () { }
2019-07-21 17:59:47 +03:00
2020-12-28 04:47:22 +07:00
public getBlocks () : BlockExtended [] {
2019-07-21 17:59:47 +03:00
return this . blocks ;
}
2020-12-28 04:47:22 +07:00
public setBlocks ( blocks : BlockExtended []) {
2020-02-29 21:52:04 +07:00
this . blocks = blocks ;
}
2022-06-15 19:53:37 +00:00
public getBlockSummaries () : BlockSummary [] {
return this . blockSummaries ;
}
public setBlockSummaries ( blockSummaries : BlockSummary []) {
this . blockSummaries = blockSummaries ;
}
2020-12-28 04:47:22 +07:00
public setNewBlockCallback ( fn : ( block : BlockExtended , txIds : string [], transactions : TransactionExtended []) => void ) {
2020-09-27 17:21:18 +07:00
this . newBlockCallbacks . push ( fn );
2019-07-21 17:59:47 +03:00
}
2023-06-25 20:37:42 -04:00
public setNewAsyncBlockCallback ( fn : ( block : BlockExtended , txIds : string [], transactions : MempoolTransactionExtended []) => Promise < void >) {
2022-11-16 18:18:59 -06:00
this . newAsyncBlockCallbacks . push ( fn );
}
2022-01-05 15:41:14 +09:00
/**
* Return the list of transaction for a block
* @param blockHash
* @param blockHeight
* @param onlyCoinbase - Set to true if you only need the coinbase transaction
2023-07-25 11:33:13 +09:00
* @param txIds - optional ordered list of transaction ids if already known
* @param quiet - don't print non-essential logs
* @param addMempoolData - calculate sigops etc
2022-01-05 15:41:14 +09:00
* @returns Promise<TransactionExtended[]>
*/
2022-02-10 23:02:12 +09:00
private async $getTransactionsExtended (
blockHash : string ,
blockHeight : number ,
2023-09-11 11:04:01 +09:00
blockTime : number ,
2022-02-10 23:02:12 +09:00
onlyCoinbase : boolean ,
2023-07-16 17:12:26 +09:00
txIds : string [] | null = null ,
2022-02-10 23:02:12 +09:00
quiet : boolean = false ,
2023-05-29 15:56:29 -04:00
addMempoolData : boolean = false ,
2022-02-10 23:02:12 +09:00
) : Promise < TransactionExtended [] > {
2023-07-25 11:33:13 +09:00
const isEsplora = config . MEMPOOL . BACKEND === 'esplora' ;
const transactionMap : { [ txid : string ] : TransactionExtended } = {};
2022-01-05 15:41:14 +09:00
2023-07-25 11:33:13 +09:00
if ( ! txIds ) {
txIds = await bitcoinApi . $getTxIdsForBlock ( blockHash );
}
2023-07-24 16:58:30 +09:00
2023-07-25 11:33:13 +09:00
const mempool = memPool . getMempool ();
let foundInMempool = 0 ;
let totalFound = 0 ;
// Copy existing transactions from the mempool
if ( ! onlyCoinbase ) {
for ( const txid of txIds ) {
if ( mempool [ txid ]) {
2023-09-11 11:04:01 +09:00
mempool [ txid ]. status = {
confirmed : true ,
block_height : blockHeight ,
block_hash : blockHash ,
block_time : blockTime ,
};
2023-07-25 11:33:13 +09:00
transactionMap [ txid ] = mempool [ txid ];
foundInMempool ++ ;
totalFound ++ ;
}
2023-07-24 16:58:30 +09:00
}
2023-07-25 11:33:13 +09:00
}
if ( onlyCoinbase ) {
try {
2023-07-27 11:45:16 +09:00
const coinbase = await transactionUtils . $getTransactionExtendedRetry ( txIds [ 0 ], false , false , false , addMempoolData );
if ( coinbase && coinbase . vin [ 0 ]. is_coinbase ) {
return [ coinbase ];
} else {
const msg = `Expected a coinbase tx, but the backend API returned something else` ;
logger . err ( msg );
throw new Error ( msg );
}
2023-07-25 11:33:13 +09:00
} catch ( e ) {
const msg = `Cannot fetch coinbase tx ${ txIds [ 0 ] } . Reason: ` + ( e instanceof Error ? e.message : e );
logger . err ( msg );
throw new Error ( msg );
2023-07-24 16:58:30 +09:00
}
2023-07-25 11:33:13 +09:00
}
// Fetch remaining txs in bulk
if ( isEsplora && ( txIds . length - totalFound > 500 )) {
try {
const rawTransactions = await bitcoinApi . $getTxsForBlock ( blockHash );
for ( const tx of rawTransactions ) {
if ( ! transactionMap [ tx . txid ]) {
transactionMap [ tx . txid ] = addMempoolData ? transactionUtils . extendMempoolTransaction ( tx ) : transactionUtils . extendTransaction ( tx );
totalFound ++ ;
2022-01-05 15:41:14 +09:00
}
}
2023-07-25 11:33:13 +09:00
} catch ( e ) {
logger . err ( `Cannot fetch bulk txs for block ${ blockHash } . Reason: ` + ( e instanceof Error ? e.message : e ));
}
}
2022-01-05 15:41:14 +09:00
2023-07-25 11:33:13 +09:00
// Fetch remaining txs individually
for ( const txid of txIds . filter ( txid => ! transactionMap [ txid ])) {
2023-07-27 11:45:16 +09:00
if ( ! quiet && ( totalFound % ( Math . round (( txIds . length ) / 10 )) === 0 || totalFound + 1 === txIds . length )) { // Avoid log spam
logger . debug ( `Indexing tx ${ totalFound + 1 } of ${ txIds . length } in block # ${ blockHeight } ` );
}
try {
const tx = await transactionUtils . $getTransactionExtendedRetry ( txid , false , false , false , addMempoolData );
transactionMap [ txid ] = tx ;
totalFound ++ ;
} catch ( e ) {
const msg = `Cannot fetch tx ${ txid } . Reason: ` + ( e instanceof Error ? e.message : e );
logger . err ( msg );
throw new Error ( msg );
2022-01-05 15:41:14 +09:00
}
2023-07-25 11:33:13 +09:00
}
2022-01-05 15:41:14 +09:00
2023-07-25 11:33:13 +09:00
if ( ! quiet ) {
logger . debug ( ` ${ foundInMempool } of ${ txIds . length } found in mempool. ${ totalFound - foundInMempool } fetched through backend service.` );
2022-02-10 23:02:12 +09:00
}
2022-01-05 15:41:14 +09:00
2023-07-27 11:45:16 +09:00
// Require the first transaction to be a coinbase
const coinbase = transactionMap [ txIds [ 0 ]];
if ( ! coinbase || ! coinbase . vin [ 0 ]. is_coinbase ) {
const msg = `Expected first tx in a block to be a coinbase, but found something else` ;
logger . err ( msg );
throw new Error ( msg );
}
// Require all transactions to be present
// (we should have thrown an error already if a tx request failed)
if ( txIds . some ( txid => ! transactionMap [ txid ])) {
const msg = `Failed to fetch ${ txIds . length - totalFound } transactions from block` ;
logger . err ( msg );
throw new Error ( msg );
}
2023-07-25 11:33:13 +09:00
// Return list of transactions, preserving block order
2023-07-27 11:45:16 +09:00
return txIds . map ( txid => transactionMap [ txid ]);
2022-01-05 15:41:14 +09:00
}
2022-06-15 19:53:37 +00:00
/**
* Return a block summary (list of stripped transactions)
* @param block
* @returns BlockSummary
*/
2023-02-27 18:00:00 +09:00
public summarizeBlock ( block : IBitcoinApi.VerboseBlock ) : BlockSummary {
2023-02-21 22:23:36 -06:00
if ( Common . isLiquid ()) {
block = this . convertLiquidFees ( block );
}
const stripped = block . tx . map (( tx : IBitcoinApi.VerboseTransaction ) => {
2022-06-15 19:53:37 +00:00
return {
txid : tx.txid ,
2022-11-04 10:37:14 -06:00
vsize : tx.weight / 4 ,
2022-06-15 19:53:37 +00:00
fee : tx.fee ? Math . round ( tx . fee * 100000000 ) : 0 ,
2023-12-21 16:20:31 +00:00
value : Math.round ( tx . vout . reduce (( acc , vout ) => acc + ( vout . value ? vout.value : 0 ), 0 ) * 100000000 ),
flags : 0 ,
2022-06-15 19:53:37 +00:00
};
});
return {
id : block.hash ,
transactions : stripped
};
}
2023-06-29 19:24:19 -04:00
public summarizeBlockTransactions ( hash : string , transactions : TransactionExtended []) : BlockSummary {
return {
id : hash ,
2023-12-21 16:20:31 +00:00
transactions : Common.classifyTransactions ( transactions ),
2023-06-29 19:24:19 -04:00
};
}
2023-02-21 22:23:36 -06:00
private convertLiquidFees ( block : IBitcoinApi.VerboseBlock ) : IBitcoinApi . VerboseBlock {
block . tx . forEach ( tx => {
2023-07-19 15:05:40 +09:00
if ( ! isFinite ( Number ( tx . fee ))) {
tx . fee = Object . values ( tx . fee || {}). reduce (( total , output ) => total + output , 0 );
}
2023-02-21 22:23:36 -06:00
});
return block ;
}
2022-01-05 15:41:14 +09:00
/**
* Return a block with additional data (reward, coinbase, fees...)
* @param block
* @param transactions
* @returns BlockExtended
*/
2022-03-13 11:38:45 +01:00
private async $getBlockExtended ( block : IEsploraApi.Block , transactions : TransactionExtended []) : Promise < BlockExtended > {
2023-02-27 18:00:00 +09:00
const coinbaseTx = transactionUtils . stripCoinbaseTransaction ( transactions [ 0 ]);
const blk : Partial < BlockExtended > = Object . assign ({}, block );
const extras : Partial < BlockExtension > = {};
extras . reward = transactions [ 0 ]. vout . reduce (( acc , curr ) => acc + curr . value , 0 );
extras . coinbaseRaw = coinbaseTx . vin [ 0 ]. scriptsig ;
extras . orphans = chainTips . getOrphanedBlocksAtHeight ( blk . height );
2022-03-11 14:54:34 +01:00
if ( block . height === 0 ) {
2023-02-27 18:00:00 +09:00
extras . medianFee = 0 ; // 50th percentiles
extras . feeRange = [ 0 , 0 , 0 , 0 , 0 , 0 , 0 ];
extras . totalFees = 0 ;
extras . avgFee = 0 ;
extras . avgFeeRate = 0 ;
extras . utxoSetChange = 0 ;
extras . avgTxSize = 0 ;
extras . totalInputs = 0 ;
extras . totalOutputs = 1 ;
extras . totalOutputAmt = 0 ;
extras . segwitTotalTxs = 0 ;
extras . segwitTotalSize = 0 ;
extras . segwitTotalWeight = 0 ;
2022-03-13 11:38:45 +01:00
} else {
2023-02-27 18:00:00 +09:00
const stats : IBitcoinApi.BlockStats = await bitcoinClient . getBlockStats ( block . id );
2023-03-12 11:09:11 +09:00
let feeStats = {
medianFee : stats.feerate_percentiles [ 2 ], // 50th percentiles
feeRange : [ stats . minfeerate , stats . feerate_percentiles , stats . maxfeerate ]. flat (),
};
if ( transactions ? . length > 1 ) {
2023-03-12 14:36:36 +09:00
feeStats = Common . calcEffectiveFeeStatistics ( transactions );
2023-03-12 11:09:11 +09:00
}
extras . medianFee = feeStats . medianFee ;
extras . feeRange = feeStats . feeRange ;
2023-02-27 18:00:00 +09:00
extras . totalFees = stats . totalfee ;
extras . avgFee = stats . avgfee ;
extras . avgFeeRate = stats . avgfeerate ;
extras . utxoSetChange = stats . utxo_increase ;
extras . avgTxSize = Math . round ( stats . total_size / stats . txs * 100 ) * 0.01 ;
extras . totalInputs = stats . ins ;
extras . totalOutputs = stats . outs ;
extras . totalOutputAmt = stats . total_out ;
extras . segwitTotalTxs = stats . swtxs ;
extras . segwitTotalSize = stats . swtotal_size ;
extras . segwitTotalWeight = stats . swtotal_weight ;
2023-02-17 21:21:21 +09:00
}
2023-02-24 11:33:36 +09:00
if ( Common . blocksSummariesIndexingEnabled ()) {
2023-02-27 18:00:00 +09:00
extras . feePercentiles = await BlocksSummariesRepository . $getFeePercentilesByBlockId ( block . id );
if ( extras . feePercentiles !== null ) {
extras . medianFeeAmt = extras . feePercentiles [ 3 ];
2023-02-19 19:17:51 +09:00
}
2023-02-18 11:26:13 +09:00
}
2023-02-17 21:21:21 +09:00
2023-02-27 18:00:00 +09:00
extras . virtualSize = block . weight / 4.0 ;
if ( coinbaseTx ? . vout . length > 0 ) {
extras . coinbaseAddress = coinbaseTx . vout [ 0 ]. scriptpubkey_address ?? null ;
2024-06-24 11:48:12 +00:00
extras . coinbaseAddresses = [... new Set < string >( coinbaseTx . vout . map ( v => v . scriptpubkey_address ). filter ( a => a ) as string [])];
2023-02-27 18:00:00 +09:00
extras . coinbaseSignature = coinbaseTx . vout [ 0 ]. scriptpubkey_asm ?? null ;
extras . coinbaseSignatureAscii = transactionUtils . hex2ascii ( coinbaseTx . vin [ 0 ]. scriptsig ) ?? null ;
2023-02-17 21:21:21 +09:00
} else {
2023-02-27 18:00:00 +09:00
extras . coinbaseAddress = null ;
2024-06-24 06:15:01 +00:00
extras . coinbaseAddresses = null ;
2023-02-27 18:00:00 +09:00
extras . coinbaseSignature = null ;
extras . coinbaseSignatureAscii = null ;
2023-02-17 21:21:21 +09:00
}
const header = await bitcoinClient . getBlockHeader ( block . id , false );
2023-02-27 18:00:00 +09:00
extras . header = header ;
2023-02-17 21:21:21 +09:00
const coinStatsIndex = indexer . isCoreIndexReady ( 'coinstatsindex' );
if ( coinStatsIndex !== null && coinStatsIndex . best_block_height >= block . height ) {
const txoutset = await bitcoinClient . getTxoutSetinfo ( 'none' , block . height );
2023-02-27 18:00:00 +09:00
extras . utxoSetSize = txoutset . txouts ,
extras . totalInputAmt = Math . round ( txoutset . block_info . prevout_spent * 100000000 );
2023-02-17 21:21:21 +09:00
} else {
2023-02-27 18:00:00 +09:00
extras . utxoSetSize = null ;
extras . totalInputAmt = null ;
2022-03-13 11:38:45 +01:00
}
2022-01-05 15:41:14 +09:00
2022-07-08 16:34:00 +02:00
if ([ 'mainnet' , 'testnet' , 'signet' ]. includes ( config . MEMPOOL . NETWORK )) {
2022-04-25 15:50:26 +09:00
let pool : PoolTag ;
2023-02-27 18:00:00 +09:00
if ( coinbaseTx !== undefined ) {
pool = await this . $findBlockMiner ( coinbaseTx );
2022-04-25 15:50:26 +09:00
} else {
2022-06-07 11:28:39 +02:00
if ( config . DATABASE . ENABLED === true ) {
pool = await poolsRepository . $getUnknownPool ();
} else {
pool = poolsParser . unknownPool ;
}
2022-04-25 15:50:26 +09:00
}
2022-04-07 18:14:28 +09:00
2022-04-25 15:50:26 +09:00
if ( ! pool ) { // We should never have this situation in practise
2023-02-17 21:21:21 +09:00
logger . warn ( `Cannot assign pool to block ${ blk . height } and 'unknown' pool does not exist. ` +
2022-04-25 15:50:26 +09:00
`Check your "pools" table entries` );
2022-10-28 10:31:55 -06:00
} else {
2023-02-27 18:00:00 +09:00
extras . pool = {
id : pool.uniqueId ,
2022-10-28 10:31:55 -06:00
name : pool.name ,
slug : pool.slug ,
};
2022-04-25 15:50:26 +09:00
}
2022-02-08 15:47:43 +09:00
2023-02-27 18:00:00 +09:00
extras . matchRate = null ;
2023-06-06 08:52:29 +02:00
extras . expectedFees = null ;
2023-06-10 12:09:06 -04:00
extras . expectedWeight = null ;
2023-02-12 21:43:12 -06:00
if ( config . MEMPOOL . AUDIT ) {
const auditScore = await BlocksAuditsRepository . $getBlockAuditScore ( block . id );
if ( auditScore != null ) {
2023-02-27 18:00:00 +09:00
extras . matchRate = auditScore . matchRate ;
2023-06-06 08:52:29 +02:00
extras . expectedFees = auditScore . expectedFees ;
2023-06-10 12:09:06 -04:00
extras . expectedWeight = auditScore . expectedWeight ;
2023-02-12 21:43:12 -06:00
}
2022-10-28 10:31:55 -06:00
}
2022-04-25 15:50:26 +09:00
}
2022-04-20 13:12:32 +09:00
2023-02-27 18:00:00 +09:00
blk . extras = < BlockExtension > extras ;
return < BlockExtended > blk ;
2022-01-05 15:41:14 +09:00
}
/**
* Try to find which miner found the block
* @param txMinerInfo
* @returns
*/
2022-01-20 17:20:02 +09:00
private async $findBlockMiner ( txMinerInfo : TransactionMinerInfo | undefined ) : Promise < PoolTag > {
2022-01-25 18:33:46 +09:00
if ( txMinerInfo === undefined || txMinerInfo . vout . length < 1 ) {
2022-06-07 11:28:39 +02:00
if ( config . DATABASE . ENABLED === true ) {
return await poolsRepository . $getUnknownPool ();
} else {
return poolsParser . unknownPool ;
}
2022-01-05 15:41:14 +09:00
}
2024-06-24 07:29:02 +00:00
const addresses = txMinerInfo . vout . map (( vout ) => vout . scriptpubkey_address ). filter ( address => address ) as string [];
2022-01-05 15:41:14 +09:00
2022-06-07 11:28:39 +02:00
let pools : PoolTag [] = [];
if ( config . DATABASE . ENABLED === true ) {
pools = await poolsRepository . $getPools ();
} else {
pools = poolsParser . miningPools ;
}
2023-02-27 18:00:00 +09:00
2024-06-24 07:29:02 +00:00
const pool = poolsParser . matchBlockMiner ( txMinerInfo . vin [ 0 ]. scriptsig , addresses || [], pools );
if ( pool ) {
return pool ;
2022-01-05 15:41:14 +09:00
}
2022-06-07 11:28:39 +02:00
if ( config . DATABASE . ENABLED === true ) {
return await poolsRepository . $getUnknownPool ();
} else {
return poolsParser . unknownPool ;
}
2022-01-05 15:41:14 +09:00
}
2022-06-18 16:48:02 +02:00
/**
* [INDEXING] Index all blocks summaries for the block txs visualization
*/
2022-11-27 13:46:23 +09:00
public async $generateBlocksSummariesDatabase () : Promise < void > {
2022-06-18 16:48:02 +02:00
if ( Common . blocksSummariesIndexingEnabled () === false ) {
return ;
}
try {
// Get all indexed block hash
const indexedBlocks = await blocksRepository . $getIndexedBlocks ();
2022-06-20 16:35:10 +02:00
const indexedBlockSummariesHashesArray = await BlocksSummariesRepository . $getIndexedSummariesId ();
const indexedBlockSummariesHashes = {}; // Use a map for faster seek during the indexing loop
for ( const hash of indexedBlockSummariesHashesArray ) {
indexedBlockSummariesHashes [ hash ] = true ;
}
2022-06-18 16:48:02 +02:00
// Logging
2022-06-20 16:35:10 +02:00
let newlyIndexed = 0 ;
let totalIndexed = indexedBlockSummariesHashesArray . length ;
2022-06-18 16:48:02 +02:00
let indexedThisRun = 0 ;
2023-07-31 16:03:18 +09:00
let timer = Date . now () / 1000 ;
const startedAt = Date . now () / 1000 ;
2022-06-18 16:48:02 +02:00
for ( const block of indexedBlocks ) {
2022-06-20 16:35:10 +02:00
if ( indexedBlockSummariesHashes [ block . hash ] === true ) {
2022-06-18 16:48:02 +02:00
continue ;
}
// Logging
2023-07-31 16:03:18 +09:00
const elapsedSeconds = ( Date . now () / 1000 ) - timer ;
2022-06-18 16:48:02 +02:00
if ( elapsedSeconds > 5 ) {
2023-07-31 16:03:18 +09:00
const runningFor = ( Date . now () / 1000 ) - startedAt ;
const blockPerSeconds = indexedThisRun / elapsedSeconds ;
2022-06-18 16:48:02 +02:00
const progress = Math . round ( totalIndexed / indexedBlocks . length * 10000 ) / 100 ;
2023-07-31 16:03:18 +09:00
logger . debug ( `Indexing block summary for # ${ block . height } | ~ ${ blockPerSeconds . toFixed ( 2 ) } blocks/sec | total: ${ totalIndexed } / ${ indexedBlocks . length } ( ${ progress } %) | elapsed: ${ runningFor . toFixed ( 2 ) } seconds` , logger . tags . mining );
timer = Date . now () / 1000 ;
2022-06-18 16:48:02 +02:00
indexedThisRun = 0 ;
}
2023-07-31 18:02:18 +09:00
if ( config . MEMPOOL . BACKEND === 'esplora' ) {
const txs = ( await bitcoinApi . $getTxsForBlock ( block . hash )). map ( tx => transactionUtils . extendTransaction ( tx ));
const cpfpSummary = await this . $indexCPFP ( block . hash , block . height , txs );
2024-01-30 16:41:35 +00:00
if ( cpfpSummary ) {
await this . $getStrippedBlockTransactions ( block . hash , true , true , cpfpSummary , block . height ); // This will index the block summary
}
2023-07-31 18:02:18 +09:00
} else {
await this . $getStrippedBlockTransactions ( block . hash , true , true ); // This will index the block summary
}
2022-06-18 16:48:02 +02:00
// Logging
indexedThisRun ++ ;
totalIndexed ++ ;
2022-06-20 16:35:10 +02:00
newlyIndexed ++ ;
2022-06-18 16:48:02 +02:00
}
2022-07-11 10:55:25 +02:00
if ( newlyIndexed > 0 ) {
2022-12-01 15:52:06 +01:00
logger . notice ( `Blocks summaries indexing completed: indexed ${ newlyIndexed } blocks` , logger . tags . mining );
2022-07-11 10:55:25 +02:00
} else {
2022-12-01 15:52:06 +01:00
logger . debug ( `Blocks summaries indexing completed: indexed ${ newlyIndexed } blocks` , logger . tags . mining );
2022-07-11 10:55:25 +02:00
}
2022-06-18 16:48:02 +02:00
} catch ( e ) {
2022-12-01 15:52:06 +01:00
logger . err ( `Blocks summaries indexing failed. Trying again in 10 seconds. Reason: ${ ( e instanceof Error ? e.message : e ) } ` , logger . tags . mining );
2022-06-25 19:50:39 +02:00
throw e ;
2022-06-18 16:48:02 +02:00
}
}
2022-11-27 13:46:23 +09:00
/**
* [INDEXING] Index transaction CPFP data for all blocks
*/
public async $generateCPFPDatabase () : Promise < void > {
if ( Common . cpfpIndexingEnabled () === false ) {
return ;
}
try {
// Get all indexed block hash
2023-01-10 17:15:55 -06:00
const unindexedBlockHeights = await blocksRepository . $getCPFPUnindexedBlocks ();
2022-11-27 13:46:23 +09:00
2023-01-10 17:15:55 -06:00
if ( ! unindexedBlockHeights ? . length ) {
2022-11-27 13:46:23 +09:00
return ;
}
2023-03-14 13:53:52 +09:00
logger . info ( `Indexing cpfp data for ${ unindexedBlockHeights . length } blocks` );
2022-11-27 13:46:23 +09:00
// Logging
let count = 0 ;
let countThisRun = 0 ;
2023-07-31 16:03:18 +09:00
let timer = Date . now () / 1000 ;
const startedAt = Date . now () / 1000 ;
2023-01-10 17:15:55 -06:00
for ( const height of unindexedBlockHeights ) {
2022-11-27 13:46:23 +09:00
// Logging
2023-01-10 17:15:55 -06:00
const hash = await bitcoinApi . $getBlockHash ( height );
2023-07-31 16:03:18 +09:00
const elapsedSeconds = ( Date . now () / 1000 ) - timer ;
2022-11-27 13:46:23 +09:00
if ( elapsedSeconds > 5 ) {
2023-07-31 16:03:18 +09:00
const runningFor = ( Date . now () / 1000 ) - startedAt ;
const blockPerSeconds = countThisRun / elapsedSeconds ;
2023-01-10 17:15:55 -06:00
const progress = Math . round ( count / unindexedBlockHeights . length * 10000 ) / 100 ;
2023-07-31 16:03:18 +09:00
logger . debug ( `Indexing cpfp clusters for # ${ height } | ~ ${ blockPerSeconds . toFixed ( 2 ) } blocks/sec | total: ${ count } / ${ unindexedBlockHeights . length } ( ${ progress } %) | elapsed: ${ runningFor . toFixed ( 2 ) } seconds` );
timer = Date . now () / 1000 ;
2022-11-27 13:46:23 +09:00
countThisRun = 0 ;
}
2023-01-10 17:15:55 -06:00
await this . $indexCPFP ( hash , height ); // Calculate and save CPFP data for transactions in this block
2022-11-27 13:46:23 +09:00
// Logging
count ++ ;
2022-11-28 17:56:50 +09:00
countThisRun ++ ;
2022-11-27 13:46:23 +09:00
}
2023-01-10 17:15:55 -06:00
logger . notice ( `CPFP indexing completed: indexed ${ count } blocks` );
2022-11-27 13:46:23 +09:00
} catch ( e ) {
logger . err ( `CPFP indexing failed. Trying again in 10 seconds. Reason: ${ ( e instanceof Error ? e.message : e ) } ` );
throw e ;
}
}
2023-06-09 13:46:43 -04:00
/**
* [INDEXING] Index expected fees & weight for all audited blocks
*/
public async $generateAuditStats () : Promise < void > {
const blockIds = await BlocksAuditsRepository . $getBlocksWithoutSummaries ();
if ( ! blockIds ? . length ) {
return ;
}
let timer = Date . now ();
let indexedThisRun = 0 ;
let indexedTotal = 0 ;
logger . debug ( `Indexing ${ blockIds . length } block audit details` );
for ( const hash of blockIds ) {
const summary = await BlocksSummariesRepository . $getTemplate ( hash );
let totalFees = 0 ;
let totalWeight = 0 ;
for ( const tx of summary ? . transactions || []) {
totalFees += tx . fee ;
totalWeight += ( tx . vsize * 4 );
}
await BlocksAuditsRepository . $setSummary ( hash , totalFees , totalWeight );
2023-06-14 16:15:33 -04:00
const cachedBlock = this . blocks . find ( block => block . id === hash );
if ( cachedBlock ) {
cachedBlock . extras . expectedFees = totalFees ;
cachedBlock . extras . expectedWeight = totalWeight ;
}
2023-06-09 13:46:43 -04:00
indexedThisRun ++ ;
indexedTotal ++ ;
const elapsedSeconds = ( Date . now () - timer ) / 1000 ;
if ( elapsedSeconds > 5 ) {
const blockPerSeconds = indexedThisRun / elapsedSeconds ;
logger . debug ( `Indexed ${ indexedTotal } / ${ blockIds . length } block audit details ( ${ blockPerSeconds . toFixed ( 1 ) } /s)` );
timer = Date . now ();
indexedThisRun = 0 ;
}
}
logger . debug ( `Indexing block audit details completed` );
}
2024-01-23 00:44:34 +00:00
/**
* [INDEXING] Index transaction classification flags for Goggles
*/
public async $classifyBlocks () : Promise < void > {
2024-02-19 02:43:19 +00:00
if ( this . classifyingBlocks ) {
return ;
}
this . classifyingBlocks = true ;
2024-01-23 00:44:34 +00:00
// classification requires an esplora backend
2024-01-27 18:22:58 +00:00
if ( ! Common . gogglesIndexingEnabled () || config . MEMPOOL . BACKEND !== 'esplora' ) {
2024-01-23 00:44:34 +00:00
return ;
}
const blockchainInfo = await bitcoinClient . getBlockchainInfo ();
const currentBlockHeight = blockchainInfo . blocks ;
2024-07-20 11:59:18 +00:00
const targetSummaryVersion : number = 1 ;
const targetTemplateVersion : number = 1 ;
const unclassifiedBlocksList = await BlocksSummariesRepository . $getSummariesBelowVersion ( targetSummaryVersion );
const unclassifiedTemplatesList = await BlocksSummariesRepository . $getTemplatesBelowVersion ( targetTemplateVersion );
2024-01-23 00:44:34 +00:00
// nothing to do
2024-01-23 13:33:59 +00:00
if ( ! unclassifiedBlocksList ? . length && ! unclassifiedTemplatesList ? . length ) {
2024-01-23 00:44:34 +00:00
return ;
}
let timer = Date . now ();
let indexedThisRun = 0 ;
let indexedTotal = 0 ;
const minHeight = Math . min (
2024-01-23 13:33:59 +00:00
unclassifiedBlocksList [ unclassifiedBlocksList . length - 1 ] ? . height ?? Infinity ,
unclassifiedTemplatesList [ unclassifiedTemplatesList . length - 1 ] ? . height ?? Infinity ,
2024-01-23 00:44:34 +00:00
);
const numToIndex = Math . max (
unclassifiedBlocksList . length ,
unclassifiedTemplatesList . length ,
);
const unclassifiedBlocks = {};
const unclassifiedTemplates = {};
for ( const block of unclassifiedBlocksList ) {
unclassifiedBlocks [ block . height ] = block . id ;
}
for ( const template of unclassifiedTemplatesList ) {
unclassifiedTemplates [ template . height ] = template . id ;
}
logger . debug ( `Classifying blocks and templates from # ${ currentBlockHeight } to # ${ minHeight } ` , logger . tags . goggles );
for ( let height = currentBlockHeight ; height >= 0 ; height -- ) {
2024-01-23 17:18:47 +00:00
try {
2024-04-06 02:24:22 +00:00
let txs : MempoolTransactionExtended [] | null = null ;
2024-01-23 17:18:47 +00:00
if ( unclassifiedBlocks [ height ]) {
const blockHash = unclassifiedBlocks [ height ];
// fetch transactions
2024-04-06 02:24:22 +00:00
txs = ( await bitcoinApi . $getTxsForBlock ( blockHash )). map ( tx => transactionUtils . extendMempoolTransaction ( tx )) || [];
2024-01-23 17:18:47 +00:00
// add CPFP
2024-04-06 02:24:22 +00:00
const cpfpSummary = calculateGoodBlockCpfp ( height , txs , []);
2024-01-23 00:44:34 +00:00
// classify
const { transactions : classifiedTxs } = this . summarizeBlockTransactions ( blockHash , cpfpSummary . transactions );
2024-07-20 11:59:18 +00:00
await BlocksSummariesRepository . $saveTransactions ( height , blockHash , classifiedTxs , 2 );
if ( unclassifiedBlocks [ height ]. version < 2 && targetSummaryVersion === 2 ) {
const cpfpClusters = await CpfpRepository . $getClustersAt ( height );
if ( ! cpfpRepository . compareClusters ( cpfpClusters , cpfpSummary . clusters )) {
// CPFP clusters changed - update the compact_cpfp tables
await CpfpRepository . $deleteClustersAt ( height );
await this . $saveCpfp ( blockHash , height , cpfpSummary );
}
}
2024-01-27 18:22:58 +00:00
await Common . sleep$ ( 250 );
2024-01-23 17:18:47 +00:00
}
if ( unclassifiedTemplates [ height ]) {
// classify template
const blockHash = unclassifiedTemplates [ height ];
const template = await BlocksSummariesRepository . $getTemplate ( blockHash );
2024-01-24 12:18:42 +00:00
const alreadyClassified = template ? . transactions ? . reduce (( classified , tx ) => ( classified || tx . flags > 0 ), false );
2024-01-23 17:18:47 +00:00
let classifiedTemplate = template ? . transactions || [];
if ( ! alreadyClassified ) {
const templateTxs : ( TransactionExtended | TransactionClassified )[] = [];
const blockTxMap : { [ txid : string ] : TransactionExtended } = {};
for ( const tx of ( txs || [])) {
blockTxMap [ tx . txid ] = tx ;
}
for ( const templateTx of ( template ? . transactions || [])) {
let tx : TransactionExtended | null = blockTxMap [ templateTx . txid ];
if ( ! tx ) {
try {
tx = await transactionUtils . $getTransactionExtended ( templateTx . txid , false , true , false );
} catch ( e ) {
// transaction probably not found
}
}
templateTxs . push ( tx || templateTx );
}
2024-04-06 02:24:22 +00:00
const cpfpSummary = calculateGoodBlockCpfp ( height , templateTxs ? . filter ( tx => tx [ 'effectiveFeePerVsize' ] != null ) as MempoolTransactionExtended [], []);
2024-01-23 17:18:47 +00:00
// classify
const { transactions : classifiedTxs } = this . summarizeBlockTransactions ( blockHash , cpfpSummary . transactions );
const classifiedTxMap : { [ txid : string ] : TransactionClassified } = {};
for ( const tx of classifiedTxs ) {
classifiedTxMap [ tx . txid ] = tx ;
2024-01-23 00:44:34 +00:00
}
2024-01-23 17:18:47 +00:00
classifiedTemplate = classifiedTemplate . map ( tx => {
if ( classifiedTxMap [ tx . txid ]) {
tx . flags = classifiedTxMap [ tx . txid ]. flags || 0 ;
}
return tx ;
});
}
await BlocksSummariesRepository . $saveTemplate ({ height , template : { id : blockHash , transactions : classifiedTemplate }, version : 1 });
2024-01-27 18:22:58 +00:00
await Common . sleep$ ( 250 );
2024-01-23 00:44:34 +00:00
}
2024-01-23 17:18:47 +00:00
} catch ( e ) {
logger . warn ( `Failed to classify template or block summary at ${ height } ` , logger . tags . goggles );
2024-01-23 00:44:34 +00:00
}
// timing & logging
2024-01-24 12:18:42 +00:00
if ( unclassifiedBlocks [ height ] || unclassifiedTemplates [ height ]) {
indexedThisRun ++ ;
indexedTotal ++ ;
}
2024-01-23 00:44:34 +00:00
const elapsedSeconds = ( Date . now () - timer ) / 1000 ;
if ( elapsedSeconds > 5 ) {
const perSecond = indexedThisRun / elapsedSeconds ;
logger . debug ( `Classified # ${ height } : ${ indexedTotal } / ${ numToIndex } blocks ( ${ perSecond . toFixed ( 1 ) } /s)` );
timer = Date . now ();
indexedThisRun = 0 ;
}
}
2024-02-19 02:43:19 +00:00
this . classifyingBlocks = false ;
2024-01-23 00:44:34 +00:00
}
2024-06-24 06:15:01 +00:00
/**
* [INDEXING] Index missing coinbase addresses for all blocks
*/
public async $indexCoinbaseAddresses () : Promise < void > {
try {
// Get all indexed block hash
const unindexedBlocks = await blocksRepository . $getBlocksWithoutCoinbaseAddresses ();
if ( ! unindexedBlocks ? . length ) {
return ;
}
logger . info ( `Indexing missing coinbase addresses for ${ unindexedBlocks . length } blocks` );
// Logging
let count = 0 ;
let countThisRun = 0 ;
let timer = Date . now () / 1000 ;
const startedAt = Date . now () / 1000 ;
for ( const { height , hash } of unindexedBlocks ) {
// Logging
const elapsedSeconds = ( Date . now () / 1000 ) - timer ;
if ( elapsedSeconds > 5 ) {
const runningFor = ( Date . now () / 1000 ) - startedAt ;
const blockPerSeconds = countThisRun / elapsedSeconds ;
const progress = Math . round ( count / unindexedBlocks . length * 10000 ) / 100 ;
logger . debug ( `Indexing coinbase addresses for # ${ height } | ~ ${ blockPerSeconds . toFixed ( 2 ) } blocks/sec | total: ${ count } / ${ unindexedBlocks . length } ( ${ progress } %) | elapsed: ${ runningFor . toFixed ( 2 ) } seconds` );
timer = Date . now () / 1000 ;
countThisRun = 0 ;
}
const coinbaseTx = await bitcoinApi . $getCoinbaseTx ( hash );
2024-06-25 02:20:44 +00:00
const addresses = new Set < string >( coinbaseTx . vout . map ( v => v . scriptpubkey_address ). filter ( a => a ) as string []);
2024-06-24 06:15:01 +00:00
await blocksRepository . $saveCoinbaseAddresses ( hash , [... addresses ]);
// Logging
count ++ ;
countThisRun ++ ;
}
logger . notice ( `coinbase addresses indexing completed: indexed ${ count } blocks` );
} catch ( e ) {
logger . err ( `coinbase addresses indexing failed. Trying again in 10 seconds. Reason: ${ ( e instanceof Error ? e.message : e ) } ` );
throw e ;
}
}
2022-01-05 15:41:14 +09:00
/**
2022-03-06 12:47:16 +01:00
* [INDEXING] Index all blocks metadata for the mining dashboard
2022-01-05 15:41:14 +09:00
*/
2022-06-20 16:35:10 +02:00
public async $generateBlockDatabase () : Promise < boolean > {
2022-01-24 15:36:30 +09:00
try {
2022-06-14 10:58:17 +02:00
const blockchainInfo = await bitcoinClient . getBlockchainInfo ();
2022-01-24 19:57:54 +09:00
let currentBlockHeight = blockchainInfo . blocks ;
2022-01-25 18:33:46 +09:00
2022-05-19 16:40:38 +02:00
let indexingBlockAmount = Math . min ( config . MEMPOOL . INDEXING_BLOCKS_AMOUNT , blockchainInfo . blocks );
2022-01-25 18:33:46 +09:00
if ( indexingBlockAmount <= - 1 ) {
indexingBlockAmount = currentBlockHeight + 1 ;
}
const lastBlockToIndex = Math . max ( 0 , currentBlockHeight - indexingBlockAmount + 1 );
2022-01-24 15:36:30 +09:00
2022-12-01 15:52:06 +01:00
logger . debug ( `Indexing blocks from # ${ currentBlockHeight } to # ${ lastBlockToIndex } ` , logger . tags . mining );
2022-05-02 17:28:58 +09:00
loadingIndicators . setProgress ( 'block-indexing' , 0 );
2022-01-24 15:36:30 +09:00
const chunkSize = 10000 ;
2022-05-10 14:52:37 +02:00
let totalIndexed = await blocksRepository . $blockCountBetweenHeight ( currentBlockHeight , lastBlockToIndex );
2022-02-16 21:20:28 +09:00
let indexedThisRun = 0 ;
2022-04-13 16:29:52 +09:00
let newlyIndexed = 0 ;
2023-07-31 16:03:18 +09:00
const startedAt = Date . now () / 1000 ;
let timer = Date . now () / 1000 ;
2022-03-10 14:21:11 +01:00
2022-01-24 17:43:11 +09:00
while ( currentBlockHeight >= lastBlockToIndex ) {
const endBlock = Math . max ( 0 , lastBlockToIndex , currentBlockHeight - chunkSize + 1 );
2022-01-24 15:36:30 +09:00
const missingBlockHeights : number [] = await blocksRepository . $getMissingBlocksBetweenHeights (
currentBlockHeight , endBlock );
if ( missingBlockHeights . length <= 0 ) {
currentBlockHeight -= chunkSize ;
continue ;
}
2022-01-18 17:37:04 +09:00
2022-12-01 15:52:06 +01:00
logger . info ( `Indexing ${ missingBlockHeights . length } blocks from # ${ currentBlockHeight } to # ${ endBlock } ` , logger . tags . mining );
2022-01-24 15:36:30 +09:00
for ( const blockHeight of missingBlockHeights ) {
2022-01-24 17:43:11 +09:00
if ( blockHeight < lastBlockToIndex ) {
break ;
}
2022-03-05 15:50:48 +01:00
++ indexedThisRun ;
2022-05-10 14:52:37 +02:00
++ totalIndexed ;
2023-07-31 16:03:18 +09:00
const elapsedSeconds = ( Date . now () / 1000 ) - timer ;
2022-03-10 14:21:11 +01:00
if ( elapsedSeconds > 5 || blockHeight === lastBlockToIndex ) {
2023-07-31 16:03:18 +09:00
const runningFor = ( Date . now () / 1000 ) - startedAt ;
const blockPerSeconds = indexedThisRun / elapsedSeconds ;
2022-05-10 14:52:37 +02:00
const progress = Math . round ( totalIndexed / indexingBlockAmount * 10000 ) / 100 ;
2023-07-31 16:03:18 +09:00
logger . debug ( `Indexing block # ${ blockHeight } | ~ ${ blockPerSeconds . toFixed ( 2 ) } blocks/sec | total: ${ totalIndexed } / ${ indexingBlockAmount } ( ${ progress . toFixed ( 2 ) } %) | elapsed: ${ runningFor . toFixed ( 2 ) } seconds` , logger . tags . mining );
timer = Date . now () / 1000 ;
2022-03-10 14:21:11 +01:00
indexedThisRun = 0 ;
2022-05-10 14:52:37 +02:00
loadingIndicators . setProgress ( 'block-indexing' , progress , false );
2022-03-10 14:23:29 +01:00
}
2022-03-05 15:50:48 +01:00
const blockHash = await bitcoinApi . $getBlockHash ( blockHeight );
2023-07-31 15:03:54 +09:00
const block : IEsploraApi.Block = await bitcoinApi . $getBlock ( blockHash );
2023-09-11 11:04:01 +09:00
const transactions = await this . $getTransactionsExtended ( blockHash , block . height , block . timestamp , true , null , true );
2022-03-05 15:50:48 +01:00
const blockExtended = await this . $getBlockExtended ( block , transactions );
2022-04-13 16:29:52 +09:00
newlyIndexed ++ ;
2022-03-05 15:50:48 +01:00
await blocksRepository . $saveBlockInDatabase ( blockExtended );
2022-01-18 17:37:04 +09:00
}
2022-01-24 15:36:30 +09:00
currentBlockHeight -= chunkSize ;
}
2022-07-11 10:55:25 +02:00
if ( newlyIndexed > 0 ) {
2022-12-01 15:52:06 +01:00
logger . notice ( `Block indexing completed: indexed ${ newlyIndexed } blocks` , logger . tags . mining );
2022-07-11 10:55:25 +02:00
} else {
2022-12-01 15:52:06 +01:00
logger . debug ( `Block indexing completed: indexed ${ newlyIndexed } blocks` , logger . tags . mining );
2022-07-11 10:55:25 +02:00
}
2022-05-02 17:28:58 +09:00
loadingIndicators . setProgress ( 'block-indexing' , 100 );
2022-01-24 15:36:30 +09:00
} catch ( e ) {
2022-12-01 15:52:06 +01:00
logger . err ( 'Block indexing failed. Trying again in 10 seconds. Reason: ' + ( e instanceof Error ? e.message : e ), logger . tags . mining );
2022-05-02 17:28:58 +09:00
loadingIndicators . setProgress ( 'block-indexing' , 100 );
2022-06-25 19:50:39 +02:00
throw e ;
2022-01-05 15:41:14 +09:00
}
2022-02-21 17:34:07 +09:00
2022-06-25 19:50:39 +02:00
return await BlocksRepository . $validateChain ();
2022-01-05 15:41:14 +09:00
}
2023-04-07 09:41:25 +09:00
public async $updateBlocks () : Promise < number > {
2023-04-27 10:19:12 +09:00
// warn if this run stalls the main loop for more than 2 minutes
const timer = this . startTimer ();
2023-05-01 14:30:30 -06:00
diskCache . lock ();
2022-04-18 17:49:22 +09:00
let fastForwarded = false ;
2023-04-07 09:41:25 +09:00
let handledBlocks = 0 ;
2023-07-16 17:12:26 +09:00
const blockHeightTip = await bitcoinCoreApi . $getBlockHeightTip ();
2023-04-27 10:19:12 +09:00
this . updateTimerProgress ( timer , 'got block height tip' );
2019-07-21 17:59:47 +03:00
2020-10-18 21:47:47 +07:00
if ( this . blocks . length === 0 ) {
2022-01-19 16:58:56 +01:00
this . currentBlockHeight = Math . max ( blockHeightTip - config . MEMPOOL . INITIAL_BLOCKS_AMOUNT , - 1 );
2020-10-18 21:47:47 +07:00
} else {
this . currentBlockHeight = this . blocks [ this . blocks . length - 1 ]. height ;
}
2024-02-11 22:50:34 +00:00
if ( this . currentBlockHeight >= 503 ) {
try {
const quarterEpochBlockHash = await bitcoinApi . $getBlockHash ( this . currentBlockHeight - 503 );
const quarterEpochBlock = await bitcoinApi . $getBlock ( quarterEpochBlockHash );
this . quarterEpochBlockTime = quarterEpochBlock ? . timestamp ;
} catch ( e ) {
this . quarterEpochBlockTime = null ;
logger . warn ( 'failed to update last epoch block time: ' + ( e instanceof Error ? e.message : e ));
}
}
2020-10-18 21:47:47 +07:00
2021-07-31 17:56:10 +03:00
if ( blockHeightTip - this . currentBlockHeight > config . MEMPOOL . INITIAL_BLOCKS_AMOUNT * 2 ) {
logger . info ( ` ${ blockHeightTip - this . currentBlockHeight } blocks since tip. Fast forwarding to the ${ config . MEMPOOL . INITIAL_BLOCKS_AMOUNT } recent blocks` );
this . currentBlockHeight = blockHeightTip - config . MEMPOOL . INITIAL_BLOCKS_AMOUNT ;
2022-04-18 17:49:22 +09:00
fastForwarded = true ;
2022-05-19 16:40:38 +02:00
logger . info ( `Re-indexing skipped blocks and corresponding hashrates data` );
indexer . reindex (); // Make sure to index the skipped blocks #1619
2020-10-18 21:47:47 +07:00
}
if ( ! this . lastDifficultyAdjustmentTime ) {
2021-09-15 01:47:24 +04:00
const blockchainInfo = await bitcoinClient . getBlockchainInfo ();
2023-04-27 10:19:12 +09:00
this . updateTimerProgress ( timer , 'got blockchain info for initial difficulty adjustment' );
2021-08-01 15:49:26 +03:00
if ( blockchainInfo . blocks === blockchainInfo . headers ) {
const heightDiff = blockHeightTip % 2016 ;
const blockHash = await bitcoinApi . $getBlockHash ( blockHeightTip - heightDiff );
2023-04-27 10:19:12 +09:00
this . updateTimerProgress ( timer , 'got block hash for initial difficulty adjustment' );
2023-07-31 15:03:54 +09:00
const block : IEsploraApi.Block = await bitcoinApi . $getBlock ( blockHash );
2023-04-27 10:19:12 +09:00
this . updateTimerProgress ( timer , 'got block for initial difficulty adjustment' );
2021-08-01 15:49:26 +03:00
this . lastDifficultyAdjustmentTime = block . timestamp ;
2023-07-31 18:22:13 -07:00
this . currentBits = block . bits ;
2021-08-01 15:49:26 +03:00
2022-03-09 11:51:36 +01:00
if ( blockHeightTip >= 2016 ) {
2022-01-19 16:58:56 +01:00
const previousPeriodBlockHash = await bitcoinApi . $getBlockHash ( blockHeightTip - heightDiff - 2016 );
2023-04-27 10:19:12 +09:00
this . updateTimerProgress ( timer , 'got previous block hash for initial difficulty adjustment' );
2023-07-31 15:03:54 +09:00
const previousPeriodBlock : IEsploraApi.Block = await bitcoinApi . $getBlock ( previousPeriodBlockHash );
2023-04-27 10:19:12 +09:00
this . updateTimerProgress ( timer , 'got previous block for initial difficulty adjustment' );
2023-08-04 20:42:14 -07:00
if ([ 'liquid' , 'liquidtestnet' ]. includes ( config . MEMPOOL . NETWORK )) {
this . previousDifficultyRetarget = NaN ;
} else {
this . previousDifficultyRetarget = calcBitsDifference ( previousPeriodBlock . bits , block . bits );
}
2022-01-19 16:58:56 +01:00
logger . debug ( `Initial difficulty adjustment data set.` );
}
2021-08-01 15:49:26 +03:00
} else {
logger . debug ( `Blockchain headers ( ${ blockchainInfo . headers } ) and blocks ( ${ blockchainInfo . blocks } ) not in sync. Waiting...` );
}
2020-10-18 21:47:47 +07:00
}
while ( this . currentBlockHeight < blockHeightTip ) {
2023-03-26 17:54:24 +09:00
if ( this . currentBlockHeight === 0 ) {
2020-10-18 21:47:47 +07:00
this . currentBlockHeight = blockHeightTip ;
2019-07-21 17:59:47 +03:00
} else {
2020-10-18 21:47:47 +07:00
this . currentBlockHeight ++ ;
logger . debug ( `New block found (# ${ this . currentBlockHeight } )!` );
2024-05-07 01:03:59 +00:00
// skip updating the orphan block cache if we've fallen behind the chain tip
if ( this . currentBlockHeight >= blockHeightTip - 2 ) {
this . updateTimerProgress ( timer , `getting orphaned blocks for ${ this . currentBlockHeight } ` );
await chainTips . updateOrphanedBlocks ();
}
2019-07-21 17:59:47 +03:00
}
2023-04-27 10:19:12 +09:00
this . updateTimerProgress ( timer , `getting block data for ${ this . currentBlockHeight } ` );
2023-07-16 17:12:26 +09:00
const blockHash = await bitcoinCoreApi . $getBlockHash ( this . currentBlockHeight );
2022-06-15 19:53:37 +00:00
const verboseBlock = await bitcoinClient . getBlock ( blockHash , 2 );
const block = BitcoinApi . convertBlock ( verboseBlock );
2023-07-16 17:12:26 +09:00
const txIds : string [] = verboseBlock . tx . map ( tx => tx . txid );
2023-09-11 11:04:01 +09:00
const transactions = await this . $getTransactionsExtended ( blockHash , block . height , block . timestamp , false , txIds , false , true ) as MempoolTransactionExtended [];
2023-07-27 11:45:16 +09:00
// fill in missing transaction fee data from verboseBlock
for ( let i = 0 ; i < transactions . length ; i ++ ) {
if ( ! transactions [ i ]. fee && transactions [ i ]. txid === verboseBlock . tx [ i ]. txid ) {
2023-08-01 17:33:03 +09:00
transactions [ i ]. fee = ( verboseBlock . tx [ i ]. fee * 100 _000_000 ) || 0 ;
2023-05-26 19:12:12 -04:00
}
}
2023-07-27 11:45:16 +09:00
2024-04-06 02:24:22 +00:00
const cpfpSummary : CpfpSummary = calculateGoodBlockCpfp ( block . height , transactions , Object . values ( mempool . getAccelerations ()). map ( a => ({ txid : a.txid , max_bid : a.feeDelta })));
2023-03-12 11:09:11 +09:00
const blockExtended : BlockExtended = await this . $getBlockExtended ( block , cpfpSummary . transactions );
2023-06-29 19:24:19 -04:00
const blockSummary : BlockSummary = this . summarizeBlockTransactions ( block . id , cpfpSummary . transactions );
2023-04-27 10:19:12 +09:00
this . updateTimerProgress ( timer , `got block data for ${ this . currentBlockHeight } ` );
2022-02-08 15:47:43 +09:00
2022-02-15 16:02:30 +09:00
if ( Common . indexingEnabled ()) {
2022-04-18 17:49:22 +09:00
if ( ! fastForwarded ) {
const lastBlock = await blocksRepository . $getBlockByHeight ( blockExtended . height - 1 );
2023-04-27 10:19:12 +09:00
this . updateTimerProgress ( timer , `got block by height for ${ this . currentBlockHeight } ` );
2023-03-01 13:50:15 +09:00
if ( lastBlock !== null && blockExtended . previousblockhash !== lastBlock . id ) {
2023-03-19 10:46:38 +09:00
logger . warn ( `Chain divergence detected at block ${ lastBlock . height } , re-indexing most recent data` , logger . tags . mining );
2022-04-19 15:45:06 +09:00
// We assume there won't be a reorg with more than 10 block depth
2023-04-27 10:19:12 +09:00
this . updateTimerProgress ( timer , `rolling back diverged chain from ${ this . currentBlockHeight } ` );
2023-03-01 13:50:15 +09:00
await BlocksRepository . $deleteBlocksFrom ( lastBlock . height - 10 );
2022-04-18 17:49:22 +09:00
await HashratesRepository . $deleteLastEntries ();
2023-03-01 13:50:15 +09:00
await cpfpRepository . $deleteClustersFrom ( lastBlock . height - 10 );
2024-04-04 08:18:34 +00:00
await AccelerationRepository . $deleteAccelerationsFrom ( lastBlock . height - 10 );
2023-07-08 00:33:14 -04:00
this . blocks = this . blocks . slice ( 0 , - 10 );
2023-04-27 10:19:12 +09:00
this . updateTimerProgress ( timer , `rolled back chain divergence from ${ this . currentBlockHeight } ` );
2022-04-19 15:45:06 +09:00
for ( let i = 10 ; i >= 0 ; -- i ) {
2023-03-01 13:50:15 +09:00
const newBlock = await this . $indexBlock ( lastBlock . height - i );
2023-07-08 00:33:14 -04:00
this . blocks . push ( newBlock );
2023-04-27 10:19:12 +09:00
this . updateTimerProgress ( timer , `reindexed block` );
2023-06-29 19:24:19 -04:00
let cpfpSummary ;
2022-12-28 05:28:37 -06:00
if ( config . MEMPOOL . CPFP_INDEXING ) {
2023-06-29 19:24:19 -04:00
cpfpSummary = await this . $indexCPFP ( newBlock . id , lastBlock . height - i );
2023-04-27 10:19:12 +09:00
this . updateTimerProgress ( timer , `reindexed block cpfp` );
2022-11-27 13:46:23 +09:00
}
2023-06-29 19:24:19 -04:00
await this . $getStrippedBlockTransactions ( newBlock . id , true , true , cpfpSummary , newBlock . height );
this . updateTimerProgress ( timer , `reindexed block summary` );
2022-04-19 15:45:06 +09:00
}
2022-06-25 12:14:32 +02:00
await mining . $indexDifficultyAdjustments ();
await DifficultyAdjustmentsRepository . $deleteLastAdjustment ();
2023-04-27 10:19:12 +09:00
this . updateTimerProgress ( timer , `reindexed difficulty adjustments` );
2023-03-19 10:46:38 +09:00
logger . info ( `Re-indexed 10 blocks and summaries. Also re-indexed the last difficulty adjustments. Will re-index latest hashrates in a few seconds.` , logger . tags . mining );
2022-06-25 12:14:32 +02:00
indexer . reindex ();
2023-07-08 01:07:06 -04:00
websocketHandler . handleReorg ();
2022-04-18 17:49:22 +09:00
}
2023-06-07 11:59:31 -04:00
}
2022-06-18 16:48:02 +02:00
2023-06-07 11:59:31 -04:00
await blocksRepository . $saveBlockInDatabase ( blockExtended );
this . updateTimerProgress ( timer , `saved ${ this . currentBlockHeight } to database` );
if ( ! fastForwarded ) {
2023-11-14 05:00:05 +00:00
let lastestPriceId ;
try {
lastestPriceId = await PricesRepository . $getLatestPriceId ();
this . updateTimerProgress ( timer , `got latest price id ${ this . currentBlockHeight } ` );
} catch ( e ) {
logger . debug ( 'failed to fetch latest price id from db: ' + ( e instanceof Error ? e.message : e ));
}
2022-07-16 09:22:45 +02:00
if ( priceUpdater . historyInserted === true && lastestPriceId !== null ) {
await blocksRepository . $saveBlockPrices ([{
height : blockExtended.height ,
priceId : lastestPriceId ,
}]);
2023-04-27 10:19:12 +09:00
this . updateTimerProgress ( timer , `saved prices for ${ this . currentBlockHeight } ` );
2022-07-16 09:22:45 +02:00
} else {
2023-03-14 13:53:52 +09:00
logger . debug ( `Cannot save block price for ${ blockExtended . height } because the price updater hasnt completed yet. Trying again in 10 seconds.` , logger . tags . mining );
2023-09-21 17:50:53 +01:00
indexer . scheduleSingleTask ( 'blocksPrices' , 10000 );
2022-07-16 09:22:45 +02:00
}
2022-06-18 16:48:02 +02:00
// Save blocks summary for visualization if it's enabled
if ( Common . blocksSummariesIndexingEnabled () === true ) {
2023-06-29 19:24:19 -04:00
await this . $getStrippedBlockTransactions ( blockExtended . id , true , false , cpfpSummary , blockExtended . height );
2023-04-27 10:19:12 +09:00
this . updateTimerProgress ( timer , `saved block summary for ${ this . currentBlockHeight } ` );
2022-06-18 16:48:02 +02:00
}
2022-12-28 05:28:37 -06:00
if ( config . MEMPOOL . CPFP_INDEXING ) {
2023-03-12 11:09:11 +09:00
this . $saveCpfp ( blockExtended . id , this . currentBlockHeight , cpfpSummary );
2023-04-27 10:19:12 +09:00
this . updateTimerProgress ( timer , `saved cpfp for ${ this . currentBlockHeight } ` );
2022-11-27 13:46:23 +09:00
}
2022-03-15 13:07:06 +01:00
}
2022-01-21 00:08:51 +09:00
}
2020-09-21 19:41:12 +07:00
2023-07-08 00:33:14 -04:00
// start async callbacks
this . updateTimerProgress ( timer , `starting async callbacks for ${ this . currentBlockHeight } ` );
const callbackPromises = this . newAsyncBlockCallbacks . map (( cb ) => cb ( blockExtended , txIds , transactions ));
2020-10-18 21:47:47 +07:00
if ( block . height % 2016 === 0 ) {
2022-06-25 12:14:32 +02:00
if ( Common . indexingEnabled ()) {
2023-08-04 20:42:14 -07:00
let adjustment ;
if ([ 'liquid' , 'liquidtestnet' ]. includes ( config . MEMPOOL . NETWORK )) {
adjustment = NaN ;
} else {
adjustment = Math . round (
// calcBitsDifference returns +- percentage, +100 returns to positive, /100 returns to ratio.
// Instead of actually doing /100, just reduce the multiplier.
( calcBitsDifference ( this . currentBits , block . bits ) + 100 ) * 10000
) / 1000000 ; // Remove float point noise
}
2022-06-25 12:14:32 +02:00
await DifficultyAdjustmentsRepository . $saveAdjustments ({
time : block.timestamp ,
height : block.height ,
difficulty : block.difficulty ,
2023-08-04 20:42:14 -07:00
adjustment ,
2022-06-25 12:14:32 +02:00
});
2023-04-27 10:19:12 +09:00
this . updateTimerProgress ( timer , `saved difficulty adjustment for ${ this . currentBlockHeight } ` );
2022-06-25 12:14:32 +02:00
}
2023-08-04 20:42:14 -07:00
if ([ 'liquid' , 'liquidtestnet' ]. includes ( config . MEMPOOL . NETWORK )) {
this . previousDifficultyRetarget = NaN ;
} else {
this . previousDifficultyRetarget = calcBitsDifference ( this . currentBits , block . bits );
}
2020-10-18 21:47:47 +07:00
this . lastDifficultyAdjustmentTime = block . timestamp ;
2023-07-31 18:22:13 -07:00
this . currentBits = block . bits ;
2020-10-18 21:47:47 +07:00
}
2019-07-21 17:59:47 +03:00
2023-06-12 15:31:47 -04:00
// wait for pending async callbacks to finish
this . updateTimerProgress ( timer , `waiting for async callbacks to complete for ${ this . currentBlockHeight } ` );
await Promise . all ( callbackPromises );
this . updateTimerProgress ( timer , `async callbacks completed for ${ this . currentBlockHeight } ` );
2020-12-28 04:47:22 +07:00
this . blocks . push ( blockExtended );
2021-07-31 17:56:10 +03:00
if ( this . blocks . length > config . MEMPOOL . INITIAL_BLOCKS_AMOUNT * 4 ) {
this . blocks = this . blocks . slice ( - config . MEMPOOL . INITIAL_BLOCKS_AMOUNT * 4 );
2019-07-21 17:59:47 +03:00
}
2024-04-08 13:43:54 +00:00
blockSummary . transactions . forEach ( tx => {
delete tx . acc ;
});
2022-06-15 19:53:37 +00:00
this . blockSummaries . push ( blockSummary );
if ( this . blockSummaries . length > config . MEMPOOL . INITIAL_BLOCKS_AMOUNT * 4 ) {
this . blockSummaries = this . blockSummaries . slice ( - config . MEMPOOL . INITIAL_BLOCKS_AMOUNT * 4 );
}
2019-07-21 17:59:47 +03:00
2020-10-18 21:47:47 +07:00
if ( this . newBlockCallbacks . length ) {
2020-12-28 04:47:22 +07:00
this . newBlockCallbacks . forEach (( cb ) => cb ( blockExtended , txIds , transactions ));
2020-10-18 21:47:47 +07:00
}
2023-05-12 16:29:45 -06:00
if ( config . MEMPOOL . CACHE_ENABLED && ! memPool . hasPriority () && ( block . height % config . MEMPOOL . DISK_CACHE_BLOCK_INTERVAL === 0 )) {
2021-01-22 23:20:39 +07:00
diskCache . $saveCacheToDisk ();
}
2022-11-16 18:18:59 -06:00
2023-05-12 16:29:45 -06:00
// Update Redis cache
if ( config . REDIS . ENABLED ) {
await redisCache . $updateBlocks ( this . blocks );
await redisCache . $updateBlockSummaries ( this . blockSummaries );
await redisCache . $removeTransactions ( txIds );
await rbfCache . updateCache ();
}
2023-04-07 09:41:25 +09:00
handledBlocks ++ ;
2023-04-27 10:19:12 +09:00
}
2023-05-01 14:30:30 -06:00
diskCache . unlock ();
2023-04-27 10:19:12 +09:00
this . clearTimer ( timer );
2023-04-07 09:41:25 +09:00
return handledBlocks ;
2023-04-27 10:19:12 +09:00
}
private startTimer() {
const state : any = {
start : Date.now (),
progress : 'begin $updateBlocks' ,
timer : null ,
};
state . timer = setTimeout (() => {
2023-05-01 00:16:23 +04:00
logger . err ( `$updateBlocks stalled at " ${ state . progress } "` );
2023-04-27 10:19:12 +09:00
}, this . mainLoopTimeout );
return state ;
}
2024-01-30 16:41:35 +00:00
private updateTimerProgress ( state , msg ) : void {
2023-04-27 10:19:12 +09:00
state . progress = msg ;
}
2024-01-30 16:41:35 +00:00
private clearTimer ( state ) : void {
2023-04-27 10:19:12 +09:00
if ( state . timer ) {
clearTimeout ( state . timer );
2019-08-29 01:17:31 +02:00
}
}
2020-05-24 22:45:45 +07:00
2022-02-08 15:47:43 +09:00
/**
* Index a block if it's missing from the database. Returns the block after indexing
*/
2022-03-13 11:38:45 +01:00
public async $indexBlock ( height : number ) : Promise < BlockExtended > {
2023-02-19 19:08:29 +09:00
if ( Common . indexingEnabled ()) {
const dbBlock = await blocksRepository . $getBlockByHeight ( height );
if ( dbBlock !== null ) {
2023-02-27 18:00:00 +09:00
return dbBlock ;
2023-02-19 19:08:29 +09:00
}
2022-02-08 15:47:43 +09:00
}
const blockHash = await bitcoinApi . $getBlockHash ( height );
2023-07-31 15:03:54 +09:00
const block : IEsploraApi.Block = await bitcoinApi . $getBlock ( blockHash );
2023-09-11 11:04:01 +09:00
const transactions = await this . $getTransactionsExtended ( blockHash , block . height , block . timestamp , true );
2022-02-08 15:47:43 +09:00
const blockExtended = await this . $getBlockExtended ( block , transactions );
2023-02-14 22:12:43 +09:00
if ( Common . indexingEnabled ()) {
await blocksRepository . $saveBlockInDatabase ( blockExtended );
}
2022-02-08 15:47:43 +09:00
2023-02-27 18:00:00 +09:00
return blockExtended ;
2022-02-08 15:47:43 +09:00
}
2023-07-08 00:33:14 -04:00
public async $indexStaleBlock ( hash : string ) : Promise < BlockExtended > {
2023-07-31 15:03:54 +09:00
const block : IEsploraApi.Block = await bitcoinApi . $getBlock ( hash );
2023-09-11 11:04:01 +09:00
const transactions = await this . $getTransactionsExtended ( hash , block . height , block . timestamp , true );
2023-07-08 00:33:14 -04:00
const blockExtended = await this . $getBlockExtended ( block , transactions );
blockExtended . canonical = await bitcoinApi . $getBlockHash ( block . height );
return blockExtended ;
}
2022-04-20 13:12:32 +09:00
/**
2023-02-27 18:00:00 +09:00
* Get one block by its hash
2022-04-20 13:12:32 +09:00
*/
public async $getBlock ( hash : string ) : Promise < BlockExtended | IEsploraApi.Block > {
2022-04-20 13:40:10 +09:00
// Check the memory cache
const blockByHash = this . getBlocks (). find (( b ) => b . id === hash );
if ( blockByHash ) {
return blockByHash ;
}
2023-02-27 18:00:00 +09:00
// Not Bitcoin network, return the block as it from the bitcoin backend
2022-04-20 13:12:32 +09:00
if ([ 'mainnet' , 'testnet' , 'signet' ]. includes ( config . MEMPOOL . NETWORK ) === false ) {
2023-03-03 13:59:17 +09:00
return await bitcoinCoreApi . $getBlock ( hash );
2022-04-20 13:12:32 +09:00
}
// Bitcoin network, add our custom data on top
2023-07-31 15:03:54 +09:00
const block : IEsploraApi.Block = await bitcoinApi . $getBlock ( hash );
2023-07-08 00:33:14 -04:00
if ( block . stale ) {
return await this . $indexStaleBlock ( hash );
} else {
return await this . $indexBlock ( block . height );
}
2022-04-20 13:12:32 +09:00
}
2022-07-11 08:41:28 +02:00
public async $getStrippedBlockTransactions ( hash : string , skipMemoryCache = false ,
2023-12-21 16:20:31 +00:00
skipDBLookup = false , cpfpSummary? : CpfpSummary , blockHeight? : number ) : Promise < TransactionClassified [] >
2022-06-20 16:35:10 +02:00
{
2022-06-18 16:48:02 +02:00
if ( skipMemoryCache === false ) {
// Check the memory cache
const cachedSummary = this . getBlockSummaries (). find (( b ) => b . id === hash );
2022-11-25 10:16:58 +09:00
if ( cachedSummary ? . transactions ? . length ) {
2022-06-18 16:48:02 +02:00
return cachedSummary . transactions ;
}
}
// Check if it's indexed in db
if ( skipDBLookup === false && Common . blocksSummariesIndexingEnabled () === true ) {
const indexedSummary = await BlocksSummariesRepository . $getByBlockId ( hash );
2022-11-25 10:16:58 +09:00
if ( indexedSummary !== undefined && indexedSummary ? . transactions ? . length ) {
2022-06-18 16:48:02 +02:00
return indexedSummary . transactions ;
}
2022-06-15 19:53:37 +00:00
}
2022-06-18 16:48:02 +02:00
2023-06-29 19:24:19 -04:00
let height = blockHeight ;
let summary : BlockSummary ;
2024-01-23 00:44:34 +00:00
let summaryVersion = 0 ;
2023-07-19 15:05:40 +09:00
if ( cpfpSummary && ! Common . isLiquid ()) {
2023-06-29 19:24:19 -04:00
summary = {
id : hash ,
transactions : cpfpSummary.transactions.map ( tx => {
2024-01-30 16:41:35 +00:00
let flags : number = 0 ;
try {
2024-04-06 07:59:18 +00:00
flags = Common . getTransactionFlags ( tx );
2024-01-30 16:41:35 +00:00
} catch ( e ) {
logger . warn ( 'Failed to classify transaction: ' + ( e instanceof Error ? e.message : e ));
}
2023-06-29 19:24:19 -04:00
return {
txid : tx.txid ,
2024-04-08 13:43:54 +00:00
time : tx.firstSeen ,
2023-08-01 17:33:03 +09:00
fee : tx.fee || 0 ,
2023-06-29 19:24:19 -04:00
vsize : tx.vsize ,
value : Math.round ( tx . vout . reduce (( acc , vout ) => acc + ( vout . value ? vout.value : 0 ), 0 )),
2023-12-21 16:20:31 +00:00
rate : tx.effectiveFeePerVsize ,
2024-01-30 16:41:35 +00:00
flags : flags ,
2023-06-29 19:24:19 -04:00
};
}),
};
2024-01-23 00:44:34 +00:00
summaryVersion = 1 ;
2023-06-29 19:24:19 -04:00
} else {
2023-07-31 18:02:18 +09:00
if ( config . MEMPOOL . BACKEND === 'esplora' ) {
const txs = ( await bitcoinApi . $getTxsForBlock ( hash )). map ( tx => transactionUtils . extendTransaction ( tx ));
summary = this . summarizeBlockTransactions ( hash , txs );
2024-01-23 00:44:34 +00:00
summaryVersion = 1 ;
2023-07-31 18:02:18 +09:00
} else {
// Call Core RPC
const block = await bitcoinClient . getBlock ( hash , 2 );
summary = this . summarizeBlock ( block );
height = block . height ;
}
2023-06-29 19:24:19 -04:00
}
if ( height == null ) {
const block = await bitcoinApi . $getBlock ( hash );
height = block . height ;
}
2022-06-18 16:48:02 +02:00
// Index the response if needed
if ( Common . blocksSummariesIndexingEnabled () === true ) {
2024-01-23 00:44:34 +00:00
await BlocksSummariesRepository . $saveTransactions ( height , hash , summary . transactions , summaryVersion );
2022-06-18 16:48:02 +02:00
}
2022-06-15 19:53:37 +00:00
return summary . transactions ;
}
2023-02-27 18:00:00 +09:00
/**
* Get 15 blocks
*
* Internally this function uses two methods to get the blocks, and
* the method is automatically selected:
* - Using previous block hash links
* - Using block height
*
* @param fromHeight
* @param limit
* @returns
*/
2022-05-20 18:11:02 +02:00
public async $getBlocks ( fromHeight? : number , limit : number = 15 ) : Promise < BlockExtended [] > {
2022-12-16 17:43:37 +01:00
let currentHeight = fromHeight !== undefined ? fromHeight : this.currentBlockHeight ;
2022-12-27 05:28:57 -06:00
if ( currentHeight > this . currentBlockHeight ) {
limit -= currentHeight - this . currentBlockHeight ;
currentHeight = this . currentBlockHeight ;
}
2022-07-08 16:34:00 +02:00
const returnBlocks : BlockExtended [] = [];
2022-02-08 15:47:43 +09:00
2022-07-08 16:34:00 +02:00
if ( currentHeight < 0 ) {
return returnBlocks ;
}
2022-02-08 15:47:43 +09:00
2022-07-08 16:34:00 +02:00
for ( let i = 0 ; i < limit && currentHeight >= 0 ; i ++ ) {
let block = this . getBlocks (). find (( b ) => b . height === currentHeight );
if ( block ) {
2023-02-27 18:00:00 +09:00
// Using the memory cache (find by height)
2022-07-08 16:34:00 +02:00
returnBlocks . push ( block );
2023-03-02 10:08:40 +09:00
} else {
2023-02-27 18:00:00 +09:00
// Using indexing (find by height, index on the fly, save in database)
2022-07-08 16:34:00 +02:00
block = await this . $indexBlock ( currentHeight );
returnBlocks . push ( block );
2022-02-08 15:47:43 +09:00
}
2022-07-08 16:34:00 +02:00
currentHeight -- ;
2022-02-08 15:47:43 +09:00
}
2022-07-08 16:34:00 +02:00
return returnBlocks ;
2022-02-08 15:47:43 +09:00
}
2023-02-17 21:21:21 +09:00
/**
* Used for bulk block data query
*
* @param fromHeight
* @param toHeight
*/
public async $getBlocksBetweenHeight ( fromHeight : number , toHeight : number ) : Promise < any > {
if ( ! Common . indexingEnabled ()) {
return [];
}
2023-02-16 15:36:16 +09:00
const blocks : any [] = [];
2023-02-17 21:21:21 +09:00
while ( fromHeight <= toHeight ) {
2023-02-27 18:00:00 +09:00
let block : BlockExtended | null = await blocksRepository . $getBlockByHeight ( fromHeight );
2023-02-17 21:21:21 +09:00
if ( ! block ) {
2023-02-18 08:42:38 +09:00
await this . $indexBlock ( fromHeight );
block = await blocksRepository . $getBlockByHeight ( fromHeight );
if ( ! block ) {
continue ;
}
2023-02-17 21:21:21 +09:00
}
2023-02-24 11:33:36 +09:00
// Cleanup fields before sending the response
const cleanBlock : any = {
height : block.height ?? null ,
hash : block.id ?? null ,
2023-02-27 18:00:00 +09:00
timestamp : block.timestamp ?? null ,
median_timestamp : block.mediantime ?? null ,
2023-02-24 11:43:38 +09:00
previous_block_hash : block.previousblockhash ?? null ,
2023-02-24 11:33:36 +09:00
difficulty : block.difficulty ?? null ,
2023-02-27 18:00:00 +09:00
header : block.extras.header ?? null ,
2023-02-24 11:33:36 +09:00
version : block.version ?? null ,
bits : block.bits ?? null ,
nonce : block.nonce ?? null ,
size : block.size ?? null ,
weight : block.weight ?? null ,
tx_count : block.tx_count ?? null ,
merkle_root : block.merkle_root ?? null ,
2023-02-27 18:00:00 +09:00
reward : block.extras.reward ?? null ,
total_fee_amt : block.extras.totalFees ?? null ,
avg_fee_amt : block.extras.avgFee ?? null ,
median_fee_amt : block.extras.medianFeeAmt ?? null ,
fee_amt_percentiles : block.extras.feePercentiles ?? null ,
avg_fee_rate : block.extras.avgFeeRate ?? null ,
median_fee_rate : block.extras.medianFee ?? null ,
fee_rate_percentiles : block.extras.feeRange ?? null ,
total_inputs : block.extras.totalInputs ?? null ,
total_input_amt : block.extras.totalInputAmt ?? null ,
total_outputs : block.extras.totalOutputs ?? null ,
total_output_amt : block.extras.totalOutputAmt ?? null ,
segwit_total_txs : block.extras.segwitTotalTxs ?? null ,
segwit_total_size : block.extras.segwitTotalSize ?? null ,
segwit_total_weight : block.extras.segwitTotalWeight ?? null ,
avg_tx_size : block.extras.avgTxSize ?? null ,
utxoset_change : block.extras.utxoSetChange ?? null ,
utxoset_size : block.extras.utxoSetSize ?? null ,
coinbase_raw : block.extras.coinbaseRaw ?? null ,
coinbase_address : block.extras.coinbaseAddress ?? null ,
2024-06-24 06:15:01 +00:00
coinbase_addresses : block.extras.coinbaseAddresses ?? null ,
2023-02-27 18:00:00 +09:00
coinbase_signature : block.extras.coinbaseSignature ?? null ,
coinbase_signature_ascii : block.extras.coinbaseSignatureAscii ?? null ,
pool_slug : block.extras.pool.slug ?? null ,
pool_id : block.extras.pool.id ?? null ,
2023-02-24 11:33:36 +09:00
};
if ( Common . blocksSummariesIndexingEnabled () && cleanBlock . fee_amt_percentiles === null ) {
cleanBlock . fee_amt_percentiles = await BlocksSummariesRepository . $getFeePercentilesByBlockId ( cleanBlock . hash );
if ( cleanBlock . fee_amt_percentiles === null ) {
2023-07-31 18:02:18 +09:00
let summary ;
2024-01-23 00:44:34 +00:00
let summaryVersion = 0 ;
2023-07-31 18:02:18 +09:00
if ( config . MEMPOOL . BACKEND === 'esplora' ) {
const txs = ( await bitcoinApi . $getTxsForBlock ( cleanBlock . hash )). map ( tx => transactionUtils . extendTransaction ( tx ));
summary = this . summarizeBlockTransactions ( cleanBlock . hash , txs );
2024-01-23 00:44:34 +00:00
summaryVersion = 1 ;
2023-07-31 18:02:18 +09:00
} else {
// Call Core RPC
const block = await bitcoinClient . getBlock ( cleanBlock . hash , 2 );
summary = this . summarizeBlock ( block );
}
2024-01-23 00:44:34 +00:00
await BlocksSummariesRepository . $saveTransactions ( cleanBlock . height , cleanBlock . hash , summary . transactions , summaryVersion );
2023-02-24 11:33:36 +09:00
cleanBlock . fee_amt_percentiles = await BlocksSummariesRepository . $getFeePercentilesByBlockId ( cleanBlock . hash );
}
if ( cleanBlock . fee_amt_percentiles !== null ) {
cleanBlock . median_fee_amt = cleanBlock . fee_amt_percentiles [ 3 ];
2023-04-06 11:55:17 +09:00
await blocksRepository . $updateFeeAmounts ( cleanBlock . hash , cleanBlock . fee_amt_percentiles , cleanBlock . median_fee_amt );
2023-02-18 11:26:13 +09:00
}
}
2023-02-24 12:48:55 +09:00
cleanBlock . fee_amt_percentiles = {
'min' : cleanBlock . fee_amt_percentiles [ 0 ],
'perc_10' : cleanBlock . fee_amt_percentiles [ 1 ],
'perc_25' : cleanBlock . fee_amt_percentiles [ 2 ],
'perc_50' : cleanBlock . fee_amt_percentiles [ 3 ],
'perc_75' : cleanBlock . fee_amt_percentiles [ 4 ],
'perc_90' : cleanBlock . fee_amt_percentiles [ 5 ],
'max' : cleanBlock . fee_amt_percentiles [ 6 ],
};
cleanBlock . fee_rate_percentiles = {
'min' : cleanBlock . fee_rate_percentiles [ 0 ],
'perc_10' : cleanBlock . fee_rate_percentiles [ 1 ],
'perc_25' : cleanBlock . fee_rate_percentiles [ 2 ],
'perc_50' : cleanBlock . fee_rate_percentiles [ 3 ],
'perc_75' : cleanBlock . fee_rate_percentiles [ 4 ],
'perc_90' : cleanBlock . fee_rate_percentiles [ 5 ],
'max' : cleanBlock . fee_rate_percentiles [ 6 ],
};
2023-02-18 14:10:07 +09:00
// Re-org can happen after indexing so we need to always get the
// latest state from core
2023-02-24 11:33:36 +09:00
cleanBlock . orphans = chainTips . getOrphanedBlocksAtHeight ( cleanBlock . height );
2023-02-18 14:10:07 +09:00
2023-02-24 11:33:36 +09:00
blocks . push ( cleanBlock );
2023-02-17 21:21:21 +09:00
fromHeight ++ ;
2023-02-16 15:36:16 +09:00
}
2023-02-17 21:21:21 +09:00
2023-02-16 15:36:16 +09:00
return blocks ;
}
2024-01-30 16:41:35 +00:00
public async $getBlockAuditSummary ( hash : string ) : Promise < BlockAudit | null > {
2022-11-28 14:26:28 +09:00
if ([ 'mainnet' , 'testnet' , 'signet' ]. includes ( config . MEMPOOL . NETWORK )) {
2023-06-20 14:54:25 -04:00
return BlocksAuditsRepository . $getBlockAudit ( hash );
} else {
return null ;
2022-11-25 19:32:50 +09:00
}
}
2024-07-10 13:13:53 +09:00
public async $getBlockTxAuditSummary ( hash : string , txid : string ) : Promise < TransactionAudit | null > {
if ([ 'mainnet' , 'testnet' , 'signet' ]. includes ( config . MEMPOOL . NETWORK )) {
return BlocksAuditsRepository . $getBlockTxAudit ( hash , txid );
} else {
return null ;
}
}
2020-09-21 19:41:12 +07:00
public getLastDifficultyAdjustmentTime () : number {
return this . lastDifficultyAdjustmentTime ;
}
2021-07-23 14:35:04 +03:00
public getPreviousDifficultyRetarget () : number {
return this . previousDifficultyRetarget ;
}
2024-02-11 22:50:34 +00:00
public getQuarterEpochBlockTime () : number | null {
return this . quarterEpochBlockTime ;
}
2020-12-21 23:08:34 +07:00
public getCurrentBlockHeight () : number {
return this . currentBlockHeight ;
}
2022-11-27 13:46:23 +09:00
2024-01-30 16:41:35 +00:00
public async $indexCPFP ( hash : string , height : number , txs? : TransactionExtended []) : Promise < CpfpSummary | null > {
2023-07-31 18:02:18 +09:00
let transactions = txs ;
if ( ! transactions ) {
if ( config . MEMPOOL . BACKEND === 'esplora' ) {
transactions = ( await bitcoinApi . $getTxsForBlock ( hash )). map ( tx => transactionUtils . extendTransaction ( tx ));
}
if ( ! transactions ) {
const block = await bitcoinClient . getBlock ( hash , 2 );
transactions = block . tx . map ( tx => {
tx . fee *= 100 _000_000 ;
return tx ;
});
}
}
2023-01-07 15:51:31 -06:00
2024-01-30 16:41:35 +00:00
if ( transactions ? . length != null ) {
2024-04-04 04:28:57 +00:00
const summary = calculateFastBlockCpfp ( height , transactions as TransactionExtended []);
2023-03-12 11:09:11 +09:00
2024-01-30 16:41:35 +00:00
await this . $saveCpfp ( hash , height , summary );
2023-03-12 11:09:11 +09:00
2024-01-30 16:41:35 +00:00
const effectiveFeeStats = Common . calcEffectiveFeeStatistics ( summary . transactions );
await blocksRepository . $saveEffectiveFeeStats ( hash , effectiveFeeStats );
2023-07-31 18:02:18 +09:00
2024-01-30 16:41:35 +00:00
return summary ;
} else {
logger . err ( `Cannot index CPFP for block ${ height } - missing transaction data` );
return null ;
}
2023-03-12 11:09:11 +09:00
}
2023-01-10 17:13:11 -06:00
2023-03-12 11:09:11 +09:00
public async $saveCpfp ( hash : string , height : number , cpfpSummary : CpfpSummary ) : Promise < void > {
2023-06-22 11:52:43 -04:00
try {
const result = await cpfpRepository . $batchSaveClusters ( cpfpSummary . clusters );
if ( ! result ) {
await cpfpRepository . $insertProgressMarker ( height );
}
} catch ( e ) {
// not a fatal error, we'll try again next time the indexer runs
2023-01-10 17:15:55 -06:00
}
2022-11-27 13:46:23 +09:00
}
2019-07-21 17:59:47 +03:00
}
export default new Blocks ();