copay/js/models/PrivateKey.js

69 lines
1.7 KiB
JavaScript
Raw Normal View History

2014-04-09 16:37:14 -07:00
'use strict';
var imports = require('soop').imports();
var bitcore = require('bitcore');
var BIP32 = bitcore.BIP32;
var WalletKey = bitcore.WalletKey;
var networks = bitcore.networks;
2014-04-09 22:16:57 -07:00
var util = bitcore.util;
2014-04-09 16:37:14 -07:00
var PublicKeyRing = require('./PublicKeyRing');
function PrivateKey(opts) {
this.network = opts.networkName === 'testnet' ?
networks.testnet : networks.livenet;
2014-04-09 22:16:57 -07:00
this.BIP32 = opts.BIP32 || new BIP32(opts.extendedPrivateKeyString || this.network.name);
this._calcId();
2014-04-09 16:37:14 -07:00
};
2014-04-09 22:16:57 -07:00
PrivateKey.prototype._calcId = function() {
this.id = util.ripe160(this.BIP32.extendedPublicKey).toString('hex');
};
2014-04-09 16:37:14 -07:00
PrivateKey.prototype.getBIP32 = function(index,isChange) {
if (typeof index === 'undefined') {
return this.BIP32;
}
return this.BIP32.derive( isChange ?
PublicKeyRing.ChangeBranch(index):PublicKeyRing.PublicBranch(index) );
};
2014-04-09 22:16:57 -07:00
PrivateKey.fromObj = function(o) {
return new PrivateKey({
extendedPrivateKeyString: o.extendedPrivateKeyString,
networkName: o.networkName,
});
};
PrivateKey.prototype.toObj = function() {
return {
extendedPrivateKeyString: this.BIP32.extendedPrivateKeyString(),
networkName: this.network.name,
};
};
2014-04-09 16:37:14 -07:00
PrivateKey.prototype.get = function(index,isChange) {
var derivedBIP32 = this.getBIP32(index,isChange);
var wk = new WalletKey({network: this.network});
var p = derivedBIP32.eckey.private.toString('hex');
wk.fromObj({priv: p});
return wk;
};
2014-04-09 19:04:22 -07:00
PrivateKey.prototype.getAll = function(addressIndex, changeAddressIndex) {
var ret = [];
2014-04-09 22:16:57 -07:00
2014-04-09 19:04:22 -07:00
for(var i=0;i<addressIndex; i++) {
ret.push(this.get(i,false));
}
for(var i=0; i<changeAddressIndex; i++) {
ret.push(this.get(i,true));
}
return ret;
};
2014-04-09 16:37:14 -07:00
module.exports = require('soop')(PrivateKey);