Wallet/js/models/Identity.js

608 lines
15 KiB
JavaScript
Raw Normal View History

2014-04-16 17:50:10 -03:00
'use strict';
2014-09-03 01:25:08 -03:00
var preconditions = require('preconditions').singleton();
2014-04-16 17:50:10 -03:00
2014-08-01 01:09:46 -03:00
var TxProposals = require('./TxProposals');
2014-04-16 17:50:10 -03:00
var PublicKeyRing = require('./PublicKeyRing');
var PrivateKey = require('./PrivateKey');
var Wallet = require('./Wallet');
var _ = require('underscore');
2014-09-23 15:24:57 -03:00
var log = require('../log');
2014-09-28 18:38:06 -03:00
var version = require('../../version').version;
2014-09-03 01:25:08 -03:00
var PluginManager = require('./PluginManager');
2014-09-27 18:00:27 -03:00
var Profile = require('./Profile');
2014-09-23 15:24:57 -03:00
var Insight = module.exports.Insight = require('./Insight');
2014-09-30 20:12:02 -03:00
var Async = module.exports.Async = require('./Async');
2014-09-10 13:56:49 -07:00
var preconditions = require('preconditions').singleton();
2014-09-23 15:24:57 -03:00
var Storage = module.exports.Storage = require('./Storage');
/**
* @desc
* Identity - stores the state for a wallet in creation
*
* @param {Object} config - configuration for this wallet
* @param {Object} config.wallet - default configuration for the wallet
2014-09-08 15:42:55 -03:00
* @constructor
2014-04-16 17:50:10 -03:00
*/
2014-09-03 01:25:08 -03:00
2014-09-28 18:38:06 -03:00
function Identity(email, password, opts) {
preconditions.checkArgument(opts);
2014-09-03 01:25:08 -03:00
var storageOpts = {};
2014-09-28 18:38:06 -03:00
if (opts.pluginManager) {
storageOpts = _.clone({
2014-09-30 21:16:46 -03:00
db: opts.pluginManager.get('DB'),
passphrase: opts.passphrase,
2014-09-28 18:38:06 -03:00
});
2014-09-27 18:53:34 -03:00
/*
* TODO (plugins for other services)
*
* blockchainOpts = {
* provider: Insight...
* }
*/
2014-09-03 01:25:08 -03:00
}
2014-09-28 18:38:06 -03:00
storageOpts.password = password;
2014-09-03 01:25:08 -03:00
2014-09-28 18:38:06 -03:00
this.storage = Identity._newStorage(storageOpts);
2014-09-30 21:16:46 -03:00
this.storage.setPassword(password);
2014-10-07 18:33:55 -03:00
this.networkOpts = {
'livenet': opts.network.livenet,
'testnet': opts.network.testnet,
};
2014-10-07 18:33:55 -03:00
this.blockchainOpts = {
'livenet': opts.network.livenet,
'testnet': opts.network.testnet,
};
2014-04-16 17:50:10 -03:00
this.walletDefaults = opts.walletDefaults || {};
2014-09-28 18:38:06 -03:00
this.version = opts.version || version;
// open wallets
2014-09-30 21:16:46 -03:00
this.openWallets = [];
2014-09-28 18:38:06 -03:00
};
/* for stubbing */
2014-09-30 15:28:02 -03:00
Identity._createProfile = function(email, password, storage, cb) {
Profile.create(email, password, storage, cb);
2014-09-28 18:38:06 -03:00
};
2014-09-30 20:12:02 -03:00
2014-09-28 18:38:06 -03:00
Identity._newStorage = function(opts) {
2014-09-27 18:53:34 -03:00
return new Storage(opts);
};
2014-09-29 19:58:00 -03:00
Identity._newWallet = function(opts) {
2014-09-29 12:11:10 -03:00
return new Wallet(opts);
};
Identity._walletFromObj = function(o, s, n, b, skip) {
return Wallet.fromObj(o, s, n, b, skip);
};
2014-10-07 18:33:55 -03:00
Identity._walletRead = function(id, r, cb) {
return Wallet.read(id, r, cb);
2014-09-29 19:58:00 -03:00
};
Identity._walletDelete = function(id, s, cb) {
return Wallet.delete(id, s, cb);
2014-09-29 19:58:00 -03:00
};
2014-10-01 08:35:17 -03:00
/* for stubbing */
Identity._openProfile = function(email, password, storage, cb) {
Profile.open(email, password, storage, cb);
};
2014-10-07 18:33:55 -03:00
/* for stubbing */
Identity._newAsync = function(opts) {
return new Async(opts);
};
2014-10-01 08:35:17 -03:00
2014-09-28 18:38:06 -03:00
/**
* creates and Identity
*
* @param email
* @param password
* @param opts
* @param cb
* @return {undefined}
*/
Identity.create = function(email, password, opts, cb) {
2014-09-30 16:04:17 -03:00
opts = opts || {};
2014-09-30 15:28:02 -03:00
2014-09-28 18:38:06 -03:00
var iden = new Identity(email, password, opts);
2014-09-30 16:04:17 -03:00
2014-09-30 15:28:02 -03:00
Identity._createProfile(email, password, iden.storage, function(err, profile) {
if (err) return cb(err);
iden.profile = profile;
2014-09-30 16:04:17 -03:00
if (opts.noWallets)
cb(null, iden);
// default wallet
var dflt = _.clone(opts.walletDefaults);
var wopts = _.extend(dflt, {
2014-09-30 16:04:17 -03:00
nickname: email,
networkName: opts.networkName,
requiredCopayers: 1,
totalCopayers: 1,
2014-09-30 21:16:46 -03:00
password: password,
name: 'general',
2014-09-30 20:12:02 -03:00
});
2014-09-30 16:04:17 -03:00
iden.createWallet(wopts, function(err, w) {
return cb(null, iden, w);
});
2014-09-28 18:38:06 -03:00
});
};
/**
* validates Profile's email
*
* @param authcode
* @param cb
* @return {undefined}
*/
Identity.prototype.validate = function(authcode, cb) {
// TODO
console.log('[Identity.js.99] TODO: Should validate email thru authcode'); //TODO
return cb();
};
/**
* open's an Identity from storage
*
* @param email
* @param password
* @param opts
* @param cb
* @return {undefined}
*/
Identity.open = function(email, password, opts, cb) {
var iden = new Identity(email, password, opts);
2014-10-01 08:35:17 -03:00
Identity._openProfile(email, password, iden.storage, function(err, profile) {
if (err) return cb(err);
iden.profile = profile;
var wids = _.pluck(iden.listWallets(), 'id');
if (!wids || !wids.length)
return new Error('Could not open any wallet from profile');
// Open All wallets from profile
//This could be optional, or opts.onlyOpen = wid
var firstWallet;
_.each(wids, function(wid) {
iden.openWallet(wid, function(err, w) {
if (err)
log.error('Cound not open wallet id:' + wid + '. Skipping')
else {
log.info('Open wallet id:' + wid + ' opened');
if (!firstWallet)
firstWallet = w;
}
})
});
2014-10-01 08:35:17 -03:00
return cb(err, iden, firstWallet);
2014-09-28 18:38:06 -03:00
});
};
/**
* isAvailable
*
* @param email
* @param opts
* @param cb
* @return {undefined}
*/
Identity.isAvailable = function(email, opts, cb) {
console.log('[Identity.js.127:isAvailable:] TODO'); //TODO
return cb();
};
/**
* store
*
* @param opts
* @param cb
* @return {undefined}
*/
2014-09-28 18:38:06 -03:00
Identity.prototype.store = function(opts, cb) {
2014-09-30 15:28:02 -03:00
preconditions.checkState(this.profile);
2014-09-28 20:50:37 -03:00
var self = this;
2014-09-28 21:22:53 -03:00
self.profile.store(opts, function(err) {
if (err) return cb(err);
2014-09-30 21:16:46 -03:00
var l = self.openWallets.length,
2014-09-28 20:50:37 -03:00
i = 0;
if (!l) return cb();
2014-09-30 21:16:46 -03:00
_.each(self.openWallets, function(w) {
2014-09-28 20:50:37 -03:00
w.store(function(err) {
if (err) return cb(err);
if (++i == l)
return cb();
})
});
});
2014-09-28 18:38:06 -03:00
};
2014-09-30 21:16:46 -03:00
Identity.prototype._cleanUp = function() {
2014-10-07 18:33:55 -03:00
// NOP
};
2014-09-30 21:16:46 -03:00
/**
* @desc Closes the wallet and disconnects all services
*/
Identity.prototype.close = function(cb) {
preconditions.checkState(this.profile);
2014-10-01 08:35:17 -03:00
var l = this.openWallets.length,
2014-09-30 21:16:46 -03:00
i = 0;
2014-10-01 08:35:17 -03:00
if (!l) {
return cb ? cb() : null;
}
2014-09-30 21:16:46 -03:00
var self = this;
2014-10-01 08:35:17 -03:00
_.each(this.openWallets, function(w) {
2014-09-30 21:16:46 -03:00
w.close(function(err) {
if (err) return cb(err);
if (++i == l) {
self._cleanUp();
if (cb) return cb();
}
2014-09-30 21:16:46 -03:00
})
});
};
/**
* @desc Imports a wallet from an encrypted base64 object
* @param {string} base64 - the base64 encoded object
2014-09-18 18:29:00 -03:00
* @param {string} passphrase - passphrase to decrypt it
* @param {string[]} skipFields - fields to ignore when importing
* @return {Wallet}
*/
2014-09-30 21:16:46 -03:00
Identity.prototype.importWallet = function(base64, password, skipFields, cb) {
2014-09-29 16:55:45 -03:00
preconditions.checkArgument(cb);
2014-09-30 21:16:46 -03:00
this.storage.setPassword(password);
2014-09-29 11:35:04 -03:00
var obj = this.storage.decrypt(base64);
if (!obj) return false;
2014-10-07 18:33:55 -03:00
var w = Identity._walletFromObj(obj, this.storage, this.networkOpts, this.blockchainOpts);
2014-09-29 11:35:04 -03:00
this._checkVersion(w.version);
2014-09-29 16:55:45 -03:00
this.addWallet(w, function(err) {
2014-09-29 11:35:04 -03:00
if (err) return cb(err);
2014-09-29 12:11:10 -03:00
w.store(cb);
2014-09-29 11:35:04 -03:00
});
2014-05-01 18:32:22 -03:00
};
Identity.prototype.closeWallet = function(wid, cb) {
var w = this.getOpenWallet(wid);
preconditions.checkState(w, 'Wallet not found');
var self = this;
w.close(function(err) {
self.openWallets = _.without(self.openWallets, function(id) {
id === wid
});
return cb(err);
});
};
/**
2014-09-14 13:52:43 -03:00
* @desc This method prepares options for a new Wallet
*
* @param {Object} opts
* @param {string} opts.id
* @param {PrivateKey=} opts.privateKey
* @param {string=} opts.privateKeyHex
* @param {number} opts.requiredCopayers
* @param {number} opts.totalCopayers
* @param {PublicKeyRing=} opts.publicKeyRing
* @param {string} opts.nickname
2014-09-30 21:16:46 -03:00
* @param {string} opts.password
* @TODO: Figure out what is this parameter
* @param {?} opts.spendUnconfirmed this.walletDefaults.spendUnconfirmed ??
* @TODO: Figure out in what unit is this reconnect delay.
* @param {number} opts.reconnectDelay milliseconds?
* @param {number=} opts.version
2014-09-03 15:43:27 -03:00
* @param {callback} opts.version
* @return {Wallet}
*/
2014-09-27 18:56:25 -03:00
Identity.prototype.createWallet = function(opts, cb) {
2014-09-08 10:46:57 -03:00
preconditions.checkArgument(cb);
2014-09-30 20:12:02 -03:00
preconditions.checkState(this.profile);
2014-09-10 13:56:49 -07:00
opts = opts || {};
opts.networkName = opts.networkName || 'testnet';
2014-09-01 12:35:40 -03:00
log.debug('### CREATING NEW WALLET.' + (opts.id ? ' USING ID: ' + opts.id : ' NEW ID') + (opts.privateKey ? ' USING PrivateKey: ' + opts.privateKey.getId() : ' NEW PrivateKey'));
2014-04-16 17:50:10 -03:00
2014-08-21 14:54:36 -04:00
var privOpts = {
networkName: opts.networkName,
2014-08-21 14:54:36 -04:00
};
2014-09-04 16:13:30 -03:00
if (opts.privateKeyHex && opts.privateKeyHex.length > 1) {
2014-08-21 14:54:36 -04:00
privOpts.extendedPrivateKeyString = opts.privateKeyHex;
}
opts.privateKey = opts.privateKey || new PrivateKey(privOpts);
2014-04-20 12:41:28 -03:00
2014-04-16 17:50:10 -03:00
var requiredCopayers = opts.requiredCopayers || this.walletDefaults.requiredCopayers;
2014-06-16 15:51:19 -03:00
var totalCopayers = opts.totalCopayers || this.walletDefaults.totalCopayers;
2014-08-14 18:46:42 -04:00
opts.lockTimeoutMin = this.walletDefaults.idleDurationMin;
2014-04-16 17:50:10 -03:00
opts.publicKeyRing = opts.publicKeyRing || new PublicKeyRing({
networkName: opts.networkName,
2014-04-16 17:50:10 -03:00
requiredCopayers: requiredCopayers,
totalCopayers: totalCopayers,
});
opts.publicKeyRing.addCopayer(
opts.privateKey.deriveBIP45Branch().extendedPublicKeyString(),
2014-08-01 11:24:16 -03:00
opts.nickname
);
2014-09-01 12:35:40 -03:00
log.debug('\t### PublicKeyRing Initialized');
2014-04-16 17:50:10 -03:00
2014-08-05 16:42:51 -03:00
opts.txProposals = opts.txProposals || new TxProposals({
networkName: opts.networkName,
2014-04-16 17:50:10 -03:00
});
2014-09-01 12:35:40 -03:00
log.debug('\t### TxProposals Initialized');
2014-04-16 17:50:10 -03:00
2014-04-16 17:50:10 -03:00
opts.storage = this.storage;
2014-10-07 18:33:55 -03:00
opts.networkOpts = this.networkOpts;
opts.blockchainOpts = this.blockchainOpts;
2014-04-16 20:58:57 -03:00
2014-04-16 17:50:10 -03:00
opts.spendUnconfirmed = opts.spendUnconfirmed || this.walletDefaults.spendUnconfirmed;
2014-06-16 15:51:19 -03:00
opts.reconnectDelay = opts.reconnectDelay || this.walletDefaults.reconnectDelay;
2014-04-16 17:50:10 -03:00
opts.requiredCopayers = requiredCopayers;
2014-06-16 15:51:19 -03:00
opts.totalCopayers = totalCopayers;
opts.version = opts.version || this.version;
2014-08-14 18:46:42 -04:00
2014-10-07 18:33:55 -03:00
if (opts.password && !this.storage.hasPassphrase())
this.storage.setPassword(opts.password);
2014-09-28 21:22:53 -03:00
2014-09-29 06:31:04 -03:00
var self = this;
2014-09-29 19:58:00 -03:00
var w = Identity._newWallet(opts);
2014-09-29 11:35:04 -03:00
this.addWallet(w, function(err) {
2014-09-14 13:52:43 -03:00
if (err) return cb(err);
self.openWallets.push(w);
2014-09-29 11:35:04 -03:00
self.profile.setLastOpenedTs(w.id, function(err) {
2014-10-07 18:33:55 -03:00
w.netStart();
2014-09-29 12:11:10 -03:00
return cb(err, w);
2014-09-03 15:43:27 -03:00
});
});
2014-04-16 17:50:10 -03:00
};
// add wallet (import)
2014-09-29 11:35:04 -03:00
Identity.prototype.addWallet = function(wallet, cb) {
2014-09-29 12:11:10 -03:00
preconditions.checkArgument(wallet);
2014-09-29 16:55:45 -03:00
preconditions.checkArgument(wallet.getId);
2014-09-29 11:35:04 -03:00
preconditions.checkArgument(cb);
2014-09-30 20:12:02 -03:00
preconditions.checkState(this.profile);
2014-09-29 11:35:04 -03:00
var self = this;
self.profile.addWallet(wallet.getId(), {
name: wallet.name
}, function(err) {
2014-09-29 11:35:04 -03:00
2014-09-30 21:16:46 -03:00
if (err) return cb(err);
2014-09-29 16:55:45 -03:00
wallet.store(function(err) {
2014-09-29 12:11:10 -03:00
return cb(err);
2014-09-29 11:35:04 -03:00
});
});
};
/**
* @desc Checks if a version is compatible with the current version
* @param {string} inVersion - a version, with major, minor, and revision, period-separated (x.y.z)
* @throws {Error} if there's a major version difference
*/
Identity.prototype._checkVersion = function(inVersion) {
2014-09-29 12:11:10 -03:00
if (inVersion) {
var thisV = this.version.split('.');
var thisV0 = parseInt(thisV[0]);
var inV = inVersion.split('.');
var inV0 = parseInt(inV[0]);
}
2014-05-14 21:02:01 -03:00
//We only check for major version differences
2014-06-16 15:51:19 -03:00
if (thisV0 < inV0) {
2014-05-14 21:02:01 -03:00
throw new Error('Major difference in software versions' +
2014-09-04 16:13:30 -03:00
'. Received:' + inVersion +
'. Current version:' + this.version +
'. Aborting.');
2014-05-14 21:02:01 -03:00
}
};
/**
* @desc Retrieve a wallet from the storage
* @param {string} walletId - the id of the wallet
2014-09-03 01:25:08 -03:00
* @param {function} callback (err, {Wallet})
* @return
*/
Identity.prototype.openWallet = function(walletId, cb) {
2014-09-08 10:46:57 -03:00
preconditions.checkArgument(cb);
preconditions.checkState(this.storage.hasPassphrase());
var self = this;
2014-10-01 08:35:17 -03:00
// TODO
// self.migrateWallet(walletId, password, function() {
2014-10-07 18:33:55 -03:00
//
2014-09-29 19:58:00 -03:00
2014-10-07 18:33:55 -03:00
Identity._walletRead(walletId, {
storage: self.storage,
networkOpts: this.networkOpts,
2014-10-07 18:33:55 -03:00
blockchainOpts: this.blockchainOpts
}, function(err, w) {
2014-10-01 08:35:17 -03:00
if (err) return cb(err);
self.openWallets.push(w);
2014-10-01 08:35:17 -03:00
w.store(function(err) {
self.profile.setLastOpenedTs(walletId, function() {
return cb(err, w);
2014-09-03 01:25:08 -03:00
});
});
});
2014-10-01 08:35:17 -03:00
// });
2014-04-16 20:58:57 -03:00
};
2014-09-29 06:31:04 -03:00
Identity.prototype.getOpenWallet = function(id) {
return _.findWhere(this.openWallets, {
id: id,
});
};
Identity.prototype.listWallets = function(a) {
var ret = this.profile.listWallets();
return ret;
};
2014-04-16 17:50:10 -03:00
/**
* @desc Deletes this wallet. This involves removing it from the storage instance
* @param {string} walletId
* @callback cb
* @return {err}
*/
2014-09-28 18:38:06 -03:00
Identity.prototype.deleteWallet = function(walletId, cb) {
var self = this;
2014-09-29 19:58:00 -03:00
Identity._walletDelete(walletId, this.storage, function(err) {
if (err) return cb(err);
self.profile.deleteWallet(walletId, function(err) {
return cb(err);
});
})
2014-04-16 17:50:10 -03:00
};
/**
* @desc Pass through to {@link Wallet#secret}
*/
Identity.prototype.decodeSecret = function(secret) {
2014-05-14 14:24:24 -07:00
try {
return Wallet.decodeSecret(secret);
} catch (e) {
return false;
}
2014-06-09 18:01:15 -03:00
};
2014-04-16 20:58:57 -03:00
/**
* @callback walletCreationCallback
2014-09-08 15:42:55 -03:00
* @param {?} err - an error, if any, that happened during the wallet creation
* @param {Wallet=} wallet - the wallet created
*/
2014-04-20 12:41:28 -03:00
/**
* @desc Start the network functionality.
*
* Start up the Network instance and try to join a wallet defined by the
* parameter <tt>secret</tt> using the parameter <tt>nickname</tt>. Encode
* information locally using <tt>passphrase</tt>. <tt>privateHex</tt> is the
* private extended master key. <tt>cb</tt> has two params: error and wallet.
*
2014-09-14 13:52:43 -03:00
* @param {object} opts
* @param {string} opts.secret - the wallet secret
* @param {string} opts.nickname - a nickname for the current user
* @param {string} opts.privateHex - the private extended master key
* @param {walletCreationCallback} cb - a callback
*/
2014-09-27 18:56:25 -03:00
Identity.prototype.joinWallet = function(opts, cb) {
2014-09-14 13:52:43 -03:00
preconditions.checkArgument(opts);
preconditions.checkArgument(opts.secret);
2014-09-08 10:46:57 -03:00
preconditions.checkArgument(cb);
2014-08-20 18:00:33 -04:00
var self = this;
2014-09-14 13:52:43 -03:00
var decodedSecret = this.decodeSecret(opts.secret);
2014-09-10 14:01:10 -07:00
if (!decodedSecret || !decodedSecret.networkName || !decodedSecret.pubKey) {
return cb('badSecret');
}
2014-06-16 15:51:19 -03:00
2014-08-20 18:00:33 -04:00
var privOpts = {
networkName: decodedSecret.networkName,
2014-08-20 18:00:33 -04:00
};
2014-09-14 13:52:43 -03:00
if (opts.privateHex && opts.privateHex.length > 1) {
2014-10-04 11:30:08 -03:00
privOpts.extendedPrivateKeyString = opts.privateHex;
2014-08-20 18:00:33 -04:00
}
2014-04-20 12:41:28 -03:00
//Create our PrivateK
2014-08-20 18:00:33 -04:00
var privateKey = new PrivateKey(privOpts);
2014-09-01 12:35:40 -03:00
log.debug('\t### PrivateKey Initialized');
2014-09-18 18:29:00 -03:00
var joinOpts = {
2014-04-24 23:13:55 -03:00
copayerId: privateKey.getId(),
privkey: privateKey.getIdPriv(),
2014-09-03 16:51:02 -03:00
key: privateKey.getIdKey(),
secretNumber: decodedSecret.secretNumber,
2014-04-24 23:13:55 -03:00
};
2014-10-07 18:33:55 -03:00
var joinNetwork = Identity._newAsync(this.networkOpts[decodedSecret.networkName]);
// This is a hack to reconize if the connection was rejected or the peer wasn't there.
var connectedOnce = false;
joinNetwork.on('connected', function(sender, data) {
connectedOnce = true;
});
joinNetwork.on('connect_error', function() {
return cb('connectionError');
});
joinNetwork.on('serverError', function() {
return cb('joinError');
});
2014-09-18 18:29:00 -03:00
joinNetwork.start(joinOpts, function() {
joinNetwork.greet(decodedSecret.pubKey, joinOpts.secretNumber);
joinNetwork.on('data', function(sender, data) {
2014-09-15 14:25:09 -03:00
if (data.type === 'walletId' && data.opts) {
2014-10-04 19:52:43 -03:00
if (!data.networkName || data.networkName !== decodedSecret.networkName) {
return cb('badNetwork');
}
2014-10-04 19:52:43 -03:00
data.opts.networkName = data.networkName;
2014-09-23 15:24:57 -03:00
var walletOpts = _.clone(data.opts);
2014-09-18 18:29:00 -03:00
walletOpts.id = data.walletId;
walletOpts.privateKey = privateKey;
walletOpts.nickname = opts.nickname || self.profile.name;
if (opts.password)
walletOpts.password = opts.password;
2014-09-18 18:29:00 -03:00
2014-09-28 18:38:06 -03:00
self.createWallet(walletOpts, function(err, w) {
2014-09-18 18:29:00 -03:00
if (w) {
w.sendWalletReady(decodedSecret.pubKey);
2014-09-15 14:25:09 -03:00
} else {
if (!err) err = 'walletFull';
2014-09-18 18:29:00 -03:00
log.info(err);
2014-09-15 14:25:09 -03:00
}
return cb(err, w);
});
2014-04-20 16:16:09 -03:00
}
2014-04-16 20:58:57 -03:00
});
});
};
2014-09-27 17:14:49 -03:00
module.exports = Identity;