add seed function to generate master privkey

This follows the spec of BIP32. With tests for main test vectors.
This commit is contained in:
Ryan X. Charles 2014-03-28 18:46:09 -04:00
parent f6aa01c445
commit 343a6af7c3
2 changed files with 48 additions and 0 deletions

View File

@ -48,6 +48,34 @@ var BIP32 = function(bytes) {
this.initFromBytes(bytes);
}
BIP32.seed = function(bytes, network) {
if (!network)
return false;
if (!Buffer.isBuffer(bytes))
bytes = new Buffer(bytes, 'hex'); //if not buffer, assume hex
if (bytes.length < 128/8)
return false; //need more entropy
var hash = coinUtil.sha512hmac(bytes, new Buffer("Bitcoin seed"));
var bip32 = new BIP32();
bip32.depth = 0x00;
bip32.parentFingerprint = new Buffer([0, 0, 0, 0]);
bip32.childIndex = new Buffer([0, 0, 0, 0]);
bip32.chainCode = hash.slice(32, 64);
bip32.version = networks[network].bip32private;
bip32.eckey = new Key();
bip32.eckey.private = hash.slice(0, 32);
bip32.eckey.regenerateSync();
bip32.hasPrivateKey = true;
bip32.pubKeyHash = coinUtil.sha256ripe160(bip32.eckey.public);
bip32.buildExtendedPublicKey();
bip32.buildExtendedPrivateKey();
return bip32;
};
BIP32.prototype.initFromBytes = function(bytes) {
// Both pub and private extended keys are 78 bytes
if(bytes.length != 78) throw new Error("not enough data");

View File

@ -274,4 +274,24 @@ describe('BIP32', function() {
child2.extendedPublicKeyString().should.equal(vector2_m02147483647h12147483646h2_public);
});
describe('#seed', function() {
it('should initialize a new BIP32 correctly from test vector 1 seed', function() {
var hex = vector1_master;
var bip32 = BIP32.seed(hex, 'livenet');
should.exist(bip32);
bip32.extendedPrivateKeyString().should.equal(vector1_m_private);
bip32.extendedPublicKeyString().should.equal(vector1_m_public);
});
it('should initialize a new BIP32 correctly from test vector 2 seed', function() {
var hex = vector2_master;
var bip32 = BIP32.seed(hex, 'livenet');
should.exist(bip32);
bip32.extendedPrivateKeyString().should.equal(vector2_m_private);
bip32.extendedPublicKeyString().should.equal(vector2_m_public);
});
});
});