コード例 #1
0
def main():
    god_key = PrivateKey.generate()
    alice_key = PrivateKey.generate()
    bob_key = PrivateKey.generate()

    god_addr = god_key.get_public_key().get_rev_address()
    alice_addr = alice_key.get_public_key().get_rev_address()
    bob_addr = bob_key.get_public_key().get_rev_address()

    with grpc.insecure_channel('172.27.0.2:40401') as channel:
        client = RClient(channel)

        god_vault_api = VaultAPI(client, god_key)
        alice_vault_api = VaultAPI(client, alice_key)
        bob_vault_api = VaultAPI(client, bob_key)

        # Most methods without deploy_ prefix create block (propose) after
        # deploy. To deploy a batch and then create block do:
        #
        #  alice_vault_api.deploy_create_vault()
        #  bob_vault_api.deploy_create_vault()
        #  client.propose()

        alice_vault_api.create_vault()
        bob_vault_api.create_vault()

        assert god_vault_api.get_balance() == 100_000
        assert alice_vault_api.get_balance() == 0
        assert bob_vault_api.get_balance() == 0

        god_vault_api.transfer(None, alice_addr, 1000)

        # Example way to get balances in one block:

        god_bal_deploy_id = god_vault_api.deploy_get_balance()
        alice_bal_deploy_id = alice_vault_api.deploy_get_balance()
        bob_bal_deploy_id = bob_vault_api.deploy_get_balance()
        client.propose()

        god_bal = god_vault_api.get_balance_from_deploy_id(god_bal_deploy_id)
        alice_bal = alice_vault_api.get_balance_from_deploy_id(
            alice_bal_deploy_id)
        bob_bal = bob_vault_api.get_balance_from_deploy_id(bob_bal_deploy_id)

        assert god_bal == 99_000
        assert alice_bal == 1000
        assert bob_bal == 0

        alice_vault_api.transfer(None, bob_addr, 400)

        assert god_vault_api.get_balance() == 99_000
        assert alice_vault_api.get_balance() == 600
        assert bob_vault_api.get_balance() == 400
コード例 #2
0
def test_sign_verify_good(key_hex: str, pub_key_hex: str,
                          rev_address: str) -> None:
    key = PrivateKey.from_hex(key_hex)
    pub_key = PublicKey.from_hex(pub_key_hex)
    message = 'hello rchain'.encode()
    signature = key.sign(message)
    pub_key.verify(signature, message)
コード例 #3
0
def test_publickey_from_hex(key_hex: str, pub_key_hex: str,
                            rev_address: str) -> None:
    key = PrivateKey.from_hex(key_hex)
    pub_key = PublicKey.from_hex(pub_key_hex)
    expected_pub_key_bytes = key.get_public_key().to_bytes()
    actual_pub_key_bytes = pub_key.to_bytes()
    assert expected_pub_key_bytes == actual_pub_key_bytes
コード例 #4
0
ファイル: http_client.py プロジェクト: scala-steward/rchain
 def deploy(self, term: str, phlo_limit: int, phlo_price: int,
            valid_after_block_number: int, deployer: PrivateKey) -> str:
     timestamp = int(time.time() * 1000)
     deploy_data = {
         "term": term,
         "timestamp": timestamp,
         "phloLimit": phlo_limit,
         "phloPrice": phlo_price,
         "validAfterBlockNumber": valid_after_block_number
     }
     deploy_proto = DeployDataProto(
         term=term,
         timestamp=timestamp,
         phloLimit=phlo_limit,
         phloPrice=phlo_price,
         validAfterBlockNumber=valid_after_block_number)
     deploy_req = {
         "data": deploy_data,
         "deployer": deployer.get_public_key().to_hex(),
         "signature": sign_deploy_data(deployer, deploy_proto).hex(),
         "sigAlgorithm": "secp256k1"
     }
     deploy_url = self.url + '/deploy'
     rep = requests.post(deploy_url, json=deploy_req)
     _check_reponse(rep)
     return rep.text
