Parcourir la source

Remove old pism directory and scripts.

parazyd il y a 4 ans
Parent
commit
358683765e
9 fichiers modifiés avec 0 ajouts et 1311 suppressions
  1. 0 460
      old/compile.py
  2. 0 40
      old/mint.aux
  3. 0 92
      old/mint.pism
  4. 0 528
      old/pism.py
  5. 0 20
      old/preprocess.py
  6. 0 5
      old/run_mint.sh
  7. 0 4
      old/run_mint_contract.sh
  8. 0 4
      old/run_spend_contract.sh
  9. 0 158
      old/spend.pism

+ 0 - 460
old/compile.py

@@ -1,460 +0,0 @@
-import argparse
-import sys
-from enum import Enum
-
-alloc_commands = {
-    "param": 1,
-    "private": 1,
-    "public": 1,
-}
-
-op_commands = {
-    "set": 2,
-    "mul": 2,
-    "add": 2, 
-    "sub": 2,
-    "divide": 2,
-    "double": 1,
-    "square": 1,
-    "invert": 1,
-    "unpack_bits": 3,
-    "load": 2,
-    "local": 1,
-    "debug": 1,
-    "dump_alloc": 0,
-    "dump_local": 0,
-}
-
-constraint_commands = {
-    "lc0_add": 1,
-    "lc1_add": 1,
-    "lc2_add": 1,
-    "lc0_sub": 1,
-    "lc1_sub": 1,
-    "lc2_sub": 1,
-    "lc0_add_one": 0,
-    "lc1_add_one": 0,
-    "lc2_add_one": 0,
-    "lc0_sub_one": 0,
-    "lc1_sub_one": 0,
-    "lc2_sub_one": 0,
-    "lc0_add_coeff": 2,
-    "lc1_add_coeff": 2,
-    "lc2_add_coeff": 2,
-    "lc0_add_constant": 1,
-    "lc1_add_constant": 1,
-    "lc2_add_constant": 1,
-    "enforce": 0,
-    "lc_coeff_reset": 0,
-    "lc_coeff_double": 0,
-}
-
-def eprint(*args):
-    print(*args, file=sys.stderr)
-
-class Line:
-
-    def __init__(self, text, line_number):
-        self.text = text
-        self.orig = text
-        self.lineno = line_number
-
-        self.clean()
-
-    def clean(self):
-        # Remove the comments
-        self.text = self.text.split("#", 1)[0]
-        # Remove whitespace
-        self.text = self.text.strip()
-
-    def is_empty(self):
-        return bool(self.text)
-
-    def __repr__(self):
-        return "Line %s: %s" % (self.lineno, self.orig.lstrip())
-
-    def command(self):
-        if not self.is_empty():
-            return None
-        return self.text.split(" ")[0]
-
-    def args(self):
-        if not self.is_empty():
-            return None
-        return self.text.split()[1:]
-
-def clean(contents):
-    # Split input into lines
-    contents = contents.split("\n")
-    contents = [Line(line, i + 1) for i, line in enumerate(contents)]
-    # Remove empty blank lines
-    contents = [line for line in contents if line.is_empty()]
-    return contents
-
-def divide_sections(contents):
-    state = "NOSCOPE"
-    segments = {}
-    current_segment = []
-    contract_name = None
-
-    for line in contents:
-        if line.command() == "contract":
-            if len(line.args()) != 1:
-                eprint("error: missing contract name")
-                eprint(line)
-                return None
-            contract_name = line.args()[0]
-
-            if state == "NOSCOPE":
-                assert not current_segment
-                state = "INSCOPE"
-                continue
-            else:
-                assert state == "INSCOPE"
-                eprint("error: double contract entry violation")
-                eprint(line)
-                return None
-        elif line.command() == "end":
-            if len(line.args()) != 0:
-                eprint("error: end takes no args")
-                eprint(line)
-                return None
-
-            if state == "NOSCOPE":
-                eprint("error: missing contract start for end")
-                eprint(line)
-                return None
-            else:
-                assert state == "INSCOPE"
-                state = "NOSCOPE"
-                segments[contract_name] = current_segment
-                current_segment = []
-                continue
-        elif state == "NOSCOPE":
-            # Ignore lines outside any contract
-            continue
-
-        current_segment.append(line)
-
-    if state != "NOSCOPE":
-        eprint("error: reached end of file with unclosed scope")
-        return None
-
-    return segments
-
-def extract_relevant_lines(contract, commands_table):
-    relevant_lines = []
-
-    for line in contract:
-        command = line.command()
-
-        if command not in commands_table.keys():
-            continue
-
-        define = commands_table[command]
-
-        if len(line.args()) != define:
-            eprint("error: wrong number of args")
-            return None
-
-        relevant_lines.append(line)
-
-    return relevant_lines
-
-class VariableType(Enum):
-    PUBLIC = 1
-    PRIVATE = 2
-
-class Variable:
-
-    def __init__(self, symbol, index, type, is_param):
-        self.symbol = symbol
-        self.index = index
-        self.type = type
-        self.is_param = is_param
-
-    def __repr__(self):
-        return "<Variable %s:%s>" % (self.symbol, self.index)
-
-def generate_alloc_table(contract):
-    relevant_lines = extract_relevant_lines(contract, alloc_commands)
-    alloc_table = {}
-    for i, line in enumerate(relevant_lines):
-        assert len(line.args()) == 1
-        symbol = line.args()[0]
-
-        command = line.command()
-
-        if command == "param":
-            type = VariableType.PRIVATE
-            is_param = True
-        elif command == "private":
-            type = VariableType.PRIVATE
-            is_param = False
-        elif command == "public":
-            type = VariableType.PUBLIC
-            is_param = False
-        else:
-            assert False
-
-        if symbol in alloc_table:
-            eprint("error: duplicate symbol '%s'" % symbol)
-            eprint(line)
-            return None
-
-        alloc_table[symbol] = Variable(symbol, i, type, is_param)
-
-    return alloc_table
-
-class Operation:
-
-    def __init__(self, line, indexes):
-        self.command = line.command()
-        self.args = indexes
-        self.line = line
-
-class VariableRefType(Enum):
-    AUX = 1
-    LOCAL = 2
-    CONST = 3
-
-class VariableRef:
-
-    def __init__(self, type, index):
-        self.type = type
-        self.index = index
-
-    def __repr__(self):
-        return "%s(%s)" % (self.type.name, self.index)
-
-def symbols_list_to_refs(line, alloc, local_vars, constants):
-    indexes = []
-    for symbol in line.args():
-        if symbol in alloc:
-            # Lookup variable index
-            index = alloc[symbol].index
-            index = VariableRef(VariableRefType.AUX, index)
-        elif symbol in local_vars:
-            index = local_vars[symbol]
-            index = VariableRef(VariableRefType.LOCAL, index)
-        elif symbol in constants:
-            index = constants[symbol][0]
-            index = VariableRef(VariableRefType.CONST, index)
-        else:
-            eprint("error: missing unallocated symbol '%s'" % symbol)
-            eprint(line)
-            return None
-        indexes.append(index)
-    return indexes
-
-def generate_ops_table(contract, alloc, constants):
-    relevant_lines = extract_relevant_lines(contract, op_commands)
-    ops = []
-    local_vars = {}
-    for line in relevant_lines:
-        # This is a special case which creates a new local stack value
-        if line.command() == "local":
-            assert len(line.args()) == 1
-            symbol = line.args()[0]
-            local_vars[symbol] = len(local_vars)
-            indexes = []
-        else:
-            if (indexes := symbols_list_to_refs(line, alloc, 
-                                                local_vars, constants)) is None:
-                return None
-
-            # Handle this here directly since only the
-            # load command deals with constants
-            if line.command() == "load":
-                assert len(indexes) == 2
-                # This is the only command which uses consts
-                if indexes[1].type != VariableRefType.CONST:
-                    eprint("error: load command takes a const argument")
-                    eprint(line)
-                    return None
-            elif any(index.type == VariableRefType.CONST for index in indexes):
-                eprint("error: invalid const arg")
-                eprint(line)
-                return None
-
-        ops.append(Operation(line, indexes))
-    return ops
-
-class Constraint:
-
-    def __init__(self, line, lcargs):
-        self.command = line.command()
-        self.args = lcargs
-        self.line = line
-
-    def args_comment(self):
-        return ", ".join("%s" % symbol for symbol in self.line.args())
-
-def symbols_list_to_lcargs(line, alloc, constants):
-    lcargs = []
-    for symbol in line.args():
-        if symbol in alloc:
-            # Lookup variable index
-            index = alloc[symbol].index
-            lcargs.append(index)
-        elif symbol in constants:
-            value = constants[symbol]
-            lcargs.append(value)
-        else:
-            eprint("error: missing unallocated symbol '%s'" % symbol)
-            eprint(line)
-            return None
-    return lcargs
-
-def generate_constraints_table(contract, alloc, constants):
-    relevant_lines = extract_relevant_lines(contract, constraint_commands)
-    constraints = []
-    for line in relevant_lines:
-        if (lcargs := symbols_list_to_lcargs(line, alloc, constants)) is None:
-            return None
-        constraints.append(Constraint(line, lcargs))
-    return constraints
-
-class Contract:
-
-    def __init__(self, constants, alloc, ops, constraints):
-        self.constants = constants
-        self.alloc = alloc
-        self.ops = ops
-        self.constraints = constraints
-
-    def __repr__(self):
-        repr_str = ""
-
-        repr_str += "Constants:\n"
-        for symbol, value in self.constants.items():
-            repr_str += "    // %s\n" % symbol
-            repr_str += "    %s: %s\n" % value
-
-        repr_str += "Alloc table:\n"
-        for symbol, variable in self.alloc.items():
-            repr_str += "    // %s\n" % symbol
-            repr_str += "    %s %s\n" % (variable.type, variable.index)
-
-        repr_str += "Operations:\n"
-        for op in self.ops:
-            repr_str += "    // %s\n" % op.line
-            repr_str += "    %s %s\n" % (op.command, op.args)
-
-        repr_str += "Constraints:\n"
-        for constraint in self.constraints:
-            if constraint.args:
-                repr_str += "    // %s\n" % constraint.args_comment()
-            repr_str += "    %s %s\n" % (constraint.command, constraint.args)
-
-        repr_str += "Stats:\n"
-        repr_str += "    Constants: %s\n" % len(self.constants)
-        repr_str += "    Alloc: %s\n" % len(self.alloc)
-        repr_str += "    Operations: %s\n" % len(self.ops)
-        repr_str += "    Constraint Instructions: %s\n" % len(self.constraints)
-
-        return repr_str
-
-def compile(contract, constants):
-    # Allocation table
-    # symbol: Private/Public, is_param, index
-    if (alloc := generate_alloc_table(contract)) is None:
-        return None
-    # Operations lines list
-    if (ops := generate_ops_table(contract, alloc, constants)) is None:
-        return None
-    # Constraint commands
-    if (constraints := generate_constraints_table(
-            contract, alloc, constants)) is None:
-        return None
-    return Contract(constants, alloc, ops, constraints)
-
-def parse_constants(contents):
-    relevant_lines = [line for line in contents if line.command() == "constant"]
-    constants = {}
-    for line in relevant_lines:
-        assert line.command() == "constant"
-        if len(line.args()) != 2:
-            eprint("error: wrong number of args for constant")
-            eprint(line)
-            return None
-        symbol, value = line.args()
-
-        try:
-            int(value, 16)
-        except ValueError:
-            eprint("error: invalid constant value for '%s'" % symbol)
-            eprint(line)
-            return None
-
-        if len(value) != 32*2 + 2 or value[:2] != "0x":
-            eprint("error: invalid hex value for constant")
-            eprint(line)
-            return None
-
-        # Remove 0x prefix
-        value = value[2:]
-
-        constants[symbol] = (len(constants), value)
-    return constants
-
-def process(contents):
-    # Remove left whitespace
-    contents = clean(contents)
-    # Parse all constants
-    if (constants := parse_constants(contents)) is None:
-        return None
-    # Divide into contract sections
-    if (pre_contracts := divide_sections(contents)) is None:
-        return None
-    # Process each contract
-    contracts = {}
-    for contract_name, pre_contract in pre_contracts.items():
-        if (contract := compile(pre_contract, constants)) is None:
-            return None
-        contracts[contract_name] = contract
-    return contracts
-
-def main(argv):
-    parser = argparse.ArgumentParser()
-    parser.add_argument("filename", help="VM PISM file: proofs/vm.pism")
-    parser.add_argument("--output", type=argparse.FileType('wb', 0),
-                        default=sys.stdout.buffer, help="Output file")
-    group = parser.add_mutually_exclusive_group()
-    group.add_argument('--display', action='store_true',
-                       help="show the compiled code in human readable format")
-    group.add_argument('--rust', action='store_true',
-                       help="output compiled code to rust for testing")
-    group.add_argument('--supervisor', action='store_true',
-                       help="output compiled code to zkvm supervisor")
-    args = parser.parse_args()
-
-    src_filename = args.filename
-    contents = open(src_filename).read()
-    if (contracts := process(contents)) is None:
-        return -2
-
-    def default_display():
-        for contract_name, contract in contracts.items():
-            print("Contract:", contract_name)
-            print(contract)
-
-    if args.display:
-        default_display()
-    elif args.rust:
-        import compile_export_rust
-        for contract_name, contract in contracts.items():
-            compile_export_rust.display(contract)
-    elif args.supervisor:
-        import compile_export_supervisor
-        for contract_name, contract in contracts.items():
-            compile_export_supervisor.export(args.output, contract_name,
-                                             contract)
-    else:
-        default_display()
-
-    return 0
-
-if __name__ == "__main__":
-    sys.exit(main(sys.argv))
-

