Ejemplo n.º 1
0
 def as_generate_secret_hash(self, secret):
     secret_hash_cl = f"(sha256 (q {secret}))"
     sec = f"({secret})"
     cost, secret_hash_preformat = clvm.run_program(
         binutils.assemble("(sha256 (f (a)))"), binutils.assemble(sec))
     secret_hash = binutils.disassemble(secret_hash_preformat)
     return secret_hash
Ejemplo n.º 2
0
def run_and_return_cost_time(chialisp):

    start = time.time()
    clvm_loop = f"((c (q ((c (f (a)) (c (f (a)) (c (f (r (a))) (c (f (r (r (a)))) (q ()))))))) (c (q ((c (i (f (r (a))) (q (i (q 1) ((c (f (a)) (c (f (a)) (c (- (f (r (a))) (q 1)) (c (f (r (r (a)))) (q ())))))) ((c (f (r (r (a)))) (q ()))))) (q (q ()))) (a)))) (a))))"
    loop_program = Program(binutils.assemble(clvm_loop))
    clvm_loop_solution = f"(1000 {chialisp})"
    solution_program = Program(binutils.assemble(clvm_loop_solution))

    cost, sexp = run_program(loop_program, solution_program)

    end = time.time()
    total_time = end - start

    return cost, total_time
Ejemplo n.º 3
0
def get_output_amount_for_puzzle_and_solution(puzzle, solution):
    conditions = clvm.run_program(puzzle, solution)[1]
    amount = 0
    while conditions != b"":
        opcode = conditions.first().first()
        if opcode == b"3":  # Check if CREATE_COIN
            amount_str = binutils.disassemble(
                conditions.first().rest().rest().first())
            if amount_str == "()":
                conditions = conditions.rest()
                continue
            elif amount_str[0:2] == "0x":  # Check for wonky decompilation
                amount += int(amount_str, 16)
            else:
                amount += int(amount_str, 10)
        conditions = conditions.rest()
    return amount
Ejemplo n.º 4
0
 def as_solution_list(self, body_program):
     try:
         cost, sexp = clvm.run_program(body_program, [])
     except clvm.EvalError.EvalError:
         raise ValueError(body_program)
     npc_list = []
     for name_solution in sexp.as_iter():
         _ = name_solution.as_python()
         if len(_) != 2:
             raise ValueError(name_solution)
         if not isinstance(_[0], bytes) or len(_[0]) != 32:
             raise ValueError(name_solution)
         if not isinstance(_[1], list) or len(_[1]) != 2:
             raise ValueError(name_solution)
         puzzle_solution_program = name_solution.rest().first()
         puzzle_program = puzzle_solution_program.first()
         puzzle_hash = ProgramHash(Program(puzzle_program))
         npc_list.append((puzzle_hash, puzzle_solution_program))
     return npc_list
Ejemplo n.º 5
0
def curry(program, args):
    """
    ;; A "curry" binds values to a function, making them constant,
    ;; and returning a new function that returns fewer arguments (since the
    ;; arguments are now fixed).
    ;; Example: (defun add2 (V1 V2) (+ V1 V2))  ; add two values
    ;; (curry add2 15) ; this yields a function that accepts ONE argument, and adds 15 to it

    `program`: an SExp
    `args`: an SExp that is a list of constants to be bound to `program`
    """

    args = SExp.to((program, args))
    r = run_program(
        CURRY_OBJ_CODE,
        args,
        quote_kw=KEYWORD_TO_ATOM["q"],
        operator_lookup=OPERATOR_LOOKUP,
    )
    return r
Ejemplo n.º 6
0
def get_name_puzzle_conditions(
    block_program: Program, ) -> Tuple[Optional[Err], List[NPC], uint64]:
    """
    Returns an error if it's unable to evaluate, otherwise
    returns a list of NPC (coin_name, solved_puzzle_hash, conditions_dict)
    """
    cost_sum = 0
    try:
        cost_run, sexp = run_program(block_program, [])
        cost_sum += cost_run
    except EvalError:
        return Err.INVALID_COIN_SOLUTION, [], uint64(0)

    npc_list = []
    for name_solution in sexp.as_iter():
        _ = name_solution.as_python()
        if len(_) != 2:
            return Err.INVALID_COIN_SOLUTION, [], uint64(cost_sum)
        if not isinstance(_[0], bytes) or len(_[0]) != 32:
            return Err.INVALID_COIN_SOLUTION, [], uint64(cost_sum)
        coin_name = bytes32(_[0])
        if not isinstance(_[1], list) or len(_[1]) != 2:
            return Err.INVALID_COIN_SOLUTION, [], uint64(cost_sum)
        puzzle_solution_program = name_solution.rest().first()
        puzzle_program = puzzle_solution_program.first()
        puzzle_hash = Program(puzzle_program).get_hash()
        try:
            error, conditions_dict, cost_run = conditions_dict_for_solution(
                puzzle_solution_program)
            cost_sum += cost_run
            if error:
                return error, [], uint64(cost_sum)
        except clvm.EvalError:
            return Err.INVALID_COIN_SOLUTION, [], uint64(cost_sum)
        if conditions_dict is None:
            conditions_dict = {}
        npc: NPC = NPC(coin_name, puzzle_hash, conditions_dict)
        npc_list.append(npc)

    return None, npc_list, uint64(cost_sum)
