chain: use binary search for byTime.

This commit is contained in:
Christopher Jeffrey 2016-01-20 22:32:32 -08:00
parent 423b52b0b7
commit 9a575e9a26

View File

@ -437,25 +437,32 @@ Chain.prototype.byHash = function byHash(hash) {
};
Chain.prototype.byTime = function byTime(ts) {
var i, delta, existing;
var step = 1;
var start = 0;
var end = this.index.count;
var pos, delta, entry;
if (ts >= this.tip.ts)
return this.tip;
for (i = this.index.count - 1; i >= 0; i -= step) {
existing = this.db.get(i);
// Do a binary search for a block
// mined within an hour of the
// timestamp.
while (start < end) {
pos = (start + end) >> 1;
entry = this.db.get(pos);
delta = Math.abs(ts - entry.ts);
if (ts >= existing.ts)
return existing;
if (delta <= 60 * 60)
return entry;
delta = existing.ts - ts;
// If they're more than 1000 blocks apart
if (delta > 1000 * 60 * 10)
step *= 2;
if (ts < entry.ts) {
end = pos;
} else {
start = pos + 1;
}
}
return this.db.get(0);
return this.db.get(start);
};
Chain.prototype.hasBlock = function hasBlock(hash) {