Ejemplo n.º 1
0
    def test_transfer_funds_insufficient(self):
        """Tests the transfer insufficient amount of funds is failed"""

        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(
                validator_id)
            client = ExonumClient(host, public_port, private_port)
            with ExonumCryptoAdvancedClient(client) as crypto_client:
                alice_keys = KeyPair.generate()
                crypto_client.create_wallet(alice_keys,
                                            "Alice" + str(validator_id))
                bob_keys = KeyPair.generate()
                crypto_client.create_wallet(bob_keys,
                                            "Bob" + str(validator_id))
                with client.create_subscriber("blocks") as subscriber:
                    subscriber.wait_for_new_event()
                    tx_response = crypto_client.transfer(
                        110, alice_keys, bob_keys.public_key.value)
                    subscriber.wait_for_new_event()
                    tx_status = client.get_tx_info(
                        tx_response.json()['tx_hash']).json()['status']['type']
                    self.assertEqual(tx_status, 'service_error')
                    alice_balance = (crypto_client.get_wallet_info(
                        alice_keys).json()['wallet_proof']['to_wallet']
                                     ['entries'][0]['value']['balance'])
                    bob_balance = (crypto_client.get_wallet_info(
                        bob_keys).json()['wallet_proof']['to_wallet']
                                   ['entries'][0]['value']['balance'])
                    self.assertEqual(alice_balance, 100)
                    self.assertEqual(bob_balance, 100)
Ejemplo n.º 2
0
    def test_create_wallet_unique_for_key_pair(self):
        """Tests the transaction with the same keys for different wallets is failed"""

        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(
                validator_id)
            client = ExonumClient(host, public_port, private_port)
            with ExonumCryptoAdvancedClient(client) as crypto_client:
                alice_keys = KeyPair.generate()
                tx_response = crypto_client.create_wallet(
                    alice_keys, "Alice" + str(validator_id))
                with client.create_subscriber("blocks") as subscriber:
                    subscriber.wait_for_new_event()
                    # TODO: Sometimes it fails without time.sleep() [ECR-3876]
                    time.sleep(2)
                tx_status = client.get_tx_info(
                    tx_response.json()['tx_hash']).json()['status']['type']
                self.assertEqual(tx_status, 'success')
                # create the wallet with the same keys again
                tx_same_keys = crypto_client.create_wallet(
                    alice_keys, "Alice_Dublicate" + str(validator_id))
                with client.create_subscriber("blocks") as subscriber:
                    subscriber.wait_for_new_event()
                tx_status = client.get_tx_info(
                    tx_same_keys.json()['tx_hash']).json()['status']['type']
                self.assertEqual(tx_status, 'service_error')
Ejemplo n.º 3
0
    def test_transfer_funds_insufficient(self):
        """Tests the transfer insufficient amount of funds is failed"""

        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(
                validator_id)
            client = ExonumClient(host, public_port, private_port)
            with ExonumCryptoAdvancedClient(client) as crypto_client:
                alice_keys = KeyPair.generate()
                crypto_client.create_wallet(alice_keys,
                                            "Alice" + str(validator_id))
                bob_keys = KeyPair.generate()
                crypto_client.create_wallet(bob_keys,
                                            "Bob" + str(validator_id))
                with client.create_subscriber("blocks") as subscriber:
                    subscriber.wait_for_new_event()
                    tx_response = crypto_client.transfer(
                        110, alice_keys, bob_keys.public_key)
                    subscriber.wait_for_new_event()
                    tx_info = client.public_api.get_tx_info(
                        tx_response.json()["tx_hash"]).json()
                    tx_status = tx_info["status"]["type"]
                    self.assertEqual(tx_status, "service_error")
                    alice_balance = crypto_client.get_balance(alice_keys)
                    bob_balance = crypto_client.get_balance(bob_keys)
                    self.assertEqual(alice_balance, 100)
                    self.assertEqual(bob_balance, 100)
