Ejemplo n.º 1
0
def test_deploy_do_nothing_and_call_by_entry_point_and_version(
    casperlabs_client, faucet_funded_accounts, algorithm
):
    key_holder, private_key_pem_path = faucet_funded_accounts[algorithm]

    deploy_hash = casperlabs_client.deploy(
        session=WASM_DIRECTORY / "test_payment_stored.wasm",
        payment_amount=10000000,
        private_key=private_key_pem_path,
    )
    result = casperlabs_client.show_deploy(
        deploy_hash, wait_for_processed=True, timeout_seconds=300
    )
    for block_info in result.processing_results:
        assert (
            not block_info.is_error
        ), f"block_info.is_error: {block_info.error_message}"
    assert len(result.processing_results) > 0, "No block_info returned"

    deploy_hash = casperlabs_client.deploy(
        session=WASM_DIRECTORY / "transfer_to_account_u512_stored.wasm",
        payment_name="test_payment_hash",
        payment_entry_point="pay",
        payment_args=ABI.args([ABI.big_int("amount", 10000000)]),
        private_key=private_key_pem_path,
    )
    result = casperlabs_client.show_deploy(
        deploy_hash, wait_for_processed=True, timeout_seconds=300
    )
    for block_info in result.processing_results:
        assert (
            not block_info.is_error
        ), f"block_info.is_error: {block_info.error_message}"
    assert len(result.processing_results) > 0, "No block_info returned"

    session_args = ABI.args(
        [
            ABI.account(
                "target",
                "1000000000000000000000000000000000000000000000000000000000000000",
            ),
            ABI.big_int("amount", 123),
        ]
    )

    deploy_hash = casperlabs_client.deploy(
        session_name="transfer_to_account",
        session_entry_point="transfer",
        session_args=session_args,
        payment_amount=10000000,
        private_key=private_key_pem_path,
    )
    result = casperlabs_client.show_deploy(
        deploy_hash, wait_for_processed=True, timeout_seconds=300
    )
    for block_info in result.processing_results:
        assert (
            not block_info.is_error
        ), f"block_info.is_error: {block_info.error_message}"
    assert len(result.processing_results) > 0, "No block_info returned"
Ejemplo n.º 2
0
def faucet_fund_account(casperlabs_client,
                        account_hash_hex,
                        amount=10000000000):
    faucet_wasm_path = WASM_DIRECTORY / "faucet.wasm"
    assert faucet_wasm_path.exists(), (
        f"Needed wasm file: {faucet_wasm_path} does not exist.\n"
        "It should be built in `build_contracts.sh`.")
    session_args = ABI.args([
        ABI.account("target", account_hash_hex),
        ABI.big_int("amount", amount)
    ])

    deploy_hash = casperlabs_client.deploy(
        private_key=FAUCET_PRIVATE_KEY_PEM_PATH,
        session=faucet_wasm_path,
        session_args=session_args,
        payment_amount=1000000,
    )
    result = casperlabs_client.show_deploy(deploy_hash,
                                           wait_for_processed=True)
    assert (len(result.processing_results) >
            0), "No processing results from faucet transfer"
    block_hash = result.processing_results[0].block_info.summary.block_hash
    result = casperlabs_client.balance(account_hash_hex, block_hash.hex())
    assert result > 0, "balance of new account is not correct"