+ 0 - 40
old/mint.aux

@@ -1,40 +0,0 @@
-{
-    "constants": {
-        "G_SPEND": {
-            "maps_to": "zcash_proofs::constants::SPENDING_KEY_GENERATOR"
-        },
-        "G_PROOF": {
-            "maps_to": "zcash_proofs::constants::PROOF_GENERATION_KEY_GENERATOR"
-        },
-        "CRH_IVK": {
-            "maps_to": "zcash_primitives::constants::CRH_IVK_PERSONALIZATION"
-        },
-        "PRF_NF": {
-            "maps_to": "zcash_primitives::constants::PRF_NF_PERSONALIZATION"
-        },
-        "G_VCV": {
-            "maps_to": "zcash_proofs::constants::VALUE_COMMITMENT_VALUE_GENERATOR"
-        },
-        "G_VCR": {
-            "maps_to": "zcash_proofs::constants::VALUE_COMMITMENT_RANDOMNESS_GENERATOR"
-        },
-        "JUBJUB_FR_CAPACITY": {
-            "maps_to": "jubjub::Fr::CAPACITY as usize"
-        },
-        "NOTE_COMMIT": {
-            "maps_to": "pedersen_hash::Personalization::NoteCommitment"
-        },
-        "MERKLE_0": {
-            "maps_to": "pedersen_hash::Personalization::MerkleTree(0)"
-        },
-        "MERKLE_1": {
-            "maps_to": "pedersen_hash::Personalization::MerkleTree(1)"
-        },
-        "MERKLE_2": {
-            "maps_to": "pedersen_hash::Personalization::MerkleTree(2)"
-        },
-        "MERKLE_3": {
-            "maps_to": "pedersen_hash::Personalization::MerkleTree(3)"
-        }
-    }
-}

