Exemplo n.º 1
0
    async def test_send(self):
        """Test the connect functionality of the webhook connection."""
        await self.webhook_connection.connect()
        assert self.webhook_connection.connection_status.is_connected is True

        http_message = HttpMessage(
            dialogue_reference=("", ""),
            target=0,
            message_id=1,
            performative=HttpMessage.Performative.REQUEST,
            method="get",
            url="/",
            headers="",
            bodyy="",
            version="",
        )
        envelope = Envelope(
            to="addr",
            sender="my_id",
            protocol_id=PublicId.from_str("fetchai/http:0.3.0"),
            message=http_message,
        )
        await self.webhook_connection.send(envelope)
Exemplo n.º 2
0
    def setup_class(cls):
        """Set the tests up."""
        cls.patch = unittest.mock.patch.object(aea.registries.base.logger,
                                               "exception")
        cls.mocked_logger = cls.patch.start()

        cls.oldcwd = os.getcwd()
        cls.agent_name = "agent_dir_test"
        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)

        contract = Contract.from_dir(
            str(Path(ROOT_DIR, "packages", "fetchai", "contracts", "erc1155")))

        cls.registry = ContractRegistry()
        cls.registry.register(contract.configuration.public_id,
                              cast(Contract, contract))
        cls.expected_contract_ids = {
            PublicId.from_str("fetchai/erc1155:0.3.0"),
        }
Exemplo n.º 3
0
    def __init__(
        self, address: Address, oef_addr: str, oef_port: int = 10000, *args, **kwargs
    ):
        """
        Initialize.

        :param address: the address of the agent.
        :param oef_addr: the OEF IP address.
        :param oef_port: the OEF port.
        :param connection_id: the identifier of the connection object.
        :param restricted_to_protocols: the only supported protocols for this connection.
        :param excluded_protocols: the excluded protocols for this connection.
        """
        if kwargs.get("connection_id") is None:
            kwargs["connection_id"] = PublicId("fetchai", "oef", "0.1.0")
        super().__init__(*args, **kwargs)
        self._core = AsyncioCore(logger=logger)  # type: AsyncioCore
        self.in_queue = None  # type: Optional[asyncio.Queue]
        self.channel = OEFChannel(
            address, oef_addr, oef_port, core=self._core,
        )  # type: ignore

        self._connection_check_thread = None  # type: Optional[Thread]
Exemplo n.º 4
0
    def __init__(self,
                 provider_addr: str,
                 provider_port: int = 8000,
                 **kwargs):
        """
        Initialize a connection to an SDK or API.

        :param provider_addr: the provider address.
        :param provider_port: the provider port.
        :param kwargs: keyword argument for the parent class.
        """
        if kwargs.get("configuration") is None and kwargs.get(
                "connection_id") is None:
            kwargs["connection_id"] = PublicId("fetchai", "p2p_client",
                                               "0.1.0")
        super().__init__(**kwargs)
        provider_addr = provider_addr
        provider_port = provider_port
        self.channel = PeerToPeerChannel(
            self.address,
            provider_addr,
            provider_port,
            excluded_protocols=self.excluded_protocols)  # type: ignore
Exemplo n.º 5
0
def test_add_behaviour_dynamically():
    """Test that we can add a behaviour dynamically."""
    agent_name = "MyAgent"
    private_key_path = os.path.join(CUR_PATH, "data", DEFAULT_PRIVATE_KEY_FILE)
    wallet = Wallet({DEFAULT_LEDGER: private_key_path})
    resources = Resources()
    identity = Identity(agent_name, address=wallet.addresses[DEFAULT_LEDGER])
    connection = _make_local_connection(identity.address, LocalNode())
    agent = AEA(
        identity,
        wallet,
        resources,
        default_connection=connection.public_id,
    )
    resources.add_connection(connection)
    resources.add_component(
        Skill.from_dir(Path(CUR_PATH, "data", "dummy_skill"),
                       agent_context=agent.context))
    for skill in resources.get_all_skills():
        skill.skill_context.set_agent_context(agent.context)

    with run_in_thread(agent.start, timeout=5, on_exit=agent.stop):
        wait_for_condition(lambda: agent.is_running, timeout=10)

        dummy_skill_id = PublicId("dummy_author", "dummy", "0.1.0")
        dummy_skill = agent.resources.get_skill(dummy_skill_id)

        wait_for_condition(lambda: dummy_skill is not None, timeout=10)

        new_behaviour = DummyBehaviour(name="dummy2",
                                       skill_context=dummy_skill.skill_context)
        dummy_skill.skill_context.new_behaviours.put(new_behaviour)

        wait_for_condition(lambda: new_behaviour.nb_act_called > 0, timeout=10)
        wait_for_condition(
            lambda: len(agent.resources.get_behaviours(dummy_skill_id)) == 2,
            timeout=10)