Ejemplo n.º 3
0
def do_transfer(
    ctx: ExecutionContext,
    cp1: Account,
    cp2: Account,
    amount: int,
    contract: ClientContract = None,
    is_refundable: bool = True,
    deploy_type: DeployType = DeployType.TRANSFER
) -> typing.Tuple[Deploy, Transfer]:
    """Executes a transfer between 2 counter-parties & returns resulting deploy hash.

    :param ctx: Execution context information.
    :param cp1: Account information of counter party 1.
    :param cp2: Account information of counter party 2.
    :param amount: Amount in motes to be transferred.
    :param contract: The transfer contract to call (if any).
    :param is_refundable: Flag indicating whether a refund is required.
    :param deploy_type: The type of deploy to dispatch.

    :returns: Dispatched deploy & transfer.

    """
    # Set client.
    node, client = utils.get_client(ctx)

    # Transfer using called contract - does not dispatch wasm.
    if contract:
        session_args = ABI.args([
            ABI.account("address", cp2.public_key),
            ABI.big_int("amount", amount)
        ])
        dhash = client.deploy(
            session_hash=bytes.fromhex(contract.chash),
            session_args=session_args,
            from_addr=cp1.public_key,
            private_key=cp1.private_key_as_pem_filepath,
            # TODO: allow these to be passed in via standard arguments
            payment_amount=defaults.CLX_TX_FEE,
            gas_price=defaults.CLX_TX_GAS_PRICE)

    # Transfer using stored contract - dispatches wasm.
    else:
        dhash = client.transfer(
            amount=amount,
            from_addr=cp1.public_key,
            private_key=cp1.private_key_as_pem_filepath,
            target_account_hex=cp2.public_key,
            # TODO: allow these to be passed in via standard arguments
            payment_amount=defaults.CLX_TX_FEE,
            gas_price=defaults.CLX_TX_GAS_PRICE)

    logger.log(
        f"PYCLX :: transfer :: {dhash} :: {amount} CLX :: {cp1.public_key[:8]} -> {cp2.public_key[:8]}"
    )

    return (node, dhash)
Ejemplo n.º 4
0
def test_legacy_args_from_json():
    json_str = json.dumps(LEGACY_ARGS)
    args = ABI.args_from_json(json_str)
    assert args[0] == ABI.long_value("amount", long_value)
    assert args[1] == ABI.account("account", account)
    assert args[2] == ABI.optional_value("main_purse", None)
    assert args[3] == ABI.big_int("number", big_int_value)
    assert args[4] == ABI.bytes_value("my_bytes", account)

    assert args[5] == ABI.key_hash("my_hash", account)
    assert args[6] == ABI.key_address("my_address", account)
    assert args[7] == ABI.key_uref("my_uref", account, access_rights=5)
    assert args[8] == ABI.key_local("my_local", account)
Ejemplo n.º 5
0
def _deploy_kwargs(args, private_key_accepted=True):
    from_addr = (
        getattr(args, "from")
        and bytes.fromhex(getattr(args, "from"))
        or getattr(args, "public_key")
        and read_pem_key(args.public_key)
        or private_to_public_key(args.private_key)
    )
    if from_addr and len(from_addr) != 32:
        raise Exception(
            "--from must be 32 bytes encoded as 64 characters long hexadecimal"
        )

    if not (args.payment_amount or args.payment_args):
        args.payment_amount = DEFAULT_PAYMENT_AMOUNT

    if args.payment_amount:
        args.payment_args = ABI.args_to_json(
            ABI.args([ABI.big_int("amount", int(args.payment_amount))])
        )

    d = dict(
        from_addr=from_addr,
        gas_price=args.gas_price,
        payment=args.payment,
        session=args.session,
        public_key=args.public_key or None,
        session_args=args.session_args
        and ABI.args_from_json(args.session_args)
        or None,
        payment_args=args.payment_args
        and ABI.args_from_json(args.payment_args)
        or None,
        payment_hash=args.payment_hash and bytes.fromhex(args.payment_hash),
        payment_name=args.payment_name,
        payment_uref=args.payment_uref and bytes.fromhex(args.payment_uref),
        session_hash=args.session_hash and bytes.fromhex(args.session_hash),
        session_name=args.session_name,
        session_uref=args.session_uref and bytes.fromhex(args.session_uref),
        ttl_millis=args.ttl_millis,
        dependencies=args.dependencies,
        chain_name=args.chain_name,
    )
    if private_key_accepted:
        d["private_key"] = args.private_key or None
    return d
