mirror of
https://github.com/tornadocash/tornado-core.git
synced 2024-11-22 09:47:13 +01:00
Merge pull request #22 from peppersec/cli-refactor
Cli refactor, relay support
This commit is contained in:
commit
df395187bf
442
cli.js
442
cli.js
@ -2,6 +2,7 @@
|
|||||||
// Temporary demo client
|
// Temporary demo client
|
||||||
// Works both in browser and node.js
|
// Works both in browser and node.js
|
||||||
const fs = require('fs')
|
const fs = require('fs')
|
||||||
|
const axios = require('axios')
|
||||||
const assert = require('assert')
|
const assert = require('assert')
|
||||||
const snarkjs = require('snarkjs')
|
const snarkjs = require('snarkjs')
|
||||||
const crypto = require('crypto')
|
const crypto = require('crypto')
|
||||||
@ -11,16 +12,31 @@ const merkleTree = require('./lib/MerkleTree')
|
|||||||
const Web3 = require('web3')
|
const Web3 = require('web3')
|
||||||
const buildGroth16 = require('websnark/src/groth16')
|
const buildGroth16 = require('websnark/src/groth16')
|
||||||
const websnarkUtils = require('websnark/src/utils')
|
const websnarkUtils = require('websnark/src/utils')
|
||||||
|
const { toWei, fromWei } = require('web3-utils')
|
||||||
|
|
||||||
let web3, mixer, erc20mixer, circuit, proving_key, groth16, erc20
|
let web3, mixer, erc20mixer, circuit, proving_key, groth16, erc20, senderAccount
|
||||||
let MERKLE_TREE_HEIGHT, ETH_AMOUNT, ERC20_TOKEN
|
let MERKLE_TREE_HEIGHT, ETH_AMOUNT, TOKEN_AMOUNT, ERC20_TOKEN
|
||||||
|
|
||||||
|
/** Whether we are in a browser or node.js */
|
||||||
const inBrowser = (typeof window !== 'undefined')
|
const inBrowser = (typeof window !== 'undefined')
|
||||||
|
|
||||||
/** Generate random number of specified byte length */
|
/** Generate random number of specified byte length */
|
||||||
const rbigint = (nbytes) => snarkjs.bigInt.leBuff2int(crypto.randomBytes(nbytes))
|
const rbigint = nbytes => snarkjs.bigInt.leBuff2int(crypto.randomBytes(nbytes))
|
||||||
|
|
||||||
/** Compute pedersen hash */
|
/** Compute pedersen hash */
|
||||||
const pedersenHash = (data) => circomlib.babyJub.unpackPoint(circomlib.pedersenHash.hash(data))[0]
|
const pedersenHash = data => circomlib.babyJub.unpackPoint(circomlib.pedersenHash.hash(data))[0]
|
||||||
|
|
||||||
|
/** BigNumber to hex string of specified length */
|
||||||
|
function toHex(number, length = 32) {
|
||||||
|
let str = number instanceof Buffer ? number.toString('hex') : bigInt(number).toString(16)
|
||||||
|
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()))
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create deposit object from secret and nullifier
|
* Create deposit object from secret and nullifier
|
||||||
@ -29,169 +45,103 @@ function createDeposit(nullifier, secret) {
|
|||||||
let deposit = { nullifier, secret }
|
let deposit = { nullifier, secret }
|
||||||
deposit.preimage = Buffer.concat([deposit.nullifier.leInt2Buff(31), deposit.secret.leInt2Buff(31)])
|
deposit.preimage = Buffer.concat([deposit.nullifier.leInt2Buff(31), deposit.secret.leInt2Buff(31)])
|
||||||
deposit.commitment = pedersenHash(deposit.preimage)
|
deposit.commitment = pedersenHash(deposit.preimage)
|
||||||
|
deposit.nullifierHash = pedersenHash(deposit.nullifier.leInt2Buff(31))
|
||||||
return deposit
|
return deposit
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Make a deposit
|
* Make an ETH deposit
|
||||||
* @returns {Promise<string>}
|
|
||||||
*/
|
*/
|
||||||
async function deposit() {
|
async function deposit() {
|
||||||
const deposit = createDeposit(rbigint(31), rbigint(31))
|
const deposit = createDeposit(rbigint(31), rbigint(31))
|
||||||
|
|
||||||
console.log('Submitting deposit transaction')
|
console.log('Submitting deposit transaction')
|
||||||
await mixer.methods.deposit('0x' + deposit.commitment.toString(16)).send({ value: ETH_AMOUNT, from: (await web3.eth.getAccounts())[0], gas:1e6 })
|
await mixer.methods.deposit(toHex(deposit.commitment)).send({ value: ETH_AMOUNT, from: senderAccount, gas:1e6 })
|
||||||
|
|
||||||
const note = '0x' + deposit.preimage.toString('hex')
|
const note = toHex(deposit.preimage, 62)
|
||||||
console.log('Your note:', note)
|
console.log('Your note:', note)
|
||||||
return note
|
return note
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Make an ERC20 deposit
|
||||||
|
*/
|
||||||
async function depositErc20() {
|
async function depositErc20() {
|
||||||
const account = (await web3.eth.getAccounts())[0]
|
|
||||||
const tokenAmount = process.env.TOKEN_AMOUNT
|
|
||||||
await erc20.methods.mint(account, tokenAmount).send({ from: account, gas:1e6 })
|
|
||||||
|
|
||||||
await erc20.methods.approve(erc20mixer.address, tokenAmount).send({ from: account, gas:1e6 })
|
|
||||||
const allowance = await erc20.methods.allowance(account, erc20mixer.address).call()
|
|
||||||
console.log('erc20mixer allowance', allowance.toString(10))
|
|
||||||
|
|
||||||
const deposit = createDeposit(rbigint(31), rbigint(31))
|
const deposit = createDeposit(rbigint(31), rbigint(31))
|
||||||
await erc20mixer.methods.deposit('0x' + deposit.commitment.toString(16)).send({ value: ETH_AMOUNT, from: account, gas:1e6 })
|
|
||||||
|
|
||||||
const balance = await erc20.methods.balanceOf(erc20mixer.address).call()
|
if(ERC20_TOKEN === '') {
|
||||||
console.log('erc20mixer balance', balance.toString(10))
|
console.log('Minting some test tokens to deposit')
|
||||||
const note = '0x' + deposit.preimage.toString('hex')
|
await erc20.methods.mint(senderAccount, TOKEN_AMOUNT).send({ from: senderAccount, gas: 1e6 })
|
||||||
console.log('Your note:', note)
|
|
||||||
return note
|
|
||||||
}
|
|
||||||
|
|
||||||
async function withdrawErc20(note, recipient, relayer) {
|
|
||||||
let buf = Buffer.from(note.slice(2), 'hex')
|
|
||||||
let deposit = createDeposit(bigInt.leBuff2int(buf.slice(0, 31)), bigInt.leBuff2int(buf.slice(31, 62)))
|
|
||||||
|
|
||||||
console.log('Getting current state from mixer contract')
|
|
||||||
const events = await erc20mixer.getPastEvents('Deposit', { fromBlock: erc20mixer.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
|
|
||||||
})
|
|
||||||
const tree = new merkleTree(MERKLE_TREE_HEIGHT, leaves)
|
|
||||||
const validRoot = await erc20mixer.methods.isKnownRoot(await tree.root()).call()
|
|
||||||
const nullifierHash = pedersenHash(deposit.nullifier.leInt2Buff(31))
|
|
||||||
const nullifierHashToCheck = nullifierHash.toString(16).padStart('66', '0x000000')
|
|
||||||
const isSpent = await erc20mixer.methods.isSpent(nullifierHashToCheck).call()
|
|
||||||
assert(validRoot === true)
|
|
||||||
assert(isSpent === false)
|
|
||||||
|
|
||||||
assert(leafIndex >= 0)
|
|
||||||
const { root, path_elements, path_index } = await tree.path(leafIndex)
|
|
||||||
// Circuit input
|
|
||||||
const input = {
|
|
||||||
// public
|
|
||||||
root: root,
|
|
||||||
nullifierHash,
|
|
||||||
recipient: bigInt(recipient),
|
|
||||||
relayer: bigInt(relayer),
|
|
||||||
fee: bigInt(web3.utils.toWei('0.01')),
|
|
||||||
refund: bigInt(0),
|
|
||||||
|
|
||||||
// private
|
|
||||||
nullifier: deposit.nullifier,
|
|
||||||
secret: deposit.secret,
|
|
||||||
pathElements: path_elements,
|
|
||||||
pathIndices: path_index,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('Generating SNARK proof')
|
console.log('Approving tokens for deposit')
|
||||||
console.time('Proof time')
|
await erc20.methods.approve(erc20mixer._address, TOKEN_AMOUNT).send({ from: senderAccount, gas:1e6 })
|
||||||
const proofData = await websnarkUtils.genWitnessAndProve(groth16, input, circuit, proving_key)
|
|
||||||
const { proof } = websnarkUtils.toSolidityInput(proofData)
|
|
||||||
console.timeEnd('Proof time')
|
|
||||||
|
|
||||||
console.log('Submitting withdraw transaction')
|
console.log('Submitting deposit transaction')
|
||||||
const args = [
|
await erc20mixer.methods.deposit(toHex(deposit.commitment)).send({ from: senderAccount, gas:1e6 })
|
||||||
toHex(input.root),
|
|
||||||
toHex(input.nullifierHash),
|
const note = toHex(deposit.preimage, 62)
|
||||||
toHex(input.recipient, 20),
|
console.log('Your note:', note)
|
||||||
toHex(input.relayer, 20),
|
return note
|
||||||
toHex(input.fee),
|
|
||||||
toHex(input.refund)
|
|
||||||
]
|
|
||||||
await erc20mixer.methods.withdraw(proof, ...args).send({ from: (await web3.eth.getAccounts())[0], gas: 1e6 })
|
|
||||||
console.log('Done')
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getBalance(recipient) {
|
/**
|
||||||
const balance = await web3.eth.getBalance(recipient)
|
* Generate merkle tree for a deposit.
|
||||||
console.log('Balance is ', web3.utils.fromWei(balance))
|
* Download deposit events from the contract, reconstructs merkle tree, finds our deposit leaf
|
||||||
}
|
* in it and generates merkle proof
|
||||||
|
* @param contract Mixer contract address
|
||||||
async function getBalanceErc20(recipient, relayer) {
|
* @param deposit Deposit object
|
||||||
const balanceRecipient = await web3.eth.getBalance(recipient)
|
*/
|
||||||
const balanceRelayer = await web3.eth.getBalance(relayer)
|
async function generateMerkleProof(contract, deposit) {
|
||||||
const tokenBalanceRecipient = await erc20.methods.balanceOf(recipient).call()
|
|
||||||
const tokenBalanceRelayer = await erc20.methods.balanceOf(relayer).call()
|
|
||||||
console.log('Recipient eth Balance is ', web3.utils.fromWei(balanceRecipient))
|
|
||||||
console.log('Relayer eth Balance is ', web3.utils.fromWei(balanceRelayer))
|
|
||||||
|
|
||||||
console.log('Recipient token Balance is ', web3.utils.fromWei(tokenBalanceRecipient.toString()))
|
|
||||||
console.log('Relayer token Balance is ', web3.utils.fromWei(tokenBalanceRelayer.toString()))
|
|
||||||
}
|
|
||||||
|
|
||||||
function toHex(number, length = 32) {
|
|
||||||
let str = bigInt(number).toString(16)
|
|
||||||
while (str.length < length * 2) str = '0' + str
|
|
||||||
str = '0x' + str
|
|
||||||
return str
|
|
||||||
}
|
|
||||||
|
|
||||||
async function withdraw(note, recipient) {
|
|
||||||
// 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
|
// Get all deposit events from smart contract and assemble merkle tree from them
|
||||||
console.log('Getting current state from mixer contract')
|
console.log('Getting current state from mixer contract')
|
||||||
const events = await mixer.getPastEvents('Deposit', { fromBlock: mixer.deployedBlock, toBlock: 'latest' })
|
const events = await contract.getPastEvents('Deposit', { fromBlock: contract.deployedBlock, toBlock: 'latest' })
|
||||||
const leaves = events
|
const leaves = events
|
||||||
.sort((a, b) => a.returnValues.leafIndex - b.returnValues.leafIndex) // Sort events in chronological order
|
.sort((a, b) => a.returnValues.leafIndex - b.returnValues.leafIndex) // Sort events in chronological order
|
||||||
.map(e => e.returnValues.commitment)
|
.map(e => e.returnValues.commitment)
|
||||||
const tree = new merkleTree(MERKLE_TREE_HEIGHT, leaves)
|
const tree = new merkleTree(MERKLE_TREE_HEIGHT, leaves)
|
||||||
|
|
||||||
// Find current commitment in the tree
|
// Find current commitment in the tree
|
||||||
let depositEvent = events.find(e => e.returnValues.commitment === paddedCommitment)
|
let depositEvent = events.find(e => e.returnValues.commitment === toHex(deposit.commitment))
|
||||||
let leafIndex = depositEvent ? depositEvent.returnValues.leafIndex : -1
|
let leafIndex = depositEvent ? depositEvent.returnValues.leafIndex : -1
|
||||||
|
|
||||||
// Validate that our data is correct
|
// Validate that our data is correct
|
||||||
const isValidRoot = await mixer.methods.isKnownRoot(toHex(await tree.root())).call()
|
const isValidRoot = await contract.methods.isKnownRoot(toHex(await tree.root())).call()
|
||||||
const isSpent = await mixer.methods.isSpent(paddedNullifierHash).call()
|
const isSpent = await contract.methods.isSpent(toHex(deposit.nullifierHash)).call()
|
||||||
assert(isValidRoot === true) // Merkle tree assembled correctly
|
assert(isValidRoot === true, 'Merkle tree is corrupted')
|
||||||
assert(isSpent === false) // The note is not spent
|
assert(isSpent === false, 'The note is already spent')
|
||||||
assert(leafIndex >= 0) // Our deposit is present in the tree
|
assert(leafIndex >= 0, 'The deposit is not found in the tree')
|
||||||
|
|
||||||
// Compute merkle proof of our commitment
|
// Compute merkle proof of our commitment
|
||||||
const { root, path_elements, path_index } = await tree.path(leafIndex)
|
return await tree.path(leafIndex)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate SNARK proof for withdrawal
|
||||||
|
* @param contract Mixer contract address
|
||||||
|
* @param note Note string
|
||||||
|
* @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)
|
||||||
|
|
||||||
// Prepare circuit input
|
// Prepare circuit input
|
||||||
const input = {
|
const input = {
|
||||||
// Public snark inputs
|
// Public snark inputs
|
||||||
root: root,
|
root: root,
|
||||||
nullifierHash,
|
nullifierHash: deposit.nullifierHash,
|
||||||
recipient: bigInt(recipient),
|
recipient: bigInt(recipient),
|
||||||
relayer: bigInt(0),
|
relayer: bigInt(relayer),
|
||||||
fee: bigInt(0),
|
fee: bigInt(fee),
|
||||||
refund: bigInt(0),
|
refund: bigInt(refund),
|
||||||
|
|
||||||
// Private snark inputs
|
// Private snark inputs
|
||||||
nullifier: deposit.nullifier,
|
nullifier: deposit.nullifier,
|
||||||
@ -206,7 +156,6 @@ async function withdraw(note, recipient) {
|
|||||||
const { proof } = websnarkUtils.toSolidityInput(proofData)
|
const { proof } = websnarkUtils.toSolidityInput(proofData)
|
||||||
console.timeEnd('Proof time')
|
console.timeEnd('Proof time')
|
||||||
|
|
||||||
console.log('Submitting withdraw transaction')
|
|
||||||
const args = [
|
const args = [
|
||||||
toHex(input.root),
|
toHex(input.root),
|
||||||
toHex(input.nullifierHash),
|
toHex(input.nullifierHash),
|
||||||
@ -215,10 +164,109 @@ async function withdraw(note, recipient) {
|
|||||||
toHex(input.fee),
|
toHex(input.fee),
|
||||||
toHex(input.refund)
|
toHex(input.refund)
|
||||||
]
|
]
|
||||||
await mixer.methods.withdraw(proof, ...args).send({ from: (await web3.eth.getAccounts())[0], gas: 1e6 })
|
|
||||||
|
return { proof, args }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Do an ETH withdrawal
|
||||||
|
* @param note Note to withdraw
|
||||||
|
* @param recipient Recipient address
|
||||||
|
*/
|
||||||
|
async function withdraw(note, recipient) {
|
||||||
|
const { proof, args } = await generateProof(mixer, note, recipient)
|
||||||
|
|
||||||
|
console.log('Submitting withdraw transaction')
|
||||||
|
await mixer.methods.withdraw(proof, ...args).send({ from: senderAccount, gas: 1e6 })
|
||||||
console.log('Done')
|
console.log('Done')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Do a ERC20 withdrawal
|
||||||
|
* @param note Note to withdraw
|
||||||
|
* @param recipient Recipient address
|
||||||
|
*/
|
||||||
|
async function withdrawErc20(note, recipient) {
|
||||||
|
const { proof, args } = await generateProof(erc20mixer, note, recipient)
|
||||||
|
|
||||||
|
console.log('Submitting withdraw transaction')
|
||||||
|
await erc20mixer.methods.withdraw(proof, ...args).send({ from: senderAccount, gas: 1e6 })
|
||||||
|
console.log('Done')
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Do an ETH withdrawal through relay
|
||||||
|
* @param note Note to withdraw
|
||||||
|
* @param recipient Recipient address
|
||||||
|
* @param relayUrl Relay url address
|
||||||
|
*/
|
||||||
|
async function withdrawRelay(note, recipient, relayUrl) {
|
||||||
|
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(mixer, note, recipient, relayerAddress, fee)
|
||||||
|
|
||||||
|
console.log('Sending withdraw transaction through relay')
|
||||||
|
const resp2 = await axios.post(relayUrl + '/relay', { contract: mixer._address, proof: { proof, publicSignals: args } })
|
||||||
|
console.log(`Transaction submitted through relay, tx hash: ${resp2.data.txHash}`)
|
||||||
|
|
||||||
|
let 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 recipient Recipient address
|
||||||
|
* @param relayUrl Relay url address
|
||||||
|
*/
|
||||||
|
async function withdrawRelayErc20(note, recipient, relayUrl) {
|
||||||
|
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(erc20mixer, note, recipient, relayerAddress, fee, refund)
|
||||||
|
|
||||||
|
console.log('Sending withdraw transaction through relay')
|
||||||
|
const resp2 = await axios.post(relayUrl + '/relay', { contract: erc20mixer._address, proof: { proof, publicSignals: args } })
|
||||||
|
console.log(`Transaction submitted through relay, tx hash: ${resp2.data.txHash}`)
|
||||||
|
|
||||||
|
let receipt = await waitForTxReceipt(resp2.data.txHash)
|
||||||
|
console.log('Transaction mined in block', receipt.blockNumber)
|
||||||
|
console.log('Done')
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Waits for transaction to be mined
|
||||||
|
* @param txHash Hash of transaction
|
||||||
|
* @param attempts
|
||||||
|
* @param delay
|
||||||
|
*/
|
||||||
|
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)
|
||||||
|
if (!result || !result.blockNumber) {
|
||||||
|
if (retryAttempt <= attempts) {
|
||||||
|
setTimeout(() => checkForTx(txHash, retryAttempt + 1), delay)
|
||||||
|
} else {
|
||||||
|
reject(new Error('tx was not mined'))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
resolve(result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
checkForTx(txHash)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Init web3, contracts, and snark
|
* Init web3, contracts, and snark
|
||||||
*/
|
*/
|
||||||
@ -233,6 +281,7 @@ async function init() {
|
|||||||
proving_key = await (await fetch('build/circuits/withdraw_proving_key.bin')).arrayBuffer()
|
proving_key = await (await fetch('build/circuits/withdraw_proving_key.bin')).arrayBuffer()
|
||||||
MERKLE_TREE_HEIGHT = 16
|
MERKLE_TREE_HEIGHT = 16
|
||||||
ETH_AMOUNT = 1e18
|
ETH_AMOUNT = 1e18
|
||||||
|
TOKEN_AMOUNT = 1e19
|
||||||
} else {
|
} else {
|
||||||
// Initialize from local node
|
// Initialize from local node
|
||||||
web3 = new Web3('http://localhost:8545', null, { transactionConfirmationBlocks: 1 })
|
web3 = new Web3('http://localhost:8545', null, { transactionConfirmationBlocks: 1 })
|
||||||
@ -242,6 +291,7 @@ async function init() {
|
|||||||
require('dotenv').config()
|
require('dotenv').config()
|
||||||
MERKLE_TREE_HEIGHT = process.env.MERKLE_TREE_HEIGHT
|
MERKLE_TREE_HEIGHT = process.env.MERKLE_TREE_HEIGHT
|
||||||
ETH_AMOUNT = process.env.ETH_AMOUNT
|
ETH_AMOUNT = process.env.ETH_AMOUNT
|
||||||
|
TOKEN_AMOUNT = process.env.TOKEN_AMOUNT
|
||||||
ERC20_TOKEN = process.env.ERC20_TOKEN
|
ERC20_TOKEN = process.env.ERC20_TOKEN
|
||||||
erc20ContractJson = require('./build/contracts/ERC20Mock.json')
|
erc20ContractJson = require('./build/contracts/ERC20Mock.json')
|
||||||
erc20mixerJson = require('./build/contracts/ERC20Mixer.json')
|
erc20mixerJson = require('./build/contracts/ERC20Mixer.json')
|
||||||
@ -263,21 +313,30 @@ async function init() {
|
|||||||
const tx2 = await web3.eth.getTransaction(erc20ContractJson.networks[netId].transactionHash)
|
const tx2 = await web3.eth.getTransaction(erc20ContractJson.networks[netId].transactionHash)
|
||||||
erc20.deployedBlock = tx2.blockNumber
|
erc20.deployedBlock = tx2.blockNumber
|
||||||
}
|
}
|
||||||
|
|
||||||
|
senderAccount = (await web3.eth.getAccounts())[0]
|
||||||
console.log('Loaded')
|
console.log('Loaded')
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========== CLI related stuff below ==============
|
// ========== CLI related stuff below ==============
|
||||||
|
|
||||||
|
/** Print command line help */
|
||||||
function printHelp(code = 0) {
|
function printHelp(code = 0) {
|
||||||
console.log(`Usage:
|
console.log(`Usage:
|
||||||
Submit a deposit from default eth account and return the resulting note
|
Submit a deposit from default eth account and return the resulting note
|
||||||
$ ./cli.js deposit
|
$ ./cli.js deposit
|
||||||
|
$ ./cli.js depositErc20
|
||||||
|
|
||||||
Withdraw a note to 'recipient' account
|
Withdraw a note to 'recipient' account
|
||||||
$ ./cli.js withdraw <note> <recipient>
|
$ ./cli.js withdraw <note> <recipient> [relayUrl]
|
||||||
|
$ ./cli.js withdrawErc20 <note> <recipient> [relayUrl]
|
||||||
|
|
||||||
Check address balance
|
Check address balance
|
||||||
$ ./cli.js balance <address>
|
$ ./cli.js balance <address>
|
||||||
|
|
||||||
|
Perform an automated test
|
||||||
|
$ ./cli.js test
|
||||||
|
$ ./cli.js testRelay
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
$ ./cli.js deposit
|
$ ./cli.js deposit
|
||||||
@ -289,75 +348,99 @@ Example:
|
|||||||
process.exit(code)
|
process.exit(code)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (inBrowser) {
|
/** Process command line args and run */
|
||||||
window.deposit = deposit
|
async function runConsole(args) {
|
||||||
window.withdraw = async () => {
|
|
||||||
const note = prompt('Enter the note to withdraw')
|
|
||||||
const recipient = (await web3.eth.getAccounts())[0]
|
|
||||||
await withdraw(note, recipient)
|
|
||||||
}
|
|
||||||
init()
|
|
||||||
} else {
|
|
||||||
const args = process.argv.slice(2)
|
|
||||||
if (args.length === 0) {
|
if (args.length === 0) {
|
||||||
printHelp()
|
printHelp()
|
||||||
} else {
|
} else {
|
||||||
switch (args[0]) {
|
switch (args[0]) {
|
||||||
case 'deposit':
|
case 'deposit':
|
||||||
if (args.length === 1) {
|
if (args.length === 1) {
|
||||||
init().then(() => deposit()).then(() => process.exit(0)).catch(err => {console.log(err); process.exit(1)})
|
await init()
|
||||||
}
|
await printBalance(mixer._address, 'Mixer')
|
||||||
else
|
await printBalance(senderAccount, 'Sender account')
|
||||||
|
await deposit()
|
||||||
|
await printBalance(mixer._address, 'Mixer')
|
||||||
|
await printBalance(senderAccount, 'Sender account')
|
||||||
|
} else {
|
||||||
printHelp(1)
|
printHelp(1)
|
||||||
|
}
|
||||||
break
|
break
|
||||||
case 'depositErc20':
|
case 'depositErc20':
|
||||||
if (args.length === 1) {
|
if (args.length === 1) {
|
||||||
init().then(() => depositErc20()).then(() => process.exit(0)).catch(err => {console.log(err); process.exit(1)})
|
await init()
|
||||||
}
|
await printBalance(erc20mixer._address, 'Mixer')
|
||||||
else
|
await printBalance(senderAccount, 'Sender account')
|
||||||
|
await depositErc20()
|
||||||
|
await printBalance(erc20mixer._address, 'Mixer')
|
||||||
|
await printBalance(senderAccount, 'Sender account')
|
||||||
|
} else {
|
||||||
printHelp(1)
|
printHelp(1)
|
||||||
|
}
|
||||||
break
|
break
|
||||||
case 'balance':
|
case 'balance':
|
||||||
if (args.length === 2 && /^0x[0-9a-fA-F]{40}$/.test(args[1])) {
|
if (args.length === 2 && /^0x[0-9a-fA-F]{40}$/.test(args[1])) {
|
||||||
init().then(() => getBalance(args[1])).then(() => process.exit(0)).catch(err => {console.log(err); process.exit(1)})
|
await init()
|
||||||
} else
|
await printBalance(args[1])
|
||||||
printHelp(1)
|
} else {
|
||||||
break
|
|
||||||
case 'balanceErc20':
|
|
||||||
if (args.length === 3 && /^0x[0-9a-fA-F]{40}$/.test(args[1]) && /^0x[0-9a-fA-F]{40}$/.test(args[2])) {
|
|
||||||
init().then(() => getBalanceErc20(args[1], args[2])).then(() => process.exit(0)).catch(err => {console.log(err); process.exit(1)})
|
|
||||||
} else
|
|
||||||
printHelp(1)
|
printHelp(1)
|
||||||
|
}
|
||||||
break
|
break
|
||||||
case 'withdraw':
|
case 'withdraw':
|
||||||
if (args.length === 3 && /^0x[0-9a-fA-F]{124}$/.test(args[1]) && /^0x[0-9a-fA-F]{40}$/.test(args[2])) {
|
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])) {
|
||||||
init().then(() => withdraw(args[1], args[2])).then(() => process.exit(0)).catch(err => {console.log(err); process.exit(1)})
|
await init()
|
||||||
}
|
await printBalance(mixer._address, 'Mixer')
|
||||||
else
|
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(mixer._address, 'Mixer')
|
||||||
|
await printBalance(args[2], 'Recipient account')
|
||||||
|
} else {
|
||||||
printHelp(1)
|
printHelp(1)
|
||||||
|
}
|
||||||
break
|
break
|
||||||
case 'withdrawErc20':
|
case 'withdrawErc20':
|
||||||
if (args.length === 4 && /^0x[0-9a-fA-F]{124}$/.test(args[1]) && /^0x[0-9a-fA-F]{40}$/.test(args[2]) && /^0x[0-9a-fA-F]{40}$/.test(args[3])) {
|
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])) {
|
||||||
init().then(() => withdrawErc20(args[1], args[2], args[3])).then(() => process.exit(0)).catch(err => {console.log(err); process.exit(1)})
|
await init()
|
||||||
}
|
await printBalance(erc20mixer._address, 'Mixer')
|
||||||
else
|
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(erc20mixer._address, 'Mixer')
|
||||||
|
await printBalance(args[2], 'Recipient account')
|
||||||
|
} else {
|
||||||
printHelp(1)
|
printHelp(1)
|
||||||
|
}
|
||||||
break
|
break
|
||||||
case 'test':
|
case 'test':
|
||||||
if (args.length === 1) {
|
if (args.length === 1) {
|
||||||
(async () => {
|
await init()
|
||||||
await init()
|
const note1 = await deposit()
|
||||||
const account = (await web3.eth.getAccounts())[0]
|
await withdraw(note1, senderAccount)
|
||||||
const note = await deposit()
|
|
||||||
await withdraw(note, account)
|
|
||||||
|
|
||||||
const note2 = await deposit()
|
const note2 = await depositErc20()
|
||||||
await withdraw(note2, account, account)
|
await withdrawErc20(note2, senderAccount)
|
||||||
process.exit(0)
|
} else {
|
||||||
})()
|
|
||||||
}
|
|
||||||
else
|
|
||||||
printHelp(1)
|
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
|
break
|
||||||
|
|
||||||
default:
|
default:
|
||||||
@ -365,3 +448,18 @@ if (inBrowser) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
runConsole(process.argv.slice(2))
|
||||||
|
.then(() => process.exit(0))
|
||||||
|
.catch(err => { console.log(err); process.exit(1) })
|
||||||
|
}
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
const jsStorage = require('./Storage')
|
const jsStorage = require('./Storage')
|
||||||
const hasherImpl = require('./MiMC')
|
const hasherImpl = require('./MiMC')
|
||||||
const { bigInt } = require('snarkjs')
|
|
||||||
|
|
||||||
class MerkleTree {
|
class MerkleTree {
|
||||||
|
|
||||||
@ -12,7 +11,7 @@ class MerkleTree {
|
|||||||
this.zero_values = []
|
this.zero_values = []
|
||||||
this.totalElements = 0
|
this.totalElements = 0
|
||||||
|
|
||||||
let current_zero_value = bigInt('5702960885942360421128284892092891246826997279710054143430547229469817701242')
|
let current_zero_value = '5702960885942360421128284892092891246826997279710054143430547229469817701242'
|
||||||
this.zero_values.push(current_zero_value)
|
this.zero_values.push(current_zero_value)
|
||||||
for (let i = 0; i < n_levels; i++) {
|
for (let i = 0; i < n_levels; i++) {
|
||||||
current_zero_value = this.hasher.hash(i, current_zero_value, current_zero_value)
|
current_zero_value = this.hasher.hash(i, current_zero_value, current_zero_value)
|
||||||
@ -77,6 +76,7 @@ class MerkleTree {
|
|||||||
this.path_index.push(element_index % 2)
|
this.path_index.push(element_index % 2)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
index = Number(index)
|
||||||
let traverser = new PathTraverser(this.prefix, this.storage, this.zero_values)
|
let traverser = new PathTraverser(this.prefix, this.storage, this.zero_values)
|
||||||
const root = await this.storage.get_or_element(
|
const root = await this.storage.get_or_element(
|
||||||
MerkleTree.index_to_key(this.prefix, this.n_levels, 0),
|
MerkleTree.index_to_key(this.prefix, this.n_levels, 0),
|
||||||
|
39
package-lock.json
generated
39
package-lock.json
generated
@ -488,6 +488,22 @@
|
|||||||
"resolved": "https://registry.npmjs.org/aws4/-/aws4-1.8.0.tgz",
|
"resolved": "https://registry.npmjs.org/aws4/-/aws4-1.8.0.tgz",
|
||||||
"integrity": "sha512-ReZxvNHIOv88FlT7rxcXIIC0fPt4KZqZbOlivyWtXLt8ESx84zd3kMC6iK5jVeS2qt+g7ftS7ye4fi06X5rtRQ=="
|
"integrity": "sha512-ReZxvNHIOv88FlT7rxcXIIC0fPt4KZqZbOlivyWtXLt8ESx84zd3kMC6iK5jVeS2qt+g7ftS7ye4fi06X5rtRQ=="
|
||||||
},
|
},
|
||||||
|
"axios": {
|
||||||
|
"version": "0.19.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/axios/-/axios-0.19.0.tgz",
|
||||||
|
"integrity": "sha512-1uvKqKQta3KBxIz14F2v06AEHZ/dIoeKfbTRkK1E5oqjDnuEerLmYTgJB5AiQZHJcljpg1TuRzdjDR06qNk0DQ==",
|
||||||
|
"requires": {
|
||||||
|
"follow-redirects": "1.5.10",
|
||||||
|
"is-buffer": "^2.0.2"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"is-buffer": {
|
||||||
|
"version": "2.0.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.4.tgz",
|
||||||
|
"integrity": "sha512-Kq1rokWXOPXWuaMAqZiJW4XxsmD9zGx9q4aePabbn3qCRGedtH7Cm+zV8WETitMfu1wdh+Rvd6w5egwSngUX2A=="
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"babel-code-frame": {
|
"babel-code-frame": {
|
||||||
"version": "6.26.0",
|
"version": "6.26.0",
|
||||||
"resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz",
|
"resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz",
|
||||||
@ -3611,6 +3627,29 @@
|
|||||||
"resolved": "https://registry.npmjs.org/flatted/-/flatted-2.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/flatted/-/flatted-2.0.1.tgz",
|
||||||
"integrity": "sha512-a1hQMktqW9Nmqr5aktAux3JMNqaucxGcjtjWnZLHX7yyPCmlSV3M54nGYbqT8K+0GhF3NBgmJCc3ma+WOgX8Jg=="
|
"integrity": "sha512-a1hQMktqW9Nmqr5aktAux3JMNqaucxGcjtjWnZLHX7yyPCmlSV3M54nGYbqT8K+0GhF3NBgmJCc3ma+WOgX8Jg=="
|
||||||
},
|
},
|
||||||
|
"follow-redirects": {
|
||||||
|
"version": "1.5.10",
|
||||||
|
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.5.10.tgz",
|
||||||
|
"integrity": "sha512-0V5l4Cizzvqt5D44aTXbFZz+FtyXV1vrDN6qrelxtfYQKW0KO0W2T/hkE8xvGa/540LkZlkaUjO4ailYTFtHVQ==",
|
||||||
|
"requires": {
|
||||||
|
"debug": "=3.1.0"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"debug": {
|
||||||
|
"version": "3.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz",
|
||||||
|
"integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==",
|
||||||
|
"requires": {
|
||||||
|
"ms": "2.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"ms": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
|
||||||
|
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"for-each": {
|
"for-each": {
|
||||||
"version": "0.3.3",
|
"version": "0.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz",
|
"resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz",
|
||||||
|
@ -30,6 +30,7 @@
|
|||||||
"@truffle/artifactor": "^4.0.38",
|
"@truffle/artifactor": "^4.0.38",
|
||||||
"@truffle/contract": "^4.0.39",
|
"@truffle/contract": "^4.0.39",
|
||||||
"@truffle/hdwallet-provider": "^1.0.24",
|
"@truffle/hdwallet-provider": "^1.0.24",
|
||||||
|
"axios": "^0.19.0",
|
||||||
"bn-chai": "^1.0.1",
|
"bn-chai": "^1.0.1",
|
||||||
"browserify": "^16.5.0",
|
"browserify": "^16.5.0",
|
||||||
"chai": "^4.2.0",
|
"chai": "^4.2.0",
|
||||||
|
Loading…
Reference in New Issue
Block a user