This commit is contained in:
poma 2019-07-09 16:05:30 +03:00
commit 12cc76f3b1
18 changed files with 41757 additions and 0 deletions

91
.gitignore vendored Normal file
View File

@ -0,0 +1,91 @@
# Created by .ignore support plugin (hsz.mobi)
### Node template
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/

View File

@ -0,0 +1,70 @@
include "../node_modules/circomlib/circuits/bitify.circom";
include "../node_modules/circomlib/circuits/mimcsponge.circom";
template HashLeftRight(rounds) {
signal input left;
signal input right;
signal output hash;
component hasher = MiMCSponge(2, rounds, 1);
hasher.ins[0] <== left;
hasher.ins[1] <== right;
hasher.k <== 0;
hash <== hasher.outs[0];
}
template Selector() {
signal input inputElement;
signal input pathElement;
signal input pathIndex;
signal output left;
signal output right;
signal leftSelector1;
signal leftSelector2;
signal rightSelector1;
signal rightSelector2;
pathIndex * (1-pathIndex) === 0
leftSelector1 <== (1 - pathIndex) * inputElement;
leftSelector2 <== (pathIndex) * pathElement;
rightSelector1 <== (pathIndex) * inputElement;
rightSelector2 <== (1 - pathIndex) * pathElement;
left <== leftSelector1 + leftSelector2;
right <== rightSelector1 + rightSelector2;
}
template MerkleTree(levels, rounds) {
signal input leaf;
signal private input pathElements[levels];
signal private input pathIndex[levels];
signal output root;
component selectors[levels];
component hashers[levels];
for (var i = 0; i < levels; i++) {
selectors[i] = Selector();
hashers[i] = HashLeftRight(rounds);
selectors[i].pathElement <== pathElements[i];
selectors[i].pathIndex <== pathIndex[i];
hashers[i].left <== selectors[i].left;
hashers[i].right <== selectors[i].right;
}
selectors[0].inputElement <== leaf;
for (var i = 1; i < levels; i++) {
selectors[i].inputElement <== hashers[i-1].hash;
}
root <== hashers[levels - 1].hash;
}

49
circuits/withdraw.circom Normal file
View File

@ -0,0 +1,49 @@
include "../node_modules/circomlib/circuits/bitify.circom";
include "../node_modules/circomlib/circuits/pedersen.circom";
include "merkleTree.circom";
template CommitmentHasher() {
signal input nullifier;
signal private input secret;
signal output hash;
component commitment = Pedersen(512);
component nullifierBits = Num2Bits(256);
component secretBits = Num2Bits(256);
nullifierBits.in <== nullifier;
secretBits.in <== secret;
for (var i = 0; i < 256; i++) {
commitment.in[i] <== nullifierBits.out[i];
commitment.in[i + 256] <== secretBits.out[i];
}
hash <== commitment.out[0];
}
template Withdraw(levels, rounds) {
signal input root;
signal input nullifier;
signal input receiver; // not taking part in any computations
signal input fee; // not taking part in any computations
signal private input secret;
signal private input pathElements[levels];
signal private input pathIndex[levels];
component hasher = CommitmentHasher();
hasher.nullifier <== nullifier;
hasher.secret <== secret;
component tree = MerkleTree(levels, rounds);
tree.leaf <== hasher.hash;
tree.pathElements <== pathElements;
tree.pathIndex <== pathIndex;
root === tree.root;
// TODO: Check if we need some kind of explicit constraints or something
fee === fee;
receiver === receiver;
}
component main = Withdraw(16, 220);

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,105 @@
pragma solidity ^0.5.8;
library MiMC {
function MiMCSponge(uint256 in_xL, uint256 in_xR, uint256 in_k) public pure returns (uint256 xL, uint256 xR);
}
contract MerkleTreeWithHistory {
uint8 levels;
uint8 constant ROOT_HISTORY_SIZE = 100;
uint256[] public roots;
uint256 public current_root = 0;
uint256[] public filled_subtrees;
uint256[] public zeros;
uint32 public next_index = 0;
event LeafAdded(uint256 leaf, uint32 leaf_index);
constructor(uint8 tree_levels, uint256 zero_value) public {
levels = tree_levels;
zeros.push(zero_value);
filled_subtrees.push(zeros[0]);
for (uint8 i = 1; i < levels; i++) {
zeros.push(HashLeftRight(zeros[i-1], zeros[i-1]));
filled_subtrees.push(zeros[i]);
}
roots = new uint256[](ROOT_HISTORY_SIZE);
roots[0] = HashLeftRight(zeros[levels - 1], zeros[levels - 1]);
}
function HashLeftRight(uint256 left, uint256 right) public pure returns (uint256 mimc_hash) {
uint256 k = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint256 R = 0;
uint256 C = 0;
R = addmod(R, left, k);
(R, C) = MiMC.MiMCSponge(R, C, 0);
R = addmod(R, right, k);
(R, C) = MiMC.MiMCSponge(R, C, 0);
mimc_hash = R;
}
function insert(uint256 leaf) internal {
uint32 leaf_index = next_index;
uint32 current_index = next_index;
next_index += 1;
uint256 current_level_hash = leaf;
uint256 left;
uint256 right;
for (uint8 i = 0; i < levels; i++) {
if (current_index % 2 == 0) {
left = current_level_hash;
right = zeros[i];
filled_subtrees[i] = current_level_hash;
} else {
left = filled_subtrees[i];
right = current_level_hash;
}
current_level_hash = HashLeftRight(left, right);
current_index /= 2;
}
current_root = (current_root + 1) % ROOT_HISTORY_SIZE;
roots[current_root] = current_level_hash;
emit LeafAdded(leaf, leaf_index);
}
function isKnownRoot(uint _root) internal view returns(bool) {
if (_root == 0) {
return false;
}
// search most recent first
uint256 i;
for(i = current_root; i >= 0; i--) {
if (_root == roots[i]) {
return true;
}
}
for(i = ROOT_HISTORY_SIZE - 1; i > current_root; i--) {
if (_root == roots[i]) {
return true;
}
}
return false;
}
function getLastRoot() public view returns(uint256) {
return roots[current_root];
}
}