Ejemplo n.º 6
0
def test_args_to_json():
    args = [
        ABI.long_value("amount", long_value),
        ABI.account("account", account),
        ABI.optional_value("purse_id", None),
        ABI.big_int("number", big_int_value),
        ABI.bytes_value("my_bytes", account),
        ABI.key_hash("my_hash", account),
        ABI.key_address("my_address", account),
        ABI.key_uref("my_uref", account, access_rights=5),
        ABI.key_local("my_local", account),
    ]
    json_str1 = json.dumps(ARGS, ensure_ascii=True, sort_keys=True, indent=2)
    json_str2 = ABI.args_to_json(ABI.args(args),
                                 ensure_ascii=True,
                                 sort_keys=True,
                                 indent=2)
    assert json_str1 == json_str2
Ejemplo n.º 7
0
def faucet_fund_account(casperlabs_client,
                        account_hash_hex,
                        amount=1000000000):
    faucet_wasm_path = WASM_DIRECTORY / "faucet.wasm"
    session_args = ABI.args([
        ABI.account("target", account_hash_hex),
        ABI.big_int("amount", amount)
    ])
    # TODO: validate faucet key path to make sure key gen worked during standup.
    deploy_hash = casperlabs_client.deploy(
        private_key=FAUCET_PRIVATE_KEY_PEM_PATH,
        session=faucet_wasm_path,
        session_args=session_args,
    )
    result = casperlabs_client.show_deploy(deploy_hash,
                                           wait_for_processed=True)
    block_hash = result.processing_results[0].block_info.summary.block_hash
    result = casperlabs_client.balance(account_hash_hex, block_hash.hex())
    assert result > 0
Ejemplo n.º 8
0
def test_args_to_json():
    args = [
        ABI.long_value("amount", long_value),
        ABI.account("account", account),
        ABI.optional_value("main_purse", None),
        ABI.big_int("number", big_int_value),
        ABI.bytes_value("my_bytes", account),
        ABI.key_hash("my_hash", account),
        ABI.key_address("my_address", account),
        ABI.key_uref("my_uref", account, access_rights=5),
        ABI.key_local("my_local", account),
    ]
    json_str1 = json.dumps(LEGACY_ARGS,
                           ensure_ascii=True,
                           sort_keys=True,
                           indent=2)
    json_str2 = ABI.args_to_json(ABI.args(args),
                                 ensure_ascii=True,
                                 sort_keys=True,
                                 indent=2)
    # TODO: fix this test to use new json format
    assert json_str1 != json_str2
Ejemplo n.º 9
0
def _deploy_kwargs(args, private_key_accepted=True):
    from_addr = (getattr(args, "from") and bytes.fromhex(getattr(args, "from"))
                 or private_to_public_key(args.private_key))
    if from_addr and len(from_addr) != 32:
        raise Exception(
            "--from must be 32 bytes encoded as 64 characters long hexadecimal"
        )

    if args.payment_amount:
        args.payment_args = ABI.args_to_json(
            ABI.args([ABI.big_int("amount", int(args.payment_amount))]))
        # Unless one of payment* options supplied use bundled standard-payment
        if not any((args.payment, args.payment_name, args.payment_hash,
                    args.payment_uref)):
            args.payment = bundled_contract("standard_payment.wasm")

    d = dict(
        from_addr=from_addr,
        gas_price=args.gas_price,
        payment=args.payment or args.session,
        session=args.session,
        public_key=args.public_key or None,
        session_args=args.session_args
        and ABI.args_from_json(args.session_args) or None,
        payment_args=args.payment_args
        and ABI.args_from_json(args.payment_args) or None,
        payment_hash=args.payment_hash and bytes.fromhex(args.payment_hash),
        payment_name=args.payment_name,
        payment_uref=args.payment_uref and bytes.fromhex(args.payment_uref),
        session_hash=args.session_hash and bytes.fromhex(args.session_hash),
        session_name=args.session_name,
        session_uref=args.session_uref and bytes.fromhex(args.session_uref),
        ttl_millis=args.ttl_millis,
        dependencies=args.dependencies,
        chain_name=args.chain_name,
    )
    if private_key_accepted:
        d["private_key"] = args.private_key or None
    return d