Exemplo n.º 6
0
    def __init__(self,
                 api_key: str,
                 soef_addr: str = "127.0.0.1",
                 soef_port: int = 10001,
                 **kwargs):
        """
        Initialize.

        :param api_key: the SOEF API key
        :param soef_addr: the SOEF IP address.
        :param soef_port: the SOEF port.
        :param kwargs: the keyword arguments (check the parent constructor)
        """
        if kwargs.get("configuration") is None and kwargs.get(
                "connection_id") is None:
            kwargs["connection_id"] = PUBLIC_ID
        if (kwargs.get("configuration") is None
                and kwargs.get("excluded_protocols") is None):
            kwargs["excluded_protocols"] = []
        if (kwargs.get("configuration") is None
                and kwargs.get("restricted_to_protocols") is None):
            kwargs["restricted_to_protocols"] = [
                PublicId.from_str("fetchai/oef_search:0.1.0")
            ]
        super().__init__(**kwargs)
        self.api_key = api_key
        self.soef_addr = soef_addr
        self.soef_port = soef_port
        self.in_queue = None  # type: Optional[asyncio.Queue]
        self.channel = SOEFChannel(
            self.address,
            self.api_key,
            self.soef_addr,
            self.soef_port,
            self.excluded_protocols,
            self.restricted_to_protocols,
        )
Exemplo n.º 7
0
    def test_send_message(self):
        """Test that the messages in the outbox are posted on the output file."""
        msg = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.BYTES,
            content=b"hello",
        )
        expected_envelope = Envelope(
            to="any",
            sender="any",
            protocol_id=DefaultMessage.protocol_id,
            message=DefaultSerializer().encode(msg),
        )

        self.multiplexer.put(expected_envelope)
        time.sleep(0.1)

        with open(self.output_file_path, "rb+") as f:
            lines = f.readlines()

        assert len(lines) == 2
        line = lines[0] + lines[1]
        to, sender, protocol_id, message, end = line.strip().split(b",",
                                                                   maxsplit=4)
        to = to.decode("utf-8")
        sender = sender.decode("utf-8")
        protocol_id = PublicId.from_str(protocol_id.decode("utf-8"))
        assert end in [b"", b"\n"]

        actual_envelope = Envelope(to=to,
                                   sender=sender,
                                   protocol_id=protocol_id,
                                   message=message)
        assert expected_envelope == actual_envelope
Exemplo n.º 8
0
    async def test_messages(self):
        """Test that at the beginning, the search request returns an empty search result."""
        msg = FIPAMessage((str(0), ""), 0, 0, FIPAMessage.Performative.CFP, query=None)
        msg_bytes = FIPASerializer().encode(msg)
        envelope = Envelope(
            to=DEFAULT_OEF,
            sender=self.address_1,
            protocol_id=FIPAMessage.protocol_id,
            message=msg_bytes,
        )
        with pytest.raises(AEAConnectionError):
            await OEFLocalConnection(
                self.address_1,
                self.node,
                connection_id=PublicId("fetchai", "local", "0.1.0"),
            ).send(envelope)

        self.multiplexer1.connect()
        msg = FIPAMessage(
            (str(0), str(1)), 0, 0, FIPAMessage.Performative.CFP, query=None
        )
        msg_bytes = FIPASerializer().encode(msg)
        envelope = Envelope(
            to="this_address_does_not_exist",
            sender=self.address_1,
            protocol_id=FIPAMessage.protocol_id,
            message=msg_bytes,
        )
        self.multiplexer1.put(envelope)

        # check the result
        response_envelope = self.multiplexer1.get(block=True, timeout=5.0)
        assert response_envelope.protocol_id == OEFMessage.protocol_id
        assert response_envelope.sender == DEFAULT_OEF
        result = OEFSerializer().decode(response_envelope.message)
        assert result.get("type") == OEFMessage.Type.DIALOGUE_ERROR
