Exemple #1
0
def test_is_valid_address():
    """Test LedgerApis.is_valid_address."""
    assert LedgerApis.is_valid_address(DEFAULT_LEDGER, FETCHAI_ADDRESS_ONE)
    assert LedgerApis.is_valid_address(EthereumCrypto.identifier,
                                       ETHEREUM_ADDRESS_ONE)
    assert LedgerApis.is_valid_address(CosmosCrypto.identifier,
                                       COSMOS_ADDRESS_ONE)
Exemple #2
0
 def test_unknown_token_balance(self):
     """Test the token_balance for the unknown tokens."""
     ledger_apis = LedgerApis({ETHEREUM: DEFAULT_ETHEREUM_CONFIG,
                              FETCHAI: DEFAULT_FETCHAI_CONFIG})
     with pytest.raises(AssertionError):
         balance = ledger_apis.token_balance("UNKNOWN", fet_address)
         assert balance == 0, "Unknown identifier so it will return 0"
Exemple #3
0
    def test_is_tx_settled_ethereum(self):
        """Test if the transaction is settled for eth."""
        ledger_apis = LedgerApis(
            {ETHEREUM: DEFAULT_ETHEREUM_CONFIG, FETCHAI: DEFAULT_FETCHAI_CONFIG},
            FETCHAI,
        )
        tx_digest = "97fcacaaf94b62318c4e4bbf53fd2608c15062f17a6d1bffee0ba7af9b710e35"
        result = HexBytes(
            "0xf85f808082c35094d898d5e829717c72e7438bad593076686d7d164a80801ba005c2e99ecee98a12fbf28ab9577423f42e9e88f2291b3acc8228de743884c874a077d6bc77a47ad41ec85c96aac2ad27f05a039c4787fca8a1e5ee2d8c7ec1bb6a"
        )
        with mock.patch.object(
            ledger_apis.apis[ETHEREUM].api.eth,
            "getTransactionReceipt",
            return_value=result,
        ):
            is_successful = ledger_apis._is_tx_settled(ETHEREUM, tx_digest=tx_digest)
            assert is_successful
            assert ledger_apis.last_tx_statuses[ETHEREUM] == "OK"

        with mock.patch.object(
            ledger_apis.apis[ETHEREUM].api.eth,
            "getTransactionReceipt",
            side_effect=Exception,
        ):
            is_successful = ledger_apis._is_tx_settled(ETHEREUM, tx_digest=tx_digest)
            assert not is_successful
            assert ledger_apis.last_tx_statuses[ETHEREUM] == "ERROR"
Exemple #4
0
    def test_failed_transfer_fetchai(self):
        """Test the transfer function for fetchai token fails."""
        private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt")
        fet_obj = FetchAICrypto(private_key_path=private_key_path)
        ledger_apis = LedgerApis(
            {ETHEREUM: DEFAULT_ETHEREUM_CONFIG, FETCHAI: DEFAULT_FETCHAI_CONFIG},
            FETCHAI,
        )

        with mock.patch.object(
            ledger_apis.apis.get(FETCHAI).api.tokens,
            "transfer",
            return_value="97fcacaaf94b62318c4e4bbf53fd2608c15062f17a6d1bffee0ba7af9b710e35",
        ):
            with mock.patch.object(
                ledger_apis.apis.get(FETCHAI).api, "sync", side_effect=Exception
            ):
                tx_digest = ledger_apis.transfer(
                    fet_obj,
                    fet_address,
                    amount=10,
                    tx_fee=10,
                    tx_nonce="transaction nonce",
                )
                assert tx_digest is None
                assert ledger_apis.last_tx_statuses[FETCHAI] == "ERROR"