Ejemplo n.º 10
0
    STANDARD_PAYMENT = "standard_payment.wasm"
    SUBCALL_REVERT_CALL = "subcall_revert_call.wasm"
    SUBCALL_REVERT_DEFINE = "subcall_revert_define.wasm"
    TRANSFER_TO_ACCOUNT = "transfer_to_account_u512.wasm"
    UPDATE_ASSOCIATED_KEY = "update_associated_key.wasm"


# TEST Account Use Notes
# test_transfer_to_accounts: 300, 299, 298
# test_transfer_with_overdraft: 297, 296
# test_bonding: 295

MAX_PAYMENT_COST = 10000000
DEFAULT_PAYMENT_COST = 100000000
INITIAL_MOTES_AMOUNT = 10**20
MAX_PAYMENT_ABI = ABI.args([ABI.big_int("amount", MAX_PAYMENT_COST)])
DEFAULT_PAYMENT_ABI = ABI.args([ABI.big_int("amount", DEFAULT_PAYMENT_COST)])
CONV_RATE = 10
TEST_ACCOUNT_INITIAL_BALANCE = 1000000000
USER_ERROR_MIN = 65536

BOOTSTRAP_PATH = "/root/.casperlabs/bootstrap"

# Empty /etc/casperlabs means it has no chainspec.
# This is a directory in resources that will be mounted
# as /etc/casperlabs in the node's docker container.
EMPTY_ETC_CASPERLABS = "etc_casperlabs_empty"