Exemplo n.º 9
0
    def test_transaction_is_not_affordable(self):
        """Test if the transaction is affordable on the ledger."""
        tx_message = TransactionMessage(
            performative=TransactionMessage.Performative.
            PROPOSE_FOR_SETTLEMENT,
            skill_callback_ids=[PublicId(AUTHOR, "a_skill", "0.1.0")],
            tx_id="transaction0",
            tx_sender_addr="agent_1",
            tx_counterparty_addr="pk",
            tx_amount_by_currency_id={"FET": -20},
            tx_sender_fee=0,
            tx_counterparty_fee=0,
            tx_quantities_by_good_id={"good_id": 10},
            ledger_id="off_chain",
            info={"some_info_key": "some_info_value"},
            tx_nonce="Transaction nonce",
        )

        with mock.patch.object(self.ledger_state_proxy.ledger_apis,
                               "token_balance",
                               return_value=0):
            result = self.ledger_state_proxy.is_affordable_transaction(
                tx_message=tx_message)
        assert not result
Exemplo n.º 10
0
class TestConnection(Connection):
    """Test class for Connection."""

    connection_id = PublicId.from_str("fetchai/some_connection:0.1.0")

    def connect(self, *args, **kwargs):
        """Connect."""
        pass

    def disconnect(self, *args, **kwargs):
        """Disconnect."""
        pass

    def from_config(self, *args, **kwargs):
        """From config."""
        pass

    def receive(self, *args, **kwargs):
        """Receive."""
        pass

    def send(self, *args, **kwargs):
        """Send."""
        pass
Exemplo n.º 11
0
def bump_package_version(
    current_public_id: PublicId,
    configuration_file_path: Path,
    type_: str,
    is_ambiguous: bool = False,
) -> None:
    """
    Bump the version references of the package in the repo.

    Includes, bumping the package itself.
    """
    ver = semver.VersionInfo.parse(current_public_id.version)
    new_version = str(ver.bump_minor())
    new_public_id = PublicId(
        current_public_id.author, current_public_id.name, new_version
    )
    for rootdir in DIRECTORIES:
        for path in Path(rootdir).glob("**/*"):
            if path.is_file() and str(path).endswith((".py", ".yaml", ".md")):
                inplace_change(
                    path, current_public_id, new_public_id, type_, is_ambiguous,
                )

    bump_version_in_yaml(configuration_file_path, type_, new_public_id.version)
Exemplo n.º 12
0
    def _split_component_id_and_config(
            component_index: int,
            component_configuration_json: Dict) -> ComponentId:
        """
        Split component id and configuration.

        :param component_index: the position of the component configuration in the agent config file..
        :param component_configuration_json: the JSON object to process.
        :return: the component id and the configuration object.
        :raises ValueError: if the component id cannot be extracted.
        """
        # author, name, version, type are mandatory fields
        missing_fields = {"public_id", "type"
                          }.difference(component_configuration_json.keys())
        if len(missing_fields) > 0:
            raise ValueError(
                f"There are missing fields in component id {component_index + 1}: {missing_fields}."
            )
        public_id_str = component_configuration_json.pop("public_id")
        component_type = ComponentType(
            component_configuration_json.pop("type"))
        component_public_id = PublicId.from_str(public_id_str)
        component_id = ComponentId(component_type, component_public_id)
        return component_id
