Skip to content

Commit

Permalink
wallet: Fix node client interface for hooks.
Browse files Browse the repository at this point in the history
bsock hooks that nodeclient tries to imitate, are handlers set on
specific event. They are expected to return results to the caller.
  • Loading branch information
nodech committed Feb 14, 2024
1 parent 42c4f99 commit 2b44a64
Showing 1 changed file with 40 additions and 7 deletions.
47 changes: 40 additions & 7 deletions lib/wallet/nodeclient.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
'use strict';

const assert = require('bsert');
const blacklist = require('bsock/lib/blacklist');
const AsyncEmitter = require('bevent');

/**
Expand All @@ -27,6 +28,7 @@ class NodeClient extends AsyncEmitter {
this.network = node.network;
this.filter = null;
this.opened = false;
this.hooks = new Map();

this.init();
}
Expand Down Expand Up @@ -98,13 +100,46 @@ class NodeClient extends AsyncEmitter {
}

/**
* Add a listener.
* @param {String} type
* Add a hook.
* @param {String} event
* @param {Function} handler
*/

hook(type, handler) {
return this.on(type, handler);
hook(event, handler) {
assert(typeof event === 'string', 'Event must be a string.');
assert(typeof handler === 'function', 'Handler must be a function.');
assert(!this.hooks.has(event), 'Hook already bound.');
assert(!Object.prototype.hasOwnProperty.call(blacklist, event),
'Blacklisted event.');
this.hooks.set(event, handler);
}

/**
* Remove a hook.
* @param {String} event
*/

unhook(event) {
assert(typeof event === 'string', 'Event must be a string.');
assert(!Object.prototype.hasOwnProperty.call(blacklist, event),
'Blacklisted event.');
this.hooks.delete(event);
}

/**
* Call a hook.
* @param {String} event
* @param {...Object} args
* @returns {Promise}
*/

handleCall(event, ...args) {
const hook = this.hooks.get(event);

if (!hook)
throw new Error('No hook available.');

return hook(...args);
}

/**
Expand Down Expand Up @@ -215,8 +250,6 @@ class NodeClient extends AsyncEmitter {
/**
* Rescan for any missed transactions.
* @param {Number|Hash} start - Start block.
* @param {Bloom} filter
* @param {Function} iter - Iterator.
* @returns {Promise}
*/

Expand All @@ -225,7 +258,7 @@ class NodeClient extends AsyncEmitter {
return this.node.chain.reset(start);

return this.node.chain.scan(start, this.filter, (entry, txs) => {
return this.emitAsync('block rescan', entry, txs);
return this.handleCall('block rescan', entry, txs);
});
}

Expand Down

0 comments on commit 2b44a64

Please sign in to comment.