ETHTornado.test.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. /* global artifacts, web3, contract */
  2. require('chai').use(require('bn-chai')(web3.utils.BN)).use(require('chai-as-promised')).should()
  3. const fs = require('fs')
  4. const { toBN, randomHex } = require('web3-utils')
  5. const { takeSnapshot, revertSnapshot } = require('../scripts/ganacheHelper')
  6. const Tornado = artifacts.require('./ETHTornado.sol')
  7. const { ETH_AMOUNT, MERKLE_TREE_HEIGHT } = process.env
  8. const websnarkUtils = require('websnark/src/utils')
  9. const buildGroth16 = require('websnark/src/groth16')
  10. const stringifyBigInts = require('websnark/tools/stringifybigint').stringifyBigInts
  11. const unstringifyBigInts2 = require('snarkjs/src/stringifybigint').unstringifyBigInts
  12. const snarkjs = require('snarkjs')
  13. const bigInt = snarkjs.bigInt
  14. const crypto = require('crypto')
  15. const circomlib = require('circomlib')
  16. const MerkleTree = require('fixed-merkle-tree')
  17. const rbigint = (nbytes) => snarkjs.bigInt.leBuff2int(crypto.randomBytes(nbytes))
  18. const pedersenHash = (data) => circomlib.babyJub.unpackPoint(circomlib.pedersenHash.hash(data))[0]
  19. const toFixedHex = (number, length = 32) =>
  20. '0x' +
  21. bigInt(number)
  22. .toString(16)
  23. .padStart(length * 2, '0')
  24. const getRandomRecipient = () => rbigint(20)
  25. function generateDeposit() {
  26. let deposit = {
  27. secret: rbigint(31),
  28. nullifier: rbigint(31),
  29. }
  30. const preimage = Buffer.concat([deposit.nullifier.leInt2Buff(31), deposit.secret.leInt2Buff(31)])
  31. deposit.commitment = pedersenHash(preimage)
  32. return deposit
  33. }
  34. // eslint-disable-next-line no-unused-vars
  35. function BNArrayToStringArray(array) {
  36. const arrayToPrint = []
  37. array.forEach((item) => {
  38. arrayToPrint.push(item.toString())
  39. })
  40. return arrayToPrint
  41. }
  42. function snarkVerify(proof) {
  43. proof = unstringifyBigInts2(proof)
  44. const verification_key = unstringifyBigInts2(require('../build/circuits/withdraw_verification_key.json'))
  45. return snarkjs['groth'].isValid(verification_key, proof, proof.publicSignals)
  46. }
  47. contract('ETHTornado', (accounts) => {
  48. let tornado
  49. const sender = accounts[0]
  50. const operator = accounts[0]
  51. const levels = MERKLE_TREE_HEIGHT || 16
  52. const value = ETH_AMOUNT || '1000000000000000000' // 1 ether
  53. let snapshotId
  54. let tree
  55. const fee = bigInt(ETH_AMOUNT).shr(1) || bigInt(1e17)
  56. const refund = bigInt(0)
  57. const recipient = getRandomRecipient()
  58. const relayer = accounts[1]
  59. let groth16
  60. let circuit
  61. let proving_key
  62. before(async () => {
  63. tree = new MerkleTree(levels)
  64. tornado = await Tornado.deployed()
  65. snapshotId = await takeSnapshot()
  66. groth16 = await buildGroth16()
  67. circuit = require('../build/circuits/withdraw.json')
  68. proving_key = fs.readFileSync('build/circuits/withdraw_proving_key.bin').buffer
  69. })
  70. describe('#constructor', () => {
  71. it('should initialize', async () => {
  72. const etherDenomination = await tornado.denomination()
  73. etherDenomination.should.be.eq.BN(toBN(value))
  74. })
  75. })
  76. describe('#deposit', () => {
  77. it('should emit event', async () => {
  78. let commitment = toFixedHex(42)
  79. let { logs } = await tornado.deposit(commitment, { value, from: sender })
  80. logs[0].event.should.be.equal('Deposit')
  81. logs[0].args.commitment.should.be.equal(commitment)
  82. logs[0].args.leafIndex.should.be.eq.BN(0)
  83. commitment = toFixedHex(12)
  84. ;({ logs } = await tornado.deposit(commitment, { value, from: accounts[2] }))
  85. logs[0].event.should.be.equal('Deposit')
  86. logs[0].args.commitment.should.be.equal(commitment)
  87. logs[0].args.leafIndex.should.be.eq.BN(1)
  88. })
  89. it('should throw if there is a such commitment', async () => {
  90. const commitment = toFixedHex(42)
  91. await tornado.deposit(commitment, { value, from: sender }).should.be.fulfilled
  92. const error = await tornado.deposit(commitment, { value, from: sender }).should.be.rejected
  93. error.reason.should.be.equal('The commitment has been submitted')
  94. })
  95. })
  96. describe('snark proof verification on js side', () => {
  97. it('should detect tampering', async () => {
  98. const deposit = generateDeposit()
  99. tree.insert(deposit.commitment)
  100. const { pathElements, pathIndices } = tree.path(0)
  101. const input = stringifyBigInts({
  102. root: tree.root(),
  103. nullifierHash: pedersenHash(deposit.nullifier.leInt2Buff(31)),
  104. nullifier: deposit.nullifier,
  105. relayer: operator,
  106. recipient,
  107. fee,
  108. refund,
  109. secret: deposit.secret,
  110. pathElements: pathElements,
  111. pathIndices: pathIndices,
  112. })
  113. let proofData = await websnarkUtils.genWitnessAndProve(groth16, input, circuit, proving_key)
  114. const originalProof = JSON.parse(JSON.stringify(proofData))
  115. let result = snarkVerify(proofData)
  116. result.should.be.equal(true)
  117. // nullifier
  118. proofData.publicSignals[1] =
  119. '133792158246920651341275668520530514036799294649489851421007411546007850802'
  120. result = snarkVerify(proofData)
  121. result.should.be.equal(false)
  122. proofData = originalProof
  123. // try to cheat with recipient
  124. proofData.publicSignals[2] = '133738360804642228759657445999390850076318544422'
  125. result = snarkVerify(proofData)
  126. result.should.be.equal(false)
  127. proofData = originalProof
  128. // fee
  129. proofData.publicSignals[3] = '1337100000000000000000'
  130. result = snarkVerify(proofData)
  131. result.should.be.equal(false)
  132. proofData = originalProof
  133. })
  134. })
  135. describe('#withdraw', () => {
  136. it('should work', async () => {
  137. const deposit = generateDeposit()
  138. const user = accounts[4]
  139. tree.insert(deposit.commitment)
  140. const balanceUserBefore = await web3.eth.getBalance(user)
  141. // Uncomment to measure gas usage
  142. // let gas = await tornado.deposit.estimateGas(toBN(deposit.commitment.toString()), { value, from: user, gasPrice: '0' })
  143. // console.log('deposit gas:', gas)
  144. await tornado.deposit(toFixedHex(deposit.commitment), { value, from: user, gasPrice: '0' })
  145. const balanceUserAfter = await web3.eth.getBalance(user)
  146. balanceUserAfter.should.be.eq.BN(toBN(balanceUserBefore).sub(toBN(value)))
  147. const { pathElements, pathIndices } = tree.path(0)
  148. // Circuit input
  149. const input = stringifyBigInts({
  150. // public
  151. root: tree.root(),
  152. nullifierHash: pedersenHash(deposit.nullifier.leInt2Buff(31)),
  153. relayer: operator,
  154. recipient,
  155. fee,
  156. refund,
  157. // private
  158. nullifier: deposit.nullifier,
  159. secret: deposit.secret,
  160. pathElements: pathElements,
  161. pathIndices: pathIndices,
  162. })
  163. const proofData = await websnarkUtils.genWitnessAndProve(groth16, input, circuit, proving_key)
  164. const { proof } = websnarkUtils.toSolidityInput(proofData)
  165. const balanceTornadoBefore = await web3.eth.getBalance(tornado.address)
  166. const balanceRelayerBefore = await web3.eth.getBalance(relayer)
  167. const balanceOperatorBefore = await web3.eth.getBalance(operator)
  168. const balanceReceiverBefore = await web3.eth.getBalance(toFixedHex(recipient, 20))
  169. let isSpent = await tornado.isSpent(toFixedHex(input.nullifierHash))
  170. isSpent.should.be.equal(false)
  171. // Uncomment to measure gas usage
  172. // gas = await tornado.withdraw.estimateGas(proof, publicSignals, { from: relayer, gasPrice: '0' })
  173. // console.log('withdraw gas:', gas)
  174. const args = [
  175. toFixedHex(input.root),
  176. toFixedHex(input.nullifierHash),
  177. toFixedHex(input.recipient, 20),
  178. toFixedHex(input.relayer, 20),
  179. toFixedHex(input.fee),
  180. toFixedHex(input.refund),
  181. ]
  182. const { logs } = await tornado.withdraw(proof, ...args, { from: relayer, gasPrice: '0' })
  183. const balanceTornadoAfter = await web3.eth.getBalance(tornado.address)
  184. const balanceRelayerAfter = await web3.eth.getBalance(relayer)
  185. const balanceOperatorAfter = await web3.eth.getBalance(operator)
  186. const balanceReceiverAfter = await web3.eth.getBalance(toFixedHex(recipient, 20))
  187. const feeBN = toBN(fee.toString())
  188. balanceTornadoAfter.should.be.eq.BN(toBN(balanceTornadoBefore).sub(toBN(value)))
  189. balanceRelayerAfter.should.be.eq.BN(toBN(balanceRelayerBefore))
  190. balanceOperatorAfter.should.be.eq.BN(toBN(balanceOperatorBefore).add(feeBN))
  191. balanceReceiverAfter.should.be.eq.BN(toBN(balanceReceiverBefore).add(toBN(value)).sub(feeBN))
  192. logs[0].event.should.be.equal('Withdrawal')
  193. logs[0].args.nullifierHash.should.be.equal(toFixedHex(input.nullifierHash))
  194. logs[0].args.relayer.should.be.eq.BN(operator)
  195. logs[0].args.fee.should.be.eq.BN(feeBN)
  196. isSpent = await tornado.isSpent(toFixedHex(input.nullifierHash))
  197. isSpent.should.be.equal(true)
  198. })
  199. it('should prevent double spend', async () => {
  200. const deposit = generateDeposit()
  201. tree.insert(deposit.commitment)
  202. await tornado.deposit(toFixedHex(deposit.commitment), { value, from: sender })
  203. const { pathElements, pathIndices } = tree.path(0)
  204. const input = stringifyBigInts({
  205. root: tree.root(),
  206. nullifierHash: pedersenHash(deposit.nullifier.leInt2Buff(31)),
  207. nullifier: deposit.nullifier,
  208. relayer: operator,
  209. recipient,
  210. fee,
  211. refund,
  212. secret: deposit.secret,
  213. pathElements: pathElements,
  214. pathIndices: pathIndices,
  215. })
  216. const proofData = await websnarkUtils.genWitnessAndProve(groth16, input, circuit, proving_key)
  217. const { proof } = websnarkUtils.toSolidityInput(proofData)
  218. const args = [
  219. toFixedHex(input.root),
  220. toFixedHex(input.nullifierHash),
  221. toFixedHex(input.recipient, 20),
  222. toFixedHex(input.relayer, 20),
  223. toFixedHex(input.fee),
  224. toFixedHex(input.refund),
  225. ]
  226. await tornado.withdraw(proof, ...args, { from: relayer }).should.be.fulfilled
  227. const error = await tornado.withdraw(proof, ...args, { from: relayer }).should.be.rejected
  228. error.reason.should.be.equal('The note has been already spent')
  229. })
  230. it('should prevent double spend with overflow', async () => {
  231. const deposit = generateDeposit()
  232. tree.insert(deposit.commitment)
  233. await tornado.deposit(toFixedHex(deposit.commitment), { value, from: sender })
  234. const { pathElements, pathIndices } = tree.path(0)
  235. const input = stringifyBigInts({
  236. root: tree.root(),
  237. nullifierHash: pedersenHash(deposit.nullifier.leInt2Buff(31)),
  238. nullifier: deposit.nullifier,
  239. relayer: operator,
  240. recipient,
  241. fee,
  242. refund,
  243. secret: deposit.secret,
  244. pathElements: pathElements,
  245. pathIndices: pathIndices,
  246. })
  247. const proofData = await websnarkUtils.genWitnessAndProve(groth16, input, circuit, proving_key)
  248. const { proof } = websnarkUtils.toSolidityInput(proofData)
  249. const args = [
  250. toFixedHex(input.root),
  251. toFixedHex(
  252. toBN(input.nullifierHash).add(
  253. toBN('21888242871839275222246405745257275088548364400416034343698204186575808495617'),
  254. ),
  255. ),
  256. toFixedHex(input.recipient, 20),
  257. toFixedHex(input.relayer, 20),
  258. toFixedHex(input.fee),
  259. toFixedHex(input.refund),
  260. ]
  261. const error = await tornado.withdraw(proof, ...args, { from: relayer }).should.be.rejected
  262. error.reason.should.be.equal('verifier-gte-snark-scalar-field')
  263. })
  264. it('fee should be less or equal transfer value', async () => {
  265. const deposit = generateDeposit()
  266. tree.insert(deposit.commitment)
  267. await tornado.deposit(toFixedHex(deposit.commitment), { value, from: sender })
  268. const { pathElements, pathIndices } = tree.path(0)
  269. const largeFee = bigInt(value).add(bigInt(1))
  270. const input = stringifyBigInts({
  271. root: tree.root(),
  272. nullifierHash: pedersenHash(deposit.nullifier.leInt2Buff(31)),
  273. nullifier: deposit.nullifier,
  274. relayer: operator,
  275. recipient,
  276. fee: largeFee,
  277. refund,
  278. secret: deposit.secret,
  279. pathElements: pathElements,
  280. pathIndices: pathIndices,
  281. })
  282. const proofData = await websnarkUtils.genWitnessAndProve(groth16, input, circuit, proving_key)
  283. const { proof } = websnarkUtils.toSolidityInput(proofData)
  284. const args = [
  285. toFixedHex(input.root),
  286. toFixedHex(input.nullifierHash),
  287. toFixedHex(input.recipient, 20),
  288. toFixedHex(input.relayer, 20),
  289. toFixedHex(input.fee),
  290. toFixedHex(input.refund),
  291. ]
  292. const error = await tornado.withdraw(proof, ...args, { from: relayer }).should.be.rejected
  293. error.reason.should.be.equal('Fee exceeds transfer value')
  294. })
  295. it('should throw for corrupted merkle tree root', async () => {
  296. const deposit = generateDeposit()
  297. tree.insert(deposit.commitment)
  298. await tornado.deposit(toFixedHex(deposit.commitment), { value, from: sender })
  299. const { pathElements, pathIndices } = tree.path(0)
  300. const input = stringifyBigInts({
  301. nullifierHash: pedersenHash(deposit.nullifier.leInt2Buff(31)),
  302. root: tree.root(),
  303. nullifier: deposit.nullifier,
  304. relayer: operator,
  305. recipient,
  306. fee,
  307. refund,
  308. secret: deposit.secret,
  309. pathElements: pathElements,
  310. pathIndices: pathIndices,
  311. })
  312. const proofData = await websnarkUtils.genWitnessAndProve(groth16, input, circuit, proving_key)
  313. const { proof } = websnarkUtils.toSolidityInput(proofData)
  314. const args = [
  315. toFixedHex(randomHex(32)),
  316. toFixedHex(input.nullifierHash),
  317. toFixedHex(input.recipient, 20),
  318. toFixedHex(input.relayer, 20),
  319. toFixedHex(input.fee),
  320. toFixedHex(input.refund),
  321. ]
  322. const error = await tornado.withdraw(proof, ...args, { from: relayer }).should.be.rejected
  323. error.reason.should.be.equal('Cannot find your merkle root')
  324. })
  325. it('should reject with tampered public inputs', async () => {
  326. const deposit = generateDeposit()
  327. tree.insert(deposit.commitment)
  328. await tornado.deposit(toFixedHex(deposit.commitment), { value, from: sender })
  329. let { pathElements, pathIndices } = tree.path(0)
  330. const input = stringifyBigInts({
  331. root: tree.root(),
  332. nullifierHash: pedersenHash(deposit.nullifier.leInt2Buff(31)),
  333. nullifier: deposit.nullifier,
  334. relayer: operator,
  335. recipient,
  336. fee,
  337. refund,
  338. secret: deposit.secret,
  339. pathElements: pathElements,
  340. pathIndices: pathIndices,
  341. })
  342. const proofData = await websnarkUtils.genWitnessAndProve(groth16, input, circuit, proving_key)
  343. let { proof } = websnarkUtils.toSolidityInput(proofData)
  344. const args = [
  345. toFixedHex(input.root),
  346. toFixedHex(input.nullifierHash),
  347. toFixedHex(input.recipient, 20),
  348. toFixedHex(input.relayer, 20),
  349. toFixedHex(input.fee),
  350. toFixedHex(input.refund),
  351. ]
  352. let incorrectArgs
  353. const originalProof = proof.slice()
  354. // recipient
  355. incorrectArgs = [
  356. toFixedHex(input.root),
  357. toFixedHex(input.nullifierHash),
  358. toFixedHex('0x0000000000000000000000007a1f9131357404ef86d7c38dbffed2da70321337', 20),
  359. toFixedHex(input.relayer, 20),
  360. toFixedHex(input.fee),
  361. toFixedHex(input.refund),
  362. ]
  363. let error = await tornado.withdraw(proof, ...incorrectArgs, { from: relayer }).should.be.rejected
  364. error.reason.should.be.equal('Invalid withdraw proof')
  365. // fee
  366. incorrectArgs = [
  367. toFixedHex(input.root),
  368. toFixedHex(input.nullifierHash),
  369. toFixedHex(input.recipient, 20),
  370. toFixedHex(input.relayer, 20),
  371. toFixedHex('0x000000000000000000000000000000000000000000000000015345785d8a0000'),
  372. toFixedHex(input.refund),
  373. ]
  374. error = await tornado.withdraw(proof, ...incorrectArgs, { from: relayer }).should.be.rejected
  375. error.reason.should.be.equal('Invalid withdraw proof')
  376. // nullifier
  377. incorrectArgs = [
  378. toFixedHex(input.root),
  379. toFixedHex('0x00abdfc78211f8807b9c6504a6e537e71b8788b2f529a95f1399ce124a8642ad'),
  380. toFixedHex(input.recipient, 20),
  381. toFixedHex(input.relayer, 20),
  382. toFixedHex(input.fee),
  383. toFixedHex(input.refund),
  384. ]
  385. error = await tornado.withdraw(proof, ...incorrectArgs, { from: relayer }).should.be.rejected
  386. error.reason.should.be.equal('Invalid withdraw proof')
  387. // proof itself
  388. proof = '0xbeef' + proof.substr(6)
  389. await tornado.withdraw(proof, ...args, { from: relayer }).should.be.rejected
  390. // should work with original values
  391. await tornado.withdraw(originalProof, ...args, { from: relayer }).should.be.fulfilled
  392. })
  393. it('should reject with non zero refund', async () => {
  394. const deposit = generateDeposit()
  395. tree.insert(deposit.commitment)
  396. await tornado.deposit(toFixedHex(deposit.commitment), { value, from: sender })
  397. const { pathElements, pathIndices } = tree.path(0)
  398. const input = stringifyBigInts({
  399. nullifierHash: pedersenHash(deposit.nullifier.leInt2Buff(31)),
  400. root: tree.root(),
  401. nullifier: deposit.nullifier,
  402. relayer: operator,
  403. recipient,
  404. fee,
  405. refund: bigInt(1),
  406. secret: deposit.secret,
  407. pathElements: pathElements,
  408. pathIndices: pathIndices,
  409. })
  410. const proofData = await websnarkUtils.genWitnessAndProve(groth16, input, circuit, proving_key)
  411. const { proof } = websnarkUtils.toSolidityInput(proofData)
  412. const args = [
  413. toFixedHex(input.root),
  414. toFixedHex(input.nullifierHash),
  415. toFixedHex(input.recipient, 20),
  416. toFixedHex(input.relayer, 20),
  417. toFixedHex(input.fee),
  418. toFixedHex(input.refund),
  419. ]
  420. const error = await tornado.withdraw(proof, ...args, { from: relayer }).should.be.rejected
  421. error.reason.should.be.equal('Refund value is supposed to be zero for ETH instance')
  422. })
  423. })
  424. describe('#isSpent', () => {
  425. it('should work', async () => {
  426. const deposit1 = generateDeposit()
  427. const deposit2 = generateDeposit()
  428. tree.insert(deposit1.commitment)
  429. tree.insert(deposit2.commitment)
  430. await tornado.deposit(toFixedHex(deposit1.commitment), { value, gasPrice: '0' })
  431. await tornado.deposit(toFixedHex(deposit2.commitment), { value, gasPrice: '0' })
  432. const { pathElements, pathIndices } = tree.path(1)
  433. // Circuit input
  434. const input = stringifyBigInts({
  435. // public
  436. root: tree.root(),
  437. nullifierHash: pedersenHash(deposit2.nullifier.leInt2Buff(31)),
  438. relayer: operator,
  439. recipient,
  440. fee,
  441. refund,
  442. // private
  443. nullifier: deposit2.nullifier,
  444. secret: deposit2.secret,
  445. pathElements: pathElements,
  446. pathIndices: pathIndices,
  447. })
  448. const proofData = await websnarkUtils.genWitnessAndProve(groth16, input, circuit, proving_key)
  449. const { proof } = websnarkUtils.toSolidityInput(proofData)
  450. const args = [
  451. toFixedHex(input.root),
  452. toFixedHex(input.nullifierHash),
  453. toFixedHex(input.recipient, 20),
  454. toFixedHex(input.relayer, 20),
  455. toFixedHex(input.fee),
  456. toFixedHex(input.refund),
  457. ]
  458. await tornado.withdraw(proof, ...args, { from: relayer, gasPrice: '0' })
  459. const nullifierHash1 = toFixedHex(pedersenHash(deposit1.nullifier.leInt2Buff(31)))
  460. const nullifierHash2 = toFixedHex(pedersenHash(deposit2.nullifier.leInt2Buff(31)))
  461. const spentArray = await tornado.isSpentArray([nullifierHash1, nullifierHash2])
  462. spentArray.should.be.deep.equal([false, true])
  463. })
  464. })
  465. afterEach(async () => {
  466. await revertSnapshot(snapshotId.result)
  467. // eslint-disable-next-line require-atomic-updates
  468. snapshotId = await takeSnapshot()
  469. tree = new MerkleTree(levels)
  470. })
  471. })