coinentry: refactor.

This commit is contained in:
Christopher Jeffrey 2017-07-31 15:12:41 -07:00
parent 1bbe36ec1a
commit 35068cb82b
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD

View File

@ -14,6 +14,13 @@ const StaticWriter = require('../utils/staticwriter');
const encoding = require('../utils/encoding');
const compress = require('./compress');
/*
* Constants
*/
const NUM_FLAGS = 3;
const MAX_HEIGHT = ((1 << (32 - NUM_FLAGS)) >>> 0) - 1;
/**
* Represents an unspent output.
* @alias module:coins.CoinEntry
@ -171,17 +178,15 @@ CoinEntry.prototype.toWriter = function toWriter(bw) {
}
let height = this.height;
let flags = 0;
// We save 29 bits for the height.
// This should be good for the next 4000 years.
if (height === -1)
height = 0x1fffffff;
let field = 0;
if (this.coinbase)
flags |= 1;
field |= 1;
const field = (height * 8) | flags;
if (height === -1)
height = MAX_HEIGHT;
field |= height << NUM_FLAGS;
bw.writeVarint(this.version);
bw.writeU32(field);
@ -219,14 +224,13 @@ CoinEntry.prototype.fromReader = function fromReader(br) {
const version = br.readVarint();
const field = br.readU32();
const flags = field & 0x07;
let height = field / 8 | 0;
let height = field >>> NUM_FLAGS;
if (height === 0x1fffffff)
if (height === MAX_HEIGHT)
height = -1;
this.version = version;
this.coinbase = (flags & 1) !== 0;
this.coinbase = (field & 1) !== 0;
this.height = height;
compress.unpack(this.output, br);