コード例 #5
0
ファイル: testnet.py プロジェクト: bitcard/transaction-server
def faucetPost(faucetRequest: FaucetRequest, request: Request):
    address = faucetRequest.address
    ip = ipaddress.ip_address(request.client.host)
    if ip.is_private:
        host = request.headers.get('X-Real-IP')
        if host:
            addr = ipaddress.ip_address(host)
        else:
            addr = request.client.host
    else:
        addr = request.client.host
    request_before = request_faucet_TTCache.get(addr)
    if request_before:
        return FaucetResponse(deployID=request_before[1],
                              message='IP:{}, Your request for testnet rev to {} is too high. Try later'.format(
                                  addr, request_before[0]))
    else:
        try:
            with RClient(setting.TARGET_TESTNET_HOST, setting.TARGET_TESTNET_PORT) as client:
                vault = VaultAPI(client)
                private = PrivateKey.from_hex(setting.TESTNET_FAUCET_PRIVATE_KEY)
                deployId = vault.transfer_ensure(private.get_public_key().get_rev_address(), address,
                                                 setting.TESTNET_FAUCET_AMOUNT, private)
                request_faucet_TTCache[addr] = (address, deployId, request.client.host)
                return FaucetResponse(deployID=deployId,
                                      message="Transfer to your address is done. You will receive the rev in some time")
        except RClientException as e:
            return FaucetResponse(deployID='',
                                  message="There is something with server {}. "
                                          "Please contact the maintainer to solve it.".format(e))
コード例 #6
0
ファイル: __main__.py プロジェクト: zsluedem/pyrchain
def sign_deploy(private_key: str, term: str, phlo_price: int, phlo_limit: int,
                valid_after_block_number: int, timestamp: int,
                sig_algorithm: str) -> None:
    pri = PrivateKey.from_hex(private_key)
    signed_deploy = create_deploy_data(pri, term, phlo_price, phlo_limit,
                                       valid_after_block_number, timestamp)
    click.echo(signed_deploy.sig.hex())
コード例 #7
0
    def __init__(self, config):
        self.setup_error_log(config['error_logs'])
        logging.info("Initialing dispatcher")
        self._config = config

        self.clients = {}
        for server in config['servers']:
            for host_name, host_config in server.items():
                self.clients[host_name] = init_client(host_name, host_config)

        logging.info("Read the deploying contract {}".format(
            config['deploy']['contract']))
        with open(config['deploy']['contract']) as f:
            self.contract = f.read()
        logging.info("Checking if deploy key is valid.")
        self.deploy_key = PrivateKey.from_hex(config['deploy']['deploy_key'])

        self.phlo_limit = int(config['deploy']['phlo_limit'])
        self.phlo_price = int(config['deploy']['phlo_price'])

        self.wait_timeout = int(config['waitTimeout'])
        self.wait_interval = int(config['waitInterval'])

        self.error_node_records = config['error_node_records']

        self.init_queue()

        self._running = False
コード例 #8
0
def faucet(address: str, request: Request):
    request_before = request_faucet_TTCache.get(request.client.host)
    if request_before:
        return FaucetResponse(
            deployID='',
            message='Your request for testnet rev is too high. Try later.')
    else:
        try:
            with RClient(setting.TARGET_TESTNET_HOST,
                         setting.TARGET_TESTNET_PORT) as client:
                vault = VaultAPI(client)
                private = PrivateKey.from_hex(
                    setting.TESTNET_FAUCET_PRIVATE_KEY)
                deployId = vault.transfer(
                    private.get_public_key().get_rev_address(), address,
                    setting.TESTNET_FAUCET_AMOUNT, private)
                request_faucet_TTCache[request.client.host] = address
                return FaucetResponse(
                    deployID=deployId,
                    message=
                    "Transfer to your address is done. You will receive the rev in some time"
                )
        except RClientException as e:
            return FaucetResponse(
                deployID='',
                message="There is something with server {}. "
                "Please contact the maintainer to solve it.".format(e))
コード例 #9
0
def test_sign_block_hash_verify_good(key_hex: str, pub_key_hex: str,
                                     rev_address: str) -> None:
    key = PrivateKey.from_hex(key_hex)
    pub_key = PublicKey.from_hex(pub_key_hex)
    message = 'hello rchain'.encode()
    digest = blake2b_32(message).digest()
    signature = key.sign_block_hash(digest)
    pub_key.verify_block_hash(signature, digest)
コード例 #10
0
ファイル: test_internal.py プロジェクト: scala-steward/rchain
def test_make_wallets_file_lines() -> None:
    wallets_map = {
        PrivateKey.from_hex("80366db5fbb8dad7946f27037422715e4176dda41d582224db87b6c3b783d709"):
        40,
        PrivateKey.from_hex("120d42175739387af0264921bb117e4c4c05fbe2ce5410031e8b158c6e414bb5"):
        45,
        PrivateKey.from_hex("1f52d0bce0a92f5c79f2a88aae6d391ddf853e2eb8e688c5aa68002205f92dad"):
        26
    }

    output = make_wallets_file_lines(wallets_map)

    assert output == [
        '26218db6e5a2eed1901f72cea58fda7ef1f602c6,40,0',
        '42c828c183163cb50f6ad5207a10899b59aae91c,45,0',
        '2a11fd494610330f3b522562f7204670f8928133,26,0',
    ]
