4

How can I perform bitwise operations with a bytes32 object in Javascript? This might seem like a general Javascript question but since this is quite common practice to obfuscate input values in a smart contract I post it here. I obtain the bytes32 as follows in Javascript:

var v1 = 'blabla';
var v2 = 'bla'
var h1 = web3.sha3(v1);
var h2 = web3.sha3(v2);
var clientHash = h1 | h2;

Unfortunately clientHash is always equal to zero - I assume because h1 and h2 are actually strings (but that remains the same even when casting it to int). In the smart contract (Solidity) I calculate the analog scenario as follows:

function testHash(bytes32 h1, bytes32 h2) constant returns (bytes32 b) {
      b = h1 ^ h2;
    }

Background: For studying purposes I am working on a rock paper scissor game on Ethereum. Of course in a secure game I would obfuscate a users choice, with a second secret random input. The combined hash of both inputs should be calculated on the client and only then sent to the smart contract. When both players have commited their choices, both players send their plaintext to the smart contract and the winner gets the pot. This is my solidity code in detail (the first part of which I would like to move to the client (JS)).

4

You need to use a big number library because Javascript's bitwise-operators only work on 32-bits. web3.sha3 output is 32 bytes.

BigNumber.js that's included in web3.js doesn't support bitwise-operators.

One option is to use bn.js, like:

const BN = require("bn");
var a = new BN.BigInteger(h1, 16);
var b = new BN.BigInteger(h2, 16);
var clientHash = '0x' + a.xor(b).toString(16);

I tested a sample but you may need to specify padding to toString.

  • I was attempting to implement that in plain simple HTML + JS (no Node.js). If I see correctly this is not possible out of the box since big numbers with custom XOR is only available via require. Let me know if you know of anything else. – Validity Labs - Sebastian May 21 '16 at 14:34
  • bn.js can be used in browser (try tools like browserify, webpack); the sample I linked in the answer runs in the browser and is one of the reasons I included it. – eth May 21 '16 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.