Ejemplo n.º 4
0
    def test_transfer_funds(self):
        """Tests the transfer funds to another wallet"""

        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(
                validator_id)
            client = ExonumClient(host, public_port, private_port)
            with ExonumCryptoAdvancedClient(client) as crypto_client:
                alice_keys = KeyPair.generate()
                bob_keys = KeyPair.generate()
                with client.create_subscriber("transactions") as subscriber:
                    crypto_client.create_wallet(alice_keys,
                                                "Alice" + str(validator_id))
                    subscriber.wait_for_new_event()
                    crypto_client.create_wallet(bob_keys,
                                                "Bob" + str(validator_id))
                    subscriber.wait_for_new_event()
                    crypto_client.transfer(20, alice_keys,
                                           bob_keys.public_key.value)
                    subscriber.wait_for_new_event()
                    alice_wallet = crypto_client.get_wallet_info(
                        alice_keys).json()
                    alice_balance = alice_wallet["wallet_proof"]["to_wallet"][
                        "entries"][0]["value"]["balance"]
                    bob_wallet = crypto_client.get_wallet_info(bob_keys).json()
                    bob_balance = bob_wallet["wallet_proof"]["to_wallet"][
                        "entries"][0]["value"]["balance"]
                    self.assertEqual(alice_balance, 80)
                    self.assertEqual(bob_balance, 120)
Ejemplo n.º 5
0
def run() -> None:
    """Example of downloading the Protobuf sources and using the compiled
    module."""
    client = ExonumClient(hostname="127.0.0.1", public_api_port=8080, private_api_port=8081)

    # Create ProtobufLoader via context manager (so that we will not have to
    # initialize/deinitialize it manually):
    with client.protobuf_loader() as loader:
        # Load core proto files:
        loader.load_main_proto_files()
        # Load proto files for the Exonum supervisor service:
        loader.load_service_proto_files(RUST_RUNTIME_ID, "exonum-supervisor:0.12.0")

        # Load the main module (runtime.proto):
        main_module = ModuleManager.import_main_module("runtime")

        # Create a Protobuf message object:
        artifact_id = main_module.ArtifactId()
        artifact_id.runtime_id = RUST_RUNTIME_ID
        artifact_id.name = "some_service:0.1.0"

        # Working with Protobuf objects, you have to follow Protobuf Python API
        # conventions. See Protobuf Python API docs for details:
        instance_spec = main_module.InstanceSpec()
        instance_spec.artifact.CopyFrom(artifact_id)

        # Load the service module (service.proto from the supervisor service):
        service_module = ModuleManager.import_service_module("exonum-supervisor:0.12.0", "service")

        # Workflow is the same as for the main modules:
        _deploy_request = service_module.DeployRequest()
Ejemplo n.º 6
0
    def test_transfer_funds(self):
        """Tests the transfer funds to another wallet"""

        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(
                validator_id)
            client = ExonumClient(host, public_port, private_port)
            with ExonumCryptoAdvancedClient(client) as crypto_client:
                alice_keys = KeyPair.generate()
                crypto_client.create_wallet(alice_keys,
                                            "Alice" + str(validator_id))
                bob_keys = KeyPair.generate()
                crypto_client.create_wallet(bob_keys,
                                            "Bob" + str(validator_id))
                with client.create_subscriber("blocks") as subscriber:
                    subscriber.wait_for_new_event()
                    # TODO: Sometimes it fails without time.sleep() [ECR-3876]
                    time.sleep(2)
                    crypto_client.transfer(20, alice_keys,
                                           bob_keys.public_key.value)
                    subscriber.wait_for_new_event()
                    # TODO: Sometimes it fails without time.sleep() [ECR-3876]
                    time.sleep(2)
                    alice_balance = (crypto_client.get_wallet_info(
                        alice_keys).json()['wallet_proof']['to_wallet']
                                     ['entries'][0]['value']['balance'])
                    bob_balance = (crypto_client.get_wallet_info(
                        bob_keys).json()['wallet_proof']['to_wallet']
                                   ['entries'][0]['value']['balance'])
                    self.assertEqual(alice_balance, 80)
                    self.assertEqual(bob_balance, 120)
Ejemplo n.º 7
0
    def test_user_agent(self):
        """Tests the `user_agent` endpoint."""

        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(validator_id)
            client = ExonumClient(host, public_port, private_port)
            user_agent_response = client.public_api.user_agent()
            self.assertEqual(user_agent_response.status_code, 200)
Ejemplo n.º 8
0
    def test_zero_block(self):
        """Tests the `block` endpoint. Check response for 0 block"""

        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(validator_id)
            client = ExonumClient(host, public_port, private_port)
            block_response = client.public_api.get_block(0)
            self.assertEqual(block_response.status_code, 200)
            self.assertEqual(block_response.json()["height"], 0)
