improvements.

This commit is contained in:
Christopher Jeffrey 2016-02-03 21:21:08 -08:00
parent eacd1e2ece
commit c23fdeba50

View File

@ -74,8 +74,10 @@ function Wallet(options) {
this.purposeKeys = options.purposeKeys || []; this.purposeKeys = options.purposeKeys || [];
this.keys = options.keys || []; this.keys = options.keys || [];
this.normal = false;
this.hd = false; this.hd = false;
this.hdpm = false; this.bip44 = false;
this.bip45 = false;
this.multisig = false; this.multisig = false;
this.type = options.type || 'pubkeyhash'; this.type = options.type || 'pubkeyhash';
@ -94,11 +96,15 @@ function Wallet(options) {
this.subtype = 'multisig'; this.subtype = 'multisig';
} }
if (this.master) if (this.master) {
this.hd = true; this.hd = true;
if (this.type === 'scripthash' && this.subtype === 'multisig')
if (this.master && this.type === 'scripthash' && this.subtype === 'multisig') this.bip45 = true;
this.hdpm = true; else
this.bip44 = true;
} else {
this.normal = true;
}
if (this.type === 'multisig' || this.subtype === 'multisig') if (this.type === 'multisig' || this.subtype === 'multisig')
this.multisig = true; this.multisig = true;
@ -112,12 +118,12 @@ function Wallet(options) {
if (this.n < 1 || this.n > this.nmax) if (this.n < 1 || this.n > this.nmax)
throw new Error('n ranges between 1 and ' + this.nmax); throw new Error('n ranges between 1 and ' + this.nmax);
if (this.hdpm) { if (this.bip45) {
this.purposeKey = this.master.hd.isPublic this.purposeKey = this.master.hd.isPurpose45()
? this.master.hd ? this.master.hd
: this.master.hd.derivePurpose45(); : this.master.hd.derivePurpose45();
} else if (this.hd) { } else if (this.hd) {
this.accountKey = this.master.hd.isPublic this.accountKey = this.master.hd.isAccount44()
? this.master.hd ? this.master.hd
: this.master.hd.deriveAccount44(this.accountIndex); : this.master.hd.deriveAccount44(this.accountIndex);
} }
@ -151,20 +157,54 @@ function Wallet(options) {
this.loading = true; this.loading = true;
this.lastTs = 0; this.lastTs = 0;
if (!this.hdpm) { var key, receiving;
if (options.addresses.length) {
this.current = bcoin.address(options.addresses[options.addresses.length - 1]); // This is a chicken and egg problem for BIP45. Real address keys cannot be
this._firstKey = { // generated until all shared keys have been added to the wallet. The flow of
priv: this.current.key._key.getPrivate().toArray(), // this wallet is, the actual address objects will be generated once all
pub: this.current.key._key.getPublic(true, 'array') // shared keys have been added. This presents a problem for non-bip45
}; // wallets: if they want to use the addKey() interface with
// wallet.getPublicKey(), we need to expose a key for them to use. Here, we
// generate the last receiving address. However, since "normal" wallets
// cannot deterministically generate keys, we have to buffer the generated
// key for later.
if (!this.bip45) {
if (this.hd) {
// Generate the last known receiving address
key = this.createKey(false, Math.max(0, this.addressDepth - 1));
this.current = bcoin.address({
priv: key.priv,
type: this.type,
subtype: this.subtype,
m: this.m,
n: this.n,
keys: options.keys
});
} else { } else {
this._firstKey = this.createKey(false, Math.max(0, this.addressDepth - 1)); // Try to find the last receiving address if there is one.
this.current = bcoin.address({ priv: this._firstKey.priv }); receiving = options.addresses.filter(function(address) {
return !address.change && (address.priv || address.pub || address.key);
}).pop();
if (receiving) {
this.current = bcoin.address(receiving);
} else {
// No receiving address is in this wallet yet, generate
// it and save it so createKey can recreate it later.
key = this.createKey();
this._firstKey = key;
this.current = bcoin.address({
priv: key.priv,
type: this.type,
subtype: this.subtype,
m: this.m,
n: this.n,
keys: options.keys
});
}
} }
} }
if (this.hdpm) if (this.bip45)
this.addKey(this.purposeKey); this.addKey(this.purposeKey);
else else
this.addKey(this.current.publicKey); this.addKey(this.current.publicKey);
@ -176,50 +216,61 @@ function Wallet(options) {
inherits(Wallet, EventEmitter); inherits(Wallet, EventEmitter);
// Wallet ID:
// bip45: Purpose key address
// HD: Account key address
// Normal: Address of first key in wallet
Wallet.prototype.getID = function() {
if (this.bip45)
return bcoin.address.key2addr(this.purposeKey.publicKey);
if (this.hd)
return bcoin.address.key2addr(this.accountKey.publicKey);
if (this.addresses.length)
return this.addresses[0].getKeyAddress();
if (this._firstKey)
return bcoin.address.key2addr(this._firstKey.pub);
assert(false);
};
Wallet.prototype._initAddresses = function() { Wallet.prototype._initAddresses = function() {
var options = this.options; var options = this.options;
assert(!this._initialized);
this._initialized = true;
options.addresses.forEach(function(address) { options.addresses.forEach(function(address) {
address = this.addAddress(address); address = this.addAddress(address);
if (!address.change) if (!this.hd) {
this.current = address; if (!address.change)
this.current = address;
else
this.changeAddress = address;
}
}, this); }, this);
if (this.hd) { if (this.hd) {
for (i = 0; i < this.addressDepth; i++) for (i = 0; i < this.addressDepth; i++)
this.createAddress(false, i); this.current = this.createAddress(false, i);
for (i = 0; i < this.changeDepth; i++) for (i = 0; i < this.changeDepth; i++)
this.createAddress(true, i); this.changeAddress = this.createAddress(true, i);
} }
// Create a non-master account address if we don't have one. if (!this.current)
if (this.addresses.length === 0) this.current = this.createAddress();
this.createAddress();
// Find the last change address if there is one. if (!this.changeAddress)
if (this.hd) { this.changeAddress = this.createAddress(true);
if (this.changeDepth === 0)
this.changeAddress = this.createAddress(true);
else
this.changeAddress = this.addresses[this.addresses.length - 1];
} else {
for (i = this.addresses.length - 1; i >= 0; i--) {
if (this.addresses[i].change)
break;
}
if (i === -1)
this.changeAddress = this.createAddress(true);
else
this.changeAddress = this.addresses[i];
}
assert(this.current); assert(this.current);
assert(!this.current.change); assert(!this.current.change);
assert(this.changeAddress.change); assert(this.changeAddress.change);
this.prefix = 'bt/wallet/' + this.getKeyAddress() + '/'; this.prefix = 'bt/wallet/' + this.getID() + '/';
this.tx = new bcoin.txPool(this); this.tx = new bcoin.txPool(this);
@ -245,9 +296,9 @@ Wallet.prototype.addKey = function addKey(key) {
key = hdKey.publicKey; key = hdKey.publicKey;
} }
if (this.hdpm) { if (this.bip45) {
if (!hdKey || !hdKey.isPurpose45()) if (!hdKey || !hdKey.isPurpose45())
throw new Error('Must add HD purpose keys to HD wallet.'); throw new Error('Must add HD purpose keys to BIP45 wallet.');
has = this.purposeKeys.some(function(pub) { has = this.purposeKeys.some(function(pub) {
return pub.xpubkey === hdKey.xpubkey; return pub.xpubkey === hdKey.xpubkey;
@ -256,6 +307,8 @@ Wallet.prototype.addKey = function addKey(key) {
if (has) if (has)
return; return;
assert(!this._keysFinalized);
this.purposeKeys.push(hdKey); this.purposeKeys.push(hdKey);
if (this.purposeKeys.length === this.n) if (this.purposeKeys.length === this.n)
@ -273,6 +326,8 @@ Wallet.prototype.addKey = function addKey(key) {
if (has) if (has)
return; return;
assert(!this._keysFinalized);
this.keys.push(key); this.keys.push(key);
if (this.keys.length === this.n) if (this.keys.length === this.n)
@ -280,11 +335,14 @@ Wallet.prototype.addKey = function addKey(key) {
}; };
Wallet.prototype.finalizeKeys = function finalizeKeys(key) { Wallet.prototype.finalizeKeys = function finalizeKeys(key) {
if (this.hdpm) { assert(!this._keysFinalized);
this._keysFinalized = true;
if (this.bip45) {
this.purposeKeys = utils.sortHDKeys(this.purposeKeys); this.purposeKeys = utils.sortHDKeys(this.purposeKeys);
for (i = 0; i < this.purposeKeys.length; i++) { for (i = 0; i < this.purposeKeys.length; i++) {
if (utils.isEqual(this.purposeKeys[i].publicKey, this.purposeKey.publicKey)) { if (this.purposeKeys[i].xpubkey === this.purposeKey.xpubkey) {
this.cosignerIndex = i; this.cosignerIndex = i;
break; break;
} }
@ -302,6 +360,8 @@ Wallet.prototype.finalizeKeys = function finalizeKeys(key) {
Wallet.prototype.removeKey = function removeKey(key) { Wallet.prototype.removeKey = function removeKey(key) {
var hdKey, index; var hdKey, index;
assert(!this._keysFinalized);
if (bcoin.hd.priv.isExtended(key)) if (bcoin.hd.priv.isExtended(key))
key = bcoin.hd.priv(key); key = bcoin.hd.priv(key);
else if (bcoin.hd.pub.isExtended(key)) else if (bcoin.hd.pub.isExtended(key))
@ -318,9 +378,9 @@ Wallet.prototype.removeKey = function removeKey(key) {
key = hd.publicKey; key = hd.publicKey;
} }
if (this.hdpm) { if (this.bip45) {
if (!hdKey || !hdKey.isPurpose45()) if (!hdKey || !hdKey.isPurpose45())
throw new Error('Must add HD purpose keys to HD wallet.'); throw new Error('Must add HD purpose keys to BIP45 wallet.');
index = this.purposeKeys.map(function(pub, i) { index = this.purposeKeys.map(function(pub, i) {
return pub.xpubkey === hdKey.xpubkey ? i : null; return pub.xpubkey === hdKey.xpubkey ? i : null;
@ -369,11 +429,13 @@ Wallet.prototype._init = function init() {
}); });
this.tx.on('tx', function(tx) { this.tx.on('tx', function(tx) {
// TX using this change address was // TX using this address was confirmed.
// confirmed. Allocate a new change address. // Allocate a new address.
if (tx.block) { if (tx.block) {
if (self.current.ownOutput(tx))
self.current = self.createAddress();
if (self.changeAddress.ownOutput(tx)) if (self.changeAddress.ownOutput(tx))
self.changeAddress = self.createChangeAddress(); self.changeAddress = self.createAddress(true);
} }
self.emit('tx', tx); self.emit('tx', tx);
}); });
@ -432,6 +494,8 @@ Wallet.prototype.createAddress = function createAddress(change, index) {
var key = this.createKey(change, index); var key = this.createKey(change, index);
var address; var address;
assert(this._initialized);
var options = { var options = {
priv: key.priv, priv: key.priv,
pub: key.pub, pub: key.pub,
@ -443,7 +507,7 @@ Wallet.prototype.createAddress = function createAddress(change, index) {
change: change change: change
}; };
if (this.hdpm) { if (this.bip45) {
this.purposeKeys.forEach(function(key, cosignerIndex) { this.purposeKeys.forEach(function(key, cosignerIndex) {
key = key key = key
.derive(cosignerIndex) .derive(cosignerIndex)
@ -469,9 +533,6 @@ Wallet.prototype.createAddress = function createAddress(change, index) {
address = this.addAddress(options); address = this.addAddress(options);
if (!change)
this.current = address;
return address; return address;
}; };
@ -492,6 +553,8 @@ Wallet.prototype.addAddress = function addAddress(address) {
var self = this; var self = this;
var index; var index;
assert(this._initialized);
if (!(address instanceof bcoin.address)) if (!(address instanceof bcoin.address))
address = bcoin.address(address); address = bcoin.address(address);
@ -527,6 +590,8 @@ Wallet.prototype.addAddress = function addAddress(address) {
Wallet.prototype.removeAddress = function removeAddress(address) { Wallet.prototype.removeAddress = function removeAddress(address) {
var i; var i;
assert(this._initialized);
assert(address instanceof bcoin.address); assert(address instanceof bcoin.address);
i = this._addressIndex(address); i = this._addressIndex(address);
@ -595,7 +660,7 @@ Wallet.prototype.createKey = function createKey(change, index) {
if (index == null) if (index == null)
index = change ? this.changeDepth : this.addressDepth; index = change ? this.changeDepth : this.addressDepth;
if (this.hdpm) { if (this.bip45) {
key = this.purposeKey key = this.purposeKey
.derive(this.cosignerIndex) .derive(this.cosignerIndex)
.derive(change ? 1 : 0) .derive(change ? 1 : 0)
@ -642,6 +707,8 @@ Wallet.prototype.ownOutput = function ownOutput(tx, index) {
Wallet.prototype.fill = function fill(tx, address, fee) { Wallet.prototype.fill = function fill(tx, address, fee) {
var unspent, items, result; var unspent, items, result;
assert(this._initialized);
if (!address) if (!address)
address = this.changeAddress.getKeyAddress(); address = this.changeAddress.getKeyAddress();
@ -841,23 +908,32 @@ Wallet.prototype.__defineGetter__('address', function() {
}); });
Wallet.prototype.toJSON = function toJSON(encrypt) { Wallet.prototype.toJSON = function toJSON(encrypt) {
assert(this._initialized);
return { return {
v: 3, v: 3,
name: 'wallet', name: 'wallet',
network: network.type, network: network.type,
type: this.type,
subtype: this.subtype,
m: this.m,
n: this.n,
accountIndex: this.accountIndex, accountIndex: this.accountIndex,
addressDepth: this.addressDepth, addressDepth: this.addressDepth,
changeDepth: this.changeDepth, changeDepth: this.changeDepth,
cosignerIndex: this.cosignerIndex,
keys: this.bip45
? this.purposeKeys.map(function(key) {
return key.xpubkey;
})
: this.keys.map(function(key) {
return utils.toBase58(key);
}),
master: this.master ? this.master.toJSON(encrypt) : null, master: this.master ? this.master.toJSON(encrypt) : null,
addresses: this.addresses.filter(function(address) { addresses: this.addresses.filter(function(address) {
if (!address.key.hd) if (this.hd)
return true;
if (address.change)
return false; return false;
return true; return true;
}).map(function(address) { }, this).map(function(address) {
return address.toJSON(encrypt); return address.toJSON(encrypt);
}), }),
balance: utils.toBTC(this.getBalance()), balance: utils.toBTC(this.getBalance()),
@ -875,12 +951,18 @@ Wallet.fromJSON = function fromJSON(json, decrypt) {
assert.equal(json.network, network.type); assert.equal(json.network, network.type);
w = new Wallet({ w = new Wallet({
type: json.type,
subtype: json.subtype,
m: json.m,
n: json.n,
accountIndex: json.accountIndex, accountIndex: json.accountIndex,
addressDepth: json.addressDepth, addressDepth: json.addressDepth,
changeDepth: json.changeDepth, changeDepth: json.changeDepth,
cosignerIndex: json.cosignerIndex,
master: json.master master: json.master
? bcoin.address.fromJSON(json.master, decrypt) ? bcoin.address.fromJSON(json.master, decrypt)
: null, : null,
keys: json.keys,
addresses: json.addresses.map(function(address) { addresses: json.addresses.map(function(address) {
return bcoin.address.fromJSON(address, decrypt); return bcoin.address.fromJSON(address, decrypt);
}) })
@ -888,17 +970,6 @@ Wallet.fromJSON = function fromJSON(json, decrypt) {
w.tx.fromJSON(json.tx); w.tx.fromJSON(json.tx);
// Make sure we have all the change
// addresses (we don't save them).
if (w.master) {
for (i = 0; i < w.changeDepth; i++) {
w.addAddress({
change: true,
priv: w.master.key.hd.deriveChange(w.accountIndex, i)
});
}
}
return w; return w;
}; };