bitmessage-js/lib/platform.browser.js

44 lines
1.1 KiB
JavaScript
Raw Normal View History

2014-12-13 19:56:14 +01:00
/**
2015-01-03 11:29:22 +01:00
* Browser implementation of platform-specific routines.
2014-12-13 19:56:14 +01:00
*/
"use strict";
var hash = require("hash.js");
2015-01-07 22:28:13 +01:00
var BN = require("bn.js");
var assert = require("./util").assert;
2014-12-18 21:54:27 +01:00
exports.sha512 = function(buf) {
2015-01-06 00:45:16 +01:00
return new Buffer(hash.sha512().update(buf).digest());
};
2014-12-18 17:47:18 +01:00
2014-12-19 13:34:33 +01:00
exports.sha256 = function(buf) {
2015-01-05 14:41:34 +01:00
return new Buffer(hash.sha256().update(buf).digest());
2014-12-19 13:34:33 +01:00
};
exports.ripemd160 = function(buf) {
2015-01-05 14:41:34 +01:00
return new Buffer(hash.ripemd160().update(buf).digest());
};
2014-12-26 18:17:01 +01:00
exports.randomBytes = function(size) {
var arr = new Uint8Array(size);
window.crypto.getRandomValues(arr);
return new Buffer(arr);
};
2015-01-07 22:28:13 +01:00
var B64 = new BN("18446744073709551616");
exports.getTarget = function(opts) {
var length = new BN(opts.payloadLength);
length.iaddn(8);
length.iaddn(opts.payloadLengthExtraBytes);
var denominator = new BN(opts.ttl);
denominator.imul(length);
denominator.idivn(65536);
denominator.iadd(length);
denominator.imul(new BN(opts.nonceTrialsPerByte));
var target = parseInt(B64.div(denominator).toString(16), 16);
assert(target <= 9007199254740991, "Unsafe target");
return target;
};