Ejemplo n.º 9
0
def wait_for_block(network: ExonumNetwork, height: int = 1) -> None:
    """Wait for block at specific height"""
    for validator_id in range(network.validators_count()):
        host, public_port, private_port = network.api_address(validator_id)
        client = ExonumClient(host, public_port, private_port)
        for _ in range(RETRIES_AMOUNT):
            if client.public_api.get_block(height).status_code == 200:
                break
            time.sleep(0.5)
Ejemplo n.º 10
0
    def test_get_blocks_with_precommits(self):
        """Tests the `blocks` endpoint. Check response for blocks with precommits"""

        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(validator_id)
            client = ExonumClient(host, public_port, private_port)
            blocks_response = client.public_api.get_blocks(count=1, add_precommits=True)
            self.assertEqual(blocks_response.status_code, 200)
            self.assertEqual(len(blocks_response.json()["blocks"][0]["precommits"]), 3)
Ejemplo n.º 11
0
    def test_get_blocks_with_time(self):
        """Tests the `blocks` endpoint. Check response for blocks with time"""

        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(validator_id)
            client = ExonumClient(host, public_port, private_port)
            blocks_response = client.public_api.get_blocks(count=1, add_blocks_time=True)
            self.assertEqual(blocks_response.status_code, 200)
            self.assertIsNotNone(blocks_response.json()['blocks'][0]['time'])
Ejemplo n.º 12
0
    def test_get_only_non_empty_blocks(self):
        """Tests the `blocks` endpoint. Check response for only non empty blocks"""

        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(validator_id)
            client = ExonumClient(host, public_port, private_port)
            blocks_response = client.public_api.get_blocks(count=5, skip_empty_blocks=True)
            self.assertEqual(blocks_response.status_code, 200)
            self.assertEqual(len(blocks_response.json()['blocks']), 0)
Ejemplo n.º 13
0
    def test_get_unknown_transaction(self):
        """Tests the `transactions` endpoint. Check response for unknown transaction"""

        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(validator_id)
            client = ExonumClient(host, public_port, private_port)
            tx_response = client.public_api.get_tx_info("b2d09e1bddca851bee8faf8ffdcfc18cb87fbde167a29bd049fa2eee4a82c1ca")
            self.assertEqual(tx_response.status_code, 404)
            self.assertEqual(tx_response.json()['type'], "unknown")
Ejemplo n.º 14
0
    def test_nonexistent_block(self):
        """Tests the `block` endpoint. Check response for nonexistent block"""

        nonexistent_height = 999
        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(validator_id)
            client = ExonumClient(host, public_port, private_port)
            block_response = client.public_api.get_block(nonexistent_height)
            self.assertEqual(block_response.status_code, 404)
Ejemplo n.º 15
0
def run() -> None:
    """Example of a simple API interaction."""
    client = ExonumClient(hostname="127.0.0.1",
                          public_api_port=8080,
                          private_api_port=8081)

    # Get the available services:
    print("Available services:")
    available_services_response = client.available_services()
    if available_services_response.status_code == 200:
        available_services = available_services_response.json()
        print(" Artifacts:")
        for artifact in available_services["artifacts"]:
            print(
                f"  - {artifact['name']} (runtime ID {artifact['runtime_id']})"
            )
        print(" Instances:")
        for instance in available_services["services"]:
            print(
                f"  - ID {instance['id']} => {instance['name']} (artifact {instance['artifact']['name']})"
            )
    else:
        print("Available services request failed")
    print("")

    # Get the health info:
    print("Health info:")
    health_info_response = client.health_info()
    if health_info_response.status_code == 200:
        health_info = health_info_response.json()
        print(f"Consensus status: {health_info['consensus_status']}")
        print(f"Connected peers: {health_info['connected_peers']}")
    else:
        print("Health info request failed.")
    print("")

    # Get the Exonum stats:
    print("Exonum stats:")
    stats_response = client.stats()
    if stats_response.status_code == 200:
        stats = stats_response.json()
        print(f"Tx pool size: {stats['tx_pool_size']}")
        print(f"Tx count: {stats['tx_count']}")
        print(f"Tx cache size: {stats['tx_cache_size']}")
    else:
        print("Stats request failed.")
    print("")

    # Get the user agent:
    print("Exonum user agent:")
    user_agent_response = client.user_agent()
    if user_agent_response.status_code == 200:
        user_agent = user_agent_response.json()
        print(f"User agent: {user_agent}")
    else:
        print("User agent request failed.")