Exemplo n.º 13
0
    def setup_class(cls):
        """Set the test up."""
        cls.runner = CliRunner()
        cls.agent_name = "myagent"
        cls.cwd = os.getcwd()
        cls.t = tempfile.mkdtemp()
        cls.skill_id = PublicId.from_str("fetchai/error:0.4.0")
        cls.skill_name = cls.skill_id.name
        cls.skill_author = cls.skill_id.author
        cls.skill_version = cls.skill_id.version

        # copy the 'packages' directory in the parent of the agent folder.
        shutil.copytree(Path(CUR_PATH, "..", "packages"),
                        Path(cls.t, "packages"))

        os.chdir(cls.t)
        result = cls.runner.invoke(
            cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR])
        assert result.exit_code == 0

        result = cls.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "create", "--local", cls.agent_name],
            standalone_mode=False,
        )
        # this also by default adds the oef skill and error skill
        assert result.exit_code == 0
        os.chdir(cls.agent_name)

        # add the error skill again
        cls.result = cls.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "add", "--local", "skill",
             str(cls.skill_id)],
            standalone_mode=False,
        )
Exemplo n.º 14
0
 def test_handle_message_signing_ethereum_deprecated(self):
     """Test message signing for ethereum deprecated."""
     message = b"0x11f3f9487724404e3a1fb7252a3226"
     signing_dialogues = SigningDialogues("agent")
     signing_msg = SigningMessage(
         performative=SigningMessage.Performative.SIGN_MESSAGE,
         dialogue_reference=signing_dialogues.new_self_initiated_dialogue_reference(),
         skill_callback_ids=(str(PublicId("author", "a_skill", "0.1.0")),),
         skill_callback_info={},
         terms=Terms(
             ledger_id=ETHEREUM,
             sender_address="pk1",
             counterparty_address="pk2",
             amount_by_currency_id={"FET": -1},
             is_sender_payable_tx_fee=True,
             quantities_by_good_id={"good_id": 10},
             nonce="transaction nonce",
         ),
         raw_message=RawMessage(ETHEREUM, message, is_deprecated_mode=True),
     )
     signing_msg.counterparty = "decision_maker"
     signing_dialogue = signing_dialogues.update(signing_msg)
     assert signing_dialogue is not None
     self.decision_maker.message_in_queue.put_nowait(signing_msg)
     signing_msg_response = self.decision_maker.message_out_queue.get(timeout=2)
     signing_msg_response.counterparty = signing_msg.counterparty
     signing_msg_response.is_incoming = True
     recovered_dialogue = signing_dialogues.update(signing_msg_response)
     assert recovered_dialogue is not None and recovered_dialogue == signing_dialogue
     assert (
         signing_msg_response.performative
         == SigningMessage.Performative.SIGNED_MESSAGE
     )
     assert signing_msg_response.skill_callback_ids == signing_msg.skill_callback_ids
     assert type(signing_msg_response.signed_message) == SignedMessage
     assert signing_msg_response.signed_message.is_deprecated_mode
Exemplo n.º 15
0
    def setup_class(cls):
        """Set the tests up."""
        # cls._patch_logger() # noqa: E800

        # 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)

        cls.resources = Resources()

        cls.resources.add_component(
            Protocol.from_dir(
                Path(ROOT_DIR, "packages", "fetchai", "protocols", "default")
            )
        )
        cls.resources.add_component(
            Skill.from_dir(
                Path(CUR_PATH, "data", "dummy_skill"),
                agent_context=MagicMock(agent_name="name"),
            )
        )
        cls.resources.add_component(
            Skill.from_dir(
                Path(ROOT_DIR, "packages", "fetchai", "skills", "error"),
                agent_context=MagicMock(agent_name="name"),
            )
        )

        cls.error_skill_public_id = ERROR_SKILL_PUBLIC_ID
        cls.dummy_skill_public_id = PublicId.from_str("dummy_author/dummy:0.1.0")

        cls.contract_public_id = ERC1155_PUBLIC_ID
Exemplo n.º 16
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))  # 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)

        cls.resources = Resources(os.path.join(cls.agent_folder))

        cls.resources.add_component(
            Protocol.from_dir(Path(aea.AEA_DIR, "protocols", "default")))
        # cls.resources.add_component(Component.load_from_directory(ComponentType.PROTOCOL, Path(ROOT_DIR, "packages", "fetchai", "protocols", "oef_search")))
        cls.resources.add_component(
            Skill.from_dir(Path(CUR_PATH, "data", "dummy_skill")))
        cls.resources.add_component(
            Skill.from_dir(Path(aea.AEA_DIR, "skills", "error")))

        cls.error_skill_public_id = PublicId("fetchai", "error", "0.1.0")
        cls.dummy_skill_public_id = PublicId.from_str(
            "dummy_author/dummy:0.1.0")

        cls.expected_skills = {
            PublicId("fetchai", "dummy", "0.1.0"),
            PublicId("fetchai", "error", "0.1.0"),
        }

        cls.expected_protocols = {
            PublicId("fetchai", "default", "0.1.0"),
            PublicId("fetchai", "oef_search", "0.1.0"),
        }
