示例#1
0
def main():
    subparsers = {
        'submit': submit,
        'status': get_job_status,
        'is_verified': is_verified,
    }

    parser = argparse.ArgumentParser(
        description='A tool to communicate with SHARP.')
    parser.add_argument('command', choices=subparsers.keys())
    parser.add_argument(
        '--bin_dir',
        type=str,
        default='',
        help=
        'The path to a directory that contains the cairo-compile and cairo-run scripts. '
        "If not specified, files are assumed to be in the system's PATH.")
    parser.add_argument('--flavor',
                        type=str,
                        default='Release',
                        choices=['Debug', 'Release', 'RelWithDebInfo'],
                        help='Build flavor')

    args, unknown = parser.parse_known_args()

    with get_crypto_lib_context_manager(args.flavor):
        try:
            # Invoke the requested command.
            return subparsers[args.command](args, unknown)
        except Exception as exc:
            print(f'Error: {exc}', file=sys.stderr)
def prepare_cairo_run():
    sys.argv.extend(['--layout', 'small'])
    sys.argv.extend(['--print_output'])
    parser = argparse.ArgumentParser(
        description='A tool to run Cairo programs.')
    parser.add_argument('--program', type=argparse.FileType('r'))
    parser.add_argument('--program_input', type=str)
    parser.add_argument('--exception', type=int)
    parser.add_argument('--print_output', action='store_true')
    parser.add_argument('--layout', default='plain')
    parser.add_argument('--flavor',
                        type=str,
                        choices=['Debug', 'Release', 'RelWithDebInfo'])
    parser.add_argument('--steps', type=int)
    parser.add_argument('--proof_mode', action='store_true')
    parser.add_argument('--input', type=str)
    python_dependencies.add_argparse_argument(parser)
    args = parser.parse_args()

    with get_crypto_lib_context_manager(args.flavor):
        try:
            res = cairo_run(args, json.loads(args.program_input))
        except VmException as err:
            res = ["0", "0"]
        except AssertionError as err:
            print(f'Error: {err}', file=sys.stderr)
            res = 0
    return res
示例#3
0
def test_builtin_segment_access():
    # Non continuous is ok.
    with get_crypto_lib_context_manager(flavor=None):
        verify_secure_runner(run_code_in_runner(
            """
%builtins pedersen
main:
[ap] = 1; ap++
[ap - 1] = [[fp - 3] + 0]
[ap - 1] = [[fp - 3] + 1]
[ap] = [[fp - 3] + 2]; ap++  # Read hash result.
[ap] = [fp - 3] + 3; ap++  # Return pedersen_ptr.
ret
""",
            layout='small'))

    # Out of bound is not ok.
    runner = run_code_in_runner(
        """
%builtins pedersen
main:
[fp - 1] = [[fp - 3] + 2]  # Access only the result portion of the builtin.
[ap] = [fp - 3] + 3; ap++  # Return pedersen_ptr.
ret
""",
        layout='small')
    # Access out of bounds manually, because runner disallows it as well.
    pedersen_base = runner.builtin_runners['pedersen_builtin'].base
    runner.vm_memory[pedersen_base + 7] = 1
    with pytest.raises(SecurityError, match='Out of bounds access to builtin segment pedersen'):
        verify_secure_runner(runner)