Ejemplo n.º 16
0
    def test_get_n_latest_blocks_negative(self):
        """Tests the `blocks` endpoint. Check response for N latest blocks if latest exceeds current height"""

        latest = 999
        number_of_blocks = 6
        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(validator_id)
            client = ExonumClient(host, public_port, private_port)
            blocks_response = client.public_api.get_blocks(count=number_of_blocks, latest=latest)
            self.assertEqual(blocks_response.status_code, 404)
Ejemplo n.º 17
0
    def test_health_check(self):
        """Tests the `healthcheck` endpoint."""

        time.sleep(10)
        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(validator_id)
            client = ExonumClient(host, public_port, private_port)
            health_info_response = client.public_api.health_info()
            self.assertEqual(health_info_response.status_code, 200)
            self.assertEqual(health_info_response.json()['connected_peers'], self.network.validators_count()-1)
            self.assertEqual(health_info_response.json()['consensus_status'], 'Active')
Ejemplo n.º 18
0
    def test_get_last_n_blocks(self):
        """Tests the `blocks` endpoint. Check response for last N blocks"""

        number_of_blocks = 5
        wait_for_block(self.network, 5)
        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(validator_id)
            client = ExonumClient(host, public_port, private_port)
            blocks_response = client.public_api.get_blocks(count=number_of_blocks)
            self.assertEqual(blocks_response.status_code, 200)
            self.assertEqual(len(blocks_response.json()["blocks"]), number_of_blocks)
Ejemplo n.º 19
0
    def test_zero_initial_stats(self):
        """Tests the `stats` endpoint. Check initial stats values"""

        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(validator_id)
            client = ExonumClient(host, public_port, private_port)
            stats = client.public_api.stats()
            self.assertEqual(stats.status_code, 200)
            self.assertEqual(stats.json()["tx_count"], 0)
            self.assertEqual(stats.json()["tx_pool_size"], 0)
            self.assertEqual(stats.json()["tx_cache_size"], 0)
Ejemplo n.º 20
0
def wait_api_to_start(network: ExonumNetwork) -> None:
    """Wait for api starting"""
    for validator_id in range(network.validators_count()):
        host, public_port, private_port = network.api_address(validator_id)
        client = ExonumClient(host, public_port, private_port)
        for _ in range(RETRIES_AMOUNT):
            try:
                client.public_api.health_info()
                break
            except ConnectionError:
                time.sleep(0.5)
Ejemplo n.º 21
0
    def test_block_response(self):
        """Tests the `block` endpoint. Check response for block"""

        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(
                validator_id)
            client = ExonumClient(host, public_port, private_port)
            block_response = client.get_block(1)
            self.assertEqual(block_response.status_code, 200)
            self.assertEqual(block_response.json()['height'], 1)
            self.assertEqual(block_response.json()['tx_count'], 0)
            self.assertIsNotNone(block_response.json()['time'])
Ejemplo n.º 22
0
    def test_deploy_regular_with_consensus_config(self):
        """Tests the deploy mechanism in regular mode with consensus config."""

        pub_configs = self.network._public_configs().split()
        validator_keys = []
        for pub_config in pub_configs:
            keys = []
            with open(pub_config, "r") as file:
                data = file.read()
                keys.append(re.search('consensus_key = "(.+?)"', data).group(1))
                keys.append(re.search('service_key = "(.+?)"', data).group(1))
            validator_keys.append(keys)

        consensus = {
            "validator_keys": validator_keys,
            "first_round_timeout": 3000,
            "status_timeout": 5000,
            "peers_timeout": 10000,
            "txs_block_limit": 5000,
            "max_message_len": 1048576,
            "min_propose_timeout": 10,
            "max_propose_timeout": 200,
            "propose_timeout_threshold": 500,
        }
        instances = {"crypto": {"artifact": "cryptocurrency"}}
        cryptocurrency_advanced_config_dict = generate_config(
            self.network, consensus=consensus, instances=instances
        )

        cryptocurrency_advanced_config = Configuration(
            cryptocurrency_advanced_config_dict
        )
        with Launcher(cryptocurrency_advanced_config) as launcher:
            explorer = launcher.explorer()

            launcher.deploy_all()
            launcher.wait_for_deploy()
            launcher.start_all()
            launcher.wait_for_start()

            for artifact in launcher.launch_state.completed_deployments():
                deployed = explorer.check_deployed(artifact)
                self.assertEqual(deployed, True)

            self.assertEqual(len(launcher.launch_state.completed_configs()), 1)

        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(validator_id)
            client = ExonumClient(host, public_port, private_port)
            supervisor_api = client.service_apis("supervisor")
            consensus_config = supervisor_api[0].get_service("consensus-config").json()
            # check that initial config has been applied
            self.assertEqual(consensus_config["txs_block_limit"], 5000)