Ejemplo n.º 7
0
def solution_for_contract(contract, puzzle_parameters, solution_parameters):
    cost, r = run_program(
        contract, Program.to((1, (puzzle_parameters, solution_parameters))))
    return r
Ejemplo n.º 8
0
def puzzle_for_contract(contract, puzzle_parameters):
    env = Program.to([]).cons(Program.to(puzzle_parameters))
    cost, r = run_program(contract, env)
    return Program.to(r)
def run(program, args):
    sexp = binutils.assemble(program)

    cost, r = run_program(sexp, args)

    return r.as_python()
Ejemplo n.º 10
0
            ConditionOpcode.ASSERT_MY_COIN_ID: [
                ConditionVarPair(ConditionOpcode.ASSERT_MY_COIN_ID,
                                 token_bytes(), None)
            ]
        })
        puzzle = puzzle_for_pk(public_key)
        puzzles.append(puzzle)
        solutions.append(solution)
        private_keys.append(private_key)
        public_keys.append(public_key)

    # Run Puzzle 1000 times
    puzzle_start = time.time()
    clvm_cost = 0
    for i in range(0, 1000):
        cost_run, sexp = run_program(puzzles[i], solutions[i])
        clvm_cost += cost_run

    puzzle_end = time.time()
    puzzle_time = puzzle_end - puzzle_start
    print(f"Puzzle_time is: {puzzle_time}")
    print(f"Puzzle cost sum is: {clvm_cost}")

    private_key = BLSPrivateKey(
        extended_secret_key.private_child(0).get_private_key())
    public_key = private_key.public_key()
    message = token_bytes()
    signature = private_key.sign(message)
    pk_message_pair = BLSSignature.PkMessagePair(public_key, message)

    # Run AggSig 1000 times
Ejemplo n.º 11
0
    async def search_for_parent_info(
        self, block_program: Program, removals: List[Coin]
    ) -> bool:

        """
        Returns an error if it's unable to evaluate, otherwise
        returns a list of NPC (coin_name, solved_puzzle_hash, conditions_dict)
        """
        cost_sum = 0
        try:
            cost_run, sexp = run_program(block_program, [])
            cost_sum += cost_run
        except EvalError:
            return False

        for name_solution in sexp.as_iter():
            _ = name_solution.as_python()
            if len(_) != 2:
                return False
            if not isinstance(_[0], bytes) or len(_[0]) != 32:
                return False
            coin_name = bytes32(_[0])
            if not isinstance(_[1], list) or len(_[1]) != 2:
                return False
            puzzle_solution_program = name_solution.rest().first()
            puzzle_program = puzzle_solution_program.first()
            try:
                error, conditions_dict, cost_run = conditions_dict_for_solution(
                    puzzle_solution_program
                )
                cost_sum += cost_run
                if error:
                    return False
            except clvm.EvalError:

                return False
            if conditions_dict is None:
                conditions_dict = {}

            if ConditionOpcode.CREATE_COIN in conditions_dict:
                created_output_conditions = conditions_dict[ConditionOpcode.CREATE_COIN]
            else:
                continue
            for cvp in created_output_conditions:
                result = await self.wallet_state_manager.puzzle_store.wallet_info_for_puzzle_hash(
                    cvp.var1
                )
                if result is None:
                    continue

                wallet_id, wallet_type = result
                if wallet_id != self.wallet_info.id:
                    continue

                coin = None
                for removed in removals:
                    if removed.name() == coin_name:
                        coin = removed
                        break

                if coin is not None:
                    if cc_wallet_puzzles.check_is_cc_puzzle(puzzle_program):
                        puzzle_string = binutils.disassemble(puzzle_program)
                        inner_puzzle_hash = hexstr_to_bytes(
                            get_innerpuzzle_from_puzzle(puzzle_string)
                        )
                        self.log.info(
                            f"parent: {coin_name} inner_puzzle for parent is {inner_puzzle_hash.hex()}"
                        )

                        await self.add_parent(
                            coin_name,
                            CCParent(
                                coin.parent_coin_info, inner_puzzle_hash, coin.amount
                            ),
                        )

                return True

        return False