refactor: improve generator perf.

This commit is contained in:
Christopher Jeffrey 2016-09-21 22:58:27 -07:00
parent 2899219033
commit ec0d50d506
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD
24 changed files with 7003 additions and 7575 deletions

View File

@ -183,8 +183,7 @@ Chain.prototype._init = function _init() {
* @param {Function} callback * @param {Function} callback
*/ */
Chain.prototype._open = function open() { Chain.prototype._open = spawn.co(function* open() {
return spawn(function *() {
var tip; var tip;
this.logger.info('Chain is loading.'); this.logger.info('Chain is loading.');
@ -223,8 +222,7 @@ Chain.prototype._open = function open() {
this.synced = true; this.synced = true;
this.emit('full'); this.emit('full');
} }
}, this); });
};
/** /**
* Close the chain, wait for the database to close. * Close the chain, wait for the database to close.
@ -254,8 +252,7 @@ Chain.prototype._lock = function _lock(block, force) {
* @param {Function} callback - Returns [{@link VerifyError}]. * @param {Function} callback - Returns [{@link VerifyError}].
*/ */
Chain.prototype.verifyContext = function verifyContext(block, prev) { Chain.prototype.verifyContext = spawn.co(function* verifyContext(block, prev) {
return spawn(function *() {
var state, view; var state, view;
state = yield this.verify(block, prev); state = yield this.verify(block, prev);
@ -268,8 +265,7 @@ Chain.prototype.verifyContext = function verifyContext(block, prev) {
this.state = state; this.state = state;
return view; return view;
}, this); });
};
/** /**
* Test whether a block is the genesis block. * Test whether a block is the genesis block.
@ -292,8 +288,7 @@ Chain.prototype.isGenesis = function isGenesis(block) {
* [{@link VerifyError}, {@link VerifyFlags}]. * [{@link VerifyError}, {@link VerifyFlags}].
*/ */
Chain.prototype.verify = function verify(block, prev) { Chain.prototype.verify = spawn.co(function* verify(block, prev) {
return spawn(function *() {
var ret = new VerifyResult(); var ret = new VerifyResult();
var i, height, ts, tx, medianTime, commitmentHash, ancestors, state; var i, height, ts, tx, medianTime, commitmentHash, ancestors, state;
@ -412,8 +407,7 @@ Chain.prototype.verify = function verify(block, prev) {
} }
return state; return state;
}, this); });
};
/** /**
* Check all deployments on a chain, ranging from p2sh to segwit. * Check all deployments on a chain, ranging from p2sh to segwit.
@ -424,8 +418,7 @@ Chain.prototype.verify = function verify(block, prev) {
* [{@link VerifyError}, {@link DeploymentState}]. * [{@link VerifyError}, {@link DeploymentState}].
*/ */
Chain.prototype.getDeployments = function getDeployments(block, prev, ancestors) { Chain.prototype.getDeployments = spawn.co(function* getDeployments(block, prev, ancestors) {
return spawn(function *() {
var state = new DeploymentState(); var state = new DeploymentState();
var active; var active;
@ -521,8 +514,7 @@ Chain.prototype.getDeployments = function getDeployments(block, prev, ancestors)
} }
return state; return state;
}, this); });
};
/** /**
* Determine whether to check block for duplicate txids in blockchain * Determine whether to check block for duplicate txids in blockchain
@ -535,8 +527,7 @@ Chain.prototype.getDeployments = function getDeployments(block, prev, ancestors)
* @param {Function} callback - Returns [{@link VerifyError}]. * @param {Function} callback - Returns [{@link VerifyError}].
*/ */
Chain.prototype.checkDuplicates = function checkDuplicates(block, prev) { Chain.prototype.checkDuplicates = spawn.co(function* checkDuplicates(block, prev) {
return spawn(function *() {
var height = prev.height + 1; var height = prev.height + 1;
var entry; var entry;
@ -564,8 +555,7 @@ Chain.prototype.checkDuplicates = function checkDuplicates(block, prev) {
return; return;
yield this.findDuplicates(block, prev); yield this.findDuplicates(block, prev);
}, this); });
};
/** /**
* Check block for duplicate txids in blockchain * Check block for duplicate txids in blockchain
@ -578,8 +568,7 @@ Chain.prototype.checkDuplicates = function checkDuplicates(block, prev) {
* @param {Function} callback - Returns [{@link VerifyError}]. * @param {Function} callback - Returns [{@link VerifyError}].
*/ */
Chain.prototype.findDuplicates = function findDuplicates(block, prev) { Chain.prototype.findDuplicates = spawn.co(function* findDuplicates(block, prev) {
return spawn(function *() {
var height = prev.height + 1; var height = prev.height + 1;
var i, tx, result; var i, tx, result;
@ -599,8 +588,7 @@ Chain.prototype.findDuplicates = function findDuplicates(block, prev) {
throw new VerifyError(block, 'invalid', 'bad-txns-BIP30', 100); throw new VerifyError(block, 'invalid', 'bad-txns-BIP30', 100);
} }
} }
}, this); });
};
/** /**
* Check block transactions for all things pertaining * Check block transactions for all things pertaining
@ -619,8 +607,7 @@ Chain.prototype.findDuplicates = function findDuplicates(block, prev) {
* @param {Function} callback - Returns [{@link VerifyError}]. * @param {Function} callback - Returns [{@link VerifyError}].
*/ */
Chain.prototype.checkInputs = function checkInputs(block, prev, state) { Chain.prototype.checkInputs = spawn.co(function* checkInputs(block, prev, state) {
return spawn(function *() {
var height = prev.height + 1; var height = prev.height + 1;
var historical = prev.isHistorical(); var historical = prev.isHistorical();
var sigops = 0; var sigops = 0;
@ -720,8 +707,7 @@ Chain.prototype.checkInputs = function checkInputs(block, prev, state) {
} }
return view; return view;
}, this); });
};
/** /**
* Get the cached height for a hash if present. * Get the cached height for a hash if present.
@ -745,8 +731,7 @@ Chain.prototype._getCachedHeight = function _getCachedHeight(hash) {
* @param {Function} callback - Returns [{@link Error}, {@link ChainEntry}]. * @param {Function} callback - Returns [{@link Error}, {@link ChainEntry}].
*/ */
Chain.prototype.findFork = function findFork(fork, longer) { Chain.prototype.findFork = spawn.co(function* findFork(fork, longer) {
return spawn(function *() {
while (fork.hash !== longer.hash) { while (fork.hash !== longer.hash) {
while (longer.height > fork.height) { while (longer.height > fork.height) {
longer = yield longer.getPrevious(); longer = yield longer.getPrevious();
@ -764,8 +749,7 @@ Chain.prototype.findFork = function findFork(fork, longer) {
} }
return fork; return fork;
}, this); });
};
/** /**
* Reorganize the blockchain (connect and disconnect inputs). * Reorganize the blockchain (connect and disconnect inputs).
@ -777,8 +761,7 @@ Chain.prototype.findFork = function findFork(fork, longer) {
* @param {Function} callback * @param {Function} callback
*/ */
Chain.prototype.reorganize = function reorganize(entry, block) { Chain.prototype.reorganize = spawn.co(function* reorganize(entry, block) {
return spawn(function *() {
var tip = this.tip; var tip = this.tip;
var fork = yield this.findFork(tip, entry); var fork = yield this.findFork(tip, entry);
var disconnect = []; var disconnect = [];
@ -816,8 +799,7 @@ Chain.prototype.reorganize = function reorganize(entry, block) {
} }
this.emit('reorganize', block, tip.height, tip.hash); this.emit('reorganize', block, tip.height, tip.hash);
}, this); });
};
/** /**
* Disconnect an entry from the chain (updates the tip). * Disconnect an entry from the chain (updates the tip).
@ -825,8 +807,7 @@ Chain.prototype.reorganize = function reorganize(entry, block) {
* @param {Function} callback * @param {Function} callback
*/ */
Chain.prototype.disconnect = function disconnect(entry) { Chain.prototype.disconnect = spawn.co(function* disconnect(entry) {
return spawn(function *() {
var items = yield this.db.disconnect(entry); var items = yield this.db.disconnect(entry);
var block = items[1]; var block = items[1];
var prev = yield entry.getPrevious(); var prev = yield entry.getPrevious();
@ -841,8 +822,7 @@ Chain.prototype.disconnect = function disconnect(entry) {
this.emit('tip', prev); this.emit('tip', prev);
this.emit('disconnect', entry, block); this.emit('disconnect', entry, block);
}, this); });
};
/** /**
* Reconnect an entry to the chain (updates the tip). * Reconnect an entry to the chain (updates the tip).
@ -853,8 +833,7 @@ Chain.prototype.disconnect = function disconnect(entry) {
* @param {Function} callback * @param {Function} callback
*/ */
Chain.prototype.reconnect = function reconnect(entry) { Chain.prototype.reconnect = spawn.co(function* reconnect(entry) {
return spawn(function *() {
var block = yield this.db.getBlock(entry.hash); var block = yield this.db.getBlock(entry.hash);
var prev, view; var prev, view;
@ -887,8 +866,7 @@ Chain.prototype.reconnect = function reconnect(entry) {
this.emit('tip', entry); this.emit('tip', entry);
this.emit('reconnect', entry, block); this.emit('reconnect', entry, block);
this.emit('connect', entry, block); this.emit('connect', entry, block);
}, this); });
};
/** /**
* Set the best chain. This is called on every valid block * Set the best chain. This is called on every valid block
@ -902,8 +880,7 @@ Chain.prototype.reconnect = function reconnect(entry) {
* @param {Function} callback - Returns [{@link VerifyError}]. * @param {Function} callback - Returns [{@link VerifyError}].
*/ */
Chain.prototype.setBestChain = function setBestChain(entry, block, prev) { Chain.prototype.setBestChain = spawn.co(function* setBestChain(entry, block, prev) {
return spawn(function *() {
var view; var view;
assert(this.tip); assert(this.tip);
@ -942,8 +919,7 @@ Chain.prototype.setBestChain = function setBestChain(entry, block, prev) {
this.height = entry.height; this.height = entry.height;
this.emit('tip', entry); this.emit('tip', entry);
}, this); });
};
/** /**
* Reset the chain to the desired height. This * Reset the chain to the desired height. This
@ -953,8 +929,7 @@ Chain.prototype.setBestChain = function setBestChain(entry, block, prev) {
* @param {Function} callback * @param {Function} callback
*/ */
Chain.prototype.reset = function reset(height, force) { Chain.prototype.reset = spawn.co(function* reset(height, force) {
return spawn(function *() {
var unlock = yield this._lock(null, force); var unlock = yield this._lock(null, force);
var result; var result;
@ -972,8 +947,7 @@ Chain.prototype.reset = function reset(height, force) {
unlock(); unlock();
return result; return result;
}, this); });
};
/** /**
* Reset the chain to the desired timestamp (within 2 * Reset the chain to the desired timestamp (within 2
@ -983,8 +957,7 @@ Chain.prototype.reset = function reset(height, force) {
* @param {Function} callback * @param {Function} callback
*/ */
Chain.prototype.resetTime = function resetTime(ts) { Chain.prototype.resetTime = spawn.co(function* resetTime(ts) {
return spawn(function *() {
var unlock = yield this._lock(); var unlock = yield this._lock();
var entry = yield this.byTime(ts); var entry = yield this.byTime(ts);
@ -996,8 +969,7 @@ Chain.prototype.resetTime = function resetTime(ts) {
} finally { } finally {
unlock(); unlock();
} }
}, this); });
};
/** /**
* Wait for the chain to drain (finish processing * Wait for the chain to drain (finish processing
@ -1026,8 +998,7 @@ Chain.prototype.isBusy = function isBusy() {
* @param {Function} callback - Returns [{@link VerifyError}]. * @param {Function} callback - Returns [{@link VerifyError}].
*/ */
Chain.prototype.add = function add(block) { Chain.prototype.add = spawn.co(function* add(block) {
return spawn(function *() {
var ret, unlock, initial, hash, prevBlock; var ret, unlock, initial, hash, prevBlock;
var height, checkpoint, orphan, entry; var height, checkpoint, orphan, entry;
var existing, prev; var existing, prev;
@ -1261,8 +1232,7 @@ Chain.prototype.add = function add(block) {
this.currentBlock = null; this.currentBlock = null;
unlock(); unlock();
}, this); });
};
/** /**
* Test whether the chain has reached its slow height. * Test whether the chain has reached its slow height.
@ -1393,8 +1363,7 @@ Chain.prototype.pruneOrphans = function pruneOrphans() {
* @param {Function} callback - Returns [Error, Boolean]. * @param {Function} callback - Returns [Error, Boolean].
*/ */
Chain.prototype.has = function has(hash) { Chain.prototype.has = spawn.co(function* has(hash) {
return spawn(function *() {
if (this.hasOrphan(hash)) if (this.hasOrphan(hash))
return true; return true;
@ -1405,8 +1374,7 @@ Chain.prototype.has = function has(hash) {
return true; return true;
return yield this.hasBlock(hash); return yield this.hasBlock(hash);
}, this); });
};
/** /**
* Find a block entry by timestamp. * Find a block entry by timestamp.
@ -1414,8 +1382,7 @@ Chain.prototype.has = function has(hash) {
* @param {Function} callback - Returns [Error, {@link ChainEntry}]. * @param {Function} callback - Returns [Error, {@link ChainEntry}].
*/ */
Chain.prototype.byTime = function byTime(ts) { Chain.prototype.byTime = spawn.co(function* byTime(ts) {
return spawn(function *() {
var start = 0; var start = 0;
var end = this.height; var end = this.height;
var pos, delta, entry; var pos, delta, entry;
@ -1445,8 +1412,7 @@ Chain.prototype.byTime = function byTime(ts) {
} }
return entry; return entry;
}, this); });
};
/** /**
* Test the chain to see if it contains a block. * Test the chain to see if it contains a block.
@ -1555,8 +1521,7 @@ Chain.prototype.getProgress = function getProgress() {
* @param {Function} callback - Returns [Error, {@link Hash}[]]. * @param {Function} callback - Returns [Error, {@link Hash}[]].
*/ */
Chain.prototype.getLocator = function getLocator(start) { Chain.prototype.getLocator = spawn.co(function* getLocator(start) {
return spawn(function *() {
var unlock = yield this._lock(); var unlock = yield this._lock();
var hashes = []; var hashes = [];
var step = 1; var step = 1;
@ -1615,8 +1580,7 @@ Chain.prototype.getLocator = function getLocator(start) {
unlock(); unlock();
return hashes; return hashes;
}, this); });
};
/** /**
* Calculate the orphan root of the hash (if it is an orphan). * Calculate the orphan root of the hash (if it is an orphan).
@ -1645,13 +1609,11 @@ Chain.prototype.getOrphanRoot = function getOrphanRoot(hash) {
* (target is in compact/mantissa form). * (target is in compact/mantissa form).
*/ */
Chain.prototype.getCurrentTarget = function getCurrentTarget() { Chain.prototype.getCurrentTarget = spawn.co(function* getCurrentTarget() {
return spawn(function *() {
if (!this.tip) if (!this.tip)
return this.network.pow.bits; return this.network.pow.bits;
return yield this.getTargetAsync(null, this.tip); return yield this.getTargetAsync(null, this.tip);
}, this); });
};
/** /**
* Calculate the target based on the passed-in chain entry. * Calculate the target based on the passed-in chain entry.
@ -1661,8 +1623,7 @@ Chain.prototype.getCurrentTarget = function getCurrentTarget() {
* (target is in compact/mantissa form). * (target is in compact/mantissa form).
*/ */
Chain.prototype.getTargetAsync = function getTargetAsync(block, prev) { Chain.prototype.getTargetAsync = spawn.co(function* getTargetAsync(block, prev) {
return spawn(function *() {
var ancestors; var ancestors;
if ((prev.height + 1) % this.network.pow.retargetInterval !== 0) { if ((prev.height + 1) % this.network.pow.retargetInterval !== 0) {
@ -1673,8 +1634,7 @@ Chain.prototype.getTargetAsync = function getTargetAsync(block, prev) {
ancestors = yield prev.getAncestors(this.network.pow.retargetInterval); ancestors = yield prev.getAncestors(this.network.pow.retargetInterval);
return this.getTarget(block, prev, ancestors); return this.getTarget(block, prev, ancestors);
}, this); });
};
/** /**
* Calculate the target synchronously. _Must_ * Calculate the target synchronously. _Must_
@ -1758,8 +1718,7 @@ Chain.prototype.retarget = function retarget(prev, first) {
* hash of the latest known block). * hash of the latest known block).
*/ */
Chain.prototype.findLocator = function findLocator(locator) { Chain.prototype.findLocator = spawn.co(function* findLocator(locator) {
return spawn(function *() {
var i, hash, main; var i, hash, main;
for (i = 0; i < locator.length; i++) { for (i = 0; i < locator.length; i++) {
@ -1771,8 +1730,7 @@ Chain.prototype.findLocator = function findLocator(locator) {
} }
return this.network.genesis.hash; return this.network.genesis.hash;
}, this); });
};
/** /**
* Check whether a versionbits deployment is active (BIP9: versionbits). * Check whether a versionbits deployment is active (BIP9: versionbits).
@ -1784,8 +1742,7 @@ Chain.prototype.findLocator = function findLocator(locator) {
* @param {Function} callback - Returns [Error, Number]. * @param {Function} callback - Returns [Error, Number].
*/ */
Chain.prototype.isActive = function isActive(prev, id) { Chain.prototype.isActive = spawn.co(function* isActive(prev, id) {
return spawn(function *() {
var state; var state;
if (prev.isHistorical()) if (prev.isHistorical())
@ -1794,8 +1751,7 @@ Chain.prototype.isActive = function isActive(prev, id) {
state = yield this.getState(prev, id); state = yield this.getState(prev, id);
return state === constants.thresholdStates.ACTIVE; return state === constants.thresholdStates.ACTIVE;
}, this); });
};
/** /**
* Get chain entry state for a deployment (BIP9: versionbits). * Get chain entry state for a deployment (BIP9: versionbits).
@ -1807,8 +1763,7 @@ Chain.prototype.isActive = function isActive(prev, id) {
* @param {Function} callback - Returns [Error, Number]. * @param {Function} callback - Returns [Error, Number].
*/ */
Chain.prototype.getState = function getState(prev, id) { Chain.prototype.getState = spawn.co(function* getState(prev, id) {
return spawn(function *() {
var period = this.network.minerWindow; var period = this.network.minerWindow;
var threshold = this.network.activationThreshold; var threshold = this.network.activationThreshold;
var deployment = this.network.deployments[id]; var deployment = this.network.deployments[id];
@ -1924,8 +1879,7 @@ Chain.prototype.getState = function getState(prev, id) {
} }
return state; return state;
}, this); });
};
/** /**
* Compute the version for a new block (BIP9: versionbits). * Compute the version for a new block (BIP9: versionbits).
@ -1934,8 +1888,7 @@ Chain.prototype.getState = function getState(prev, id) {
* @param {Function} callback - Returns [Error, Number]. * @param {Function} callback - Returns [Error, Number].
*/ */
Chain.prototype.computeBlockVersion = function computeBlockVersion(prev) { Chain.prototype.computeBlockVersion = spawn.co(function* computeBlockVersion(prev) {
return spawn(function *() {
var keys = Object.keys(this.network.deployments); var keys = Object.keys(this.network.deployments);
var version = 0; var version = 0;
var i, id, deployment, state; var i, id, deployment, state;
@ -1955,8 +1908,7 @@ Chain.prototype.computeBlockVersion = function computeBlockVersion(prev) {
version >>>= 0; version >>>= 0;
return version; return version;
}, this); });
};
/** /**
* Get the current deployment state of the chain. Called on load. * Get the current deployment state of the chain. Called on load.
@ -1964,8 +1916,7 @@ Chain.prototype.computeBlockVersion = function computeBlockVersion(prev) {
* @param {Function} callback - Returns [Error, {@link DeploymentState}]. * @param {Function} callback - Returns [Error, {@link DeploymentState}].
*/ */
Chain.prototype.getDeploymentState = function getDeploymentState() { Chain.prototype.getDeploymentState = spawn.co(function* getDeploymentState() {
return spawn(function *() {
var prev, ancestors; var prev, ancestors;
if (!this.tip) if (!this.tip)
@ -1979,8 +1930,7 @@ Chain.prototype.getDeploymentState = function getDeploymentState() {
ancestors = yield prev.getRetargetAncestors(); ancestors = yield prev.getRetargetAncestors();
return yield this.getDeployments(this.tip, prev, ancestors); return yield this.getDeployments(this.tip, prev, ancestors);
}, this); });
};
/** /**
* Check transaction finality, taking into account MEDIAN_TIME_PAST * Check transaction finality, taking into account MEDIAN_TIME_PAST
@ -1991,8 +1941,7 @@ Chain.prototype.getDeploymentState = function getDeploymentState() {
* @param {Function} callback - Returns [Error, Boolean]. * @param {Function} callback - Returns [Error, Boolean].
*/ */
Chain.prototype.checkFinal = function checkFinal(prev, tx, flags) { Chain.prototype.checkFinal = spawn.co(function* checkFinal(prev, tx, flags) {
return spawn(function *() {
var height = prev.height + 1; var height = prev.height + 1;
var ts; var ts;
@ -2006,8 +1955,7 @@ Chain.prototype.checkFinal = function checkFinal(prev, tx, flags) {
} }
return tx.isFinal(height, bcoin.now()); return tx.isFinal(height, bcoin.now());
}, this); });
};
/** /**
* Get the necessary minimum time and height sequence locks for a transaction. * Get the necessary minimum time and height sequence locks for a transaction.
@ -2018,8 +1966,7 @@ Chain.prototype.checkFinal = function checkFinal(prev, tx, flags) {
* [Error, Number(minTime), Number(minHeight)]. * [Error, Number(minTime), Number(minHeight)].
*/ */
Chain.prototype.getLocks = function getLocks(prev, tx, flags) { Chain.prototype.getLocks = spawn.co(function* getLocks(prev, tx, flags) {
return spawn(function *() {
var mask = constants.sequence.MASK; var mask = constants.sequence.MASK;
var granularity = constants.sequence.GRANULARITY; var granularity = constants.sequence.GRANULARITY;
var disableFlag = constants.sequence.DISABLE_FLAG; var disableFlag = constants.sequence.DISABLE_FLAG;
@ -2058,8 +2005,7 @@ Chain.prototype.getLocks = function getLocks(prev, tx, flags) {
} }
return [minHeight, minTime]; return [minHeight, minTime];
}, this); });
};
/** /**
* Evaluate sequence locks. * Evaluate sequence locks.
@ -2069,8 +2015,7 @@ Chain.prototype.getLocks = function getLocks(prev, tx, flags) {
* @param {Function} callback - Returns [Error, Boolean]. * @param {Function} callback - Returns [Error, Boolean].
*/ */
Chain.prototype.evalLocks = function evalLocks(prev, minHeight, minTime) { Chain.prototype.evalLocks = spawn.co(function* evalLocks(prev, minHeight, minTime) {
return spawn(function *() {
var medianTime; var medianTime;
if (minHeight >= prev.height + 1) if (minHeight >= prev.height + 1)
@ -2085,8 +2030,7 @@ Chain.prototype.evalLocks = function evalLocks(prev, minHeight, minTime) {
return false; return false;
return true; return true;
}, this); });
};
/** /**
* Verify sequence locks. * Verify sequence locks.
@ -2096,14 +2040,12 @@ Chain.prototype.evalLocks = function evalLocks(prev, minHeight, minTime) {
* @param {Function} callback - Returns [Error, Boolean]. * @param {Function} callback - Returns [Error, Boolean].
*/ */
Chain.prototype.checkLocks = function checkLocks(prev, tx, flags) { Chain.prototype.checkLocks = spawn.co(function* checkLocks(prev, tx, flags) {
return spawn(function *() {
var times = yield this.getLocks(prev, tx, flags); var times = yield this.getLocks(prev, tx, flags);
var minHeight = times[0]; var minHeight = times[0];
var minTime = times[1]; var minTime = times[1];
return yield this.evalLocks(prev, minHeight, minTime); return yield this.evalLocks(prev, minHeight, minTime);
}, this); });
};
/** /**
* Represents the deployment state of the chain. * Represents the deployment state of the chain.

View File

@ -214,8 +214,7 @@ ChainDB.layout = layout;
* @param {Function} callback * @param {Function} callback
*/ */
ChainDB.prototype._open = function open() { ChainDB.prototype._open = spawn.co(function* open() {
return spawn(function *() {
var result, genesis, block; var result, genesis, block;
this.logger.info('Starting chain load.'); this.logger.info('Starting chain load.');
@ -245,8 +244,7 @@ ChainDB.prototype._open = function open() {
utils.btc(this.state.value)); utils.btc(this.state.value));
yield this.db.checkVersion('V', 1); yield this.db.checkVersion('V', 1);
}, this); });
};
/** /**
* Close the chain db, wait for the database to close. * Close the chain db, wait for the database to close.
@ -320,8 +318,7 @@ ChainDB.prototype.drop = function drop() {
* @param {Function} callback * @param {Function} callback
*/ */
ChainDB.prototype.commit = function commit() { ChainDB.prototype.commit = spawn.co(function* commit() {
return spawn(function *() {
assert(this.current); assert(this.current);
assert(this.pending); assert(this.pending);
@ -344,8 +341,7 @@ ChainDB.prototype.commit = function commit() {
this.state = this.pending; this.state = this.pending;
this.pending = null; this.pending = null;
}, this); });
};
/** /**
* Add an entry to the LRU cache. * Add an entry to the LRU cache.
@ -393,8 +389,7 @@ ChainDB.prototype.getCache = function getCache(hash) {
* @param {Function} callback - Returns [Error, Number]. * @param {Function} callback - Returns [Error, Number].
*/ */
ChainDB.prototype.getHeight = function getHeight(hash) { ChainDB.prototype.getHeight = spawn.co(function* getHeight(hash) {
return spawn(function *() {
var entry, height; var entry, height;
checkHash(hash); checkHash(hash);
@ -419,8 +414,7 @@ ChainDB.prototype.getHeight = function getHeight(hash) {
return -1; return -1;
return height; return height;
}, this); });
};
/** /**
* Get the hash of a block by height. Note that this * Get the hash of a block by height. Note that this
@ -429,8 +423,7 @@ ChainDB.prototype.getHeight = function getHeight(hash) {
* @param {Function} callback - Returns [Error, {@link Hash}]. * @param {Function} callback - Returns [Error, {@link Hash}].
*/ */
ChainDB.prototype.getHash = function getHash(height) { ChainDB.prototype.getHash = spawn.co(function* getHash(height) {
return spawn(function *() {
var entry; var entry;
checkHash(height); checkHash(height);
@ -447,23 +440,20 @@ ChainDB.prototype.getHash = function getHash(height) {
assert(data.length === 32, 'Database corruption.'); assert(data.length === 32, 'Database corruption.');
return data.toString('hex'); return data.toString('hex');
}); });
}, this); });
};
/** /**
* Get the current chain height from the tip record. * Get the current chain height from the tip record.
* @param {Function} callback - Returns [Error, Number]. * @param {Function} callback - Returns [Error, Number].
*/ */
ChainDB.prototype.getChainHeight = function getChainHeight() { ChainDB.prototype.getChainHeight = spawn.co(function* getChainHeight() {
return spawn(function *() {
var entry = yield this.getTip(); var entry = yield this.getTip();
if (!entry) if (!entry)
return -1; return -1;
return entry.height; return entry.height;
}, this); });
};
/** /**
* Get both hash and height depending on the value passed in. * Get both hash and height depending on the value passed in.
@ -471,8 +461,7 @@ ChainDB.prototype.getChainHeight = function getChainHeight() {
* @param {Function} callback - Returns [Error, {@link Hash}, Number]. * @param {Function} callback - Returns [Error, {@link Hash}, Number].
*/ */
ChainDB.prototype.getBoth = function getBoth(block) { ChainDB.prototype.getBoth = spawn.co(function* getBoth(block) {
return spawn(function *() {
var hash, height; var hash, height;
checkHash(block); checkHash(block);
@ -497,8 +486,7 @@ ChainDB.prototype.getBoth = function getBoth(block) {
hash = null; hash = null;
return [hash, height]; return [hash, height];
}, this); });
};
/** /**
* Retrieve a chain entry but do _not_ add it to the LRU cache. * Retrieve a chain entry but do _not_ add it to the LRU cache.
@ -506,8 +494,7 @@ ChainDB.prototype.getBoth = function getBoth(block) {
* @param {Function} callback - Returns [Error, {@link ChainEntry}]. * @param {Function} callback - Returns [Error, {@link ChainEntry}].
*/ */
ChainDB.prototype.getEntry = function getEntry(hash) { ChainDB.prototype.getEntry = spawn.co(function* getEntry(hash) {
return spawn(function *() {
var self = this; var self = this;
var entry; var entry;
@ -526,8 +513,7 @@ ChainDB.prototype.getEntry = function getEntry(hash) {
return yield this.db.fetch(layout.e(hash), function(data) { return yield this.db.fetch(layout.e(hash), function(data) {
return bcoin.chainentry.fromRaw(self.chain, data); return bcoin.chainentry.fromRaw(self.chain, data);
}); });
}, this); });
};
/** /**
* Retrieve a chain entry and add it to the LRU cache. * Retrieve a chain entry and add it to the LRU cache.
@ -535,8 +521,7 @@ ChainDB.prototype.getEntry = function getEntry(hash) {
* @param {Function} callback - Returns [Error, {@link ChainEntry}]. * @param {Function} callback - Returns [Error, {@link ChainEntry}].
*/ */
ChainDB.prototype.get = function get(hash) { ChainDB.prototype.get = spawn.co(function* get(hash) {
return spawn(function *() {
var entry = yield this.getEntry(hash); var entry = yield this.getEntry(hash);
if (!entry) if (!entry)
@ -548,8 +533,7 @@ ChainDB.prototype.get = function get(hash) {
this.cacheHash.set(entry.hash, entry); this.cacheHash.set(entry.hash, entry);
return entry; return entry;
}, this); });
};
/** /**
* Save an entry to the database and optionally * Save an entry to the database and optionally
@ -564,8 +548,7 @@ ChainDB.prototype.get = function get(hash) {
* @param {Function} callback * @param {Function} callback
*/ */
ChainDB.prototype.save = function save(entry, block, view, connect) { ChainDB.prototype.save = spawn.co(function* save(entry, block, view, connect) {
return spawn(function *() {
var hash = block.hash(); var hash = block.hash();
var height = new Buffer(4); var height = new Buffer(4);
@ -602,16 +585,14 @@ ChainDB.prototype.save = function save(entry, block, view, connect) {
this.put(layout.R, this.pending.commit(hash)); this.put(layout.R, this.pending.commit(hash));
yield this.commit(); yield this.commit();
}, this); });
};
/** /**
* Retrieve the chain state. * Retrieve the chain state.
* @param {Function} callback - Returns [Error, {@link ChainState}]. * @param {Function} callback - Returns [Error, {@link ChainState}].
*/ */
ChainDB.prototype.initState = function initState() { ChainDB.prototype.initState = spawn.co(function* initState() {
return spawn(function *() {
var state = yield this.db.fetch(layout.R, function(data) { var state = yield this.db.fetch(layout.R, function(data) {
return ChainState.fromRaw(data); return ChainState.fromRaw(data);
}); });
@ -621,8 +602,7 @@ ChainDB.prototype.initState = function initState() {
this.state = state; this.state = state;
return state; return state;
}, this); });
};
/** /**
* Retrieve the tip entry from the tip record. * Retrieve the tip entry from the tip record.
@ -642,8 +622,7 @@ ChainDB.prototype.getTip = function getTip() {
* Returns [Error, {@link ChainEntry}, {@link Block}]. * Returns [Error, {@link ChainEntry}, {@link Block}].
*/ */
ChainDB.prototype.reconnect = function reconnect(entry, block, view) { ChainDB.prototype.reconnect = spawn.co(function* reconnect(entry, block, view) {
return spawn(function *() {
var hash = block.hash(); var hash = block.hash();
this.start(); this.start();
@ -666,8 +645,7 @@ ChainDB.prototype.reconnect = function reconnect(entry, block, view) {
yield this.commit(); yield this.commit();
return [entry, block]; return [entry, block];
}, this); });
};
/** /**
* Disconnect block from the chain. * Disconnect block from the chain.
@ -676,8 +654,7 @@ ChainDB.prototype.reconnect = function reconnect(entry, block, view) {
* Returns [Error, {@link ChainEntry}, {@link Block}]. * Returns [Error, {@link ChainEntry}, {@link Block}].
*/ */
ChainDB.prototype.disconnect = function disconnect(entry) { ChainDB.prototype.disconnect = spawn.co(function* disconnect(entry) {
return spawn(function *() {
var block; var block;
this.start(); this.start();
@ -716,8 +693,7 @@ ChainDB.prototype.disconnect = function disconnect(entry) {
yield this.commit(); yield this.commit();
return [entry, block]; return [entry, block];
}, this); });
};
/** /**
* Get the _next_ block hash (does not work by height). * Get the _next_ block hash (does not work by height).
@ -738,8 +714,7 @@ ChainDB.prototype.getNextHash = function getNextHash(hash) {
* @param {Function} callback - Returns [Error, Boolean]. * @param {Function} callback - Returns [Error, Boolean].
*/ */
ChainDB.prototype.isMainChain = function isMainChain(hash) { ChainDB.prototype.isMainChain = spawn.co(function* isMainChain(hash) {
return spawn(function *() {
var query, height, existing; var query, height, existing;
if (hash instanceof bcoin.chainentry) { if (hash instanceof bcoin.chainentry) {
@ -761,8 +736,7 @@ ChainDB.prototype.isMainChain = function isMainChain(hash) {
return false; return false;
return hash === existing; return hash === existing;
}, this); });
};
/** /**
* Reset the chain to a height or hash. Useful for replaying * Reset the chain to a height or hash. Useful for replaying
@ -771,8 +745,7 @@ ChainDB.prototype.isMainChain = function isMainChain(hash) {
* @param {Function} callback * @param {Function} callback
*/ */
ChainDB.prototype.reset = function reset(block) { ChainDB.prototype.reset = spawn.co(function* reset(block) {
return spawn(function *() {
var entry = yield this.get(block); var entry = yield this.get(block);
var tip; var tip;
@ -807,8 +780,7 @@ ChainDB.prototype.reset = function reset(block) {
tip = yield this.get(tip.prevBlock); tip = yield this.get(tip.prevBlock);
} }
}, this); });
};
/** /**
* Test whether the chain contains a block in the * Test whether the chain contains a block in the
@ -818,8 +790,7 @@ ChainDB.prototype.reset = function reset(block) {
* @param {Function} callback - Returns [Error, Boolean]. * @param {Function} callback - Returns [Error, Boolean].
*/ */
ChainDB.prototype.has = function has(height) { ChainDB.prototype.has = spawn.co(function* has(height) {
return spawn(function *() {
var items, hash; var items, hash;
checkHash(height); checkHash(height);
@ -828,8 +799,7 @@ ChainDB.prototype.has = function has(height) {
hash = items[0]; hash = items[0];
return hash != null; return hash != null;
}, this); });
};
/** /**
* Save a block (not an entry) to the * Save a block (not an entry) to the
@ -839,8 +809,7 @@ ChainDB.prototype.has = function has(height) {
* @param {Function} callback - Returns [Error, {@link Block}]. * @param {Function} callback - Returns [Error, {@link Block}].
*/ */
ChainDB.prototype.saveBlock = function saveBlock(block, view, connect) { ChainDB.prototype.saveBlock = spawn.co(function* saveBlock(block, view, connect) {
return spawn(function *() {
if (this.options.spv) if (this.options.spv)
return block; return block;
@ -852,8 +821,7 @@ ChainDB.prototype.saveBlock = function saveBlock(block, view, connect) {
yield this.connectBlock(block, view); yield this.connectBlock(block, view);
return block; return block;
}, this); });
};
/** /**
* Remove a block (not an entry) to the database. * Remove a block (not an entry) to the database.
@ -862,8 +830,7 @@ ChainDB.prototype.saveBlock = function saveBlock(block, view, connect) {
* @param {Function} callback - Returns [Error, {@link Block}]. * @param {Function} callback - Returns [Error, {@link Block}].
*/ */
ChainDB.prototype.removeBlock = function removeBlock(hash) { ChainDB.prototype.removeBlock = spawn.co(function* removeBlock(hash) {
return spawn(function *() {
var block = yield this.getBlock(hash); var block = yield this.getBlock(hash);
if (!block) if (!block)
@ -872,8 +839,7 @@ ChainDB.prototype.removeBlock = function removeBlock(hash) {
this.del(layout.b(block.hash())); this.del(layout.b(block.hash()));
return yield this.disconnectBlock(block); return yield this.disconnectBlock(block);
}, this); });
};
/** /**
* Connect block inputs. * Connect block inputs.
@ -881,8 +847,7 @@ ChainDB.prototype.removeBlock = function removeBlock(hash) {
* @param {Function} callback - Returns [Error, {@link Block}]. * @param {Function} callback - Returns [Error, {@link Block}].
*/ */
ChainDB.prototype.connectBlock = function connectBlock(block, view) { ChainDB.prototype.connectBlock = spawn.co(function* connectBlock(block, view) {
return spawn(function *() {
var undo = new BufferWriter(); var undo = new BufferWriter();
var i, j, tx, input, output, prev; var i, j, tx, input, output, prev;
var hashes, address, hash, coins, raw; var hashes, address, hash, coins, raw;
@ -973,8 +938,7 @@ ChainDB.prototype.connectBlock = function connectBlock(block, view) {
yield this.pruneBlock(block); yield this.pruneBlock(block);
return block; return block;
}, this); });
};
/** /**
* Disconnect block inputs. * Disconnect block inputs.
@ -982,8 +946,7 @@ ChainDB.prototype.connectBlock = function connectBlock(block, view) {
* @param {Function} callback - Returns [Error, {@link Block}]. * @param {Function} callback - Returns [Error, {@link Block}].
*/ */
ChainDB.prototype.disconnectBlock = function disconnectBlock(block) { ChainDB.prototype.disconnectBlock = spawn.co(function* disconnectBlock(block) {
return spawn(function *() {
var i, j, tx, input, output, prev, view; var i, j, tx, input, output, prev, view;
var hashes, address, hash, coins, raw; var hashes, address, hash, coins, raw;
@ -1069,8 +1032,7 @@ ChainDB.prototype.disconnectBlock = function disconnectBlock(block) {
this.del(layout.u(block.hash())); this.del(layout.u(block.hash()));
return block; return block;
}, this); });
};
/** /**
* Fill a transaction with coins (only unspents). * Fill a transaction with coins (only unspents).
@ -1078,8 +1040,7 @@ ChainDB.prototype.disconnectBlock = function disconnectBlock(block) {
* @param {Function} callback - Returns [Error, {@link TX}]. * @param {Function} callback - Returns [Error, {@link TX}].
*/ */
ChainDB.prototype.fillCoins = function fillCoins(tx) { ChainDB.prototype.fillCoins = spawn.co(function* fillCoins(tx) {
return spawn(function *() {
var i, input, coin; var i, input, coin;
if (tx.isCoinbase()) if (tx.isCoinbase())
@ -1098,8 +1059,7 @@ ChainDB.prototype.fillCoins = function fillCoins(tx) {
} }
return tx; return tx;
}, this); });
};
/** /**
* Fill a transaction with coins (all historical coins). * Fill a transaction with coins (all historical coins).
@ -1107,8 +1067,7 @@ ChainDB.prototype.fillCoins = function fillCoins(tx) {
* @param {Function} callback - Returns [Error, {@link TX}]. * @param {Function} callback - Returns [Error, {@link TX}].
*/ */
ChainDB.prototype.fillHistory = function fillHistory(tx) { ChainDB.prototype.fillHistory = spawn.co(function* fillHistory(tx) {
return spawn(function *() {
var i, input, tx; var i, input, tx;
if (!this.options.indexTX) if (!this.options.indexTX)
@ -1130,8 +1089,7 @@ ChainDB.prototype.fillHistory = function fillHistory(tx) {
} }
return tx; return tx;
}, this); });
};
/** /**
* Get a coin (unspents only). * Get a coin (unspents only).
@ -1140,8 +1098,7 @@ ChainDB.prototype.fillHistory = function fillHistory(tx) {
* @param {Function} callback - Returns [Error, {@link Coin}]. * @param {Function} callback - Returns [Error, {@link Coin}].
*/ */
ChainDB.prototype.getCoin = function getCoin(hash, index) { ChainDB.prototype.getCoin = spawn.co(function* getCoin(hash, index) {
return spawn(function *() {
var self = this; var self = this;
var coins = this.coinCache.get(hash); var coins = this.coinCache.get(hash);
@ -1152,8 +1109,7 @@ ChainDB.prototype.getCoin = function getCoin(hash, index) {
self.coinCache.set(hash, data); self.coinCache.set(hash, data);
return bcoin.coins.parseCoin(data, hash, index); return bcoin.coins.parseCoin(data, hash, index);
}); });
}, this); });
};
/** /**
* Get coins (unspents only). * Get coins (unspents only).
@ -1161,8 +1117,7 @@ ChainDB.prototype.getCoin = function getCoin(hash, index) {
* @param {Function} callback - Returns [Error, {@link Coins}]. * @param {Function} callback - Returns [Error, {@link Coins}].
*/ */
ChainDB.prototype.getCoins = function getCoins(hash) { ChainDB.prototype.getCoins = spawn.co(function* getCoins(hash) {
return spawn(function *() {
var self = this; var self = this;
var coins = this.coinCache.get(hash); var coins = this.coinCache.get(hash);
@ -1173,8 +1128,7 @@ ChainDB.prototype.getCoins = function getCoins(hash) {
self.coinCache.set(hash, data); self.coinCache.set(hash, data);
return bcoin.coins.fromRaw(data, hash); return bcoin.coins.fromRaw(data, hash);
}); });
}, this); });
};
/** /**
* Scan the blockchain for transactions containing specified address hashes. * Scan the blockchain for transactions containing specified address hashes.
@ -1184,8 +1138,7 @@ ChainDB.prototype.getCoins = function getCoins(hash) {
* @param {Function} callback * @param {Function} callback
*/ */
ChainDB.prototype.scan = function scan(start, filter, iter) { ChainDB.prototype.scan = spawn.co(function* scan(start, filter, iter) {
return spawn(function *() {
var total = 0; var total = 0;
var i, j, entry, hashes, hash, tx, txs, block; var i, j, entry, hashes, hash, tx, txs, block;
@ -1236,8 +1189,7 @@ ChainDB.prototype.scan = function scan(start, filter, iter) {
} }
this.logger.info('Finished scanning %d blocks.', total); this.logger.info('Finished scanning %d blocks.', total);
}, this); });
};
/** /**
* Retrieve a transaction (not filled with coins). * Retrieve a transaction (not filled with coins).
@ -1272,8 +1224,7 @@ ChainDB.prototype.hasTX = function hasTX(hash) {
* @param {Function} callback - Returns [Error, {@link Coin}[]]. * @param {Function} callback - Returns [Error, {@link Coin}[]].
*/ */
ChainDB.prototype.getCoinsByAddress = function getCoinsByAddress(addresses) { ChainDB.prototype.getCoinsByAddress = spawn.co(function* getCoinsByAddress(addresses) {
return spawn(function *() {
var coins = []; var coins = [];
var i, j, address, hash, keys, key, coin; var i, j, address, hash, keys, key, coin;
@ -1306,8 +1257,7 @@ ChainDB.prototype.getCoinsByAddress = function getCoinsByAddress(addresses) {
} }
return coins; return coins;
}, this); });
};
/** /**
* Get all entries. * Get all entries.
@ -1333,8 +1283,7 @@ ChainDB.prototype.getEntries = function getEntries() {
* @param {Function} callback - Returns [Error, {@link Hash}[]]. * @param {Function} callback - Returns [Error, {@link Hash}[]].
*/ */
ChainDB.prototype.getHashesByAddress = function getHashesByAddress(addresses) { ChainDB.prototype.getHashesByAddress = spawn.co(function* getHashesByAddress(addresses) {
return spawn(function *() {
var hashes = {}; var hashes = {};
var i, address, hash; var i, address, hash;
@ -1359,8 +1308,7 @@ ChainDB.prototype.getHashesByAddress = function getHashesByAddress(addresses) {
} }
return Object.keys(hashes); return Object.keys(hashes);
}, this); });
};
/** /**
* Get all transactions pertinent to an address. * Get all transactions pertinent to an address.
@ -1368,8 +1316,7 @@ ChainDB.prototype.getHashesByAddress = function getHashesByAddress(addresses) {
* @param {Function} callback - Returns [Error, {@link TX}[]]. * @param {Function} callback - Returns [Error, {@link TX}[]].
*/ */
ChainDB.prototype.getTXByAddress = function getTXByAddress(addresses) { ChainDB.prototype.getTXByAddress = spawn.co(function* getTXByAddress(addresses) {
return spawn(function *() {
var txs = []; var txs = [];
var i, hashes, hash, tx; var i, hashes, hash, tx;
@ -1389,8 +1336,7 @@ ChainDB.prototype.getTXByAddress = function getTXByAddress(addresses) {
} }
return txs; return txs;
}, this); });
};
/** /**
* Get a transaction and fill it with coins (historical). * Get a transaction and fill it with coins (historical).
@ -1398,8 +1344,7 @@ ChainDB.prototype.getTXByAddress = function getTXByAddress(addresses) {
* @param {Function} callback - Returns [Error, {@link TX}]. * @param {Function} callback - Returns [Error, {@link TX}].
*/ */
ChainDB.prototype.getFullTX = function getFullTX(hash) { ChainDB.prototype.getFullTX = spawn.co(function* getFullTX(hash) {
return spawn(function *() {
var tx; var tx;
if (!this.options.indexTX) if (!this.options.indexTX)
@ -1413,8 +1358,7 @@ ChainDB.prototype.getFullTX = function getFullTX(hash) {
yield this.fillHistory(tx); yield this.fillHistory(tx);
return tx; return tx;
}, this); });
};
/** /**
* Get a block and fill it with coins (historical). * Get a block and fill it with coins (historical).
@ -1422,8 +1366,7 @@ ChainDB.prototype.getFullTX = function getFullTX(hash) {
* @param {Function} callback - Returns [Error, {@link Block}]. * @param {Function} callback - Returns [Error, {@link Block}].
*/ */
ChainDB.prototype.getFullBlock = function getFullBlock(hash) { ChainDB.prototype.getFullBlock = spawn.co(function* getFullBlock(hash) {
return spawn(function *() {
var block = yield this.getBlock(hash); var block = yield this.getBlock(hash);
var view; var view;
@ -1433,8 +1376,7 @@ ChainDB.prototype.getFullBlock = function getFullBlock(hash) {
view = yield this.getUndoView(block); view = yield this.getUndoView(block);
return block; return block;
}, this); });
};
/** /**
* Get a view of the existing coins necessary to verify a block. * Get a view of the existing coins necessary to verify a block.
@ -1442,8 +1384,7 @@ ChainDB.prototype.getFullBlock = function getFullBlock(hash) {
* @param {Function} callback - Returns [Error, {@link CoinView}]. * @param {Function} callback - Returns [Error, {@link CoinView}].
*/ */
ChainDB.prototype.getCoinView = function getCoinView(block, callback) { ChainDB.prototype.getCoinView = spawn.co(function* getCoinView(block, callback) {
return spawn(function *() {
var view = new bcoin.coinview(); var view = new bcoin.coinview();
var prevout = block.getPrevout(); var prevout = block.getPrevout();
var i, prev, coins; var i, prev, coins;
@ -1456,8 +1397,7 @@ ChainDB.prototype.getCoinView = function getCoinView(block, callback) {
} }
return view; return view;
}, this); });
};
/** /**
* Get coins necessary to be resurrected during a reorg. * Get coins necessary to be resurrected during a reorg.
@ -1485,8 +1425,7 @@ ChainDB.prototype.getUndoCoins = function getUndoCoins(hash) {
* @param {Function} callback - Returns [Error, {@link CoinView}]. * @param {Function} callback - Returns [Error, {@link CoinView}].
*/ */
ChainDB.prototype.getUndoView = function getUndoView(block) { ChainDB.prototype.getUndoView = spawn.co(function* getUndoView(block) {
return spawn(function *() {
var i, j, k, tx, input, coin, view, coins; var i, j, k, tx, input, coin, view, coins;
view = yield this.getCoinView(block); view = yield this.getCoinView(block);
@ -1512,8 +1451,7 @@ ChainDB.prototype.getUndoView = function getUndoView(block) {
} }
return view; return view;
}, this); });
};
/** /**
* Retrieve a block from the database (not filled with coins). * Retrieve a block from the database (not filled with coins).
@ -1521,8 +1459,7 @@ ChainDB.prototype.getUndoView = function getUndoView(block) {
* @param {Function} callback - Returns [Error, {@link Block}]. * @param {Function} callback - Returns [Error, {@link Block}].
*/ */
ChainDB.prototype.getBlock = function getBlock(hash) { ChainDB.prototype.getBlock = spawn.co(function* getBlock(hash) {
return spawn(function *() {
var items = yield this.getBoth(hash); var items = yield this.getBoth(hash);
var height; var height;
@ -1537,8 +1474,7 @@ ChainDB.prototype.getBlock = function getBlock(hash) {
block.setHeight(height); block.setHeight(height);
return block; return block;
}); });
}, this); });
};
/** /**
* Check whether coins are still unspent. Necessary for bip30. * Check whether coins are still unspent. Necessary for bip30.
@ -1559,8 +1495,7 @@ ChainDB.prototype.hasCoins = function hasCoins(hash) {
* @param {Function} callback * @param {Function} callback
*/ */
ChainDB.prototype.pruneBlock = function pruneBlock(block) { ChainDB.prototype.pruneBlock = spawn.co(function* pruneBlock(block) {
return spawn(function *() {
var futureHeight, key, hash; var futureHeight, key, hash;
if (this.options.spv) if (this.options.spv)
@ -1589,8 +1524,7 @@ ChainDB.prototype.pruneBlock = function pruneBlock(block) {
this.del(key); this.del(key);
this.del(layout.b(hash)); this.del(layout.b(hash));
this.del(layout.u(hash)); this.del(layout.u(hash));
}, this); });
};
/** /**
* Chain State * Chain State

View File

@ -177,8 +177,7 @@ ChainEntry.prototype.getRetargetAncestors = function getRetargetAncestors() {
* @param {Function} callback - Returns [Error, ChainEntry[]]. * @param {Function} callback - Returns [Error, ChainEntry[]].
*/ */
ChainEntry.prototype.getAncestors = function getAncestors(max) { ChainEntry.prototype.getAncestors = spawn.co(function* getAncestors(max) {
return spawn(function *() {
var entry = this; var entry = this;
var ancestors = []; var ancestors = [];
var cached; var cached;
@ -214,8 +213,7 @@ ChainEntry.prototype.getAncestors = function getAncestors(max) {
} }
return ancestors; return ancestors;
}, this); });
};
/** /**
* Test whether the entry is in the main chain. * Test whether the entry is in the main chain.
@ -232,8 +230,7 @@ ChainEntry.prototype.isMainChain = function isMainChain() {
* @param {Function} callback - Returns [Error, ChainEntry[]]. * @param {Function} callback - Returns [Error, ChainEntry[]].
*/ */
ChainEntry.prototype.getAncestorByHeight = function getAncestorByHeight(height) { ChainEntry.prototype.getAncestorByHeight = spawn.co(function* getAncestorByHeight(height) {
return spawn(function *() {
var main, entry; var main, entry;
if (height < 0) if (height < 0)
@ -255,8 +252,7 @@ ChainEntry.prototype.getAncestorByHeight = function getAncestorByHeight(height)
assert(entry.height === height); assert(entry.height === height);
return entry; return entry;
}, this); });
};
/** /**
* Get a single ancestor by index. Note that index-0 is * Get a single ancestor by index. Note that index-0 is
@ -266,8 +262,7 @@ ChainEntry.prototype.getAncestorByHeight = function getAncestorByHeight(height)
* @returns {Function} callback - Returns [Error, ChainEntry]. * @returns {Function} callback - Returns [Error, ChainEntry].
*/ */
ChainEntry.prototype.getAncestor = function getAncestor(index) { ChainEntry.prototype.getAncestor = spawn.co(function* getAncestor(index) {
return spawn(function *() {
var ancestors; var ancestors;
assert(index >= 0); assert(index >= 0);
@ -278,8 +273,7 @@ ChainEntry.prototype.getAncestor = function getAncestor(index) {
return; return;
return ancestors[index]; return ancestors[index];
}, this); });
};
/** /**
* Get previous entry. * Get previous entry.
@ -295,14 +289,12 @@ ChainEntry.prototype.getPrevious = function getPrevious() {
* @param {Function} callback - Returns [Error, ChainEntry]. * @param {Function} callback - Returns [Error, ChainEntry].
*/ */
ChainEntry.prototype.getNext = function getNext() { ChainEntry.prototype.getNext = spawn.co(function* getNext() {
return spawn(function *() {
var hash = yield this.chain.db.getNextHash(this.hash); var hash = yield this.chain.db.getNextHash(this.hash);
if (!hash) if (!hash)
return; return;
return yield this.chain.db.get(hash); return yield this.chain.db.get(hash);
}, this); });
};
/** /**
* Get median time past. * Get median time past.
@ -330,13 +322,11 @@ ChainEntry.prototype.getMedianTime = function getMedianTime(ancestors) {
* @param {Function} callback - Returns [Error, Number]. * @param {Function} callback - Returns [Error, Number].
*/ */
ChainEntry.prototype.getMedianTimeAsync = function getMedianTimeAsync() { ChainEntry.prototype.getMedianTimeAsync = spawn.co(function* getMedianTimeAsync() {
return spawn(function *() {
var MEDIAN_TIMESPAN = constants.block.MEDIAN_TIMESPAN; var MEDIAN_TIMESPAN = constants.block.MEDIAN_TIMESPAN;
var ancestors = yield this.getAncestors(MEDIAN_TIMESPAN); var ancestors = yield this.getAncestors(MEDIAN_TIMESPAN);
return this.getMedianTime(ancestors); return this.getMedianTime(ancestors);
}, this); });
};
/** /**
* Check isSuperMajority against majorityRejectOutdated. * Check isSuperMajority against majorityRejectOutdated.
@ -419,13 +409,11 @@ ChainEntry.prototype.isSuperMajority = function isSuperMajority(version, require
* @returns {Boolean} * @returns {Boolean}
*/ */
ChainEntry.prototype.isSuperMajorityAsync = function isSuperMajorityAsync(version, required) { ChainEntry.prototype.isSuperMajorityAsync = spawn.co(function* isSuperMajorityAsync(version, required) {
return spawn(function *() {
var majorityWindow = this.network.block.majorityWindow; var majorityWindow = this.network.block.majorityWindow;
var ancestors = yield this.getAncestors(majorityWindow); var ancestors = yield this.getAncestors(majorityWindow);
return this.isSuperMajority(version, required, ancestors); return this.isSuperMajority(version, required, ancestors);
}, this); });
};
/** /**
* Test whether the entry is potentially an ancestor of a checkpoint. * Test whether the entry is potentially an ancestor of a checkpoint.

View File

@ -290,12 +290,10 @@ LowlevelUp.prototype.approximateSize = function approximateSize(start, end) {
* @param {Function} callback - Returns [Error, Boolean]. * @param {Function} callback - Returns [Error, Boolean].
*/ */
LowlevelUp.prototype.has = function has(key) { LowlevelUp.prototype.has = spawn.co(function* has(key) {
return spawn(function *() {
var value = yield this.get(key); var value = yield this.get(key);
return value != null; return value != null;
}, this); });
};
/** /**
* Get and deserialize a record with a callback. * Get and deserialize a record with a callback.
@ -305,15 +303,13 @@ LowlevelUp.prototype.has = function has(key) {
* @param {Function} callback - Returns [Error, Object]. * @param {Function} callback - Returns [Error, Object].
*/ */
LowlevelUp.prototype.fetch = function fetch(key, parse) { LowlevelUp.prototype.fetch = spawn.co(function* fetch(key, parse) {
return spawn(function *() {
var value = yield this.get(key); var value = yield this.get(key);
if (!value) if (!value)
return; return;
return parse(value, key); return parse(value, key);
}, this); });
};
/** /**
* Collect all keys from iterator options. * Collect all keys from iterator options.
@ -321,8 +317,7 @@ LowlevelUp.prototype.fetch = function fetch(key, parse) {
* @param {Function} callback - Returns [Error, Array]. * @param {Function} callback - Returns [Error, Array].
*/ */
LowlevelUp.prototype.iterate = function iterate(options) { LowlevelUp.prototype.iterate = spawn.co(function* iterate(options) {
return spawn(function *() {
var items = []; var items = [];
var iter, kv, result; var iter, kv, result;
@ -342,8 +337,7 @@ LowlevelUp.prototype.iterate = function iterate(options) {
} }
return items; return items;
}, this); });
};
/** /**
* Write and assert a version number for the database. * Write and assert a version number for the database.
@ -351,8 +345,7 @@ LowlevelUp.prototype.iterate = function iterate(options) {
* @param {Function} callback * @param {Function} callback
*/ */
LowlevelUp.prototype.checkVersion = function checkVersion(key, version) { LowlevelUp.prototype.checkVersion = spawn.co(function* checkVersion(key, version) {
return spawn(function *() {
var data = yield this.get(key); var data = yield this.get(key);
if (!data) { if (!data) {
@ -366,8 +359,7 @@ LowlevelUp.prototype.checkVersion = function checkVersion(key, version) {
if (data !== version) if (data !== version)
throw new Error(VERSION_ERROR); throw new Error(VERSION_ERROR);
}, this); });
};
/** /**
* Clone the database. * Clone the database.
@ -375,8 +367,7 @@ LowlevelUp.prototype.checkVersion = function checkVersion(key, version) {
* @param {Function} callback * @param {Function} callback
*/ */
LowlevelUp.prototype.clone = function clone(path) { LowlevelUp.prototype.clone = spawn.co(function* clone(path) {
return spawn(function *() {
var opt = { keys: true, values: true }; var opt = { keys: true, values: true };
var options = utils.merge({}, this.options); var options = utils.merge({}, this.options);
var hwm = 256 << 20; var hwm = 256 << 20;
@ -427,8 +418,7 @@ LowlevelUp.prototype.clone = function clone(path) {
batch = tmp.batch(); batch = tmp.batch();
} }
} }
}, this); });
};
function Batch(db) { function Batch(db) {
this.db = db; this.db = db;

View File

@ -56,8 +56,7 @@ utils.inherits(HTTPClient, AsyncObject);
* @param {Function} callback * @param {Function} callback
*/ */
HTTPClient.prototype._open = function _open() { HTTPClient.prototype._open = spawn.co(function* _open() {
return spawn(function *() {
var self = this; var self = this;
var IOClient; var IOClient;
@ -119,8 +118,7 @@ HTTPClient.prototype._open = function _open() {
yield this._onConnect(); yield this._onConnect();
yield this._sendAuth(); yield this._sendAuth();
}, this); });
};
HTTPClient.prototype._onConnect = function _onConnect() { HTTPClient.prototype._onConnect = function _onConnect() {
var self = this; var self = this;
@ -165,8 +163,7 @@ HTTPClient.prototype._close = function close() {
* @param {Function} callback - Returns [Error, Object?]. * @param {Function} callback - Returns [Error, Object?].
*/ */
HTTPClient.prototype._request = function _request(method, endpoint, json) { HTTPClient.prototype._request = spawn.co(function* _request(method, endpoint, json) {
return spawn(function *() {
var query, network, height, res; var query, network, height, res;
if (this.token) { if (this.token) {
@ -215,8 +212,7 @@ HTTPClient.prototype._request = function _request(method, endpoint, json) {
} }
return res.body; return res.body;
}, this); });
};
/** /**
* Make a GET http request to endpoint. * Make a GET http request to endpoint.
@ -569,13 +565,11 @@ HTTPClient.prototype.send = function send(id, options) {
* @param {Function} callback * @param {Function} callback
*/ */
HTTPClient.prototype.retoken = function retoken(id, passphrase) { HTTPClient.prototype.retoken = spawn.co(function* retoken(id, passphrase) {
return spawn(function *() {
var options = { passphrase: passphrase }; var options = { passphrase: passphrase };
var body = yield this._post('/wallet/' + id + '/retoken', options); var body = yield this._post('/wallet/' + id + '/retoken', options);
return body.token; return body.token;
}, this); });
};
/** /**
* Change or set master key's passphrase. * Change or set master key's passphrase.

View File

@ -293,8 +293,7 @@ RPC.prototype.execute = function execute(json) {
* Overall control/query calls * Overall control/query calls
*/ */
RPC.prototype.getinfo = function getinfo(args) { RPC.prototype.getinfo = spawn.co(function* getinfo(args) {
return spawn(function *() {
var balance; var balance;
if (args.help || args.length !== 0) if (args.help || args.length !== 0)
@ -320,8 +319,7 @@ RPC.prototype.getinfo = function getinfo(args) {
relayfee: +utils.btc(this.network.getMinRelay()), relayfee: +utils.btc(this.network.getMinRelay()),
errors: '' errors: ''
}; };
}, this); });
};
RPC.prototype.help = function help(args) { RPC.prototype.help = function help(args) {
var json; var json;
@ -617,8 +615,7 @@ RPC.prototype._getSoftforks = function _getSoftforks() {
]; ];
}; };
RPC.prototype._getBIP9Softforks = function _getBIP9Softforks() { RPC.prototype._getBIP9Softforks = spawn.co(function* _getBIP9Softforks() {
return spawn(function *() {
var forks = {}; var forks = {};
var keys = Object.keys(this.network.deployments); var keys = Object.keys(this.network.deployments);
var i, id, deployment, state; var i, id, deployment, state;
@ -655,12 +652,10 @@ RPC.prototype._getBIP9Softforks = function _getBIP9Softforks() {
} }
return forks; return forks;
}, this); });
};
/* Block chain and UTXO */ /* Block chain and UTXO */
RPC.prototype.getblockchaininfo = function getblockchaininfo(args) { RPC.prototype.getblockchaininfo = spawn.co(function* getblockchaininfo(args) {
return spawn(function *() {
if (args.help || args.length !== 0) if (args.help || args.length !== 0)
throw new RPCError('getblockchaininfo'); throw new RPCError('getblockchaininfo');
@ -680,8 +675,7 @@ RPC.prototype.getblockchaininfo = function getblockchaininfo(args) {
? Math.max(0, this.chain.height - this.chain.db.keepBlocks) ? Math.max(0, this.chain.height - this.chain.db.keepBlocks)
: null : null
}; };
}, this); });
};
RPC.prototype._getDifficulty = function getDifficulty(entry) { RPC.prototype._getDifficulty = function getDifficulty(entry) {
var shift, diff; var shift, diff;
@ -722,8 +716,7 @@ RPC.prototype.getblockcount = function getblockcount(args) {
return Promise.resolve(this.chain.tip.height); return Promise.resolve(this.chain.tip.height);
}; };
RPC.prototype.getblock = function getblock(args) { RPC.prototype.getblock = spawn.co(function* getblock(args) {
return spawn(function *() {
var hash, verbose, entry, block; var hash, verbose, entry, block;
if (args.help || args.length < 1 || args.length > 2) if (args.help || args.length < 1 || args.length > 2)
@ -760,8 +753,7 @@ RPC.prototype.getblock = function getblock(args) {
return block.toRaw().toString('hex'); return block.toRaw().toString('hex');
return yield this._blockToJSON(entry, block, false); return yield this._blockToJSON(entry, block, false);
}, this); });
};
RPC.prototype._txToJSON = function _txToJSON(tx) { RPC.prototype._txToJSON = function _txToJSON(tx) {
var self = this; var self = this;
@ -827,8 +819,7 @@ RPC.prototype._scriptToJSON = function scriptToJSON(script, hex) {
return out; return out;
}; };
RPC.prototype.getblockhash = function getblockhash(args) { RPC.prototype.getblockhash = spawn.co(function* getblockhash(args) {
return spawn(function *() {
var height, entry; var height, entry;
if (args.help || args.length !== 1) if (args.help || args.length !== 1)
@ -845,11 +836,9 @@ RPC.prototype.getblockhash = function getblockhash(args) {
throw new RPCError('Not found.'); throw new RPCError('Not found.');
return entry.rhash; return entry.rhash;
}, this); });
};
RPC.prototype.getblockheader = function getblockheader(args) { RPC.prototype.getblockheader = spawn.co(function* getblockheader(args) {
return spawn(function *() {
var hash, verbose, entry; var hash, verbose, entry;
if (args.help || args.length < 1 || args.length > 2) if (args.help || args.length < 1 || args.length > 2)
@ -874,11 +863,9 @@ RPC.prototype.getblockheader = function getblockheader(args) {
return entry.toRaw().toString('hex', 0, 80); return entry.toRaw().toString('hex', 0, 80);
return yield this._headerToJSON(entry); return yield this._headerToJSON(entry);
}, this); });
};
RPC.prototype._headerToJSON = function _headerToJSON(entry) { RPC.prototype._headerToJSON = spawn.co(function* _headerToJSON(entry) {
return spawn(function *() {
var medianTime = yield entry.getMedianTimeAsync(); var medianTime = yield entry.getMedianTimeAsync();
var nextHash = yield this.chain.db.getNextHash(entry.hash); var nextHash = yield this.chain.db.getNextHash(entry.hash);
@ -898,11 +885,9 @@ RPC.prototype._headerToJSON = function _headerToJSON(entry) {
: null, : null,
nextblockhash: nextHash ? utils.revHex(nextHash) : null nextblockhash: nextHash ? utils.revHex(nextHash) : null
}; };
}, this); });
};
RPC.prototype._blockToJSON = function _blockToJSON(entry, block, txDetails) { RPC.prototype._blockToJSON = spawn.co(function* _blockToJSON(entry, block, txDetails) {
return spawn(function *() {
var self = this; var self = this;
var medianTime = yield entry.getMedianTimeAsync(); var medianTime = yield entry.getMedianTimeAsync();
var nextHash = yield this.chain.db.getNextHash(entry.hash); var nextHash = yield this.chain.db.getNextHash(entry.hash);
@ -931,11 +916,9 @@ RPC.prototype._blockToJSON = function _blockToJSON(entry, block, txDetails) {
: null, : null,
nextblockhash: nextHash ? utils.revHex(nextHash) : null nextblockhash: nextHash ? utils.revHex(nextHash) : null
}; };
}, this); });
};
RPC.prototype.getchaintips = function getchaintips(args) { RPC.prototype.getchaintips = spawn.co(function* getchaintips(args) {
return spawn(function *() {
var i, tips, orphans, prevs, result; var i, tips, orphans, prevs, result;
var orphan, entries, entry, main, fork; var orphan, entries, entry, main, fork;
@ -979,19 +962,16 @@ RPC.prototype.getchaintips = function getchaintips(args) {
} }
return result; return result;
}, this); });
};
RPC.prototype._findFork = function _findFork(entry) { RPC.prototype._findFork = spawn.co(function* _findFork(entry) {
return spawn(function *() {
while (entry) { while (entry) {
if (yield entry.isMainChain()) if (yield entry.isMainChain())
return entry; return entry;
entry = yield entry.getPrevious(); entry = yield entry.getPrevious();
} }
throw new Error('Fork not found.'); throw new Error('Fork not found.');
}, this); });
};
RPC.prototype.getdifficulty = function getdifficulty(args) { RPC.prototype.getdifficulty = function getdifficulty(args) {
if (args.help || args.length !== 0) if (args.help || args.length !== 0)
@ -1167,8 +1147,7 @@ RPC.prototype._entryToJSON = function _entryToJSON(entry) {
}; };
}; };
RPC.prototype.gettxout = function gettxout(args) { RPC.prototype.gettxout = spawn.co(function* gettxout(args) {
return spawn(function *() {
var hash, index, mempool, coin; var hash, index, mempool, coin;
if (args.help || args.length < 2 || args.length > 3) if (args.help || args.length < 2 || args.length > 3)
@ -1206,11 +1185,9 @@ RPC.prototype.gettxout = function gettxout(args) {
version: coin.version, version: coin.version,
coinbase: coin.coinbase coinbase: coin.coinbase
}; };
}, this); });
};
RPC.prototype.gettxoutproof = function gettxoutproof(args) { RPC.prototype.gettxoutproof = spawn.co(function* gettxoutproof(args) {
return spawn(function *() {
var uniq = {}; var uniq = {};
var i, txids, block, hash, last, tx, coins; var i, txids, block, hash, last, tx, coins;
@ -1274,11 +1251,9 @@ RPC.prototype.gettxoutproof = function gettxoutproof(args) {
block = bcoin.merkleblock.fromHashes(block, txids); block = bcoin.merkleblock.fromHashes(block, txids);
return block.toRaw().toString('hex'); return block.toRaw().toString('hex');
}, this); });
};
RPC.prototype.verifytxoutproof = function verifytxoutproof(args) { RPC.prototype.verifytxoutproof = spawn.co(function* verifytxoutproof(args) {
return spawn(function *() {
var res = []; var res = [];
var i, block, hash, entry; var i, block, hash, entry;
@ -1301,8 +1276,7 @@ RPC.prototype.verifytxoutproof = function verifytxoutproof(args) {
} }
return res; return res;
}, this); });
};
RPC.prototype.gettxoutsetinfo = function gettxoutsetinfo(args) { RPC.prototype.gettxoutsetinfo = function gettxoutsetinfo(args) {
if (args.help || args.length !== 0) if (args.help || args.length !== 0)
@ -1339,8 +1313,7 @@ RPC.prototype.verifychain = function verifychain(args) {
* Mining * Mining
*/ */
RPC.prototype._submitwork = function _submitwork(data) { RPC.prototype._submitwork = spawn.co(function* _submitwork(data) {
return spawn(function *() {
var attempt = this.attempt; var attempt = this.attempt;
var block, header, cb, cur; var block, header, cb, cur;
@ -1395,11 +1368,9 @@ RPC.prototype._submitwork = function _submitwork(data) {
} }
return true; return true;
}, this); });
};
RPC.prototype._getwork = function _getwork() { RPC.prototype._getwork = spawn.co(function* _getwork() {
return spawn(function *() {
var attempt = yield this._getAttempt(true); var attempt = yield this._getAttempt(true);
var data, abbr; var data, abbr;
@ -1419,8 +1390,7 @@ RPC.prototype._getwork = function _getwork() {
target: attempt.target.toString('hex'), target: attempt.target.toString('hex'),
height: attempt.height height: attempt.height
}; };
}, this); });
};
RPC.prototype.getworklp = function getworklp(args) { RPC.prototype.getworklp = function getworklp(args) {
var self = this; var self = this;
@ -1431,8 +1401,7 @@ RPC.prototype.getworklp = function getworklp(args) {
}); });
}; };
RPC.prototype.getwork = function getwork(args) { RPC.prototype.getwork = spawn.co(function* getwork(args) {
return spawn(function *() {
var unlock = yield this.locker.lock(); var unlock = yield this.locker.lock();
var data, result; var data, result;
@ -1468,11 +1437,9 @@ RPC.prototype.getwork = function getwork(args) {
unlock(); unlock();
return result; return result;
}, this); });
};
RPC.prototype.submitblock = function submitblock(args) { RPC.prototype.submitblock = spawn.co(function* submitblock(args) {
return spawn(function *() {
var unlock = yield this.locker.lock(); var unlock = yield this.locker.lock();
var block; var block;
@ -1484,11 +1451,9 @@ RPC.prototype.submitblock = function submitblock(args) {
block = bcoin.block.fromRaw(toString(args[0]), 'hex'); block = bcoin.block.fromRaw(toString(args[0]), 'hex');
return yield this._submitblock(block); return yield this._submitblock(block);
}, this); });
};
RPC.prototype._submitblock = function submitblock(block) { RPC.prototype._submitblock = spawn.co(function* submitblock(block) {
return spawn(function *() {
if (block.prevBlock !== this.chain.tip.hash) if (block.prevBlock !== this.chain.tip.hash)
return 'rejected: inconclusive-not-best-prevblk'; return 'rejected: inconclusive-not-best-prevblk';
@ -1501,11 +1466,9 @@ RPC.prototype._submitblock = function submitblock(block) {
} }
return null; return null;
}, this); });
};
RPC.prototype.getblocktemplate = function getblocktemplate(args) { RPC.prototype.getblocktemplate = spawn.co(function* getblocktemplate(args) {
return spawn(function *() {
var mode = 'template'; var mode = 'template';
var version = -1; var version = -1;
var coinbase = true; var coinbase = true;
@ -1572,11 +1535,9 @@ RPC.prototype.getblocktemplate = function getblocktemplate(args) {
yield this._poll(lpid); yield this._poll(lpid);
return yield this._tmpl(version, coinbase, rules); return yield this._tmpl(version, coinbase, rules);
}, this); });
};
RPC.prototype._tmpl = function _tmpl(version, coinbase, rules) { RPC.prototype._tmpl = spawn.co(function* _tmpl(version, coinbase, rules) {
return spawn(function *() {
var unlock = yield this.locker.lock(); var unlock = yield this.locker.lock();
var txs = []; var txs = [];
var txIndex = {}; var txIndex = {};
@ -1722,8 +1683,7 @@ RPC.prototype._tmpl = function _tmpl(version, coinbase, rules) {
unlock(); unlock();
return template; return template;
}, this); });
};
RPC.prototype._poll = function _poll(lpid) { RPC.prototype._poll = function _poll(lpid) {
var self = this; var self = this;
@ -1785,8 +1745,7 @@ RPC.prototype._bindChain = function _bindChain() {
}); });
}; };
RPC.prototype._getAttempt = function _getAttempt(update) { RPC.prototype._getAttempt = spawn.co(function* _getAttempt(update) {
return spawn(function *() {
var attempt = this.attempt; var attempt = this.attempt;
this._bindChain(); this._bindChain();
@ -1806,15 +1765,13 @@ RPC.prototype._getAttempt = function _getAttempt(update) {
this.coinbase[attempt.block.merkleRoot] = attempt.coinbase.clone(); this.coinbase[attempt.block.merkleRoot] = attempt.coinbase.clone();
return attempt; return attempt;
}, this); });
};
RPC.prototype._totalTX = function _totalTX() { RPC.prototype._totalTX = function _totalTX() {
return this.mempool ? this.mempool.totalTX : 0; return this.mempool ? this.mempool.totalTX : 0;
}; };
RPC.prototype.getmininginfo = function getmininginfo(args) { RPC.prototype.getmininginfo = spawn.co(function* getmininginfo(args) {
return spawn(function *() {
var block, hashps; var block, hashps;
if (args.help || args.length !== 0) if (args.help || args.length !== 0)
@ -1840,8 +1797,7 @@ RPC.prototype.getmininginfo = function getmininginfo(args) {
chain: 'main', chain: 'main',
generate: this.mining generate: this.mining
}; };
}, this); });
};
RPC.prototype.getnetworkhashps = function getnetworkhashps(args) { RPC.prototype.getnetworkhashps = function getnetworkhashps(args) {
var lookup = 120; var lookup = 120;
@ -1897,8 +1853,7 @@ RPC.prototype.prioritisetransaction = function prioritisetransaction(args) {
return Promise.resolve(true); return Promise.resolve(true);
}; };
RPC.prototype._hashps = function _hashps(lookup, height) { RPC.prototype._hashps = spawn.co(function* _hashps(lookup, height) {
return spawn(function *() {
var i, minTime, maxTime, pb0, time; var i, minTime, maxTime, pb0, time;
var workDiff, timeDiff, ps, pb, entry; var workDiff, timeDiff, ps, pb, entry;
@ -1939,8 +1894,7 @@ RPC.prototype._hashps = function _hashps(lookup, height) {
ps = +workDiff.toString(10) / timeDiff; ps = +workDiff.toString(10) / timeDiff;
return ps; return ps;
}, this); });
};
/* /*
* Coin generation * Coin generation
@ -1967,8 +1921,7 @@ RPC.prototype.setgenerate = function setgenerate(args) {
return Promise.resolve(this.mining); return Promise.resolve(this.mining);
}; };
RPC.prototype.generate = function generate(args) { RPC.prototype.generate = spawn.co(function* generate(args) {
return spawn(function *() {
var unlock = yield this.locker.lock(); var unlock = yield this.locker.lock();
var numblocks; var numblocks;
@ -1980,11 +1933,9 @@ RPC.prototype.generate = function generate(args) {
numblocks = toNumber(args[0], 1); numblocks = toNumber(args[0], 1);
return yield this._generate(numblocks); return yield this._generate(numblocks);
}, this); });
};
RPC.prototype._generate = function _generate(numblocks) { RPC.prototype._generate = spawn.co(function* _generate(numblocks) {
return spawn(function *() {
var hashes = []; var hashes = [];
var i, block; var i, block;
@ -1995,11 +1946,9 @@ RPC.prototype._generate = function _generate(numblocks) {
} }
return hashes; return hashes;
}, this); });
};
RPC.prototype.generatetoaddress = function generatetoaddress(args) { RPC.prototype.generatetoaddress = spawn.co(function* generatetoaddress(args) {
return spawn(function *() {
var unlock = yield this.locker.lock(); var unlock = yield this.locker.lock();
var numblocks, address, hashes; var numblocks, address, hashes;
@ -2019,8 +1968,7 @@ RPC.prototype.generatetoaddress = function generatetoaddress(args) {
unlock(); unlock();
return hashes; return hashes;
}, this); });
};
/* /*
* Raw transactions * Raw transactions
@ -2157,8 +2105,7 @@ RPC.prototype.decodescript = function decodescript(args) {
return Promise.resolve(script); return Promise.resolve(script);
}; };
RPC.prototype.getrawtransaction = function getrawtransaction(args) { RPC.prototype.getrawtransaction = spawn.co(function* getrawtransaction(args) {
return spawn(function *() {
var hash, verbose, json, tx; var hash, verbose, json, tx;
if (args.help || args.length < 1 || args.length > 2) if (args.help || args.length < 1 || args.length > 2)
@ -2186,8 +2133,7 @@ RPC.prototype.getrawtransaction = function getrawtransaction(args) {
json.hex = tx.toRaw().toString('hex'); json.hex = tx.toRaw().toString('hex');
return json; return json;
}, this); });
};
RPC.prototype.sendrawtransaction = function sendrawtransaction(args) { RPC.prototype.sendrawtransaction = function sendrawtransaction(args) {
var tx; var tx;
@ -2207,8 +2153,7 @@ RPC.prototype.sendrawtransaction = function sendrawtransaction(args) {
return tx.rhash; return tx.rhash;
}; };
RPC.prototype.signrawtransaction = function signrawtransaction(args) { RPC.prototype.signrawtransaction = spawn.co(function* signrawtransaction(args) {
return spawn(function *() {
var raw, p, txs, merged; var raw, p, txs, merged;
if (args.help || args.length < 1 || args.length > 4) { if (args.help || args.length < 1 || args.length > 4) {
@ -2235,8 +2180,7 @@ RPC.prototype.signrawtransaction = function signrawtransaction(args) {
yield this.wallet.fillCoins(merged); yield this.wallet.fillCoins(merged);
return yield this._signrawtransaction(merged, txs, args); return yield this._signrawtransaction(merged, txs, args);
}, this); });
};
RPC.prototype._fillCoins = function _fillCoins(tx) { RPC.prototype._fillCoins = function _fillCoins(tx) {
if (this.chain.db.options.spv) if (this.chain.db.options.spv)
@ -2245,8 +2189,7 @@ RPC.prototype._fillCoins = function _fillCoins(tx) {
return this.node.fillCoins(tx); return this.node.fillCoins(tx);
}; };
RPC.prototype._signrawtransaction = function signrawtransaction(merged, txs, args) { RPC.prototype._signrawtransaction = spawn.co(function* signrawtransaction(merged, txs, args) {
return spawn(function *() {
var keys = []; var keys = [];
var keyMap = {}; var keyMap = {};
var k, i, secret, key; var k, i, secret, key;
@ -2353,11 +2296,9 @@ RPC.prototype._signrawtransaction = function signrawtransaction(merged, txs, arg
hex: merged.toRaw().toString('hex'), hex: merged.toRaw().toString('hex'),
complete: merged.isSigned() complete: merged.isSigned()
}; };
}, this); });
};
RPC.prototype.fundrawtransaction = function fundrawtransaction(args) { RPC.prototype.fundrawtransaction = spawn.co(function* fundrawtransaction(args) {
return spawn(function *() {
var tx, options, changeAddress, feeRate; var tx, options, changeAddress, feeRate;
if (args.help || args.length < 1 || args.length > 2) if (args.help || args.length < 1 || args.length > 2)
@ -2393,11 +2334,9 @@ RPC.prototype.fundrawtransaction = function fundrawtransaction(args) {
changepos: tx.changeIndex, changepos: tx.changeIndex,
fee: +utils.btc(tx.getFee()) fee: +utils.btc(tx.getFee())
}; };
}, this); });
};
RPC.prototype._createRedeem = function _createRedeem(args) { RPC.prototype._createRedeem = spawn.co(function* _createRedeem(args) {
return spawn(function *() {
var i, m, n, keys, hash, script, key, ring; var i, m, n, keys, hash, script, key, ring;
if (!utils.isNumber(args[0]) if (!utils.isNumber(args[0])
@ -2445,15 +2384,13 @@ RPC.prototype._createRedeem = function _createRedeem(args) {
throw new RPCError('Redeem script exceeds size limit.'); throw new RPCError('Redeem script exceeds size limit.');
return script; return script;
}, this); });
};
/* /*
* Utility functions * Utility spawn.co(function* s
*/ */
RPC.prototype.createmultisig = function createmultisig(args) { RPC.prototype.createmultisig = function createmultisig(args) {
return spawn(function *() {
var script; var script;
if (args.help || args.length < 2 || args.length > 2) if (args.help || args.length < 2 || args.length > 2)
@ -2465,8 +2402,7 @@ RPC.prototype.createmultisig = function createmultisig(args) {
address: script.getAddress().toBase58(this.network), address: script.getAddress().toBase58(this.network),
redeemScript: script.toJSON() redeemScript: script.toJSON()
}; };
}, this); });
};
RPC.prototype._scriptForWitness = function scriptForWitness(script) { RPC.prototype._scriptForWitness = function scriptForWitness(script) {
var hash; var hash;
@ -2501,8 +2437,7 @@ RPC.prototype.createwitnessaddress = function createwitnessaddress(args) {
}); });
}; };
RPC.prototype.validateaddress = function validateaddress(args) { RPC.prototype.validateaddress = spawn.co(function* validateaddress(args) {
return spawn(function *() {
var b58, address, json, path; var b58, address, json, path;
if (args.help || args.length !== 1) if (args.help || args.length !== 1)
@ -2535,8 +2470,7 @@ RPC.prototype.validateaddress = function validateaddress(args) {
json.hdkeypath = path.toPath(); json.hdkeypath = path.toPath();
return json; return json;
}, this); });
};
RPC.magic = 'Bitcoin Signed Message:\n'; RPC.magic = 'Bitcoin Signed Message:\n';
@ -2736,8 +2670,7 @@ RPC.prototype.setmocktime = function setmocktime(args) {
* Wallet * Wallet
*/ */
RPC.prototype.resendwallettransactions = function resendwallettransactions(args) { RPC.prototype.resendwallettransactions = spawn.co(function* resendwallettransactions(args) {
return spawn(function *() {
var hashes = []; var hashes = [];
var i, tx, txs; var i, tx, txs;
@ -2752,8 +2685,7 @@ RPC.prototype.resendwallettransactions = function resendwallettransactions(args)
} }
return hashes; return hashes;
}, this); });
};
RPC.prototype.addmultisigaddress = function addmultisigaddress(args) { RPC.prototype.addmultisigaddress = function addmultisigaddress(args) {
if (args.help || args.length < 2 || args.length > 3) { if (args.help || args.length < 2 || args.length > 3) {
@ -2771,8 +2703,7 @@ RPC.prototype.addwitnessaddress = function addwitnessaddress(args) {
Promise.reject(new Error('Not implemented.')); Promise.reject(new Error('Not implemented.'));
}; };
RPC.prototype.backupwallet = function backupwallet(args) { RPC.prototype.backupwallet = spawn.co(function* backupwallet(args) {
return spawn(function *() {
var dest; var dest;
if (args.help || args.length !== 1) if (args.help || args.length !== 1)
@ -2782,11 +2713,9 @@ RPC.prototype.backupwallet = function backupwallet(args) {
yield this.walletdb.backup(dest); yield this.walletdb.backup(dest);
return null; return null;
}, this); });
};
RPC.prototype.dumpprivkey = function dumpprivkey(args) { RPC.prototype.dumpprivkey = spawn.co(function* dumpprivkey(args) {
return spawn(function *() {
var hash, ring; var hash, ring;
if (args.help || args.length !== 1) if (args.help || args.length !== 1)
@ -2806,11 +2735,9 @@ RPC.prototype.dumpprivkey = function dumpprivkey(args) {
throw new RPCError('Wallet is locked.'); throw new RPCError('Wallet is locked.');
return ring.toSecret(); return ring.toSecret();
}, this); });
};
RPC.prototype.dumpwallet = function dumpwallet(args) { RPC.prototype.dumpwallet = spawn.co(function* dumpwallet(args) {
return spawn(function *() {
var i, file, time, address, fmt, str, out, hash, hashes, ring; var i, file, time, address, fmt, str, out, hash, hashes, ring;
if (args.help || args.length !== 1) if (args.help || args.length !== 1)
@ -2866,11 +2793,9 @@ RPC.prototype.dumpwallet = function dumpwallet(args) {
yield writeFile(file, out); yield writeFile(file, out);
return out; return out;
}, this); });
};
RPC.prototype.encryptwallet = function encryptwallet(args) { RPC.prototype.encryptwallet = spawn.co(function* encryptwallet(args) {
return spawn(function *() {
var passphrase; var passphrase;
if (!this.wallet.master.encrypted && (args.help || args.help !== 1)) if (!this.wallet.master.encrypted && (args.help || args.help !== 1))
@ -2887,11 +2812,9 @@ RPC.prototype.encryptwallet = function encryptwallet(args) {
yield this.wallet.setPassphrase(passphrase); yield this.wallet.setPassphrase(passphrase);
return 'wallet encrypted; we do not need to stop!'; return 'wallet encrypted; we do not need to stop!';
}, this); });
};
RPC.prototype.getaccountaddress = function getaccountaddress(args) { RPC.prototype.getaccountaddress = spawn.co(function* getaccountaddress(args) {
return spawn(function *() {
var account; var account;
if (args.help || args.length !== 1) if (args.help || args.length !== 1)
@ -2908,11 +2831,9 @@ RPC.prototype.getaccountaddress = function getaccountaddress(args) {
return ''; return '';
return account.receiveAddress.getAddress('base58'); return account.receiveAddress.getAddress('base58');
}, this); });
};
RPC.prototype.getaccount = function getaccount(args) { RPC.prototype.getaccount = spawn.co(function* getaccount(args) {
return spawn(function *() {
var hash, path; var hash, path;
if (args.help || args.length !== 1) if (args.help || args.length !== 1)
@ -2929,11 +2850,9 @@ RPC.prototype.getaccount = function getaccount(args) {
return ''; return '';
return path.name; return path.name;
}, this); });
};
RPC.prototype.getaddressesbyaccount = function getaddressesbyaccount(args) { RPC.prototype.getaddressesbyaccount = spawn.co(function* getaddressesbyaccount(args) {
return spawn(function *() {
var i, path, account, addrs, paths; var i, path, account, addrs, paths;
if (args.help || args.length !== 1) if (args.help || args.length !== 1)
@ -2954,11 +2873,9 @@ RPC.prototype.getaddressesbyaccount = function getaddressesbyaccount(args) {
} }
return addrs; return addrs;
}, this); });
};
RPC.prototype.getbalance = function getbalance(args) { RPC.prototype.getbalance = spawn.co(function* getbalance(args) {
return spawn(function *() {
var minconf = 0; var minconf = 0;
var account, value, balance; var account, value, balance;
@ -2984,11 +2901,9 @@ RPC.prototype.getbalance = function getbalance(args) {
value = balance.total; value = balance.total;
return +utils.btc(value); return +utils.btc(value);
}, this); });
};
RPC.prototype.getnewaddress = function getnewaddress(args) { RPC.prototype.getnewaddress = spawn.co(function* getnewaddress(args) {
return spawn(function *() {
var account, address; var account, address;
if (args.help || args.length > 1) if (args.help || args.length > 1)
@ -3003,11 +2918,9 @@ RPC.prototype.getnewaddress = function getnewaddress(args) {
address = yield this.wallet.createReceive(account); address = yield this.wallet.createReceive(account);
return address.getAddress('base58'); return address.getAddress('base58');
}, this); });
};
RPC.prototype.getrawchangeaddress = function getrawchangeaddress(args) { RPC.prototype.getrawchangeaddress = spawn.co(function* getrawchangeaddress(args) {
return spawn(function *() {
var address; var address;
if (args.help || args.length > 1) if (args.help || args.length > 1)
@ -3016,11 +2929,9 @@ RPC.prototype.getrawchangeaddress = function getrawchangeaddress(args) {
address = yield this.wallet.createChange(); address = yield this.wallet.createChange();
return address.getAddress('base58'); return address.getAddress('base58');
}, this); });
};
RPC.prototype.getreceivedbyaccount = function getreceivedbyaccount(args) { RPC.prototype.getreceivedbyaccount = spawn.co(function* getreceivedbyaccount(args) {
return spawn(function *() {
var minconf = 0; var minconf = 0;
var total = 0; var total = 0;
var filter = {}; var filter = {};
@ -3071,11 +2982,9 @@ RPC.prototype.getreceivedbyaccount = function getreceivedbyaccount(args) {
} }
return +utils.btc(total); return +utils.btc(total);
}, this); });
};
RPC.prototype.getreceivedbyaddress = function getreceivedbyaddress(args) { RPC.prototype.getreceivedbyaddress = spawn.co(function* getreceivedbyaddress(args) {
return spawn(function *() {
var self = this; var self = this;
var minconf = 0; var minconf = 0;
var total = 0; var total = 0;
@ -3110,11 +3019,9 @@ RPC.prototype.getreceivedbyaddress = function getreceivedbyaddress(args) {
} }
return +utils.btc(total); return +utils.btc(total);
}, this); });
};
RPC.prototype._toWalletTX = function _toWalletTX(tx) { RPC.prototype._toWalletTX = spawn.co(function* _toWalletTX(tx) {
return spawn(function *() {
var i, det, receive, member, sent, received, json, details; var i, det, receive, member, sent, received, json, details;
details = yield this.wallet.toDetails(tx); details = yield this.wallet.toDetails(tx);
@ -3189,11 +3096,9 @@ RPC.prototype._toWalletTX = function _toWalletTX(tx) {
}; };
return json; return json;
}, this); });
};
RPC.prototype.gettransaction = function gettransaction(args) { RPC.prototype.gettransaction = spawn.co(function* gettransaction(args) {
return spawn(function *() {
var hash, tx; var hash, tx;
if (args.help || args.length < 1 || args.length > 2) if (args.help || args.length < 1 || args.length > 2)
@ -3210,11 +3115,9 @@ RPC.prototype.gettransaction = function gettransaction(args) {
throw new RPCError('TX not found.'); throw new RPCError('TX not found.');
return yield this._toWalletTX(tx); return yield this._toWalletTX(tx);
}, this); });
};
RPC.prototype.abandontransaction = function abandontransaction(args) { RPC.prototype.abandontransaction = spawn.co(function* abandontransaction(args) {
return spawn(function *() {
var hash, result; var hash, result;
if (args.help || args.length !== 1) if (args.help || args.length !== 1)
@ -3231,11 +3134,9 @@ RPC.prototype.abandontransaction = function abandontransaction(args) {
throw new RPCError('Transaction not in wallet.'); throw new RPCError('Transaction not in wallet.');
return null; return null;
}, this); });
};
RPC.prototype.getunconfirmedbalance = function getunconfirmedbalance(args) { RPC.prototype.getunconfirmedbalance = spawn.co(function* getunconfirmedbalance(args) {
return spawn(function *() {
var balance; var balance;
if (args.help || args.length > 0) if (args.help || args.length > 0)
@ -3244,11 +3145,9 @@ RPC.prototype.getunconfirmedbalance = function getunconfirmedbalance(args) {
balance = yield this.wallet.getBalance(); balance = yield this.wallet.getBalance();
return +utils.btc(balance.unconfirmed); return +utils.btc(balance.unconfirmed);
}, this); });
};
RPC.prototype.getwalletinfo = function getwalletinfo(args) { RPC.prototype.getwalletinfo = spawn.co(function* getwalletinfo(args) {
return spawn(function *() {
var balance, hashes; var balance, hashes;
if (args.help || args.length !== 0) if (args.help || args.length !== 0)
@ -3270,11 +3169,9 @@ RPC.prototype.getwalletinfo = function getwalletinfo(args) {
? +utils.btc(this.feeRate) ? +utils.btc(this.feeRate)
: +utils.btc(0) : +utils.btc(0)
}; };
}, this); });
};
RPC.prototype.importprivkey = function importprivkey(args) { RPC.prototype.importprivkey = spawn.co(function* importprivkey(args) {
return spawn(function *() {
var secret, label, rescan, key; var secret, label, rescan, key;
if (args.help || args.length < 1 || args.length > 3) if (args.help || args.length < 1 || args.length > 3)
@ -3301,11 +3198,9 @@ RPC.prototype.importprivkey = function importprivkey(args) {
yield this.walletdb.rescan(this.chain.db, 0); yield this.walletdb.rescan(this.chain.db, 0);
return null; return null;
}, this); });
};
RPC.prototype.importwallet = function importwallet(args) { RPC.prototype.importwallet = spawn.co(function* importwallet(args) {
return spawn(function *() {
var file, keys, lines, line, parts; var file, keys, lines, line, parts;
var i, secret, time, label, addr; var i, secret, time, label, addr;
var data, key; var data, key;
@ -3354,8 +3249,7 @@ RPC.prototype.importwallet = function importwallet(args) {
yield this.walletdb.rescan(this.chain.db, 0); yield this.walletdb.rescan(this.chain.db, 0);
return null; return null;
}, this); });
};
RPC.prototype.importaddress = function importaddress(args) { RPC.prototype.importaddress = function importaddress(args) {
if (args.help || args.length < 1 || args.length > 4) { if (args.help || args.length < 1 || args.length > 4) {
@ -3366,8 +3260,7 @@ RPC.prototype.importaddress = function importaddress(args) {
return Promise.reject(new Error('Not implemented.')); return Promise.reject(new Error('Not implemented.'));
}; };
RPC.prototype.importpubkey = function importpubkey(args) { RPC.prototype.importpubkey = spawn.co(function* importpubkey(args) {
return spawn(function *() {
var pubkey, label, rescan, key; var pubkey, label, rescan, key;
if (args.help || args.length < 1 || args.length > 4) if (args.help || args.length < 1 || args.length > 4)
@ -3399,8 +3292,7 @@ RPC.prototype.importpubkey = function importpubkey(args) {
yield this.walletdb.rescan(this.chain.db, 0); yield this.walletdb.rescan(this.chain.db, 0);
return null; return null;
}, this); });
};
RPC.prototype.keypoolrefill = function keypoolrefill(args) { RPC.prototype.keypoolrefill = function keypoolrefill(args) {
if (args.help || args.length > 1) if (args.help || args.length > 1)
@ -3408,8 +3300,7 @@ RPC.prototype.keypoolrefill = function keypoolrefill(args) {
return Promise.resolve(null); return Promise.resolve(null);
}; };
RPC.prototype.listaccounts = function listaccounts(args) { RPC.prototype.listaccounts = spawn.co(function* listaccounts(args) {
return spawn(function *() {
var i, map, accounts, account, balance; var i, map, accounts, account, balance;
if (args.help || args.length > 2) if (args.help || args.length > 2)
@ -3425,8 +3316,7 @@ RPC.prototype.listaccounts = function listaccounts(args) {
} }
return map; return map;
}, this); });
};
RPC.prototype.listaddressgroupings = function listaddressgroupings(args) { RPC.prototype.listaddressgroupings = function listaddressgroupings(args) {
if (args.help) if (args.help)
@ -3490,8 +3380,7 @@ RPC.prototype.listreceivedbyaddress = function listreceivedbyaddress(args) {
return this._listReceived(minconf, includeEmpty, false); return this._listReceived(minconf, includeEmpty, false);
}; };
RPC.prototype._listReceived = function _listReceived(minconf, empty, account) { RPC.prototype._listReceived = spawn.co(function* _listReceived(minconf, empty, account) {
return spawn(function *() {
var out = []; var out = [];
var result = []; var result = [];
var map = {}; var map = {};
@ -3581,11 +3470,9 @@ RPC.prototype._listReceived = function _listReceived(minconf, empty, account) {
} }
return result; return result;
}, this); });
};
RPC.prototype.listsinceblock = function listsinceblock(args) { RPC.prototype.listsinceblock = spawn.co(function* listsinceblock(args) {
return spawn(function *() {
var block, conf, out, highest; var block, conf, out, highest;
var i, height, txs, tx, json; var i, height, txs, tx, json;
@ -3637,11 +3524,9 @@ RPC.prototype.listsinceblock = function listsinceblock(args) {
? utils.revHex(highest.block) ? utils.revHex(highest.block)
: constants.NULL_HASH : constants.NULL_HASH
}; };
}, this); });
};
RPC.prototype._toListTX = function _toListTX(tx) { RPC.prototype._toListTX = spawn.co(function* _toListTX(tx) {
return spawn(function *() {
var i, receive, member, det, sent, received, index; var i, receive, member, det, sent, received, index;
var sendMember, recMember, sendIndex, recIndex, json; var sendMember, recMember, sendIndex, recIndex, json;
var details; var details;
@ -3717,11 +3602,9 @@ RPC.prototype._toListTX = function _toListTX(tx) {
}; };
return json; return json;
}, this); });
};
RPC.prototype.listtransactions = function listtransactions(args) { RPC.prototype.listtransactions = spawn.co(function* listtransactions(args) {
return spawn(function *() {
var i, account, count, txs, tx, json; var i, account, count, txs, tx, json;
if (args.help || args.length > 4) { if (args.help || args.length > 4) {
@ -3754,11 +3637,9 @@ RPC.prototype.listtransactions = function listtransactions(args) {
} }
return txs; return txs;
}, this); });
};
RPC.prototype.listunspent = function listunspent(args) { RPC.prototype.listunspent = spawn.co(function* listunspent(args) {
return spawn(function *() {
var minDepth = 1; var minDepth = 1;
var maxDepth = 9999999; var maxDepth = 9999999;
var out = []; var out = [];
@ -3837,8 +3718,7 @@ RPC.prototype.listunspent = function listunspent(args) {
} }
return out; return out;
}, this); });
};
RPC.prototype.lockunspent = function lockunspent(args) { RPC.prototype.lockunspent = function lockunspent(args) {
var i, unlock, outputs, output, outpoint; var i, unlock, outputs, output, outpoint;
@ -3891,8 +3771,7 @@ RPC.prototype.move = function move(args) {
Promise.reject(new Error('Not implemented.')); Promise.reject(new Error('Not implemented.'));
}; };
RPC.prototype._send = function _send(account, address, amount, subtractFee) { RPC.prototype._send = spawn.co(function* _send(account, address, amount, subtractFee) {
return spawn(function *() {
var tx, options; var tx, options;
options = { options = {
@ -3908,8 +3787,7 @@ RPC.prototype._send = function _send(account, address, amount, subtractFee) {
tx = yield this.wallet.send(options); tx = yield this.wallet.send(options);
return tx.rhash; return tx.rhash;
}, this); });
};
RPC.prototype.sendfrom = function sendfrom(args) { RPC.prototype.sendfrom = function sendfrom(args) {
var account, address, amount; var account, address, amount;
@ -3930,8 +3808,7 @@ RPC.prototype.sendfrom = function sendfrom(args) {
return this._send(account, address, amount, false); return this._send(account, address, amount, false);
}; };
RPC.prototype.sendmany = function sendmany(args) { RPC.prototype.sendmany = spawn.co(function* sendmany(args) {
return spawn(function *() {
var account, sendTo, minDepth, comment, subtractFee; var account, sendTo, minDepth, comment, subtractFee;
var i, outputs, keys, uniq, tx; var i, outputs, keys, uniq, tx;
var key, value, address, hash, output, options; var key, value, address, hash, output, options;
@ -3992,8 +3869,7 @@ RPC.prototype.sendmany = function sendmany(args) {
tx = yield this.wallet.send(options); tx = yield this.wallet.send(options);
return tx.rhash; return tx.rhash;
}, this); });
};
RPC.prototype.sendtoaddress = function sendtoaddress(args) { RPC.prototype.sendtoaddress = function sendtoaddress(args) {
var address, amount, subtractFee; var address, amount, subtractFee;
@ -4030,8 +3906,7 @@ RPC.prototype.settxfee = function settxfee(args) {
return Promise.resolve(true); return Promise.resolve(true);
}; };
RPC.prototype.signmessage = function signmessage(args) { RPC.prototype.signmessage = spawn.co(function* signmessage(args) {
return spawn(function *() {
var address, msg, sig, ring; var address, msg, sig, ring;
if (args.help || args.length !== 2) if (args.help || args.length !== 2)
@ -4059,8 +3934,7 @@ RPC.prototype.signmessage = function signmessage(args) {
sig = ring.sign(msg); sig = ring.sign(msg);
return sig.toString('base64'); return sig.toString('base64');
}, this); });
};
RPC.prototype.walletlock = function walletlock(args) { RPC.prototype.walletlock = function walletlock(args) {
if (args.help || (this.wallet.master.encrypted && args.length !== 0)) if (args.help || (this.wallet.master.encrypted && args.length !== 0))
@ -4074,8 +3948,7 @@ RPC.prototype.walletlock = function walletlock(args) {
return null; return null;
}; };
RPC.prototype.walletpassphrasechange = function walletpassphrasechange(args) { RPC.prototype.walletpassphrasechange = spawn.co(function* walletpassphrasechange(args) {
return spawn(function *() {
var old, new_; var old, new_;
if (args.help || (this.wallet.master.encrypted && args.length !== 2)) { if (args.help || (this.wallet.master.encrypted && args.length !== 2)) {
@ -4095,11 +3968,9 @@ RPC.prototype.walletpassphrasechange = function walletpassphrasechange(args) {
yield this.wallet.setPassphrase(old, new_); yield this.wallet.setPassphrase(old, new_);
return null; return null;
}, this); });
};
RPC.prototype.walletpassphrase = function walletpassphrase(args) { RPC.prototype.walletpassphrase = spawn.co(function* walletpassphrase(args) {
return spawn(function *() {
var passphrase, timeout; var passphrase, timeout;
if (args.help || (this.wallet.master.encrypted && args.length !== 2)) if (args.help || (this.wallet.master.encrypted && args.length !== 2))
@ -4120,11 +3991,9 @@ RPC.prototype.walletpassphrase = function walletpassphrase(args) {
yield this.wallet.unlock(passphrase, timeout); yield this.wallet.unlock(passphrase, timeout);
return null; return null;
}, this); });
};
RPC.prototype.importprunedfunds = function importprunedfunds(args) { RPC.prototype.importprunedfunds = spawn.co(function* importprunedfunds(args) {
return spawn(function *() {
var tx, block, label, height, added; var tx, block, label, height, added;
if (args.help || args.length < 2 || args.length > 3) { if (args.help || args.length < 2 || args.length > 3) {
@ -4166,11 +4035,9 @@ RPC.prototype.importprunedfunds = function importprunedfunds(args) {
throw new RPCError('No tracked address for TX.'); throw new RPCError('No tracked address for TX.');
return null; return null;
}, this); });
};
RPC.prototype.removeprunedfunds = function removeprunedfunds(args) { RPC.prototype.removeprunedfunds = spawn.co(function* removeprunedfunds(args) {
return spawn(function *() {
var hash, removed; var hash, removed;
if (args.help || args.length !== 1) if (args.help || args.length !== 1)
@ -4187,8 +4054,7 @@ RPC.prototype.removeprunedfunds = function removeprunedfunds(args) {
throw new RPCError('Transaction not in wallet.'); throw new RPCError('Transaction not in wallet.');
return null; return null;
}, this); });
};
RPC.prototype.getmemory = function getmemory(args) { RPC.prototype.getmemory = function getmemory(args) {
var mem; var mem;

View File

@ -44,8 +44,7 @@ function RPCClient(options) {
* @param {Function} callback - Returns [Error, Object?]. * @param {Function} callback - Returns [Error, Object?].
*/ */
RPCClient.prototype.call = function call(method, params) { RPCClient.prototype.call = spawn.co(function* call(method, params) {
return spawn(function *() {
var res = yield request.promise({ var res = yield request.promise({
method: 'POST', method: 'POST',
uri: this.uri, uri: this.uri,
@ -74,8 +73,7 @@ RPCClient.prototype.call = function call(method, params) {
} }
return res.body.result; return res.body.result;
}, this); });
};
/* /*
* Expose * Expose

View File

@ -1062,8 +1062,7 @@ HTTPServer.prototype._initIO = function _initIO() {
* @param {Function} callback * @param {Function} callback
*/ */
HTTPServer.prototype.open = function open() { HTTPServer.prototype.open = spawn.co(function* open() {
return spawn(function *() {
yield this.server.open(); yield this.server.open();
this.logger.info('HTTP server loaded.'); this.logger.info('HTTP server loaded.');
@ -1074,8 +1073,7 @@ HTTPServer.prototype.open = function open() {
} else if (!this.apiHash) { } else if (!this.apiHash) {
this.logger.warning('WARNING: Your http server is open to the world.'); this.logger.warning('WARNING: Your http server is open to the world.');
} }
}, this); });
};
/** /**
* Close the server, wait for server socket to close. * Close the server, wait for server socket to close.

View File

@ -89,8 +89,7 @@ HTTPWallet.prototype._init = function _init() {
* @param {Function} callback * @param {Function} callback
*/ */
HTTPWallet.prototype.open = function open(options) { HTTPWallet.prototype.open = spawn.co(function* open(options) {
return spawn(function *() {
var wallet; var wallet;
this.id = options.id; this.id = options.id;
@ -109,8 +108,7 @@ HTTPWallet.prototype.open = function open(options) {
yield this.client.join(this.id, wallet.token); yield this.client.join(this.id, wallet.token);
return wallet; return wallet;
}, this); });
};
/** /**
* Open the client and create a wallet. * Open the client and create a wallet.
@ -118,8 +116,7 @@ HTTPWallet.prototype.open = function open(options) {
* @param {Function} callback * @param {Function} callback
*/ */
HTTPWallet.prototype.create = function create(options) { HTTPWallet.prototype.create = spawn.co(function* create(options) {
return spawn(function *() {
var wallet; var wallet;
yield this.client.open(); yield this.client.open();
wallet = yield this.client.createWallet(options); wallet = yield this.client.createWallet(options);
@ -127,8 +124,7 @@ HTTPWallet.prototype.create = function create(options) {
id: wallet.id, id: wallet.id,
token: wallet.token token: wallet.token
}); });
}, this); });
};
/** /**
* Close the client, wait for the socket to close. * Close the client, wait for the socket to close.
@ -296,16 +292,14 @@ HTTPWallet.prototype.setPassphrase = function setPassphrase(old, new_) {
* @see Wallet#retoken * @see Wallet#retoken
*/ */
HTTPWallet.prototype.retoken = function retoken(passphrase) { HTTPWallet.prototype.retoken = spawn.co(function* retoken(passphrase) {
return spawn(function *() {
var token = yield this.client.retoken(this.id, passphrase); var token = yield this.client.retoken(this.id, passphrase);
this.token = token; this.token = token;
this.client.token = token; this.client.token = token;
return token; return token;
}, this); });
};
/* /*
* Expose * Expose

View File

@ -119,13 +119,11 @@ utils.inherits(Mempool, AsyncObject);
* @param {Function} callback * @param {Function} callback
*/ */
Mempool.prototype._open = function open() { Mempool.prototype._open = spawn.co(function* open() {
return spawn(function *() {
var size = (this.maxSize / 1024).toFixed(2); var size = (this.maxSize / 1024).toFixed(2);
yield this.chain.open(); yield this.chain.open();
this.logger.info('Mempool loaded (maxsize=%dkb).', size); this.logger.info('Mempool loaded (maxsize=%dkb).', size);
}, this); });
};
/** /**
* Close the chain, wait for the database to close. * Close the chain, wait for the database to close.
@ -155,8 +153,7 @@ Mempool.prototype._lock = function _lock(tx, force) {
* @param {Function} callback * @param {Function} callback
*/ */
Mempool.prototype.addBlock = function addBlock(block) { Mempool.prototype.addBlock = spawn.co(function* addBlock(block) {
return spawn(function *() {
var unlock = yield this._lock(); var unlock = yield this._lock();
var entries = []; var entries = [];
var i, entry, tx, hash; var i, entry, tx, hash;
@ -193,8 +190,7 @@ Mempool.prototype.addBlock = function addBlock(block) {
yield utils.wait(); yield utils.wait();
unlock(); unlock();
}, this); });
};
/** /**
* Notify the mempool that a block has been disconnected * Notify the mempool that a block has been disconnected
@ -203,8 +199,7 @@ Mempool.prototype.addBlock = function addBlock(block) {
* @param {Function} callback * @param {Function} callback
*/ */
Mempool.prototype.removeBlock = function removeBlock(block) { Mempool.prototype.removeBlock = spawn.co(function* removeBlock(block) {
return spawn(function *() {
var unlock = yield this.lock(); var unlock = yield this.lock();
var i, entry, tx, hash; var i, entry, tx, hash;
@ -233,8 +228,7 @@ Mempool.prototype.removeBlock = function removeBlock(block) {
this.rejects.reset(); this.rejects.reset();
unlock(); unlock();
}, this); });
};
/** /**
* Ensure the size of the mempool stays below 300mb. * Ensure the size of the mempool stays below 300mb.
@ -530,8 +524,7 @@ Mempool.prototype.hasReject = function hasReject(hash) {
* @param {Function} callback - Returns [{@link VerifyError}]. * @param {Function} callback - Returns [{@link VerifyError}].
*/ */
Mempool.prototype.addTX = function addTX(tx) { Mempool.prototype.addTX = spawn.co(function* addTX(tx) {
return spawn(function *() {
var unlock = yield this._lock(tx); var unlock = yield this._lock(tx);
var missing; var missing;
@ -548,8 +541,7 @@ Mempool.prototype.addTX = function addTX(tx) {
unlock(); unlock();
return missing; return missing;
}, this); });
};
/** /**
* Add a transaction to the mempool. * Add a transaction to the mempool.
@ -558,8 +550,7 @@ Mempool.prototype.addTX = function addTX(tx) {
* @param {Function} callback - Returns [{@link VerifyError}]. * @param {Function} callback - Returns [{@link VerifyError}].
*/ */
Mempool.prototype._addTX = function _addTX(tx) { Mempool.prototype._addTX = spawn.co(function* _addTX(tx) {
return spawn(function *() {
var lockFlags = constants.flags.STANDARD_LOCKTIME_FLAGS; var lockFlags = constants.flags.STANDARD_LOCKTIME_FLAGS;
var hash = tx.hash('hex'); var hash = tx.hash('hex');
var ret, entry, missing; var ret, entry, missing;
@ -667,8 +658,7 @@ Mempool.prototype._addTX = function _addTX(tx) {
'mempool full', 'mempool full',
0); 0);
} }
}, this); });
};
/** /**
* Add a transaction to the mempool without performing any * Add a transaction to the mempool without performing any
@ -680,8 +670,7 @@ Mempool.prototype._addTX = function _addTX(tx) {
* @param {Function} callback - Returns [{@link VerifyError}]. * @param {Function} callback - Returns [{@link VerifyError}].
*/ */
Mempool.prototype.addUnchecked = function addUnchecked(entry, force) { Mempool.prototype.addUnchecked = spawn.co(function* addUnchecked(entry, force) {
return spawn(function *() {
var unlock = yield this._lock(null, force); var unlock = yield this._lock(null, force);
var i, resolved, tx, orphan; var i, resolved, tx, orphan;
@ -729,8 +718,7 @@ Mempool.prototype.addUnchecked = function addUnchecked(entry, force) {
} }
unlock(); unlock();
}, this); });
};
/** /**
* Remove a transaction from the mempool. Generally * Remove a transaction from the mempool. Generally
@ -816,8 +804,7 @@ Mempool.prototype.getMinRate = function getMinRate() {
* @param {Function} callback - Returns [{@link VerifyError}]. * @param {Function} callback - Returns [{@link VerifyError}].
*/ */
Mempool.prototype.verify = function verify(entry) { Mempool.prototype.verify = spawn.co(function* verify(entry) {
return spawn(function *() {
var height = this.chain.height + 1; var height = this.chain.height + 1;
var lockFlags = flags.STANDARD_LOCKTIME_FLAGS; var lockFlags = flags.STANDARD_LOCKTIME_FLAGS;
var flags1 = flags.STANDARD_VERIFY_FLAGS; var flags1 = flags.STANDARD_VERIFY_FLAGS;
@ -963,8 +950,7 @@ Mempool.prototype.verify = function verify(entry) {
result = yield this.checkResult(tx, mandatory); result = yield this.checkResult(tx, mandatory);
assert(result, 'BUG: Verify failed for mandatory but not standard.'); assert(result, 'BUG: Verify failed for mandatory but not standard.');
} }
}, this); });
};
/** /**
* Verify inputs, return a boolean * Verify inputs, return a boolean
@ -974,8 +960,7 @@ Mempool.prototype.verify = function verify(entry) {
* @param {Function} callback * @param {Function} callback
*/ */
Mempool.prototype.checkResult = function checkResult(tx, flags) { Mempool.prototype.checkResult = spawn.co(function* checkResult(tx, flags) {
return spawn(function *() {
try { try {
yield this.checkInputs(tx, flags); yield this.checkInputs(tx, flags);
} catch (err) { } catch (err) {
@ -984,8 +969,7 @@ Mempool.prototype.checkResult = function checkResult(tx, flags) {
throw err; throw err;
} }
return true; return true;
}, this); });
};
/** /**
* Verify inputs for standard * Verify inputs for standard
@ -995,8 +979,7 @@ Mempool.prototype.checkResult = function checkResult(tx, flags) {
* @param {Function} callback * @param {Function} callback
*/ */
Mempool.prototype.checkInputs = function checkInputs(tx, flags) { Mempool.prototype.checkInputs = spawn.co(function* checkInputs(tx, flags) {
return spawn(function *() {
var result = yield tx.verifyAsync(flags); var result = yield tx.verifyAsync(flags);
if (result) if (result)
return; return;
@ -1023,8 +1006,7 @@ Mempool.prototype.checkInputs = function checkInputs(tx, flags) {
'nonstandard', 'nonstandard',
'mandatory-script-verify-flag', 'mandatory-script-verify-flag',
100); 100);
}, this); });
};
/** /**
* Count the highest number of * Count the highest number of
@ -1405,8 +1387,7 @@ Mempool.prototype.fillAllHistory = function fillAllHistory(tx) {
* @param {Function} callback - Returns [Error, {@link TX}]. * @param {Function} callback - Returns [Error, {@link TX}].
*/ */
Mempool.prototype.fillAllCoins = function fillAllCoins(tx) { Mempool.prototype.fillAllCoins = spawn.co(function* fillAllCoins(tx) {
return spawn(function *() {
var i, input, hash, index, coin; var i, input, hash, index, coin;
this.fillCoins(tx); this.fillCoins(tx);
@ -1429,8 +1410,7 @@ Mempool.prototype.fillAllCoins = function fillAllCoins(tx) {
} }
return tx; return tx;
}, this); });
};
/** /**
* Get a snapshot of all transaction hashes in the mempool. Used * Get a snapshot of all transaction hashes in the mempool. Used
@ -1483,8 +1463,7 @@ Mempool.prototype.isDoubleSpend = function isDoubleSpend(tx) {
* @param {Function} callback - Returns [Error, Number]. * @param {Function} callback - Returns [Error, Number].
*/ */
Mempool.prototype.getConfidence = function getConfidence(hash) { Mempool.prototype.getConfidence = spawn.co(function* getConfidence(hash) {
return spawn(function *() {
var tx, result; var tx, result;
if (hash instanceof bcoin.tx) { if (hash instanceof bcoin.tx) {
@ -1513,8 +1492,7 @@ Mempool.prototype.getConfidence = function getConfidence(hash) {
return constants.confidence.BUILDING; return constants.confidence.BUILDING;
return constants.confidence.UNKNOWN; return constants.confidence.UNKNOWN;
}, this); });
};
/** /**
* Map a transaction to the mempool. * Map a transaction to the mempool.

View File

@ -134,8 +134,7 @@ Miner.prototype._init = function _init() {
* @param {Function} callback * @param {Function} callback
*/ */
Miner.prototype._open = function open() { Miner.prototype._open = spawn.co(function* open() {
return spawn(function *() {
if (this.mempool) if (this.mempool)
yield this.mempool.open(); yield this.mempool.open();
else else
@ -143,8 +142,7 @@ Miner.prototype._open = function open() {
this.logger.info('Miner loaded (flags=%s).', this.logger.info('Miner loaded (flags=%s).',
this.coinbaseFlags.toString('utf8')); this.coinbaseFlags.toString('utf8'));
}, this); });
};
/** /**
* Close the miner. * Close the miner.
@ -242,8 +240,7 @@ Miner.prototype.stop = function stop() {
* @param {Function} callback - Returns [Error, {@link MinerBlock}]. * @param {Function} callback - Returns [Error, {@link MinerBlock}].
*/ */
Miner.prototype.createBlock = function createBlock(tip) { Miner.prototype.createBlock = spawn.co(function* createBlock(tip) {
return spawn(function *() {
var i, ts, attempt, txs, tx, target, version; var i, ts, attempt, txs, tx, target, version;
if (!this.loaded) if (!this.loaded)
@ -289,8 +286,7 @@ Miner.prototype.createBlock = function createBlock(tip) {
} }
return attempt; return attempt;
}, this); });
};
/** /**
* Mine a single block. * Mine a single block.
@ -298,13 +294,11 @@ Miner.prototype.createBlock = function createBlock(tip) {
* @param {Function} callback - Returns [Error, [{@link Block}]]. * @param {Function} callback - Returns [Error, [{@link Block}]].
*/ */
Miner.prototype.mineBlock = function mineBlock(tip) { Miner.prototype.mineBlock = spawn.co(function* mineBlock(tip) {
return spawn(function *() {
// Create a new block and start hashing // Create a new block and start hashing
var attempt = yield this.createBlock(tip); var attempt = yield this.createBlock(tip);
return yield attempt.mineAsync(); return yield attempt.mineAsync();
}, this); });
};
/* /*
* Expose * Expose

View File

@ -349,8 +349,7 @@ MinerBlock.prototype.sendStatus = function sendStatus() {
* @param {Function} callback - Returns [Error, {@link Block}]. * @param {Function} callback - Returns [Error, {@link Block}].
*/ */
MinerBlock.prototype.mine = function mine() { MinerBlock.prototype.mine = spawn.co(function* mine() {
return spawn(function *() {
yield this.wait(100); yield this.wait(100);
// Try to find a block: do one iteration of extraNonce // Try to find a block: do one iteration of extraNonce
@ -360,8 +359,7 @@ MinerBlock.prototype.mine = function mine() {
} }
return this.block; return this.block;
}, this); });
};
/** /**
* Wait for a timeout. * Wait for a timeout.
@ -393,8 +391,7 @@ MinerBlock.prototype.mineSync = function mineSync() {
* @param {Function} callback - Returns [Error, {@link Block}]. * @param {Function} callback - Returns [Error, {@link Block}].
*/ */
MinerBlock.prototype.mineAsync = function mineAsync() { MinerBlock.prototype.mineAsync = spawn.co(function* mineAsync() {
return spawn(function *() {
var block; var block;
if (!this.workerPool) if (!this.workerPool)
@ -405,8 +402,7 @@ MinerBlock.prototype.mineAsync = function mineAsync() {
this.workerPool.destroy(); this.workerPool.destroy();
return block; return block;
}, this); });
};
/** /**
* Destroy the minerblock. Stop mining. Clear timeout. * Destroy the minerblock. Stop mining. Clear timeout.

View File

@ -1430,8 +1430,7 @@ Peer.prototype._handleMempool = function _handleMempool(packet) {
* [Error, {@link Block}|{@link MempoolEntry}]. * [Error, {@link Block}|{@link MempoolEntry}].
*/ */
Peer.prototype._getItem = function _getItem(item) { Peer.prototype._getItem = spawn.co(function* _getItem(item) {
return spawn(function *() {
var entry = this.pool.invMap[item.hash]; var entry = this.pool.invMap[item.hash];
if (entry) { if (entry) {
@ -1472,8 +1471,7 @@ Peer.prototype._getItem = function _getItem(item) {
return; return;
return yield this.chain.db.getBlock(item.hash); return yield this.chain.db.getBlock(item.hash);
}, this); });
};
/** /**
* Handle `getdata` packet. * Handle `getdata` packet.
@ -2351,8 +2349,7 @@ Peer.prototype.reject = function reject(obj, code, reason, score) {
* @param {Function} callback * @param {Function} callback
*/ */
Peer.prototype.resolveOrphan = function resolveOrphan(tip, orphan) { Peer.prototype.resolveOrphan = spawn.co(function* resolveOrphan(tip, orphan) {
return spawn(function *() {
var root, locator; var root, locator;
assert(orphan); assert(orphan);
@ -2367,8 +2364,7 @@ Peer.prototype.resolveOrphan = function resolveOrphan(tip, orphan) {
} }
this.sendGetBlocks(locator, root); this.sendGetBlocks(locator, root);
}, this); });
};
/** /**
* Send `getheaders` to peer after building locator. * Send `getheaders` to peer after building locator.
@ -2377,12 +2373,10 @@ Peer.prototype.resolveOrphan = function resolveOrphan(tip, orphan) {
* @param {Function} callback * @param {Function} callback
*/ */
Peer.prototype.getHeaders = function getHeaders(tip, stop) { Peer.prototype.getHeaders = spawn.co(function* getHeaders(tip, stop) {
return spawn(function *() {
var locator = yield this.chain.getLocator(tip); var locator = yield this.chain.getLocator(tip);
this.sendGetHeaders(locator, stop); this.sendGetHeaders(locator, stop);
}, this); });
};
/** /**
* Send `getblocks` to peer after building locator. * Send `getblocks` to peer after building locator.
@ -2391,12 +2385,10 @@ Peer.prototype.getHeaders = function getHeaders(tip, stop) {
* @param {Function} callback * @param {Function} callback
*/ */
Peer.prototype.getBlocks = function getBlocks(tip, stop) { Peer.prototype.getBlocks = spawn.co(function* getBlocks(tip, stop) {
return spawn(function *() {
var locator = yield this.chain.getLocator(tip); var locator = yield this.chain.getLocator(tip);
this.sendGetBlocks(locator, stop); this.sendGetBlocks(locator, stop);
}, this); });
};
/** /**
* Start syncing from peer. * Start syncing from peer.

View File

@ -290,8 +290,7 @@ Pool.prototype._lock = function _lock(force) {
* @param {Function} callback * @param {Function} callback
*/ */
Pool.prototype._open = function _open() { Pool.prototype._open = spawn.co(function* _open() {
return spawn(function *() {
var ip, key; var ip, key;
try { try {
@ -322,8 +321,7 @@ Pool.prototype._open = function _open() {
return; return;
yield this.listen(); yield this.listen();
}, this); });
};
/** /**
* Close and destroy the pool. * Close and destroy the pool.
@ -331,8 +329,7 @@ Pool.prototype._open = function _open() {
* @param {Function} callback * @param {Function} callback
*/ */
Pool.prototype._close = function close() { Pool.prototype._close = spawn.co(function* close() {
return spawn(function *() {
var i, items, hashes, hash; var i, items, hashes, hash;
this.stopSync(); this.stopSync();
@ -360,8 +357,7 @@ Pool.prototype._close = function close() {
} }
yield this.unlisten(); yield this.unlisten();
}, this); });
};
/** /**
* Connect to the network. * Connect to the network.
@ -724,8 +720,7 @@ Pool.prototype.stopSync = function stopSync() {
* @param {Function} callback * @param {Function} callback
*/ */
Pool.prototype._handleHeaders = function _handleHeaders(headers, peer) { Pool.prototype._handleHeaders = spawn.co(function* _handleHeaders(headers, peer) {
return spawn(function *() {
var i, unlock, ret, header, hash, last; var i, unlock, ret, header, hash, last;
if (!this.options.headers) if (!this.options.headers)
@ -784,8 +779,7 @@ Pool.prototype._handleHeaders = function _handleHeaders(headers, peer) {
yield peer.getHeaders(last, null); yield peer.getHeaders(last, null);
unlock(); unlock();
}, this); });
};
/** /**
* Handle `inv` packet from peer (containing only BLOCK types). * Handle `inv` packet from peer (containing only BLOCK types).
@ -795,8 +789,7 @@ Pool.prototype._handleHeaders = function _handleHeaders(headers, peer) {
* @param {Function} callback * @param {Function} callback
*/ */
Pool.prototype._handleBlocks = function _handleBlocks(hashes, peer) { Pool.prototype._handleBlocks = spawn.co(function* _handleBlocks(hashes, peer) {
return spawn(function *() {
var i, hash, exists; var i, hash, exists;
assert(!this.options.headers); assert(!this.options.headers);
@ -853,8 +846,7 @@ Pool.prototype._handleBlocks = function _handleBlocks(hashes, peer) {
} }
this.scheduleRequests(peer); this.scheduleRequests(peer);
}, this); });
};
/** /**
* Handle `inv` packet from peer (containing only BLOCK types). * Handle `inv` packet from peer (containing only BLOCK types).
@ -865,8 +857,7 @@ Pool.prototype._handleBlocks = function _handleBlocks(hashes, peer) {
* @param {Function} callback * @param {Function} callback
*/ */
Pool.prototype._handleInv = function _handleInv(hashes, peer) { Pool.prototype._handleInv = spawn.co(function* _handleInv(hashes, peer) {
return spawn(function *() {
var unlock = yield this._lock(); var unlock = yield this._lock();
var i, hash; var i, hash;
@ -887,8 +878,7 @@ Pool.prototype._handleInv = function _handleInv(hashes, peer) {
this.scheduleRequests(peer); this.scheduleRequests(peer);
unlock(); unlock();
}, this); });
};
/** /**
* Handle `block` packet. Attempt to add to chain. * Handle `block` packet. Attempt to add to chain.
@ -898,8 +888,7 @@ Pool.prototype._handleInv = function _handleInv(hashes, peer) {
* @param {Function} callback * @param {Function} callback
*/ */
Pool.prototype._handleBlock = function _handleBlock(block, peer) { Pool.prototype._handleBlock = spawn.co(function* _handleBlock(block, peer) {
return spawn(function *() {
var requested; var requested;
// Fulfill the load request. // Fulfill the load request.
@ -971,8 +960,7 @@ Pool.prototype._handleBlock = function _handleBlock(block, peer) {
this.chain.height, this.chain.height,
block.rhash); block.rhash);
} }
}, this); });
};
/** /**
* Send `mempool` to all peers. * Send `mempool` to all peers.
@ -1304,8 +1292,7 @@ Pool.prototype.hasReject = function hasReject(hash) {
* @param {Function} callback * @param {Function} callback
*/ */
Pool.prototype._handleTX = function _handleTX(tx, peer) { Pool.prototype._handleTX = spawn.co(function* _handleTX(tx, peer) {
return spawn(function *() {
var i, requested, missing; var i, requested, missing;
// Fulfill the load request. // Fulfill the load request.
@ -1350,8 +1337,7 @@ Pool.prototype._handleTX = function _handleTX(tx, peer) {
} }
this.emit('tx', tx, peer); this.emit('tx', tx, peer);
}, this); });
};
/** /**
* Create a leech peer from an existing socket. * Create a leech peer from an existing socket.
@ -1517,8 +1503,7 @@ Pool.prototype.watchAddress = function watchAddress(address) {
* @param {Function} callback * @param {Function} callback
*/ */
Pool.prototype.getData = function getData(peer, type, hash) { Pool.prototype.getData = spawn.co(function* getData(peer, type, hash) {
return spawn(function *() {
var self = this; var self = this;
var item, exists; var item, exists;
@ -1554,8 +1539,7 @@ Pool.prototype.getData = function getData(peer, type, hash) {
peer.queueBlock.push(item); peer.queueBlock.push(item);
return false; return false;
}, this); });
};
/** /**
* Queue a `getdata` request to be sent. Promise * Queue a `getdata` request to be sent. Promise
@ -1581,8 +1565,7 @@ Pool.prototype.getDataSync = function getDataSync(peer, type, hash) {
* @param {Function} callback - Returns [Error, Boolean]. * @param {Function} callback - Returns [Error, Boolean].
*/ */
Pool.prototype.has = function has(peer, type, hash) { Pool.prototype.has = spawn.co(function* has(peer, type, hash) {
return spawn(function *() {
var exists = yield this.exists(type, hash); var exists = yield this.exists(type, hash);
if (exists) if (exists)
@ -1604,8 +1587,7 @@ Pool.prototype.has = function has(peer, type, hash) {
} }
return false; return false;
}, this); });
};
/** /**
* Test whether the chain or mempool has seen an item. * Test whether the chain or mempool has seen an item.
@ -1873,8 +1855,7 @@ Pool.prototype.isIgnored = function isIgnored(addr) {
* @param {Function} callback * @param {Function} callback
*/ */
Pool.prototype.getIP = function getIP() { Pool.prototype.getIP = spawn.co(function* getIP() {
return spawn(function *() {
var request, res, ip; var request, res, ip;
if (utils.isBrowser) if (utils.isBrowser)
@ -1899,16 +1880,14 @@ Pool.prototype.getIP = function getIP() {
return yield this.getIP2(); return yield this.getIP2();
return IP.normalize(ip); return IP.normalize(ip);
}, this); });
};
/** /**
* Attempt to retrieve external IP from dyndns.org. * Attempt to retrieve external IP from dyndns.org.
* @param {Function} callback * @param {Function} callback
*/ */
Pool.prototype.getIP2 = function getIP2() { Pool.prototype.getIP2 = spawn.co(function* getIP2() {
return spawn(function *() {
var request, res, ip; var request, res, ip;
if (utils.isBrowser) if (utils.isBrowser)
@ -1929,8 +1908,7 @@ Pool.prototype.getIP2 = function getIP2() {
throw new Error('Could not find IP.'); throw new Error('Could not find IP.');
return IP.normalize(ip[1]); return IP.normalize(ip[1]);
}, this); });
};
/** /**
* Peer List * Peer List

View File

@ -223,8 +223,7 @@ Fullnode.prototype._init = function _init() {
* @param {Function} callback * @param {Function} callback
*/ */
Fullnode.prototype._open = function open() { Fullnode.prototype._open = spawn.co(function* open() {
return spawn(function *() {
yield this.chain.open(); yield this.chain.open();
yield this.mempool.open(); yield this.mempool.open();
yield this.miner.open(); yield this.miner.open();
@ -244,8 +243,7 @@ Fullnode.prototype._open = function open() {
yield this.http.open(); yield this.http.open();
this.logger.info('Node is loaded.'); this.logger.info('Node is loaded.');
}, this); });
};
/** /**
* Close the node, wait for the database to close. * Close the node, wait for the database to close.
@ -253,8 +251,7 @@ Fullnode.prototype._open = function open() {
* @param {Function} callback * @param {Function} callback
*/ */
Fullnode.prototype._close = function close() { Fullnode.prototype._close = spawn.co(function* close() {
return spawn(function *() {
this.wallet = null; this.wallet = null;
if (this.http) if (this.http)
@ -267,8 +264,7 @@ Fullnode.prototype._close = function close() {
this.chain.close(); this.chain.close();
this.logger.info('Node is closed.'); this.logger.info('Node is closed.');
}, this); });
};
/** /**
* Rescan for any missed transactions. * Rescan for any missed transactions.
@ -309,8 +305,7 @@ Fullnode.prototype.broadcast = function broadcast(item, callback) {
* @param {TX} tx * @param {TX} tx
*/ */
Fullnode.prototype.sendTX = function sendTX(tx) { Fullnode.prototype.sendTX = spawn.co(function* sendTX(tx) {
return spawn(function *() {
try { try {
yield this.mempool.addTX(tx); yield this.mempool.addTX(tx);
} catch (err) { } catch (err) {
@ -327,8 +322,7 @@ Fullnode.prototype.sendTX = function sendTX(tx) {
tx = tx.toInv(); tx = tx.toInv();
return this.pool.broadcast(tx); return this.pool.broadcast(tx);
}, this); });
};
/** /**
* Listen on a server socket on * Listen on a server socket on
@ -410,8 +404,7 @@ Fullnode.prototype.getCoin = function getCoin(hash, index) {
* @param {Function} callback - Returns [Error, {@link Coin}[]]. * @param {Function} callback - Returns [Error, {@link Coin}[]].
*/ */
Fullnode.prototype.getCoinsByAddress = function getCoinsByAddress(addresses) { Fullnode.prototype.getCoinsByAddress = spawn.co(function* getCoinsByAddress(addresses) {
return spawn(function *() {
var coins = this.mempool.getCoinsByAddress(addresses); var coins = this.mempool.getCoinsByAddress(addresses);
var i, blockCoins, coin, spent; var i, blockCoins, coin, spent;
@ -426,8 +419,7 @@ Fullnode.prototype.getCoinsByAddress = function getCoinsByAddress(addresses) {
} }
return coins; return coins;
}, this); });
};
/** /**
* Retrieve transactions pertaining to an * Retrieve transactions pertaining to an
@ -436,13 +428,11 @@ Fullnode.prototype.getCoinsByAddress = function getCoinsByAddress(addresses) {
* @param {Function} callback - Returns [Error, {@link TX}[]]. * @param {Function} callback - Returns [Error, {@link TX}[]].
*/ */
Fullnode.prototype.getTXByAddress = function getTXByAddress(addresses) { Fullnode.prototype.getTXByAddress = spawn.co(function* getTXByAddress(addresses) {
return spawn(function *() {
var mempool = this.mempool.getTXByAddress(addresses); var mempool = this.mempool.getTXByAddress(addresses);
var txs = yield this.chain.db.getTXByAddress(addresses); var txs = yield this.chain.db.getTXByAddress(addresses);
return mempool.concat(txs); return mempool.concat(txs);
}, this); });
};
/** /**
* Retrieve a transaction from the mempool or chain database. * Retrieve a transaction from the mempool or chain database.

View File

@ -233,8 +233,7 @@ Node.prototype.location = function location(name) {
* @param {Function} callback * @param {Function} callback
*/ */
Node.prototype.openWallet = function openWallet() { Node.prototype.openWallet = spawn.co(function* openWallet() {
return spawn(function *() {
var options, wallet; var options, wallet;
assert(!this.wallet); assert(!this.wallet);
@ -258,8 +257,7 @@ Node.prototype.openWallet = function openWallet() {
} }
this.wallet = wallet; this.wallet = wallet;
}, this); });
};
/** /**
* Resend all pending transactions. * Resend all pending transactions.

View File

@ -147,8 +147,7 @@ SPVNode.prototype._init = function _init() {
* @param {Function} callback * @param {Function} callback
*/ */
SPVNode.prototype._open = function open(callback) { SPVNode.prototype._open = spawn.co(function* open(callback) {
return spawn(function *() {
yield this.chain.open(); yield this.chain.open();
yield this.pool.open(); yield this.pool.open();
yield this.walletdb.open(); yield this.walletdb.open();
@ -169,8 +168,7 @@ SPVNode.prototype._open = function open(callback) {
yield this.http.open(); yield this.http.open();
this.logger.info('Node is loaded.'); this.logger.info('Node is loaded.');
}, this); });
};
/** /**
* Close the node, wait for the database to close. * Close the node, wait for the database to close.
@ -178,24 +176,21 @@ SPVNode.prototype._open = function open(callback) {
* @param {Function} callback * @param {Function} callback
*/ */
SPVNode.prototype._close = function close() { SPVNode.prototype._close = spawn.co(function* close() {
return spawn(function *() {
this.wallet = null; this.wallet = null;
if (this.http) if (this.http)
yield this.http.close(); yield this.http.close();
yield this.walletdb.close(); yield this.walletdb.close();
yield this.pool.close(); yield this.pool.close();
yield this.chain.close(); yield this.chain.close();
}, this); });
};
/** /**
* Initialize p2p bloom filter for address watching. * Initialize p2p bloom filter for address watching.
* @param {Function} callback * @param {Function} callback
*/ */
SPVNode.prototype.openFilter = function openFilter() { SPVNode.prototype.openFilter = spawn.co(function* openFilter() {
return spawn(function *() {
var hashes = yield this.walletdb.getAddressHashes(); var hashes = yield this.walletdb.getAddressHashes();
var i; var i;
@ -204,8 +199,7 @@ SPVNode.prototype.openFilter = function openFilter() {
for (i = 0; i < hashes.length; i++) for (i = 0; i < hashes.length; i++)
this.pool.watch(hashes[i], 'hex'); this.pool.watch(hashes[i], 'hex');
}, this); });
};
/** /**
* Rescan for any missed transactions. * Rescan for any missed transactions.

View File

@ -53,8 +53,7 @@ AsyncObject.prototype._onClose = function _onClose() {
}); });
}; };
AsyncObject.prototype.open = function open() { AsyncObject.prototype.open = spawn.co(function* open() {
return spawn(function *() {
var err, unlock; var err, unlock;
assert(!this.closing, 'Cannot open while closing.'); assert(!this.closing, 'Cannot open while closing.');
@ -94,16 +93,14 @@ AsyncObject.prototype.open = function open() {
if (unlock) if (unlock)
unlock(); unlock();
}, this); });
};
/** /**
* Close the object (recallable). * Close the object (recallable).
* @param {Function} callback * @param {Function} callback
*/ */
AsyncObject.prototype.close = function close() { AsyncObject.prototype.close = spawn.co(function* close() {
return spawn(function *() {
var unlock, err; var unlock, err;
assert(!this.loading, 'Cannot close while loading.'); assert(!this.loading, 'Cannot close while loading.');
@ -143,8 +140,7 @@ AsyncObject.prototype.close = function close() {
if (unlock) if (unlock)
unlock(); unlock();
}, this); });
};
/** /**
* Close the object (recallable). * Close the object (recallable).

View File

@ -1,11 +1,7 @@
'use strict'; 'use strict';
// See: https://github.com/yoursnetwork/asink function exec(gen) {
function spawn(generator, self) {
return new Promise(function(resolve, reject) { return new Promise(function(resolve, reject) {
var gen = generator.call(self);
function step(value, rejection) { function step(value, rejection) {
var next; var next;
@ -38,4 +34,18 @@ function spawn(generator, self) {
}); });
} }
function spawn(generator, self) {
var gen = generator.call(self);
return exec(gen);
}
function co(generator) {
return function() {
var gen = generator.apply(this, arguments);
return exec(gen);
};
}
spawn.co = co;
module.exports = spawn; module.exports = spawn;

View File

@ -204,8 +204,7 @@ Account.MAX_LOOKAHEAD = 5;
* @param {Function} callback * @param {Function} callback
*/ */
Account.prototype.init = function init() { Account.prototype.init = spawn.co(function* init() {
return spawn(function *() {
// Waiting for more keys. // Waiting for more keys.
if (this.keys.length !== this.n - 1) { if (this.keys.length !== this.n - 1) {
assert(!this.initialized); assert(!this.initialized);
@ -218,8 +217,7 @@ Account.prototype.init = function init() {
this.initialized = true; this.initialized = true;
yield this.setDepth(1, 1); yield this.setDepth(1, 1);
}, this); });
};
/** /**
* Open the account (done after retrieval). * Open the account (done after retrieval).
@ -306,8 +304,7 @@ Account.prototype.spliceKey = function spliceKey(key) {
* @param {Function} callback * @param {Function} callback
*/ */
Account.prototype.addKey = function addKey(key) { Account.prototype.addKey = spawn.co(function* addKey(key) {
return spawn(function *() {
var result = false; var result = false;
var exists; var exists;
@ -328,8 +325,7 @@ Account.prototype.addKey = function addKey(key) {
yield this.init(); yield this.init();
return result; return result;
}, this); });
};
/** /**
* Ensure accounts are not sharing keys. * Ensure accounts are not sharing keys.
@ -337,8 +333,7 @@ Account.prototype.addKey = function addKey(key) {
* @param {Function} callback * @param {Function} callback
*/ */
Account.prototype._checkKeys = function _checkKeys() { Account.prototype._checkKeys = spawn.co(function* _checkKeys() {
return spawn(function *() {
var ring, hash, paths; var ring, hash, paths;
if (this.initialized || this.type !== Account.types.MULTISIG) if (this.initialized || this.type !== Account.types.MULTISIG)
@ -356,8 +351,7 @@ Account.prototype._checkKeys = function _checkKeys() {
return false; return false;
return paths[this.wid] != null; return paths[this.wid] != null;
}, this); });
};
/** /**
* Remove a public account key from the account (multisig). * Remove a public account key from the account (multisig).
@ -404,8 +398,7 @@ Account.prototype.createChange = function createChange() {
* @param {Function} callback - Returns [Error, {@link KeyRing}]. * @param {Function} callback - Returns [Error, {@link KeyRing}].
*/ */
Account.prototype.createAddress = function createAddress(change) { Account.prototype.createAddress = spawn.co(function* createAddress(change) {
return spawn(function *() {
var ring, lookahead; var ring, lookahead;
if (change) { if (change) {
@ -425,8 +418,7 @@ Account.prototype.createAddress = function createAddress(change) {
this.save(); this.save();
return ring; return ring;
}, this); });
};
/** /**
* Derive a receiving address at `index`. Do not increment depth. * Derive a receiving address at `index`. Do not increment depth.
@ -568,8 +560,7 @@ Account.prototype.saveAddress = function saveAddress(rings) {
* @param {Function} callback - Returns [Error, {@link KeyRing}, {@link KeyRing}]. * @param {Function} callback - Returns [Error, {@link KeyRing}, {@link KeyRing}].
*/ */
Account.prototype.setDepth = function setDepth(receiveDepth, changeDepth) { Account.prototype.setDepth = spawn.co(function* setDepth(receiveDepth, changeDepth) {
return spawn(function *() {
var rings = []; var rings = [];
var i, receive, change; var i, receive, change;
@ -607,8 +598,7 @@ Account.prototype.setDepth = function setDepth(receiveDepth, changeDepth) {
this.save(); this.save();
return [receive, change]; return [receive, change];
}, this); });
};
/** /**
* Convert the account to a more inspection-friendly object. * Convert the account to a more inspection-friendly object.

View File

@ -229,8 +229,7 @@ TXDB.layout = layout;
* @param {Function} callback * @param {Function} callback
*/ */
TXDB.prototype.open = function open() { TXDB.prototype.open = spawn.co(function* open() {
return spawn(function *() {
this.balance = yield this.getBalance(); this.balance = yield this.getBalance();
this.logger.info('TXDB loaded for %s.', this.wallet.id); this.logger.info('TXDB loaded for %s.', this.wallet.id);
this.logger.info( this.logger.info(
@ -238,8 +237,7 @@ TXDB.prototype.open = function open() {
utils.btc(this.balance.unconfirmed), utils.btc(this.balance.unconfirmed),
utils.btc(this.balance.confirmed), utils.btc(this.balance.confirmed),
utils.btc(this.balance.total)); utils.btc(this.balance.total));
}, this); });
};
/** /**
* Emit transaction event. * Emit transaction event.
@ -374,8 +372,7 @@ TXDB.prototype.iterate = function iterate(options) {
* @param {Function} callback * @param {Function} callback
*/ */
TXDB.prototype.commit = function commit() { TXDB.prototype.commit = spawn.co(function* commit() {
return spawn(function *() {
assert(this.current); assert(this.current);
try { try {
yield this.current.write(); yield this.current.write();
@ -384,8 +381,7 @@ TXDB.prototype.commit = function commit() {
throw e; throw e;
} }
this.current = null; this.current = null;
}, this); });
};
/** /**
* Map a transactions' addresses to wallet IDs. * Map a transactions' addresses to wallet IDs.
@ -406,8 +402,7 @@ TXDB.prototype.getInfo = function getInfo(tx) {
* @param {Function} callback - Returns [Error, Buffer]. * @param {Function} callback - Returns [Error, Buffer].
*/ */
TXDB.prototype._addOrphan = function _addOrphan(prevout, spender) { TXDB.prototype._addOrphan = spawn.co(function* _addOrphan(prevout, spender) {
return spawn(function *() {
var p = new BufferWriter(); var p = new BufferWriter();
var key = layout.o(prevout.hash, prevout.index); var key = layout.o(prevout.hash, prevout.index);
var data = yield this.get(key); var data = yield this.get(key);
@ -418,8 +413,7 @@ TXDB.prototype._addOrphan = function _addOrphan(prevout, spender) {
p.writeBytes(spender); p.writeBytes(spender);
this.put(key, p.render()); this.put(key, p.render());
}, this); });
};
/** /**
* Retrieve orphan list by coin ID. * Retrieve orphan list by coin ID.
@ -429,8 +423,7 @@ TXDB.prototype._addOrphan = function _addOrphan(prevout, spender) {
* @param {Function} callback - Returns [Error, {@link Orphan}]. * @param {Function} callback - Returns [Error, {@link Orphan}].
*/ */
TXDB.prototype._getOrphans = function _getOrphans(hash, index) { TXDB.prototype._getOrphans = spawn.co(function* _getOrphans(hash, index) {
return spawn(function *() {
var items = []; var items = [];
var i, orphans, orphan, tx; var i, orphans, orphan, tx;
@ -454,8 +447,7 @@ TXDB.prototype._getOrphans = function _getOrphans(hash, index) {
} }
return items; return items;
}, this); });
};
/** /**
* Retrieve coins for own inputs, remove * Retrieve coins for own inputs, remove
@ -466,8 +458,7 @@ TXDB.prototype._getOrphans = function _getOrphans(hash, index) {
* @param {Function} callback - Returns [Error]. * @param {Function} callback - Returns [Error].
*/ */
TXDB.prototype._verify = function _verify(tx, info) { TXDB.prototype._verify = spawn.co(function* _verify(tx, info) {
return spawn(function *() {
var i, input, prevout, address, coin, spent, rtx, rinfo, result; var i, input, prevout, address, coin, spent, rtx, rinfo, result;
for (i = 0; i < tx.inputs.length; i++) { for (i = 0; i < tx.inputs.length; i++) {
@ -538,8 +529,7 @@ TXDB.prototype._verify = function _verify(tx, info) {
} }
return true; return true;
}, this); });
};
/** /**
* Attempt to resolve orphans for an output. * Attempt to resolve orphans for an output.
@ -549,8 +539,7 @@ TXDB.prototype._verify = function _verify(tx, info) {
* @param {Function} callback * @param {Function} callback
*/ */
TXDB.prototype._resolveOrphans = function _resolveOrphans(tx, index) { TXDB.prototype._resolveOrphans = spawn.co(function* _resolveOrphans(tx, index) {
return spawn(function *() {
var hash = tx.hash('hex'); var hash = tx.hash('hex');
var i, orphans, coin, item, input, orphan; var i, orphans, coin, item, input, orphan;
@ -592,8 +581,7 @@ TXDB.prototype._resolveOrphans = function _resolveOrphans(tx, index) {
this.balance.sub(coin); this.balance.sub(coin);
return false; return false;
}, this); });
};
/** /**
* Add transaction, runs _confirm (separate batch) and * Add transaction, runs _confirm (separate batch) and
@ -604,8 +592,7 @@ TXDB.prototype._resolveOrphans = function _resolveOrphans(tx, index) {
* @param {Function} callback * @param {Function} callback
*/ */
TXDB.prototype.add = function add(tx, info) { TXDB.prototype.add = spawn.co(function* add(tx, info) {
return spawn(function *() {
var unlock = yield this._lock(); var unlock = yield this._lock();
var hash, path, account; var hash, path, account;
var i, result, input, output, coin; var i, result, input, output, coin;
@ -742,8 +729,7 @@ TXDB.prototype.add = function add(tx, info) {
unlock(); unlock();
return true; return true;
}, this); });
};
/** /**
* Remove spenders that have not been confirmed. We do this in the * Remove spenders that have not been confirmed. We do this in the
@ -757,8 +743,7 @@ TXDB.prototype.add = function add(tx, info) {
* @param {Function} callback - Returns [Error, Boolean]. * @param {Function} callback - Returns [Error, Boolean].
*/ */
TXDB.prototype._removeConflict = function _removeConflict(hash, ref) { TXDB.prototype._removeConflict = spawn.co(function* _removeConflict(hash, ref) {
return spawn(function *() {
var tx = yield this.getTX(hash); var tx = yield this.getTX(hash);
var info; var info;
@ -790,8 +775,7 @@ TXDB.prototype._removeConflict = function _removeConflict(hash, ref) {
info = yield this._removeRecursive(tx); info = yield this._removeRecursive(tx);
return [tx, info]; return [tx, info];
}, this); });
};
/** /**
* Remove a transaction and recursively * Remove a transaction and recursively
@ -801,8 +785,7 @@ TXDB.prototype._removeConflict = function _removeConflict(hash, ref) {
* @param {Function} callback - Returns [Error, Boolean]. * @param {Function} callback - Returns [Error, Boolean].
*/ */
TXDB.prototype._removeRecursive = function _removeRecursive(tx) { TXDB.prototype._removeRecursive = spawn.co(function* _removeRecursive(tx) {
return spawn(function *() {
var hash = tx.hash('hex'); var hash = tx.hash('hex');
var i, spent, stx, info; var i, spent, stx, info;
@ -838,8 +821,7 @@ TXDB.prototype._removeRecursive = function _removeRecursive(tx) {
yield this.commit(); yield this.commit();
return info; return info;
}, this); });
};
/** /**
* Test an entire transaction to see * Test an entire transaction to see
@ -848,8 +830,7 @@ TXDB.prototype._removeRecursive = function _removeRecursive(tx) {
* @param {Function} callback - Returns [Error, Boolean]. * @param {Function} callback - Returns [Error, Boolean].
*/ */
TXDB.prototype.isDoubleSpend = function isDoubleSpend(tx) { TXDB.prototype.isDoubleSpend = spawn.co(function* isDoubleSpend(tx) {
return spawn(function *() {
var i, input, prevout, spent; var i, input, prevout, spent;
for (i = 0; i < tx.inputs.length; i++) { for (i = 0; i < tx.inputs.length; i++) {
@ -861,8 +842,7 @@ TXDB.prototype.isDoubleSpend = function isDoubleSpend(tx) {
} }
return false; return false;
}, this); });
};
/** /**
* Test a whether a coin has been spent. * Test a whether a coin has been spent.
@ -888,8 +868,7 @@ TXDB.prototype.isSpent = function isSpent(hash, index) {
* transaction was confirmed, or should be ignored. * transaction was confirmed, or should be ignored.
*/ */
TXDB.prototype._confirm = function _confirm(tx, info) { TXDB.prototype._confirm = spawn.co(function* _confirm(tx, info) {
return spawn(function *() {
var hash = tx.hash('hex'); var hash = tx.hash('hex');
var i, account, existing, output, coin; var i, account, existing, output, coin;
var address, key; var address, key;
@ -975,8 +954,7 @@ TXDB.prototype._confirm = function _confirm(tx, info) {
this.emit('confirmed', tx, info); this.emit('confirmed', tx, info);
return true; return true;
}, this); });
};
/** /**
* Remove a transaction from the database. Disconnect inputs. * Remove a transaction from the database. Disconnect inputs.
@ -984,8 +962,7 @@ TXDB.prototype._confirm = function _confirm(tx, info) {
* @param {Function} callback - Returns [Error]. * @param {Function} callback - Returns [Error].
*/ */
TXDB.prototype.remove = function remove(hash, force) { TXDB.prototype.remove = spawn.co(function* remove(hash, force) {
return spawn(function *() {
var unlock = yield this._lock(force); var unlock = yield this._lock(force);
var info = yield this._removeRecursive(); var info = yield this._removeRecursive();
@ -995,8 +972,7 @@ TXDB.prototype.remove = function remove(hash, force) {
return; return;
return info; return info;
}, this); });
};
/** /**
* Remove a transaction from the database, but do not * Remove a transaction from the database, but do not
@ -1006,15 +982,13 @@ TXDB.prototype.remove = function remove(hash, force) {
* @param {Function} callback - Returns [Error]. * @param {Function} callback - Returns [Error].
*/ */
TXDB.prototype._lazyRemove = function lazyRemove(tx) { TXDB.prototype._lazyRemove = spawn.co(function* lazyRemove(tx) {
return spawn(function *() {
var info = yield this.getInfo(tx); var info = yield this.getInfo(tx);
if (!info) if (!info)
return; return;
return yield this._remove(tx, info); return yield this._remove(tx, info);
}, this); });
};
/** /**
* Remove a transaction from the database. Disconnect inputs. * Remove a transaction from the database. Disconnect inputs.
@ -1024,8 +998,7 @@ TXDB.prototype._lazyRemove = function lazyRemove(tx) {
* @param {Function} callback - Returns [Error]. * @param {Function} callback - Returns [Error].
*/ */
TXDB.prototype._remove = function remove(tx, info) { TXDB.prototype._remove = spawn.co(function* remove(tx, info) {
return spawn(function *() {
var hash = tx.hash('hex'); var hash = tx.hash('hex');
var i, path, account, key, prevout; var i, path, account, key, prevout;
var address, input, output, coin; var address, input, output, coin;
@ -1104,8 +1077,7 @@ TXDB.prototype._remove = function remove(tx, info) {
this.emit('remove tx', tx, info); this.emit('remove tx', tx, info);
return info; return info;
}, this); });
};
/** /**
* Unconfirm a transaction. This is usually necessary after a reorg. * Unconfirm a transaction. This is usually necessary after a reorg.
@ -1113,8 +1085,7 @@ TXDB.prototype._remove = function remove(tx, info) {
* @param {Function} callback * @param {Function} callback
*/ */
TXDB.prototype.unconfirm = function unconfirm(hash, force) { TXDB.prototype.unconfirm = spawn.co(function* unconfirm(hash, force) {
return spawn(function *() {
var unlock = yield this._lock(force); var unlock = yield this._lock(force);
var tx, info, result; var tx, info, result;
@ -1161,8 +1132,7 @@ TXDB.prototype.unconfirm = function unconfirm(hash, force) {
unlock(); unlock();
return result; return result;
}, this); });
};
/** /**
* Unconfirm a transaction. This is usually necessary after a reorg. * Unconfirm a transaction. This is usually necessary after a reorg.
@ -1171,8 +1141,7 @@ TXDB.prototype.unconfirm = function unconfirm(hash, force) {
* @param {Function} callback * @param {Function} callback
*/ */
TXDB.prototype._unconfirm = function unconfirm(tx, info) { TXDB.prototype._unconfirm = spawn.co(function* unconfirm(tx, info) {
return spawn(function *() {
var hash = tx.hash('hex'); var hash = tx.hash('hex');
var height = tx.height; var height = tx.height;
var i, account, output, key, coin; var i, account, output, key, coin;
@ -1219,8 +1188,7 @@ TXDB.prototype._unconfirm = function unconfirm(tx, info) {
this.emit('unconfirmed', tx, info); this.emit('unconfirmed', tx, info);
return info; return info;
}, this); });
};
/** /**
* Lock all coins in a transaction. * Lock all coins in a transaction.
@ -1507,8 +1475,7 @@ TXDB.prototype.getRangeHashes = function getRangeHashes(account, options) {
* @param {Function} callback - Returns [Error, {@link TX}[]]. * @param {Function} callback - Returns [Error, {@link TX}[]].
*/ */
TXDB.prototype.getRange = function getRange(account, options) { TXDB.prototype.getRange = spawn.co(function* getRange(account, options) {
return spawn(function *() {
var txs = []; var txs = [];
var i, hashes, hash, tx; var i, hashes, hash, tx;
@ -1530,8 +1497,7 @@ TXDB.prototype.getRange = function getRange(account, options) {
} }
return txs; return txs;
}, this); });
};
/** /**
* Get last N transactions. * Get last N transactions.
@ -1578,8 +1544,7 @@ TXDB.prototype.getHistory = function getHistory(account) {
* @param {Function} callback - Returns [Error, {@link TX}[]]. * @param {Function} callback - Returns [Error, {@link TX}[]].
*/ */
TXDB.prototype.getAccountHistory = function getAccountHistory(account) { TXDB.prototype.getAccountHistory = spawn.co(function* getAccountHistory(account) {
return spawn(function *() {
var txs = []; var txs = [];
var i, hashes, hash, tx; var i, hashes, hash, tx;
@ -1596,8 +1561,7 @@ TXDB.prototype.getAccountHistory = function getAccountHistory(account) {
} }
return sortTX(txs); return sortTX(txs);
}, this); });
};
/** /**
* Get unconfirmed transactions. * Get unconfirmed transactions.
@ -1605,8 +1569,7 @@ TXDB.prototype.getAccountHistory = function getAccountHistory(account) {
* @param {Function} callback - Returns [Error, {@link TX}[]]. * @param {Function} callback - Returns [Error, {@link TX}[]].
*/ */
TXDB.prototype.getUnconfirmed = function getUnconfirmed(account) { TXDB.prototype.getUnconfirmed = spawn.co(function* getUnconfirmed(account) {
return spawn(function *() {
var txs = []; var txs = [];
var i, hashes, hash, tx; var i, hashes, hash, tx;
@ -1623,8 +1586,7 @@ TXDB.prototype.getUnconfirmed = function getUnconfirmed(account) {
} }
return sortTX(txs); return sortTX(txs);
}, this); });
};
/** /**
* Get coins. * Get coins.
@ -1664,8 +1626,7 @@ TXDB.prototype.getCoins = function getCoins(account) {
* @param {Function} callback - Returns [Error, {@link Coin}[]]. * @param {Function} callback - Returns [Error, {@link Coin}[]].
*/ */
TXDB.prototype.getAccountCoins = function getCoins(account) { TXDB.prototype.getAccountCoins = spawn.co(function* getCoins(account) {
return spawn(function *() {
var coins = []; var coins = [];
var i, hashes, key, coin; var i, hashes, key, coin;
@ -1680,8 +1641,7 @@ TXDB.prototype.getAccountCoins = function getCoins(account) {
} }
return coins; return coins;
}, this); });
};
/** /**
* Fill a transaction with coins (all historical coins). * Fill a transaction with coins (all historical coins).
@ -1718,8 +1678,7 @@ TXDB.prototype.fillHistory = function fillHistory(tx) {
* @param {Function} callback - Returns [Error, {@link TX}]. * @param {Function} callback - Returns [Error, {@link TX}].
*/ */
TXDB.prototype.fillCoins = function fillCoins(tx) { TXDB.prototype.fillCoins = spawn.co(function* fillCoins(tx) {
return spawn(function *() {
var i, input, prevout, coin; var i, input, prevout, coin;
if (tx.isCoinbase()) if (tx.isCoinbase())
@ -1739,8 +1698,7 @@ TXDB.prototype.fillCoins = function fillCoins(tx) {
} }
return tx; return tx;
}, this); });
};
/** /**
* Get transaction. * Get transaction.
@ -1760,16 +1718,14 @@ TXDB.prototype.getTX = function getTX(hash) {
* @param {Function} callback - Returns [Error, {@link TXDetails}]. * @param {Function} callback - Returns [Error, {@link TXDetails}].
*/ */
TXDB.prototype.getDetails = function getDetails(hash) { TXDB.prototype.getDetails = spawn.co(function* getDetails(hash) {
return spawn(function *() {
var tx = yield this.getTX(hash); var tx = yield this.getTX(hash);
if (!tx) if (!tx)
return; return;
return yield this.toDetails(tx); return yield this.toDetails(tx);
}, this); });
};
/** /**
* Convert transaction to transaction details. * Convert transaction to transaction details.
@ -1777,8 +1733,7 @@ TXDB.prototype.getDetails = function getDetails(hash) {
* @param {Function} callback * @param {Function} callback
*/ */
TXDB.prototype.toDetails = function toDetails(tx) { TXDB.prototype.toDetails = spawn.co(function* toDetails(tx) {
return spawn(function *() {
var i, out, txs, details, info; var i, out, txs, details, info;
if (Array.isArray(tx)) { if (Array.isArray(tx)) {
@ -1806,8 +1761,7 @@ TXDB.prototype.toDetails = function toDetails(tx) {
throw new Error('Info not found.'); throw new Error('Info not found.');
return info.toDetails(); return info.toDetails();
}, this); });
};
/** /**
* Test whether the database has a transaction. * Test whether the database has a transaction.
@ -1874,8 +1828,7 @@ TXDB.prototype.getSpentCoin = function getSpentCoin(spent, prevout) {
* @param {Function} callback * @param {Function} callback
*/ */
TXDB.prototype.updateSpentCoin = function updateSpentCoin(tx, i) { TXDB.prototype.updateSpentCoin = spawn.co(function* updateSpentCoin(tx, i) {
return spawn(function *() {
var prevout = bcoin.outpoint.fromTX(tx, i); var prevout = bcoin.outpoint.fromTX(tx, i);
var spent = yield this.isSpent(prevout.hash, prevout.index); var spent = yield this.isSpent(prevout.hash, prevout.index);
var coin; var coin;
@ -1891,8 +1844,7 @@ TXDB.prototype.updateSpentCoin = function updateSpentCoin(tx, i) {
coin.height = tx.height; coin.height = tx.height;
this.put(layout.d(spent.hash, spent.index), coin.toRaw()); this.put(layout.d(spent.hash, spent.index), coin.toRaw());
}, this); });
};
/** /**
* Test whether the database has a transaction. * Test whether the database has a transaction.
@ -1915,8 +1867,7 @@ TXDB.prototype.hasCoin = function hasCoin(hash, index) {
* @param {Function} callback - Returns [Error, {@link Balance}]. * @param {Function} callback - Returns [Error, {@link Balance}].
*/ */
TXDB.prototype.getBalance = function getBalance(account) { TXDB.prototype.getBalance = spawn.co(function* getBalance(account) {
return spawn(function *() {
var self = this; var self = this;
var balance; var balance;
@ -1946,8 +1897,7 @@ TXDB.prototype.getBalance = function getBalance(account) {
}); });
return balance; return balance;
}, this); });
};
/** /**
* Calculate balance by account. * Calculate balance by account.
@ -1955,8 +1905,7 @@ TXDB.prototype.getBalance = function getBalance(account) {
* @param {Function} callback - Returns [Error, {@link Balance}]. * @param {Function} callback - Returns [Error, {@link Balance}].
*/ */
TXDB.prototype.getAccountBalance = function getBalance(account) { TXDB.prototype.getAccountBalance = spawn.co(function* getBalance(account) {
return spawn(function *() {
var balance = new Balance(this.wallet); var balance = new Balance(this.wallet);
var i, key, coin, hashes, hash, data; var i, key, coin, hashes, hash, data;
@ -1983,8 +1932,7 @@ TXDB.prototype.getAccountBalance = function getBalance(account) {
} }
return balance; return balance;
}, this); });
};
/** /**
* @param {Number?} account * @param {Number?} account
@ -1992,8 +1940,7 @@ TXDB.prototype.getAccountBalance = function getBalance(account) {
* @param {Function} callback * @param {Function} callback
*/ */
TXDB.prototype.zap = function zap(account, age) { TXDB.prototype.zap = spawn.co(function* zap(account, age) {
return spawn(function *() {
var unlock = yield this._lock(); var unlock = yield this._lock();
var i, txs, tx, hash; var i, txs, tx, hash;
@ -2021,8 +1968,7 @@ TXDB.prototype.zap = function zap(account, age) {
} }
unlock(); unlock();
}, this); });
};
/** /**
* Abandon transaction. * Abandon transaction.
@ -2030,14 +1976,12 @@ TXDB.prototype.zap = function zap(account, age) {
* @param {Function} callback * @param {Function} callback
*/ */
TXDB.prototype.abandon = function abandon(hash) { TXDB.prototype.abandon = spawn.co(function* abandon(hash) {
return spawn(function *() {
var result = yield this.has(layout.p(hash)); var result = yield this.has(layout.p(hash));
if (!result) if (!result)
throw new Error('TX not eligible.'); throw new Error('TX not eligible.');
return yield this.remove(hash); return yield this.remove(hash);
}, this); });
};
/* /*
* Balance * Balance

View File

@ -179,8 +179,7 @@ Wallet.fromOptions = function fromOptions(db, options) {
* @param {Function} callback * @param {Function} callback
*/ */
Wallet.prototype.init = function init(options) { Wallet.prototype.init = spawn.co(function* init(options) {
return spawn(function *() {
var account; var account;
assert(!this.initialized); assert(!this.initialized);
@ -197,16 +196,14 @@ Wallet.prototype.init = function init(options) {
this.logger.info('Wallet initialized (%s).', this.id); this.logger.info('Wallet initialized (%s).', this.id);
yield this.tx.open(); yield this.tx.open();
}, this); });
};
/** /**
* Open wallet (done after retrieval). * Open wallet (done after retrieval).
* @param {Function} callback * @param {Function} callback
*/ */
Wallet.prototype.open = function open() { Wallet.prototype.open = spawn.co(function* open() {
return spawn(function *() {
var account; var account;
assert(this.initialized); assert(this.initialized);
@ -221,8 +218,7 @@ Wallet.prototype.open = function open() {
this.logger.info('Wallet opened (%s).', this.id); this.logger.info('Wallet opened (%s).', this.id);
yield this.tx.open(); yield this.tx.open();
}, this); });
};
/** /**
* Close the wallet, unregister with the database. * Close the wallet, unregister with the database.
@ -248,8 +244,7 @@ Wallet.prototype.destroy = function destroy() {
* @param {Function} callback * @param {Function} callback
*/ */
Wallet.prototype.addKey = function addKey(account, key) { Wallet.prototype.addKey = spawn.co(function* addKey(account, key) {
return spawn(function *() {
var unlock = yield this._lockWrite(); var unlock = yield this._lockWrite();
var result; var result;
@ -282,8 +277,7 @@ Wallet.prototype.addKey = function addKey(account, key) {
unlock(); unlock();
return result; return result;
}, this); });
};
/** /**
* Remove a public account key from the wallet (multisig). * Remove a public account key from the wallet (multisig).
@ -292,8 +286,7 @@ Wallet.prototype.addKey = function addKey(account, key) {
* @param {Function} callback * @param {Function} callback
*/ */
Wallet.prototype.removeKey = function removeKey(account, key) { Wallet.prototype.removeKey = spawn.co(function* removeKey(account, key) {
return spawn(function *() {
var unlock = yield this._lockWrite(); var unlock = yield this._lockWrite();
var result; var result;
@ -326,8 +319,7 @@ Wallet.prototype.removeKey = function removeKey(account, key) {
unlock(); unlock();
return result; return result;
}, this); });
};
/** /**
* Change or set master key's passphrase. * Change or set master key's passphrase.
@ -336,8 +328,7 @@ Wallet.prototype.removeKey = function removeKey(account, key) {
* @param {Function} callback * @param {Function} callback
*/ */
Wallet.prototype.setPassphrase = function setPassphrase(old, new_) { Wallet.prototype.setPassphrase = spawn.co(function* setPassphrase(old, new_) {
return spawn(function *() {
var unlock = yield this._lockWrite(); var unlock = yield this._lockWrite();
if (!new_) { if (!new_) {
@ -359,8 +350,7 @@ Wallet.prototype.setPassphrase = function setPassphrase(old, new_) {
this.save(); this.save();
yield this.commit(); yield this.commit();
unlock(); unlock();
}, this); });
};
/** /**
* Generate a new token. * Generate a new token.
@ -368,8 +358,7 @@ Wallet.prototype.setPassphrase = function setPassphrase(old, new_) {
* @param {Function} callback * @param {Function} callback
*/ */
Wallet.prototype.retoken = function retoken(passphrase) { Wallet.prototype.retoken = spawn.co(function* retoken(passphrase) {
return spawn(function *() {
var unlock = yield this._lockWrite(); var unlock = yield this._lockWrite();
var master; var master;
@ -389,8 +378,7 @@ Wallet.prototype.retoken = function retoken(passphrase) {
unlock(); unlock();
return this.token; return this.token;
}, this); });
};
/** /**
* Lock the wallet, destroy decrypted key. * Lock the wallet, destroy decrypted key.
@ -471,8 +459,7 @@ Wallet.prototype.getToken = function getToken(master, nonce) {
* @param {Function} callback - Returns [Error, {@link Account}]. * @param {Function} callback - Returns [Error, {@link Account}].
*/ */
Wallet.prototype.createAccount = function createAccount(options) { Wallet.prototype.createAccount = spawn.co(function* createAccount(options) {
return spawn(function *() {
var unlock = yield this._lockWrite(); var unlock = yield this._lockWrite();
var passphrase = options.passphrase; var passphrase = options.passphrase;
var timeout = options.timeout; var timeout = options.timeout;
@ -524,8 +511,7 @@ Wallet.prototype.createAccount = function createAccount(options) {
unlock(); unlock();
return account; return account;
}, this); });
};
/** /**
* Ensure an account. Requires passphrase if master key is encrypted. * Ensure an account. Requires passphrase if master key is encrypted.
@ -533,8 +519,7 @@ Wallet.prototype.createAccount = function createAccount(options) {
* @param {Function} callback - Returns [Error, {@link Account}]. * @param {Function} callback - Returns [Error, {@link Account}].
*/ */
Wallet.prototype.ensureAccount = function ensureAccount(options) { Wallet.prototype.ensureAccount = spawn.co(function* ensureAccount(options) {
return spawn(function *() {
var account = options.account; var account = options.account;
var exists; var exists;
@ -547,8 +532,7 @@ Wallet.prototype.ensureAccount = function ensureAccount(options) {
return yield this.getAccount(account); return yield this.getAccount(account);
return this.createAccount(options); return this.createAccount(options);
}, this); });
};
/** /**
* List account names and indexes from the db. * List account names and indexes from the db.
@ -574,8 +558,7 @@ Wallet.prototype.getAddressHashes = function getAddressHashes() {
* @param {Function} callback - Returns [Error, {@link Account}]. * @param {Function} callback - Returns [Error, {@link Account}].
*/ */
Wallet.prototype.getAccount = function getAccount(account) { Wallet.prototype.getAccount = spawn.co(function* getAccount(account) {
return spawn(function *() {
if (this.account) { if (this.account) {
if (account === 0 || account === 'default') if (account === 0 || account === 'default')
return this.account; return this.account;
@ -590,8 +573,7 @@ Wallet.prototype.getAccount = function getAccount(account) {
account.id = this.id; account.id = this.id;
return account; return account;
}, this); });
};
/** /**
* Test whether an account exists. * Test whether an account exists.
@ -630,8 +612,7 @@ Wallet.prototype.createChange = function createChange(account) {
* @param {Function} callback - Returns [Error, {@link KeyRing}]. * @param {Function} callback - Returns [Error, {@link KeyRing}].
*/ */
Wallet.prototype.createAddress = function createAddress(account, change) { Wallet.prototype.createAddress = spawn.co(function* createAddress(account, change) {
return spawn(function *() {
var unlock = yield this._lockWrite(); var unlock = yield this._lockWrite();
var result; var result;
@ -669,8 +650,7 @@ Wallet.prototype.createAddress = function createAddress(account, change) {
unlock(); unlock();
return result; return result;
}, this); });
};
/** /**
* Save the wallet to the database. Necessary * Save the wallet to the database. Necessary
@ -728,8 +708,7 @@ Wallet.prototype.hasAddress = function hasAddress(address) {
* @param {Function} callback - Returns [Error, {@link Path}]. * @param {Function} callback - Returns [Error, {@link Path}].
*/ */
Wallet.prototype.getPath = function getPath(address) { Wallet.prototype.getPath = spawn.co(function* getPath(address) {
return spawn(function *() {
var hash = bcoin.address.getHash(address, 'hex'); var hash = bcoin.address.getHash(address, 'hex');
var path; var path;
@ -744,8 +723,7 @@ Wallet.prototype.getPath = function getPath(address) {
path.id = this.id; path.id = this.id;
return path; return path;
}, this); });
};
/** /**
* Get all wallet paths. * Get all wallet paths.
@ -753,8 +731,7 @@ Wallet.prototype.getPath = function getPath(address) {
* @param {Function} callback - Returns [Error, {@link Path}]. * @param {Function} callback - Returns [Error, {@link Path}].
*/ */
Wallet.prototype.getPaths = function getPaths(account) { Wallet.prototype.getPaths = spawn.co(function* getPaths(account) {
return spawn(function *() {
var out = []; var out = [];
var i, account, paths, path; var i, account, paths, path;
@ -770,8 +747,7 @@ Wallet.prototype.getPaths = function getPaths(account) {
} }
return out; return out;
}, this); });
};
/** /**
* Import a keyring (will not exist on derivation chain). * Import a keyring (will not exist on derivation chain).
@ -782,8 +758,7 @@ Wallet.prototype.getPaths = function getPaths(account) {
* @param {Function} callback * @param {Function} callback
*/ */
Wallet.prototype.importKey = function importKey(account, ring, passphrase) { Wallet.prototype.importKey = spawn.co(function* importKey(account, ring, passphrase) {
return spawn(function *() {
var unlock = yield this._lockWrite(); var unlock = yield this._lockWrite();
var exists, account, raw, path; var exists, account, raw, path;
@ -851,8 +826,7 @@ Wallet.prototype.importKey = function importKey(account, ring, passphrase) {
yield this.commit(); yield this.commit();
unlock(); unlock();
}, this); });
};
/** /**
* Fill a transaction with inputs, estimate * Fill a transaction with inputs, estimate
@ -878,8 +852,7 @@ Wallet.prototype.importKey = function importKey(account, ring, passphrase) {
* fee from existing outputs rather than adding more inputs. * fee from existing outputs rather than adding more inputs.
*/ */
Wallet.prototype.fund = function fund(tx, options, force) { Wallet.prototype.fund = spawn.co(function* fund(tx, options, force) {
return spawn(function *() {
var unlock = yield this._lockFund(force); var unlock = yield this._lockFund(force);
var rate, account, coins; var rate, account, coins;
@ -940,8 +913,7 @@ Wallet.prototype.fund = function fund(tx, options, force) {
} finally { } finally {
unlock(); unlock();
} }
}, this); });
};
/** /**
* Build a transaction, fill it with outputs and inputs, * Build a transaction, fill it with outputs and inputs,
@ -952,8 +924,7 @@ Wallet.prototype.fund = function fund(tx, options, force) {
* @param {Function} callback - Returns [Error, {@link MTX}]. * @param {Function} callback - Returns [Error, {@link MTX}].
*/ */
Wallet.prototype.createTX = function createTX(options, force) { Wallet.prototype.createTX = spawn.co(function* createTX(options, force) {
return spawn(function *() {
var outputs = options.outputs; var outputs = options.outputs;
var i, tx, total; var i, tx, total;
@ -992,8 +963,7 @@ Wallet.prototype.createTX = function createTX(options, force) {
throw new Error('template failed.'); throw new Error('template failed.');
return tx; return tx;
}, this); });
};
/** /**
* Build a transaction, fill it with outputs and inputs, * Build a transaction, fill it with outputs and inputs,
@ -1005,8 +975,7 @@ Wallet.prototype.createTX = function createTX(options, force) {
* @param {Function} callback - Returns [Error, {@link TX}]. * @param {Function} callback - Returns [Error, {@link TX}].
*/ */
Wallet.prototype.send = function send(options) { Wallet.prototype.send = spawn.co(function* send(options) {
return spawn(function *() {
var unlock = yield this._lockFund(); var unlock = yield this._lockFund();
var tx; var tx;
@ -1038,16 +1007,14 @@ Wallet.prototype.send = function send(options) {
unlock(); unlock();
return tx; return tx;
}, this); });
};
/** /**
* Resend pending wallet transactions. * Resend pending wallet transactions.
* @param {Function} callback * @param {Function} callback
*/ */
Wallet.prototype.resend = function resend() { Wallet.prototype.resend = spawn.co(function* resend() {
return spawn(function *() {
var txs = yield this.getUnconfirmed(); var txs = yield this.getUnconfirmed();
var i; var i;
@ -1058,8 +1025,7 @@ Wallet.prototype.resend = function resend() {
this.db.emit('send', txs[i]); this.db.emit('send', txs[i]);
return txs; return txs;
}, this); });
};
/** /**
* Derive necessary addresses for signing a transaction. * Derive necessary addresses for signing a transaction.
@ -1068,8 +1034,7 @@ Wallet.prototype.resend = function resend() {
* @param {Function} callback - Returns [Error, {@link KeyRing}[]]. * @param {Function} callback - Returns [Error, {@link KeyRing}[]].
*/ */
Wallet.prototype.deriveInputs = function deriveInputs(tx) { Wallet.prototype.deriveInputs = spawn.co(function* deriveInputs(tx) {
return spawn(function *() {
var rings = []; var rings = [];
var i, paths, path, account, ring; var i, paths, path, account, ring;
@ -1089,8 +1054,7 @@ Wallet.prototype.deriveInputs = function deriveInputs(tx) {
} }
return rings; return rings;
}, this); });
};
/** /**
* Retrieve a single keyring by address. * Retrieve a single keyring by address.
@ -1098,8 +1062,7 @@ Wallet.prototype.deriveInputs = function deriveInputs(tx) {
* @param {Function} callback * @param {Function} callback
*/ */
Wallet.prototype.getKeyRing = function getKeyRing(address) { Wallet.prototype.getKeyRing = spawn.co(function* getKeyRing(address) {
return spawn(function *() {
var hash = bcoin.address.getHash(address, 'hex'); var hash = bcoin.address.getHash(address, 'hex');
var path, account; var path, account;
@ -1117,8 +1080,7 @@ Wallet.prototype.getKeyRing = function getKeyRing(address) {
return; return;
return account.derivePath(path, this.master); return account.derivePath(path, this.master);
}, this); });
};
/** /**
* Map input addresses to paths. * Map input addresses to paths.
@ -1126,8 +1088,7 @@ Wallet.prototype.getKeyRing = function getKeyRing(address) {
* @param {Function} callback - Returns [Error, {@link Path}[]]. * @param {Function} callback - Returns [Error, {@link Path}[]].
*/ */
Wallet.prototype.getInputPaths = function getInputPaths(tx) { Wallet.prototype.getInputPaths = spawn.co(function* getInputPaths(tx) {
return spawn(function *() {
var paths = []; var paths = [];
var hashes = []; var hashes = [];
var i, hash, path; var i, hash, path;
@ -1157,8 +1118,7 @@ Wallet.prototype.getInputPaths = function getInputPaths(tx) {
} }
return paths; return paths;
}, this); });
};
/** /**
* Map output addresses to paths. * Map output addresses to paths.
@ -1166,8 +1126,7 @@ Wallet.prototype.getInputPaths = function getInputPaths(tx) {
* @param {Function} callback - Returns [Error, {@link Path}[]]. * @param {Function} callback - Returns [Error, {@link Path}[]].
*/ */
Wallet.prototype.getOutputPaths = function getOutputPaths(tx) { Wallet.prototype.getOutputPaths = spawn.co(function* getOutputPaths(tx) {
return spawn(function *() {
var paths = []; var paths = [];
var hashes = []; var hashes = [];
var i, hash, path; var i, hash, path;
@ -1188,8 +1147,7 @@ Wallet.prototype.getOutputPaths = function getOutputPaths(tx) {
} }
return paths; return paths;
}, this); });
};
/** /**
* Sync address depths based on a transaction's outputs. * Sync address depths based on a transaction's outputs.
@ -1200,8 +1158,7 @@ Wallet.prototype.getOutputPaths = function getOutputPaths(tx) {
* (true if new addresses were allocated). * (true if new addresses were allocated).
*/ */
Wallet.prototype.syncOutputDepth = function syncOutputDepth(info) { Wallet.prototype.syncOutputDepth = spawn.co(function* syncOutputDepth(info) {
return spawn(function *() {
var unlock = yield this._lockWrite(); var unlock = yield this._lockWrite();
var receive = []; var receive = [];
var accounts = {}; var accounts = {};
@ -1279,8 +1236,7 @@ Wallet.prototype.syncOutputDepth = function syncOutputDepth(info) {
unlock(); unlock();
return receive; return receive;
}, this); });
};
/** /**
* Emit balance events after a tx is saved. * Emit balance events after a tx is saved.
@ -1290,8 +1246,7 @@ Wallet.prototype.syncOutputDepth = function syncOutputDepth(info) {
* @param {Function} callback * @param {Function} callback
*/ */
Wallet.prototype.updateBalances = function updateBalances() { Wallet.prototype.updateBalances = spawn.co(function* updateBalances() {
return spawn(function *() {
var balance; var balance;
if (this.db.listeners('balance').length === 0 if (this.db.listeners('balance').length === 0
@ -1303,8 +1258,7 @@ Wallet.prototype.updateBalances = function updateBalances() {
this.db.emit('balance', this.id, balance); this.db.emit('balance', this.id, balance);
this.emit('balance', balance); this.emit('balance', balance);
}, this); });
};
/** /**
* Derive new addresses and emit balance. * Derive new addresses and emit balance.
@ -1314,12 +1268,10 @@ Wallet.prototype.updateBalances = function updateBalances() {
* @param {Function} callback * @param {Function} callback
*/ */
Wallet.prototype.handleTX = function handleTX(info) { Wallet.prototype.handleTX = spawn.co(function* handleTX(info) {
return spawn(function *() {
yield this.syncOutputDepth(info); yield this.syncOutputDepth(info);
yield this.updateBalances(); yield this.updateBalances();
}, this); });
};
/** /**
* Get a redeem script or witness script by hash. * Get a redeem script or witness script by hash.
@ -1327,8 +1279,7 @@ Wallet.prototype.handleTX = function handleTX(info) {
* @returns {Script} * @returns {Script}
*/ */
Wallet.prototype.getRedeem = function getRedeem(hash) { Wallet.prototype.getRedeem = spawn.co(function* getRedeem(hash) {
return spawn(function *() {
var ring; var ring;
if (typeof hash === 'string') if (typeof hash === 'string')
@ -1340,8 +1291,7 @@ Wallet.prototype.getRedeem = function getRedeem(hash) {
return; return;
return ring.getRedeem(hash); return ring.getRedeem(hash);
}, this); });
};
/** /**
* Build input scripts templates for a transaction (does not * Build input scripts templates for a transaction (does not
@ -1352,8 +1302,7 @@ Wallet.prototype.getRedeem = function getRedeem(hash) {
* (total number of scripts built). * (total number of scripts built).
*/ */
Wallet.prototype.template = function template(tx) { Wallet.prototype.template = spawn.co(function* template(tx) {
return spawn(function *() {
var total = 0; var total = 0;
var i, rings, ring; var i, rings, ring;
@ -1365,8 +1314,7 @@ Wallet.prototype.template = function template(tx) {
} }
return total; return total;
}, this); });
};
/** /**
* Build input scripts and sign inputs for a transaction. Only attempts * Build input scripts and sign inputs for a transaction. Only attempts
@ -1377,8 +1325,7 @@ Wallet.prototype.template = function template(tx) {
* of inputs scripts built and signed). * of inputs scripts built and signed).
*/ */
Wallet.prototype.sign = function sign(tx, options) { Wallet.prototype.sign = spawn.co(function* sign(tx, options) {
return spawn(function *() {
var passphrase, timeout, master, rings; var passphrase, timeout, master, rings;
if (!options) if (!options)
@ -1394,8 +1341,7 @@ Wallet.prototype.sign = function sign(tx, options) {
rings = yield this.deriveInputs(tx); rings = yield this.deriveInputs(tx);
return yield this.signAsync(rings, tx); return yield this.signAsync(rings, tx);
}, this); });
};
/** /**
* Sign a transaction asynchronously. * Sign a transaction asynchronously.
@ -1497,12 +1443,10 @@ Wallet.prototype.addTX = function addTX(tx) {
* @param {Function} callback - Returns [Error, {@link TX}[]]. * @param {Function} callback - Returns [Error, {@link TX}[]].
*/ */
Wallet.prototype.getHistory = function getHistory(account) { Wallet.prototype.getHistory = spawn.co(function* getHistory(account) {
return spawn(function *() {
account = yield this._getIndex(account); account = yield this._getIndex(account);
return this.tx.getHistory(account); return this.tx.getHistory(account);
}, this); });
};
/** /**
* Get all available coins (accesses db). * Get all available coins (accesses db).
@ -1510,12 +1454,10 @@ Wallet.prototype.getHistory = function getHistory(account) {
* @param {Function} callback - Returns [Error, {@link Coin}[]]. * @param {Function} callback - Returns [Error, {@link Coin}[]].
*/ */
Wallet.prototype.getCoins = function getCoins(account) { Wallet.prototype.getCoins = spawn.co(function* getCoins(account) {
return spawn(function *() {
account = yield this._getIndex(account); account = yield this._getIndex(account);
return yield this.tx.getCoins(account); return yield this.tx.getCoins(account);
}, this); });
};
/** /**
* Get all pending/unconfirmed transactions (accesses db). * Get all pending/unconfirmed transactions (accesses db).
@ -1523,12 +1465,10 @@ Wallet.prototype.getCoins = function getCoins(account) {
* @param {Function} callback - Returns [Error, {@link TX}[]]. * @param {Function} callback - Returns [Error, {@link TX}[]].
*/ */
Wallet.prototype.getUnconfirmed = function getUnconfirmed(account) { Wallet.prototype.getUnconfirmed = spawn.co(function* getUnconfirmed(account) {
return spawn(function *() {
account = yield this._getIndex(account); account = yield this._getIndex(account);
return yield this.tx.getUnconfirmed(account); return yield this.tx.getUnconfirmed(account);
}, this); });
};
/** /**
* Get wallet balance (accesses db). * Get wallet balance (accesses db).
@ -1536,12 +1476,10 @@ Wallet.prototype.getUnconfirmed = function getUnconfirmed(account) {
* @param {Function} callback - Returns [Error, {@link Balance}]. * @param {Function} callback - Returns [Error, {@link Balance}].
*/ */
Wallet.prototype.getBalance = function getBalance(account) { Wallet.prototype.getBalance = spawn.co(function* getBalance(account) {
return spawn(function *() {
account = yield this._getIndex(account); account = yield this._getIndex(account);
return yield this.tx.getBalance(account); return yield this.tx.getBalance(account);
}, this); });
};
/** /**
* Get a range of transactions between two timestamps (accesses db). * Get a range of transactions between two timestamps (accesses db).
@ -1552,16 +1490,14 @@ Wallet.prototype.getBalance = function getBalance(account) {
* @param {Function} callback - Returns [Error, {@link TX}[]]. * @param {Function} callback - Returns [Error, {@link TX}[]].
*/ */
Wallet.prototype.getRange = function getRange(account, options) { Wallet.prototype.getRange = spawn.co(function* getRange(account, options) {
return spawn(function *() {
if (account && typeof account === 'object') { if (account && typeof account === 'object') {
options = account; options = account;
account = null; account = null;
} }
account = yield this._getIndex(account); account = yield this._getIndex(account);
return yield this.tx.getRange(account, options); return yield this.tx.getRange(account, options);
}, this); });
};
/** /**
* Get the last N transactions (accesses db). * Get the last N transactions (accesses db).
@ -1570,12 +1506,10 @@ Wallet.prototype.getRange = function getRange(account, options) {
* @param {Function} callback - Returns [Error, {@link TX}[]]. * @param {Function} callback - Returns [Error, {@link TX}[]].
*/ */
Wallet.prototype.getLast = function getLast(account, limit) { Wallet.prototype.getLast = spawn.co(function* getLast(account, limit) {
return spawn(function *() {
account = yield this._getIndex(account); account = yield this._getIndex(account);
return yield this.tx.getLast(account, limit); return yield this.tx.getLast(account, limit);
}, this); });
};
/** /**
* Zap stale TXs from wallet (accesses db). * Zap stale TXs from wallet (accesses db).
@ -1584,12 +1518,10 @@ Wallet.prototype.getLast = function getLast(account, limit) {
* @param {Function} callback - Returns [Error]. * @param {Function} callback - Returns [Error].
*/ */
Wallet.prototype.zap = function zap(account, age) { Wallet.prototype.zap = spawn.co(function* zap(account, age) {
return spawn(function *() {
account = yield this._getIndex(account); account = yield this._getIndex(account);
return yield this.tx.zap(account, age); return yield this.tx.zap(account, age);
}, this); });
};
/** /**
* Abandon transaction (accesses db). * Abandon transaction (accesses db).
@ -1609,8 +1541,7 @@ Wallet.prototype.abandon = function abandon(hash) {
* @param {Function} callback * @param {Function} callback
*/ */
Wallet.prototype._getIndex = function _getIndex(account) { Wallet.prototype._getIndex = spawn.co(function* _getIndex(account) {
return spawn(function *() {
var index; var index;
if (account == null) if (account == null)
@ -1622,8 +1553,7 @@ Wallet.prototype._getIndex = function _getIndex(account) {
throw new Error('Account not found.'); throw new Error('Account not found.');
return index; return index;
}, this); });
};
/** /**
* Get public key for current receiving address. * Get public key for current receiving address.
@ -2087,8 +2017,7 @@ MasterKey.prototype._lock = function _lock(force) {
* @param {Function} callback - Returns [Error, {@link HDPrivateKey}]. * @param {Function} callback - Returns [Error, {@link HDPrivateKey}].
*/ */
MasterKey.prototype.unlock = function _unlock(passphrase, timeout) { MasterKey.prototype.unlock = spawn.co(function* _unlock(passphrase, timeout) {
return spawn(function *() {
var unlock = yield this._lock(); var unlock = yield this._lock();
var data, key; var data, key;
@ -2120,8 +2049,7 @@ MasterKey.prototype.unlock = function _unlock(passphrase, timeout) {
unlock(); unlock();
return this.key; return this.key;
}, this); });
};
/** /**
* Start the destroy timer. * Start the destroy timer.
@ -2207,8 +2135,7 @@ MasterKey.prototype.destroy = function destroy() {
* @param {Function} callback * @param {Function} callback
*/ */
MasterKey.prototype.decrypt = function decrypt(passphrase) { MasterKey.prototype.decrypt = spawn.co(function* decrypt(passphrase) {
return spawn(function *() {
var unlock = yield this._lock(); var unlock = yield this._lock();
var data; var data;
@ -2241,8 +2168,7 @@ MasterKey.prototype.decrypt = function decrypt(passphrase) {
this.ciphertext = null; this.ciphertext = null;
unlock(); unlock();
}, this); });
};
/** /**
* Encrypt the key permanently. * Encrypt the key permanently.
@ -2250,8 +2176,7 @@ MasterKey.prototype.decrypt = function decrypt(passphrase) {
* @param {Function} callback * @param {Function} callback
*/ */
MasterKey.prototype.encrypt = function encrypt(passphrase) { MasterKey.prototype.encrypt = spawn.co(function* encrypt(passphrase) {
return spawn(function *() {
var unlock = yield this._lock(); var unlock = yield this._lock();
var data, iv; var data, iv;
@ -2279,8 +2204,7 @@ MasterKey.prototype.encrypt = function encrypt(passphrase) {
this.ciphertext = data; this.ciphertext = data;
unlock(); unlock();
}, this); });
};
/** /**
* Serialize the key in the form of: * Serialize the key in the form of:

View File

@ -225,8 +225,7 @@ WalletDB.prototype._lockTX = function _lockTX(force) {
* @param {Function} callback * @param {Function} callback
*/ */
WalletDB.prototype._open = function open() { WalletDB.prototype._open = spawn.co(function* open() {
return spawn(function *() {
yield this.db.open(); yield this.db.open();
yield this.db.checkVersion('V', 2); yield this.db.checkVersion('V', 2);
yield this.writeGenesis(); yield this.writeGenesis();
@ -238,8 +237,7 @@ WalletDB.prototype._open = function open() {
this.depth, this.height); this.depth, this.height);
yield this.loadFilter(); yield this.loadFilter();
}, this); });
};
/** /**
* Close the walletdb, wait for the database to close. * Close the walletdb, wait for the database to close.
@ -247,8 +245,7 @@ WalletDB.prototype._open = function open() {
* @param {Function} callback * @param {Function} callback
*/ */
WalletDB.prototype._close = function close() { WalletDB.prototype._close = spawn.co(function* close() {
return spawn(function *() {
var keys = Object.keys(this.wallets); var keys = Object.keys(this.wallets);
var i, key, wallet; var i, key, wallet;
@ -259,8 +256,7 @@ WalletDB.prototype._close = function close() {
} }
yield this.db.close(); yield this.db.close();
}, this); });
};
/** /**
* Backup the wallet db. * Backup the wallet db.
@ -278,8 +274,7 @@ WalletDB.prototype.backup = function backup(path) {
* @param {Function} callback * @param {Function} callback
*/ */
WalletDB.prototype.getDepth = function getDepth() { WalletDB.prototype.getDepth = spawn.co(function* getDepth() {
return spawn(function *() {
var kv, iter, depth; var kv, iter, depth;
// This may seem like a strange way to do // This may seem like a strange way to do
@ -307,8 +302,7 @@ WalletDB.prototype.getDepth = function getDepth() {
depth = layout.ww(kv[0]); depth = layout.ww(kv[0]);
return depth + 1; return depth + 1;
}, this); });
};
/** /**
* Start batch. * Start batch.
@ -410,8 +404,7 @@ WalletDB.prototype.testFilter = function testFilter(hashes) {
* @param {Function} callback - Returns [Error, Object]. * @param {Function} callback - Returns [Error, Object].
*/ */
WalletDB.prototype.dump = function dump() { WalletDB.prototype.dump = spawn.co(function* dump() {
return spawn(function *() {
var records = {}; var records = {};
yield this.db.iterate({ yield this.db.iterate({
gte: ' ', gte: ' ',
@ -422,8 +415,7 @@ WalletDB.prototype.dump = function dump() {
} }
}); });
return records; return records;
}, this); });
};
/** /**
* Register an object with the walletdb. * Register an object with the walletdb.
@ -480,8 +472,7 @@ WalletDB.prototype.getWalletID = function getWalletID(id) {
* @param {Function} callback - Returns [Error, {@link Wallet}]. * @param {Function} callback - Returns [Error, {@link Wallet}].
*/ */
WalletDB.prototype.get = function get(wid) { WalletDB.prototype.get = spawn.co(function* get(wid) {
return spawn(function *() {
var self = this; var self = this;
var wallet, unlock; var wallet, unlock;
@ -520,8 +511,7 @@ WalletDB.prototype.get = function get(wid) {
unlock(); unlock();
return wallet; return wallet;
}, this); });
};
/** /**
* Save a wallet to the database. * Save a wallet to the database.
@ -545,8 +535,7 @@ WalletDB.prototype.save = function save(wallet) {
* @param {Function} callback * @param {Function} callback
*/ */
WalletDB.prototype.auth = function auth(wid, token) { WalletDB.prototype.auth = spawn.co(function* auth(wid, token) {
return spawn(function *() {
var wallet = yield this.get(wid); var wallet = yield this.get(wid);
if (!wallet) if (!wallet)
return; return;
@ -562,8 +551,7 @@ WalletDB.prototype.auth = function auth(wid, token) {
throw new Error('Authentication error.'); throw new Error('Authentication error.');
return wallet; return wallet;
}, this); });
};
/** /**
* Create a new wallet, save to database, setup watcher. * Create a new wallet, save to database, setup watcher.
@ -571,8 +559,7 @@ WalletDB.prototype.auth = function auth(wid, token) {
* @param {Function} callback - Returns [Error, {@link Wallet}]. * @param {Function} callback - Returns [Error, {@link Wallet}].
*/ */
WalletDB.prototype.create = function create(options) { WalletDB.prototype.create = spawn.co(function* create(options) {
return spawn(function *() {
var unlock, wallet, exists; var unlock, wallet, exists;
if (!options) if (!options)
@ -601,8 +588,7 @@ WalletDB.prototype.create = function create(options) {
unlock(); unlock();
return wallet; return wallet;
}, this); });
};
/** /**
* Test for the existence of a wallet. * Test for the existence of a wallet.
@ -610,12 +596,10 @@ WalletDB.prototype.create = function create(options) {
* @param {Function} callback * @param {Function} callback
*/ */
WalletDB.prototype.has = function has(id) { WalletDB.prototype.has = spawn.co(function* has(id) {
return spawn(function *() {
var wid = yield this.getWalletID(id); var wid = yield this.getWalletID(id);
return wid != null; return wid != null;
}, this); });
};
/** /**
* Attempt to create wallet, return wallet if already exists. * Attempt to create wallet, return wallet if already exists.
@ -623,14 +607,12 @@ WalletDB.prototype.has = function has(id) {
* @param {Function} callback * @param {Function} callback
*/ */
WalletDB.prototype.ensure = function ensure(options) { WalletDB.prototype.ensure = spawn.co(function* ensure(options) {
return spawn(function *() {
var wallet = yield this.get(options.id); var wallet = yield this.get(options.id);
if (wallet) if (wallet)
return wallet; return wallet;
return yield this.create(options); return yield this.create(options);
}, this); });
};
/** /**
* Get an account from the database. * Get an account from the database.
@ -639,8 +621,7 @@ WalletDB.prototype.ensure = function ensure(options) {
* @param {Function} callback - Returns [Error, {@link Wallet}]. * @param {Function} callback - Returns [Error, {@link Wallet}].
*/ */
WalletDB.prototype.getAccount = function getAccount(wid, name) { WalletDB.prototype.getAccount = spawn.co(function* getAccount(wid, name) {
return spawn(function *() {
var index = yield this.getAccountIndex(wid, name); var index = yield this.getAccountIndex(wid, name);
var account; var account;
@ -654,8 +635,7 @@ WalletDB.prototype.getAccount = function getAccount(wid, name) {
yield account.open(); yield account.open();
return account; return account;
}, this); });
};
/** /**
* Get an account from the database. Do not setup watcher. * Get an account from the database. Do not setup watcher.
@ -686,8 +666,7 @@ WalletDB.prototype._getAccount = function getAccount(wid, index) {
* @param {Function} callback - Returns [Error, Array]. * @param {Function} callback - Returns [Error, Array].
*/ */
WalletDB.prototype.getAccounts = function getAccounts(wid) { WalletDB.prototype.getAccounts = spawn.co(function* getAccounts(wid) {
return spawn(function *() {
var map = []; var map = [];
var i, accounts; var i, accounts;
@ -711,8 +690,7 @@ WalletDB.prototype.getAccounts = function getAccounts(wid) {
} }
return accounts; return accounts;
}, this); });
};
/** /**
* Lookup the corresponding account name's index. * Lookup the corresponding account name's index.
@ -721,8 +699,7 @@ WalletDB.prototype.getAccounts = function getAccounts(wid) {
* @param {Function} callback - Returns [Error, Number]. * @param {Function} callback - Returns [Error, Number].
*/ */
WalletDB.prototype.getAccountIndex = function getAccountIndex(wid, name) { WalletDB.prototype.getAccountIndex = spawn.co(function* getAccountIndex(wid, name) {
return spawn(function *() {
var index; var index;
if (!wid) if (!wid)
@ -740,8 +717,7 @@ WalletDB.prototype.getAccountIndex = function getAccountIndex(wid, name) {
return -1; return -1;
return index.readUInt32LE(0, true); return index.readUInt32LE(0, true);
}, this); });
};
/** /**
* Save an account to the database. * Save an account to the database.
@ -768,8 +744,7 @@ WalletDB.prototype.saveAccount = function saveAccount(account) {
* @param {Function} callback - Returns [Error, {@link Account}]. * @param {Function} callback - Returns [Error, {@link Account}].
*/ */
WalletDB.prototype.createAccount = function createAccount(options) { WalletDB.prototype.createAccount = spawn.co(function* createAccount(options) {
return spawn(function *() {
var exists = yield this.hasAccount(options.wid, options.name); var exists = yield this.hasAccount(options.wid, options.name);
var account; var account;
@ -786,8 +761,7 @@ WalletDB.prototype.createAccount = function createAccount(options) {
account.accountIndex); account.accountIndex);
return account; return account;
}, this); });
};
/** /**
* Test for the existence of an account. * Test for the existence of an account.
@ -796,8 +770,7 @@ WalletDB.prototype.createAccount = function createAccount(options) {
* @param {Function} callback - Returns [Error, Boolean]. * @param {Function} callback - Returns [Error, Boolean].
*/ */
WalletDB.prototype.hasAccount = function hasAccount(wid, account) { WalletDB.prototype.hasAccount = spawn.co(function* hasAccount(wid, account) {
return spawn(function *() {
var index, key; var index, key;
if (!wid) if (!wid)
@ -814,8 +787,7 @@ WalletDB.prototype.hasAccount = function hasAccount(wid, account) {
return true; return true;
return yield this.db.has(layout.a(wid, index)); return yield this.db.has(layout.a(wid, index));
}, this); });
};
/** /**
* Save addresses to the path map. * Save addresses to the path map.
@ -826,8 +798,7 @@ WalletDB.prototype.hasAccount = function hasAccount(wid, account) {
* @param {Function} callback * @param {Function} callback
*/ */
WalletDB.prototype.saveAddress = function saveAddress(wid, rings) { WalletDB.prototype.saveAddress = spawn.co(function* saveAddress(wid, rings) {
return spawn(function *() {
var i, ring, path; var i, ring, path;
for (i = 0; i < rings.length; i++) { for (i = 0; i < rings.length; i++) {
@ -842,8 +813,7 @@ WalletDB.prototype.saveAddress = function saveAddress(wid, rings) {
yield this.writeAddress(wid, ring.getProgramAddress(), path); yield this.writeAddress(wid, ring.getProgramAddress(), path);
} }
} }
}, this); });
};
/** /**
* Save a single address to the path map. * Save a single address to the path map.
@ -853,8 +823,7 @@ WalletDB.prototype.saveAddress = function saveAddress(wid, rings) {
* @param {Function} callback * @param {Function} callback
*/ */
WalletDB.prototype.writeAddress = function writeAddress(wid, address, path) { WalletDB.prototype.writeAddress = spawn.co(function* writeAddress(wid, address, path) {
return spawn(function *() {
var hash = address.getHash('hex'); var hash = address.getHash('hex');
var batch = this.batch(wid); var batch = this.batch(wid);
var paths; var paths;
@ -877,8 +846,7 @@ WalletDB.prototype.writeAddress = function writeAddress(wid, address, path) {
this.pathCache.set(hash, paths); this.pathCache.set(hash, paths);
batch.put(layout.p(hash), serializePaths(paths)); batch.put(layout.p(hash), serializePaths(paths));
}, this); });
};
/** /**
* Retrieve paths by hash. * Retrieve paths by hash.
@ -886,8 +854,7 @@ WalletDB.prototype.writeAddress = function writeAddress(wid, address, path) {
* @param {Function} callback * @param {Function} callback
*/ */
WalletDB.prototype.getAddressPaths = function getAddressPaths(hash) { WalletDB.prototype.getAddressPaths = spawn.co(function* getAddressPaths(hash) {
return spawn(function *() {
var paths; var paths;
if (!hash) if (!hash)
@ -908,8 +875,7 @@ WalletDB.prototype.getAddressPaths = function getAddressPaths(hash) {
this.pathCache.set(hash, paths); this.pathCache.set(hash, paths);
return paths; return paths;
}, this); });
};
/** /**
* Test whether an address hash exists in the * Test whether an address hash exists in the
@ -919,16 +885,14 @@ WalletDB.prototype.getAddressPaths = function getAddressPaths(hash) {
* @param {Function} callback * @param {Function} callback
*/ */
WalletDB.prototype.hasAddress = function hasAddress(wid, hash) { WalletDB.prototype.hasAddress = spawn.co(function* hasAddress(wid, hash) {
return spawn(function *() {
var paths = yield this.getAddressPaths(hash); var paths = yield this.getAddressPaths(hash);
if (!paths || !paths[wid]) if (!paths || !paths[wid])
return false; return false;
return true; return true;
}, this); });
};
/** /**
* Get all address hashes. * Get all address hashes.
@ -997,8 +961,7 @@ WalletDB.prototype.getWallets = function getWallets() {
* @param {Function} callback * @param {Function} callback
*/ */
WalletDB.prototype.rescan = function rescan(chaindb, height) { WalletDB.prototype.rescan = spawn.co(function* rescan(chaindb, height) {
return spawn(function *() {
var self = this; var self = this;
var unlock = yield this._lockTX(); var unlock = yield this._lockTX();
var hashes; var hashes;
@ -1020,8 +983,7 @@ WalletDB.prototype.rescan = function rescan(chaindb, height) {
} }
unlock(); unlock();
}, this); });
};
/** /**
* Get keys of all pending transactions * Get keys of all pending transactions
@ -1062,8 +1024,7 @@ WalletDB.prototype.getPendingKeys = function getPendingKeys() {
* @param {Function} callback * @param {Function} callback
*/ */
WalletDB.prototype.resend = function resend() { WalletDB.prototype.resend = spawn.co(function* resend() {
return spawn(function *() {
var self = this; var self = this;
var i, keys, key, tx; var i, keys, key, tx;
@ -1081,8 +1042,7 @@ WalletDB.prototype.resend = function resend() {
continue; continue;
this.emit('send', tx); this.emit('send', tx);
} }
}, this); });
};
/** /**
* Map a transactions' addresses to wallet IDs. * Map a transactions' addresses to wallet IDs.
@ -1090,8 +1050,7 @@ WalletDB.prototype.resend = function resend() {
* @param {Function} callback - Returns [Error, {@link PathInfo[]}]. * @param {Function} callback - Returns [Error, {@link PathInfo[]}].
*/ */
WalletDB.prototype.mapWallets = function mapWallets(tx) { WalletDB.prototype.mapWallets = spawn.co(function* mapWallets(tx) {
return spawn(function *() {
var hashes = tx.getHashes('hex'); var hashes = tx.getHashes('hex');
var table; var table;
@ -1104,8 +1063,7 @@ WalletDB.prototype.mapWallets = function mapWallets(tx) {
return; return;
return PathInfo.map(this, tx, table); return PathInfo.map(this, tx, table);
}, this); });
};
/** /**
* Map a transactions' addresses to wallet IDs. * Map a transactions' addresses to wallet IDs.
@ -1113,8 +1071,7 @@ WalletDB.prototype.mapWallets = function mapWallets(tx) {
* @param {Function} callback - Returns [Error, {@link PathInfo}]. * @param {Function} callback - Returns [Error, {@link PathInfo}].
*/ */
WalletDB.prototype.getPathInfo = function getPathInfo(wallet, tx) { WalletDB.prototype.getPathInfo = spawn.co(function* getPathInfo(wallet, tx) {
return spawn(function *() {
var hashes = tx.getHashes('hex'); var hashes = tx.getHashes('hex');
var table = yield this.getTable(hashes); var table = yield this.getTable(hashes);
var info; var info;
@ -1126,8 +1083,7 @@ WalletDB.prototype.getPathInfo = function getPathInfo(wallet, tx) {
info.id = wallet.id; info.id = wallet.id;
return info; return info;
}, this); });
};
/** /**
* Map address hashes to paths. * Map address hashes to paths.
@ -1135,8 +1091,7 @@ WalletDB.prototype.getPathInfo = function getPathInfo(wallet, tx) {
* @param {Function} callback - Returns [Error, {@link AddressTable}]. * @param {Function} callback - Returns [Error, {@link AddressTable}].
*/ */
WalletDB.prototype.getTable = function getTable(hashes) { WalletDB.prototype.getTable = spawn.co(function* getTable(hashes) {
return spawn(function *() {
var table = {}; var table = {};
var count = 0; var count = 0;
var i, j, keys, values, hash, paths; var i, j, keys, values, hash, paths;
@ -1166,16 +1121,14 @@ WalletDB.prototype.getTable = function getTable(hashes) {
return; return;
return table; return table;
}, this); });
};
/** /**
* Write the genesis block as the best hash. * Write the genesis block as the best hash.
* @param {Function} callback * @param {Function} callback
*/ */
WalletDB.prototype.writeGenesis = function writeGenesis() { WalletDB.prototype.writeGenesis = spawn.co(function* writeGenesis() {
return spawn(function *() {
var block = yield this.getTip(); var block = yield this.getTip();
if (block) { if (block) {
this.tip = block.hash; this.tip = block.hash;
@ -1183,8 +1136,7 @@ WalletDB.prototype.writeGenesis = function writeGenesis() {
return; return;
} }
yield this.setTip(this.network.genesis.hash, 0); yield this.setTip(this.network.genesis.hash, 0);
}, this); });
};
/** /**
* Get the best block hash. * Get the best block hash.
@ -1204,16 +1156,14 @@ WalletDB.prototype.getTip = function getTip() {
* @param {Function} callback * @param {Function} callback
*/ */
WalletDB.prototype.setTip = function setTip(hash, height) { WalletDB.prototype.setTip = spawn.co(function* setTip(hash, height) {
return spawn(function *() {
var block = new WalletBlock(hash, height); var block = new WalletBlock(hash, height);
yield this.db.put(layout.R, block.toTip()); yield this.db.put(layout.R, block.toTip());
this.tip = block.hash; this.tip = block.hash;
this.height = block.height; this.height = block.height;
}, this); });
};
/** /**
* Connect a block. * Connect a block.
@ -1284,8 +1234,7 @@ WalletDB.prototype.getWalletsByTX = function getWalletsByTX(hash) {
* @param {Function} callback * @param {Function} callback
*/ */
WalletDB.prototype.addBlock = function addBlock(entry, txs, force) { WalletDB.prototype.addBlock = spawn.co(function* addBlock(entry, txs, force) {
return spawn(function *() {
var unlock = yield this._lockTX(force); var unlock = yield this._lockTX(force);
var i, block, matches, hash, tx, wallets; var i, block, matches, hash, tx, wallets;
@ -1344,8 +1293,7 @@ WalletDB.prototype.addBlock = function addBlock(entry, txs, force) {
} }
unlock(); unlock();
}, this); });
};
/** /**
* Unconfirm a block's transactions * Unconfirm a block's transactions
@ -1354,8 +1302,7 @@ WalletDB.prototype.addBlock = function addBlock(entry, txs, force) {
* @param {Function} callback * @param {Function} callback
*/ */
WalletDB.prototype.removeBlock = function removeBlock(entry) { WalletDB.prototype.removeBlock = spawn.co(function* removeBlock(entry) {
return spawn(function *() {
var unlock = yield this._lockTX(); var unlock = yield this._lockTX();
var i, j, block, data, hash, wallets, wid, wallet; var i, j, block, data, hash, wallets, wid, wallet;
@ -1403,8 +1350,7 @@ WalletDB.prototype.removeBlock = function removeBlock(entry) {
this.height = block.height; this.height = block.height;
unlock(); unlock();
}, this); });
};
/** /**
* Add a transaction to the database, map addresses * Add a transaction to the database, map addresses
@ -1414,8 +1360,7 @@ WalletDB.prototype.removeBlock = function removeBlock(entry) {
* @param {Function} callback - Returns [Error]. * @param {Function} callback - Returns [Error].
*/ */
WalletDB.prototype.addTX = function addTX(tx, force) { WalletDB.prototype.addTX = spawn.co(function* addTX(tx, force) {
return spawn(function *() {
var unlock = yield this._lockTX(force); var unlock = yield this._lockTX(force);
var i, wallets, info, wallet; var i, wallets, info, wallet;
@ -1463,8 +1408,7 @@ WalletDB.prototype.addTX = function addTX(tx, force) {
unlock(); unlock();
return wallets; return wallets;
}, this); });
};
/** /**
* Get the corresponding path for an address hash. * Get the corresponding path for an address hash.
@ -1473,8 +1417,7 @@ WalletDB.prototype.addTX = function addTX(tx, force) {
* @param {Function} callback * @param {Function} callback
*/ */
WalletDB.prototype.getAddressPath = function getAddressPath(wid, hash) { WalletDB.prototype.getAddressPath = spawn.co(function* getAddressPath(wid, hash) {
return spawn(function *() {
var paths = yield this.getAddressPaths(hash); var paths = yield this.getAddressPaths(hash);
var path; var path;
@ -1487,8 +1430,7 @@ WalletDB.prototype.getAddressPath = function getAddressPath(wid, hash) {
return; return;
return path; return path;
}, this); });
};
/** /**
* Path Info * Path Info

View File

@ -247,8 +247,7 @@ Workers.prototype.verify = function verify(tx, flags) {
* @param {Function} callback * @param {Function} callback
*/ */
Workers.prototype.sign = function sign(tx, ring, type) { Workers.prototype.sign = spawn.co(function* sign(tx, ring, type) {
return spawn(function *() {
var i, result, input, sig, sigs, total; var i, result, input, sig, sigs, total;
result = yield this.execute('sign', [tx, ring, type], -1); result = yield this.execute('sign', [tx, ring, type], -1);
@ -264,8 +263,7 @@ Workers.prototype.sign = function sign(tx, ring, type) {
} }
return total; return total;
}, this); });
};
/** /**
* Execute the mining job (no timeout). * Execute the mining job (no timeout).