Ejemplo n.º 23
0
    def test_get_nonexistent_wallet(self):
        """Tests the wallet history is None for nonexistent wallet"""

        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(
                validator_id)
            client = ExonumClient(host, public_port, private_port)
            with ExonumCryptoAdvancedClient(client) as crypto_client:
                alice_keys = KeyPair.generate()
                wallet_history = crypto_client.get_wallet_info(
                    alice_keys).json()["wallet_history"]
                self.assertIsNone(wallet_history)
Ejemplo n.º 24
0
    def test_node_stats(self):
        """Tests the `stats` endpoint."""

        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(
                validator_id)
            client = ExonumClient(host, public_port, private_port)
            node_stats_response = client.private_api.get_stats()
            self.assertEqual(node_stats_response.status_code, 200)
            node_stats = node_stats_response.json()
            self.assertEqual(node_stats["tx_count"], 0)
            self.assertEqual(node_stats["tx_pool_size"], 0)
            self.assertEqual(node_stats["tx_cache_size"], 0)
Ejemplo n.º 25
0
    def _load_clients(self) -> List[ExonumClient]:
        clients: List[ExonumClient] = []

        for network in self.config.networks:
            client = ExonumClient(network["host"], network["public-api-port"],
                                  network["private-api-port"], network["ssl"])
            clients.append(client)

            # Do not need more than one node in a 'Simple' mode
            if self.config.is_simple():
                break

        return clients
Ejemplo n.º 26
0
    def test_freeze_service(self):
        host, public_port, private_port = self.network.api_address(0)
        client = ExonumClient(host, public_port, private_port)

        # Create wallet
        alice_keys = KeyPair.generate()
        with ExonumCryptoAdvancedClient(client) as crypto_client:
            crypto_client.create_wallet(alice_keys, "Alice")
            with client.create_subscriber("transactions") as subscriber:
                subscriber.wait_for_new_event()
                alice_balance = crypto_client.get_balance(alice_keys)
                self.assertEqual(alice_balance, 100)

        # Freeze the service
        instances = {
            "crypto": {
                "artifact": "cryptocurrency",
                "action": "freeze"
            }
        }
        cryptocurrency_advanced_config_dict = generate_config(
            self.network, instances=instances, artifact_action="none")

        cryptocurrency_advanced_config = Configuration(
            cryptocurrency_advanced_config_dict)
        with Launcher(cryptocurrency_advanced_config) as launcher:
            launcher.deploy_all()
            launcher.wait_for_deploy()
            launcher.start_all()
            launcher.wait_for_start()

        # Check that the service status has been changed to `frozen`.
        for service in client.public_api.available_services().json(
        )["services"]:
            if service["spec"]["name"] == "crypto":
                self.assertEqual(service["status"]["type"], "frozen")

        # Try to create a new wallet. The operation should fail.
        with ExonumCryptoAdvancedClient(client) as crypto_client:
            bob_keys = KeyPair.generate()
            response = crypto_client.create_wallet(bob_keys, "Bob")
            self.assertEqual(response.status_code, 400)
            # Because the service is frozen, transaction should be inadmissible.
            self.assertEqual(response.json()["title"],
                             "Failed to add transaction to memory pool")

        # Check that we can use service endpoints for data retrieving. Check wallet once again.
        with ExonumCryptoAdvancedClient(client) as crypto_client:
            alice_balance = crypto_client.get_balance(alice_keys)
            self.assertEqual(alice_balance, 100)
Ejemplo n.º 27
0
    def test_node_info_check(self):
        """Tests the `info` endpoint."""

        time.sleep(10)
        for validator_id in range(self.network.validators_count()):
            host, public_port, private_port = self.network.api_address(
                validator_id)
            client = ExonumClient(host, public_port, private_port)
            node_info_response = client.private_api.get_info()
            self.assertEqual(node_info_response.status_code, 200)
            node_info = node_info_response.json()
            self.assertEqual(len(node_info["connected_peers"]),
                             self.network.validators_count() - 1)
            self.assertEqual(node_info["consensus_status"], "active")
