copay/js/models/core/PublicKeyRing.js

456 lines
12 KiB
JavaScript
Raw Normal View History

2014-03-26 11:26:31 -07:00
'use strict';
var preconditions = require('preconditions').instance();
2014-06-24 08:57:15 -07:00
var bitcore = require('bitcore');
var HK = bitcore.HierarchicalKey;
var PrivateKey = require('./PrivateKey');
2014-07-29 07:23:58 -07:00
var HDPath = require('./HDPath');
var HDParams = require('./HDParams');
2014-06-24 08:57:15 -07:00
var Address = bitcore.Address;
var Script = bitcore.Script;
2014-03-26 11:26:31 -07:00
2014-04-04 11:57:28 -07:00
function PublicKeyRing(opts) {
2014-03-26 11:26:31 -07:00
opts = opts || {};
2014-04-15 08:17:28 -07:00
this.walletId = opts.walletId;
2014-06-24 08:57:15 -07:00
this.network = opts.networkName === 'livenet' ?
bitcore.networks.livenet : bitcore.networks.testnet;
2014-03-26 11:26:31 -07:00
2014-04-04 11:57:28 -07:00
this.requiredCopayers = opts.requiredCopayers || 3;
this.totalCopayers = opts.totalCopayers || 5;
2014-03-26 11:26:31 -07:00
2014-05-14 16:55:34 -07:00
this.copayersHK = opts.copayersHK || [];
2014-03-26 18:00:42 -07:00
this.indexes = opts.indexes ? HDParams.fromList(opts.indexes) : HDParams.init(this.totalCopayers);
2014-08-19 08:00:18 -07:00
this.publicKeysCache = {};
this.nicknameFor = opts.nicknameFor || {};
this.copayerIds = [];
this.copayersBackup = opts.copayersBackup || [];
this.addressToPath = {};
2014-03-26 11:26:31 -07:00
}
2014-06-24 08:57:15 -07:00
PublicKeyRing.fromObj = function(data) {
if (data instanceof PublicKeyRing) {
throw new Error('bad data format: Did you use .toObj()?');
}
// Support old indexes schema
if (!Array.isArray(data.indexes)) {
2014-07-29 07:23:58 -07:00
data.indexes = HDParams.update(data.indexes, data.totalCopayers);
}
2014-06-24 08:57:15 -07:00
var ret = new PublicKeyRing(data);
2014-05-01 05:41:18 -07:00
for (var k in data.copayersExtPubKeys) {
ret.addCopayer(data.copayersExtPubKeys[k]);
}
return ret;
2014-03-26 13:55:02 -07:00
};
2014-04-07 07:46:45 -07:00
PublicKeyRing.prototype.toObj = function() {
2014-04-04 16:16:15 -07:00
return {
2014-04-15 08:17:28 -07:00
walletId: this.walletId,
2014-04-07 07:46:45 -07:00
networkName: this.network.name,
requiredCopayers: this.requiredCopayers,
2014-04-04 11:57:28 -07:00
totalCopayers: this.totalCopayers,
2014-07-29 07:23:58 -07:00
indexes: HDParams.serialize(this.indexes),
copayersBackup: this.copayersBackup,
2014-04-07 07:46:45 -07:00
2014-06-24 08:57:15 -07:00
copayersExtPubKeys: this.copayersHK.map(function(b) {
return b.extendedPublicKeyString();
2014-03-26 13:55:02 -07:00
}),
2014-05-01 05:41:18 -07:00
nicknameFor: this.nicknameFor,
2014-04-04 16:16:15 -07:00
};
};
2014-04-23 18:43:17 -07:00
PublicKeyRing.prototype.getCopayerId = function(i) {
preconditions.checkArgument(typeof i !== 'undefined');
2014-04-23 18:43:17 -07:00
return this.copayerIds[i];
2014-04-20 08:41:28 -07:00
};
2014-04-18 14:25:51 -07:00
2014-06-24 08:57:15 -07:00
PublicKeyRing.prototype.registeredCopayers = function() {
2014-05-14 16:55:34 -07:00
return this.copayersHK.length;
2014-03-26 11:26:31 -07:00
};
2014-06-24 08:57:15 -07:00
PublicKeyRing.prototype.isComplete = function() {
return this.remainingCopayers() == 0;
};
PublicKeyRing.prototype.remainingCopayers = function() {
return this.totalCopayers - this.registeredCopayers();
2014-04-24 19:13:55 -07:00
};
PublicKeyRing.prototype.getAllCopayerIds = function() {
2014-05-01 05:41:18 -07:00
return this.copayerIds;
2014-04-24 19:13:55 -07:00
};
PublicKeyRing.prototype.myCopayerId = function(i) {
return this.getCopayerId(0);
2014-03-26 18:00:42 -07:00
};
2014-04-04 11:57:28 -07:00
PublicKeyRing.prototype._checkKeys = function() {
2014-03-26 18:00:42 -07:00
2014-04-09 10:30:12 -07:00
if (!this.isComplete())
2014-06-24 08:57:15 -07:00
throw new Error('dont have required keys yet');
2014-03-26 18:00:42 -07:00
};
2014-06-24 08:57:15 -07:00
PublicKeyRing.prototype._updateBip = function(index) {
2014-07-29 07:23:58 -07:00
var hk = this.copayersHK[index].derive(HDPath.IdBranch);
2014-06-24 08:57:15 -07:00
this.copayerIds[index] = hk.eckey.public.toString('hex');
2014-05-01 05:41:18 -07:00
};
2014-06-24 08:57:15 -07:00
PublicKeyRing.prototype._setNicknameForIndex = function(index, nickname) {
2014-05-01 05:41:18 -07:00
this.nicknameFor[this.copayerIds[index]] = nickname;
};
2014-03-26 11:26:31 -07:00
PublicKeyRing.prototype.nicknameForIndex = function(index) {
2014-05-01 05:41:18 -07:00
return this.nicknameFor[this.copayerIds[index]];
};
PublicKeyRing.prototype.nicknameForCopayer = function(copayerId) {
return this.nicknameFor[copayerId] || 'NN';
2014-05-01 05:41:18 -07:00
};
PublicKeyRing.prototype.addCopayer = function(newEpk, nickname) {
preconditions.checkArgument(newEpk);
2014-04-09 10:30:12 -07:00
if (this.isComplete())
2014-06-24 08:57:15 -07:00
throw new Error('PKR already has all required key:' + this.totalCopayers);
2014-03-26 11:26:31 -07:00
2014-06-24 08:57:15 -07:00
this.copayersHK.forEach(function(b) {
if (b.extendedPublicKeyString() === newEpk)
throw new Error('PKR already has that key');
2014-03-26 11:26:31 -07:00
});
var i = this.copayersHK.length;
2014-05-14 16:55:34 -07:00
var bip = new HK(newEpk);
this.copayersHK.push(bip);
2014-05-01 05:41:18 -07:00
this._updateBip(i);
2014-06-24 08:57:15 -07:00
if (nickname) {
this._setNicknameForIndex(i, nickname);
2014-05-01 05:41:18 -07:00
}
return newEpk;
2014-03-26 11:26:31 -07:00
};
2014-07-29 07:23:58 -07:00
PublicKeyRing.prototype.getPubKeys = function(index, isChange, copayerIndex) {
2014-03-26 18:00:42 -07:00
this._checkKeys();
2014-03-26 11:26:31 -07:00
2014-07-29 07:23:58 -07:00
var path = HDPath.Branch(index, isChange, copayerIndex);
var pubKeys = this.publicKeysCache[path];
if (!pubKeys) {
pubKeys = [];
2014-05-14 16:55:34 -07:00
var l = this.copayersHK.length;
2014-06-24 08:57:15 -07:00
for (var i = 0; i < l; i++) {
2014-05-14 16:55:34 -07:00
var hk = this.copayersHK[i].derive(path);
pubKeys[i] = hk.eckey.public;
}
2014-06-24 08:57:15 -07:00
this.publicKeysCache[path] = pubKeys.map(function(pk) {
return pk.toString('hex');
});
} else {
pubKeys = pubKeys.map(function(s) {
return new Buffer(s, 'hex');
});
2014-03-26 18:00:42 -07:00
}
2014-06-12 10:27:53 -07:00
2014-03-26 19:55:46 -07:00
return pubKeys;
};
2014-04-22 18:07:18 -07:00
// TODO this could be cached
2014-07-29 07:23:58 -07:00
PublicKeyRing.prototype.getRedeemScript = function(index, isChange, copayerIndex) {
var pubKeys = this.getPubKeys(index, isChange, copayerIndex);
2014-06-24 08:57:15 -07:00
var script = Script.createMultisig(this.requiredCopayers, pubKeys);
return script;
};
2014-04-22 18:07:18 -07:00
// TODO this could be cached
PublicKeyRing.prototype.getAddress = function(index, isChange, id) {
2014-07-29 07:23:58 -07:00
var copayerIndex = this.getCosigner(id);
var script = this.getRedeemScript(index, isChange, copayerIndex);
2014-05-30 11:07:52 -07:00
var address = Address.fromScript(script, this.network.name);
2014-07-29 07:23:58 -07:00
this.addressToPath[address.toString()] = HDPath.FullBranch(index, isChange, copayerIndex);
2014-05-30 11:07:52 -07:00
return address;
};
// Overloaded to receive a PubkeyString or a consigner index
PublicKeyRing.prototype.getHDParams = function(id) {
2014-07-29 07:23:58 -07:00
var copayerIndex = this.getCosigner(id);
var index = this.indexes.filter(function(i) {
return i.copayerIndex == copayerIndex
});
if (index.length != 1) throw new Error('no index for copayerIndex');
2014-07-29 07:23:58 -07:00
return index[0];
};
2014-05-30 11:07:52 -07:00
PublicKeyRing.prototype.pathForAddress = function(address) {
var path = this.addressToPath[address];
2014-06-24 08:57:15 -07:00
if (!path) throw new Error('Couldn\'t find path for address ' + address);
2014-05-30 11:07:52 -07:00
return path;
2014-03-26 11:26:31 -07:00
};
2014-04-22 18:07:18 -07:00
// TODO this could be cached
PublicKeyRing.prototype.getScriptPubKeyHex = function(index, isChange, pubkey) {
2014-07-29 07:23:58 -07:00
var copayerIndex = this.getCosigner(pubkey);
var addr = this.getAddress(index, isChange, copayerIndex);
2014-04-10 21:09:42 -07:00
return Script.createP2SH(addr.payload()).getBuffer().toString('hex');
};
2014-04-04 11:57:28 -07:00
//generate a new address, update index.
PublicKeyRing.prototype.generateAddress = function(isChange, pubkey) {
2014-06-24 10:40:03 -07:00
isChange = !!isChange;
var HDParams = this.getHDParams(pubkey);
var index = isChange ? HDParams.getChangeIndex() : HDParams.getReceiveIndex();
var ret = this.getAddress(index, isChange, HDParams.copayerIndex);
HDParams.increment(isChange);
2014-03-26 18:00:42 -07:00
return ret;
};
2014-05-01 06:07:30 -07:00
PublicKeyRing.prototype.getAddresses = function(opts) {
return this.getAddressesInfo(opts).map(function(info) {
2014-04-30 15:50:13 -07:00
return info.address;
});
};
PublicKeyRing.prototype.getCosigner = function(pubKey) {
2014-07-29 07:23:58 -07:00
if (typeof pubKey == 'undefined') return HDPath.SHARED_INDEX;
2014-07-04 05:45:02 -07:00
if (typeof pubKey == 'number') return pubKey;
var sorted = this.copayersHK.map(function(h, i) {
return h.eckey.public.toString('hex');
}).sort(function(h1, h2) {
return h1.localeCompare(h2);
});
var index = sorted.indexOf(pubKey);
if (index == -1) throw new Error('no public key in ring');
return index;
}
PublicKeyRing.prototype.getAddressesInfo = function(opts, pubkey) {
var ret = [];
var self = this;
2014-07-29 07:23:58 -07:00
var copayerIndex = pubkey && this.getCosigner(pubkey);
this.indexes.forEach(function(index) {
2014-07-29 07:23:58 -07:00
ret = ret.concat(self.getAddressesInfoForIndex(index, opts, copayerIndex));
});
return ret;
}
2014-07-29 07:23:58 -07:00
PublicKeyRing.prototype.getAddressesInfoForIndex = function(index, opts, copayerIndex) {
2014-05-01 06:07:30 -07:00
opts = opts || {};
var isOwned = index.copayerIndex == HDPath.SHARED_INDEX || index.copayerIndex == copayerIndex;
var ret = [];
if (!opts.excludeChange) {
for (var i = 0; i < index.changeIndex; i++) {
var a = this.getAddress(i, true, index.copayerIndex);
ret.unshift({
address: a,
addressStr: a.toString(),
isChange: true,
owned: isOwned
});
}
}
2014-04-30 15:50:13 -07:00
if (!opts.excludeMain) {
for (var i = 0; i < index.receiveIndex; i++) {
var a = this.getAddress(i, false, index.copayerIndex);
ret.unshift({
address: a,
addressStr: a.toString(),
isChange: false,
owned: isOwned
});
2014-05-01 06:07:30 -07:00
}
}
2014-04-30 15:50:13 -07:00
return ret;
};
PublicKeyRing.prototype.getForPath = function(path) {
var p = HDPath.indexesForPath(path);
var pubKeys = this.getPubKeys(p.addressIndex, p.isChange, p.copayerIndex);
return pubKeys;
};
2014-07-30 07:54:11 -07:00
PublicKeyRing.prototype.getForPaths = function(paths) {
2014-08-04 13:12:53 -07:00
preconditions.checkArgument(paths);
2014-07-30 07:54:11 -07:00
return paths.map(this.getForPath.bind(this));
};
2014-07-30 07:59:07 -07:00
PublicKeyRing.prototype.forPaths = function(paths) {
return {
pubKeys: paths.map(this.getForPath.bind(this)),
copayerIds: this.copayerIds,
}
};
2014-08-03 18:34:47 -07:00
// returns pubkey -> copayerId.
PublicKeyRing.prototype.copayersForPubkeys = function(pubkeys, paths) {
2014-08-04 13:12:53 -07:00
preconditions.checkArgument(pubkeys);
preconditions.checkArgument(paths);
2014-08-03 18:34:47 -07:00
var inKeyMap = {}, ret = {};
for(var i in pubkeys ){
inKeyMap[pubkeys[i]] = 1;
};
var keys = this.getForPaths(paths);
for(var i in keys ){
for(var copayerIndex in keys[i] ){
var kHex = keys[i][copayerIndex].toString('hex');
if (inKeyMap[kHex]) {
2014-08-03 18:34:47 -07:00
ret[kHex] =this.copayerIds[copayerIndex];
delete inKeyMap[kHex];
}
}
}
for(var i in inKeyMap)
throw new Error('Pubkey not identified')
return ret;
};
2014-04-30 08:25:33 -07:00
// TODO this could be cached
2014-06-24 09:17:22 -07:00
PublicKeyRing.prototype._addScriptMap = function(map, path) {
var p = HDPath.indexesForPath(path);
var script = this.getRedeemScript(p.addressIndex, p.isChange, p.copayerIndex);
2014-04-30 08:25:33 -07:00
map[Address.fromScript(script, this.network.name).toString()] = script.getBuffer().toString('hex');
};
2014-06-24 09:17:22 -07:00
PublicKeyRing.prototype.getRedeemScriptMap = function(paths) {
2014-04-09 13:28:35 -07:00
var ret = {};
2014-06-24 09:17:22 -07:00
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
this._addScriptMap(ret, path);
2014-04-09 13:28:35 -07:00
}
return ret;
};
2014-06-09 13:28:56 -07:00
PublicKeyRing.prototype._checkInPKR = function(inPKR, ignoreId) {
2014-04-07 20:54:38 -07:00
2014-06-24 08:57:15 -07:00
if (!ignoreId && this.walletId !== inPKR.walletId) {
2014-06-09 13:28:56 -07:00
throw new Error('inPKR walletId mismatch');
2014-04-07 20:54:38 -07:00
}
2014-04-07 07:46:45 -07:00
2014-06-09 13:28:56 -07:00
if (this.network.name !== inPKR.network.name) {
2014-06-24 08:57:15 -07:00
throw new Error('Network mismatch. Should be ' + this.network.name +
2014-07-29 07:23:58 -07:00
' and found ' + inPKR.network.name);
2014-06-09 13:28:56 -07:00
}
2014-04-07 07:46:45 -07:00
if (
this.requiredCopayers && inPKR.requiredCopayers &&
2014-07-29 07:23:58 -07:00
(this.requiredCopayers !== inPKR.requiredCopayers))
throw new Error('inPKR requiredCopayers mismatch ' + this.requiredCopayers + '!=' + inPKR.requiredCopayers);
2014-04-07 07:46:45 -07:00
2014-07-29 07:23:58 -07:00
if (
this.totalCopayers && inPKR.totalCopayers &&
(this.totalCopayers !== inPKR.totalCopayers))
throw new Error('inPKR totalCopayers mismatch' + this.totalCopayers + '!=' + inPKR.requiredCopayers);
2014-04-07 07:46:45 -07:00
};
PublicKeyRing.prototype._mergePubkeys = function(inPKR) {
var self = this;
var hasChanged = false;
2014-06-24 08:57:15 -07:00
var l = self.copayersHK.length;
if (self.isComplete())
2014-04-22 22:01:54 -07:00
return;
2014-04-07 07:46:45 -07:00
2014-06-24 08:57:15 -07:00
inPKR.copayersHK.forEach(function(b) {
2014-04-07 07:46:45 -07:00
var haveIt = false;
2014-06-24 08:57:15 -07:00
var epk = b.extendedPublicKeyString();
for (var j = 0; j < l; j++) {
2014-05-14 16:55:34 -07:00
if (self.copayersHK[j].extendedPublicKeyString() === epk) {
2014-06-24 08:57:15 -07:00
haveIt = true;
2014-04-07 07:46:45 -07:00
break;
}
}
if (!haveIt) {
if (self.isComplete()) {
throw new Error('trying to add more pubkeys, when PKR isComplete at merge');
}
2014-05-14 16:55:34 -07:00
var l2 = self.copayersHK.length;
self.copayersHK.push(new HK(epk));
2014-05-01 05:41:18 -07:00
self._updateBip(l2);
if (inPKR.nicknameFor[self.getCopayerId(l2)])
2014-06-24 08:57:15 -07:00
self._setNicknameForIndex(l2, inPKR.nicknameFor[self.getCopayerId(l2)]);
hasChanged = true;
2014-04-07 07:46:45 -07:00
}
});
return hasChanged;
};
PublicKeyRing.prototype.setBackupReady = function(copayerId) {
if (this.isBackupReady()) return false;
var cid = this.myCopayerId();
this.copayersBackup.push(cid);
return true;
}
PublicKeyRing.prototype.isBackupReady = function(copayerId) {
var cid = copayerId || this.myCopayerId();
return this.copayersBackup.indexOf(cid) != -1;
}
PublicKeyRing.prototype.isFullyBackup = function(copayerId) {
return this.remainingBackups() == 0;
}
PublicKeyRing.prototype.remainingBackups = function() {
return this.totalCopayers - this.copayersBackup.length;
};
2014-04-07 20:54:38 -07:00
PublicKeyRing.prototype.merge = function(inPKR, ignoreId) {
this._checkInPKR(inPKR, ignoreId);
2014-04-07 07:46:45 -07:00
var hasChanged = false;
hasChanged |= this.mergeIndexes(inPKR.indexes);
hasChanged |= this._mergePubkeys(inPKR);
hasChanged |= this.mergeBackups(inPKR.copayersBackup);
2014-04-07 07:46:45 -07:00
return !!hasChanged;
};
2014-04-07 07:46:45 -07:00
PublicKeyRing.prototype.mergeIndexes = function(indexes) {
var self = this;
var hasChanged = false;
2014-04-07 07:46:45 -07:00
indexes.forEach(function(theirs) {
var mine = self.getHDParams(theirs.copayerIndex);
hasChanged |= mine.merge(theirs);
});
2014-04-07 07:46:45 -07:00
return !!hasChanged
}
2014-04-07 07:46:45 -07:00
PublicKeyRing.prototype.mergeBackups = function(backups) {
var self = this;
var hasChanged = false;
backups.forEach(function(cid) {
var isNew = self.copayersBackup.indexOf(cid) == -1;
if (isNew) self.copayersBackup.push(cid);
hasChanged |= isNew;
});
return !!hasChanged
}
2014-07-29 07:23:58 -07:00
module.exports = PublicKeyRing;