net/miner/hd: classify.

This commit is contained in:
Christopher Jeffrey 2017-11-15 21:23:47 -08:00
parent daa55a05bc
commit 280d5d38e5
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD
6 changed files with 5434 additions and 5333 deletions

View File

@ -28,6 +28,11 @@ const wordlistCache = Object.create(null);
/** /**
* HD Mnemonic * HD Mnemonic
* @alias module:hd.Mnemonic * @alias module:hd.Mnemonic
*/
class Mnemonic {
/**
* Create a mnemonic.
* @constructor * @constructor
* @param {Object} options * @param {Object} options
* @param {Number?} options.bit - Bits of entropy (Must * @param {Number?} options.bit - Bits of entropy (Must
@ -42,10 +47,7 @@ const wordlistCache = Object.create(null);
* @param {String?} options.language - Language. * @param {String?} options.language - Language.
*/ */
function Mnemonic(options) { constructor(options) {
if (!(this instanceof Mnemonic))
return new Mnemonic(options);
this.bits = common.MIN_ENTROPY; this.bits = common.MIN_ENTROPY;
this.language = 'english'; this.language = 'english';
this.entropy = null; this.entropy = null;
@ -54,31 +56,15 @@ function Mnemonic(options) {
if (options) if (options)
this.fromOptions(options); this.fromOptions(options);
} }
/** /**
* List of languages.
* @const {String[]}
* @default
*/
Mnemonic.languages = [
'simplified chinese',
'traditional chinese',
'english',
'french',
'italian',
'japanese',
'spanish'
];
/**
* Inject properties from options object. * Inject properties from options object.
* @private * @private
* @param {Object} options * @param {Object} options
*/ */
Mnemonic.prototype.fromOptions = function fromOptions(options) { fromOptions(options) {
if (typeof options === 'string') if (typeof options === 'string')
options = { phrase: options }; options = { phrase: options };
@ -112,23 +98,23 @@ Mnemonic.prototype.fromOptions = function fromOptions(options) {
} }
return this; return this;
}; }
/** /**
* Instantiate mnemonic from options. * Instantiate mnemonic from options.
* @param {Object} options * @param {Object} options
* @returns {Mnemonic} * @returns {Mnemonic}
*/ */
Mnemonic.fromOptions = function fromOptions(options) { static fromOptions(options) {
return new Mnemonic().fromOptions(options); return new this().fromOptions(options);
}; }
/** /**
* Destroy the mnemonic (zeroes entropy). * Destroy the mnemonic (zeroes entropy).
*/ */
Mnemonic.prototype.destroy = function destroy() { destroy() {
this.bits = common.MIN_ENTROPY; this.bits = common.MIN_ENTROPY;
this.language = 'english'; this.language = 'english';
if (this.entropy) { if (this.entropy) {
@ -137,15 +123,15 @@ Mnemonic.prototype.destroy = function destroy() {
} }
this.phrase = null; this.phrase = null;
this.passphrase = ''; this.passphrase = '';
}; }
/** /**
* Generate the seed. * Generate the seed.
* @param {String?} passphrase * @param {String?} passphrase
* @returns {Buffer} pbkdf2 seed. * @returns {Buffer} pbkdf2 seed.
*/ */
Mnemonic.prototype.toSeed = function toSeed(passphrase) { toSeed(passphrase) {
if (!passphrase) if (!passphrase)
passphrase = this.passphrase; passphrase = this.passphrase;
@ -158,28 +144,28 @@ Mnemonic.prototype.toSeed = function toSeed(passphrase) {
Buffer.from(phrase, 'utf8'), Buffer.from(phrase, 'utf8'),
Buffer.from(passwd, 'utf8'), Buffer.from(passwd, 'utf8'),
2048, 64); 2048, 64);
}; }
/** /**
* Get or generate entropy. * Get or generate entropy.
* @returns {Buffer} * @returns {Buffer}
*/ */
Mnemonic.prototype.getEntropy = function getEntropy() { getEntropy() {
if (!this.entropy) if (!this.entropy)
this.entropy = random.randomBytes(this.bits / 8); this.entropy = random.randomBytes(this.bits / 8);
assert(this.bits / 8 === this.entropy.length); assert(this.bits / 8 === this.entropy.length);
return this.entropy; return this.entropy;
}; }
/** /**
* Generate a mnemonic phrase from chosen language. * Generate a mnemonic phrase from chosen language.
* @returns {String} * @returns {String}
*/ */
Mnemonic.prototype.getPhrase = function getPhrase() { getPhrase() {
if (this.phrase) if (this.phrase)
return this.phrase; return this.phrase;
@ -225,15 +211,15 @@ Mnemonic.prototype.getPhrase = function getPhrase() {
this.phrase = phrase; this.phrase = phrase;
return phrase; return phrase;
}; }
/** /**
* Inject properties from phrase. * Inject properties from phrase.
* @private * @private
* @param {String} phrase * @param {String} phrase
*/ */
Mnemonic.prototype.fromPhrase = function fromPhrase(phrase) { fromPhrase(phrase) {
assert(typeof phrase === 'string'); assert(typeof phrase === 'string');
assert(phrase.length <= 1000); assert(phrase.length <= 1000);
@ -296,27 +282,27 @@ Mnemonic.prototype.fromPhrase = function fromPhrase(phrase) {
this.phrase = phrase; this.phrase = phrase;
return this; return this;
}; }
/** /**
* Instantiate mnemonic from a phrase (validates checksum). * Instantiate mnemonic from a phrase (validates checksum).
* @param {String} phrase * @param {String} phrase
* @returns {Mnemonic} * @returns {Mnemonic}
* @throws on bad checksum * @throws on bad checksum
*/ */
Mnemonic.fromPhrase = function fromPhrase(phrase) { static fromPhrase(phrase) {
return new Mnemonic().fromPhrase(phrase); return new this().fromPhrase(phrase);
}; }
/** /**
* Inject properties from entropy. * Inject properties from entropy.
* @private * @private
* @param {Buffer} entropy * @param {Buffer} entropy
* @param {String?} lang * @param {String?} lang
*/ */
Mnemonic.prototype.fromEntropy = function fromEntropy(entropy, lang) { fromEntropy(entropy, lang) {
assert(Buffer.isBuffer(entropy)); assert(Buffer.isBuffer(entropy));
assert(entropy.length * 8 >= common.MIN_ENTROPY); assert(entropy.length * 8 >= common.MIN_ENTROPY);
assert(entropy.length * 8 <= common.MAX_ENTROPY); assert(entropy.length * 8 <= common.MAX_ENTROPY);
@ -330,27 +316,27 @@ Mnemonic.prototype.fromEntropy = function fromEntropy(entropy, lang) {
this.language = lang; this.language = lang;
return this; return this;
}; }
/** /**
* Instantiate mnemonic from entropy. * Instantiate mnemonic from entropy.
* @param {Buffer} entropy * @param {Buffer} entropy
* @param {String?} lang * @param {String?} lang
* @returns {Mnemonic} * @returns {Mnemonic}
*/ */
Mnemonic.fromEntropy = function fromEntropy(entropy, lang) { static fromEntropy(entropy, lang) {
return new Mnemonic().fromEntropy(entropy, lang); return new this().fromEntropy(entropy, lang);
}; }
/** /**
* Determine a single word's language. * Determine a single word's language.
* @param {String} word * @param {String} word
* @returns {String} Language. * @returns {String} Language.
* @throws on not found. * @throws on not found.
*/ */
Mnemonic.getLanguage = function getLanguage(word) { static getLanguage(word) {
for (const lang of Mnemonic.languages) { for (const lang of Mnemonic.languages) {
const list = Mnemonic.getWordlist(lang); const list = Mnemonic.getWordlist(lang);
if (list.map[word] != null) if (list.map[word] != null)
@ -358,15 +344,15 @@ Mnemonic.getLanguage = function getLanguage(word) {
} }
throw new Error('Could not determine language.'); throw new Error('Could not determine language.');
}; }
/** /**
* Retrieve the wordlist for a language. * Retrieve the wordlist for a language.
* @param {String} lang * @param {String} lang
* @returns {Object} * @returns {Object}
*/ */
Mnemonic.getWordlist = function getWordlist(lang) { static getWordlist(lang) {
const cache = wordlistCache[lang]; const cache = wordlistCache[lang];
if (cache) if (cache)
@ -378,14 +364,14 @@ Mnemonic.getWordlist = function getWordlist(lang) {
wordlistCache[lang] = list; wordlistCache[lang] = list;
return list; return list;
}; }
/** /**
* Convert mnemonic to a json-friendly object. * Convert mnemonic to a json-friendly object.
* @returns {Object} * @returns {Object}
*/ */
Mnemonic.prototype.toJSON = function toJSON() { toJSON() {
return { return {
bits: this.bits, bits: this.bits,
language: this.language, language: this.language,
@ -393,15 +379,15 @@ Mnemonic.prototype.toJSON = function toJSON() {
phrase: this.getPhrase(), phrase: this.getPhrase(),
passphrase: this.passphrase passphrase: this.passphrase
}; };
}; }
/** /**
* Inject properties from json object. * Inject properties from json object.
* @private * @private
* @param {Object} json * @param {Object} json
*/ */
Mnemonic.prototype.fromJSON = function fromJSON(json) { fromJSON(json) {
assert(json); assert(json);
assert((json.bits & 0xffff) === json.bits); assert((json.bits & 0xffff) === json.bits);
assert(typeof json.language === 'string'); assert(typeof json.language === 'string');
@ -420,38 +406,38 @@ Mnemonic.prototype.fromJSON = function fromJSON(json) {
this.passphrase = json.passphrase; this.passphrase = json.passphrase;
return this; return this;
}; }
/** /**
* Instantiate mnemonic from json object. * Instantiate mnemonic from json object.
* @param {Object} json * @param {Object} json
* @returns {Mnemonic} * @returns {Mnemonic}
*/ */
Mnemonic.fromJSON = function fromJSON(json) { static fromJSON(json) {
return new Mnemonic().fromJSON(json); return new this().fromJSON(json);
}; }
/** /**
* Calculate serialization size. * Calculate serialization size.
* @returns {Number} * @returns {Number}
*/ */
Mnemonic.prototype.getSize = function getSize() { getSize() {
let size = 0; let size = 0;
size += 3; size += 3;
size += this.getEntropy().length; size += this.getEntropy().length;
size += encoding.sizeVarString(this.getPhrase(), 'utf8'); size += encoding.sizeVarString(this.getPhrase(), 'utf8');
size += encoding.sizeVarString(this.passphrase, 'utf8'); size += encoding.sizeVarString(this.passphrase, 'utf8');
return size; return size;
}; }
/** /**
* Write the mnemonic to a buffer writer. * Write the mnemonic to a buffer writer.
* @params {BufferWriter} bw * @params {BufferWriter} bw
*/ */
Mnemonic.prototype.toWriter = function toWriter(bw) { toWriter(bw) {
const lang = Mnemonic.languages.indexOf(this.language); const lang = Mnemonic.languages.indexOf(this.language);
assert(lang !== -1); assert(lang !== -1);
@ -463,25 +449,25 @@ Mnemonic.prototype.toWriter = function toWriter(bw) {
bw.writeVarString(this.passphrase, 'utf8'); bw.writeVarString(this.passphrase, 'utf8');
return bw; return bw;
}; }
/** /**
* Serialize mnemonic. * Serialize mnemonic.
* @returns {Buffer} * @returns {Buffer}
*/ */
Mnemonic.prototype.toRaw = function toRaw(writer) { toRaw(writer) {
const size = this.getSize(); const size = this.getSize();
return this.toWriter(new StaticWriter(size)).render(); return this.toWriter(new StaticWriter(size)).render();
}; }
/** /**
* Inject properties from buffer reader. * Inject properties from buffer reader.
* @private * @private
* @param {BufferReader} br * @param {BufferReader} br
*/ */
Mnemonic.prototype.fromReader = function fromReader(br) { fromReader(br) {
const bits = br.readU16(); const bits = br.readU16();
assert(bits >= common.MIN_ENTROPY); assert(bits >= common.MIN_ENTROPY);
@ -498,74 +484,97 @@ Mnemonic.prototype.fromReader = function fromReader(br) {
this.passphrase = br.readVarString('utf8'); this.passphrase = br.readVarString('utf8');
return this; return this;
}; }
/** /**
* Inject properties from serialized data. * Inject properties from serialized data.
* @private * @private
* @param {Buffer} data * @param {Buffer} data
*/ */
Mnemonic.prototype.fromRaw = function fromRaw(data) { fromRaw(data) {
return this.fromReader(new BufferReader(data)); return this.fromReader(new BufferReader(data));
}; }
/** /**
* Instantiate mnemonic from buffer reader. * Instantiate mnemonic from buffer reader.
* @param {BufferReader} br * @param {BufferReader} br
* @returns {Mnemonic} * @returns {Mnemonic}
*/ */
Mnemonic.fromReader = function fromReader(br) { static fromReader(br) {
return new Mnemonic().fromReader(br); return new this().fromReader(br);
}; }
/** /**
* Instantiate mnemonic from serialized data. * Instantiate mnemonic from serialized data.
* @param {Buffer} data * @param {Buffer} data
* @returns {Mnemonic} * @returns {Mnemonic}
*/ */
Mnemonic.fromRaw = function fromRaw(data) { static fromRaw(data) {
return new Mnemonic().fromRaw(data); return new this().fromRaw(data);
}; }
/** /**
* Convert the mnemonic to a string. * Convert the mnemonic to a string.
* @returns {String} * @returns {String}
*/ */
Mnemonic.prototype.toString = function toString() { toString() {
return this.getPhrase(); return this.getPhrase();
}; }
/** /**
* Inspect the mnemonic. * Inspect the mnemonic.
* @returns {String} * @returns {String}
*/ */
Mnemonic.prototype.inspect = function inspect() { inspect() {
return `<Mnemonic: ${this.getPhrase()}>`; return `<Mnemonic: ${this.getPhrase()}>`;
}; }
/** /**
* Test whether an object is a Mnemonic. * Test whether an object is a Mnemonic.
* @param {Object} obj * @param {Object} obj
* @returns {Boolean} * @returns {Boolean}
*/ */
Mnemonic.isMnemonic = function isMnemonic(obj) { static isMnemonic(obj) {
return obj instanceof Mnemonic; return obj instanceof Mnemonic;
}; }
}
/**
* List of languages.
* @const {String[]}
* @default
*/
Mnemonic.languages = [
'simplified chinese',
'traditional chinese',
'english',
'french',
'italian',
'japanese',
'spanish'
];
/** /**
* Word List * Word List
* @ignore
*/
class WordList {
/**
* Create word list.
* @constructor * @constructor
* @ignore * @ignore
* @param {Array} words * @param {Array} words
*/ */
function WordList(words) { constructor(words) {
this.words = words; this.words = words;
this.map = Object.create(null); this.map = Object.create(null);
@ -573,6 +582,7 @@ function WordList(words) {
const word = words[i]; const word = words[i];
this.map[word] = i; this.map[word] = i;
} }
}
} }
/* /*

View File

@ -31,14 +31,6 @@ const SEED_SALT = Buffer.from('Bitcoin seed', 'ascii');
/** /**
* HDPrivateKey * HDPrivateKey
* @alias module:hd.PrivateKey * @alias module:hd.PrivateKey
* @constructor
* @param {Object|Base58String} options
* @param {Base58String?} options.xkey - Serialized base58 key.
* @param {Number?} options.depth
* @param {Number?} options.parentFingerPrint
* @param {Number?} options.childIndex
* @param {Buffer?} options.chainCode
* @param {Buffer?} options.privateKey
* @property {Number} depth * @property {Number} depth
* @property {Number} parentFingerPrint * @property {Number} parentFingerPrint
* @property {Number} childIndex * @property {Number} childIndex
@ -46,10 +38,19 @@ const SEED_SALT = Buffer.from('Bitcoin seed', 'ascii');
* @property {Buffer} privateKey * @property {Buffer} privateKey
*/ */
function HDPrivateKey(options) { class HDPrivateKey {
if (!(this instanceof HDPrivateKey)) /**
return new HDPrivateKey(options); * Create an hd private key.
* @constructor
* @param {Object|String} options
* @param {Number?} options.depth
* @param {Number?} options.parentFingerPrint
* @param {Number?} options.childIndex
* @param {Buffer?} options.chainCode
* @param {Buffer?} options.privateKey
*/
constructor(options) {
this.depth = 0; this.depth = 0;
this.parentFingerPrint = 0; this.parentFingerPrint = 0;
this.childIndex = 0; this.childIndex = 0;
@ -63,15 +64,15 @@ function HDPrivateKey(options) {
if (options) if (options)
this.fromOptions(options); this.fromOptions(options);
} }
/** /**
* Inject properties from options object. * Inject properties from options object.
* @private * @private
* @param {Object} options * @param {Object} options
*/ */
HDPrivateKey.prototype.fromOptions = function fromOptions(options) { fromOptions(options) {
assert(options, 'No options for HD private key.'); assert(options, 'No options for HD private key.');
assert((options.depth & 0xff) === options.depth); assert((options.depth & 0xff) === options.depth);
assert((options.parentFingerPrint >>> 0) === options.parentFingerPrint); assert((options.parentFingerPrint >>> 0) === options.parentFingerPrint);
@ -87,24 +88,24 @@ HDPrivateKey.prototype.fromOptions = function fromOptions(options) {
this.publicKey = secp256k1.publicKeyCreate(options.privateKey, true); this.publicKey = secp256k1.publicKeyCreate(options.privateKey, true);
return this; return this;
}; }
/** /**
* Instantiate HD private key from options object. * Instantiate HD private key from options object.
* @param {Object} options * @param {Object} options
* @returns {HDPrivateKey} * @returns {HDPrivateKey}
*/ */
HDPrivateKey.fromOptions = function fromOptions(options) { static fromOptions(options) {
return new HDPrivateKey().fromOptions(options); return new this().fromOptions(options);
}; }
/** /**
* Get HD public key. * Get HD public key.
* @returns {HDPublicKey} * @returns {HDPublicKey}
*/ */
HDPrivateKey.prototype.toPublic = function toPublic() { toPublic() {
let key = this._hdPublicKey; let key = this._hdPublicKey;
if (!key) { if (!key) {
@ -118,32 +119,32 @@ HDPrivateKey.prototype.toPublic = function toPublic() {
} }
return key; return key;
}; }
/** /**
* Get cached base58 xprivkey. * Get cached base58 xprivkey.
* @returns {Base58String} * @returns {Base58String}
*/ */
HDPrivateKey.prototype.xprivkey = function xprivkey(network) { xprivkey(network) {
return this.toBase58(network); return this.toBase58(network);
}; }
/** /**
* Get cached base58 xpubkey. * Get cached base58 xpubkey.
* @returns {Base58String} * @returns {Base58String}
*/ */
HDPrivateKey.prototype.xpubkey = function xpubkey(network) { xpubkey(network) {
return this.toPublic().xpubkey(network); return this.toPublic().xpubkey(network);
}; }
/** /**
* Destroy the key (zeroes chain code, privkey, and pubkey). * Destroy the key (zeroes chain code, privkey, and pubkey).
* @param {Boolean} pub - Destroy hd public key as well. * @param {Boolean} pub - Destroy hd public key as well.
*/ */
HDPrivateKey.prototype.destroy = function destroy(pub) { destroy(pub) {
this.depth = 0; this.depth = 0;
this.childIndex = 0; this.childIndex = 0;
this.parentFingerPrint = 0; this.parentFingerPrint = 0;
@ -159,16 +160,16 @@ HDPrivateKey.prototype.destroy = function destroy(pub) {
this._hdPublicKey.destroy(); this._hdPublicKey.destroy();
this._hdPublicKey = null; this._hdPublicKey = null;
} }
}; }
/** /**
* Derive a child key. * Derive a child key.
* @param {Number} index - Derivation index. * @param {Number} index - Derivation index.
* @param {Boolean?} hardened - Whether the derivation should be hardened. * @param {Boolean?} hardened - Whether the derivation should be hardened.
* @returns {HDPrivateKey} * @returns {HDPrivateKey}
*/ */
HDPrivateKey.prototype.derive = function derive(index, hardened) { derive(index, hardened) {
assert(typeof index === 'number'); assert(typeof index === 'number');
if ((index >>> 0) !== index) if ((index >>> 0) !== index)
@ -217,7 +218,7 @@ HDPrivateKey.prototype.derive = function derive(index, hardened) {
this.fingerPrint = fp.readUInt32BE(0, true); this.fingerPrint = fp.readUInt32BE(0, true);
} }
const child = new HDPrivateKey(); const child = new this.constructor();
child.depth = this.depth + 1; child.depth = this.depth + 1;
child.parentFingerPrint = this.fingerPrint; child.parentFingerPrint = this.fingerPrint;
child.childIndex = index; child.childIndex = index;
@ -228,20 +229,20 @@ HDPrivateKey.prototype.derive = function derive(index, hardened) {
common.cache.set(id, child); common.cache.set(id, child);
return child; return child;
}; }
/** /**
* Unique HD key ID. * Unique HD key ID.
* @private * @private
* @param {Number} index * @param {Number} index
* @returns {String} * @returns {String}
*/ */
HDPrivateKey.prototype.getID = function getID(index) { getID(index) {
return 'v' + this.publicKey.toString('hex') + index; return 'v' + this.publicKey.toString('hex') + index;
}; }
/** /**
* Derive a BIP44 account key. * Derive a BIP44 account key.
* @param {Number} purpose * @param {Number} purpose
* @param {Number} type * @param {Number} type
@ -250,7 +251,7 @@ HDPrivateKey.prototype.getID = function getID(index) {
* @throws Error if key is not a master key. * @throws Error if key is not a master key.
*/ */
HDPrivateKey.prototype.deriveAccount = function deriveAccount(purpose, type, account) { deriveAccount(purpose, type, account) {
assert((purpose >>> 0) === purpose, 'Purpose must be a number.'); assert((purpose >>> 0) === purpose, 'Purpose must be a number.');
assert((type >>> 0) === type, 'Account index must be a number.'); assert((type >>> 0) === type, 'Account index must be a number.');
assert((account >>> 0) === account, 'Account index must be a number.'); assert((account >>> 0) === account, 'Account index must be a number.');
@ -259,35 +260,35 @@ HDPrivateKey.prototype.deriveAccount = function deriveAccount(purpose, type, acc
.derive(purpose, true) .derive(purpose, true)
.derive(type, true) .derive(type, true)
.derive(account, true); .derive(account, true);
}; }
/** /**
* Test whether the key is a master key. * Test whether the key is a master key.
* @returns {Boolean} * @returns {Boolean}
*/ */
HDPrivateKey.prototype.isMaster = function isMaster() { isMaster() {
return common.isMaster(this); return common.isMaster(this);
}; }
/** /**
* Test whether the key is (most likely) a BIP44 account key. * Test whether the key is (most likely) a BIP44 account key.
* @param {Number?} account * @param {Number?} account
* @returns {Boolean} * @returns {Boolean}
*/ */
HDPrivateKey.prototype.isAccount = function isAccount(account) { isAccount(account) {
return common.isAccount(this, account); return common.isAccount(this, account);
}; }
/** /**
* Test whether an object is in the form of a base58 xprivkey. * Test whether an object is in the form of a base58 xprivkey.
* @param {String} data * @param {String} data
* @param {Network?} network * @param {Network?} network
* @returns {Boolean} * @returns {Boolean}
*/ */
HDPrivateKey.isBase58 = function isBase58(data, network) { static isBase58(data, network) {
if (typeof data !== 'string') if (typeof data !== 'string')
return false; return false;
@ -302,16 +303,16 @@ HDPrivateKey.isBase58 = function isBase58(data, network) {
} catch (e) { } catch (e) {
return false; return false;
} }
}; }
/** /**
* Test whether a buffer has a valid network prefix. * Test whether a buffer has a valid network prefix.
* @param {Buffer} data * @param {Buffer} data
* @param {Network?} network * @param {Network?} network
* @returns {Boolean} * @returns {Boolean}
*/ */
HDPrivateKey.isRaw = function isRaw(data, network) { static isRaw(data, network) {
if (!Buffer.isBuffer(data)) if (!Buffer.isBuffer(data))
return false; return false;
@ -326,31 +327,31 @@ HDPrivateKey.isRaw = function isRaw(data, network) {
} catch (e) { } catch (e) {
return false; return false;
} }
}; }
/** /**
* Test whether a string is a valid path. * Test whether a string is a valid path.
* @param {String} path * @param {String} path
* @returns {Boolean} * @returns {Boolean}
*/ */
HDPrivateKey.isValidPath = function isValidPath(path) { static isValidPath(path) {
try { try {
common.parsePath(path, true); common.parsePath(path, true);
return true; return true;
} catch (e) { } catch (e) {
return false; return false;
} }
}; }
/** /**
* Derive a key from a derivation path. * Derive a key from a derivation path.
* @param {String} path * @param {String} path
* @returns {HDPrivateKey} * @returns {HDPrivateKey}
* @throws Error if `path` is not a valid path. * @throws Error if `path` is not a valid path.
*/ */
HDPrivateKey.prototype.derivePath = function derivePath(path) { derivePath(path) {
const indexes = common.parsePath(path, true); const indexes = common.parsePath(path, true);
let key = this; let key = this;
@ -359,15 +360,15 @@ HDPrivateKey.prototype.derivePath = function derivePath(path) {
key = key.derive(index); key = key.derive(index);
return key; return key;
}; }
/** /**
* Compare a key against an object. * Compare a key against an object.
* @param {Object} obj * @param {Object} obj
* @returns {Boolean} * @returns {Boolean}
*/ */
HDPrivateKey.prototype.equals = function equals(obj) { equals(obj) {
assert(HDPrivateKey.isHDPrivateKey(obj)); assert(HDPrivateKey.isHDPrivateKey(obj));
return this.depth === obj.depth return this.depth === obj.depth
@ -375,15 +376,15 @@ HDPrivateKey.prototype.equals = function equals(obj) {
&& this.childIndex === obj.childIndex && this.childIndex === obj.childIndex
&& this.chainCode.equals(obj.chainCode) && this.chainCode.equals(obj.chainCode)
&& this.privateKey.equals(obj.privateKey); && this.privateKey.equals(obj.privateKey);
}; }
/** /**
* Compare a key against an object. * Compare a key against an object.
* @param {Object} obj * @param {Object} obj
* @returns {Boolean} * @returns {Boolean}
*/ */
HDPrivateKey.prototype.compare = function compare(key) { compare(key) {
assert(HDPrivateKey.isHDPrivateKey(key)); assert(HDPrivateKey.isHDPrivateKey(key));
let cmp = this.depth - key.depth; let cmp = this.depth - key.depth;
@ -412,15 +413,15 @@ HDPrivateKey.prototype.compare = function compare(key) {
return cmp; return cmp;
return 0; return 0;
}; }
/** /**
* Inject properties from seed. * Inject properties from seed.
* @private * @private
* @param {Buffer} seed * @param {Buffer} seed
*/ */
HDPrivateKey.prototype.fromSeed = function fromSeed(seed) { fromSeed(seed) {
assert(Buffer.isBuffer(seed)); assert(Buffer.isBuffer(seed));
if (seed.length * 8 < common.MIN_ENTROPY if (seed.length * 8 < common.MIN_ENTROPY
@ -444,69 +445,69 @@ HDPrivateKey.prototype.fromSeed = function fromSeed(seed) {
this.publicKey = secp256k1.publicKeyCreate(left, true); this.publicKey = secp256k1.publicKeyCreate(left, true);
return this; return this;
}; }
/** /**
* Instantiate an hd private key from a 512 bit seed. * Instantiate an hd private key from a 512 bit seed.
* @param {Buffer} seed * @param {Buffer} seed
* @returns {HDPrivateKey} * @returns {HDPrivateKey}
*/ */
HDPrivateKey.fromSeed = function fromSeed(seed) { static fromSeed(seed) {
return new HDPrivateKey().fromSeed(seed); return new this().fromSeed(seed);
}; }
/** /**
* Inject properties from a mnemonic. * Inject properties from a mnemonic.
* @private * @private
* @param {Mnemonic} mnemonic * @param {Mnemonic} mnemonic
*/ */
HDPrivateKey.prototype.fromMnemonic = function fromMnemonic(mnemonic) { fromMnemonic(mnemonic) {
assert(mnemonic instanceof Mnemonic); assert(mnemonic instanceof Mnemonic);
return this.fromSeed(mnemonic.toSeed()); return this.fromSeed(mnemonic.toSeed());
}; }
/** /**
* Instantiate an hd private key from a mnemonic. * Instantiate an hd private key from a mnemonic.
* @param {Mnemonic} mnemonic * @param {Mnemonic} mnemonic
* @returns {HDPrivateKey} * @returns {HDPrivateKey}
*/ */
HDPrivateKey.fromMnemonic = function fromMnemonic(mnemonic) { static fromMnemonic(mnemonic) {
return new HDPrivateKey().fromMnemonic(mnemonic); return new this().fromMnemonic(mnemonic);
}; }
/** /**
* Inject properties from a mnemonic. * Inject properties from a mnemonic.
* @private * @private
* @param {String} mnemonic * @param {String} mnemonic
*/ */
HDPrivateKey.prototype.fromPhrase = function fromPhrase(phrase) { fromPhrase(phrase) {
const mnemonic = Mnemonic.fromPhrase(phrase); const mnemonic = Mnemonic.fromPhrase(phrase);
this.fromMnemonic(mnemonic); this.fromMnemonic(mnemonic);
return this; return this;
}; }
/** /**
* Instantiate an hd private key from a phrase. * Instantiate an hd private key from a phrase.
* @param {String} phrase * @param {String} phrase
* @returns {HDPrivateKey} * @returns {HDPrivateKey}
*/ */
HDPrivateKey.fromPhrase = function fromPhrase(phrase) { static fromPhrase(phrase) {
return new HDPrivateKey().fromPhrase(phrase); return new this().fromPhrase(phrase);
}; }
/** /**
* Inject properties from privateKey and entropy. * Inject properties from privateKey and entropy.
* @private * @private
* @param {Buffer} key * @param {Buffer} key
* @param {Buffer} entropy * @param {Buffer} entropy
*/ */
HDPrivateKey.prototype.fromKey = function fromKey(key, entropy) { fromKey(key, entropy) {
assert(Buffer.isBuffer(key) && key.length === 32); assert(Buffer.isBuffer(key) && key.length === 32);
assert(Buffer.isBuffer(entropy) && entropy.length === 32); assert(Buffer.isBuffer(entropy) && entropy.length === 32);
this.depth = 0; this.depth = 0;
@ -516,50 +517,50 @@ HDPrivateKey.prototype.fromKey = function fromKey(key, entropy) {
this.privateKey = key; this.privateKey = key;
this.publicKey = secp256k1.publicKeyCreate(key, true); this.publicKey = secp256k1.publicKeyCreate(key, true);
return this; return this;
}; }
/** /**
* Create an hd private key from a key and entropy bytes. * Create an hd private key from a key and entropy bytes.
* @param {Buffer} key * @param {Buffer} key
* @param {Buffer} entropy * @param {Buffer} entropy
* @returns {HDPrivateKey} * @returns {HDPrivateKey}
*/ */
HDPrivateKey.fromKey = function fromKey(key, entropy) { static fromKey(key, entropy) {
return new HDPrivateKey().fromKey(key, entropy); return new this().fromKey(key, entropy);
}; }
/** /**
* Generate an hd private key. * Generate an hd private key.
* @returns {HDPrivateKey} * @returns {HDPrivateKey}
*/ */
HDPrivateKey.generate = function generate() { static generate() {
const key = secp256k1.generatePrivateKey(); const key = secp256k1.generatePrivateKey();
const entropy = random.randomBytes(32); const entropy = random.randomBytes(32);
return HDPrivateKey.fromKey(key, entropy); return HDPrivateKey.fromKey(key, entropy);
}; }
/** /**
* Inject properties from base58 key. * Inject properties from base58 key.
* @private * @private
* @param {Base58String} xkey * @param {Base58String} xkey
* @param {Network?} network * @param {Network?} network
*/ */
HDPrivateKey.prototype.fromBase58 = function fromBase58(xkey, network) { fromBase58(xkey, network) {
assert(typeof xkey === 'string'); assert(typeof xkey === 'string');
return this.fromRaw(base58.decode(xkey), network); return this.fromRaw(base58.decode(xkey), network);
}; }
/** /**
* Inject properties from serialized data. * Inject properties from serialized data.
* @private * @private
* @param {BufferReader} br * @param {BufferReader} br
* @param {(Network|NetworkType)?} network * @param {(Network|NetworkType)?} network
*/ */
HDPrivateKey.prototype.fromReader = function fromReader(br, network) { fromReader(br, network) {
const version = br.readU32BE(); const version = br.readU32BE();
Network.fromPrivate(version, network); Network.fromPrivate(version, network);
@ -575,45 +576,45 @@ HDPrivateKey.prototype.fromReader = function fromReader(br, network) {
br.verifyChecksum(hash256.digest); br.verifyChecksum(hash256.digest);
return this; return this;
}; }
/** /**
* Inject properties from serialized data. * Inject properties from serialized data.
* @private * @private
* @param {Buffer} data * @param {Buffer} data
* @param {(Network|NetworkType)?} network * @param {(Network|NetworkType)?} network
*/ */
HDPrivateKey.prototype.fromRaw = function fromRaw(data, network) { fromRaw(data, network) {
return this.fromReader(new BufferReader(data), network); return this.fromReader(new BufferReader(data), network);
}; }
/** /**
* Serialize key to a base58 string. * Serialize key to a base58 string.
* @param {(Network|NetworkType)?} network * @param {(Network|NetworkType)?} network
* @returns {Base58String} * @returns {Base58String}
*/ */
HDPrivateKey.prototype.toBase58 = function toBase58(network) { toBase58(network) {
return base58.encode(this.toRaw(network)); return base58.encode(this.toRaw(network));
}; }
/** /**
* Calculate serialization size. * Calculate serialization size.
* @returns {Number} * @returns {Number}
*/ */
HDPrivateKey.prototype.getSize = function getSize() { getSize() {
return 82; return 82;
}; }
/** /**
* Write the key to a buffer writer. * Write the key to a buffer writer.
* @param {BufferWriter} bw * @param {BufferWriter} bw
* @param {(Network|NetworkType)?} network * @param {(Network|NetworkType)?} network
*/ */
HDPrivateKey.prototype.toWriter = function toWriter(bw, network) { toWriter(bw, network) {
network = Network.get(network); network = Network.get(network);
bw.writeU32BE(network.keyPrefix.xprivkey); bw.writeU32BE(network.keyPrefix.xprivkey);
@ -626,97 +627,98 @@ HDPrivateKey.prototype.toWriter = function toWriter(bw, network) {
bw.writeChecksum(hash256.digest); bw.writeChecksum(hash256.digest);
return bw; return bw;
}; }
/** /**
* Serialize the key. * Serialize the key.
* @param {(Network|NetworkType)?} network * @param {(Network|NetworkType)?} network
* @returns {Buffer} * @returns {Buffer}
*/ */
HDPrivateKey.prototype.toRaw = function toRaw(network) { toRaw(network) {
return this.toWriter(new StaticWriter(82), network).render(); return this.toWriter(new StaticWriter(82), network).render();
}; }
/** /**
* Instantiate an HD private key from a base58 string. * Instantiate an HD private key from a base58 string.
* @param {Base58String} xkey * @param {Base58String} xkey
* @param {Network?} network * @param {Network?} network
* @returns {HDPrivateKey} * @returns {HDPrivateKey}
*/ */
HDPrivateKey.fromBase58 = function fromBase58(xkey, network) { static fromBase58(xkey, network) {
return new HDPrivateKey().fromBase58(xkey, network); return new this().fromBase58(xkey, network);
}; }
/** /**
* Instantiate key from buffer reader. * Instantiate key from buffer reader.
* @param {BufferReader} br * @param {BufferReader} br
* @param {(Network|NetworkType)?} network * @param {(Network|NetworkType)?} network
* @returns {HDPrivateKey} * @returns {HDPrivateKey}
*/ */
HDPrivateKey.fromReader = function fromReader(br, network) { static fromReader(br, network) {
return new HDPrivateKey().fromReader(br, network); return new this().fromReader(br, network);
}; }
/** /**
* Instantiate key from serialized data. * Instantiate key from serialized data.
* @param {Buffer} data * @param {Buffer} data
* @param {(Network|NetworkType)?} network * @param {(Network|NetworkType)?} network
* @returns {HDPrivateKey} * @returns {HDPrivateKey}
*/ */
HDPrivateKey.fromRaw = function fromRaw(data, network) { static fromRaw(data, network) {
return new HDPrivateKey().fromRaw(data, network); return new this().fromRaw(data, network);
}; }
/** /**
* Convert key to a more json-friendly object. * Convert key to a more json-friendly object.
* @returns {Object} * @returns {Object}
*/ */
HDPrivateKey.prototype.toJSON = function toJSON(network) { toJSON(network) {
return { return {
xprivkey: this.xprivkey(network) xprivkey: this.xprivkey(network)
}; };
}; }
/** /**
* Inject properties from json object. * Inject properties from json object.
* @private * @private
* @param {Object} json * @param {Object} json
* @param {Network?} network * @param {Network?} network
*/ */
HDPrivateKey.prototype.fromJSON = function fromJSON(json, network) { fromJSON(json, network) {
assert(json.xprivkey, 'Could not handle key JSON.'); assert(json.xprivkey, 'Could not handle key JSON.');
this.fromBase58(json.xprivkey, network); this.fromBase58(json.xprivkey, network);
return this; return this;
}; }
/** /**
* Instantiate an HDPrivateKey from a jsonified key object. * Instantiate an HDPrivateKey from a jsonified key object.
* @param {Object} json - The jsonified key object. * @param {Object} json - The jsonified key object.
* @param {Network?} network * @param {Network?} network
* @returns {HDPrivateKey} * @returns {HDPrivateKey}
*/ */
HDPrivateKey.fromJSON = function fromJSON(json, network) { static fromJSON(json, network) {
return new HDPrivateKey().fromJSON(json, network); return new this().fromJSON(json, network);
}; }
/** /**
* Test whether an object is an HDPrivateKey. * Test whether an object is an HDPrivateKey.
* @param {Object} obj * @param {Object} obj
* @returns {Boolean} * @returns {Boolean}
*/ */
HDPrivateKey.isHDPrivateKey = function isHDPrivateKey(obj) { static isHDPrivateKey(obj) {
return obj instanceof HDPrivateKey; return obj instanceof HDPrivateKey;
}; }
}
/* /*
* Expose * Expose

View File

@ -22,6 +22,16 @@ const common = require('./common');
/** /**
* HDPublicKey * HDPublicKey
* @alias module:hd.PublicKey * @alias module:hd.PublicKey
* @property {Number} depth
* @property {Number} parentFingerPrint
* @property {Number} childIndex
* @property {Buffer} chainCode
* @property {Buffer} publicKey
*/
class HDPublicKey {
/**
* Create an HD public key.
* @constructor * @constructor
* @param {Object|Base58String} options * @param {Object|Base58String} options
* @param {Base58String?} options.xkey - Serialized base58 key. * @param {Base58String?} options.xkey - Serialized base58 key.
@ -30,17 +40,9 @@ const common = require('./common');
* @param {Number?} options.childIndex * @param {Number?} options.childIndex
* @param {Buffer?} options.chainCode * @param {Buffer?} options.chainCode
* @param {Buffer?} options.publicKey * @param {Buffer?} options.publicKey
* @property {Number} depth
* @property {Number} parentFingerPrint
* @property {Number} childIndex
* @property {Buffer} chainCode
* @property {Buffer} publicKey
*/ */
function HDPublicKey(options) { constructor(options) {
if (!(this instanceof HDPublicKey))
return new HDPublicKey(options);
this.depth = 0; this.depth = 0;
this.parentFingerPrint = 0; this.parentFingerPrint = 0;
this.childIndex = 0; this.childIndex = 0;
@ -51,15 +53,15 @@ function HDPublicKey(options) {
if (options) if (options)
this.fromOptions(options); this.fromOptions(options);
} }
/** /**
* Inject properties from options object. * Inject properties from options object.
* @private * @private
* @param {Object} options * @param {Object} options
*/ */
HDPublicKey.prototype.fromOptions = function fromOptions(options) { fromOptions(options) {
assert(options, 'No options for HDPublicKey'); assert(options, 'No options for HDPublicKey');
assert((options.depth & 0xff) === options.depth); assert((options.depth & 0xff) === options.depth);
assert((options.parentFingerPrint >>> 0) === options.parentFingerPrint); assert((options.parentFingerPrint >>> 0) === options.parentFingerPrint);
@ -74,50 +76,50 @@ HDPublicKey.prototype.fromOptions = function fromOptions(options) {
this.publicKey = options.publicKey; this.publicKey = options.publicKey;
return this; return this;
}; }
/** /**
* Instantiate HD public key from options object. * Instantiate HD public key from options object.
* @param {Object} options * @param {Object} options
* @returns {HDPublicKey} * @returns {HDPublicKey}
*/ */
HDPublicKey.fromOptions = function fromOptions(options) { static fromOptions(options) {
return new HDPublicKey().fromOptions(options); return new this().fromOptions(options);
}; }
/** /**
* Get HD public key (self). * Get HD public key (self).
* @returns {HDPublicKey} * @returns {HDPublicKey}
*/ */
HDPublicKey.prototype.toPublic = function toPublic() { toPublic() {
return this; return this;
}; }
/** /**
* Get cached base58 xprivkey (always null here). * Get cached base58 xprivkey (always null here).
* @returns {null} * @returns {null}
*/ */
HDPublicKey.prototype.xprivkey = function xprivkey(network) { xprivkey(network) {
return null; return null;
}; }
/** /**
* Get cached base58 xpubkey. * Get cached base58 xpubkey.
* @returns {Base58String} * @returns {Base58String}
*/ */
HDPublicKey.prototype.xpubkey = function xpubkey(network) { xpubkey(network) {
return this.toBase58(network); return this.toBase58(network);
}; }
/** /**
* Destroy the key (zeroes chain code and pubkey). * Destroy the key (zeroes chain code and pubkey).
*/ */
HDPublicKey.prototype.destroy = function destroy() { destroy() {
this.depth = 0; this.depth = 0;
this.childIndex = 0; this.childIndex = 0;
this.parentFingerPrint = 0; this.parentFingerPrint = 0;
@ -126,9 +128,9 @@ HDPublicKey.prototype.destroy = function destroy() {
cleanse(this.publicKey); cleanse(this.publicKey);
this.fingerPrint = -1; this.fingerPrint = -1;
}; }
/** /**
* Derive a child key. * Derive a child key.
* @param {Number} index - Derivation index. * @param {Number} index - Derivation index.
* @param {Boolean?} hardened - Whether the derivation * @param {Boolean?} hardened - Whether the derivation
@ -137,7 +139,7 @@ HDPublicKey.prototype.destroy = function destroy() {
* @throws on `hardened` * @throws on `hardened`
*/ */
HDPublicKey.prototype.derive = function derive(index, hardened) { derive(index, hardened) {
assert(typeof index === 'number'); assert(typeof index === 'number');
if ((index >>> 0) !== index) if ((index >>> 0) !== index)
@ -178,7 +180,7 @@ HDPublicKey.prototype.derive = function derive(index, hardened) {
this.fingerPrint = fp.readUInt32BE(0, true); this.fingerPrint = fp.readUInt32BE(0, true);
} }
const child = new HDPublicKey(); const child = new this.constructor();
child.depth = this.depth + 1; child.depth = this.depth + 1;
child.parentFingerPrint = this.fingerPrint; child.parentFingerPrint = this.fingerPrint;
child.childIndex = index; child.childIndex = index;
@ -188,20 +190,20 @@ HDPublicKey.prototype.derive = function derive(index, hardened) {
common.cache.set(id, child); common.cache.set(id, child);
return child; return child;
}; }
/** /**
* Unique HD key ID. * Unique HD key ID.
* @private * @private
* @param {Number} index * @param {Number} index
* @returns {String} * @returns {String}
*/ */
HDPublicKey.prototype.getID = function getID(index) { getID(index) {
return 'b' + this.publicKey.toString('hex') + index; return 'b' + this.publicKey.toString('hex') + index;
}; }
/** /**
* Derive a BIP44 account key (does not derive, only ensures account key). * Derive a BIP44 account key (does not derive, only ensures account key).
* @method * @method
* @param {Number} purpose * @param {Number} purpose
@ -211,52 +213,52 @@ HDPublicKey.prototype.getID = function getID(index) {
* @throws Error if key is not already an account key. * @throws Error if key is not already an account key.
*/ */
HDPublicKey.prototype.deriveAccount = function deriveAccount(purpose, type, account) { deriveAccount(purpose, type, account) {
assert((purpose >>> 0) === purpose); assert((purpose >>> 0) === purpose);
assert((type >>> 0) === type); assert((type >>> 0) === type);
assert((account >>> 0) === account); assert((account >>> 0) === account);
assert(this.isAccount(account), 'Cannot derive account index.'); assert(this.isAccount(account), 'Cannot derive account index.');
return this; return this;
}; }
/** /**
* Test whether the key is a master key. * Test whether the key is a master key.
* @method * @method
* @returns {Boolean} * @returns {Boolean}
*/ */
HDPublicKey.prototype.isMaster = function isMaster() { isMaster() {
return common.isMaster(this); return common.isMaster(this);
}; }
/** /**
* Test whether the key is (most likely) a BIP44 account key. * Test whether the key is (most likely) a BIP44 account key.
* @method * @method
* @param {Number?} account * @param {Number?} account
* @returns {Boolean} * @returns {Boolean}
*/ */
HDPublicKey.prototype.isAccount = function isAccount(account) { isAccount(account) {
return common.isAccount(this, account); return common.isAccount(this, account);
}; }
/** /**
* Test whether a string is a valid path. * Test whether a string is a valid path.
* @param {String} path * @param {String} path
* @param {Boolean?} hardened * @param {Boolean?} hardened
* @returns {Boolean} * @returns {Boolean}
*/ */
HDPublicKey.isValidPath = function isValidPath(path) { static isValidPath(path) {
try { try {
common.parsePath(path, false); common.parsePath(path, false);
return true; return true;
} catch (e) { } catch (e) {
return false; return false;
} }
}; }
/** /**
* Derive a key from a derivation path. * Derive a key from a derivation path.
* @param {String} path * @param {String} path
* @returns {HDPublicKey} * @returns {HDPublicKey}
@ -264,7 +266,7 @@ HDPublicKey.isValidPath = function isValidPath(path) {
* @throws Error if hardened. * @throws Error if hardened.
*/ */
HDPublicKey.prototype.derivePath = function derivePath(path) { derivePath(path) {
const indexes = common.parsePath(path, false); const indexes = common.parsePath(path, false);
let key = this; let key = this;
@ -273,15 +275,15 @@ HDPublicKey.prototype.derivePath = function derivePath(path) {
key = key.derive(index); key = key.derive(index);
return key; return key;
}; }
/** /**
* Compare a key against an object. * Compare a key against an object.
* @param {Object} obj * @param {Object} obj
* @returns {Boolean} * @returns {Boolean}
*/ */
HDPublicKey.prototype.equals = function equals(obj) { equals(obj) {
assert(HDPublicKey.isHDPublicKey(obj)); assert(HDPublicKey.isHDPublicKey(obj));
return this.depth === obj.depth return this.depth === obj.depth
@ -289,15 +291,15 @@ HDPublicKey.prototype.equals = function equals(obj) {
&& this.childIndex === obj.childIndex && this.childIndex === obj.childIndex
&& this.chainCode.equals(obj.chainCode) && this.chainCode.equals(obj.chainCode)
&& this.publicKey.equals(obj.publicKey); && this.publicKey.equals(obj.publicKey);
}; }
/** /**
* Compare a key against an object. * Compare a key against an object.
* @param {Object} obj * @param {Object} obj
* @returns {Boolean} * @returns {Boolean}
*/ */
HDPublicKey.prototype.compare = function compare(key) { compare(key) {
assert(HDPublicKey.isHDPublicKey(key)); assert(HDPublicKey.isHDPublicKey(key));
let cmp = this.depth - key.depth; let cmp = this.depth - key.depth;
@ -326,51 +328,51 @@ HDPublicKey.prototype.compare = function compare(key) {
return cmp; return cmp;
return 0; return 0;
}; }
/** /**
* Convert key to a more json-friendly object. * Convert key to a more json-friendly object.
* @returns {Object} * @returns {Object}
*/ */
HDPublicKey.prototype.toJSON = function toJSON(network) { toJSON(network) {
return { return {
xpubkey: this.xpubkey(network) xpubkey: this.xpubkey(network)
}; };
}; }
/** /**
* Inject properties from json object. * Inject properties from json object.
* @private * @private
* @param {Object} json * @param {Object} json
* @param {Network?} network * @param {Network?} network
*/ */
HDPublicKey.prototype.fromJSON = function fromJSON(json, network) { fromJSON(json, network) {
assert(json.xpubkey, 'Could not handle HD key JSON.'); assert(json.xpubkey, 'Could not handle HD key JSON.');
this.fromBase58(json.xpubkey, network); this.fromBase58(json.xpubkey, network);
return this; return this;
}; }
/** /**
* Instantiate an HDPublicKey from a jsonified key object. * Instantiate an HDPublicKey from a jsonified key object.
* @param {Object} json - The jsonified transaction object. * @param {Object} json - The jsonified transaction object.
* @param {Network?} network * @param {Network?} network
* @returns {HDPrivateKey} * @returns {HDPrivateKey}
*/ */
HDPublicKey.fromJSON = function fromJSON(json, network) { static fromJSON(json, network) {
return new HDPublicKey().fromJSON(json, network); return new this().fromJSON(json, network);
}; }
/** /**
* Test whether an object is in the form of a base58 xpubkey. * Test whether an object is in the form of a base58 xpubkey.
* @param {String} data * @param {String} data
* @param {(Network|NetworkType)?} network * @param {(Network|NetworkType)?} network
* @returns {Boolean} * @returns {Boolean}
*/ */
HDPublicKey.isBase58 = function isBase58(data, network) { static isBase58(data, network) {
if (typeof data !== 'string') if (typeof data !== 'string')
return false; return false;
@ -385,16 +387,16 @@ HDPublicKey.isBase58 = function isBase58(data, network) {
} catch (e) { } catch (e) {
return false; return false;
} }
}; }
/** /**
* Test whether a buffer has a valid network prefix. * Test whether a buffer has a valid network prefix.
* @param {Buffer} data * @param {Buffer} data
* @param {(Network|NetworkType)?} network * @param {(Network|NetworkType)?} network
* @returns {NetworkType} * @returns {NetworkType}
*/ */
HDPublicKey.isRaw = function isRaw(data, network) { static isRaw(data, network) {
if (!Buffer.isBuffer(data)) if (!Buffer.isBuffer(data))
return false; return false;
@ -409,28 +411,28 @@ HDPublicKey.isRaw = function isRaw(data, network) {
} catch (e) { } catch (e) {
return false; return false;
} }
}; }
/** /**
* Inject properties from a base58 key. * Inject properties from a base58 key.
* @private * @private
* @param {Base58String} xkey * @param {Base58String} xkey
* @param {Network?} network * @param {Network?} network
*/ */
HDPublicKey.prototype.fromBase58 = function fromBase58(xkey, network) { fromBase58(xkey, network) {
assert(typeof xkey === 'string'); assert(typeof xkey === 'string');
return this.fromRaw(base58.decode(xkey), network); return this.fromRaw(base58.decode(xkey), network);
}; }
/** /**
* Inject properties from serialized data. * Inject properties from serialized data.
* @private * @private
* @param {BufferReader} br * @param {BufferReader} br
* @param {(Network|NetworkType)?} network * @param {(Network|NetworkType)?} network
*/ */
HDPublicKey.prototype.fromReader = function fromReader(br, network) { fromReader(br, network) {
const version = br.readU32BE(); const version = br.readU32BE();
Network.fromPublic(version, network); Network.fromPublic(version, network);
@ -444,36 +446,36 @@ HDPublicKey.prototype.fromReader = function fromReader(br, network) {
br.verifyChecksum(hash256.digest); br.verifyChecksum(hash256.digest);
return this; return this;
}; }
/** /**
* Inject properties from serialized data. * Inject properties from serialized data.
* @private * @private
* @param {Buffer} data * @param {Buffer} data
* @param {(Network|NetworkType)?} network * @param {(Network|NetworkType)?} network
*/ */
HDPublicKey.prototype.fromRaw = function fromRaw(data, network) { fromRaw(data, network) {
return this.fromReader(new BufferReader(data), network); return this.fromReader(new BufferReader(data), network);
}; }
/** /**
* Serialize key data to base58 extended key. * Serialize key data to base58 extended key.
* @param {(Network|NetworkType)?} network * @param {(Network|NetworkType)?} network
* @returns {Base58String} * @returns {Base58String}
*/ */
HDPublicKey.prototype.toBase58 = function toBase58(network) { toBase58(network) {
return base58.encode(this.toRaw(network)); return base58.encode(this.toRaw(network));
}; }
/** /**
* Write the key to a buffer writer. * Write the key to a buffer writer.
* @param {BufferWriter} bw * @param {BufferWriter} bw
* @param {(Network|NetworkType)?} network * @param {(Network|NetworkType)?} network
*/ */
HDPublicKey.prototype.toWriter = function toWriter(bw, network) { toWriter(bw, network) {
network = Network.get(network); network = Network.get(network);
bw.writeU32BE(network.keyPrefix.xpubkey); bw.writeU32BE(network.keyPrefix.xpubkey);
@ -485,69 +487,70 @@ HDPublicKey.prototype.toWriter = function toWriter(bw, network) {
bw.writeChecksum(hash256.digest); bw.writeChecksum(hash256.digest);
return bw; return bw;
}; }
/** /**
* Calculate serialization size. * Calculate serialization size.
* @returns {Number} * @returns {Number}
*/ */
HDPublicKey.prototype.getSize = function getSize() { getSize() {
return 82; return 82;
}; }
/** /**
* Serialize the key. * Serialize the key.
* @param {(Network|NetworkType)?} network * @param {(Network|NetworkType)?} network
* @returns {Buffer} * @returns {Buffer}
*/ */
HDPublicKey.prototype.toRaw = function toRaw(network) { toRaw(network) {
return this.toWriter(new StaticWriter(82), network).render(); return this.toWriter(new StaticWriter(82), network).render();
}; }
/** /**
* Instantiate an HD public key from a base58 string. * Instantiate an HD public key from a base58 string.
* @param {Base58String} xkey * @param {Base58String} xkey
* @param {Network?} network * @param {Network?} network
* @returns {HDPublicKey} * @returns {HDPublicKey}
*/ */
HDPublicKey.fromBase58 = function fromBase58(xkey, network) { static fromBase58(xkey, network) {
return new HDPublicKey().fromBase58(xkey, network); return new this().fromBase58(xkey, network);
}; }
/** /**
* Instantiate key from serialized data. * Instantiate key from serialized data.
* @param {BufferReader} br * @param {BufferReader} br
* @param {(Network|NetworkType)?} network * @param {(Network|NetworkType)?} network
* @returns {HDPublicKey} * @returns {HDPublicKey}
*/ */
HDPublicKey.fromReader = function fromReader(br, network) { static fromReader(br, network) {
return new HDPublicKey().fromReader(br, network); return new this().fromReader(br, network);
}; }
/** /**
* Instantiate key from serialized data. * Instantiate key from serialized data.
* @param {Buffer} data * @param {Buffer} data
* @param {(Network|NetworkType)?} network * @param {(Network|NetworkType)?} network
* @returns {HDPublicKey} * @returns {HDPublicKey}
*/ */
HDPublicKey.fromRaw = function fromRaw(data, network) { static fromRaw(data, network) {
return new HDPublicKey().fromRaw(data, network); return new this().fromRaw(data, network);
}; }
/** /**
* Test whether an object is a HDPublicKey. * Test whether an object is a HDPublicKey.
* @param {Object} obj * @param {Object} obj
* @returns {Boolean} * @returns {Boolean}
*/ */
HDPublicKey.isHDPublicKey = function isHDPublicKey(obj) { static isHDPublicKey(obj) {
return obj instanceof HDPublicKey; return obj instanceof HDPublicKey;
}; }
}
/* /*
* Expose * Expose

View File

@ -14,15 +14,9 @@ const StaticWriter = require('bufio/lib/staticwriter');
const TX = require('../primitives/tx'); const TX = require('../primitives/tx');
/** /**
* Mempool Entry
* Represents a mempool entry. * Represents a mempool entry.
* @alias module:mempool.MempoolEntry * @alias module:mempool.MempoolEntry
* @constructor
* @param {Object} options
* @param {TX} options.tx - Transaction in mempool.
* @param {Number} options.height - Entry height.
* @param {Number} options.priority - Entry priority.
* @param {Number} options.time - Entry time.
* @param {Amount} options.value - Value of on-chain coins.
* @property {TX} tx * @property {TX} tx
* @property {Number} height * @property {Number} height
* @property {Number} priority * @property {Number} priority
@ -30,10 +24,19 @@ const TX = require('../primitives/tx');
* @property {Amount} value * @property {Amount} value
*/ */
function MempoolEntry(options) { class MempoolEntry {
if (!(this instanceof MempoolEntry)) /**
return new MempoolEntry(options); * Create a mempool entry.
* @constructor
* @param {Object} options
* @param {TX} options.tx - Transaction in mempool.
* @param {Number} options.height - Entry height.
* @param {Number} options.priority - Entry priority.
* @param {Number} options.time - Entry time.
* @param {Amount} options.value - Value of on-chain coins.
*/
constructor(options) {
this.tx = null; this.tx = null;
this.height = -1; this.height = -1;
this.size = 0; this.size = 0;
@ -50,15 +53,15 @@ function MempoolEntry(options) {
if (options) if (options)
this.fromOptions(options); this.fromOptions(options);
} }
/** /**
* Inject properties from options object. * Inject properties from options object.
* @private * @private
* @param {Object} options * @param {Object} options
*/ */
MempoolEntry.prototype.fromOptions = function fromOptions(options) { fromOptions(options) {
this.tx = options.tx; this.tx = options.tx;
this.height = options.height; this.height = options.height;
this.size = options.size; this.size = options.size;
@ -73,26 +76,26 @@ MempoolEntry.prototype.fromOptions = function fromOptions(options) {
this.descFee = options.descFee; this.descFee = options.descFee;
this.descSize = options.descSize; this.descSize = options.descSize;
return this; return this;
}; }
/** /**
* Instantiate mempool entry from options. * Instantiate mempool entry from options.
* @param {Object} options * @param {Object} options
* @returns {MempoolEntry} * @returns {MempoolEntry}
*/ */
MempoolEntry.fromOptions = function fromOptions(options) { static fromOptions(options) {
return new MempoolEntry().fromOptions(options); return new this().fromOptions(options);
}; }
/** /**
* Inject properties from transaction. * Inject properties from transaction.
* @private * @private
* @param {TX} tx * @param {TX} tx
* @param {Number} height * @param {Number} height
*/ */
MempoolEntry.prototype.fromTX = function fromTX(tx, view, height) { fromTX(tx, view, height) {
const flags = Script.flags.STANDARD_VERIFY_FLAGS; const flags = Script.flags.STANDARD_VERIFY_FLAGS;
const value = tx.getChainValue(view); const value = tx.getChainValue(view);
const sigops = tx.getSigopsCost(view, flags); const sigops = tx.getSigopsCost(view, flags);
@ -126,39 +129,39 @@ MempoolEntry.prototype.fromTX = function fromTX(tx, view, height) {
this.descSize = size; this.descSize = size;
return this; return this;
}; }
/** /**
* Create a mempool entry from a TX. * Create a mempool entry from a TX.
* @param {TX} tx * @param {TX} tx
* @param {Number} height - Entry height. * @param {Number} height - Entry height.
* @returns {MempoolEntry} * @returns {MempoolEntry}
*/ */
MempoolEntry.fromTX = function fromTX(tx, view, height) { static fromTX(tx, view, height) {
return new MempoolEntry().fromTX(tx, view, height); return new this().fromTX(tx, view, height);
}; }
/** /**
* Calculate transaction hash. * Calculate transaction hash.
* @param {String?} enc * @param {String?} enc
* @returns {Hash} * @returns {Hash}
*/ */
MempoolEntry.prototype.hash = function hash(enc) { hash(enc) {
return this.tx.hash(enc); return this.tx.hash(enc);
}; }
/** /**
* Calculate reverse transaction hash. * Calculate reverse transaction hash.
* @returns {Hash} * @returns {Hash}
*/ */
MempoolEntry.prototype.txid = function txid() { txid() {
return this.tx.txid(); return this.tx.txid();
}; }
/** /**
* Calculate priority, taking into account * Calculate priority, taking into account
* the entry height delta, modified size, * the entry height delta, modified size,
* and chain value. * and chain value.
@ -166,61 +169,64 @@ MempoolEntry.prototype.txid = function txid() {
* @returns {Number} Priority. * @returns {Number} Priority.
*/ */
MempoolEntry.prototype.getPriority = function getPriority(height) { getPriority(height) {
const delta = height - this.height; const delta = height - this.height;
const priority = (delta * this.value) / this.size; const priority = (delta * this.value) / this.size;
let result = this.priority + Math.floor(priority); let result = this.priority + Math.floor(priority);
if (result < 0) if (result < 0)
result = 0; result = 0;
return result;
};
/** return result;
}
/**
* Get fee. * Get fee.
* @returns {Amount} * @returns {Amount}
*/ */
MempoolEntry.prototype.getFee = function getFee() { getFee() {
return this.fee; return this.fee;
}; }
/** /**
* Get delta fee. * Get delta fee.
* @returns {Amount} * @returns {Amount}
*/ */
MempoolEntry.prototype.getDeltaFee = function getDeltaFee() { getDeltaFee() {
return this.deltaFee; return this.deltaFee;
}; }
/** /**
* Calculate fee rate. * Calculate fee rate.
* @returns {Rate} * @returns {Rate}
*/ */
MempoolEntry.prototype.getRate = function getRate() { getRate() {
return policy.getRate(this.size, this.fee); return policy.getRate(this.size, this.fee);
}; }
/** /**
* Calculate delta fee rate. * Calculate delta fee rate.
* @returns {Rate} * @returns {Rate}
*/ */
MempoolEntry.prototype.getDeltaRate = function getDeltaRate() { getDeltaRate() {
return policy.getRate(this.size, this.deltaFee); return policy.getRate(this.size, this.deltaFee);
}; }
/** /**
* Calculate fee cumulative descendant rate. * Calculate fee cumulative descendant rate.
* @returns {Rate} * @returns {Rate}
*/ */
MempoolEntry.prototype.getDescRate = function getDescRate() { getDescRate() {
return policy.getRate(this.descSize, this.descFee); return policy.getRate(this.descSize, this.descFee);
}; }
/** /**
* Calculate the memory usage of a transaction. * Calculate the memory usage of a transaction.
* Note that this only calculates the JS heap * Note that this only calculates the JS heap
* size. Sizes of buffers are ignored (the v8 * size. Sizes of buffers are ignored (the v8
@ -230,7 +236,7 @@ MempoolEntry.prototype.getDescRate = function getDescRate() {
* @returns {Number} Usage in bytes. * @returns {Number} Usage in bytes.
*/ */
MempoolEntry.prototype.memUsage = function memUsage() { memUsage() {
const tx = this.tx; const tx = this.tx;
let total = 0; let total = 0;
@ -283,9 +289,9 @@ MempoolEntry.prototype.memUsage = function memUsage() {
} }
return total; return total;
}; }
/** /**
* Test whether the entry is free with * Test whether the entry is free with
* the current priority (calculated by * the current priority (calculated by
* current height). * current height).
@ -293,26 +299,26 @@ MempoolEntry.prototype.memUsage = function memUsage() {
* @returns {Boolean} * @returns {Boolean}
*/ */
MempoolEntry.prototype.isFree = function isFree(height) { isFree(height) {
const priority = this.getPriority(height); const priority = this.getPriority(height);
return priority > policy.FREE_THRESHOLD; return priority > policy.FREE_THRESHOLD;
}; }
/** /**
* Get entry serialization size. * Get entry serialization size.
* @returns {Number} * @returns {Number}
*/ */
MempoolEntry.prototype.getSize = function getSize() { getSize() {
return this.tx.getSize() + 42; return this.tx.getSize() + 42;
}; }
/** /**
* Serialize entry to a buffer. * Serialize entry to a buffer.
* @returns {Buffer} * @returns {Buffer}
*/ */
MempoolEntry.prototype.toRaw = function toRaw() { toRaw() {
const bw = new StaticWriter(this.getSize()); const bw = new StaticWriter(this.getSize());
bw.writeBytes(this.tx.toRaw()); bw.writeBytes(this.tx.toRaw());
bw.writeU32(this.height); bw.writeU32(this.height);
@ -325,16 +331,16 @@ MempoolEntry.prototype.toRaw = function toRaw() {
bw.writeU8(this.coinbase ? 1 : 0); bw.writeU8(this.coinbase ? 1 : 0);
bw.writeU8(this.dependencies ? 1 : 0); bw.writeU8(this.dependencies ? 1 : 0);
return bw.render(); return bw.render();
}; }
/** /**
* Inject properties from serialized data. * Inject properties from serialized data.
* @private * @private
* @param {Buffer} data * @param {Buffer} data
* @returns {MempoolEntry} * @returns {MempoolEntry}
*/ */
MempoolEntry.prototype.fromRaw = function fromRaw(data) { fromRaw(data) {
const br = new BufferReader(data); const br = new BufferReader(data);
this.tx = TX.fromReader(br); this.tx = TX.fromReader(br);
this.height = br.readU32(); this.height = br.readU32();
@ -350,17 +356,18 @@ MempoolEntry.prototype.fromRaw = function fromRaw(data) {
this.descFee = this.fee; this.descFee = this.fee;
this.descSize = this.size; this.descSize = this.size;
return this; return this;
}; }
/** /**
* Instantiate entry from serialized data. * Instantiate entry from serialized data.
* @param {Buffer} data * @param {Buffer} data
* @returns {MempoolEntry} * @returns {MempoolEntry}
*/ */
MempoolEntry.fromRaw = function fromRaw(data) { static fromRaw(data) {
return new MempoolEntry().fromRaw(data); return new this().fromRaw(data);
}; }
}
/* /*
* Expose * Expose

View File

@ -27,14 +27,16 @@ const DUMMY = Buffer.alloc(0);
/** /**
* Block Template * Block Template
* @alias module:mining.BlockTemplate * @alias module:mining.BlockTemplate
*/
class BlockTemplate {
/**
* Create a block template.
* @constructor * @constructor
* @param {Object} options * @param {Object} options
*/ */
function BlockTemplate(options) { constructor(options) {
if (!(this instanceof BlockTemplate))
return new BlockTemplate(options);
this.prevBlock = encoding.NULL_HASH; this.prevBlock = encoding.NULL_HASH;
this.version = 1; this.version = 1;
this.height = 0; this.height = 0;
@ -59,16 +61,16 @@ function BlockTemplate(options) {
if (options) if (options)
this.fromOptions(options); this.fromOptions(options);
} }
/** /**
* Inject properties from options. * Inject properties from options.
* @private * @private
* @param {Object} options * @param {Object} options
* @returns {BlockTemplate} * @returns {BlockTemplate}
*/ */
BlockTemplate.prototype.fromOptions = function fromOptions(options) { fromOptions(options) {
assert(options); assert(options);
if (options.prevBlock != null) { if (options.prevBlock != null) {
@ -151,87 +153,87 @@ BlockTemplate.prototype.fromOptions = function fromOptions(options) {
} }
return this; return this;
}; }
/** /**
* Instantiate block template from options. * Instantiate block template from options.
* @param {Object} options * @param {Object} options
* @returns {BlockTemplate} * @returns {BlockTemplate}
*/ */
BlockTemplate.fromOptions = function fromOptions(options) { static fromOptions(options) {
return new BlockTemplate().fromOptions(options); return new this().fromOptions(options);
}; }
/** /**
* Create witness commitment hash. * Create witness commitment hash.
* @returns {Buffer} * @returns {Buffer}
*/ */
BlockTemplate.prototype.getWitnessHash = function getWitnessHash() { getWitnessHash() {
const nonce = encoding.ZERO_HASH; const nonce = encoding.ZERO_HASH;
const leaves = []; const leaves = [];
leaves.push(encoding.ZERO_HASH); leaves.push(encoding.ZERO_HASH);
for (const item of this.items) for (const {tx} of this.items)
leaves.push(item.tx.witnessHash()); leaves.push(tx.witnessHash());
const [root, malleated] = merkle.createRoot(hash256, leaves); const [root, malleated] = merkle.createRoot(hash256, leaves);
assert(!malleated); assert(!malleated);
return hash256.root(root, nonce); return hash256.root(root, nonce);
}; }
/** /**
* Create witness commitment script. * Create witness commitment script.
* @returns {Script} * @returns {Script}
*/ */
BlockTemplate.prototype.getWitnessScript = function getWitnessScript() { getWitnessScript() {
return Script.fromCommitment(this.commitment); return Script.fromCommitment(this.commitment);
}; }
/** /**
* Set the target (bits). * Set the target (bits).
* @param {Number} bits * @param {Number} bits
*/ */
BlockTemplate.prototype.setBits = function setBits(bits) { setBits(bits) {
assert(typeof bits === 'number'); assert(typeof bits === 'number');
this.bits = bits; this.bits = bits;
this.target = common.getTarget(bits); this.target = common.getTarget(bits);
}; }
/** /**
* Set the target (uint256le). * Set the target (uint256le).
* @param {Buffer} target * @param {Buffer} target
*/ */
BlockTemplate.prototype.setTarget = function setTarget(target) { setTarget(target) {
assert(Buffer.isBuffer(target)); assert(Buffer.isBuffer(target));
this.bits = common.getBits(target); this.bits = common.getBits(target);
this.target = target; this.target = target;
}; }
/** /**
* Calculate the block reward. * Calculate the block reward.
* @returns {Amount} * @returns {Amount}
*/ */
BlockTemplate.prototype.getReward = function getReward() { getReward() {
const reward = consensus.getReward(this.height, this.interval); const reward = consensus.getReward(this.height, this.interval);
return reward + this.fees; return reward + this.fees;
}; }
/** /**
* Initialize the default coinbase. * Initialize the default coinbase.
* @param {Buffer} hash - Witness commitment hash. * @param {Buffer} hash - Witness commitment hash.
* @returns {TX} * @returns {TX}
*/ */
BlockTemplate.prototype.createCoinbase = function createCoinbase(hash) { createCoinbase(hash) {
const scale = consensus.WITNESS_SCALE_FACTOR; const scale = consensus.WITNESS_SCALE_FACTOR;
const cb = new TX(); const cb = new TX();
@ -319,13 +321,13 @@ BlockTemplate.prototype.createCoinbase = function createCoinbase(hash) {
'Coinbase input script is too large!'); 'Coinbase input script is too large!');
return cb; return cb;
}; }
/** /**
* Refresh the coinbase and merkle tree. * Refresh the coinbase and merkle tree.
*/ */
BlockTemplate.prototype.refresh = function refresh() { refresh() {
const hash = this.getWitnessHash(); const hash = this.getWitnessHash();
const cb = this.createCoinbase(hash); const cb = this.createCoinbase(hash);
const raw = cb.toNormal(); const raw = cb.toNormal();
@ -348,16 +350,16 @@ BlockTemplate.prototype.refresh = function refresh() {
this.left = left; this.left = left;
this.right = right; this.right = right;
this.tree = MerkleTree.fromItems(this.items); this.tree = MerkleTree.fromItems(this.items);
}; }
/** /**
* Get raw coinbase with desired nonces. * Get raw coinbase with desired nonces.
* @param {Number} nonce1 * @param {Number} nonce1
* @param {Number} nonce2 * @param {Number} nonce2
* @returns {Buffer} * @returns {Buffer}
*/ */
BlockTemplate.prototype.getRawCoinbase = function getRawCoinbase(nonce1, nonce2) { getRawCoinbase(nonce1, nonce2) {
let size = 0; let size = 0;
size += this.left.length; size += this.left.length;
@ -371,22 +373,22 @@ BlockTemplate.prototype.getRawCoinbase = function getRawCoinbase(nonce1, nonce2)
bw.writeBytes(this.right); bw.writeBytes(this.right);
return bw.render(); return bw.render();
}; }
/** /**
* Calculate the merkle root with given nonces. * Calculate the merkle root with given nonces.
* @param {Number} nonce1 * @param {Number} nonce1
* @param {Number} nonce2 * @param {Number} nonce2
* @returns {Buffer} * @returns {Buffer}
*/ */
BlockTemplate.prototype.getRoot = function getRoot(nonce1, nonce2) { getRoot(nonce1, nonce2) {
const raw = this.getRawCoinbase(nonce1, nonce2); const raw = this.getRawCoinbase(nonce1, nonce2);
const hash = hash256.digest(raw); const hash = hash256.digest(raw);
return this.tree.withFirst(hash); return this.tree.withFirst(hash);
}; }
/** /**
* Create raw block header with given parameters. * Create raw block header with given parameters.
* @param {Buffer} root * @param {Buffer} root
* @param {Number} time * @param {Number} time
@ -394,7 +396,7 @@ BlockTemplate.prototype.getRoot = function getRoot(nonce1, nonce2) {
* @returns {Buffer} * @returns {Buffer}
*/ */
BlockTemplate.prototype.getHeader = function getHeader(root, time, nonce) { getHeader(root, time, nonce) {
const bw = new StaticWriter(80); const bw = new StaticWriter(80);
bw.writeU32(this.version); bw.writeU32(this.version);
@ -405,9 +407,9 @@ BlockTemplate.prototype.getHeader = function getHeader(root, time, nonce) {
bw.writeU32(nonce); bw.writeU32(nonce);
return bw.render(); return bw.render();
}; }
/** /**
* Calculate proof with given parameters. * Calculate proof with given parameters.
* @param {Number} nonce1 * @param {Number} nonce1
* @param {Number} nonce2 * @param {Number} nonce2
@ -416,21 +418,21 @@ BlockTemplate.prototype.getHeader = function getHeader(root, time, nonce) {
* @returns {BlockProof} * @returns {BlockProof}
*/ */
BlockTemplate.prototype.getProof = function getProof(nonce1, nonce2, time, nonce) { getProof(nonce1, nonce2, time, nonce) {
const root = this.getRoot(nonce1, nonce2); const root = this.getRoot(nonce1, nonce2);
const data = this.getHeader(root, time, nonce); const data = this.getHeader(root, time, nonce);
const hash = hash256.digest(data); const hash = hash256.digest(data);
return new BlockProof(hash, root, nonce1, nonce2, time, nonce); return new BlockProof(hash, root, nonce1, nonce2, time, nonce);
}; }
/** /**
* Create coinbase from given parameters. * Create coinbase from given parameters.
* @param {Number} nonce1 * @param {Number} nonce1
* @param {Number} nonce2 * @param {Number} nonce2
* @returns {TX} * @returns {TX}
*/ */
BlockTemplate.prototype.getCoinbase = function getCoinbase(nonce1, nonce2) { getCoinbase(nonce1, nonce2) {
const raw = this.getRawCoinbase(nonce1, nonce2); const raw = this.getRawCoinbase(nonce1, nonce2);
const tx = TX.fromRaw(raw); const tx = TX.fromRaw(raw);
@ -442,15 +444,15 @@ BlockTemplate.prototype.getCoinbase = function getCoinbase(nonce1, nonce2) {
} }
return tx; return tx;
}; }
/** /**
* Create block from calculated proof. * Create block from calculated proof.
* @param {BlockProof} proof * @param {BlockProof} proof
* @returns {Block} * @returns {Block}
*/ */
BlockTemplate.prototype.commit = function commit(proof) { commit(proof) {
const root = proof.root; const root = proof.root;
const n1 = proof.nonce1; const n1 = proof.nonce1;
const n2 = proof.nonce2; const n2 = proof.nonce2;
@ -473,56 +475,56 @@ BlockTemplate.prototype.commit = function commit(proof) {
block.txs.push(item.tx); block.txs.push(item.tx);
return block; return block;
}; }
/** /**
* Quick and dirty way to * Quick and dirty way to
* get a coinbase tx object. * get a coinbase tx object.
* @returns {TX} * @returns {TX}
*/ */
BlockTemplate.prototype.toCoinbase = function toCoinbase() { toCoinbase() {
return this.getCoinbase(0, 0); return this.getCoinbase(0, 0);
}; }
/** /**
* Quick and dirty way to get a block * Quick and dirty way to get a block
* object (most likely to be an invalid one). * object (most likely to be an invalid one).
* @returns {Block} * @returns {Block}
*/ */
BlockTemplate.prototype.toBlock = function toBlock() { toBlock() {
const proof = this.getProof(0, 0, this.time, 0); const proof = this.getProof(0, 0, this.time, 0);
return this.commit(proof); return this.commit(proof);
}; }
/** /**
* Calculate the target difficulty. * Calculate the target difficulty.
* @returns {Number} * @returns {Number}
*/ */
BlockTemplate.prototype.getDifficulty = function getDifficulty() { getDifficulty() {
return common.getDifficulty(this.target); return common.getDifficulty(this.target);
}; }
/** /**
* Set the reward output * Set the reward output
* address and refresh. * address and refresh.
* @param {Address} address * @param {Address} address
*/ */
BlockTemplate.prototype.setAddress = function setAddress(address) { setAddress(address) {
this.address = new Address(address); this.address = new Address(address);
this.refresh(); this.refresh();
}; }
/** /**
* Add a transaction to the template. * Add a transaction to the template.
* @param {TX} tx * @param {TX} tx
* @param {CoinView} view * @param {CoinView} view
*/ */
BlockTemplate.prototype.addTX = function addTX(tx, view) { addTX(tx, view) {
assert(!tx.mutable, 'Cannot add mutable TX to block.'); assert(!tx.mutable, 'Cannot add mutable TX to block.');
const item = BlockEntry.fromTX(tx, view, this); const item = BlockEntry.fromTX(tx, view, this);
@ -549,16 +551,16 @@ BlockTemplate.prototype.addTX = function addTX(tx, view) {
this.items.push(item); this.items.push(item);
return true; return true;
}; }
/** /**
* Add a transaction to the template * Add a transaction to the template
* (less verification than addTX). * (less verification than addTX).
* @param {TX} tx * @param {TX} tx
* @param {CoinView?} view * @param {CoinView?} view
*/ */
BlockTemplate.prototype.pushTX = function pushTX(tx, view) { pushTX(tx, view) {
assert(!tx.mutable, 'Cannot add mutable TX to block.'); assert(!tx.mutable, 'Cannot add mutable TX to block.');
if (!view) if (!view)
@ -576,13 +578,12 @@ BlockTemplate.prototype.pushTX = function pushTX(tx, view) {
this.items.push(item); this.items.push(item);
return true; return true;
}; }
}
/** /**
* BlockEntry * Block Entry
* @alias module:mining.BlockEntry * @alias module:mining.BlockEntry
* @constructor
* @param {TX} tx
* @property {TX} tx * @property {TX} tx
* @property {Hash} hash * @property {Hash} hash
* @property {Amount} fee * @property {Amount} fee
@ -593,7 +594,14 @@ BlockTemplate.prototype.pushTX = function pushTX(tx, view) {
* @property {Number} depCount * @property {Number} depCount
*/ */
function BlockEntry(tx) { class BlockEntry {
/**
* Create a block entry.
* @constructor
* @param {TX} tx
*/
constructor(tx) {
this.tx = tx; this.tx = tx;
this.hash = tx.hash('hex'); this.hash = tx.hash('hex');
this.fee = 0; this.fee = 0;
@ -603,9 +611,9 @@ function BlockEntry(tx) {
this.sigops = 0; this.sigops = 0;
this.descRate = 0; this.descRate = 0;
this.depCount = 0; this.depCount = 0;
} }
/** /**
* Instantiate block entry from transaction. * Instantiate block entry from transaction.
* @param {TX} tx * @param {TX} tx
* @param {CoinView} view * @param {CoinView} view
@ -613,8 +621,8 @@ function BlockEntry(tx) {
* @returns {BlockEntry} * @returns {BlockEntry}
*/ */
BlockEntry.fromTX = function fromTX(tx, view, attempt) { static fromTX(tx, view, attempt) {
const item = new BlockEntry(tx); const item = new this(tx);
item.fee = tx.getFee(view); item.fee = tx.getFee(view);
item.rate = tx.getRate(view); item.rate = tx.getRate(view);
item.priority = tx.getPriority(view, attempt.height); item.priority = tx.getPriority(view, attempt.height);
@ -622,17 +630,17 @@ BlockEntry.fromTX = function fromTX(tx, view, attempt) {
item.sigops = tx.getSigopsCost(view, attempt.flags); item.sigops = tx.getSigopsCost(view, attempt.flags);
item.descRate = item.rate; item.descRate = item.rate;
return item; return item;
}; }
/** /**
* Instantiate block entry from mempool entry. * Instantiate block entry from mempool entry.
* @param {MempoolEntry} entry * @param {MempoolEntry} entry
* @param {BlockTemplate} attempt * @param {BlockTemplate} attempt
* @returns {BlockEntry} * @returns {BlockEntry}
*/ */
BlockEntry.fromEntry = function fromEntry(entry, attempt) { static fromEntry(entry, attempt) {
const item = new BlockEntry(entry.tx); const item = new this(entry.tx);
item.fee = entry.getFee(); item.fee = entry.getFee();
item.rate = entry.getDeltaRate(); item.rate = entry.getDeltaRate();
item.priority = entry.getPriority(attempt.height); item.priority = entry.getPriority(attempt.height);
@ -640,10 +648,16 @@ BlockEntry.fromEntry = function fromEntry(entry, attempt) {
item.sigops = entry.sigops; item.sigops = entry.sigops;
item.descRate = entry.getDescRate(); item.descRate = entry.getDescRate();
return item; return item;
}; }
}
/* /**
* BlockProof * Block Proof
*/
class BlockProof {
/**
* Create a block proof.
* @constructor * @constructor
* @param {Hash} hash * @param {Hash} hash
* @param {Hash} root * @param {Hash} root
@ -653,53 +667,59 @@ BlockEntry.fromEntry = function fromEntry(entry, attempt) {
* @param {Number} nonce * @param {Number} nonce
*/ */
function BlockProof(hash, root, nonce1, nonce2, time, nonce) { constructor(hash, root, nonce1, nonce2, time, nonce) {
this.hash = hash; this.hash = hash;
this.root = root; this.root = root;
this.nonce1 = nonce1; this.nonce1 = nonce1;
this.nonce2 = nonce2; this.nonce2 = nonce2;
this.time = time; this.time = time;
this.nonce = nonce; this.nonce = nonce;
}
rhash() {
return encoding.revHex(this.hash.toString('hex'));
}
verify(target) {
return common.rcmp(this.hash, target) <= 0;
}
getDifficulty() {
return common.getDifficulty(this.hash);
}
} }
BlockProof.prototype.rhash = function rhash() { /**
return encoding.revHex(this.hash.toString('hex')); * Merkle Tree
};
BlockProof.prototype.verify = function verify(target) {
return common.rcmp(this.hash, target) <= 0;
};
BlockProof.prototype.getDifficulty = function getDifficulty() {
return common.getDifficulty(this.hash);
};
/*
* MerkleTree
* @constructor
* @property {Hash[]} steps * @property {Hash[]} steps
*/ */
function MerkleTree() { class MerkleTree {
this.steps = []; /**
} * Create a merkle tree.
* @constructor
*/
MerkleTree.prototype.withFirst = function withFirst(hash) { constructor() {
this.steps = [];
}
withFirst(hash) {
for (const step of this.steps) for (const step of this.steps)
hash = hash256.root(hash, step); hash = hash256.root(hash, step);
return hash; return hash;
}; }
MerkleTree.prototype.toJSON = function toJSON() { toJSON() {
const steps = []; const steps = [];
for (const step of this.steps) for (const step of this.steps)
steps.push(step.toString('hex')); steps.push(step.toString('hex'));
return steps; return steps;
}; }
MerkleTree.prototype.fromItems = function fromItems(items) { fromItems(items) {
const leaves = []; const leaves = [];
leaves.push(encoding.ZERO_HASH); leaves.push(encoding.ZERO_HASH);
@ -708,13 +728,13 @@ MerkleTree.prototype.fromItems = function fromItems(items) {
leaves.push(item.tx.hash()); leaves.push(item.tx.hash());
return this.fromLeaves(leaves); return this.fromLeaves(leaves);
}; }
MerkleTree.fromItems = function fromItems(items) { static fromItems(items) {
return new MerkleTree().fromItems(items); return new this().fromItems(items);
}; }
MerkleTree.prototype.fromBlock = function fromBlock(txs) { fromBlock(txs) {
const leaves = []; const leaves = [];
leaves.push(encoding.ZERO_HASH); leaves.push(encoding.ZERO_HASH);
@ -725,13 +745,13 @@ MerkleTree.prototype.fromBlock = function fromBlock(txs) {
} }
return this.fromLeaves(leaves); return this.fromLeaves(leaves);
}; }
MerkleTree.fromBlock = function fromBlock(txs) { static fromBlock(txs) {
return new MerkleTree().fromBlock(txs); return new this().fromBlock(txs);
}; }
MerkleTree.prototype.fromLeaves = function fromLeaves(leaves) { fromLeaves(leaves) {
let len = leaves.length; let len = leaves.length;
while (len > 1) { while (len > 1) {
@ -752,11 +772,12 @@ MerkleTree.prototype.fromLeaves = function fromLeaves(leaves) {
} }
return this; return this;
}; }
MerkleTree.fromLeaves = function fromLeaves(leaves) { static fromLeaves(leaves) {
return new MerkleTree().fromLeaves(leaves); return new this().fromLeaves(leaves);
}; }
}
/* /*
* Expose * Expose

File diff suppressed because it is too large Load Diff