+ 0 - 92
old/mint.pism

@@ -1,92 +0,0 @@
-# :set syntax=pism
-# :source ../scripts/pism.vim
-constant G_VCV FixedGenerator
-constant G_VCR FixedGenerator
-constant CRH_IVK BlakePersonalization
-#constant JUBJUB_FR_CAPACITY BinarySize
-#constant NOTE_COMMIT PedersenPersonalization
-
-contract mint_contract
-    # Value commitment
-    param value U64
-    param token_id Fr
-    param randomness_value Fr
-    param randomness_token Fr
-
-    param serial Fr
-    param randomness_coin Fr
-    param public Point
-start
-    # Witness input values
-    u64_as_binary_le value param:value
-    fr_as_binary_le token_id param:token_id
-    fr_as_binary_le randomness_value param:randomness_value
-    fr_as_binary_le randomness_token param:randomness_token
-    fr_as_binary_le serial param:serial
-    fr_as_binary_le randomness_coin param:randomness_coin
-
-    witness public param:public
-    assert_not_small_order public
-
-    # Make value commitment
-    # V = v * G_VCV + r * G_VCR
-
-    ec_mul_const vcv value G_VCV
-    ec_mul_const rcv randomness_value G_VCR
-    ec_add cv vcv rcv
-    # emit cv
-    emit_ec cv
-
-    # Make token_id commitment
-    # A = a * G_VCV + r_a * G_VCR
-
-    ec_mul_const vca token_id G_VCV
-    ec_mul_const rca randomness_token G_VCR
-    ec_add ca vca rca
-    # emit ca
-    emit_ec ca
-
-
-    # Make the coin
-    # C = Hash(public_key, value, token_id, serial, randomness_coin)
-
-    # Build the preimage to hash
-    alloc_binary preimage
-
-    # public_key
-    ec_repr repr_public public
-    binary_extend preimage repr_public
-
-    # value
-    binary_extend preimage value
-
-# Fr values are 252 bits so we need to pad it with extra 0s
-# to match the Rust values which are 256 bits
-{% macro binary_put_fr(binary, var) -%}
-    binary_extend {{ binary }} {{ var }}
-    {% for n in range(4) %}
-        alloc_const_bit zero_bit false
-        binary_push {{ binary }} zero_bit
-    {% endfor %}
-{%- endmacro %}
-
-    # serial
-    {{ binary_put_fr("preimage", "serial") }}
-
-    # randomness_coin
-    {{ binary_put_fr("preimage", "randomness_coin") }}
-
-    # token_id
-    {{ binary_put_fr("preimage", "token_id") }}
-
-    # Public key:       SubgroupPoint   = 256 bits
-    # Value:            u64             = 64 bits
-    # AssetID:          Fr              = 252 + 4 bits padding
-    # Serial:           Fr              = 252 + 4 bits padding
-    # Randomness coin   Fr              = 252 + 4 bits padding
-    # TOTAL: 1088 bits for preimage
-    static_assert_binary_size preimage 1088
-    blake2s coin preimage CRH_IVK
-    emit_binary coin
-end
-