Exemplo n.º 17
0
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
#   Copyright 2018-2019 Fetch.AI Limited
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
# ------------------------------------------------------------------------------

"""This module contains the implementation of the error skill."""

from aea.configurations.base import PublicId


PUBLIC_ID = PublicId.from_str("fetchai/error:0.11.0")
Exemplo n.º 18
0
 def test_public_id_lt_positive(self):
     """Test case for json __lt__ method positive result."""
     obj1 = PublicId(AUTHOR, "name", "1.0.0")
     obj2 = PublicId(AUTHOR, "name", "2.0.0")
     self.assertTrue(obj1 < obj2)
Exemplo n.º 19
0
 def test_public_id_json_positive(self):
     """Test case for json property positive result."""
     obj = PublicId(AUTHOR, "name", "0.1.0")
     obj.json
Exemplo n.º 20
0
 def test_public_id_from_json_positive(self):
     """Test case for from_json method positive result."""
     obj = {"author": AUTHOR, "name": "name", "version": "0.1.0"}
     PublicId.from_json(obj)
Exemplo n.º 21
0
 def test_public_id_from_str_not_matching(self, *mocks):
     """Test case for from_str method regex not matching."""
     with self.assertRaises(ValueError):
         PublicId.from_str("public_id_str")
Exemplo n.º 22
0
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
#   Copyright 2018-2019 Fetch.AI Limited
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
# ------------------------------------------------------------------------------
"""This module contains the implementation of the simple oracle skill."""

from aea.configurations.base import PublicId