コード例 #11
0
def test_sign_verify_bad(key_hex: str, pub_key_hex: str,
                         rev_address: str) -> None:
    key = PrivateKey.from_hex(key_hex)
    pub_key = PublicKey.from_hex(pub_key_hex)
    sign_message = 'hello rchain'.encode()
    verify_message = 'hello world'.encode()
    signature = key.sign(sign_message)
    with pytest.raises(BadSignatureError):
        pub_key.verify(signature, verify_message)
コード例 #12
0
def test_sign_block_hash_verify_bad(key_hex: str, pub_key_hex: str,
                                    rev_address: str) -> None:
    key = PrivateKey.from_hex(key_hex)
    pub_key = PublicKey.from_hex(pub_key_hex)
    sign_message = 'hello rchain'.encode()
    verify_message = 'hello world'.encode()
    block_hash = blake2b_32(sign_message).digest()
    signature = key.sign_block_hash(block_hash)
    verify_digest = blake2b_32(verify_message).digest()
    with pytest.raises(BadSignatureError):
        pub_key.verify_block_hash(signature, verify_digest)
コード例 #13
0
ファイル: __main__.py プロジェクト: zsluedem/pyrchain
def get_rev_addr(input_type: str, input: str) -> None:
    if input_type == 'eth':
        click.echo(generate_rev_addr_from_eth(input))
    elif input_type == 'public':
        pub = PublicKey.from_hex(input)
        click.echo(pub.get_rev_address())
    elif input_type == 'private':
        private = PrivateKey.from_hex(input)
        click.echo(private.get_public_key().get_rev_address())
    else:
        raise NotImplementedError("Not supported type {}".format(input_type))
コード例 #14
0
ファイル: test_slash.py プロジェクト: scala-steward/rchain
def test_slash_justification_not_correct(command_line_options: CommandLineOptions, random_generator: Random, docker_client: DockerClient) -> None:
    """
    Slash a validator which proposed a block with justifications not matching bonded validators of main parent

    1. v1 proposes a valid block b1
    2. v1 proposes an invalid block b3 which contains justifications not matching bonded validators and send it to v2
    3. v2 records the invalid block b3 (InvalidFollows)
    4. v2 proposes a new block which slashes v1.
    """
    bonded_validators = {
        BOOTSTRAP_NODE_KEY: 100,
        BONDED_VALIDATOR_KEY_1: 100,
        BONDED_VALIDATOR_KEY_2: 100,
        BONDED_VALIDATOR_KEY_3: 100,
    }
    with three_nodes_network_with_node_client(command_line_options, random_generator, docker_client, validator_bonds_dict=bonded_validators) as  (context, _ , validator1, validator2, client):
        contract = '/opt/docker/examples/tut-hello.rho'

        validator1.deploy(contract, BONDED_VALIDATOR_KEY_1)
        blockhash = validator1.propose()

        wait_for_node_sees_block(context, validator2, blockhash)

        block_info = validator1.get_block(blockhash)

        block_msg = client.block_request(block_info.blockInfo.blockHash, validator1)

        invalid_justifications_block = BlockMessage()
        invalid_justifications_block.CopyFrom(block_msg)
        error_justification = Justification(validator=PrivateKey.generate().to_bytes(), latestBlockHash=block_msg.blockHash)

        invalid_justifications_block.justifications.append(error_justification)  # pylint: disable=maybe-no-member
        # change timestamp to make block hash different
        invalid_justifications_block.header.timestamp = block_msg.header.timestamp + 1  # pylint: disable=maybe-no-member
        invalid_block_hash = gen_block_hash_from_block(invalid_justifications_block)
        invalid_justifications_block.sig = BONDED_VALIDATOR_KEY_1.sign_block_hash(invalid_block_hash)
        invalid_justifications_block.blockHash = invalid_block_hash
        client.send_block(invalid_justifications_block, validator2)

        record_invalid = re.compile("Recording invalid block {}... for InvalidFollows".format(invalid_block_hash.hex()[:10]))
        wait_for_log_match(context, validator2, record_invalid)

        validator2.deploy(contract, BONDED_VALIDATOR_KEY_2)
        slashed_block_hash = validator2.propose()

        block_info = validator2.get_block(slashed_block_hash)
        bonds_validators = {b.validator: b.stake for b in block_info.blockInfo.bonds}

        assert bonds_validators[BONDED_VALIDATOR_KEY_1.get_public_key().to_hex()] == 0.0
