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

64 lines
1.4 KiB
JavaScript
Raw Normal View History

2015-02-03 10:44:44 -08:00
var _ = require('lodash');
2015-02-22 12:35:27 -08:00
var SHARED_INDEX = 0x80000000 - 1;
2015-02-03 10:44:44 -08:00
2015-02-17 16:20:08 -08:00
function AddressManager() {
this.version = '1.0.0';
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();
2015-02-17 16:20:08 -08:00
x.receiveAddressIndex = 0;
x.changeAddressIndex = 0;
2015-02-22 12:35:27 -08:00
x.copayerIndex = (opts && _.isNumber(opts.copayerIndex)) ? opts.copayerIndex : SHARED_INDEX;
2015-02-17 16:20:08 -08:00
return x;
};
AddressManager.fromObj = function(obj) {
var x = new AddressManager();
x.receiveAddressIndex = obj.receiveAddressIndex;
2015-02-03 10:44:44 -08:00
x.changeAddressIndex = obj.changeAddressIndex;
x.copayerIndex = obj.copayerIndex;
return x;
};
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-02-22 12:54:47 -08:00
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;