PUBLIC_ID = PublicId.from_str("fetchai/simple_oracle:0.5.0")
Exemplo n.º 23
0
class FipaMessage(Message):
    """A protocol for FIPA ACL."""

    protocol_id = PublicId.from_str("fetchai/fipa:0.14.0")
    protocol_specification_id = PublicId.from_str("fetchai/fipa:0.1.0")

    Description = CustomDescription

    Query = CustomQuery

    class Performative(Message.Performative):
        """Performatives for the fipa protocol."""

        ACCEPT = "accept"
        ACCEPT_W_INFORM = "accept_w_inform"
        CFP = "cfp"
        DECLINE = "decline"
        END = "end"
        INFORM = "inform"
        MATCH_ACCEPT = "match_accept"
        MATCH_ACCEPT_W_INFORM = "match_accept_w_inform"
        PROPOSE = "propose"

        def __str__(self) -> str:
            """Get the string representation."""
            return str(self.value)

    _performatives = {
        "accept",
        "accept_w_inform",
        "cfp",
        "decline",
        "end",
        "inform",
        "match_accept",
        "match_accept_w_inform",
        "propose",
    }
    __slots__: Tuple[str, ...] = tuple()

    class _SlotsCls:
        __slots__ = (
            "dialogue_reference",
            "info",
            "message_id",
            "performative",
            "proposal",
            "query",
            "target",
        )

    def __init__(
        self,
        performative: Performative,
        dialogue_reference: Tuple[str, str] = ("", ""),
        message_id: int = 1,
        target: int = 0,
        **kwargs: Any,
    ):
        """
        Initialise an instance of FipaMessage.

        :param message_id: the message id.
        :param dialogue_reference: the dialogue reference.
        :param target: the message target.
        :param performative: the message performative.
        """
        super().__init__(
            dialogue_reference=dialogue_reference,
            message_id=message_id,
            target=target,
            performative=FipaMessage.Performative(performative),
            **kwargs,
        )

    @property
    def valid_performatives(self) -> Set[str]:
        """Get valid performatives."""
        return self._performatives

    @property
    def dialogue_reference(self) -> Tuple[str, str]:
        """Get the dialogue_reference of the message."""
        enforce(self.is_set("dialogue_reference"), "dialogue_reference is not set.")
        return cast(Tuple[str, str], self.get("dialogue_reference"))

    @property
    def message_id(self) -> int:
        """Get the message_id of the message."""
        enforce(self.is_set("message_id"), "message_id is not set.")
        return cast(int, self.get("message_id"))

    @property
    def performative(self) -> Performative:  # type: ignore # noqa: F821
        """Get the performative of the message."""
        enforce(self.is_set("performative"), "performative is not set.")
        return cast(FipaMessage.Performative, self.get("performative"))

    @property
    def target(self) -> int:
        """Get the target of the message."""
        enforce(self.is_set("target"), "target is not set.")
        return cast(int, self.get("target"))

    @property
    def info(self) -> Dict[str, str]:
        """Get the 'info' content from the message."""
        enforce(self.is_set("info"), "'info' content is not set.")
        return cast(Dict[str, str], self.get("info"))

    @property
    def proposal(self) -> CustomDescription:
        """Get the 'proposal' content from the message."""
        enforce(self.is_set("proposal"), "'proposal' content is not set.")
        return cast(CustomDescription, self.get("proposal"))

    @property
    def query(self) -> CustomQuery:
        """Get the 'query' content from the message."""
        enforce(self.is_set("query"), "'query' content is not set.")
        return cast(CustomQuery, self.get("query"))

    def _is_consistent(self) -> bool:
        """Check that the message follows the fipa protocol."""
        try:
            enforce(
                type(self.dialogue_reference) == tuple,
                "Invalid type for 'dialogue_reference'. Expected 'tuple'. Found '{}'.".format(
                    type(self.dialogue_reference)
                ),
            )
            enforce(
                type(self.dialogue_reference[0]) == str,
                "Invalid type for 'dialogue_reference[0]'. Expected 'str'. Found '{}'.".format(
                    type(self.dialogue_reference[0])
                ),
            )
            enforce(
                type(self.dialogue_reference[1]) == str,
                "Invalid type for 'dialogue_reference[1]'. Expected 'str'. Found '{}'.".format(
                    type(self.dialogue_reference[1])
                ),
            )
            enforce(
                type(self.message_id) == int,
                "Invalid type for 'message_id'. Expected 'int'. Found '{}'.".format(
                    type(self.message_id)
                ),
            )
            enforce(
                type(self.target) == int,
                "Invalid type for 'target'. Expected 'int'. Found '{}'.".format(
                    type(self.target)
                ),
            )

            # Light Protocol Rule 2
            # Check correct performative
            enforce(
                type(self.performative) == FipaMessage.Performative,
                "Invalid 'performative'. Expected either of '{}'. Found '{}'.".format(
                    self.valid_performatives, self.performative
                ),
            )

            # Check correct contents
            actual_nb_of_contents = len(self._body) - DEFAULT_BODY_SIZE
            expected_nb_of_contents = 0
            if self.performative == FipaMessage.Performative.CFP:
                expected_nb_of_contents = 1
                enforce(
                    type(self.query) == CustomQuery,
                    "Invalid type for content 'query'. Expected 'Query'. Found '{}'.".format(
                        type(self.query)
                    ),
                )
            elif self.performative == FipaMessage.Performative.PROPOSE:
                expected_nb_of_contents = 1
                enforce(
                    type(self.proposal) == CustomDescription,
                    "Invalid type for content 'proposal'. Expected 'Description'. Found '{}'.".format(
                        type(self.proposal)
                    ),
                )
            elif self.performative == FipaMessage.Performative.ACCEPT_W_INFORM:
                expected_nb_of_contents = 1
                enforce(
                    type(self.info) == dict,
                    "Invalid type for content 'info'. Expected 'dict'. Found '{}'.".format(
                        type(self.info)
                    ),
                )
                for key_of_info, value_of_info in self.info.items():
                    enforce(
                        type(key_of_info) == str,
                        "Invalid type for dictionary keys in content 'info'. Expected 'str'. Found '{}'.".format(
                            type(key_of_info)
                        ),
                    )
                    enforce(
                        type(value_of_info) == str,
                        "Invalid type for dictionary values in content 'info'. Expected 'str'. Found '{}'.".format(
                            type(value_of_info)
                        ),
                    )
            elif self.performative == FipaMessage.Performative.MATCH_ACCEPT_W_INFORM:
                expected_nb_of_contents = 1
                enforce(
                    type(self.info) == dict,
                    "Invalid type for content 'info'. Expected 'dict'. Found '{}'.".format(
                        type(self.info)
                    ),
                )
                for key_of_info, value_of_info in self.info.items():
                    enforce(
                        type(key_of_info) == str,
                        "Invalid type for dictionary keys in content 'info'. Expected 'str'. Found '{}'.".format(
                            type(key_of_info)
                        ),
                    )
                    enforce(
                        type(value_of_info) == str,
                        "Invalid type for dictionary values in content 'info'. Expected 'str'. Found '{}'.".format(
                            type(value_of_info)
                        ),
                    )
            elif self.performative == FipaMessage.Performative.INFORM:
                expected_nb_of_contents = 1
                enforce(
                    type(self.info) == dict,
                    "Invalid type for content 'info'. Expected 'dict'. Found '{}'.".format(
                        type(self.info)
                    ),
                )
                for key_of_info, value_of_info in self.info.items():
                    enforce(
                        type(key_of_info) == str,
                        "Invalid type for dictionary keys in content 'info'. Expected 'str'. Found '{}'.".format(
                            type(key_of_info)
                        ),
                    )
                    enforce(
                        type(value_of_info) == str,
                        "Invalid type for dictionary values in content 'info'. Expected 'str'. Found '{}'.".format(
                            type(value_of_info)
                        ),
                    )
            elif self.performative == FipaMessage.Performative.ACCEPT:
                expected_nb_of_contents = 0
            elif self.performative == FipaMessage.Performative.DECLINE:
                expected_nb_of_contents = 0
            elif self.performative == FipaMessage.Performative.MATCH_ACCEPT:
                expected_nb_of_contents = 0
            elif self.performative == FipaMessage.Performative.END:
                expected_nb_of_contents = 0

            # Check correct content count
            enforce(
                expected_nb_of_contents == actual_nb_of_contents,
                "Incorrect number of contents. Expected {}. Found {}".format(
                    expected_nb_of_contents, actual_nb_of_contents
                ),
            )

            # Light Protocol Rule 3
            if self.message_id == 1:
                enforce(
                    self.target == 0,
                    "Invalid 'target'. Expected 0 (because 'message_id' is 1). Found {}.".format(
                        self.target
                    ),
                )
        except (AEAEnforceError, ValueError, KeyError) as e:
            _default_logger.error(str(e))
            return False

        return True