コード例 #15
0
ファイル: test_cli.py プロジェクト: zsluedem/pyrchain
def test_sign_deploy(key: PrivateKey, terms: str, phlo_price: int, phlo_limit: int, valid_after_block_no: int,
                     timestamp_millis: int):
    runner = CliRunner()
    result = runner.invoke(cli, ['sign-deploy', '--private-key', key.to_hex(),
                                 '--term', terms,
                                 "--phlo-price", phlo_price,
                                 "--phlo-limit", phlo_limit,
                                 "--valid-after-block-number", valid_after_block_no,
                                 "--timestamp", timestamp_millis,
                                 "--sig-algorithm", "secp256k1"
                                 ])
    assert result.exit_code == 0
    sig = result.output.strip()

    data = DeployDataProto(
        deployer=key.get_public_key().to_bytes(),
        term=terms,
        phloPrice=phlo_price,
        phloLimit=phlo_limit,
        validAfterBlockNumber=valid_after_block_no,
        timestamp=timestamp_millis,
        sigAlgorithm='secp256k1',
    )
    assert verify_deploy_data(key.get_public_key(), bytes.fromhex(sig), data)
コード例 #16
0
ファイル: test_client.py プロジェクト: vx-qa/pyrchain
def test_client_deploy(key: PrivateKey, terms: str, phlo_price: int,
                       phlo_limit: int, valid_after_block_no: int,
                       timestamp_millis: int) -> None:
    class DummyDeploySerivce(DeployServiceServicer):
        def doDeploy(self, request: DeployDataProto,
                     context: grpc.ServicerContext) -> DeployResponse:
            return DeployResponse(result=request.sig.hex())

    with deploy_service(DummyDeploySerivce()) as (server, port), \
            RClient(TEST_HOST, port) as client:
        ret = client.deploy(key, terms, phlo_price, phlo_limit,
                            valid_after_block_no, timestamp_millis)
        assert verify_deploy_data(
            key.get_public_key(), bytes.fromhex(ret),
            create_deploy_data(key, terms, phlo_price, phlo_limit,
                               valid_after_block_no, timestamp_millis))
コード例 #17
0
def faucetPost(faucetRequest: FaucetRequest, request: Request):
    address = faucetRequest.address
    realIp = request.headers.get('X-Real-IP')
    if realIp:
        addr = ipaddress.ip_address(realIp)
    else:
        addr = request.client.host
    request_before = request_faucet_TTCache.get(addr)
    if request_before:
        return FaucetResponse(
            deployID=request_before[1],
            message=
            'IP:{}, Your request for testnet rev to {} is too high. Try later'.
            format(addr, request_before[0]))
    else:
        try:
            with RClient(setting.TARGET_TESTNET_HOST,
                         setting.TARGET_TESTNET_PORT) as client:
                private = PrivateKey.from_hex(
                    setting.TESTNET_FAUCET_PRIVATE_KEY)
                contract = render_contract_template(
                    TRANSFER_ENSURE_TO_RHO_TPL, {
                        'from': private.get_public_key().get_rev_address(),
                        'to': address,
                        'amount': str(setting.TESTNET_FAUCET_AMOUNT)
                    })
                timestamp_mill = int(time.time() * 1000)
                deployId = client.deploy_with_vabn_filled(
                    private, contract, TRANSFER_PHLO_PRICE,
                    TRANSFER_PHLO_LIMIT, timestamp_mill,
                    setting.TESTNET_FAUCET_SHARDID)
                request_faucet_TTCache[addr] = (address, deployId,
                                                request.client.host)
                return FaucetResponse(
                    deployID=deployId,
                    message=
                    "Transfer to your address is done. You will receive the rev in some time"
                )
        except RClientException as e:
            return FaucetResponse(
                deployID='',
                message="There is something with server {}. "
                "Please contact the maintainer to solve it.".format(e))
コード例 #18
0
ファイル: test_cli.py プロジェクト: zsluedem/pyrchain
def test_submit_deploy(key: PrivateKey, terms: str, phlo_price: int, phlo_limit: int, valid_after_block_no: int,
                       timestamp_millis: int):
    class DummyDeploySerivce(DeployServiceServicer):
        def doDeploy(self, request: DeployDataProto, context: grpc.ServicerContext) -> DeployResponse:
            return DeployResponse(result=request.sig.hex())

    with deploy_service(DummyDeploySerivce()) as (server, port):
        runner = CliRunner()
        result = runner.invoke(cli, ['submit-deploy', '--deployer', key.get_public_key().to_hex(),
                                     '--term', terms,
                                     "--phlo-price", phlo_price,
                                     "--phlo-limit", phlo_limit,
                                     "--valid-after-block-number", valid_after_block_no,
                                     "--timestamp", timestamp_millis,
                                     "--sig-algorithm", "secp256k1",
                                     "--sig", "1111",
                                     "--host", 'localhost',
                                     "--port", port
                                     ])
        assert result.exit_code == 0
