improve toBTC and fromBTC while ensuring safety.

This commit is contained in:
Christopher Jeffrey 2015-12-09 17:31:45 -08:00
parent f939d73b38
commit 14f08e891c

View File

@ -451,7 +451,18 @@ utils.assert.equal = function assertEqual(l, r, msg) {
throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
};
utils.toBTC = function toBTC(satoshi) {
utils.toBTC = function toBTC(satoshi, strict) {
if (typeof satoshi === 'string' && /^\d+(?:\.\d+)?$/.test(satoshi)) {
satoshi = new bn(satoshi, 10);
} else if (typeof satoshi === 'number') {
// XXX Dangerous precision - do not use for any real txes
if (!strict)
satoshi = new bn(Math.floor(+satoshi || 0).toString(16), 16);
}
if (!(satoshi instanceof bn))
throw new Error('could not calculate btc');
var m = new bn(10000000).mul(new bn(10));
var lo = satoshi.mod(m);
if (lo.cmpn(0) !== 0) {
@ -462,9 +473,35 @@ utils.toBTC = function toBTC(satoshi) {
} else {
lo = '';
}
return satoshi.div(m).toString(10) + lo.replace(/0+$/, '');
};
utils.fromBTC = function(btc, strict) {
var satoshi;
if (typeof btc === 'string' && /^\d+(?:\.\d+)?$/.test(btc)) {
var parts = btc.split('.');
parts[0] = parts[0] || '0';
parts[1] = parts[1] || '0';
while (parts[1].length < 8)
parts[1] += '0';
parts[0] = parts[0].replace(/^0+/, '');
satoshi = new bn(parts[0] + parts[1], 10);
} else if (typeof btc === 'number') {
// XXX Dangerous precision - do not use for any real txes
if (!strict)
satoshi = new bn(+btc || 0);
}
if (!(satoshi instanceof bn))
throw new Error('could not calculate satoshis');
var m = new bn(10000000).mul(new bn(10));
satoshi.imuln(m);
return satoshi;
};
utils.isIP = function(ip) {
if (typeof ip !== 'string')
return 0;
@ -519,14 +556,3 @@ utils.merge = function(target) {
});
return target;
};
utils.fromBTC = function(btc) {
var satoshi = new bn(+btc || 0);
satoshi.imuln(100000000);
return satoshi;
};
utils.ntoBTC = function(satoshi) {
satoshi = new bn(Math.floor(+satoshi || 0).toString(16), 16);
return bcoin.utils.toBTC(satoshi);
};