Exemplo n.º 24
0
 def extract_package_id(match: Match) -> PackageId:
     package_public_id = match.group(1)
     package_id = PackageId(PackageType.AGENT,
                            PublicId.from_str(package_public_id))
     return package_id
Exemplo n.º 25
0
 def extract_package_id(match: Match) -> PackageId:
     package_type, package = match.group(1), match.group(2)
     package_id = PackageId(PackageType(package_type),
                            PublicId.from_str(package))
     return package_id
Exemplo n.º 26
0
 def test_fetch(self):
     """Test that the `fetch` method works as expected."""
     contract_id = PublicId.from_str("fetchai/erc1155:0.6.0")
     contract = self.registry.fetch(ComponentId(ComponentType.CONTRACT, contract_id))
     assert isinstance(contract, Contract)
     assert contract.id == contract_id
Exemplo n.º 27
0
 def test_unregister_by_skill_when_item_not_registered(self):
     """Test 'unregister_by_skill' in case the item is not registered."""
     with pytest.raises(
         ValueError, match="No component of skill .* present in the registry."
     ):
         self.registry.unregister_by_skill(PublicId.from_str("author/skill:0.1.0"))
Exemplo n.º 28
0
 def test_unregister_when_item_not_registered(self):
     """Test 'unregister' in case the item is not registered."""
     with pytest.raises(ValueError):
         self.registry.unregister(
             (PublicId.from_str("author/name:0.1.0"), "component_name")
         )
Exemplo n.º 29
0
#
# ------------------------------------------------------------------------------
"""This module contains the class to connect to an Oracle contract."""

import logging
from typing import Any, Dict

from vyper.utils import keccak256

from aea.common import Address, JSONLike
from aea.configurations.base import PublicId
from aea.contracts.base import Contract
from aea.crypto.base import LedgerApi
from aea.crypto.ethereum import EthereumApi

PUBLIC_ID = PublicId.from_str("fetchai/oracle:0.4.0")
CONTRACT_ROLE = keccak256(b"ORACLE_ROLE")

_default_logger = logging.getLogger(
    "aea.packages.fetchai.contracts.oracle.contract")


class FetchOracleContract(Contract):
    """The Fetch oracle contract."""
    @classmethod
    def get_grant_role_transaction(
        cls,
        ledger_api: LedgerApi,
        contract_address: Address,
        oracle_address: Address,
        gas: int = 0,
Exemplo n.º 30
0
 def test_handle_messages_from_two_dialogues_same_agent(self):
     """Test message signing for unknown."""
     message = b"0x11f3f9487724404e3a1fb7252a322656b90ba0455a2ca5fcdcbe6eeee5f8126d"
     signing_dialogues = SigningDialogues("agent")
     dialogue_reference = signing_dialogues.new_self_initiated_dialogue_reference()
     signing_msg = SigningMessage(
         performative=SigningMessage.Performative.SIGN_MESSAGE,
         dialogue_reference=dialogue_reference,
         skill_callback_ids=(str(PublicId("author", "a_skill", "0.1.0")),),
         skill_callback_info={},
         terms=Terms(
             ledger_id="unknown",
             sender_address="pk1",
             counterparty_address="pk2",
             amount_by_currency_id={"FET": -1},
             is_sender_payable_tx_fee=True,
             quantities_by_good_id={"good_id": 10},
             nonce="transaction nonce",
         ),
         raw_message=RawMessage("unknown", message),
     )
     signing_msg.counterparty = "decision_maker"
     signing_dialogue = signing_dialogues.update(signing_msg)
     assert signing_dialogue is not None
     self.decision_maker.message_in_queue.put_nowait(signing_msg)
     signing_msg_response = self.decision_maker.message_out_queue.get(timeout=2)
     assert signing_msg_response is not None
     signing_dialogues = SigningDialogues("agent")
     signing_msg = SigningMessage(
         performative=SigningMessage.Performative.SIGN_MESSAGE,
         dialogue_reference=dialogue_reference,
         skill_callback_ids=(str(PublicId("author", "a_skill", "0.1.0")),),
         skill_callback_info={},
         terms=Terms(
             ledger_id="unknown",
             sender_address="pk1",
             counterparty_address="pk2",
             amount_by_currency_id={"FET": -1},
             is_sender_payable_tx_fee=True,
             quantities_by_good_id={"good_id": 10},
             nonce="transaction nonce",
         ),
         raw_message=RawMessage("unknown", message),
     )
     signing_msg.counterparty = "decision_maker"
     signing_dialogue = signing_dialogues.update(signing_msg)
     assert signing_dialogue is not None
     with pytest.raises(Exception):
         # Exception occurs because the same counterparty sends two identical dialogue references
         self.decision_maker.message_out_queue.get(timeout=1)
     # test twice; should work again even from same agent
     signing_dialogues = SigningDialogues("agent")
     signing_msg = SigningMessage(
         performative=SigningMessage.Performative.SIGN_MESSAGE,
         dialogue_reference=signing_dialogues.new_self_initiated_dialogue_reference(),
         skill_callback_ids=(str(PublicId("author", "a_skill", "0.1.0")),),
         skill_callback_info={},
         terms=Terms(
             ledger_id="unknown",
             sender_address="pk1",
             counterparty_address="pk2",
             amount_by_currency_id={"FET": -1},
             is_sender_payable_tx_fee=True,
             quantities_by_good_id={"good_id": 10},
             nonce="transaction nonce",
         ),
         raw_message=RawMessage("unknown", message),
     )
     signing_msg.counterparty = "decision_maker"
     signing_dialogue = signing_dialogues.update(signing_msg)
     assert signing_dialogue is not None
     self.decision_maker.message_in_queue.put_nowait(signing_msg)
     signing_msg_response = self.decision_maker.message_out_queue.get(timeout=2)
     assert signing_msg_response is not None