bitcore-wallet-service/lib/model/addressmanager.js

72 lines
2.0 KiB
JavaScript
Raw Normal View History

2015-02-03 10:44:44 -08:00
var _ = require('lodash');
var $ = require('preconditions').singleton();
2015-10-30 11:24:47 -07:00
var Bitcore = require('bitcore-lib');
var Constants = require('../common/constants');
2015-02-03 10:44:44 -08:00
function AddressManager() {};
2015-02-03 10:44:44 -08:00
2015-02-17 16:20:08 -08:00
AddressManager.create = function(opts) {
opts = opts || {};
2015-02-03 10:44:44 -08:00
var x = new AddressManager();
x.version = 2;
2015-10-30 11:24:47 -07:00
x.derivationStrategy = opts.derivationStrategy || Constants.DERIVATION_STRATEGIES.BIP45;
$.checkState(_.contains(_.values(Constants.DERIVATION_STRATEGIES), x.derivationStrategy));
2015-02-17 16:20:08 -08:00
x.receiveAddressIndex = 0;
x.changeAddressIndex = 0;
x.copayerIndex = _.isNumber(opts.copayerIndex) ? opts.copayerIndex : Constants.BIP45_SHARED_INDEX;
2015-02-17 16:20:08 -08:00
return x;
};
AddressManager.fromObj = function(obj) {
var x = new AddressManager();
x.version = obj.version;
2015-10-30 11:24:47 -07:00
x.derivationStrategy = obj.derivationStrategy || Constants.DERIVATION_STRATEGIES.BIP45;
2015-02-17 16:20:08 -08:00
x.receiveAddressIndex = obj.receiveAddressIndex;
2015-02-03 10:44:44 -08:00
x.changeAddressIndex = obj.changeAddressIndex;
x.copayerIndex = obj.copayerIndex;
return x;
};
AddressManager.supportsCopayerBranches = function(derivationStrategy) {
2015-10-30 11:24:47 -07:00
return derivationStrategy == Constants.DERIVATION_STRATEGIES.BIP45;
};
2015-02-22 12:35:27 -08:00
2015-02-17 16:20:08 -08:00
AddressManager.prototype._incrementIndex = function(isChange) {
2015-02-03 10:44:44 -08:00
if (isChange) {
this.changeAddressIndex++;
} else {
this.receiveAddressIndex++;
}
};
2015-04-17 14:25:41 -07:00
AddressManager.prototype.rewindIndex = function(isChange, n) {
n = _.isUndefined(n) ? 1 : n;
if (isChange) {
2015-04-17 14:31:47 -07:00
this.changeAddressIndex = Math.max(0, this.changeAddressIndex - n);
2015-04-17 14:25:41 -07:00
} else {
2015-04-17 14:31:47 -07:00
this.receiveAddressIndex = Math.max(0, this.receiveAddressIndex - n);
2015-04-17 14:25:41 -07:00
}
};
2015-02-17 16:20:08 -08:00
AddressManager.prototype.getCurrentAddressPath = function(isChange) {
2015-02-22 12:35:27 -08:00
return 'm/' +
2015-10-30 11:24:47 -07:00
(this.derivationStrategy == Constants.DERIVATION_STRATEGIES.BIP45 ? this.copayerIndex + '/' : '') +
2015-02-22 12:35:27 -08:00
(isChange ? 1 : 0) + '/' +
(isChange ? this.changeAddressIndex : this.receiveAddressIndex);
};
2015-02-17 16:20:08 -08:00
AddressManager.prototype.getNewAddressPath = function(isChange) {
2015-02-03 11:46:28 -08:00
var ret = this.getCurrentAddressPath(isChange);
2015-02-03 10:44:44 -08:00
this._incrementIndex(isChange);
2015-02-03 11:46:28 -08:00
return ret;
2015-02-03 10:44:44 -08:00
};
module.exports = AddressManager;