def test_builtin_segment_access():
    with get_crypto_lib_context_manager(flavor=None):
        verify_secure_runner(
            run_code_in_runner("""
%builtins pedersen
main:
[ap] = 1; ap++
[ap - 1] = [[fp - 3] + 0]
[ap - 1] = [[fp - 3] + 1]
[ap] = [[fp - 3] + 2]; ap++  # Read hash result.
[ap] = [fp - 3] + 3; ap++  # Return pedersen_ptr.
ret
""",
                               layout='small'))

    # Out of bound is not ok.
    runner = run_code_in_runner("""
%builtins pedersen
main:
[fp - 1] = [[fp - 3] + 2]  # Access only the result portion of the builtin.
[ap] = [fp - 3] + 3; ap++  # Return pedersen_ptr.
ret
""",
                                layout='small')
    # Access out of bounds manually, because runner disallows it as well.
    pedersen_base = runner.builtin_runners['pedersen_builtin'].base
    runner.vm_memory.unfreeze_for_testing()
    runner.vm_memory[pedersen_base + 7] = 1
    with pytest.raises(
            SecurityError,
            match='Out of bounds access to builtin segment pedersen'):
        verify_secure_runner(runner)

    # Invalid segment size (only first input is written).
    with pytest.raises(
            SecurityError,
            match='Unexpected number of memory cells for pedersen: 1'):
        verify_secure_runner(
            run_code_in_runner("""
%builtins pedersen
func main{pedersen_ptr}():
    assert [pedersen_ptr] = 0
    let pedersen_ptr = pedersen_ptr + 1
    return ()
end
""",
                               layout='small'))
示例#5
0
def main():
    parser = argparse.ArgumentParser(
        description='A tool to compute the hash of a cairo program')
    parser.add_argument('--program',
                        type=argparse.FileType('r'),
                        required=True,
                        help='The name of the program json file.')
    parser.add_argument('--flavor',
                        type=str,
                        default='Release',
                        choices=['Debug', 'Release', 'RelWithDebInfo'],
                        help='Build flavor')
    args = parser.parse_args()

    with get_crypto_lib_context_manager(args.flavor):
        program = Program.Schema().load(json.load(args.program))
        print(hex(compute_program_hash_chain(program)))
def prepare_cairo_run():
    subparsers = {
        'submit': submit,
        'status': get_job_status,
        'is_verified': is_verified,
    }

    parser = argparse.ArgumentParser(
        description='A tool to communicate with SHARP.')
    parser.add_argument('command', choices=subparsers.keys())
    parser.add_argument('--bin_dir', type=str, default='')
    parser.add_argument('--flavor',
                        type=str,
                        default='Release',
                        choices=['Debug', 'Release', 'RelWithDebInfo'])
    args, unknown = parser.parse_known_args()

    with get_crypto_lib_context_manager(args.flavor):
        try:
            res = subparsers[args.command](args, unknown)
        except Exception as exc:
            res = ["", ""]
    return res