@dataclasses.dataclass(eq=True, frozen=True)
class KeyPair:
Ejemplo n.º 11
0
class CLI:

    _DEFAULT_PAYMENT_JSON = ABI.args_to_json(
        ABI.args([ABI.big_int("amount", DEFAULT_PAYMENT_COST)]))

    def __init__(self, node, cli_cmd="casperlabs_client", tls_parameters=None):
        self.node = node
        self.host = (os.environ.get("TAG_NAME", None) and node.container_name
                     or "localhost")
        self.port = node.grpc_external_docker_port
        self.port_internal = node.grpc_internal_docker_port
        self.cli_cmd = cli_cmd
        self.tls_parameters = tls_parameters or {}
        self.default_deploy_args = []
        self.resources_directory = resources_path()

    def set_default_deploy_args(self, *args):
        """ Set args that will be appended to subsequent deploy command. """
        self.default_deploy_args = [str(arg) for arg in args]

    def resource(self, file_name):
        return self.resources_directory / file_name

    @property
    def _local_connection_details(self):
        return [
            "--host",
            f"{self.host}",
            "--port",
            f"{self.port}",
            "--port-internal",
            f"{self.port_internal}",
        ]

    def expand_args(self, args):
        connection_details = self._local_connection_details
        if self.tls_parameters:
            connection_details += reduce(
                add,
                [[str(p), str(self.tls_parameters[p])]
                 for p in self.tls_parameters],
            )
        string_args = [str(a) for a in list(args)]

        if args and args[0] == "deploy":
            string_args += self.default_deploy_args

        return "--help" in args and string_args or connection_details + string_args

    @staticmethod
    def parse_output(command, binary_output):

        if command in ("make-deploy", "sign-deploy"):
            return binary_output

        output = binary_output.decode("utf-8")

        if command in ("deploy", "send-deploy", "bond", "unbond", "transfer"):
            return output.split()[2]
            # "Success! Deploy 0d4036bebb95de793b28de452d594531a29f8dc3c5394526094d30723fa5ff65 deployed."

        if command == "show-blocks":
            return parse_show_blocks(output)

        if command == "show-deploys":
            return parse_show_deploys(output)

        if command in ("show-deploy", "show-block", "query-state"):
            return parse(output)

        if command in ("balance", ):
            # 'Balance:\n9d39b7fba47d07c1af6f711efe604a112ab371e2deefb99a613d2b3dcdfba414 : 1000000000'
            return int(output.split(":")[-1])

        return output

    def __call__(self, *args):
        command_line = [str(self.cli_cmd)] + self.expand_args(args)
        # logging.info(f"EXECUTING []: {command_line}")
        logging.info(f"EXECUTING: {' '.join(command_line)}")
        cp = subprocess.run(command_line,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
        binary_output = cp.stdout
        if cp.returncode != 0:
            output = binary_output
            try:
                output = binary_output.decode("utf-8")
            except UnicodeDecodeError:
                pass
            raise CLIErrorExit(cp, output)

        return self.parse_output(args[0], binary_output)

    def public_key_path(self, account):
        return account.public_key_path

    def private_key_path(self, account):
        return account.private_key_path

    def format_json_str(self, args: str) -> str:
        return args

    @property
    def payment_json(self) -> str:
        return self.format_json_str(self._DEFAULT_PAYMENT_JSON)
def disable_test_multiple_deploys_per_block(cli):
    """
    Two deploys from the same account then propose.
    Both deploys should be be included in the new block.

    Create named purses to pay from for each deploy
    (standard payment cannot be used because it causes
    a WRITE against the main purse balance, but every
    deploy has a READ against that balance to check it meets
    the minimum balance condition, so standard payment calls
    always conflict with any other deploy from the same account)
    """
    account = cli.node.test_account
    cli.set_default_deploy_args('--from',
                                account.public_key_hex, '--private-key',
                                cli.private_key_path(account), '--public-key',
                                cli.public_key_path(account))

    # Create purse_1
    deploy_hash = cli(
        'deploy', '--session', cli.resource(Contract.CREATE_NAMED_PURSE),
        '--session-args',
        ABI.args_to_json(
            ABI.args([
                ABI.big_int("amount", 100000000),
                ABI.string_value("purse-name", "purse_1")
            ])), '--payment', cli.resource(Contract.STANDARD_PAYMENT),
        '--payment-args',
        ABI.args_to_json(ABI.args([ABI.big_int("amount", 100000000)])))
    check_no_errors(cli, deploy_hash)

    # Create purse_2
    deploy_hash = cli(
        'deploy', '--session', cli.resource(Contract.CREATE_NAMED_PURSE),
        '--session-args',
        ABI.args_to_json(
            ABI.args([
                ABI.big_int("amount", 100000000),
                ABI.string_value("purse-name", "purse_2")
            ])), '--payment', cli.resource(Contract.STANDARD_PAYMENT),
        '--payment-args',
        ABI.args_to_json(ABI.args([ABI.big_int("amount", 100000000)])))
    check_no_errors(cli, deploy_hash)

    # First deploy uses first purse for payment
    deploy_hash1 = cli(
        'deploy', '--from', account.public_key_hex, '--session',
        cli.resource(Contract.COUNTER_DEFINE), '--payment',
        cli.resource(Contract.PAYMENT_FROM_NAMED_PURSE), '--payment-args',
        ABI.args_to_json(
            ABI.args([
                ABI.big_int("amount", 100000000),
                ABI.string_value("purse-name", "purse_1")
            ])))

    # Second deploy uses second purse for payment
    deploy_hash2 = cli(
        'deploy', '--from', account.public_key_hex, '--session',
        cli.resource(Contract.MAILING_LIST_DEFINE), '--payment',
        cli.resource(Contract.PAYMENT_FROM_NAMED_PURSE), '--payment-args',
        ABI.args_to_json(
            ABI.args([
                ABI.big_int("amount", 100000000),
                ABI.string_value("purse-name", "purse_2")
            ])))
    block_hash = check_no_errors(cli, deploy_hash2)

    # Propose should include both deploys.
    deploys = list(cli("show-deploys", block_hash))
    # TODO: with auto-propose this may fail:
    assert len(deploys) == 2
    assert set(d.deploy.deploy_hash for d in deploys) == set(
        (deploy_hash1, deploy_hash2))