load mempool txs in bulk from esplora

This commit is contained in:
Mononaut
2023-07-22 14:09:11 +09:00
parent e2fdacfddd
commit 202d4122b4
4 changed files with 86 additions and 35 deletions

View File

@@ -3,6 +3,7 @@ import { IEsploraApi } from './esplora-api.interface';
export interface AbstractBitcoinApi {
$getRawMempool(): Promise<IEsploraApi.Transaction['txid'][]>;
$getRawTransaction(txId: string, skipConversion?: boolean, addPrevout?: boolean, lazyPrevouts?: boolean): Promise<IEsploraApi.Transaction>;
$getMempoolTransactions(expectedCount: number);
$getTransactionHex(txId: string): Promise<string>;
$getBlockHeightTip(): Promise<number>;
$getBlockHashTip(): Promise<string>;

View File

@@ -59,6 +59,10 @@ class BitcoinApi implements AbstractBitcoinApi {
});
}
$getMempoolTransactions(expectedCount: number): Promise<IEsploraApi.Transaction[]> {
return Promise.resolve([]);
}
$getTransactionHex(txId: string): Promise<string> {
return this.$getRawTransaction(txId, true)
.then((tx) => tx.hex || '');

View File

@@ -5,6 +5,8 @@ import { AbstractBitcoinApi } from './bitcoin-api-abstract-factory';
import { IEsploraApi } from './esplora-api.interface';
import logger from '../../logger';
import JsonStream from 'JSONStream';
const axiosConnection = axios.create({
httpAgent: new http.Agent({ keepAlive: true, })
});
@@ -69,6 +71,27 @@ class ElectrsApi implements AbstractBitcoinApi {
return this.$queryWrapper<IEsploraApi.Transaction>(config.ESPLORA.REST_API_URL + '/tx/' + txId);
}
async $getMempoolTransactions(expectedCount: number): Promise<IEsploraApi.Transaction[]> {
const transactions: IEsploraApi.Transaction[] = [];
let count = 0;
return new Promise((resolve, reject) => {
axiosConnection.get(config.ESPLORA.REST_API_URL + '/mempool/txs', { ...this.activeAxiosConfig, timeout: 60000, responseType: 'stream' }).then(response => {
response.data.pipe(JsonStream.parse('*')).on('data', transaction => {
count++;
if (count % 10000 === 0) {
logger.info(`Fetched ${count} of ${expectedCount} mempool transactions from esplora`);
}
transactions.push(transaction);
}).on('end', () => {
logger.info(`Fetched all ${count} of ${expectedCount} mempool transactions from esplora`);
resolve(transactions);
}).on('error', (err) => {
reject(err);
});
});
});
}
$getTransactionHex(txId: string): Promise<string> {
return this.$queryWrapper<string>(config.ESPLORA.REST_API_URL + '/tx/' + txId + '/hex');
}