mempool/backend/src/api/transaction-utils.ts

63 lines
2.0 KiB
TypeScript
Raw Normal View History

2020-12-21 17:08:34 +01:00
import bitcoinApi from './bitcoin/bitcoin-api-factory';
import logger from '../logger';
import { TransactionExtended, TransactionMinerInfo } from '../mempool.interfaces';
import { IEsploraApi } from './bitcoin/esplora-api.interface';
2020-12-21 17:08:34 +01:00
class TransactionUtils {
constructor() { }
public async $addPrevoutsToTransaction(transaction: TransactionExtended): Promise<TransactionExtended> {
if (transaction.vin[0].is_coinbase) {
2020-12-21 17:08:34 +01:00
return transaction;
}
for (const vin of transaction.vin) {
const innerTx = await bitcoinApi.$getRawTransaction(vin.txid);
vin.prevout = innerTx.vout[vin.vout];
2020-12-21 17:08:34 +01:00
}
return transaction;
2020-12-21 17:08:34 +01:00
}
public extendTransaction(transaction: IEsploraApi.Transaction): TransactionExtended {
2020-12-22 00:04:31 +01:00
transaction['vsize'] = Math.round(transaction.weight / 4);
transaction['feePerVsize'] = Math.max(1, (transaction.fee || 0) / (transaction.weight / 4));
if (!transaction.status.confirmed) {
2020-12-22 00:04:31 +01:00
transaction['firstSeen'] = Math.round((new Date().getTime() / 1000));
}
2020-12-21 17:08:34 +01:00
// @ts-ignore
2020-12-22 00:04:31 +01:00
return transaction;
2020-12-21 17:08:34 +01:00
}
public stripCoinbaseTransaction(tx: TransactionExtended): TransactionMinerInfo {
return {
vin: [{
scriptsig: tx.vin[0].scriptsig || tx.vin[0]['coinbase']
}],
vout: tx.vout
.map((vout) => ({
scriptpubkey_address: vout.scriptpubkey_address,
value: vout.value
}))
.filter((vout) => vout.value)
};
}
public async $getTransactionExtended(txId: string, inMempool = false, addPrevouts = false): Promise<TransactionExtended | null> {
2020-12-21 17:08:34 +01:00
try {
let transaction: IEsploraApi.Transaction;
2020-12-21 17:08:34 +01:00
if (inMempool) {
transaction = await bitcoinApi.$getRawTransactionBitcoind(txId, false, addPrevouts);
2020-12-21 17:08:34 +01:00
} else {
transaction = await bitcoinApi.$getRawTransaction(txId, false, addPrevouts);
2020-12-21 17:08:34 +01:00
}
return this.extendTransaction(transaction);
} catch (e) {
logger.debug('getTransactionExtended error: ' + (e.message || e));
console.log(e);
return null;
}
}
}
export default new TransactionUtils();