View File

@ -0,0 +1,23 @@
pragma solidity >=0.4.21 <0.6.0;
contract Migrations {
address public owner;
uint public last_completed_migration;
constructor() public {
owner = msg.sender;
}
modifier restricted() {
if (msg.sender == owner) _;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}

View File

@ -0,0 +1,49 @@
pragma solidity ^0.5.8;
import "./MerkleTreeWithHistory.sol";
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract IVerifier {
function verify(uint256[2] memory a, uint256[2][2] memory b, uint256[2] memory c, uint256[4] memory input) public returns(bool);
}
contract Mixer is MerkleTreeWithHistory {
using SafeMath for uint256;
uint256 public transferValue;
mapping(uint256 => bool) public nullifiers;
IVerifier verifier;
event Deposit(address from, uint256 commitment);
event Withdraw(address to, uint256 nullifier, uint256 fee);
constructor(address _verifier, uint256 _transferValue) MerkleTreeWithHistory(16, 0) public {
verifier = IVerifier(_verifier);
transferValue = _transferValue;
}
function deposit(uint256 commitment) public payable {
require(msg.value == transferValue, "Please send `transferValue` ETH along with transaction");
insert(commitment);
emit Deposit(msg.sender, commitment);
}
function withdraw(uint256[2] memory a, uint256[2][2] memory b, uint256[2] memory c, uint256[4] memory input) public {
uint256 root = input[0];
uint256 nullifier = input[1];
address payable receiver = address(input[2]);
uint256 fee = input[3];
require(fee < transferValue, "Fee exceeds transfer value");
require(!nullifiers[nullifier], "The note has been already spent");
require(isKnownRoot(root), "Cannot find your merkle root"); // Make sure to use a recent one
require(verifier.verify(a, b, c, input), "Invalid withdraw proof");
nullifiers[nullifier] = true;
receiver.transfer(transferValue - fee);
if (fee > 0) {
msg.sender.transfer(fee);
}
emit Withdraw(receiver, nullifier, fee);
}
}

View File

@ -0,0 +1,5 @@
const Migrations = artifacts.require("Migrations");
module.exports = function(deployer) {
deployer.deploy(Migrations);
};

13
contracts/package-lock.json generated Normal file
View File

@ -0,0 +1,13 @@
{
"name": "contracts",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"openzeppelin-solidity": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/openzeppelin-solidity/-/openzeppelin-solidity-2.3.0.tgz",
"integrity": "sha512-QYeiPLvB1oSbDt6lDQvvpx7k8ODczvE474hb2kLXZBPKMsxKT1WxTCHBYrCU7kS7hfAku4DcJ0jqOyL+jvjwQw=="
}
}
}

