chain: optimize isMainChain.

This commit is contained in:
Christopher Jeffrey 2016-10-21 19:11:52 -07:00
parent b0b8d333a5
commit ab9cf9ec7e
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD
2 changed files with 27 additions and 21 deletions

View File

@ -596,27 +596,17 @@ ChainDB.prototype.getNextHash = co(function* getNextHash(hash) {
*/
ChainDB.prototype.isMainChain = co(function* isMainChain(hash) {
var query, height, existing;
if (hash instanceof ChainEntry) {
query = hash.height;
hash = hash.hash;
} else {
query = hash;
}
assert(typeof hash === 'string');
if (hash === this.chain.tip.hash
|| hash === this.network.genesis.hash) {
return true;
}
height = yield this.getHeight(query);
existing = yield this.getHash(height);
if (yield this.getNextHash(hash))
return true;
if (!existing)
return false;
return hash === existing;
return false;
});
/**

View File

@ -223,9 +223,27 @@ ChainEntry.prototype.getAncestors = co(function* getAncestors(max) {
* @returns {Promise} - Return Boolean.
*/
ChainEntry.prototype.isMainChain = function isMainChain() {
return this.chain.db.isMainChain(this);
};
ChainEntry.prototype.isMainChain = co(function* isMainChain() {
var entry;
if (this.hash === this.chain.tip.hash
|| this.hash === this.network.genesis.hash) {
return true;
}
entry = this.chain.db.getCache(this.height);
if (entry) {
if (entry.hash === this.hash)
return true;
return false;
}
if (yield this.chain.db.getNextHash(this.hash))
return true;
return false;
});
/**
* Collect ancestors up to `height`.
@ -234,7 +252,7 @@ ChainEntry.prototype.isMainChain = function isMainChain() {
*/
ChainEntry.prototype.getAncestorByHeight = co(function* getAncestorByHeight(height) {
var main, entry;
var entry;
if (height < 0)
return yield co.wait();
@ -242,9 +260,7 @@ ChainEntry.prototype.getAncestorByHeight = co(function* getAncestorByHeight(heig
assert(height >= 0);
assert(height <= this.height);
main = yield this.isMainChain();
if (main)
if (yield this.isMainChain())
return yield this.chain.db.get(height);
entry = yield this.getAncestor(this.height - height);