Exemple #5
0
def do_transfer(ctx: Context, identifier: str, address: Address, amount: int,
                tx_fee: int) -> Optional[str]:
    """
    Perform wealth transfer to another account.

    :param ctx: click context
    :param identifier: str, ledger id to perform transfer operation
    :param address: address of the recepient
    :param amount: int, amount of wealth to transfer
    :param tx_fee: int, fee for transaction

    :return: str, transaction digest or None if failed.
    """
    click.echo("Starting transfer ...")
    wallet = get_wallet_from_context(ctx)
    source_address = wallet.addresses[identifier]

    _override_ledger_configurations(ctx.agent_config)
    balance = int(try_get_balance(ctx.agent_config, wallet, identifier))
    total_payable = amount + tx_fee
    if total_payable > balance:
        raise click.ClickException(
            f"Balance is not enough! Available={balance}, required={total_payable}!"
        )

    tx_nonce = LedgerApis.generate_tx_nonce(identifier, source_address,
                                            address)
    transaction = LedgerApis.get_transfer_transaction(identifier,
                                                      source_address, address,
                                                      amount, tx_fee, tx_nonce)
    tx_signed = wallet.sign_transaction(identifier, transaction)
    return LedgerApis.send_signed_transaction(identifier, tx_signed)
def try_get_balance(agent_config: AgentConfig, wallet: Wallet,
                    type_: str) -> int:
    """
    Try to get wallet balance.

    :param agent_config: agent config object.
    :param wallet: wallet object.
    :param type_: type of ledger API.

    :retun: token balance.
    """
    try:
        if type_ not in agent_config.ledger_apis_dict:  # pragma: no cover
            raise ValueError(
                "No ledger api config for {} provided in aea-config.yaml.".
                format(type_))
        ledger_apis = LedgerApis(agent_config.ledger_apis_dict,
                                 agent_config.default_ledger)
        address = wallet.addresses[type_]
        balance = ledger_apis.get_balance(type_, address)
        if balance is None:  # pragma: no cover
            raise ValueError("No balance returned!")
        return balance
    except (AssertionError, ValueError) as e:  # pragma: no cover
        raise click.ClickException(str(e))
 def test_failed_transfer_ethereum(self):
     """Test the transfer function for ethereum token fails."""
     private_key_path = os.path.join(CUR_PATH, "data",
                                     "eth_private_key.txt")
     eth_obj = EthereumCrypto(private_key_path=private_key_path)
     ledger_apis = LedgerApis(
         {
             ETHEREUM: DEFAULT_ETHEREUM_CONFIG,
             FETCHAI: DEFAULT_FETCHAI_CONFIG
         },
         FETCHAI,
     )
     with mock.patch.object(
             ledger_apis.apis.get(ETHEREUM).api.eth,
             "getTransactionCount",
             return_value=5,
             side_effect=Exception,
     ):
         tx_digest = ledger_apis.transfer(
             eth_obj,
             eth_address,
             amount=10,
             tx_fee=200000,
             tx_nonce="transaction nonce",
         )
         assert tx_digest is None
         assert ledger_apis.last_tx_statuses[ETHEREUM] == "ERROR"
Exemple #8
0
 def test_generate_tx_nonce_negative(self, *mocks):
     """Test generate_tx_nonce init negative result."""
     ledger_apis = LedgerApis(
         {ETHEREUM: DEFAULT_ETHEREUM_CONFIG, FETCHAI: DEFAULT_FETCHAI_CONFIG},
         FETCHAI,
     )
     result = ledger_apis.generate_tx_nonce(FETCHAI, "seller", "client")
     assert result == ""
