crypto.js 7.96 KB
Newer Older
XFT's avatar
XFT committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
const { toBN, keccak256, fromWei, toWei, randomHex } = require('web3-utils')
const pedersenHash = (data) => circomlib.babyJub.unpackPoint(circomlib.pedersenHash.hash(data))[0]
const toFixedHex = (number, length = 32) => '0x' + bigInt(number).toString(16).padStart(length * 2, '0');
const websnarkUtils = require('websnark/src/utils')
const buildGroth16 = require('websnark/src/groth16')
const stringifyBigInts = require('websnark/tools/stringifybigint').stringifyBigInts
const snarkjs = require('snarkjs')
const bigInt = snarkjs.bigInt
const MerkleTree = require('fixed-merkle-tree')
const crypto = require('crypto')
const circomlib = require('circomlib')
const Web3 = require('web3');
const rbigint = (nbytes) => snarkjs.bigInt.leBuff2int(crypto.randomBytes(nbytes))
const levels = 20;
const fs = require('fs')
const subtle = crypto.subtle;

let web3, storage, depositAccount, groth16, circuit, proving_key;

global.cryptoController = {

  storageABI: require('../deps/Storage.json').abi,
  shifterABI: require('../deps/XFTanon.json').abi,
  tokenABI: require('../deps/Token.json').abi,

  helpers: {
    randomHex: randomHex,
    toFixedHex: toFixedHex,
    toBN: toBN,
    keccak256: keccak256,
    fromWei: fromWei,
    toWei: toWei,
    pedersenHash: pedersenHash,
    rbigint: rbigint,
    stringifyBigInts: stringifyBigInts,
    isAddress: (address) => web3.utils.isAddress(address)
  },

  account: {
    balance: 0,
    tokenBalances: {}
  },

  loadFactories: async () => {

    web3 = new Web3(new Web3.providers.HttpProvider(config.rpc), null, { transactionConfirmationBlocks: 1 })

    storage = await new web3.eth.Contract(cryptoController.storageABI, config.storageContract);

    depositAccount = web3.eth.accounts.privateKeyToAccount(config.walletKey);
    web3.eth.accounts.wallet.add(depositAccount);

    groth16 = await buildGroth16()
    circuit = require('../deps/withdraw.json')
    proving_key = fs.readFileSync('./deps/withdraw_proving_key.bin').buffer

    cryptoController.sender = depositAccount.address

    let relayerConfig = await (await fetch(config.relayUrl + "/config")).json()
    cryptoController.relayer = {};
    cryptoController.relayer.refund = toBN(relayerConfig.refund);
    cryptoController.relayer.fee = toBN(relayerConfig.fee);
    cryptoController.relayer.address = relayerConfig.address;
    cryptoController.relayer.shifters = relayerConfig.shifters;

    cryptoController.shifterList = await cryptoController.getShifters();
    cryptoController.shifters = {};
    cryptoController.tokens = {};
    cryptoController.shifterTokens = {};


    if (!cryptoController.xft) {
      cryptoController.xftAddress = config.xftContract;
      cryptoController.xft = await new web3.eth.Contract(cryptoController.tokenABI, cryptoController.xftAddress);
      cryptoController.account.balance = await cryptoController.xft.methods.balanceOf(cryptoController.sender).call()
    }


    for (let i = 0; i < cryptoController.shifterList.length; i++) {

      let shifter = cryptoController.shifterList[i];
      cryptoController.shifters[shifter] = await new web3.eth.Contract(cryptoController.shifterABI, shifter);

      let shifterToken = await cryptoController.shifters[shifter].methods.token().call();
      cryptoController.tokens[shifterToken] = await new web3.eth.Contract(cryptoController.tokenABI, shifterToken);
      cryptoController.shifterTokens[shifter] = shifterToken;

      let newBalance = await cryptoController.tokens[shifterToken].methods.balanceOf(cryptoController.sender).call();
      cryptoController.account.tokenBalances[shifterToken] = cryptoController.account.tokenBalances[shifterToken] + newBalance;
    }
  },
  getOrSetPasswordLocally: () => {
    if (!config.storagePassword) {
      let password = randomHex(32);
      console.log(`No password found. Creating a new one. This will be the only time it is shown. \n\n>> ${password} <<`);
      configController.setConfig('storagePassword', password);
    };
    return config.storagePassword;
  },
  parseSaveNote: (saveNote) => {

    const nullifier = BigInt(`0x${saveNote.slice(2, 64)}`)
    const secret = BigInt(`0x${saveNote.slice(64, 126)}`)
    const preimage = Buffer.concat([nullifier.leInt2Buff(31), secret.leInt2Buff(31)])

    let hexNote = `0x${preimage.toString('hex')}`
    const buffNote = Buffer.from(hexNote.slice(2), 'hex')
    const commitment = pedersenHash(buffNote)

    const CUT_LENGTH = 31

    const nullifierBuff = buffNote.slice(0, CUT_LENGTH)
    const nullifierHash = BigInt(pedersenHash(nullifierBuff))

    return {
      secret,
      nullifier,
      commitment,
      nullifierBuff,
      nullifierHash,
      commitmentHex: toFixedHex(commitment),
      nullifierHex: toFixedHex(nullifierHash)
    }
  },
  refBalance: async (shifterAddress) => {

    if (shifterAddress) {
      let shifterToken = cryptoController.shifterTokens[shifterAddress]
      let newBalance = await cryptoController.tokens[shifterToken].methods.balanceOf(cryptoController.sender).call();
      cryptoController.account.tokenBalances[cryptoController.shifterTokens[shifterAddress]._address] = newBalance;
      cryptoController.account.balance = await cryptoController.xft.methods.balanceOf(cryptoController.sender).call();
    } else {
      for (let i = 0; i < cryptoController.tokens.length; i++) {
        let token = cryptoController.tokens[i];
        let newBalance = await token.methods.balanceOf(cryptoController.sender).call();
        cryptoController.account.tokenBalances[token._address] = newBalance;
      }
    }

  },
  xcrypt: async (data, password, shifter, address, nonce) => {

    if (!nonce && nonce != 0) nonce = (await storage.methods.getDepositsLength(shifter, address, keccak256(password)).call({ from: address }));

    const iv = (await subtle.digest('SHA-256', new Uint8Array(Buffer.from((password + nonce))))).slice(0, 16);
    const dataBuffer = new Uint8Array(Buffer.from(data.slice(2), 'hex'));
    const keyBuffer = new Uint8Array(Buffer.from(password.slice(2), 'hex'));
    const key = await subtle.importKey('raw', keyBuffer, { name: 'AES-GCM' }, false, ['encrypt']);

    try {
      let encrypted = await subtle.encrypt({ name: 'AES-GCM', iv }, key, dataBuffer);
      return "0x" + Buffer.from(encrypted).toString('hex').slice(0, 124);
    } catch (err) {
      console.log(err)
      throw new Error("The data provided couldn't be encrypted or decrypted, please check the inputs");
    }
  },
  generateProof: async (shifter, recipient, note) => {

    const deposit = cryptoController.parseSaveNote(note);
    let { fee, refund, address } = cryptoController.relayer;
    let relayer = address;
    let leafIndex;
    const leaves = await shifter.methods.commitmentList().call()
    leaves.forEach((e, i) => {
      const index = toBN(i).toNumber();
      if (toBN(e).eq(toBN(toFixedHex(deposit.commitment)))) {
        leafIndex = index;
      }
      leaves[i] = toBN(e).toString(10);
    });

    let nullHash = deposit.nullifierHash;
    tree = new MerkleTree(levels, leaves)
    const { pathElements, pathIndices } = tree.path(leafIndex)
    const input = stringifyBigInts({

      root: tree.root(),
      nullifierHash: nullHash,
      relayer,
      recipient,
      fee,
      refund,


      nullifier: deposit.nullifier,
      secret: deposit.secret,
      pathElements: pathElements,
      pathIndices: pathIndices,
    })
    const proofData = await websnarkUtils.genWitnessAndProve(groth16, input, circuit, proving_key)
    const { proof } = websnarkUtils.toSolidityInput(proofData)

    const withdrawArgs = [
      toFixedHex(input.root),
      toFixedHex(input.nullifierHash),
      toFixedHex(input.recipient, 20),
      toFixedHex(input.relayer, 20),
      toFixedHex(input.fee),
      toFixedHex(input.refund),
    ]

    return { proof, withdrawArgs }
  },
  getShifters: async () => {
    const storageShifters = await storage.methods.getAllShifters().call();
    const relayerShifters = cryptoController.relayer.shifters;
    return storageShifters.filter(shifter => relayerShifters.includes(shifter));
  }
}

global.helpers = cryptoController.helpers;