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

@ -4,27 +4,31 @@ const bb = require('bytebuffer');
// Increment Uint8Array nonce by 1 with carrying
function incrementNonce(nonce) {
let idx = nonce.length - 1;
nonce[idx] += 1;
// Nonce will just reset to 0 if all values are 255 causing infinite loop, should never happen
while (nonce[idx] == 0 && idx >= 0) {
nonce[--idx] += 1;
const newNonce = nonce;
newNonce[idx] += 1;
// Nonce will just reset to 0 if all values are 255 causing infinite loop
while (nonce[idx] === 0 && idx > 0) {
idx -= 1;
newNonce[idx] += 1;
}
return nonce;
}
// Convert a Uint8Array to a base64 string
function bufferToBase64(buf) {
let binstr = Array.prototype.map.call(buf, function (ch) {
function mapFn(ch) {
return String.fromCharCode(ch);
}).join('');
};
const binstr = Array.prototype.map.call(buf, mapFn).join('');
return bb.btoa(binstr);
}
// Convert javascript number to Uint8Array of length 8
function numberToUintArr(numberVal) {
let arr = new Uint8Array(8);
for (let idx = 7; idx >= 0; idx--) {
let n = 8 - (idx + 1);
const arr = new Uint8Array(8);
let n;
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
arr[idx] = (numberVal / 256**n) % 256;
}
@ -32,12 +36,14 @@ function numberToUintArr(numberVal) {
}
// Return nonce that hashes together with payload lower than the target
function calcPoW(timestamp, ttl, pub_key, data) {
const leadingString = timestamp.toString() + ttl.toString() + pub_key;
function calcPoW(timestamp, ttl, pubKey, data) {
const leadingString = timestamp.toString() + ttl.toString() + pubKey;
const leadingArray = new Uint8Array(bb.wrap(leadingString, 'binary').toArrayBuffer());
// Payload constructed from concatenating timestamp, ttl and pubkey strings, converting to Uint8Array
// and then appending to the message data array
const payload = leadingArray + data;
// Payload constructed from concatenating timestamp, ttl and pubkey strings,
// converting to Uint8Array and then appending to the message data array
const payload = new Uint8Array(leadingArray.length + data.length);
payload.set(leadingArray);
payload.set(data, leadingArray.length);
const nonceLen = 8;
// Modify this value for difficulty scaling
// 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 trialValue = numberToUintArr(Number.MAX_SAFE_INTEGER);
// 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 * (
payload.length + nonceLen + (
(ttl * ( payload.length + nonceLen ))
/ Math.pow(2, 16)
(ttl * ( payload.length + nonceLen )) /
2**16
)
)
)));
));
const target = numberToUintArr(targetNum);
const initialHash = new Uint8Array(bb.wrap(hash(payload), 'hex').toArrayBuffer());
while (trialValue > target) {
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
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