Exemple #9
0
    def get_hash(
        ledger_id: str,
        sender_address: str,
        counterparty_address: str,
        good_ids: List[str],
        sender_supplied_quantities: List[int],
        counterparty_supplied_quantities: List[int],
        sender_payable_amount: int,
        counterparty_payable_amount: int,
        nonce: str,
    ) -> str:
        """
        Generate a hash from transaction information.

        :param sender_addr: the sender address
        :param counterparty_addr: the counterparty address
        :param good_ids: the list of good ids
        :param sender_supplied_quantities: the quantities supplied by the sender (must all be positive)
        :param counterparty_supplied_quantities: the quantities supplied by the counterparty (must all be positive)
        :param sender_payable_amount: the amount payable by the sender
        :param counterparty_payable_amount: the amount payable by the counterparty
        :param tx_nonce: the nonce of the transaction
        :return: the hash
        """
        if len(good_ids) == 0:
            aggregate_hash = LedgerApis.get_hash(ledger_id, b"")
        else:
            aggregate_hash = LedgerApis.get_hash(
                ledger_id,
                b"".join([
                    good_ids[0].encode("utf-8"),
                    sender_supplied_quantities[0].to_bytes(32, "big"),
                    counterparty_supplied_quantities[0].to_bytes(32, "big"),
                ]),
            )
        for idx, good_id in enumerate(good_ids):
            if idx == 0:
                continue
            aggregate_hash = LedgerApis.get_hash(
                ledger_id,
                b"".join([
                    aggregate_hash.encode("utf-8"),
                    good_id.encode("utf-8"),
                    sender_supplied_quantities[idx].to_bytes(32, "big"),
                    counterparty_supplied_quantities[idx].to_bytes(32, "big"),
                ]),
            )

        m_list = []  # type: List[bytes]
        m_list.append(sender_address.encode("utf-8"))
        m_list.append(counterparty_address.encode("utf-8"))
        m_list.append(aggregate_hash.encode("utf-8"))
        m_list.append(sender_payable_amount.to_bytes(32, "big"))
        m_list.append(counterparty_payable_amount.to_bytes(32, "big"))
        m_list.append(nonce.encode("utf-8"))
        digest = LedgerApis.get_hash(ledger_id, b"".join(m_list))
        return digest
Exemple #10
0
def _try_get_balance(agent_config, wallet, type_):
    try:
        ledger_apis = LedgerApis(agent_config.ledger_apis_dict,
                                 agent_config.default_ledger)

        address = wallet.addresses[type_]
        return ledger_apis.token_balance(type_, address)
    except (AssertionError, ValueError) as e:  # pragma: no cover
        logger.error(str(e))
        sys.exit(1)
Exemple #11
0
 def test_is_tx_valid_negative(self, *mocks):
     """Test is_tx_valid init negative result."""
     ledger_apis = LedgerApis(
         {ETHEREUM: DEFAULT_ETHEREUM_CONFIG, FETCHAI: DEFAULT_FETCHAI_CONFIG},
         FETCHAI,
     )
     result = ledger_apis.is_tx_valid(
         FETCHAI, "tx_digest", "seller", "client", "tx_nonce", 1
     )
     assert not result
Exemple #12
0
def test_initialisation():
    """Test the initialisation of the ledger APIs."""
    ledger_apis = LedgerApis
    assert ledger_apis.has_ledger(FetchAIApi.identifier)
    assert type(LedgerApis.get_api(FetchAIApi.identifier)) == FetchAIApi
    assert LedgerApis.has_ledger(EthereumApi.identifier)
    assert type(LedgerApis.get_api(EthereumApi.identifier)) == EthereumApi
    assert LedgerApis.has_ledger(CosmosApi.identifier)
    assert type(LedgerApis.get_api(CosmosApi.identifier)) == CosmosApi
    with pytest.raises(AEAEnforceError):
        ledger_apis.get_api("UNKNOWN")
Exemple #13
0
 def test_initialisation(self):
     """Test the initialisation of the ledger APIs."""
     ledger_apis = LedgerApis({ETHEREUM: DEFAULT_ETHEREUM_CONFIG,
                               FETCHAI: DEFAULT_FETCHAI_CONFIG})
     assert ledger_apis.configs.get(ETHEREUM) == DEFAULT_ETHEREUM_CONFIG
     assert ledger_apis.has_fetchai
     assert ledger_apis.has_ethereum
     assert isinstance(ledger_apis.last_tx_statuses, Dict)
     unknown_config = ("UknownPath", 8080)
     with pytest.raises(ValueError):
         LedgerApis({"UNKNOWN": unknown_config})
Exemple #14
0
def _try_get_balance(agent_config, wallet, type_):
    try:
        if type_ not in agent_config.ledger_apis_dict:
            raise ValueError(
                "No ledger api config for {} provided in aea-config.yaml.".
                format(type_))
        ledger_apis = LedgerApis(agent_config.ledger_apis_dict,
                                 agent_config.default_ledger)
        address = wallet.addresses[type_]
        return ledger_apis.token_balance(type_, address)
    except (AssertionError, ValueError) as e:  # pragma: no cover
        raise click.ClickException(str(e))