Ejemplo n.º 28
0
def run() -> None:
    """Example of a simple API interaction."""
    client = ExonumClient(hostname="127.0.0.1",
                          public_api_port=8080,
                          private_api_port=8081)

    # Get the available services:
    print("Available services:")
    available_services_response = client.public_api.available_services()
    if available_services_response.status_code == 200:
        available_services = available_services_response.json()
        print(" Artifacts:")
        for artifact in available_services["artifacts"]:
            print(
                f"  - {artifact['name']}:{artifact['version']} (runtime ID {artifact['runtime_id']})"
            )
        print(" Instances:")
        for state in available_services["services"]:
            instance = state["spec"]
            print(
                f"  - ID {instance['id']} => {instance['name']} (artifact {instance['artifact']['name']})"
            )
    else:
        print("Available services request failed")
    print("")

    # Get the health info:
    print("Node info:")
    node_info_response = client.private_api.get_info()
    if node_info_response.status_code == 200:
        node_info = node_info_response.json()
        print(f"Consensus status: {node_info['consensus_status']}")
        print(f"Connected peers: {node_info['connected_peers']}")
    else:
        print("Node info request failed.")
    print("")

    # Get the Exonum stats:
    print("Exonum stats:")
    stats_response = client.private_api.get_stats()
    if stats_response.status_code == 200:
        stats = stats_response.json()
        print(f"Current height: {stats['height']}")
        print(f"Tx pool size: {stats['tx_pool_size']}")
        print(f"Tx count: {stats['tx_count']}")
        print(f"Tx cache size: {stats['tx_cache_size']}")
    else:
        print("Stats request failed.")
    print("")
Ejemplo n.º 29
0
    def test_get_n_latest_blocks(self):
        """Tests the `blocks` endpoint. Check response for N latest blocks"""

        latest = 5
        number_of_blocks = 15
        time.sleep(5)
        for validator_id in range(self.network.validators_count()):
            height_counter = latest
            host, public_port, private_port = self.network.api_address(validator_id)
            client = ExonumClient(host, public_port, private_port)
            blocks_response = client.public_api.get_blocks(count=number_of_blocks, latest=latest)
            self.assertEqual(len(blocks_response.json()['blocks']), latest+1)
            for block in blocks_response.json()['blocks']:
                self.assertEqual(int(block['height']), height_counter)
                height_counter -= 1
Ejemplo n.º 30
0
def run() -> None:
    """This example creates two wallets (for Alice and Bob) and performs several
    transactions between these wallets."""
    client = ExonumClient(hostname="127.0.0.1",
                          public_api_port=8080,
                          private_api_port=8081)

    with client.protobuf_loader() as loader:
        # Load and compile proto files:
        loader.load_main_proto_files()
        loader.load_service_proto_files(RUST_RUNTIME_ID,
                                        CRYPTOCURRENCY_ARTIFACT_NAME,
                                        CRYPTOCURRENCY_ARTIFACT_VERSION)

        instance_id = get_cryptocurrency_instance_id(client)

        cryptocurrency_message_generator = MessageGenerator(
            instance_id, CRYPTOCURRENCY_ARTIFACT_NAME,
            CRYPTOCURRENCY_ARTIFACT_VERSION)

        alice_keypair = create_wallet(client, cryptocurrency_message_generator,
                                      "Alice")
        bob_keypair = create_wallet(client, cryptocurrency_message_generator,
                                    "Bob")

        alice_balance = get_balance(client, alice_keypair.public_key)
        bob_balance = get_balance(client, bob_keypair.public_key)
        print("Created the wallets for Alice and Bob. Balance:")
        print(f" Alice => {alice_balance}")
        print(f" Bob => {bob_balance}")

        amount = 10
        alice_balance, bob_balance = transfer(
            client, cryptocurrency_message_generator, alice_keypair,
            bob_keypair.public_key, amount)

        print(f"Transferred {amount} tokens from Alice's wallet to Bob's one")
        print(f" Alice => {alice_balance}")
        print(f" Bob => {bob_balance}")

        amount = 25
        bob_balance, alice_balance = transfer(
            client, cryptocurrency_message_generator, bob_keypair,
            alice_keypair.public_key, amount)

        print(f"Transferred {amount} tokens from Bob's wallet to Alice's one")
        print(f" Alice => {alice_balance}")
        print(f" Bob => {bob_balance}")