tornado-core/test/ERC20Mixer.test.js

355 lines
15 KiB
JavaScript
Raw Normal View History

2019-08-20 16:39:21 -04:00
/* global artifacts, web3, contract */
require('chai')
.use(require('bn-chai')(web3.utils.BN))
.use(require('chai-as-promised'))
.should()
const fs = require('fs')
2019-08-27 16:42:24 -04:00
const { toBN, toHex } = require('web3-utils')
2019-08-20 16:39:21 -04:00
const { takeSnapshot, revertSnapshot } = require('../lib/ganacheHelper')
const Mixer = artifacts.require('./ERC20Mixer.sol')
const Token = artifacts.require('./ERC20Mock.sol')
2019-08-30 06:06:17 -04:00
const USDTToken = artifacts.require('./IUSDT.sol')
const { ETH_AMOUNT, TOKEN_AMOUNT, MERKLE_TREE_HEIGHT, EMPTY_ELEMENT, ERC20_TOKEN } = process.env
2019-08-20 16:39:21 -04:00
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 crypto = require('crypto')
const circomlib = require('circomlib')
const MerkleTree = require('../lib/MerkleTree')
const rbigint = (nbytes) => snarkjs.bigInt.leBuff2int(crypto.randomBytes(nbytes))
const pedersenHash = (data) => circomlib.babyJub.unpackPoint(circomlib.pedersenHash.hash(data))[0]
function generateDeposit() {
let deposit = {
secret: rbigint(31),
nullifier: rbigint(31),
}
const preimage = Buffer.concat([deposit.nullifier.leInt2Buff(31), deposit.secret.leInt2Buff(31)])
deposit.commitment = pedersenHash(preimage)
return deposit
}
function getRandomReceiver() {
let receiver = rbigint(20)
while (toHex(receiver.toString()).length !== 42) {
receiver = rbigint(20)
}
return receiver
}
2019-08-27 16:42:24 -04:00
contract('ERC20Mixer', accounts => {
2019-08-20 16:39:21 -04:00
let mixer
let token
2019-08-30 06:06:17 -04:00
let usdtToken
2019-08-20 16:39:21 -04:00
const sender = accounts[0]
const operator = accounts[0]
const levels = MERKLE_TREE_HEIGHT || 16
const zeroValue = EMPTY_ELEMENT || 1337
2019-08-30 06:06:17 -04:00
let tokenDenomination = TOKEN_AMOUNT || '1000000000000000000' // 1 ether
2019-08-27 16:42:24 -04:00
const value = ETH_AMOUNT || '1000000000000000000' // 1 ether
2019-08-20 16:39:21 -04:00
let snapshotId
let prefix = 'test'
let tree
2019-08-27 16:42:24 -04:00
const fee = bigInt(ETH_AMOUNT).shr(1) || bigInt(1e17)
2019-08-20 16:39:21 -04:00
const receiver = getRandomReceiver()
const relayer = accounts[1]
let groth16
let circuit
let proving_key
before(async () => {
tree = new MerkleTree(
levels,
zeroValue,
null,
prefix,
)
mixer = await Mixer.deployed()
2019-08-30 06:06:17 -04:00
if (ERC20_TOKEN) {
token = await Token.at(ERC20_TOKEN)
usdtToken = await USDTToken.at(ERC20_TOKEN)
} else {
token = await Token.deployed()
await token.mint(sender, tokenDenomination)
}
2019-08-20 16:39:21 -04:00
snapshotId = await takeSnapshot()
groth16 = await buildGroth16()
circuit = require('../build/circuits/withdraw.json')
proving_key = fs.readFileSync('build/circuits/withdraw_proving_key.bin').buffer
})
describe('#constructor', () => {
it('should initialize', async () => {
const tokenFromContract = await mixer.token()
tokenFromContract.should.be.equal(token.address)
})
})
describe('#deposit', () => {
2019-08-24 06:18:52 -04:00
it('should work', async () => {
2019-08-20 16:39:21 -04:00
const commitment = 43
2019-08-27 16:42:24 -04:00
await token.approve(mixer.address, tokenDenomination)
2019-08-20 16:39:21 -04:00
2019-08-27 16:42:24 -04:00
let { logs } = await mixer.deposit(commitment, { value, from: sender })
2019-08-20 16:39:21 -04:00
logs[0].event.should.be.equal('Deposit')
logs[0].args.commitment.should.be.eq.BN(toBN(commitment))
logs[0].args.leafIndex.should.be.eq.BN(toBN(0))
})
})
2019-08-24 06:18:52 -04:00
describe('#withdraw', () => {
it('should work', async () => {
const deposit = generateDeposit()
const user = accounts[4]
await tree.insert(deposit.commitment)
2019-08-27 16:42:24 -04:00
await token.mint(user, tokenDenomination)
2019-08-24 06:18:52 -04:00
const balanceUserBefore = await token.balanceOf(user)
2019-08-27 16:42:24 -04:00
await token.approve(mixer.address, tokenDenomination, { from: user })
2019-08-24 06:18:52 -04:00
// Uncomment to measure gas usage
// let gas = await mixer.deposit.estimateGas(toBN(deposit.commitment.toString()), { value, from: user, gasPrice: '0' })
// console.log('deposit gas:', gas)
2019-08-27 16:42:24 -04:00
await mixer.deposit(toBN(deposit.commitment.toString()), { value, from: user, gasPrice: '0' })
2019-08-24 06:18:52 -04:00
const balanceUserAfter = await token.balanceOf(user)
2019-08-27 16:42:24 -04:00
balanceUserAfter.should.be.eq.BN(toBN(balanceUserBefore).sub(toBN(tokenDenomination)))
2019-08-24 06:18:52 -04:00
const { root, path_elements, path_index } = await tree.path(0)
// Circuit input
const input = stringifyBigInts({
// public
root,
nullifierHash: pedersenHash(deposit.nullifier.leInt2Buff(31)),
2019-09-10 09:31:34 -04:00
relayer,
2019-08-24 06:18:52 -04:00
receiver,
fee,
// private
nullifier: deposit.nullifier,
secret: deposit.secret,
pathElements: path_elements,
pathIndex: path_index,
})
const proof = await websnarkUtils.genWitnessAndProve(groth16, input, circuit, proving_key)
const { pi_a, pi_b, pi_c, publicSignals } = websnarkUtils.toSolidityInput(proof)
const balanceMixerBefore = await token.balanceOf(mixer.address)
const balanceRelayerBefore = await token.balanceOf(relayer)
2019-08-27 16:42:24 -04:00
const ethBalanceOperatorBefore = await web3.eth.getBalance(operator)
2019-08-24 06:18:52 -04:00
const balanceRecieverBefore = await token.balanceOf(toHex(receiver.toString()))
2019-08-27 16:42:24 -04:00
const ethBalanceRecieverBefore = await web3.eth.getBalance(toHex(receiver.toString()))
2019-08-24 06:18:52 -04:00
let isSpent = await mixer.isSpent(input.nullifierHash.toString(16).padStart(66, '0x00000'))
isSpent.should.be.equal(false)
// Uncomment to measure gas usage
// gas = await mixer.withdraw.estimateGas(pi_a, pi_b, pi_c, publicSignals, { from: relayer, gasPrice: '0' })
// console.log('withdraw gas:', gas)
const { logs } = await mixer.withdraw(pi_a, pi_b, pi_c, publicSignals, { from: relayer, gasPrice: '0' })
const balanceMixerAfter = await token.balanceOf(mixer.address)
const balanceRelayerAfter = await token.balanceOf(relayer)
2019-08-27 16:42:24 -04:00
const ethBalanceOperatorAfter = await web3.eth.getBalance(operator)
2019-08-24 06:18:52 -04:00
const balanceRecieverAfter = await token.balanceOf(toHex(receiver.toString()))
2019-08-27 16:42:24 -04:00
const ethBalanceRecieverAfter = await web3.eth.getBalance(toHex(receiver.toString()))
2019-08-24 06:18:52 -04:00
const feeBN = toBN(fee.toString())
2019-09-10 09:31:34 -04:00
balanceMixerAfter.should.be.eq.BN(toBN(balanceMixerBefore).sub(toBN(tokenDenomination)))
balanceRelayerAfter.should.be.eq.BN(toBN(balanceRelayerBefore).add(feeBN))
2019-09-06 17:22:30 -04:00
ethBalanceOperatorAfter.should.be.eq.BN(toBN(ethBalanceOperatorBefore))
balanceRecieverAfter.should.be.eq.BN(toBN(balanceRecieverBefore).add(toBN(tokenDenomination).sub(feeBN)))
ethBalanceRecieverAfter.should.be.eq.BN(toBN(ethBalanceRecieverBefore).add(toBN(value)))
2019-08-30 06:06:17 -04:00
logs[0].event.should.be.equal('Withdraw')
logs[0].args.nullifierHash.should.be.eq.BN(toBN(input.nullifierHash.toString()))
2019-09-10 09:31:34 -04:00
logs[0].args.relayer.should.be.eq.BN(relayer)
2019-08-30 06:06:17 -04:00
logs[0].args.fee.should.be.eq.BN(feeBN)
isSpent = await mixer.isSpent(input.nullifierHash.toString(16).padStart(66, '0x00000'))
isSpent.should.be.equal(true)
})
it.skip('should work with REAL USDT', async () => {
// dont forget to specify your token in .env
// USDT decimals is 6, so TOKEN_AMOUNT=1000000
// and sent `tokenDenomination` to accounts[0] (0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1)
// run ganache as
// ganache-cli --fork https://kovan.infura.io/v3/27a9649f826b4e31a83e07ae09a87448@13147586 -d --keepAliveTimeout 20
const deposit = generateDeposit()
const user = accounts[4]
const userBal = await usdtToken.balanceOf(user)
console.log('userBal', userBal.toString())
const senderBal = await usdtToken.balanceOf(sender)
console.log('senderBal', senderBal.toString())
await tree.insert(deposit.commitment)
await usdtToken.transfer(user, tokenDenomination, { from: sender })
console.log('transfer done')
const balanceUserBefore = await usdtToken.balanceOf(user)
console.log('balanceUserBefore', balanceUserBefore.toString())
await usdtToken.approve(mixer.address, tokenDenomination, { from: user })
console.log('approve done')
const allowanceUser = await usdtToken.allowance(user, mixer.address)
console.log('allowanceUser', allowanceUser.toString())
await mixer.deposit(toBN(deposit.commitment.toString()), { value, from: user, gasPrice: '0' })
console.log('deposit done')
const balanceUserAfter = await usdtToken.balanceOf(user)
balanceUserAfter.should.be.eq.BN(toBN(balanceUserBefore).sub(toBN(tokenDenomination)))
const { root, path_elements, path_index } = await tree.path(0)
// Circuit input
const input = stringifyBigInts({
// public
root,
nullifierHash: pedersenHash(deposit.nullifier.leInt2Buff(31)),
2019-09-06 16:54:37 -04:00
relayer: operator,
2019-08-30 06:06:17 -04:00
receiver,
fee,
// private
nullifier: deposit.nullifier,
secret: deposit.secret,
pathElements: path_elements,
pathIndex: path_index,
})
const proof = await websnarkUtils.genWitnessAndProve(groth16, input, circuit, proving_key)
const { pi_a, pi_b, pi_c, publicSignals } = websnarkUtils.toSolidityInput(proof)
const balanceMixerBefore = await usdtToken.balanceOf(mixer.address)
const balanceRelayerBefore = await usdtToken.balanceOf(relayer)
const ethBalanceOperatorBefore = await web3.eth.getBalance(operator)
const balanceRecieverBefore = await usdtToken.balanceOf(toHex(receiver.toString()))
const ethBalanceRecieverBefore = await web3.eth.getBalance(toHex(receiver.toString()))
let isSpent = await mixer.isSpent(input.nullifierHash.toString(16).padStart(66, '0x00000'))
isSpent.should.be.equal(false)
// Uncomment to measure gas usage
// gas = await mixer.withdraw.estimateGas(pi_a, pi_b, pi_c, publicSignals, { from: relayer, gasPrice: '0' })
// console.log('withdraw gas:', gas)
const { logs } = await mixer.withdraw(pi_a, pi_b, pi_c, publicSignals, { from: relayer, gasPrice: '0' })
const balanceMixerAfter = await usdtToken.balanceOf(mixer.address)
const balanceRelayerAfter = await usdtToken.balanceOf(relayer)
const ethBalanceOperatorAfter = await web3.eth.getBalance(operator)
const balanceRecieverAfter = await usdtToken.balanceOf(toHex(receiver.toString()))
const ethBalanceRecieverAfter = await web3.eth.getBalance(toHex(receiver.toString()))
const feeBN = toBN(fee.toString())
balanceMixerAfter.should.be.eq.BN(toBN(balanceMixerBefore).sub(toBN(tokenDenomination)))
balanceRelayerAfter.should.be.eq.BN(toBN(balanceRelayerBefore))
ethBalanceOperatorAfter.should.be.eq.BN(toBN(ethBalanceOperatorBefore).add(feeBN))
balanceRecieverAfter.should.be.eq.BN(toBN(balanceRecieverBefore).add(toBN(tokenDenomination)))
ethBalanceRecieverAfter.should.be.eq.BN(toBN(ethBalanceRecieverBefore).add(toBN(value)).sub(feeBN))
logs[0].event.should.be.equal('Withdraw')
logs[0].args.nullifierHash.should.be.eq.BN(toBN(input.nullifierHash.toString()))
2019-09-06 16:54:37 -04:00
logs[0].args.relayer.should.be.eq.BN(operator)
2019-08-30 06:06:17 -04:00
logs[0].args.fee.should.be.eq.BN(feeBN)
isSpent = await mixer.isSpent(input.nullifierHash.toString(16).padStart(66, '0x00000'))
isSpent.should.be.equal(true)
})
it.skip('should work with REAL DAI', async () => {
// dont forget to specify your token in .env
2019-09-06 17:22:30 -04:00
// and send `tokenDenomination` to accounts[0] (0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1)
2019-08-30 06:06:17 -04:00
// run ganache as
2019-09-06 17:22:30 -04:00
// npx ganache-cli --fork https://kovan.infura.io/v3/27a9649f826b4e31a83e07ae09a87448@13146218 -d --keepAliveTimeout 20
2019-08-30 06:06:17 -04:00
const deposit = generateDeposit()
const user = accounts[4]
const userBal = await token.balanceOf(user)
console.log('userBal', userBal.toString())
const senderBal = await token.balanceOf(sender)
console.log('senderBal', senderBal.toString())
await tree.insert(deposit.commitment)
await token.transfer(user, tokenDenomination, { from: sender })
console.log('transfer done')
const balanceUserBefore = await token.balanceOf(user)
console.log('balanceUserBefore', balanceUserBefore.toString())
await token.approve(mixer.address, tokenDenomination, { from: user })
console.log('approve done')
await mixer.deposit(toBN(deposit.commitment.toString()), { value, from: user, gasPrice: '0' })
console.log('deposit done')
const balanceUserAfter = await token.balanceOf(user)
balanceUserAfter.should.be.eq.BN(toBN(balanceUserBefore).sub(toBN(tokenDenomination)))
const { root, path_elements, path_index } = await tree.path(0)
// Circuit input
const input = stringifyBigInts({
// public
root,
nullifierHash: pedersenHash(deposit.nullifier.leInt2Buff(31)),
2019-09-06 16:54:37 -04:00
relayer: operator,
2019-08-30 06:06:17 -04:00
receiver,
fee,
// private
nullifier: deposit.nullifier,
secret: deposit.secret,
pathElements: path_elements,
pathIndex: path_index,
})
const proof = await websnarkUtils.genWitnessAndProve(groth16, input, circuit, proving_key)
const { pi_a, pi_b, pi_c, publicSignals } = websnarkUtils.toSolidityInput(proof)
const balanceMixerBefore = await token.balanceOf(mixer.address)
const balanceRelayerBefore = await token.balanceOf(relayer)
const ethBalanceOperatorBefore = await web3.eth.getBalance(operator)
const balanceRecieverBefore = await token.balanceOf(toHex(receiver.toString()))
const ethBalanceRecieverBefore = await web3.eth.getBalance(toHex(receiver.toString()))
let isSpent = await mixer.isSpent(input.nullifierHash.toString(16).padStart(66, '0x00000'))
isSpent.should.be.equal(false)
// Uncomment to measure gas usage
// gas = await mixer.withdraw.estimateGas(pi_a, pi_b, pi_c, publicSignals, { from: relayer, gasPrice: '0' })
// console.log('withdraw gas:', gas)
const { logs } = await mixer.withdraw(pi_a, pi_b, pi_c, publicSignals, { from: relayer, gasPrice: '0' })
console.log('withdraw done')
const balanceMixerAfter = await token.balanceOf(mixer.address)
const balanceRelayerAfter = await token.balanceOf(relayer)
const ethBalanceOperatorAfter = await web3.eth.getBalance(operator)
const balanceRecieverAfter = await token.balanceOf(toHex(receiver.toString()))
const ethBalanceRecieverAfter = await web3.eth.getBalance(toHex(receiver.toString()))
const feeBN = toBN(fee.toString())
balanceMixerAfter.should.be.eq.BN(toBN(balanceMixerBefore).sub(toBN(tokenDenomination)))
2019-08-24 06:18:52 -04:00
balanceRelayerAfter.should.be.eq.BN(toBN(balanceRelayerBefore))
2019-08-27 16:42:24 -04:00
ethBalanceOperatorAfter.should.be.eq.BN(toBN(ethBalanceOperatorBefore).add(feeBN))
balanceRecieverAfter.should.be.eq.BN(toBN(balanceRecieverBefore).add(toBN(tokenDenomination)))
ethBalanceRecieverAfter.should.be.eq.BN(toBN(ethBalanceRecieverBefore).add(toBN(value)).sub(feeBN))
2019-08-24 06:18:52 -04:00
logs[0].event.should.be.equal('Withdraw')
logs[0].args.nullifierHash.should.be.eq.BN(toBN(input.nullifierHash.toString()))
2019-09-06 16:54:37 -04:00
logs[0].args.relayer.should.be.eq.BN(operator)
2019-08-24 06:18:52 -04:00
logs[0].args.fee.should.be.eq.BN(feeBN)
isSpent = await mixer.isSpent(input.nullifierHash.toString(16).padStart(66, '0x00000'))
isSpent.should.be.equal(true)
})
})
2019-08-20 16:39:21 -04:00
afterEach(async () => {
await revertSnapshot(snapshotId.result)
// eslint-disable-next-line require-atomic-updates
snapshotId = await takeSnapshot()
tree = new MerkleTree(
levels,
zeroValue,
null,
prefix,
)
})
})