Skip to content

Instantly share code, notes, and snippets.

@urish
Created February 20, 2022 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save urish/c4c85a03dfb10b2a3a895e3c3aecd36c to your computer and use it in GitHub Desktop.
Save urish/c4c85a03dfb10b2a3a895e3c3aecd36c to your computer and use it in GitHub Desktop.
function galoisMultiply1(x, y) {
const Zi = new Uint32Array(4);
const Vi = new Uint32Array(y);
for (let i = 0; i < 128; i++) {
const xi = (x[i >> 5] & (1 << (31 - (i % 32)))) !== 0;
if (xi) {
Zi[0] ^= Vi[0];
Zi[1] ^= Vi[1];
Zi[2] ^= Vi[2];
Zi[3] ^= Vi[3];
}
const lsbValue = Vi[3] & 1;
Vi[3] = (Vi[3] >>> 1) | ((Vi[2] & 1) << 31);
Vi[2] = (Vi[2] >>> 1) | ((Vi[1] & 1) << 31);
Vi[1] = (Vi[1] >>> 1) | ((Vi[0] & 1) << 31);
Vi[0] = Vi[0] >>> 1;
if (lsbValue) {
Vi[0] ^= 0xe1000000;
}
}
return Zi;
}
function galoisMultiply2(x, y) {
const Zi = new Uint32Array(4);
const Vi = new Uint32Array(y);
for (let i = 0; i < 128; i++) {
const xi = (x[i >> 5] & (1 << (31 - (i % 32)))) !== 0;
if (xi) {
Zi[0] ^= Vi[0];
Zi[1] ^= Vi[1];
Zi[2] ^= Vi[2];
Zi[3] ^= Vi[3];
}
const lsbValue = !!(Vi[3] & 1);
Vi[3] = (Vi[3] >>> 1) | ((Vi[2] & 1) << 31);
Vi[2] = (Vi[2] >>> 1) | ((Vi[1] & 1) << 31);
Vi[1] = (Vi[1] >>> 1) | ((Vi[0] & 1) << 31);
Vi[0] = Vi[0] >>> 1;
if (lsbValue) {
Vi[0] ^= 0xe1000000;
}
}
return Zi;
}
function testGalois(fn) {
const x = new Uint32Array([2425393296, 2425393296, 2425393296, 2425393296]);
const y = new Uint32Array([3692772234, 3144594163, 3014792419, 2386452453]);
const expected = [2793996538, 14267392, 3369100906, 2506634262];
for (let i = 0; i < 100; i++) {
const result = Array.from(fn(x, y));
if (JSON.stringify(result) != JSON.stringify(expected)) {
console.error('Failed on iteration', i, 'expected', expected, 'result', result)
return;
}
}
console.log('Pass!');
}
console.log('Testing galoisMultiply1')
testGalois(galoisMultiply1);
console.log('Testing galoisMultiply2')
testGalois(galoisMultiply2);
@eternaleclipse
Copy link

Minimized test case:

// To view JIT generated function disassembly, run with `node --print-opt-code`

function weird() {
  let lsbValues = [];
  const Vi = new Uint32Array([1, 1, 1]);
  // for (let i = 0; i < 6; i++) {
  for (let i = 0; i < 128; i++) {
    const lsbValue = !!(Vi[2] & 1);
    // const lsbValue = Vi[2] & 1;
    Vi[2] = Vi[1] & 2;
    Vi[1] = (Vi[1] & 1) | (Vi[0] & 1);
    lsbValues.push(lsbValue);

    // Uncommenting this line will cause it to work
    // console.log(Vi[0], lsbValue)
  }

  console.log(lsbValues);
  if (lsbValues[0] === false) {
    return 'wut';
  }
  return Vi;
}

function test() {
  for (let i = 0; i < 100; i++) {
    if (weird() === 'wut') {
      console.log(`Failed at ${i}th iteration`);
      return;
    }
  }
  console.log('Success');
}

console.log('Testing weird');
test(weird);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment