From 27316a1edd1315465b6eb21f41a2c7437c8d93e7 Mon Sep 17 00:00:00 2001 From: Alexey Date: Tue, 25 Feb 2020 11:04:13 +0300 Subject: [PATCH 1/6] poma WIP --- cli.js | 72 ++++++++++++++++---------- config.js | 151 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 197 insertions(+), 26 deletions(-) create mode 100644 config.js diff --git a/cli.js b/cli.js index 9e575f6..50844ac 100755 --- a/cli.js +++ b/cli.js @@ -13,6 +13,7 @@ const Web3 = require('web3') const buildGroth16 = require('websnark/src/groth16') const websnarkUtils = require('websnark/src/utils') const { toWei, fromWei } = require('web3-utils') +const config = require('./config') let web3, tornado, erc20tornado, circuit, proving_key, groth16, erc20, senderAccount let MERKLE_TREE_HEIGHT, ETH_AMOUNT, TOKEN_AMOUNT, ERC20_TOKEN @@ -28,7 +29,7 @@ const pedersenHash = data => circomlib.babyJub.unpackPoint(circomlib.pedersenHas /** BigNumber to hex string of specified length */ function toHex(number, length = 32) { - let str = number instanceof Buffer ? number.toString('hex') : bigInt(number).toString(16) + const str = number instanceof Buffer ? number.toString('hex') : bigInt(number).toString(16) return '0x' + str.padStart(length * 2, '0') } @@ -42,7 +43,7 @@ async function printBalance(account, name) { * Create deposit object from secret and nullifier */ function createDeposit(nullifier, secret) { - let deposit = { nullifier, secret } + const deposit = { nullifier, secret } deposit.preimage = Buffer.concat([deposit.nullifier.leInt2Buff(31), deposit.secret.leInt2Buff(31)]) deposit.commitment = pedersenHash(deposit.preimage) deposit.nullifierHash = pedersenHash(deposit.nullifier.leInt2Buff(31)) @@ -102,8 +103,8 @@ async function generateMerkleProof(contract, deposit) { const tree = new merkleTree(MERKLE_TREE_HEIGHT, leaves) // Find current commitment in the tree - let depositEvent = events.find(e => e.returnValues.commitment === toHex(deposit.commitment)) - let leafIndex = depositEvent ? depositEvent.returnValues.leafIndex : -1 + const depositEvent = events.find(e => e.returnValues.commitment === toHex(deposit.commitment)) + const leafIndex = depositEvent ? depositEvent.returnValues.leafIndex : -1 // Validate that our data is correct const isValidRoot = await contract.methods.isKnownRoot(toHex(await tree.root())).call() @@ -119,33 +120,29 @@ async function generateMerkleProof(contract, deposit) { /** * Generate SNARK proof for withdrawal * @param contract Tornado contract address - * @param note Note string + * @param note Note * @param recipient Funds recipient * @param relayer Relayer address * @param fee Relayer fee * @param refund Receive ether for exchanged tokens */ async function generateProof(contract, note, recipient, relayer = 0, fee = 0, refund = 0) { - // Decode hex string and restore the deposit object - let buf = Buffer.from(note.slice(2), 'hex') - let deposit = createDeposit(bigInt.leBuff2int(buf.slice(0, 31)), bigInt.leBuff2int(buf.slice(31, 62))) - // Compute merkle proof of our commitment - const { root, path_elements, path_index } = await generateMerkleProof(contract, deposit) + const { root, path_elements, path_index } = await generateMerkleProof(contract, note.deposit) // Prepare circuit input const input = { // Public snark inputs root: root, - nullifierHash: deposit.nullifierHash, + nullifierHash: note.deposit.nullifierHash, recipient: bigInt(recipient), relayer: bigInt(relayer), fee: bigInt(fee), refund: bigInt(refund), // Private snark inputs - nullifier: deposit.nullifier, - secret: deposit.secret, + nullifier: note.deposit.nullifier, + secret: note.deposit.secret, pathElements: path_elements, pathIndices: path_index, } @@ -170,10 +167,11 @@ async function generateProof(contract, note, recipient, relayer = 0, fee = 0, re /** * Do an ETH withdrawal - * @param note Note to withdraw + * @param noteString Note to withdraw * @param recipient Recipient address */ -async function withdraw(note, recipient) { +async function withdraw(noteString, recipient) { + const note = parseNote(noteString) const { proof, args } = await generateProof(tornado, note, recipient) console.log('Submitting withdraw transaction') @@ -183,10 +181,11 @@ async function withdraw(note, recipient) { /** * Do a ERC20 withdrawal - * @param note Note to withdraw + * @param noteString Note to withdraw * @param recipient Recipient address */ -async function withdrawErc20(note, recipient) { +async function withdrawErc20(noteString, recipient) { + const note = parseNote(noteString) const { proof, args } = await generateProof(erc20tornado, note, recipient) console.log('Submitting withdraw transaction') @@ -196,11 +195,12 @@ async function withdrawErc20(note, recipient) { /** * Do an ETH withdrawal through relay - * @param note Note to withdraw + * @param noteString Note to withdraw * @param recipient Recipient address * @param relayUrl Relay url address */ -async function withdrawRelay(note, recipient, relayUrl) { +async function withdrawRelay(noteString, recipient, relayUrl) { + const note = parseNote(noteString) const resp = await axios.get(relayUrl + '/status') const { relayerAddress, netId, gasPrices } = resp.data assert(netId === await web3.eth.net.getId() || netId === '*', 'This relay is for different network') @@ -213,18 +213,19 @@ async function withdrawRelay(note, recipient, relayUrl) { const resp2 = await axios.post(relayUrl + '/relay', { contract: tornado._address, proof: { proof, publicSignals: args } }) console.log(`Transaction submitted through relay, tx hash: ${resp2.data.txHash}`) - let receipt = await waitForTxReceipt(resp2.data.txHash) + const receipt = await waitForTxReceipt(resp2.data.txHash) console.log('Transaction mined in block', receipt.blockNumber) console.log('Done') } /** * Do a ERC20 withdrawal through relay - * @param note Note to withdraw + * @param noteString Note to withdraw * @param recipient Recipient address * @param relayUrl Relay url address */ -async function withdrawRelayErc20(note, recipient, relayUrl) { +async function withdrawRelayErc20(noteString, recipient, relayUrl) { + const note = parseNote(noteString) const resp = await axios.get(relayUrl + '/status') const { relayerAddress, netId, gasPrices, ethPriceInDai } = resp.data assert(netId === await web3.eth.net.getId() || netId === '*', 'This relay is for different network') @@ -238,7 +239,7 @@ async function withdrawRelayErc20(note, recipient, relayUrl) { const resp2 = await axios.post(relayUrl + '/relay', { contract: erc20tornado._address, proof: { proof, publicSignals: args } }) console.log(`Transaction submitted through relay, tx hash: ${resp2.data.txHash}`) - let receipt = await waitForTxReceipt(resp2.data.txHash) + const receipt = await waitForTxReceipt(resp2.data.txHash) console.log('Transaction mined in block', receipt.blockNumber) console.log('Done') } @@ -267,6 +268,25 @@ function waitForTxReceipt(txHash, attempts = 60, delay = 1000) { }) } +function parseNote(noteString) { + const noteRegex = /tornado-(?\w+)-(?[\d.]+)-(?\d+)-0x(?[0-9a-fA-F]{124})/g + const match = noteRegex.exec(noteString) + if (!match) { + throw new Error('The note has invalid format') + } + + const buf = Buffer.from(match.groups.note, 'hex') + const nullifier = bigInt.leBuff2int(buf.slice(0, 31)) + const secret = bigInt.leBuff2int(buf.slice(31, 62)) + const deposit = createDeposit(nullifier, secret) + + + const netId = Number(match.groups.netId) + const address = config.mixers['netId' + netId][match.groups.currency][match.groups.amount] + + return { address, netId, deposit } +} + /** * Init web3, contracts, and snark */ @@ -284,7 +304,7 @@ async function init() { TOKEN_AMOUNT = 1e19 } else { // Initialize from local node - web3 = new Web3('http://localhost:8545', null, { transactionConfirmationBlocks: 1 }) + web3 = new Web3('https://mainnet.infura.io', null, { transactionConfirmationBlocks: 1 }) contractJson = require('./build/contracts/ETHTornado.json') circuit = require('./build/circuits/withdraw.json') proving_key = fs.readFileSync('build/circuits/withdraw_proving_key.bin').buffer @@ -297,10 +317,10 @@ async function init() { erc20tornadoJson = require('./build/contracts/ERC20Tornado.json') } groth16 = await buildGroth16() - let netId = await web3.eth.net.getId() + const netId = await web3.eth.net.getId() if (contractJson.networks[netId]) { const tx = await web3.eth.getTransaction(contractJson.networks[netId].transactionHash) - tornado = new web3.eth.Contract(contractJson.abi, contractJson.networks[netId].address) + tornado = new web3.eth.Contract(contractJson.abi, '0xb541fc07bC7619fD4062A54d96268525cBC6FfEF') tornado.deployedBlock = tx.blockNumber } diff --git a/config.js b/config.js new file mode 100644 index 0000000..dd1a26f --- /dev/null +++ b/config.js @@ -0,0 +1,151 @@ +require('dotenv').config() + +module.exports = { + version: '2.2', + netId: Number(process.env.NET_ID) || 42, + redisUrl: process.env.REDIS_URL, + rpcUrl: process.env.RPC_URL || 'https://kovan.infura.io/', + oracleRpcUrl: process.env.ORACLE_RPC_URL || 'https://mainnet.infura.io/', + oracleAddress: '0xB5eE7907FF5f4c1FC9086Fc117E6c397431F39ad', + privateKey: process.env.PRIVATE_KEY, + mixers: { + netId1: { + eth: { + mixerAddress: { + '0.1': '0x12D66f87A04A9E220743712cE6d9bB1B5616B8Fc', + '1': '0x47CE0C6eD5B0Ce3d3A51fdb1C52DC66a7c3c2936', + '10': '0x910Cbd523D972eb0a6f4cAe4618aD62622b39DbF', + '100': '0xA160cdAB225685dA1d56aa342Ad8841c3b53f291' + }, + symbol: 'ETH', + decimals: 18 + }, + dai: { + mixerAddress: { + '100': '0xD4B88Df4D29F5CedD6857912842cff3b20C8Cfa3', + '1000': '0xFD8610d20aA15b7B2E3Be39B396a1bC3516c7144', + '10000': '0xF60dD140cFf0706bAE9Cd734Ac3ae76AD9eBC32A', + '100000': undefined + }, + tokenAddress: '0x6B175474E89094C44Da98b954EedeAC495271d0F', + symbol: 'DAI', + decimals: 18 + }, + cdai: { + mixerAddress: { + '5000': '0x22aaA7720ddd5388A3c0A3333430953C68f1849b', + '50000': '0xBA214C1c1928a32Bffe790263E38B4Af9bFCD659', + '500000': '0xb1C8094B234DcE6e03f10a5b673c1d8C69739A00', + '5000000': undefined + }, + tokenAddress: '0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643', + symbol: 'cDAI', + decimals: 8 + }, + usdc: { + mixerAddress: { + '100': '0xd96f2B1c14Db8458374d9Aca76E26c3D18364307', + '1000': '0x4736dCf1b7A3d580672CcE6E7c65cd5cc9cFBa9D', + '10000': '0xD691F27f38B395864Ea86CfC7253969B409c362d', + '100000': undefined + }, + tokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', + symbol: 'USDC', + decimals: 6 + }, + cusdc: { + mixerAddress: { + '5000': '0xaEaaC358560e11f52454D997AAFF2c5731B6f8a6', + '50000': '0x1356c899D8C9467C7f71C195612F8A395aBf2f0a', + '500000': '0xA60C772958a3eD56c1F15dD055bA37AC8e523a0D', + '5000000': undefined + }, + tokenAddress: '0x39AA39c021dfbaE8faC545936693aC917d5E7563', + symbol: 'cUSDC', + decimals: 8 + }, + usdt: { + mixerAddress: { + '100': '0x169AD27A470D064DEDE56a2D3ff727986b15D52B', + '1000': '0x0836222F2B2B24A3F36f98668Ed8F0B38D1a872f', + '10000': '0xF67721A2D8F736E75a49FdD7FAd2e31D8676542a', + '100000': '0x9AD122c22B14202B4490eDAf288FDb3C7cb3ff5E' + }, + tokenAddress: '0xdAC17F958D2ee523a2206206994597C13D831ec7', + symbol: 'USDT', + decimals: 6 + } + }, + netId42: { + eth: { + mixerAddress: { + '0.1': '0x8b3f5393bA08c24cc7ff5A66a832562aAB7bC95f', + '1': '0xD6a6AC46d02253c938B96D12BE439F570227aE8E', + '10': '0xe1BE96331391E519471100c3c1528B66B8F4e5a7', + '100': '0xd037E0Ac98Dab2fCb7E296c69C6e52767Ae5414D' + }, + symbol: 'ETH', + decimals: 18 + }, + dai: { + mixerAddress: { + '100': '0xdf2d3cC5F361CF95b3f62c4bB66deFe3FDE47e3D', + '1000': '0xD96291dFa35d180a71964D0894a1Ae54247C4ccD', + '10000': '0xb192794f72EA45e33C3DF6fe212B9c18f6F45AE3', + '100000': undefined + }, + tokenAddress: '0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa', + symbol: 'DAI', + decimals: 18 + }, + cdai: { + mixerAddress: { + '5000': '0x6Fc9386ABAf83147b3a89C36D422c625F44121C8', + '50000': '0x7182EA067e0f050997444FCb065985Fd677C16b6', + '500000': '0xC22ceFd90fbd1FdEeE554AE6Cc671179BC3b10Ae', + '5000000': undefined + }, + tokenAddress: '0xe7bc397DBd069fC7d0109C0636d06888bb50668c', + symbol: 'cDAI', + decimals: 8 + }, + usdc: { + mixerAddress: { + '100': '0x137E2B6d185018e7f09f6cf175a970e7fC73826C', + '1000': '0xcC7f1633A5068E86E3830e692e3e3f8f520525Af', + '10000': '0x28C8f149a0ab8A9bdB006B8F984fFFCCE52ef5EF', + '100000': undefined + }, + tokenAddress: '0x75B0622Cec14130172EaE9Cf166B92E5C112FaFF', + symbol: 'USDC', + decimals: 6 + }, + cusdc: { + mixerAddress: { + '5000': '0xc0648F28ABA385c8a1421Bbf1B59e3c474F89cB0', + '50000': '0x0C53853379c6b1A7B74E0A324AcbDD5Eabd4981D', + '500000': '0xf84016A0E03917cBe700D318EB1b7a53e6e3dEe1', + '5000000': undefined + }, + tokenAddress: '0xcfC9bB230F00bFFDB560fCe2428b4E05F3442E35', + symbol: 'cUSDC', + decimals: 8 + }, + usdt: { + mixerAddress: { + '100': '0x327853Da7916a6A0935563FB1919A48843036b42', + '1000': '0x531AA4DF5858EA1d0031Dad16e3274609DE5AcC0', + '10000': '0x0958275F0362cf6f07D21373aEE0cf37dFe415dD', + '100000': '0x14aEd24B67EaF3FF28503eB92aeb217C47514364' + }, + tokenAddress: '0x03c5F29e9296006876d8DF210BCFfD7EA5Db1Cf1', + symbol: 'USDT', + decimals: 6 + } + } + }, + defaultGasPrice: 2, + gasOracleUrls: ['https://ethgasstation.info/json/ethgasAPI.json', 'https://gasprice.poa.network/'], + port: process.env.APP_PORT, + relayerServiceFee: Number(process.env.RELAYER_FEE) +} From ff71072700dd30cf0d132ed8356b3e4e3bd7e65e Mon Sep 17 00:00:00 2001 From: Alexey Date: Wed, 26 Feb 2020 16:57:53 +0300 Subject: [PATCH 2/6] WIP --- cli.js | 565 +++++++++++++++++++++++----------------------- config.js | 28 +-- package-lock.json | 19 +- package.json | 1 + 4 files changed, 314 insertions(+), 299 deletions(-) diff --git a/cli.js b/cli.js index 50844ac..89a126a 100755 --- a/cli.js +++ b/cli.js @@ -12,14 +12,17 @@ const merkleTree = require('./lib/MerkleTree') const Web3 = require('web3') const buildGroth16 = require('websnark/src/groth16') const websnarkUtils = require('websnark/src/utils') -const { toWei, fromWei } = require('web3-utils') +const { toWei, fromWei, toBN, BN } = require('web3-utils') const config = require('./config') +const program = require('commander') -let web3, tornado, erc20tornado, circuit, proving_key, groth16, erc20, senderAccount -let MERKLE_TREE_HEIGHT, ETH_AMOUNT, TOKEN_AMOUNT, ERC20_TOKEN +let web3, tornado, circuit, proving_key, groth16, erc20, senderAccount, netId +let MERKLE_TREE_HEIGHT, ETH_AMOUNT, TOKEN_AMOUNT, PRIVATE_KEY /** Whether we are in a browser or node.js */ const inBrowser = (typeof window !== 'undefined') +let isLocalRPC = false +const networks = { '1': 'mainnet', '42': 'kovan' } /** Generate random number of specified byte length */ const rbigint = nbytes => snarkjs.bigInt.leBuff2int(crypto.randomBytes(nbytes)) @@ -33,16 +36,22 @@ function toHex(number, length = 32) { return '0x' + str.padStart(length * 2, '0') } -/** Display account balance */ -async function printBalance(account, name) { - console.log(`${name} ETH balance is`, web3.utils.fromWei(await web3.eth.getBalance(account))) - console.log(`${name} Token Balance is`, web3.utils.fromWei(await erc20.methods.balanceOf(account).call())) +/** Display ETH account balance */ +async function printETHBalance({ address, name }) { + console.log(`${name} ETH balance is`, web3.utils.fromWei(await web3.eth.getBalance(address))) +} + +/** Display ERC20 account balance */ +async function printERC20Balance({ address, name, tokenAddress }) { + const erc20ContractJson = require('./build/contracts/ERC20Mock.json') + erc20 = tokenAddress ? new web3.eth.Contract(erc20ContractJson.abi, tokenAddress) : erc20 + console.log(`${name} Token Balance is`, web3.utils.fromWei(await erc20.methods.balanceOf(address).call())) } /** * Create deposit object from secret and nullifier */ -function createDeposit(nullifier, secret) { +function createDeposit({ nullifier, secret }) { const deposit = { nullifier, secret } deposit.preimage = Buffer.concat([deposit.nullifier.leInt2Buff(31), deposit.secret.leInt2Buff(31)]) deposit.commitment = pedersenHash(deposit.preimage) @@ -51,52 +60,59 @@ function createDeposit(nullifier, secret) { } /** - * Make an ETH deposit + * Make a deposit + * @param currency Сurrency + * @param amount Deposit amount */ -async function deposit() { - const deposit = createDeposit(rbigint(31), rbigint(31)) - - console.log('Submitting deposit transaction') - await tornado.methods.deposit(toHex(deposit.commitment)).send({ value: ETH_AMOUNT, from: senderAccount, gas:2e6 }) - +async function deposit({ currency, amount }) { + const deposit = createDeposit({ nullifier: rbigint(31), secret: rbigint(31) }) const note = toHex(deposit.preimage, 62) - console.log('Your note:', note) - return note -} + const noteString = `tornado-${currency}-${amount}-${netId}-${note}` + console.log(`Your note: ${noteString}`) + if (currency === 'eth') { + await printETHBalance({ address: tornado._address, name: 'Tornado' }) + await printETHBalance({ address: senderAccount, name: 'Sender account' }) + const value = isLocalRPC ? ETH_AMOUNT : fromDecimals({ amount, decimals: 18 }) + console.log('Submitting deposit transaction') + await tornado.methods.deposit(toHex(deposit.commitment)).send({ value, from: senderAccount, gas:2e6 }) + await printETHBalance({ address: tornado._address, name: 'Tornado' }) + await printETHBalance({ address: senderAccount, name: 'Sender account' }) + } else { + await printERC20Balance({ address: tornado._address, name: 'Tornado' }) + await printERC20Balance({ address: senderAccount, name: 'Sender account' }) + const decimals = isLocalRPC ? 18 : config.deployments[`netId${netId}`][currency].decimals + const tokenAmount = isLocalRPC ? TOKEN_AMOUNT : fromDecimals({ amount, decimals }) + if(isLocalRPC) { + console.log('Minting some test tokens to deposit') + await erc20.methods.mint(senderAccount, tokenAmount).send({ from: senderAccount, gas: 2e6 }) + } -/** - * Make an ERC20 deposit - */ -async function depositErc20() { - const deposit = createDeposit(rbigint(31), rbigint(31)) + const allowance = await erc20.methods.allowance(senderAccount, tornado._address).call({ from: senderAccount }) + console.log('Current allowance is', fromWei(allowance)) + if (toBN(allowance).lt(toBN(tokenAmount))) { + console.log('Approving tokens for deposit') + await erc20.methods.approve(tornado._address, tokenAmount).send({ from: senderAccount, gas:1e6 }) + } - if(ERC20_TOKEN === '') { - console.log('Minting some test tokens to deposit') - await erc20.methods.mint(senderAccount, TOKEN_AMOUNT).send({ from: senderAccount, gas: 2e6 }) + console.log('Submitting deposit transaction') + await tornado.methods.deposit(toHex(deposit.commitment)).send({ from: senderAccount, gas:2e6 }) + await printERC20Balance({ address: tornado._address, name: 'Tornado' }) + await printERC20Balance({ address: senderAccount, name: 'Sender account' }) } - console.log('Approving tokens for deposit') - await erc20.methods.approve(erc20tornado._address, TOKEN_AMOUNT).send({ from: senderAccount, gas:1e6 }) - - console.log('Submitting deposit transaction') - await erc20tornado.methods.deposit(toHex(deposit.commitment)).send({ from: senderAccount, gas:2e6 }) - - const note = toHex(deposit.preimage, 62) - console.log('Your note:', note) - return note + return noteString } /** * Generate merkle tree for a deposit. - * Download deposit events from the contract, reconstructs merkle tree, finds our deposit leaf + * Download deposit events from the tornado, reconstructs merkle tree, finds our deposit leaf * in it and generates merkle proof - * @param contract Tornado contract address * @param deposit Deposit object */ -async function generateMerkleProof(contract, deposit) { +async function generateMerkleProof(deposit) { // Get all deposit events from smart contract and assemble merkle tree from them console.log('Getting current state from tornado contract') - const events = await contract.getPastEvents('Deposit', { fromBlock: contract.deployedBlock, toBlock: 'latest' }) + const events = await tornado.getPastEvents('Deposit', { fromBlock: 0, toBlock: 'latest' }) const leaves = events .sort((a, b) => a.returnValues.leafIndex - b.returnValues.leafIndex) // Sort events in chronological order .map(e => e.returnValues.commitment) @@ -107,8 +123,8 @@ async function generateMerkleProof(contract, deposit) { const leafIndex = depositEvent ? depositEvent.returnValues.leafIndex : -1 // Validate that our data is correct - const isValidRoot = await contract.methods.isKnownRoot(toHex(await tree.root())).call() - const isSpent = await contract.methods.isSpent(toHex(deposit.nullifierHash)).call() + const isValidRoot = await tornado.methods.isKnownRoot(toHex(await tree.root())).call() + const isSpent = await tornado.methods.isSpent(toHex(deposit.nullifierHash)).call() assert(isValidRoot === true, 'Merkle tree is corrupted') assert(isSpent === false, 'The note is already spent') assert(leafIndex >= 0, 'The deposit is not found in the tree') @@ -119,30 +135,29 @@ async function generateMerkleProof(contract, deposit) { /** * Generate SNARK proof for withdrawal - * @param contract Tornado contract address * @param note Note * @param recipient Funds recipient * @param relayer Relayer address * @param fee Relayer fee * @param refund Receive ether for exchanged tokens */ -async function generateProof(contract, note, recipient, relayer = 0, fee = 0, refund = 0) { +async function generateProof({ deposit, recipient, relayerAddress = 0, fee = 0, refund = 0 }) { // Compute merkle proof of our commitment - const { root, path_elements, path_index } = await generateMerkleProof(contract, note.deposit) + const { root, path_elements, path_index } = await generateMerkleProof(deposit) // Prepare circuit input const input = { // Public snark inputs root: root, - nullifierHash: note.deposit.nullifierHash, + nullifierHash: deposit.nullifierHash, recipient: bigInt(recipient), - relayer: bigInt(relayer), + relayer: bigInt(relayerAddress), fee: bigInt(fee), refund: bigInt(refund), // Private snark inputs - nullifier: note.deposit.nullifier, - secret: note.deposit.secret, + nullifier: deposit.nullifier, + secret: deposit.secret, pathElements: path_elements, pathIndices: path_index, } @@ -170,78 +185,132 @@ async function generateProof(contract, note, recipient, relayer = 0, fee = 0, re * @param noteString Note to withdraw * @param recipient Recipient address */ -async function withdraw(noteString, recipient) { - const note = parseNote(noteString) - const { proof, args } = await generateProof(tornado, note, recipient) +async function withdraw({ deposit, currency, amount, recipient, relayerURL, refund = '0' }) { + if (currency === 'eth' && refund !== '0') { + throw new Error('The ETH purchase is supposted to be 0 for ETH withdrawals') + } + refund = toWei(refund) + if (relayerURL) { + const relayerStatus = await axios.get(relayerURL + '/status') + const { relayerAddress, netId, gasPrices, ethPrices, relayerServiceFee } = relayerStatus.data + assert(netId === await web3.eth.net.getId() || netId === '*', 'This relay is for different network') + console.log('Relay address: ', relayerAddress) - console.log('Submitting withdraw transaction') - await tornado.methods.withdraw(proof, ...args).send({ from: senderAccount, gas: 1e6 }) + const decimals = isLocalRPC ? 18 : config.deployments[`netId${netId}`][currency].decimals + const fee = calculateFee({ gasPrices, currency, amount, refund, ethPrices, relayerServiceFee, decimals }) + if (fee.gt(fromDecimals({ amount, decimals }))) { + throw new Error('Too high refund') + } + const { proof, args } = await generateProof({ deposit, recipient, relayerAddress, fee, refund }) + + console.log('Sending withdraw transaction through relay') + try{ + const relay = await axios.post(relayerURL + '/relay', { contract: tornado._address, proof, args }) + if (netId === 1 || netId === 42) { + console.log(`Transaction submitted through the relay. View transaction on etherscan https://${networks[netId]}.etherscan.io/tx/${relay.data.txHash}`) + } else { + console.log(`Transaction submitted through the relay. The transaction hash is ${relay.data.txHash}`) + } + + const receipt = await waitForTxReceipt({ txHash: relay.data.txHash }) + console.log('Transaction mined in block', receipt.blockNumber) + } catch(e) { + if (e.response) { + console.error(e.response.data.error) + } else { + console.error(e.message) + } + } + } else { + const { proof, args } = await generateProof({ deposit, recipient, refund }) + + console.log('Submitting withdraw transaction') + await tornado.methods.withdraw(proof, ...args).send({ from: senderAccount, value: refund.toString(), gas: 1e6 }) + .on('transactionHash', function(txHash){ + if (netId === 1 || netId === 42) { + console.log(`View transaction on etherscan https://${networks[netId]}.etherscan.io/tx/${txHash}`) + } else { + console.log(`The transaction hash is ${txHash}`) + } + }).on('error', function(e){ + console.error('on transactionHash error', e.message) + }) + } console.log('Done') } -/** - * Do a ERC20 withdrawal - * @param noteString Note to withdraw - * @param recipient Recipient address - */ -async function withdrawErc20(noteString, recipient) { - const note = parseNote(noteString) - const { proof, args } = await generateProof(erc20tornado, note, recipient) +function fromDecimals({ amount, decimals }) { + amount = amount.toString() + let ether = amount.toString() + const base = new BN('10').pow(new BN(decimals)) + const baseLength = base.toString(10).length - 1 || 1 - console.log('Submitting withdraw transaction') - await erc20tornado.methods.withdraw(proof, ...args).send({ from: senderAccount, gas: 1e6 }) - console.log('Done') + const negative = ether.substring(0, 1) === '-' + if (negative) { + ether = ether.substring(1) + } + + if (ether === '.') { + throw new Error('[ethjs-unit] while converting number ' + amount + ' to wei, invalid value') + } + + // Split it into a whole and fractional part + const comps = ether.split('.') + if (comps.length > 2) { + throw new Error( + '[ethjs-unit] while converting number ' + amount + ' to wei, too many decimal points' + ) + } + + let whole = comps[0] + let fraction = comps[1] + + if (!whole) { + whole = '0' + } + if (!fraction) { + fraction = '0' + } + if (fraction.length > baseLength) { + throw new Error( + '[ethjs-unit] while converting number ' + amount + ' to wei, too many decimal places' + ) + } + + while (fraction.length < baseLength) { + fraction += '0' + } + + whole = new BN(whole) + fraction = new BN(fraction) + let wei = whole.mul(base).add(fraction) + + if (negative) { + wei = wei.mul(negative) + } + + return new BN(wei.toString(10), 10) } -/** - * Do an ETH withdrawal through relay - * @param noteString Note to withdraw - * @param recipient Recipient address - * @param relayUrl Relay url address - */ -async function withdrawRelay(noteString, recipient, relayUrl) { - const note = parseNote(noteString) - const resp = await axios.get(relayUrl + '/status') - const { relayerAddress, netId, gasPrices } = resp.data - assert(netId === await web3.eth.net.getId() || netId === '*', 'This relay is for different network') - console.log('Relay address: ', relayerAddress) - - const fee = bigInt(toWei(gasPrices.fast.toString(), 'gwei')).mul(bigInt(1e6)) - const { proof, args } = await generateProof(tornado, note, recipient, relayerAddress, fee) - - console.log('Sending withdraw transaction through relay') - const resp2 = await axios.post(relayUrl + '/relay', { contract: tornado._address, proof: { proof, publicSignals: args } }) - console.log(`Transaction submitted through relay, tx hash: ${resp2.data.txHash}`) - - const receipt = await waitForTxReceipt(resp2.data.txHash) - console.log('Transaction mined in block', receipt.blockNumber) - console.log('Done') -} - -/** - * Do a ERC20 withdrawal through relay - * @param noteString Note to withdraw - * @param recipient Recipient address - * @param relayUrl Relay url address - */ -async function withdrawRelayErc20(noteString, recipient, relayUrl) { - const note = parseNote(noteString) - const resp = await axios.get(relayUrl + '/status') - const { relayerAddress, netId, gasPrices, ethPriceInDai } = resp.data - assert(netId === await web3.eth.net.getId() || netId === '*', 'This relay is for different network') - console.log('Relay address: ', relayerAddress) - - const refund = bigInt(toWei('0.001')) - const fee = bigInt(toWei(gasPrices.fast.toString(), 'gwei')).mul(bigInt(1e6)).add(refund).mul(bigInt(fromWei(ethPriceInDai.toString()))) - const { proof, args } = await generateProof(erc20tornado, note, recipient, relayerAddress, fee, refund) - - console.log('Sending withdraw transaction through relay') - const resp2 = await axios.post(relayUrl + '/relay', { contract: erc20tornado._address, proof: { proof, publicSignals: args } }) - console.log(`Transaction submitted through relay, tx hash: ${resp2.data.txHash}`) - - const receipt = await waitForTxReceipt(resp2.data.txHash) - console.log('Transaction mined in block', receipt.blockNumber) - console.log('Done') +function calculateFee({ gasPrices, currency, amount, refund, ethPrices, relayerServiceFee, decimals }) { + const feePercent = toBN(fromDecimals({ amount, decimals })).mul(toBN(relayerServiceFee * 10)).div(toBN('1000')) + const expense = toBN(toWei(gasPrices.fast.toString(), 'gwei')).mul(toBN(5e5)) + let desiredFee + switch (currency) { + case 'eth': { + desiredFee = expense.add(feePercent) + break + } + default: { + desiredFee = + expense.add(toBN(refund)) + .mul(toBN(10 ** decimals)) + .div(toBN(ethPrices[currency])) + desiredFee = desiredFee.add(feePercent) + break + } + } + return desiredFee } /** @@ -250,7 +319,7 @@ async function withdrawRelayErc20(noteString, recipient, relayUrl) { * @param attempts * @param delay */ -function waitForTxReceipt(txHash, attempts = 60, delay = 1000) { +function waitForTxReceipt({ txHash, attempts = 60, delay = 1000 }) { return new Promise((resolve, reject) => { const checkForTx = async (txHash, retryAttempt = 0) => { const result = await web3.eth.getTransactionReceipt(txHash) @@ -268,6 +337,10 @@ function waitForTxReceipt(txHash, attempts = 60, delay = 1000) { }) } +/** + * Parses Tornado.cash note + * @param noteString the note + */ function parseNote(noteString) { const noteRegex = /tornado-(?\w+)-(?[\d.]+)-(?\d+)-0x(?[0-9a-fA-F]{124})/g const match = noteRegex.exec(noteString) @@ -278,20 +351,18 @@ function parseNote(noteString) { const buf = Buffer.from(match.groups.note, 'hex') const nullifier = bigInt.leBuff2int(buf.slice(0, 31)) const secret = bigInt.leBuff2int(buf.slice(31, 62)) - const deposit = createDeposit(nullifier, secret) - - + const deposit = createDeposit({ nullifier, secret }) const netId = Number(match.groups.netId) - const address = config.mixers['netId' + netId][match.groups.currency][match.groups.amount] - return { address, netId, deposit } + return { currency: match.groups.currency, amount: match.groups.amount, netId, deposit } } /** * Init web3, contracts, and snark */ -async function init() { - let contractJson, erc20ContractJson, erc20tornadoJson +async function init({ rpc, noteNetId, currency = 'dai', amount = '100' }) { + let contractJson, erc20ContractJson, erc20tornadoJson, tornadoAddress, tokenAddress + // TODO do we need this? should it work in browser really? if (inBrowser) { // Initialize using injected web3 (Metamask) // To assemble web version run `npm run browserify` @@ -304,7 +375,7 @@ async function init() { TOKEN_AMOUNT = 1e19 } else { // Initialize from local node - web3 = new Web3('https://mainnet.infura.io', null, { transactionConfirmationBlocks: 1 }) + web3 = new Web3(rpc, null, { transactionConfirmationBlocks: 1 }) contractJson = require('./build/contracts/ETHTornado.json') circuit = require('./build/circuits/withdraw.json') proving_key = fs.readFileSync('build/circuits/withdraw_proving_key.bin').buffer @@ -312,174 +383,110 @@ async function init() { MERKLE_TREE_HEIGHT = process.env.MERKLE_TREE_HEIGHT ETH_AMOUNT = process.env.ETH_AMOUNT TOKEN_AMOUNT = process.env.TOKEN_AMOUNT - ERC20_TOKEN = process.env.ERC20_TOKEN + PRIVATE_KEY = process.env.PRIVATE_KEY erc20ContractJson = require('./build/contracts/ERC20Mock.json') erc20tornadoJson = require('./build/contracts/ERC20Tornado.json') } groth16 = await buildGroth16() - const netId = await web3.eth.net.getId() - if (contractJson.networks[netId]) { - const tx = await web3.eth.getTransaction(contractJson.networks[netId].transactionHash) - tornado = new web3.eth.Contract(contractJson.abi, '0xb541fc07bC7619fD4062A54d96268525cBC6FfEF') - tornado.deployedBlock = tx.blockNumber + netId = await web3.eth.net.getId() + if (noteNetId && Number(noteNetId) !== netId) { + throw new Error('This note is for a different network. Specify the --rpc option explicitly') } + isLocalRPC = netId > 42 - const tx3 = await web3.eth.getTransaction(erc20tornadoJson.networks[netId].transactionHash) - erc20tornado = new web3.eth.Contract(erc20tornadoJson.abi, erc20tornadoJson.networks[netId].address) - erc20tornado.deployedBlock = tx3.blockNumber - - if(ERC20_TOKEN === '') { - erc20 = new web3.eth.Contract(erc20ContractJson.abi, erc20ContractJson.networks[netId].address) - const tx2 = await web3.eth.getTransaction(erc20ContractJson.networks[netId].transactionHash) - erc20.deployedBlock = tx2.blockNumber - } - - senderAccount = (await web3.eth.getAccounts())[0] - console.log('Loaded') -} - -// ========== CLI related stuff below ============== - -/** Print command line help */ -function printHelp(code = 0) { - console.log(`Usage: - Submit a deposit from default eth account and return the resulting note - $ ./cli.js deposit - $ ./cli.js depositErc20 - - Withdraw a note to 'recipient' account - $ ./cli.js withdraw [relayUrl] - $ ./cli.js withdrawErc20 [relayUrl] - - Check address balance - $ ./cli.js balance
- - Perform an automated test - $ ./cli.js test - $ ./cli.js testRelay - -Example: - $ ./cli.js deposit - ... - Your note: 0x1941fa999e2b4bfeec3ce53c2440c3bc991b1b84c9bb650ea19f8331baf621001e696487e2a2ee54541fa12f49498d71e24d00b1731a8ccd4f5f5126f3d9f400 - - $ ./cli.js withdraw 0x1941fa999e2b4bfeec3ce53c2440c3bc991b1b84c9bb650ea19f8331baf621001e696487e2a2ee54541fa12f49498d71e24d00b1731a8ccd4f5f5126f3d9f400 0xee6249BA80596A4890D1BD84dbf5E4322eA4E7f0 -`) - process.exit(code) -} - -/** Process command line args and run */ -async function runConsole(args) { - if (args.length === 0) { - printHelp() + if (isLocalRPC) { + tornadoAddress = currency === 'eth' ? contractJson.networks[netId].address : erc20tornadoJson.networks[netId].address + tokenAddress = currency !== 'eth' ? erc20ContractJson.networks[netId].address : null + senderAccount = (await web3.eth.getAccounts())[0] } else { - switch (args[0]) { - case 'deposit': - if (args.length === 1) { - await init() - await printBalance(tornado._address, 'Tornado') - await printBalance(senderAccount, 'Sender account') - await deposit() - await printBalance(tornado._address, 'Tornado') - await printBalance(senderAccount, 'Sender account') - } else { - printHelp(1) + try{ + tornadoAddress = config.deployments[`netId${netId}`][currency].instanceAddress[amount] + if (!tornadoAddress) { + throw new Error() } - break - case 'depositErc20': - if (args.length === 1) { - await init() - await printBalance(erc20tornado._address, 'Tornado') - await printBalance(senderAccount, 'Sender account') - await depositErc20() - await printBalance(erc20tornado._address, 'Tornado') - await printBalance(senderAccount, 'Sender account') - } else { - printHelp(1) - } - break - case 'balance': - if (args.length === 2 && /^0x[0-9a-fA-F]{40}$/.test(args[1])) { - await init() - await printBalance(args[1]) - } else { - printHelp(1) - } - break - case 'withdraw': - if (args.length >= 3 && args.length <= 4 && /^0x[0-9a-fA-F]{124}$/.test(args[1]) && /^0x[0-9a-fA-F]{40}$/.test(args[2])) { - await init() - await printBalance(tornado._address, 'Tornado') - await printBalance(args[2], 'Recipient account') - if (args[3]) { - await withdrawRelay(args[1], args[2], args[3]) - } else { - await withdraw(args[1], args[2]) - } - await printBalance(tornado._address, 'Tornado') - await printBalance(args[2], 'Recipient account') - } else { - printHelp(1) - } - break - case 'withdrawErc20': - if (args.length >= 3 && args.length <= 4 && /^0x[0-9a-fA-F]{124}$/.test(args[1]) && /^0x[0-9a-fA-F]{40}$/.test(args[2])) { - await init() - await printBalance(erc20tornado._address, 'Tornado') - await printBalance(args[2], 'Recipient account') - if (args[3]) { - await withdrawRelayErc20(args[1], args[2], args[3]) - } else { - await withdrawErc20(args[1], args[2]) - } - await printBalance(erc20tornado._address, 'Tornado') - await printBalance(args[2], 'Recipient account') - } else { - printHelp(1) - } - break - case 'test': - if (args.length === 1) { - await init() - const note1 = await deposit() - await withdraw(note1, senderAccount) - - const note2 = await depositErc20() - await withdrawErc20(note2, senderAccount) - } else { - printHelp(1) - } - break - case 'testRelay': - if (args.length === 1) { - await init() - const note1 = await deposit() - await withdrawRelay(note1, senderAccount, 'http://localhost:8000') - - const note2 = await depositErc20() - await withdrawRelayErc20(note2, senderAccount, 'http://localhost:8000') - } else { - printHelp(1) - } - break - - default: - printHelp(1) + tokenAddress = config.deployments[`netId${netId}`][currency].tokenAddress + const account = web3.eth.accounts.privateKeyToAccount('0x' + PRIVATE_KEY) + web3.eth.accounts.wallet.add('0x' + PRIVATE_KEY) + web3.eth.defaultAccount = account.address + senderAccount = account.address + } catch(e) { + console.error('There is no such tornado instance, check the currency and amount you provide') + process.exit(1) } } + tornado = new web3.eth.Contract(contractJson.abi, tornadoAddress) + erc20 = currency !== 'eth' ? new web3.eth.Contract(erc20ContractJson.abi, tokenAddress) : {} } -if (inBrowser) { - window.deposit = deposit - window.depositErc20 = depositErc20 - window.withdraw = async () => { - const note = prompt('Enter the note to withdraw') - const recipient = (await web3.eth.getAccounts())[0] - await withdraw(note, recipient) +async function main() { + process.setMaxListeners(30) + if (inBrowser) { + // window.deposit = deposit + // window.depositErc20 = depositErc20 + // window.withdraw = async () => { + // const note = prompt('Enter the note to withdraw') + // const recipient = (await web3.eth.getAccounts())[0] + // await withdraw(note, recipient) + // } + // init() + } else { + program + .option('-r, --rpc ', 'The RPC, CLI should interact with', 'http://localhost:8545') + .option('-R, --relayer ', 'Withdraw via relayer') + program + .command('deposit ') + .description('Submit a deposit of specified currency and amount from default eth account and return the resulting note. The currency is one of (ETH|DAI|cDAI|USDC|cUSDC|USDT). The amount depends on currency, see config.js file or visit https://tornado.cash.') + .action(async (currency, amount) => { + currency = currency.toLowerCase() + await init({ rpc: program.rpc, currency, amount }) + await deposit({ currency, amount }) + }) + program + .command('withdraw [ETH_purchase]') + .description('Withdraw a note to a recipient account using relayer or specified private key. You can exchange some of your deposit`s tokens to ETH during the withdrawal by specifing ETH_purchase (e.g. 0.01) to pay for gas in future transactions. Also see the --relayer option.') + .action(async (noteString, recipient, refund) => { + const { currency, amount, netId, deposit } = parseNote(noteString) + await init({ rpc: program.rpc, noteNetId: netId, currency, amount }) + await withdraw({ deposit, currency, amount, recipient, refund, relayerURL: program.relayer }) + }) + program + .command('balance
[token_address]') + .description('Check ETH and ERC20 balance') + .action(async (address, tokenAddress) => { + await init({ rpc: program.rpc }) + await printETHBalance({ address, name: '' }) + if (tokenAddress) { + await printERC20Balance({ address, name: '', tokenAddress }) + } + }) + program + .command('test') + .description('Perform an automated test. It deposits and withdraws one ETH and one ERC20 note. Uses ganache.') + .action(async () => { + console.log('Start performing ETH deposit-withdraw test') + let currency = 'eth' + let amount = '0.1' + await init({ rpc: program.rpc, currency, amount }) + let noteString = await deposit({ currency, amount }) + let parsedNote = parseNote(noteString) + await withdraw({ deposit: parsedNote.deposit, currency, amount, recipient: senderAccount, relayerURL: program.relayer }) + + console.log('\nStart performing DAI deposit-withdraw test') + currency = 'dai' + amount = '100' + await init({ rpc: program.rpc, currency, amount }) + noteString = await deposit({ currency, amount }) + ;(parsedNote = parseNote(noteString)) + await withdraw({ deposit: parsedNote.deposit, currency, amount, recipient: senderAccount, refund: '0.02', relayerURL: program.relayer }) + }) + try { + await program.parseAsync(process.argv) + } catch(e) { + console.log('Error:', e) + process.exit(1) + } + process.exit(0) } - init() -} else { - runConsole(process.argv.slice(2)) - .then(() => process.exit(0)) - .catch(err => { console.log(err); process.exit(1) }) } + +main() diff --git a/config.js b/config.js index dd1a26f..3b1bce5 100644 --- a/config.js +++ b/config.js @@ -5,13 +5,13 @@ module.exports = { netId: Number(process.env.NET_ID) || 42, redisUrl: process.env.REDIS_URL, rpcUrl: process.env.RPC_URL || 'https://kovan.infura.io/', - oracleRpcUrl: process.env.ORACLE_RPC_URL || 'https://mainnet.infura.io/', + oracleRpcUrl: process.env.ORACLE_RPC_URL || 'https://cloudflare-eth.com', oracleAddress: '0xB5eE7907FF5f4c1FC9086Fc117E6c397431F39ad', privateKey: process.env.PRIVATE_KEY, - mixers: { + deployments: { netId1: { eth: { - mixerAddress: { + instanceAddress: { '0.1': '0x12D66f87A04A9E220743712cE6d9bB1B5616B8Fc', '1': '0x47CE0C6eD5B0Ce3d3A51fdb1C52DC66a7c3c2936', '10': '0x910Cbd523D972eb0a6f4cAe4618aD62622b39DbF', @@ -21,7 +21,7 @@ module.exports = { decimals: 18 }, dai: { - mixerAddress: { + instanceAddress: { '100': '0xD4B88Df4D29F5CedD6857912842cff3b20C8Cfa3', '1000': '0xFD8610d20aA15b7B2E3Be39B396a1bC3516c7144', '10000': '0xF60dD140cFf0706bAE9Cd734Ac3ae76AD9eBC32A', @@ -32,7 +32,7 @@ module.exports = { decimals: 18 }, cdai: { - mixerAddress: { + instanceAddress: { '5000': '0x22aaA7720ddd5388A3c0A3333430953C68f1849b', '50000': '0xBA214C1c1928a32Bffe790263E38B4Af9bFCD659', '500000': '0xb1C8094B234DcE6e03f10a5b673c1d8C69739A00', @@ -43,7 +43,7 @@ module.exports = { decimals: 8 }, usdc: { - mixerAddress: { + instanceAddress: { '100': '0xd96f2B1c14Db8458374d9Aca76E26c3D18364307', '1000': '0x4736dCf1b7A3d580672CcE6E7c65cd5cc9cFBa9D', '10000': '0xD691F27f38B395864Ea86CfC7253969B409c362d', @@ -54,7 +54,7 @@ module.exports = { decimals: 6 }, cusdc: { - mixerAddress: { + instanceAddress: { '5000': '0xaEaaC358560e11f52454D997AAFF2c5731B6f8a6', '50000': '0x1356c899D8C9467C7f71C195612F8A395aBf2f0a', '500000': '0xA60C772958a3eD56c1F15dD055bA37AC8e523a0D', @@ -65,7 +65,7 @@ module.exports = { decimals: 8 }, usdt: { - mixerAddress: { + instanceAddress: { '100': '0x169AD27A470D064DEDE56a2D3ff727986b15D52B', '1000': '0x0836222F2B2B24A3F36f98668Ed8F0B38D1a872f', '10000': '0xF67721A2D8F736E75a49FdD7FAd2e31D8676542a', @@ -78,7 +78,7 @@ module.exports = { }, netId42: { eth: { - mixerAddress: { + instanceAddress: { '0.1': '0x8b3f5393bA08c24cc7ff5A66a832562aAB7bC95f', '1': '0xD6a6AC46d02253c938B96D12BE439F570227aE8E', '10': '0xe1BE96331391E519471100c3c1528B66B8F4e5a7', @@ -88,7 +88,7 @@ module.exports = { decimals: 18 }, dai: { - mixerAddress: { + instanceAddress: { '100': '0xdf2d3cC5F361CF95b3f62c4bB66deFe3FDE47e3D', '1000': '0xD96291dFa35d180a71964D0894a1Ae54247C4ccD', '10000': '0xb192794f72EA45e33C3DF6fe212B9c18f6F45AE3', @@ -99,7 +99,7 @@ module.exports = { decimals: 18 }, cdai: { - mixerAddress: { + instanceAddress: { '5000': '0x6Fc9386ABAf83147b3a89C36D422c625F44121C8', '50000': '0x7182EA067e0f050997444FCb065985Fd677C16b6', '500000': '0xC22ceFd90fbd1FdEeE554AE6Cc671179BC3b10Ae', @@ -110,7 +110,7 @@ module.exports = { decimals: 8 }, usdc: { - mixerAddress: { + instanceAddress: { '100': '0x137E2B6d185018e7f09f6cf175a970e7fC73826C', '1000': '0xcC7f1633A5068E86E3830e692e3e3f8f520525Af', '10000': '0x28C8f149a0ab8A9bdB006B8F984fFFCCE52ef5EF', @@ -121,7 +121,7 @@ module.exports = { decimals: 6 }, cusdc: { - mixerAddress: { + instanceAddress: { '5000': '0xc0648F28ABA385c8a1421Bbf1B59e3c474F89cB0', '50000': '0x0C53853379c6b1A7B74E0A324AcbDD5Eabd4981D', '500000': '0xf84016A0E03917cBe700D318EB1b7a53e6e3dEe1', @@ -132,7 +132,7 @@ module.exports = { decimals: 8 }, usdt: { - mixerAddress: { + instanceAddress: { '100': '0x327853Da7916a6A0935563FB1919A48843036b42', '1000': '0x531AA4DF5858EA1d0031Dad16e3274609DE5AcC0', '10000': '0x0958275F0362cf6f07D21373aEE0cf37dFe415dD', diff --git a/package-lock.json b/package-lock.json index 1eb4ecc..4c9d15b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1809,12 +1809,9 @@ } }, "commander": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.8.1.tgz", - "integrity": "sha1-Br42f+v9oMMwqh4qBy09yXYkJdQ=", - "requires": { - "graceful-readlink": ">= 1.0.0" - } + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==" }, "concat-map": { "version": "0.0.1", @@ -6259,6 +6256,16 @@ "integrity": "sha1-z+kXyz0nS8/6x5J1ivUxc+sfq9w=", "requires": { "commander": "~2.8.1" + }, + "dependencies": { + "commander": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.8.1.tgz", + "integrity": "sha1-Br42f+v9oMMwqh4qBy09yXYkJdQ=", + "requires": { + "graceful-readlink": ">= 1.0.0" + } + } } }, "semaphore": { diff --git a/package.json b/package.json index 604ef88..f4588f1 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,7 @@ "chai-as-promised": "^7.1.1", "circom": "0.0.34", "circomlib": "git+https://github.com/tornadocash/circomlib.git#347822604996bf25f659f96ee0f02810a1f71bb0", + "commander": "^4.1.1", "dotenv": "^8.2.0", "eslint": "^6.6.0", "ganache-cli": "^6.7.0", From 8afd208765f82bd705e79d3ce5b1f4e7359f9997 Mon Sep 17 00:00:00 2001 From: Alexey Date: Thu, 27 Feb 2020 10:46:43 +0300 Subject: [PATCH 3/6] fix bugs --- cli.js | 30 +++++++++++++++--------------- test.js | 22 ++++++++++++++++++++++ 2 files changed, 37 insertions(+), 15 deletions(-) create mode 100644 test.js diff --git a/cli.js b/cli.js index 89a126a..1d582ed 100755 --- a/cli.js +++ b/cli.js @@ -1,6 +1,7 @@ #!/usr/bin/env node // Temporary demo client // Works both in browser and node.js +require('dotenv').config() const fs = require('fs') const axios = require('axios') const assert = require('assert') @@ -77,7 +78,7 @@ async function deposit({ currency, amount }) { await tornado.methods.deposit(toHex(deposit.commitment)).send({ value, from: senderAccount, gas:2e6 }) await printETHBalance({ address: tornado._address, name: 'Tornado' }) await printETHBalance({ address: senderAccount, name: 'Sender account' }) - } else { + } else { // a token await printERC20Balance({ address: tornado._address, name: 'Tornado' }) await printERC20Balance({ address: senderAccount, name: 'Sender account' }) const decimals = isLocalRPC ? 18 : config.deployments[`netId${netId}`][currency].decimals @@ -130,12 +131,12 @@ async function generateMerkleProof(deposit) { assert(leafIndex >= 0, 'The deposit is not found in the tree') // Compute merkle proof of our commitment - return await tree.path(leafIndex) + return tree.path(leafIndex) } /** * Generate SNARK proof for withdrawal - * @param note Note + * @param deposit Deposit object * @param recipient Funds recipient * @param relayer Relayer address * @param fee Relayer fee @@ -221,7 +222,7 @@ async function withdraw({ deposit, currency, amount, recipient, relayerURL, refu console.error(e.message) } } - } else { + } else { // using private key const { proof, args } = await generateProof({ deposit, recipient, refund }) console.log('Submitting withdraw transaction') @@ -366,20 +367,19 @@ async function init({ rpc, noteNetId, currency = 'dai', amount = '100' }) { if (inBrowser) { // Initialize using injected web3 (Metamask) // To assemble web version run `npm run browserify` - web3 = new Web3(window.web3.currentProvider, null, { transactionConfirmationBlocks: 1 }) - contractJson = await (await fetch('build/contracts/ETHTornado.json')).json() - circuit = await (await fetch('build/circuits/withdraw.json')).json() - proving_key = await (await fetch('build/circuits/withdraw_proving_key.bin')).arrayBuffer() - MERKLE_TREE_HEIGHT = 16 - ETH_AMOUNT = 1e18 - TOKEN_AMOUNT = 1e19 + // web3 = new Web3(window.web3.currentProvider, null, { transactionConfirmationBlocks: 1 }) + // contractJson = await (await fetch('build/contracts/ETHTornado.json')).json() + // circuit = await (await fetch('build/circuits/withdraw.json')).json() + // proving_key = await (await fetch('build/circuits/withdraw_proving_key.bin')).arrayBuffer() + // MERKLE_TREE_HEIGHT = 16 + // ETH_AMOUNT = 1e18 + // TOKEN_AMOUNT = 1e19 } else { // Initialize from local node web3 = new Web3(rpc, null, { transactionConfirmationBlocks: 1 }) contractJson = require('./build/contracts/ETHTornado.json') circuit = require('./build/circuits/withdraw.json') proving_key = fs.readFileSync('build/circuits/withdraw_proving_key.bin').buffer - require('dotenv').config() MERKLE_TREE_HEIGHT = process.env.MERKLE_TREE_HEIGHT ETH_AMOUNT = process.env.ETH_AMOUNT TOKEN_AMOUNT = process.env.TOKEN_AMOUNT @@ -387,6 +387,7 @@ async function init({ rpc, noteNetId, currency = 'dai', amount = '100' }) { erc20ContractJson = require('./build/contracts/ERC20Mock.json') erc20tornadoJson = require('./build/contracts/ERC20Tornado.json') } + // groth16 initialises a lot of Promises that will never be resolved, that's why we need to use process.exit to terminate the CLI groth16 = await buildGroth16() netId = await web3.eth.net.getId() if (noteNetId && Number(noteNetId) !== netId) { @@ -407,6 +408,7 @@ async function init({ rpc, noteNetId, currency = 'dai', amount = '100' }) { tokenAddress = config.deployments[`netId${netId}`][currency].tokenAddress const account = web3.eth.accounts.privateKeyToAccount('0x' + PRIVATE_KEY) web3.eth.accounts.wallet.add('0x' + PRIVATE_KEY) + // eslint-disable-next-line require-atomic-updates web3.eth.defaultAccount = account.address senderAccount = account.address } catch(e) { @@ -419,7 +421,6 @@ async function init({ rpc, noteNetId, currency = 'dai', amount = '100' }) { } async function main() { - process.setMaxListeners(30) if (inBrowser) { // window.deposit = deposit // window.depositErc20 = depositErc20 @@ -485,8 +486,7 @@ async function main() { console.log('Error:', e) process.exit(1) } - process.exit(0) } } -main() +main().then(process.exit(0)) diff --git a/test.js b/test.js new file mode 100644 index 0000000..a76075d --- /dev/null +++ b/test.js @@ -0,0 +1,22 @@ +const program = require('commander') +const buildGroth16 = require('websnark/src/groth16') + +const sleep = () => { + return new Promise(resolve => setTimeout(resolve, 100)) +} + +async function main() { + program + .command('deposit ') + .description('Submit a deposit of specified currency and amount from default eth account and return the resulting note. The currency is one of (ETH|DAI|cDAI|USDC|cUSDC|USDT). The amount depends on currency, see config.js file or visit https://tornado.cash.') + .action(async (currency, amount) => { + console.log('currency, amount', currency, amount) + let groth16 = await buildGroth16() + console.log('groth16', groth16) + groth16 = null + }) + + await program.parseAsync(process.argv) +} + +main().then(process.exit(0)) From 62c7951961bac5003a901d863c5b47fd823413f7 Mon Sep 17 00:00:00 2001 From: Alexey Date: Thu, 27 Feb 2020 16:32:10 +0300 Subject: [PATCH 4/6] fix browser version; readme update --- README.md | 45 ++++++++++++++++++++++++++++++++----------- cli.js | 51 ++++++++++++++++++++++++++++--------------------- downloadKeys.js | 43 +++++++++++++++++++++++++++++++++++++++++ package.json | 3 ++- 4 files changed, 108 insertions(+), 34 deletions(-) create mode 100644 downloadKeys.js diff --git a/README.md b/README.md index 216c3f7..59b77f7 100644 --- a/README.md +++ b/README.md @@ -53,20 +53,43 @@ Use browser version on Kovan: 1. `npx http-server` - serve current dir, you can use any other static http server 1. Open `localhost:8080` -Use with command line version with Ganache: -### ETHTornado -1. `npm run migrate:dev` -1. `./cli.js deposit` -1. `./cli.js withdraw ` -1. `./cli.js balance ` +Use with command line version. Works for Ganache, Kovan and Mainnet: +### Initialization +1. `cp .env.example .env` +1. `npm run download` +1. `npm run build:contract` -### ERC20Tornado +### Ganache +1. make sure you complete steps from Initialization +1. `ganache-cli -i 1337` 1. `npm run migrate:dev` -1. `./cli.js depositErc20` -1. `./cli.js withdrawErc20 ` -1. `./cli.js balanceErc20 ` +1. `./cli.js test` +1. `./cli.js --help` -If you want, you can point the app to existing tornado contracts on Mainnet or Kovan. It should work without any problems +### Kovan, Mainnet +1. make sure you complete steps from Initialization +1. Add `PRIVATE_KEY` to `.env` file +1. `./cli.js --help` + +Example: +```bash +./cli.js deposit ETH 0.1 --rpc https://kovan.infura.io/v3/27a9649f826b4e31a83e07ae09a87448 +Your note: tornado-eth-0.1-42-0xf73dd6833ccbcc046c44228c8e2aa312bf49e08389dadc7c65e6a73239867b7ef49c705c4db227e2fadd8489a494b6880bdcb6016047e019d1abec1c7652 +Tornado ETH balance is 8.9 +Sender account ETH balance is 1004873.470619891361352542 +Submitting deposit transaction +Tornado ETH balance is 9 +Sender account ETH balance is 1004873.361652048361352542 + +./cli.js withdraw tornado-eth-0.1-42-0xf73dd6833ccbcc046c44228c8e2aa312bf49e08389dadc7c65e6a73239867b7ef49c705c4db227e2fadd8489a494b6880bdcb6016047e019d1abec1c7652 0x8589427373D6D84E98730D7795D8f6f8731FDA16 --rpc https://kovan.infura.io/v3/27a9649f826b4e31a83e07ae09a87448 --relayer https://kovan-frelay.duckdns.orgRelay address: 0x6A31736e7490AbE5D5676be059DFf064AB4aC754 +Getting current state from tornado contract +Generating SNARK proof +Proof time: 9117.051ms +Sending withdraw transaction through relay +Transaction submitted through the relay. View transaction on etherscan https://kovan.etherscan.io/tx/0xcb21ae8cad723818c6bc7273e83e00c8393fcdbe74802ce5d562acad691a2a7b +Transaction mined in block 17036120 +Done +``` ## Deploy ETH Tornado Cash 1. `cp .env.example .env` diff --git a/cli.js b/cli.js index 1d582ed..838864a 100755 --- a/cli.js +++ b/cli.js @@ -1,6 +1,7 @@ -#!/usr/bin/env node +#!/usr/bin/env NODE_OPTIONS=--no-warnings node // Temporary demo client // Works both in browser and node.js + require('dotenv').config() const fs = require('fs') const axios = require('axios') @@ -367,13 +368,14 @@ async function init({ rpc, noteNetId, currency = 'dai', amount = '100' }) { if (inBrowser) { // Initialize using injected web3 (Metamask) // To assemble web version run `npm run browserify` - // web3 = new Web3(window.web3.currentProvider, null, { transactionConfirmationBlocks: 1 }) - // contractJson = await (await fetch('build/contracts/ETHTornado.json')).json() - // circuit = await (await fetch('build/circuits/withdraw.json')).json() - // proving_key = await (await fetch('build/circuits/withdraw_proving_key.bin')).arrayBuffer() - // MERKLE_TREE_HEIGHT = 16 - // ETH_AMOUNT = 1e18 - // TOKEN_AMOUNT = 1e19 + web3 = new Web3(window.web3.currentProvider, null, { transactionConfirmationBlocks: 1 }) + contractJson = await (await fetch('build/contracts/ETHTornado.json')).json() + circuit = await (await fetch('build/circuits/withdraw.json')).json() + proving_key = await (await fetch('build/circuits/withdraw_proving_key.bin')).arrayBuffer() + MERKLE_TREE_HEIGHT = 20 + ETH_AMOUNT = 1e18 + TOKEN_AMOUNT = 1e19 + senderAccount = (await web3.eth.getAccounts())[0] } else { // Initialize from local node web3 = new Web3(rpc, null, { transactionConfirmationBlocks: 1 }) @@ -386,6 +388,10 @@ async function init({ rpc, noteNetId, currency = 'dai', amount = '100' }) { PRIVATE_KEY = process.env.PRIVATE_KEY erc20ContractJson = require('./build/contracts/ERC20Mock.json') erc20tornadoJson = require('./build/contracts/ERC20Tornado.json') + const account = web3.eth.accounts.privateKeyToAccount('0x' + PRIVATE_KEY) + web3.eth.accounts.wallet.add('0x' + PRIVATE_KEY) + web3.eth.defaultAccount = account.address + senderAccount = account.address } // groth16 initialises a lot of Promises that will never be resolved, that's why we need to use process.exit to terminate the CLI groth16 = await buildGroth16() @@ -406,11 +412,6 @@ async function init({ rpc, noteNetId, currency = 'dai', amount = '100' }) { throw new Error() } tokenAddress = config.deployments[`netId${netId}`][currency].tokenAddress - const account = web3.eth.accounts.privateKeyToAccount('0x' + PRIVATE_KEY) - web3.eth.accounts.wallet.add('0x' + PRIVATE_KEY) - // eslint-disable-next-line require-atomic-updates - web3.eth.defaultAccount = account.address - senderAccount = account.address } catch(e) { console.error('There is no such tornado instance, check the currency and amount you provide') process.exit(1) @@ -422,14 +423,19 @@ async function init({ rpc, noteNetId, currency = 'dai', amount = '100' }) { async function main() { if (inBrowser) { - // window.deposit = deposit - // window.depositErc20 = depositErc20 - // window.withdraw = async () => { - // const note = prompt('Enter the note to withdraw') - // const recipient = (await web3.eth.getAccounts())[0] - // await withdraw(note, recipient) - // } - // init() + const instance = { currency: 'eth', amount: '0.1' } + await init(instance) + window.deposit = async () => { + await deposit(instance) + } + window.withdraw = async () => { + const noteString = prompt('Enter the note to withdraw') + const recipient = (await web3.eth.getAccounts())[0] + + const { currency, amount, netId, deposit } = parseNote(noteString) + await init({ noteNetId: netId, currency, amount }) + await withdraw({ deposit, currency, amount, recipient }) + } } else { program .option('-r, --rpc ', 'The RPC, CLI should interact with', 'http://localhost:8545') @@ -482,6 +488,7 @@ async function main() { }) try { await program.parseAsync(process.argv) + process.exit(0) } catch(e) { console.log('Error:', e) process.exit(1) @@ -489,4 +496,4 @@ async function main() { } } -main().then(process.exit(0)) +main() diff --git a/downloadKeys.js b/downloadKeys.js new file mode 100644 index 0000000..da966ea --- /dev/null +++ b/downloadKeys.js @@ -0,0 +1,43 @@ +const axios = require('axios') +const path = require('path') +const fs = require('fs') +const files = ['withdraw.json', 'withdraw_proving_key.bin', 'Verifier.sol', 'withdraw_verification_key.json'] +const circuitsPath = 'build/circuits' +const contractsPath = 'build/contracts' + +async function downloadFile({ url, path }) { + const writer = fs.createWriteStream(path) + + const response = await axios({ + url, + method: 'GET', + responseType: 'stream' + }) + + response.data.pipe(writer) + + return new Promise((resolve, reject) => { + writer.on('finish', resolve) + writer.on('error', reject) + }) +} + +async function main() { + const release = await axios.get('https://api.github.com/repos/tornadocash/tornado-core/releases/latest') + const { assets } = release.data + if (!fs.existsSync(circuitsPath)){ + fs.mkdirSync(circuitsPath, { recursive: true }) + fs.mkdirSync(contractsPath, { recursive: true }) + } + for(let asset of assets) { + if (files.includes(asset.name)) { + console.log(`Downloading ${asset.name} ...`) + await downloadFile({ + url: asset.browser_download_url, + path: path.resolve(__dirname, circuitsPath, asset.name) + }) + } + } +} + +main() diff --git a/package.json b/package.json index f4588f1..cec34d8 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,8 @@ "migrate:rinkeby": "npx truffle migrate --network rinkeby --reset", "migrate:mainnet": "npx truffle migrate --network mainnet", "eslint": "npx eslint --ignore-path .gitignore .", - "flat": "npx truffle-flattener contracts/ETHTornado.sol > ETHTornado_flat.sol && npx truffle-flattener contracts/ERC20Tornado.sol > ERC20Tornado_flat.sol" + "flat": "npx truffle-flattener contracts/ETHTornado.sol > ETHTornado_flat.sol && npx truffle-flattener contracts/ERC20Tornado.sol > ERC20Tornado_flat.sol", + "download": "node downloadKeys.js" }, "keywords": [], "author": "", From 3e9df20f35334999aadecee7b7e3bb71e844b343 Mon Sep 17 00:00:00 2001 From: Alexey Date: Thu, 27 Feb 2020 16:36:44 +0300 Subject: [PATCH 5/6] tidy --- config.js | 13 +------------ test.js | 22 ---------------------- 2 files changed, 1 insertion(+), 34 deletions(-) delete mode 100644 test.js diff --git a/config.js b/config.js index 3b1bce5..65d7f2a 100644 --- a/config.js +++ b/config.js @@ -1,13 +1,6 @@ require('dotenv').config() module.exports = { - version: '2.2', - netId: Number(process.env.NET_ID) || 42, - redisUrl: process.env.REDIS_URL, - rpcUrl: process.env.RPC_URL || 'https://kovan.infura.io/', - oracleRpcUrl: process.env.ORACLE_RPC_URL || 'https://cloudflare-eth.com', - oracleAddress: '0xB5eE7907FF5f4c1FC9086Fc117E6c397431F39ad', - privateKey: process.env.PRIVATE_KEY, deployments: { netId1: { eth: { @@ -143,9 +136,5 @@ module.exports = { decimals: 6 } } - }, - defaultGasPrice: 2, - gasOracleUrls: ['https://ethgasstation.info/json/ethgasAPI.json', 'https://gasprice.poa.network/'], - port: process.env.APP_PORT, - relayerServiceFee: Number(process.env.RELAYER_FEE) + } } diff --git a/test.js b/test.js deleted file mode 100644 index a76075d..0000000 --- a/test.js +++ /dev/null @@ -1,22 +0,0 @@ -const program = require('commander') -const buildGroth16 = require('websnark/src/groth16') - -const sleep = () => { - return new Promise(resolve => setTimeout(resolve, 100)) -} - -async function main() { - program - .command('deposit ') - .description('Submit a deposit of specified currency and amount from default eth account and return the resulting note. The currency is one of (ETH|DAI|cDAI|USDC|cUSDC|USDT). The amount depends on currency, see config.js file or visit https://tornado.cash.') - .action(async (currency, amount) => { - console.log('currency, amount', currency, amount) - let groth16 = await buildGroth16() - console.log('groth16', groth16) - groth16 = null - }) - - await program.parseAsync(process.argv) -} - -main().then(process.exit(0)) From 0e0ac72b0f27fde84b374a1ae79e012f1eae45d6 Mon Sep 17 00:00:00 2001 From: Alexey Date: Thu, 27 Feb 2020 16:40:21 +0300 Subject: [PATCH 6/6] readme fix --- README.md | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 59b77f7..43c505f 100644 --- a/README.md +++ b/README.md @@ -74,22 +74,27 @@ Use with command line version. Works for Ganache, Kovan and Mainnet: Example: ```bash ./cli.js deposit ETH 0.1 --rpc https://kovan.infura.io/v3/27a9649f826b4e31a83e07ae09a87448 -Your note: tornado-eth-0.1-42-0xf73dd6833ccbcc046c44228c8e2aa312bf49e08389dadc7c65e6a73239867b7ef49c705c4db227e2fadd8489a494b6880bdcb6016047e019d1abec1c7652 -Tornado ETH balance is 8.9 -Sender account ETH balance is 1004873.470619891361352542 -Submitting deposit transaction -Tornado ETH balance is 9 -Sender account ETH balance is 1004873.361652048361352542 - -./cli.js withdraw tornado-eth-0.1-42-0xf73dd6833ccbcc046c44228c8e2aa312bf49e08389dadc7c65e6a73239867b7ef49c705c4db227e2fadd8489a494b6880bdcb6016047e019d1abec1c7652 0x8589427373D6D84E98730D7795D8f6f8731FDA16 --rpc https://kovan.infura.io/v3/27a9649f826b4e31a83e07ae09a87448 --relayer https://kovan-frelay.duckdns.orgRelay address: 0x6A31736e7490AbE5D5676be059DFf064AB4aC754 -Getting current state from tornado contract -Generating SNARK proof -Proof time: 9117.051ms -Sending withdraw transaction through relay -Transaction submitted through the relay. View transaction on etherscan https://kovan.etherscan.io/tx/0xcb21ae8cad723818c6bc7273e83e00c8393fcdbe74802ce5d562acad691a2a7b -Transaction mined in block 17036120 -Done ``` +> Your note: tornado-eth-0.1-42-0xf73dd6833ccbcc046c44228c8e2aa312bf49e08389dadc7c65e6a73239867b7ef49c705c4db227e2fadd8489a494b6880bdcb6016047e019d1abec1c7652 +> Tornado ETH balance is 8.9 +> Sender account ETH balance is 1004873.470619891361352542 +> Submitting deposit transaction +> Tornado ETH balance is 9 +> Sender account ETH balance is 1004873.361652048361352542 + +```bash +./cli.js withdraw tornado-eth-0.1-42-0xf73dd6833ccbcc046c44228c8e2aa312bf49e08389dadc7c65e6a73239867b7ef49c705c4db227e2fadd8489a494b6880bdcb6016047e019d1abec1c7652 0x8589427373D6D84E98730D7795D8f6f8731FDA16 --rpc https://kovan.infura.io/v3/27a9649f826b4e31a83e07ae09a87448 --relayer https://kovan-frelay.duckdns.org +``` + +> Relay address: 0x6A31736e7490AbE5D5676be059DFf064AB4aC754 +> Getting current state from tornado contract +> Generating SNARK proof +> Proof time: 9117.051ms +> Sending withdraw transaction through relay +> Transaction submitted through the relay. View transaction on etherscan https://kovan.etherscan.io/tx/0xcb21ae8cad723818c6bc7273e83e00c8393fcdbe74802ce5d562acad691a2a7b +> Transaction mined in block 17036120 +> Done + ## Deploy ETH Tornado Cash 1. `cp .env.example .env`