コード例 #19
0
ファイル: test_wallets.py プロジェクト: scala-steward/rchain
def test_transfer_to_not_exist_vault(command_line_options: CommandLineOptions,
                                     docker_client: DockerClient,
                                     random_generator: Random) -> None:
    genesis_vault = {CHARLIE_KEY: 500000000, ALICE_KEY: 500000000}

    not_exist_vault = PrivateKey.generate()
    with testing_context(command_line_options, random_generator, docker_client, wallets_dict=genesis_vault) as context, \
            started_bootstrap_with_network(context=context) as bootstrap:

        transfer_amount = 2000000
        wait_for_approved_block_received_handler_state(context, bootstrap)
        alice_rev_address = ALICE_KEY.get_public_key().get_rev_address()
        no_exist_address = not_exist_vault.get_public_key().get_rev_address()

        alice_balance = get_vault_balance(context, bootstrap,
                                          alice_rev_address, CHARLIE_KEY,
                                          1000000, 1)
        assert alice_balance == 500000000

        with pytest.raises(WaitTimeoutError):
            # transfer to a vault which does not exist in the genesis vault
            # the result can not be got because the vault is not created in the tuplespace
            log_marker = random_string(context, 10)
            transfer_funds_result_pattern = re.compile(
                '"{} (Successfully|Failing) reason: (?P<reason>[a-zA-Z0-9 ]*)"'
                .format(log_marker))
            deploy_transfer(log_marker, bootstrap, alice_rev_address,
                            no_exist_address, transfer_amount, ALICE_KEY,
                            1000000, 1)
            wait_transfer_result(context, bootstrap,
                                 transfer_funds_result_pattern)

        # the get_vault_balance contract would call the method `findOrCreate` to generate the not-exist vault
        # then the transfer above can get the continuation and transfer is done
        no_vault_balance = get_vault_balance(context, bootstrap,
                                             no_exist_address, CHARLIE_KEY,
                                             1000000, 1)
        wait_transfer_result(context, bootstrap, transfer_funds_result_pattern)
        assert no_vault_balance == transfer_amount
コード例 #20
0
#!/usr/bin/python

import time

from rchain.client import RClient
from rchain.crypto import PrivateKey

from pyrgov.rgov import rgovAPI

RCHAIN_SERVER = ['localhost', 'rhobot']

admin = PrivateKey.from_hex(
    '28a5c9ac133b4449ca38e9bdf7cacdce31079ef6b3ac2f0a080af83ecff98b36')
alpha = PrivateKey.from_hex(
    '7139b72b9939334ff76e1479072c0558dca2c3620971c2bb233a7b25a690d610')
bravo = PrivateKey.from_hex(
    'dd0dd23cd51460e6c42a154623df19372be332f0a61a51755603ab897f6ede39')
#alpha = PrivateKey.generate()
#bravo = PrivateKey.generate()
charlie = PrivateKey.generate()


def print_balances(rgov: rgovAPI):
    # get balance of vault
    admin_balance = rgov.checkBalance(admin.get_public_key().get_rev_address())
    print("admin Balance ", admin_balance, " REV ",
          admin.get_public_key().get_rev_address())
    charlie_balance = rgov.checkBalance(
        charlie.get_public_key().get_rev_address())
    print("charlie Balance ", charlie_balance, " REV ",
          charlie.get_public_key().get_rev_address())
コード例 #21
0
from rchain.crypto import PrivateKey

PREGENERATED_KEYPAIRS = [
    PrivateKey.from_hex(
        "80366db5fbb8dad7946f27037422715e4176dda41d582224db87b6c3b783d709"),
    PrivateKey.from_hex(
        "120d42175739387af0264921bb117e4c4c05fbe2ce5410031e8b158c6e414bb5"),
    PrivateKey.from_hex(
        "1f52d0bce0a92f5c79f2a88aae6d391ddf853e2eb8e688c5aa68002205f92dad"),
    PrivateKey.from_hex(
        "5322dbb1828bdb44cb3275d35672bb3453347ee249a1f32d3c035e5ec3bfad1a"),
    PrivateKey.from_hex(
        "632a21e0176c4daed1ca78f08f98885f61d2050e0391e31eae59ff1a35ccca7f"),
    PrivateKey.from_hex(
        "2bdedd2e4dd2e7b5f176b7a5bc155f10fafd3fbd9c03fb7556f2ffd22c786f8b"),
    PrivateKey.from_hex(
        "ff2ba092524bafdbc85fa0c7eddb2b41c69bc9bf066a4711a8a16f749199e5be")
]
コード例 #22
0
ファイル: test_cli.py プロジェクト: zsluedem/pyrchain
import grpc
import pytest
from click.testing import CliRunner

