From cf3a3f5b4af15158461bc2c610a69e5ad5e01f68 Mon Sep 17 00:00:00 2001 From: youwenbusi <1245549353@qq.com> Date: Mon, 3 Aug 2020 15:03:57 +0800 Subject: [PATCH] deposit from web and async every once after deposit --- .../template => template}/get.html | 0 .../template => template}/index.html | 0 .../template => template}/post.html | 0 .../template => template}/result.html | 0 zeth/merkle_tree.py | 39 +- zeth/wallet.py | 5 +- zkclient/settings.py | 19 +- zkclientapp/__init__.py | 2 + zkclientapp/admin.py | 5 +- zkclientapp/models.py | 3 +- zkclientapp/routes.py | 121 ++- zkclientapp/urls.py | 3 + zkclientapp/views.py | 10 +- zkservice/zkserver/db.sqlite3 | Bin 143360 -> 0 bytes zkservice/zkserver/manage.py | 21 - zkservice/zkserver/zkserver/__init__.py | 0 zkservice/zkserver/zkserver/asgi.py | 16 - zkservice/zkserver/zkserver/settings.py | 125 --- zkservice/zkserver/zkserver/urls.py | 22 - zkservice/zkserver/zkserver/wsgi.py | 16 - zkservice/zkserver/zkserverapp/.views.py.swp | Bin 12288 -> 0 bytes zkservice/zkserver/zkserverapp/__init__.py | 2 - zkservice/zkserver/zkserverapp/admin.py | 8 - .../zkserver/zkserverapp/api/__init__.py | 3 - .../zkserverapp/api/ec_group_messages_pb2.py | 137 ---- .../zkserverapp/api/ec_group_messages_pb2.pyi | 67 -- .../api/ec_group_messages_pb2_grpc.py | 3 - .../zkserverapp/api/groth16_messages_pb2.py | 159 ---- .../zkserverapp/api/groth16_messages_pb2.pyi | 92 --- .../api/groth16_messages_pb2_grpc.py | 3 - .../zkserverapp/api/pghr13_messages_pb2.py | 231 ------ .../zkserverapp/api/pghr13_messages_pb2.pyi | 128 --- .../api/pghr13_messages_pb2_grpc.py | 3 - .../zkserver/zkserverapp/api/prover_pb2.py | 68 -- .../zkserver/zkserverapp/api/prover_pb2.pyi | 6 - .../zkserverapp/api/prover_pb2_grpc.py | 65 -- zkservice/zkserver/zkserverapp/api/py.typed | 5 - .../zkserverapp/api/snark_messages_pb2.py | 148 ---- .../zkserverapp/api/snark_messages_pb2.pyi | 86 -- .../api/snark_messages_pb2_grpc.py | 3 - .../zkserverapp/api/zeth_messages_pb2.py | 242 ------ .../zkserverapp/api/zeth_messages_pb2.pyi | 116 --- .../zkserverapp/api/zeth_messages_pb2_grpc.py | 3 - zkservice/zkserver/zkserverapp/apps.py | 5 - .../zkserver/zkserverapp/commands/__init__.py | 3 - .../zkserverapp/commands/constants.py | 20 - .../zkserverapp/commands/event_sync.py | 139 ---- .../zkserver/zkserverapp/commands/py.typed | 5 - .../zkserver/zkserverapp/commands/utils.py | 320 -------- .../zkserverapp/commands/zeth_deploy.py | 54 -- .../zkserverapp/commands/zeth_deposit.py | 69 -- .../zkserverapp/commands/zeth_gen_address.py | 39 - .../commands/zeth_gen_fisco_address.py | 39 - .../zkserverapp/commands/zeth_ls_commits.py | 25 - .../zkserverapp/commands/zeth_ls_notes.py | 36 - .../zkserver/zkserverapp/commands/zeth_mix.py | 80 -- .../commands/zeth_token_approve.py | 51 -- .../zkserverapp/commands/zeth_token_deploy.py | 46 -- .../zkserver/zkserverapp/contract/ERC20.sol | 230 ------ .../zkserverapp/contract/ERC20Mintable.abi | 1 - .../zkserverapp/contract/ERC20Mintable.bin | 1 - .../zkserverapp/contract/ERC20Mintable.py | 121 --- .../zkserverapp/contract/Groth16Mixer.abi | 18 - .../zkserverapp/contract/Groth16Mixer.bin | 1 - .../zkserverapp/contract/Groth16Mixer.py | 86 -- .../zkserver/zkserverapp/contract/__init__.py | 3 - .../contract/mixer/BaseMerkleTree.sol | 66 -- .../zkserverapp/contract/mixer/BaseMixer.sol | 381 --------- .../contract/mixer/Groth16Mixer.sol | 371 --------- .../contract/mixer/MerkleTreeMiMC7.sol | 116 --- .../contract/mixer/MerkleTreeMiMC7_test.sol | 39 - .../contract/mixer/MerkleTreeSha256.sol | 42 - .../zkserverapp/contract/mixer/MiMC7.sol | 80 -- .../zkserverapp/contract/mixer/Migrations.sol | 27 - .../contract/mixer/OTSchnorrVerifier.sol | 120 --- .../zkserverapp/contract/mixer/Pairing.sol | 214 ----- .../contract/mixer/Pghr13Mixer.sol | 282 ------- .../zkserverapp/contract/mixer/README.md | 11 - .../contract/mixer/abi/Groth16Mixer.abi | 1 - .../contract/mixer/abi/Groth16Mixer.bin | 1 - .../zkserverapp/migrations/0001_initial.py | 22 - .../zkserverapp/migrations/0002_entry.py | 26 - .../migrations/0003_auto_20200731_0257.py | 29 - .../zkserverapp/migrations/__init__.py | 0 zkservice/zkserver/zkserverapp/models.py | 9 - zkservice/zkserver/zkserverapp/python_web3 | 1 - zkservice/zkserver/zkserverapp/routes.py | 66 -- zkservice/zkserver/zkserverapp/tests.py | 3 - zkservice/zkserver/zkserverapp/urls.py | 22 - zkservice/zkserver/zkserverapp/views.py | 31 - .../zkserver/zkserverapp/zeth/__init__.py | 5 - .../zkserver/zkserverapp/zeth/constants.py | 116 --- .../zkserver/zkserverapp/zeth/contracts.py | 340 -------- .../zkserver/zkserverapp/zeth/encryption.py | 266 ------- zkservice/zkserver/zkserverapp/zeth/errors.py | 9 - .../zkserver/zkserverapp/zeth/merkle_tree.py | 323 -------- zkservice/zkserver/zkserverapp/zeth/mimc.py | 66 -- .../zkserver/zkserverapp/zeth/mixer_client.py | 739 ------------------ .../zkserver/zkserverapp/zeth/ownership.py | 76 -- .../zkserverapp/zeth/prover_client.py | 42 - zkservice/zkserver/zkserverapp/zeth/py.typed | 5 - .../zkserver/zkserverapp/zeth/signing.py | 162 ---- .../zkserverapp/zeth/testing_utils.py | 108 --- zkservice/zkserver/zkserverapp/zeth/timer.py | 30 - zkservice/zkserver/zkserverapp/zeth/utils.py | 275 ------- zkservice/zkserver/zkserverapp/zeth/wallet.py | 322 -------- .../zkserver/zkserverapp/zeth/zeth_address.py | 113 --- .../zkserver/zkserverapp/zeth/zksnark.py | 204 ----- 108 files changed, 179 insertions(+), 8359 deletions(-) rename {zkservice/zkserver/zkserverapp/template => template}/get.html (100%) rename {zkservice/zkserver/zkserverapp/template => template}/index.html (100%) rename {zkservice/zkserver/zkserverapp/template => template}/post.html (100%) rename {zkservice/zkserver/zkserverapp/template => template}/result.html (100%) delete mode 100644 zkservice/zkserver/db.sqlite3 delete mode 100644 zkservice/zkserver/manage.py delete mode 100644 zkservice/zkserver/zkserver/__init__.py delete mode 100644 zkservice/zkserver/zkserver/asgi.py delete mode 100644 zkservice/zkserver/zkserver/settings.py delete mode 100644 zkservice/zkserver/zkserver/urls.py delete mode 100644 zkservice/zkserver/zkserver/wsgi.py delete mode 100644 zkservice/zkserver/zkserverapp/.views.py.swp delete mode 100644 zkservice/zkserver/zkserverapp/__init__.py delete mode 100644 zkservice/zkserver/zkserverapp/admin.py delete mode 100644 zkservice/zkserver/zkserverapp/api/__init__.py delete mode 100644 zkservice/zkserver/zkserverapp/api/ec_group_messages_pb2.py delete mode 100644 zkservice/zkserver/zkserverapp/api/ec_group_messages_pb2.pyi delete mode 100644 zkservice/zkserver/zkserverapp/api/ec_group_messages_pb2_grpc.py delete mode 100644 zkservice/zkserver/zkserverapp/api/groth16_messages_pb2.py delete mode 100644 zkservice/zkserver/zkserverapp/api/groth16_messages_pb2.pyi delete mode 100644 zkservice/zkserver/zkserverapp/api/groth16_messages_pb2_grpc.py delete mode 100644 zkservice/zkserver/zkserverapp/api/pghr13_messages_pb2.py delete mode 100644 zkservice/zkserver/zkserverapp/api/pghr13_messages_pb2.pyi delete mode 100644 zkservice/zkserver/zkserverapp/api/pghr13_messages_pb2_grpc.py delete mode 100644 zkservice/zkserver/zkserverapp/api/prover_pb2.py delete mode 100644 zkservice/zkserver/zkserverapp/api/prover_pb2.pyi delete mode 100644 zkservice/zkserver/zkserverapp/api/prover_pb2_grpc.py delete mode 100644 zkservice/zkserver/zkserverapp/api/py.typed delete mode 100644 zkservice/zkserver/zkserverapp/api/snark_messages_pb2.py delete mode 100644 zkservice/zkserver/zkserverapp/api/snark_messages_pb2.pyi delete mode 100644 zkservice/zkserver/zkserverapp/api/snark_messages_pb2_grpc.py delete mode 100644 zkservice/zkserver/zkserverapp/api/zeth_messages_pb2.py delete mode 100644 zkservice/zkserver/zkserverapp/api/zeth_messages_pb2.pyi delete mode 100644 zkservice/zkserver/zkserverapp/api/zeth_messages_pb2_grpc.py delete mode 100644 zkservice/zkserver/zkserverapp/apps.py delete mode 100644 zkservice/zkserver/zkserverapp/commands/__init__.py delete mode 100644 zkservice/zkserver/zkserverapp/commands/constants.py delete mode 100644 zkservice/zkserver/zkserverapp/commands/event_sync.py delete mode 100644 zkservice/zkserver/zkserverapp/commands/py.typed delete mode 100644 zkservice/zkserver/zkserverapp/commands/utils.py delete mode 100644 zkservice/zkserver/zkserverapp/commands/zeth_deploy.py delete mode 100644 zkservice/zkserver/zkserverapp/commands/zeth_deposit.py delete mode 100644 zkservice/zkserver/zkserverapp/commands/zeth_gen_address.py delete mode 100644 zkservice/zkserver/zkserverapp/commands/zeth_gen_fisco_address.py delete mode 100644 zkservice/zkserver/zkserverapp/commands/zeth_ls_commits.py delete mode 100644 zkservice/zkserver/zkserverapp/commands/zeth_ls_notes.py delete mode 100644 zkservice/zkserver/zkserverapp/commands/zeth_mix.py delete mode 100644 zkservice/zkserver/zkserverapp/commands/zeth_token_approve.py delete mode 100644 zkservice/zkserver/zkserverapp/commands/zeth_token_deploy.py delete mode 100644 zkservice/zkserver/zkserverapp/contract/ERC20.sol delete mode 100644 zkservice/zkserver/zkserverapp/contract/ERC20Mintable.abi delete mode 100644 zkservice/zkserver/zkserverapp/contract/ERC20Mintable.bin delete mode 100644 zkservice/zkserver/zkserverapp/contract/ERC20Mintable.py delete mode 100644 zkservice/zkserver/zkserverapp/contract/Groth16Mixer.abi delete mode 100644 zkservice/zkserver/zkserverapp/contract/Groth16Mixer.bin delete mode 100644 zkservice/zkserver/zkserverapp/contract/Groth16Mixer.py delete mode 100644 zkservice/zkserver/zkserverapp/contract/__init__.py delete mode 100644 zkservice/zkserver/zkserverapp/contract/mixer/BaseMerkleTree.sol delete mode 100644 zkservice/zkserver/zkserverapp/contract/mixer/BaseMixer.sol delete mode 100644 zkservice/zkserver/zkserverapp/contract/mixer/Groth16Mixer.sol delete mode 100644 zkservice/zkserver/zkserverapp/contract/mixer/MerkleTreeMiMC7.sol delete mode 100644 zkservice/zkserver/zkserverapp/contract/mixer/MerkleTreeMiMC7_test.sol delete mode 100644 zkservice/zkserver/zkserverapp/contract/mixer/MerkleTreeSha256.sol delete mode 100644 zkservice/zkserver/zkserverapp/contract/mixer/MiMC7.sol delete mode 100644 zkservice/zkserver/zkserverapp/contract/mixer/Migrations.sol delete mode 100644 zkservice/zkserver/zkserverapp/contract/mixer/OTSchnorrVerifier.sol delete mode 100644 zkservice/zkserver/zkserverapp/contract/mixer/Pairing.sol delete mode 100644 zkservice/zkserver/zkserverapp/contract/mixer/Pghr13Mixer.sol delete mode 100644 zkservice/zkserver/zkserverapp/contract/mixer/README.md delete mode 100644 zkservice/zkserver/zkserverapp/contract/mixer/abi/Groth16Mixer.abi delete mode 100644 zkservice/zkserver/zkserverapp/contract/mixer/abi/Groth16Mixer.bin delete mode 100644 zkservice/zkserver/zkserverapp/migrations/0001_initial.py delete mode 100644 zkservice/zkserver/zkserverapp/migrations/0002_entry.py delete mode 100644 zkservice/zkserver/zkserverapp/migrations/0003_auto_20200731_0257.py delete mode 100644 zkservice/zkserver/zkserverapp/migrations/__init__.py delete mode 100644 zkservice/zkserver/zkserverapp/models.py delete mode 160000 zkservice/zkserver/zkserverapp/python_web3 delete mode 100644 zkservice/zkserver/zkserverapp/routes.py delete mode 100644 zkservice/zkserver/zkserverapp/tests.py delete mode 100644 zkservice/zkserver/zkserverapp/urls.py delete mode 100644 zkservice/zkserver/zkserverapp/views.py delete mode 100644 zkservice/zkserver/zkserverapp/zeth/__init__.py delete mode 100644 zkservice/zkserver/zkserverapp/zeth/constants.py delete mode 100644 zkservice/zkserver/zkserverapp/zeth/contracts.py delete mode 100644 zkservice/zkserver/zkserverapp/zeth/encryption.py delete mode 100644 zkservice/zkserver/zkserverapp/zeth/errors.py delete mode 100644 zkservice/zkserver/zkserverapp/zeth/merkle_tree.py delete mode 100644 zkservice/zkserver/zkserverapp/zeth/mimc.py delete mode 100644 zkservice/zkserver/zkserverapp/zeth/mixer_client.py delete mode 100644 zkservice/zkserver/zkserverapp/zeth/ownership.py delete mode 100644 zkservice/zkserver/zkserverapp/zeth/prover_client.py delete mode 100644 zkservice/zkserver/zkserverapp/zeth/py.typed delete mode 100644 zkservice/zkserver/zkserverapp/zeth/signing.py delete mode 100644 zkservice/zkserver/zkserverapp/zeth/testing_utils.py delete mode 100644 zkservice/zkserver/zkserverapp/zeth/timer.py delete mode 100644 zkservice/zkserver/zkserverapp/zeth/utils.py delete mode 100644 zkservice/zkserver/zkserverapp/zeth/wallet.py delete mode 100644 zkservice/zkserver/zkserverapp/zeth/zeth_address.py delete mode 100644 zkservice/zkserver/zkserverapp/zeth/zksnark.py diff --git a/zkservice/zkserver/zkserverapp/template/get.html b/template/get.html similarity index 100% rename from zkservice/zkserver/zkserverapp/template/get.html rename to template/get.html diff --git a/zkservice/zkserver/zkserverapp/template/index.html b/template/index.html similarity index 100% rename from zkservice/zkserver/zkserverapp/template/index.html rename to template/index.html diff --git a/zkservice/zkserver/zkserverapp/template/post.html b/template/post.html similarity index 100% rename from zkservice/zkserver/zkserverapp/template/post.html rename to template/post.html diff --git a/zkservice/zkserver/zkserverapp/template/result.html b/template/result.html similarity index 100% rename from zkservice/zkserver/zkserverapp/template/result.html rename to template/result.html diff --git a/zeth/merkle_tree.py b/zeth/merkle_tree.py index 4b0b9ae..4e21a63 100644 --- a/zeth/merkle_tree.py +++ b/zeth/merkle_tree.py @@ -4,11 +4,15 @@ from __future__ import annotations from zeth.mimc import MiMC7 -from os.path import exists +from os.path import exists, dirname, abspath import json import math from typing import Dict, List, Tuple, Iterator, cast, Any +import sys +sys.path.append('../zkservice/zkserver') +#sys.path.append('./zkservice/zkserver') +from zkserverapp.models import merkletree ZERO_ENTRY = bytes.fromhex( "0000000000000000000000000000000000000000000000000000000000000000") @@ -223,6 +227,39 @@ def save(self) -> None: with open(self.filename, "w") as tree_f: json.dump(self.tree_data.to_json_dict(), tree_f) +class sqlMerkleTree(MerkleTree): + """ + Version of MerkleTree that load the MerkleTree data from mysql. + """ + def __init__( + self, tree_data: MerkleTreeData, depth: int): + MerkleTree.__init__(self, tree_data, depth) + + def open(max_num_leaves: int) -> sqlMerkleTree: + depth = int(math.log(max_num_leaves, 2)) + if merkletree.objects.all().count() == 0: + tree_data = MerkleTreeData.empty_with_depth(depth) + else: + result = merkletree.objects.all().last() + print("mysql search result: ", result) + json_dict = json.loads(result.tree_data) + tree_data = MerkleTreeData.from_json_dict(json_dict) + assert depth == tree_data.depth + return sqlMerkleTree(tree_data, depth) + + def save(self) -> None: + if merkletree.objects.all().count() == 0: + json_str = json.dumps(self.tree_data.to_json_dict()) + print("json_str: ", json_str) + merkletree.objects.create(tree_data = json_str, is_new = True) + else: + result = merkletree.objects.all().last() + print("mysql search result: ", result) + json_str = json.dumps(self.tree_data.to_json_dict()) + result.tree_data = json_str + result.is_new = True + result.save() + def _leaf_address_to_node_address(address_leaf: int, tree_depth: int) -> int: """ diff --git a/zeth/wallet.py b/zeth/wallet.py index 6f68ed2..f7219ed 100644 --- a/zeth/wallet.py +++ b/zeth/wallet.py @@ -10,7 +10,7 @@ receive_note, compute_nullifier, compute_commitment from zeth.constants import ZETH_MERKLE_TREE_DEPTH from zeth.contracts import MixOutputEvents -from zeth.merkle_tree import PersistentMerkleTree +from zeth.merkle_tree import sqlMerkleTree from zeth.utils import EtherValue, short_commitment, from_zeth_units from api.zeth_messages_pb2 import ZethNote from os.path import join, basename, exists @@ -133,8 +133,7 @@ def __init__( self.state_file = join(wallet_dir, f"state_{username}") self.state = _load_state_or_default(self.state_file) _ensure_dir(join(self.wallet_dir, SPENT_SUBDIRECTORY)) - self.merkle_tree = PersistentMerkleTree.open( - join(wallet_dir, MERKLE_TREE_FILE), + self.merkle_tree = sqlMerkleTree.open( int(math.pow(2, ZETH_MERKLE_TREE_DEPTH))) self.merkle_tree_changed = False self.next_addr = self.merkle_tree.get_num_entries() diff --git a/zkclient/settings.py b/zkclient/settings.py index 6b14814..b40e76d 100644 --- a/zkclient/settings.py +++ b/zkclient/settings.py @@ -1,5 +1,5 @@ """ -Django settings for zkclient project. +Django settings for zkserver project. Generated by 'django-admin startproject' using Django 3.0.8. @@ -20,7 +20,7 @@ # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! -SECRET_KEY = 'yg!x=us*u&ja2*rfqz38v96nr$z(-^=c-&%)gvj+vaxq*csw6f' +SECRET_KEY = 'zt9&h=+9^j@!%jc^5pv==$fe&^ak7+2c0d$6k4!ao9ck4(ydc7' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True @@ -37,6 +37,7 @@ 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', + 'zkserverapp' ] MIDDLEWARE = [ @@ -49,12 +50,12 @@ 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -ROOT_URLCONF = 'zkclient.urls' +ROOT_URLCONF = 'zkserver.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [], + 'DIRS': [BASE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ @@ -67,7 +68,7 @@ }, ] -WSGI_APPLICATION = 'zkclient.wsgi.application' +WSGI_APPLICATION = 'zkserver.wsgi.application' # Database @@ -75,8 +76,12 @@ DATABASES = { 'default': { - 'ENGINE': 'django.db.backends.sqlite3', - 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), + 'ENGINE': 'django.db.backends.mysql', + 'NAME': 'merkletree', + 'USER': 'root', + 'PASSWORD': '8614', + 'HOST':'127.0.0.1', + 'PORT':'3306', } } diff --git a/zkclientapp/__init__.py b/zkclientapp/__init__.py index e69de29..063cd2c 100644 --- a/zkclientapp/__init__.py +++ b/zkclientapp/__init__.py @@ -0,0 +1,2 @@ +import pymysql +pymysql.install_as_MySQLdb() diff --git a/zkclientapp/admin.py b/zkclientapp/admin.py index 8b89b49..55ccb05 100644 --- a/zkclientapp/admin.py +++ b/zkclientapp/admin.py @@ -1,9 +1,8 @@ from django.contrib import admin - -# Register your models here. from .models import merkletree # Register your models here. -admin.site.register(merkletree) \ No newline at end of file +admin.site.register(merkletree) + diff --git a/zkclientapp/models.py b/zkclientapp/models.py index a630891..e6613d2 100644 --- a/zkclientapp/models.py +++ b/zkclientapp/models.py @@ -5,4 +5,5 @@ class merkletree(models.Model): class Meta: db_table = 'merkletree' mid = models.AutoField(max_length=11,db_column='MID',primary_key=True) - tree_data = models.TextField(max_length=40000, db_column='tree_data', blank=False) \ No newline at end of file + tree_data = models.TextField(max_length=40000, db_column='tree_data', blank=False) + is_new = models.BooleanField(db_column='is_new', default=False, blank=False) diff --git a/zkclientapp/routes.py b/zkclientapp/routes.py index 26508e8..5585285 100644 --- a/zkclientapp/routes.py +++ b/zkclientapp/routes.py @@ -3,15 +3,22 @@ from commands.event_sync import event_sync from commands.zeth_deposit import deposit from commands.zeth_token_approve import token_approve +from commands.zeth_token_deploy import deploy_token +from commands.zeth_deploy import deploy from commands.zeth_mix import mix from commands.zeth_ls_commits import ls_commits from commands.zeth_ls_notes import ls_notes from commands.zeth_deploy import deploy +from commands.utils import load_zeth_address, load_zeth_address_secret, open_wallet +from zeth.utils import EtherValue from python_web3.eth_account.account import Account -from commands.constants import USER_DIR, FISCO_ADDRESS_FILE, WALLET_DIR_DEFAULT +from commands.constants import USER_DIR, FISCO_ADDRESS_FILE, WALLET_DIR_DEFAULT, ADDRESS_FILE_DEFAULT from django.shortcuts import render import json +import time from django.http import JsonResponse +from os.path import exists +from . import models ''' The wallet of user is designed as that every wallet need to be specified a username and store the @@ -27,10 +34,17 @@ def genFiscoAddr(request) -> None: result = {} req = json.loads(request.body) + keystore_file = "{}/{}/{}".format(USER_DIR, req['username'], FISCO_ADDRESS_FILE) + if exists(keystore_file): + result['status'] = 1 + result['text'] = 'keystore existed' + return JsonResponse(result) (address, publickey) = gen_fisco_address(req['username'], req['password']) + result['status'] = 0 result['address'] = address - result['publickey'] = publickey - JsonResponse(result) + pubkey = ''.join(['%02X' % b for b in publickey]) + result['publickey'] = "0x" + pubkey.lower() + return JsonResponse(result) ''' make wallet by import the Fisco account that the user want to use with privatekey, username and password @@ -41,7 +55,9 @@ def importFiscoAddr(request) -> None: account = Account.privateKeyToAccount(req['privatekey']) keystore_file = "{}/{}/{}".format(USER_DIR, req['username'], FISCO_ADDRESS_FILE) if exists(keystore_file): - raise ClickException(f"ZethAddress file {keystore_file} exists") + result['status'] = 1 + result['text'] = 'keystore existed' + return JsonResponse(result) user_dir = "{}/{}/{}".format(USER_DIR, req['username'], WALLET_DIR_DEFAULT) _ensure_dir(user_dir) keytext = Account.encrypt(account.privateKey, req['password']) @@ -50,9 +66,11 @@ def importFiscoAddr(request) -> None: print(f"{req['username']}'s address: {account.address}") print(f"{req['username']}'s publickey: {account.publickey}") print(f"fisco account keypair written to {keystore_file}") + result['status'] = 0 result['address'] = account.address - result['publickey'] = account.publickey - JsonResponse(result) + pubkey = ''.join(['%02X' % b for b in account.publickey]) + result['publickey'] = "0x" + pubkey.lower() + return JsonResponse(result) ''' @@ -61,6 +79,93 @@ def importFiscoAddr(request) -> None: def genZbacAddr(request) -> None: result = {} req = json.loads(request.body) + addr_file = "{}/{}/{}".format(USER_DIR, req['username'], ADDRESS_FILE_DEFAULT) + if exists(addr_file): + result['status'] = 1 + result['text'] = 'account existed' + return JsonResponse(result) zbac_addr = gen_address(req['username']) - result['address'] = zbac_addr - JsonResponse(result) \ No newline at end of file + result['status'] = 0 + result['address'] = str(zbac_addr) + return JsonResponse(result) + +''' +deploy bac contract, only used by admin +''' +def deployToken(request) -> None: + result = {} + req = json.loads(request.body) + token_address = deploy_token(req['miner_address'], req['token_amount']) + if token_address : + result['status'] = 0 + result['address'] = str(token_address) + return JsonResponse(result) + result['status'] = 1 + result['text'] = 'deploy bac contract failed' + return JsonResponse(result) + +''' +deploy zksnark mixer contract, only used by admin +''' +def deployMixer(request) -> None: + result = {} + req = json.loads(request.body) + mixer_address = deploy(req['token_address']) + if mixer_address : + result['status'] = 0 + result['address'] = str(mixer_address) + return JsonResponse(result) + result['status'] = 1 + result['text'] = 'deploy zksnark mixer contract failed' + return JsonResponse(result) + +''' +deposit bac to mixer and get two notes with specified value +''' +def depositBac(request) -> None: + #todo: 从数据库中获取前一个交易是否已经完成,也就是merkletree是否已经更新 + #即is_new是否为True,如果不是则等待,如果是则置为False,开始执行交易 + while (models.merkletree.objects.all().count() and not models.merkletree.objects.all().last().is_new): + time.sleep(1) + sqlResult = models.merkletree.objects.all().last() + if models.merkletree.objects.all().count(): + sqlResult.is_new = False + sqlResult.save() + result = {} + req = json.loads(request.body) + keystore_file = "{}/{}/{}".format(USER_DIR, req['username'], FISCO_ADDRESS_FILE) + addr_file = "{}/{}/{}".format(USER_DIR, req['username'], ADDRESS_FILE_DEFAULT) + if exists(keystore_file) and exists(addr_file) : + outputapprove = token_approve(req['token_amount'], req['mixer_address'], req['token_address'], req['username'], req['password']) + if outputapprove : + zeth_address = load_zeth_address(req['username']) + output_specs = [] + print(str(zeth_address.addr_pk) + ',' + str(req['value1'])) + output_specs.append(str(zeth_address.addr_pk) + ',' + str(req['value1'])) + output_specs.append(str(zeth_address.addr_pk) + ',' + str(req['value2'])) + outputdeposit = deposit(req['mixer_address'], req['username'], req['password'], req['token_amount'], output_specs) + if outputdeposit : + event_sync(req['mixer_address']) + js_secret = load_zeth_address_secret(req['username']) + wallet = open_wallet(None, js_secret, req['username']) + total = EtherValue(0) + commits = [] + for addr, short_commit, value in wallet.note_summaries(): + total = total + value + commits.append(short_commit) + result['status'] = 0 + result['commits'] = commits + result['total_value'] = total.ether() + return JsonResponse(result) + else: + result['status'] = 1 + result['text'] = 'deposit failed' + return JsonResponse(result) + else: + result['status'] = 1 + result['text'] = 'token approve failed' + return JsonResponse(result) + + result['status'] = 1 + result['text'] = 'your account is not recorded in server, please import it firstly or create a new one' + return JsonResponse(result) \ No newline at end of file diff --git a/zkclientapp/urls.py b/zkclientapp/urls.py index 9708077..e1b8bbe 100644 --- a/zkclientapp/urls.py +++ b/zkclientapp/urls.py @@ -19,4 +19,7 @@ url(r'^post$', views.post), url(r'^genFiscoAddr$', routes.genFiscoAddr), url(r'^genZbacAddr$', routes.genZbacAddr), + url(r'^deployToken$', routes.deployToken), + url(r'^deployMixer$', routes.deployMixer), + url(r'^depositBac$', routes.depositBac), ] diff --git a/zkclientapp/views.py b/zkclientapp/views.py index aeecb2f..7e87e21 100644 --- a/zkclientapp/views.py +++ b/zkclientapp/views.py @@ -6,26 +6,26 @@ def index(request): "学习笔记的主页" - return render(request,'zkclientapp/template/index.html') + return render(request,'zkserverapp/template/index.html') def get_html(request): - return render(request, 'zkclientapp/template/get.html') + return render(request, 'zkserverapp/template/get.html') def get(request): context = {} # 通过request.GET['name']形式获取get表单内容 # result为重定向到的result.html所使用的变量 context['result'] = f"你搜索的内容为:{request.GET['q']}" - return render(request, 'zkclientapp/template/result.html', context) + return render(request, 'zkserverapp/template/result.html', context) def post_html(request): # 不能和get一样使用render_to_response必须使用render进行重定向,不然服务端不会设置csrf_token # return render_to_response('post.html') - return render(request, 'zkclientapp/template/post.html') + return render(request, 'zkserverapp/template/post.html') def post(request): context = {} # 通过request.GET['name']形式获取post表单内容 # result为重定向到的result.html所使用的变量 context['result'] = f"你搜索的内容为:{request.POST['q']}" - return render(request, 'zkclientapp/template/result.html', context) + return render(request, 'zkserverapp/template/result.html', context) diff --git a/zkservice/zkserver/db.sqlite3 b/zkservice/zkserver/db.sqlite3 deleted file mode 100644 index 29bb5fc39195cc65e301b76ad187ca4ef018ff4a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 143360 zcmeI5du$v@UdOvVPsg4qKQr0Q!(%(%WaM?+)ARCVZ`t)GUavRtWRo}#M=VXxOncnU zyfQO(?3{$;>@J7y00|H$I0+UZA%WnJ;{e?scl!s2&>kQ-gzgX=cSsoxku-Hg!RqV4@&Z%+zmj(yR?jLCm9n~?EqFLR`W00@8p2!H?xfB*=9 z00@8p2!H?xJbD77Cj!*zaNqL+d7pfq8184Bu9B6X^vj*ZwC;RNY5qH@`Zlt=gp>{l<8+nE$Wm{ zrB+wed|uINwMtDXQQ&Gpt9PqiBA%E_%kzEI*;3P4QmJWoHuajOm-IqSWosby;X~A^ zpC|(P0r?B^ZSo%Z4e~jnkWI(65Cs7c009sH0T2KI5C8!X009sH0T9@mz^HpNB-#!P z@k0oHXKJHT)pNcP_wl1*^SF=s+k4DCH7VLpMA+VY0`AdKzKp#)=`X}L3ikQFJBU99*AJ)|NZ1A1oD0I_vFvXSIN8Nv!p>2@B#r4009sH0T2KI z5C8!X009sH0T4JKff2u3m<&1R|06y}Dxd!kd)>nEqmKFiQIA`gnzYUN>$dm(ZnrQx z%8m%I`G3GgV<8sf^Z%h98Xad*YyLkdx`oj3w)sEX{|^U#K_EY*yZ?VmzC?bFyhBRl z23aI=GEN4F82n-IyTQKg z0w4eaAOHd&00JNY0w4eaAC16(TO1etTe^1F_+W|fkXxJ*{dujZ(GPOq`^RHOQf{3d z{Wg@CjH$3U6kz~5zNzZaOKIVqUpW!B6?#7&% z9vN|q5z%WpG802aqUp*^JUr+YCq*xFW~PiDc8fEjhr6@QV@Hm-#i-~pUD`5+jSSPR zEn{fZEl!Ib=GvAz$kn^Kdp08;-~!yHUzS3Q6w@I~2?pKbana2@@kuo2=Hf1lQ}~>K z%k;sM`ivyg2~Rr2uk2!8c)XYE>)~#!>9;@R7H7pC)0dU*Gty0mR=Sr{?O|T6M9+}B z_ms#zH}~+}Bkta5(RABPbn!&fXEU*9z}-7V4*=v_pJKrF|Ha_f1p0#)2!H?xfB*=9 z00@8p2!H?xfB*BknckAZsYwC^5`Xzm7dr7~m-;`gC<`>u3@;5WZTrsV$-pJH$-ALSC z+NkKa7OU&oQhw`VDYKO=U)fP_EN!mdye_Hd5-q#jP9l?)uN1QjuTve3VzzWyzj*HT zHE#E6I+~NO@7$Ev*K=}#T~l6OytaMm{L;PUmD_UWUSWHAV>z0+w{$nNLF=+{J3;f~ znH!g5%PY&<%cZ5e%d}ogW$8uZvkB*BqB8$<(&X7#`b;twm!t&S{};)31p0#)2!H?x zfB*=900@8p2!H?xfB*=9z!OMd(zV?Cpj8pJ|1S(Yft7<~5C8!X009sH0T2KI5C8!X z009sHfddoZ=l{t~f&SnH0w4eaAOHd&00JNY0w4eaAOHd&@DT~@PKg0wH!|NF3e5KQ z&IhX5+xazFsjsVYB6%`8C(+l*>)UtEzfxZ))h}HvpL~7i{7NBlU0*++kTz~<>l@V# z?P_K5+SdGq{Oq;tt$V5MbE~%+IsM|2d7eKtBd2ZW`Q=nPCh-sVi^}mtBA$*VVlUsh zb0$|Q8R!37_VKe)^h}(Jkmro^{~rqE!;e@&n1cWafB*=900@8p2!H?xfB*=900=zp z1pKa$@jZYz|Npo*74(4s2!H?xfB*=900@8p2!H?xfWXHmfcgK&X9y1<00JNY0w4ea zAOHd&00JNY0wD0X6JY26!(>4qKO!HJe<$B3ACP|{|3JP)zCr$s{0VuFe3|?{`Cal` zg0w4eaAOHd&00JNY0w4eaAn>#k z@VG?LALij04^Qy$I17EpczBeD&+_mY7J85HFvP>dJRD`AXM~5tJRIWTAPe0CJS02} z@-V~|a_Wz&u&WZYg00@8p2!H?x zfB*=900@8p2!Mbfu>F60{~vk+2!H?xfB*=900@8p2!H?xfB*fB*=900@8p2!H?xfB*=900@A<(@!Aa`wxML z?+fH)@Nas*<^5XVZvSV!Bc2=XU+(*`_a*;A-=|z(7vJx>B>tlC*TRbq9(_OXzT-$j z^#6sxTR(Ne7n+$7KQr4oPPu4S`{H95C;foILWvXnW$aFaH3vvvpdJQ2Q>*{>L*Wa(pgBfBpR`9im6#NE21 zGKE@YvsyQr)-w>JC;JjeAukOwan7xYYX9ydK}29vld1nroGuI zX#Z&Hp*1)==nECn;;w4dz{s_#>THU+crKAk%Np0;VLa5O89Iy{job8S6W>v!8~*75 zU+7ILetAFfh9?R?8Gj=C?j)>pSE9rXKUw z=gc<8>_@xxHM>A(sgHMGXjSq6j=8O={sDKgNZ)h98;|lawR?BeAKLAm7w^wnJ%&T! zfxXL{s2m+N8dsCqWK4F9UuWqf4;aZ#`__%ZQo!$d_N&=C8ZYkj;TYm=p6ECq9`S`P z(>qndQE}cJb=w^(l}Mx$@wl_U9quwbxP-kNIQ1HKOeKHE@1OTGeqSh^7T-=;L&C_l z>W9>J231EU84Oq>X6P`$$G*j)u^oH z=WK!vgOR;t?or+;&M<42v_a@i#FZBBPgICN_2cwk!m4|a{n8$I68^t8Cj!Pf5-^@gU@wL6{_pySy#Gpf|4XhvcKv+MAGlV<_j1d9+R|!tRYGZ0s(P*?VZ43)q$B^K)=$`$v2BUOvBAt%M(BQdzWXZ4 z?#P@kbTuOGruovOx!_Z$yU}dRTidScHBB*GByvePnT)lYgv|<>dynmzUCSG5i|vN2 z+O})a-G^k-7m7s0`={&+Q>Lu;vc7ht?U~GRvog1}9g9-jwhM3H{HF_fO?z5vwR1n- zF0;$3(+eqY=u$)!I8AfijjnW7cwA{0r$pQ1{@ua2FElq#t<>mJV)LX%RGw>Fi7cx120L=1m+i}q^b`i| zGkRUAZ_))_EH3~J+N~&J8M9PVHn@A?4p{}h> zgq(gx;>(=_VVn36@_B75I>N6!gNP5Icyz}uoVP^?Sy;bKKkbQv^O z?n4b7C+7Y4KFoWby^wj;2k)`8>TC^C$J4I8lgjqZgvjn|C+SI|n7I3C`?Jn2L}5?v zqMFr;N{P08QAs7U`B*-dL&Xdc= ztZ|QtCw-K)YO(*{3wDXTi20Cuz+Vg4|9_Mt0KPx~1V8`;KmY_l00ck)1V8`;K;SVY zfb;*4X~RGk2!H?xfB*=900@8p2!H?xfB*Zd`o7)w)xKZpYfuMxfdB}A00@8p2!H?xfWRk|z=^O&5XU3_EnT~-@UK2QruF`7R$R>lUrBI1)Gf#H*Ag_r#54!{Pb(9EhjW$nJQWqrV7L6S;NLu(XugB@c6N3xC$Rr(K28v3=c=R2QOD) zerI$`hZ%n^L~SBbuc^dlWol{K9X9MtH8wj_kC_r4rFN6kUZ%)q#59@F=@Du%lk#v? z=9fh_cB)!SnVA-5iL=AhIQoLel;#sw<)!mZ))TgLBqn-*0eB1vFNh_YH@tZ&BQdbnF{v) zL_f_NkGS~N3$@B-wRL$Oo9LtYQ!_5}`Yj7nfMIjUurU?1Y)lC}eyo?;jGb~Z4J`vE zf=5pKY3_8ahpVu@mA56uN_yT$EoW0brXDMU*_xuP#OJ++wW-X?VAiHQEAcrGwT?u4 zm_{p=nKGeP%1O6J=sgwXV(Ir{w?;cl2-5^(w4QcRtLcO()NW_Wv@CnLr76;GX-aHa zPKeZUYL*GKn=yGU8=U|Dgg&HDZ4dwf5C8!X009sH0T2KI5CDNs6ahB>7s)>h^an2x z009sH0T2KI5C8!X009sH0T2LzCzil**L<%m$1FuGoyWK5`;UDnV+wHb#L{p5$MDr&3c4l|qym{|4Gn;HW zUCr%h&v7m8W&&k5A?l$z@7Fu~h(1e*EQ-v!U9G5Hs=(B0R)ly$Vw8G(K}tP?l!b~v z{z#Y#%rn@dP`NMchevjc%H@Vnl01E3dR1{t1JwsX3nYL9HWN@;@Ni3Q+p(iZ?5$q! zs^j+VY1?dvcaQ)QKmter2_OL^fCP{L68LWkFsX)IgY33B86I@%n(u1o5-TKt1dsp{ zKmter2_OL^fCP{L5;M1K_y5{1LOy`rf>uEbpm|UnGzq!@ zY6Tq!ecnmPC(t_RJ?Js03$!0ps3pV%y#uv_8bLK60{XavkTp;e6aXCnS#f-^V!?t0 zkN^@u0!RP}AOR$R1dzaQ5a6K5l&P`+l@OqEgG_r>s<0-Gm#Lygm^;Lx5x$A@ivpwl ztdUq}hVSG~azU4tP3EU&j2E*;VpP8|rl*&+rPmvo#E|3D-Fp7g>8qu;jV|vc=8h=WA}>@*?pbxA?TrD5}-lOvMOcXc!JnQKf_|#7NHbb zSV>d>^fJ*4(MzJB&<1|9v9=U5uV?jp6WtW@9?2&ci`fNm;XK<-y5@!01kxly*ISB50s8CMPYt7|W^Q@SHKQ#UJ6#doN z2gcPWAB?ujq`Pzu-8z2GXjF>$81>Ndda%|Kxcddp{0}{bVJr5R7MZ;oUHa1}+H%rZ zm^Rba2GN#Q3aOVa_(p~yZS%?;>bX-gh0wSGQI$FSoIDqzGIbLYl*K3)xZ)GKMYj?X RW#(6z!iA#}G@W+<`386R3itp3 diff --git a/zkservice/zkserver/zkserverapp/__init__.py b/zkservice/zkserver/zkserverapp/__init__.py deleted file mode 100644 index 063cd2c..0000000 --- a/zkservice/zkserver/zkserverapp/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -import pymysql -pymysql.install_as_MySQLdb() diff --git a/zkservice/zkserver/zkserverapp/admin.py b/zkservice/zkserver/zkserverapp/admin.py deleted file mode 100644 index 55ccb05..0000000 --- a/zkservice/zkserver/zkserverapp/admin.py +++ /dev/null @@ -1,8 +0,0 @@ -from django.contrib import admin -from .models import merkletree - -# Register your models here. - - -admin.site.register(merkletree) - diff --git a/zkservice/zkserver/zkserverapp/api/__init__.py b/zkservice/zkserver/zkserverapp/api/__init__.py deleted file mode 100644 index b6e016d..0000000 --- a/zkservice/zkserver/zkserverapp/api/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ diff --git a/zkservice/zkserver/zkserverapp/api/ec_group_messages_pb2.py b/zkservice/zkserver/zkserverapp/api/ec_group_messages_pb2.py deleted file mode 100644 index d889287..0000000 --- a/zkservice/zkserver/zkserverapp/api/ec_group_messages_pb2.py +++ /dev/null @@ -1,137 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: api/ec_group_messages.proto - -import sys -_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - - - -DESCRIPTOR = _descriptor.FileDescriptor( - name='api/ec_group_messages.proto', - package='zeth_proto', - syntax='proto3', - serialized_options=None, - serialized_pb=_b('\n\x1b\x61pi/ec_group_messages.proto\x12\nzeth_proto\"<\n\x18HexPointBaseGroup1Affine\x12\x0f\n\x07x_coord\x18\x01 \x01(\t\x12\x0f\n\x07y_coord\x18\x02 \x01(\t\"j\n\x18HexPointBaseGroup2Affine\x12\x12\n\nx_c1_coord\x18\x01 \x01(\t\x12\x12\n\nx_c0_coord\x18\x02 \x01(\t\x12\x12\n\ny_c1_coord\x18\x03 \x01(\t\x12\x12\n\ny_c0_coord\x18\x04 \x01(\tb\x06proto3') -) - - - - -_HEXPOINTBASEGROUP1AFFINE = _descriptor.Descriptor( - name='HexPointBaseGroup1Affine', - full_name='zeth_proto.HexPointBaseGroup1Affine', - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name='x_coord', full_name='zeth_proto.HexPointBaseGroup1Affine.x_coord', index=0, - number=1, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='y_coord', full_name='zeth_proto.HexPointBaseGroup1Affine.y_coord', index=1, - number=2, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - ], - extensions=[ - ], - nested_types=[], - enum_types=[ - ], - serialized_options=None, - is_extendable=False, - syntax='proto3', - extension_ranges=[], - oneofs=[ - ], - serialized_start=43, - serialized_end=103, -) - - -_HEXPOINTBASEGROUP2AFFINE = _descriptor.Descriptor( - name='HexPointBaseGroup2Affine', - full_name='zeth_proto.HexPointBaseGroup2Affine', - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name='x_c1_coord', full_name='zeth_proto.HexPointBaseGroup2Affine.x_c1_coord', index=0, - number=1, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='x_c0_coord', full_name='zeth_proto.HexPointBaseGroup2Affine.x_c0_coord', index=1, - number=2, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='y_c1_coord', full_name='zeth_proto.HexPointBaseGroup2Affine.y_c1_coord', index=2, - number=3, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='y_c0_coord', full_name='zeth_proto.HexPointBaseGroup2Affine.y_c0_coord', index=3, - number=4, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - ], - extensions=[ - ], - nested_types=[], - enum_types=[ - ], - serialized_options=None, - is_extendable=False, - syntax='proto3', - extension_ranges=[], - oneofs=[ - ], - serialized_start=105, - serialized_end=211, -) - -DESCRIPTOR.message_types_by_name['HexPointBaseGroup1Affine'] = _HEXPOINTBASEGROUP1AFFINE -DESCRIPTOR.message_types_by_name['HexPointBaseGroup2Affine'] = _HEXPOINTBASEGROUP2AFFINE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -HexPointBaseGroup1Affine = _reflection.GeneratedProtocolMessageType('HexPointBaseGroup1Affine', (_message.Message,), { - 'DESCRIPTOR' : _HEXPOINTBASEGROUP1AFFINE, - '__module__' : 'api.ec_group_messages_pb2' - # @@protoc_insertion_point(class_scope:zeth_proto.HexPointBaseGroup1Affine) - }) -_sym_db.RegisterMessage(HexPointBaseGroup1Affine) - -HexPointBaseGroup2Affine = _reflection.GeneratedProtocolMessageType('HexPointBaseGroup2Affine', (_message.Message,), { - 'DESCRIPTOR' : _HEXPOINTBASEGROUP2AFFINE, - '__module__' : 'api.ec_group_messages_pb2' - # @@protoc_insertion_point(class_scope:zeth_proto.HexPointBaseGroup2Affine) - }) -_sym_db.RegisterMessage(HexPointBaseGroup2Affine) - - -# @@protoc_insertion_point(module_scope) diff --git a/zkservice/zkserver/zkserverapp/api/ec_group_messages_pb2.pyi b/zkservice/zkserver/zkserverapp/api/ec_group_messages_pb2.pyi deleted file mode 100644 index c195068..0000000 --- a/zkservice/zkserver/zkserverapp/api/ec_group_messages_pb2.pyi +++ /dev/null @@ -1,67 +0,0 @@ -# @generated by generate_proto_mypy_stubs.py. Do not edit! -import sys -from google.protobuf.descriptor import ( - Descriptor as google___protobuf___descriptor___Descriptor, -) - -from google.protobuf.message import ( - Message as google___protobuf___message___Message, -) - -from typing import ( - Optional as typing___Optional, - Text as typing___Text, -) - -from typing_extensions import ( - Literal as typing_extensions___Literal, -) - - -builtin___bool = bool -builtin___bytes = bytes -builtin___float = float -builtin___int = int - - -class HexPointBaseGroup1Affine(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - x_coord = ... # type: typing___Text - y_coord = ... # type: typing___Text - - def __init__(self, - *, - x_coord : typing___Optional[typing___Text] = None, - y_coord : typing___Optional[typing___Text] = None, - ) -> None: ... - @classmethod - def FromString(cls, s: builtin___bytes) -> HexPointBaseGroup1Affine: ... - def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - if sys.version_info >= (3,): - def ClearField(self, field_name: typing_extensions___Literal[u"x_coord",u"y_coord"]) -> None: ... - else: - def ClearField(self, field_name: typing_extensions___Literal[u"x_coord",b"x_coord",u"y_coord",b"y_coord"]) -> None: ... - -class HexPointBaseGroup2Affine(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - x_c1_coord = ... # type: typing___Text - x_c0_coord = ... # type: typing___Text - y_c1_coord = ... # type: typing___Text - y_c0_coord = ... # type: typing___Text - - def __init__(self, - *, - x_c1_coord : typing___Optional[typing___Text] = None, - x_c0_coord : typing___Optional[typing___Text] = None, - y_c1_coord : typing___Optional[typing___Text] = None, - y_c0_coord : typing___Optional[typing___Text] = None, - ) -> None: ... - @classmethod - def FromString(cls, s: builtin___bytes) -> HexPointBaseGroup2Affine: ... - def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - if sys.version_info >= (3,): - def ClearField(self, field_name: typing_extensions___Literal[u"x_c0_coord",u"x_c1_coord",u"y_c0_coord",u"y_c1_coord"]) -> None: ... - else: - def ClearField(self, field_name: typing_extensions___Literal[u"x_c0_coord",b"x_c0_coord",u"x_c1_coord",b"x_c1_coord",u"y_c0_coord",b"y_c0_coord",u"y_c1_coord",b"y_c1_coord"]) -> None: ... diff --git a/zkservice/zkserver/zkserverapp/api/ec_group_messages_pb2_grpc.py b/zkservice/zkserver/zkserverapp/api/ec_group_messages_pb2_grpc.py deleted file mode 100644 index a894352..0000000 --- a/zkservice/zkserver/zkserverapp/api/ec_group_messages_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc - diff --git a/zkservice/zkserver/zkserverapp/api/groth16_messages_pb2.py b/zkservice/zkserver/zkserverapp/api/groth16_messages_pb2.py deleted file mode 100644 index 10dd78a..0000000 --- a/zkservice/zkserver/zkserverapp/api/groth16_messages_pb2.py +++ /dev/null @@ -1,159 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: api/groth16_messages.proto - -import sys -_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from api import ec_group_messages_pb2 as api_dot_ec__group__messages__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name='api/groth16_messages.proto', - package='zeth_proto', - syntax='proto3', - serialized_options=None, - serialized_pb=_b('\n\x1a\x61pi/groth16_messages.proto\x12\nzeth_proto\x1a\x1b\x61pi/ec_group_messages.proto\"\xcf\x01\n\x16VerificationKeyGROTH16\x12\x36\n\x08\x61lpha_g1\x18\x01 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup1Affine\x12\x35\n\x07\x62\x65ta_g2\x18\x02 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup2Affine\x12\x36\n\x08\x64\x65lta_g2\x18\x04 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup2Affine\x12\x0e\n\x06\x61\x62\x63_g1\x18\x05 \x01(\t\"\xb9\x01\n\x14\x45xtendedProofGROTH16\x12/\n\x01\x61\x18\x01 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup1Affine\x12/\n\x01\x62\x18\x02 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup2Affine\x12/\n\x01\x63\x18\x03 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup1Affine\x12\x0e\n\x06inputs\x18\x04 \x01(\tb\x06proto3') - , - dependencies=[api_dot_ec__group__messages__pb2.DESCRIPTOR,]) - - - - -_VERIFICATIONKEYGROTH16 = _descriptor.Descriptor( - name='VerificationKeyGROTH16', - full_name='zeth_proto.VerificationKeyGROTH16', - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name='alpha_g1', full_name='zeth_proto.VerificationKeyGROTH16.alpha_g1', index=0, - number=1, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='beta_g2', full_name='zeth_proto.VerificationKeyGROTH16.beta_g2', index=1, - number=2, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='delta_g2', full_name='zeth_proto.VerificationKeyGROTH16.delta_g2', index=2, - number=4, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='abc_g1', full_name='zeth_proto.VerificationKeyGROTH16.abc_g1', index=3, - number=5, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - ], - extensions=[ - ], - nested_types=[], - enum_types=[ - ], - serialized_options=None, - is_extendable=False, - syntax='proto3', - extension_ranges=[], - oneofs=[ - ], - serialized_start=72, - serialized_end=279, -) - - -_EXTENDEDPROOFGROTH16 = _descriptor.Descriptor( - name='ExtendedProofGROTH16', - full_name='zeth_proto.ExtendedProofGROTH16', - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name='a', full_name='zeth_proto.ExtendedProofGROTH16.a', index=0, - number=1, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='b', full_name='zeth_proto.ExtendedProofGROTH16.b', index=1, - number=2, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='c', full_name='zeth_proto.ExtendedProofGROTH16.c', index=2, - number=3, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='inputs', full_name='zeth_proto.ExtendedProofGROTH16.inputs', index=3, - number=4, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - ], - extensions=[ - ], - nested_types=[], - enum_types=[ - ], - serialized_options=None, - is_extendable=False, - syntax='proto3', - extension_ranges=[], - oneofs=[ - ], - serialized_start=282, - serialized_end=467, -) - -_VERIFICATIONKEYGROTH16.fields_by_name['alpha_g1'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP1AFFINE -_VERIFICATIONKEYGROTH16.fields_by_name['beta_g2'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP2AFFINE -_VERIFICATIONKEYGROTH16.fields_by_name['delta_g2'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP2AFFINE -_EXTENDEDPROOFGROTH16.fields_by_name['a'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP1AFFINE -_EXTENDEDPROOFGROTH16.fields_by_name['b'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP2AFFINE -_EXTENDEDPROOFGROTH16.fields_by_name['c'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP1AFFINE -DESCRIPTOR.message_types_by_name['VerificationKeyGROTH16'] = _VERIFICATIONKEYGROTH16 -DESCRIPTOR.message_types_by_name['ExtendedProofGROTH16'] = _EXTENDEDPROOFGROTH16 -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -VerificationKeyGROTH16 = _reflection.GeneratedProtocolMessageType('VerificationKeyGROTH16', (_message.Message,), { - 'DESCRIPTOR' : _VERIFICATIONKEYGROTH16, - '__module__' : 'api.groth16_messages_pb2' - # @@protoc_insertion_point(class_scope:zeth_proto.VerificationKeyGROTH16) - }) -_sym_db.RegisterMessage(VerificationKeyGROTH16) - -ExtendedProofGROTH16 = _reflection.GeneratedProtocolMessageType('ExtendedProofGROTH16', (_message.Message,), { - 'DESCRIPTOR' : _EXTENDEDPROOFGROTH16, - '__module__' : 'api.groth16_messages_pb2' - # @@protoc_insertion_point(class_scope:zeth_proto.ExtendedProofGROTH16) - }) -_sym_db.RegisterMessage(ExtendedProofGROTH16) - - -# @@protoc_insertion_point(module_scope) diff --git a/zkservice/zkserver/zkserverapp/api/groth16_messages_pb2.pyi b/zkservice/zkserver/zkserverapp/api/groth16_messages_pb2.pyi deleted file mode 100644 index 8adc59b..0000000 --- a/zkservice/zkserver/zkserverapp/api/groth16_messages_pb2.pyi +++ /dev/null @@ -1,92 +0,0 @@ -# @generated by generate_proto_mypy_stubs.py. Do not edit! -import sys -from api.ec_group_messages_pb2 import ( - HexPointBaseGroup1Affine as api___ec_group_messages_pb2___HexPointBaseGroup1Affine, - HexPointBaseGroup2Affine as api___ec_group_messages_pb2___HexPointBaseGroup2Affine, -) - -from google.protobuf.descriptor import ( - Descriptor as google___protobuf___descriptor___Descriptor, -) - -from google.protobuf.message import ( - Message as google___protobuf___message___Message, -) - -from typing import ( - Optional as typing___Optional, - Text as typing___Text, -) - -from typing_extensions import ( - Literal as typing_extensions___Literal, -) - - -builtin___bool = bool -builtin___bytes = bytes -builtin___float = float -builtin___int = int - - -class VerificationKeyGROTH16(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - abc_g1 = ... # type: typing___Text - - @property - def alpha_g1(self) -> api___ec_group_messages_pb2___HexPointBaseGroup1Affine: ... - - @property - def beta_g2(self) -> api___ec_group_messages_pb2___HexPointBaseGroup2Affine: ... - - @property - def delta_g2(self) -> api___ec_group_messages_pb2___HexPointBaseGroup2Affine: ... - - def __init__(self, - *, - alpha_g1 : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup1Affine] = None, - beta_g2 : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup2Affine] = None, - delta_g2 : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup2Affine] = None, - abc_g1 : typing___Optional[typing___Text] = None, - ) -> None: ... - @classmethod - def FromString(cls, s: builtin___bytes) -> VerificationKeyGROTH16: ... - def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - if sys.version_info >= (3,): - def HasField(self, field_name: typing_extensions___Literal[u"alpha_g1",u"beta_g2",u"delta_g2"]) -> builtin___bool: ... - def ClearField(self, field_name: typing_extensions___Literal[u"abc_g1",u"alpha_g1",u"beta_g2",u"delta_g2"]) -> None: ... - else: - def HasField(self, field_name: typing_extensions___Literal[u"alpha_g1",b"alpha_g1",u"beta_g2",b"beta_g2",u"delta_g2",b"delta_g2"]) -> builtin___bool: ... - def ClearField(self, field_name: typing_extensions___Literal[u"abc_g1",b"abc_g1",u"alpha_g1",b"alpha_g1",u"beta_g2",b"beta_g2",u"delta_g2",b"delta_g2"]) -> None: ... - -class ExtendedProofGROTH16(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - inputs = ... # type: typing___Text - - @property - def a(self) -> api___ec_group_messages_pb2___HexPointBaseGroup1Affine: ... - - @property - def b(self) -> api___ec_group_messages_pb2___HexPointBaseGroup2Affine: ... - - @property - def c(self) -> api___ec_group_messages_pb2___HexPointBaseGroup1Affine: ... - - def __init__(self, - *, - a : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup1Affine] = None, - b : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup2Affine] = None, - c : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup1Affine] = None, - inputs : typing___Optional[typing___Text] = None, - ) -> None: ... - @classmethod - def FromString(cls, s: builtin___bytes) -> ExtendedProofGROTH16: ... - def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - if sys.version_info >= (3,): - def HasField(self, field_name: typing_extensions___Literal[u"a",u"b",u"c"]) -> builtin___bool: ... - def ClearField(self, field_name: typing_extensions___Literal[u"a",u"b",u"c",u"inputs"]) -> None: ... - else: - def HasField(self, field_name: typing_extensions___Literal[u"a",b"a",u"b",b"b",u"c",b"c"]) -> builtin___bool: ... - def ClearField(self, field_name: typing_extensions___Literal[u"a",b"a",u"b",b"b",u"c",b"c",u"inputs",b"inputs"]) -> None: ... diff --git a/zkservice/zkserver/zkserverapp/api/groth16_messages_pb2_grpc.py b/zkservice/zkserver/zkserverapp/api/groth16_messages_pb2_grpc.py deleted file mode 100644 index a894352..0000000 --- a/zkservice/zkserver/zkserverapp/api/groth16_messages_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc - diff --git a/zkservice/zkserver/zkserverapp/api/pghr13_messages_pb2.py b/zkservice/zkserver/zkserverapp/api/pghr13_messages_pb2.py deleted file mode 100644 index f51a7b6..0000000 --- a/zkservice/zkserver/zkserverapp/api/pghr13_messages_pb2.py +++ /dev/null @@ -1,231 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: api/pghr13_messages.proto - -import sys -_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from api import ec_group_messages_pb2 as api_dot_ec__group__messages__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name='api/pghr13_messages.proto', - package='zeth_proto', - syntax='proto3', - serialized_options=None, - serialized_pb=_b('\n\x19\x61pi/pghr13_messages.proto\x12\nzeth_proto\x1a\x1b\x61pi/ec_group_messages.proto\"\x96\x03\n\x15VerificationKeyPGHR13\x12/\n\x01\x61\x18\x01 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup2Affine\x12/\n\x01\x62\x18\x02 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup1Affine\x12/\n\x01\x63\x18\x03 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup2Affine\x12\x33\n\x05gamma\x18\x04 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup2Affine\x12;\n\rgamma_beta_g1\x18\x05 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup1Affine\x12;\n\rgamma_beta_g2\x18\x06 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup2Affine\x12/\n\x01z\x18\x07 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup2Affine\x12\n\n\x02ic\x18\x08 \x01(\t\"\xb3\x03\n\x13\x45xtendedProofPGHR13\x12/\n\x01\x61\x18\x01 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup1Affine\x12\x31\n\x03\x61_p\x18\x02 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup1Affine\x12/\n\x01\x62\x18\x03 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup2Affine\x12\x31\n\x03\x62_p\x18\x04 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup1Affine\x12/\n\x01\x63\x18\x05 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup1Affine\x12\x31\n\x03\x63_p\x18\x06 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup1Affine\x12/\n\x01h\x18\x07 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup1Affine\x12/\n\x01k\x18\x08 \x01(\x0b\x32$.zeth_proto.HexPointBaseGroup1Affine\x12\x0e\n\x06inputs\x18\t \x01(\tb\x06proto3') - , - dependencies=[api_dot_ec__group__messages__pb2.DESCRIPTOR,]) - - - - -_VERIFICATIONKEYPGHR13 = _descriptor.Descriptor( - name='VerificationKeyPGHR13', - full_name='zeth_proto.VerificationKeyPGHR13', - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name='a', full_name='zeth_proto.VerificationKeyPGHR13.a', index=0, - number=1, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='b', full_name='zeth_proto.VerificationKeyPGHR13.b', index=1, - number=2, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='c', full_name='zeth_proto.VerificationKeyPGHR13.c', index=2, - number=3, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='gamma', full_name='zeth_proto.VerificationKeyPGHR13.gamma', index=3, - number=4, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='gamma_beta_g1', full_name='zeth_proto.VerificationKeyPGHR13.gamma_beta_g1', index=4, - number=5, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='gamma_beta_g2', full_name='zeth_proto.VerificationKeyPGHR13.gamma_beta_g2', index=5, - number=6, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='z', full_name='zeth_proto.VerificationKeyPGHR13.z', index=6, - number=7, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='ic', full_name='zeth_proto.VerificationKeyPGHR13.ic', index=7, - number=8, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - ], - extensions=[ - ], - nested_types=[], - enum_types=[ - ], - serialized_options=None, - is_extendable=False, - syntax='proto3', - extension_ranges=[], - oneofs=[ - ], - serialized_start=71, - serialized_end=477, -) - - -_EXTENDEDPROOFPGHR13 = _descriptor.Descriptor( - name='ExtendedProofPGHR13', - full_name='zeth_proto.ExtendedProofPGHR13', - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name='a', full_name='zeth_proto.ExtendedProofPGHR13.a', index=0, - number=1, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='a_p', full_name='zeth_proto.ExtendedProofPGHR13.a_p', index=1, - number=2, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='b', full_name='zeth_proto.ExtendedProofPGHR13.b', index=2, - number=3, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='b_p', full_name='zeth_proto.ExtendedProofPGHR13.b_p', index=3, - number=4, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='c', full_name='zeth_proto.ExtendedProofPGHR13.c', index=4, - number=5, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='c_p', full_name='zeth_proto.ExtendedProofPGHR13.c_p', index=5, - number=6, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='h', full_name='zeth_proto.ExtendedProofPGHR13.h', index=6, - number=7, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='k', full_name='zeth_proto.ExtendedProofPGHR13.k', index=7, - number=8, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='inputs', full_name='zeth_proto.ExtendedProofPGHR13.inputs', index=8, - number=9, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - ], - extensions=[ - ], - nested_types=[], - enum_types=[ - ], - serialized_options=None, - is_extendable=False, - syntax='proto3', - extension_ranges=[], - oneofs=[ - ], - serialized_start=480, - serialized_end=915, -) - -_VERIFICATIONKEYPGHR13.fields_by_name['a'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP2AFFINE -_VERIFICATIONKEYPGHR13.fields_by_name['b'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP1AFFINE -_VERIFICATIONKEYPGHR13.fields_by_name['c'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP2AFFINE -_VERIFICATIONKEYPGHR13.fields_by_name['gamma'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP2AFFINE -_VERIFICATIONKEYPGHR13.fields_by_name['gamma_beta_g1'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP1AFFINE -_VERIFICATIONKEYPGHR13.fields_by_name['gamma_beta_g2'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP2AFFINE -_VERIFICATIONKEYPGHR13.fields_by_name['z'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP2AFFINE -_EXTENDEDPROOFPGHR13.fields_by_name['a'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP1AFFINE -_EXTENDEDPROOFPGHR13.fields_by_name['a_p'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP1AFFINE -_EXTENDEDPROOFPGHR13.fields_by_name['b'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP2AFFINE -_EXTENDEDPROOFPGHR13.fields_by_name['b_p'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP1AFFINE -_EXTENDEDPROOFPGHR13.fields_by_name['c'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP1AFFINE -_EXTENDEDPROOFPGHR13.fields_by_name['c_p'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP1AFFINE -_EXTENDEDPROOFPGHR13.fields_by_name['h'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP1AFFINE -_EXTENDEDPROOFPGHR13.fields_by_name['k'].message_type = api_dot_ec__group__messages__pb2._HEXPOINTBASEGROUP1AFFINE -DESCRIPTOR.message_types_by_name['VerificationKeyPGHR13'] = _VERIFICATIONKEYPGHR13 -DESCRIPTOR.message_types_by_name['ExtendedProofPGHR13'] = _EXTENDEDPROOFPGHR13 -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -VerificationKeyPGHR13 = _reflection.GeneratedProtocolMessageType('VerificationKeyPGHR13', (_message.Message,), { - 'DESCRIPTOR' : _VERIFICATIONKEYPGHR13, - '__module__' : 'api.pghr13_messages_pb2' - # @@protoc_insertion_point(class_scope:zeth_proto.VerificationKeyPGHR13) - }) -_sym_db.RegisterMessage(VerificationKeyPGHR13) - -ExtendedProofPGHR13 = _reflection.GeneratedProtocolMessageType('ExtendedProofPGHR13', (_message.Message,), { - 'DESCRIPTOR' : _EXTENDEDPROOFPGHR13, - '__module__' : 'api.pghr13_messages_pb2' - # @@protoc_insertion_point(class_scope:zeth_proto.ExtendedProofPGHR13) - }) -_sym_db.RegisterMessage(ExtendedProofPGHR13) - - -# @@protoc_insertion_point(module_scope) diff --git a/zkservice/zkserver/zkserverapp/api/pghr13_messages_pb2.pyi b/zkservice/zkserver/zkserverapp/api/pghr13_messages_pb2.pyi deleted file mode 100644 index 30600a2..0000000 --- a/zkservice/zkserver/zkserverapp/api/pghr13_messages_pb2.pyi +++ /dev/null @@ -1,128 +0,0 @@ -# @generated by generate_proto_mypy_stubs.py. Do not edit! -import sys -from api.ec_group_messages_pb2 import ( - HexPointBaseGroup1Affine as api___ec_group_messages_pb2___HexPointBaseGroup1Affine, - HexPointBaseGroup2Affine as api___ec_group_messages_pb2___HexPointBaseGroup2Affine, -) - -from google.protobuf.descriptor import ( - Descriptor as google___protobuf___descriptor___Descriptor, -) - -from google.protobuf.message import ( - Message as google___protobuf___message___Message, -) - -from typing import ( - Optional as typing___Optional, - Text as typing___Text, -) - -from typing_extensions import ( - Literal as typing_extensions___Literal, -) - - -builtin___bool = bool -builtin___bytes = bytes -builtin___float = float -builtin___int = int - - -class VerificationKeyPGHR13(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - ic = ... # type: typing___Text - - @property - def a(self) -> api___ec_group_messages_pb2___HexPointBaseGroup2Affine: ... - - @property - def b(self) -> api___ec_group_messages_pb2___HexPointBaseGroup1Affine: ... - - @property - def c(self) -> api___ec_group_messages_pb2___HexPointBaseGroup2Affine: ... - - @property - def gamma(self) -> api___ec_group_messages_pb2___HexPointBaseGroup2Affine: ... - - @property - def gamma_beta_g1(self) -> api___ec_group_messages_pb2___HexPointBaseGroup1Affine: ... - - @property - def gamma_beta_g2(self) -> api___ec_group_messages_pb2___HexPointBaseGroup2Affine: ... - - @property - def z(self) -> api___ec_group_messages_pb2___HexPointBaseGroup2Affine: ... - - def __init__(self, - *, - a : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup2Affine] = None, - b : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup1Affine] = None, - c : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup2Affine] = None, - gamma : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup2Affine] = None, - gamma_beta_g1 : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup1Affine] = None, - gamma_beta_g2 : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup2Affine] = None, - z : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup2Affine] = None, - ic : typing___Optional[typing___Text] = None, - ) -> None: ... - @classmethod - def FromString(cls, s: builtin___bytes) -> VerificationKeyPGHR13: ... - def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - if sys.version_info >= (3,): - def HasField(self, field_name: typing_extensions___Literal[u"a",u"b",u"c",u"gamma",u"gamma_beta_g1",u"gamma_beta_g2",u"z"]) -> builtin___bool: ... - def ClearField(self, field_name: typing_extensions___Literal[u"a",u"b",u"c",u"gamma",u"gamma_beta_g1",u"gamma_beta_g2",u"ic",u"z"]) -> None: ... - else: - def HasField(self, field_name: typing_extensions___Literal[u"a",b"a",u"b",b"b",u"c",b"c",u"gamma",b"gamma",u"gamma_beta_g1",b"gamma_beta_g1",u"gamma_beta_g2",b"gamma_beta_g2",u"z",b"z"]) -> builtin___bool: ... - def ClearField(self, field_name: typing_extensions___Literal[u"a",b"a",u"b",b"b",u"c",b"c",u"gamma",b"gamma",u"gamma_beta_g1",b"gamma_beta_g1",u"gamma_beta_g2",b"gamma_beta_g2",u"ic",b"ic",u"z",b"z"]) -> None: ... - -class ExtendedProofPGHR13(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - inputs = ... # type: typing___Text - - @property - def a(self) -> api___ec_group_messages_pb2___HexPointBaseGroup1Affine: ... - - @property - def a_p(self) -> api___ec_group_messages_pb2___HexPointBaseGroup1Affine: ... - - @property - def b(self) -> api___ec_group_messages_pb2___HexPointBaseGroup2Affine: ... - - @property - def b_p(self) -> api___ec_group_messages_pb2___HexPointBaseGroup1Affine: ... - - @property - def c(self) -> api___ec_group_messages_pb2___HexPointBaseGroup1Affine: ... - - @property - def c_p(self) -> api___ec_group_messages_pb2___HexPointBaseGroup1Affine: ... - - @property - def h(self) -> api___ec_group_messages_pb2___HexPointBaseGroup1Affine: ... - - @property - def k(self) -> api___ec_group_messages_pb2___HexPointBaseGroup1Affine: ... - - def __init__(self, - *, - a : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup1Affine] = None, - a_p : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup1Affine] = None, - b : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup2Affine] = None, - b_p : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup1Affine] = None, - c : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup1Affine] = None, - c_p : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup1Affine] = None, - h : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup1Affine] = None, - k : typing___Optional[api___ec_group_messages_pb2___HexPointBaseGroup1Affine] = None, - inputs : typing___Optional[typing___Text] = None, - ) -> None: ... - @classmethod - def FromString(cls, s: builtin___bytes) -> ExtendedProofPGHR13: ... - def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - if sys.version_info >= (3,): - def HasField(self, field_name: typing_extensions___Literal[u"a",u"a_p",u"b",u"b_p",u"c",u"c_p",u"h",u"k"]) -> builtin___bool: ... - def ClearField(self, field_name: typing_extensions___Literal[u"a",u"a_p",u"b",u"b_p",u"c",u"c_p",u"h",u"inputs",u"k"]) -> None: ... - else: - def HasField(self, field_name: typing_extensions___Literal[u"a",b"a",u"a_p",b"a_p",u"b",b"b",u"b_p",b"b_p",u"c",b"c",u"c_p",b"c_p",u"h",b"h",u"k",b"k"]) -> builtin___bool: ... - def ClearField(self, field_name: typing_extensions___Literal[u"a",b"a",u"a_p",b"a_p",u"b",b"b",u"b_p",b"b_p",u"c",b"c",u"c_p",b"c_p",u"h",b"h",u"inputs",b"inputs",u"k",b"k"]) -> None: ... diff --git a/zkservice/zkserver/zkserverapp/api/pghr13_messages_pb2_grpc.py b/zkservice/zkserver/zkserverapp/api/pghr13_messages_pb2_grpc.py deleted file mode 100644 index a894352..0000000 --- a/zkservice/zkserver/zkserverapp/api/pghr13_messages_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc - diff --git a/zkservice/zkserver/zkserverapp/api/prover_pb2.py b/zkservice/zkserver/zkserverapp/api/prover_pb2.py deleted file mode 100644 index aa7073d..0000000 --- a/zkservice/zkserver/zkserverapp/api/prover_pb2.py +++ /dev/null @@ -1,68 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: api/prover.proto - -import sys -_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 -from api import zeth_messages_pb2 as api_dot_zeth__messages__pb2 -from api import snark_messages_pb2 as api_dot_snark__messages__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name='api/prover.proto', - package='zeth_proto', - syntax='proto3', - serialized_options=None, - serialized_pb=_b('\n\x10\x61pi/prover.proto\x12\nzeth_proto\x1a\x1bgoogle/protobuf/empty.proto\x1a\x17\x61pi/zeth_messages.proto\x1a\x18\x61pi/snark_messages.proto2\x94\x01\n\x06Prover\x12K\n\x12GetVerificationKey\x12\x16.google.protobuf.Empty\x1a\x1b.zeth_proto.VerificationKey\"\x00\x12=\n\x05Prove\x12\x17.zeth_proto.ProofInputs\x1a\x19.zeth_proto.ExtendedProof\"\x00\x62\x06proto3') - , - dependencies=[google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,api_dot_zeth__messages__pb2.DESCRIPTOR,api_dot_snark__messages__pb2.DESCRIPTOR,]) - - - -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - - - -_PROVER = _descriptor.ServiceDescriptor( - name='Prover', - full_name='zeth_proto.Prover', - file=DESCRIPTOR, - index=0, - serialized_options=None, - serialized_start=113, - serialized_end=261, - methods=[ - _descriptor.MethodDescriptor( - name='GetVerificationKey', - full_name='zeth_proto.Prover.GetVerificationKey', - index=0, - containing_service=None, - input_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - output_type=api_dot_snark__messages__pb2._VERIFICATIONKEY, - serialized_options=None, - ), - _descriptor.MethodDescriptor( - name='Prove', - full_name='zeth_proto.Prover.Prove', - index=1, - containing_service=None, - input_type=api_dot_zeth__messages__pb2._PROOFINPUTS, - output_type=api_dot_snark__messages__pb2._EXTENDEDPROOF, - serialized_options=None, - ), -]) -_sym_db.RegisterServiceDescriptor(_PROVER) - -DESCRIPTOR.services_by_name['Prover'] = _PROVER - -# @@protoc_insertion_point(module_scope) diff --git a/zkservice/zkserver/zkserverapp/api/prover_pb2.pyi b/zkservice/zkserver/zkserverapp/api/prover_pb2.pyi deleted file mode 100644 index 8bba4ff..0000000 --- a/zkservice/zkserver/zkserverapp/api/prover_pb2.pyi +++ /dev/null @@ -1,6 +0,0 @@ -# @generated by generate_proto_mypy_stubs.py. Do not edit! -import sys -from google.protobuf.message import ( - Message as google___protobuf___message___Message, -) - diff --git a/zkservice/zkserver/zkserverapp/api/prover_pb2_grpc.py b/zkservice/zkserver/zkserverapp/api/prover_pb2_grpc.py deleted file mode 100644 index 7730c39..0000000 --- a/zkservice/zkserver/zkserverapp/api/prover_pb2_grpc.py +++ /dev/null @@ -1,65 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc - -from api import snark_messages_pb2 as api_dot_snark__messages__pb2 -from api import zeth_messages_pb2 as api_dot_zeth__messages__pb2 -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 - - -class ProverStub(object): - # missing associated documentation comment in .proto file - pass - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.GetVerificationKey = channel.unary_unary( - '/zeth_proto.Prover/GetVerificationKey', - request_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - response_deserializer=api_dot_snark__messages__pb2.VerificationKey.FromString, - ) - self.Prove = channel.unary_unary( - '/zeth_proto.Prover/Prove', - request_serializer=api_dot_zeth__messages__pb2.ProofInputs.SerializeToString, - response_deserializer=api_dot_snark__messages__pb2.ExtendedProof.FromString, - ) - - -class ProverServicer(object): - # missing associated documentation comment in .proto file - pass - - def GetVerificationKey(self, request, context): - """Fetch the verification key from the prover server - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - def Prove(self, request, context): - """Request a proof generation on the given inputs - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - -def add_ProverServicer_to_server(servicer, server): - rpc_method_handlers = { - 'GetVerificationKey': grpc.unary_unary_rpc_method_handler( - servicer.GetVerificationKey, - request_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - response_serializer=api_dot_snark__messages__pb2.VerificationKey.SerializeToString, - ), - 'Prove': grpc.unary_unary_rpc_method_handler( - servicer.Prove, - request_deserializer=api_dot_zeth__messages__pb2.ProofInputs.FromString, - response_serializer=api_dot_snark__messages__pb2.ExtendedProof.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - 'zeth_proto.Prover', rpc_method_handlers) - server.add_generic_rpc_handlers((generic_handler,)) diff --git a/zkservice/zkserver/zkserverapp/api/py.typed b/zkservice/zkserver/zkserverapp/api/py.typed deleted file mode 100644 index a0c5d77..0000000 --- a/zkservice/zkserver/zkserverapp/api/py.typed +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -# Empty file, required for mypy. \ No newline at end of file diff --git a/zkservice/zkserver/zkserverapp/api/snark_messages_pb2.py b/zkservice/zkserver/zkserverapp/api/snark_messages_pb2.py deleted file mode 100644 index 5311b65..0000000 --- a/zkservice/zkserver/zkserverapp/api/snark_messages_pb2.py +++ /dev/null @@ -1,148 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: api/snark_messages.proto - -import sys -_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from api import pghr13_messages_pb2 as api_dot_pghr13__messages__pb2 -from api import groth16_messages_pb2 as api_dot_groth16__messages__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name='api/snark_messages.proto', - package='zeth_proto', - syntax='proto3', - serialized_options=None, - serialized_pb=_b('\n\x18\x61pi/snark_messages.proto\x12\nzeth_proto\x1a\x19\x61pi/pghr13_messages.proto\x1a\x1a\x61pi/groth16_messages.proto\"\xa5\x01\n\x0fVerificationKey\x12\x44\n\x17pghr13_verification_key\x18\x01 \x01(\x0b\x32!.zeth_proto.VerificationKeyPGHR13H\x00\x12\x46\n\x18groth16_verification_key\x18\x02 \x01(\x0b\x32\".zeth_proto.VerificationKeyGROTH16H\x00\x42\x04\n\x02VK\"\x9b\x01\n\rExtendedProof\x12@\n\x15pghr13_extended_proof\x18\x01 \x01(\x0b\x32\x1f.zeth_proto.ExtendedProofPGHR13H\x00\x12\x42\n\x16groth16_extended_proof\x18\x02 \x01(\x0b\x32 .zeth_proto.ExtendedProofGROTH16H\x00\x42\x04\n\x02\x45Pb\x06proto3') - , - dependencies=[api_dot_pghr13__messages__pb2.DESCRIPTOR,api_dot_groth16__messages__pb2.DESCRIPTOR,]) - - - - -_VERIFICATIONKEY = _descriptor.Descriptor( - name='VerificationKey', - full_name='zeth_proto.VerificationKey', - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name='pghr13_verification_key', full_name='zeth_proto.VerificationKey.pghr13_verification_key', index=0, - number=1, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='groth16_verification_key', full_name='zeth_proto.VerificationKey.groth16_verification_key', index=1, - number=2, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - ], - extensions=[ - ], - nested_types=[], - enum_types=[ - ], - serialized_options=None, - is_extendable=False, - syntax='proto3', - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name='VK', full_name='zeth_proto.VerificationKey.VK', - index=0, containing_type=None, fields=[]), - ], - serialized_start=96, - serialized_end=261, -) - - -_EXTENDEDPROOF = _descriptor.Descriptor( - name='ExtendedProof', - full_name='zeth_proto.ExtendedProof', - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name='pghr13_extended_proof', full_name='zeth_proto.ExtendedProof.pghr13_extended_proof', index=0, - number=1, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='groth16_extended_proof', full_name='zeth_proto.ExtendedProof.groth16_extended_proof', index=1, - number=2, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - ], - extensions=[ - ], - nested_types=[], - enum_types=[ - ], - serialized_options=None, - is_extendable=False, - syntax='proto3', - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name='EP', full_name='zeth_proto.ExtendedProof.EP', - index=0, containing_type=None, fields=[]), - ], - serialized_start=264, - serialized_end=419, -) - -_VERIFICATIONKEY.fields_by_name['pghr13_verification_key'].message_type = api_dot_pghr13__messages__pb2._VERIFICATIONKEYPGHR13 -_VERIFICATIONKEY.fields_by_name['groth16_verification_key'].message_type = api_dot_groth16__messages__pb2._VERIFICATIONKEYGROTH16 -_VERIFICATIONKEY.oneofs_by_name['VK'].fields.append( - _VERIFICATIONKEY.fields_by_name['pghr13_verification_key']) -_VERIFICATIONKEY.fields_by_name['pghr13_verification_key'].containing_oneof = _VERIFICATIONKEY.oneofs_by_name['VK'] -_VERIFICATIONKEY.oneofs_by_name['VK'].fields.append( - _VERIFICATIONKEY.fields_by_name['groth16_verification_key']) -_VERIFICATIONKEY.fields_by_name['groth16_verification_key'].containing_oneof = _VERIFICATIONKEY.oneofs_by_name['VK'] -_EXTENDEDPROOF.fields_by_name['pghr13_extended_proof'].message_type = api_dot_pghr13__messages__pb2._EXTENDEDPROOFPGHR13 -_EXTENDEDPROOF.fields_by_name['groth16_extended_proof'].message_type = api_dot_groth16__messages__pb2._EXTENDEDPROOFGROTH16 -_EXTENDEDPROOF.oneofs_by_name['EP'].fields.append( - _EXTENDEDPROOF.fields_by_name['pghr13_extended_proof']) -_EXTENDEDPROOF.fields_by_name['pghr13_extended_proof'].containing_oneof = _EXTENDEDPROOF.oneofs_by_name['EP'] -_EXTENDEDPROOF.oneofs_by_name['EP'].fields.append( - _EXTENDEDPROOF.fields_by_name['groth16_extended_proof']) -_EXTENDEDPROOF.fields_by_name['groth16_extended_proof'].containing_oneof = _EXTENDEDPROOF.oneofs_by_name['EP'] -DESCRIPTOR.message_types_by_name['VerificationKey'] = _VERIFICATIONKEY -DESCRIPTOR.message_types_by_name['ExtendedProof'] = _EXTENDEDPROOF -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -VerificationKey = _reflection.GeneratedProtocolMessageType('VerificationKey', (_message.Message,), { - 'DESCRIPTOR' : _VERIFICATIONKEY, - '__module__' : 'api.snark_messages_pb2' - # @@protoc_insertion_point(class_scope:zeth_proto.VerificationKey) - }) -_sym_db.RegisterMessage(VerificationKey) - -ExtendedProof = _reflection.GeneratedProtocolMessageType('ExtendedProof', (_message.Message,), { - 'DESCRIPTOR' : _EXTENDEDPROOF, - '__module__' : 'api.snark_messages_pb2' - # @@protoc_insertion_point(class_scope:zeth_proto.ExtendedProof) - }) -_sym_db.RegisterMessage(ExtendedProof) - - -# @@protoc_insertion_point(module_scope) diff --git a/zkservice/zkserver/zkserverapp/api/snark_messages_pb2.pyi b/zkservice/zkserver/zkserverapp/api/snark_messages_pb2.pyi deleted file mode 100644 index f444881..0000000 --- a/zkservice/zkserver/zkserverapp/api/snark_messages_pb2.pyi +++ /dev/null @@ -1,86 +0,0 @@ -# @generated by generate_proto_mypy_stubs.py. Do not edit! -import sys -from api.groth16_messages_pb2 import ( - ExtendedProofGROTH16 as api___groth16_messages_pb2___ExtendedProofGROTH16, - VerificationKeyGROTH16 as api___groth16_messages_pb2___VerificationKeyGROTH16, -) - -from api.pghr13_messages_pb2 import ( - ExtendedProofPGHR13 as api___pghr13_messages_pb2___ExtendedProofPGHR13, - VerificationKeyPGHR13 as api___pghr13_messages_pb2___VerificationKeyPGHR13, -) - -from google.protobuf.descriptor import ( - Descriptor as google___protobuf___descriptor___Descriptor, -) - -from google.protobuf.message import ( - Message as google___protobuf___message___Message, -) - -from typing import ( - Optional as typing___Optional, -) - -from typing_extensions import ( - Literal as typing_extensions___Literal, -) - - -builtin___bool = bool -builtin___bytes = bytes -builtin___float = float -builtin___int = int - - -class VerificationKey(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - - @property - def pghr13_verification_key(self) -> api___pghr13_messages_pb2___VerificationKeyPGHR13: ... - - @property - def groth16_verification_key(self) -> api___groth16_messages_pb2___VerificationKeyGROTH16: ... - - def __init__(self, - *, - pghr13_verification_key : typing___Optional[api___pghr13_messages_pb2___VerificationKeyPGHR13] = None, - groth16_verification_key : typing___Optional[api___groth16_messages_pb2___VerificationKeyGROTH16] = None, - ) -> None: ... - @classmethod - def FromString(cls, s: builtin___bytes) -> VerificationKey: ... - def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - if sys.version_info >= (3,): - def HasField(self, field_name: typing_extensions___Literal[u"VK",u"groth16_verification_key",u"pghr13_verification_key"]) -> builtin___bool: ... - def ClearField(self, field_name: typing_extensions___Literal[u"VK",u"groth16_verification_key",u"pghr13_verification_key"]) -> None: ... - else: - def HasField(self, field_name: typing_extensions___Literal[u"VK",b"VK",u"groth16_verification_key",b"groth16_verification_key",u"pghr13_verification_key",b"pghr13_verification_key"]) -> builtin___bool: ... - def ClearField(self, field_name: typing_extensions___Literal[u"VK",b"VK",u"groth16_verification_key",b"groth16_verification_key",u"pghr13_verification_key",b"pghr13_verification_key"]) -> None: ... - def WhichOneof(self, oneof_group: typing_extensions___Literal[u"VK",b"VK"]) -> typing_extensions___Literal["pghr13_verification_key","groth16_verification_key"]: ... - -class ExtendedProof(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - - @property - def pghr13_extended_proof(self) -> api___pghr13_messages_pb2___ExtendedProofPGHR13: ... - - @property - def groth16_extended_proof(self) -> api___groth16_messages_pb2___ExtendedProofGROTH16: ... - - def __init__(self, - *, - pghr13_extended_proof : typing___Optional[api___pghr13_messages_pb2___ExtendedProofPGHR13] = None, - groth16_extended_proof : typing___Optional[api___groth16_messages_pb2___ExtendedProofGROTH16] = None, - ) -> None: ... - @classmethod - def FromString(cls, s: builtin___bytes) -> ExtendedProof: ... - def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - if sys.version_info >= (3,): - def HasField(self, field_name: typing_extensions___Literal[u"EP",u"groth16_extended_proof",u"pghr13_extended_proof"]) -> builtin___bool: ... - def ClearField(self, field_name: typing_extensions___Literal[u"EP",u"groth16_extended_proof",u"pghr13_extended_proof"]) -> None: ... - else: - def HasField(self, field_name: typing_extensions___Literal[u"EP",b"EP",u"groth16_extended_proof",b"groth16_extended_proof",u"pghr13_extended_proof",b"pghr13_extended_proof"]) -> builtin___bool: ... - def ClearField(self, field_name: typing_extensions___Literal[u"EP",b"EP",u"groth16_extended_proof",b"groth16_extended_proof",u"pghr13_extended_proof",b"pghr13_extended_proof"]) -> None: ... - def WhichOneof(self, oneof_group: typing_extensions___Literal[u"EP",b"EP"]) -> typing_extensions___Literal["pghr13_extended_proof","groth16_extended_proof"]: ... diff --git a/zkservice/zkserver/zkserverapp/api/snark_messages_pb2_grpc.py b/zkservice/zkserver/zkserverapp/api/snark_messages_pb2_grpc.py deleted file mode 100644 index a894352..0000000 --- a/zkservice/zkserver/zkserverapp/api/snark_messages_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc - diff --git a/zkservice/zkserver/zkserverapp/api/zeth_messages_pb2.py b/zkservice/zkserver/zkserverapp/api/zeth_messages_pb2.py deleted file mode 100644 index 637b1ee..0000000 --- a/zkservice/zkserver/zkserverapp/api/zeth_messages_pb2.py +++ /dev/null @@ -1,242 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: api/zeth_messages.proto - -import sys -_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - - - -DESCRIPTOR = _descriptor.FileDescriptor( - name='api/zeth_messages.proto', - package='zeth_proto', - syntax='proto3', - serialized_options=None, - serialized_pb=_b('\n\x17\x61pi/zeth_messages.proto\x12\nzeth_proto\"C\n\x08ZethNote\x12\x0b\n\x03\x61pk\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t\x12\x0b\n\x03rho\x18\x03 \x01(\t\x12\x0e\n\x06trap_r\x18\x04 \x01(\t\"\x83\x01\n\x0eJoinsplitInput\x12\x13\n\x0bmerkle_path\x18\x01 \x03(\t\x12\x0f\n\x07\x61\x64\x64ress\x18\x02 \x01(\x03\x12\"\n\x04note\x18\x03 \x01(\x0b\x32\x14.zeth_proto.ZethNote\x12\x14\n\x0cspending_ask\x18\x04 \x01(\t\x12\x11\n\tnullifier\x18\x05 \x01(\t\"\xc0\x01\n\x0bProofInputs\x12\x0f\n\x07mk_root\x18\x01 \x01(\t\x12-\n\tjs_inputs\x18\x02 \x03(\x0b\x32\x1a.zeth_proto.JoinsplitInput\x12(\n\njs_outputs\x18\x03 \x03(\x0b\x32\x14.zeth_proto.ZethNote\x12\x14\n\x0cpub_in_value\x18\x04 \x01(\t\x12\x15\n\rpub_out_value\x18\x05 \x01(\t\x12\r\n\x05h_sig\x18\x06 \x01(\t\x12\x0b\n\x03phi\x18\x07 \x01(\tb\x06proto3') -) - - - - -_ZETHNOTE = _descriptor.Descriptor( - name='ZethNote', - full_name='zeth_proto.ZethNote', - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name='apk', full_name='zeth_proto.ZethNote.apk', index=0, - number=1, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='value', full_name='zeth_proto.ZethNote.value', index=1, - number=2, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='rho', full_name='zeth_proto.ZethNote.rho', index=2, - number=3, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='trap_r', full_name='zeth_proto.ZethNote.trap_r', index=3, - number=4, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - ], - extensions=[ - ], - nested_types=[], - enum_types=[ - ], - serialized_options=None, - is_extendable=False, - syntax='proto3', - extension_ranges=[], - oneofs=[ - ], - serialized_start=39, - serialized_end=106, -) - - -_JOINSPLITINPUT = _descriptor.Descriptor( - name='JoinsplitInput', - full_name='zeth_proto.JoinsplitInput', - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name='merkle_path', full_name='zeth_proto.JoinsplitInput.merkle_path', index=0, - number=1, type=9, cpp_type=9, label=3, - has_default_value=False, default_value=[], - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='address', full_name='zeth_proto.JoinsplitInput.address', index=1, - number=2, type=3, cpp_type=2, label=1, - has_default_value=False, default_value=0, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='note', full_name='zeth_proto.JoinsplitInput.note', index=2, - number=3, type=11, cpp_type=10, label=1, - has_default_value=False, default_value=None, - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='spending_ask', full_name='zeth_proto.JoinsplitInput.spending_ask', index=3, - number=4, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='nullifier', full_name='zeth_proto.JoinsplitInput.nullifier', index=4, - number=5, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - ], - extensions=[ - ], - nested_types=[], - enum_types=[ - ], - serialized_options=None, - is_extendable=False, - syntax='proto3', - extension_ranges=[], - oneofs=[ - ], - serialized_start=109, - serialized_end=240, -) - - -_PROOFINPUTS = _descriptor.Descriptor( - name='ProofInputs', - full_name='zeth_proto.ProofInputs', - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name='mk_root', full_name='zeth_proto.ProofInputs.mk_root', index=0, - number=1, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='js_inputs', full_name='zeth_proto.ProofInputs.js_inputs', index=1, - number=2, type=11, cpp_type=10, label=3, - has_default_value=False, default_value=[], - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='js_outputs', full_name='zeth_proto.ProofInputs.js_outputs', index=2, - number=3, type=11, cpp_type=10, label=3, - has_default_value=False, default_value=[], - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='pub_in_value', full_name='zeth_proto.ProofInputs.pub_in_value', index=3, - number=4, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='pub_out_value', full_name='zeth_proto.ProofInputs.pub_out_value', index=4, - number=5, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='h_sig', full_name='zeth_proto.ProofInputs.h_sig', index=5, - number=6, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='phi', full_name='zeth_proto.ProofInputs.phi', index=6, - number=7, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - serialized_options=None, file=DESCRIPTOR), - ], - extensions=[ - ], - nested_types=[], - enum_types=[ - ], - serialized_options=None, - is_extendable=False, - syntax='proto3', - extension_ranges=[], - oneofs=[ - ], - serialized_start=243, - serialized_end=435, -) - -_JOINSPLITINPUT.fields_by_name['note'].message_type = _ZETHNOTE -_PROOFINPUTS.fields_by_name['js_inputs'].message_type = _JOINSPLITINPUT -_PROOFINPUTS.fields_by_name['js_outputs'].message_type = _ZETHNOTE -DESCRIPTOR.message_types_by_name['ZethNote'] = _ZETHNOTE -DESCRIPTOR.message_types_by_name['JoinsplitInput'] = _JOINSPLITINPUT -DESCRIPTOR.message_types_by_name['ProofInputs'] = _PROOFINPUTS -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -ZethNote = _reflection.GeneratedProtocolMessageType('ZethNote', (_message.Message,), { - 'DESCRIPTOR' : _ZETHNOTE, - '__module__' : 'api.zeth_messages_pb2' - # @@protoc_insertion_point(class_scope:zeth_proto.ZethNote) - }) -_sym_db.RegisterMessage(ZethNote) - -JoinsplitInput = _reflection.GeneratedProtocolMessageType('JoinsplitInput', (_message.Message,), { - 'DESCRIPTOR' : _JOINSPLITINPUT, - '__module__' : 'api.zeth_messages_pb2' - # @@protoc_insertion_point(class_scope:zeth_proto.JoinsplitInput) - }) -_sym_db.RegisterMessage(JoinsplitInput) - -ProofInputs = _reflection.GeneratedProtocolMessageType('ProofInputs', (_message.Message,), { - 'DESCRIPTOR' : _PROOFINPUTS, - '__module__' : 'api.zeth_messages_pb2' - # @@protoc_insertion_point(class_scope:zeth_proto.ProofInputs) - }) -_sym_db.RegisterMessage(ProofInputs) - - -# @@protoc_insertion_point(module_scope) diff --git a/zkservice/zkserver/zkserverapp/api/zeth_messages_pb2.pyi b/zkservice/zkserver/zkserverapp/api/zeth_messages_pb2.pyi deleted file mode 100644 index bf84520..0000000 --- a/zkservice/zkserver/zkserverapp/api/zeth_messages_pb2.pyi +++ /dev/null @@ -1,116 +0,0 @@ -# @generated by generate_proto_mypy_stubs.py. Do not edit! -import sys -from google.protobuf.descriptor import ( - Descriptor as google___protobuf___descriptor___Descriptor, -) - -from google.protobuf.internal.containers import ( - RepeatedCompositeFieldContainer as google___protobuf___internal___containers___RepeatedCompositeFieldContainer, - RepeatedScalarFieldContainer as google___protobuf___internal___containers___RepeatedScalarFieldContainer, -) - -from google.protobuf.message import ( - Message as google___protobuf___message___Message, -) - -from typing import ( - Iterable as typing___Iterable, - Optional as typing___Optional, - Text as typing___Text, -) - -from typing_extensions import ( - Literal as typing_extensions___Literal, -) - - -builtin___bool = bool -builtin___bytes = bytes -builtin___float = float -builtin___int = int - - -class ZethNote(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - apk = ... # type: typing___Text - value = ... # type: typing___Text - rho = ... # type: typing___Text - trap_r = ... # type: typing___Text - - def __init__(self, - *, - apk : typing___Optional[typing___Text] = None, - value : typing___Optional[typing___Text] = None, - rho : typing___Optional[typing___Text] = None, - trap_r : typing___Optional[typing___Text] = None, - ) -> None: ... - @classmethod - def FromString(cls, s: builtin___bytes) -> ZethNote: ... - def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - if sys.version_info >= (3,): - def ClearField(self, field_name: typing_extensions___Literal[u"apk",u"rho",u"trap_r",u"value"]) -> None: ... - else: - def ClearField(self, field_name: typing_extensions___Literal[u"apk",b"apk",u"rho",b"rho",u"trap_r",b"trap_r",u"value",b"value"]) -> None: ... - -class JoinsplitInput(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - merkle_path = ... # type: google___protobuf___internal___containers___RepeatedScalarFieldContainer[typing___Text] - address = ... # type: builtin___int - spending_ask = ... # type: typing___Text - nullifier = ... # type: typing___Text - - @property - def note(self) -> ZethNote: ... - - def __init__(self, - *, - merkle_path : typing___Optional[typing___Iterable[typing___Text]] = None, - address : typing___Optional[builtin___int] = None, - note : typing___Optional[ZethNote] = None, - spending_ask : typing___Optional[typing___Text] = None, - nullifier : typing___Optional[typing___Text] = None, - ) -> None: ... - @classmethod - def FromString(cls, s: builtin___bytes) -> JoinsplitInput: ... - def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - if sys.version_info >= (3,): - def HasField(self, field_name: typing_extensions___Literal[u"note"]) -> builtin___bool: ... - def ClearField(self, field_name: typing_extensions___Literal[u"address",u"merkle_path",u"note",u"nullifier",u"spending_ask"]) -> None: ... - else: - def HasField(self, field_name: typing_extensions___Literal[u"note",b"note"]) -> builtin___bool: ... - def ClearField(self, field_name: typing_extensions___Literal[u"address",b"address",u"merkle_path",b"merkle_path",u"note",b"note",u"nullifier",b"nullifier",u"spending_ask",b"spending_ask"]) -> None: ... - -class ProofInputs(google___protobuf___message___Message): - DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... - mk_root = ... # type: typing___Text - pub_in_value = ... # type: typing___Text - pub_out_value = ... # type: typing___Text - h_sig = ... # type: typing___Text - phi = ... # type: typing___Text - - @property - def js_inputs(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[JoinsplitInput]: ... - - @property - def js_outputs(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[ZethNote]: ... - - def __init__(self, - *, - mk_root : typing___Optional[typing___Text] = None, - js_inputs : typing___Optional[typing___Iterable[JoinsplitInput]] = None, - js_outputs : typing___Optional[typing___Iterable[ZethNote]] = None, - pub_in_value : typing___Optional[typing___Text] = None, - pub_out_value : typing___Optional[typing___Text] = None, - h_sig : typing___Optional[typing___Text] = None, - phi : typing___Optional[typing___Text] = None, - ) -> None: ... - @classmethod - def FromString(cls, s: builtin___bytes) -> ProofInputs: ... - def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ... - if sys.version_info >= (3,): - def ClearField(self, field_name: typing_extensions___Literal[u"h_sig",u"js_inputs",u"js_outputs",u"mk_root",u"phi",u"pub_in_value",u"pub_out_value"]) -> None: ... - else: - def ClearField(self, field_name: typing_extensions___Literal[u"h_sig",b"h_sig",u"js_inputs",b"js_inputs",u"js_outputs",b"js_outputs",u"mk_root",b"mk_root",u"phi",b"phi",u"pub_in_value",b"pub_in_value",u"pub_out_value",b"pub_out_value"]) -> None: ... diff --git a/zkservice/zkserver/zkserverapp/api/zeth_messages_pb2_grpc.py b/zkservice/zkserver/zkserverapp/api/zeth_messages_pb2_grpc.py deleted file mode 100644 index a894352..0000000 --- a/zkservice/zkserver/zkserverapp/api/zeth_messages_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc - diff --git a/zkservice/zkserver/zkserverapp/apps.py b/zkservice/zkserver/zkserverapp/apps.py deleted file mode 100644 index f8e804b..0000000 --- a/zkservice/zkserver/zkserverapp/apps.py +++ /dev/null @@ -1,5 +0,0 @@ -from django.apps import AppConfig - - -class ZkserverappConfig(AppConfig): - name = 'zkserverapp' diff --git a/zkservice/zkserver/zkserverapp/commands/__init__.py b/zkservice/zkserver/zkserverapp/commands/__init__.py deleted file mode 100644 index b6e016d..0000000 --- a/zkservice/zkserver/zkserverapp/commands/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ diff --git a/zkservice/zkserver/zkserverapp/commands/constants.py b/zkservice/zkserver/zkserverapp/commands/constants.py deleted file mode 100644 index e6b0c12..0000000 --- a/zkservice/zkserver/zkserverapp/commands/constants.py +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - - -""" -Constants and defaults specific to the CLI interface. -""" - -FISCO_RPC_ENDPOINT_DEFAULT = "http://119.23.46.126:8545" -PROVER_SERVER_ENDPOINT_DEFAULT = "139.9.222.236:50051" - -FISCO_ADDRESS_FILE = "fisco_account.keystore" -ADDRESS_FILE_DEFAULT = "zeth-address.json" -#INSTANCE_FILE_DEFAULT = "zeth-instance.json" -#ETH_ADDRESS_DEFAULT = "eth-address" - -WALLET_DIR_DEFAULT = "wallet" -WALLET_USERNAME = "zbac" -USER_DIR = "user" diff --git a/zkservice/zkserver/zkserverapp/commands/event_sync.py b/zkservice/zkserver/zkserverapp/commands/event_sync.py deleted file mode 100644 index 6ca3303..0000000 --- a/zkservice/zkserver/zkserverapp/commands/event_sync.py +++ /dev/null @@ -1,139 +0,0 @@ -import sys -from python_web3.client.bcosclient import BcosClient -from python_web3.client.datatype_parser import DatatypeParser -from python_web3.client.contractnote import ContractNote -import json -import time -from python_web3.client.channel_push_dispatcher import ChannelPushHandler -from python_web3.client.event_callback import BcosEventCallback -from python_web3.client.event_callback import EventCallbackHandler -from click import command, argument, option, pass_context, ClickException, Context -from zeth.contracts import _event_args_to_mix_result -import os -from commands.constants import WALLET_USERNAME, FISCO_ADDRESS_FILE, USER_DIR, ADDRESS_FILE_DEFAULT, WALLET_DIR_DEFAULT -from click import command, argument, option, pass_context, ClickException, Context -from zeth.wallet import Wallet, ZethNoteDescription -from commands.utils import load_zeth_address -from typing import List -''' -def usage(): - usagetext = '\nUsage:\nparams: contractname address event_name indexed\n' \ - '\t1. contractname :\t合约的文件名,不需要带sol后缀,默认在当前目录的contracts目录下\n' \ - '\t2. address :\t十六进制的合约地址,或者可以为:last,表示采用bin/contract.ini里的记录\n' \ - '\t3. event_name :\t可选,如不设置监听所有事件 \n' \ - '\t4. indexed :\t可选,根据event定义里的indexed字段,作为过滤条件)\n\n' - usagetext = usagetext + "\teg: for contract sample [contracts/HelloEvent.sol], use cmdline:\n\n" - - usagetext = usagetext + "\tpython demo_event_callback.py HelloEvent last \n" - usagetext = usagetext + "\t--listen all event at all indexed : \n\n" - - usagetext = usagetext + "\tpython demo_event_callback.py HelloEvent last on_set \n" - usagetext = usagetext + "\t--listen event on_set(string newname) (no indexed): \n\n" - - usagetext = usagetext + \ - "\tpython demo_event_callback.py HelloEvent last on_number 5\n" - usagetext = usagetext + \ - "\t--listen event on_number(string name,int indexed age), age ONLY 5 : \n" - usagetext = usagetext + "\n...(and other events)" - print(usagetext) -''' - -class LogMixEvent(object): - def __init__( - self, - root: bytes, - nullifiers: bytes(2), - commitments: bytes(2), - ciphertexts: bytes(2)): - self.root = root - self.nullifiers = nullifiers - self.commitments = commitments - self.ciphertexts = ciphertexts - -def make_wallet() -> List[Wallet]: - ''' - Return all the wallet in local server - ''' - wallet_list = [] - for username in os.listdir(USER_DIR): - wallet_dir = "{}/{}/{}".format(USER_DIR, username, WALLET_DIR_DEFAULT) - zeth_address = load_zeth_address(username) - wallet_list.append(Wallet(None, username, wallet_dir, zeth_address.addr_sk)) - return wallet_list - -class EventCallbackImpl(EventCallbackHandler): - """sample event push handler for application level, - user can make a class base on "ChannelPushHandler" ,implement the on_push interface - handle the message from nodes,message in ChannelPack type #see client/channelpack.py - EVENT_LOG_PUSH type is 0x1002 - message in pack.data decode by utf-8 - EVENT_LOG format see https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/sdk/java_sdk.html#id19 - """ - abiparser: DatatypeParser = None - - def on_event(self, eventdata): - logresult = self.abiparser.parse_event_logs(eventdata["logs"]) - print("--------------------EventCallbackImpl--------------------\n") - logMix = logresult[0]['eventdata'] - logMixEvent = LogMixEvent(logMix[0],logMix[1], logMix[2], logMix[3]) - mix_result = _event_args_to_mix_result(logMixEvent) - new_merkle_root = mix_result.new_merkle_root - print("new_merkle_root in log: ", new_merkle_root) - for wallet in make_wallet(): - # check merkel root - if new_merkle_root==wallet.merkle_tree.get_root(): - return - # received_notes - wallet.receive_notes(mix_result.output_events) - spent_commits = wallet.mark_nullifiers_used(mix_result.nullifiers) - for commit in spent_commits: - print(f"{wallet.username} spent commits: {commit}") - wallet.update_and_save_state() - update_merkle_root = wallet.merkle_tree.get_root() - print(f"The update_merkle_root in wallet of {wallet.username} is {update_merkle_root}") - - - -def event_sync(mixer_addr: str): - - indexed_value = None - try: - bcos_event = BcosEventCallback() - bcos_event.setclient(BcosClient()) - print(bcos_event.client.getinfo()) - ''' - print("usage input {},{},{},{}".format(contractname, address, event_name, indexed_value)) - if address == "last": - cn = ContractNote() - address = cn.get_last(contractname) - print("hex address :", address) - ''' - abifile = "contract/Groth16Mixer.abi" - abiparser = DatatypeParser(abifile) - eventcallback = EventCallbackImpl() - eventcallback.abiparser = abiparser - - result = bcos_event.register_eventlog_filter( - eventcallback, abiparser, [mixer_addr], "LogMix", indexed_value) - #result = bcos_event.register_eventlog_filter(eventcallback02,abiparser, [address], "on_number") - - print( - "after register LogMix,result:{},all:{}".format( - result['result'], result)) - - while True: - print("waiting event...") - time.sleep(10) - except Exception as e: - print("Exception!") - import traceback - traceback.print_exc() - finally: - print("event callback finished!") - if bcos_event.client is not None: - bcos_event.client.finish() - sys.exit(-1) - - -if __name__ == "__main__": - event_sync() diff --git a/zkservice/zkserver/zkserverapp/commands/py.typed b/zkservice/zkserver/zkserverapp/commands/py.typed deleted file mode 100644 index a0c5d77..0000000 --- a/zkservice/zkserver/zkserverapp/commands/py.typed +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -# Empty file, required for mypy. \ No newline at end of file diff --git a/zkservice/zkserver/zkserverapp/commands/utils.py b/zkservice/zkserver/zkserverapp/commands/utils.py deleted file mode 100644 index 0573823..0000000 --- a/zkservice/zkserver/zkserverapp/commands/utils.py +++ /dev/null @@ -1,320 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -from __future__ import annotations -from commands.constants import FISCO_ADDRESS_FILE, USER_DIR, ADDRESS_FILE_DEFAULT, WALLET_DIR_DEFAULT -from zeth.zeth_address import ZethAddressPub, ZethAddressPriv, ZethAddress -from zeth.contracts import \ - get_mix_results -from zeth.mixer_client import MixerClient -from zeth.utils import \ - short_commitment, EtherValue, get_zeth_dir, from_zeth_units -from zeth.wallet import ZethNoteDescription, Wallet -from click import ClickException -import json -from os.path import exists, join -from typing import Dict, Tuple, Optional, Callable, Any -#from web3 import Web3 # type: ignore -from contract.Groth16Mixer import Groth16Mixer -from contract.ERC20Mintable import ERC20Mintable -from python_web3.eth_account.account import Account -from python_web3.client.bcoskeypair import BcosKeyPair #todo - - -class ClientConfig: - """ - Context for users of these client tools - """ - def __init__( - self, - eth_rpc_endpoint: str, - prover_server_endpoint: str, - #instance_file: str, - address_file: str, - wallet_dir: str): - self.eth_rpc_endpoint = eth_rpc_endpoint - self.prover_server_endpoint = prover_server_endpoint - #self.instance_file = instance_file - self.address_file = address_file - self.wallet_dir = wallet_dir - -''' -def open_web3_from_ctx(ctx: ClientConfig) -> Any: - return open_web3(ctx.eth_rpc_endpoint) -''' -''' -class MixerDescription: - """ - Holds an InstanceDescription for the mixer contract, and optionally an - InstanceDescription for the token contract. - """ - def __init__( - self, - mixer: InstanceDescription, - token: Optional[InstanceDescription]): - self.mixer = mixer - self.token = token - - def to_json(self) -> str: - json_dict = { - "mixer": self.mixer.to_json_dict() - } - if self.token: - json_dict["token"] = self.token.to_json_dict() - return json.dumps(json_dict) - - @staticmethod - def from_json(json_str: str) -> MixerDescription: - json_dict = json.loads(json_str) - mixer = InstanceDescription.from_json_dict(json_dict["mixer"]) - token_dict = json_dict.get("token", None) - token = InstanceDescription.from_json_dict(token_dict) \ - if token_dict else None - return MixerDescription(mixer, token) - - -def get_erc20_abi() -> Dict[str, Any]: - zeth_dir = get_zeth_dir() - openzeppelin_dir = join( - zeth_dir, "zeth_contracts", "node_modules", "openzeppelin-solidity") - ierc20_path = join( - openzeppelin_dir, "contracts", "token", "ERC20", "IERC20.sol") - compiled_sol = compile_files([ierc20_path]) - erc20_interface = compiled_sol[ierc20_path + ":IERC20"] - return erc20_interface["abi"] - - -def get_erc20_instance_description(token_address: str) -> InstanceDescription: - return InstanceDescription(token_address, get_erc20_abi()) - - -def write_mixer_description( - mixer_desc_file: str, - mixer_desc: MixerDescription) -> None: - """ - Write the mixer (and token) instance information - """ - with open(mixer_desc_file, "w") as instance_f: - instance_f.write(mixer_desc.to_json()) - - -def load_mixer_description(mixer_description_file: str) -> MixerDescription: - """ - Return mixer and token (if present) contract instances - """ - with open(mixer_description_file, "r") as desc_f: - return MixerDescription.from_json(desc_f.read()) - - -def load_mixer_description_from_ctx(ctx: ClientConfig) -> MixerDescription: - return load_mixer_description(ctx.instance_file) -''' - -def get_zeth_address_file(username: str) -> str: - addr_file = "{}/{}/{}".format(USER_DIR, username, ADDRESS_FILE_DEFAULT) - return addr_file - - -def load_zeth_address_public(username: str) -> ZethAddressPub: - """ - Load a ZethAddressPub from a key file. - """ - secret_key_file = get_zeth_address_file(username) - pub_addr_file = pub_address_file(secret_key_file) - with open(pub_addr_file, "r") as pub_addr_f: - return ZethAddressPub.parse(pub_addr_f.read()) - - -def write_zeth_address_public( - pub_addr: ZethAddressPub, pub_addr_file: str) -> None: - """ - Write a ZethAddressPub to a file - """ - with open(pub_addr_file, "w") as pub_addr_f: - pub_addr_f.write(str(pub_addr)) - - -def load_zeth_address_secret(username: str) -> ZethAddressPriv: - """ - Read ZethAddressPriv - """ - addr_file = get_zeth_address_file(username) - with open(addr_file, "r") as addr_f: - return ZethAddressPriv.from_json(addr_f.read()) - - -def write_zeth_address_secret( - secret_addr: ZethAddressPriv, addr_file: str) -> None: - """ - Write ZethAddressPriv to file - """ - with open(addr_file, "w") as addr_f: - addr_f.write(secret_addr.to_json()) - - -def load_zeth_address(username: str) -> ZethAddress: - """ - Load a ZethAddress secret from a file, and the associated public address, - and return as a ZethAddress. - """ - return ZethAddress.from_secret_public( - load_zeth_address_secret(username), - load_zeth_address_public(username)) - - -def open_wallet( - mixer_instance: Any, - js_secret: ZethAddressPriv, - username: str - ) -> Wallet: - """ - Load a wallet using a secret key. - """ - wallet_dir = "{}/{}/{}".format(USER_DIR, username, WALLET_DIR_DEFAULT) - return Wallet(mixer_instance, username, wallet_dir, js_secret) - - -def do_sync( - wallet: Wallet, - receipt: Any, - callback: Optional[Callable[[ZethNoteDescription], None]] = None) -> int: - """ - Implementation of sync, reused by several commands. Returns the - block_number synced to. Also updates and saves the MerkleTree. - """ - def _do_sync() -> int: - #wallet_next_block = wallet.get_next_block() - #chain_block_number: int = get_block_number(web3) - - #if chain_block_number >= wallet_next_block: - #new_merkle_root: Optional[bytes] = None - - #print(f"SYNCHING blocks ({wallet_next_block} - {chain_block_number})") - mixer_instance = wallet.mixer_instance - mix_result = get_mix_results(mixer_instance, receipt) - new_merkle_root = mix_result.new_merkle_root - for note_desc in wallet.receive_notes(mix_result.output_events): - if callback: - callback(note_desc) - - spent_commits = wallet.mark_nullifiers_used(mix_result.nullifiers) - for commit in spent_commits: - print(f" SPENT: {commit}") - - wallet.update_and_save_state() - - # Check merkle root and save the updated tree - if new_merkle_root: - our_merkle_root = wallet.merkle_tree.get_root() - assert new_merkle_root == our_merkle_root - - return new_merkle_root - - # Do a sync upfront (it would be a waste of time to wait for a tx before - # syncing, as it can take time to traverse all blocks). Then wait for a tx - # if requested, and sync again. - ''' - if wait_tx: - _do_sync() - tx_receipt = web3.eth.waitForTransactionReceipt(wait_tx, 10000) - gas_used = tx_receipt.gasUsed - status = tx_receipt.status - print(f"{wait_tx[0:8]}: gasUsed={gas_used}, status={status}") - ''' - return _do_sync() - - -def pub_address_file(addr_file: str) -> str: - """ - The name of a public address file, given the secret address file. - """ - return addr_file + ".pub" - - -def find_pub_address_file(base_file: str) -> str: - """ - Given a file name, which could point to a private or public key file, guess - at the name of the public key file. - """ - pub_addr_file = pub_address_file(base_file) - if exists(pub_addr_file): - return pub_addr_file - if exists(base_file): - return base_file - - raise ClickException(f"No public key file {pub_addr_file} or {base_file}") - -''' -def create_mixer_client(ctx: ClientConfig) -> MixerClient: - """ - Create a MixerClient for an existing deployment. - """ - web3 = open_web3_from_ctx(ctx) - mixer_desc = load_mixer_description_from_ctx(ctx) - mixer_instance = mixer_desc.mixer.instantiate(web3) - return MixerClient.open(web3, ctx.prover_server_endpoint, mixer_instance) -''' - -def create_zeth_client_and_mixer_desc( - prover_server_endpoint: str, mixer_addr: str, username: str, password: str) -> Tuple[MixerClient, MixerDescription]: - """ - Create a MixerClient and MixerDescription object, for an existing deployment. - """ - #web3 = open_web3_from_ctx(ctx) - #mixer_desc = load_mixer_description_from_ctx(ctx) - mixer_instance = Groth16Mixer(mixer_addr) - keystore_file = "{}/{}/{}".format(USER_DIR, username, FISCO_ADDRESS_FILE) - if exists(keystore_file) is False: - raise ClickException(f"invalid output spec: {keystore_file}") - with open(keystore_file, "r") as dump_f: - keytext = json.load(dump_f) - privkey = Account.decrypt(keytext, password) - mixer_instance.client.ecdsa_account = Account.from_key(privkey) - keypair = BcosKeyPair() - keypair.private_key = mixer_instance.client.ecdsa_account.privateKey - keypair.public_key = mixer_instance.client.ecdsa_account.publickey - keypair.address = mixer_instance.client.ecdsa_account.address - mixer_instance.client.keypair = keypair - zeth_client = MixerClient.open( - prover_server_endpoint, mixer_instance) - return (zeth_client) - - -def zeth_note_short(note_desc: ZethNoteDescription) -> str: - """ - Generate a short human-readable description of a commitment. - """ - value = from_zeth_units(int(note_desc.note.value, 16)).ether() - cm = short_commitment(note_desc.commitment) - return f"{cm}: value={value} ETH, addr={note_desc.address}" - - -def zeth_note_short_print(note_desc: ZethNoteDescription) -> None: - print(f" NEW NOTE: {zeth_note_short(note_desc)}") - - -def parse_output(output_str: str) -> Tuple[ZethAddressPub, EtherValue]: - """ - Parse a string of the form "," to an output - specification. - """ - parts = output_str.split(",") - if len(parts) != 2: - raise ClickException(f"invalid output spec: {output_str}") - return (ZethAddressPub.parse(parts[0]), EtherValue(parts[1])) - -''' -def load_eth_address(eth_addr: Optional[str]) -> str: - """ - Given an --eth-addr command line param, either parse the address, load from - the file, or use a default file name. - """ - eth_addr = eth_addr or ETH_ADDRESS_DEFAULT - if eth_addr.startswith("0x"): - return Web3.toChecksumAddress(eth_addr) - if exists(eth_addr): - with open(eth_addr, "r") as eth_addr_f: - return Web3.toChecksumAddress(eth_addr_f.read().rstrip()) - raise ClickException(f"could find file or parse eth address: {eth_addr}") -''' \ No newline at end of file diff --git a/zkservice/zkserver/zkserverapp/commands/zeth_deploy.py b/zkservice/zkserver/zkserverapp/commands/zeth_deploy.py deleted file mode 100644 index 6250964..0000000 --- a/zkservice/zkserver/zkserverapp/commands/zeth_deploy.py +++ /dev/null @@ -1,54 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ -''' -from commands.utils import \ - open_web3_from_ctx, get_erc20_instance_description, load_eth_address, \ - write_mixer_description, MixerDescription -from zeth.mixer_client import MixerClient -from zeth.utils import EtherValue -''' -from click import Context, command, option, pass_context -from typing import Optional -import sys -sys.path.append('../') -from python_web3.eth_utils import to_checksum_address -from python_web3.client.bcosclient import BcosClient -from contract.Groth16Mixer import Groth16Mixer -from zeth.prover_client import ProverClient -from zeth.mixer_client import write_verification_key -from zeth.zksnark import get_zksnark_provider -from commands.constants import PROVER_SERVER_ENDPOINT_DEFAULT - - -def deploy( - token_address: Optional[str] - ) -> None: - """ - Deploy the zeth contracts and record the instantiation details. - """ - zksnark = get_zksnark_provider("GROTH16") - prover_client = ProverClient(PROVER_SERVER_ENDPOINT_DEFAULT) - vk_obj = prover_client.get_verification_key() - vk_json = zksnark.parse_verification_key(vk_obj) - #print("VK.json: ", vk_json) - - print("Received VK, writing verification key...") - write_verification_key(vk_json) - verification_key_params = zksnark.verification_key_parameters(vk_json) - constructArgs = [5, to_checksum_address(token_address), verification_key_params['Alpha'], verification_key_params['Beta1'], verification_key_params['Beta2'], verification_key_params['Delta1'], verification_key_params['Delta2'], verification_key_params['ABC_coords']] - - si = Groth16Mixer("") - abi5 = [{'inputs': [{'internalType': 'uint256', 'name': 'mk_depth', 'type': 'uint256'}, {'internalType': 'address', 'name': 'token', 'type': 'address'}, {'internalType': 'uint256[2]', 'name': 'Alpha', 'type': 'uint256[2]'}, {'internalType': 'uint256[2]', 'name': 'Beta1', 'type': 'uint256[2]'}, {'internalType': 'uint256[2]', 'name': 'Beta2', 'type': 'uint256[2]'}, {'internalType': 'uint256[2]', 'name': 'Delta1', 'type': 'uint256[2]'}, {'internalType': 'uint256[2]', 'name': 'Delta2', 'type': 'uint256[2]'}, {'internalType': 'uint256[]', 'name': 'ABC_coords', 'type': 'uint256[]'}], 'payable': False, 'stateMutability': 'nonpayable', 'type': 'constructor'}, {'anonymous': False, 'inputs': [{'indexed': False, 'internalType': 'string', 'name': 'message', 'type': 'string'}], 'name': 'LogDebug', 'type': 'event'}, {'anonymous': False, 'inputs': [{'indexed': False, 'internalType': 'bytes32', 'name': 'message', 'type': 'bytes32'}], 'name': 'LogDebug', 'type': 'event'}, {'anonymous': False, 'inputs': [{'indexed': False, 'internalType': 'bytes32', 'name': 'root', 'type': 'bytes32'}, {'indexed': False, 'internalType': 'bytes32[2]', 'name': 'nullifiers', 'type': 'bytes32[2]'}, {'indexed': False, 'internalType': 'bytes32[2]', 'name': 'commitments', 'type': 'bytes32[2]'}, {'indexed': False, 'internalType': 'bytes[2]', 'name': 'ciphertexts', 'type': 'bytes[2]'}], 'name': 'LogMix', 'type': 'event'}, {'constant': True, 'inputs': [{'internalType': 'uint256[9]', 'name': 'primary_inputs', 'type': 'uint256[9]'}], 'name': 'assemble_hsig', 'outputs': [{'internalType': 'bytes32', 'name': 'hsig', 'type': 'bytes32'}], 'payable': False, 'stateMutability': 'pure', 'type': 'function'}, {'constant': True, 'inputs': [{'internalType': 'uint256', 'name': 'index', 'type': 'uint256'}, {'internalType': 'uint256[9]', 'name': 'primary_inputs', 'type': 'uint256[9]'}], 'name': 'assemble_nullifier', 'outputs': [{'internalType': 'bytes32', 'name': 'nf', 'type': 'bytes32'}], 'payable': False, 'stateMutability': 'pure', 'type': 'function'}, {'constant': True, 'inputs': [{'internalType': 'uint256[9]', 'name': 'primary_inputs', 'type': 'uint256[9]'}], 'name': 'assemble_public_values', 'outputs': [{'internalType': 'uint256', 'name': 'vpub_in', 'type': 'uint256'}, {'internalType': 'uint256', 'name': 'vpub_out', 'type': 'uint256'}], 'payable': False, 'stateMutability': 'pure', 'type': 'function'}, {'constant': True, 'inputs': [], 'name': 'get_constants', 'outputs': [{'internalType': 'uint256', 'name': 'js_in', 'type': 'uint256'}, {'internalType': 'uint256', 'name': 'js_out', 'type': 'uint256'}, {'internalType': 'uint256', 'name': 'num_inputs', 'type': 'uint256'}], 'payable': False, 'stateMutability': 'pure', 'type': 'function'}, {'constant': False, 'inputs': [{'internalType': 'bytes32', 'name': 'commitment', 'type': 'bytes32'}], 'name': 'insert', 'outputs': [], 'payable': False, 'stateMutability': 'nonpayable', 'type': 'function'}, {'constant': False, 'inputs': [{'internalType': 'uint256[2]', 'name': 'a', 'type': 'uint256[2]'}, {'internalType': 'uint256[4]', 'name': 'b', 'type': 'uint256[4]'}, {'internalType': 'uint256[2]', 'name': 'c', 'type': 'uint256[2]'}, {'internalType': 'uint256[4]', 'name': 'vk', 'type': 'uint256[4]'}, {'internalType': 'uint256', 'name': 'sigma', 'type': 'uint256'}, {'internalType': 'uint256[9]', 'name': 'input', 'type': 'uint256[9]'}, {'internalType': 'bytes[2]', 'name': 'ciphertexts', 'type': 'bytes[2]'}], 'name': 'mix', 'outputs': [], 'payable': True, 'stateMutability': 'payable', 'type': 'function'}, {'constant': True, 'inputs': [], 'name': 'token', 'outputs': [{'internalType': 'address', 'name': '', 'type': 'address'}], 'payable': False, 'stateMutability': 'view', 'type': 'function'}, {'constant': True, 'inputs': [{'internalType': 'address', 'name': 'from', 'type': 'address'}, {'internalType': 'uint256', 'name': 'value', 'type': 'uint256'}, {'internalType': 'bytes', 'name': 'data', 'type': 'bytes'}], 'name': 'tokenFallback', 'outputs': [], 'payable': False, 'stateMutability': 'pure', 'type': 'function'}] - bin5 = "60806040523480156200001157600080fd5b50604051620037d3380380620037d3833981810160405262000037919081019062000685565b878781806005811462000081576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016200007890620008ba565b60405180910390fd5b50620000926200040360201b60201c565b506000806000603f8110620000a357fe5b0154905060016040600083815260200190815260200160002060006101000a81548160ff02191690831515021790555081604260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555061010060fd106200015c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401620001539062000876565b60405180910390fd5b60fd6002800260010160fd610100030260406002020110620001b5576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401620001ac9062000898565b60405180910390fd5b505050604051806040016040528087600060028110620001d157fe5b6020020151815260200187600160028110620001e957fe5b6020020151815250604360000160008201518160000155602082015181600101559050506040518060800160405280866000600281106200022657fe5b60200201518152602001866001600281106200023e57fe5b60200201518152602001856000600281106200025657fe5b60200201518152602001856001600281106200026e57fe5b6020020151815250604360020160008201518160000155602082015181600101556040820151816002015560608201518160030155905050604051806080016040528084600060028110620002bf57fe5b6020020151815260200184600160028110620002d757fe5b6020020151815260200183600060028110620002ef57fe5b60200201518152602001836001600281106200030757fe5b602002015181525060436006016000820151816000015560208201518160010155604082015181600201556060820151816003015590505060008090505b60028251816200035157fe5b046043600a018054905014620003f4576043600a0160405180604001604052808484815181106200037e57fe5b602002602001015181526020018460018501815181106200039b57fe5b602002602001015181525090806001815401808255809150509060018203906000526020600020906002020160009091929091909150600082015181600001556020820151816001015550505060028101905062000345565b505050505050505050620009d9565b60008060001b90508060006002600560020a60020203603f81106200042457fe5b018190555060006002600560020a816200043a57fe5b0490505b600081111562000495576200045f82836200049960201b620016c61760201c565b9150600060028260020203905082600082603f81106200047b57fe5b0181905550600282816200048b57fe5b049150506200043e565b5050565b60007fdec937b7fa8db3de380427a8cc947bfab68514522c3439cfa2e99655098368146000527f30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f00000018284828282088381820984858383098683840909925060005b605a8112156200053457602060002080600052868688838808089350868485099250868488858a8788090909945050600181019050620004f9565b508484868a8888880808089550505050505092915050565b6000815190506200055d81620009a5565b92915050565b600082601f8301126200057557600080fd5b60026200058c62000586826200090a565b620008dc565b91508183856020840282011115620005a357600080fd5b60005b83811015620005d75781620005bc88826200066e565b845260208401935060208301925050600181019050620005a6565b5050505092915050565b600082601f830112620005f357600080fd5b81516200060a62000604826200092d565b620008dc565b915081818352602084019350602081019050838560208402820111156200063057600080fd5b60005b838110156200066457816200064988826200066e565b84526020840193506020830192505060018101905062000633565b5050505092915050565b6000815190506200067f81620009bf565b92915050565b6000806000806000806000806101a0898b031215620006a357600080fd5b6000620006b38b828c016200066e565b9850506020620006c68b828c016200054c565b9750506040620006d98b828c0162000563565b9650506080620006ec8b828c0162000563565b95505060c0620006ff8b828c0162000563565b945050610100620007138b828c0162000563565b935050610140620007278b828c0162000563565b92505061018089015167ffffffffffffffff8111156200074657600080fd5b620007548b828c01620005e1565b9150509295985092959890939650565b600062000773602d8362000956565b91507f41206861736820646967657374206669747320696e20612073696e676c65206660008301527f69656c6420656c656d656e742e000000000000000000000000000000000000006020830152604082019050919050565b6000620007db602b8362000956565b91507f546f6f206d616e7920696e70757420616e64206f7574707574206e6f7465732060008301527f636f6e736964657265642e0000000000000000000000000000000000000000006020830152604082019050919050565b600062000843601f8362000956565b91507f496e76616c696420646570746820696e20426173654d65726b6c6554726565006000830152602082019050919050565b60006020820190508181036000830152620008918162000764565b9050919050565b60006020820190508181036000830152620008b381620007cc565b9050919050565b60006020820190508181036000830152620008d58162000834565b9050919050565b6000604051905081810181811067ffffffffffffffff821117156200090057600080fd5b8060405250919050565b600067ffffffffffffffff8211156200092257600080fd5b602082029050919050565b600067ffffffffffffffff8211156200094557600080fd5b602082029050602081019050919050565b600082825260208201905092915050565b600062000974826200097b565b9050919050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b6000819050919050565b620009b08162000967565b8114620009bc57600080fd5b50565b620009ca816200099b565b8114620009d657600080fd5b50565b612dea80620009e96000396000f3fe60806040526004361061007b5760003560e01c806397e004891161004e57806397e0048914610161578063c0ee0b8a1461017d578063f9eb943f146101a6578063fc0c546a146101d35761007b565b806305ceb93c146100805780631f40927c146100bd5780632d287e43146100fb578063354d06fd14610124575b600080fd5b34801561008c57600080fd5b506100a760048036036100a29190810190611cdb565b6101fe565b6040516100b491906127a6565b60405180910390f35b3480156100c957600080fd5b506100e460048036036100df9190810190611c5f565b61031e565b6040516100f29291906129ed565b60405180910390f35b34801561010757600080fd5b50610122600480360361011d9190810190611c89565b61039b565b005b34801561013057600080fd5b5061014b60048036036101469190810190611c5f565b610420565b60405161015891906127a6565b60405180910390f35b61017b60048036036101769190810190611ba4565b61049e565b005b34801561018957600080fd5b506101a4600480360361019f9190810190611b3d565b6106c0565b005b3480156101b257600080fd5b506101bb6108cb565b6040516101ca93929190612a16565b60405180910390f35b3480156101df57600080fd5b506101e86108ef565b6040516101f5919061272b565b60405180910390f35b600060028310610243576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161023a9061280d565b60405180910390fd5b600060fd610100038460010102604060020201905060fd61010003810160fd10156102a3576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161029a906128ad565b60405180910390fd5b600060fd826002800260010160fd610100030260406002020161010003018560028002600101600260010101600981106102d957fe5b602002015160001b901b901c9050600060fd6101000385876002600101016009811061030157fe5b6020020151901b90508160001c810160001b935050505092915050565b600080600083600280026001016002600101016009811061033b57fe5b602002015190506002800260010160fd610100030281901c905064e8d4a5100067ffffffffffffffff168167ffffffffffffffff1602915064e8d4a5100067ffffffffffffffff16604082901c67ffffffffffffffff1602925050915091565b600560020a603f54106103e3576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016103da9061288d565b60405180910390fd5b6000603f549050603f60008154600101919050819055506000816001600560020a0301905082600082603f811061041657fe5b0181905550505050565b60008060fd60406002026002800260010160fd6101000302604060020201610100030184600280026001016002600101016009811061045b57fe5b602002015160001b901b901c9050600060fd6101000384600280600101016009811061048357fe5b6020020151901b90508160001c810160001b92505050919050565b6104a6611777565b6104b1858483610915565b600060023373ffffffffffffffffffffffffffffffffffffffff16846000600281106104d957fe5b6020020151856001600281106104eb57fe5b60200201518c8c8c8a60405160200161050a97969594939291906126b1565b6040516020818303038152906040526040516105269190612685565b602060405180830381855afa158015610543573d6000803e3d6000fd5b5050506040513d601f19601f820116820180604052506105669190810190611cb2565b90506105ba8660006004811061057857fe5b60200201518760016004811061058a57fe5b60200201518860026004811061059c57fe5b6020020151896003600481106105ae57fe5b60200201518986610b23565b6105f9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016105f09061298d565b60405180910390fd5b61060589898987610bfa565b610644576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063b9061292d565b60405180910390fd5b61064c611777565b6106568582610e03565b60006106626002610e5f565b905061066d81610ec1565b7f36ed7c3f2ecfb5a5226c478b034d33144c060afe361be291e948f861dcddc618818584886040516106a294939291906127c1565b60405180910390a16106b386610ef0565b5050505050505050505050565b6106c8611799565b83816000019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff168152505082816020018181525050818160400181905250600060188360038151811061072457fe5b602001015160f81c60f81b7effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916901c60e01c60108460028151811061078457fe5b602001015160f81c60f81b7effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916901c60e01c6008856001815181106107e457fe5b602001015160f81c60f81b7effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916901c60e01c8560008151811061084257fe5b602001015160f81c60f81b7effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff191660e01c01010190508060e01b82606001907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff191690817bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916815250505050505050565b60008060006002925060029150600160028002600101600260010101019050909192565b604260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b604060008360006009811061092657fe5b602002015160001b815260200190815260200160002060009054906101000a900460ff16610989576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610980906128cd565b60405180910390fd5b60008090505b6002811015610a575760006109a482856101fe565b90506041600082815260200190815260200160002060009054906101000a900460ff1615610a07576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016109fe9061282d565b60405180910390fd5b60016041600083815260200190815260200160002060006101000a81548160ff02191690831515021790555080838360028110610a4057fe5b60200201818152505050808060010191505061098f565b50600060028285604051602001610a6f929190612659565b604051602081830303815290604052604051610a8b9190612685565b602060405180830381855afa158015610aa8573d6000803e3d6000fd5b5050506040513d601f19601f82011682018060405250610acb9190810190611cb2565b90506000610ad884610420565b9050808214610b1c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b13906128ed565b60405180910390fd5b5050505050565b6000610b2d6117f6565b6107d05a038682528560208301528360408301526020608083016060846000600286f150604082018981528860208201526040816060836000600787f1506040836080856000600687f15060016040840152600260608401528560808401526040816060836000600787f150505080600260058110610ba857fe5b602002015181600060058110610bba57fe5b6020020151148015610bed575080600360058110610bd457fe5b602002015181600160058110610be657fe5b6020020151145b9150509695505050505050565b6000807f30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f00000019050610c28611818565b86600060028110610c3557fe5b602002015181600001818152505086600160028110610c5057fe5b602002015181602001818152505085600060048110610c6b57fe5b602002015181604001818152505085600160048110610c8657fe5b602002015181606001818152505085600260048110610ca157fe5b602002015181608001818152505085600360048110610cbc57fe5b60200201518160a001818152505084600060028110610cd757fe5b60200201518160c001818152505084600160028110610cf257fe5b60200201518160e0018181525050606060016002800260010160026001010101604051908082528060200260200182016040528015610d405781602001602082028038833980820191505090505b50905060008090505b60016002800260010160026001010101811015610de85783868260098110610d6d57fe5b602002015110610db2576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610da99061296d565b60405180910390fd5b858160098110610dbe57fe5b6020020151828281518110610dcf57fe5b6020026020010181815250508080600101915050610d49565b50610df381836112a8565b6001149350505050949350505050565b60008090505b6002811015610e5a576000838260010160098110610e2357fe5b602002015160001b905080838360028110610e3a57fe5b602002018181525050610e4c8161039b565b508080600101915050610e09565b505050565b600080603f549050600083603f540390506000600560020a90505b6001811115610ea857610e8e8183856115c5565b809450819350505060028181610ea057fe5b049050610e7a565b600080603f8110610eb557fe5b01549350505050919050565b60016040600083815260200190815260200160002060006101000a81548160ff02191690831515021790555050565b600080610efc8361031e565b91509150600082111561104357600073ffffffffffffffffffffffffffffffffffffffff16604260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610ffb576000604260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690508073ffffffffffffffffffffffffffffffffffffffff166323b872dd3330866040518463ffffffff1660e01b8152600401610fc393929190612746565b600060405180830381600087803b158015610fdd57600080fd5b505af1158015610ff1573d6000803e3d6000fd5b505050505061103e565b81341461103d576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016110349061294d565b60405180910390fd5b5b6110fb565b60003411156110fa5760003373ffffffffffffffffffffffffffffffffffffffff16346040516110729061269c565b60006040518083038185875af1925050503d80600081146110af576040519150601f19603f3d011682016040523d82523d6000602084013e6110b4565b606091505b50509050806110f8576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016110ef9061284d565b60405180910390fd5b505b5b60008111156112a357600073ffffffffffffffffffffffffffffffffffffffff16604260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16146111f4576000604260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690508073ffffffffffffffffffffffffffffffffffffffff1663a9059cbb33846040518363ffffffff1660e01b81526004016111bc92919061277d565b600060405180830381600087803b1580156111d657600080fd5b505af11580156111ea573d6000803e3d6000fd5b50505050506112a2565b60003373ffffffffffffffffffffffffffffffffffffffff168260405161121a9061269c565b60006040518083038185875af1925050503d8060008114611257576040519150601f19603f3d011682016040523d82523d6000602084013e61125c565b606091505b50509050806112a0576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016112979061286d565b60405180910390fd5b505b5b505050565b60006043600a01805490506001845101146112f8576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016112ef9061290d565b60405180910390fd5b61130061185d565b6000600190506107d05a03600a60430183526020832060208701875160200281018254865260018301546020870152600283019250604086015b8183101561138957835481526001840154602082015282516040820152604081606083600060078af160408860808a600060068bf180821688169750505060028401935060208301925061133a565b5050505050806113ce576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016113c5906129cd565b60405180910390fd5b7f198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c260408301527f1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed60608301527f090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b60808301527f12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa60a083015260435460c083015260016043015460e083015260026043015461010083015260036043015461012083015260046043015461014083015260056043015461016083015283516101808301527f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47602085015181810682036101a085015260408601516101c085015260608601516101e0850152608086015161020085015260a086015161022085015260c086015161024085015260e08601516102608501526006604301546102808501526007604301546102a08501526008604301546102c08501526009604301546102e085015260208461030086600060086107d05a03f192505050806115a9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016115a0906129ad565b60405180910390fd5b816000601881106115b657fe5b60200201519250505092915050565b60008060006001860390506000600119861682019050600080600187161461163c576001868401039050611618600082603f81106115ff57fe5b0154600085600202603f811061161157fe5b01546116c6565b60006002600184038161162757fe5b04603f811061163257fe5b0181905550611642565b85830190505b5b8181111561169e5760028103905061167a600082603f811061166157fe5b0154600060018401603f811061167357fe5b01546116c6565b60006002600184038161168957fe5b04603f811061169457fe5b0181905550611643565b600287816116a857fe5b04600260018801816116b657fe5b0494509450505050935093915050565b60007fdec937b7fa8db3de380427a8cc947bfab68514522c3439cfa2e99655098368146000527f30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f00000018284828282088381820984858383098683840909925060005b605a81121561175f57602060002080600052868688838808089350868485099250868488858a8788090909945050600181019050611726565b508484868a8888880808089550505050505092915050565b6040518060400160405280600290602082028038833980820191505090505090565b6040518060800160405280600073ffffffffffffffffffffffffffffffffffffffff168152602001600081526020016060815260200160007bffffffffffffffffffffffffffffffffffffffffffffffffffffffff191681525090565b6040518060a00160405280600590602082028038833980820191505090505090565b60405180610100016040528060008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b604051806103000160405280601890602082028038833980820191505090505090565b60008135905061188f81612d62565b92915050565b600082601f8301126118a657600080fd5b60026118b96118b482612a7a565b612a4d565b9150818360005b838110156118f057813586016118d68882611a80565b8452602084019350602083019250506001810190506118c0565b5050505092915050565b600082601f83011261190b57600080fd5b600261191e61191982612a9c565b612a4d565b9150818385602084028201111561193457600080fd5b60005b83811015611964578161194a8882611b28565b845260208401935060208301925050600181019050611937565b5050505092915050565b600082601f83011261197f57600080fd5b600461199261198d82612abe565b612a4d565b915081838560208402820111156119a857600080fd5b60005b838110156119d857816119be8882611b28565b8452602084019350602083019250506001810190506119ab565b5050505092915050565b600082601f8301126119f357600080fd5b6009611a06611a0182612ae0565b612a4d565b91508183856020840282011115611a1c57600080fd5b60005b83811015611a4c5781611a328882611b28565b845260208401935060208301925050600181019050611a1f565b5050505092915050565b600081359050611a6581612d79565b92915050565b600081519050611a7a81612d79565b92915050565b600082601f830112611a9157600080fd5b8135611aa4611a9f82612b02565b612a4d565b91508082526020830160208301858383011115611ac057600080fd5b611acb838284612d05565b50505092915050565b600082601f830112611ae557600080fd5b8135611af8611af382612b2e565b612a4d565b91508082526020830160208301858383011115611b1457600080fd5b611b1f838284612d05565b50505092915050565b600081359050611b3781612d90565b92915050565b600080600060608486031215611b5257600080fd5b6000611b6086828701611880565b9350506020611b7186828701611b28565b925050604084013567ffffffffffffffff811115611b8e57600080fd5b611b9a86828701611ad4565b9150509250925092565b60008060008060008060006102e0888a031215611bc057600080fd5b6000611bce8a828b016118fa565b9750506040611bdf8a828b0161196e565b96505060c0611bf08a828b016118fa565b955050610100611c028a828b0161196e565b945050610180611c148a828b01611b28565b9350506101a0611c268a828b016119e2565b9250506102c088013567ffffffffffffffff811115611c4457600080fd5b611c508a828b01611895565b91505092959891949750929550565b60006101208284031215611c7257600080fd5b6000611c80848285016119e2565b91505092915050565b600060208284031215611c9b57600080fd5b6000611ca984828501611a56565b91505092915050565b600060208284031215611cc457600080fd5b6000611cd284828501611a6b565b91505092915050565b6000806101408385031215611cef57600080fd5b6000611cfd85828601611b28565b9250506020611d0e858286016119e2565b9150509250929050565b6000611d248383611fba565b60208301905092915050565b6000611d3c8383611fd8565b60208301905092915050565b6000611d548383612018565b905092915050565b6000611d688383612633565b60208301905092915050565b611d7d81612ccf565b82525050565b611d8c81612c89565b82525050565b611d9b81612b8c565b611da58184612c1a565b9250611db082612b5a565b8060005b83811015611de1578151611dc88782611d18565b9650611dd383612bd9565b925050600181019050611db4565b505050505050565b611df281612b8c565b611dfc8184612c25565b9250611e0782612b5a565b8060005b83811015611e38578151611e1f8782611d30565b9650611e2a83612bd9565b925050600181019050611e0b565b505050505050565b6000611e4b82612b97565b611e558185612c30565b935083602082028501611e6785612b64565b8060005b85811015611ea35784840389528151611e848582611d48565b9450611e8f83612be6565b925060208a01995050600181019050611e6b565b50829750879550505050505092915050565b611ebe81612ba2565b611ec88184612c3b565b9250611ed382612b6e565b8060005b83811015611f04578151611eeb8782611d5c565b9650611ef683612bf3565b925050600181019050611ed7565b505050505050565b611f1581612bad565b611f1f8184612c46565b9250611f2a82612b78565b8060005b83811015611f5b578151611f428782611d5c565b9650611f4d83612c00565b925050600181019050611f2e565b505050505050565b611f6c81612bb8565b611f768184612c51565b9250611f8182612b82565b8060005b83811015611fb2578151611f998782611d5c565b9650611fa483612c0d565b925050600181019050611f85565b505050505050565b611fc381612c9b565b82525050565b611fd281612c9b565b82525050565b611fe181612c9b565b82525050565b6000611ff282612bce565b611ffc8185612c6d565b935061200c818560208601612d14565b80840191505092915050565b600061202382612bc3565b61202d8185612c5c565b935061203d818560208601612d14565b61204681612d51565b840191505092915050565b600061205c82612bc3565b6120668185612c6d565b9350612076818560208601612d14565b80840191505092915050565b600061208f601883612c78565b91507f6e756c6c696669657220696e646578206f766572666c6f7700000000000000006000830152602082019050919050565b60006120cf603783612c78565b91507f496e76616c6964206e756c6c69666965723a2054686973206e756c6c6966696560008301527f722068617320616c7265616479206265656e20757365640000000000000000006020830152604082019050919050565b6000612135601e83612c78565b91507f767075625f696e2072657475726e207472616e73666572206661696c656400006000830152602082019050919050565b6000612175601883612c78565b91507f767075625f6f7574207472616e73666572206661696c656400000000000000006000830152602082019050919050565b60006121b5602783612c78565b91507f4d65726b6c6520747265652066756c6c3a2043616e6e6f7420617070656e642060008301527f616e796d6f7265000000000000000000000000000000000000000000000000006020830152604082019050919050565b600061221b603083612c78565b91507f6e756c6c6966696572207772697474656e20696e20646966666572656e74207260008301527f6573696475616c2062697420662e652e000000000000000000000000000000006020830152604082019050919050565b6000612281602583612c78565b91507f496e76616c696420726f6f743a205468697320726f6f7420646f65736e27742060008301527f65786973740000000000000000000000000000000000000000000000000000006020830152604082019050919050565b60006122e7604983612c78565b91507f496e76616c696420687369673a2054686973206873696720646f6573206e6f7460008301527f20636f72726573706f6e6420746f207468652068617368206f6620766b20616e60208301527f6420746865206e667300000000000000000000000000000000000000000000006040830152606082019050919050565b6000612373602283612c78565b91507f496e707574206c656e67746820646966666572732066726f6d2065787065637460008301527f65640000000000000000000000000000000000000000000000000000000000006020830152604082019050919050565b60006123d9603383612c78565b91507f496e76616c69642070726f6f663a20556e61626c6520746f207665726966792060008301527f7468652070726f6f6620636f72726563746c79000000000000000000000000006020830152604082019050919050565b600061243f602a83612c78565b91507f57726f6e67206d73672e76616c75653a2056616c75652070616964206973206e60008301527f6f7420636f7272656374000000000000000000000000000000000000000000006020830152604082019050919050565b60006124a5601c83612c78565b91507f496e707574206973206e6f7420696e207363616c6172206669656c64000000006000830152602082019050919050565b60006124e5603b83612c78565b91507f496e76616c6964207369676e61747572653a20556e61626c6520746f2076657260008301527f69667920746865207369676e617475726520636f72726563746c7900000000006020830152604082019050919050565b600061254b600083612c6d565b9150600082019050919050565b6000612565603783612c78565b91507f43616c6c20746f20626e3235364164642c20626e3235365363616c61724d756c60008301527f206f7220626e32353650616972696e67206661696c65640000000000000000006020830152604082019050919050565b60006125cb603983612c78565b91507f43616c6c20746f2074686520626e323536416464206f7220626e32353653636160008301527f6c61724d756c20707265636f6d70696c6564206661696c6564000000000000006020830152604082019050919050565b61262d81612cc5565b82525050565b61263c81612cc5565b82525050565b61265361264e82612cc5565b612d47565b82525050565b60006126658285611de9565b6040820191506126758284611f0c565b6080820191508190509392505050565b60006126918284611fe7565b915081905092915050565b60006126a78261253e565b9150819050919050565b60006126bd828a612642565b6020820191506126cd8289612051565b91506126d98288612051565b91506126e58287611eb5565b6040820191506126f58286611f0c565b6080820191506127058285611eb5565b6040820191506127158284611f63565b6101208201915081905098975050505050505050565b60006020820190506127406000830184611d83565b92915050565b600060608201905061275b6000830186611d74565b6127686020830185611d83565b6127756040830184612624565b949350505050565b60006040820190506127926000830185611d74565b61279f6020830184612624565b9392505050565b60006020820190506127bb6000830184611fc9565b92915050565b600060c0820190506127d66000830187611fc9565b6127e36020830186611d92565b6127f06060830185611d92565b81810360a08301526128028184611e40565b905095945050505050565b6000602082019050818103600083015261282681612082565b9050919050565b60006020820190508181036000830152612846816120c2565b9050919050565b6000602082019050818103600083015261286681612128565b9050919050565b6000602082019050818103600083015261288681612168565b9050919050565b600060208201905081810360008301526128a6816121a8565b9050919050565b600060208201905081810360008301526128c68161220e565b9050919050565b600060208201905081810360008301526128e681612274565b9050919050565b60006020820190508181036000830152612906816122da565b9050919050565b6000602082019050818103600083015261292681612366565b9050919050565b60006020820190508181036000830152612946816123cc565b9050919050565b6000602082019050818103600083015261296681612432565b9050919050565b6000602082019050818103600083015261298681612498565b9050919050565b600060208201905081810360008301526129a6816124d8565b9050919050565b600060208201905081810360008301526129c681612558565b9050919050565b600060208201905081810360008301526129e6816125be565b9050919050565b6000604082019050612a026000830185612624565b612a0f6020830184612624565b9392505050565b6000606082019050612a2b6000830186612624565b612a386020830185612624565b612a456040830184612624565b949350505050565b6000604051905081810181811067ffffffffffffffff82111715612a7057600080fd5b8060405250919050565b600067ffffffffffffffff821115612a9157600080fd5b602082029050919050565b600067ffffffffffffffff821115612ab357600080fd5b602082029050919050565b600067ffffffffffffffff821115612ad557600080fd5b602082029050919050565b600067ffffffffffffffff821115612af757600080fd5b602082029050919050565b600067ffffffffffffffff821115612b1957600080fd5b601f19601f8301169050602081019050919050565b600067ffffffffffffffff821115612b4557600080fd5b601f19601f8301169050602081019050919050565b6000819050919050565b6000819050919050565b6000819050919050565b6000819050919050565b6000819050919050565b600060029050919050565b600060029050919050565b600060029050919050565b600060049050919050565b600060099050919050565b600081519050919050565b600081519050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b600081905092915050565b600081905092915050565b600081905092915050565b600081905092915050565b600081905092915050565b600081905092915050565b600082825260208201905092915050565b600081905092915050565b600082825260208201905092915050565b6000612c9482612ca5565b9050919050565b6000819050919050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b6000819050919050565b6000612cda82612ce1565b9050919050565b6000612cec82612cf3565b9050919050565b6000612cfe82612ca5565b9050919050565b82818337600083830152505050565b60005b83811015612d32578082015181840152602081019050612d17565b83811115612d41576000848401525b50505050565b6000819050919050565b6000601f19601f8301169050919050565b612d6b81612c89565b8114612d7657600080fd5b50565b612d8281612c9b565b8114612d8d57600080fd5b50565b612d9981612cc5565b8114612da457600080fd5b5056fea365627a7a72315820581195eb613966cd593b726868fc28cf68f8daa35097a7bd66193af259e0d6006c6578706572696d656e74616cf564736f6c63430005110040" - - client = BcosClient() - mixerTransactionRecipient = client.sendRawTransactionGetReceipt("", abi5, None, constructArgs, bin5, 30000000, 15) - mixer_address = mixerTransactionRecipient['contractAddress'] - print(f"deploy: mixer_address={mixer_address}") - #mixer_instance = Groth16Mixer(address) - - -if __name__ == '__main__': - deploy() - diff --git a/zkservice/zkserver/zkserverapp/commands/zeth_deposit.py b/zkservice/zkserver/zkserverapp/commands/zeth_deposit.py deleted file mode 100644 index 17bb4cf..0000000 --- a/zkservice/zkserver/zkserverapp/commands/zeth_deposit.py +++ /dev/null @@ -1,69 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -from commands.utils import create_zeth_client_and_mixer_desc, \ - load_zeth_address, open_wallet, parse_output, do_sync -from zeth.constants import JS_INPUTS, JS_OUTPUTS -from commands.constants import PROVER_SERVER_ENDPOINT_DEFAULT -from zeth.mixer_client import ZethAddressPub -from zeth.utils import EtherValue, from_zeth_units -from api.zeth_messages_pb2 import ZethNote -from click import command, option, pass_context, ClickException, Context -from typing import List, Tuple, Optional -import sys -sys.path.append('../') -from contract.Groth16Mixer import Groth16Mixer -from python_web3.eth_account.account import Account - - -def deposit( - mixer_addr: str, - username: str, - password: str, - vin: str, - output_specs: List[str] - ) -> None: - """ - Generic mix function - """ - # Some sanity checks - if len(output_specs) > JS_OUTPUTS: - raise ClickException(f"too many outputs (max {JS_OUTPUTS})") - - print(f"vin = {vin}") - - vin_pub = EtherValue(vin) - zeth_client = create_zeth_client_and_mixer_desc(PROVER_SERVER_ENDPOINT_DEFAULT, mixer_addr, username, password) - - zeth_address = load_zeth_address(username) - wallet = open_wallet( - zeth_client.mixer_instance, zeth_address.addr_sk, username) - - outputs: List[Tuple[ZethAddressPub, EtherValue]] = [ - parse_output(out_spec) for out_spec in output_specs] - - # Compute input and output value total and check that they match - output_note_sum = sum([value for _, value in outputs], EtherValue(0)) - if vin_pub != output_note_sum: - raise ClickException("input and output value mismatch") - - #eth_address = load_eth_address(eth_addr) - fisco_bcos_address = zeth_client.mixer_instance.client.ecdsa_account.address - # If instance uses an ERC20 token, tx_value can be 0 not default vin_pub. - tx_value: Optional[EtherValue] = EtherValue(0) - #if mixer_desc.token: - # tx_value = EtherValue(0) - - (outputresult, receipt) = zeth_client.deposit( - wallet.merkle_tree, - zeth_address, - fisco_bcos_address, - vin_pub, - outputs, - tx_value) - - print("receipt status: ", receipt['status']) - #do_sync(wallet, receipt) -if __name__ == '__main__': - deposit() \ No newline at end of file diff --git a/zkservice/zkserver/zkserverapp/commands/zeth_gen_address.py b/zkservice/zkserver/zkserverapp/commands/zeth_gen_address.py deleted file mode 100644 index d6192fd..0000000 --- a/zkservice/zkserver/zkserverapp/commands/zeth_gen_address.py +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -from zeth.zeth_address import generate_zeth_address -from typing import Optional -from commands.utils import get_zeth_address_file, pub_address_file, \ - write_zeth_address_secret, write_zeth_address_public -from commands.constants import USER_DIR, WALLET_DIR_DEFAULT -from click import command, pass_context, ClickException, Context, option -from os.path import exists -from zeth.wallet import _ensure_dir -ADDRESS_FILE_DEFAULT = "zeth-address.json" - - -def gen_address(username: str) : - """ - Generate a new Zeth secret key and public address - """ - #client_ctx = ctx.obj - #addr_file_name = get_zeth_address_file(client_ctx) - addr_file = "{}/{}/{}".format(USER_DIR, username, ADDRESS_FILE_DEFAULT) - if exists(addr_file): - raise ClickException(f"ZethAddress file {addr_file} exists") - user_dir = "{}/{}/{}".format(USER_DIR, username, WALLET_DIR_DEFAULT) - _ensure_dir(user_dir) - pub_addr_file = pub_address_file(addr_file) - if exists(pub_addr_file): - raise ClickException(f"ZethAddress pub file {pub_addr_file} exists") - - zeth_address = generate_zeth_address() - write_zeth_address_secret(zeth_address.addr_sk, addr_file) - print(f"ZethAddress Secret key written to {addr_file}") - write_zeth_address_public(zeth_address.addr_pk, pub_addr_file) - print(f"Public ZethAddress written to {pub_addr_file}") - return zeth_address.addr_pk - -if __name__ == '__main__': - gen_address() \ No newline at end of file diff --git a/zkservice/zkserver/zkserverapp/commands/zeth_gen_fisco_address.py b/zkservice/zkserver/zkserverapp/commands/zeth_gen_fisco_address.py deleted file mode 100644 index a8832a5..0000000 --- a/zkservice/zkserver/zkserverapp/commands/zeth_gen_fisco_address.py +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -from zeth.zeth_address import generate_zeth_address -from typing import Optional -from commands.utils import get_zeth_address_file, pub_address_file, \ - write_zeth_address_secret, write_zeth_address_public -from commands.constants import USER_DIR, FISCO_ADDRESS_FILE, WALLET_DIR_DEFAULT -from click import command, ClickException, option -from os.path import exists -from python_web3.eth_account.account import Account -from zeth.wallet import _ensure_dir -import json - - - - -def gen_fisco_address(username: str, password: str) : - """ - Generate a new fisco account - """ - account = Account.create(password) - keystore_file = "{}/{}/{}".format(USER_DIR, username, FISCO_ADDRESS_FILE) - if exists(keystore_file): - raise ClickException(f"ZethAddress file {keystore_file} exists") - user_dir = "{}/{}/{}".format(USER_DIR, username, WALLET_DIR_DEFAULT) - _ensure_dir(user_dir) - keytext = Account.encrypt(account.privateKey, password) - with open(keystore_file, "w") as dump_f: - json.dump(keytext, dump_f) - print(f"{username}'s address: {account.address}") - print(f"{username}'s publickey: {account.publickey}") - print(f"fisco account keypair written to {keystore_file}") - return account.address account.publickey - - -if __name__ == '__main__': - gen_fisco_address() \ No newline at end of file diff --git a/zkservice/zkserver/zkserverapp/commands/zeth_ls_commits.py b/zkservice/zkserver/zkserverapp/commands/zeth_ls_commits.py deleted file mode 100644 index 6c2b94f..0000000 --- a/zkservice/zkserver/zkserverapp/commands/zeth_ls_commits.py +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -from commands.utils import \ - create_zeth_client_and_mixer_desc, load_zeth_address, open_wallet -from zeth.utils import short_commitment -from click import Context, command, pass_context, option -from commands.constants import PROVER_SERVER_ENDPOINT_DEFAULT - - -def ls_commits(username: str, password: str) -> None: - """ - List all commitments in the joinsplit contract - """ - #zeth_client = create_zeth_client_and_mixer_desc(PROVER_SERVER_ENDPOINT_DEFAULT, mixer_addr, username, password) - zeth_address = load_zeth_address(username) - wallet = open_wallet( - None, zeth_address.addr_sk, username) - print("COMMITMENTS:") - for commit in wallet.merkle_tree.get_leaves(): - print(f" {short_commitment(commit)}") - -if __name__ == '__main__': - ls_commits() diff --git a/zkservice/zkserver/zkserverapp/commands/zeth_ls_notes.py b/zkservice/zkserver/zkserverapp/commands/zeth_ls_notes.py deleted file mode 100644 index da65d79..0000000 --- a/zkservice/zkserver/zkserverapp/commands/zeth_ls_notes.py +++ /dev/null @@ -1,36 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -from commands.utils import load_zeth_address_secret, open_wallet -from zeth.utils import EtherValue -from click import Context, command, option, pass_context -import sys -sys.path.append('../') -#from contract.Groth16Mixer import Groth16Mixer - - -def ls_notes(username: str) -> None: - """ - List the set of notes owned by this wallet - """ - #client_ctx = ctx.obj - #web3 = open_web3_from_ctx(client_ctx) - #mixer_desc = load_mixer_description_from_ctx(client_ctx) - #mixer_instance = mixer_desc.mixer.instantiate(web3) - #mixer_instance = Groth16Mixer(mixer_addr) - js_secret = load_zeth_address_secret(username) - wallet = open_wallet(None, js_secret, username) - - total = EtherValue(0) - for addr, short_commit, value in wallet.note_summaries(): - print(f"{short_commit}: value={value.ether()}, addr={addr}") - total = total + value - - print(f"TOTAL BALANCE: {total.ether()}") - - print("SPENT NOTES:") - for addr, short_commit, value in wallet.spent_note_summaries(): - print(f"{short_commit}: value={value.ether()}, addr={addr}") -if __name__ == '__main__': - ls_notes() diff --git a/zkservice/zkserver/zkserverapp/commands/zeth_mix.py b/zkservice/zkserver/zkserverapp/commands/zeth_mix.py deleted file mode 100644 index 805fef1..0000000 --- a/zkservice/zkserver/zkserverapp/commands/zeth_mix.py +++ /dev/null @@ -1,80 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -from commands.utils import create_zeth_client_and_mixer_desc, \ - load_zeth_address, open_wallet, parse_output, do_sync -from zeth.constants import JS_INPUTS, JS_OUTPUTS -from commands.constants import PROVER_SERVER_ENDPOINT_DEFAULT -from zeth.mixer_client import ZethAddressPub -from zeth.utils import EtherValue, from_zeth_units -from api.zeth_messages_pb2 import ZethNote -from click import command, option, pass_context, ClickException, Context -from typing import List, Tuple, Optional -import sys -sys.path.append('../') -from contract.Groth16Mixer import Groth16Mixer -from python_web3.eth_account.account import Account - -def mix( - mixer_addr: str, - username: str, - password: str, - vin: str, - vout: str, - input_notes: List[str], - output_specs: List[str] - ) -> None: - """ - Generic mix function - """ - # Some sanity checks - if len(input_notes) > JS_INPUTS: - raise ClickException(f"too many inputs (max {JS_INPUTS})") - if len(output_specs) > JS_OUTPUTS: - raise ClickException(f"too many outputs (max {JS_OUTPUTS})") - - print(f"vin = {vin}") - print(f"vout = {vout}") - - vin_pub = EtherValue(vin) - vout_pub = EtherValue(vout) - zeth_client = create_zeth_client_and_mixer_desc(PROVER_SERVER_ENDPOINT_DEFAULT, mixer_addr, username, password) - - zeth_address = load_zeth_address(username) - wallet = open_wallet( - zeth_client.mixer_instance, zeth_address.addr_sk, username) - - inputs: List[Tuple[int, ZethNote]] = [ - wallet.find_note(note_id).as_input() for note_id in input_notes] - outputs: List[Tuple[ZethAddressPub, EtherValue]] = [ - parse_output(out_spec) for out_spec in output_specs] - - # Compute input and output value total and check that they match - input_note_sum = from_zeth_units( - sum([int(note.value, 16) for _, note in inputs])) - output_note_sum = sum([value for _, value in outputs], EtherValue(0)) - if vin_pub + input_note_sum != vout_pub + output_note_sum: - raise ClickException("input and output value mismatch") - - #eth_address = load_eth_address(eth_addr) - fisco_bcos_address = zeth_client.mixer_instance.client.ecdsa_account.address - # If instance uses an ERC20 token, tx_value can be 0 not default vin_pub. - tx_value: Optional[EtherValue] = EtherValue(0) - #if mixer_desc.token: - # tx_value = EtherValue(0) - - (outputresult, receipt) = zeth_client.joinsplit( - wallet.merkle_tree, - zeth_address.ownership_keypair(), - fisco_bcos_address, - inputs, - outputs, - vin_pub, - vout_pub, - tx_value) - - print("receipt output :", outputresult) - #do_sync(wallet, receipt) -if __name__ == '__main__': - mix() \ No newline at end of file diff --git a/zkservice/zkserver/zkserverapp/commands/zeth_token_approve.py b/zkservice/zkserver/zkserverapp/commands/zeth_token_approve.py deleted file mode 100644 index 36ab388..0000000 --- a/zkservice/zkserver/zkserverapp/commands/zeth_token_approve.py +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -from commands.utils import EtherValue -from click import command, argument, option, pass_context, ClickException, Context -import sys -sys.path.append('../') -from contract.Groth16Mixer import Groth16Mixer -from contract.ERC20Mintable import ERC20Mintable -from python_web3.eth_account.account import Account -from python_web3.client.bcoskeypair import BcosKeyPair -from commands.constants import USER_DIR, FISCO_ADDRESS_FILE -import json -from os.path import exists - - -def token_approve(tokens: str, mixer_addr: str, token_addr: str, username: str, password: str) -> None: - """ - Approve the mixer to spend some amount of tokens - """ - approve_value = EtherValue(tokens) - #eth_addr = load_eth_address(eth_addr) - #client_ctx = ctx.obj - #web3 = open_web3_from_ctx(client_ctx) - #mixer_desc = load_mixer_description_from_ctx(client_ctx) - #if not mixer_desc.token: - # raise ClickException("no token for mixer {mixer_desc.mixer.address}") - - token_instance = ERC20Mintable(token_addr) - keystore_file = "{}/{}/{}".format(USER_DIR, username, FISCO_ADDRESS_FILE) - if exists(keystore_file) is False: - raise ClickException(f"invalid output spec: {keystore_file}") - with open(keystore_file, "r") as dump_f: - keytext = json.load(dump_f) - privkey = Account.decrypt(keytext, password) - token_instance.client.ecdsa_account = Account.from_key(privkey) - keypair = BcosKeyPair() - keypair.private_key = token_instance.client.ecdsa_account.privateKey - keypair.public_key = token_instance.client.ecdsa_account.publickey - keypair.address = token_instance.client.ecdsa_account.address - token_instance.client.keypair = keypair - print(f"- {username} approves the transfer of ERC20Token to the Mixer") - token_instance.approve( - mixer_addr, - approve_value.wei) - outputresult = token_instance.allowance(token_instance.client.ecdsa_account.address, mixer_addr) - print(f"- The allowance for the Mixer from {username} is: {outputresult}") - -if __name__ == '__main__': - token_approve() \ No newline at end of file diff --git a/zkservice/zkserver/zkserverapp/commands/zeth_token_deploy.py b/zkservice/zkserver/zkserverapp/commands/zeth_token_deploy.py deleted file mode 100644 index 3e0993d..0000000 --- a/zkservice/zkserver/zkserverapp/commands/zeth_token_deploy.py +++ /dev/null @@ -1,46 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ -''' -from commands.utils import \ - open_web3_from_ctx, get_erc20_instance_description, load_eth_address, \ - write_mixer_description, MixerDescription -from zeth.mixer_client import MixerClient -from zeth.utils import EtherValue -''' -from click import Context, command, option, pass_context -from typing import Optional -from web3 import Web3 -import sys -sys.path.append('../') -from contract.ERC20Mintable import ERC20Mintable -#from test_commands.deploy_test_token import mint_token - - - -@command() -@option("--miner-address", help="Address of miner") -@option("--token-amount", help="amount of token been mint") -@pass_context -def deploy_token( - ctx: Context, - miner_address: Optional[str], - token_amount: Optional[int] - ) -> None: - """ - Deploy the zeth contracts and record the instantiation details. - """ - token_si = ERC20Mintable("") - token_result = token_si.deploy("contract/ERC20Mintable.bin") - token_address = token_result['contractAddress'] - token_instance = ERC20Mintable(token_address) - print(f"deploy: token_address={token_address}") - token_instance.mint( - miner_address, - Web3.toWei(token_amount, 'ether')) - print("- Initial balances: ") - outputresult = token_instance.balanceOf(miner_address) - print(f" {miner_address} : {outputresult}") - -if __name__ == '__main__': - deploy_token() diff --git a/zkservice/zkserver/zkserverapp/contract/ERC20.sol b/zkservice/zkserver/zkserverapp/contract/ERC20.sol deleted file mode 100644 index 0846fb2..0000000 --- a/zkservice/zkserver/zkserverapp/contract/ERC20.sol +++ /dev/null @@ -1,230 +0,0 @@ -pragma solidity ^0.5.0; - -import "../../GSN/Context.sol"; -import "./IERC20.sol"; -import "../../math/SafeMath.sol"; - -/** - * @dev Implementation of the {IERC20} interface. - * - * This implementation is agnostic to the way tokens are created. This means - * that a supply mechanism has to be added in a derived contract using {_mint}. - * For a generic mechanism see {ERC20Mintable}. - * - * TIP: For a detailed writeup see our guide - * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How - * to implement supply mechanisms]. - * - * We have followed general OpenZeppelin guidelines: functions revert instead - * of returning `false` on failure. This behavior is nonetheless conventional - * and does not conflict with the expectations of ERC20 applications. - * - * Additionally, an {Approval} event is emitted on calls to {transferFrom}. - * This allows applications to reconstruct the allowance for all accounts just - * by listening to said events. Other implementations of the EIP may not emit - * these events, as it isn't required by the specification. - * - * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} - * functions have been added to mitigate the well-known issues around setting - * allowances. See {IERC20-approve}. - */ -contract ERC20 is Context, IERC20 { - using SafeMath for uint256; - - mapping (address => uint256) private _balances; - - mapping (address => mapping (address => uint256)) private _allowances; - - uint256 private _totalSupply; - - /** - * @dev See {IERC20-totalSupply}. - */ - function totalSupply() public view returns (uint256) { - return _totalSupply; - } - - /** - * @dev See {IERC20-balanceOf}. - */ - function balanceOf(address account) public view returns (uint256) { - return _balances[account]; - } - - /** - * @dev See {IERC20-transfer}. - * - * Requirements: - * - * - `recipient` cannot be the zero address. - * - the caller must have a balance of at least `amount`. - */ - function transfer(address recipient, uint256 amount) public returns (bool) { - _transfer(_msgSender(), recipient, amount); - return true; - } - - /** - * @dev See {IERC20-allowance}. - */ - function allowance(address owner, address spender) public view returns (uint256) { - return _allowances[owner][spender]; - } - - /** - * @dev See {IERC20-approve}. - * - * Requirements: - * - * - `spender` cannot be the zero address. - */ - function approve(address spender, uint256 amount) public returns (bool) { - _approve(_msgSender(), spender, amount); - return true; - } - - /** - * @dev See {IERC20-transferFrom}. - * - * Emits an {Approval} event indicating the updated allowance. This is not - * required by the EIP. See the note at the beginning of {ERC20}; - * - * Requirements: - * - `sender` and `recipient` cannot be the zero address. - * - `sender` must have a balance of at least `amount`. - * - the caller must have allowance for `sender`'s tokens of at least - * `amount`. - */ - function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { - _transfer(sender, recipient, amount); - _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); - return true; - } - - /** - * @dev Atomically increases the allowance granted to `spender` by the caller. - * - * This is an alternative to {approve} that can be used as a mitigation for - * problems described in {IERC20-approve}. - * - * Emits an {Approval} event indicating the updated allowance. - * - * Requirements: - * - * - `spender` cannot be the zero address. - */ - function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { - _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); - return true; - } - - /** - * @dev Atomically decreases the allowance granted to `spender` by the caller. - * - * This is an alternative to {approve} that can be used as a mitigation for - * problems described in {IERC20-approve}. - * - * Emits an {Approval} event indicating the updated allowance. - * - * Requirements: - * - * - `spender` cannot be the zero address. - * - `spender` must have allowance for the caller of at least - * `subtractedValue`. - */ - function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { - _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); - return true; - } - - /** - * @dev Moves tokens `amount` from `sender` to `recipient`. - * - * This is internal function is equivalent to {transfer}, and can be used to - * e.g. implement automatic token fees, slashing mechanisms, etc. - * - * Emits a {Transfer} event. - * - * Requirements: - * - * - `sender` cannot be the zero address. - * - `recipient` cannot be the zero address. - * - `sender` must have a balance of at least `amount`. - */ - function _transfer(address sender, address recipient, uint256 amount) internal { - require(sender != address(0), "ERC20: transfer from the zero address"); - require(recipient != address(0), "ERC20: transfer to the zero address"); - - _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); - _balances[recipient] = _balances[recipient].add(amount); - emit Transfer(sender, recipient, amount); - } - - /** @dev Creates `amount` tokens and assigns them to `account`, increasing - * the total supply. - * - * Emits a {Transfer} event with `from` set to the zero address. - * - * Requirements - * - * - `to` cannot be the zero address. - */ - function _mint(address account, uint256 amount) internal { - require(account != address(0), "ERC20: mint to the zero address"); - - _totalSupply = _totalSupply.add(amount); - _balances[account] = _balances[account].add(amount); - emit Transfer(address(0), account, amount); - } - - /** - * @dev Destroys `amount` tokens from `account`, reducing the - * total supply. - * - * Emits a {Transfer} event with `to` set to the zero address. - * - * Requirements - * - * - `account` cannot be the zero address. - * - `account` must have at least `amount` tokens. - */ - function _burn(address account, uint256 amount) internal { - require(account != address(0), "ERC20: burn from the zero address"); - - _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); - _totalSupply = _totalSupply.sub(amount); - emit Transfer(account, address(0), amount); - } - - /** - * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. - * - * This is internal function is equivalent to `approve`, and can be used to - * e.g. set automatic allowances for certain subsystems, etc. - * - * Emits an {Approval} event. - * - * Requirements: - * - * - `owner` cannot be the zero address. - * - `spender` cannot be the zero address. - */ - function _approve(address owner, address spender, uint256 amount) internal { - require(owner != address(0), "ERC20: approve from the zero address"); - require(spender != address(0), "ERC20: approve to the zero address"); - - _allowances[owner][spender] = amount; - emit Approval(owner, spender, amount); - } - - /** - * @dev Destroys `amount` tokens from `account`.`amount` is then deducted - * from the caller's allowance. - * - * See {_burn} and {_approve}. - */ - function _burnFrom(address account, uint256 amount) internal { - _burn(account, amount); - _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); - } -} diff --git a/zkservice/zkserver/zkserverapp/contract/ERC20Mintable.abi b/zkservice/zkserver/zkserverapp/contract/ERC20Mintable.abi deleted file mode 100644 index 1ddb114..0000000 --- a/zkservice/zkserver/zkserverapp/contract/ERC20Mintable.abi +++ /dev/null @@ -1 +0,0 @@ -[{"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "owner", "type": "address"}, {"indexed": true, "internalType": "address", "name": "spender", "type": "address"}, {"indexed": false, "internalType": "uint256", "name": "value", "type": "uint256"}], "name": "Approval", "type": "event"}, {"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "account", "type": "address"}], "name": "MinterAdded", "type": "event"}, {"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "account", "type": "address"}], "name": "MinterRemoved", "type": "event"}, {"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "from", "type": "address"}, {"indexed": true, "internalType": "address", "name": "to", "type": "address"}, {"indexed": false, "internalType": "uint256", "name": "value", "type": "uint256"}], "name": "Transfer", "type": "event"}, {"constant": false, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "addMinter", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [{"internalType": "address", "name": "owner", "type": "address"}, {"internalType": "address", "name": "spender", "type": "address"}], "name": "allowance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [{"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}], "name": "approve", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "balanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [{"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "subtractedValue", "type": "uint256"}], "name": "decreaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": false, "inputs": [{"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "addedValue", "type": "uint256"}], "name": "increaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "isMinter", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [{"internalType": "address", "name": "account", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}], "name": "mint", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": false, "inputs": [], "name": "renounceMinter", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [], "name": "totalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [{"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}], "name": "transfer", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": false, "inputs": [{"internalType": "address", "name": "sender", "type": "address"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}], "name": "transferFrom", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}] \ No newline at end of file diff --git a/zkservice/zkserver/zkserverapp/contract/ERC20Mintable.bin b/zkservice/zkserver/zkserverapp/contract/ERC20Mintable.bin deleted file mode 100644 index 46bc80d..0000000 --- a/zkservice/zkserver/zkserverapp/contract/ERC20Mintable.bin +++ /dev/null @@ -1 +0,0 @@ -608060405262000024620000186200002a60201b60201c565b6200003260201b60201c565b62000257565b600033905090565b6200004d8160036200009360201b620012a81790919060201c565b8073ffffffffffffffffffffffffffffffffffffffff167f6ae172837ea30b801fbfcdd4108aa1d5bf8ff775444fd70256b44e6bf3dfc3f660405160405180910390a250565b620000a582826200017760201b60201c565b1562000119576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601f8152602001807f526f6c65733a206163636f756e7420616c72656164792068617320726f6c650081525060200191505060405180910390fd5b60018260000160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055505050565b60008073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16141562000200576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180620018506022913960400191505060405180910390fd5b8260000160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16905092915050565b6115e980620002676000396000f3fe608060405234801561001057600080fd5b50600436106100b45760003560e01c8063983b2d5611610071578063983b2d56146102e7578063986502751461032b578063a457c2d714610335578063a9059cbb1461039b578063aa271e1a14610401578063dd62ed3e1461045d576100b4565b8063095ea7b3146100b957806318160ddd1461011f57806323b872dd1461013d57806339509351146101c357806340c10f191461022957806370a082311461028f575b600080fd5b610105600480360360408110156100cf57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506104d5565b604051808215151515815260200191505060405180910390f35b6101276104f3565b6040518082815260200191505060405180910390f35b6101a96004803603606081101561015357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506104fd565b604051808215151515815260200191505060405180910390f35b61020f600480360360408110156101d957600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506105d6565b604051808215151515815260200191505060405180910390f35b6102756004803603604081101561023f57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610689565b604051808215151515815260200191505060405180910390f35b6102d1600480360360208110156102a557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610704565b6040518082815260200191505060405180910390f35b610329600480360360208110156102fd57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061074c565b005b6103336107bd565b005b6103816004803603604081101561034b57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506107cf565b604051808215151515815260200191505060405180910390f35b6103e7600480360360408110156103b157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061089c565b604051808215151515815260200191505060405180910390f35b6104436004803603602081101561041757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506108ba565b604051808215151515815260200191505060405180910390f35b6104bf6004803603604081101561047357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506108d7565b6040518082815260200191505060405180910390f35b60006104e96104e261095e565b8484610966565b6001905092915050565b6000600254905090565b600061050a848484610b5d565b6105cb8461051661095e565b6105c6856040518060600160405280602881526020016114fd60289139600160008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600061057c61095e565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e139092919063ffffffff16565b610966565b600190509392505050565b600061067f6105e361095e565b8461067a85600160006105f461095e565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610ed390919063ffffffff16565b610966565b6001905092915050565b600061069b61069661095e565b6108ba565b6106f0576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260308152602001806114ac6030913960400191505060405180910390fd5b6106fa8383610f5b565b6001905092915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b61075c61075761095e565b6108ba565b6107b1576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260308152602001806114ac6030913960400191505060405180910390fd5b6107ba81611116565b50565b6107cd6107c861095e565b611170565b565b60006108926107dc61095e565b8461088d85604051806060016040528060258152602001611590602591396001600061080661095e565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e139092919063ffffffff16565b610966565b6001905092915050565b60006108b06108a961095e565b8484610b5d565b6001905092915050565b60006108d08260036111ca90919063ffffffff16565b9050919050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614156109ec576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602481526020018061156c6024913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610a72576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806114646022913960400191505060405180910390fd5b80600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610be3576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260258152602001806115476025913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610c69576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260238152602001806114416023913960400191505060405180910390fd5b610cd481604051806060016040528060268152602001611486602691396000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e139092919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610d67816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610ed390919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b6000838311158290610ec0576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610e85578082015181840152602081019050610e6a565b50505050905090810190601f168015610eb25780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b600080828401905083811015610f51576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610ffe576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601f8152602001807f45524332303a206d696e7420746f20746865207a65726f20616464726573730081525060200191505060405180910390fd5b61101381600254610ed390919063ffffffff16565b60028190555061106a816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610ed390919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a35050565b61112a8160036112a890919063ffffffff16565b8073ffffffffffffffffffffffffffffffffffffffff167f6ae172837ea30b801fbfcdd4108aa1d5bf8ff775444fd70256b44e6bf3dfc3f660405160405180910390a250565b61118481600361138390919063ffffffff16565b8073ffffffffffffffffffffffffffffffffffffffff167fe94479a9f7e1952cc78f2d6baab678adc1b772d936c6583def489e524cb6669260405160405180910390a250565b60008073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415611251576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806115256022913960400191505060405180910390fd5b8260000160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16905092915050565b6112b282826111ca565b15611325576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601f8152602001807f526f6c65733a206163636f756e7420616c72656164792068617320726f6c650081525060200191505060405180910390fd5b60018260000160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055505050565b61138d82826111ca565b6113e2576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260218152602001806114dc6021913960400191505060405180910390fd5b60008260000160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff021916908315150217905550505056fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e63654d696e746572526f6c653a2063616c6c657220646f6573206e6f74206861766520746865204d696e74657220726f6c65526f6c65733a206163636f756e7420646f6573206e6f74206861766520726f6c6545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e6365526f6c65733a206163636f756e7420697320746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa265627a7a723158200bc878b43475e3971e822ce426de56a885c06df5280a7bfeed7fcc76dc165bef64736f6c63430005110032526f6c65733a206163636f756e7420697320746865207a65726f2061646472657373 \ No newline at end of file diff --git a/zkservice/zkserver/zkserverapp/contract/ERC20Mintable.py b/zkservice/zkserver/zkserverapp/contract/ERC20Mintable.py deleted file mode 100644 index 3daf82a..0000000 --- a/zkservice/zkserver/zkserverapp/contract/ERC20Mintable.py +++ /dev/null @@ -1,121 +0,0 @@ -# template for codegen -import sys -sys.path.append('../') -from python_web3.client.bcosclient import ( - BcosClient -) -from python_web3.client.datatype_parser import DatatypeParser -import json - -from python_web3.eth_utils import to_checksum_address - - -class ERC20Mintable: # name of abi - address = None - contract_abi_string = '''[{"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "owner", "type": "address"}, {"indexed": true, "internalType": "address", "name": "spender", "type": "address"}, {"indexed": false, "internalType": "uint256", "name": "value", "type": "uint256"}], "name": "Approval", "type": "event", "topic": "0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925"}, {"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "account", "type": "address"}], "name": "MinterAdded", "type": "event", "topic": "0x6ae172837ea30b801fbfcdd4108aa1d5bf8ff775444fd70256b44e6bf3dfc3f6"}, {"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "account", "type": "address"}], "name": "MinterRemoved", "type": "event", "topic": "0xe94479a9f7e1952cc78f2d6baab678adc1b772d936c6583def489e524cb66692"}, {"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "from", "type": "address"}, {"indexed": true, "internalType": "address", "name": "to", "type": "address"}, {"indexed": false, "internalType": "uint256", "name": "value", "type": "uint256"}], "name": "Transfer", "type": "event", "topic": "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"}, {"constant": false, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "addMinter", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [{"internalType": "address", "name": "owner", "type": "address"}, {"internalType": "address", "name": "spender", "type": "address"}], "name": "allowance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [{"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}], "name": "approve", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "balanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [{"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "subtractedValue", "type": "uint256"}], "name": "decreaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": false, "inputs": [{"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "addedValue", "type": "uint256"}], "name": "increaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "isMinter", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [{"internalType": "address", "name": "account", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}], "name": "mint", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": false, "inputs": [], "name": "renounceMinter", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [], "name": "totalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [{"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}], "name": "transfer", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": false, "inputs": [{"internalType": "address", "name": "sender", "type": "address"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}], "name": "transferFrom", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}]''' - contract_abi = None - data_parser = DatatypeParser() - client = None - - def __init__(self, address): - self.client = BcosClient() - self.address = address - self.contract_abi = json.loads(self.contract_abi_string) - self.data_parser.set_abi(self.contract_abi) - - def deploy(self, contract_bin_file): - result = self.client.deployFromFile(contract_bin_file) - self.address = result["contractAddress"] - return result - - # ------------------------------------------ - def addMinter(self, account): - func_name = 'addMinter' - args = [to_checksum_address(account)] - receipt = self.client.sendRawTransactionGetReceipt(self.address, self.contract_abi, func_name, args) - outputresult = self.data_parser.parse_receipt_output(func_name, receipt['output']) - return outputresult, receipt - - # ------------------------------------------ - def allowance(self, owner, spender): - func_name = 'allowance' - args = [to_checksum_address(owner), to_checksum_address(spender)] - result = self.client.call(self.address, self.contract_abi, func_name, args) - return result - - # ------------------------------------------ - def approve(self, spender, amount): - func_name = 'approve' - args = [to_checksum_address(spender), amount] - receipt = self.client.sendRawTransactionGetReceipt(self.address, self.contract_abi, func_name, args) - outputresult = self.data_parser.parse_receipt_output(func_name, receipt['output']) - return outputresult, receipt - - # ------------------------------------------ - def balanceOf(self, account): - func_name = 'balanceOf' - args = [to_checksum_address(account)] - result = self.client.call(self.address, self.contract_abi, func_name, args) - return result - - # ------------------------------------------ - def decreaseAllowance(self, spender, subtractedValue): - func_name = 'decreaseAllowance' - args = [to_checksum_address(spender), subtractedValue] - receipt = self.client.sendRawTransactionGetReceipt(self.address, self.contract_abi, func_name, args) - outputresult = self.data_parser.parse_receipt_output(func_name, receipt['output']) - return outputresult, receipt - - # ------------------------------------------ - def increaseAllowance(self, spender, addedValue): - func_name = 'increaseAllowance' - args = [to_checksum_address(spender), addedValue] - receipt = self.client.sendRawTransactionGetReceipt(self.address, self.contract_abi, func_name, args) - outputresult = self.data_parser.parse_receipt_output(func_name, receipt['output']) - return outputresult, receipt - - # ------------------------------------------ - def isMinter(self, account): - func_name = 'isMinter' - args = [to_checksum_address(account)] - result = self.client.call(self.address, self.contract_abi, func_name, args) - return result - - # ------------------------------------------ - def mint(self, account, amount): - func_name = 'mint' - args = [to_checksum_address(account), amount] - receipt = self.client.sendRawTransactionGetReceipt(self.address, self.contract_abi, func_name, args) - outputresult = self.data_parser.parse_receipt_output(func_name, receipt['output']) - return outputresult, receipt - - # ------------------------------------------ - def renounceMinter(self): - func_name = 'renounceMinter' - args = [] - receipt = self.client.sendRawTransactionGetReceipt(self.address, self.contract_abi, func_name, args) - outputresult = self.data_parser.parse_receipt_output(func_name, receipt['output']) - return outputresult, receipt - - # ------------------------------------------ - def totalSupply(self): - func_name = 'totalSupply' - args = [] - result = self.client.call(self.address, self.contract_abi, func_name, args) - return result - - # ------------------------------------------ - def transfer(self, recipient, amount): - func_name = 'transfer' - args = [to_checksum_address(recipient), amount] - receipt = self.client.sendRawTransactionGetReceipt(self.address, self.contract_abi, func_name, args) - outputresult = self.data_parser.parse_receipt_output(func_name, receipt['output']) - return outputresult, receipt - - # ------------------------------------------ - def transferFrom(self, sender, recipient, amount): - func_name = 'transferFrom' - args = [to_checksum_address(sender), to_checksum_address(recipient), amount] - receipt = self.client.sendRawTransactionGetReceipt(self.address, self.contract_abi, func_name, args) - outputresult = self.data_parser.parse_receipt_output(func_name, receipt['output']) - return outputresult, receipt diff --git a/zkservice/zkserver/zkserverapp/contract/Groth16Mixer.abi b/zkservice/zkserver/zkserverapp/contract/Groth16Mixer.abi deleted file mode 100644 index 0eec46b..0000000 --- a/zkservice/zkserver/zkserverapp/contract/Groth16Mixer.abi +++ /dev/null @@ -1,18 +0,0 @@ -[ -{"inputs": [{"internalType": "uint256", "name": "mk_depth", "type": "uint256"}, -{"internalType": "address", "name": "token", "type": "address"}, - {"internalType": "uint256[2]", "name": "Alpha", "type": "uint256[2]"}, - {"internalType": "uint256[2]", "name": "Beta1", "type": "uint256[2]"}, - {"internalType": "uint256[2]", "name": "Beta2", "type": "uint256[2]"}, - {"internalType": "uint256[2]", "name": "Delta1", "type": "uint256[2]"}, - {"internalType": "uint256[2]", "name": "Delta2", "type": "uint256[2]"}, - {"internalType": "uint256[]", "name": "ABC_coords", "type": "uint256[]"}], - "payable": false, "stateMutability": "nonpayable", "type": "constructor"}, - {"anonymous": false, "inputs": [{"indexed": false, "internalType": "string", "name": "message", "type": "string"}], "name": "LogDebug", "type": "event"}, - {"anonymous": false, "inputs": [{"indexed": false, "internalType": "bytes32", "name": "message", "type": "bytes32"}], "name": "LogDebug", "type": "event"}, - {"anonymous": false, "inputs": [{"indexed": false, "internalType": "bytes32", "name": "root", "type": "bytes32"}, - {"indexed": false, "internalType": "bytes32[2]", "name": "nullifiers", "type": "bytes32[2]"}, - {"indexed": false, "internalType": "bytes32[2]", "name": "commitments", "type": "bytes32[2]"}, - {"indexed": false, "internalType": "bytes[2]", "name": "ciphertexts", "type": "bytes[2]"}], - "name": "LogMix", "type": "event"}, {"constant": true, "inputs": [{"internalType": "uint256[9]", "name": "primary_inputs", "type": "uint256[9]"}], "name": "assemble_hsig", "outputs": [{"internalType": "bytes32", "name": "hsig", "type": "bytes32"}], "payable": false, "stateMutability": "pure", "type": "function"}, - {"constant": true, "inputs": [{"internalType": "uint256", "name": "index", "type": "uint256"}, {"internalType": "uint256[9]", "name": "primary_inputs", "type": "uint256[9]"}], "name": "assemble_nullifier", "outputs": [{"internalType": "bytes32", "name": "nf", "type": "bytes32"}], "payable": false, "stateMutability": "pure", "type": "function"}, {"constant": true, "inputs": [{"internalType": "uint256[9]", "name": "primary_inputs", "type": "uint256[9]"}], "name": "assemble_public_values", "outputs": [{"internalType": "uint256", "name": "vpub_in", "type": "uint256"}, {"internalType": "uint256", "name": "vpub_out", "type": "uint256"}], "payable": false, "stateMutability": "pure", "type": "function"}, {"constant": true, "inputs": [], "name": "get_constants", "outputs": [{"internalType": "uint256", "name": "js_in", "type": "uint256"}, {"internalType": "uint256", "name": "js_out", "type": "uint256"}, {"internalType": "uint256", "name": "num_inputs", "type": "uint256"}], "payable": false, "stateMutability": "pure", "type": "function"}, {"constant": false, "inputs": [{"internalType": "bytes32", "name": "commitment", "type": "bytes32"}], "name": "insert", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": false, "inputs": [{"internalType": "uint256[2]", "name": "a", "type": "uint256[2]"}, {"internalType": "uint256[4]", "name": "b", "type": "uint256[4]"}, {"internalType": "uint256[2]", "name": "c", "type": "uint256[2]"}, {"internalType": "uint256[4]", "name": "vk", "type": "uint256[4]"}, {"internalType": "uint256", "name": "sigma", "type": "uint256"}, {"internalType": "uint256[9]", "name": "input", "type": "uint256[9]"}, {"internalType": "bytes[2]", "name": "ciphertexts", "type": "bytes[2]"}], "name": "mix", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function"}, {"constant": true, "inputs": [], "name": "token", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": true, "inputs": [{"internalType": "address", "name": "from", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}, {"internalType": "bytes", "name": "data", "type": "bytes"}], "name": "tokenFallback", "outputs": [], "payable": false, "stateMutability": "pure", "type": "function"}] diff --git a/zkservice/zkserver/zkserverapp/contract/Groth16Mixer.bin b/zkservice/zkserver/zkserverapp/contract/Groth16Mixer.bin deleted file mode 100644 index 1b18255..0000000 --- a/zkservice/zkserver/zkserverapp/contract/Groth16Mixer.bin +++ /dev/null @@ -1 +0,0 @@ -60806040523480156200001157600080fd5b50604051620025a4380380620025a4833981016040819052620000349162000479565b8787818060208114620000645760405162461bcd60e51b81526004016200005b9062000590565b60405180910390fd5b50620000786001600160e01b036200025a16565b50600080800154600081815264020000000060205260409020805460ff1916600117905564020000000280546001600160a01b0385166001600160a01b03199091161790559050505050604051806040016040528087600060028110620000db57fe5b6020020151815260200187600160028110620000f357fe5b602090810291909101519091528151640200000003559081015164020000000455604080516080808201835288518083528985015183860181905289518486018190528a87015160609586018190526402000000059390935564020000000691909155640200000007556402000000085582519081018352865180825287850151828601819052875194830185905294870151919092018190526402000000099190915564020000000a9290925564020000000b5564020000000c5560005b6002825181620001be57fe5b64020000000d54919004146200024b57640200000003600a016040518060400160405280848481518110620001ef57fe5b602002602001015181526020018484600101815181106200020c57fe5b602090810291909101810151909152825460018181018555600094855293829020835160029283029091019081559290910151919092015501620001b2565b5050505050505050506200064b565b60006401fffffffe81905563800000005b8015620002b357620002898283620002b760201b62000ef41760201c565b91506001196002820201826000826401ffffffff8110620002a657fe5b015550600290046200026b565b5050565b60007fdec937b7fa8db3de380427a8cc947bfab68514522c3439cfa2e99655098368146000527f30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f00000018284828282088381820984858383098683840909925060005b605a8112156200034f57602060002080600052868688838808089350868485099250868488858a878809090994505060010162000317565b508484868a88888808080898975050505050505050565b8051620003738162000626565b92915050565b600082601f8301126200038b57600080fd5b6002620003a26200039c82620005c9565b620005a2565b91508183856020840282011115620003b957600080fd5b60005b83811015620003e95781620003d288826200046c565b8452506020928301929190910190600101620003bc565b5050505092915050565b600082601f8301126200040557600080fd5b8151620004166200039c82620005e7565b915081818352602084019350602081019050838560208402820111156200043c57600080fd5b60005b83811015620003e957816200045588826200046c565b84525060209283019291909101906001016200043f565b8051620003738162000640565b6000806000806000806000806101a0898b0312156200049757600080fd5b6000620004a58b8b6200046c565b9850506020620004b88b828c0162000366565b9750506040620004cb8b828c0162000379565b9650506080620004de8b828c0162000379565b95505060c0620004f18b828c0162000379565b945050610100620005058b828c0162000379565b935050610140620005198b828c0162000379565b9250506101808901516001600160401b038111156200053757600080fd5b620005458b828c01620003f3565b9150509295985092959890939650565b600062000564601f8362000608565b7f496e76616c696420646570746820696e20426173654d65726b6c655472656500815260200192915050565b60208082528101620003738162000555565b6040518181016001600160401b0381118282101715620005c157600080fd5b604052919050565b60006001600160401b03821115620005e057600080fd5b5060200290565b60006001600160401b03821115620005fe57600080fd5b5060209081020190565b90815260200190565b60006001600160a01b03821662000373565b90565b620006318162000611565b81146200063d57600080fd5b50565b620006318162000623565b611f49806200065b6000396000f3fe60806040526004361061007b5760003560e01c806397e004891161004e57806397e0048914610126578063c0ee0b8a14610139578063f9eb943f14610159578063fc0c546a1461017d5761007b565b806305ceb93c146100805780631f40927c146100b65780632d287e43146100e4578063354d06fd14610106575b600080fd5b34801561008c57600080fd5b506100a061009b3660046113e9565b61019f565b6040516100ad9190611c7d565b60405180910390f35b3480156100c257600080fd5b506100d66100d136600461138e565b61022d565b6040516100ad929190611dbf565b3480156100f057600080fd5b506101046100ff3660046113ad565b610256565b005b34801561011257600080fd5b506100a061012136600461138e565b6102ad565b6101046101343660046112d5565b6102cc565b34801561014557600080fd5b50610104610154366004611270565b61043f565b34801561016557600080fd5b5061016e610526565b6040516100ad93929190611dcd565b34801561018957600080fd5b50610192610530565b6040516100ad9190611c2c565b6000600283106101ca5760405162461bcd60e51b81526004016101c190611ccf565b60405180910390fd5b60036001840102608081019060830160fd10156101f95760405162461bcd60e51b81526004016101c190611d1f565b610100830151607182011b60fd1c60006003858782016009811061021957fe5b6020020151901b9190910195945050505050565b610100015164e8d4a5100067ffffffffffffffff604f83901c8116820293600f9390931c160290565b6401ffffffff54640100000000116102805760405162461bcd60e51b81526004016101c190611d0f565b6401ffffffff80546001810182559063ffffffff8201908390600090839081106102a657fe5b0155505050565b61010081015160a09091015160031b6007600c9290921c919091160190565b6102d4610fa1565b6102df858483610543565b815160208084015160405160009360029361030693339390918f918f918f918d9101611bb8565b60408051601f198184030181529082905261032091611ba1565b602060405180830381855afa15801561033d573d6000803e3d6000fd5b5050506040513d601f19601f8201168201806040525061036091908101906113cb565b86516020880151604089015160608a015193945061037f9389866106a4565b61039b5760405162461bcd60e51b81526004016101c190611d8f565b6103a789898987610743565b6103c35760405162461bcd60e51b81526004016101c190611d5f565b6103cb610fa1565b6103d58582610860565b60006103e160026108ad565b90506103ec816108ee565b7f36ed7c3f2ecfb5a5226c478b034d33144c060afe361be291e948f861dcddc618818584886040516104219493929190611c8b565b60405180910390a16104328661090d565b5050505050505050505050565b610447610fbf565b6001600160a01b0384168152602081018390526040810182905281516000906018908490600390811061047657fe5b016020015184516001600160f81b031990911690911c60e01c90601090859060029081106104a057fe5b016020015185516001600160f81b031990911690911c60e01c90600890869060019081106104ca57fe5b016020015186516001600160f81b031990911690911c60e01c9086906000906104ef57fe5b01602001516001600160e01b031963ff00000060e092831c16929092019290920192909201901b1660609092019190915250505050565b6002908190600990565b640200000002546001600160a01b031681565b81516000908152640200000000602052604090205460ff166105775760405162461bcd60e51b81526004016101c190611d2f565b60005b60028110156105fd57600061058f828561019f565b6000818152640200000001602052604090205490915060ff16156105c55760405162461bcd60e51b81526004016101c190611cdf565b600081815264020000000160205260409020805460ff19166001179055808383600281106105ef57fe5b60200201525060010161057a565b50600060028285604051602001610615929190611b7b565b60408051601f198184030181529082905261062f91611ba1565b602060405180830381855afa15801561064c573d6000803e3d6000fd5b5050506040513d601f19601f8201168201806040525061066f91908101906113cb565b9050600061067c846102ad565b905080821461069d5760405162461bcd60e51b81526004016101c190611d3f565b5050505050565b60006106ae610ffa565b6107d05a038682528560208301528360408301526020608083016060846000600286f150604082018981528860208201526040816060836000600787f1506040836080856000600687f15060016040840152600260608401528560808401526040816060836000600787f150505060408101518151148015610737575060608101516020820151145b98975050505050505050565b60007f30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f000000161076e611018565b86518152602080880151828201528651604080840191909152878201516060808501919091528189015160808501528089015160a0850152875160c08501528783015160e0850152815160098082526101408201909352909290919082016101208038833901905050905060005b600981101561084457838682600981106107f257fe5b6020020151106108145760405162461bcd60e51b81526004016101c190611d7f565b85816009811061082057fe5b602002015182828151811061083157fe5b60209081029190910101526001016107dc565b5061084f8183610b60565b60011493505050505b949350505050565b60005b60028110156108a857600083826001016009811061087d57fe5b602002015190508083836002811061089157fe5b602002015261089f81610256565b50600101610863565b505050565b6401ffffffff546000908281036401000000005b60018111156108e2576108d5818385610e2b565b93509150600290046108c1565b50506000549392505050565b600090815264020000000060205260409020805460ff19166001179055565b6000806109198361022d565b909250905081156109cf57640200000002546001600160a01b0316156109ab57640200000002546040516323b872dd60e01b81526001600160a01b039091169081906323b872dd9061097390339030908890600401611c3a565b600060405180830381600087803b15801561098d57600080fd5b505af11580156109a1573d6000803e3d6000fd5b50505050506109ca565b8134146109ca5760405162461bcd60e51b81526004016101c190611d6f565b610a53565b3415610a53576000336001600160a01b0316346040516109ee90611bad565b60006040518083038185875af1925050503d8060008114610a2b576040519150601f19603f3d011682016040523d82523d6000602084013e610a30565b606091505b5050905080610a515760405162461bcd60e51b81526004016101c190611cef565b505b80156108a857640200000002546001600160a01b031615610ade576402000000025460405163a9059cbb60e01b81526001600160a01b0390911690819063a9059cbb90610aa69033908690600401611c62565b600060405180830381600087803b158015610ac057600080fd5b505af1158015610ad4573d6000803e3d6000fd5b50505050506108a8565b6000336001600160a01b031682604051610af790611bad565b60006040518083038185875af1925050503d8060008114610b34576040519150601f19603f3d011682016040523d82523d6000602084013e610b39565b606091505b5050905080610b5a5760405162461bcd60e51b81526004016101c190611cff565b50505050565b64020000000d548251600091600190910114610b8e5760405162461bcd60e51b81526004016101c190611d4f565b610b9661105d565b60016107d05a03600a6402000000030183526020832060208701875160200281018254865260018301546020870152600283019250604086015b81831015610c1e57835481526001840154602082015282516040820152604081606083600060078af160408860808a600060068bf11695909516946002939093019260209290920191610bd0565b505050505080610c405760405162461bcd60e51b81526004016101c190611daf565b7f198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c260408301527f1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed60608301527f090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b60808301527f12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa60a08301526402000000035460c08301526001640200000003015460e08301526002640200000003015461010083015260036402000000030154610120830152600464020000000301546101408301526005640200000003015461016083015283516101808301527f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47602085015181810682036101a085015260408601516101c085015260608601516101e0850152608086015161020085015260a086015161022085015260c086015161024085015260e086015161026085015260066402000000030154610280850152600764020000000301546102a0850152600864020000000301546102c0850152600964020000000301546102e085015260208461030086600060086107d05a03f19250505080610e205760405162461bcd60e51b81526004016101c190611d9f565b505190505b92915050565b600080600019808601906001198616870101826001861615610e9f575060001982860101610e806000826401ffffffff8110610e6357fe5b01546000856002026401ffffffff8110610e7957fe5b0154610ef4565b600060026000198401046401ffffffff8110610e9857fe5b0155610ea4565b508185015b81811115610eda5760011901610e806000826401ffffffff8110610ec457fe5b01546000836001016401ffffffff8110610e7957fe5b600287046002600188010494509450505050935093915050565b60007fdec937b7fa8db3de380427a8cc947bfab68514522c3439cfa2e99655098368146000527f30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f00000018284828282088381820984858383098683840909925060005b605a811215610f8a57602060002080600052868688838808089350868485099250868488858a8788090909945050600101610f54565b508484868a88888808080898975050505050505050565b60405180604001604052806002906020820280388339509192915050565b604051806080016040528060006001600160a01b03168152602001600081526020016060815260200160006001600160e01b03191681525090565b6040518060a001604052806005906020820280388339509192915050565b60405180610100016040528060008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b6040518061030001604052806018906020820280388339509192915050565b8035610e2581611ee6565b600082601f83011261109857600080fd5b60026110ab6110a682611e0f565b611de8565b9150818360005b838110156110de57813586016110c88882611221565b84525060209283019291909101906001016110b2565b5050505092915050565b600082601f8301126110f957600080fd5b60026111076110a682611e0f565b9150818385602084028201111561111d57600080fd5b60005b838110156110de5781611133888261120b565b8452506020928301929190910190600101611120565b600082601f83011261115a57600080fd5b60046111686110a682611e0f565b9150818385602084028201111561117e57600080fd5b60005b838110156110de5781611194888261120b565b8452506020928301929190910190600101611181565b600082601f8301126111bb57600080fd5b60096111c96110a682611e0f565b915081838560208402820111156111df57600080fd5b60005b838110156110de57816111f5888261120b565b84525060209283019291909101906001016111e2565b8035610e2581611efd565b8051610e2581611efd565b600082601f83011261123257600080fd5b81356112406110a682611e2d565b9150808252602083016020830185838301111561125c57600080fd5b611267838284611ea4565b50505092915050565b60008060006060848603121561128557600080fd5b6000611291868661107c565b93505060206112a28682870161120b565b925050604084013567ffffffffffffffff8111156112bf57600080fd5b6112cb86828701611221565b9150509250925092565b60008060008060008060006102e0888a0312156112f157600080fd5b60006112fd8a8a6110e8565b975050604061130e8a828b01611149565b96505060c061131f8a828b016110e8565b9550506101006113318a828b01611149565b9450506101806113438a828b0161120b565b9350506101a06113558a828b016111aa565b9250506102c088013567ffffffffffffffff81111561137357600080fd5b61137f8a828b01611087565b91505092959891949750929550565b600061012082840312156113a157600080fd5b600061085884846111aa565b6000602082840312156113bf57600080fd5b6000610858848461120b565b6000602082840312156113dd57600080fd5b60006108588484611216565b60008061014083850312156113fd57600080fd5b6000611409858561120b565b925050602061141a858286016111aa565b9150509250929050565b60006114308383611655565b505060200190565b6000611444838361168d565b9392505050565b61145481611e93565b82525050565b61145481611e82565b61146c81611e58565b6114768184611e74565b925061148182611e55565b8060005b838110156114af5781516114998782611424565b96506114a483611e6e565b925050600101611485565b505050505050565b6114c081611e58565b6114ca8184611e74565b92506114d582611e55565b8060005b838110156114af5781516114ed8782611424565b96506114f883611e6e565b9250506001016114d9565b600061150e82611e58565b6115188185611e74565b93508360208202850161152a85611e55565b8060005b8581101561156457848403895281516115478582611438565b945061155283611e6e565b60209a909a019992505060010161152e565b5091979650505050505050565b61157a81611e58565b6115848184611e74565b925061158f82611e55565b8060005b838110156114af5781516115a78782611424565b96506115b283611e6e565b925050600101611593565b6115c681611e5e565b6115d08184611e74565b92506115db82611e55565b8060005b838110156114af5781516115f38782611424565b96506115fe83611e6e565b9250506001016115df565b61161281611e64565b61161c8184611e74565b925061162782611e55565b8060005b838110156114af57815161163f8782611424565b965061164a83611e6e565b92505060010161162b565b61145481611e55565b600061166982611e6a565b6116738185611e74565b9350611683818560208601611eb0565b9290920192915050565b600061169882611e6a565b6116a28185611e79565b93506116b2818560208601611eb0565b6116bb81611edc565b9093019392505050565b60006116d2601883611e79565b7f6e756c6c696669657220696e646578206f766572666c6f770000000000000000815260200192915050565b600061170b603783611e79565b7f496e76616c6964206e756c6c69666965723a2054686973206e756c6c6966696581527f722068617320616c7265616479206265656e2075736564000000000000000000602082015260400192915050565b600061176a601e83611e79565b7f767075625f696e2072657475726e207472616e73666572206661696c65640000815260200192915050565b60006117a3601883611e79565b7f767075625f6f7574207472616e73666572206661696c65640000000000000000815260200192915050565b60006117dc602783611e79565b7f4d65726b6c6520747265652066756c6c3a2043616e6e6f7420617070656e6420815266616e796d6f726560c81b602082015260400192915050565b6000611825603083611e79565b7f6e756c6c6966696572207772697474656e20696e20646966666572656e74207281526f32b9b4b23ab0b6103134ba103317329760811b602082015260400192915050565b6000611877602583611e79565b7f496e76616c696420726f6f743a205468697320726f6f7420646f65736e277420815264195e1a5cdd60da1b602082015260400192915050565b60006118be604983611e79565b7f496e76616c696420687369673a2054686973206873696720646f6573206e6f7481527f20636f72726573706f6e6420746f207468652068617368206f6620766b20616e6020820152686420746865206e667360b81b604082015260600192915050565b600061192f602283611e79565b7f496e707574206c656e67746820646966666572732066726f6d20657870656374815261195960f21b602082015260400192915050565b6000611973603383611e79565b7f496e76616c69642070726f6f663a20556e61626c6520746f20766572696679208152727468652070726f6f6620636f72726563746c7960681b602082015260400192915050565b60006119c8602a83611e79565b7f57726f6e67206d73672e76616c75653a2056616c75652070616964206973206e8152691bdd0818dbdc9c9958dd60b21b602082015260400192915050565b6000611a14601c83611e79565b7f496e707574206973206e6f7420696e207363616c6172206669656c6400000000815260200192915050565b6000611a4d603b83611e79565b7f496e76616c6964207369676e61747572653a20556e61626c6520746f2076657281527f69667920746865207369676e617475726520636f72726563746c790000000000602082015260400192915050565b6000610e25600083611e74565b6000611ab9603783611e79565b7f43616c6c20746f20626e3235364164642c20626e3235365363616c61724d756c81527f206f7220626e32353650616972696e67206661696c6564000000000000000000602082015260400192915050565b6000611b18603983611e79565b7f43616c6c20746f2074686520626e323536416464206f7220626e32353653636181527f6c61724d756c20707265636f6d70696c6564206661696c656400000000000000602082015260400192915050565b611454611b7682611e55565b611e55565b6000611b8782856114b7565b604082019150611b9782846115bd565b5060800192915050565b6000611444828461165e565b6000610e2582611a9f565b6000611bc4828a611b6a565b602082019150611bd4828961165e565b9150611be0828861165e565b9150611bec8287611571565b604082019150611bfc82866115bd565b608082019150611c0c8285611571565b604082019150611c1c8284611609565b5061012001979650505050505050565b60208101610e25828461145a565b60608101611c48828661144b565b611c55602083018561145a565b6108586040830184611655565b60408101611c70828561144b565b6114446020830184611655565b60208101610e258284611655565b60c08101611c998287611655565b611ca66020830186611463565b611cb36060830185611463565b81810360a0830152611cc58184611503565b9695505050505050565b60208082528101610e25816116c5565b60208082528101610e25816116fe565b60208082528101610e258161175d565b60208082528101610e2581611796565b60208082528101610e25816117cf565b60208082528101610e2581611818565b60208082528101610e258161186a565b60208082528101610e25816118b1565b60208082528101610e2581611922565b60208082528101610e2581611966565b60208082528101610e25816119bb565b60208082528101610e2581611a07565b60208082528101610e2581611a40565b60208082528101610e2581611aac565b60208082528101610e2581611b0b565b60408101611c708285611655565b60608101611ddb8286611655565b611c556020830185611655565b60405181810167ffffffffffffffff81118282101715611e0757600080fd5b604052919050565b600067ffffffffffffffff821115611e2657600080fd5b5060200290565b600067ffffffffffffffff821115611e4457600080fd5b506020601f91909101601f19160190565b90565b50600290565b50600490565b50600990565b5190565b60200190565b919050565b90815260200190565b60006001600160a01b038216610e25565b6000610e25826000610e2582611e82565b82818337506000910152565b60005b83811015611ecb578181015183820152602001611eb3565b83811115610b5a5750506000910152565b601f01601f191690565b611eef81611e82565b8114611efa57600080fd5b50565b611eef81611e5556fea365627a7a72315820e42326a4694c17436c7722fd4a82ac810b74162de26e7fd1035ac3ef5d5a29d16c6578706572696d656e74616cf564736f6c63430005110040 \ No newline at end of file diff --git a/zkservice/zkserver/zkserverapp/contract/Groth16Mixer.py b/zkservice/zkserver/zkserverapp/contract/Groth16Mixer.py deleted file mode 100644 index d66d676..0000000 --- a/zkservice/zkserver/zkserverapp/contract/Groth16Mixer.py +++ /dev/null @@ -1,86 +0,0 @@ -# template for codegen - -from python_web3.client.bcosclient import ( - BcosClient -) -from python_web3.client.datatype_parser import DatatypeParser -import json - -from python_web3.eth_utils import to_checksum_address - - -class Groth16Mixer: # name of abi - address = None - contract_abi_string = '''[{"inputs": [{"internalType": "uint256", "name": "mk_depth", "type": "uint256"}, {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256[2]", "name": "Alpha", "type": "uint256[2]"}, {"internalType": "uint256[2]", "name": "Beta1", "type": "uint256[2]"}, {"internalType": "uint256[2]", "name": "Beta2", "type": "uint256[2]"}, {"internalType": "uint256[2]", "name": "Delta1", "type": "uint256[2]"}, {"internalType": "uint256[2]", "name": "Delta2", "type": "uint256[2]"}, {"internalType": "uint256[]", "name": "ABC_coords", "type": "uint256[]"}], "payable": false, "stateMutability": "nonpayable", "type": "constructor"}, {"anonymous": false, "inputs": [{"indexed": false, "internalType": "string", "name": "message", "type": "string"}], "name": "LogDebug", "type": "event", "topic": "0xd44da6836c8376d1693e8b9cacf1c39b9bed3599164ad6d8e60902515f83938e"}, {"anonymous": false, "inputs": [{"indexed": false, "internalType": "bytes32", "name": "message", "type": "bytes32"}], "name": "LogDebug", "type": "event", "topic": "0x05e46912c9be87d8a6830598db8544b61884d9d22f3921597a9a6e8a340914b3"}, {"anonymous": false, "inputs": [{"indexed": false, "internalType": "bytes32", "name": "root", "type": "bytes32"}, {"indexed": false, "internalType": "bytes32[2]", "name": "nullifiers", "type": "bytes32[2]"}, {"indexed": false, "internalType": "bytes32[2]", "name": "commitments", "type": "bytes32[2]"}, {"indexed": false, "internalType": "bytes[2]", "name": "ciphertexts", "type": "bytes[2]"}], "name": "LogMix", "type": "event", "topic": "0x36ed7c3f2ecfb5a5226c478b034d33144c060afe361be291e948f861dcddc618"}, {"constant": true, "inputs": [{"internalType": "uint256[9]", "name": "primary_inputs", "type": "uint256[9]"}], "name": "assemble_hsig", "outputs": [{"internalType": "bytes32", "name": "hsig", "type": "bytes32"}], "payable": false, "stateMutability": "pure", "type": "function"}, {"constant": true, "inputs": [{"internalType": "uint256", "name": "index", "type": "uint256"}, {"internalType": "uint256[9]", "name": "primary_inputs", "type": "uint256[9]"}], "name": "assemble_nullifier", "outputs": [{"internalType": "bytes32", "name": "nf", "type": "bytes32"}], "payable": false, "stateMutability": "pure", "type": "function"}, {"constant": true, "inputs": [{"internalType": "uint256[9]", "name": "primary_inputs", "type": "uint256[9]"}], "name": "assemble_public_values", "outputs": [{"internalType": "uint256", "name": "vpub_in", "type": "uint256"}, {"internalType": "uint256", "name": "vpub_out", "type": "uint256"}], "payable": false, "stateMutability": "pure", "type": "function"}, {"constant": true, "inputs": [], "name": "get_constants", "outputs": [{"internalType": "uint256", "name": "js_in", "type": "uint256"}, {"internalType": "uint256", "name": "js_out", "type": "uint256"}, {"internalType": "uint256", "name": "num_inputs", "type": "uint256"}], "payable": false, "stateMutability": "pure", "type": "function"}, {"constant": false, "inputs": [{"internalType": "bytes32", "name": "commitment", "type": "bytes32"}], "name": "insert", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": false, "inputs": [{"internalType": "uint256[2]", "name": "a", "type": "uint256[2]"}, {"internalType": "uint256[4]", "name": "b", "type": "uint256[4]"}, {"internalType": "uint256[2]", "name": "c", "type": "uint256[2]"}, {"internalType": "uint256[4]", "name": "vk", "type": "uint256[4]"}, {"internalType": "uint256", "name": "sigma", "type": "uint256"}, {"internalType": "uint256[9]", "name": "input", "type": "uint256[9]"}, {"internalType": "bytes[2]", "name": "ciphertexts", "type": "bytes[2]"}], "name": "mix", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function"}, {"constant": true, "inputs": [], "name": "token", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": true, "inputs": [{"internalType": "address", "name": "from", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}, {"internalType": "bytes", "name": "data", "type": "bytes"}], "name": "tokenFallback", "outputs": [], "payable": false, "stateMutability": "pure", "type": "function"}]''' - contract_abi = None - data_parser = DatatypeParser() - client = None - - def __init__(self, address): - self.client = BcosClient() - self.address = address - self.contract_abi = json.loads(self.contract_abi_string) - self.data_parser.set_abi(self.contract_abi) - - def deploy(self, contract_bin_file): - result = self.client.deployFromFile(contract_bin_file) - self.address = result["contractAddress"] - return result - - # ------------------------------------------ - def assemble_hsig(self, primary_inputs): - func_name = 'assemble_hsig' - args = [primary_inputs] - result = self.client.call(self.address, self.contract_abi, func_name, args) - return result - - # ------------------------------------------ - def assemble_nullifier(self, index, primary_inputs): - func_name = 'assemble_nullifier' - args = [index, primary_inputs] - result = self.client.call(self.address, self.contract_abi, func_name, args) - return result - - # ------------------------------------------ - def assemble_public_values(self, primary_inputs): - func_name = 'assemble_public_values' - args = [primary_inputs] - result = self.client.call(self.address, self.contract_abi, func_name, args) - return result - - # ------------------------------------------ - def get_constants(self): - func_name = 'get_constants' - args = [] - result = self.client.call(self.address, self.contract_abi, func_name, args) - return result - - # ------------------------------------------ - def insert(self, commitment): - func_name = 'insert' - args = [commitment] - receipt = self.client.sendRawTransactionGetReceipt(self.address, self.contract_abi, func_name, args) - outputresult = self.data_parser.parse_receipt_output(func_name, receipt['output']) - return outputresult, receipt - - # ------------------------------------------ - def mix(self, a, b, c, vk, sigma, input, ciphertexts): - func_name = 'mix' - args = [a, b, c, vk, sigma, input, ciphertexts] - receipt = self.client.sendRawTransactionGetReceipt(self.address, self.contract_abi, func_name, args) - outputresult = self.data_parser.parse_receipt_output(func_name, receipt['output']) - return outputresult, receipt - - # ------------------------------------------ - def token(self): - func_name = 'token' - args = [] - result = self.client.call(self.address, self.contract_abi, func_name, args) - return result - - # ------------------------------------------ - def tokenFallback(self, from1, value, data): - func_name = 'tokenFallback' - args = [to_checksum_address(from1), value, data] - result = self.client.call(self.address, self.contract_abi, func_name, args) - return result diff --git a/zkservice/zkserver/zkserverapp/contract/__init__.py b/zkservice/zkserver/zkserverapp/contract/__init__.py deleted file mode 100644 index b6e016d..0000000 --- a/zkservice/zkserver/zkserverapp/contract/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ diff --git a/zkservice/zkserver/zkserverapp/contract/mixer/BaseMerkleTree.sol b/zkservice/zkserver/zkserverapp/contract/mixer/BaseMerkleTree.sol deleted file mode 100644 index 453a239..0000000 --- a/zkservice/zkserver/zkserverapp/contract/mixer/BaseMerkleTree.sol +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) 2015-2020 Clearmatics Technologies Ltd -// -// SPDX-License-Identifier: LGPL-3.0+ - -pragma solidity ^0.5.0; - -// Adapted from: https://github.com/zcash-hackworks/babyzoe - -contract BaseMerkleTree { - // Depth of the merkle tree (should be set with the same depth set in the - // cpp prover) - uint256 constant DEPTH = 5; - - // Number of leaves - uint256 constant MAX_NUM_LEAVES = 2**DEPTH; - - // Number of nodes - uint constant MAX_NUM_NODES = (MAX_NUM_LEAVES * 2) - 1; - - bytes32 constant DEFAULT_LEAF_VALUE = 0x0; - - // Array containing the 2^(depth) leaves of the merkle tree. We can switch - // the leaves to be of type bytes and not bytes32 to support digest of - // various size (eg: if we use different hash functions). That way we'd - // have a merkle tree for any type of hash function (that can be implemented - // as a precompiled contract for instance) - // - // Leaves is a 2D array - - // Sparse array of populated leaves of the merkle tree. Unpopulated leaves - // have the DEFAULT_LEAF_VALUE. - - bytes32[MAX_NUM_NODES] nodes; - - // Number of leaves populated in `nodes`. - uint256 num_leaves; - - // Debug only - event LogDebug(bytes32 message); - - // Constructor - constructor(uint256 treeDepth) public { - require ( - treeDepth == DEPTH, - "Invalid depth in BaseMerkleTree"); - } - - // Appends a commitment to the tree, and returns its address - function insert(bytes32 commitment) public { - - // If this require fails => the merkle tree is full, we can't append - // leaves anymore. - require( - num_leaves < MAX_NUM_LEAVES, - "Merkle tree full: Cannot append anymore" - ); - - // Address of the next leaf is the current number of leaves (before - // insertion). Compute the next index in the full set of nodes, and - // write. - uint256 next_address = num_leaves; - ++num_leaves; - uint256 next_entry_idx = (MAX_NUM_LEAVES - 1) + next_address; - nodes[next_entry_idx] = commitment; - } -} diff --git a/zkservice/zkserver/zkserverapp/contract/mixer/BaseMixer.sol b/zkservice/zkserver/zkserverapp/contract/mixer/BaseMixer.sol deleted file mode 100644 index 2aef07c..0000000 --- a/zkservice/zkserver/zkserverapp/contract/mixer/BaseMixer.sol +++ /dev/null @@ -1,381 +0,0 @@ -// Copyright (c) 2015-2020 Clearmatics Technologies Ltd -// -// SPDX-License-Identifier: LGPL-3.0+ - -pragma solidity ^0.5.0; -pragma experimental ABIEncoderV2; - -import "./MerkleTreeMiMC7.sol"; - -// Declare the ERC20 interface in order to handle ERC20 tokens transfers to and -// from the Mixer. Note that we only declare the functions we are interested in, -// namely, transferFrom() (used to do a Deposit), and transfer() (used to do a -// withdrawal) -contract ERC20 { - function transferFrom(address from, address to, uint256 value) public; - function transfer(address to, uint256 value) public; -} - -// ERC223 token compatible contract -contract ERC223ReceivingContract { - // See: - // https://github.com/Dexaran/ERC223-token-standard/blob/Recommended/Receiver_Interface.sol - struct Token { - address sender; - uint256 value; - bytes data; - bytes4 sig; - } - - function tokenFallback(address from, uint256 value, bytes memory data) - public pure { - Token memory tkn; - tkn.sender = from; - tkn.value = value; - tkn.data = data; - - // See: - // https://solidity.readthedocs.io/en/v0.5.5/types.html#conversions-between-elementary-types - uint32 u = - uint32(bytes4(data[0])) + - uint32(bytes4(data[1]) >> 8) + - uint32(bytes4(data[2]) >> 16) + - uint32(bytes4(data[3]) >> 24); - tkn.sig = bytes4(u); - } -} - -// BaseMixer implements the functions shared across all Mixers (regardless which -// zkSNARK is used) -contract BaseMixer is MerkleTreeMiMC7, ERC223ReceivingContract { - - // The roots of the different updated trees - mapping(bytes32 => bool) roots; - - // The public list of nullifiers (prevents double spend) - mapping(bytes32 => bool) nullifiers; - - // JoinSplit description, gives the number of inputs (nullifiers) and - // outputs (commitments/ciphertexts) to receive and process. - // - // IMPORTANT NOTE: We need to employ the same JS configuration than the one - // used in the cpp prover. Here we use 2 inputs and 2 outputs (it is a 2-2 - // JS). - uint256 constant jsIn = 2; // Nb of nullifiers - uint256 constant jsOut = 2; // Nb of commitments/ciphertexts - - // Size of the public values in bits - uint256 constant public_value_length = 64; - - // Constants regarding the hash digest length, the prime number used and - // its associated length in bits and the max values (v_in and v_out) - // uint r = 21888242871839275222246405745257275088548364400416034343698204186575808495617; - // field_capacity = floor( log_2(r) ) - uint256 constant digest_length = 256; - uint256 constant field_capacity = 253; - - // Variable representing the number of "residual" bits we can expect from - // converting a hash digest into a field element see primary input - // `residual_bits` in Reminder below - uint256 constant packing_residue_length = digest_length - field_capacity; - - // Number of hash digests in the primary inputs: - // 1 (the root) - // 2 * jsIn (nullifier and message auth tag per JS input) - // jsOut (commitment per JS output) - uint256 constant nb_hash_digests = 1 + 2*jsIn; - - // Bit offset of v_out in residual_bits - uint256 constant residual_hash_bits = packing_residue_length*nb_hash_digests; - - // Total number of residual bits from packing of 256-bit long string into - // 253-bit long field elements to which are added the public value of size - // 64 bits - uint256 constant length_bit_residual = 2 * public_value_length + - packing_residue_length * nb_hash_digests; - - // Number of field elements required to hold residual bits. - // (length_bit_residual + field_capacity - 1) / field_capacity - // (Note, compiler complains if we use the above expression in the - // definition of the constant, so this must be set explicitly.) - uint256 constant nb_field_residual = 1; - - // Padding size in the residual field element (we require a single residual - // f.e. (c.f. constructor)) - uint256 constant padding_size = digest_length - length_bit_residual; - - // The number of public inputs is: - // - 1 (the root) - // - jsIn (the nullifiers) - // - jsOut (the commitments) - // - 1 (hsig) - // - JsIn (the message auth. tags) - // - nb_field_residual (the residual bits not fitting in a single field - // element and the in and out public values) - uint256 constant nbInputs = 1 + jsOut + nb_hash_digests + nb_field_residual; - - // Contract variable that indicates the address of the token contract - // If token = address(0) then the mixer works with ether - address public token; - - // The unit used for public values (ether in and out), in Wei. Must match - // the python wrappers. Use Szabos (10^12 Wei). - uint64 constant public_unit_value_wei = 1 szabo; - - // solium complains if the parameters here are indented. - event LogMix( - bytes32 root, - bytes32[jsIn] nullifiers, - bytes32[jsOut] commitments, - bytes[jsOut] ciphertexts); - - // Debug only - event LogDebug(string message); - - // Constructor - constructor(uint256 depth, address token_address) MerkleTreeMiMC7(depth) - public { - bytes32 initialRoot = nodes[0]; - roots[initialRoot] = true; - - token = token_address; - - // We require the need of a single residual field elements - require( - field_capacity < digest_length, - "A hash digest fits in a single field element." - ); - require( - length_bit_residual < field_capacity, - "Too many input and output notes considered." - ); - } - - // Function allowing external users of the contract to retrieve some of the - // constants used in the mixer (since the solidity interfaces do not export - // this information as-of the current version). The intention is that - // external users and contraacts can query this function and ensure that - // they are compatible with the mixer configurations. - // - // Returns the number of input notes, the number of output notes and the - // total number of - function get_constants() - external pure - returns (uint256 js_in, uint256 js_out, uint256 num_inputs) - { - js_in = jsIn; - js_out = jsOut; - num_inputs = nbInputs; - } - - // ====================================================================== // - // Reminder: Remember that the primary inputs are ordered as follows: - // - // [Root, CommitmentS, NullifierS, h_sig, h_iS, Residual Field Element(S)] - // - // ie, below is the index mapping of the primary input elements on the - // protoboard: - // - // - Index of the "Root" field elements: {0} - // - Index of the "CommitmentS" field elements: [1, 1 + NumOutputs[ - // - Index of the "NullifierS" field elements: - // [1 + NumOutputs, 1 + NumOutputs + NumInputs[ - // - Index of the "h_sig" field element: {1 + NumOutputs + NumInputs} - // - Index of the "Message Authentication TagS" (h_i) field elements: - // [1 + NumOutputs + NumInputs + 1, - // 1 + NumOutputs + NumInputs + 1 + NumInputs[ - // - Index of the "Residual Field Element(s)" field elements: - // [1 + NumOutputs + NumInputs + 1 + NumInputs, - // 1 + NumOutputs + NumInputs + 1 + NumInputs + nb_field_residual[ - // - // The Residual field elements are structured as follows: - // - v_pub_in [0, public_value_length[ - // - v_pub_out [public_value_length, 2*public_value_length[ - // - h_sig remaining bits - // [2*public_value_length, - // 2*public_value_length + (digest_length-field_capacity)[ - // - nullifierS remaining bits: - // [2*public_value_length + (digest_length-field_capacity), - // 2*public_value_length + (1+NumInputs)*(digest_length-field_capacity)[ - // - message authentication tagS remaining bits: - // [2*public_value_length + (1+NumInputs)*(digest_length-field_capacity), - // 2*public_value_length + (1+2*NumInputs)*(digest_length-field_capacity)] - // ============================================================================================ // - - // This function is used to extract the public values (vpub_in, vpub_out) - // from the residual field element(S) - function assemble_public_values(uint256[nbInputs] memory primary_inputs) - public pure - returns (uint256 vpub_in, uint256 vpub_out){ - // We know vpub_in corresponds to the first 64 bits of the first - // residual field element after padding. We retrieve the public value - // in and remove any extra bits (due to the padding) - - uint256 residual_bits = primary_inputs[1 + jsOut + nb_hash_digests]; - residual_bits = residual_bits >> residual_hash_bits; - vpub_out = uint256(uint64(residual_bits)) * public_unit_value_wei; - vpub_in = uint256(uint64(residual_bits >> public_value_length)) * - public_unit_value_wei; - } - - // This function is used to reassemble hsig given the the primary_inputs To - // do so, we extract the remaining bits of hsig from the residual field - // element(S) and combine them with the hsig field element - function assemble_hsig(uint256[nbInputs] memory primary_inputs) - public pure - returns (bytes32 hsig) { - - // We know hsig residual bits correspond to the 128th to 130st bits of - // the first residual field element after padding. We retrieve hsig's - // residual bits and remove any extra bits (due to the padding) They - // correspond to the (digest_length - field_capacity) least significant - // bits of hsig in big endian - bytes32 hsig_bytes = - (bytes32(primary_inputs[1 + jsOut + nb_hash_digests]) << padding_size + - 2*public_value_length) >> field_capacity; - - // We retrieve the field element corresponding to the `field_capacity` - // most significant bits of hsig We remove the left padding due to - // casting `field_capacity` bits into a bytes32 We reassemble hsig by - // adding the values - uint256 high_bits = uint( - primary_inputs[1 + jsIn + jsOut] << (digest_length - field_capacity)); - hsig = bytes32(high_bits + uint(hsig_bytes)); - } - - // This function is used to reassemble the nullifiers given the nullifier - // index [0, jsIn[ and the primary_inputs To do so, we extract the - // remaining bits of the nullifier from the residual field element(S) and - // combine them with the nullifier field element - function assemble_nullifier( - uint256 index, uint256[nbInputs] memory primary_inputs) - public pure - returns (bytes32 nf) { - - // We first check that the nullifier we want to retrieve exists - require( - index < jsIn, - "nullifier index overflow" - ); - - // We compute the nullifier's residual bits index and check the 1st - // f.e. indeed comprises it. See the way the residual bits are ordered - // in the extended proof - uint256 nf_bit_index = - 2*public_value_length + (1 + index) * packing_residue_length; - require( - field_capacity >= nf_bit_index + packing_residue_length, - "nullifier written in different residual bit f.e." - ); - - // We retrieve nf's residual bits and remove any extra bits (due to the - // padding). They correspond to the (digest_length - field_capacity) - // least significant bits of nf in big endian - bytes32 nf_bytes = ( - bytes32(primary_inputs[1 + jsOut + nb_hash_digests]) - << (padding_size + nf_bit_index)) >> field_capacity; - - // We offset the nullifier index by the number of values preceding the - // nullifiers in the primary inputs: the root (1) and the cms (jsOut) - // We retrieve the field element corresponding to the `field_capacity` - // most significant bits of nf. We remove the left padding due to - // casting `field_capacity` bits into a bytes32. We reassemble nf by - // adding the values. - uint256 high_bits = uint( - primary_inputs[1 + jsOut + index] << (digest_length - field_capacity)); - nf = bytes32(high_bits + uint(nf_bytes)); - } - - // This function processes the primary inputs to append and check the root - // and nullifiers in the primary inputs (instance) and modifies the state - // of the mixer contract accordingly. (ie: Appends the commitments to the - // tree, appends the nullifiers to the list and so on). - function check_mkroot_nullifiers_hsig_append_nullifiers_state( - uint256[4] memory vk, - uint256[nbInputs] memory primary_inputs, - bytes32[jsIn] memory nfs) - internal { - // 1. We re-assemble the full root digest and check it is in the tree - require( - roots[bytes32(primary_inputs[0])], - "Invalid root: This root doesn't exist" - ); - - // 2. We re-assemble the nullifiers (JSInputs) and check they were not - // already seen. - for (uint256 i = 0; i < jsIn; i++) { - bytes32 nullifier = assemble_nullifier(i, primary_inputs); - require( - !nullifiers[nullifier], - "Invalid nullifier: This nullifier has already been used" - ); - nullifiers[nullifier] = true; - - nfs[i] = nullifier; - } - - // 3. We re-compute h_sig, re-assemble the expected h_sig and check - // they are equal (i.e. that h_sig re-assembled was correctly generated - // from vk). - bytes32 expected_hsig = sha256(abi.encodePacked(nfs, vk)); - bytes32 hsig = assemble_hsig(primary_inputs); - require( - expected_hsig == hsig, - "Invalid hsig: This hsig does not correspond to the hash of vk and the nfs" - ); - } - - function assemble_commitments_and_append_to_state( - uint256[nbInputs] memory primary_inputs, - bytes32[jsOut] memory comms) - internal { - // We re-assemble the commitments (JSOutputs) - for (uint256 i = 0; i < jsOut; i++) { - bytes32 current_commitment = bytes32(primary_inputs[1 + i]); - comms[i] = current_commitment; - insert(current_commitment); - } - } - - function process_public_values(uint256[nbInputs] memory primary_inputs) - internal { - // We get vpub_in and vpub_out in wei - (uint256 vpub_in, uint256 vpub_out) = - assemble_public_values(primary_inputs); - - // If the vpub_in is > 0, we need to make sure the right amount is paid - if (vpub_in > 0) { - if (token != address(0)) { - ERC20 erc20Token = ERC20(token); - erc20Token.transferFrom(msg.sender, address(this), vpub_in); - } else { - require( - msg.value == vpub_in, - "Wrong msg.value: Value paid is not correct" - ); - } - } else { - // If vpub_in = 0, return incoming Ether to the caller - if (msg.value > 0) { - (bool success, ) = msg.sender.call.value(msg.value)(""); - require(success, "vpub_in return transfer failed"); - } - } - - // If value_pub_out > 0 then we do a withdraw. We retrieve the - // msg.sender and send him the appropriate value IF proof is valid - if (vpub_out > 0) { - if (token != address(0)) { - ERC20 erc20Token = ERC20(token); - erc20Token.transfer(msg.sender, vpub_out); - } else { - (bool success, ) = msg.sender.call.value(vpub_out)(""); - require(success, "vpub_out transfer failed"); - } - } - } - - function add_merkle_root(bytes32 root) internal { - roots[root] = true; - } -} diff --git a/zkservice/zkserver/zkserverapp/contract/mixer/Groth16Mixer.sol b/zkservice/zkserver/zkserverapp/contract/mixer/Groth16Mixer.sol deleted file mode 100644 index d63c162..0000000 --- a/zkservice/zkserver/zkserverapp/contract/mixer/Groth16Mixer.sol +++ /dev/null @@ -1,371 +0,0 @@ -// Copyright (c) 2015-2020 Clearmatics Technologies Ltd -// -// SPDX-License-Identifier: LGPL-3.0+ - -pragma solidity ^0.5.0; -pragma experimental ABIEncoderV2; - -import "./OTSchnorrVerifier.sol"; -import "./BaseMixer.sol"; -import "./Pairing.sol"; - -contract Groth16Mixer is BaseMixer { - - // The structure of the verification key differs from the reference paper. - // It doesn't contain any element of GT, but only elements of G1 and G2 (the - // source groups). This is due to the lack of precompiled contract to - // manipulate elements of the target group GT on Ethereum. - struct VerifyingKey { - Pairing.G1Point Alpha; // slots 0x00, 0x01 - Pairing.G2Point Beta; // slots 0x02, 0x03, 0x04, 0x05 - Pairing.G2Point Delta; // slots 0x06, 0x07, 0x08, 0x09 - Pairing.G1Point[] ABC; // slot 0x0a - } - - // Internal Proof structure. Avoids reusing the G1 and G2 structs, since - // these cause extra pointers in memory, and complexity passing the data to - // precompiled contracts. - struct Proof { - // Pairing.G1Point A; - uint256 A_X; - uint256 A_Y; - // Pairing.G2Point B; - uint256 B_X0; - uint256 B_X1; - uint256 B_Y0; - uint256 B_Y1; - // Pairing.G1Point C; - uint256 C_X; - uint256 C_Y; - } - - VerifyingKey verifyKey; - - // Constructor - constructor( - uint256 mk_depth, - address token, - uint256[2] memory Alpha, - uint256[2] memory Beta1, - uint256[2] memory Beta2, - uint256[2] memory Delta1, - uint256[2] memory Delta2, - uint256[] memory ABC_coords) - BaseMixer(mk_depth, token) - public { - verifyKey.Alpha = Pairing.G1Point(Alpha[0], Alpha[1]); - verifyKey.Beta = Pairing.G2Point(Beta1[0], Beta1[1], Beta2[0], Beta2[1]); - verifyKey.Delta = Pairing.G2Point( - Delta1[0], Delta1[1], Delta2[0], Delta2[1]); - - // The `ABC` are elements of G1 (and thus have 2 coordinates in the - // underlying field). Here, we reconstruct these group elements from - // field elements (ABC_coords are field elements) - uint256 i = 0; - while(verifyKey.ABC.length != ABC_coords.length/2) { - verifyKey.ABC.push(Pairing.G1Point(ABC_coords[i], ABC_coords[i+1])); - i += 2; - } - } - - // This function mixes coins and executes payments in zero knowledge. - function mix( - uint256[2] memory a, - uint256[4] memory b, - uint256[2] memory c, - uint256[4] memory vk, - uint256 sigma, - uint256[nbInputs] memory input, - bytes[jsOut] memory ciphertexts) - public payable { - - // 1. Check the root and the nullifiers - bytes32[jsIn] memory nullifiers; - check_mkroot_nullifiers_hsig_append_nullifiers_state( - vk, input, nullifiers); - - // 2.a Verify the signature on the hash of data_to_be_signed - bytes32 hash_to_be_signed = sha256( - abi.encodePacked( - uint256(msg.sender), - // Unfortunately, we have to unroll this for now. We could - // replace encodePacked with a custom function but this would - // increase complexity and possibly gas usage. - ciphertexts[0], - ciphertexts[1], - a, - b, - c, - input - )); - require( - OTSchnorrVerifier.verify( - vk[0], vk[1], vk[2], vk[3], sigma, hash_to_be_signed), - "Invalid signature: Unable to verify the signature correctly" - ); - - // 2.b Verify the proof - require( - verifyTx(a, b, c, input), - "Invalid proof: Unable to verify the proof correctly" - ); - - // 3. Append the commitments to the tree - bytes32[jsOut] memory commitments; - assemble_commitments_and_append_to_state(input, commitments); - - // 4. Add the new root to the list of existing roots - bytes32 new_merkle_root = recomputeRoot(jsOut); - add_merkle_root(new_merkle_root); - - // 5. Emit the all Mix data - emit LogMix( - new_merkle_root, - nullifiers, - commitments, - ciphertexts); - - // 6. Get the public values in Wei and modify the state depending on - // their values - process_public_values(input); - } - - function verify(uint256[] memory input, Proof memory proof) - internal - returns (uint) { - - // `input.length` = size of the instance = l (see notations in the - // reference paper). We have coefficients indexed in the range[1..l], - // where l is the instance size, and we define a_0 = 1. This is the - // reason we need to check that: input.length + 1 == vk.ABC.length (the - // +1 accounts for a_0). This equality is a strong consistency check - // (len(givenInputs) needs to equal expectedInputSize (not less)) - require( - input.length + 1 == verifyKey.ABC.length, - "Input length differs from expected"); - - // Memory scratch pad, large enough to accomodate the max used size - // (see layout diagrams below). - uint256[24] memory pad; - - // 1. Compute the linear combination - // vk_x = \sum_{i=0}^{l} a_i * vk.ABC[i], vk_x in G1. - // - // ORIGINAL CODE: - // Pairing.G1Point memory vk_x = vk.ABC[0]; // a_0 = 1 - // for (uint256 i = 0; i < input.length; i++) { - // vk_x = Pairing.add(vk_x, Pairing.mul(vk.ABC[i + 1], input[i])); - // } - // - // The linear combination loop was the biggest cost center of the mixer - // contract. The following assembly block removes a lot of unnecessary - // memory usage and data copying, but relies on the structure of storage - // data. - // - // `pad` is layed out as follows, (so that calls to precompiled - // contracts can be done with minimal data copying) - // - // OFFSET USAGE - // 0x20 accum_y - // 0x00 accum_x - - // In each iteration, copy scalar multiplicaation data to 0x40+ - // - // OFFSET USAGE - // 0x80 input_i -- - // 0x60 abc_y | compute abc[i+1] * input[i] in-place - // 0x40 abc_x -- - // 0x20 accum_y - // 0x00 accum_x - // - // ready to call bn256ScalarMul(in: 0x40, out: 0x40). This results in: - // - // OFFSET USAGE - // 0x80 - // 0x60 input_i * abc_y -- - // 0x40 input_i * abc_x | accum = accum + input[i] * abc[i+1] - // 0x20 accum_y | - // 0x00 accum_x -- - // - // ready to call bn256Add(in: 0x00, out: 0x00) to update accum_x, - // accum_y in place. - - bool success = true; - assembly { - - let g := sub(gas, 2000) - - // Compute slot of ABC[0]. Solidity memory array layout defines the - // first entry of verifyKey.ABC as the keccak256 hash of the slot - // of verifyKey.ABC. The slot of verifyKey.ABC is computed using - // Solidity implicit `_slot` notation. - mstore(pad, add(verifyKey_slot, 10)) - let abc_slot := keccak256(pad, 32) - - // Compute input array bounds (layout: ,elem_0,elem_1...) - let input_i := add(input, 0x20) - let input_end := add(input_i, mul(0x20, mload(input))) - - // Initialize pad[0] with abc[0] - mstore(pad, sload(abc_slot)) - mstore(add(pad, 0x20), sload(add(abc_slot, 1))) - abc_slot := add(abc_slot, 2) - - // Location within pad to do scalar mul operation - let mul_in := add(pad, 0x40) - - // Iterate over all inputs / ABC values - for - { } - lt(input_i, input_end) - { - abc_slot := add(abc_slot, 2) - input_i := add(input_i, 0x20) - } - { - // Copy abc[i+1] into mul_in, incrementing abc - mstore(mul_in, sload(abc_slot)) - mstore(add(mul_in, 0x20), sload(add(abc_slot, 1))) - - // Copy input[i] into mul_in + 0x40, and increment index_i - mstore(add(mul_in, 0x40), mload(input_i)) - - // bn256ScalarMul and bn256Add can be done with no copying - let s1 := call(g, 7, 0, mul_in, 0x60, mul_in, 0x40) - let s2 := call(g, 6, 0, pad, 0x80, pad, 0x40) - success := and(success, and(s1, s2)) - } - } - - require( - success, - "Call to the bn256Add or bn256ScalarMul precompiled failed"); - - // 2. The verification check: - // e(Proof.A, Proof.B) = - // e(vk.Alpha, vk.Beta) * e(vk_x, P2) * e(Proof.C, vk.Delta) - // where: - // - e: G_1 x G_2 -> G_T is a bilinear map - // - `*`: denote the group operation in G_T - - // ORIGINAL CODE: - // bool res = Pairing.pairingProd4( - // Pairing.negate(Pairing.G1Point(proof.A_X, proof.A_Y)), - // Pairing.G2Point(proof.B_X0, proof.B_X1, proof.B_Y0, proof.B_Y1), - // verifyKey.Alpha, verifyKey.Beta, - // vk_x, Pairing.P2(), - // Pairing.G1Point(proof.C_X, proof.C_Y), - // verifyKey.Delta); - // if (!res) { - // return 0; - // } - // return 1; - - // Assembly below fills out pad and calls bn256Pairing, performing a - // check of the form: - // - // e(vk_x, P2) * e(vk.Alpha, vk.Beta) * - // e(negate(Proof.A), Proof.B) * e(Proof.C, vk.Delta) == 1 - // - // See Pairing.pairing(). Note terms have been re-ordered since vk_x is - // already at offset 0x00. Memory is laid out: - // - // 0x0300 - // 0x0280 - verifyKey.Delta in G2 - // 0x0240 - proof.C in G1 - // 0x01c0 - Proof.B in G2 - // 0x0180 - negate(Proof.A) in G1 - // 0x0100 - vk.Beta in G2 - // 0x00c0 - vk.Alpha in G1 - // 0x0040 - P2 in G2 - // 0x0000 - vk_x in G1 (Already present, by the above) - - assembly { - - // Write P2, from offset 0x40. See Pairing for these values. - mstore( - add(pad, 0x040), - 11559732032986387107991004021392285783925812861821192530917403151452391805634) - mstore( - add(pad, 0x060), - 10857046999023057135944570762232829481370756359578518086990519993285655852781) - mstore( - add(pad, 0x080), - 4082367875863433681332203403145435568316851327593401208105741076214120093531) - mstore( - add(pad, 0x0a0), - 8495653923123431417604973247489272438418190587263600148770280649306958101930) - - // Write vk.Alpha, vk.Beta (first 6 uints from verifyKey) from - // offset 0x0c0. - mstore(add(pad, 0x0c0), sload(verifyKey_slot)) - mstore(add(pad, 0x0e0), sload(add(verifyKey_slot, 1))) - mstore(add(pad, 0x100), sload(add(verifyKey_slot, 2))) - mstore(add(pad, 0x120), sload(add(verifyKey_slot, 3))) - mstore(add(pad, 0x140), sload(add(verifyKey_slot, 4))) - mstore(add(pad, 0x160), sload(add(verifyKey_slot, 5))) - - // Write negate(Proof.A) and Proof.B from offset 0x180. - mstore(add(pad, 0x180), mload(proof)) - let q := 21888242871839275222246405745257275088696311157297823662689037894645226208583 - let proof_A_y := mload(add(proof, 0x20)) - mstore(add(pad, 0x1a0), sub(q, mod(proof_A_y, q))) - mstore(add(pad, 0x1c0), mload(add(proof, 0x40))) - mstore(add(pad, 0x1e0), mload(add(proof, 0x60))) - mstore(add(pad, 0x200), mload(add(proof, 0x80))) - mstore(add(pad, 0x220), mload(add(proof, 0xa0))) - - // Proof.C and verifyKey.Delta from offset 0x240. - mstore(add(pad, 0x240), mload(add(proof, 0xc0))) - mstore(add(pad, 0x260), mload(add(proof, 0xe0))) - mstore(add(pad, 0x280), sload(add(verifyKey_slot, 6))) - mstore(add(pad, 0x2a0), sload(add(verifyKey_slot, 7))) - mstore(add(pad, 0x2c0), sload(add(verifyKey_slot, 8))) - mstore(add(pad, 0x2e0), sload(add(verifyKey_slot, 9))) - - success := call(sub(gas, 2000), 8, 0, pad, 0x300, pad, 0x20) - } - - require( - success, - "Call to bn256Add, bn256ScalarMul or bn256Pairing failed"); - return pad[0]; - } - - function verifyTx( - uint256[2] memory a, - uint256[4] memory b, - uint256[2] memory c, - uint256[nbInputs] memory primaryInputs) - internal - returns (bool) { - // Scalar field characteristic - // solium-disable-next-line - uint256 r = 21888242871839275222246405745257275088548364400416034343698204186575808495617; - - Proof memory proof; - proof.A_X = a[0]; - proof.A_Y = a[1]; - proof.B_X0 = b[0]; - proof.B_X1 = b[1]; - proof.B_Y0 = b[2]; - proof.B_Y1 = b[3]; - proof.C_X = c[0]; - proof.C_Y = c[1]; - - // Make sure that all primary inputs lie in the scalar field - - // TODO: For some reason, using a statically sized array (or - // primaryInputs directly) causes an out-of-gas exception, which seems - // completely counter-intuitive. Until that is tracked down, we use a - // dynamic array. - - uint256[] memory inputValues = new uint256[](nbInputs); - for (uint256 i = 0 ; i < nbInputs; i++) { - require(primaryInputs[i] < r, "Input is not in scalar field"); - inputValues[i] = primaryInputs[i]; - } - - return 1 == verify(inputValues, proof); - } -} diff --git a/zkservice/zkserver/zkserverapp/contract/mixer/MerkleTreeMiMC7.sol b/zkservice/zkserver/zkserverapp/contract/mixer/MerkleTreeMiMC7.sol deleted file mode 100644 index 41d6aa1..0000000 --- a/zkservice/zkserver/zkserverapp/contract/mixer/MerkleTreeMiMC7.sol +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) 2015-2020 Clearmatics Technologies Ltd -// -// SPDX-License-Identifier: LGPL-3.0+ - -pragma solidity ^0.5.0; - -import "./BaseMerkleTree.sol"; -import "./MiMC7.sol"; - -// The Merkle tree implementation must trade-off complexity, storage, -// initialization cost, and update & root computation cost. -// -// This implementation stores all leaves and nodes, skipping those that have -// not been populated yet. The final entry in each layer stores that layer's -// default value. -contract MerkleTreeMiMC7 is BaseMerkleTree -{ - uint256 constant MASK_LS_BIT = ~uint256(1); - - constructor(uint256 treeDepth) BaseMerkleTree(treeDepth) public - { - initializeTree(); - } - - function initializeTree() private - { - // First layer - bytes32 default_value = DEFAULT_LEAF_VALUE; - nodes[2 * MAX_NUM_LEAVES - 2] = default_value; - uint256 layer_size = MAX_NUM_LEAVES / 2; - - // Subsequent layers - while (layer_size > 0) { - default_value = MiMC7.hash(default_value, default_value); - uint256 layer_final_entry_idx = 2 * layer_size - 2; - nodes[layer_final_entry_idx] = default_value; - layer_size = layer_size / 2; - } - } - - function recomputeRoot(uint num_new_leaves) internal returns (bytes32) - { - // Assume `num_new_leaves` have been written into the leaf slots. - // Update any affected nodes in the tree, up to the root, using the - // default values for any missing nodes. - - uint256 end_idx = num_leaves; - uint256 start_idx = num_leaves - num_new_leaves; - uint256 layer_size = MAX_NUM_LEAVES; - - while (layer_size > 1) { - (start_idx, end_idx) = - recomputeParentLayer(layer_size, start_idx, end_idx); - layer_size = layer_size / 2; - } - - return nodes[0]; - } - - // Recompute nodes in the parent layer that are affected by entries - // [child_start_idx, child_end_idx[ in the child layer. If - // `child_end_idx` is required in the calculation, the final entry of - // the child layer is used (since this contains the default entry for - // the layer if the tree is not full). - // - // / \ / \ / \ - // Parent: ? ? F G H 0 - // / \ / \ / \ / \ / \ / \ - // Child: ? ? ? ? A B C D E ? ? 0 - // ^ ^ - // child_start_idx child_end_idx - // - // Returns the start and end indices (within the parent layer) of touched - // parent nodes. - function recomputeParentLayer( - uint256 child_layer_size, - uint256 child_start_idx, - uint256 child_end_idx) - private - returns (uint256, uint256) - { - uint256 child_layer_start = child_layer_size - 1; - - // Start at the right and iterate left, so we only execute the - // default_value logic once. child_left_idx_rend (reverse-end) is the - // smallest value of child_left_idx at which we should recompute the - // parent node hash. - - uint256 child_left_idx_rend = - child_layer_start + (child_start_idx & MASK_LS_BIT); - - // If child_end_idx is odd, it is the RIGHT of a computation we need to - // make. Do the computation using the default value, and move to the - // next pair (on the left). Otherwise, we have a fully populated pair. - - uint256 child_left_idx; - if ((child_end_idx & 1) != 0) { - child_left_idx = child_layer_start + child_end_idx - 1; - nodes[(child_left_idx - 1) / 2] = - MiMC7.hash(nodes[child_left_idx], nodes[2 * child_layer_start]); - } else { - child_left_idx = child_layer_start + child_end_idx; - } - - // At this stage, pairs are all populated. Compute until we reach - // child_left_idx_rend. - - while (child_left_idx > child_left_idx_rend) { - child_left_idx = child_left_idx - 2; - nodes[(child_left_idx - 1) / 2] = - MiMC7.hash(nodes[child_left_idx], nodes[child_left_idx + 1]); - } - - return (child_start_idx / 2, (child_end_idx + 1) / 2); - } -} diff --git a/zkservice/zkserver/zkserverapp/contract/mixer/MerkleTreeMiMC7_test.sol b/zkservice/zkserver/zkserverapp/contract/mixer/MerkleTreeMiMC7_test.sol deleted file mode 100644 index 13e819f..0000000 --- a/zkservice/zkserver/zkserverapp/contract/mixer/MerkleTreeMiMC7_test.sol +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2015-2020 Clearmatics Technologies Ltd -// -// SPDX-License-Identifier: LGPL-3.0+ - -pragma solidity ^0.5.0; - -import "./MerkleTreeMiMC7.sol"; - - -// Simple contract used for testing MerkleTreeMiMC7. -contract MerkleTreeMiMC7_test is MerkleTreeMiMC7 -{ - constructor(uint treeDepth) MerkleTreeMiMC7(treeDepth) public - { - } - - // Add some leaves, computing the root, then adding more leaves and - // recomputing the root. Returns the full set of nodes at the end. This - // allows testing of the update code paths for any starting / finishing - // state combination. - function testAddLeaves( - bytes32[] memory first, - bytes32[] memory second) - public returns (bytes32[MAX_NUM_NODES] memory) - { - for (uint i = 0 ; i < first.length ; ++i) { - insert(first[i]); - } - bytes32 root = recomputeRoot(first.length); - - for (uint i = 0 ; i < second.length ; ++i) { - insert(second[i]); - } - root = recomputeRoot(second.length); - log1(bytes32(0), root); - - return nodes; - } -} diff --git a/zkservice/zkserver/zkserverapp/contract/mixer/MerkleTreeSha256.sol b/zkservice/zkserver/zkserverapp/contract/mixer/MerkleTreeSha256.sol deleted file mode 100644 index 0485cb0..0000000 --- a/zkservice/zkserver/zkserverapp/contract/mixer/MerkleTreeSha256.sol +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2015-2020 Clearmatics Technologies Ltd -// -// SPDX-License-Identifier: LGPL-3.0+ - -pragma solidity ^0.5.0; - -// Adapted from: https://github.com/zcash-hackworks/babyzoe -import "./BaseMerkleTree.sol"; - -contract MerkleTreeSha256 is BaseMerkleTree { - - constructor(uint256 treeDepth) BaseMerkleTree(treeDepth) public { - // Nothing - } - - // Returns the current merkle tree - function getTree() internal view returns (bytes32[] memory) { - uint256 nbNodes = 2**(depth + 1) - 1; - bytes32[] memory tmpTree = new bytes32[](nbNodes); - - // Dump the leaves in the right indexes in the tree - for (uint256 i = 0; i < nbLeaves; i++) { - tmpTree[(nbLeaves - 1) + i] = leaves[i]; - } - - // Compute the internal nodes of the merkle tree - for (uint256 i = nbLeaves - 2; i > 0; i--) { - tmpTree[i] = sha256( - abi.encodePacked(tmpTree[i*2+1], tmpTree[2*(i+1)])); - } - - // Compute the merkle root - tmpTree[0] = sha256(abi.encodePacked(tmpTree[1], tmpTree[2])); - - return tmpTree; - } - - // Returns the root of the merkle tree - function getRoot() internal view returns(bytes32) { - return getTree()[0]; - } -} diff --git a/zkservice/zkserver/zkserverapp/contract/mixer/MiMC7.sol b/zkservice/zkserver/zkserverapp/contract/mixer/MiMC7.sol deleted file mode 100644 index 548b923..0000000 --- a/zkservice/zkserver/zkserverapp/contract/mixer/MiMC7.sol +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) 2015-2020 Clearmatics Technologies Ltd -// -// SPDX-License-Identifier: LGPL-3.0+ - -pragma solidity ^0.5.0; - -library MiMC7 -{ - /* - * Reference papers: - * - * \[AGRRT16]: - * "MiMC: Efficient Encryption and Cryptographic Hashing with Minimal - * Multiplicative Complexity", Martin Albrecht, Lorenzo Grassi, Christian - * Rechberger, Arnab Roy, and Tyge Tiessen, ASIACRYPT 2016, - * - * - * "One-way compression function" - * Section: "Miyaguchi–Preneel" - * - **/ - function hash(bytes32 x, bytes32 y) internal pure returns (bytes32 out) { - assembly { - // Use scratch space (0x00) for roundConstant. Must use memory since - // keccak256 is iteratively applied. Start with seed = - // keccak256("clearmatics_mt_seed") - mstore(0x0, 0xdec937b7fa8db3de380427a8cc947bfab68514522c3439cfa2e9965509836814) - - // See: - // https://github.com/ethereum/go-ethereum/blob/master/crypto/bn256/cloudflare/constants.go#L23 - let r := 21888242871839275222246405745257275088548364400416034343698204186575808495617 - - // y will be use used as round key of the block cipher as defined by - // Miyaguchi-Prenel construction - let key := y - - // Round function f(message) = (message + key + roundConstant)^d - // d (= exponent) = 7; #rounds = 91 - // - // Note on the exponent: gcd(7, r - 1) = 1 which confirms that the - // monomial x^7 is a permutation in Fr. See: Proposition 1, Section - // 4 and section 5; https://eprint.iacr.org/2016/492.pdf - // - // In the first round the constant is not used - let outPermutation := x - - // a = outPermutation + roundConstant + key mod r - let a := addmod(outPermutation, key, r) - // a2 = a^2 mod r - let a2 := mulmod(a, a, r) - // outPermutation = a^7 mod r - // (x^7 is the permutation polynomial used) - outPermutation := mulmod(mulmod(a2, a2, r), mulmod(a2, a, r), r) - - for {let j := 0} slt(j, 90) {j := add(j,1)} { - // roundConstant = H(roundConstant); - // we derive the (round) constants by iterative hash on the seed - let roundConstant := keccak256(0x0, 32) - mstore(0x0, roundConstant) - // a = outPermutation + roundConstant + key mod r - a := addmod(addmod(outPermutation, roundConstant, r), key, r) - // a2 = a^2 mod r - a2 := mulmod(a, a, r) - // outPermutation = a^7 mod r - // (x^7 is the permutation polynomial used) - outPermutation := mulmod(mulmod(mulmod(a2, a2, r), a2, r), a, r) - } - - // Compute H_i from H_{i-1} to generate the round key for the next - // entry in the input slice x. In MiMC the output of the last round - // is mixed with the round key: This corresponds to the - // `outMiMCCipher = addmod(outPermutation, key, r)`. And, the - // Myjaguchi-Prenell OWCF is ran: `addmod(addmod(outMiMCCipher, - // message, r), key, r)`. Note that we have merged the key addition - // ( +key ) of the last round of MiMC with the Myjaguchi-Prenell - // step. - out := addmod(addmod(addmod(outPermutation, key, r), x, r), key, r) - } - } -} diff --git a/zkservice/zkserver/zkserverapp/contract/mixer/Migrations.sol b/zkservice/zkserver/zkserverapp/contract/mixer/Migrations.sol deleted file mode 100644 index 1d9cb95..0000000 --- a/zkservice/zkserver/zkserverapp/contract/mixer/Migrations.sol +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2015-2020 Clearmatics Technologies Ltd -// -// SPDX-License-Identifier: LGPL-3.0+ - -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); - } -} diff --git a/zkservice/zkserver/zkserverapp/contract/mixer/OTSchnorrVerifier.sol b/zkservice/zkserver/zkserverapp/contract/mixer/OTSchnorrVerifier.sol deleted file mode 100644 index 2541813..0000000 --- a/zkservice/zkserver/zkserverapp/contract/mixer/OTSchnorrVerifier.sol +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright (c) 2015-2020 Clearmatics Technologies Ltd -// -// SPDX-License-Identifier: LGPL-3.0+ - -pragma solidity ^0.5.0; - -/* - * Reference paper: - * - * \[Bel07]: - * "Two-Tier Signatures, Strongly Unforgeable Signatures and Fiat-Shamir without Random Oracles", - * Mihir Bellare, Sarah Shoup, - * International Workshop on Public Key Cryptography, 2007, - * -**/ - -library OTSchnorrVerifier { - - function verify( - uint256 vk0, - uint256 vk1, - uint256 vk2, - uint256 vk3, - uint256 sigma, - bytes32 hash_to_be_signed) - internal - returns (bool) - { - // Original code: - // - // bytes32 h_bytes = sha256( - // abi.encodePacked(vk[2], vk[3], hash_to_be_signed)); - // uint256 h = uint256(h_bytes); - // - // // X = g^{x}, where g represents a generator of the cyclic group G - // Pairing.G1Point memory X = Pairing.G1Point(vk[0], vk[1]); - // // Y = g^{y} - // Pairing.G1Point memory Y = Pairing.G1Point(vk[2], vk[3]); - // - // // S = g^{sigma} - // Pairing.G1Point memory S = Pairing.mul(Pairing.P1(), sigma); - // // S_comp = g^{y + xh} - // Pairing.G1Point memory S_comp = Pairing.add(Y, Pairing.mul(X, h)); - // - // // Check that g^{sigma} == g^{y + xh} - // return (S.X == S_comp.X && S.Y == S_comp.Y); - - // Pad - uint256[5] memory pad; - - assembly { - - let g := sub(gas, 2000) - - // pad: - // 0x40 hash_to_be_signed - // 0x20 Y[1] - // 0x00 Y[0] - // Compute sha256 into 0x40 - - mstore(pad, vk2) - mstore(add(pad, 0x20), vk3) - mstore(add(pad, 0x40), hash_to_be_signed) - pop(call(g, 2, 0, pad, 0x60, add(pad, 0x80), 0x20)) - - // pad: - // 0x80 h = sha256(Y || hash_to_be_signed) - // 0x60 - // 0x40 - // 0x20 Y[1] - // 0x00 Y[0] - // Write X from 0x40 and call bn256ScalarMul(in: 0x40, out: 0x40) - - let x_location := add(pad, 0x40) - mstore(x_location, vk0) - mstore(add(x_location, 0x20), vk1) - pop(call(g, 7, 0, x_location, 0x60, x_location, 0x40)) - - // pad: - // 0x60 h.X[1] - // 0x40 h.X[0] - // 0x20 Y[1] - // 0x00 Y[0] - // Call bn256Sum(in: 0x00, out: 0x00) - - pop(call(g, 6, 0, pad, 0x80, pad, 0x40)) - - // pad: - // 0x60 - // 0x40 - // 0x20 (Y + h.X)[1] - // 0x00 (Y + h.X)[0] - // copy P1 and sigma (see Pairing.sol for values) - - mstore(add(pad, 0x40), 1) - mstore(add(pad, 0x60), 2) - mstore(add(pad, 0x80), sigma) - - // pad: - // 0x80 sigma - // 0x60 P1[1] - // 0x40 P1[0] - // 0x20 (Y + h.X)[1] - // 0x00 (Y + h.X)[0] - // call bn256ScalarMul(in: 0x40, out: 0x40) - - pop(call(g, 7, 0, x_location, 0x60, x_location, 0x40)) - - // pad: - // 0x60 sigma.P1[1] - // 0x40 sigma.P1[0] - // 0x20 (Y + h.X)[1] - // 0x00 (Y + h.X)[0] - } - - // compare - - return pad[0] == pad[2] && pad[1] == pad[3]; - } -} diff --git a/zkservice/zkserver/zkserverapp/contract/mixer/Pairing.sol b/zkservice/zkserver/zkserverapp/contract/mixer/Pairing.sol deleted file mode 100644 index 87c98ba..0000000 --- a/zkservice/zkserver/zkserverapp/contract/mixer/Pairing.sol +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright (c) 2015-2020 Clearmatics Technologies Ltd -// -// SPDX-License-Identifier: LGPL-3.0+ - -pragma solidity ^0.5.0; - -// Several pairing-related utility functions. -// -// Precompiled contract details (bn256Add, bn256ScalarMul, bn256Pairing) can be -// found at the following links. Implementations: -// https://github.com/ethereum/go-ethereum/blob/master/core/vm/contracts.go gas -// and costs: -// https://github.com/ethereum/go-ethereum/blob/master/params/protocol_params.go - -library Pairing { - - struct G1Point { - uint256 X; - uint256 Y; - } - - // Encoding of field elements is: X[0] * z + X[1] - struct G2Point { - uint256 X0; - uint256 X1; - uint256 Y0; - uint256 Y1; - } - - // Return the generator of G1 - function P1() internal pure returns (G1Point memory) { - return G1Point(1, 2); - } - - // Return the generator of G2 - function P2() internal pure returns (G2Point memory) { - return G2Point( - // solium-disable-next-line - 11559732032986387107991004021392285783925812861821192530917403151452391805634, - // solium-disable-next-line - 10857046999023057135944570762232829481370756359578518086990519993285655852781, - // solium-disable-next-line - 4082367875863433681332203403145435568316851327593401208105741076214120093531, - // solium-disable-next-line - 8495653923123431417604973247489272438418190587263600148770280649306958101930); - } - - // Return the negation of p, i.e. p.add(p.negate()) should be zero. - function negate(G1Point memory p) internal pure returns (G1Point memory) { - // The prime q in the base field F_q for G1 - // solium-disable-next-line - uint256 q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; - if (p.X == 0 && p.Y == 0) - return G1Point(0, 0); - return G1Point(p.X, q - (p.Y % q)); - } - - // Return the sum of two points of G1 - function add(G1Point memory p1, G1Point memory p2) - internal - returns (G1Point memory r) { - uint256[4] memory input; - input[0] = p1.X; - input[1] = p1.Y; - input[2] = p2.X; - input[3] = p2.Y; - bool success; - assembly { - // Call bn256Add([p1.X, p1.Y, p2.X, p2.Y]) - success := call(sub(gas, 2000), 6, 0, input, 0x80, r, 0x40) - // Use "invalid" to make gas estimation work - //switch success case 0 { invalid } - } - require( - success, - "Call to the bn256Add precompiled failed (probably an out of gas error?)" - ); - } - - // Return the product of a point on G1 and a scalar, i.e. - // p == p.mul(1) and p.add(p) == p.mul(2) for all points p. - function mul(G1Point memory p, uint256 s) - internal - returns (G1Point memory r) { - uint256[3] memory input; - input[0] = p.X; - input[1] = p.Y; - input[2] = s; - bool success; - assembly { - // Call bn256ScalarMul([p.X, p.Y, s]) - success := call(sub(gas, 2000), 7, 0, input, 0x60, r, 0x40) - // Use "invalid" to make gas estimation work - //switch success case 0 { invalid } - } - require ( - success, - "Call to bn256ScalarMul failed (probably an out of gas error?)" - ); - } - - // Return the result of computing the pairing check - function pairing(G1Point[] memory p1, G2Point[] memory p2) - internal - returns (bool) { - require( - p1.length == p2.length, - "Mismatch between the number of elements in G1 and elements in G2" - ); - // For each pairing check we have 2 coordinates for the elements in G1, - // and 4 coordinates for the elements in G2 - uint256 elements = p1.length; - uint256 inputSize = elements * 6; - uint256[] memory input = new uint256[](inputSize); - for (uint256 i = 0; i < elements; i++) - { - // Curve point (G1) - 2 coordinates of 32bytes (0x20 in hex) - input[i * 6 + 0] = p1[i].X; - input[i * 6 + 1] = p1[i].Y; - // Twist point (G2) - 2*2 coordinates of 32bytes (0x20 in hex) - input[i * 6 + 2] = p2[i].X0; - input[i * 6 + 3] = p2[i].X1; - input[i * 6 + 4] = p2[i].Y0; - input[i * 6 + 5] = p2[i].Y1; - } - uint256[1] memory out; - bool success; - assembly { - // bn256Pairing precompiled: - // https://github.com/ethereum/go-ethereum/blob/master/core/vm/contracts.go#L59 - // - // The bn256Pairing precompiled takes an input of size N * 192 (a - // set of pairs of elements (g1, g2) \in G1 x G2 has a size of - // 192bytes), and carries out a pairing check (not a pairing!) (ie: - // the result is a boolean, not an element in G_T). - // - // As a consequence, and looking in the Cloudflare bn256 library - // used in Geth, we see that the PairingCheck function runs a Miller - // loop on every given pair of elements (g1, g2) \in G1 x G2, - // multiplies the result of the miller loops and runs - // finalExponentiation to get a result is G_T. If the result - // obtained is ONE then the result of the pairing check is True, - // else False. - // - // Looking at the comments above, we see we can run PairingChecks on - // any number of pairs (g1, g2) \in G1 x G2. To check something in - // the form: e(g1, g2) = e(g'1, g'2), we need to call the - // precompiled bn256Pairing on input [(g1, g2), (neg(g'1), g'2)] - success := call(sub(gas, 2000), 8, 0, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) - // Use "invalid" to make gas estimation work - //switch success case 0 { invalid } - } - require( - success, - "Call to the bn256Pairing precompiled failed (probably an out of gas error?)" - ); - - return out[0] != 0; - } - - // Convenience method for a pairing check for two pairs. - function pairingProd2( - G1Point memory a1, G2Point memory a2, - G1Point memory b1, G2Point memory b2) - internal - returns (bool) { - G1Point[] memory p1 = new G1Point[](2); - G2Point[] memory p2 = new G2Point[](2); - p1[0] = a1; - p1[1] = b1; - p2[0] = a2; - p2[1] = b2; - return pairing(p1, p2); - } - - // Convenience method for a pairing check for three pairs. - function pairingProd3( - G1Point memory a1, G2Point memory a2, - G1Point memory b1, G2Point memory b2, - G1Point memory c1, G2Point memory c2) - internal - returns (bool) { - G1Point[] memory p1 = new G1Point[](3); - G2Point[] memory p2 = new G2Point[](3); - p1[0] = a1; - p1[1] = b1; - p1[2] = c1; - p2[0] = a2; - p2[1] = b2; - p2[2] = c2; - return pairing(p1, p2); - } - - // Convenience method for a pairing check for 4 pairs. - function pairingProd4( - G1Point memory a1, G2Point memory a2, - G1Point memory b1, G2Point memory b2, - G1Point memory c1, G2Point memory c2, - G1Point memory d1, G2Point memory d2) - internal - returns (bool) { - G1Point[] memory p1 = new G1Point[](4); - G2Point[] memory p2 = new G2Point[](4); - p1[0] = a1; - p1[1] = b1; - p1[2] = c1; - p1[3] = d1; - p2[0] = a2; - p2[1] = b2; - p2[2] = c2; - p2[3] = d2; - return pairing(p1, p2); - } -} diff --git a/zkservice/zkserver/zkserverapp/contract/mixer/Pghr13Mixer.sol b/zkservice/zkserver/zkserverapp/contract/mixer/Pghr13Mixer.sol deleted file mode 100644 index 9a18fe4..0000000 --- a/zkservice/zkserver/zkserverapp/contract/mixer/Pghr13Mixer.sol +++ /dev/null @@ -1,282 +0,0 @@ -// Copyright (c) 2015-2020 Clearmatics Technologies Ltd -// -// SPDX-License-Identifier: LGPL-3.0+ - -pragma solidity ^0.5.0; -pragma experimental ABIEncoderV2; - -import "./OTSchnorrVerifier.sol"; -import "./Pairing.sol"; -import "./BaseMixer.sol"; - -contract Pghr13Mixer is BaseMixer { - - struct VerifyingKey { - Pairing.G2Point A; - Pairing.G1Point B; - Pairing.G2Point C; - Pairing.G2Point gamma; - Pairing.G1Point gammaBeta1; - Pairing.G2Point gammaBeta2; - Pairing.G2Point Z; - Pairing.G1Point[] IC; - } - - struct Proof { - Pairing.G1Point A; - Pairing.G1Point A_p; - Pairing.G2Point B; - Pairing.G1Point B_p; - Pairing.G1Point C; - Pairing.G1Point C_p; - Pairing.G1Point K; - Pairing.G1Point H; - } - - VerifyingKey verifyKey; - - // Constructor - constructor( - uint256 mk_depth, - address token, - uint256[2] memory A1, - uint256[2] memory A2, - uint256[2] memory B, - uint256[2] memory C1, - uint256[2] memory C2, - uint256[2] memory gamma1, - uint256[2] memory gamma2, - uint256[2] memory gammaBeta1, - uint256[2] memory gammaBeta2_1, - uint256[2] memory gammaBeta2_2, - uint256[2] memory Z1, - uint256[2] memory Z2, - uint256[] memory IC_coefficients) - BaseMixer(mk_depth, token) - public { - verifyKey.A = Pairing.G2Point(A1[0], A1[1], A2[0], A2[1]); - verifyKey.B = Pairing.G1Point(B[0], B[1]); - verifyKey.C = Pairing.G2Point(C1[0], C1[1], C2[0], C2[1]); - verifyKey.gamma = Pairing.G2Point( - gamma1[0], gamma1[1], gamma2[0], gamma1[1]); - verifyKey.gammaBeta1 = Pairing.G1Point(gammaBeta1[0], gammaBeta1[1]); - verifyKey.gammaBeta2 = Pairing.G2Point( - gammaBeta2_1[0], gammaBeta2_1[1], gammaBeta2_2[0], gammaBeta2_2[1]); - verifyKey.Z = Pairing.G2Point(Z1[0], Z1[1], Z2[0], Z2[1]); - - uint256 i = 0; - while(verifyKey.IC.length != IC_coefficients.length/2) { - verifyKey.IC.push( - Pairing.G1Point(IC_coefficients[i], IC_coefficients[i+1])); - i += 2; - } - } - - // This function allows to mix coins and execute payments in zero knowledge. - // Nb of ciphertexts depends on the JS description (Here 2 inputs) - function mix ( - uint256[2] memory a, - uint256[2] memory a_p, - uint256[2][2] memory b, - uint256[2] memory b_p, - uint256[2] memory c, - uint256[2] memory c_p, - uint256[2] memory h, - uint256[2] memory k, - uint256[4] memory vk, - uint256 sigma, - uint256[nbInputs] memory input, - bytes32 pk_sender, - bytes[jsOut] memory ciphertexts) - public payable { - - // 1. Check the root and the nullifiers - bytes32[jsIn] memory nullifiers; - check_mkroot_nullifiers_hsig_append_nullifiers_state( - vk, input, nullifiers); - - // 2.a Verify the signature on the hash of data_to_be_signed - bytes32 hash_to_be_signed = sha256( - abi.encodePacked( - pk_sender, - // Must be unrolled for now. - ciphertexts[0], - ciphertexts[1], - a, - a_p, - b, - b_p, - c, - c_p, - h, - k, - input - ) - ); - require( - OTSchnorrVerifier.verify( - vk[0], - vk[1], - vk[2], - vk[3], - sigma, - hash_to_be_signed - ), - "Invalid signature: Unable to verify the signature correctly" - ); - - // 2.b Verify the proof - require( - verifyTx(a, a_p, b, b_p, c, c_p, h, k, input), - "Invalid proof: Unable to verify the proof correctly" - ); - - // 3. Append the commitments to the tree - bytes32[jsOut] memory commitments; - assemble_commitments_and_append_to_state(input, commitments); - - // 4. get the public values in Wei and modify the state depending on - // their values - process_public_values(input); - - // 5. Add the new root to the list of existing roots and emit it - bytes32 new_merkle_root = recomputeRoot(jsOut); - add_merkle_root(new_merkle_root); - - // Emit the all Mix data - emit LogMix( - new_merkle_root, - nullifiers, - pk_sender, - commitments, - ciphertexts); - } - - function getIC(uint256 i) public view returns (uint) { - return(verifyKey.IC[i].X); - } - - function getICLen() public view returns (uint) { - return(verifyKey.IC.length); - } - - function verify( - uint256[nbInputs] memory input, - Proof memory proof) - internal - returns (uint) { - VerifyingKey memory vk = verifyKey; - // |I_{in}| == input.length, and vk.IC also contains A_0(s). Thus - // ||vk.IC| == input.length + 1 - require( - input.length + 1 == vk.IC.length, - "Using strong input consistency, and the input length differs from expected" - ); - - // 1. Compute the linear combination - // vk_x := vk_{IC,0} + \sum_{i=1}^{n} x_i * vk_{IC,i}, vk_x ∈ G1 - // - // E(A_{in}(s)) if the encoding of - // A_{in}(s) = \sum_{k ∈ I_{in}} a_k · A_k(s), - // where I_{in} denotes the indices of the input wires. - // - // |I_{in}| = n here as we assume that we have a vector x of inputs of - // size n. - Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); - for (uint256 i = 0; i < input.length; i++) { - vk_x = Pairing.add(vk_x, Pairing.mul(vk.IC[i + 1], input[i])); - } - vk_x = Pairing.add(vk_x, vk.IC[0]); - - // 2. Check the validity of knowledge commitments for A, B, C - // e(π_A, vk_A) = e(π′A, P2), e(vk_B, π_B) - // = e(π′_B, P2), e(vk_C, π_C) - // = e(π′_C, P2), - if (!Pairing.pairingProd2( - proof.A, vk.A, - Pairing.negate(proof.A_p), Pairing.P2()) - ) { - return 1; - } - if (!Pairing.pairingProd2( - vk.B, proof.B, - Pairing.negate(proof.B_p), Pairing.P2()) - ) { - return 2; - } - if (!Pairing.pairingProd2( - proof.C, vk.C, - Pairing.negate(proof.C_p), Pairing.P2()) - ) { - return 3; - } - - // 3. Check same coefficients were used - // e(π_K, vk_γ) = e(vk_x + π_A + π_C, vk_{γβ2}) · e(vk_{γβ1}, π_B) - if (!Pairing.pairingProd3( - proof.K, vk.gamma, - Pairing.negate(Pairing.add(vk_x, Pairing.add(proof.A, proof.C))), vk.gammaBeta2, - Pairing.negate(vk.gammaBeta1), proof.B) - ) { - return 4; - } - - // 4. Check QAP divisibility - // e(vk_x + π_A, π_B) = e(π_H, vk_Z) · e(π_C, P2) - if (!Pairing.pairingProd3( - Pairing.add(vk_x, proof.A), proof.B, - Pairing.negate(proof.H), vk.Z, - Pairing.negate(proof.C), Pairing.P2()) - ) { - return 5; - } - - return 0; - } - - function verifyTx( - uint256[2] memory a, - uint256[2] memory a_p, - uint256[2][2] memory b, - uint256[2] memory b_p, - uint256[2] memory c, - uint256[2] memory c_p, - uint256[2] memory h, - uint256[2] memory k, - uint256[nbInputs] memory primaryInputs) - public - returns (bool) { - // Scalar field characteristic - // solium-disable-next-line - uint256 r = 21888242871839275222246405745257275088548364400416034343698204186575808495617; - - Proof memory proof; - proof.A = Pairing.G1Point(a[0], a[1]); - proof.A_p = Pairing.G1Point(a_p[0], a_p[1]); - proof.B = Pairing.G2Point(b[0][0], b[0][1], b[1][0], b[1][1]); - proof.B_p = Pairing.G1Point(b_p[0], b_p[1]); - proof.C = Pairing.G1Point(c[0], c[1]); - proof.C_p = Pairing.G1Point(c_p[0], c_p[1]); - proof.H = Pairing.G1Point(h[0], h[1]); - proof.K = Pairing.G1Point(k[0], k[1]); - - // uint256[] memory inputValues = new uint256[](primaryInputs.length); - for(uint256 i = 0; i < primaryInputs.length; i++){ - // Make sure that all primary inputs lie in the scalar field - require( - primaryInputs[i] < r, - "Input is not is scalar field" - ); - /* inputValues[i] = primaryInputs[i]; */ - } - - uint256 verification_result = verify(primaryInputs, proof); - if (verification_result != 0) { - /* emit LogVerifier("Failed to verify the transaction"); */ - return false; - } - - /* emit LogVerifier("Proof verification successfull"); */ - return true; - } -} diff --git a/zkservice/zkserver/zkserverapp/contract/mixer/README.md b/zkservice/zkserver/zkserverapp/contract/mixer/README.md deleted file mode 100644 index e84b231..0000000 --- a/zkservice/zkserver/zkserverapp/contract/mixer/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# On-chain verification contracts - -The Byzantium hard fork of Ethereum has introduced [pre-compiled contracts for elliptic curves operations](https://github.com/ethereum/go-ethereum/blob/master/core/vm/contracts.go#L56-L59). - -As we know that a SNARK proof is composed of a few (bilinear) group elements, and that the verification mainly consists -in doing pairing operations to check quadratic equality, one can see that it is now possible to verify SNARK proofs on-chain -(**Assuming that the encoding scheme is compatible with the publicly verifiable setting**, here this is the case because -the SNARK we use, uses exponentiation in a bilinear group as encoding). - -This repository contains all the smart-contracts that are used to carry-out the on-chain verification, and to maintain the -merkle tree of commitments as described in the zerocash paper. diff --git a/zkservice/zkserver/zkserverapp/contract/mixer/abi/Groth16Mixer.abi b/zkservice/zkserver/zkserverapp/contract/mixer/abi/Groth16Mixer.abi deleted file mode 100644 index cea9bbb..0000000 --- a/zkservice/zkserver/zkserverapp/contract/mixer/abi/Groth16Mixer.abi +++ /dev/null @@ -1 +0,0 @@ -[{"inputs": [{"internalType": "uint256", "name": "mk_depth", "type": "uint256"}, {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256[2]", "name": "Alpha", "type": "uint256[2]"}, {"internalType": "uint256[2]", "name": "Beta1", "type": "uint256[2]"}, {"internalType": "uint256[2]", "name": "Beta2", "type": "uint256[2]"}, {"internalType": "uint256[2]", "name": "Delta1", "type": "uint256[2]"}, {"internalType": "uint256[2]", "name": "Delta2", "type": "uint256[2]"}, {"internalType": "uint256[]", "name": "ABC_coords", "type": "uint256[]"}], "payable": false, "stateMutability": "nonpayable", "type": "constructor"}, {"anonymous": false, "inputs": [{"indexed": false, "internalType": "string", "name": "message", "type": "string"}], "name": "LogDebug", "type": "event"}, {"anonymous": false, "inputs": [{"indexed": false, "internalType": "bytes32", "name": "message", "type": "bytes32"}], "name": "LogDebug", "type": "event"}, {"anonymous": false, "inputs": [{"indexed": false, "internalType": "bytes32", "name": "root", "type": "bytes32"}, {"indexed": false, "internalType": "bytes32[2]", "name": "nullifiers", "type": "bytes32[2]"}, {"indexed": false, "internalType": "bytes32[2]", "name": "commitments", "type": "bytes32[2]"}, {"indexed": false, "internalType": "bytes[2]", "name": "ciphertexts", "type": "bytes[2]"}], "name": "LogMix", "type": "event"}, {"constant": true, "inputs": [{"internalType": "uint256[9]", "name": "primary_inputs", "type": "uint256[9]"}], "name": "assemble_hsig", "outputs": [{"internalType": "bytes32", "name": "hsig", "type": "bytes32"}], "payable": false, "stateMutability": "pure", "type": "function"}, {"constant": true, "inputs": [{"internalType": "uint256", "name": "index", "type": "uint256"}, {"internalType": "uint256[9]", "name": "primary_inputs", "type": "uint256[9]"}], "name": "assemble_nullifier", "outputs": [{"internalType": "bytes32", "name": "nf", "type": "bytes32"}], "payable": false, "stateMutability": "pure", "type": "function"}, {"constant": true, "inputs": [{"internalType": "uint256[9]", "name": "primary_inputs", "type": "uint256[9]"}], "name": "assemble_public_values", "outputs": [{"internalType": "uint256", "name": "vpub_in", "type": "uint256"}, {"internalType": "uint256", "name": "vpub_out", "type": "uint256"}], "payable": false, "stateMutability": "pure", "type": "function"}, {"constant": true, "inputs": [], "name": "get_constants", "outputs": [{"internalType": "uint256", "name": "js_in", "type": "uint256"}, {"internalType": "uint256", "name": "js_out", "type": "uint256"}, {"internalType": "uint256", "name": "num_inputs", "type": "uint256"}], "payable": false, "stateMutability": "pure", "type": "function"}, {"constant": false, "inputs": [{"internalType": "bytes32", "name": "commitment", "type": "bytes32"}], "name": "insert", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": false, "inputs": [{"internalType": "uint256[2]", "name": "a", "type": "uint256[2]"}, {"internalType": "uint256[4]", "name": "b", "type": "uint256[4]"}, {"internalType": "uint256[2]", "name": "c", "type": "uint256[2]"}, {"internalType": "uint256[4]", "name": "vk", "type": "uint256[4]"}, {"internalType": "uint256", "name": "sigma", "type": "uint256"}, {"internalType": "uint256[9]", "name": "input", "type": "uint256[9]"}, {"internalType": "bytes[2]", "name": "ciphertexts", "type": "bytes[2]"}], "name": "mix", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function"}, {"constant": true, "inputs": [], "name": "token", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": true, "inputs": [{"internalType": "address", "name": "from", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}, {"internalType": "bytes", "name": "data", "type": "bytes"}], "name": "tokenFallback", "outputs": [], "payable": false, "stateMutability": "pure", "type": "function"}] \ No newline at end of file diff --git a/zkservice/zkserver/zkserverapp/contract/mixer/abi/Groth16Mixer.bin b/zkservice/zkserver/zkserverapp/contract/mixer/abi/Groth16Mixer.bin deleted file mode 100644 index 2449bce..0000000 --- a/zkservice/zkserver/zkserverapp/contract/mixer/abi/Groth16Mixer.bin +++ /dev/null @@ -1 +0,0 @@ -60806040523480156200001157600080fd5b50604051620037d3380380620037d3833981810160405262000037919081019062000685565b878781806005811462000081576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016200007890620008ba565b60405180910390fd5b50620000926200040360201b60201c565b506000806000603f8110620000a357fe5b0154905060016040600083815260200190815260200160002060006101000a81548160ff02191690831515021790555081604260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555061010060fd106200015c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401620001539062000876565b60405180910390fd5b60fd6002800260010160fd610100030260406002020110620001b5576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401620001ac9062000898565b60405180910390fd5b505050604051806040016040528087600060028110620001d157fe5b6020020151815260200187600160028110620001e957fe5b6020020151815250604360000160008201518160000155602082015181600101559050506040518060800160405280866000600281106200022657fe5b60200201518152602001866001600281106200023e57fe5b60200201518152602001856000600281106200025657fe5b60200201518152602001856001600281106200026e57fe5b6020020151815250604360020160008201518160000155602082015181600101556040820151816002015560608201518160030155905050604051806080016040528084600060028110620002bf57fe5b6020020151815260200184600160028110620002d757fe5b6020020151815260200183600060028110620002ef57fe5b60200201518152602001836001600281106200030757fe5b602002015181525060436006016000820151816000015560208201518160010155604082015181600201556060820151816003015590505060008090505b60028251816200035157fe5b046043600a018054905014620003f4576043600a0160405180604001604052808484815181106200037e57fe5b602002602001015181526020018460018501815181106200039b57fe5b602002602001015181525090806001815401808255809150509060018203906000526020600020906002020160009091929091909150600082015181600001556020820151816001015550505060028101905062000345565b505050505050505050620009d9565b60008060001b90508060006002600560020a60020203603f81106200042457fe5b018190555060006002600560020a816200043a57fe5b0490505b600081111562000495576200045f82836200049960201b620016c61760201c565b9150600060028260020203905082600082603f81106200047b57fe5b0181905550600282816200048b57fe5b049150506200043e565b5050565b60007fdec937b7fa8db3de380427a8cc947bfab68514522c3439cfa2e99655098368146000527f30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f00000018284828282088381820984858383098683840909925060005b605a8112156200053457602060002080600052868688838808089350868485099250868488858a8788090909945050600181019050620004f9565b508484868a8888880808089550505050505092915050565b6000815190506200055d81620009a5565b92915050565b600082601f8301126200057557600080fd5b60026200058c62000586826200090a565b620008dc565b91508183856020840282011115620005a357600080fd5b60005b83811015620005d75781620005bc88826200066e565b845260208401935060208301925050600181019050620005a6565b5050505092915050565b600082601f830112620005f357600080fd5b81516200060a62000604826200092d565b620008dc565b915081818352602084019350602081019050838560208402820111156200063057600080fd5b60005b838110156200066457816200064988826200066e565b84526020840193506020830192505060018101905062000633565b5050505092915050565b6000815190506200067f81620009bf565b92915050565b6000806000806000806000806101a0898b031215620006a357600080fd5b6000620006b38b828c016200066e565b9850506020620006c68b828c016200054c565b9750506040620006d98b828c0162000563565b9650506080620006ec8b828c0162000563565b95505060c0620006ff8b828c0162000563565b945050610100620007138b828c0162000563565b935050610140620007278b828c0162000563565b92505061018089015167ffffffffffffffff8111156200074657600080fd5b620007548b828c01620005e1565b9150509295985092959890939650565b600062000773602d8362000956565b91507f41206861736820646967657374206669747320696e20612073696e676c65206660008301527f69656c6420656c656d656e742e000000000000000000000000000000000000006020830152604082019050919050565b6000620007db602b8362000956565b91507f546f6f206d616e7920696e70757420616e64206f7574707574206e6f7465732060008301527f636f6e736964657265642e0000000000000000000000000000000000000000006020830152604082019050919050565b600062000843601f8362000956565b91507f496e76616c696420646570746820696e20426173654d65726b6c6554726565006000830152602082019050919050565b60006020820190508181036000830152620008918162000764565b9050919050565b60006020820190508181036000830152620008b381620007cc565b9050919050565b60006020820190508181036000830152620008d58162000834565b9050919050565b6000604051905081810181811067ffffffffffffffff821117156200090057600080fd5b8060405250919050565b600067ffffffffffffffff8211156200092257600080fd5b602082029050919050565b600067ffffffffffffffff8211156200094557600080fd5b602082029050602081019050919050565b600082825260208201905092915050565b600062000974826200097b565b9050919050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b6000819050919050565b620009b08162000967565b8114620009bc57600080fd5b50565b620009ca816200099b565b8114620009d657600080fd5b50565b612dea80620009e96000396000f3fe60806040526004361061007b5760003560e01c806397e004891161004e57806397e0048914610161578063c0ee0b8a1461017d578063f9eb943f146101a6578063fc0c546a146101d35761007b565b806305ceb93c146100805780631f40927c146100bd5780632d287e43146100fb578063354d06fd14610124575b600080fd5b34801561008c57600080fd5b506100a760048036036100a29190810190611cdb565b6101fe565b6040516100b491906127a6565b60405180910390f35b3480156100c957600080fd5b506100e460048036036100df9190810190611c5f565b61031e565b6040516100f29291906129ed565b60405180910390f35b34801561010757600080fd5b50610122600480360361011d9190810190611c89565b61039b565b005b34801561013057600080fd5b5061014b60048036036101469190810190611c5f565b610420565b60405161015891906127a6565b60405180910390f35b61017b60048036036101769190810190611ba4565b61049e565b005b34801561018957600080fd5b506101a4600480360361019f9190810190611b3d565b6106c0565b005b3480156101b257600080fd5b506101bb6108cb565b6040516101ca93929190612a16565b60405180910390f35b3480156101df57600080fd5b506101e86108ef565b6040516101f5919061272b565b60405180910390f35b600060028310610243576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161023a9061280d565b60405180910390fd5b600060fd610100038460010102604060020201905060fd61010003810160fd10156102a3576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161029a906128ad565b60405180910390fd5b600060fd826002800260010160fd610100030260406002020161010003018560028002600101600260010101600981106102d957fe5b602002015160001b901b901c9050600060fd6101000385876002600101016009811061030157fe5b6020020151901b90508160001c810160001b935050505092915050565b600080600083600280026001016002600101016009811061033b57fe5b602002015190506002800260010160fd610100030281901c905064e8d4a5100067ffffffffffffffff168167ffffffffffffffff1602915064e8d4a5100067ffffffffffffffff16604082901c67ffffffffffffffff1602925050915091565b600560020a603f54106103e3576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016103da9061288d565b60405180910390fd5b6000603f549050603f60008154600101919050819055506000816001600560020a0301905082600082603f811061041657fe5b0181905550505050565b60008060fd60406002026002800260010160fd6101000302604060020201610100030184600280026001016002600101016009811061045b57fe5b602002015160001b901b901c9050600060fd6101000384600280600101016009811061048357fe5b6020020151901b90508160001c810160001b92505050919050565b6104a6611777565b6104b1858483610915565b600060023373ffffffffffffffffffffffffffffffffffffffff16846000600281106104d957fe5b6020020151856001600281106104eb57fe5b60200201518c8c8c8a60405160200161050a97969594939291906126b1565b6040516020818303038152906040526040516105269190612685565b602060405180830381855afa158015610543573d6000803e3d6000fd5b5050506040513d601f19601f820116820180604052506105669190810190611cb2565b90506105ba8660006004811061057857fe5b60200201518760016004811061058a57fe5b60200201518860026004811061059c57fe5b6020020151896003600481106105ae57fe5b60200201518986610b23565b6105f9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016105f09061298d565b60405180910390fd5b61060589898987610bfa565b610644576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063b9061292d565b60405180910390fd5b61064c611777565b6106568582610e03565b60006106626002610e5f565b905061066d81610ec1565b7f36ed7c3f2ecfb5a5226c478b034d33144c060afe361be291e948f861dcddc618818584886040516106a294939291906127c1565b60405180910390a16106b386610ef0565b5050505050505050505050565b6106c8611799565b83816000019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff168152505082816020018181525050818160400181905250600060188360038151811061072457fe5b602001015160f81c60f81b7effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916901c60e01c60108460028151811061078457fe5b602001015160f81c60f81b7effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916901c60e01c6008856001815181106107e457fe5b602001015160f81c60f81b7effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916901c60e01c8560008151811061084257fe5b602001015160f81c60f81b7effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff191660e01c01010190508060e01b82606001907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff191690817bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916815250505050505050565b60008060006002925060029150600160028002600101600260010101019050909192565b604260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b604060008360006009811061092657fe5b602002015160001b815260200190815260200160002060009054906101000a900460ff16610989576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610980906128cd565b60405180910390fd5b60008090505b6002811015610a575760006109a482856101fe565b90506041600082815260200190815260200160002060009054906101000a900460ff1615610a07576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016109fe9061282d565b60405180910390fd5b60016041600083815260200190815260200160002060006101000a81548160ff02191690831515021790555080838360028110610a4057fe5b60200201818152505050808060010191505061098f565b50600060028285604051602001610a6f929190612659565b604051602081830303815290604052604051610a8b9190612685565b602060405180830381855afa158015610aa8573d6000803e3d6000fd5b5050506040513d601f19601f82011682018060405250610acb9190810190611cb2565b90506000610ad884610420565b9050808214610b1c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b13906128ed565b60405180910390fd5b5050505050565b6000610b2d6117f6565b6107d05a038682528560208301528360408301526020608083016060846000600286f150604082018981528860208201526040816060836000600787f1506040836080856000600687f15060016040840152600260608401528560808401526040816060836000600787f150505080600260058110610ba857fe5b602002015181600060058110610bba57fe5b6020020151148015610bed575080600360058110610bd457fe5b602002015181600160058110610be657fe5b6020020151145b9150509695505050505050565b6000807f30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f00000019050610c28611818565b86600060028110610c3557fe5b602002015181600001818152505086600160028110610c5057fe5b602002015181602001818152505085600060048110610c6b57fe5b602002015181604001818152505085600160048110610c8657fe5b602002015181606001818152505085600260048110610ca157fe5b602002015181608001818152505085600360048110610cbc57fe5b60200201518160a001818152505084600060028110610cd757fe5b60200201518160c001818152505084600160028110610cf257fe5b60200201518160e0018181525050606060016002800260010160026001010101604051908082528060200260200182016040528015610d405781602001602082028038833980820191505090505b50905060008090505b60016002800260010160026001010101811015610de85783868260098110610d6d57fe5b602002015110610db2576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610da99061296d565b60405180910390fd5b858160098110610dbe57fe5b6020020151828281518110610dcf57fe5b6020026020010181815250508080600101915050610d49565b50610df381836112a8565b6001149350505050949350505050565b60008090505b6002811015610e5a576000838260010160098110610e2357fe5b602002015160001b905080838360028110610e3a57fe5b602002018181525050610e4c8161039b565b508080600101915050610e09565b505050565b600080603f549050600083603f540390506000600560020a90505b6001811115610ea857610e8e8183856115c5565b809450819350505060028181610ea057fe5b049050610e7a565b600080603f8110610eb557fe5b01549350505050919050565b60016040600083815260200190815260200160002060006101000a81548160ff02191690831515021790555050565b600080610efc8361031e565b91509150600082111561104357600073ffffffffffffffffffffffffffffffffffffffff16604260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610ffb576000604260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690508073ffffffffffffffffffffffffffffffffffffffff166323b872dd3330866040518463ffffffff1660e01b8152600401610fc393929190612746565b600060405180830381600087803b158015610fdd57600080fd5b505af1158015610ff1573d6000803e3d6000fd5b505050505061103e565b81341461103d576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016110349061294d565b60405180910390fd5b5b6110fb565b60003411156110fa5760003373ffffffffffffffffffffffffffffffffffffffff16346040516110729061269c565b60006040518083038185875af1925050503d80600081146110af576040519150601f19603f3d011682016040523d82523d6000602084013e6110b4565b606091505b50509050806110f8576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016110ef9061284d565b60405180910390fd5b505b5b60008111156112a357600073ffffffffffffffffffffffffffffffffffffffff16604260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16146111f4576000604260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690508073ffffffffffffffffffffffffffffffffffffffff1663a9059cbb33846040518363ffffffff1660e01b81526004016111bc92919061277d565b600060405180830381600087803b1580156111d657600080fd5b505af11580156111ea573d6000803e3d6000fd5b50505050506112a2565b60003373ffffffffffffffffffffffffffffffffffffffff168260405161121a9061269c565b60006040518083038185875af1925050503d8060008114611257576040519150601f19603f3d011682016040523d82523d6000602084013e61125c565b606091505b50509050806112a0576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016112979061286d565b60405180910390fd5b505b5b505050565b60006043600a01805490506001845101146112f8576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016112ef9061290d565b60405180910390fd5b61130061185d565b6000600190506107d05a03600a60430183526020832060208701875160200281018254865260018301546020870152600283019250604086015b8183101561138957835481526001840154602082015282516040820152604081606083600060078af160408860808a600060068bf180821688169750505060028401935060208301925061133a565b5050505050806113ce576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016113c5906129cd565b60405180910390fd5b7f198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c260408301527f1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed60608301527f090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b60808301527f12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa60a083015260435460c083015260016043015460e083015260026043015461010083015260036043015461012083015260046043015461014083015260056043015461016083015283516101808301527f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47602085015181810682036101a085015260408601516101c085015260608601516101e0850152608086015161020085015260a086015161022085015260c086015161024085015260e08601516102608501526006604301546102808501526007604301546102a08501526008604301546102c08501526009604301546102e085015260208461030086600060086107d05a03f192505050806115a9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016115a0906129ad565b60405180910390fd5b816000601881106115b657fe5b60200201519250505092915050565b60008060006001860390506000600119861682019050600080600187161461163c576001868401039050611618600082603f81106115ff57fe5b0154600085600202603f811061161157fe5b01546116c6565b60006002600184038161162757fe5b04603f811061163257fe5b0181905550611642565b85830190505b5b8181111561169e5760028103905061167a600082603f811061166157fe5b0154600060018401603f811061167357fe5b01546116c6565b60006002600184038161168957fe5b04603f811061169457fe5b0181905550611643565b600287816116a857fe5b04600260018801816116b657fe5b0494509450505050935093915050565b60007fdec937b7fa8db3de380427a8cc947bfab68514522c3439cfa2e99655098368146000527f30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f00000018284828282088381820984858383098683840909925060005b605a81121561175f57602060002080600052868688838808089350868485099250868488858a8788090909945050600181019050611726565b508484868a8888880808089550505050505092915050565b6040518060400160405280600290602082028038833980820191505090505090565b6040518060800160405280600073ffffffffffffffffffffffffffffffffffffffff168152602001600081526020016060815260200160007bffffffffffffffffffffffffffffffffffffffffffffffffffffffff191681525090565b6040518060a00160405280600590602082028038833980820191505090505090565b60405180610100016040528060008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b604051806103000160405280601890602082028038833980820191505090505090565b60008135905061188f81612d62565b92915050565b600082601f8301126118a657600080fd5b60026118b96118b482612a7a565b612a4d565b9150818360005b838110156118f057813586016118d68882611a80565b8452602084019350602083019250506001810190506118c0565b5050505092915050565b600082601f83011261190b57600080fd5b600261191e61191982612a9c565b612a4d565b9150818385602084028201111561193457600080fd5b60005b83811015611964578161194a8882611b28565b845260208401935060208301925050600181019050611937565b5050505092915050565b600082601f83011261197f57600080fd5b600461199261198d82612abe565b612a4d565b915081838560208402820111156119a857600080fd5b60005b838110156119d857816119be8882611b28565b8452602084019350602083019250506001810190506119ab565b5050505092915050565b600082601f8301126119f357600080fd5b6009611a06611a0182612ae0565b612a4d565b91508183856020840282011115611a1c57600080fd5b60005b83811015611a4c5781611a328882611b28565b845260208401935060208301925050600181019050611a1f565b5050505092915050565b600081359050611a6581612d79565b92915050565b600081519050611a7a81612d79565b92915050565b600082601f830112611a9157600080fd5b8135611aa4611a9f82612b02565b612a4d565b91508082526020830160208301858383011115611ac057600080fd5b611acb838284612d05565b50505092915050565b600082601f830112611ae557600080fd5b8135611af8611af382612b2e565b612a4d565b91508082526020830160208301858383011115611b1457600080fd5b611b1f838284612d05565b50505092915050565b600081359050611b3781612d90565b92915050565b600080600060608486031215611b5257600080fd5b6000611b6086828701611880565b9350506020611b7186828701611b28565b925050604084013567ffffffffffffffff811115611b8e57600080fd5b611b9a86828701611ad4565b9150509250925092565b60008060008060008060006102e0888a031215611bc057600080fd5b6000611bce8a828b016118fa565b9750506040611bdf8a828b0161196e565b96505060c0611bf08a828b016118fa565b955050610100611c028a828b0161196e565b945050610180611c148a828b01611b28565b9350506101a0611c268a828b016119e2565b9250506102c088013567ffffffffffffffff811115611c4457600080fd5b611c508a828b01611895565b91505092959891949750929550565b60006101208284031215611c7257600080fd5b6000611c80848285016119e2565b91505092915050565b600060208284031215611c9b57600080fd5b6000611ca984828501611a56565b91505092915050565b600060208284031215611cc457600080fd5b6000611cd284828501611a6b565b91505092915050565b6000806101408385031215611cef57600080fd5b6000611cfd85828601611b28565b9250506020611d0e858286016119e2565b9150509250929050565b6000611d248383611fba565b60208301905092915050565b6000611d3c8383611fd8565b60208301905092915050565b6000611d548383612018565b905092915050565b6000611d688383612633565b60208301905092915050565b611d7d81612ccf565b82525050565b611d8c81612c89565b82525050565b611d9b81612b8c565b611da58184612c1a565b9250611db082612b5a565b8060005b83811015611de1578151611dc88782611d18565b9650611dd383612bd9565b925050600181019050611db4565b505050505050565b611df281612b8c565b611dfc8184612c25565b9250611e0782612b5a565b8060005b83811015611e38578151611e1f8782611d30565b9650611e2a83612bd9565b925050600181019050611e0b565b505050505050565b6000611e4b82612b97565b611e558185612c30565b935083602082028501611e6785612b64565b8060005b85811015611ea35784840389528151611e848582611d48565b9450611e8f83612be6565b925060208a01995050600181019050611e6b565b50829750879550505050505092915050565b611ebe81612ba2565b611ec88184612c3b565b9250611ed382612b6e565b8060005b83811015611f04578151611eeb8782611d5c565b9650611ef683612bf3565b925050600181019050611ed7565b505050505050565b611f1581612bad565b611f1f8184612c46565b9250611f2a82612b78565b8060005b83811015611f5b578151611f428782611d5c565b9650611f4d83612c00565b925050600181019050611f2e565b505050505050565b611f6c81612bb8565b611f768184612c51565b9250611f8182612b82565b8060005b83811015611fb2578151611f998782611d5c565b9650611fa483612c0d565b925050600181019050611f85565b505050505050565b611fc381612c9b565b82525050565b611fd281612c9b565b82525050565b611fe181612c9b565b82525050565b6000611ff282612bce565b611ffc8185612c6d565b935061200c818560208601612d14565b80840191505092915050565b600061202382612bc3565b61202d8185612c5c565b935061203d818560208601612d14565b61204681612d51565b840191505092915050565b600061205c82612bc3565b6120668185612c6d565b9350612076818560208601612d14565b80840191505092915050565b600061208f601883612c78565b91507f6e756c6c696669657220696e646578206f766572666c6f7700000000000000006000830152602082019050919050565b60006120cf603783612c78565b91507f496e76616c6964206e756c6c69666965723a2054686973206e756c6c6966696560008301527f722068617320616c7265616479206265656e20757365640000000000000000006020830152604082019050919050565b6000612135601e83612c78565b91507f767075625f696e2072657475726e207472616e73666572206661696c656400006000830152602082019050919050565b6000612175601883612c78565b91507f767075625f6f7574207472616e73666572206661696c656400000000000000006000830152602082019050919050565b60006121b5602783612c78565b91507f4d65726b6c6520747265652066756c6c3a2043616e6e6f7420617070656e642060008301527f616e796d6f7265000000000000000000000000000000000000000000000000006020830152604082019050919050565b600061221b603083612c78565b91507f6e756c6c6966696572207772697474656e20696e20646966666572656e74207260008301527f6573696475616c2062697420662e652e000000000000000000000000000000006020830152604082019050919050565b6000612281602583612c78565b91507f496e76616c696420726f6f743a205468697320726f6f7420646f65736e27742060008301527f65786973740000000000000000000000000000000000000000000000000000006020830152604082019050919050565b60006122e7604983612c78565b91507f496e76616c696420687369673a2054686973206873696720646f6573206e6f7460008301527f20636f72726573706f6e6420746f207468652068617368206f6620766b20616e60208301527f6420746865206e667300000000000000000000000000000000000000000000006040830152606082019050919050565b6000612373602283612c78565b91507f496e707574206c656e67746820646966666572732066726f6d2065787065637460008301527f65640000000000000000000000000000000000000000000000000000000000006020830152604082019050919050565b60006123d9603383612c78565b91507f496e76616c69642070726f6f663a20556e61626c6520746f207665726966792060008301527f7468652070726f6f6620636f72726563746c79000000000000000000000000006020830152604082019050919050565b600061243f602a83612c78565b91507f57726f6e67206d73672e76616c75653a2056616c75652070616964206973206e60008301527f6f7420636f7272656374000000000000000000000000000000000000000000006020830152604082019050919050565b60006124a5601c83612c78565b91507f496e707574206973206e6f7420696e207363616c6172206669656c64000000006000830152602082019050919050565b60006124e5603b83612c78565b91507f496e76616c6964207369676e61747572653a20556e61626c6520746f2076657260008301527f69667920746865207369676e617475726520636f72726563746c7900000000006020830152604082019050919050565b600061254b600083612c6d565b9150600082019050919050565b6000612565603783612c78565b91507f43616c6c20746f20626e3235364164642c20626e3235365363616c61724d756c60008301527f206f7220626e32353650616972696e67206661696c65640000000000000000006020830152604082019050919050565b60006125cb603983612c78565b91507f43616c6c20746f2074686520626e323536416464206f7220626e32353653636160008301527f6c61724d756c20707265636f6d70696c6564206661696c6564000000000000006020830152604082019050919050565b61262d81612cc5565b82525050565b61263c81612cc5565b82525050565b61265361264e82612cc5565b612d47565b82525050565b60006126658285611de9565b6040820191506126758284611f0c565b6080820191508190509392505050565b60006126918284611fe7565b915081905092915050565b60006126a78261253e565b9150819050919050565b60006126bd828a612642565b6020820191506126cd8289612051565b91506126d98288612051565b91506126e58287611eb5565b6040820191506126f58286611f0c565b6080820191506127058285611eb5565b6040820191506127158284611f63565b6101208201915081905098975050505050505050565b60006020820190506127406000830184611d83565b92915050565b600060608201905061275b6000830186611d74565b6127686020830185611d83565b6127756040830184612624565b949350505050565b60006040820190506127926000830185611d74565b61279f6020830184612624565b9392505050565b60006020820190506127bb6000830184611fc9565b92915050565b600060c0820190506127d66000830187611fc9565b6127e36020830186611d92565b6127f06060830185611d92565b81810360a08301526128028184611e40565b905095945050505050565b6000602082019050818103600083015261282681612082565b9050919050565b60006020820190508181036000830152612846816120c2565b9050919050565b6000602082019050818103600083015261286681612128565b9050919050565b6000602082019050818103600083015261288681612168565b9050919050565b600060208201905081810360008301526128a6816121a8565b9050919050565b600060208201905081810360008301526128c68161220e565b9050919050565b600060208201905081810360008301526128e681612274565b9050919050565b60006020820190508181036000830152612906816122da565b9050919050565b6000602082019050818103600083015261292681612366565b9050919050565b60006020820190508181036000830152612946816123cc565b9050919050565b6000602082019050818103600083015261296681612432565b9050919050565b6000602082019050818103600083015261298681612498565b9050919050565b600060208201905081810360008301526129a6816124d8565b9050919050565b600060208201905081810360008301526129c681612558565b9050919050565b600060208201905081810360008301526129e6816125be565b9050919050565b6000604082019050612a026000830185612624565b612a0f6020830184612624565b9392505050565b6000606082019050612a2b6000830186612624565b612a386020830185612624565b612a456040830184612624565b949350505050565b6000604051905081810181811067ffffffffffffffff82111715612a7057600080fd5b8060405250919050565b600067ffffffffffffffff821115612a9157600080fd5b602082029050919050565b600067ffffffffffffffff821115612ab357600080fd5b602082029050919050565b600067ffffffffffffffff821115612ad557600080fd5b602082029050919050565b600067ffffffffffffffff821115612af757600080fd5b602082029050919050565b600067ffffffffffffffff821115612b1957600080fd5b601f19601f8301169050602081019050919050565b600067ffffffffffffffff821115612b4557600080fd5b601f19601f8301169050602081019050919050565b6000819050919050565b6000819050919050565b6000819050919050565b6000819050919050565b6000819050919050565b600060029050919050565b600060029050919050565b600060029050919050565b600060049050919050565b600060099050919050565b600081519050919050565b600081519050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b600081905092915050565b600081905092915050565b600081905092915050565b600081905092915050565b600081905092915050565b600081905092915050565b600082825260208201905092915050565b600081905092915050565b600082825260208201905092915050565b6000612c9482612ca5565b9050919050565b6000819050919050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b6000819050919050565b6000612cda82612ce1565b9050919050565b6000612cec82612cf3565b9050919050565b6000612cfe82612ca5565b9050919050565b82818337600083830152505050565b60005b83811015612d32578082015181840152602081019050612d17565b83811115612d41576000848401525b50505050565b6000819050919050565b6000601f19601f8301169050919050565b612d6b81612c89565b8114612d7657600080fd5b50565b612d8281612c9b565b8114612d8d57600080fd5b50565b612d9981612cc5565b8114612da457600080fd5b5056fea365627a7a7231582050896d86e76884fde4fc8b2c86258ea7642db8c7044364187de62ad90657faf46c6578706572696d656e74616cf564736f6c63430005110040 \ No newline at end of file diff --git a/zkservice/zkserver/zkserverapp/migrations/0001_initial.py b/zkservice/zkserver/zkserverapp/migrations/0001_initial.py deleted file mode 100644 index 104e8db..0000000 --- a/zkservice/zkserver/zkserverapp/migrations/0001_initial.py +++ /dev/null @@ -1,22 +0,0 @@ -# Generated by Django 3.0.8 on 2020-07-29 02:35 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ] - - operations = [ - migrations.CreateModel( - name='Topic', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('text', models.CharField(max_length=200)), - ('date_added', models.DateTimeField(auto_now_add=True)), - ], - ), - ] diff --git a/zkservice/zkserver/zkserverapp/migrations/0002_entry.py b/zkservice/zkserver/zkserverapp/migrations/0002_entry.py deleted file mode 100644 index ac4b226..0000000 --- a/zkservice/zkserver/zkserverapp/migrations/0002_entry.py +++ /dev/null @@ -1,26 +0,0 @@ -# Generated by Django 3.0.8 on 2020-07-29 02:49 - -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - dependencies = [ - ('zkserverapp', '0001_initial'), - ] - - operations = [ - migrations.CreateModel( - name='Entry', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('text', models.TextField()), - ('date_added', models.DateTimeField(auto_now_add=True)), - ('topic', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zkserverapp.Topic')), - ], - options={ - 'verbose_name_plural': 'entries', - }, - ), - ] diff --git a/zkservice/zkserver/zkserverapp/migrations/0003_auto_20200731_0257.py b/zkservice/zkserver/zkserverapp/migrations/0003_auto_20200731_0257.py deleted file mode 100644 index 1bd4719..0000000 --- a/zkservice/zkserver/zkserverapp/migrations/0003_auto_20200731_0257.py +++ /dev/null @@ -1,29 +0,0 @@ -# Generated by Django 3.0.8 on 2020-07-31 02:57 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('zkserverapp', '0002_entry'), - ] - - operations = [ - migrations.CreateModel( - name='merkletree', - fields=[ - ('mid', models.AutoField(db_column='MID', max_length=11, primary_key=True, serialize=False)), - ('tree_data', models.TextField(db_column='tree_data', max_length=40000)), - ], - options={ - 'db_table': 'merkletree', - }, - ), - migrations.DeleteModel( - name='Entry', - ), - migrations.DeleteModel( - name='Topic', - ), - ] diff --git a/zkservice/zkserver/zkserverapp/migrations/__init__.py b/zkservice/zkserver/zkserverapp/migrations/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/zkservice/zkserver/zkserverapp/models.py b/zkservice/zkserver/zkserverapp/models.py deleted file mode 100644 index b125367..0000000 --- a/zkservice/zkserver/zkserverapp/models.py +++ /dev/null @@ -1,9 +0,0 @@ -from django.db import models - -# Create your models here. -class merkletree(models.Model): - class Meta: - db_table = 'merkletree' - mid = models.AutoField(max_length=11,db_column='MID',primary_key=True) - tree_data = models.TextField(max_length=40000, db_column='tree_data', blank=False) - diff --git a/zkservice/zkserver/zkserverapp/python_web3 b/zkservice/zkserver/zkserverapp/python_web3 deleted file mode 160000 index 7841309..0000000 --- a/zkservice/zkserver/zkserverapp/python_web3 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 78413090e8b825b8b38fc27a9e775e6dc1028dd8 diff --git a/zkservice/zkserver/zkserverapp/routes.py b/zkservice/zkserver/zkserverapp/routes.py deleted file mode 100644 index b433c20..0000000 --- a/zkservice/zkserver/zkserverapp/routes.py +++ /dev/null @@ -1,66 +0,0 @@ -from commands.zeth_gen_fisco_address import gen_fisco_address -from commands.zeth_gen_address import gen_address -from commands.event_sync import event_sync -from commands.zeth_deposit import deposit -from commands.zeth_token_approve import token_approve -from commands.zeth_mix import mix -from commands.zeth_ls_commits import ls_commits -from commands.zeth_ls_notes import ls_notes -from commands.zeth_deploy import deploy -from python_web3.eth_account.account import Account -from commands.constants import USER_DIR, FISCO_ADDRESS_FILE, WALLET_DIR_DEFAULT -from django.shortcuts import render -import json -from django.http import JsonResponse - -''' -The wallet of user is designed as that every wallet need to be specified a username and store the -reference accounts and assets data of that user. There two kinds of account in the wallet of a user, -including Fisco account (saved as keystore) and zbac account (saved as publickey file and privatekey file). -Note that different wallet must have different zbac account but any of them are allowed to have same Fisco -account. -''' - -''' -make wallet by generate a new Fisco account for user with username and password -''' -def genFiscoAddr(request) -> None: - result = {} - req = json.loads(request.body) - (address, publickey) = gen_fisco_address(req['username'], req['password']) - result['address'] = address - result['publickey'] = publickey - JsonResponse(result) - -''' -make wallet by import the Fisco account that the user want to use with privatekey, username and password -''' -def importFiscoAddr(request) -> None: - result = {} - req = json.loads(request.body) - account = Account.privateKeyToAccount(req['privatekey']) - keystore_file = "{}/{}/{}".format(USER_DIR, req['username'], FISCO_ADDRESS_FILE) - if exists(keystore_file): - raise ClickException(f"ZethAddress file {keystore_file} exists") - user_dir = "{}/{}/{}".format(USER_DIR, req['username'], WALLET_DIR_DEFAULT) - _ensure_dir(user_dir) - keytext = Account.encrypt(account.privateKey, req['password']) - with open(keystore_file, "w") as dump_f: - json.dump(keytext, dump_f) - print(f"{req['username']}'s address: {account.address}") - print(f"{req['username']}'s publickey: {account.publickey}") - print(f"fisco account keypair written to {keystore_file}") - result['address'] = account.address - result['publickey'] = account.publickey - JsonResponse(result) - - -''' -generate a new zbac account for user with username, return the zbac address used for recieving notes -''' -def genZbacAddr(request) -> None: - result = {} - req = json.loads(request.body) - zbac_addr = gen_address(req['username']) - result['address'] = zbac_addr - JsonResponse(result) \ No newline at end of file diff --git a/zkservice/zkserver/zkserverapp/tests.py b/zkservice/zkserver/zkserverapp/tests.py deleted file mode 100644 index 7ce503c..0000000 --- a/zkservice/zkserver/zkserverapp/tests.py +++ /dev/null @@ -1,3 +0,0 @@ -from django.test import TestCase - -# Create your tests here. diff --git a/zkservice/zkserver/zkserverapp/urls.py b/zkservice/zkserver/zkserverapp/urls.py deleted file mode 100644 index 9592f8c..0000000 --- a/zkservice/zkserver/zkserverapp/urls.py +++ /dev/null @@ -1,22 +0,0 @@ - -from django.conf.urls import url - -from . import views -from . import routes - - - - - -urlpatterns = [ - - #主页 - - url(r'^$',views.index,name='index'), - url(r'^get\.html$', views.get_html), - url(r'^get$', views.get), - url(r'^post\.html$', views.post_html), - url(r'^post$', views.post), - usr(r'^genFiscoAddr$', routes.genFiscoAddr), - usr(r'^genZbacAddr$', routes.genZbacAddr), -] diff --git a/zkservice/zkserver/zkserverapp/views.py b/zkservice/zkserver/zkserverapp/views.py deleted file mode 100644 index 7e87e21..0000000 --- a/zkservice/zkserver/zkserverapp/views.py +++ /dev/null @@ -1,31 +0,0 @@ -from django.shortcuts import render - -# Create your views here. - -def index(request): - - "学习笔记的主页" - - return render(request,'zkserverapp/template/index.html') - -def get_html(request): - return render(request, 'zkserverapp/template/get.html') - -def get(request): - context = {} - # 通过request.GET['name']形式获取get表单内容 - # result为重定向到的result.html所使用的变量 - context['result'] = f"你搜索的内容为:{request.GET['q']}" - return render(request, 'zkserverapp/template/result.html', context) - -def post_html(request): - # 不能和get一样使用render_to_response必须使用render进行重定向,不然服务端不会设置csrf_token - # return render_to_response('post.html') - return render(request, 'zkserverapp/template/post.html') - -def post(request): - context = {} - # 通过request.GET['name']形式获取post表单内容 - # result为重定向到的result.html所使用的变量 - context['result'] = f"你搜索的内容为:{request.POST['q']}" - return render(request, 'zkserverapp/template/result.html', context) diff --git a/zkservice/zkserver/zkserverapp/zeth/__init__.py b/zkservice/zkserver/zkserverapp/zeth/__init__.py deleted file mode 100644 index 6fb9229..0000000 --- a/zkservice/zkserver/zkserverapp/zeth/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ diff --git a/zkservice/zkserver/zkserverapp/zeth/constants.py b/zkservice/zkserver/zkserverapp/zeth/constants.py deleted file mode 100644 index 4ae3d43..0000000 --- a/zkservice/zkserver/zkserverapp/zeth/constants.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -""" -Constants used by zeth. By convention lengths are given in bits as -`*_LENGTH` and the corresponding `*_LENGTH_BYTES` variable holds the size in -bytes (where this is meaningful). -""" - -from typing import List - - -# Defined here instead of utils.py to avoid circular imports, since utils.py -# depends on some of the values defined here. -def bit_length_to_byte_length(bit_length: int) -> int: - """ - Convert bit length to byte length - """ - assert \ - bit_length >= 0 and bit_length % 8 == 0, \ - "Not valid bit_length inserted" - return int(bit_length/8) - - -# GROTH16 constants -GROTH16_ZKSNARK: str = "GROTH16" -GROTH16_MIXER_CONTRACT: str = "Groth16Mixer" - -# PGHR13 constants -PGHR13_ZKSNARK: str = "PGHR13" -PGHR13_MIXER_CONTRACT: str = "Pghr13Mixer" - -# Set of valid snarks -VALID_ZKSNARKS: List[str] = [GROTH16_ZKSNARK, PGHR13_ZKSNARK] - -# Default zk-snark -ZKSNARK_DEFAULT: str = GROTH16_ZKSNARK - -# Merkle tree depth -ZETH_MERKLE_TREE_DEPTH: int = 5 - -# Nb of input notes -JS_INPUTS: int = 2 - -# Nb of output notes -JS_OUTPUTS: int = 2 - -# Gas cost estimates -DEPLOYMENT_GAS_WEI: int = ZETH_MERKLE_TREE_DEPTH * 250000 - -DEFAULT_MIX_GAS_WEI: int = DEPLOYMENT_GAS_WEI - -# Order of the largest prime order subgroup of the elliptic curve group. See: -# https://github.com/ethereum/go-ethereum/blob/master/crypto/bn256/cloudflare/constants.go#L23 -# # noqa -ZETH_PRIME: int = \ - 21888242871839275222246405745257275088548364400416034343698204186575808495617 - -# Field capacity (=floor(log_2(ZETH_PRIME))) -FIELD_CAPACITY: int = 253 - -# Hash digest length (for commitment and PRFs) -DIGEST_LENGTH: int = 256 - -# Public value length (v_pub_in and v_pub_out) -PUBLIC_VALUE_LENGTH: int = 64 -PUBLIC_VALUE_LENGTH_BYTES: int = bit_length_to_byte_length(PUBLIC_VALUE_LENGTH) -PUBLIC_VALUE_MASK: int = (1 << PUBLIC_VALUE_LENGTH) - 1 - -# Number of residual bits when encoding digests into field values -DIGEST_RESIDUAL_BITS: int = max(0, DIGEST_LENGTH - FIELD_CAPACITY) - -PHI_LENGTH: int = 256 -PHI_LENGTH_BYTES: int = bit_length_to_byte_length(PHI_LENGTH) - -APK_LENGTH: int = 256 -APK_LENGTH_BYTES: int = bit_length_to_byte_length(APK_LENGTH) - -RHO_LENGTH: int = 256 -RHO_LENGTH_BYTES: int = bit_length_to_byte_length(RHO_LENGTH) - -TRAPR_LENGTH: int = 256 -TRAPR_LENGTH_BYTES: int = bit_length_to_byte_length(TRAPR_LENGTH) - -NOTE_LENGTH: int = APK_LENGTH + PUBLIC_VALUE_LENGTH + RHO_LENGTH + TRAPR_LENGTH -NOTE_LENGTH_BYTES: int = bit_length_to_byte_length(NOTE_LENGTH) - -# Public inputs are (see BaseMixer.sol): -# [0 ] - 1 x merkle root -# [1 ] - jsOut x commitment -# [1 + jsOut ] - jsIn x nullifier (partial) -# [1 + jsOut + jsIn ] - 1 x hsig (partial) -# [2 + jsOut + jsIn ] - JsIn x message auth tags (partial) -# [2 + jsOut + 2*jsIn] - 1 x residual bits, v_in, v_out - -# Index (in public inputs) of residual bits -RESIDUAL_BITS_INDEX: int = (2 * JS_INPUTS) + JS_OUTPUTS + 2 - -# Number of full-length digests to be encoded in public inputs -NUM_INPUT_DIGESTS: int = (2 * JS_INPUTS) + 1 - -# Total number of residual bits corresponding to digests in public inputs -TOTAL_DIGEST_RESIDUAL_BITS: int = NUM_INPUT_DIGESTS * DIGEST_RESIDUAL_BITS - -# Solidity compiler version -SOL_COMPILER_VERSION: str = 'v0.5.17' - -# Seed for MIMC -MIMC_MT_SEED: str = "clearmatics_mt_seed" - -# Units for vpub_in and vpub_out, given in Wei. i.e. -# Value (in Wei) = vpub_{in,out} * ZETH_PUBLIC_UNIT_VALUE -ZETH_PUBLIC_UNIT_VALUE: int = 1000000000000 # 1 Szabo (10^12 Wei). diff --git a/zkservice/zkserver/zkserverapp/zeth/contracts.py b/zkservice/zkserver/zkserverapp/zeth/contracts.py deleted file mode 100644 index 1f5c14c..0000000 --- a/zkservice/zkserver/zkserverapp/zeth/contracts.py +++ /dev/null @@ -1,340 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -from __future__ import annotations -from zeth.signing import SigningVerificationKey, Signature, \ - verification_key_as_mix_parameter, verification_key_from_mix_parameter, \ - signature_as_mix_parameter, signature_from_mix_parameter -from zeth.zksnark import IZKSnarkProvider, GenericProof -from zeth.utils import EtherValue, hex_to_int -#from zeth.constants import SOL_COMPILER_VERSION -import json -import solcx -import traceback -from typing import Dict, List, Iterator, Optional, Any - -# Avoid trying to read too much data into memory -SYNC_BLOCKS_PER_BATCH = 10 - -Interface = Dict[str, Any] - - -class MixParameters: - """ - Arguments to the mix call. - """ - def __init__( - self, - extended_proof: GenericProof, - signature_vk: SigningVerificationKey, - signature: Signature, - ciphertexts: List[bytes]): - self.extended_proof = extended_proof - self.signature_vk = signature_vk - self.signature = signature - self.ciphertexts = ciphertexts - - @staticmethod - def from_json(params_json: str) -> MixParameters: - return MixParameters._from_json_dict(json.loads(params_json)) - - def to_json(self) -> str: - return json.dumps(self._to_json_dict()) - - def _to_json_dict(self) -> Dict[str, Any]: - signature_vk_json = [ - str(x) for x in verification_key_as_mix_parameter(self.signature_vk)] - signature_json = str(signature_as_mix_parameter(self.signature)) - ciphertexts_json = [x.hex() for x in self.ciphertexts] - return { - "extended_proof": self.extended_proof, - "signature_vk": signature_vk_json, - "signature": signature_json, - "ciphertexts": ciphertexts_json, - } - - @staticmethod - def _from_json_dict(json_dict: Dict[str, Any]) -> MixParameters: - ext_proof = json_dict["extended_proof"] - signature_pk_param = [int(x) for x in json_dict["signature_vk"]] - signature_pk = verification_key_from_mix_parameter(signature_pk_param) - signature = signature_from_mix_parameter(int(json_dict["signature"])) - ciphertexts = [bytes.fromhex(x) for x in json_dict["ciphertexts"]] - return MixParameters( - ext_proof, signature_pk, signature, ciphertexts) - - -class MixOutputEvents: - """ - Event data for a single joinsplit output. Holds address (in merkle tree), - commitment and ciphertext. - """ - def __init__( - self, commitment: bytes, ciphertext: bytes): - self.commitment = commitment - self.ciphertext = ciphertext - - -class MixResult: - """ - Data structure representing the result of the mix call. - """ - def __init__( - self, - new_merkle_root: bytes, - nullifiers: List[bytes], - output_events: List[MixOutputEvents]): - self.new_merkle_root = new_merkle_root - self.nullifiers = nullifiers - self.output_events = output_events - - -def _event_args_to_mix_result(event_args: Any) -> MixResult: - mix_out_args = zip(event_args.commitments, event_args.ciphertexts) - out_events = [MixOutputEvents(c, ciph) for (c, ciph) in mix_out_args] - return MixResult( - new_merkle_root=event_args.root, - nullifiers=event_args.nullifiers, - output_events=out_events) - -''' -class InstanceDescription: - """ - Minimal data required to instantiate the in-memory interface to a contract. - """ - def __init__(self, address: str, abi: Dict[str, Any]): - self.address = address - self.abi = abi - - def to_json_dict(self) -> Dict[str, Any]: - return { - "address": self.address, - "abi": self.abi - } - - @staticmethod - def from_json_dict(desc_json: Dict[str, Any]) -> InstanceDescription: - return InstanceDescription(desc_json["address"], desc_json["abi"]) - - @staticmethod - def deploy( - web3: Any, - source_file: str, - contract_name: str, - deployer_address: str, - deployment_gas: EtherValue, - compiler_flags: Dict[str, Any] = None, - **kwargs: Any) -> InstanceDescription: - """ - Compile and deploy a contract, returning the live instance and an instance - description (which the caller should save in order to access the - instance in the future). - """ - compiled = InstanceDescription.compile( - source_file, contract_name, compiler_flags) - assert compiled - instance_desc = InstanceDescription.deploy_from_compiled( - web3, deployer_address, deployment_gas, compiled, **kwargs) - print( - f"deploy: contract: {contract_name} " - f"to address: {instance_desc.address}") - return instance_desc - - @staticmethod - def deploy_from_compiled( - web3: Any, - deployer_address: str, - deployment_gas: EtherValue, - compiled: Any, - **kwargs: Any) -> InstanceDescription: - contract = web3.eth.contract( - abi=compiled['abi'], bytecode=compiled['bin']) - tx_hash = contract.constructor(**kwargs).transact({ - 'from': deployer_address, - 'gas': deployment_gas.wei - }) - tx_receipt = web3.eth.waitForTransactionReceipt(tx_hash, 10000) - contract_address = tx_receipt['contractAddress'] - print( - f"deploy: tx_hash={tx_hash[0:8].hex()}, " + - f" gasUsed={tx_receipt.gasUsed}, status={tx_receipt.status}") - return InstanceDescription(contract_address, compiled['abi']) - - @staticmethod - def compile( - source_file: str, - contract_name: str, - compiler_flags: Dict[str, Any] = None) \ - -> Any: - compiled_all = compile_files([source_file], **(compiler_flags or {})) - assert compiled_all - compiled = compiled_all[f"{source_file}:{contract_name}"] - assert compiled - return compiled - - def instantiate(self, web3: Any) -> Any: - """ - Return the instantiated contract - """ - return web3.eth.contract(address=self.address, abi=self.abi) -''' - -def get_block_number(web3: Any) -> int: - return web3.eth.blockNumber - -''' -def install_sol() -> None: - solcx.install_solc(SOL_COMPILER_VERSION) - - -def compile_files(files: List[str], **kwargs: Any) -> Any: - """ - Wrapper around solcx which ensures the required version of the compiler is - used. - """ - solcx.set_solc_version(SOL_COMPILER_VERSION) - return solcx.compile_files(files, optimize=True, **kwargs) -''' - -def mix_parameters_as_contract_arguments( - zksnark: IZKSnarkProvider, - mix_parameters: MixParameters) -> List[Any]: - """ - Convert MixParameters to a list of eth ABI objects which can be passed to - the contract's mix method. - """ - proof_params: List[Any] = zksnark.mixer_proof_parameters( - mix_parameters.extended_proof) - # print("signature_vk ppk : ", mix_parameters.signature_vk.ppk) - # print("signature_vk spk: ", mix_parameters.signature_vk.spk) - # print("signature: ", mix_parameters.signature) - proof_params.extend([ - verification_key_as_mix_parameter(mix_parameters.signature_vk), - signature_as_mix_parameter(mix_parameters.signature), - hex_to_int(mix_parameters.extended_proof["inputs"]), - mix_parameters.ciphertexts - ]) - return proof_params - - -def _create_web3_mixer_call( - zksnark: IZKSnarkProvider, - mixer_instance: Any, - mix_parameters: MixParameters) -> Any: - mix_params_eth = mix_parameters_as_contract_arguments(zksnark, mix_parameters) - return mixer_instance.mix(*mix_params_eth) - -''' -def mix_call( - zksnark: IZKSnarkProvider, - mixer_instance: Any, - mix_parameters: MixParameters, - sender_address: str, - wei_pub_value: int, - call_gas: int) -> bool: - """ - Call the mix method (executes on the RPC host, without creating a - transaction). Returns True if the call succeeds. False, otherwise. - """ - mixer_call = _create_web3_mixer_call(zksnark, mixer_instance, mix_parameters) - try: - mixer_call.call({ - 'from': sender_address, - 'value': wei_pub_value, - 'gas': call_gas - }) - return True - - except ValueError: - print("error executing mix call:") - traceback.print_exc() - - return False -''' - -def mix( - zksnark: IZKSnarkProvider, - mixer_instance: Any, - mix_parameters: MixParameters, - #sender_address: str, - wei_pub_value: int, - call_gas: int) -> str: - """ - Create and broadcast a transaction that calls the mix method of the Mixer - """ - ''' - mixer_call = _create_web3_mixer_call(zksnark, mixer_instance, mix_parameters) - tx_hash = mixer_call.transact({ - 'from': sender_address, - 'value': wei_pub_value, - 'gas': call_gas - }) - ''' - return _create_web3_mixer_call(zksnark, mixer_instance, mix_parameters) - -class LogMixEvent(object): - def __init__( - self, - root: bytes, - nullifiers: bytes(2), - commitments: bytes(2), - ciphertexts: bytes(2)): - self.root = root - self.nullifiers = nullifiers - self.commitments = commitments - self.ciphertexts = ciphertexts - -def parse_mix_call( - mixer_instance: Any, - _tx_receipt: str) -> MixResult: - """ - Get the logs data associated with this mixing - """ - log_mix_filter = mixer_instance.eventFilter("LogMix", {'fromBlock': 'latest'}) - log_mix_events = log_mix_filter.get_all_entries() - mix_results = [_event_args_to_mix_result(ev.args) for ev in log_mix_events] - return mix_results[0] - - -def _next_nullifier_or_none(nullifier_iter: Iterator[bytes]) -> Optional[Any]: - try: - return next(nullifier_iter) - except StopIteration: - return None - - -def get_mix_results( - #web3: Any, - mixer_instance: Any, - receipt: Any - #start_block: int, - #end_block: int - ) -> Iterator[MixResult]: - """ - Iterator for all events generated by 'mix' executions, over some block - range. Batches eth RPC calls to avoid holding huge numbers of events in - memory. - """ - ''' - for batch_start in range(start_block, end_block + 1, SYNC_BLOCKS_PER_BATCH): - # Get mk_root, address and ciphertext filters for - try: - filter_params = { - 'fromBlock': batch_start, - 'toBlock': batch_start + SYNC_BLOCKS_PER_BATCH - 1, - } - log_mix_filter = mixer_instance.eventFilter("LogMix", filter_params) - for log_mix_event in log_mix_filter.get_all_entries(): - yield _event_args_to_mix_result(log_mix_event.args) - - finally: - web3.eth.uninstallFilter(log_mix_filter.filter_id) - ''' - logresult = mixer_instance.data_parser.parse_event_logs(receipt["logs"]) - logMix = logresult[0]['eventdata'] - logMixEvent = LogMixEvent(logMix[0],logMix[1], logMix[2], logMix[3]) - result = _event_args_to_mix_result(logMixEvent) - diff --git a/zkservice/zkserver/zkserverapp/zeth/encryption.py b/zkservice/zkserver/zkserverapp/zeth/encryption.py deleted file mode 100644 index ec7c02f..0000000 --- a/zkservice/zkserver/zkserverapp/zeth/encryption.py +++ /dev/null @@ -1,266 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -""" -Encryption operations for Zeth notes. Supports an `encrypt` operation using -receivers public key, and a `decrypt` operation using the corresponding private -key. `decrypt` fails (except with negligible probability) if the ciphertext was -encrypted with a different public key. - -This implementation makes use of the `cryptography` library with OpenSSL -backend. For the avoidance of doubt, the implementation adheres to the -appropriate standards as follows. (links refer to specific versions of external -libraries, to ensure that line numbers are correct, but the descriptions are -expected to hold for all versions.) - -As described in [Bernstein06], private keys may be generated as 32 random bytes -with bits 0, 1 and 2 of the first byte cleared, bit 7 of the last byte cleared, -and bit 6 of the last byte set. This happens at key generation time. See: - - https://github.com/openssl/openssl/blob/be9d82bb35812ac65cd92316d1ae7c7c75efe9cf/crypto/ec/ecx_meth.c#L81 - -[LangleyN18] describes Poly1305, including the requirement that the "r" value of -the key (r, s) be "clamped". Note that this clamping is carried out by the -cryptography library when the key is generated. See: - - https://github.com/openssl/openssl/blob/master/crypto/poly1305/poly1305.c#L143 - -The specification of the ChaCha20 stream cipher in [LangleyN18] (page 10) -describes the inputs to the encryption functions as a 256-bit key, a 32-bit -counter and a 96-bit nonce. This differs slightly from the signature of the -encryption function in the cryptography library, which accepts a 256-bit key and -128-bit nonce. That is, no counter is mentioned leaving ambiguity as to whether -this data is processed exactly as described in [LangleyN18]. Internally, the -cryptography library treats the first 32-bit word of the nonce as a counter and -increments this as necessary in accordance with [LangleyN18]. See: - - https://github.com/openssl/openssl/blob/be9d82bb35812ac65cd92316d1ae7c7c75efe9cf/crypto/chacha/chacha_enc.c#L128 - https://github.com/openssl/openssl/blob/be9d82bb35812ac65cd92316d1ae7c7c75efe9cf/crypto/evp/e_chacha20_poly1305.c#L95 - -References: - -\\[Bernstein06] - "Curve25519:new Diffie-Hellman speed records" - Daniel J. Bernstein, - International Workshop on Public Key Cryptography, 2006, - - -\\[LangleyN18] - "Chacha20 and poly1305 for ietf protocols." - Adam Langley and Yoav Nir, - RFC 8439, 2018, - -""" - -from zeth.constants import NOTE_LENGTH_BYTES, bit_length_to_byte_length -from cryptography.hazmat.primitives.asymmetric.x25519 \ - import X25519PrivateKey, X25519PublicKey -from cryptography.hazmat.primitives.ciphers import Cipher, algorithms -from cryptography.hazmat.backends import default_backend -from cryptography.hazmat.primitives import hashes, poly1305 -from cryptography.hazmat.primitives.serialization import \ - Encoding, PrivateFormat, PublicFormat, NoEncryption -from cryptography.exceptions import InvalidSignature \ - as cryptography_InvalidSignature -from typing import Tuple, NewType - - -# Internal sizes for the scheme -_SYM_KEY_LENGTH: int = 256 -_SYM_KEY_LENGTH_BYTES: int = bit_length_to_byte_length(_SYM_KEY_LENGTH) - -_MAC_KEY_LENGTH: int = 256 -_MAC_KEY_LENGTH_BYTES: int = bit_length_to_byte_length(_MAC_KEY_LENGTH) - -_KEY_MATERIAL_LENGTH_BYTES: int = _SYM_KEY_LENGTH_BYTES + _MAC_KEY_LENGTH_BYTES - -_TAG_LENGTH: int = 128 -_TAG_LENGTH_BYTES = bit_length_to_byte_length(_TAG_LENGTH) - -_SYM_NONCE_LENGTH: int = 128 -_SYM_NONCE_LENGTH_BYTES: int = bit_length_to_byte_length(_SYM_NONCE_LENGTH) - -# Nonce as 4 32-bit words [counter, nonce, nonce, nonce] (see above). -_SYM_NONCE_VALUE: bytes = b"\x00" * _SYM_NONCE_LENGTH_BYTES - -# Key Derivation Tag "ZethEnc" utf-8 encoding -_KDF_TAG: bytes = b'ZethEnc' - -# Public sizes -EC_PRIVATE_KEY_LENGTH: int = 256 -EC_PUBLIC_KEY_LENGTH: int = 256 -EC_PUBLIC_KEY_LENGTH_BYTES: int = bit_length_to_byte_length(EC_PUBLIC_KEY_LENGTH) -ENCRYPTED_NOTE_LENGTH_BYTES: int = \ - EC_PUBLIC_KEY_LENGTH_BYTES + NOTE_LENGTH_BYTES + _TAG_LENGTH_BYTES - -# Expose the exception type -InvalidSignature = cryptography_InvalidSignature - -# Represents a secret key for encryption -EncryptionSecretKey = NewType('EncryptionSecretKey', object) - - -def generate_encryption_secret_key() -> EncryptionSecretKey: - return EncryptionSecretKey(X25519PrivateKey.generate()) # type: ignore - - -def encode_encryption_secret_key(sk: EncryptionSecretKey) -> bytes: - return sk.private_bytes( # type: ignore - Encoding.Raw, PrivateFormat.Raw, NoEncryption()) - - -def decode_encryption_secret_key(sk_bytes: bytes) -> EncryptionSecretKey: - return EncryptionSecretKey( - X25519PrivateKey.from_private_bytes(sk_bytes)) - - -def encryption_secret_key_as_hex(sk: EncryptionSecretKey) -> str: - return encode_encryption_secret_key(sk).hex() # type: ignore - - -def encryption_secret_key_from_hex(pk_str: str) -> EncryptionSecretKey: - return EncryptionSecretKey( - X25519PrivateKey.from_private_bytes(bytes.fromhex(pk_str))) - - -# Public key for decryption -EncryptionPublicKey = NewType('EncryptionPublicKey', object) - - -def get_encryption_public_key( - enc_secret: EncryptionSecretKey) -> EncryptionPublicKey: - return enc_secret.public_key() # type: ignore - - -def encode_encryption_public_key(pk: EncryptionPublicKey) -> bytes: - return pk.public_bytes(Encoding.Raw, PublicFormat.Raw) # type: ignore - - -def decode_encryption_public_key(pk_data: bytes) -> EncryptionPublicKey: - return EncryptionPublicKey(X25519PublicKey.from_public_bytes(pk_data)) - - -def encryption_public_key_as_hex(pk: EncryptionPublicKey) -> str: - return encode_encryption_public_key(pk).hex() - - -def encryption_public_key_from_hex(pk_str: str) -> EncryptionPublicKey: - return decode_encryption_public_key(bytes.fromhex(pk_str)) - - -class EncryptionKeyPair: - """ - Key-pair for encrypting joinsplit notes. - """ - def __init__(self, k_sk: EncryptionSecretKey, k_pk: EncryptionPublicKey): - self.k_pk: EncryptionPublicKey = k_pk - self.k_sk: EncryptionSecretKey = k_sk - - -def generate_encryption_keypair() -> EncryptionKeyPair: - sk = generate_encryption_secret_key() - return EncryptionKeyPair(sk, get_encryption_public_key(sk)) - - -def encrypt(message: bytes, pk_receiver: EncryptionPublicKey) -> bytes: - """ - Encrypts a string message under a ec25519 public key by using a custom - dhaes-based scheme. See: https://eprint.iacr.org/1999/007 - """ - assert \ - len(message) == NOTE_LENGTH_BYTES, \ - f"expected message length {NOTE_LENGTH_BYTES}, saw {len(message)}" - - # Generate ephemeral keypair - eph_keypair = generate_encryption_keypair() - - # Compute shared secret and eph key - shared_key = _exchange(eph_keypair.k_sk, pk_receiver) - pk_sender_bytes = encode_encryption_public_key(eph_keypair.k_pk) - - # Generate key material - sym_key, mac_key = _kdf(pk_sender_bytes, shared_key) - - # Generate symmetric ciphertext - # Chacha encryption - algorithm = algorithms.ChaCha20(sym_key, _SYM_NONCE_VALUE) - cipher = Cipher(algorithm, mode=None, backend=default_backend()) - encryptor = cipher.encryptor() - sym_ciphertext = encryptor.update(message) - - # Generate mac - mac = poly1305.Poly1305(mac_key) - mac.update(sym_ciphertext) - tag = mac.finalize() - - # Arrange ciphertext - return pk_sender_bytes+sym_ciphertext+tag - - -def decrypt( - encrypted_message: bytes, - sk_receiver: EncryptionSecretKey) -> bytes: - """ - Decrypts a NOTE_LENGTH-byte message by using valid ec25519 private key - objects. See: https://pynacl.readthedocs.io/en/stable/public/ - """ - assert \ - len(encrypted_message) == ENCRYPTED_NOTE_LENGTH_BYTES, \ - "encrypted_message byte-length must be: "+str(ENCRYPTED_NOTE_LENGTH_BYTES) - - assert(isinstance(sk_receiver, X25519PrivateKey)), \ - f"PrivateKey: {sk_receiver} ({type(sk_receiver)})" - - # Compute shared secret - pk_sender_bytes = encrypted_message[:EC_PUBLIC_KEY_LENGTH_BYTES] - pk_sender = decode_encryption_public_key(pk_sender_bytes) - shared_key = _exchange(sk_receiver, pk_sender) - - # Generate key material and recover keys - sym_key, mac_key = _kdf(pk_sender_bytes, shared_key) - - # ct_sym and mac - ct_sym = encrypted_message[ - EC_PUBLIC_KEY_LENGTH_BYTES: - EC_PUBLIC_KEY_LENGTH_BYTES + NOTE_LENGTH_BYTES] - tag = encrypted_message[ - EC_PUBLIC_KEY_LENGTH_BYTES + NOTE_LENGTH_BYTES: - EC_PUBLIC_KEY_LENGTH_BYTES + NOTE_LENGTH_BYTES + _TAG_LENGTH_BYTES] - - # Verify the mac - mac = poly1305.Poly1305(mac_key) - mac.update(ct_sym) - mac.verify(tag) - - # Decrypt sym ciphertext - algorithm = algorithms.ChaCha20(sym_key, _SYM_NONCE_VALUE) - cipher = Cipher(algorithm, mode=None, backend=default_backend()) - decryptor = cipher.decryptor() - message = decryptor.update(ct_sym) - - return message - - -def _exchange(sk: EncryptionSecretKey, pk: EncryptionPublicKey) -> bytes: - return sk.exchange(pk) # type: ignore - - -def _kdf(eph_pk: bytes, shared_key: bytes) -> Tuple[bytes, bytes]: - """ - Key derivation function - """ - # Hashing - key_material = hashes.Hash( - hashes.BLAKE2b(64), - backend=default_backend()) - key_material.update(_KDF_TAG) - key_material.update(eph_pk) - key_material.update(shared_key) - key_material = key_material.finalize() - assert len(key_material) == _KEY_MATERIAL_LENGTH_BYTES - return \ - key_material[:_SYM_KEY_LENGTH_BYTES], \ - key_material[_SYM_KEY_LENGTH_BYTES:] diff --git a/zkservice/zkserver/zkserverapp/zeth/errors.py b/zkservice/zkserver/zkserverapp/zeth/errors.py deleted file mode 100644 index a9fdb28..0000000 --- a/zkservice/zkserver/zkserverapp/zeth/errors.py +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -# Zeth standard error messages -SNARK_NOT_SUPPORTED: str = \ - "Invalid zkSNARK, should be one of ('PGHR13', 'GROTH16')" diff --git a/zkservice/zkserver/zkserverapp/zeth/merkle_tree.py b/zkservice/zkserver/zkserverapp/zeth/merkle_tree.py deleted file mode 100644 index 4f0effc..0000000 --- a/zkservice/zkserver/zkserverapp/zeth/merkle_tree.py +++ /dev/null @@ -1,323 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -from __future__ import annotations -from zeth.mimc import MiMC7 -from os.path import exists, dirname, abspath -import json -import math -from typing import Dict, List, Tuple, Iterator, cast, Any -from commands.constants import MYSQLADDR -APP_DIR = dirname(abspath(__file__)) - -from APP_DIR.models import merkletree - -ZERO_ENTRY = bytes.fromhex( - "0000000000000000000000000000000000000000000000000000000000000000") - -HASH = MiMC7() - - -class MerkleTreeData: - """ - Simple container to be persisted for a client-side Merkle tree. Does not - perform any computation. Layers are ordered from top (smallest) to bottom. - """ - def __init__( - self, - depth: int, - default_values: List[bytes], - layers: List[List[bytes]]): - self.depth = depth - self.default_values = default_values - self.layers = layers - - @staticmethod - def empty_with_depth(depth: int) -> MerkleTreeData: - # Compute default values for each layer - default_values = [ZERO_ENTRY] * (depth + 1) - for i in range(depth - 1, -1, -1): - default_values[i] = MerkleTree.combine( - default_values[i + 1], default_values[i + 1]) - - # Initial layer data (fill the 0-th layer with the default root so it's - # always available). - layers: List[List[bytes]] = [[default_values[0]]] - layers.extend([[] for _ in range(depth)]) - assert len(default_values) == depth + 1 - assert len(layers) == depth + 1 - return MerkleTreeData(depth, default_values, layers) - - @staticmethod - def from_json_dict(json_dict: Dict[str, Any]) -> MerkleTreeData: - depth = cast(int, json_dict["depth"]) - default_values = _to_list_bytes( - cast(List[str], json_dict["default_values"])) - layers = [ - _to_list_bytes(layer) - for layer in cast(List[List[str]], json_dict["layers"])] - return MerkleTreeData(depth, default_values, layers) - - def to_json_dict(self) -> Dict[str, Any]: - return { - "depth": self.depth, - "default_values": _to_list_str(self.default_values), - "layers": [_to_list_str(layer) for layer in self.layers], - } - - -class MerkleTree: - """ - Merkle tree structure matching that used in the mixer contract. Simple - implementation where unpopulated values (zeroes) are also stored. - """ - def __init__(self, tree_data: MerkleTreeData, depth: int): - self.max_num_leaves = pow(2, depth) - self.depth = tree_data.depth - self.tree_data = tree_data - self.num_new_leaves = 0 - - @staticmethod - def empty_with_depth(depth: int) -> MerkleTree: - return MerkleTree(MerkleTreeData.empty_with_depth(depth), depth) - - @staticmethod - def empty_with_size(num_leaves: int) -> MerkleTree: - depth = int(math.log(num_leaves, 2)) - assert pow(2, depth) == num_leaves, f"Non-pow-2 size {num_leaves} given" - return MerkleTree.empty_with_depth(depth) - - @staticmethod - def combine(left: bytes, right: bytes) -> bytes: - result_i = HASH.mimc_mp( - int.from_bytes(left, byteorder='big'), - int.from_bytes(right, byteorder='big')) - return result_i.to_bytes(32, byteorder='big') - - def get_num_entries(self) -> int: - return len(self.tree_data.layers[self.depth]) - - def get_leaf(self, index: int) -> bytes: - leaves = self.tree_data.layers[self.depth] - if index < len(leaves): - return leaves[index] - return ZERO_ENTRY - - def get_leaves(self) -> List[bytes]: - return self.tree_data.layers[self.depth] - - def get_node(self, layer_idx: int, node_idx: int) -> bytes: - assert layer_idx <= self.depth - assert self.num_new_leaves == 0 - layer_idx = self.depth - layer_idx - layer = self.tree_data.layers[layer_idx] - if node_idx < len(layer): - return layer[node_idx] - return self.tree_data.default_values[layer_idx] - - def get_layers(self) -> Iterator[Tuple[bytes, List[bytes]]]: - """ - Public layers iterator. - """ - assert self.num_new_leaves == 0 - return self._get_layers() - - def get_root(self) -> bytes: - assert self.num_new_leaves == 0 - return self.tree_data.layers[0][0] - - def insert(self, value: bytes) -> None: - leaves = self.tree_data.layers[self.depth] - assert len(leaves) < self.max_num_leaves - leaves.append(value) - self.num_new_leaves = self.num_new_leaves + 1 - - def recompute_root(self) -> bytes: - """ - After some new leaves have been added, perform the minimal set of hashes - to recompute the tree, expanding each layer to accommodate new nodes. - """ - if self.num_new_leaves == 0: - return self.get_root() - - layers_it = self._get_layers() - - layer_default, layer = next(layers_it) - end_idx = len(layer) - start_idx = end_idx - self.num_new_leaves - layer_size = self.max_num_leaves - - for parent_default, parent_layer in layers_it: - # Computation for each layer is performed in _recompute_layer, which - # also computes the start and end indices for the next layer in the - # tree. - start_idx, end_idx = _recompute_layer( - layer, - start_idx, - end_idx, - layer_default, - parent_layer) - layer = parent_layer - layer_default = parent_default - layer_size = int(layer_size / 2) - - self.num_new_leaves = 0 - assert len(layer) == 1 - assert layer_size == 1 - return layer[0] - - def _get_layers(self) -> Iterator[Tuple[bytes, List[bytes]]]: - """ - Internal version of layers iterator for use during updating. - With 0-th layer as the leaves (matching the public interface). - """ - default_values = self.tree_data.default_values - layers = self.tree_data.layers - for i in range(self.depth, -1, -1): - yield (default_values[i], layers[i]) - - -def compute_merkle_path(address: int, mk_tree: MerkleTree) -> List[str]: - """ - Given an "address" (index into leaves of a Merkle tree), compute the path to - the root. - """ - merkle_path: List[str] = [] - if address == -1: - return merkle_path - - # Check each bit of address in turn. If it is set, take the left node, - # otherwise take the right node. - for depth in range(mk_tree.depth): - address_bit = address & 0x1 - if address_bit: - merkle_path.append(mk_tree.get_node(depth, address - 1).hex()) - else: - merkle_path.append(mk_tree.get_node(depth, address + 1).hex()) - address = address >> 1 - return merkle_path - - -class PersistentMerkleTree(MerkleTree): - """ - Version of MerkleTree that also supports persistence. - """ - def __init__( - self, filename: str, tree_data: MerkleTreeData, depth: int): - MerkleTree.__init__(self, tree_data, depth) - self.filename = filename - - @staticmethod - def open(filename: str, max_num_leaves: int) -> PersistentMerkleTree: - depth = int(math.log(max_num_leaves, 2)) - assert max_num_leaves == int(math.pow(2, depth)) - if exists(filename): - with open(filename, "r") as tree_f: - json_dict = json.load(tree_f) - tree_data = MerkleTreeData.from_json_dict(json_dict) - assert depth == tree_data.depth - else: - tree_data = MerkleTreeData.empty_with_depth(depth) - - return PersistentMerkleTree(filename, tree_data, depth) - - def save(self) -> None: - with open(self.filename, "w") as tree_f: - json.dump(self.tree_data.to_json_dict(), tree_f) - -class sqlMerkleTree(MerkleTree): - """ - Version of MerkleTree that load the MerkleTree data from mysql. - """ - def __init__( - self, tree_data: MerkleTreeData, depth: int): - MerkleTree.__init__(self, tree_data, depth) - - def open(max_num_leaves: int) -> sqlMerkleTree: - if merkletree.objects.all().count() == 0: - tree_data = MerkleTreeData.empty_with_depth(depth) - else: - result = merkletree.objects.all().last() - print("mysql search result: ", result) - json_dict = json.load(result.tree_data) - tree_data = MerkleTreeData.from_json_dict(json_dict) - assert depth == tree_data.depth - return sqlMerkleTree(tree_data, depth) - - def save(self) -> None: - result = merkletree.objects.all().last() - print("mysql search result: ", result) - json_str = json.dump(self.tree_data.to_json_dict()) - result.tree_data = json_str - result.save() - - -def _leaf_address_to_node_address(address_leaf: int, tree_depth: int) -> int: - """ - Converts the relative address of a leaf to an absolute address in the tree - Important note: The merkle root index is 0 (not 1!) - """ - address = address_leaf + (2 ** tree_depth - 1) - if address > (2 ** (tree_depth + 1) - 1): - return -1 - return address - - -def _recompute_layer( - child_layer: List[bytes], - child_start_idx: int, - child_end_idx: int, - child_default_value: bytes, - parent_layer: List[bytes]) -> Tuple[int, int]: - """ - Recompute nodes in the parent layer that are affected by entries - [child_start_idx, child_end_idx[ in the child layer. If `child_end_idx` is - required in the calculation, the final entry of the child layer is used - (since this contains the default entry for the layer if the tree is not - full). Returns the start and end indices (within the parent layer) of - touched parent nodes. - """ - - # / \ / \ / \ - # Parent: ? ? F G H 0 - # / \ / \ / \ / \ / \ / \ - # Child: ? ? ? ? A B C D E ? ? 0 - # ^ ^ - # child_start_idx child_end_idx - - # Extend the parent layer to ensure it has enough capacity. - new_parent_layer_length = int((child_end_idx + 1) / 2) - parent_layer.extend( - [ZERO_ENTRY] * (new_parent_layer_length - len(parent_layer))) - - # Compute the further right pair to compute, and iterate left until we reach - # `child_idx_rend` (reverse-end). `child_idx_rend` is the `child_start_idx` - # rounded down to the next even number. - child_left_idx_rend = int(child_start_idx / 2) * 2 - - # If the child_end_idx is odd, the first hash must use the child layer's - # default value on the right. - if child_end_idx & 1: - child_left_idx = child_end_idx - 1 - parent_layer[child_left_idx >> 1] = MerkleTree.combine( - child_layer[child_left_idx], child_default_value) - else: - child_left_idx = child_end_idx - - # At this stage, all remaining pairs are populated. Hash pairs and write - # them to the parent layer. - while child_left_idx > child_left_idx_rend: - child_left_idx = child_left_idx - 2 - parent_layer[child_left_idx >> 1] = MerkleTree.combine( - child_layer[child_left_idx], child_layer[child_left_idx + 1]) - - return child_start_idx >> 1, new_parent_layer_length - - -def _to_list_bytes(list_str: List[str]) -> List[bytes]: - return [bytes.fromhex(entry) for entry in list_str] - - -def _to_list_str(list_bytes: List[bytes]) -> List[str]: - return [entry.hex() for entry in list_bytes] diff --git a/zkservice/zkserver/zkserverapp/zeth/mimc.py b/zkservice/zkserver/zkserverapp/zeth/mimc.py deleted file mode 100644 index 37c1f11..0000000 --- a/zkservice/zkserver/zkserverapp/zeth/mimc.py +++ /dev/null @@ -1,66 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -from zeth.constants import ZETH_PRIME, MIMC_MT_SEED -from Crypto.Hash import keccak \ - # pylint: disable=import-error,no-name-in-module,line-too-long #type: ignore -from typing import Optional - - -class MiMC7: - """ - Python implementation of MiMC7 algorithm used in the mixer contract - """ - - def __init__( - self, - seed: str = MIMC_MT_SEED, - prime: int = ZETH_PRIME): - self.prime = prime - self.seed = seed - - def mimc_round(self, message: int, key: int, rc: int) -> int: - xored = (message + key + rc) % self.prime - return xored ** 7 % self.prime - - def mimc_encrypt( - self, - message: int, - ek: int, - seed: Optional[str] = None, - rounds: int = 91) -> int: - seed = seed or self.seed - res = message % self.prime - key = ek % self.prime - - # In the paper the first round constant is set to 0 - res = self.mimc_round(res, key, 0) - - round_constant: int = _keccak_256(_str_to_bytes(seed)) - - for _ in range(rounds - 1): - round_constant = _keccak_256(_int_to_bytes32(round_constant)) - res = self.mimc_round(res, key, round_constant) - - return (res + key) % self.prime - - def mimc_mp(self, x: int, y: int) -> int: - x = x % self.prime - y = y % self.prime - return (self.mimc_encrypt(x, y, self.seed) + x + y) % self.prime - - -def _str_to_bytes(value: str) -> bytes: - return value.encode('ascii') - - -def _int_to_bytes32(value: int) -> bytes: - return value.to_bytes(32, 'big') - - -def _keccak_256(data_bytes: bytes) -> int: - h = keccak.new(digest_bits=256) - h.update(data_bytes) - hashed = h.digest() - return int.from_bytes(hashed, 'big') diff --git a/zkservice/zkserver/zkserverapp/zeth/mixer_client.py b/zkservice/zkserver/zkserverapp/zeth/mixer_client.py deleted file mode 100644 index e5b970a..0000000 --- a/zkservice/zkserver/zkserverapp/zeth/mixer_client.py +++ /dev/null @@ -1,739 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -from __future__ import annotations -import zeth.contracts as contracts -import zeth.constants as constants -from zeth.zeth_address import ZethAddressPub, ZethAddress -from zeth.ownership import OwnershipPublicKey, OwnershipSecretKey, \ - OwnershipKeyPair, ownership_key_as_hex -from zeth.encryption import \ - EncryptionPublicKey, EncryptionSecretKey, InvalidSignature, \ - generate_encryption_keypair, encrypt, decrypt -from zeth.merkle_tree import MerkleTree, compute_merkle_path -import zeth.signing as signing -from zeth.timer import Timer -from zeth.zksnark import \ - IZKSnarkProvider, get_zksnark_provider, GenericProof, GenericVerificationKey -from zeth.utils import EtherValue, get_trusted_setup_dir, \ - hex_digest_to_binary_string, digest_to_binary_string, int64_to_hex, \ - message_to_bytes, eth_address_to_bytes32, eth_uint256_to_int, to_zeth_units, \ - get_contracts_dir -from zeth.prover_client import ProverClient -from api.zeth_messages_pb2 import ZethNote, JoinsplitInput, ProofInputs - -import os -import json -from Crypto import Random -from hashlib import blake2s, sha256 -from typing import Tuple, Dict, List, Callable, Optional, Any - - -ZERO_UNITS_HEX = "0000000000000000" - -# ZethNote binary serialization format: -# [apk : APK_LENGTH_BYTES] -# [value : PUBLIC_VALUE_LENGTH_BYTES] -# [rho : RHO_LENGTH_BYTES] -# [trapr : TRAPR_LENGTH_BYTES] -_APK_OFFSET_BYTES = 0 -_VALUE_OFFSET_BYTES = _APK_OFFSET_BYTES + constants.APK_LENGTH_BYTES -_RHO_OFFSET_BYTES = _VALUE_OFFSET_BYTES + constants.PUBLIC_VALUE_LENGTH_BYTES -_TRAPR_OFFSET_BYTES = _RHO_OFFSET_BYTES + constants.RHO_LENGTH_BYTES -assert _TRAPR_OFFSET_BYTES + constants.TRAPR_LENGTH_BYTES \ - == constants.NOTE_LENGTH_BYTES - -# JoinSplit Signature Keys definitions -JoinsplitSigVerificationKey = signing.SigningVerificationKey -JoinsplitSigSecretKey = signing.SigningSecretKey -JoinsplitSigKeyPair = signing.SigningKeyPair - - -ComputeHSigCB = Callable[[bytes, bytes, JoinsplitSigVerificationKey], bytes] - - -class JoinsplitInputNote: - """ - A ZethNote, along with the nullifier and location in Merkle tree. - """ - - def __init__(self, note: ZethNote, nullifier: str, merkle_location: int): - self.note = note - self.nullifier = nullifier - self.merkle_location = merkle_location - - -def create_zeth_notes( - phi: str, - hsig: bytes, - output0: Tuple[OwnershipPublicKey, int], - output1: Tuple[OwnershipPublicKey, int] -) -> Tuple[ZethNote, ZethNote]: - """ - Create two ordered ZethNotes. This function is used to generate new output - notes. - """ - (recipient0, value0) = output0 - (recipient1, value1) = output1 - - rho0 = _compute_rho_i(phi, hsig, 0) - trap_r0 = trap_r_randomness() - note0 = ZethNote( - apk=ownership_key_as_hex(recipient0), - value=int64_to_hex(value0), - rho=rho0.hex(), - trap_r=trap_r0) - - rho1 = _compute_rho_i(phi, hsig, 1) - trap_r1 = trap_r_randomness() - note1 = ZethNote( - apk=ownership_key_as_hex(recipient1), - value=int64_to_hex(value1), - rho=rho1.hex(), - trap_r=trap_r1) - - return note0, note1 - - -def zeth_note_to_json_dict(zeth_note_grpc_obj: ZethNote) -> Dict[str, str]: - return { - "a_pk": zeth_note_grpc_obj.apk, - "value": zeth_note_grpc_obj.value, - "rho": zeth_note_grpc_obj.rho, - "trap_r": zeth_note_grpc_obj.trap_r, - } - - -def zeth_note_from_json_dict(parsed_zeth_note: Dict[str, str]) -> ZethNote: - note = ZethNote( - apk=parsed_zeth_note["a_pk"], - value=parsed_zeth_note["value"], - rho=parsed_zeth_note["rho"], - trap_r=parsed_zeth_note["trap_r"] - ) - return note - - -def zeth_note_to_bytes(zeth_note_grpc_obj: ZethNote) -> bytes: - apk_bytes = bytes.fromhex(zeth_note_grpc_obj.apk) - value_bytes = bytes.fromhex(zeth_note_grpc_obj.value) - rho_bytes = bytes.fromhex(zeth_note_grpc_obj.rho) - trap_r_bytes = bytes.fromhex(zeth_note_grpc_obj.trap_r) - note_bytes = apk_bytes + value_bytes + rho_bytes + trap_r_bytes - assert len(note_bytes) == (constants.NOTE_LENGTH_BYTES) - return note_bytes - - -def zeth_note_from_bytes(note_bytes: bytes) -> ZethNote: - if len(note_bytes) != (constants.NOTE_LENGTH_BYTES): - raise ValueError( - f"note_bytes len {len(note_bytes)}, " - f"(expected {constants.NOTE_LENGTH_BYTES})") - apk = note_bytes[ - _APK_OFFSET_BYTES:_APK_OFFSET_BYTES + constants.APK_LENGTH_BYTES] - value = note_bytes[ - _VALUE_OFFSET_BYTES: - _VALUE_OFFSET_BYTES + constants.PUBLIC_VALUE_LENGTH_BYTES] - rho = note_bytes[ - _RHO_OFFSET_BYTES:_RHO_OFFSET_BYTES + constants.RHO_LENGTH_BYTES] - trap_r = note_bytes[_TRAPR_OFFSET_BYTES:] - return ZethNote( - apk=apk.hex(), value=value.hex(), rho=rho.hex(), trap_r=trap_r.hex()) - - -def compute_commitment(zeth_note: ZethNote) -> bytes: - """ - Used by the recipient of a payment to recompute the commitment and check - the membership in the tree to confirm the validity of a payment - """ - # inner_k = blake2s(r || a_pk || rho || v) - blake = blake2s() - blake.update(bytes.fromhex(zeth_note.trap_r)) - blake.update(bytes.fromhex(zeth_note.apk)) - blake.update(bytes.fromhex(zeth_note.rho)) - blake.update(bytes.fromhex(zeth_note.value)) - cm = blake.digest() - - cm_field = int.from_bytes(cm, byteorder="big") % constants.ZETH_PRIME - return cm_field.to_bytes(int(constants.DIGEST_LENGTH/8), byteorder="big") - - -def compute_nullifier( - zeth_note: ZethNote, - spending_authority_ask: OwnershipSecretKey) -> bytes: - """ - Returns nf = blake2s(1110 || [a_sk]_252 || rho) - """ - binary_ask = digest_to_binary_string(spending_authority_ask) - first_252bits_ask = binary_ask[:252] - left_leg_bin = "1110" + first_252bits_ask - left_leg = int(left_leg_bin, 2).to_bytes(32, byteorder='big') - blake_hash = blake2s() - blake_hash.update(left_leg) - blake_hash.update(bytes.fromhex(zeth_note.rho)) - return blake_hash.digest() - - -def create_joinsplit_input( - merkle_path: List[str], - address: int, - note: ZethNote, - a_sk: OwnershipSecretKey, - nullifier: bytes) -> JoinsplitInput: - return JoinsplitInput( - merkle_path=merkle_path, - address=address, - note=note, - spending_ask=ownership_key_as_hex(a_sk), - nullifier=nullifier.hex()) - - -def write_verification_key(vk_json: GenericVerificationKey) -> None: - """ - Writes the verification key (object) in a json file - """ - #setup_dir = get_trusted_setup_dir() - filename = "vk.json" - with open(filename, 'w') as outfile: - json.dump(vk_json, outfile) - - -def get_dummy_rho() -> str: - assert (constants.RHO_LENGTH_BYTES << 3) == constants.RHO_LENGTH - return bytes(Random.get_random_bytes(constants.RHO_LENGTH_BYTES)).hex() - - -def get_dummy_input_and_address( - a_pk: OwnershipPublicKey) -> Tuple[int, ZethNote]: - """ - Create a zeth note and address, for use as circuit inputs where there is no - real input. - """ - dummy_note = ZethNote( - apk=ownership_key_as_hex(a_pk), - value=ZERO_UNITS_HEX, - rho=get_dummy_rho(), - trap_r=trap_r_randomness()) - # Note that the Merkle path is not fully checked against the root by the - # circuit since the note value is 0. Hence the address used here is - # arbitrary. - dummy_note_address = 0 - return (dummy_note_address, dummy_note) - - -def compute_joinsplit2x2_inputs( - mk_root: bytes, - input0: Tuple[int, ZethNote], - mk_path0: List[str], - input1: Tuple[int, ZethNote], - mk_path1: List[str], - sender_ask: OwnershipSecretKey, - output0: Tuple[OwnershipPublicKey, int], - output1: Tuple[OwnershipPublicKey, int], - public_in_value_zeth_units: int, - public_out_value_zeth_units: int, - sign_vk: JoinsplitSigVerificationKey, - compute_h_sig_cb: Optional[ComputeHSigCB] = None -) -> ProofInputs: - """ - Create a ProofInput object for joinsplit parameters - """ - (input_address0, input_note0) = input0 - (input_address1, input_note1) = input1 - - input_nullifier0 = compute_nullifier(input_note0, sender_ask) - input_nullifier1 = compute_nullifier(input_note1, sender_ask) - js_inputs: List[JoinsplitInput] = [ - create_joinsplit_input( - mk_path0, input_address0, input_note0, sender_ask, input_nullifier0), - create_joinsplit_input( - mk_path1, input_address1, input_note1, sender_ask, input_nullifier1) - ] - - # Use the specified or default h_sig computation - compute_h_sig_cb = compute_h_sig_cb or compute_h_sig - h_sig = compute_h_sig_cb( - input_nullifier0, - input_nullifier1, - sign_vk) - phi = _phi_randomness() - - output_note0, output_note1 = create_zeth_notes( - phi, - h_sig, - output0, - output1) - - js_outputs = [ - output_note0, - output_note1 - ] - - return ProofInputs( - mk_root=mk_root.hex(), - js_inputs=js_inputs, - js_outputs=js_outputs, - pub_in_value=int64_to_hex(public_in_value_zeth_units), - pub_out_value=int64_to_hex(public_out_value_zeth_units), - h_sig=h_sig.hex(), - phi=phi) - - -class MixerClient: - """ - Interface to operations on the Mixer contract. - """ - def __init__( - self, - #web3: Any, - prover_client: ProverClient, - mixer_instance: Any, - zksnark: IZKSnarkProvider): - self._prover_client = prover_client - #self.web3 = web3 - self._zksnark = zksnark - self.mixer_instance = mixer_instance - - @staticmethod - def open( - #web3: Any, - prover_server_endpoint: str, - mixer_instance: Any) -> MixerClient: - """ - Create a client for an existing Zeth deployment. - """ - return MixerClient( - #web3, - ProverClient(prover_server_endpoint), - mixer_instance, - get_zksnark_provider(constants.ZKSNARK_DEFAULT)) - - ''' - @staticmethod - def deploy( - web3: Any, - prover_server_endpoint: str, - deployer_eth_address: str, - token_address: Optional[str] = None, - deploy_gas: Optional[EtherValue] = None, - zksnark: Optional[IZKSnarkProvider] = None) \ - -> Tuple[MixerClient, contracts.InstanceDescription]: - """ - Deploy Zeth contracts. - """ - print("[INFO] 1. Fetching verification key from the proving server") - zksnark = zksnark or get_zksnark_provider(constants.ZKSNARK_DEFAULT) #Groth16SnarkProvider - prover_client = ProverClient(prover_server_endpoint) #gRPC客户端实例 - vk_obj = prover_client.get_verification_key() - vk_json = zksnark.parse_verification_key(vk_obj) - deploy_gas = deploy_gas or \ - EtherValue(constants.DEPLOYMENT_GAS_WEI, 'wei') - - print("[INFO] 2. Received VK, writing verification key...") - write_verification_key(vk_json) - - print("[INFO] 3. VK written, deploying smart contracts...") - contracts_dir = get_contracts_dir() #../../zeth_contract - mixer_name = zksnark.get_contract_name() #Groth16Mixer - mixer_src = os.path.join(contracts_dir, mixer_name + ".sol") - - verification_key_params = zksnark.verification_key_parameters(vk_json) - mixer_description = contracts.InstanceDescription.deploy( - web3, - mixer_src, - mixer_name, - deployer_eth_address, - deploy_gas, - {}, - mk_depth=constants.ZETH_MERKLE_TREE_DEPTH, - token=token_address or "0x0000000000000000000000000000000000000000", - **verification_key_params) - mixer_instance = mixer_description.instantiate(web3) - client = MixerClient(web3, prover_client, mixer_instance, zksnark) - return client, mixer_description - ''' - def deposit( - self, - mk_tree: MerkleTree, - zeth_address: ZethAddress, - sender_eth_address: str, - eth_amount: EtherValue, - outputs: Optional[List[Tuple[ZethAddressPub, EtherValue]]] = None, - tx_value: Optional[EtherValue] = None - ) -> str: - if not outputs or len(outputs) == 0: - outputs = [(zeth_address.addr_pk, eth_amount)] - return self.joinsplit( - mk_tree, - sender_ownership_keypair=zeth_address.ownership_keypair(), - sender_eth_address=sender_eth_address, - inputs=[], - outputs=outputs, - v_in=eth_amount, - v_out=EtherValue(0), - tx_value=tx_value) - - def joinsplit( - self, - mk_tree: MerkleTree, - sender_ownership_keypair: OwnershipKeyPair, - sender_eth_address: str, - inputs: List[Tuple[int, ZethNote]], - outputs: List[Tuple[ZethAddressPub, EtherValue]], - v_in: EtherValue, - v_out: EtherValue, - tx_value: Optional[EtherValue] = None, - compute_h_sig_cb: Optional[ComputeHSigCB] = None) -> str: - mix_params = self.create_mix_parameters( - mk_tree, - sender_ownership_keypair, - sender_eth_address, - inputs, - outputs, - v_in, - v_out, - compute_h_sig_cb) - - # By default transfer exactly v_in, otherwise allow caller to manually - # specify. - tx_value = tx_value or v_in #如果是deposit eth,则tx_value等于v_in,如果是deposit erc20,则tx_value等于EtherValue(0) - return self.mix( - mix_params, - sender_eth_address, - tx_value.wei, - constants.DEFAULT_MIX_GAS_WEI) - - def create_mix_parameters_keep_signing_key( - self, - mk_tree: MerkleTree, - sender_ownership_keypair: OwnershipKeyPair, - sender_eth_address: str, - inputs: List[Tuple[int, ZethNote]], - outputs: List[Tuple[ZethAddressPub, EtherValue]], - v_in: EtherValue, - v_out: EtherValue, - compute_h_sig_cb: Optional[ComputeHSigCB] = None - ) -> Tuple[contracts.MixParameters, JoinsplitSigKeyPair]: - assert len(inputs) <= constants.JS_INPUTS - assert len(outputs) <= constants.JS_OUTPUTS - - sender_a_sk = sender_ownership_keypair.a_sk - sender_a_pk = sender_ownership_keypair.a_pk - inputs = \ - inputs + \ - [get_dummy_input_and_address(sender_a_pk) - for _ in range(constants.JS_INPUTS - len(inputs))] - mk_root = mk_tree.get_root() - mk_paths = [compute_merkle_path(addr, mk_tree) for addr, _ in inputs] - - # Generate output notes and proof. Dummy outputs are constructed with - # value 0 to an invalid ZethAddressPub, formed from the senders - # a_pk, and an ephemeral k_pk. - dummy_k_pk = generate_encryption_keypair().k_pk - dummy_addr_pk = ZethAddressPub(sender_a_pk, dummy_k_pk) - outputs = \ - outputs + \ - [(dummy_addr_pk, EtherValue(0)) - for _ in range(constants.JS_OUTPUTS - len(outputs))] #根据需要构造dummy output,缺多少个构造多少个 - outputs_with_a_pk = \ - [(zeth_addr.a_pk, to_zeth_units(value)) - for (zeth_addr, value) in outputs] - - # Timer used to time proof-generation round trip time. - timer = Timer.started() - - (output_note1, output_note2, proof_json, signing_keypair) = \ - self.get_proof_joinsplit_2_by_2( - mk_root, - inputs[0], - mk_paths[0], - inputs[1], - mk_paths[1], - sender_a_sk, - outputs_with_a_pk[0], - outputs_with_a_pk[1], - to_zeth_units(v_in), - to_zeth_units(v_out), - compute_h_sig_cb) - - proof_gen_time_s = timer.elapsed_seconds() - print(f"PROOF GEN ROUND TRIP: {proof_gen_time_s} seconds") - - # Encrypt the notes - outputs_and_notes = zip(outputs, [output_note1, output_note2]) - output_notes_with_k_pk = \ - [(note, zeth_addr.k_pk) - for ((zeth_addr, _), note) in outputs_and_notes] - ciphertexts = encrypt_notes(output_notes_with_k_pk) - - # Sign - signature = joinsplit_sign( - signing_keypair, - sender_eth_address, - ciphertexts, - proof_json) - - mix_params = contracts.MixParameters( - proof_json, - signing_keypair.vk, - signature, - ciphertexts) - return mix_params, signing_keypair - - def create_mix_parameters( - self, - mk_tree: MerkleTree, - sender_ownership_keypair: OwnershipKeyPair, - sender_eth_address: str, - inputs: List[Tuple[int, ZethNote]], - outputs: List[Tuple[ZethAddressPub, EtherValue]], - v_in: EtherValue, - v_out: EtherValue, - compute_h_sig_cb: Optional[ComputeHSigCB] = None - ) -> contracts.MixParameters: - mix_params, _sig_keypair = self.create_mix_parameters_keep_signing_key( - mk_tree, - sender_ownership_keypair, - sender_eth_address, - inputs, - outputs, - v_in, - v_out, - compute_h_sig_cb) - return mix_params - - def mix( - self, - mix_params: contracts.MixParameters, - sender_eth_address: str, - wei_pub_value: int, - call_gas: int) -> str: - return contracts.mix( - self._zksnark, - self.mixer_instance, - mix_params, - #sender_eth_address, - wei_pub_value, - call_gas) - ''' - def mix_call( - self, - mix_params: contracts.MixParameters, - sender_eth_address: str, - wei_pub_value: int, - call_gas: int) -> bool: - return contracts.mix_call( - self._zksnark, - self.mixer_instance, - mix_params, - sender_eth_address, - wei_pub_value, - call_gas) - ''' - def get_proof_joinsplit_2_by_2( - self, - mk_root: bytes, - input0: Tuple[int, ZethNote], - mk_path0: List[str], - input1: Tuple[int, ZethNote], - mk_path1: List[str], - sender_ask: OwnershipSecretKey, - output0: Tuple[OwnershipPublicKey, int], - output1: Tuple[OwnershipPublicKey, int], - public_in_value_zeth_units: int, - public_out_value_zeth_units: int, - compute_h_sig_cb: Optional[ComputeHSigCB] = None - ) -> Tuple[ZethNote, ZethNote, Dict[str, Any], JoinsplitSigKeyPair]: - """ - Query the prover server to generate a proof for the given joinsplit - parameters. - """ - signing_keypair = signing.gen_signing_keypair() - proof_input = compute_joinsplit2x2_inputs( - mk_root, - input0, - mk_path0, - input1, - mk_path1, - sender_ask, - output0, - output1, - public_in_value_zeth_units, - public_out_value_zeth_units, - signing_keypair.vk, - compute_h_sig_cb) - proof_obj = self._prover_client.get_proof(proof_input) - proof_json = self._zksnark.parse_proof(proof_obj) - - # Sanity check our unpacking code against the prover server output. - pub_inputs = proof_json["inputs"] - print(f"pub_inputs: {pub_inputs}") - # pub_inputs_bytes = [bytes.fromhex(x) for x in pub_inputs] - (v_in, v_out) = public_inputs_extract_public_values(pub_inputs) - assert public_in_value_zeth_units == v_in - assert public_out_value_zeth_units == v_out - - # We return the zeth notes to be able to spend them later - # and the proof used to create them - return ( - proof_input.js_outputs[0], # pylint: disable=no-member - proof_input.js_outputs[1], # pylint: disable=no-member - proof_json, - signing_keypair) - - -def encrypt_notes( - notes: List[Tuple[ZethNote, EncryptionPublicKey]] -) -> List[bytes]: - """ - Encrypts a set of output notes to be decrypted by the respective receivers. - Returns the ciphertexts corresponding to each note. - """ - - def _encrypt_note(out_note: ZethNote, pub_key: EncryptionPublicKey) -> bytes: - out_note_bytes = zeth_note_to_bytes(out_note) - - return encrypt(out_note_bytes, pub_key) - - ciphertexts = [_encrypt_note(note, pk) for (note, pk) in notes] - return ciphertexts - - -def receive_note( - out_ev: contracts.MixOutputEvents, - receiver_k_sk: EncryptionSecretKey -) -> Optional[Tuple[bytes, ZethNote]]: - """ - Given the receivers secret key, and the event data from a transaction - (encrypted notes), decrypt any that are intended for the receiver. Return - tuples `(, ZethNote)`. Callers should record the - address-in-merkle-tree along with ZethNote information, for convenience - when spending the notes. - """ - try: - plaintext = decrypt(out_ev.ciphertext, receiver_k_sk) - return ( - out_ev.commitment, - zeth_note_from_bytes(plaintext)) - except InvalidSignature: - return None - except ValueError: - return None - - -def _encode_proof_and_inputs(proof_json: GenericProof) -> Tuple[bytes, bytes]: - """ - Given a proof object, compute the hash of the properties excluding "inputs", - and the hash of the "inputs". - """ - - proof_elements: List[int] = [] - for key in proof_json.keys(): - if key != "inputs": - proof_elements.extend(proof_json[key]) - return ( - message_to_bytes(proof_elements), - message_to_bytes(proof_json["inputs"])) - - -def joinsplit_sign( - signing_keypair: JoinsplitSigKeyPair, - sender_eth_address: str, - ciphertexts: List[bytes], - proof_json: GenericProof, -) -> int: - """ - Generate a signature on the hash of the ciphertexts, proofs and - primary inputs. This is used to solve transaction malleability. We chose - to sign the hash and not the values themselves for modularity (to use the - same code regardless of whether GROTH16 or PGHR13 proof system is chosen), - and sign the hash of the ciphers and inputs for consistency. - """ - assert len(ciphertexts) == constants.JS_INPUTS - - # The message to sign consists of (in order): - # - senders Ethereum address - # - ciphertexts - # - proof elements - # - public input elements - h = sha256() - h.update(eth_address_to_bytes32(sender_eth_address)) - for ciphertext in ciphertexts: - h.update(ciphertext) - - proof_bytes, pub_inputs_bytes = _encode_proof_and_inputs(proof_json) - h.update(proof_bytes) - h.update(pub_inputs_bytes) - message_digest = h.digest() - #print("message digest: ", message_digest) - return signing.sign(signing_keypair.sk, message_digest) - - -def compute_h_sig( - nf0: bytes, - nf1: bytes, - sign_vk: JoinsplitSigVerificationKey) -> bytes: - """ - Compute h_sig = sha256(nf0 || nf1 || sign_vk) - Flatten the verification key - """ - h = sha256() - h.update(nf0) - h.update(nf1) - h.update(signing.encode_vk_to_bytes(sign_vk)) - return h.digest() - - -def trap_r_randomness() -> str: - """ - Compute randomness `r` - """ - assert (constants.TRAPR_LENGTH_BYTES << 3) == constants.TRAPR_LENGTH - return bytes(Random.get_random_bytes(constants.TRAPR_LENGTH_BYTES)).hex() - - -def public_inputs_extract_public_values( - public_inputs: List[str]) -> Tuple[int, int]: - """ - Extract (v_in, v_out) from encoded public inputs. Allows client code to - check these properties of MixParameters without needing to know the details - of the structure / packing policy. - """ - residual = eth_uint256_to_int(public_inputs[constants.RESIDUAL_BITS_INDEX]) - residual = residual >> constants.TOTAL_DIGEST_RESIDUAL_BITS - v_out = (residual & constants.PUBLIC_VALUE_MASK) - v_in = \ - (residual >> constants.PUBLIC_VALUE_LENGTH) & constants.PUBLIC_VALUE_MASK - return (v_in, v_out) - - -def _compute_rho_i(phi: str, hsig: bytes, i: int) -> bytes: - """ - Returns rho_i = blake2s(0 || i || 10 || [phi]_252 || hsig) - See: Zcash protocol spec p. 57, Section 5.4.2 Pseudo Random Functions - """ - # [SANITY CHECK] make sure i is in the interval [0, JS_INPUTS]. For now, - # this code also relies on JS_INPUTS being <= 2. - assert i < constants.JS_INPUTS - assert constants.JS_INPUTS <= 2, \ - "function needs updating to support JS_INPUTS > 2" - - blake_hash = blake2s() - - # Append PRF^{rho} tag to a_sk - binary_phi = hex_digest_to_binary_string(phi) - first_252bits_phi = binary_phi[:252] - left_leg_bin = "0" + str(i) + "10" + first_252bits_phi - blake_hash.update(int(left_leg_bin, 2).to_bytes(32, byteorder='big')) - blake_hash.update(hsig) - return blake_hash.digest() - - -def _phi_randomness() -> str: - """ - Compute the transaction randomness "phi", used for computing the new rhoS - """ - return bytes(Random.get_random_bytes(constants.PHI_LENGTH_BYTES)).hex() diff --git a/zkservice/zkserver/zkserverapp/zeth/ownership.py b/zkservice/zkserver/zkserverapp/zeth/ownership.py deleted file mode 100644 index b7c6b01..0000000 --- a/zkservice/zkserver/zkserverapp/zeth/ownership.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -from __future__ import annotations - -from zeth.utils import hex_extend_32bytes, digest_to_binary_string, encode_abi - -from Crypto import Random -from hashlib import blake2s -from typing import NewType - - -# Secret key for proving ownership -OwnershipSecretKey = NewType('OwnershipSecretKey', bytes) - - -# Public key for proving owenership -OwnershipPublicKey = NewType('OwnershipPublicKey', bytes) - - -class OwnershipKeyPair: - """ - Key-pair for ownership proof - """ - def __init__(self, a_sk: OwnershipSecretKey, a_pk: OwnershipPublicKey): - self.a_sk: OwnershipSecretKey = a_sk - self.a_pk: OwnershipPublicKey = a_pk - - -def ownership_key_as_hex(a_sk: bytes) -> str: - """ - Convert either a secret or public ownership key to hex representation of the - underlying 32-byte object. - """ - return hex_extend_32bytes(a_sk.hex()) - - -def ownership_public_key_from_hex(key_hex: str) -> OwnershipPublicKey: - """ - Read an ownership public key from a hex string. - """ - return OwnershipPublicKey(bytes.fromhex(key_hex)) - - -def ownership_secret_key_from_hex(key_hex: str) -> OwnershipSecretKey: - """ - Read an ownership public key from a hex string. - """ - return OwnershipSecretKey(bytes.fromhex(key_hex)) - - -def gen_ownership_keypair() -> OwnershipKeyPair: - a_sk = OwnershipSecretKey(Random.get_random_bytes(32)) - a_pk = _derive_a_pk(a_sk) - keypair = OwnershipKeyPair(a_sk, a_pk) - return keypair - - -def _derive_a_pk(a_sk: OwnershipSecretKey) -> OwnershipPublicKey: - """ - Returns a_pk = blake2s(1100 || [a_sk]_252 || 0^256) - """ - binary_a_sk = digest_to_binary_string(a_sk) - first_252bits_ask = binary_a_sk[:252] - left_leg_bin = "1100" + first_252bits_ask - left_leg_hex = "{0:0>4X}".format(int(left_leg_bin, 2)) - zeroes = "0000000000000000000000000000000000000000000000000000000000000000" - a_pk = blake2s( - encode_abi( - ["bytes32", "bytes32"], - [bytes.fromhex(left_leg_hex), bytes.fromhex(zeroes)]) - ).digest() - return OwnershipPublicKey(a_pk) diff --git a/zkservice/zkserver/zkserverapp/zeth/prover_client.py b/zkservice/zkserver/zkserverapp/zeth/prover_client.py deleted file mode 100644 index 6adbae4..0000000 --- a/zkservice/zkserver/zkserverapp/zeth/prover_client.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -import grpc # type: ignore -from google.protobuf import empty_pb2 -from api.zeth_messages_pb2 import ProofInputs -from api.snark_messages_pb2 import VerificationKey, ExtendedProof -from api import prover_pb2_grpc # type: ignore - - -class ProverClient: - def __init__(self, endpoint: str): - self.endpoint = endpoint - - def get_verification_key(self) -> VerificationKey: - """ - Fetch the verification key from the proving service - """ - with grpc.insecure_channel(self.endpoint) as channel: - stub = prover_pb2_grpc.ProverStub(channel) # type: ignore - print("-------------- Get the verification key --------------") - verificationkey = stub.GetVerificationKey(_make_empty_message()) - return verificationkey - - def get_proof( - self, - proof_inputs: ProofInputs) -> ExtendedProof: - """ - Request a proof generation to the proving service - """ - with grpc.insecure_channel(self.endpoint) as channel: - stub = prover_pb2_grpc.ProverStub(channel) # type: ignore - print("-------------- Get the proof --------------") - proof = stub.Prove(proof_inputs) - return proof - - -def _make_empty_message() -> empty_pb2.Empty: - return empty_pb2.Empty() diff --git a/zkservice/zkserver/zkserverapp/zeth/py.typed b/zkservice/zkserver/zkserverapp/zeth/py.typed deleted file mode 100644 index a0c5d77..0000000 --- a/zkservice/zkserver/zkserverapp/zeth/py.typed +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -# Empty file, required for mypy. \ No newline at end of file diff --git a/zkservice/zkserver/zkserverapp/zeth/signing.py b/zkservice/zkserver/zkserverapp/zeth/signing.py deleted file mode 100644 index 174c127..0000000 --- a/zkservice/zkserver/zkserverapp/zeth/signing.py +++ /dev/null @@ -1,162 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -""" -Implementation of Schnorr-based one-time signature from: "Two-tier -signatures, strongly unforgeable signatures, and Fiat-Shamir without random -oracles" by Bellare and Shoup (https://eprint.iacr.org/2007/273.pdf) over Curve -BN128 -""" - -from math import ceil -from os import urandom -from hashlib import sha256 -from py_ecc import bn128 as ec -from zeth.utils import FQ, G1, g1_to_bytes -from zeth.constants import ZETH_PRIME -from typing import List - - -class SigningVerificationKey: - """ - An OT-Schnorr verification key. - """ - def __init__(self, x_g1: G1, y_g1: G1): - self.ppk = x_g1 - self.spk = y_g1 - - -class SigningSecretKey: - """ - An OT-Schnorr signing key. - """ - def __init__(self, x: FQ, y: FQ, y_g1: G1): - self.psk = x - self.ssk = (y, y_g1) - - -class SigningKeyPair: - """ - An OT-Schnorr signing and verification keypair. - """ - def __init__(self, x: FQ, y: FQ, x_g1: G1, y_g1: G1): - # We include y_g1 in the signing key - self.sk = SigningSecretKey(x, y, y_g1) - self.vk = SigningVerificationKey(x_g1, y_g1) - - -Signature = int - - -def gen_signing_keypair() -> SigningKeyPair: - """ - Return a one-time signature key-pair - composed of elements of F_q and G1. - """ - key_size_byte = ceil(len("{0:b}".format(ZETH_PRIME)) / 8) - x = FQ( - int(bytes(urandom(key_size_byte)).hex(), 16) % ZETH_PRIME) - y = FQ( - int(bytes(urandom(key_size_byte)).hex(), 16) % ZETH_PRIME) - X = ec.multiply(ec.G1, x.n) - Y = ec.multiply(ec.G1, y.n) - return SigningKeyPair(x, y, X, Y) - - -def encode_vk_to_bytes(vk: SigningVerificationKey) -> bytes: - """ - Encode a verification key as a byte string - We assume here the group prime $p$ is written in less than 256 bits - to conform with Ethereum bytes32 type - """ - vk_byte = g1_to_bytes(vk.ppk) - vk_byte += g1_to_bytes(vk.spk) - return vk_byte - - -def encode_signature_to_bytes(signature: Signature) -> bytes: - return signature.to_bytes(32, byteorder='big') - - -def decode_signature_from_bytes(sig_bytes: bytes) -> Signature: - return int.from_bytes(sig_bytes, byteorder='big') - - -def sign( - sk: SigningSecretKey, - m: bytes) -> Signature: - """ - Generate a Schnorr signature on a message m. - We assume here that the message fits in an Ethereum word (i.e. bit_len(m) - <= 256), so that it can be represented by a single bytes32 on the smart- - contract during the signature verification. - """ - - # Encode and hash the verifying key and input hashes - challenge_to_hash = g1_to_bytes(sk.ssk[1]) + m - - # Convert the hex digest into a field element - challenge = int(sha256(challenge_to_hash).hexdigest(), 16) - challenge = challenge % ZETH_PRIME - - # Compute the signature sigma - sigma = (sk.ssk[0].n + challenge * sk.psk.n) % ZETH_PRIME - - return sigma - - -def verify( - vk: SigningVerificationKey, - m: bytes, - sigma: int) -> bool: - """ - Return true if the signature sigma is valid on message m and vk. - We assume here that the message is an hexadecimal string written in - less than 256 bits to conform with Ethereum bytes32 type. - """ - # Encode and hash the verifying key and input hashes - challenge_to_hash = g1_to_bytes(vk.spk) + m - - challenge = int(sha256(challenge_to_hash).hexdigest(), 16) - challenge = challenge % ZETH_PRIME - - left_part = ec.multiply(ec.G1, FQ(sigma).n) - right_part = ec.add(vk.spk, ec.multiply(vk.ppk, FQ(challenge).n)) - - return ec.eq(left_part, right_part) - - -def verification_key_as_mix_parameter(vk: SigningVerificationKey) -> List[int]: - """ - Transform a verification key to the format required by the mix function. - """ - return [int(vk.ppk[0]), int(vk.ppk[1]), int(vk.spk[0]), int(vk.spk[1])] - - -def verification_key_from_mix_parameter( - param: List[int]) -> SigningVerificationKey: - """ - Transform mix function parameter to verification key. - """ - return SigningVerificationKey( - (FQ(param[0]), FQ(param[1])), - (FQ(param[2]), FQ(param[3]))) - - -def signature_as_mix_parameter(signature: Signature) -> int: - """ - Transform a signature to the format required by the mix function. - """ - # This function happens to be the identity but in the general case some - # transform will be required. - return signature - - -def signature_from_mix_parameter(param: int) -> Signature: - """ - Transform mix function parameters to a signature. - """ - return param diff --git a/zkservice/zkserver/zkserverapp/zeth/testing_utils.py b/zkservice/zkserver/zkserverapp/zeth/testing_utils.py deleted file mode 100644 index 8a9583a..0000000 --- a/zkservice/zkserver/zkserverapp/zeth/testing_utils.py +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -from zeth.encryption import generate_encryption_secret_key,\ - encode_encryption_secret_key, get_encryption_public_key,\ - encode_encryption_public_key - -from typing import Tuple, List -from zeth.mimc import MiMC7 - - -def gen_keys_utility( - to_print: bool = False) -> Tuple[List[bytes], List[bytes], List[bytes]]: - """ - Generates private/public keys (kP, k) over Curve25519 for Alice, Bob and - Charlie - """ - - # Alice - sk_alice = generate_encryption_secret_key() - sk_alice_bytes = encode_encryption_secret_key(sk_alice) - pk_alice = get_encryption_public_key(sk_alice) - pk_alice_bytes = encode_encryption_public_key(pk_alice) - - alice_keys_bytes = [pk_alice_bytes, sk_alice_bytes] - - # Bob - sk_bob = generate_encryption_secret_key() - sk_bob_bytes = encode_encryption_secret_key(sk_bob) - pk_bob = get_encryption_public_key(sk_bob) - pk_bob_bytes = encode_encryption_public_key(pk_bob) - - bob_keys_bytes = [pk_bob_bytes, sk_bob_bytes] - - # Charlie - sk_charlie = generate_encryption_secret_key() - sk_charlie_bytes = encode_encryption_secret_key(sk_charlie) - pk_charlie = get_encryption_public_key(sk_charlie) - pk_charlie_bytes = encode_encryption_public_key(pk_charlie) - - charlie_keys_bytes = [pk_charlie_bytes, sk_charlie_bytes] - - if to_print: - print("Alice") - print(pk_alice_bytes) - print(sk_alice_bytes) - - print("Bob") - print(pk_bob_bytes) - print(sk_bob_bytes) - - print("Charlie") - print(pk_charlie_bytes) - print(sk_charlie_bytes) - - return alice_keys_bytes, bob_keys_bytes, charlie_keys_bytes - - -def mimc_encrypt_utility() -> None: - """ - Generates test vector for MiMC encrypt - """ - m = MiMC7() - msg = 3703141493535563179657531719960160174296085208671919316200479060314459804651 # noqa - ek = \ - 15683951496311901749339509118960676303290224812129752890706581988986633412003 # noqa - ct = m.mimc_encrypt(msg, ek) - print("MiMC encrypt test vector:") - print(f"msg = {msg}") - print(f"ek = {ek}") - print(f"ct = {ct}\n") - - -def mimc_mp_utility() -> None: - """ - Generates test vector for MiMC Hash - """ - m = MiMC7() - x = 3703141493535563179657531719960160174296085208671919316200479060314459804651 # noqa - y = 15683951496311901749339509118960676303290224812129752890706581988986633412003 # noqa - - digest = m.mimc_mp(x, y) - print("MiMC MP test vector:") - print(f"x = {x}") - print(f"y = {y}") - print(f"digest = {digest}\n") - - -def mimc_tree_utility() -> None: - """ - # Generates test vectors for testing the MiMC Merkle Tree contract. A - # 16 entry (4 level) merkle tree with 0 values everywhere. - """ - m = MiMC7() - level_3 = m.mimc_mp(0, 0) - level_2 = m.mimc_mp(level_3, level_3) - level_1 = m.mimc_mp(level_2, level_2) - root = m.mimc_mp(level_1, level_1) - - print("MiMC Tree test vector (4 entries, all zero):") - - print(f"Level 2 = {level_3}") - print(f"Level 2 = {level_2}") - print(f"Level 1 = {level_1}") - print(f"Root = {root}\n") diff --git a/zkservice/zkserver/zkserverapp/zeth/timer.py b/zkservice/zkserver/zkserverapp/zeth/timer.py deleted file mode 100644 index c56eadd..0000000 --- a/zkservice/zkserver/zkserverapp/zeth/timer.py +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -from __future__ import annotations -import time -from typing import Optional - - -class Timer: - """ - Very simple class to help measure time. - """ - - def __init__(self) -> None: - self._start_time: Optional[float] = None - - def start(self) -> None: - assert self._start_time is None - self._start_time = time.time() - - @staticmethod - def started() -> Timer: - timer = Timer() - timer.start() - return timer - - def elapsed_seconds(self) -> float: - assert self._start_time is not None - return time.time() - self._start_time diff --git a/zkservice/zkserver/zkserverapp/zeth/utils.py b/zkservice/zkserver/zkserverapp/zeth/utils.py deleted file mode 100644 index 9d33068..0000000 --- a/zkservice/zkserver/zkserverapp/zeth/utils.py +++ /dev/null @@ -1,275 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -# Parse the arguments given to the script - -from __future__ import annotations -from . import constants -from . import errors - -import argparse -import sys -import os -from os.path import join, dirname, normpath -import eth_abi -from web3 import Web3 # type: ignore -from py_ecc import bn128 as ec -from typing import List, Tuple, Union, Any, cast - -# Some Ethereum node implementations can cause a timeout if the contract -# execution takes too long. We expect the contract to complete in under 30s on -# most machines, but allow 1 min. -WEB3_HTTP_PROVIDER_TIMEOUT_SEC = 60 - -''' -def open_web3(url: str) -> Any: - """ - Create a Web3 context from an http URL. - """ - return Web3(HTTPProvider( - url, - request_kwargs={'timeout': WEB3_HTTP_PROVIDER_TIMEOUT_SEC})) -''' - -FQ = ec.FQ -G1 = Tuple[ec.FQ, ec.FQ] - - -class EtherValue: - """ - Representation of some amount of Ether (or any token) in terms of Wei. - Disambiguates Ether values from other units such as zeth_units. - """ - def __init__(self, val: Union[str, int, float], units: str = 'ether'): - self.wei = Web3.toWei(val, units) - - def __str__(self) -> str: - return str(self.wei) - - def __add__(self, other: EtherValue) -> EtherValue: - return EtherValue(self.wei + other.wei, 'wei') - - def __sub__(self, other: EtherValue) -> EtherValue: - return EtherValue(self.wei - other.wei, 'wei') - - def __eq__(self, other: Any) -> bool: - if not isinstance(other, EtherValue): - return False - return self.wei == other.wei - - def __ne__(self, other: Any) -> bool: - return not self.__eq__(other) - - def __lt__(self, other: EtherValue) -> bool: - return self.wei < other.wei - - def __le__(self, other: EtherValue) -> bool: - return self.wei <= other.wei - - def __gt__(self, other: EtherValue) -> bool: - return self.wei > other.wei - - def __ge__(self, other: EtherValue) -> bool: - return self.wei >= other.wei - - def __bool__(self) -> bool: - return int(self.wei) != 0 - - def ether(self) -> str: - return str(Web3.fromWei(self.wei, 'ether')) - - -def encode_single(type_name: str, data: bytes) -> bytes: - """ - Typed wrapper around eth_abi.encode_single - """ - return eth_abi.encode_single(type_name, data) # type: ignore - - -def encode_abi(type_names: List[str], data: List[bytes]) -> bytes: - """ - Typed wrapper around eth_abi.encode_abi - """ - return eth_abi.encode_abi(type_names, data) # type: ignore - - -def eth_address_to_bytes(eth_addr: str) -> bytes: - """ - Binary encoding of ethereum address to 20 bytes - """ - # Strip the leading '0x' and hex-decode. - assert len(eth_addr) == 42 - assert eth_addr.startswith("0x") - return bytes.fromhex(eth_addr[2:]) - - -def eth_address_to_bytes32(eth_addr: str) -> bytes: - """ - Binary encoding of ethereum address to 32 bytes - """ - return extend_32bytes(eth_address_to_bytes(eth_addr)) - - -def eth_uint256_to_int(eth_uint256: str) -> int: - assert isinstance(eth_uint256, str) - assert eth_uint256.startswith("0x") - return int.from_bytes( - bytes.fromhex(hex_extend_32bytes(eth_uint256[2:])), - byteorder='big') - - -def g1_to_bytes(group_el: G1) -> bytes: - """ - Encode a group element into a byte string - We assume here the group prime $p$ is written in less than 256 bits - to conform with Ethereum bytes32 type. - """ - return \ - int(group_el[0]).to_bytes(32, byteorder='big') + \ - int(group_el[1]).to_bytes(32, byteorder='big') - - -def int64_to_bytes(number: int) -> bytes: - return number.to_bytes(8, 'big') - - -def int64_to_hex(number: int) -> str: - return int64_to_bytes(number).hex() - - -def hex_digest_to_binary_string(digest: str) -> str: - if len(digest) % 2 == 1: - digest = "0" + digest - return "".join(["{0:04b}".format(int(c, 16)) for c in digest]) - - -def digest_to_binary_string(digest: bytes) -> str: - return "".join(["{0:08b}".format(b) for b in digest]) - - -def hex_to_int(elements: List[str]) -> List[int]: - """ - Given an array of hex strings, return an array of int values - """ - return [int(x, 16) for x in elements] - - -def extend_32bytes(value: bytes) -> bytes: - """ - Pad value on the left with zeros, to make 32 bytes. - """ - assert len(value) <= 32 - return bytes(32-len(value)) + value - - -def hex_extend_32bytes(element: str) -> str: - """ - Extend a hex string to represent 32 bytes - """ - res = str(element) - if len(res) % 2 != 0: - res = "0" + res - return extend_32bytes(bytes.fromhex(res)).hex() - - -def to_zeth_units(value: EtherValue) -> int: - """ - Convert a quantity of ether / token to Zeth units - """ - return int(value.wei / constants.ZETH_PUBLIC_UNIT_VALUE) - - -def from_zeth_units(zeth_units: int) -> EtherValue: - """ - Convert a quantity of ether / token to Zeth units - """ - return EtherValue(zeth_units * constants.ZETH_PUBLIC_UNIT_VALUE, "wei") - - -def parse_zksnark_arg() -> str: - """ - Parse the zksnark argument and return its value - """ - parser = argparse.ArgumentParser( - description="Testing Zeth transactions using the specified zkSNARK " + - "('GROTH16' or 'PGHR13').\nNote that the zkSNARK must match the one " + - "used on the prover server.") - parser.add_argument("zksnark", help="Set the zkSNARK to use") - args = parser.parse_args() - if args.zksnark not in constants.VALID_ZKSNARKS: - return sys.exit(errors.SNARK_NOT_SUPPORTED) - return args.zksnark - - -def get_zeth_dir() -> str: - return os.environ.get( - 'ZETH', - normpath(join(dirname(__file__), "..", ".."))) - - -def get_trusted_setup_dir() -> str: - return os.environ.get( - 'ZETH_TRUSTED_SETUP_DIR', - join(get_zeth_dir(), "trusted_setup")) - - -def get_contracts_dir() -> str: - return os.environ.get( - 'ZETH_CONTRACTS_DIR', - join(get_zeth_dir(), "zeth_contracts", "contracts")) - - -def string_list_flatten( - strs_list: Union[List[str], List[Union[str, List[str]]]]) -> List[str]: - """ - Flatten a list containing strings or lists of strings. - """ - if any(isinstance(el, (list, tuple)) for el in strs_list): - strs: List[str] = [] - for el in strs_list: - if isinstance(el, (list, tuple)): - strs.extend(el) - else: - strs.append(cast(str, el)) - return strs - - return cast(List[str], strs_list) - - -def message_to_bytes(message_list: Any) -> bytes: - # message_list: Union[List[str], List[Union[int, str, List[str]]]]) -> bytes: - """ - Encode a list of variables, or list of lists of variables into a byte - vector - """ - - messages = string_list_flatten(message_list) - - data_bytes = bytearray() - for m in messages: - # For each element - m_hex = m - - # Convert it into a hex - if isinstance(m, int): - m_hex = "{0:0>4X}".format(m) - elif isinstance(m, str) and (m[1] == "x"): - m_hex = m[2:] - - # [SANITY CHECK] Make sure the hex is 32 byte long - m_hex = hex_extend_32bytes(m_hex) - - # Encode the hex into a byte array and append it to result - data_bytes += encode_single("bytes32", bytes.fromhex(m_hex)) - - return data_bytes - - -def short_commitment(cm: bytes) -> str: - """ - Summary of the commitment value, in some standard format. - """ - return cm[0:4].hex() diff --git a/zkservice/zkserver/zkserverapp/zeth/wallet.py b/zkservice/zkserver/zkserverapp/zeth/wallet.py deleted file mode 100644 index d2d5881..0000000 --- a/zkservice/zkserver/zkserverapp/zeth/wallet.py +++ /dev/null @@ -1,322 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -from __future__ import annotations -from zeth.zeth_address import ZethAddressPriv -from zeth.mixer_client import zeth_note_to_json_dict, zeth_note_from_json_dict, \ - receive_note, compute_nullifier, compute_commitment -from zeth.constants import ZETH_MERKLE_TREE_DEPTH -from zeth.contracts import MixOutputEvents -from zeth.merkle_tree import sqlMerkleTree -from zeth.utils import EtherValue, short_commitment, from_zeth_units -from api.zeth_messages_pb2 import ZethNote -from os.path import join, basename, exists -from os import makedirs -from shutil import move -from typing import Dict, List, Tuple, Optional, Iterator, Any, cast -import glob -import json -import math - - -# pylint: disable=too-many-instance-attributes - -SPENT_SUBDIRECTORY: str = "spent" -MERKLE_TREE_FILE: str = "merkle-tree.dat" - -# Map nullifier to short commitment string identifying the commitment. -NullifierMap = Dict[str, str] - - -class ZethNoteDescription: - """ - All secret data about a single ZethNote, including address in the merkle - tree and the commit value. - """ - def __init__(self, note: ZethNote, address: int, commitment: bytes): - self.note = note - self.address = address - self.commitment = commitment - - def as_input(self) -> Tuple[int, ZethNote]: - """ - Returns the description in a form suitable for joinsplit. - """ - return (self.address, self.note) - - def to_json(self) -> str: - json_dict = { - "note": zeth_note_to_json_dict(self.note), - "address": str(self.address), - "commitment": self.commitment.hex(), - } - return json.dumps(json_dict, indent=4) - - @staticmethod - def from_json(json_str: str) -> ZethNoteDescription: - json_dict = json.loads(json_str) - return ZethNoteDescription( - note=zeth_note_from_json_dict(json_dict["note"]), - address=int(json_dict["address"]), - commitment=bytes.fromhex(json_dict["commitment"])) - - -class WalletState: - """ - State to be saved in the wallet (excluding individual notes). As well as - the next block to query, we store some information about the state of the - Zeth deployment such as the number of notes or the number of distinct - addresses seen. This can be useful to estimate the security of a given - transaction. - """ - def __init__( - self, num_notes: int, nullifier_map: NullifierMap): - #self.next_block = next_block - self.num_notes = num_notes - self.nullifier_map = nullifier_map - - def to_json(self) -> str: - json_dict = { - #"next_block": self.next_block, - "num_notes": self.num_notes, - "nullifier_map": self.nullifier_map, - } - return json.dumps(json_dict, indent=4) - - @staticmethod - def from_json(json_str: str) -> WalletState: - json_dict = json.loads(json_str) - return WalletState( - #next_block=int(json_dict["next_block"]), - num_notes=int(json_dict["num_notes"]), - nullifier_map=cast(NullifierMap, json_dict["nullifier_map"])) - - -def _load_state_or_default(state_file: str) -> WalletState: - if not exists(state_file): - return WalletState(0, {}) - with open(state_file, "r") as state_f: - return WalletState.from_json(state_f.read()) - - -def _save_state(state_file: str, state: WalletState) -> None: - with open(state_file, "w") as state_f: - state_f.write(state.to_json()) - - -class Wallet: - """ - Very simple class to track the list of notes owned by a Zeth user. - - Note: this class does not store the notes in encrypted form, and encodes - some information (including value) in the filename. It is a proof of - concept implementation and NOT intended to be secure against intruders who - have access to the file system. However, we expect that a secure - implementation could expose similar interface and functionality. - """ - def __init__( - self, - mixer_instance: Any, - username: str, - wallet_dir: str, - secret_address: ZethAddressPriv): - # k_sk_receiver: EncryptionSecretKey): - assert "_" not in username - self.mixer_instance = mixer_instance - self.username = username - self.wallet_dir = wallet_dir - self.a_sk = secret_address.a_sk - self.k_sk_receiver = secret_address.k_sk - self.state_file = join(wallet_dir, f"state_{username}") - self.state = _load_state_or_default(self.state_file) - _ensure_dir(join(self.wallet_dir, SPENT_SUBDIRECTORY)) - self.merkle_tree = sqlMerkleTree.open( - join(wallet_dir, MERKLE_TREE_FILE), - int(math.pow(2, ZETH_MERKLE_TREE_DEPTH))) - self.merkle_tree_changed = False - self.next_addr = self.merkle_tree.get_num_entries() - - def receive_note( - self, - comm_addr: int, - out_ev: MixOutputEvents) -> Optional[ZethNoteDescription]: - # Check this output event to see if it belongs to this wallet. - our_note = receive_note(out_ev, self.k_sk_receiver) - if our_note is None: - return None - - (commit, note) = our_note - if not _check_note(commit, note): - return None - - note_desc = ZethNoteDescription(note, comm_addr, commit) - self._write_note(note_desc) - - # Add the nullifier to the map in the state file - nullifier = compute_nullifier(note_desc.note, self.a_sk) - self.state.nullifier_map[nullifier.hex()] = \ - short_commitment(commit) - return note_desc - - def receive_notes( - self, - output_events: List[MixOutputEvents]) -> List[ZethNoteDescription]: - """ - Decrypt any notes we can, verify them as being valid, and store them in - the database. - """ - new_notes = [] - - self.merkle_tree_changed = len(output_events) != 0 - for out_ev in output_events: - print( - f"wallet.receive_notes: idx:{self.next_addr}, " + - f"comm:{out_ev.commitment[:8].hex()}") - - # All commitments must be added to the tree in order. - self.merkle_tree.insert(out_ev.commitment) - note_desc = self.receive_note(self.next_addr, out_ev) - if note_desc is not None: - new_notes.append(note_desc) - - self.next_addr = self.next_addr + 1 - - # Record full set of notes seen to keep an estimate of the total in the - # mixer. - self.state.num_notes = self.state.num_notes + len(output_events) - - return new_notes - - def mark_nullifiers_used(self, nullifiers: List[bytes]) -> List[str]: - """ - Process nullifiers, marking any of our notes that they spend. - """ - commits: List[str] = [] - for nullifier in nullifiers: - nullifier_hex = nullifier.hex() - short_commit = self.state.nullifier_map.get(nullifier_hex, None) - if short_commit: - commits.append(short_commit) - self._mark_note_spent(nullifier_hex, short_commit) - - return commits - - def note_summaries(self) -> Iterator[Tuple[int, str, EtherValue]]: - """ - Returns simple information that can be efficiently read from the notes - store. - """ - return self._decode_note_files_in_dir(self.wallet_dir) - - def spent_note_summaries(self) -> Iterator[Tuple[int, str, EtherValue]]: - """ - Returns simple info from note filenames in the spent directory. - """ - return self._decode_note_files_in_dir( - join(self.wallet_dir, SPENT_SUBDIRECTORY)) - - def get_next_block(self) -> int: - return self.state.next_block - - def update_and_save_state(self) -> None: - #self.state.next_block = next_block - _save_state(self.state_file, self.state) - self._save_merkle_tree_if_changed() - - def find_note(self, note_id: str) -> ZethNoteDescription: - note_file = self._find_note_file(note_id) - if not note_file: - raise Exception(f"no note with id {note_id}") - with open(note_file, "r") as note_f: - return ZethNoteDescription.from_json(note_f.read()) - - def _save_merkle_tree_if_changed(self) -> None: - if self.merkle_tree_changed: - self.merkle_tree_changed = False - self.merkle_tree.recompute_root() - self.merkle_tree.save() - - def _write_note(self, note_desc: ZethNoteDescription) -> None: - """ - Write a note to the database (currently just a file-per-note). - """ - note_filename = join(self.wallet_dir, self._note_basename(note_desc)) - with open(note_filename, "w") as note_f: - note_f.write(note_desc.to_json()) - - def _mark_note_spent(self, nullifier_hex: str, short_commit: str) -> None: - """ - Mark a note as having been spent. Find the file, move it to the `spent` - subdirectory, and remove the entry from the `nullifier_map`. - """ - note_file = self._find_note_file(short_commit) - if note_file is None: - raise Exception(f"expected to find file for commit {short_commit}") - spent_file = \ - join(self.wallet_dir, SPENT_SUBDIRECTORY, basename(note_file)) - move(note_file, spent_file) - del self.state.nullifier_map[nullifier_hex] - - def _note_basename(self, note_desc: ZethNoteDescription) -> str: - value_eth = from_zeth_units(int(note_desc.note.value, 16)).ether() - cm_str = short_commitment(note_desc.commitment) - return "note_%s_%04d_%s_%s" % ( - self.username, note_desc.address, cm_str, value_eth) - - @staticmethod - def _decode_basename(filename: str) -> Tuple[int, str, EtherValue]: - components = filename.split("_") - addr = int(components[2]) - short_commit = components[3] - value = EtherValue(components[4], 'ether') - return (addr, short_commit, value) - - def _decode_note_files_in_dir( - self, dir_name: str) -> Iterator[Tuple[int, str, EtherValue]]: - wildcard = join(dir_name, f"note_{self.username}_*") - filenames = sorted(glob.glob(wildcard)) - for filename in filenames: - try: - yield self._decode_basename(basename(filename)) - # print(f"wallet: _decoded_note_filenames: file={filename}") - except ValueError: - # print(f"wallet: _decoded_note_filenames: FAILED {filename}") - continue - - def _find_note_file(self, key: str) -> Optional[str]: - """ - Given some (fragment of) address or short commit, try to uniquely - identify a note file. - """ - # If len <= 4, assume it's an address, otherwise a commit - if len(key) < 5: - try: - addr = "%04d" % int(key) - wildcard = f"note_{self.username}_{addr}_*" - except Exception: - return None - else: - wildcard = f"note_{self.username}_*_{key}_*" - - candidates = list(glob.glob(join(self.wallet_dir, wildcard))) - return candidates[0] if len(candidates) == 1 else None - - -def _check_note(commit: bytes, note: ZethNote) -> bool: - """ - Recalculate the note commitment and check that it matches `commit`, the - value emitted by the contract. - """ - cm = compute_commitment(note) - if commit != cm: - print(f"WARN: bad commitment commit={commit.hex()}, cm={cm.hex()}") - return False - return True - - -def _ensure_dir(directory_name: str) -> None: - if not exists(directory_name): - makedirs(directory_name) diff --git a/zkservice/zkserver/zkserverapp/zeth/zeth_address.py b/zkservice/zkserver/zkserverapp/zeth/zeth_address.py deleted file mode 100644 index 6a2d27a..0000000 --- a/zkservice/zkserver/zkserverapp/zeth/zeth_address.py +++ /dev/null @@ -1,113 +0,0 @@ -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -from __future__ import annotations -from zeth.ownership import OwnershipPublicKey, OwnershipSecretKey, \ - OwnershipKeyPair, ownership_key_as_hex, gen_ownership_keypair, \ - ownership_public_key_from_hex, ownership_secret_key_from_hex -from zeth.encryption import \ - EncryptionKeyPair, EncryptionPublicKey, EncryptionSecretKey, \ - generate_encryption_keypair, encryption_public_key_as_hex, \ - encryption_public_key_from_hex, encryption_secret_key_as_hex, \ - encryption_secret_key_from_hex -import json -from typing import Dict, Any - - -class ZethAddressPub: - """ - Public half of a zethAddress. addr_pk = (a_pk and k_pk) - """ - def __init__(self, a_pk: OwnershipPublicKey, k_pk: EncryptionPublicKey): - self.a_pk: OwnershipPublicKey = a_pk - self.k_pk: EncryptionPublicKey = k_pk - - def __str__(self) -> str: - """ - Write the address as ":". - (Technically the ":" is not required, since the first key is written - with fixed length, but a separator provides some limited sanity - checking). - """ - a_pk_hex = ownership_key_as_hex(self.a_pk) - k_pk_hex = encryption_public_key_as_hex(self.k_pk) - return f"{a_pk_hex}:{k_pk_hex}" - - @staticmethod - def parse(key_hex: str) -> ZethAddressPub: - owner_enc = key_hex.split(":") - if len(owner_enc) != 2: - raise Exception("invalid JoinSplitPublicKey format") - a_pk = ownership_public_key_from_hex(owner_enc[0]) - k_pk = encryption_public_key_from_hex(owner_enc[1]) - return ZethAddressPub(a_pk, k_pk) - - -class ZethAddressPriv: - """ - Secret half of a zethAddress. addr_sk = (a_sk and k_sk) - """ - def __init__(self, a_sk: OwnershipSecretKey, k_sk: EncryptionSecretKey): - self.a_sk: OwnershipSecretKey = a_sk - self.k_sk: EncryptionSecretKey = k_sk - - def to_json(self) -> str: - return json.dumps(self._to_json_dict()) - - @staticmethod - def from_json(key_json: str) -> ZethAddressPriv: - return ZethAddressPriv._from_json_dict(json.loads(key_json)) - - def _to_json_dict(self) -> Dict[str, Any]: - return { - "a_sk": ownership_key_as_hex(self.a_sk), - "k_sk": encryption_secret_key_as_hex(self.k_sk), - } - - @staticmethod - def _from_json_dict(key_dict: Dict[str, Any]) -> ZethAddressPriv: - return ZethAddressPriv( - ownership_secret_key_from_hex(key_dict["a_sk"]), - encryption_secret_key_from_hex(key_dict["k_sk"])) - - -class ZethAddress: - """ - Secret and public keys for both ownership and encryption (referrred to as - "zethAddress" in the paper). - """ - def __init__( - self, - a_pk: OwnershipPublicKey, - k_pk: EncryptionPublicKey, - a_sk: OwnershipSecretKey, - k_sk: EncryptionSecretKey): - self.addr_pk = ZethAddressPub(a_pk, k_pk) - self.addr_sk = ZethAddressPriv(a_sk, k_sk) - - @staticmethod - def from_key_pairs( - ownership: OwnershipKeyPair, - encryption: EncryptionKeyPair) -> ZethAddress: - return ZethAddress( - ownership.a_pk, - encryption.k_pk, - ownership.a_sk, - encryption.k_sk) - - @staticmethod - def from_secret_public( - js_secret: ZethAddressPriv, - js_public: ZethAddressPub) -> ZethAddress: - return ZethAddress( - js_public.a_pk, js_public.k_pk, js_secret.a_sk, js_secret.k_sk) - - def ownership_keypair(self) -> OwnershipKeyPair: - return OwnershipKeyPair(self.addr_sk.a_sk, self.addr_pk.a_pk) - - -def generate_zeth_address() -> ZethAddress: - ownership_keypair = gen_ownership_keypair() - encryption_keypair = generate_encryption_keypair() - return ZethAddress.from_key_pairs(ownership_keypair, encryption_keypair) diff --git a/zkservice/zkserver/zkserverapp/zeth/zksnark.py b/zkservice/zkserver/zkserverapp/zeth/zksnark.py deleted file mode 100644 index f4a6bff..0000000 --- a/zkservice/zkserver/zkserverapp/zeth/zksnark.py +++ /dev/null @@ -1,204 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) 2015-2020 Clearmatics Technologies Ltd -# -# SPDX-License-Identifier: LGPL-3.0+ - -""" -zk-SNARK abstraction -""" - -from zeth.utils import hex_to_int -import zeth.constants as constants -from api.snark_messages_pb2 import VerificationKey, ExtendedProof -from api.ec_group_messages_pb2 import HexPointBaseGroup1Affine, \ - HexPointBaseGroup2Affine - -import json -from abc import (ABC, abstractmethod) -from typing import Dict, List, Tuple, Any -# pylint: disable=unnecessary-pass - -# Dictionary representing a VerificationKey from any supported snark -GenericVerificationKey = Dict[str, Any] - -# Dictionary representing a Proof from any supported snark -GenericProof = Dict[str, Any] - - -class IZKSnarkProvider(ABC): - """ - Interface to be implemented by specific zk-snark providers. Ideally, the - rest of the logic should deal only with this interface and have no - understanding of the underlying mechanisms. - """ - - @staticmethod - @abstractmethod - def get_contract_name() -> str: - """ - Get the verifier and mixer contracts for this SNARK. - """ - pass - - @staticmethod - @abstractmethod - def verification_key_parameters( - vk: GenericVerificationKey) -> Dict[str, List[int]]: - pass - - @staticmethod - @abstractmethod - def parse_verification_key( - vk_obj: VerificationKey) -> GenericVerificationKey: - pass - - @staticmethod - @abstractmethod - def parse_proof(proof_obj: ExtendedProof) -> GenericProof: - pass - - @staticmethod - @abstractmethod - def mixer_proof_parameters(parsed_proof: GenericProof) -> List[List[int]]: - """ - Generate the leading parameters to the mix function for this SNARK, from a - GenericProof object. - """ - pass - - -class Groth16SnarkProvider(IZKSnarkProvider): - - @staticmethod - def get_contract_name() -> str: - return constants.GROTH16_MIXER_CONTRACT - - @staticmethod - def verification_key_parameters( - vk: GenericVerificationKey) -> Dict[str, List[int]]: - return { - "Alpha": hex_to_int(vk["alpha_g1"]), - "Beta1": hex_to_int(vk["beta_g2"][0]), - "Beta2": hex_to_int(vk["beta_g2"][1]), - "Delta1": hex_to_int(vk["delta_g2"][0]), - "Delta2": hex_to_int(vk["delta_g2"][1]), - "ABC_coords": hex_to_int(sum(vk["abc_g1"], [])), - } - - @staticmethod - def parse_verification_key( - vk_obj: VerificationKey) -> GenericVerificationKey: - vk = vk_obj.groth16_verification_key - return { - "alpha_g1": _parse_hex_point_base_group1_affine(vk.alpha_g1), - "beta_g2": _parse_hex_point_base_group2_affine(vk.beta_g2), - "delta_g2": _parse_hex_point_base_group2_affine(vk.delta_g2), - "abc_g1": json.loads(vk.abc_g1), - } - - @staticmethod - def parse_proof(proof_obj: ExtendedProof) -> GenericProof: - proof = proof_obj.groth16_extended_proof - return { - "a": _parse_hex_point_base_group1_affine(proof.a), - "b": _parse_hex_point_base_group2_affine(proof.b), - "c": _parse_hex_point_base_group1_affine(proof.c), - "inputs": json.loads(proof.inputs), - } - - @staticmethod - def mixer_proof_parameters(parsed_proof: GenericProof) -> List[List[Any]]: - return [ - hex_to_int(parsed_proof["a"]), - hex_to_int(parsed_proof["b"][0] + parsed_proof["b"][1]), - hex_to_int(parsed_proof["c"])] - - -class PGHR13SnarkProvider(IZKSnarkProvider): - - @staticmethod - def get_contract_name() -> str: - return constants.PGHR13_MIXER_CONTRACT - - @staticmethod - def verification_key_parameters( - vk: GenericVerificationKey) -> Dict[str, List[int]]: - return { - "A1": hex_to_int(vk["a"][0]), - "A2": hex_to_int(vk["a"][1]), - "B": hex_to_int(vk["b"]), - "C1": hex_to_int(vk["c"][0]), - "C2": hex_to_int(vk["c"][1]), - "gamma1": hex_to_int(vk["g"][0]), - "gamma2": hex_to_int(vk["g"][1]), - "gammaBeta1": hex_to_int(vk["gb1"]), - "gammaBeta2_1": hex_to_int(vk["gb2"][0]), - "gammaBeta2_2": hex_to_int(vk["gb2"][1]), - "Z1": hex_to_int(vk["z"][0]), - "Z2": hex_to_int(vk["z"][1]), - "IC_coefficients": hex_to_int(sum(vk["IC"], [])), - } - - @staticmethod - def parse_verification_key(vk_obj: VerificationKey) -> GenericVerificationKey: - vk = vk_obj.pghr13_verification_key - return { - "a": _parse_hex_point_base_group2_affine(vk.a), - "b": _parse_hex_point_base_group1_affine(vk.b), - "c": _parse_hex_point_base_group2_affine(vk.c), - "g": _parse_hex_point_base_group2_affine(vk.gamma), - "gb1": _parse_hex_point_base_group1_affine(vk.gamma_beta_g1), - "gb2": _parse_hex_point_base_group2_affine(vk.gamma_beta_g2), - "z": _parse_hex_point_base_group2_affine(vk.z), - "IC": json.loads(vk.ic), - } - - @staticmethod - def parse_proof(proof_obj: ExtendedProof) -> GenericProof: - proof = proof_obj.pghr13_extended_proof - return { - "a": _parse_hex_point_base_group1_affine(proof.a), - "a_p": _parse_hex_point_base_group1_affine(proof.a_p), - "b": _parse_hex_point_base_group2_affine(proof.b), - "b_p": _parse_hex_point_base_group1_affine(proof.b_p), - "c": _parse_hex_point_base_group1_affine(proof.c), - "c_p": _parse_hex_point_base_group1_affine(proof.c_p), - "h": _parse_hex_point_base_group1_affine(proof.h), - "k": _parse_hex_point_base_group1_affine(proof.k), - "inputs": json.loads(proof.inputs), - } - - @staticmethod - def mixer_proof_parameters(parsed_proof: GenericProof) -> List[List[Any]]: - return [ - hex_to_int(parsed_proof["a"]) + - hex_to_int(parsed_proof["a_p"]), - [hex_to_int(parsed_proof["b"][0]), - hex_to_int(parsed_proof["b"][1])], - hex_to_int(parsed_proof["b_p"]), - hex_to_int(parsed_proof["c"]), - hex_to_int(parsed_proof["c_p"]), - hex_to_int(parsed_proof["h"]), - hex_to_int(parsed_proof["k"])] - - -def get_zksnark_provider(zksnark_name: str) -> IZKSnarkProvider: - if zksnark_name == constants.PGHR13_ZKSNARK: - return PGHR13SnarkProvider() - if zksnark_name == constants.GROTH16_ZKSNARK: - return Groth16SnarkProvider() - raise Exception(f"unknown zk-SNARK name: {zksnark_name}") - - -def _parse_hex_point_base_group1_affine( - point: HexPointBaseGroup1Affine) -> Tuple[str, str]: - return (point.x_coord, point.y_coord) - - -def _parse_hex_point_base_group2_affine( - point: HexPointBaseGroup2Affine -) -> Tuple[Tuple[str, str], Tuple[str, str]]: - return ( - (point.x_c1_coord, point.x_c0_coord), - (point.y_c1_coord, point.y_c0_coord))