@node-dlc/chainmon
Version:
Bitcoin on-chain transaction monitoring tool for DLCs
86 lines • 2.76 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.TxWatcher = void 0;
const bitcoin_1 = require("@node-dlc/bitcoin");
const events_1 = require("events");
class TxWatcher extends events_1.EventEmitter {
/**
* TxWatcher listens for transactions that match certain patterns
* and events when a transaction is found matching the pattern
*
* @param client
*/
constructor(client) {
super();
this._client = client;
this.watchedOutPoints = new Map();
this.watchedScriptPubKeys = new Map();
}
/**
* Starts watching for transactions
*/
start() {
this._client.subscribeRawTx();
this._client.on('rawtx', this._onRawTx.bind(this));
}
/**
* Stops watching for transactions
*/
stop() {
// this._client.close();
}
/**
* Watches an outpoint for broadcase in a new transaction
* @param outpoint
*/
watchOutpoint(outpoint) {
const key = outpoint.toString();
this.watchedOutPoints.set(key, outpoint);
}
/**
* Watches a scriptpubkey for broadcast in a new transaction
* @param scriptPubKey
* @param value
*/
watchScriptPubKey(scriptPubKey, value) {
const key = scriptPubKey.toString();
this.watchedScriptPubKeys.set(key, [scriptPubKey, value]);
}
////////////////////////////////////////////////////////////////
_checkOutpoints(tx) {
for (const vin of tx.inputs) {
const key = vin.outpoint.toString();
const watchedOutpoint = this.watchedOutPoints.get(key);
if (watchedOutpoint) {
this.watchedOutPoints.delete(key);
this.emit('outpointspent', tx, watchedOutpoint);
}
}
}
_checkScriptPubkeys(tx) {
for (const vout of tx.outputs) {
const key = vout.scriptPubKey.toString();
const watchedScriptPubKey = this.watchedScriptPubKeys.get(key);
if (watchedScriptPubKey) {
const [, value] = watchedScriptPubKey;
if (!value || (value && vout.value === value)) {
this.watchedScriptPubKeys.delete(key);
this.emit('scriptpubkeyreceived', tx, watchedScriptPubKey);
}
}
}
}
_onRawTx(buf) {
try {
const tx = bitcoin_1.Tx.fromBuffer(buf);
this.emit('tx', tx);
this._checkOutpoints(tx);
this._checkScriptPubkeys(tx);
}
catch (e) {
console.error('Failed to deserialize tx', buf.toString('hex'));
}
}
}
exports.TxWatcher = TxWatcher;
//# sourceMappingURL=TxWatcher.js.map