from rchain.__main__ import cli
from rchain.crypto import PrivateKey
from rchain.pb.CasperMessage_pb2 import DeployDataProto
from rchain.pb.DeployServiceV1_pb2 import DeployResponse
from rchain.pb.DeployServiceV1_pb2_grpc import DeployServiceServicer
from rchain.util import verify_deploy_data

from .test_client import deploy_service

key = PrivateKey.generate()


def test_get_rev_from_private():
    runner = CliRunner()
    result = runner.invoke(cli, ['get-rev-addr', '--input-type', 'private', '--input',
                                 "1000000000000000000000000000000000000000000000000000000000000000"])
    assert result.exit_code == 0
    assert result.output == '1111cnoFDAa7GubxBMHpPLbbediPegnjSdZwNjxg9oqYvSvSmfqQL\n'


def test_get_rev_from_pub():
    runner = CliRunner()
    result = runner.invoke(cli, ['get-rev-addr', '--input-type', 'public', '--input',
                                 "0408ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"])
    assert result.exit_code == 0
    assert result.output == '1111cnoFDAa7GubxBMHpPLbbediPegnjSdZwNjxg9oqYvSvSmfqQL\n'
コード例 #23
0
# Requires the following line in wallets.txt
#
# 0x06a441c277bf454c5d159b0e5bdafca69b296733,1000000,0

import grpc

from rchain.crypto import PrivateKey
from rchain.client import RClient

from rchain.vault import VaultAPI

alice_key = PrivateKey.from_hex(
    "2a6cd3b196a0b154446a23443cee70629cdb3db0398ea6fb099175708f47f590")
alice_public_key = alice_key.get_public_key()

print("Private key is " + alice_key.to_hex())
print("Public key is " + alice_public_key.to_hex())
print("Eth address is " + alice_public_key.get_eth_address())
print("Rev address is " + alice_public_key.get_rev_address())

with grpc.insecure_channel('localhost:10401') as channel:
    client = RClient(channel)

    alice_vault_api = VaultAPI(client, alice_key)
    alice_vault_api.bond(amount=100)

    alice_bal_deploy_id = alice_vault_api.deploy_get_balance()
    client.propose()

    alice_bal = alice_vault_api.get_balance_from_deploy_id(alice_bal_deploy_id)
    assert alice_bal == 999900
コード例 #24
0
ファイル: test_wallets.py プロジェクト: scala-steward/rchain
from .conftest import (
    testing_context, )
from .rnode import (
    Node,
    started_bootstrap_with_network,
)
from .common import (
    TestingContext,
    TransderFundsError,
)
from .wait import (wait_for_log_match_result, wait_for_log_match_result_raise,
                   wait_for_approved_block_received_handler_state,
                   WaitTimeoutError)

ALICE_KEY = PrivateKey.from_hex(
    "b2527b00340a83e302beae2a8daf6d654e8e57541acfa261cc1b5635eb16aa15")
BOB_KEY = PrivateKey.from_hex(
    "9a801debae8bb97fe54c99389cafa576c60612503348578125b65ab182ff5850")
CHARLIE_KEY = PrivateKey.from_hex(
    "567ea426deaeb8233f134c3a266149fb196d6eea7d28b447dfefff92002cb400")


def wait_transfer_result(context: TestingContext, node: Node,
                         transfer_funds_result_pattern: Pattern) -> None:
    transfer_result_match = wait_for_log_match_result_raise(
        context, node, transfer_funds_result_pattern)
    reason = transfer_result_match.group('reason')
    if reason != "Nil":
        raise TransderFundsError(reason)

コード例 #25
0
ファイル: test_voting.py プロジェクト: rchain-community/rgov
#!/usr/bin/python

import time

from rchain.client import RClient
from rchain.crypto import PrivateKey
from rchain.util import create_deploy_data

from pyrgov.rgov import rgovAPI

RCHAIN_SERVER = ['localhost', 'rhobot', 'testnet', 'demo', 'mainnet']

TRANSFER_PHLO_LIMIT = 10000000
TRANSFER_PHLO_PRICE = 1

admin = PrivateKey.from_hex('28a5c9ac133b4449ca38e9bdf7cacdce31079ef6b3ac2f0a080af83ecff98b36')
alpha = PrivateKey.from_hex('7139b72b9939334ff76e1479072c0558dca2c3620971c2bb233a7b25a690d610')
bravo = PrivateKey.from_hex('dd0dd23cd51460e6c42a154623df19372be332f0a61a51755603ab897f6ede39')
charlie = PrivateKey.from_hex('79cf7604de08deee525ac9f500e118eef6036c56b175adf5afac94bb9542c5c1')

def print_balances(rgov: rgovAPI):
    # get balance of vault
    admin_balance = rgov.checkBalance(admin.get_public_key().get_rev_address())
    print("admin Balance ", admin_balance, " REV ", admin.get_public_key().get_rev_address())
    bravo_balance = rgov.checkBalance(bravo.get_public_key().get_rev_address())
    print("bravo Balance ", bravo_balance, " REV ", bravo.get_public_key().get_rev_address())


rgov = rgovAPI(RCHAIN_SERVER[0])

result = rgov.newInbox(alpha)
コード例 #26
0
# https://github.com/tgrospic/rnode-client-js/blob/master/src/nodejs/client-insert-signed.js
# the logic below mostly copied from the logic of the link above

from rchain.crypto import PrivateKey, blake2b_32
from rchain.client import RClient
from rchain.pb.RhoTypes_pb2 import Par, Expr, ETuple, Bundle, GPrivate, GUnforgeable

host = "localhost"
port = 40402

deployKey = PrivateKey.generate()
timestamp = 1559156356769
nonce = 9223372036854775807
publicKey = deployKey.get_public_key()

with RClient(host, port) as client:
    ret = client.previewPrivateNames(publicKey, timestamp, 3)
    unforgeable = ret.payload.ids[0]