示例#7
0
def main():
    start_time = time.time()

    parser = argparse.ArgumentParser(
        description='A tool to run Cairo programs.')
    parser.add_argument('--program',
                        type=argparse.FileType('r'),
                        help='The name of the program json file.')
    parser.add_argument(
        '--program_input',
        type=argparse.FileType('r'),
        help=
        'Path to a json file representing the (private) input of the program.')
    parser.add_argument(
        '--steps',
        type=int,
        help=
        'The number of instructions to perform. If steps is not given, runs the program until '
        'the __end__ instruction, and then continues until the number of steps is a power of 2.'
    )
    parser.add_argument(
        '--min_steps',
        type=int,
        help=
        'The minimal number of instructions to perform. This can be used to guarantee that '
        'there will be enough builtin instances for the program.')
    parser.add_argument(
        '--debug_error',
        action='store_true',
        help=
        'If there is an error during the execution, stop the execution, but produce the '
        'partial outputs.')
    parser.add_argument(
        '--no_end',
        action='store_true',
        help="Don't check that the program ended successfully.")
    parser.add_argument(
        '--print_memory',
        action='store_true',
        help='Show the values on the memory after the execution.')
    parser.add_argument('--relocate_prints',
                        action='store_true',
                        help='Print memory and info after memory relocation.')
    parser.add_argument(
        '--secure_run',
        action='store_true',
        help=
        'Verify the run is secure and can be run safely using the bootloader.')
    parser.add_argument(
        '--print_info',
        action='store_true',
        help='Print information on the execution of the program.')
    parser.add_argument(
        '--print_output',
        action='store_true',
        help='Prints the program output (if the output builtin is used).')
    parser.add_argument('--memory_file',
                        type=argparse.FileType('wb'),
                        help='Output file name for the memory.')
    parser.add_argument('--trace_file',
                        type=argparse.FileType('wb'),
                        help='Output file name for the execution trace.')
    parser.add_argument(
        '--run_from_cairo_pie',
        type=argparse.FileType('rb'),
        help='Runs a Cairo PIE file, instead of a program. '
        'This flag can be used with --secure_run to verify the correctness of a Cairo PIE file.'
    )
    parser.add_argument('--cairo_pie_output',
                        type=argparse.FileType('wb'),
                        help='Output file name for the CairoPIE object.')
    parser.add_argument(
        '--debug_info_file',
        type=argparse.FileType('w'),
        help='Output file name for debug information created at run time.')
    parser.add_argument(
        '--air_public_input',
        type=argparse.FileType('w'),
        help='Output file name for the public input json file of the Cairo AIR.'
    )
    parser.add_argument(
        '--air_private_input',
        type=argparse.FileType('w'),
        help=
        'Output file name for the private input json file of the Cairo AIR.')
    parser.add_argument('--layout',
                        choices=LAYOUTS.keys(),
                        default='plain',
                        help='The layout of the Cairo AIR.')
    parser.add_argument('--tracer',
                        action='store_true',
                        help='Run the tracer.')
    parser.add_argument('--proof_mode',
                        action='store_true',
                        help='Prepare a provable execution trace.')
    parser.add_argument('--flavor',
                        type=str,
                        choices=['Debug', 'Release', 'RelWithDebInfo'],
                        help='Build flavor.')
    python_dependencies.add_argparse_argument(parser)

    args = parser.parse_args()

    assert int(args.program is not None) + int(args.run_from_cairo_pie is not None) == 1, \
        'Exactly one of --program, --run_from_cairo_pie must be specified.'
    assert not (args.proof_mode and args.run_from_cairo_pie), \
        '--proof_mode cannot be used with --run_from_cairo_pie.'
    assert not (args.steps and args.min_steps
                ), '--steps and --min_steps cannot be both specified.'
    assert not (args.cairo_pie_output and args.no_end), \
        '--no_end and --cairo_pie_output cannot be both specified.'
    if args.air_public_input:
        assert args.proof_mode, '--air_public_input can only be used in proof_mode.'
    if args.air_private_input:
        assert args.proof_mode, '--air_private_input can only be used in proof_mode.'

    with get_crypto_lib_context_manager(args.flavor):
        try:
            res = cairo_run(args)
        except VmException as err:
            print(err, file=sys.stderr)
            res = 1
        except AssertionError as err:
            print(f'Error: {err}', file=sys.stderr)
            res = 1

    # Generate python dependencies.
    python_dependencies.process_args(args, start_time)

    return res
示例#8
0
    print(f'Transaction sent. tx_hash={tx_hash} .')
    receipt = w3.eth.waitForTransactionReceipt(tx_hash)
    print('Transaction successfully mined.')
    return receipt


def get_merkle_root(accounts: Dict[int, Balance]) -> int:
    """
    Returns the merkle root given accounts state.

    accounts: the state of the accounts (the merkle tree leaves).
    """
    tree = MerkleTree(tree_height=10, default_leaf=0)
    return tree.compute_merkle_root([
        (i, pedersen_hash(pedersen_hash(a.pub_key, a.balance.a), a.balance.b))
        for i, a in accounts.items()
    ])


def rand_transaction() -> SwapTransaction:
    """
    Draws a random swap transaction.
    """
    return SwapTransaction(account_id=random.randint(0, N_ACCOUNTS - 1),
                           token_a_amount=random.randint(1, 1000))


if __name__ == '__main__':
    with get_crypto_lib_context_manager('Release'):
        main()