+ 0 - 528
old/pism.py

@@ -1,528 +0,0 @@
-import json
-import os
-import sys
-
-import codegen
-
-symbol_table = {
-    "contract": 1,
-    "param": 2,
-    "start": 0,
-    "end": 0,
-}
-
-types_map = {
-    "U64": "u64",
-    "Fr": "jubjub::Fr",
-    "Point": "jubjub::SubgroupPoint",
-    "Scalar": "bls12_381::Scalar",
-    "Bool": "bool"
-}
-
-feature_includes = {"G_SPEND": "use crate::crypto::merkle_node::SAPLING_COMMITMENT_TREE_DEPTH;\n"}
-
-command_desc = {
-    "witness": (
-        ("EdwardsPoint",    True),
-        ("Point",           False)
-    ),
-    "assert_not_small_order": (
-        ("EdwardsPoint",    False),
-    ),
-    "u64_as_binary_le": (
-        ("Vec<Boolean>",    True),
-        ("U64",             False),
-    ),
-    "fr_as_binary_le": (
-        ("Vec<Boolean>",    True),
-        ("Fr",              False)
-    ),
-    "ec_mul_const": (
-        ("EdwardsPoint",    True),
-        ("Vec<Boolean>",    False),
-        ("FixedGenerator",  False)
-    ),
-    "ec_mul": (
-        ("EdwardsPoint",    True),
-        ("Vec<Boolean>",    False),
-        ("EdwardsPoint",    False),
-    ),
-    "ec_add": (
-        ("EdwardsPoint",    True),
-        ("EdwardsPoint",    False),
-        ("EdwardsPoint",    False),
-    ),
-    "ec_repr": (
-        ("Vec<Boolean>",    True),
-        ("EdwardsPoint",    False),
-    ),
-    "ec_get_u": (
-        ("ScalarNum",       True),
-        ("EdwardsPoint",    False),
-    ),
-    "emit_ec": (
-        ("EdwardsPoint",    False),
-    ),
-    "alloc_binary": (
-        ("Vec<Boolean>",    True),
-    ),
-    "binary_clone": (
-        ("Vec<Boolean>",    True),
-        ("Vec<Boolean>",    False),
-    ),
-    "binary_extend": (
-        ("Vec<Boolean>",    False),
-        ("Vec<Boolean>",    False),
-    ),
-    "binary_push": (
-        ("Vec<Boolean>",    False),
-        ("Boolean",         False),
-    ),
-    "binary_truncate": (
-        ("Vec<Boolean>",    False),
-        ("BinarySize",      False),
-    ),
-    "static_assert_binary_size": (
-        ("Vec<Boolean>",    False),
-        ("INTEGER",         False),
-    ),
-    "blake2s": (
-        ("Vec<Boolean>",    True),
-        ("Vec<Boolean>",    False),
-        ("BlakePersonalization", False),
-    ),
-    "pedersen_hash": (
-        ("EdwardsPoint",    True),
-        ("Vec<Boolean>",    False),
-        ("PedersenPersonalization", False),
-    ),
-    "emit_binary": (
-        ("Vec<Boolean>",    False),
-    ),
-    "alloc_bit": (
-        ("Boolean",         True),
-        ("Bool",            False),
-    ),
-    "alloc_const_bit": (
-        ("Boolean",         True),
-        ("BOOL_CONST",      False),
-    ),
-    "clone_bit": (
-        ("Boolean",         True),
-        ("Boolean",         False),
-    ),
-    "alloc_scalar": (
-        ("ScalarNum",       True),
-        ("Scalar",          False),
-    ),
-    "scalar_as_binary": (
-        ("Vec<Boolean>",    True),
-        ("ScalarNum",       False),
-    ),
-    "emit_scalar": (
-        ("ScalarNum",       False),
-    ),
-    "scalar_enforce_equal": (
-        ("ScalarNum",       False),
-        ("ScalarNum",       False),
-    ),
-    "conditionally_reverse": (
-        ("ScalarNum",       True),
-        ("ScalarNum",       True),
-        ("ScalarNum",       False),
-        ("ScalarNum",       False),
-        ("Boolean",         False),
-    ),
-}
-
-def eprint(*args):
-    print(*args, file=sys.stderr)
-
-class Line:
-
-    def __init__(self, text, line_number):
-        self.text = text
-        self.orig = text
-        self.lineno = line_number
-
-        self.clean()
-
-    def clean(self):
-        # Remove the comments
-        self.text = self.text.split("#", 1)[0]
-        # Remove whitespace
-        self.text = self.text.strip()
-
-    def is_empty(self):
-        return bool(self.text)
-
-    def __repr__(self):
-        return "Line %s: %s" % (self.lineno, self.orig.lstrip())
-
-    def command(self):
-        if not self.is_empty():
-            return None
-        return self.text.split(" ")[0]
-
-    def args(self):
-        if not self.is_empty():
-            return None
-        return self.text.split(" ")[1:]
-
-def clean(contents):
-    # Split input into lines
-    contents = contents.split("\n")
-    contents = [Line(line, i) for i, line in enumerate(contents)]
-    # Remove empty blank lines
-    contents = [line for line in contents if line.is_empty()]
-    return contents
-
-def make_segments(contents):
-    constants = [line for line in contents if line.command() == "constant"]
-
-    segments = []
-    current_segment = []
-    for line in contents:
-        if line.command() == "contract":
-            current_segment = []
-
-        current_segment.append(line)
-
-        if line.command() == "end":
-            segments.append(current_segment)
-            current_segment = []
-
-    return constants, segments
-
-def build_constants_table(constants):
-    table = {}
-    for line in constants:
-        args = line.args()
-        if len(args) != 2:
-            eprint("error: wrong number of args")
-            eprint(line)
-            return None
-        name, type = args
-        table[name] = type
-    return table
-
-def extract(segment):
-    assert segment
-    # Does it have a declaration?
-    if not segment[0].command() == "contract":
-        eprint("error: missing contract declaration")
-        eprint(segment[0])
-        return None
-    # Does it have an end?
-    if not segment[-1].command() == "end":
-        eprint("error: missing contract end")
-        eprint(segment[-1])
-        return None
-    # Does it have a start?
-    if not [line for line in segment if line.command() == "start"]:
-        eprint("error: missing contract start")
-        eprint(segment[0])
-        return None
-
-    for line in segment:
-        command, args = line.command(), line.args()
-
-        if command in symbol_table:
-            if symbol_table[command] != len(args):
-                eprint("error: wrong number of args for command '%s'" % command)
-                eprint(line)
-                return None
-        elif command in command_desc:
-            if len(command_desc[command]) != len(args):
-                eprint("error: wrong number of args for command '%s'" % command)
-                eprint(line)
-                return None
-        else:
-            eprint("error: missing symbol for command '%s'" % command)
-            eprint(line)
-            return None
-
-    contract_name = segment[0].args()[0]
-
-    start_index = [index for index, line in enumerate(segment)
-                   if line.command() == "start"]
-    if len(start_index) > 1:
-        eprint("error: multiple start statements in contract '%s'" %
-               contract_name)
-        for index in start_index:
-            eprint(segment[index])
-        eprint("Aborting.")
-        return None
-    assert len(start_index) == 1
-    start_index = start_index[0]
-
-    header = segment[1:start_index]
-    code = segment[start_index + 1:-1]
-
-    params = {}
-    for param_decl in header:
-        args = param_decl.args()
-        assert len(args) == 2
-        name, type = args
-        params[name] = type
-
-    program = []
-    for line in code:
-        command, args = line.command(), line.args()
-        program.append((command, args, line))
-
-    return Contract(contract_name, params, program)
-
-def to_initial_caps(snake_str):
-    components = snake_str.split("_")
-    return "".join(x.title() for x in components)
-
-class Contract:
-
-    def __init__(self, name, params, program):
-        self.name = name
-        self.params = params
-        self.program = program
-
-    def _includes(self):
-        return \
-r"""#![allow(unused_imports)]
-#![allow(unused_mut)]
-use bellman::{
-    gadgets::{
-        boolean,
-        boolean::{AllocatedBit, Boolean},
-        multipack,
-        blake2s,
-        num,
-        Assignment,
-    },
-    groth16, Circuit, ConstraintSystem, SynthesisError,
-};
-use bls12_381::Bls12;
-use ff::{PrimeField, Field};
-use group::Curve;
-use zcash_proofs::circuit::{ecc, pedersen_hash};
-"""
-
-    def _compile_header(self):
-        code = "pub struct %s {\n" % to_initial_caps(self.name)
-        for param_name, param_type in self.params.items():
-            try:
-                mapped_type = types_map[param_type]
-            except KeyError:
-                return None
-            code += "    pub %s: Option<%s>,\n" % (param_name, mapped_type)
-        code += "}\n"
-        return code
-
-    def _compile_body(self):
-        self.stack = {}
-        code = "\n"
-        #indent = " " * 8
-        for command, args, line in self.program:
-            if (code_text := self._compile_line(command, args, line)) is None:
-                return None
-            code += "// %s\n" % str(line)
-            code += code_text + "\n\n"
-        return code
-
-    def _preprocess_args(self, args, line):
-        nargs = []
-        for arg in args:
-            if not arg.startswith("param:"):
-                nargs.append((arg, False))
-                continue
-            _, argname = arg.split(":", 1)
-            if argname not in self.params:
-                eprint("error: non-existant param referenced")
-                eprint(line)
-                return None
-            nargs.append((argname, True))
-        return nargs
-
-    def type_checking(self, command, args, line):
-        assert command in command_desc
-        type_list = command_desc[command]
-        if len(type_list) != len(args):
-            eprint("error: wrong number of arguments!")
-            eprint(line)
-            return False
-
-        for (expected_type, new_val), (argname, is_param) in \
-            zip(type_list, args):
-            # Only type check input arguments, not output values
-            if new_val:
-                continue
-
-            if expected_type == "INTEGER" or expected_type == "BOOL_CONST":
-                continue
-
-            if is_param:
-                actual_type = self.params[argname]
-            elif argname in self.constants:
-                actual_type = self.constants[argname]
-            else:
-                # Check the stack here
-                if argname not in self.stack:
-                    eprint("error: cannot find value '%s' on the stack!" %
-                           argname)
-                    eprint(line)
-                    return False
-
-                actual_type = self.stack[argname]
-
-            if expected_type != actual_type:
-                eprint("error: wrong type for arg '%s'!" % argname)
-                eprint(line)
-                return False
-
-        return True
-
-    def _check_args(self, command, args, line):
-        assert command in command_desc
-        type_list = command_desc[command]
-        assert len(type_list) == len(args)
-
-        for (expected_type, is_new_val), (arg, is_param) in zip(type_list, args):
-            if is_param:
-                continue
-            if is_new_val:
-                continue
-            if arg in self.stack:
-                continue
-            if arg in self.constants:
-                continue
-
-            if expected_type == "INTEGER" or expected_type == "BOOL_CONST":
-                continue
-
-            eprint("error: cannot find '%s' in the stack" % arg)
-            eprint(line)
-            return False
-        return True
-
-    def _compile_line(self, command, args, line):
-        if (args := self._preprocess_args(args, line)) is None:
-            return None
-        if not self.type_checking(command, args, line):
-            return None
-
-        if not self._check_args(command, args, line):
-            return None
-
-        self.modify_stack(command, args)
-
-        args = [self.carg(arg) for arg in args]
-
-        try:
-            codegen_method = getattr(codegen, command)
-        except AttributeError:
-            eprint("error: missing command '%s' does not exist" % command)
-            eprint(line)
-            return None
-
-        return codegen_method(line, *args)
-
-    def carg(self, arg):
-        argname, is_param = arg
-        if is_param:
-            return "self.%s" % argname
-        if argname in self.rename_consts:
-            return self.rename_consts[argname]
-        return argname
-
-    def modify_stack(self, command, args):
-        type_list = command_desc[command]
-        assert len(type_list) == len(args)
-        for (expected_type, new_val), (argname, is_param) in \
-            zip(type_list, args):
-            if is_param:
-                assert not new_val
-                continue
-
-            # Now apply the new values to the stack
-            if new_val:
-                self.stack[argname] = expected_type
-
-    def compile(self, constants, aux):
-        self.constants = constants
-        code = ""
-
-        code += self._includes()
-
-        self.rename_consts = {}
-        if "constants" in aux:
-            for const_name, value in aux["constants"].items():
-                if "maps_to" not in value:
-                    eprint("error: bad aux config '%s', missing maps_to" %
-                           const_name)
-                    return None
-
-                if const_name in feature_includes:
-                    code += feature_includes[const_name]
-
-                mapped_type = value["maps_to"]
-                self.rename_consts[const_name] = mapped_type
-
-        code += "\n"
-
-        if (header := self._compile_header()) is None:
-            return None
-        code += header
-
-        code += \
-r"""impl Circuit<bls12_381::Scalar> for %s {
-    fn synthesize<CS: ConstraintSystem<bls12_381::Scalar>>(
-        self,
-        cs: &mut CS,
-    ) -> Result<(), SynthesisError> {
-""" % to_initial_caps(self.name)
-
-        if (body := self._compile_body()) is None:
-            return None
-        code += body
-        code += "Ok(())\n"
-
-        code += "    }\n"
-        code += "}\n"
-
-        return code
-
-def process(contents, aux):
-    contents = clean(contents)
-    constants, segments = make_segments(contents)
-    if (constants := build_constants_table(constants)) is None:
-        return False
-
-    codes = []
-    for segment in segments:
-        if (contract := extract(segment)) is None:
-            return False
-        if (code := contract.compile(constants, aux)) is None:
-            return False
-        codes.append(code)
-
-    # Success! Output finished product.
-    [print(code) for code in codes]
-
-    return True
-
-def main(argv):
-    if len(argv) != 3:
-        eprint("pism FILENAME AUX_FILENAME")
-        return -1
-
-    aux_filename = argv[2]
-    aux = json.loads(open(aux_filename).read())
-
-    src_filename = argv[1]
-    contents = open(src_filename).read()
-    if not process(contents, aux):
-        return -2
-
-    return 0
-
-if __name__ == "__main__":
-    sys.exit(main(sys.argv))
-

