mirror of
https://github.com/tornadocash/tornado-core.git
synced 2024-12-22 17:23:38 +01:00
add comments, improve readability, improve readme, fix default values
This commit is contained in:
parent
51b06ed661
commit
d39eb3ca4b
@ -1,5 +1,5 @@
|
||||
MERKLE_TREE_HEIGHT=16
|
||||
# in wei
|
||||
AMOUNT=1000000000000000000
|
||||
EMPTY_ELEMENT=1337
|
||||
EMPTY_ELEMENT=1
|
||||
PRIVATE_KEY=
|
||||
|
38
README.md
38
README.md
@ -1,20 +1,29 @@
|
||||
# Tornado mixer [![Build Status](https://travis-ci.org/peppersec/tornado-mixer.svg?branch=master)](https://travis-ci.org/peppersec/tornado-mixer)
|
||||
|
||||
![mixer image](./mixer.png)
|
||||
Tornado is a non-custodial Ethereum and ERC20 mixer based on zkSNARKs. It improves transaction privacy by breaking the on-chain link between recipient and destination addresses. It uses a smart contract that accepts ETH deposits that can be withdrawn by a different address. Whenever ETH is withdrawn by the new address, there is no way to link the withdrawal to the deposit, ensuring complete privacy.
|
||||
|
||||
To make a deposit user generates a secret and sends its hash (called a commitment) along with deposit amount to the Tornado smart contract. The contract accepts the deposit and adds the commitment to its list of deposits.
|
||||
|
||||
Later, the user decides to make a withdraw. In order to do that the user should provide a proof that he or she possesses a secret to an unspent commitment from the smart contract’s list of deposits. zkSnark technology allows to do that without revealing which exact deposit corresponds to this secret. The smart contract will check the proof, and transfer deposited funds to the address specified for withdrawal. An external observer will be unable to determine which deposit this withdrawal comes from.
|
||||
|
||||
You can read more about it in [this medium article](https://medium.com/@tornado.cash.mixer/introducing-private-transactions-on-ethereum-now-42ee915babe0)
|
||||
|
||||
## Specs
|
||||
- Deposit gas cost: deposit 888054
|
||||
- Deposit gas const: 888054 (43381 + 50859 * tree_depth)
|
||||
- Withdraw gas cost: 692133
|
||||
- Circuit constraints: 22617
|
||||
- Circuit proving time: 6116ms
|
||||
- Circuit Constraints = 22617 (1869 + 1325 * tree_depth)
|
||||
- Circuit Proof time = 6116ms (1071 + 347 * tree_depth)
|
||||
- Serverless
|
||||
|
||||
![mixer image](./mixer.png)
|
||||
|
||||
## Security risks
|
||||
* Cryptographic tools used by mixer (zkSNARKS, Pedersen commitment, MiMC hash) are not yet extensively audited by cryptographic experts and may be vulnerable
|
||||
* Note: we use MiMC hash only for merkle tree, so even if a preimage attack on MiMC is discovered, it will not allow to deanonymize users. To drain funds attacker needs to be able to generate arbitrary hash collisions, which is a pretty strong assumption.
|
||||
* Bugs in contract. Even though we have an extensive experience in smart contract security audits, we can still make mistakes. An external audit is needed to reduce probablility of bugs. Our mixer is currently being audited, stay tuned.
|
||||
* Relayer is frontrunnable. When relayer submits a transaction someone can see it in tx pool and frontrun it with higher gas price to get the fee and drain relayer funds.
|
||||
* Workaround: we can set high gas price so that (almost) all fee is used on gas. The relayer will not receive profit this way, but this approach is acceptable until we develop more sophisticated system that prevents frontrunning
|
||||
* Bugs in contract. Even though we have an extensive experience in smart contract security audits, we can still make mistakes. An external audit is needed to reduce probablility of bugs
|
||||
* Workaround: we can set high gas price so that (almost) all fee is used on gas
|
||||
* Second workaround: allow only single hardcoded relayer, we use this approach for now
|
||||
* ~~Nullifier griefing. when you submit a withdraw transaction you reveal the nullifier for your note. If someone manages to
|
||||
make a deposit with the same nullifier and withdraw it while your transaction is still in tx pool, your note will be considered
|
||||
spent since it has the same nullifier and it will prevent you from withdrawing your funds~~
|
||||
@ -25,22 +34,33 @@ spent since it has the same nullifier and it will prevent you from withdrawing y
|
||||
2. `npm install -g npx`
|
||||
|
||||
## Usage
|
||||
1. `npm i`
|
||||
|
||||
You can see example usage in cli.js, it works both in console and in browser.
|
||||
|
||||
1. `npm install`
|
||||
1. `cp .env.example .env`
|
||||
1. `npm run build:circuit` - may take 10 minutes or more
|
||||
1. `npm run build:circuit` - this may take 10 minutes or more
|
||||
1. `npm run build:contract`
|
||||
1. `npm run browserify`
|
||||
1. `npx ganache-cli`
|
||||
1. `npm run test` - optionally run tests. It may fail for the first time, just run one more time.
|
||||
|
||||
Use with command line version with Ganache:
|
||||
|
||||
1. `npm run migrate:dev`
|
||||
1. `./cli.js deposit`
|
||||
1. `./cli.js withdraw <note from previous step> <destination eth address>`
|
||||
1. `./cli.js balance <destination eth address>`
|
||||
|
||||
Use browser version on Kovan:
|
||||
|
||||
1. `vi .env` - add your Kovan private key to deploy contracts
|
||||
1. `npm run migrate`
|
||||
1. `npx http-server` - serve current dir, you can use any other http server
|
||||
1. `npx http-server` - serve current dir, you can use any other static http server
|
||||
1. Open `localhost:8080`
|
||||
|
||||
If you want, you can point the app to existing tornado contracts on Mainnet or Kovan, it should work without any changes
|
||||
|
||||
## Credits
|
||||
|
||||
Special thanks to @barryWhiteHat and @kobigurk for valuable input,
|
||||
|
83
cli.js
83
cli.js
@ -14,11 +14,16 @@ const websnarkUtils = require('websnark/src/utils')
|
||||
|
||||
let web3, mixer, circuit, proving_key, groth16
|
||||
let MERKLE_TREE_HEIGHT, AMOUNT, EMPTY_ELEMENT
|
||||
const inBrowser = (typeof window !== 'undefined')
|
||||
|
||||
/** Generate random number of specified byte length */
|
||||
const rbigint = (nbytes) => snarkjs.bigInt.leBuff2int(crypto.randomBytes(nbytes))
|
||||
|
||||
/** Compute pedersen hash */
|
||||
const pedersenHash = (data) => circomlib.babyJub.unpackPoint(circomlib.pedersenHash.hash(data))[0]
|
||||
|
||||
/**
|
||||
* Create deposit object from secret and nullifier
|
||||
*/
|
||||
function createDeposit(nullifier, secret) {
|
||||
let deposit = { nullifier, secret }
|
||||
deposit.preimage = Buffer.concat([deposit.nullifier.leInt2Buff(31), deposit.secret.leInt2Buff(31)])
|
||||
@ -26,6 +31,10 @@ function createDeposit(nullifier, secret) {
|
||||
return deposit
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a deposit
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async function deposit() {
|
||||
const deposit = createDeposit(rbigint(31), rbigint(31))
|
||||
|
||||
@ -37,47 +46,51 @@ async function deposit() {
|
||||
return note
|
||||
}
|
||||
|
||||
async function getBalance(receiver) {
|
||||
const balance = await web3.eth.getBalance(receiver)
|
||||
console.log('Balance is ', web3.utils.fromWei(balance))
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a withdrawal
|
||||
* @param note A preimage containing secret and nullifier
|
||||
* @param receiver Address for receiving funds
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function withdraw(note, receiver) {
|
||||
// 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)))
|
||||
const nullifierHash = pedersenHash(deposit.nullifier.leInt2Buff(31))
|
||||
const paddedNullifierHash = nullifierHash.toString(16).padStart('66', '0x000000')
|
||||
const paddedCommitment = deposit.commitment.toString(16).padStart('66', '0x000000')
|
||||
|
||||
// Get all deposit events from smart contract and assemble merkle tree from them
|
||||
console.log('Getting current state from mixer contract')
|
||||
const events = await mixer.getPastEvents('Deposit', { fromBlock: mixer.deployedBlock, toBlock: 'latest' })
|
||||
let leafIndex
|
||||
|
||||
const commitment = deposit.commitment.toString(16).padStart('66', '0x000000')
|
||||
const leaves = events
|
||||
.sort((a, b) => a.returnValues.leafIndex.sub(b.returnValues.leafIndex))
|
||||
.map(e => {
|
||||
if (e.returnValues.commitment.eq(commitment)) {
|
||||
leafIndex = e.returnValues.leafIndex.toNumber()
|
||||
}
|
||||
return e.returnValues.commitment
|
||||
})
|
||||
.sort((a, b) => a.returnValues.leafIndex.sub(b.returnValues.leafIndex)) // Sort events in chronological order
|
||||
.map(e => e.returnValues.commitment)
|
||||
const tree = new merkleTree(MERKLE_TREE_HEIGHT, EMPTY_ELEMENT, leaves)
|
||||
const validRoot = await mixer.methods.isKnownRoot(await tree.root()).call()
|
||||
const nullifierHash = pedersenHash(deposit.nullifier.leInt2Buff(31))
|
||||
const nullifierHashToCheck = nullifierHash.toString(16).padStart('66', '0x000000')
|
||||
const isSpent = await mixer.methods.isSpent(nullifierHashToCheck).call()
|
||||
assert(validRoot === true)
|
||||
assert(isSpent === false)
|
||||
|
||||
assert(leafIndex >= 0)
|
||||
// Find current commitment in the tree
|
||||
let depositEvent = events.find(e => e.returnValues.commitment.eq(paddedCommitment))
|
||||
let leafIndex = depositEvent ? depositEvent.returnValues.leafIndex.toNumber() : -1
|
||||
|
||||
// Validate that our data is correct
|
||||
const isValidRoot = await mixer.methods.isKnownRoot(await tree.root()).call()
|
||||
const isSpent = await mixer.methods.isSpent(paddedNullifierHash).call()
|
||||
assert(isValidRoot === true) // Merkle tree assembled correctly
|
||||
assert(isSpent === false) // The note is not spent
|
||||
assert(leafIndex >= 0) // Our deposit is present in the tree
|
||||
|
||||
// Compute merkle proof of our commitment
|
||||
const { root, path_elements, path_index } = await tree.path(leafIndex)
|
||||
// Circuit input
|
||||
|
||||
// Prepare circuit input
|
||||
const input = {
|
||||
// public
|
||||
// Public snark inputs
|
||||
root: root,
|
||||
nullifierHash,
|
||||
receiver: bigInt(receiver),
|
||||
fee: bigInt(0),
|
||||
|
||||
// private
|
||||
// Private snark inputs
|
||||
nullifier: deposit.nullifier,
|
||||
secret: deposit.secret,
|
||||
pathElements: path_elements,
|
||||
@ -95,17 +108,33 @@ async function withdraw(note, receiver) {
|
||||
console.log('Done')
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default wallet balance
|
||||
*/
|
||||
async function getBalance(receiver) {
|
||||
const balance = await web3.eth.getBalance(receiver)
|
||||
console.log('Balance is ', web3.utils.fromWei(balance))
|
||||
}
|
||||
|
||||
const inBrowser = (typeof window !== 'undefined')
|
||||
|
||||
/**
|
||||
* Init web3, contracts, and snark
|
||||
*/
|
||||
async function init() {
|
||||
let contractJson
|
||||
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/Mixer.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
|
||||
AMOUNT = 1e18
|
||||
EMPTY_ELEMENT = 0
|
||||
EMPTY_ELEMENT = 1
|
||||
} else {
|
||||
// Initialize from local node
|
||||
web3 = new Web3('http://localhost:8545', null, { transactionConfirmationBlocks: 1 })
|
||||
contractJson = require('./build/contracts/Mixer.json')
|
||||
circuit = require('./build/circuits/withdraw.json')
|
||||
|
@ -133,5 +133,3 @@ contract MerkleTreeWithHistory {
|
||||
return _zeros;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user