Some syntax tidying up, plus fixed bug with message data not being a uint8array after IPC message

pull/21/head
Beaudan 7 years ago
parent 143b1e883d
commit d4180b3ca6

@ -17,10 +17,10 @@ function initialize({ url }) {
function connect() { function connect() {
return { return {
sendMessage sendMessage,
}; };
function getPoWNonce(timestamp, ttl, pub_key, data) { function getPoWNonce(timestamp, ttl, pubKey, data) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
// Create forked node process to calculate PoW without blocking main process // Create forked node process to calculate PoW without blocking main process
const child = fork('./libloki/proof-of-work.js'); const child = fork('./libloki/proof-of-work.js');
@ -29,8 +29,8 @@ function initialize({ url }) {
child.send({ child.send({
timestamp, timestamp,
ttl, ttl,
pub_key, pubKey,
data data,
}); });
// Handle child process error (should never happen) // Handle child process error (should never happen)
@ -49,14 +49,14 @@ function initialize({ url }) {
}); });
}); });
}; }
async function sendMessage(pub_key, data, ttl) { async function sendMessage(pubKey, data, ttl) {
const timestamp = Math.floor(Date.now() / 1000); const timestamp = Math.floor(Date.now() / 1000);
// Nonce is returned as a base64 string to include in header // Nonce is returned as a base64 string to include in header
let nonce; let nonce;
try { try {
nonce = await getPoWNonce(timestamp, ttl, pub_key, data); nonce = await getPoWNonce(timestamp, ttl, pubKey, data);
} catch(err) { } catch(err) {
// Something went horribly wrong // Something went horribly wrong
// TODO: Handle gracefully // TODO: Handle gracefully
@ -67,7 +67,7 @@ function initialize({ url }) {
url: `${url}/send_message`, url: `${url}/send_message`,
type: 'POST', type: 'POST',
responseType: undefined, responseType: undefined,
timeout: undefined timeout: undefined,
}; };
log.info(options.type, options.url); log.info(options.type, options.url);
@ -79,7 +79,7 @@ function initialize({ url }) {
'X-Loki-pow-nonce': nonce, 'X-Loki-pow-nonce': nonce,
'X-Loki-timestamp': timestamp.toString(), 'X-Loki-timestamp': timestamp.toString(),
'X-Loki-ttl': ttl.toString(), 'X-Loki-ttl': ttl.toString(),
'X-Loki-recipient': pub_key, 'X-Loki-recipient': pubKey,
'Content-Length': data.byteLength, 'Content-Length': data.byteLength,
}, },
timeout: options.timeout, timeout: options.timeout,

@ -4,27 +4,31 @@ const bb = require('bytebuffer');
// Increment Uint8Array nonce by 1 with carrying // Increment Uint8Array nonce by 1 with carrying
function incrementNonce(nonce) { function incrementNonce(nonce) {
let idx = nonce.length - 1; let idx = nonce.length - 1;
nonce[idx] += 1; const newNonce = nonce;
// Nonce will just reset to 0 if all values are 255 causing infinite loop, should never happen newNonce[idx] += 1;
while (nonce[idx] == 0 && idx >= 0) { // Nonce will just reset to 0 if all values are 255 causing infinite loop
nonce[--idx] += 1; while (nonce[idx] === 0 && idx > 0) {
idx -= 1;
newNonce[idx] += 1;
} }
return nonce; return nonce;
} }
// Convert a Uint8Array to a base64 string // Convert a Uint8Array to a base64 string
function bufferToBase64(buf) { function bufferToBase64(buf) {
let binstr = Array.prototype.map.call(buf, function (ch) { function mapFn(ch) {
return String.fromCharCode(ch); return String.fromCharCode(ch);
}).join(''); };
const binstr = Array.prototype.map.call(buf, mapFn).join('');
return bb.btoa(binstr); return bb.btoa(binstr);
} }
// Convert javascript number to Uint8Array of length 8 // Convert javascript number to Uint8Array of length 8
function numberToUintArr(numberVal) { function numberToUintArr(numberVal) {
let arr = new Uint8Array(8); const arr = new Uint8Array(8);
for (let idx = 7; idx >= 0; idx--) { let n;
let n = 8 - (idx + 1); for (let idx = 7; idx >= 0; idx -= 1) {
n = 8 - (idx + 1);
// 256 ** n is the value of one bit in arr[idx], modulus to carry over // 256 ** n is the value of one bit in arr[idx], modulus to carry over
arr[idx] = (numberVal / 256**n) % 256; arr[idx] = (numberVal / 256**n) % 256;
} }
@ -32,12 +36,14 @@ function numberToUintArr(numberVal) {
} }
// Return nonce that hashes together with payload lower than the target // Return nonce that hashes together with payload lower than the target
function calcPoW(timestamp, ttl, pub_key, data) { function calcPoW(timestamp, ttl, pubKey, data) {
const leadingString = timestamp.toString() + ttl.toString() + pub_key; const leadingString = timestamp.toString() + ttl.toString() + pubKey;
const leadingArray = new Uint8Array(bb.wrap(leadingString, 'binary').toArrayBuffer()); const leadingArray = new Uint8Array(bb.wrap(leadingString, 'binary').toArrayBuffer());
// Payload constructed from concatenating timestamp, ttl and pubkey strings, converting to Uint8Array // Payload constructed from concatenating timestamp, ttl and pubkey strings,
// and then appending to the message data array // converting to Uint8Array and then appending to the message data array
const payload = leadingArray + data; const payload = new Uint8Array(leadingArray.length + data.length);
payload.set(leadingArray);
payload.set(data, leadingArray.length);
const nonceLen = 8; const nonceLen = 8;
// Modify this value for difficulty scaling // Modify this value for difficulty scaling
// TODO: Have more informed reason for setting this to 100 // TODO: Have more informed reason for setting this to 100
@ -45,14 +51,15 @@ function calcPoW(timestamp, ttl, pub_key, data) {
let nonce = new Uint8Array(nonceLen); let nonce = new Uint8Array(nonceLen);
let trialValue = numberToUintArr(Number.MAX_SAFE_INTEGER); let trialValue = numberToUintArr(Number.MAX_SAFE_INTEGER);
// Target is converter to Uint8Array for simple comparison with trialValue // Target is converter to Uint8Array for simple comparison with trialValue
const target = numberToUintArr(Math.floor(Math.pow(2, 64) / ( const targetNum = Math.floor(2**64 / (
nonceTrialsPerByte * ( nonceTrialsPerByte * (
payload.length + nonceLen + ( payload.length + nonceLen + (
(ttl * ( payload.length + nonceLen )) (ttl * ( payload.length + nonceLen )) /
/ Math.pow(2, 16) 2**16
) )
) )
))); ));
const target = numberToUintArr(targetNum);
const initialHash = new Uint8Array(bb.wrap(hash(payload), 'hex').toArrayBuffer()); const initialHash = new Uint8Array(bb.wrap(hash(payload), 'hex').toArrayBuffer());
while (trialValue > target) { while (trialValue > target) {
nonce = incrementNonce(nonce); nonce = incrementNonce(nonce);
@ -63,5 +70,11 @@ function calcPoW(timestamp, ttl, pub_key, data) {
// Start calculation in child process when main process sends message data // Start calculation in child process when main process sends message data
process.on('message', (msg) => { process.on('message', (msg) => {
process.send({nonce: calcPoW(msg.timestamp, msg.ttl, msg.pub_key, msg.data)}); // Convert data back to Uint8Array after IPC has serialised to JSON
const msgLen = Object.keys(msg.data).length;
const msgData = new Uint8Array(msgLen);
for (let i = 0; i < msgLen; i += 1) {
msgData[i] = msg.data[i];
}
process.send({nonce: calcPoW(msg.timestamp, msg.ttl, msg.pubKey, msgData)});
}); });
Loading…
Cancel
Save