print(unforgeable)
dataToSign = Par(exprs=[
    Expr(e_tuple_body=ETuple(ps=[
        Par(exprs=[Expr(g_int=nonce)]),
        Par(bundles=[
            Bundle(body=Par(unforgeables=[
                GUnforgeable(g_private_body=GPrivate(id=unforgeable))
            ]),
                   writeFlag=True,
                   readFlag=False)
        ])
    ]))
コード例 #27
0
from rchain.crypto import PrivateKey

MAINNET_SERVER = ['node0.root-shard.mainnet.rchain.coop',
                  'node1.root-shard.mainnet.rchain.coop',
                  'node2.root-shard.mainnet.rchain.coop',
                  'node3.root-shard.mainnet.rchain.coop',
                  'node4.root-shard.mainnet.rchain.coop',
                  'node5.root-shard.mainnet.rchain.coop',
                  'node6.root-shard.mainnet.rchain.coop',
                  'node7.root-shard.mainnet.rchain.coop',
                  'node8.root-shard.mainnet.rchain.coop']
READONLY_SERVER = ['observer-asia.services.mainnet.rchain.coop',
                   'observer-us.services.mainnet.rchain.coop',
                   'observer-eu.services.mainnet.rchain.coop']

admin_key = PrivateKey.generate()
contract = "@1!(2)"

exploratory_term = 'new return in{return!("a")}'

block_hash = '4d135ce5773a05a782d1c52a7dfb42c4142b1a471bc3c57d77eee4d5affdef9a'
find_deploy = '3045022100c4cdd5e8bb05b1627c2302ffd90393cf30ed0ad693ef63d46e5d8b99856a44c40220055b2dff342934b59b3fac5ac1f81c7b7763db9ee945809d86b04dbd48867bd4'

# read-only node can not deploy with deploy request
with RClient(READONLY_SERVER[0], 40401) as client:
    # get the latest 10 block in the rnode
    block_infos = client.show_blocks(depth=10)

    # get the detailed info in the rnode
    block = client.show_block(block_hash)
コード例 #28
0
from .common import (
    CommandLineOptions,
)
from .rnode import (
    started_peer,
    started_bootstrap_with_network,
)
from .wait import (
    wait_for_block_approval,
    wait_for_approved_block_received_handler_state,
    wait_for_sent_approved_block,
)



CEREMONY_MASTER_KEYPAIR = PrivateKey.from_hex("80366db5fbb8dad7946f27037422715e4176dda41d582224db87b6c3b783d709")
VALIDATOR_A_KEYPAIR = PrivateKey.from_hex("120d42175739387af0264921bb117e4c4c05fbe2ce5410031e8b158c6e414bb5")
VALIDATOR_B_KEYPAIR = PrivateKey.from_hex("1f52d0bce0a92f5c79f2a88aae6d391ddf853e2eb8e688c5aa68002205f92dad")
VALIDATOR_C_KEYPAIR = PrivateKey.from_hex("5322dbb1828bdb44cb3275d35672bb3453347ee249a1f32d3c035e5ec3bfad1a")
READONLY_A_KEYPAIR = PrivateKey.from_hex("632a21e0176c4daed1ca78f08f98885f61d2050e0391e31eae59ff1a35ccca7f")


def test_successful_genesis_ceremony(command_line_options: CommandLineOptions, random_generator: Random, docker_client: DockerClient) -> None:
    """
    https://docs.google.com/document/d/1Z5Of7OVVeMGl2Fw054xrwpRmDmKCC-nAoIxtIIHD-Tc/
    """
    bootstrap_cli_options = {
        '--deploy-timestamp'   : '1',
        '--required-signatures': '2',
        '--approve-duration'   : '1min',
        '--approve-interval'   : '10sec',
コード例 #29
0
ファイル: transfer.py プロジェクト: tgrospic/rshard
                    help="private key of the sender vault")
parser.add_argument("-r",
                    "--receiver",
                    action="store",
                    type=str,
                    required=True,
                    dest="receiver",
                    help="receiver of the transfer")
parser.add_argument("-a",
                    "--amount",
                    action="store",
                    type=int,
                    required=True,
                    dest="amount",
                    help="the amount of the transfer")

args = parser.parse_args()
try:
    private_key = PrivateKey.from_hex(args.private_key)
except:
    logging.error("The private you provided is not valid")
    sys.exit(1)

with grpc.insecure_channel('localhost:40401') as channel:
    client = RClient(channel)
    vault = VaultAPI(client, private_key)
    vault.transfer(from_addr=None, to_addr=args.receiver, amount=args.amount)
    logging.info("Succeed transfer {} from {} to {} .".format(
        args.amount,
        private_key.get_public_key().get_rev_address(), args.receiver))
コード例 #30
0
ファイル: rnode.py プロジェクト: scala-steward/rchain
def make_peer(
    *,
    docker_client: DockerClient,
    network: str,
    name: str,
    bonds_file: str,
    command_timeout: int,
    bootstrap: Node,
    private_key: PrivateKey,
    allowed_peers: Optional[List[str]] = None,
    mem_limit: Optional[str] = None,
    wallets_file: Optional[str] = None,
    cli_flags: Optional[AbstractSet] = None,
    cli_options: Optional[Dict] = None,
    extra_volumes: Optional[List[str]] = None,
    synchrony_constraint_threshold: float = 0.0,
    max_peer_queue_size: int = 10,
    give_up_after_skipped: int = 0,
    drop_peer_after_retries: int = 0,
    number_of_active_validators: int = 10,
    epoch_length: int = 10000,
    quarantine_length: int = 50000
) -> Node:
    assert isinstance(name, str)
    assert '_' not in name, 'Underscore is not allowed in host name'
    name = make_peer_name(network, name)

    bootstrap_address = bootstrap.get_rnode_address()

    container_command_flags = set([
        "--prometheus",
        "--no-upnp",
        "--allow-private-addresses"
    ])

    if cli_flags is not None:
        container_command_flags.update(cli_flags)

    container_command_options = {
        "--bootstrap":                      bootstrap_address,
        "--validator-private-key":          private_key.to_hex(),
        "--validator-public-key":           private_key.get_public_key().to_hex(),
        "--host":                           name,
        "--synchrony-constraint-threshold": synchrony_constraint_threshold,
        "--frrd-max-peer-queue-size":            max_peer_queue_size,
        "--frrd-give-up-after-skipped":          give_up_after_skipped,
        "--frrd-drop-peer-after-retries":        drop_peer_after_retries,
        "--number-of-active-validators":    number_of_active_validators,
        "--epoch-length":                   epoch_length,
        "--quarantine-length":              quarantine_length
    }

    if cli_options is not None:
        container_command_options.update(cli_options)

    container = make_node(
        docker_client=docker_client,
        name=name,
        network=network,
        bonds_file=bonds_file,
        container_command='run',
        container_command_flags=container_command_flags,
        container_command_options=container_command_options,
        command_timeout=command_timeout,
        extra_volumes=extra_volumes,
        allowed_peers=allowed_peers,
        mem_limit=mem_limit if not None else '4G',
        wallets_file=wallets_file,
    )
    return container