Exemple #15
0
    def _handle_transaction_receipt(
            self, ledger_api_msg: LedgerApiMessage,
            ledger_api_dialogue: LedgerApiDialogue) -> None:
        """
        Handle a message of balance performative.

        :param ledger_api_message: the ledger api message
        :param ledger_api_dialogue: the ledger api dialogue
        """
        fipa_dialogue = ledger_api_dialogue.associated_fipa_dialogue
        is_settled = LedgerApis.is_transaction_settled(
            fipa_dialogue.terms.ledger_id,
            ledger_api_msg.transaction_receipt.receipt)
        is_valid = LedgerApis.is_transaction_valid(
            fipa_dialogue.terms.ledger_id,
            ledger_api_msg.transaction_receipt.transaction,
            fipa_dialogue.terms.sender_address,
            fipa_dialogue.terms.counterparty_address,
            fipa_dialogue.terms.nonce,
            fipa_dialogue.terms.counterparty_payable_amount,
        )
        if is_settled and is_valid:
            last_message = cast(Optional[FipaMessage],
                                fipa_dialogue.last_incoming_message)
            assert last_message is not None, "Cannot retrieve last fipa message."
            inform_msg = FipaMessage(
                message_id=last_message.message_id + 1,
                dialogue_reference=fipa_dialogue.dialogue_label.
                dialogue_reference,
                target=last_message.message_id,
                performative=FipaMessage.Performative.INFORM,
                info=fipa_dialogue.data_for_sale,
            )
            inform_msg.counterparty = last_message.counterparty
            fipa_dialogue.update(inform_msg)
            self.context.outbox.put_message(message=inform_msg)
            fipa_dialogues = cast(FipaDialogues, self.context.fipa_dialogues)
            fipa_dialogues.dialogue_stats.add_dialogue_endstate(
                FipaDialogue.EndState.SUCCESSFUL,
                fipa_dialogue.is_self_initiated)
            self.context.logger.info(
                "[{}]: transaction confirmed, sending data={} to buyer={}.".
                format(
                    self.context.agent_name,
                    fipa_dialogue.data_for_sale,
                    last_message.counterparty[-5:],
                ))
        else:
            self.context.logger.info(
                "[{}]: transaction_receipt={} not settled or not valid, aborting"
                .format(self.context.agent_name,
                        ledger_api_msg.transaction_receipt))
Exemple #16
0
    def test_transfer_fetchai(self):
        """Test the transfer function for fetchai token."""
        private_key_path = os.path.join(CUR_PATH, 'data', "fet_private_key.txt")
        fet_obj = FetchAICrypto(private_key_path=private_key_path)
        ledger_apis = LedgerApis({ETHEREUM: DEFAULT_ETHEREUM_CONFIG,
                                  FETCHAI: DEFAULT_FETCHAI_CONFIG})

        with mock.patch.object(ledger_apis.apis.get(FETCHAI).tokens, 'transfer',
                               return_value="97fcacaaf94b62318c4e4bbf53fd2608c15062f17a6d1bffee0ba7af9b710e35"):
            with mock.patch.object(ledger_apis.apis.get(FETCHAI), 'sync'):
                tx_digest = ledger_apis.transfer(FETCHAI, fet_obj, fet_address, amount=10, tx_fee=10)
                assert tx_digest is not None
                assert ledger_apis.last_tx_statuses[FETCHAI] == 'OK'
