2015-01-03 11:29:22 +01:00
|
|
|
/**
|
|
|
|
* Node.js implementation of platform-specific routines.
|
|
|
|
*/
|
|
|
|
|
|
|
|
"use strict";
|
|
|
|
|
|
|
|
var crypto = require("crypto");
|
2015-01-07 22:28:13 +01:00
|
|
|
var bignum = require("bignum");
|
|
|
|
var assert = require("./util").assert;
|
|
|
|
|
2015-01-03 15:52:27 +01:00
|
|
|
var createHash = crypto.createHash;
|
2015-01-03 11:29:22 +01:00
|
|
|
|
|
|
|
exports.sha512 = function(buf) {
|
2015-01-03 15:52:27 +01:00
|
|
|
return createHash("sha512").update(buf).digest();
|
2015-01-03 11:29:22 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
exports.sha256 = function(buf) {
|
2015-01-03 15:52:27 +01:00
|
|
|
return createHash("sha256").update(buf).digest();
|
2015-01-03 11:29:22 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
exports.ripemd160 = function(buf) {
|
2015-01-03 15:52:27 +01:00
|
|
|
return createHash("ripemd160").update(buf).digest();
|
2015-01-03 11:29:22 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
exports.randomBytes = crypto.randomBytes;
|
2015-01-07 22:28:13 +01:00
|
|
|
|
|
|
|
// 2^64.
|
|
|
|
var B64 = bignum("18446744073709551616");
|
|
|
|
|
|
|
|
// NOTE(Kagami): We can't calculate entire target in JavaScript but the
|
|
|
|
// result can be represented in native number type without losing
|
|
|
|
// precision (targets mainly much less than 2^53).
|
|
|
|
exports.getTarget = function(opts) {
|
|
|
|
// Calculate it bottom-up, right-to-left.
|
|
|
|
var length = bignum(opts.payloadLength)
|
|
|
|
// To account for the nonce which we will append later.
|
|
|
|
.add(8)
|
|
|
|
.add(opts.payloadLengthExtraBytes);
|
|
|
|
var denominator = bignum(opts.ttl)
|
|
|
|
.mul(length)
|
|
|
|
.div(65536)
|
|
|
|
.add(length)
|
|
|
|
.mul(opts.nonceTrialsPerByte);
|
|
|
|
var target = B64.div(denominator).toNumber();
|
|
|
|
assert(target <= 9007199254740991, "Unsafe target");
|
|
|
|
return target;
|
|
|
|
};
|