18
contracts/package.json Normal file
View File

@ -0,0 +1,18 @@
{
"name": "contracts",
"version": "1.0.0",
"description": "",
"main": "truffle-config.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"openzeppelin-solidity": "^2.3.0"
}
}

View File

@ -0,0 +1,99 @@
/**
* Use this file to configure your truffle project. It's seeded with some
* common settings for different networks and features like migrations,
* compilation and testing. Uncomment the ones you need or modify
* them to suit your project as necessary.
*
* More information about configuration can be found at:
*
* truffleframework.com/docs/advanced/configuration
*
* To deploy via Infura you'll need a wallet provider (like truffle-hdwallet-provider)
* to sign your transactions before they're sent to a remote public node. Infura accounts
* are available for free at: infura.io/register.
*
* You'll also need a mnemonic - the twelve word phrase the wallet uses to generate
* public/private key pairs. If you're publishing your code to GitHub make sure you load this
* phrase from a file you've .gitignored so it doesn't accidentally become public.
*
*/
// const HDWalletProvider = require('truffle-hdwallet-provider');
// const infuraKey = "fj4jll3k.....";
//
// const fs = require('fs');
// const mnemonic = fs.readFileSync(".secret").toString().trim();
module.exports = {
/**
* Networks define how you connect to your ethereum client and let you set the
* defaults web3 uses to send transactions. If you don't specify one truffle
* will spin up a development blockchain for you on port 9545 when you
* run `develop` or `test`. You can ask a truffle command to use a specific
* network from the command line, e.g
*
* $ truffle test --network <network-name>
*/
networks: {
// Useful for testing. The `development` name is special - truffle uses it by default
// if it's defined here and no other network is specified at the command line.
// You should run a client (like ganache-cli, geth or parity) in a separate terminal
// tab if you use this network and you must also set the `host`, `port` and `network_id`
// options below to some value.
//
// development: {
// host: "127.0.0.1", // Localhost (default: none)
// port: 8545, // Standard Ethereum port (default: none)
// network_id: "*", // Any network (default: none)
// },
// Another network with more advanced options...
// advanced: {
// port: 8777, // Custom port
// network_id: 1342, // Custom network
// gas: 8500000, // Gas sent with each transaction (default: ~6700000)
// gasPrice: 20000000000, // 20 gwei (in wei) (default: 100 gwei)
// from: <address>, // Account to send txs from (default: accounts[0])
// websockets: true // Enable EventEmitter interface for web3 (default: false)
// },
// Useful for deploying to a public network.
// NB: It's important to wrap the provider as a function.
// ropsten: {
// provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/YOUR-PROJECT-ID`),
// network_id: 3, // Ropsten's id
// gas: 5500000, // Ropsten has a lower block limit than mainnet
// confirmations: 2, // # of confs to wait between deployments. (default: 0)
// timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50)
// skipDryRun: true // Skip dry run before migrations? (default: false for public nets )
// },
// Useful for private networks
// private: {
// provider: () => new HDWalletProvider(mnemonic, `https://network.io`),
// network_id: 2111, // This network is yours, in the cloud.
// production: true // Treats this network as if it was a public net. (default: false)
// }
},
// Set default mocha options here, use special reporters etc.
mocha: {
// timeout: 100000
},
// Configure your compilers
compilers: {
solc: {
version: "0.5.8", // Fetch exact version from solc-bin (default: truffle's version)
// docker: true, // Use "0.5.1" you've installed locally with docker (default: false)
// settings: { // See the solidity docs for advice about optimization and evmVersion
// optimizer: {
// enabled: false,
// runs: 200
// },
// evmVersion: "byzantium"
// }
}
}
}

5299
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

18
package.json Normal file
View File

@ -0,0 +1,18 @@
{
"name": "circuits",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"circom": "0.0.30",
"circomlib": "0.0.10",
"snarkjs": "^0.1.14",
"websnark": "0.0.4"
}
}