Exemple #17
0
    def test_validate_ethereum_transaction(self):
        seller = EthereumCrypto()
        client = EthereumCrypto()
        ledger_apis = LedgerApis(
            {ETHEREUM: DEFAULT_ETHEREUM_CONFIG, FETCHAI: DEFAULT_FETCHAI_CONFIG},
            FETCHAI,
        )
        tx_nonce = ledger_apis.generate_tx_nonce(
            ETHEREUM, seller.address, client.address
        )

        tx_digest = "0xbefa7768c313ff49bf274eefed001042a0ff9e3cfbe75ff1a9c2baf18001cec4"
        result = AttributeDict(
            {
                "blockHash": HexBytes(
                    "0x0bfc237d2a17f719a3300a4822779391ec6e3a74832fe1b05b8c477902b0b59e"
                ),
                "blockNumber": 7161932,
                "from": client.address,
                "gas": 200000,
                "gasPrice": 50000000000,
                "hash": HexBytes(
                    "0xbefa7768c313ff49bf274eefed001042a0ff9e3cfbe75ff1a9c2baf18001cec4"
                ),
                "input": tx_nonce,
                "nonce": 4,
                "r": HexBytes(
                    "0xb54ce8b9fa1d1be7be316c068af59a125d511e8dd51202b1a7e3002dee432b52"
                ),
                "s": HexBytes(
                    "0x4f44702b3812d3b4e4b76da0fd5b554b3ae76d1717db5b6b5faebd7b85ae0303"
                ),
                "to": seller.address,
                "transactionIndex": 0,
                "v": 42,
                "value": 2,
            }
        )
        with mock.patch.object(
            ledger_apis.apis.get(ETHEREUM).api.eth,
            "getTransaction",
            return_value=result,
        ):
            assert ledger_apis.is_tx_valid(
                identifier=ETHEREUM,
                tx_digest=tx_digest,
                seller=seller.address,
                client=client.address,
                tx_nonce=tx_nonce,
                amount=2,
            )
Exemple #18
0
    def test_validate_transaction_fetchai(self):
        """Test the validate transaction for fetchai ledger."""
        seller_crypto = FetchAICrypto()
        client_crypto = FetchAICrypto()
        ledger_apis = LedgerApis(
            {
                ETHEREUM: DEFAULT_ETHEREUM_CONFIG,
                FETCHAI: DEFAULT_FETCHAI_CONFIG
            },
            FETCHAI,
        )

        seller_address = str(seller_crypto.address)
        client_address = str(client_crypto.address)
        tx_contents = TxContents(
            digest=b"digest",
            action="action",
            chain_code="1",
            from_address=client_address,
            contract_digest="Contract_digest",
            contract_address=None,
            valid_from=1,
            valid_until=6,
            charge=10,
            charge_limit=2,
            transfers=[{
                "to": seller_address,
                "amount": 100
            }],
            signatories=["signatories"],
            data="data",
        )

        with mock.patch.object(ledger_apis.apis.get(FETCHAI)._api.tx,
                               "contents",
                               return_value=tx_contents):
            with mock.patch.object(
                    ledger_apis.apis.get(FETCHAI),
                    "is_transaction_settled",
                    return_value=True,
            ):
                result = ledger_apis.is_tx_valid(
                    identifier=FETCHAI,
                    tx_digest="transaction_digest",
                    seller=seller_address,
                    client=client_address,
                    tx_nonce="tx_nonce",
                    amount=100,
                )
                assert result
Exemple #19
0
 def test_generate_tx_nonce_fetchai(self):
     """Test the generated tx_nonce."""
     seller_crypto = FetchAICrypto()
     client_crypto = FetchAICrypto()
     ledger_apis = LedgerApis(
         {ETHEREUM: DEFAULT_ETHEREUM_CONFIG, FETCHAI: DEFAULT_FETCHAI_CONFIG},
         FETCHAI,
     )
     seller_address = seller_crypto.address
     client_address = client_crypto.address
     tx_nonce = ledger_apis.generate_tx_nonce(
         FETCHAI, seller_address, client_address
     )
     logger.info(tx_nonce)
     assert tx_nonce != ""
Exemple #20
0
    def test_fet_token_balance(self):
        """Test the token_balance for the fet tokens."""
        ledger_apis = LedgerApis({ETHEREUM: DEFAULT_ETHEREUM_CONFIG,
                                  FETCHAI: DEFAULT_FETCHAI_CONFIG})

        api = ledger_apis.apis[FETCHAI]
        with mock.patch.object(api.tokens, 'balance', return_value=10):
            balance = ledger_apis.token_balance(FETCHAI, fet_address)
            assert balance == 10
            assert ledger_apis.last_tx_statuses[FETCHAI] == 'OK'

        with mock.patch.object(api.tokens, 'balance', return_value=0, side_effect=Exception):
            balance = ledger_apis.token_balance(FETCHAI, eth_address)
            assert balance == 0, "This must be 0 since the address is wrong"
            assert ledger_apis.last_tx_statuses[FETCHAI] == 'ERROR'
