diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000..afa0b5084 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,10 @@ +tutorials +docs +coverage +demos +.circleci +.github +.travis.yml +*.html +*.md +/dist \ No newline at end of file diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 000000000..f967ca00c --- /dev/null +++ b/.prettierrc @@ -0,0 +1,6 @@ +{ + "printWidth": 200, + "singleQuote": true, + "trailingComma": "none", + "tabWidth": 2 +} diff --git a/lib/client/api.js b/lib/client/api.js index 59d9a58d6..885a4066a 100644 --- a/lib/client/api.js +++ b/lib/client/api.js @@ -7,7 +7,6 @@ var synchronization = require('./api/synchronization.js'); var protocols = require('./api/protocols.js'); var bitsProtocols = require('./api/bits.js'); - module.exports = function (jiffClient) { initialization(jiffClient); sharing(jiffClient); @@ -17,4 +16,4 @@ module.exports = function (jiffClient) { protocols(jiffClient); bitsProtocols(jiffClient); -}; \ No newline at end of file +}; diff --git a/lib/client/api/bits.js b/lib/client/api/bits.js index f8e33c286..698610aa5 100644 --- a/lib/client/api/bits.js +++ b/lib/client/api/bits.js @@ -387,4 +387,4 @@ module.exports = function (jiffClient) { * @returns {promise} a (JQuery) promise to the open value of the secret */ jiffClient.protocols.bits.receive_open = sharing.receive_open_bits.bind(null, jiffClient); -}; \ No newline at end of file +}; diff --git a/lib/client/api/crypto_provider.js b/lib/client/api/crypto_provider.js index a7e52310c..9fcd9ca11 100644 --- a/lib/client/api/crypto_provider.js +++ b/lib/client/api/crypto_provider.js @@ -41,7 +41,7 @@ module.exports = function (jiffClient) { } // Send a request to the server - var msg = {label: label, op_id: op_id, receivers: receivers_list, threshold: threshold, Zp: Zp, params: params}; + var msg = { label: label, op_id: op_id, receivers: receivers_list, threshold: threshold, Zp: Zp, params: params }; msg = jiffClient.hooks.execute_array_hooks('beforeOperation', [jiffClient, 'crypto_provider', msg], 2); msg = JSON.stringify(msg); @@ -53,4 +53,4 @@ module.exports = function (jiffClient) { jiffClient.socket.safe_emit('crypto_provider', msg); return result; }; -}; \ No newline at end of file +}; diff --git a/lib/client/api/custom.js b/lib/client/api/custom.js index 4d9f7907a..504b29ec1 100644 --- a/lib/client/api/custom.js +++ b/lib/client/api/custom.js @@ -10,7 +10,7 @@ module.exports = function (jiffClient) { * @param {boolean} [encrypt=true] - if true, messages will be encrypted */ jiffClient.emit = function (tag, receivers, message, encrypt) { - if (typeof(message) !== 'string') { + if (typeof message !== 'string') { throw new Error('Emit: message must be a string'); } @@ -27,7 +27,7 @@ module.exports = function (jiffClient) { continue; } - var message_to_send = {tag: tag, party_id: receivers[p], message: message, encrypted: encrypt}; + var message_to_send = { tag: tag, party_id: receivers[p], message: message, encrypted: encrypt }; message_to_send = jiffClient.hooks.execute_array_hooks('beforeOperation', [jiffClient, 'custom', message_to_send], 2); if (message_to_send['encrypted'] !== false) { @@ -40,7 +40,7 @@ module.exports = function (jiffClient) { // receive our own message if specified if (receivers.indexOf(jiffClient.id) > -1) { - jiffClient.handlers.receive_custom({tag: tag, party_id: jiffClient.id, message: message, encrypted: false}); + jiffClient.handlers.receive_custom({ tag: tag, party_id: jiffClient.id, message: message, encrypted: false }); } }; @@ -80,4 +80,4 @@ module.exports = function (jiffClient) { jiffClient.remove_listener = function (tag) { delete jiffClient.listeners[tag]; }; -}; \ No newline at end of file +}; diff --git a/lib/client/api/initialization.js b/lib/client/api/initialization.js index b040d9d60..b3246acc7 100644 --- a/lib/client/api/initialization.js +++ b/lib/client/api/initialization.js @@ -21,7 +21,7 @@ module.exports = function (jiffClient) { wait_for_initialization = true; } - jiffClient.wait_callbacks.push({parties: parties, callback: callback, initialization: wait_for_initialization}); + jiffClient.wait_callbacks.push({ parties: parties, callback: callback, initialization: wait_for_initialization }); jiffClient.execute_wait_callbacks(); // See if the callback can be executed immediately }; @@ -65,4 +65,4 @@ module.exports = function (jiffClient) { var msg = jiffClient.hooks.execute_array_hooks('beforeOperation', [jiffClient, 'free', {}], 2); jiffClient.socket.safe_emit('free', JSON.stringify(msg)); }; -}; \ No newline at end of file +}; diff --git a/lib/client/api/protocols.js b/lib/client/api/protocols.js index 734b1aaa9..c7850b5d8 100644 --- a/lib/client/api/protocols.js +++ b/lib/client/api/protocols.js @@ -167,4 +167,4 @@ module.exports = function (jiffClient) { * - The promise is consumed and a new promise is returned by .preprocessing that is resolved after this returned promise (and all other promise generated by that .preprocessing call) are resolved */ jiffClient.protocols.rejection_sampling = sampling.bind(null, jiffClient); -}; \ No newline at end of file +}; diff --git a/lib/client/api/sharing.js b/lib/client/api/sharing.js index 614dd982c..6e12893dc 100644 --- a/lib/client/api/sharing.js +++ b/lib/client/api/sharing.js @@ -39,11 +39,11 @@ module.exports = function (jiffClient) { jiffClient.share = function (secret, threshold, receivers_list, senders_list, Zp, share_id) { // type check to confirm the secret to be shared is a number // for fixed-point extension it should allow non-ints - if (secret != null && (typeof(secret) !== 'number' || Math.floor(secret) !== secret || secret < 0)) { - throw new Error('secret \'' + secret + '\' must be a non-negative whole number'); + if (secret != null && (typeof secret !== 'number' || Math.floor(secret) !== secret || secret < 0)) { + throw new Error("secret '" + secret + "' must be a non-negative whole number"); } - if (secret != null && (secret >= (Zp == null ? jiffClient.Zp : Zp))) { - throw new Error('secret \'' + secret + '\' must fit inside Zp'); + if (secret != null && secret >= (Zp == null ? jiffClient.Zp : Zp)) { + throw new Error("secret '" + secret + "' must fit inside Zp"); } return jiffClient.internal_share(secret, threshold, receivers_list, senders_list, Zp, share_id); }; diff --git a/lib/client/api/synchronization.js b/lib/client/api/synchronization.js index 346616f42..8e19bd335 100644 --- a/lib/client/api/synchronization.js +++ b/lib/client/api/synchronization.js @@ -14,7 +14,7 @@ module.exports = function (jiffClient) { */ jiffClient.start_barrier = function () { openBarriers++; - currentBarrierId = (currentBarrierId + 1 % maxBarrierId); + currentBarrierId = currentBarrierId + (1 % maxBarrierId); jiffClient.barriers[currentBarrierId] = []; return currentBarrierId; }; @@ -59,4 +59,4 @@ module.exports = function (jiffClient) { delete jiffClient.barriers[barrier_id]; return promise; }; -}; \ No newline at end of file +}; diff --git a/lib/client/arch/counters.js b/lib/client/arch/counters.js index c27bd60d8..8de7e76c8 100644 --- a/lib/client/arch/counters.js +++ b/lib/client/arch/counters.js @@ -1,6 +1,5 @@ // Manages op_id counters and generation module.exports = function (jiffClient) { - /** * Resets all the counters for op_ids * @method counters.reset @@ -59,7 +58,7 @@ module.exports = function (jiffClient) { if (jiffClient.counters.op_count[label] == null) { jiffClient.counters.op_count[label] = 0; } - return label + ':' + (jiffClient.counters.op_count[label]++); + return label + ':' + jiffClient.counters.op_count[label]++; }; /** @@ -80,7 +79,7 @@ module.exports = function (jiffClient) { if (jiffClient.counters.op_count[label] == null) { jiffClient.counters.op_count[label] = 0; } - return label + ':' + (jiffClient.counters.op_count[label]++); + return label + ':' + jiffClient.counters.op_count[label]++; }; /** @@ -99,7 +98,7 @@ module.exports = function (jiffClient) { if (jiffClient.counters.op_count_preprocessing[label] == null) { jiffClient.counters.op_count_preprocessing[label] = 0; } - return label + ':' + (jiffClient.counters.op_count_preprocessing[label]++); + return label + ':' + jiffClient.counters.op_count_preprocessing[label]++; }; /** @@ -120,6 +119,6 @@ module.exports = function (jiffClient) { if (jiffClient.counters.op_count_preprocessing[label] == null) { jiffClient.counters.op_count_preprocessing[label] = 0; } - return label + ':' + (jiffClient.counters.op_count_preprocessing[label]++); + return label + ':' + jiffClient.counters.op_count_preprocessing[label]++; }; -}; \ No newline at end of file +}; diff --git a/lib/client/arch/extensions.js b/lib/client/arch/extensions.js index 8b5d524c2..628f76e20 100644 --- a/lib/client/arch/extensions.js +++ b/lib/client/arch/extensions.js @@ -62,4 +62,4 @@ module.exports = function (JIFFClient) { * @param {object} [options={}] - the options passed by the user to the newly applied extension. */ JIFFClient.prototype.extension_applied = function (name, options) {}; -}; \ No newline at end of file +}; diff --git a/lib/client/arch/hooks.js b/lib/client/arch/hooks.js index 1ff616865..e8347e7c6 100644 --- a/lib/client/arch/hooks.js +++ b/lib/client/arch/hooks.js @@ -16,7 +16,7 @@ function Hooks(jiffClient) { // avoid sharing aliases to the same array for (hook in Hooks.prototype) { - if (Hooks.prototype.hasOwnProperty(hook) && typeof(Hooks.prototype[hook].length) === 'number' && Hooks.prototype[hook].slice) { + if (Hooks.prototype.hasOwnProperty(hook) && typeof Hooks.prototype[hook].length === 'number' && Hooks.prototype[hook].slice) { this[hook] = Hooks.prototype[hook].slice(); } } @@ -65,9 +65,9 @@ Hooks.prototype.decryptSign = function (jiffClient, cipher) { Hooks.prototype.generateKeyPair = function (jiffClient) { if (jiffClient.sodium_ !== false) { var key = jiffClient.sodium_.crypto_box_keypair(); // this party's public and secret key - return { public_key: key.publicKey, secret_key: key.privateKey } + return { public_key: key.publicKey, secret_key: key.privateKey }; } else { - return { public_key: '', secret_key: ''}; + return { public_key: '', secret_key: '' }; } }; @@ -122,7 +122,7 @@ Hooks.prototype.afterOperation = [ */ Hooks.prototype.execute_array_hooks = function (hook_name, params, acc_index) { var arr = this.jiffClient.hooks[hook_name]; - arr = (arr == null ? [] : arr); + arr = arr == null ? [] : arr; for (var i = 0; i < arr.length; i++) { params[acc_index] = arr[i].apply(this.jiffClient, params); @@ -130,4 +130,4 @@ Hooks.prototype.execute_array_hooks = function (hook_name, params, acc_index) { return params[acc_index]; }; -module.exports = Hooks; \ No newline at end of file +module.exports = Hooks; diff --git a/lib/client/handlers.js b/lib/client/handlers.js index 7ec85d720..694f8923a 100644 --- a/lib/client/handlers.js +++ b/lib/client/handlers.js @@ -17,4 +17,4 @@ module.exports = function (jiffClient) { shareHandlers(jiffClient); customHandlers(jiffClient); cryptoProviderHandlers(jiffClient); -}; \ No newline at end of file +}; diff --git a/lib/client/handlers/crypto_provider.js b/lib/client/handlers/crypto_provider.js index 0d30ec648..a5bc95be1 100644 --- a/lib/client/handlers/crypto_provider.js +++ b/lib/client/handlers/crypto_provider.js @@ -36,4 +36,4 @@ module.exports = function (jiffClient) { jiffClient.deferreds[op_id].resolve(result); delete jiffClient.deferreds[op_id]; }; -}; \ No newline at end of file +}; diff --git a/lib/client/handlers/custom.js b/lib/client/handlers/custom.js index c256318be..3a31ca2d9 100644 --- a/lib/client/handlers/custom.js +++ b/lib/client/handlers/custom.js @@ -30,7 +30,7 @@ module.exports = function (jiffClient) { jiffClient.custom_messages_mailbox[tag] = stored_messages; } - stored_messages.push({sender_id: sender_id, message: message}); + stored_messages.push({ sender_id: sender_id, message: message }); } - } -}; \ No newline at end of file + }; +}; diff --git a/lib/client/handlers/initialization.js b/lib/client/handlers/initialization.js index caff2b6db..7bf661402 100644 --- a/lib/client/handlers/initialization.js +++ b/lib/client/handlers/initialization.js @@ -131,4 +131,4 @@ module.exports = function (jiffClient) { } } }; -}; \ No newline at end of file +}; diff --git a/lib/client/handlers/sharing.js b/lib/client/handlers/sharing.js index d3a3f6bd5..3731263ce 100644 --- a/lib/client/handlers/sharing.js +++ b/lib/client/handlers/sharing.js @@ -62,7 +62,7 @@ module.exports = function (jiffClient) { } // Accumulate received shares - jiffClient.deferreds[op_id].shares.push({value: share, sender_id: sender_id, Zp: Zp}); + jiffClient.deferreds[op_id].shares.push({ value: share, sender_id: sender_id, Zp: Zp }); // Resolve when ready if (jiffClient.deferreds[op_id].shares.length === jiffClient.deferreds[op_id].threshold) { @@ -73,5 +73,5 @@ module.exports = function (jiffClient) { if (jiffClient.deferreds[op_id] != null && jiffClient.deferreds[op_id].deferred === 'CLEAN' && jiffClient.deferreds[op_id].shares.length === jiffClient.deferreds[op_id].total) { delete jiffClient.deferreds[op_id]; } - } -}; \ No newline at end of file + }; +}; diff --git a/lib/client/preprocessing/api.js b/lib/client/preprocessing/api.js index 7d11af9eb..f575b9b65 100644 --- a/lib/client/preprocessing/api.js +++ b/lib/client/preprocessing/api.js @@ -129,16 +129,16 @@ module.exports = function (jiffClient) { // Create preprocessing tasks var task = { - dependent_op : dependent_op, - count : count, - threshold : threshold, - receivers_list : receivers_list, - compute_list : compute_list, - Zp : Zp, - id_list : id_list, - id : null, - params : params, - protocols : protocols, + dependent_op: dependent_op, + count: count, + threshold: threshold, + receivers_list: receivers_list, + compute_list: compute_list, + Zp: Zp, + id_list: id_list, + id: null, + params: params, + protocols: protocols, deferred: new jiffClient.helpers.Deferred() }; diff --git a/lib/client/preprocessing/daemon.js b/lib/client/preprocessing/daemon.js index 25c4599c9..d823202b0 100644 --- a/lib/client/preprocessing/daemon.js +++ b/lib/client/preprocessing/daemon.js @@ -38,7 +38,8 @@ module.exports = function (jiffClient) { var buildID = function (task) { // Two kinds of operations: one that relies on different sets of senders and receivers, and one that has a set of holders - if (task.dependent_op === 'open' || task.dependent_op === 'bits.open') { // TODO: make this part of the description in table + if (task.dependent_op === 'open' || task.dependent_op === 'bits.open') { + // TODO: make this part of the description in table var open_parties = task.params['open_parties'] != null ? task.params['open_parties'] : task.receivers_list; task.id = jiffClient.counters.gen_op_id2_preprocessing(task.dependent_op, open_parties, task.receivers_list); } else { @@ -49,7 +50,7 @@ module.exports = function (jiffClient) { var taskIsExecutable = function (task) { // if the protocol name is in the map, it can be directly executed var namespace = find_closest_namespace(task.dependent_op, task.params['namespace']); - return (namespace == null); + return namespace == null; }; var find_closest_namespace = function (op, starting_namespace) { @@ -104,8 +105,20 @@ module.exports = function (jiffClient) { var namespace = find_closest_namespace(task.dependent_op, _params['namespace']); var preprocessing_dependencies = jiffClient.preprocessing_function_map[namespace][task.dependent_op]; - if (typeof(preprocessing_dependencies) === 'function') { - preprocessing_dependencies = preprocessing_dependencies(task.dependent_op, task.count, task.protocols, task.threshold, task.receivers_list, task.compute_list, task.Zp, task.id, _params, task, jiffClient); + if (typeof preprocessing_dependencies === 'function') { + preprocessing_dependencies = preprocessing_dependencies( + task.dependent_op, + task.count, + task.protocols, + task.threshold, + task.receivers_list, + task.compute_list, + task.Zp, + task.id, + _params, + task, + jiffClient + ); } var newTasks = linkedList(); @@ -133,25 +146,25 @@ module.exports = function (jiffClient) { if (next_count == null) { next_count = 1; - next_id_list[0] = dependency['absolute_op_id'] || (task.id + dependency['op_id']); + next_id_list[0] = dependency['absolute_op_id'] || task.id + dependency['op_id']; } else { next_count = next_count(task.threshold, task.receivers_list, task.compute_list, task.Zp, task.id, extra_params); for (var j = 0; j < next_count; j++) { - next_id_list.push(dependency['absolute_op_id'] || (task.id + dependency['op_id'] + j)); + next_id_list.push(dependency['absolute_op_id'] || task.id + dependency['op_id'] + j); } } var nextTask = { - dependent_op : next_op, - count : next_count, - threshold : dependency['threshold'] || task.threshold, - receivers_list : dependency['receivers_list'] || task.receivers_list, - compute_list : dependency['compute_list'] || task.compute_list, - Zp : dependency['Zp'] || task.Zp, - id_list : next_id_list, - id : null, - params : extra_params, - protocols : task.protocols, + dependent_op: next_op, + count: next_count, + threshold: dependency['threshold'] || task.threshold, + receivers_list: dependency['receivers_list'] || task.receivers_list, + compute_list: dependency['compute_list'] || task.compute_list, + Zp: dependency['Zp'] || task.Zp, + id_list: next_id_list, + id: null, + params: extra_params, + protocols: task.protocols, deferred: new jiffClient.helpers.Deferred() }; @@ -161,16 +174,26 @@ module.exports = function (jiffClient) { var required_ops = []; for (var r = 0; r < dependency.requires.length; r++) { if (dependency.requires[r] >= k) { - throw new Error('Preprocessing dependency "' + next_op + '" in preprocessingMap for "' + task.dependent_op - + '" at namespace "' + namespace + '" cannot require subsequent dependency ' + dependency.requires[r]); + throw new Error( + 'Preprocessing dependency "' + + next_op + + '" in preprocessingMap for "' + + task.dependent_op + + '" at namespace "' + + namespace + + '" cannot require subsequent dependency ' + + dependency.requires[r] + ); } required_ops.push(deferredChain[dependency.requires[r]]); } - Promise.all(required_ops).then(function (nextTask) { - delete nextTask['wait']; - jiffClient.preprocessingDaemon(); - }.bind(null, nextTask)); + Promise.all(required_ops).then( + function (nextTask) { + delete nextTask['wait']; + jiffClient.preprocessingDaemon(); + }.bind(null, nextTask) + ); // add waiting task to the tail of the queue // jiffClient.currentPreprocessingTasks.add(nextTask); diff --git a/lib/client/preprocessing/handlers.js b/lib/client/preprocessing/handlers.js index 6c95861e0..3bcf1f90b 100644 --- a/lib/client/preprocessing/handlers.js +++ b/lib/client/preprocessing/handlers.js @@ -24,8 +24,8 @@ module.exports = { // for every bit from constant, pre-process for one bits.sadd of the right size var ops = []; for (var i = 0; i < constantBits; i++) { - var accLength = i === 0 ? 1 : (bitLength + i); - ops.push({ op: 'bits.sadd', op_id: ':bits.sadd:' + i, params: {bitLengthLeft: accLength, bitLengthRight: bitLength + i}}); + var accLength = i === 0 ? 1 : bitLength + i; + ops.push({ op: 'bits.sadd', op_id: ':bits.sadd:' + i, params: { bitLengthLeft: accLength, bitLengthRight: bitLength + i } }); } return ops; }, @@ -47,8 +47,8 @@ module.exports = { for (var j = 0; j < max + i; j++) { ops.push({ op: 'if_else', op_id: ':if_else:' + i + ':' + j }); } - var accLength = i === 0 ? min : (max + i); - ops.push({ op: 'bits.sadd', op_id: ':bits.sadd:'+i, params: {bitLengthLeft: accLength, bitLengthRight: max + i}}); + var accLength = i === 0 ? min : max + i; + ops.push({ op: 'bits.sadd', op_id: ':bits.sadd:' + i, params: { bitLengthLeft: accLength, bitLengthRight: max + i } }); } return ops; }, @@ -87,8 +87,8 @@ module.exports = { var ops = []; for (var i = 0; i < left; i++) { - var accLength = Math.min(i+1, min+1); - ops.push({ op: 'bits.ssub', op_id: ':bits.ssub:'+i, params: {bitLengthLeft: accLength, bitLengthRight: right}}); + var accLength = Math.min(i + 1, min + 1); + ops.push({ op: 'bits.ssub', op_id: ':bits.ssub:' + i, params: { bitLengthLeft: accLength, bitLengthRight: right } }); for (var j = 0; j < accLength; j++) { ops.push({ op: 'if_else', op_id: ':if_else:' + i + ':' + j }); } @@ -108,29 +108,29 @@ module.exports = { var min = Math.min(bitLength, constantBits); var ops = []; - var loopCounter = (dir === 'left') ? bitLength : constantBits; + var loopCounter = dir === 'left' ? bitLength : constantBits; for (var i = 0; i < loopCounter; i++) { var accLength = Math.min(i + 1, min + 1); if (dir === 'left') { ops.push({ op: 'bits.csubl', op_id: ':bits.csubl:' + i, - params: {bitLength: accLength, constantBits: constantBits} + params: { bitLength: accLength, constantBits: constantBits } }); } else { ops.push({ op: 'bits.ssub', op_id: ':bits.ssub:' + i, - params: {bitLengthLeft: accLength, bitLengthRight: bitLength} + params: { bitLengthLeft: accLength, bitLengthRight: bitLength } }); } for (var j = 0; j < accLength; j++) { - ops.push({op: 'if_else', op_id: ':if_else:' + i + ':' + j}); + ops.push({ op: 'if_else', op_id: ':if_else:' + i + ':' + j }); } } return ops; - } + }; }, // rejection sampling dynamic_rejection_sampling: function (dependent_op, count, protocols, threshold, receivers_list, compute_list, Zp, task_id, params, task, jiff) { @@ -139,16 +139,17 @@ module.exports = { if (previousPreprocessing == null || previousPreprocessing === 'RETRY' || (previousPreprocessing[0] != null && previousPreprocessing[0].value === 'RETRY')) { if (!params.defaultBounds && (params.lower_bound == null || params.upper_bound == null)) { - jiff.store_preprocessing(task.id, {ondemand: true}); + jiff.store_preprocessing(task.id, { ondemand: true }); return []; } var compute_threshold = params.compute_threshold; - if (compute_threshold == null) { // honest majority BGW + if (compute_threshold == null) { + // honest majority BGW compute_threshold = Math.floor((compute_list.length + 1) / 2); } - var extra_params = {compute_threshold: compute_threshold}; + var extra_params = { compute_threshold: compute_threshold }; var reject_count = ++params.reject_count; Zp = Zp != null ? Zp : jiff.Zp; @@ -167,7 +168,7 @@ module.exports = { throw new Error('rejection sampling preprocessing called with range 0, no numbers to sample!'); } if (range.toString() === '1') { - return [{op: 'sampling', op_id: '', params: extra_params}]; + return [{ op: 'sampling', op_id: '', params: extra_params }]; } var bitLength = jiff.helpers.ceil(jiff.helpers.bLog(range, 2)); @@ -179,21 +180,18 @@ module.exports = { var requires = []; if (jiff.helpers.bLog(range, 2).toString().indexOf('.') > -1) { dependent_ops = [ - {op: 'bits.clt', op_id: ':bits.clt:' + reject_count, params: extra_params, threshold: compute_threshold, receivers_list: compute_list}, - {op: 'open', op_id: ':open:' + reject_count, params: extra_params, threshold: compute_threshold, receivers_list: compute_list} + { op: 'bits.clt', op_id: ':bits.clt:' + reject_count, params: extra_params, threshold: compute_threshold, receivers_list: compute_list }, + { op: 'open', op_id: ':open:' + reject_count, params: extra_params, threshold: compute_threshold, receivers_list: compute_list } ]; requires = [0, 1]; } if (params.lower_bound.toString() !== '0' && bitLength > 1) { - dependent_ops.push({op: 'bits.cadd', op_id: ':bits.cadd:' + reject_count, params: extra_params, threshold: compute_threshold, receivers_list: compute_list}); + dependent_ops.push({ op: 'bits.cadd', op_id: ':bits.cadd:' + reject_count, params: extra_params, threshold: compute_threshold, receivers_list: compute_list }); requires.push(dependent_ops.length - 1); } - dependent_ops.push( - {op: 'sampling', op_id: '', requires: requires, params: extra_params}, - {op: 'rejection_sampling', op_id: '', requires: [dependent_ops.length]} - ); + dependent_ops.push({ op: 'sampling', op_id: '', requires: requires, params: extra_params }, { op: 'rejection_sampling', op_id: '', requires: [dependent_ops.length] }); return dependent_ops; } @@ -206,25 +204,26 @@ module.exports = { }, // random quotients for cdiv dynamic_random_and_quotient: function (dependent_op, count, protocols, threshold, receivers_list, compute_list, Zp, task_id, params, task, jiff) { - var constantNotProvided = (params.constant == null); + var constantNotProvided = params.constant == null; receivers_list = constantNotProvided ? compute_list : receivers_list; Zp = Zp ? Zp : jiff.Zp; - var newParams = {compute_threshold: params.compute_threshold}; - if (params.compute_threshold == null) { // honest majority BGW + var newParams = { compute_threshold: params.compute_threshold }; + if (params.compute_threshold == null) { + // honest majority BGW newParams.compute_threshold = Math.floor((compute_list.length + 1) / 2); } threshold = newParams.compute_threshold; var dependent_ops = [ - {op: 'bits.cgteq', op_id: ':bits_cgteq', receivers_list: receivers_list, threshold: threshold, params: newParams}, - {op: 'if_else', op_id: ':ifelse1', receivers_list: receivers_list, threshold: threshold, params: newParams}, - {op: 'if_else', op_id: ':ifelse2', receivers_list: receivers_list, threshold: threshold, params: newParams}, - {op: 'rejection_sampling', op_id: ':rejection1', receivers_list: receivers_list, threshold: threshold, params: {lower_bound: 0, upper_bound: Zp, compute_threshold: threshold}} + { op: 'bits.cgteq', op_id: ':bits_cgteq', receivers_list: receivers_list, threshold: threshold, params: newParams }, + { op: 'if_else', op_id: ':ifelse1', receivers_list: receivers_list, threshold: threshold, params: newParams }, + { op: 'if_else', op_id: ':ifelse2', receivers_list: receivers_list, threshold: threshold, params: newParams }, + { op: 'rejection_sampling', op_id: ':rejection1', receivers_list: receivers_list, threshold: threshold, params: { lower_bound: 0, upper_bound: Zp, compute_threshold: threshold } } ]; if (constantNotProvided) { - jiff.store_preprocessing(task_id, {ondemand: true}); + jiff.store_preprocessing(task_id, { ondemand: true }); return dependent_ops; } @@ -232,9 +231,9 @@ module.exports = { var largestQuotient = jiff.share_helpers['floor'](jiff.share_helpers['/'](Zp, params.constant)); dependent_ops.push( - {op: 'rejection_sampling', op_id: ':rejection2', threshold: threshold, params: {lower_bound: 0, upper_bound: largestQuotient, compute_threshold: threshold}}, - {op: 'rejection_sampling', op_id: ':rejection3', threshold: threshold, params: {lower_bound: 0, upper_bound: params.constant, compute_threshold: threshold}}, - {op: 'generate_random_and_quotient', op_id: '', requires: [0, 1, 2, 3, 4, 5], params: newParams} + { op: 'rejection_sampling', op_id: ':rejection2', threshold: threshold, params: { lower_bound: 0, upper_bound: largestQuotient, compute_threshold: threshold } }, + { op: 'rejection_sampling', op_id: ':rejection3', threshold: threshold, params: { lower_bound: 0, upper_bound: params.constant, compute_threshold: threshold } }, + { op: 'generate_random_and_quotient', op_id: '', requires: [0, 1, 2, 3, 4, 5], params: newParams } ); return dependent_ops; @@ -253,11 +252,11 @@ module.exports = { var ops = []; if (constantNotProvided) { - for (var i = 0; i < constantBits-1; i++) { - ops.push({op: 'smult', op_id: ':smult0:' + i}); - ops.push({op: 'smult', op_id: ':smult1:' + i}); + for (var i = 0; i < constantBits - 1; i++) { + ops.push({ op: 'smult', op_id: ':smult0:' + i }); + ops.push({ op: 'smult', op_id: ':smult1:' + i }); } - ops.push({op: 'smult', op_id: ':smult0:' + i}); + ops.push({ op: 'smult', op_id: ':smult0:' + i }); return ops; } @@ -268,13 +267,13 @@ module.exports = { // preprocess for exactly the needed amount of multiplications for (i = 0; jiff.share_helpers['<'](1, constant); i++) { - ops.push({op: 'smult', op_id: ':smult0:' + i}); + ops.push({ op: 'smult', op_id: ':smult0:' + i }); if (!jiff.share_helpers['even'](constant)) { - ops.push({op: 'smult', op_id: ':smult1:' + i}); + ops.push({ op: 'smult', op_id: ':smult1:' + i }); } constant = jiff.share_helpers['floor'](jiff.share_helpers['/'](constant, 2)); } - ops.push({op: 'smult', op_id: ':smult0:' + i}); + ops.push({ op: 'smult', op_id: ':smult0:' + i }); return ops; }, // for various equality tests, preprocess of cpow(Zp - 1) (Fermat's little theorem) @@ -283,4 +282,4 @@ module.exports = { params.constant = jiff.share_helpers['-'](Zp, 1); return params; } -}; \ No newline at end of file +}; diff --git a/lib/client/preprocessing/map.js b/lib/client/preprocessing/map.js index dc4513bf5..3a596e3c3 100644 --- a/lib/client/preprocessing/map.js +++ b/lib/client/preprocessing/map.js @@ -14,124 +14,108 @@ module.exports = function (jiffClient) { jiffClient.preprocessing_function_map = { base: { // arithmetic sharing protocols - 'smult': [ - {op: 'open', op_id: ':open1'}, - {op: 'generate_beaver', op_id: ':triplet'}, - {op: 'open', op_id: ':open2'} - ], - 'sxor_bit': [ - {op: 'smult', op_id: ':smult1'} - ], - 'slt': [ - {op: 'lt_halfprime', op_id: ':halfprime:1'}, - {op: 'lt_halfprime', op_id: ':halfprime:2'}, - {op: 'lt_halfprime', op_id: ':halfprime:3'}, - {op: 'smult', op_id: ':smult1'}, - {op: 'smult', op_id: ':smult2'} - ], - 'cgt': [ - {op: 'lt_halfprime', op_id: ':halfprime:1'}, - {op: 'lt_halfprime', op_id: ':halfprime:2'}, - {op: 'smult', op_id: ':smult1'} - ], - 'clt': [ - {op: 'lt_halfprime', op_id: ':halfprime:1'}, - {op: 'lt_halfprime', op_id: ':halfprime:2'}, - {op: 'smult', op_id: ':smult1'} - ], - 'lt_halfprime': [ - {op: 'rejection_sampling', op_id: ':sampling', params: {defaultBounds: true}}, - {op: 'smult', op_id: ':smult1'}, - {op: 'bits.cgt', op_id: ':bits.cgt'}, - {op: 'sxor_bit', op_id: ':sxor_bit'}, - {op: 'open', op_id: ':open'} - ], - 'cneq': [ - {op: 'cpow', op_id: ':cpow', handler: handlers.handler_cpow_Zp_minus_1} - ], - 'cpow': handlers.dynamic_fast_exponentiation, - 'cdiv': [ - {op: 'cgt', op_id: ':wrap_cgt'}, - {op: 'cgteq', op_id: ':cor1'}, - {op: 'cgteq', op_id: ':cor2'}, - {op: 'smult', op_id: ':smult'}, - {op: 'clt', op_id: ':zero_check'}, - {op: 'smult', op_id: ':zero_it'}, - {op: 'open', op_id: ':open'}, - {op: 'quotient', op_id: ':quotient'} - ], - 'sdiv': [ - {op: 'bit_decomposition', op_id: ':decomposition1'}, - {op: 'bit_decomposition', op_id: ':decomposition2'}, - {op: 'bits.sdiv', op_id: ':bits.sdiv'} - ], - 'if_else': [ - {op: 'smult', op_id: ':smult'} - ], + smult: [ + { op: 'open', op_id: ':open1' }, + { op: 'generate_beaver', op_id: ':triplet' }, + { op: 'open', op_id: ':open2' } + ], + sxor_bit: [{ op: 'smult', op_id: ':smult1' }], + slt: [ + { op: 'lt_halfprime', op_id: ':halfprime:1' }, + { op: 'lt_halfprime', op_id: ':halfprime:2' }, + { op: 'lt_halfprime', op_id: ':halfprime:3' }, + { op: 'smult', op_id: ':smult1' }, + { op: 'smult', op_id: ':smult2' } + ], + cgt: [ + { op: 'lt_halfprime', op_id: ':halfprime:1' }, + { op: 'lt_halfprime', op_id: ':halfprime:2' }, + { op: 'smult', op_id: ':smult1' } + ], + clt: [ + { op: 'lt_halfprime', op_id: ':halfprime:1' }, + { op: 'lt_halfprime', op_id: ':halfprime:2' }, + { op: 'smult', op_id: ':smult1' } + ], + lt_halfprime: [ + { op: 'rejection_sampling', op_id: ':sampling', params: { defaultBounds: true } }, + { op: 'smult', op_id: ':smult1' }, + { op: 'bits.cgt', op_id: ':bits.cgt' }, + { op: 'sxor_bit', op_id: ':sxor_bit' }, + { op: 'open', op_id: ':open' } + ], + cneq: [{ op: 'cpow', op_id: ':cpow', handler: handlers.handler_cpow_Zp_minus_1 }], + cpow: handlers.dynamic_fast_exponentiation, + cdiv: [ + { op: 'cgt', op_id: ':wrap_cgt' }, + { op: 'cgteq', op_id: ':cor1' }, + { op: 'cgteq', op_id: ':cor2' }, + { op: 'smult', op_id: ':smult' }, + { op: 'clt', op_id: ':zero_check' }, + { op: 'smult', op_id: ':zero_it' }, + { op: 'open', op_id: ':open' }, + { op: 'quotient', op_id: ':quotient' } + ], + sdiv: [ + { op: 'bit_decomposition', op_id: ':decomposition1' }, + { op: 'bit_decomposition', op_id: ':decomposition2' }, + { op: 'bits.sdiv', op_id: ':bits.sdiv' } + ], + if_else: [{ op: 'smult', op_id: ':smult' }], // bits protocols - 'bit_decomposition': [ - {op: 'rejection_sampling', op_id: ':sampling', params: {defaultBounds: true}}, - {op: 'bits.csubr', op_id: ':bits.csubr:1'}, - {op: 'bits.csubr', op_id: ':bits.csubr:2'}, - {op: 'if_else', op_id: ':if_else:', count: handlers.decomposition_ifelse_count}, - {op: 'open', op_id: ':open'} + bit_decomposition: [ + { op: 'rejection_sampling', op_id: ':sampling', params: { defaultBounds: true } }, + { op: 'bits.csubr', op_id: ':bits.csubr:1' }, + { op: 'bits.csubr', op_id: ':bits.csubr:2' }, + { op: 'if_else', op_id: ':if_else:', count: handlers.decomposition_ifelse_count }, + { op: 'open', op_id: ':open' } ], // comparisons - 'bits.cgteq': [ - {op: 'smult', op_id: ':smult:', count: handlers.constant_bits_count} - ], - 'bits.cneq': [ - {op: 'sor_bit', op_id: ':sor_bit:', count: handlers.constant_bits_count} - ], + 'bits.cgteq': [{ op: 'smult', op_id: ':smult:', count: handlers.constant_bits_count }], + 'bits.cneq': [{ op: 'sor_bit', op_id: ':sor_bit:', count: handlers.constant_bits_count }], 'bits.sneq': [ - {op: 'sxor_bit', op_id: ':sxor_bit:initial'}, - {op: 'sxor_bit', op_id: ':sxor_bit:', count: handlers.choice_bits_count(Math.min, -1)}, - {op: 'sor_bit', op_id: ':sor_bit:', count: handlers.choice_bits_count(Math.max, -1)} + { op: 'sxor_bit', op_id: ':sxor_bit:initial' }, + { op: 'sxor_bit', op_id: ':sxor_bit:', count: handlers.choice_bits_count(Math.min, -1) }, + { op: 'sor_bit', op_id: ':sor_bit:', count: handlers.choice_bits_count(Math.max, -1) } ], 'bits.sgteq': [ - {op: 'smult', op_id: ':smult:initial'}, - {op: 'smult', op_id: ':smult1:', count: handlers.choice_bits_count(Math.max, -1)}, - {op: 'sxor_bit', op_id: ':sxor_bit1:', count: handlers.choice_bits_count(Math.min, -1)}, - {op: 'smult', op_id: ':smult2:', count: handlers.choice_bits_count(Math.min, -1)} + { op: 'smult', op_id: ':smult:initial' }, + { op: 'smult', op_id: ':smult1:', count: handlers.choice_bits_count(Math.max, -1) }, + { op: 'sxor_bit', op_id: ':sxor_bit1:', count: handlers.choice_bits_count(Math.min, -1) }, + { op: 'smult', op_id: ':smult2:', count: handlers.choice_bits_count(Math.min, -1) } ], 'bits.sgt': [ - {op: 'bits.sgteq', op_id: ':bits.sgteq'}, - {op: 'bits.sneq', op_id: ':bits.sneq'}, - {op: 'smult', op_id: ':smult'} + { op: 'bits.sgteq', op_id: ':bits.sgteq' }, + { op: 'bits.sneq', op_id: ':bits.sneq' }, + { op: 'smult', op_id: ':smult' } ], // constant arithmetic 'bits.cadd': [ - {op: 'smult', op_id: ':smult:', count: handlers.constant_bits_count}, - {op: 'sxor_bit', op_id: ':sxor_bit:', count: handlers.constant_bits_count} + { op: 'smult', op_id: ':smult:', count: handlers.constant_bits_count }, + { op: 'sxor_bit', op_id: ':sxor_bit:', count: handlers.constant_bits_count } ], 'bits.cmult': handlers.dynamic_bits_cmult, 'bits.cdivl': handlers.dynamic_bits_cdiv('left'), 'bits.cdivr': handlers.dynamic_bits_cdiv('right'), // secret arithmetic 'bits.sadd': [ - {op: 'sxor_bit', op_id: ':sxor_bit:initial'}, - {op: 'smult', op_id: ':smult:initial'}, - {op: 'smult', op_id: ':smult1:', count: handlers.choice_bits_count(Math.max, -1)}, - {op: 'sxor_bit', op_id: ':sxor_bit1:', count: handlers.choice_bits_count(Math.max, -1)}, - {op: 'smult', op_id: ':smult2:', count: handlers.choice_bits_count(Math.min, -1)}, - {op: 'sxor_bit', op_id: ':sxor_bit2:', count: handlers.choice_bits_count(Math.min, -1)} + { op: 'sxor_bit', op_id: ':sxor_bit:initial' }, + { op: 'smult', op_id: ':smult:initial' }, + { op: 'smult', op_id: ':smult1:', count: handlers.choice_bits_count(Math.max, -1) }, + { op: 'sxor_bit', op_id: ':sxor_bit1:', count: handlers.choice_bits_count(Math.max, -1) }, + { op: 'smult', op_id: ':smult2:', count: handlers.choice_bits_count(Math.min, -1) }, + { op: 'sxor_bit', op_id: ':sxor_bit2:', count: handlers.choice_bits_count(Math.min, -1) } ], 'bits.smult': handlers.dynamic_bits_smult, 'bits.sdiv': handlers.dynamic_bits_sdiv, - 'bits.open': [ - {op: 'open', op_id: ':', count: handlers.bits_count} - ], + 'bits.open': [{ op: 'open', op_id: ':', count: handlers.bits_count }], // refresh/open - 'refresh': [ - {op: 'generate_zero', op_id: ''} - ], - 'open': [ - {op: 'refresh', op_id: ':refresh'} - ], + refresh: [{ op: 'generate_zero', op_id: '' }], + open: [{ op: 'refresh', op_id: ':refresh' }], // generating a random number and its quotient / constant - 'quotient': handlers.dynamic_random_and_quotient, + quotient: handlers.dynamic_random_and_quotient, // rejection sampling - 'rejection_sampling': handlers.dynamic_rejection_sampling + rejection_sampling: handlers.dynamic_rejection_sampling } }; diff --git a/lib/client/protocols/arrays/open.js b/lib/client/protocols/arrays/open.js index d5c6e4304..fc4a263b3 100644 --- a/lib/client/protocols/arrays/open.js +++ b/lib/client/protocols/arrays/open.js @@ -2,7 +2,7 @@ const open_array = function (jiff, shares, parties, op_ids) { var i; // A base operation id is provided to use for all opens. - if (typeof(op_ids) === 'string' || typeof(op_ids) === 'number') { + if (typeof op_ids === 'string' || typeof op_ids === 'number') { var tmp = { s1: op_ids }; for (i = 1; i <= jiff.party_count; i++) { tmp[i] = op_ids; @@ -35,9 +35,9 @@ const open_ND_array = function (jiff, shares, receivers_list, senders_list, op_i var final_deferred = new jiff.helpers.Deferred(); var final_promise = final_deferred.promise; var resolve_open = function (shares) { - final_deferred.resolve(( - function __open_ND_array(shares, parties, op_ids) { - if (typeof(shares.length) === 'undefined') { + final_deferred.resolve( + (function __open_ND_array(shares, parties, op_ids) { + if (typeof shares.length === 'undefined') { return jiff.internal_open(shares, parties); } else if (shares.length === 0) { return Promise.resolve([]); @@ -48,14 +48,14 @@ const open_ND_array = function (jiff, shares, receivers_list, senders_list, op_i } return Promise.all(promised_array); } - } - )(shares, receivers_list, op_ids)); + })(shares, receivers_list, op_ids) + ); }; if (is_sending) { // Must emit the skeleton for any parties that are not holders but are receiving the open var skeleton = (function __unwipe(nd_array, replace) { - if (!(typeof (nd_array.length) === 'undefined') || nd_array.length === 0) { + if (!(typeof nd_array.length === 'undefined') || nd_array.length === 0) { var unwiped_array = []; for (var k = 0; k < nd_array.length; k++) { unwiped_array.push(__unwipe(nd_array[k], replace)); @@ -72,7 +72,7 @@ const open_ND_array = function (jiff, shares, receivers_list, senders_list, op_i var revive_shares = function (skeleton) { const share = new jiff.SecretShare({}, senders_list, senders_list.length, jiff.Zp); return (function __unwipe(nd_array, replace) { - if (nd_array != null && !(typeof (nd_array.length) === 'undefined' && nd_array.length > 0)) { + if (nd_array != null && !(typeof nd_array.length === 'undefined' && nd_array.length > 0)) { var unwiped_array = []; for (var k = 0; k < nd_array.length; k++) { unwiped_array.push(__unwipe(nd_array[k], replace)); @@ -81,7 +81,7 @@ const open_ND_array = function (jiff, shares, receivers_list, senders_list, op_i } return replace; })(skeleton, share); - } + }; // If this party is not a sender, then the variable `shares` may be a skeleton if (shares != null) { @@ -90,10 +90,10 @@ const open_ND_array = function (jiff, shares, receivers_list, senders_list, op_i resolve_open(shares); } else { // Receive skeleton from senders - jiff.listen(op_ids + 'skeleton', function (sender, skeleton) { - jiff.remove_listener(op_ids + 'skeleton'); // This doesn't seem to work + jiff.listen(op_ids + 'skeleton', function (sender, skeleton) { + jiff.remove_listener(op_ids + 'skeleton'); // This doesn't seem to work - if (typeof(skeleton) === 'string') { + if (typeof skeleton === 'string') { skeleton = JSON.parse(skeleton); } diff --git a/lib/client/protocols/arrays/share.js b/lib/client/protocols/arrays/share.js index 0711535a9..8b3e882bd 100644 --- a/lib/client/protocols/arrays/share.js +++ b/lib/client/protocols/arrays/share.js @@ -4,7 +4,7 @@ const share_array = function (jiff, array, lengths, threshold, receivers_list, s var skeletons = null; if (lengths != null) { // Check format of lengths - if (lengths != null && typeof(lengths) !== 'number' && typeof(lengths) !== 'object') { + if (lengths != null && typeof lengths !== 'number' && typeof lengths !== 'object') { throw new Error('share_array: unrecognized lengths'); } @@ -18,7 +18,7 @@ const share_array = function (jiff, array, lengths, threshold, receivers_list, s // Generate skeletons from lengths skeletons = {}; - if (typeof(lengths) === 'number') { + if (typeof lengths === 'number') { // All arrays are of the same length var skeleton = []; for (var i = 0; i < lengths; i++) { @@ -49,7 +49,7 @@ const share_2D_array = function (jiff, array, lengths, threshold, receivers_list var i; // Check format of lengths - if (lengths != null && typeof(lengths) !== 'object') { + if (lengths != null && typeof lengths !== 'object') { throw new Error('share_array: unrecognized lengths'); } @@ -103,7 +103,7 @@ const share_2D_array = function (jiff, array, lengths, threshold, receivers_list lengths_deferred.resolve(lengths); } }); - } else if (typeof(lengths.rows) === 'number') { + } else if (typeof lengths.rows === 'number') { // All arrays are of the same length var l = lengths; lengths = {}; @@ -192,13 +192,15 @@ const share_2D_array = function (jiff, array, lengths, threshold, receivers_list }; const share_from_skeleton_unbound = function (jiff, that, sender, skeleton) { - var shares = typeof(skeleton) === 'string' ? JSON.parse(skeleton) : skeleton; + var shares = typeof skeleton === 'string' ? JSON.parse(skeleton) : skeleton; var promise = share_array_single_sender(jiff, shares, that.threshold, that.receivers_list, sender, that.Zp, that.share_id + ':p_id_' + sender); - promise.then(function (sender, array) { - that.deferreds[sender].resolve(array); - }.bind(null, sender)); + promise.then( + function (sender, array) { + that.deferreds[sender].resolve(array); + }.bind(null, sender) + ); }; const share_array_single_sender = function (jiff, secrets, threshold, receivers_list, sender, Zp, share_id) { @@ -236,7 +238,7 @@ const share_ND_array_deferred = function (jiff, secrets, skeletons, threshold, r var isReceiving = receivers_list.indexOf(jiff.id) > -1; var isSending = senders_list.indexOf(jiff.id) > -1; if (!isSending && !isReceiving) { - return null; // This party is neither a sender nor a receiver, do nothing! + return null; // This party is neither a sender nor a receiver, do nothing! } // Setup deferreds: required because we don't yet know how many shares to account for @@ -250,23 +252,26 @@ const share_ND_array_deferred = function (jiff, secrets, skeletons, threshold, r deferreds: final_deferreds, threshold: threshold, receivers_list: receivers_list, - Zp: Zp, share_id: share_id + Zp: Zp, + share_id: share_id }); if (skeletons == null) { - if (isSending) { // Send the shape and lengths of this party's array to all receivers - skeleton = jiff.skeleton_of(secrets); // All secrets are removed while maintaing the array's orginial structure. - var skeleton_str = JSON.stringify(skeleton); // serialize for emit + if (isSending) { + // Send the shape and lengths of this party's array to all receivers + skeleton = jiff.skeleton_of(secrets); // All secrets are removed while maintaing the array's orginial structure. + var skeleton_str = JSON.stringify(skeleton); // serialize for emit jiff.emit(share_id + 'skeleton', receivers_list, skeleton_str); - share_from_skeleton(jiff.id, secrets); // Share the real values matching the emitted skeleton + share_from_skeleton(jiff.id, secrets); // Share the real values matching the emitted skeleton } if (isReceiving) { - jiff.listen(share_id + 'skeleton', share_from_skeleton); // Receive shares when dimensions are known + jiff.listen(share_id + 'skeleton', share_from_skeleton); // Receive shares when dimensions are known } } else { - senders_list = Array.from(senders_list); // remove jiff helpers' internal properties - util.match_skeletons(jiff, skeletons, senders_list); // Saftey check array dimention presets - for (i in senders_list) { // Share each party's array + senders_list = Array.from(senders_list); // remove jiff helpers' internal properties + util.match_skeletons(jiff, skeletons, senders_list); // Saftey check array dimention presets + for (i in senders_list) { + // Share each party's array p_id = senders_list[i]; var myself = p_id === jiff.id; skeleton = skeletons[p_id]; @@ -274,18 +279,19 @@ const share_ND_array_deferred = function (jiff, secrets, skeletons, threshold, r } } - // Combine all promises and re-index final array map var final_deferred = new jiff.helpers.Deferred(); var final_promise = isReceiving ? final_deferred.promise : Promise.resolve({}); - Promise.all((function () { - var all_promises = []; - for (var i = 0; i < senders_list.length; i++) { - var p_id = senders_list[i] - all_promises.push(final_deferreds[p_id].promise); - } - return all_promises; - })()).then(function (array) { + Promise.all( + (function () { + var all_promises = []; + for (var i = 0; i < senders_list.length; i++) { + var p_id = senders_list[i]; + all_promises.push(final_deferreds[p_id].promise); + } + return all_promises; + })() + ).then(function (array) { var shares = {}; for (var i = 0; i < senders_list.length; i++) { var p_id = senders_list[i]; @@ -295,7 +301,7 @@ const share_ND_array_deferred = function (jiff, secrets, skeletons, threshold, r jiff.remove_listener(share_id + 'skeleton'); }); - return final_promise; // Return promise to map of secret-shared arrays + return final_promise; // Return promise to map of secret-shared arrays }; const share_ND_array_static = function (jiff, secrets, skeletons, threshold, receivers_list, senders_list, Zp, share_id) { @@ -324,18 +330,19 @@ const share_ND_array_static = function (jiff, secrets, skeletons, threshold, rec return jiff.share(__secrets, threshold, receivers_list, [sender], Zp, 'share:' + share_id)[sender]; } })(skeleton, share_id + ':p_id_' + sender); - } + }; - senders_list = Array.from(senders_list); // remove jiff helpers' internal properties - util.match_skeletons(jiff, skeletons, senders_list); // Saftey check array dimention presets - for (i in senders_list) { // Share each party's array + senders_list = Array.from(senders_list); // remove jiff helpers' internal properties + util.match_skeletons(jiff, skeletons, senders_list); // Saftey check array dimention presets + for (i in senders_list) { + // Share each party's array var p_id = senders_list[i]; var skeleton = skeletons[p_id]; shares[p_id] = share_from_skeleton(p_id, p_id === jiff.id ? secrets : skeleton); } } - return isReceiving ? shares : {}; // Return promise to map of secret-shared arrays + return isReceiving ? shares : {}; // Return promise to map of secret-shared arrays }; const share_ND_array = function (jiff, secrets, skeletons, threshold, receivers_list, senders_list, Zp, share_id) { diff --git a/lib/client/protocols/arrays/util.js b/lib/client/protocols/arrays/util.js index e68c9f6a6..927ef1a43 100644 --- a/lib/client/protocols/arrays/util.js +++ b/lib/client/protocols/arrays/util.js @@ -6,7 +6,7 @@ const sanitize_array_params = function (jiff, receivers_list, senders_list, thre party_list.push(i); } } - jiff.helpers.sort_ids(party_list); // sort to get the same order + jiff.helpers.sort_ids(party_list); // sort to get the same order return party_list; }); @@ -22,7 +22,8 @@ const sanitize_array_params = function (jiff, receivers_list, senders_list, thre Zp = jiff.Zp; } - if (share_id == null) { // Make a unique id for this array + if (share_id == null) { + // Make a unique id for this array share_id = jiff.counters.gen_op_id2('share_array', receivers_list, senders_list); } @@ -30,10 +31,10 @@ const sanitize_array_params = function (jiff, receivers_list, senders_list, thre }; const skeleton_of = function (jiff, nd_array, replace) { - if (typeof(replace) === 'undefined') { + if (typeof replace === 'undefined') { replace = null; } - if (!(typeof(nd_array.length) === 'undefined') || nd_array.length === 0) { + if (!(typeof nd_array.length === 'undefined') || nd_array.length === 0) { var wiped_array = []; for (var k = 0; k < nd_array.length; k++) { wiped_array.push(jiff.skeleton_of(nd_array[k], replace)); @@ -51,11 +52,11 @@ const match_skeletons = function (jiff, skeletons, senders_list) { if (!(keys[i] === expected_keys[i])) { console.log('senders: ', senders_list); console.log('skeleton keys', keys); - throw new Error('Keys of parameter \'skeletons\' should be the same as the senders'); + throw new Error("Keys of parameter 'skeletons' should be the same as the senders"); } } } else { - throw new Error('Invalid parameter \'skeletons\''); + throw new Error("Invalid parameter 'skeletons'"); } }; diff --git a/lib/client/protocols/bits/arithmetic.js b/lib/client/protocols/bits/arithmetic.js index a831eb42f..73da2f5ac 100644 --- a/lib/client/protocols/bits/arithmetic.js +++ b/lib/client/protocols/bits/arithmetic.js @@ -13,7 +13,7 @@ module.exports = { * in case of potential overflow / carry */ cadd: function (jiff, bits, constant, op_id) { - if (!(bits[0].isConstant(constant))) { + if (!bits[0].isConstant(constant)) { throw new Error('parameter should be a number (bits.cadd)'); } if (op_id == null) { @@ -80,7 +80,7 @@ module.exports = { * and the bit at index |bits| is 1 if the result overflows, or 0 otherwise */ csubl: function (jiff, bits, constant, op_id) { - if (!(bits[0].isConstant(constant))) { + if (!bits[0].isConstant(constant)) { throw new Error('parameter should be a number (bits.csubl)'); } if (op_id == null) { @@ -149,7 +149,7 @@ module.exports = { * and the bit at index |bits| is 1 if the result overflows, or 0 otherwise */ csubr: function (jiff, constant, bits, op_id) { - if (!(bits[0].isConstant(constant))) { + if (!bits[0].isConstant(constant)) { throw new Error('parameter should be a number (bits.csubr)'); } if (op_id == null) { @@ -308,7 +308,8 @@ module.exports = { // xor is equal to the value of bits1[i], andNot is equal to 0, since bits[2] is all zeros here diff = bits1[i].isxor_bit(borrow, op_id + ':sxor_bit1:' + (i - 1)); borrow = bits1[i].inot().ismult(borrow, op_id + ':smult1:' + (i - 1)); - } else { // i < bits2.length + } else { + // i < bits2.length // xor and andNot are equal to the value of bits2[i] diff = bits2[i].isxor_bit(borrow, op_id + ':sxor_bit1:' + (i - 1)); borrow = bits2[i].inot().ismult(borrow, op_id + ':smult1:' + (i - 1)); @@ -335,7 +336,7 @@ module.exports = { * if constant is zero, the result will then be [ zero share ] */ cmult: function (jiff, bits, constant, op_id) { - if (!(bits[0].isConstant(constant))) { + if (!bits[0].isConstant(constant)) { throw new Error('parameter should be a number (bits.cmult)'); } if (op_id == null) { @@ -367,26 +368,34 @@ module.exports = { } // main function - jiff.utils.bit_combinator(final_deferred, 0, constant_bits.length, initial, function (i, intermediate) { - // Shift bits to create the intermediate values, - // and sum if the corresponding bit in a is 1 - if (constant_bits[i].toString() === '1') { - intermediate = jiff.protocols.bits.sadd(intermediate, bits, op_id + ':bits.sadd:' + i); + jiff.utils.bit_combinator( + final_deferred, + 0, + constant_bits.length, + initial, + function (i, intermediate) { + // Shift bits to create the intermediate values, + // and sum if the corresponding bit in a is 1 + if (constant_bits[i].toString() === '1') { + intermediate = jiff.protocols.bits.sadd(intermediate, bits, op_id + ':bits.sadd:' + i); + } + + bits.unshift(zero); + return intermediate; + }, + function (intermediate) { + // promise-ify an array of intermediate results + var promises = []; + for (var i = 0; i < intermediate.length; i++) { + promises.push(intermediate[i].value); + } + return Promise.all(promises); + }, + function (result) { + // identity + return result; } - - bits.unshift(zero); - return intermediate; - }, function (intermediate) { - // promise-ify an array of intermediate results - var promises = []; - for (var i = 0; i < intermediate.length; i++) { - promises.push(intermediate[i].value); - } - return Promise.all(promises); - }, function (result) { - // identity - return result; - }); + ); return result; }, @@ -427,30 +436,38 @@ module.exports = { final_deferred.promise.then(jiff.utils.resolve_many_secrets.bind(null, deferreds)); // Loop over *shortest* array one bit at a time - jiff.utils.bit_combinator(final_deferred, 0, bits2.length, bits2, function (i, intermediate) { - var this_bit = bits2[i]; - var bit_mult = []; // add bits1 or 0 to the result according to this bit - for (var j = 0; j < bits1.length; j++) { - bit_mult[j] = this_bit.iif_else(bits1[j], 0, op_id + ':if_else:' + i + ':' + j); + jiff.utils.bit_combinator( + final_deferred, + 0, + bits2.length, + bits2, + function (i, intermediate) { + var this_bit = bits2[i]; + var bit_mult = []; // add bits1 or 0 to the result according to this bit + for (var j = 0; j < bits1.length; j++) { + bit_mult[j] = this_bit.iif_else(bits1[j], 0, op_id + ':if_else:' + i + ':' + j); + } + bits1.unshift(0); // increase magnitude + + if (i === 0) { + return bit_mult; + } + + return jiff.protocols.bits.sadd(intermediate, bit_mult, op_id + ':bits.sadd:' + i); + }, + function (intermediate) { + // promise-ify an array of intermediate results + var promises = []; + for (var i = 0; i < intermediate.length; i++) { + promises.push(intermediate[i].value); + } + return Promise.all(promises); + }, + function (result) { + // identity + return result; } - bits1.unshift(0); // increase magnitude - - if (i === 0) { - return bit_mult; - } - - return jiff.protocols.bits.sadd(intermediate, bit_mult, op_id + ':bits.sadd:' + i); - }, function (intermediate) { - // promise-ify an array of intermediate results - var promises = []; - for (var i = 0; i < intermediate.length; i++) { - promises.push(intermediate[i].value); - } - return Promise.all(promises); - }, function (result) { - // identity - return result; - }); + ); return result; }, @@ -496,46 +513,54 @@ module.exports = { }); var initial = []; // initial remainder - jiff.utils.bit_combinator(final_deferred, bits1.length - 1, -1, initial, function (i, _remainder) { - var iterationCounter = (bits1.length - i - 1); - - // add bit i to the head of remainder (least significant bit) - _remainder.unshift(bits1[i]); - - // Get the next bit of the quotient - // and conditionally subtract b from the - // intermediate remainder to continue - var sub = jiff.protocols.bits.ssub(_remainder, bits2, op_id + ':bits.ssub:' + iterationCounter); - var noUnderflow = sub.pop().inot(); // get the overflow bit, sub is now the result of subtraction - - // Get next bit of quotient - noUnderflow.wThen(quotientDeferreds[i].resolve); - - // Update remainder - for (var j = 0; j < _remainder.length; j++) { - // note, if noUnderflow, then |# bits in sub| <= |# bits in remainder| - _remainder[j] = noUnderflow.iif_else(sub[j], _remainder[j], op_id + ':if_else:' + iterationCounter + ':' + j); + jiff.utils.bit_combinator( + final_deferred, + bits1.length - 1, + -1, + initial, + function (i, _remainder) { + var iterationCounter = bits1.length - i - 1; + + // add bit i to the head of remainder (least significant bit) + _remainder.unshift(bits1[i]); + + // Get the next bit of the quotient + // and conditionally subtract b from the + // intermediate remainder to continue + var sub = jiff.protocols.bits.ssub(_remainder, bits2, op_id + ':bits.ssub:' + iterationCounter); + var noUnderflow = sub.pop().inot(); // get the overflow bit, sub is now the result of subtraction + + // Get next bit of quotient + noUnderflow.wThen(quotientDeferreds[i].resolve); + + // Update remainder + for (var j = 0; j < _remainder.length; j++) { + // note, if noUnderflow, then |# bits in sub| <= |# bits in remainder| + _remainder[j] = noUnderflow.iif_else(sub[j], _remainder[j], op_id + ':if_else:' + iterationCounter + ':' + j); + } + + // Remainder cannot be greater than divisor at this point + while (_remainder.length > remainder.length) { + _remainder.pop(); + } + + return _remainder; + }, + function (intermediate) { + // promise-ify an array of intermediate results + var promises = []; + for (var i = 0; i < intermediate.length; i++) { + promises.push(intermediate[i].value); + } + return Promise.all(promises); + }, + function (result) { + // identity + return result; } + ); - // Remainder cannot be greater than divisor at this point - while (_remainder.length > remainder.length) { - _remainder.pop(); - } - - return _remainder; - }, function (intermediate) { - // promise-ify an array of intermediate results - var promises = []; - for (var i = 0; i < intermediate.length; i++) { - promises.push(intermediate[i].value); - } - return Promise.all(promises); - }, function (result) { - // identity - return result; - }); - - return {quotient: quotient, remainder: remainder} + return { quotient: quotient, remainder: remainder }; }, /** * Computes integer division of [secret bits] / constant @@ -554,7 +579,7 @@ module.exports = { * @throws if constant is 0. */ cdivl: function (jiff, bits, constant, op_id) { - if (!(bits[0].isConstant(constant))) { + if (!bits[0].isConstant(constant)) { throw new Error('parameter should be a number (bits.cdivl)'); } if (op_id == null) { @@ -573,7 +598,7 @@ module.exports = { return { quotient: bits, remainder: [new jiff.SecretShare(0, bits[0].holders, bits[0].threshold, bits[0].Zp)] - } + }; } // Initialize the result @@ -592,46 +617,54 @@ module.exports = { final_deferred.promise.then(jiff.utils.resolve_many_secrets.bind(null, remainderDeferreds)); var initial = []; // initial remainder - jiff.utils.bit_combinator(final_deferred, bits.length - 1, -1, initial, function (i, _remainder) { - var iterationCounter = (bits.length - i - 1); - - // add bit i to the head of remainder (least significant bit) - _remainder.unshift(bits[i]); - - // Get the next bit of the quotient - // and conditionally subtract b from the - // intermediate remainder to continue - var sub = jiff.protocols.bits.csubl(_remainder, constant, op_id + ':bits.csubl:' + iterationCounter); - var noUnderflow = sub.pop().inot(); // get the overflow bit, sub is now the result of subtraction - - // Get next bit of quotient - noUnderflow.wThen(quotientDeferreds[i].resolve); - - // Update remainder - for (var j = 0; j < _remainder.length; j++) { - // note, if noUnderflow, then |# bits in sub| <= |# bits in remainder| - _remainder[j] = noUnderflow.iif_else(sub[j], _remainder[j], op_id + ':if_else:' + iterationCounter + ':' + j); - } - - // Remainder cannot be greater than constant at this point - while (_remainder.length > remainder.length) { - _remainder.pop(); + jiff.utils.bit_combinator( + final_deferred, + bits.length - 1, + -1, + initial, + function (i, _remainder) { + var iterationCounter = bits.length - i - 1; + + // add bit i to the head of remainder (least significant bit) + _remainder.unshift(bits[i]); + + // Get the next bit of the quotient + // and conditionally subtract b from the + // intermediate remainder to continue + var sub = jiff.protocols.bits.csubl(_remainder, constant, op_id + ':bits.csubl:' + iterationCounter); + var noUnderflow = sub.pop().inot(); // get the overflow bit, sub is now the result of subtraction + + // Get next bit of quotient + noUnderflow.wThen(quotientDeferreds[i].resolve); + + // Update remainder + for (var j = 0; j < _remainder.length; j++) { + // note, if noUnderflow, then |# bits in sub| <= |# bits in remainder| + _remainder[j] = noUnderflow.iif_else(sub[j], _remainder[j], op_id + ':if_else:' + iterationCounter + ':' + j); + } + + // Remainder cannot be greater than constant at this point + while (_remainder.length > remainder.length) { + _remainder.pop(); + } + + return _remainder; + }, + function (intermediate) { + // promise-ify an array of intermediate results + var promises = []; + for (var i = 0; i < intermediate.length; i++) { + promises.push(intermediate[i].value); + } + return Promise.all(promises); + }, + function (result) { + // identity + return result; } + ); - return _remainder; - }, function (intermediate) { - // promise-ify an array of intermediate results - var promises = []; - for (var i = 0; i < intermediate.length; i++) { - promises.push(intermediate[i].value); - } - return Promise.all(promises); - }, function (result) { - // identity - return result; - }); - - return {quotient: quotient, remainder: remainder}; + return { quotient: quotient, remainder: remainder }; }, /** * Computes integer division of constant / [secret bits] @@ -651,7 +684,7 @@ module.exports = { * is equal to constant */ cdivr: function (jiff, constant, bits, op_id) { - if (!(bits[0].isConstant(constant))) { + if (!bits[0].isConstant(constant)) { throw new Error('parameter should be a number (bits.cdivr)'); } if (op_id == null) { @@ -678,47 +711,55 @@ module.exports = { final_deferred.promise.then(jiff.utils.resolve_many_secrets.bind(null, remainderDeferreds)); var initial = []; // initial remainder - jiff.utils.bit_combinator(final_deferred, constant_bits.length - 1, -1, initial, function (i, _remainder) { - var iterationCounter = (constant_bits.length - i - 1); - - // add bit i to the head of remainder (least significant bit) - // turn into a secret without communication, just for typing - var cbit_share = new jiff.SecretShare(constant_bits[i], bits[0].holders, bits[0].threshold, bits[0].Zp); - _remainder.unshift(cbit_share); - - // Get the next bit of the quotient - // and conditionally subtract b from the - // intermediate remainder to continue - var sub = jiff.protocols.bits.ssub(_remainder, bits, op_id + ':bits.ssub:' + iterationCounter); - var noUnderflow = sub.pop().inot(); // get the overflow bit, sub is now the result of subtraction - - // Get next bit of quotient - noUnderflow.wThen(quotientDeferreds[i].resolve); - - // Update remainder - for (var j = 0; j < _remainder.length; j++) { - // note, if noUnderflow, then |# bits in sub| <= |# bits in remainder| - _remainder[j] = noUnderflow.iif_else(sub[j], _remainder[j], op_id + ':if_else:' + iterationCounter + ':' + j); - } - - // cannot be bigger than divisor at this point - while (_remainder.length > remainder.length) { - _remainder.pop(); - } - - return _remainder; - }, function (intermediate) { - // promise-ify an array of intermediate results - var promises = []; - for (var i = 0; i < intermediate.length; i++) { - promises.push(intermediate[i].value); + jiff.utils.bit_combinator( + final_deferred, + constant_bits.length - 1, + -1, + initial, + function (i, _remainder) { + var iterationCounter = constant_bits.length - i - 1; + + // add bit i to the head of remainder (least significant bit) + // turn into a secret without communication, just for typing + var cbit_share = new jiff.SecretShare(constant_bits[i], bits[0].holders, bits[0].threshold, bits[0].Zp); + _remainder.unshift(cbit_share); + + // Get the next bit of the quotient + // and conditionally subtract b from the + // intermediate remainder to continue + var sub = jiff.protocols.bits.ssub(_remainder, bits, op_id + ':bits.ssub:' + iterationCounter); + var noUnderflow = sub.pop().inot(); // get the overflow bit, sub is now the result of subtraction + + // Get next bit of quotient + noUnderflow.wThen(quotientDeferreds[i].resolve); + + // Update remainder + for (var j = 0; j < _remainder.length; j++) { + // note, if noUnderflow, then |# bits in sub| <= |# bits in remainder| + _remainder[j] = noUnderflow.iif_else(sub[j], _remainder[j], op_id + ':if_else:' + iterationCounter + ':' + j); + } + + // cannot be bigger than divisor at this point + while (_remainder.length > remainder.length) { + _remainder.pop(); + } + + return _remainder; + }, + function (intermediate) { + // promise-ify an array of intermediate results + var promises = []; + for (var i = 0; i < intermediate.length; i++) { + promises.push(intermediate[i].value); + } + return Promise.all(promises); + }, + function (result) { + // identity + return result; } - return Promise.all(promises); - }, function (result) { - // identity - return result; - }); + ); - return {quotient: quotient, remainder: remainder}; + return { quotient: quotient, remainder: remainder }; } -}; \ No newline at end of file +}; diff --git a/lib/client/protocols/bits/comparison.js b/lib/client/protocols/bits/comparison.js index 9ae2c72b2..1c5c6f255 100644 --- a/lib/client/protocols/bits/comparison.js +++ b/lib/client/protocols/bits/comparison.js @@ -14,7 +14,7 @@ module.exports = { * returned immediately as a boolean */ ceq: function (jiff, bits, constant, op_id) { - if (!(bits[0].isConstant(constant))) { + if (!bits[0].isConstant(constant)) { throw new Error('parameter should be a number (bits.ceq)'); } if (op_id == null) { @@ -41,7 +41,7 @@ module.exports = { * returned immediately as a boolean */ cneq: function (jiff, bits, constant, op_id) { - if (!(bits[0].isConstant(constant))) { + if (!bits[0].isConstant(constant)) { throw new Error('parameter should be a number (bits.cneq)'); } @@ -86,7 +86,7 @@ module.exports = { * returned immediately as a boolean */ cgt: function (jiff, bits, constant, op_id) { - if (!(bits[0].isConstant(constant))) { + if (!bits[0].isConstant(constant)) { throw new Error('parameter should be a number (bits.cgt)'); } if (op_id == null) { @@ -109,7 +109,7 @@ module.exports = { * returned immediately as a boolean */ cgteq: function (jiff, bits, constant, op_id) { - if (!(bits[0].isConstant(constant))) { + if (!bits[0].isConstant(constant)) { throw new Error('parameter should be a number (bits.cgteq)'); } @@ -166,7 +166,7 @@ module.exports = { * returned immediately as a boolean */ clt: function (jiff, bits, constant, op_id) { - if (!(bits[0].isConstant(constant))) { + if (!bits[0].isConstant(constant)) { throw new Error('parameter should be a number (bits.clt)'); } if (op_id == null) { @@ -193,7 +193,7 @@ module.exports = { * returned immediately as a boolean */ clteq: function (jiff, bits, constant, op_id) { - if (!(bits[0].isConstant(constant))) { + if (!bits[0].isConstant(constant)) { throw new Error('parameter should be a number (bits.clteq)'); } if (op_id == null) { @@ -328,7 +328,8 @@ module.exports = { } else if (i < bits1.length) { // xor is equal to the value of bits1[i], andNot is equal to 0, since bits[2] is all zeros here borrow = bits1[i].inot().ismult(borrow, op_id + ':smult1:' + (i - 1)); - } else { // i < bits2.length + } else { + // i < bits2.length // xor and andNot are equal to the value of bits2[i] borrow = bits2[i].inot().ismult(borrow, op_id + ':smult1:' + (i - 1)); borrow = borrow.isadd(bits2[i]); @@ -377,4 +378,4 @@ module.exports = { var result = jiff.protocols.bits.sgt(bits1, bits2, op_id); return result.inot(); } -}; \ No newline at end of file +}; diff --git a/lib/client/protocols/bits/protocols.js b/lib/client/protocols/bits/protocols.js index ae558c92f..55829166c 100644 --- a/lib/client/protocols/bits/protocols.js +++ b/lib/client/protocols/bits/protocols.js @@ -63,7 +63,8 @@ module.exports = { promise.then(function (result) { jiff.utils.resolve_many_secrets(final_deferreds, result['shares']); }); - } else { // preprocess on demand + } else { + // preprocess on demand delete jiff.preprocessing_table[op_id]; jiff.preprocessing('rejection_sampling', 1, null, threshold, parties, parties, Zp, [op_id], { lower_bound: lower_bound, @@ -94,4 +95,4 @@ module.exports = { } return result; } -}; \ No newline at end of file +}; diff --git a/lib/client/protocols/bits/sharing.js b/lib/client/protocols/bits/sharing.js index e47f5ff8c..385f3b8e0 100644 --- a/lib/client/protocols/bits/sharing.js +++ b/lib/client/protocols/bits/sharing.js @@ -155,4 +155,4 @@ module.exports = { return jiff.helpers.bits_to_number(bits, bits.length); }); } -}; \ No newline at end of file +}; diff --git a/lib/client/protocols/booleans/boolean.js b/lib/client/protocols/booleans/boolean.js index be9abcb3f..c43a11a66 100644 --- a/lib/client/protocols/booleans/boolean.js +++ b/lib/client/protocols/booleans/boolean.js @@ -9,7 +9,7 @@ module.exports = function (SecretShare) { * @instance */ SecretShare.prototype.cxor_bit = function (cst) { - if (!(this.isConstant(cst))) { + if (!this.isConstant(cst)) { throw new Error('parameter should be a number (^)'); } if (!this.jiff.share_helpers['binary'](cst)) { @@ -28,7 +28,7 @@ module.exports = function (SecretShare) { * @instance */ SecretShare.prototype.cor_bit = function (cst) { - if (!(this.isConstant(cst))) { + if (!this.isConstant(cst)) { throw new Error('parameter should be a number (|)'); } if (!this.jiff.share_helpers['binary'](cst)) { @@ -141,11 +141,13 @@ module.exports = function (SecretShare) { if (const1 && const2) { return this.icmult(trueVal).isadd(this.inot().icmult(falseVal)); } else if (const1) { - return this.inot().ismult(falseVal.icsub(trueVal), op_id + ':smult').icadd(trueVal); + return this.inot() + .ismult(falseVal.icsub(trueVal), op_id + ':smult') + .icadd(trueVal); } else if (const2) { return this.ismult(trueVal.icsub(falseVal), op_id + ':smult').icadd(falseVal); } else { return this.ismult(trueVal.issub(falseVal), op_id + ':smult').isadd(falseVal); } }; -}; \ No newline at end of file +}; diff --git a/lib/client/protocols/generic.js b/lib/client/protocols/generic.js index 698df2d2d..fec95d141 100644 --- a/lib/client/protocols/generic.js +++ b/lib/client/protocols/generic.js @@ -10,7 +10,7 @@ module.exports = function (SecretShare) { * @return {boolean} true if o is a valid constant, false otherwise. */ SecretShare.prototype.isConstant = function (o) { - return typeof(o) === 'number'; + return typeof o === 'number'; }; /** @@ -37,7 +37,6 @@ module.exports = function (SecretShare) { return this.sadd(o); }; - /** * Generic Subtraction. * Uses either the constant or secret version of this operator depending on type of paramter. @@ -54,7 +53,6 @@ module.exports = function (SecretShare) { return this.ssub(o); }; - /** * Generic Multiplication. * Uses either the constant or secret version of this operator depending on type of paramter. @@ -76,7 +74,6 @@ module.exports = function (SecretShare) { return this.smult(o, op_id); }; - /** * Generic XOR for bits (both this and o have to be bits to work correctly). * Uses either the constant or secret version of this operator depending on type of paramter. @@ -136,7 +133,6 @@ module.exports = function (SecretShare) { return this.sgteq(o); }; - /** * Generic Greater than. * Uses either the constant or secret version of this operator depending on type of paramter. @@ -156,7 +152,6 @@ module.exports = function (SecretShare) { return this.sgt(o, op_id); }; - /** * Generic Less or equal. * Uses either the constant or secret version of this operator depending on type of paramter. @@ -176,7 +171,6 @@ module.exports = function (SecretShare) { return this.slteq(o, op_id); }; - /** * Generic Less than. * Uses either the constant or secret version of this operator depending on type of paramter. @@ -196,7 +190,6 @@ module.exports = function (SecretShare) { return this.slt(o, op_id); }; - /** * Generic Equals. * Uses either the constant or secret version of this operator depending on type of paramter. @@ -216,7 +209,6 @@ module.exports = function (SecretShare) { return this.seq(o, op_id); }; - /** * Generic Not Equals. * Uses either the constant or secret version of this operator depending on type of paramter. @@ -236,7 +228,6 @@ module.exports = function (SecretShare) { return this.sneq(o, op_id); }; - /** * Generic Integer Divison. * Uses either the constant or secret version of this operator depending on type of paramter. @@ -256,4 +247,4 @@ module.exports = function (SecretShare) { } return this.sdiv(o, l, op_id); }; -}; \ No newline at end of file +}; diff --git a/lib/client/protocols/numbers/arithmetic.js b/lib/client/protocols/numbers/arithmetic.js index 2bfdaf2fa..24041803b 100644 --- a/lib/client/protocols/numbers/arithmetic.js +++ b/lib/client/protocols/numbers/arithmetic.js @@ -9,7 +9,7 @@ module.exports = function (SecretShare) { * @instance */ SecretShare.prototype.cadd = function (cst) { - if (!(this.isConstant(cst))) { + if (!this.isConstant(cst)) { throw new Error('parameter should be a number (+)'); } @@ -30,7 +30,7 @@ module.exports = function (SecretShare) { * @instance */ SecretShare.prototype.csub = function (cst) { - if (!(this.isConstant(cst))) { + if (!this.isConstant(cst)) { throw new Error('parameter should be a number (-)'); } @@ -51,7 +51,7 @@ module.exports = function (SecretShare) { * @instance */ SecretShare.prototype.cmult = function (cst) { - if (!(this.isConstant(cst))) { + if (!this.isConstant(cst)) { throw new Error('parameter should be a number (*)'); } @@ -72,7 +72,7 @@ module.exports = function (SecretShare) { * @instance */ SecretShare.prototype.cdivfac = function (cst) { - if (!(this.isConstant(cst))) { + if (!this.isConstant(cst)) { throw new Error('Parameter should be a number (cdivfac)'); } @@ -256,7 +256,7 @@ module.exports = function (SecretShare) { if (!this.jiff.helpers.array_equals(this.holders, o.holders)) { throw new Error('shares must be held by the same parties (bgw*)'); } - if ((this.threshold - 1) + (o.threshold - 1) > this.holders.length - 1) { + if (this.threshold - 1 + (o.threshold - 1) > this.holders.length - 1) { throw new Error('threshold too high for BGW (*)'); } @@ -265,7 +265,7 @@ module.exports = function (SecretShare) { } // ensure thresholds are fine - var new_threshold = (this.threshold - 1) + (o.threshold - 1) + 1; + var new_threshold = this.threshold - 1 + (o.threshold - 1) + 1; if (new_threshold > this.holders) { var errorMsg = 'Threshold too large for smult_bgw: ' + new_threshold; errorMsg += '. Shares: ' + this.toString() + ', ' + o.toString(); @@ -312,7 +312,7 @@ module.exports = function (SecretShare) { // figure out maximum output bit length var lZp = this.jiff.share_helpers['ceil'](this.jiff.helpers.bLog(this.Zp, 2)); - l = (l != null && l < lZp) ? l : lZp; + l = l != null && l < lZp ? l : lZp; // Convert to bits var dividend_bits = this.bit_decomposition(op_id + ':decomposition1').slice(0, l); @@ -337,7 +337,7 @@ module.exports = function (SecretShare) { * @instance */ SecretShare.prototype.cdiv = function (cst, op_id) { - if (!(this.isConstant(cst))) { + if (!this.isConstant(cst)) { throw new Error('parameter should be a number (/)'); } @@ -387,18 +387,21 @@ module.exports = function (SecretShare) { // Preprocessing cases var quotient = this.jiff.get_preprocessing(op_id + ':quotient'); - if (quotient == null) { // case 1: no preprocessing with crypto provider! - var promise = this.jiff.from_crypto_provider('quotient', this.holders, this.threshold, this.Zp, op_id + ':quotient', {constant: cst}); + if (quotient == null) { + // case 1: no preprocessing with crypto provider! + var promise = this.jiff.from_crypto_provider('quotient', this.holders, this.threshold, this.Zp, op_id + ':quotient', { constant: cst }); promise.then(function (msg) { ready_quotient(msg['shares'][0], msg['shares'][1]); }); - } else if (quotient.ondemand === true) { // case 2: constant was not available at preprocessing time, must do it now! - this.jiff.preprocessing('quotient', 1, null, this.threshold, this.holders, this.holders, this.Zp, [op_id + ':quotient'], {constant: cst, namespace: 'base'}); + } else if (quotient.ondemand === true) { + // case 2: constant was not available at preprocessing time, must do it now! + this.jiff.preprocessing('quotient', 1, null, this.threshold, this.holders, this.holders, this.Zp, [op_id + ':quotient'], { constant: cst, namespace: 'base' }); this.jiff.executePreprocessing(function () { var quotient = self.jiff.get_preprocessing(op_id + ':quotient'); ready_quotient(quotient.r, quotient.q); }); - } else { // case 3: preprocessing is completed! + } else { + // case 3: preprocessing is completed! ready_quotient(quotient.r, quotient.q); } @@ -436,7 +439,7 @@ module.exports = function (SecretShare) { // figure out maximum output bit length var lZp = this.jiff.share_helpers['ceil'](this.jiff.helpers.bLog(this.Zp, 2)); - l = (l != null && l < lZp) ? l : lZp; + l = l != null && l < lZp ? l : lZp; // Convert to bits var dividend_bits = this.bit_decomposition(op_id + ':decomposition1').slice(0, l); @@ -461,7 +464,7 @@ module.exports = function (SecretShare) { * @instance */ SecretShare.prototype.cpow = function (cst, op_id) { - if (!(this.isConstant(cst))) { + if (!this.isConstant(cst)) { throw new Error('parameter should be a number (*)'); } @@ -492,15 +495,15 @@ module.exports = function (SecretShare) { for (var i = 0; this.jiff.share_helpers['<'](1, cst); i++) { if (this.jiff.share_helpers['even'](cst)) { - evens = evens.ismult(evens, op_id + ':smult0:'+i); + evens = evens.ismult(evens, op_id + ':smult0:' + i); cst = this.jiff.share_helpers['/'](cst, 2); } else { - odds = evens.ismult(odds, op_id + ':smult0:'+i); - evens = evens.ismult(evens, op_id + ':smult1:'+i); + odds = evens.ismult(odds, op_id + ':smult0:' + i); + evens = evens.ismult(evens, op_id + ':smult1:' + i); cst = this.jiff.share_helpers['/'](this.jiff.share_helpers['-'](cst, 1), 2); } } return evens.ismult(odds, op_id + ':smult0:' + i); }; -}; \ No newline at end of file +}; diff --git a/lib/client/protocols/numbers/comparison.js b/lib/client/protocols/numbers/comparison.js index 9fd688134..6f861244e 100644 --- a/lib/client/protocols/numbers/comparison.js +++ b/lib/client/protocols/numbers/comparison.js @@ -126,7 +126,12 @@ module.exports = function (SecretShare) { var y = self.issub(o).ilt_halfprime(op_id + ':halfprime:3'); y.wThen(function () { var xy = x.ismult(y, op_id + ':smult1'); - var answer = x.icmult(-1).icadd(1).issub(y).isadd(xy).isadd(w.ismult(x.isadd(y).issub(xy.icmult(2)), op_id + ':smult2')); + var answer = x + .icmult(-1) + .icadd(1) + .issub(y) + .isadd(xy) + .isadd(w.ismult(x.isadd(y).issub(xy.icmult(2)), op_id + ':smult2')); answer.wThen(final_deferred.resolve); }); }); @@ -147,7 +152,7 @@ module.exports = function (SecretShare) { * @instance */ SecretShare.prototype.cgteq = function (cst, op_id) { - if (!(this.isConstant(cst))) { + if (!this.isConstant(cst)) { throw new Error('parameter should be a number (>=)'); } @@ -171,7 +176,7 @@ module.exports = function (SecretShare) { * @instance */ SecretShare.prototype.cgt = function (cst, op_id) { - if (!(this.isConstant(cst))) { + if (!this.isConstant(cst)) { throw new Error('parameter should be a number (>)'); } @@ -188,10 +193,18 @@ module.exports = function (SecretShare) { var self = this; x.wThen(function () { - var y = self.icmult(-1).icadd(cst).ilt_halfprime(op_id + ':halfprime:2'); + var y = self + .icmult(-1) + .icadd(cst) + .ilt_halfprime(op_id + ':halfprime:2'); y.wThen(function () { var xy = y.ismult(x, op_id + ':smult1'); - var answer = x.icmult(-1).icadd(1).issub(y).isadd(xy).isadd(x.isadd(y).issub(xy.icmult(2)).icmult(w)); + var answer = x + .icmult(-1) + .icadd(1) + .issub(y) + .isadd(xy) + .isadd(x.isadd(y).issub(xy.icmult(2)).icmult(w)); answer.wThen(final_deferred.resolve); }); }); @@ -211,7 +224,7 @@ module.exports = function (SecretShare) { * @instance */ SecretShare.prototype.clteq = function (cst, op_id) { - if (!(this.isConstant(cst))) { + if (!this.isConstant(cst)) { throw new Error('parameter should be a number (<=)'); } @@ -234,7 +247,7 @@ module.exports = function (SecretShare) { * @instance */ SecretShare.prototype.clt = function (cst, op_id) { - if (!(this.isConstant(cst))) { + if (!this.isConstant(cst)) { throw new Error('parameter should be a number (<)'); } @@ -254,7 +267,11 @@ module.exports = function (SecretShare) { var y = self.icsub(cst).ilt_halfprime(op_id + ':halfprime:2'); y.wThen(function () { var xy = y.icmult(x); - var answer = y.icmult(-1).icadd(1 - x).isadd(xy).isadd(w.ismult(y.icadd(x).issub(xy.icmult(2)), op_id + ':smult1')); + var answer = y + .icmult(-1) + .icadd(1 - x) + .isadd(xy) + .isadd(w.ismult(y.icadd(x).issub(xy.icmult(2)), op_id + ':smult1')); answer.wThen(final_deferred.resolve); }); }); @@ -330,7 +347,7 @@ module.exports = function (SecretShare) { * @instance */ SecretShare.prototype.ceq = function (cst, op_id) { - if (!(this.isConstant(cst))) { + if (!this.isConstant(cst)) { throw new Error('parameter should be a number (==)'); } if (op_id == null) { @@ -352,7 +369,7 @@ module.exports = function (SecretShare) { * @instance */ SecretShare.prototype.cneq = function (cst, op_id) { - if (!(this.isConstant(cst))) { + if (!this.isConstant(cst)) { throw new Error('parameter should be a number (!=)'); } if (op_id == null) { @@ -427,4 +444,4 @@ module.exports = function (SecretShare) { return result; }; -}; \ No newline at end of file +}; diff --git a/lib/client/protocols/numbers/protocols.js b/lib/client/protocols/numbers/protocols.js index 9ae133e9a..bc8c5d963 100644 --- a/lib/client/protocols/numbers/protocols.js +++ b/lib/client/protocols/numbers/protocols.js @@ -106,4 +106,4 @@ module.exports = function (SecretShare) { return result; }; -}; \ No newline at end of file +}; diff --git a/lib/client/protocols/preprocessing/bits.js b/lib/client/protocols/preprocessing/bits.js index c13c29b18..0b833f4da 100644 --- a/lib/client/protocols/preprocessing/bits.js +++ b/lib/client/protocols/preprocessing/bits.js @@ -36,7 +36,7 @@ module.exports = { for (var i = 1; i < compute_list.length; i++) { var party_id = compute_list[i]; var obit = bit_shares[party_id]; - random_bit = random_bit.isxor_bit(obit, op_id + ':sxor_bit:' + i); + random_bit = random_bit.isxor_bit(obit, op_id + ':sxor_bit:' + i); } promise = random_bit.value; @@ -47,7 +47,7 @@ module.exports = { if (receivers_list.indexOf(jiff.id) > -1) { promise = random_bit.value; } - return {share: random_bit, promise: promise}; + return { share: random_bit, promise: promise }; }, /** * Generates a random bit under MPC by xoring all bits sent by participating parties using smult_bgw @@ -98,7 +98,7 @@ module.exports = { if (receivers_list.indexOf(jiff.id) > -1) { promise = random_bit.value; } - return {share: random_bit, promise: promise}; + return { share: random_bit, promise: promise }; }, /** * Generates a sequence of random bits under MPC @@ -149,6 +149,6 @@ module.exports = { if (bits.length === 0) { bits = null; } - return {share: bits, promise: Promise.all(promises)}; + return { share: bits, promise: Promise.all(promises) }; } -}; \ No newline at end of file +}; diff --git a/lib/client/protocols/preprocessing/numbers.js b/lib/client/protocols/preprocessing/numbers.js index 9e21d5c5c..f2f612eb4 100644 --- a/lib/client/protocols/preprocessing/numbers.js +++ b/lib/client/protocols/preprocessing/numbers.js @@ -45,7 +45,7 @@ var jiff_share_all_number = function (jiff, n, threshold, receivers_list, comput promise = result.value; } - return {share: result, promise: promise}; + return { share: result, promise: promise }; }; module.exports = { @@ -98,4 +98,4 @@ module.exports = { } return jiff_share_all_number(jiff, 0, threshold, receivers_list, compute_list, Zp, params); } -}; \ No newline at end of file +}; diff --git a/lib/client/protocols/preprocessing/quotients.js b/lib/client/protocols/preprocessing/quotients.js index db98755de..ca713d709 100644 --- a/lib/client/protocols/preprocessing/quotients.js +++ b/lib/client/protocols/preprocessing/quotients.js @@ -69,5 +69,5 @@ module.exports = function (jiff, threshold, receivers_list, compute_list, Zp, pa if (receivers_list.indexOf(jiff.id) > -1) { promise = Promise.all([r.value, q.value]); } - return {share: {r: r, q: q}, promise: promise}; -}; \ No newline at end of file + return { share: { r: r, q: q }, promise: promise }; +}; diff --git a/lib/client/protocols/preprocessing/sampling.js b/lib/client/protocols/preprocessing/sampling.js index 9068bce4f..5ebfe40d9 100644 --- a/lib/client/protocols/preprocessing/sampling.js +++ b/lib/client/protocols/preprocessing/sampling.js @@ -29,7 +29,7 @@ var one_round_sampling = function (jiff, lower_bound, upper_bound, compute_list, while (resultOne.length > finalLength) { resultOne.pop(); } - return {share: resultOne, promise: true}; + return { share: resultOne, promise: true }; } // Rejection protocol @@ -38,17 +38,19 @@ var one_round_sampling = function (jiff, lower_bound, upper_bound, compute_list, var bits_add = jiff.protocols.bits.cadd(bits, lower_bound, params.output_op_id + ':bits.cadd:' + reject_count); if (cmp === true) { - return {share: bits_add, promise: true}; - } else if (cmp === false) { // need to resample - return {share: bits_add, promise: false}; + return { share: bits_add, promise: true }; + } else if (cmp === false) { + // need to resample + return { share: bits_add, promise: false }; } var promise = jiff.internal_open(cmp, compute_list, params.output_op_id + ':open:' + reject_count); - return {share: bits_add, promise: promise.then( - function (cmp) { + return { + share: bits_add, + promise: promise.then(function (cmp) { return cmp.toString() === '1'; - } - )}; + }) + }; }; var computeParty = function (jiff, lower_bound, upper_bound, threshold, receivers_list, compute_list, Zp, params, protocols, op_id, finalLength, reject_count) { @@ -59,7 +61,7 @@ var computeParty = function (jiff, lower_bound, upper_bound, threshold, receiver return reshareResult(jiff, upper_bound, threshold, receivers_list, compute_list, Zp, op_id, finalLength, result.share); } if (result.promise === false) { - return {share: 'RETRY', promise: jiff.utils.all_promises(result.share)}; + return { share: 'RETRY', promise: jiff.utils.all_promises(result.share) }; } // Case 2: we only have a promise to whether the sampling succeeded or not @@ -87,7 +89,7 @@ var computeParty = function (jiff, lower_bound, upper_bound, threshold, receiver } }); - return {share: many_shares.shares, promise: jiff.utils.all_promises(many_shares.shares)}; + return { share: many_shares.shares, promise: jiff.utils.all_promises(many_shares.shares) }; }; var reshareResult = function (jiff, upper_bound, threshold, receivers_list, compute_list, Zp, op_id, finalLength, shares) { @@ -109,7 +111,7 @@ var reshareResult = function (jiff, upper_bound, threshold, receivers_list, comp } // handle rejection case - return {share: shares, promise: Promise.all(promises)}; + return { share: shares, promise: Promise.all(promises) }; }; /** @@ -146,7 +148,8 @@ module.exports = function (jiff, threshold, receivers_list, compute_list, Zp, pa // defaults (for internal preprocessing) var lower_bound = params.lower_bound != null ? params.lower_bound : 0; var upper_bound = params.upper_bound != null ? params.upper_bound : Zp; - if (params.compute_threshold == null) { // honest majority BGW + if (params.compute_threshold == null) { + // honest majority BGW params.compute_threshold = Math.floor((compute_list.length + 1) / 2); } @@ -166,7 +169,7 @@ module.exports = function (jiff, threshold, receivers_list, compute_list, Zp, pa var reject_count = params.reject_count || 0; if (compute_list.indexOf(jiff.id) === -1) { - return reshareResult(jiff, upper_bound, threshold, receivers_list, compute_list, Zp, op_id, finalLength, []) + return reshareResult(jiff, upper_bound, threshold, receivers_list, compute_list, Zp, op_id, finalLength, []); } return computeParty(jiff, lower_bound, upper_bound, threshold, receivers_list, compute_list, Zp, params, protocols, op_id, finalLength, reject_count); diff --git a/lib/client/protocols/shamir/open.js b/lib/client/protocols/shamir/open.js index 98ad053db..1c4c9e4b6 100644 --- a/lib/client/protocols/shamir/open.js +++ b/lib/client/protocols/shamir/open.js @@ -17,7 +17,7 @@ var jiff_broadcast = function (jiff, share, parties, op_id) { } // encrypt, sign and send - var msg = {party_id: i, share: share.value, op_id: op_id, Zp: share.Zp}; + var msg = { party_id: i, share: share.value, op_id: op_id, Zp: share.Zp }; msg = jiff.hooks.execute_array_hooks('beforeOperation', [jiff, 'open', msg], 2); msg['share'] = jiff.hooks.encryptSign(jiff, msg['share'].toString(), jiff.keymap[msg['party_id']], jiff.secret_key); @@ -146,10 +146,10 @@ module.exports = { var recons_secret = 0; for (var p = 0; p < shares.length; p++) { var party = jiff.helpers.get_party_number(shares[p].sender_id); - var tmp = jiff.helpers.mod((shares[p].value * lagrange_coeff[party]), shares[p].Zp); - recons_secret = jiff.helpers.mod((recons_secret + tmp), shares[p].Zp); + var tmp = jiff.helpers.mod(shares[p].value * lagrange_coeff[party], shares[p].Zp); + recons_secret = jiff.helpers.mod(recons_secret + tmp, shares[p].Zp); } return recons_secret; } -}; \ No newline at end of file +}; diff --git a/lib/client/protocols/shamir/reshare.js b/lib/client/protocols/shamir/reshare.js index d01098047..43ef9ccdf 100644 --- a/lib/client/protocols/shamir/reshare.js +++ b/lib/client/protocols/shamir/reshare.js @@ -86,7 +86,7 @@ module.exports = function (jiff, share, threshold, receivers_list, senders_list, var party_id = senders_list[i]; //shamir reconstruct takes an array of objects //has attributes: {value: x, sender_id: y, Zp: jiff_instance.Zp} - reconstruct_parts[i] = {value: intermediate_shares[party_id].value, sender_id: party_id, Zp: Zp}; + reconstruct_parts[i] = { value: intermediate_shares[party_id].value, sender_id: party_id, Zp: Zp }; } var value = jiff.hooks.reconstructShare(jiff, reconstruct_parts); final_deferred.resolve(value); @@ -96,9 +96,10 @@ module.exports = function (jiff, share, threshold, receivers_list, senders_list, if (isSender && !share.ready) { share.value.then(ready_share); - } else { // either a receiver or share is ready + } else { + // either a receiver or share is ready ready_share(); } return result; -}; \ No newline at end of file +}; diff --git a/lib/client/protocols/shamir/share.js b/lib/client/protocols/shamir/share.js index f177b4089..45197c9f4 100644 --- a/lib/client/protocols/shamir/share.js +++ b/lib/client/protocols/shamir/share.js @@ -39,8 +39,8 @@ module.exports = { var power = jiff.helpers.get_party_number(p_id); for (var j = 1; j < polynomial.length; j++) { - var tmp = jiff.helpers.mod((polynomial[j] * power), Zp); - shares[p_id] = jiff.helpers.mod((shares[p_id] + tmp), Zp); + var tmp = jiff.helpers.mod(polynomial[j] * power, Zp); + shares[p_id] = jiff.helpers.mod(shares[p_id] + tmp, Zp); power = jiff.helpers.mod(power * jiff.helpers.get_party_number(p_id), Zp); } } @@ -131,7 +131,7 @@ module.exports = { } // send encrypted and signed shares_id[p_id] to party p_id - var msg = {party_id: p_id, share: shares[p_id], op_id: share_id}; + var msg = { party_id: p_id, share: shares[p_id], op_id: share_id }; msg = jiff.hooks.execute_array_hooks('beforeOperation', [jiff, 'share', msg], 2); msg['share'] = jiff.hooks.encryptSign(jiff, msg['share'].toString(10), jiff.keymap[msg['party_id']], jiff.secret_key); @@ -150,7 +150,8 @@ module.exports = { var _remaining = senders_list.length; for (i = 0; i < senders_list.length; i++) { p_id = senders_list[i]; - if (p_id === jiff.id) { // Keep party's own share + if (p_id === jiff.id) { + // Keep party's own share var my_share = jiff.hooks.execute_array_hooks('receiveShare', [jiff, p_id, shares[p_id]], 2); result[p_id] = new jiff.SecretShare(my_share, receivers_list, threshold, Zp); _remaining--; @@ -158,13 +159,15 @@ module.exports = { } // check if a deferred is set up (maybe the message was previously received) - if (jiff.deferreds[share_id][p_id] == null) { // not ready, setup a deferred + if (jiff.deferreds[share_id][p_id] == null) { + // not ready, setup a deferred jiff.deferreds[share_id][p_id] = new jiff.helpers.Deferred(); } var promise = jiff.deferreds[share_id][p_id].promise; // destroy deferred when done - (function (promise, p_id) { // p_id is modified in a for loop, must do this to avoid scoping issues. + (function (promise, p_id) { + // p_id is modified in a for loop, must do this to avoid scoping issues. promise.then(function () { delete jiff.deferreds[share_id][p_id]; _remaining--; @@ -181,4 +184,4 @@ module.exports = { return result; } -}; \ No newline at end of file +}; diff --git a/lib/client/share.js b/lib/client/share.js index a372b1403..4142ce90b 100644 --- a/lib/client/share.js +++ b/lib/client/share.js @@ -18,7 +18,7 @@ module.exports = function (jiff) { * @memberof module:jiff-client~JIFFClient#SecretShare * @instance */ - this.ready = (value.then == null); + this.ready = value.then == null; /** * The value of the share (or a promise to it) @@ -215,15 +215,41 @@ module.exports = function (jiff) { booleans(SecretShare); // internal variant of primitives, to use internally by other primitives - var internals = ['cadd', 'csub', 'cmult', 'sadd', 'ssub', 'smult', 'smult_bgw', - 'cxor_bit', 'sxor_bit', 'cor_bit', 'sor_bit', - 'slt', 'slteq', 'sgt', 'sgteq', 'seq', 'sneq', - 'clt', 'clteq', 'cgt', 'cgteq', 'ceq', 'cneq', - 'sdiv', 'cdiv', 'not', 'cpow', 'lt_halfprime', 'if_else']; + var internals = [ + 'cadd', + 'csub', + 'cmult', + 'sadd', + 'ssub', + 'smult', + 'smult_bgw', + 'cxor_bit', + 'sxor_bit', + 'cor_bit', + 'sor_bit', + 'slt', + 'slteq', + 'sgt', + 'sgteq', + 'seq', + 'sneq', + 'clt', + 'clteq', + 'cgt', + 'cgteq', + 'ceq', + 'cneq', + 'sdiv', + 'cdiv', + 'not', + 'cpow', + 'lt_halfprime', + 'if_else' + ]; for (var i = 0; i < internals.length; i++) { var key = internals[i]; SecretShare.prototype['i' + key] = SecretShare.prototype[key]; } return SecretShare; -}; \ No newline at end of file +}; diff --git a/lib/client/shareHelpers.js b/lib/client/shareHelpers.js index 1bf61f2ac..2589a3739 100644 --- a/lib/client/shareHelpers.js +++ b/lib/client/shareHelpers.js @@ -17,28 +17,28 @@ module.exports = { '<=': function (v1, v2) { return v1 <= v2; }, - 'floor': function (v) { + floor: function (v) { return Math.floor(v); }, - 'ceil': function (v) { + ceil: function (v) { return Math.ceil(v); }, 'floor/': function (v1, v2) { return Math.floor(v1 / v2); }, - 'pow': function (v1, v2) { + pow: function (v1, v2) { return Math.pow(v1, v2); }, - 'binary': function (v) { + binary: function (v) { return v === 1 || v === 0; }, - 'abs': function (v) { + abs: function (v) { return Math.abs(v); }, '==': function (v1, v2) { return v1 === v2; }, - 'even': function (v1) { - return (v1 % 2) === 0; + even: function (v1) { + return v1 % 2 === 0; } -}; \ No newline at end of file +}; diff --git a/lib/client/socket/events.js b/lib/client/socket/events.js index f34216c54..af6c1f1b5 100644 --- a/lib/client/socket/events.js +++ b/lib/client/socket/events.js @@ -37,7 +37,7 @@ module.exports = function (JIFFClient) { if (jiffClient.messagesWaitingKeys[sender_id] == null) { jiffClient.messagesWaitingKeys[sender_id] = []; } - jiffClient.messagesWaitingKeys[sender_id].push({label: 'share', msg: json_msg}); + jiffClient.messagesWaitingKeys[sender_id].push({ label: 'share', msg: json_msg }); } }); @@ -54,7 +54,7 @@ module.exports = function (JIFFClient) { if (jiffClient.messagesWaitingKeys[sender_id] == null) { jiffClient.messagesWaitingKeys[sender_id] = []; } - jiffClient.messagesWaitingKeys[sender_id].push({label: 'open', msg: json_msg}); + jiffClient.messagesWaitingKeys[sender_id].push({ label: 'open', msg: json_msg }); } }); @@ -73,7 +73,7 @@ module.exports = function (JIFFClient) { if (jiffClient.messagesWaitingKeys[sender_id] == null) { jiffClient.messagesWaitingKeys[sender_id] = []; } - jiffClient.messagesWaitingKeys[sender_id].push({label: 'custom', msg: json_msg}); + jiffClient.messagesWaitingKeys[sender_id].push({ label: 'custom', msg: json_msg }); } }); @@ -166,4 +166,4 @@ module.exports = function (JIFFClient) { this.messagesWaitingKeys[party_id] = null; } }; -}; \ No newline at end of file +}; diff --git a/lib/client/socket/internal.js b/lib/client/socket/internal.js index 4f39c66b9..4b265de75 100644 --- a/lib/client/socket/internal.js +++ b/lib/client/socket/internal.js @@ -25,4 +25,4 @@ module.exports = function (jiffClient, __internal_socket) { }; return __internal_socket; -}; \ No newline at end of file +}; diff --git a/lib/client/socket/mailbox.js b/lib/client/socket/mailbox.js index d9a5ea5b2..292450447 100644 --- a/lib/client/socket/mailbox.js +++ b/lib/client/socket/mailbox.js @@ -111,7 +111,7 @@ var disconnect = function () { * @instance * @param {boolean} [free=false] - if true, a free message will be issued prior to disconnecting * @param {function()} [callback] - given callback will be executed after safe disconnection is complete - */ + */ var safe_disconnect = function (free, callback) { if (this.is_empty()) { if (free) { @@ -141,4 +141,4 @@ var is_empty = function () { return this.mailbox.head == null && this.jiffClient.counters.pending_opens === 0; }; -module.exports = guardedSocket; \ No newline at end of file +module.exports = guardedSocket; diff --git a/lib/client/util/constants.js b/lib/client/util/constants.js index ad21cd156..103f358a1 100644 --- a/lib/client/util/constants.js +++ b/lib/client/util/constants.js @@ -15,4 +15,4 @@ module.exports = { * Maximum numbers of retries on failed initialization. */ maxInitializationRetries: 2 -}; \ No newline at end of file +}; diff --git a/lib/client/util/crypto.js b/lib/client/util/crypto.js index 88df4451e..c2d5cab82 100644 --- a/lib/client/util/crypto.js +++ b/lib/client/util/crypto.js @@ -36,4 +36,4 @@ exports.decrypt_and_sign = function (jiff, cipher_text, decryption_secret_key, s } catch (_) { throw new Error('Bad signature or Bad nonce: Cipher: ' + cipher_text + '. DecSKey: ' + decryption_secret_key + '. SignPKey: ' + signing_public_key); } -}; \ No newline at end of file +}; diff --git a/lib/client/util/helpers.js b/lib/client/util/helpers.js index fd39dbabd..365a1d3aa 100644 --- a/lib/client/util/helpers.js +++ b/lib/client/util/helpers.js @@ -44,10 +44,12 @@ module.exports = function (jiffClient) { * @member {Promise} promise * @instance */ - this.promise = new Promise(function (resolve, reject) { - this.resolve = resolve; - this.reject = reject; - }.bind(this)); + this.promise = new Promise( + function (resolve, reject) { + this.resolve = resolve; + this.reject = reject; + }.bind(this) + ); Object.freeze(this); }; @@ -279,5 +281,5 @@ module.exports = function (jiffClient) { return e1 - e2; }); ids.__jiff_sorted = true; - } -}; \ No newline at end of file + }; +}; diff --git a/lib/client/util/utils.js b/lib/client/util/utils.js index cba00a99a..c84476ab4 100644 --- a/lib/client/util/utils.js +++ b/lib/client/util/utils.js @@ -27,7 +27,7 @@ module.exports = function (jiffClient) { deferreds.push(deferred); } - return {shares: shares, deferreds: deferreds}; + return { shares: shares, deferreds: deferreds }; }; /** @@ -80,14 +80,14 @@ module.exports = function (jiffClient) { jiffClient.utils.bit_combinator = function (deferred, start, length, initial, func, promisify, valufy) { if (promisify == null) { promisify = function (share) { - return {then: share.wThen.bind(share)}; - } + return { then: share.wThen.bind(share) }; + }; } if (valufy == null) { valufy = function (share) { return share.value; - } + }; } var next = start <= length ? 1 : -1; @@ -115,5 +115,5 @@ module.exports = function (jiffClient) { __bit_combinator(start, initial); }); } - } -}; \ No newline at end of file + }; +}; diff --git a/lib/common/helpers.js b/lib/common/helpers.js index 5fbab5a01..8614ff8e7 100644 --- a/lib/common/helpers.js +++ b/lib/common/helpers.js @@ -1,5 +1,5 @@ var crypto_; -if (typeof(window) === 'undefined') { +if (typeof window === 'undefined') { crypto_ = require('crypto'); crypto_.__randomBytesWrapper = crypto_.randomBytes; } else { @@ -23,12 +23,13 @@ exports.random = function (max) { throw new RangeError('Max value should be smaller than or equal to 2^49'); } - var bitsNeeded = Math.ceil(Math.log(max)/Math.log(2)); + var bitsNeeded = Math.ceil(Math.log(max) / Math.log(2)); var bytesNeeded = Math.ceil(bitsNeeded / 8); var maxValue = Math.pow(256, bytesNeeded); // Keep trying until we find a random value within bounds - while (true) { // eslint-disable-line + while (true) { + // eslint-disable-line var randomBytes = crypto_.__randomBytesWrapper(bytesNeeded); var randomValue = 0; @@ -37,7 +38,7 @@ exports.random = function (max) { } // randomValue should be smaller than largest multiple of max within maxBytes - if (randomValue < maxValue - maxValue % max) { + if (randomValue < maxValue - (maxValue % max)) { return randomValue % max; } } @@ -53,7 +54,7 @@ exports.mod = function (x, y) { // get the party number from the given party_id, the number is used to compute/open shares exports.get_party_number = function (party_id) { - if (typeof(party_id) === 'number') { + if (typeof party_id === 'number') { return party_id; } if (party_id.startsWith('s')) { @@ -73,4 +74,4 @@ exports.number_to_bits = function (number, length) { bits.push(0); } return bits; -}; \ No newline at end of file +}; diff --git a/lib/common/linkedlist.js b/lib/common/linkedlist.js index 1c0ebc4af..57d333a14 100644 --- a/lib/common/linkedlist.js +++ b/lib/common/linkedlist.js @@ -6,7 +6,7 @@ module.exports = function () { // next: pointer to next, // previous: pointer to previous, // object: stored object. - var list = {head: null, tail: null}; + var list = { head: null, tail: null }; // TODO rename this to pushTail || push list.add = function (obj) { var node = { object: obj, next: null, previous: null }; @@ -22,7 +22,7 @@ module.exports = function () { }; list.pushHead = function (obj) { - list.head = {object: obj, next : list.head, previous : null}; + list.head = { object: obj, next: list.head, previous: null }; if (list.head.next != null) { list.head.next.previous = list.head; } else { @@ -37,7 +37,7 @@ module.exports = function () { if (list.head == null) { list.tail = null; } else { - list.head.previous = null; + list.head.previous = null; } } return result; @@ -69,22 +69,26 @@ module.exports = function () { return; } - if (prev == null) { // ptr is head (or both head and tail) + if (prev == null) { + // ptr is head (or both head and tail) list.head = next; if (list.head != null) { list.head.previous = null; } else { list.tail = null; } - } else if (next == null) { // ptr is tail (and not head) + } else if (next == null) { + // ptr is tail (and not head) list.tail = prev; prev.next = null; - } else { // ptr is inside + } else { + // ptr is inside prev.next = next; next.previous = prev; } }; - list.slice = function (ptr) { // remove all elements from head to ptr (including ptr). + list.slice = function (ptr) { + // remove all elements from head to ptr (including ptr). if (ptr == null) { return; } diff --git a/lib/ext/jiff-client-bignumber.js b/lib/ext/jiff-client-bignumber.js index de0a90a24..9ef217ab5 100644 --- a/lib/ext/jiff-client-bignumber.js +++ b/lib/ext/jiff-client-bignumber.js @@ -118,7 +118,7 @@ var shares = {}; // Keeps the shares var i; - secret = secret != null ? secret : 0; // allow asymmetric receiving even self-receiving + secret = secret != null ? secret : 0; // allow asymmetric receiving even self-receiving secret = jiff.helpers.BigNumber(secret); Zp = jiff.helpers.BigNumber(Zp); @@ -230,13 +230,13 @@ return v.toString() === '1' || v.toString() === '0'; }; jiff.share_helpers['floor'] = function (v) { - if (typeof(v) === 'number') { + if (typeof v === 'number') { return Math.floor(v); } return v.floor(); }; jiff.share_helpers['ceil'] = function (v) { - if (typeof(v) === 'number') { + if (typeof v === 'number') { return Math.ceil(v); } return v.ceil(); @@ -278,7 +278,7 @@ /* HELPERS */ jiff.helpers._BigNumber = BigNumber_; - jiff.helpers._BigNumber.config({CRYPTO: true}); + jiff.helpers._BigNumber.config({ CRYPTO: true }); jiff.helpers.BigNumber = function (n) { // eslint-disable-next-line no-undef return new jiff.helpers._BigNumber(n); @@ -301,19 +301,17 @@ jiff.helpers.extended_gcd = function (a, b) { a = jiff.helpers.BigNumber(a); b = jiff.helpers.BigNumber(b); - return ( - function recursive_helper(a, b) { - if (b.isZero()) { - return [jiff.helpers.BigNumber(1), jiff.helpers.BigNumber(0), a]; - } - - var temp = recursive_helper(b, jiff.helpers.mod(a, b)); - var x = temp[0]; - var y = temp[1]; - var d = temp[2]; - return [y, x.minus(y.times(a.div(b).floor())), d]; + return (function recursive_helper(a, b) { + if (b.isZero()) { + return [jiff.helpers.BigNumber(1), jiff.helpers.BigNumber(0), a]; } - )(a, b); + + var temp = recursive_helper(b, jiff.helpers.mod(a, b)); + var x = temp[0]; + var y = temp[1]; + var d = temp[2]; + return [y, x.minus(y.times(a.div(b).floor())), d]; + })(a, b); }; jiff.helpers.bLog = function (value, base) { @@ -367,7 +365,7 @@ }; jiff.protocols.bits.cgt = function (bits, constant, op_id) { - if (!(bits[0].isConstant(constant))) { + if (!bits[0].isConstant(constant)) { throw new Error('parameter should be a number (bits.cgt)'); } if (op_id == null) { @@ -381,10 +379,10 @@ jiff.share = function (secret, threshold, receivers_list, senders_list, Zp, share_id) { secret = secret != null ? jiff.helpers.BigNumber(secret) : secret; if (secret != null && (!secret.floor().eq(secret) || secret.lt(0))) { - throw new Error('secret \'' + secret + '\' must be a non-negative whole number'); + throw new Error("secret '" + secret + "' must be a non-negative whole number"); } - if (secret != null && (secret.gte(Zp == null ? jiff.Zp : Zp))) { - throw new Error('secret \'' + secret + '\' must fit inside Zp'); + if (secret != null && secret.gte(Zp == null ? jiff.Zp : Zp)) { + throw new Error("secret '" + secret + "' must fit inside Zp"); } return jiff.internal_share(secret, threshold, receivers_list, senders_list, Zp, share_id); }; @@ -415,6 +413,6 @@ // Expose the API for this extension. exports.make_jiff = make_jiff; - exports.sharing_schemes = {shamir_share: jiff_compute_shares, shamir_reconstruct: jiff_lagrange}; - exports.utils = {is_prime: is_prime}; -}((typeof exports === 'undefined' ? this.jiff_bignumber = {} : exports), typeof exports !== 'undefined')); + exports.sharing_schemes = { shamir_share: jiff_compute_shares, shamir_reconstruct: jiff_lagrange }; + exports.utils = { is_prime: is_prime }; +})(typeof exports === 'undefined' ? (this.jiff_bignumber = {}) : exports, typeof exports !== 'undefined'); diff --git a/lib/ext/jiff-client-debugging.js b/lib/ext/jiff-client-debugging.js index f3eed82d3..1c3100e41 100644 --- a/lib/ext/jiff-client-debugging.js +++ b/lib/ext/jiff-client-debugging.js @@ -7,7 +7,7 @@ // next: pointer to next, // previous: pointer to previous, // object: stored object. - var list = {head: null, tail: null}; + var list = { head: null, tail: null }; list.add = function (obj) { list._size++; var node = { object: obj, next: null, previous: null }; @@ -32,17 +32,20 @@ return; } - if (prev == null) { // ptr is head (or both head and tail) + if (prev == null) { + // ptr is head (or both head and tail) list.head = next; if (list.head != null) { list.head.previous = null; } else { list.tail = null; } - } else if (next == null) { // ptr is tail (and not head) + } else if (next == null) { + // ptr is tail (and not head) list.tail = prev; prev.next = null; - } else { // ptr is inside + } else { + // ptr is inside prev.next = next; next.previous = prev; } @@ -99,13 +102,15 @@ /* A newly created Promise object. * Initially in pending state. */ - this.promise = new Promise(function (resolve, reject) { - self.resolve = function () { - stacks.remove(self.ptr); - resolve.apply(self.promise, arguments); - }; - self.reject = reject; - }.bind(this)); + this.promise = new Promise( + function (resolve, reject) { + self.resolve = function () { + stacks.remove(self.ptr); + resolve.apply(self.promise, arguments); + }; + self.reject = reject; + }.bind(this) + ); Object.freeze(this); }; @@ -150,5 +155,5 @@ }; return jiff; - } -}((typeof exports === 'undefined' ? this.jiff_performance = {} : exports), typeof exports !== 'undefined')); + }; +})(typeof exports === 'undefined' ? (this.jiff_performance = {}) : exports, typeof exports !== 'undefined'); diff --git a/lib/ext/jiff-client-fixedpoint.js b/lib/ext/jiff-client-fixedpoint.js index 184da7f37..318850a8c 100644 --- a/lib/ext/jiff-client-fixedpoint.js +++ b/lib/ext/jiff-client-fixedpoint.js @@ -16,13 +16,39 @@ function createFixedpointSecretShare(jiff_instance, share) { share.legacy = {}; - var internals = ['cadd', 'csub', 'cmult', - 'sadd', 'ssub', 'smult', 'smult_bgw', - 'cdivfac', 'cdiv', 'sdiv', 'smod', - 'cxor_bit', 'sxor_bit', 'cor_bit', 'sor_bit', 'not', - 'slt', 'slteq', 'sgt', 'sgteq', 'seq', 'sneq', - 'clt', 'clteq', 'cgt', 'cgteq', 'ceq', 'cneq', - 'lt_halfprime', 'if_else', 'cpow' ]; + var internals = [ + 'cadd', + 'csub', + 'cmult', + 'sadd', + 'ssub', + 'smult', + 'smult_bgw', + 'cdivfac', + 'cdiv', + 'sdiv', + 'smod', + 'cxor_bit', + 'sxor_bit', + 'cor_bit', + 'sor_bit', + 'not', + 'slt', + 'slteq', + 'sgt', + 'sgteq', + 'seq', + 'sneq', + 'clt', + 'clteq', + 'cgt', + 'cgteq', + 'ceq', + 'cneq', + 'lt_halfprime', + 'if_else', + 'cpow' + ]; for (var i = 0; i < internals.length; i++) { var key = internals[i]; share.legacy[key] = share[key].bind(share); @@ -40,7 +66,7 @@ // Constant arithmetic operations share.cadd = function (cst) { - if (!(share.isConstant(cst))) { + if (!share.isConstant(cst)) { throw new Error('parameter should be a number (+)'); } @@ -49,7 +75,7 @@ return share.legacy.cadd(cst); }; share.csub = function (cst) { - if (!(share.isConstant(cst))) { + if (!share.isConstant(cst)) { throw new Error('parameter should be a number (-)'); } @@ -58,7 +84,7 @@ return share.legacy.csub(cst); }; share.cmult = function (cst, op_id, div) { - if (!(share.isConstant(cst))) { + if (!share.isConstant(cst)) { throw new Error('parameter should be a number (-)'); } if (op_id == null) { @@ -106,7 +132,7 @@ }; share.cdivfac = function (cst) { - if (!(share.isConstant(cst))) { + if (!share.isConstant(cst)) { throw new Error('Parameter should be a number (cdivfac)'); } @@ -209,7 +235,7 @@ // boolean operations on BINARY shares share.cxor_bit = function (cst) { - if (!(share.isConstant(cst))) { + if (!share.isConstant(cst)) { throw new Error('parameter should be a number (^)'); } if (!share.jiff.share_helpers['binary'](cst)) { @@ -223,7 +249,7 @@ return reduced_xor.legacy.cmult(magnitude); }; share.cor_bit = function (cst) { - if (!(share.isConstant(cst))) { + if (!share.isConstant(cst)) { throw new Error('parameter should be a number (|)'); } if (!share.jiff.share_helpers['binary'](cst)) { @@ -283,17 +309,13 @@ }; // secret and constant comparisons - var comparisons = [ - 'slt', 'slteq', 'sgt', 'sgteq', 'seq', 'sneq', - 'clt', 'clteq', 'cgt', 'cgteq', 'ceq', 'cneq', - 'lt_halfprime' - ]; + var comparisons = ['slt', 'slteq', 'sgt', 'sgteq', 'seq', 'sneq', 'clt', 'clteq', 'cgt', 'cgteq', 'ceq', 'cneq', 'lt_halfprime']; for (i = 0; i < comparisons.length; i++) { key = comparisons[i]; share[key] = (function (key, i) { return function () { if (i > 5 && i < 12) { - if (!(share.isConstant(arguments[0]))) { + if (!share.isConstant(arguments[0])) { throw new Error('Parameter should be a number (' + key + ')'); } arguments[0] = share.jiff.helpers.BigNumber(arguments[0]); @@ -328,7 +350,7 @@ return increased.legacy.sdiv(o, l, op_id); }; share.cdiv = function (cst, op_id) { - if (!(share.isConstant(cst))) { + if (!share.isConstant(cst)) { throw new Error('parameter should be a number (/)'); } if (op_id == null) { @@ -412,7 +434,11 @@ } if (base_instance.free_digits < options.decimal_digits) { if (!(options.warn === false)) { - console.log('Warning: Fixedpoint extension: not enough free_digits to perform secret multiplications/divisions/mod or constant multiplications/divisions against non-integer constants safely. Need ' + (options.decimal_digits - base_instance.free_digits) + ' more digits in Zp.'); + console.log( + 'Warning: Fixedpoint extension: not enough free_digits to perform secret multiplications/divisions/mod or constant multiplications/divisions against non-integer constants safely. Need ' + + (options.decimal_digits - base_instance.free_digits) + + ' more digits in Zp.' + ); } base_instance.free_digits = 0; } @@ -446,7 +472,6 @@ v = base_instance.helpers.BigNumber(v); var str = v.toFixed(base_instance.decimal_digits, base_instance.helpers._BigNumber.ROUND_FLOOR); return base_instance.helpers.BigNumber(str); - }; // Speed up calculating certain popular inverses by pre-computing @@ -480,7 +505,7 @@ }; /* changes to preprocessing */ - var previous_namespace = base_instance.extensions[base_instance.extensions.indexOf(exports.name)-1]; + var previous_namespace = base_instance.extensions[base_instance.extensions.indexOf(exports.name) - 1]; var optional_div = function (threshold, receivers_list, compute_list, Zp, op_id, params) { if (params.div === false) { params.ignore = true; @@ -495,22 +520,16 @@ }; base_instance.preprocessing_function_map[exports.name] = { - cmult: [ - { op: 'cdiv', op_id: '', namespace: previous_namespace, handler: optional_div } - ], + cmult: [{ op: 'cdiv', op_id: '', namespace: previous_namespace, handler: optional_div }], smult: [ { op: 'smult', op_id: '', namespace: previous_namespace }, { op: 'cdiv', op_id: ':reduce', namespace: previous_namespace, handler: optional_div } ], - smult_bgw: [ - { op: 'cdiv', op_id: ':reduce', namespace: previous_namespace, handler: optional_div } - ], + smult_bgw: [{ op: 'cdiv', op_id: ':reduce', namespace: previous_namespace, handler: optional_div }], - floor: [ - { op: 'cdiv', op_id: '', namespace: previous_namespace, handler: cdiv_constant } - ] + floor: [{ op: 'cdiv', op_id: '', namespace: previous_namespace, handler: cdiv_constant }] }; /* HOOKS */ @@ -521,4 +540,4 @@ // Expose API exports.make_jiff = make_jiff; -}((typeof exports === 'undefined' ? this.jiff_fixedpoint = {} : exports), typeof exports !== 'undefined')); +})(typeof exports === 'undefined' ? (this.jiff_fixedpoint = {}) : exports, typeof exports !== 'undefined'); diff --git a/lib/ext/jiff-client-negativenumber.js b/lib/ext/jiff-client-negativenumber.js index 6d9cbe7ef..d696f36e2 100644 --- a/lib/ext/jiff-client-negativenumber.js +++ b/lib/ext/jiff-client-negativenumber.js @@ -26,13 +26,39 @@ // Keep a copy of the previous implementation of changed primitives share.negative_legacy = {}; - var internals = ['cadd', 'csub', 'cmult', - 'sadd', 'ssub', 'smult', 'smult_bgw', - 'cdivfac', 'cdiv', 'sdiv', 'smod', - 'cxor_bit', 'sxor_bit', 'cor_bit', 'sor_bit', 'not', - 'slt', 'slteq', 'sgt', 'sgteq', 'seq', 'sneq', - 'clt', 'clteq', 'cgt', 'cgteq', 'ceq', 'cneq', - 'lt_halfprime', 'if_else', 'cpow' ]; + var internals = [ + 'cadd', + 'csub', + 'cmult', + 'sadd', + 'ssub', + 'smult', + 'smult_bgw', + 'cdivfac', + 'cdiv', + 'sdiv', + 'smod', + 'cxor_bit', + 'sxor_bit', + 'cor_bit', + 'sor_bit', + 'not', + 'slt', + 'slteq', + 'sgt', + 'sgteq', + 'seq', + 'sneq', + 'clt', + 'clteq', + 'cgt', + 'cgteq', + 'ceq', + 'cneq', + 'lt_halfprime', + 'if_else', + 'cpow' + ]; for (var i = 0; i < internals.length; i++) { var key = internals[i]; share.negative_legacy[key] = share[key].bind(share); @@ -140,17 +166,13 @@ }; // secret and constant comparisons - var comparisons = [ - 'slt', 'slteq', 'sgt', 'sgteq', 'seq', 'sneq', - 'clt', 'clteq', 'cgt', 'cgteq', 'ceq', 'cneq', - 'lt_halfprime' - ]; + var comparisons = ['slt', 'slteq', 'sgt', 'sgteq', 'seq', 'sneq', 'clt', 'clteq', 'cgt', 'cgteq', 'ceq', 'cneq', 'lt_halfprime']; for (i = 0; i < comparisons.length; i++) { key = comparisons[i]; share[key] = (function (key, i) { return function () { if (i > 5 && i < 12) { - if (!(share.isConstant(arguments[0]))) { + if (!share.isConstant(arguments[0])) { throw new Error('Parameter should be a number (' + key + ')'); } arguments[0] = jiff.share_helpers['+'](offset, arguments[0]); @@ -175,7 +197,7 @@ // Divisions share.cdivfac = function (cst, op_id) { - if (!(share.isConstant(cst))) { + if (!share.isConstant(cst)) { throw new Error('Parameter should be a number (cdivfac)'); } if (op_id == null) { @@ -201,15 +223,17 @@ var signUnit = selfNegative.icmult(-2).icadd(1); // if negative this is -1, if positive this is 1 // o is positive - if (!otherNegative) { // only need to correct for if share is negative + if (!otherNegative) { + // only need to correct for if share is negative result = result.ismult(signUnit, op_id + ':cor1'); - } else { // o is negative, correct if share is positive + } else { + // o is negative, correct if share is positive result = result.ismult(signUnit.icmult(-1), op_id + ':cor1'); } return result.negative_legacy.cadd(offset); }; share.cdiv = function (cst, op_id, floor_down) { - if (!(share.isConstant(cst))) { + if (!share.isConstant(cst)) { throw new Error('Parameter should be a number (cdiv)'); } if (op_id == null) { @@ -232,7 +256,8 @@ selfNegative = reduce_representation(selfNegative); var signUnit = selfNegative.icmult(-2).icadd(1); // if negative this is -1, if positive this is 1 var result; - if (!otherNegative) { // only need to correct for if share is negative + if (!otherNegative) { + // only need to correct for if share is negative result = resultAbs.ismult(signUnit, op_id + ':cor1'); } else { result = resultAbs.ismult(signUnit.icmult(-1), op_id + ':cor1'); @@ -240,9 +265,11 @@ result = result.negative_legacy.cadd(offset); // Floor correction - if (floor_down === false) { // Round to zero + if (floor_down === false) { + // Round to zero return result; - } else { // Round down + } else { + // Round down var magnitude = hasFixedPoint ? share.jiff.helpers.magnitude(share.jiff.decimal_digits) : 1; magnitude = cstAbs.toString().indexOf('.') > -1 ? magnitude : 1; magnitude = hasBigNumber ? share.jiff.helpers.BigNumber(magnitude) : magnitude; @@ -252,7 +279,7 @@ var xorNegative = selfNegative.icxor_bit(otherNegative ? 1 : 0); // we must correct if (1) need rounding (i.e. cst does not divide share) (2) xorNegative (i.e. result is negative) - var and = need_round.ismult(xorNegative, op_id+':floor:and'); + var and = need_round.ismult(xorNegative, op_id + ':floor:and'); return result.issub(and); } }; @@ -262,10 +289,10 @@ } // Absolute value of share and o - var shareAbs = share.iabs(op_id+':abs1', true); + var shareAbs = share.iabs(op_id + ':abs1', true); var negative = shareAbs.isNegative; shareAbs = shareAbs.result.negative_legacy.csub(offset); - var oAbs = o.iabs(op_id+':abs2').negative_legacy.csub(offset); + var oAbs = o.iabs(op_id + ':abs2').negative_legacy.csub(offset); // |share| % |o| var result = shareAbs.negative_legacy.smod(oAbs, l, op_id + ':smod'); @@ -273,7 +300,7 @@ // Sign correction negative = negative.icmult(-2).icadd(1); // if negative = -1, else = 1 - result = result.ismult(negative, op_id+':smult'); + result = result.ismult(negative, op_id + ':smult'); return result.negative_legacy.cadd(offset); }; share.sdiv = function (o, l, op_id, floor_down) { @@ -302,11 +329,13 @@ result = result.negative_legacy.cadd(offset); // Floor correction - if (floor_down === false) { // Round to zero + if (floor_down === false) { + // Round to zero return result; - } else { // Round down + } else { + // Round down var magnitude = hasFixedPoint ? share.jiff.helpers.magnitude(share.jiff.decimal_digits) : 1; - var need_round = resultAbs.ismult(otherAbs, op_id+':floor:smult').isneq(shareAbs.icmult(magnitude), op_id+':floor:sneq'); + var need_round = resultAbs.ismult(otherAbs, op_id + ':floor:smult').isneq(shareAbs.icmult(magnitude), op_id + ':floor:sneq'); // we must correct if (1) need rounding (i.e. cst does not divide share) (2) xorNegative (i.e. result is negative) var and = xorNegative.ismult(need_round, op_id + ':floor:and'); @@ -386,10 +415,11 @@ msg += 'Need Zp >= ' + maxNoMult.toString() + ' to fit parameters.'; throw msg; } - var maxWithMult = jiff.helpers.magnitude(jiff.integer_digits + 2*jiff.decimal_digits).times(2); + var maxWithMult = jiff.helpers.magnitude(jiff.integer_digits + 2 * jiff.decimal_digits).times(2); if (!maxWithMult.lte(jiff.Zp) && !(options.warn === false)) { - var warnMsg = 'Warning: Fixedpoint|NegativeNumber extension: not enough free_digits to perform secret multiplications/divisions or constant multiplications/divisions against non-integer constants safely. '; - warnMsg += 'Need Zp >= ' +maxWithMult.toString(); + var warnMsg = + 'Warning: Fixedpoint|NegativeNumber extension: not enough free_digits to perform secret multiplications/divisions or constant multiplications/divisions against non-integer constants safely. '; + warnMsg += 'Need Zp >= ' + maxWithMult.toString(); console.log(warnMsg); } } else { @@ -419,7 +449,7 @@ }; /* changes to preprocessing */ - var previous_namespace = jiff.extensions[jiff.extensions.indexOf(exports.name)-1]; + var previous_namespace = jiff.extensions[jiff.extensions.indexOf(exports.name) - 1]; var should_floor_down_preprocessing = function (threshold, receivers_list, compute_list, Zp, op_id, params) { if (params.floor_down === false) { params.ignore = true; @@ -469,5 +499,4 @@ // Expose API exports.make_jiff = make_jiff; - -}((typeof exports === 'undefined' ? this.jiff_negativenumber = {} : exports), typeof exports !== 'undefined')); +})(typeof exports === 'undefined' ? (this.jiff_negativenumber = {}) : exports, typeof exports !== 'undefined'); diff --git a/lib/ext/jiff-client-performance.js b/lib/ext/jiff-client-performance.js index 017178143..61bb93941 100644 --- a/lib/ext/jiff-client-performance.js +++ b/lib/ext/jiff-client-performance.js @@ -22,5 +22,5 @@ } return jiff_instance; - } -}((typeof exports === 'undefined' ? this.jiff_performance = {} : exports), typeof exports !== 'undefined')); + }; +})(typeof exports === 'undefined' ? (this.jiff_performance = {}) : exports, typeof exports !== 'undefined'); diff --git a/lib/ext/jiff-client-restful.js b/lib/ext/jiff-client-restful.js index 9b89b8a0b..f20bd0a5c 100644 --- a/lib/ext/jiff-client-restful.js +++ b/lib/ext/jiff-client-restful.js @@ -140,10 +140,7 @@ jiff.hooks.execute_array_hooks('afterOperation', [jiff, 'disconnect', {}], -1); }; jiff.socket.is_empty = function () { - return jiff.socket.mailbox.pending == null - && jiff.socket.mailbox.current.initialization == null - && jiff.socket.mailbox.current.messages.length === 0 - && jiff.counters.pending_opens === 0; + return jiff.socket.mailbox.pending == null && jiff.socket.mailbox.current.initialization == null && jiff.socket.mailbox.current.messages.length === 0 && jiff.counters.pending_opens === 0; }; // aliases and empty methods @@ -161,7 +158,7 @@ // Use this as the socket.io dependency in jiff-client // if you want to remove socket.io completely. exports.io = function () { - var listeners = { connect : [ 0 ] }; + var listeners = { connect: [0] }; var self = {}; self.on = function (event, listener) { if (listeners[event] == null) { @@ -187,9 +184,9 @@ } // Default parameters - options.pollInterval = (options.pollInterval == null ? 0 : options.pollInterval); - options.flushInterval = (options.flushInterval == null ? 250 : options.flushInterval); - jiff.maxBatchSize = (options.maxBatchSize == null) ? 150 : options.maxBatchSize; + options.pollInterval = options.pollInterval == null ? 0 : options.pollInterval; + options.flushInterval = options.flushInterval == null ? 250 : options.flushInterval; + jiff.maxBatchSize = options.maxBatchSize == null ? 150 : options.maxBatchSize; // Stop the socket just in case it got connected somehow (if user forgot to disabled autoConnect) if (jiff.socket == null) { @@ -254,7 +251,7 @@ body = JSON.parse(body); if (!body['success']) { - execute_listeners(jiff, 'error', JSON.stringify({label: body['label'], error: body['error']})); + execute_listeners(jiff, 'error', JSON.stringify({ label: body['label'], error: body['error'] })); return; } @@ -303,4 +300,4 @@ return jiff; }; -}((typeof exports === 'undefined' ? this.jiff_restAPI = {} : exports), typeof exports !== 'undefined')); +})(typeof exports === 'undefined' ? (this.jiff_restAPI = {}) : exports, typeof exports !== 'undefined'); diff --git a/lib/ext/jiff-client-websockets.js b/lib/ext/jiff-client-websockets.js index 48f41691c..d6b2b7de5 100644 --- a/lib/ext/jiff-client-websockets.js +++ b/lib/ext/jiff-client-websockets.js @@ -10,8 +10,6 @@ * When using this extension in browser, "/dist/jiff-client-websockets.js" must be loaded in client.html instead of this file. */ - - (function (exports, node) { /** * The name of this extension: 'websocket' @@ -29,19 +27,18 @@ ws = require('ws'); } else { if (typeof WebSocket !== 'undefined') { - ws = WebSocket + ws = WebSocket; } else if (typeof MozWebSocket !== 'undefined') { - ws = MozWebSocket + ws = MozWebSocket; } else if (typeof global !== 'undefined') { - ws = global.WebSocket || global.MozWebSocket + ws = global.WebSocket || global.MozWebSocket; } else if (typeof window !== 'undefined') { - ws = window.WebSocket || window.MozWebSocket + ws = window.WebSocket || window.MozWebSocket; } else if (typeof self !== 'undefined') { - ws = self.WebSocket || self.MozWebSocket + ws = self.WebSocket || self.MozWebSocket; } } - // Take the jiff-client base instance and options for this extension, and use them // to construct an instance for this extension. function make_jiff(base_instance, options) { @@ -69,7 +66,6 @@ // Public keys were updated on the server, and it sent us the updates function publicKeysChanged(msg, callback) { - msg = JSON.parse(msg); msg = jiffClient.hooks.execute_array_hooks('afterOperation', [jiffClient, 'public_keys', msg], 2); @@ -78,7 +74,6 @@ // Setup receiving matching shares function share(msg, callback) { - // parse message var json_msg = JSON.parse(msg); var sender_id = json_msg['party_id']; @@ -149,7 +144,7 @@ this.socket.onclose = function (reason) { socketClose(reason.code); - } + }; /** * In every message sent over ws, we will send along with it a socketProtocol string @@ -190,14 +185,12 @@ default: console.log('Uknown protocol, ' + msg.socketProtocol + ', received'); } - } - + }; }; /* Overwrite the socketConnect function from jiff-client.js */ jiff.socketConnect = function (JIFFClientInstance) { - if (options.__internal_socket == null) { /** * Socket wrapper between this instance and the server, based on sockets.io @@ -231,9 +224,8 @@ JIFFClientInstance.socket.send(JSON.stringify({ socketProtocol: 'initialization', data: msg })); }; - JIFFClientInstance.initSocket(); - } + }; /* Functions that overwrite client/socket/mailbox.js functionality */ @@ -241,13 +233,12 @@ // Create plain socket io object which we will wrap in this var socket; if (jiffClient.hostname.startsWith('http')) { - var modifiedHostName = 'ws' + jiffClient.hostname.substring(jiffClient.hostname.indexOf(':')) - socket = new ws(modifiedHostName) + var modifiedHostName = 'ws' + jiffClient.hostname.substring(jiffClient.hostname.indexOf(':')); + socket = new ws(modifiedHostName); } else { socket = new ws(jiffClient.hostname); } - socket.old_disconnect = socket.close; socket.mailbox = linkedList(); // for outgoing messages @@ -272,7 +263,6 @@ // emit the message, if an acknowledgment is received, remove it from mailbox this.send(JSON.stringify({ socketProtocol: label, data: msg }), null, function (status) { - self.mailbox.remove(mailbox_pointer); if (self.is_empty() && self.empty_deferred != null) { @@ -284,7 +274,6 @@ } }); } - } function resend_mailbox() { @@ -301,21 +290,16 @@ this.safe_emit(label, msg); current_node = current_node.next; } - } function disconnect() { - this.jiffClient.hooks.execute_array_hooks('beforeOperation', [this.jiffClient, 'disconnect', {}], -1); - this.old_disconnect.apply(this, arguments); } function safe_disconnect(free, callback) { - if (this.is_empty()) { - if (free) { this.jiffClient.free(); free = false; @@ -331,21 +315,17 @@ this.empty_deferred = new this.jiffClient.helpers.Deferred(); this.empty_deferred.promise.then(this.safe_disconnect.bind(this, free, callback)); - } function is_empty() { return this.mailbox.head == null && this.jiffClient.counters.pending_opens === 0; - } /* PREPROCESSING IS THE SAME */ jiff.preprocessing_function_map[exports.name] = {}; - return jiff; } // Expose the API for this extension. exports.make_jiff = make_jiff; - -}((typeof exports === 'undefined' ? this.jiff_websockets = {} : exports), typeof exports !== 'undefined')); +})(typeof exports === 'undefined' ? (this.jiff_websockets = {}) : exports, typeof exports !== 'undefined'); diff --git a/lib/ext/jiff-server-bignumber.js b/lib/ext/jiff-server-bignumber.js index 4f21b84cb..5a254c02a 100644 --- a/lib/ext/jiff-server-bignumber.js +++ b/lib/ext/jiff-server-bignumber.js @@ -2,7 +2,7 @@ global.crypto = require('crypto'); var client_bignumber = require('./jiff-client-bignumber.js'); var BigNumber = require('bignumber.js'); -BigNumber.config({CRYPTO: true}); +BigNumber.config({ CRYPTO: true }); function secureRandom(max) { var precision = max.toString().length; @@ -122,4 +122,4 @@ function default_preprocessing() { return { secrets: numbers }; } }; -} \ No newline at end of file +} diff --git a/lib/ext/jiff-server-restful.js b/lib/ext/jiff-server-restful.js index 36fdc900a..bc51d8276 100644 --- a/lib/ext/jiff-server-restful.js +++ b/lib/ext/jiff-server-restful.js @@ -15,7 +15,7 @@ module.exports = { return; } - var maxBatchSize = (options.maxBatchSize == null) ? 150 : options.maxBatchSize; + var maxBatchSize = options.maxBatchSize == null ? 150 : options.maxBatchSize; if (options.routes == null) { options.routes = {}; } @@ -167,14 +167,15 @@ module.exports = { // Execute start hooks try { - msg = jiff.hooks.execute_array_hooks('beforeOperation', [jiff, 'poll', msg['computation_id'], msg['from_id'], msg], 4); + msg = jiff.hooks.execute_array_hooks('beforeOperation', [jiff, 'poll', msg['computation_id'], msg['from_id'], msg], 4); } catch (err) { - return res.json({ success: false, label: 'poll', error: typeof(err) === 'string' ? err : err.message }); + return res.json({ success: false, label: 'poll', error: typeof err === 'string' ? err : err.message }); } // First: attempt to initialize if needed. var output = jiff.restful.initializeParty(msg); - if (!output.success) { // failed to initialize + if (!output.success) { + // failed to initialize return res.json({ success: false, label: 'initialization', error: output.error }); } diff --git a/lib/ext/jiff-server-websockets.js b/lib/ext/jiff-server-websockets.js index 3dd79e59a..eea384bed 100644 --- a/lib/ext/jiff-server-websockets.js +++ b/lib/ext/jiff-server-websockets.js @@ -20,7 +20,6 @@ var $ = require('jquery-deferred'); */ exports.name = 'websocket'; - // Take the jiff-server base instance and options for this extension, and use them // to construct an instance for this extension. function make_jiff(base_instance, options) { @@ -39,7 +38,7 @@ var $ = require('jquery-deferred'); computationId: {}, partyId: {}, clientSocket: {} - } + }; /* Edit initComputation and freeComputation to use the new socketMaps structure */ jiff.initComputation = function (computation_id, party_id, party_count) { @@ -78,7 +77,6 @@ var $ = require('jquery-deferred'); delete this.cryptoMap[computation_id]; }; - /* Functions that overwrite server/socket.js functionality */ /** @@ -96,7 +94,6 @@ var $ = require('jquery-deferred'); this.io = wss; this.io.on('connection', function (socket, req) { - jiff.hooks.log(jiff, 'user connected'); socket.id = req.headers['sec-websocket-key']; @@ -144,7 +141,6 @@ var $ = require('jquery-deferred'); var computation_id = jiff.socketMaps.computationId[socket.id]; var from_id = jiff.socketMaps.partyId[socket.id]; - var output = jiff.handlers.share(computation_id, from_id, msg); if (!output.success) { var errorMsg = JSON.stringify({ label: 'share', error: output.error }); @@ -264,7 +260,6 @@ var $ = require('jquery-deferred'); console.log('Unknown protocol received'); } }); - }); }; @@ -306,9 +301,6 @@ var $ = require('jquery-deferred'); } }; - - - /** Make sure that our socket is closed in case one was created * before the exension was able to execute. Then, open the server * for connections to clients. @@ -322,5 +314,4 @@ var $ = require('jquery-deferred'); } // Expose the API for this extension. exports.make_jiff = make_jiff; - -}((typeof exports === 'undefined' ? this.jiffserver_websockets = {} : exports), typeof exports !== 'undefined')); \ No newline at end of file +})(typeof exports === 'undefined' ? (this.jiffserver_websockets = {}) : exports, typeof exports !== 'undefined'); diff --git a/lib/jiff-client.js b/lib/jiff-client.js index 16ff9fff1..47121b2c7 100644 --- a/lib/jiff-client.js +++ b/lib/jiff-client.js @@ -166,10 +166,10 @@ function JIFFClient(hostname, computation_id, options) { this.options = options; - // Parse and verify options options.maxInitializationRetries = options.maxInitializationRetries || constants.maxInitializationRetries; - if (typeof(options.Zp) === 'number' && options.safemod !== false) { // big numbers are checked by extension + if (typeof options.Zp === 'number' && options.safemod !== false) { + // big numbers are checked by extension if (!this.helpers.is_prime(options.Zp)) { throw new Error('Zp = ' + options.Zp + ' is not prime. Please use a prime number for the modulus or set safemod to false.'); } @@ -227,7 +227,7 @@ function JIFFClient(hostname, computation_id, options) { * Flags whether to use the server as a fallback for objects that were not pre-processed properly * @type {!boolean} */ - this.crypto_provider = (options.crypto_provider === true); + this.crypto_provider = options.crypto_provider === true; /** * Stores messages that are received with a signature prior to acquiring the public keys of the sender. @@ -427,9 +427,7 @@ function JIFFClient(hostname, computation_id, options) { // set up counters for op_ids counters(this); - this.socketConnect = function (JIFFClientInstance) { - if (options.__internal_socket == null) { /** * Socket wrapper between this instance and the server, based on sockets.io @@ -445,9 +443,8 @@ function JIFFClient(hostname, computation_id, options) { JIFFClientInstance.initSocket(); - JIFFClientInstance.socket.connect(); - } + }; /** * Connect to the server and starts listening. @@ -473,7 +470,6 @@ function JIFFClient(hostname, computation_id, options) { } } - // Add socket event handlers to prototype socketEvents(JIFFClient); diff --git a/lib/jiff-server.js b/lib/jiff-server.js index be3214690..c9f85b944 100644 --- a/lib/jiff-server.js +++ b/lib/jiff-server.js @@ -120,4 +120,4 @@ extensions(JIFFServer); compute(JIFFServer); socket(JIFFServer); -mailbox.initPrototype(JIFFServer); \ No newline at end of file +mailbox.initPrototype(JIFFServer); diff --git a/lib/server/compute.js b/lib/server/compute.js index 37594463d..9d24acb7d 100644 --- a/lib/server/compute.js +++ b/lib/server/compute.js @@ -79,8 +79,8 @@ InternalSocket.prototype.emit = function (label, msg) { if (['share', 'open', 'custom', 'crypto_provider'].indexOf(label) > -1) { var output = this.jiff.handlers[label](this.computation_id, from_id, msg); if (!output.success) { - var errorMsg = JSON.stringify({label: label, error: output.error}); + var errorMsg = JSON.stringify({ label: label, error: output.error }); this.receive('error', errorMsg); } } -}; \ No newline at end of file +}; diff --git a/lib/server/constants.js b/lib/server/constants.js index c5099fdb6..b0e43ef94 100644 --- a/lib/server/constants.js +++ b/lib/server/constants.js @@ -1,4 +1,4 @@ module.exports = { PING_TIMEOUT: 5000, PING_INTERVAL: 25000 -}; \ No newline at end of file +}; diff --git a/lib/server/cryptoprovider.js b/lib/server/cryptoprovider.js index 2f2833086..88dfcbe60 100644 --- a/lib/server/cryptoprovider.js +++ b/lib/server/cryptoprovider.js @@ -16,14 +16,14 @@ CryptoProviderHandlers.prototype.triplet = function (jiff, computation_id, recei var a = jiff.helpers.random(Zp); var b = jiff.helpers.random(Zp); var c = (a * b) % Zp; - return {secrets: [a, b, c]}; + return { secrets: [a, b, c] }; }; CryptoProviderHandlers.prototype.quotient = function (jiff, computation_id, receivers_list, threshold, Zp, params) { var constant = params['constant']; var noise = jiff.helpers.random(Zp); var quotient = Math.floor(noise / constant); - return {secrets: [noise, quotient]}; + return { secrets: [noise, quotient] }; }; CryptoProviderHandlers.prototype.numbers = function (jiff, computation_id, receivers_list, threshold, Zp, params) { @@ -58,7 +58,7 @@ CryptoProviderHandlers.prototype.numbers = function (jiff, computation_id, recei } } - return {secrets: numbers}; + return { secrets: numbers }; }; -module.exports = CryptoProviderHandlers; \ No newline at end of file +module.exports = CryptoProviderHandlers; diff --git a/lib/server/datastructures/intervals.js b/lib/server/datastructures/intervals.js index 735a06315..162812bdb 100644 --- a/lib/server/datastructures/intervals.js +++ b/lib/server/datastructures/intervals.js @@ -5,7 +5,7 @@ // intervals are inclusive of endpoints: [ start, end ]. function intervals(start, end) { var obj = {}; - obj.val = [{start: start, end: end}]; + obj.val = [{ start: start, end: end }]; obj.is_free = function (point) { return find_point(obj.val, point) > -1; }; @@ -34,12 +34,12 @@ function remove_point(intervals, point) { if (current_interval.start === current_interval.end) { intervals.splice(index, 1); } else if (current_interval.start === point) { - intervals[index] = {start: current_interval.start + 1, end: current_interval.end}; + intervals[index] = { start: current_interval.start + 1, end: current_interval.end }; } else if (current_interval.end === point) { - intervals[index] = {start: current_interval.start, end: current_interval.end - 1}; + intervals[index] = { start: current_interval.start, end: current_interval.end - 1 }; } else { - intervals[index] = {start: current_interval.start, end: point - 1}; - intervals.splice(index+1, 0, {start: point + 1, end: current_interval.end}); + intervals[index] = { start: current_interval.start, end: point - 1 }; + intervals.splice(index + 1, 0, { start: point + 1, end: current_interval.end }); } return true; @@ -65,7 +65,7 @@ function find_point(intervals, point) { } function interval_contains(index) { - return (intervals[index].start <= point && point <= intervals[index].end); + return intervals[index].start <= point && point <= intervals[index].end; } function go_left(index) { diff --git a/lib/server/extensions.js b/lib/server/extensions.js index 501fe9049..684f72ffb 100644 --- a/lib/server/extensions.js +++ b/lib/server/extensions.js @@ -27,4 +27,4 @@ module.exports = function (JIFFServer) { }; JIFFServer.prototype.extension_applied = function (name, options) {}; -}; \ No newline at end of file +}; diff --git a/lib/server/handlers.js b/lib/server/handlers.js index 047d2e0f0..d6a24d5a7 100644 --- a/lib/server/handlers.js +++ b/lib/server/handlers.js @@ -33,23 +33,25 @@ module.exports = function (jiffServer) { party_count = hook_result.party_count; party_id = hook_result.party_id; } catch (err) { - return { success: false, error: typeof(err) === 'string' ? err : err.message }; + return { success: false, error: typeof err === 'string' ? err : err.message }; } // Fourth: Make sure party id is fine. // if party_id is given, try to reserve it if free. // if no party_id is given, generate a new free one. - if (party_id != null) { // party_id is given, check validity + if (party_id != null) { + // party_id is given, check validity if (party_id !== 's1' && !jiffServer.computationMaps.spareIds[computation_id].is_free(party_id)) { // ID is not spare, but maybe it has disconnected and trying to reconnect? maybe a mistaken client? maybe malicious? // Cannot handle all possible applications logic, rely on hooks to allow developers to inject case-specific logic. try { party_id = jiffServer.hooks.onInitializeUsedId(jiffServer, computation_id, party_id, party_count, msg); } catch (err) { - return { success: false, error: typeof(err) === 'string' ? err : err.message }; + return { success: false, error: typeof err === 'string' ? err : err.message }; } } - } else { // generate spare party_id + } else { + // generate spare party_id party_id = jiffServer.computationMaps.spareIds[computation_id].create_free(computation_id, msg); } @@ -74,7 +76,8 @@ module.exports = function (jiffServer) { jiffServer.handlers.storeAndSendPublicKey = function (computation_id, party_id, msg) { // store public key in key map var tmp = jiffServer.computationMaps.keys[computation_id]; - if (tmp['s1'] == null) { // generate public and secret key for server if they don't exist + if (tmp['s1'] == null) { + // generate public and secret key for server if they don't exist var genkey = jiffServer.hooks.generateKeyPair(jiffServer); jiffServer.computationMaps.secretKeys[computation_id] = genkey.secret_key; tmp['s1'] = genkey.public_key; @@ -91,7 +94,7 @@ module.exports = function (jiffServer) { keymap_to_send[key] = jiffServer.hooks.dumpKey(jiffServer, jiffServer.computationMaps.keys[computation_id][key]); } } - var broadcast_message = JSON.stringify({public_keys: keymap_to_send}); + var broadcast_message = JSON.stringify({ public_keys: keymap_to_send }); // Send the public keys to all previously connected parties, except the party that caused this update var send_to_parties = jiffServer.computationMaps.clientIds[computation_id]; @@ -110,7 +113,7 @@ module.exports = function (jiffServer) { try { msg = jiffServer.hooks.execute_array_hooks('beforeOperation', [jiffServer, 'share', computation_id, from_id, msg], 4); } catch (err) { - return { success: false, error: typeof(err) === 'string' ? err : err.message }; + return { success: false, error: typeof err === 'string' ? err : err.message }; } var to_id = msg['party_id']; @@ -128,7 +131,7 @@ module.exports = function (jiffServer) { try { msg = jiffServer.hooks.execute_array_hooks('beforeOperation', [jiffServer, 'open', computation_id, from_id, msg], 4); } catch (err) { - return { success: false, error: typeof(err) === 'string' ? err : err.message }; + return { success: false, error: typeof err === 'string' ? err : err.message }; } var to_id = msg['party_id']; @@ -146,7 +149,7 @@ module.exports = function (jiffServer) { try { msg = jiffServer.hooks.execute_array_hooks('beforeOperation', [jiffServer, 'crypto_provider', computation_id, from_id, msg], 4); } catch (err) { - return {success: false, error: typeof(err) === 'string' ? err : err.message}; + return { success: false, error: typeof err === 'string' ? err : err.message }; } // request/generate triplet share @@ -189,7 +192,7 @@ module.exports = function (jiffServer) { threshold: threshold, Zp: Zp, values: result.values, - shares: result.shares[from_id] // send only shares allocated to requesting party + shares: result.shares[from_id] // send only shares allocated to requesting party }; // clean up memory @@ -215,7 +218,7 @@ module.exports = function (jiffServer) { try { msg = jiffServer.hooks.execute_array_hooks('beforeOperation', [jiffServer, 'custom', computation_id, from_id, msg], 4); } catch (err) { - return { success: false, error: typeof(err) === 'string' ? err : err.message }; + return { success: false, error: typeof err === 'string' ? err : err.message }; } //message already parsed @@ -234,7 +237,7 @@ module.exports = function (jiffServer) { try { jiffServer.hooks.execute_array_hooks('beforeFree', [jiffServer, computation_id, party_id, msg], -1); } catch (err) { - return { success: false, error: typeof(err) === 'string' ? err : err.message }; + return { success: false, error: typeof err === 'string' ? err : err.message }; } jiffServer.computationMaps.freeParties[computation_id][party_id] = true; @@ -247,4 +250,4 @@ module.exports = function (jiffServer) { return { success: true }; }; -}; \ No newline at end of file +}; diff --git a/lib/server/hooks.js b/lib/server/hooks.js index 59ea9a469..7895193e4 100644 --- a/lib/server/hooks.js +++ b/lib/server/hooks.js @@ -9,7 +9,7 @@ function ServerHooks(jiffServer) { // avoid sharing aliases to the same array for (hook in ServerHooks.prototype) { - if (ServerHooks.prototype.hasOwnProperty(hook) && typeof(ServerHooks.prototype[hook].length) === 'number' && ServerHooks.prototype[hook].slice) { + if (ServerHooks.prototype.hasOwnProperty(hook) && typeof ServerHooks.prototype[hook].length === 'number' && ServerHooks.prototype[hook].slice) { this[hook] = ServerHooks.prototype[hook].slice(); } } @@ -34,36 +34,41 @@ ServerHooks.prototype.log = function (jiff) { }; // Lifecycle array hooks -ServerHooks.prototype.beforeInitialization = [function (jiff, computation_id, msg, params) { - var party_count = params.party_count; - // validate party_count - if (party_count == null) { // no party count given or saved. - throw new Error('party count is not specified nor pre-saved'); - } else if (party_count < 1) { // Too small - throw new Error('party count is less than 1'); - } else if (jiff.computationMaps.maxCount[computation_id] != null && party_count !== jiff.computationMaps.maxCount[computation_id]) { - // contradicting values - throw new Error('contradicting party count'); - } +ServerHooks.prototype.beforeInitialization = [ + function (jiff, computation_id, msg, params) { + var party_count = params.party_count; + // validate party_count + if (party_count == null) { + // no party count given or saved. + throw new Error('party count is not specified nor pre-saved'); + } else if (party_count < 1) { + // Too small + throw new Error('party count is less than 1'); + } else if (jiff.computationMaps.maxCount[computation_id] != null && party_count !== jiff.computationMaps.maxCount[computation_id]) { + // contradicting values + throw new Error('contradicting party count'); + } - // validate party_id - var party_id = params.party_id; - if (party_id != null) { // party_id is given, check validity - if (party_id !== 's1') { - if (isNaN(party_id) || party_id <= 0 || party_id > party_count) { - throw new Error('Invalid party ID: not a valid number'); + // validate party_id + var party_id = params.party_id; + if (party_id != null) { + // party_id is given, check validity + if (party_id !== 's1') { + if (isNaN(party_id) || party_id <= 0 || party_id > party_count) { + throw new Error('Invalid party ID: not a valid number'); + } + } + } else { + // party_id is null, must generate a new free id, if the computation is full we have a problem! + if (jiff.computationMaps.clientIds[computation_id] != null && jiff.computationMaps.clientIds[computation_id].length === jiff.computationMaps.maxCount[computation_id]) { + throw new Error('Maximum parties capacity reached'); } } - } else { - // party_id is null, must generate a new free id, if the computation is full we have a problem! - if (jiff.computationMaps.clientIds[computation_id] != null && jiff.computationMaps.clientIds[computation_id].length === jiff.computationMaps.maxCount[computation_id]) { - throw new Error('Maximum parties capacity reached'); - } - } - // All is good - return params; -}]; + // All is good + return params; + } +]; ServerHooks.prototype.afterInitialization = []; ServerHooks.prototype.beforeOperation = []; @@ -99,9 +104,9 @@ ServerHooks.prototype.computeShares = shamir_share.jiff_compute_shares; ServerHooks.prototype.generateKeyPair = function (jiff) { if (jiff.sodium) { var key = jiff.sodium.crypto_box_keypair(); // this party's public and secret key - return {public_key: key.publicKey, secret_key: key.privateKey} + return { public_key: key.publicKey, secret_key: key.privateKey }; } else { - return {public_key: '', secret_key: ''} + return { public_key: '', secret_key: '' }; } }; @@ -130,7 +135,7 @@ ServerHooks.prototype.sliceMailbox = mailbox.hooks.sliceMailbox; // Executor ServerHooks.prototype.execute_array_hooks = function (hook_name, params, acc_index) { var arr = this[hook_name]; - arr = (arr == null ? [] : arr); + arr = arr == null ? [] : arr; for (var i = 0; i < arr.length; i++) { var result = arr[i].apply(this.jiff, params); @@ -143,4 +148,4 @@ ServerHooks.prototype.execute_array_hooks = function (hook_name, params, acc_ind } }; -module.exports = ServerHooks; \ No newline at end of file +module.exports = ServerHooks; diff --git a/lib/server/mailbox.js b/lib/server/mailbox.js index eeb6687bc..9929d83ca 100644 --- a/lib/server/mailbox.js +++ b/lib/server/mailbox.js @@ -9,7 +9,7 @@ exports.hooks = { } // add message to mailbox, return pointer - return computation_mailbox[to_id].add({label: label, msg: msg}); + return computation_mailbox[to_id].add({ label: label, msg: msg }); }, getFromMailbox: function (jiff, computation_id, party_id) { var computation_mailbox = jiff.mailbox[computation_id]; @@ -76,7 +76,7 @@ exports.initPrototype = function (JIFFServer) { JIFFServer.prototype.safe_emit = function (label, msg, computation_id, to_id) { var jiff = this; - if (to_id === 's1' ) { + if (to_id === 's1') { this.computation_instances_deferred[computation_id].then(function () { jiff.computation_instances_map[computation_id].socket.receive(label, msg); }); @@ -106,4 +106,4 @@ exports.initPrototype = function (JIFFServer) { this.emit(label, msg, computation_id, party_id, callback.bind(this, store_id)); } }; -}; \ No newline at end of file +}; diff --git a/lib/server/socket.js b/lib/server/socket.js index 7bf9c6bea..c576f7cf6 100644 --- a/lib/server/socket.js +++ b/lib/server/socket.js @@ -8,10 +8,13 @@ module.exports = function (JIFFServer) { var jiff = this; // socket io options - var socketOptions = Object.assign({ - pingTimeout: constants.PING_TIMEOUT, - pingInterval: constants.PING_INTERVAL - }, this.options.socketOptions); + var socketOptions = Object.assign( + { + pingTimeout: constants.PING_TIMEOUT, + pingInterval: constants.PING_INTERVAL + }, + this.options.socketOptions + ); // create socket io server and listen to connection this.io = io(this.http, socketOptions); @@ -47,7 +50,7 @@ module.exports = function (JIFFServer) { // send the mailbox with pending messages to the party. jiff.resend_mailbox(computation_id, party_id); } else { - jiff.io.to(socket.id).emit('error', JSON.stringify({label: 'initialization', error: output.error})); + jiff.io.to(socket.id).emit('error', JSON.stringify({ label: 'initialization', error: output.error })); } // END OF SOCKET SPECIFIC OUTPUT/CLEANUP }); @@ -61,7 +64,7 @@ module.exports = function (JIFFServer) { var output = jiff.handlers.share(computation_id, from_id, json_msg); if (!output.success) { - var errorMsg = JSON.stringify({label: 'share', error: output.error}); + var errorMsg = JSON.stringify({ label: 'share', error: output.error }); jiff.emit('error', errorMsg, computation_id, from_id); } }); @@ -75,7 +78,7 @@ module.exports = function (JIFFServer) { var output = jiff.handlers.open(computation_id, from_id, json_msg); if (!output.success) { - var errorMsg = JSON.stringify({label: 'open', error: output.error}); + var errorMsg = JSON.stringify({ label: 'open', error: output.error }); jiff.emit('error', errorMsg, computation_id, from_id); } }); @@ -89,7 +92,7 @@ module.exports = function (JIFFServer) { var output = jiff.handlers.custom(computation_id, from_id, json_msg); if (!output.success) { - var errorMsg = JSON.stringify({label: 'custom', error: output.error}); + var errorMsg = JSON.stringify({ label: 'custom', error: output.error }); jiff.emit('error', errorMsg, computation_id, from_id); } }); @@ -103,7 +106,7 @@ module.exports = function (JIFFServer) { var res = jiff.handlers.crypto_provider(computation_id, from_id, msg); if (!res.success) { - var errorMsg = JSON.stringify({label: 'crypto_provider', error: res.error}); + var errorMsg = JSON.stringify({ label: 'crypto_provider', error: res.error }); jiff.emit('error', errorMsg, computation_id, from_id); } }); @@ -132,7 +135,7 @@ module.exports = function (JIFFServer) { var output = jiff.handlers.free(computation_id, from_id, msg); if (!output.success) { - var errorMsg = JSON.stringify({label: 'free', error: output.error}); + var errorMsg = JSON.stringify({ label: 'free', error: output.error }); jiff.emit('error', errorMsg, computation_id, from_id); } @@ -144,4 +147,4 @@ module.exports = function (JIFFServer) { }); }); }; -}; \ No newline at end of file +}; diff --git a/package-lock.json b/package-lock.json index e8e4de0a5..f5be5dfaa 100644 --- a/package-lock.json +++ b/package-lock.json @@ -36,7 +36,8 @@ "marked": "^4.0.10", "minimist": "^1.2.0", "mocha": "^4.1.0", - "neptune-notebook": "^1.3.1" + "neptune-notebook": "^1.3.1", + "prettier": "3.2.5" } }, "node_modules/@babel/parser": { @@ -3402,6 +3403,21 @@ "node": ">= 0.8.0" } }, + "node_modules/prettier": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.5.tgz", + "integrity": "sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==", + "dev": true, + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, "node_modules/process": { "version": "0.11.10", "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=", @@ -7543,6 +7559,12 @@ "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", "dev": true }, + "prettier": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.5.tgz", + "integrity": "sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==", + "dev": true + }, "process": { "version": "0.11.10", "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=", diff --git a/package.json b/package.json index 60ce05a37..2e18dacf0 100644 --- a/package.json +++ b/package.json @@ -45,6 +45,8 @@ "fix-memory-limit": "cross-env LIMIT=4096 increase-memory-limit", "lint": "eslint .", "lint:fix": "eslint . --fix", + "prettier": "npx prettier . --check", + "prettier:fix": "npx prettier --write '**/*.{js,ts}'", "tutorial": "npm install && cd tutorials && node index.js", "build": "browserify lib/jiff-client.js --debug -s JIFFClient -o dist/jiff-client.js && browserify lib/ext/jiff-client-websockets.js --debug -s jiff_websockets -o dist/jiff-client-websockets.js" }, @@ -76,6 +78,7 @@ "marked": "^4.0.10", "minimist": "^1.2.0", "mocha": "^4.1.0", - "neptune-notebook": "^1.3.1" + "neptune-notebook": "^1.3.1", + "prettier": "3.2.5" } } diff --git a/tests/dev/2D_array/mpc.js b/tests/dev/2D_array/mpc.js index 44a0725df..95d9aacf7 100644 --- a/tests/dev/2D_array/mpc.js +++ b/tests/dev/2D_array/mpc.js @@ -26,9 +26,13 @@ jiff_instance = saved_instance; } - var my_input = [ [1, 2, 3], [2, 3, 4], [3, 4, 5, 6]]; + var my_input = [ + [1, 2, 3], + [2, 3, 4], + [3, 4, 5, 6] + ]; - var x = jiff_instance.share_2D_array(my_input, { 1: { rows: 3, cols: 3, 2: 4 }, 2: { rows: 3, cols: 2 } } ); + var x = jiff_instance.share_2D_array(my_input, { 1: { rows: 3, cols: 3, 2: 4 }, 2: { rows: 3, cols: 2 } }); return x.then(function (arrays) { try { @@ -44,9 +48,9 @@ } var parties = { - parties: [ 2 ], // default for all elements - 0: { parties: [ 1 ] }, // for first row - 2: { parties: [ 1, 2 ], 0: [ 1 ] } // last row, by default to 1, 2 except first element to 1 only. + parties: [2], // default for all elements + 0: { parties: [1] }, // for first row + 2: { parties: [1, 2], 0: [1] } // last row, by default to 1, 2 except first element to 1 only. }; var op_ids = 'custom me'; @@ -57,4 +61,4 @@ } }); }; -}((typeof exports === 'undefined' ? this.mpc = {} : exports), typeof exports !== 'undefined')); +})(typeof exports === 'undefined' ? (this.mpc = {}) : exports, typeof exports !== 'undefined'); diff --git a/tests/dev/2D_array/party.js b/tests/dev/2D_array/party.js index 34bdb85ac..63a1930dd 100644 --- a/tests/dev/2D_array/party.js +++ b/tests/dev/2D_array/party.js @@ -27,7 +27,7 @@ if (party_id != null) { } // JIFF options -var options = {party_count: party_count, party_id: party_id}; +var options = { party_count: party_count, party_id: party_id }; options.onConnect = function (jiff_instance) { var promise = mpc.compute(); diff --git a/tests/dev/communication-test/client.html b/tests/dev/communication-test/client.html index fc9c21278..10f872caa 100644 --- a/tests/dev/communication-test/client.html +++ b/tests/dev/communication-test/client.html @@ -20,12 +20,13 @@

Connect JIFF

-

-