+ 0 - 20
old/preprocess.py

@@ -1,20 +0,0 @@
-import os.path
-import sys
-from jinja2 import Environment, FileSystemLoader, Template
-
-def main(argv):
-    if len(argv) != 2:
-        print("error: missing arg", file=sys.stderr)
-        return -1
-
-    path = argv[1]
-    dirname, filename = os.path.dirname(path), os.path.basename(path)
-    env = Environment(loader = FileSystemLoader([dirname]))
-    template = env.get_template(filename)
-    print(template.render())
-
-    return 0
-
-if __name__ == "__main__":
-    sys.exit(main(sys.argv))
-

+ 0 - 5
old/run_mint.sh

@@ -1,5 +0,0 @@
-#!/bin/bash -x
-python3 scripts/preprocess.py proofs/mint2.psm > /tmp/mint2.psm || exit $?
-python3 scripts/compile.py --supervisor /tmp/mint2.psm --output mint.zcd || exit $?
-cargo run --release --bin mint
-

+ 0 - 4
old/run_mint_contract.sh

@@ -1,4 +0,0 @@
-#!/bin/bash -x
-python scripts/preprocess.py proofs/mint.pism > /tmp/mint.pism
-python scripts/pism.py /tmp/mint.pism proofs/mint.aux | rustfmt > src/mint_contract.rs
-cargo run --release --bin mint