Exemple #21
0
    def setup_class(cls):
        """Test the initialisation of the AEA."""
        cls.node = LocalNode()
        private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt")
        cls.wallet = Wallet({FETCHAI: private_key_path})
        cls.ledger_apis = LedgerApis({}, FETCHAI)
        cls.agent_name = "Agent0"

        cls.connection = _make_dummy_connection()
        cls.connections = [cls.connection]
        cls.identity = Identity(cls.agent_name, address=cls.wallet.addresses[FETCHAI])
        cls.address = cls.identity.address
        cls.my_aea = AEA(
            cls.identity,
            cls.connections,
            cls.wallet,
            cls.ledger_apis,
            timeout=2.0,
            resources=Resources(str(Path(CUR_PATH, "data/dummy_aea"))),
            is_programmatic=False,
        )
        cls.skill_context = SkillContext(cls.my_aea._context)
        logger_name = "aea.{}.skills.{}.{}".format(
            cls.my_aea._context.agent_name, "fetchai", "error"
        )
        cls.skill_context._logger = logging.getLogger(logger_name)
        cls.my_error_handler = ErrorHandler(
            name="error", skill_context=cls.skill_context
        )
        cls.t = Thread(target=cls.my_aea.start)
        cls.t.start()
        time.sleep(0.5)
Exemple #22
0
    def setup_class(cls):
        """Set the test up."""
        cls.node = LocalNode()
        cls.node.start()
        cls.agent_name = "MyAgent"
        cls.private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem")
        cls.wallet = Wallet({'default': cls.private_key_pem_path})
        cls.ledger_apis = LedgerApis({})
        cls.connection = OEFLocalConnection(cls.agent_name, cls.node)
        cls.connections = [cls.connection]

        cls.temp = tempfile.mkdtemp(prefix="test_aea_resources")
        cls.resources = Resources(cls.temp)
        cls.aea = AEA(cls.agent_name, cls.connections, cls.wallet, cls.ledger_apis, resources=cls.resources)

        cls.default_protocol_configuration = ProtocolConfig.from_json(
            yaml.safe_load(open(Path(AEA_DIR, "protocols", "default", "protocol.yaml"))))
        cls.default_protocol = Protocol("default",
                                        DefaultSerializer(),
                                        cls.default_protocol_configuration)
        cls.resources.protocol_registry.register(("default", None), cls.default_protocol)

        cls.error_skill = Skill.from_dir(Path(AEA_DIR, "skills", "error"), cls.aea.context)
        cls.dummy_skill = Skill.from_dir(Path(CUR_PATH, "data", "dummy_skill"), cls.aea.context)
        cls.resources.add_skill(cls.dummy_skill)
        cls.resources.add_skill(cls.error_skill)

        cls.expected_message = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello")

        cls.t = Thread(target=cls.aea.start)
        cls.t.start()
        time.sleep(0.5)

        cls.aea.outbox.put(Envelope(to=cls.agent_name, sender=cls.agent_name, protocol_id="default", message=DefaultSerializer().encode(cls.expected_message)))
Exemple #23
0
 def setup_class(cls):
     """Test the initialisation of the AEA."""
     eth_private_key_path = os.path.join(CUR_PATH, "data",
                                         "eth_private_key.txt")
     fet_private_key_path = os.path.join(CUR_PATH, "data",
                                         "fet_private_key.txt")
     cls.wallet = Wallet({
         ETHEREUM: eth_private_key_path,
         FETCHAI: fet_private_key_path
     })
     cls.ledger_apis = LedgerApis({FETCHAI: {
         "network": "testnet"
     }}, FETCHAI)
     cls.connections = [
         DummyConnection(connection_id=DUMMY_CONNECTION_PUBLIC_ID)
     ]
     cls.identity = Identity("name",
                             addresses=cls.wallet.addresses,
                             default_address_key=FETCHAI)
     cls.my_aea = AEA(
         cls.identity,
         cls.connections,
         cls.wallet,
         cls.ledger_apis,
         resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea"))),
         is_programmatic=False,
     )
     cls.skill_context = SkillContext(cls.my_aea.context)
