copay/js/models/core/Structure.js

76 lines
2.2 KiB
JavaScript
Raw Normal View History

2014-05-29 13:19:14 -07:00
'use strict';
2014-06-24 10:40:03 -07:00
var preconditions = require('preconditions').singleton();
2014-05-29 13:19:14 -07:00
2014-05-30 07:07:34 -07:00
function Structure() {}
2014-05-29 13:19:14 -07:00
/*
* Based on https://github.com/maraoz/bips/blob/master/bip-NNNN.mediawiki
2014-07-29 06:14:15 -07:00
* m / purpose' / copayerIndex / change / addressIndex
2014-05-29 13:19:14 -07:00
*/
var PURPOSE = 45;
2014-05-30 06:29:51 -07:00
var MAX_NON_HARDENED = 0x80000000 - 1;
2014-05-29 13:19:14 -07:00
var SHARED_INDEX = MAX_NON_HARDENED - 0;
var ID_INDEX = MAX_NON_HARDENED - 1;
2014-05-30 07:07:34 -07:00
var BIP45_PUBLIC_PREFIX = 'm/' + PURPOSE + '\'';
2014-05-29 13:19:14 -07:00
Structure.BIP45_PUBLIC_PREFIX = BIP45_PUBLIC_PREFIX;
2014-07-29 06:14:15 -07:00
Structure.Branch = function(addressIndex, isChange, copayerIndex) {
preconditions.shouldBeNumber(addressIndex);
2014-06-24 10:40:03 -07:00
preconditions.shouldBeBoolean(isChange);
2014-05-30 07:07:34 -07:00
var ret = 'm/' +
2014-07-29 06:14:15 -07:00
(typeof copayerIndex !== 'undefined' ? copayerIndex : SHARED_INDEX) + '/' +
2014-05-30 07:07:34 -07:00
(isChange ? 1 : 0) + '/' +
2014-07-29 06:14:15 -07:00
addressIndex;
2014-05-29 13:19:14 -07:00
return ret;
};
2014-07-29 06:14:15 -07:00
Structure.FullBranch = function(addressIndex, isChange, copayerIndex) {
var sub = Structure.Branch(addressIndex, isChange, copayerIndex);
2014-05-29 13:19:14 -07:00
sub = sub.substring(2);
return BIP45_PUBLIC_PREFIX + '/' + sub;
};
2014-06-24 09:17:22 -07:00
Structure.indicesForPath = function(path) {
2014-06-24 10:40:03 -07:00
preconditions.shouldBeString(path);
2014-06-24 09:17:22 -07:00
var s = path.split('/');
return {
isChange: s[3] === '1',
index: parseInt(s[4]),
cosigner: parseInt(s[2])
2014-06-24 09:17:22 -07:00
};
};
2014-06-24 10:40:03 -07:00
Structure.IdFullBranch = Structure.FullBranch(0, false, ID_INDEX);
Structure.IdBranch = Structure.Branch(0, false, ID_INDEX);
2014-05-30 06:29:51 -07:00
Structure.PURPOSE = PURPOSE;
Structure.MAX_NON_HARDENED = MAX_NON_HARDENED;
Structure.SHARED_INDEX = SHARED_INDEX;
Structure.ID_INDEX = ID_INDEX;
2014-05-29 13:19:14 -07:00
2014-07-03 08:52:28 -07:00
Structure.parseBitcoinURI = function(uri) {
var ret = {};
var data = decodeURIComponent(uri);
var splitDots = data.split(':');
ret.protocol = splitDots[0];
data = splitDots[1];
var splitQuestion = data.split('?');
ret.address = splitQuestion[0];
2014-07-25 07:08:29 -07:00
if (splitQuestion.length > 1) {
var search = splitQuestion[1];
data = JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g, '":"') + '"}',
2014-07-29 06:14:43 -07:00
function(key, value) {
return key === "" ? value : decodeURIComponent(value);
});
ret.amount = parseFloat(data.amount);
ret.message = data.message;
2014-07-25 07:08:29 -07:00
}
2014-07-03 08:52:28 -07:00
return ret;
};
2014-07-29 06:14:43 -07:00
module.exports = Structure;