+ 0 - 4
old/run_spend_contract.sh

@@ -1,4 +0,0 @@
-#!/bin/bash -x
-python scripts/preprocess.py proofs/spend.pism > /tmp/spend.pism
-python scripts/pism.py /tmp/spend.pism proofs/mint.aux | rustfmt > src/spend_contract.rs
-cargo run --release --bin spend

+ 0 - 158
old/spend.pism

@@ -1,158 +0,0 @@
-constant G_VCV FixedGenerator
-constant G_VCR FixedGenerator
-constant G_SPEND FixedGenerator
-constant PRF_NF BlakePersonalization
-constant CRH_IVK BlakePersonalization
-constant NOTE_COMMIT PedersenPersonalization
-{% for i in range(32) %}
-    constant MERKLE_{{ i }} PedersenPersonalization
-{% endfor %}
-
-contract spend_contract
-    # Value commitment
-    param value U64
-    param token_id Fr
-    param randomness_value Fr
-    param randomness_token Fr
-
-    param serial Fr
-    param randomness_coin Fr
-    param secret Fr
-    param signature_secret Fr
-
-{% for i in range(32) %}
-    param branch_{{ i }} Scalar
-    param is_right_{{ i }} Bool
-{% endfor %}
-start
-    # Witness input values
-    u64_as_binary_le value param:value
-    fr_as_binary_le token_id param:token_id
-    fr_as_binary_le randomness_value param:randomness_value
-    fr_as_binary_le randomness_token param:randomness_token
-
-    # Make value commitment
-    # V = v * G_VCV + r * G_VCR
-
-    ec_mul_const vcv value G_VCV
-    ec_mul_const rcv randomness_value G_VCR
-    ec_add cv vcv rcv
-    # emit cv
-    emit_ec cv
-
-    # Make token_id commitment
-    # A = a * G_VCV + r * G_VCR
-
-    ec_mul_const vca token_id G_VCV
-    ec_mul_const rca randomness_token G_VCR
-    ec_add ca vca rca
-    # emit ca
-    emit_ec ca
-
-    # Make the nullifier
-    # N = Hash(secret, serial)
-    fr_as_binary_le serial param:serial
-    fr_as_binary_le secret param:secret
-
-    alloc_binary nf_preimage
-
-# Fr values are 252 bits so we need to pad it with extra 0s
-# to match the Rust values which are 256 bits
-{% macro binary_put_fr(binary, var) -%}
-    binary_extend {{ binary }} {{ var }}
-    {% for n in range(4) %}
-        alloc_const_bit zero_bit false
-        binary_push {{ binary }} zero_bit
-    {% endfor %}
-{%- endmacro %}
-
-    # secret
-    binary_clone secret2 secret
-    {{ binary_put_fr("nf_preimage", "secret2") }}
-
-    # serial
-    binary_clone serial2 serial
-    {{ binary_put_fr("nf_preimage", "serial2") }}
-
-    # Secret:           Fr              = 252 + 4 bits padding
-    # Serial:           Fr              = 252 + 4 bits padding
-    # TOTAL: 512 bits for preimage
-    static_assert_binary_size nf_preimage 512
-    blake2s nf nf_preimage PRF_NF
-    emit_binary nf
-
-    # Derive the public key
-    # P = secret * G
-    ec_mul_const public secret G_SPEND
-
-    # Make the coin (same as mint contract)
-    # C = Hash(public_key, value, token_id, serial, randomness_coin)
-    fr_as_binary_le randomness_coin param:randomness_coin
-
-    # Build the preimage to hash
-    alloc_binary preimage
-
-    # public_key
-    ec_repr repr_public public
-    binary_extend preimage repr_public
-
-    # value
-    binary_extend preimage value
-
-    # serial
-    {{ binary_put_fr("preimage", "serial") }}
-
-    # randomness_coin
-    {{ binary_put_fr("preimage", "randomness_coin") }}
-
-    # token_id
-    {{ binary_put_fr("preimage", "token_id") }}
-
-    # Public key:       SubgroupPoint   = 256 bits
-    # Value:            u64             = 64 bits
-    # AssetID:          Fr              = 252 + 4 bits padding
-    # Serial:           Fr              = 252 + 4 bits padding
-    # Randomness coin   Fr              = 252 + 4 bits padding
-    # TOTAL: 1088 bits for preimage
-    static_assert_binary_size preimage 1088
-    blake2s coin preimage CRH_IVK
-    # Debug stuff. Normally we don't reveal the coin in the spend proof.
-    #binary_clone coin2 coin
-    #emit_binary coin2
-
-    # coin_commit = PedersenHash(coin)
-    pedersen_hash cm coin NOTE_COMMIT
-    # left = coin_commit.u
-    ec_get_u current cm
-
-    # Our merkle tree has a height of 32
-{% for i in range(32) %}
-    # left = current
-    # right = branch[{{ i }}]
-    alloc_scalar branch param:branch_{{ i }}
-
-    # is_right = is_right[{{ i }}]
-    alloc_bit is_right param:is_right_{{ i }}
-
-    # reverse(a, b, condition) = if condition (b, a) else (a, b)
-    conditionally_reverse left right current branch is_right
-
-    # coin_commit = PedersenHash(left || right)
-    scalar_as_binary left left
-    scalar_as_binary right right
-    alloc_binary preimage
-    binary_extend preimage left
-    binary_extend preimage right
-    pedersen_hash cm preimage MERKLE_{{ i }}
-    # current = coin_commit.u
-    ec_get_u current cm
-{% endfor %}
-    # Reveal the merkle root
-    emit_scalar current
-
-    # Emit the signature public key
-    fr_as_binary_le signature_secret param:signature_secret
-    ec_mul_const signature_public signature_secret G_SPEND
-    emit_ec signature_public
-end
-