Exemple #24
0
    def setup_class(cls):
        """Set the tests up."""
        cls._patch_logger()

        cls.cwd = os.getcwd()
        cls.t = tempfile.mkdtemp()
        cls.skill_directory = Path(cls.t, "dummy_skill")
        shutil.copytree(Path(CUR_PATH, "data", "dummy_skill"),
                        cls.skill_directory)
        os.chdir(cls.t)

        private_key_path = os.path.join(CUR_PATH, "data",
                                        "fet_private_key.txt")
        cls.wallet = Wallet({FETCHAI: private_key_path})
        ledger_apis = LedgerApis({}, FETCHAI)
        cls.connections = [
            DummyConnection(connection_id=DUMMY_CONNECTION_PUBLIC_ID)
        ]
        cls.identity = Identity("name", address=cls.wallet.addresses[FETCHAI])
        cls.my_aea = AEA(
            cls.identity,
            cls.connections,
            cls.wallet,
            ledger_apis,
            resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea"))),
            is_programmatic=False,
        )
        cls.agent_context = cls.my_aea.context
Exemple #25
0
    def setup_class(cls):
        """Set the tests up."""
        cls._patch_logger()

        # create temp agent folder
        cls.oldcwd = os.getcwd()
        cls.agent_name = "agent_test" + str(random.randint(0, 1000))
        cls.t = tempfile.mkdtemp()
        cls.agent_folder = os.path.join(cls.t, cls.agent_name)
        shutil.copytree(os.path.join(CUR_PATH, "data", "dummy_aea"), cls.agent_folder)
        os.chdir(cls.agent_folder)

        # make fake skill
        cls.fake_skill_id = "fake"
        agent_config_path = Path(cls.agent_folder, DEFAULT_AEA_CONFIG_FILE)
        agent_config = yaml.safe_load(agent_config_path.read_text())
        agent_config.get("skills").append(cls.fake_skill_id)
        yaml.safe_dump(agent_config, open(agent_config_path, "w"))
        Path(cls.agent_folder, "skills", cls.fake_skill_id).mkdir()

        connections = [DummyConnection()]
        private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem")
        wallet = Wallet({'default': private_key_pem_path})
        ledger_apis = LedgerApis({})
        cls.resources = Resources(os.path.join(cls.agent_folder))
        cls.aea = AEA(cls.agent_name, connections, wallet, ledger_apis, resources=cls.resources)
        cls.resources.load(cls.aea.context)

        cls.expected_skills = {"dummy", "error"}
Exemple #26
0
    def setup_class(cls):
        """Set the tests up."""
        # create temp agent folder
        cls.oldcwd = os.getcwd()
        cls.agent_name = "agent_test" + str(random.randint(0, 1000))  # nosec
        cls.t = tempfile.mkdtemp()
        cls.agent_folder = os.path.join(cls.t, cls.agent_name)
        shutil.copytree(os.path.join(CUR_PATH, "data", "dummy_aea"),
                        cls.agent_folder)
        os.chdir(cls.agent_folder)

        connections = [_make_dummy_connection()]
        private_key_path = os.path.join(CUR_PATH, "data",
                                        "fet_private_key.txt")
        wallet = Wallet({FETCHAI: private_key_path})
        ledger_apis = LedgerApis({}, FETCHAI)
        identity = Identity(cls.agent_name, address=wallet.addresses[FETCHAI])
        resources = Resources(cls.agent_folder)

        resources.add_component(
            Skill.from_dir(Path(CUR_PATH, "data", "dummy_skill")))

        cls.aea = AEA(
            identity,
            connections,
            wallet,
            ledger_apis,
            resources=resources,
            is_programmatic=False,
        )
        cls.aea.setup()
def run():
    # Create a private keys
    _create_fetchai_private_key(private_key_file=FETCHAI_PRIVATE_KEY_FILE_1)
    _create_fetchai_private_key(private_key_file=FETCHAI_PRIVATE_KEY_FILE_2)

    # Set up the wallets
    wallet_1 = Wallet({FETCHAI: FETCHAI_PRIVATE_KEY_FILE_1})
    wallet_2 = Wallet({FETCHAI: FETCHAI_PRIVATE_KEY_FILE_2})

    # Set up the LedgerApis
    ledger_apis = LedgerApis({FETCHAI: {"network": "testnet"}}, FETCHAI)

    # Generate some wealth
    _try_generate_testnet_wealth(FETCHAI, wallet_1.addresses[FETCHAI])

    logger.info("Sending amount to {}".format(wallet_2.addresses.get(FETCHAI)))

    # Create the transaction and send it to the ledger.
    ledger_api = ledger_apis.apis[FETCHAI]
    tx_nonce = ledger_api.generate_tx_nonce(
        wallet_2.addresses.get(FETCHAI), wallet_1.addresses.get(FETCHAI)
    )
    tx_digest = ledger_api.send_transaction(
        crypto=wallet_1.crypto_objects.get(FETCHAI),
        destination_address=wallet_2.addresses.get(FETCHAI),
        amount=1,
        tx_fee=1,
        tx_nonce=tx_nonce,
    )
    logger.info("Transaction complete.")
    logger.info("The transaction digest is {}".format(tx_digest))
Exemple #28
0
def test_act():
    """Tests the act function of the AEA."""
    with LocalNode() as node:
        agent_name = "MyAgent"
        private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem")
        wallet = Wallet({'default': private_key_pem_path})
        ledger_apis = LedgerApis({})
        public_key = wallet.public_keys['default']
        connections = [OEFLocalConnection(public_key, node)]

        agent = AEA(
            agent_name,
            connections,
            wallet,
            ledger_apis,
            resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea"))))
        t = Thread(target=agent.start)
        try:
            t.start()
            time.sleep(1.0)

            behaviour = agent.resources.behaviour_registry.fetch("dummy")
            assert behaviour[0].nb_act_called > 0, "Act() wasn't called"
        finally:
            agent.stop()
            t.join()
Exemple #29
0
    def setup_class(cls):
        """Set the test up."""
        agent_name = "MyAgent"
        private_key_path = os.path.join(CUR_PATH, "data",
                                        "fet_private_key.txt")
        wallet = Wallet({FETCHAI: private_key_path})
        ledger_apis = LedgerApis({}, FETCHAI)
        resources = Resources()
        resources.add_component(
            Skill.from_dir(Path(CUR_PATH, "data", "dummy_skill")))
        identity = Identity(agent_name, address=wallet.addresses[FETCHAI])
        cls.input_file = tempfile.mkstemp()[1]
        cls.output_file = tempfile.mkstemp()[1]
        cls.agent = AEA(
            identity,
            [_make_local_connection(identity.address, LocalNode())],
            wallet,
            ledger_apis,
            resources,
        )
        for skill in resources.get_all_skills():
            skill.skill_context.set_agent_context(cls.agent.context)

        cls.t = Thread(target=cls.agent.start)
        cls.t.start()
        time.sleep(1.0)
Exemple #30
0
    def setup_class(cls):
        """Initialise the decision maker."""
        cls._patch_logger()
        cls.multiplexer = Multiplexer([_make_dummy_connection()])
        private_key_pem_path = os.path.join(CUR_PATH, "data",
                                            "fet_private_key.txt")
        eth_private_key_pem_path = os.path.join(CUR_PATH, "data",
                                                "fet_private_key.txt")
        cls.wallet = Wallet({
            FETCHAI: private_key_pem_path,
            ETHEREUM: eth_private_key_pem_path
        })
        cls.ledger_apis = LedgerApis({FETCHAI: DEFAULT_FETCHAI_CONFIG},
                                     FETCHAI)
        cls.agent_name = "test"
        cls.identity = Identity(cls.agent_name,
                                addresses=cls.wallet.addresses,
                                default_address_key=FETCHAI)
        cls.ownership_state = OwnershipState()
        cls.preferences = Preferences()
        cls.decision_maker = DecisionMaker(
            identity=cls.identity,
            wallet=cls.wallet,
            ledger_apis=cls.ledger_apis,
        )
        cls.multiplexer.connect()

        cls.tx_id = "transaction0"
        cls.tx_sender_addr = "agent_1"
        cls.tx_counterparty_addr = "pk"
        cls.info = {"some_info_key": "some_info_value"}
        cls.ledger_id = "fetchai"

        cls.decision_maker.start()