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

        cls.registry = AgentComponentRegistry()

        protocol_1 = Protocol.from_dir(Path(aea.AEA_DIR, "protocols", "default"))
        protocol_2 = Protocol.from_dir(
            Path(ROOT_DIR, "packages", "fetchai", "protocols", "fipa"),
        )
        cls.registry.register(protocol_1.component_id, protocol_1)
        cls.registry.register(protocol_2.component_id, protocol_2)

        cls.expected_protocol_ids = {
            DEFAULT_PROTOCOL,
            PublicId.from_str("fetchai/fipa:0.4.0"),
        }
Exemple #2
0
def make_agent(agent_name="my_agent", runtime_mode="threaded") -> AEA:
    """Make AEA instance."""
    wallet = Wallet({DEFAULT_LEDGER: None})
    identity = Identity(agent_name, address=agent_name)
    resources = Resources()
    agent_context = MagicMock()
    agent_context.agent_name = agent_name
    agent_context.agent_address = agent_name

    resources.add_skill(
        Skill.from_dir(
            str(
                PACKAGES_DIR / FETCHAI / SKILLS / PublicId.from_str(DEFAULT_SKILL).name
            ),
            agent_context=agent_context,
        )
    )
    resources.add_protocol(
        Protocol.from_dir(
            str(
                PACKAGES_DIR
                / FETCHAI
                / PROTOCOLS
                / PublicId.from_str(DEFAULT_PROTOCOL).name
            )
        )
    )
    return AEA(identity, wallet, resources, runtime_mode=runtime_mode)
Exemple #3
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 #4
0
def make_agent(*args: Any, **kwargs: Any) -> AEA:
    """Make agent with http protocol support."""
    aea = base_make_agent(*args, **kwargs)
    aea.resources.add_protocol(
        Protocol.from_dir(str(PACKAGES_DIR / "fetchai" / "protocols" /
                              "http")))
    return aea
def test_multiple_builds_with_component_instance():
    """Test multiple calls to the 'build()' method when adding component instances."""
    builder = AEABuilder()
    builder.set_name("aea_1")
    builder.add_private_key("fetchai")

    a_protocol = Protocol(
        ProtocolConfig("a_protocol", "author", "0.1.0"), DefaultMessage
    )
    builder.add_component_instance(a_protocol)

    # the first call works
    aea_1 = builder.build()
    assert isinstance(aea_1, AEA)

    # the second call fails
    with pytest.raises(ValueError, match="Cannot build.*"):
        builder.build()

    # after reset, it works
    builder.reset()
    builder.set_name("aea_1")
    builder.add_private_key("fetchai")
    builder.add_component_instance(a_protocol)
    aea_2 = builder.build()
    assert isinstance(aea_2, AEA)
Exemple #6
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
Exemple #7
0
    def _add_protocol(self, directory: str, protocol_name: str):
        """
        Add a protocol.

        :param directory: the agent's resources directory.
        :param protocol_name: the name of the protocol to be added.
        :return: None
        """
        # get the serializer
        serialization_spec = importlib.util.spec_from_file_location("serialization",
                                                                    os.path.join(directory, "protocols", protocol_name, "serialization.py"))
        serialization_module = importlib.util.module_from_spec(serialization_spec)
        serialization_spec.loader.exec_module(serialization_module)  # type: ignore
        classes = inspect.getmembers(serialization_module, inspect.isclass)
        serializer_classes = list(filter(lambda x: re.match("\\w+Serializer", x[0]), classes))
        serializer_class = serializer_classes[0][1]

        logger.debug("Found serializer class {serializer_class} for protocol {protocol_name}"
                     .format(serializer_class=serializer_class, protocol_name=protocol_name))
        serializer = serializer_class()

        config_loader = ConfigLoader("protocol-config_schema.json", ProtocolConfig)
        protocol_config = config_loader.load(open(Path(directory, "protocols", protocol_name, DEFAULT_PROTOCOL_CONFIG_FILE)))

        # instantiate the protocol manager.
        protocol = Protocol(protocol_name, serializer, protocol_config)
        self.register((protocol_name, None), protocol)
Exemple #8
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()

        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"), agent_context=MagicMock(),
            )
        )
        cls.resources.add_component(
            Skill.from_dir(
                Path(aea.AEA_DIR, "skills", "error"), agent_context=MagicMock(),
            )
        )

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

        cls.contract_public_id = PublicId.from_str("fetchai/erc1155:0.6.0")
Exemple #9
0
    def setup_class(cls):
        """Set the test up."""
        cls.node = LocalNode()
        cls.node.start()
        cls.agent_name = "MyAgent"
        cls.private_key_path = os.path.join(CUR_PATH, "data",
                                            "fet_private_key.txt")
        cls.wallet = Wallet({FETCHAI: cls.private_key_path})
        cls.ledger_apis = LedgerApis({}, FETCHAI)
        cls.identity = Identity(cls.agent_name,
                                address=cls.wallet.addresses[FETCHAI])
        cls.connection = _make_local_connection(cls.agent_name, cls.node)
        cls.connections = [cls.connection]
        cls.temp = tempfile.mkdtemp(prefix="test_aea_resources")
        cls.resources = Resources(cls.temp)

        cls.default_protocol = Protocol.from_dir(
            str(Path(AEA_DIR, "protocols", "default")))
        cls.resources.add_protocol(cls.default_protocol)

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

        cls.aea = AEA(
            cls.identity,
            cls.connections,
            cls.wallet,
            cls.ledger_apis,
            resources=cls.resources,
        )

        cls.error_skill.skill_context.set_agent_context(cls.aea.context)
        cls.dummy_skill.skill_context.set_agent_context(cls.aea.context)

        default_protocol_id = DefaultMessage.protocol_id

        cls.expected_message = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.BYTES,
            content=b"hello",
        )
        cls.expected_message.counterparty = cls.agent_name

        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_protocol_id,
                message=DefaultSerializer().encode(cls.expected_message),
            ))
Exemple #10
0
 def test_protocols_config(self):
     """Test the protocol config."""
     protocol = Protocol(
         protocol_id=PublicId.from_str("author/my_own_protocol:0.1.0"),
         serializer=cast(Serializer, ProtobufSerializer),
         config=ProtocolConfig(),
     )
     assert protocol.config is not None
Exemple #11
0
 def test_add_protocol(self):
     """Test that the 'add protocol' method works correctly."""
     oef_protocol = Protocol.from_dir(
         Path(ROOT_DIR, "packages", "fetchai", "protocols", "oef_search"), )
     self.resources.add_protocol(cast(Protocol, oef_protocol))
     for protocol_id in self.expected_protocols:
         assert (self.resources.get_protocol(protocol_id)
                 is not None), "Protocol missing!"
Exemple #12
0
 def test_protocol_load_positive(self):
     """Test protocol loaded correctly."""
     default_protocol = Protocol.from_dir(
         os.path.join(AEA_DIR, "protocols", "default")
     )
     assert (
         str(default_protocol.id) == "fetchai/default:0.1.0"
     ), "Protocol not loaded correctly."
 def test_add_protocol(self):
     """Test that the 'add protocol' method works correctly."""
     oef_protocol = Protocol.from_dir(
         os.path.join(ROOT_DIR, "packages", "fetchai", "protocols", "oef"))
     self.resources.add_protocol(oef_protocol)
     for protocol_id in self.expected_protocols:
         assert (self.resources.protocol_registry.fetch(protocol_id)
                 is not None), "Protocol missing!"
Exemple #14
0
 def test_add_and_remove_protocol(self):
     """Test that the 'add protocol' and 'remove protocol' method work correctly."""
     a_protocol = Protocol.from_dir(
         Path(ROOT_DIR, "packages", "fetchai", "protocols", "oef_search"), )
     self.resources.add_component(cast(Protocol, a_protocol))
     assert self.resources.get_protocol(a_protocol.public_id) == a_protocol
     # restore state
     self.resources.remove_protocol(a_protocol.public_id)
     assert self.resources.get_protocol(a_protocol.public_id) is None
Exemple #15
0
 def test_protocol_load_positive(self):
     """Test protocol loaded correctly."""
     default_protocol = Protocol.from_dir(
         Path("packages", "fetchai", "protocols", "default")
     )
     assert str(default_protocol.public_id) == str(
         DefaultMessage.protocol_id
     ), "Protocol not loaded correctly."
     assert default_protocol.serializer is not None
def test_find_component_failed():
    """Test fail on compomnent not found."""
    builder = AEABuilder()
    builder.set_name("aea_1")
    builder.add_private_key("fetchai")
    a_protocol = Protocol(ProtocolConfig("a_protocol", "author", "0.1.0"),
                          DefaultMessage)
    with pytest.raises(ValueError, match=r"Package .* not found"):
        builder._find_component_directory_from_component_id(
            Path("/some_dir"), a_protocol.component_id)
Exemple #17
0
 def _load_and_add_protocols(self) -> None:
     for configuration in self._package_dependency_manager.protocols.values():
         configuration = cast(ProtocolConfig, configuration)
         try:
             protocol = Protocol.from_config(configuration)
         except Exception as e:
             raise Exception(
                 "An error occurred while loading protocol {}: {}".format(
                     configuration.public_id, str(e)
                 )
             )
         self._add_component_to_resources(protocol)
Exemple #18
0
def _load_packages(agent_identity: Identity) -> None:
    """Load packages in the current interpreter."""
    default_protocol_id = PublicId.from_str(DEFAULT_PROTOCOL)
    Protocol.from_dir(
        os.path.join(VENDOR, default_protocol_id.author, PROTOCOLS,
                     default_protocol_id.name))
    signing_protocol_id = PublicId.from_str(SIGNING_PROTOCOL)
    Protocol.from_dir(
        os.path.join(VENDOR, signing_protocol_id.author, PROTOCOLS,
                     signing_protocol_id.name))
    state_update_protocol_id = PublicId.from_str(STATE_UPDATE_PROTOCOL)
    Protocol.from_dir(
        os.path.join(
            VENDOR,
            state_update_protocol_id.author,
            PROTOCOLS,
            state_update_protocol_id.name,
        ))
    stub_connection_id = PublicId.from_str(STUB_CONNECTION)
    Connection.from_dir(
        os.path.join(
            VENDOR,
            stub_connection_id.author,
            CONNECTIONS,
            stub_connection_id.name,
        ),
        agent_identity,
        CryptoStore(),
        os.getcwd(),
    )
Exemple #19
0
def test_remove_protocol():
    """Test add/remove protocol."""
    builder = AEABuilder()
    builder.set_name("aea_1")
    builder.add_private_key("fetchai")
    a_protocol = Protocol(
        ProtocolConfig("a_protocol", "author", "0.1.0"), DefaultMessage
    )
    num_deps = len(builder._package_dependency_manager.all_dependencies)
    builder.add_component_instance(a_protocol)
    assert len(builder._package_dependency_manager.all_dependencies) == num_deps + 1
    builder.remove_protocol(a_protocol.public_id)
    assert len(builder._package_dependency_manager.all_dependencies) == num_deps
Exemple #20
0
    def _add_protocol(
        self,
        protocol_directory: Path,
        allowed_protocols: Optional[Set[PublicId]] = None,
    ):
        """
        Add a protocol. If the protocol is not allowed, it is ignored.

        :param protocol_directory: the directory of the protocol to be added.
        :param allowed_protocols: an optional set of allowed protocols.
                                  If None, every protocol is allowed.
        :return: None
        """
        protocol_name = protocol_directory.name
        config_loader = ConfigLoader("protocol-config_schema.json",
                                     ProtocolConfig)
        protocol_config = config_loader.load(
            open(protocol_directory / DEFAULT_PROTOCOL_CONFIG_FILE))
        protocol_public_id = PublicId(protocol_config.author,
                                      protocol_config.name,
                                      protocol_config.version)
        if (allowed_protocols is not None
                and protocol_public_id not in allowed_protocols):
            logger.debug(
                "Ignoring protocol {}, not declared in the configuration file."
                .format(protocol_public_id))
            return

        # get the serializer
        serialization_spec = importlib.util.spec_from_file_location(
            "serialization", protocol_directory / "serialization.py")
        serialization_module = importlib.util.module_from_spec(
            serialization_spec)
        serialization_spec.loader.exec_module(
            serialization_module)  # type: ignore
        classes = inspect.getmembers(serialization_module, inspect.isclass)
        serializer_classes = list(
            filter(lambda x: re.match("\\w+Serializer", x[0]), classes))
        serializer_class = serializer_classes[0][1]

        logger.debug(
            "Found serializer class {serializer_class} for protocol {protocol_name}"
            .format(serializer_class=serializer_class,
                    protocol_name=protocol_name))
        serializer = serializer_class()

        # instantiate the protocol
        protocol = Protocol(protocol_config.public_id, serializer,
                            protocol_config)
        self.register(protocol_public_id, protocol)
Exemple #21
0
def test_component_add_bad_dep():
    """Test component load failed cause dependency."""
    builder = AEABuilder()
    builder.set_name("aea_1")
    builder.add_private_key("fetchai")
    connection = _make_dummy_connection()
    connection.configuration.pypi_dependencies = {
        "something": Dependency("something", "==0.1.0")
    }
    builder.add_component_instance(connection)

    a_protocol = Protocol(
        ProtocolConfig("a_protocol", "author", "0.1.0"), DefaultMessage
    )
    a_protocol.configuration.pypi_dependencies = {
        "something": Dependency("something", "==0.2.0")
    }
    with pytest.raises(
        AEAException, match=r"Conflict on package something: specifier set .*"
    ):
        builder.add_component_instance(a_protocol)
Exemple #22
0
def _load_packages(agent_identity: Identity):
    """Load packages in the current interpreter."""
    Protocol.from_dir(
        os.path.join("vendor", DEFAULT_PROTOCOL.author, "protocols",
                     DEFAULT_PROTOCOL.name))
    Protocol.from_dir(
        os.path.join("vendor", SIGNING_PROTOCOL.author, "protocols",
                     SIGNING_PROTOCOL.name))
    Protocol.from_dir(
        os.path.join(
            "vendor",
            STATE_UPDATE_PROTOCOL.author,
            "protocols",
            STATE_UPDATE_PROTOCOL.name,
        ))
    Connection.from_dir(
        os.path.join("vendor", DEFAULT_CONNECTION.author, "connections",
                     DEFAULT_CONNECTION.name),
        agent_identity,
        CryptoStore(),
    )
Exemple #23
0
 def test_protocols_config(self):
     """Test the protocol config."""
     protocol = Protocol(id="test",
                         serializer=cast(Serializer, ProtobufSerializer),
                         config=ProtocolConfig())
     assert protocol.config is not None
Exemple #24
0
def test_initialize_aea_programmatically_build_resources():
    """Test that we can initialize the agent by building the resource object."""
    try:
        temp = tempfile.mkdtemp(prefix="test_aea_resources")
        with LocalNode() as node:
            agent_name = "MyAgent"
            private_key_path = os.path.join(CUR_PATH, "data",
                                            DEFAULT_PRIVATE_KEY_FILE)
            wallet = Wallet({DEFAULT_LEDGER: private_key_path})
            identity = Identity(agent_name,
                                address=wallet.addresses[DEFAULT_LEDGER])
            connection = _make_local_connection(agent_name, node)

            resources = Resources()
            aea = AEA(
                identity,
                wallet,
                resources=resources,
                default_connection=connection.public_id,
            )

            default_protocol = Protocol.from_dir(
                str(Path(AEA_DIR, "protocols", "default")))
            resources.add_protocol(default_protocol)
            resources.add_connection(connection)

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

            default_protocol_id = DefaultMessage.protocol_id

            expected_message = DefaultMessage(
                dialogue_reference=("", ""),
                message_id=1,
                target=0,
                performative=DefaultMessage.Performative.BYTES,
                content=b"hello",
            )
            expected_message.counterparty = agent_name
            expected_message.sender = agent_name

            with run_in_thread(aea.start, timeout=5, on_exit=aea.stop):
                wait_for_condition(lambda: aea.is_running, timeout=10)
                aea.outbox.put(
                    Envelope(
                        to=agent_name,
                        sender=agent_name,
                        protocol_id=default_protocol_id,
                        message=expected_message,
                    ))

                dummy_skill_id = DUMMY_SKILL_PUBLIC_ID
                dummy_behaviour_name = "dummy"
                dummy_behaviour = aea.resources.get_behaviour(
                    dummy_skill_id, dummy_behaviour_name)
                wait_for_condition(lambda: dummy_behaviour is not None,
                                   timeout=10)
                wait_for_condition(lambda: dummy_behaviour.nb_act_called > 0,
                                   timeout=10)

                dummy_task = DummyTask()
                task_id = aea.task_manager.enqueue_task(dummy_task)
                async_result = aea.task_manager.get_task_result(task_id)
                expected_dummy_task = async_result.get(10.0)
                wait_for_condition(
                    lambda: expected_dummy_task.nb_execute_called > 0,
                    timeout=10)
                dummy_handler_name = "dummy"
                dummy_handler = aea.resources._handler_registry.fetch(
                    (dummy_skill_id, dummy_handler_name))
                dummy_handler_alt = aea.resources.get_handler(
                    DefaultMessage.protocol_id, dummy_skill_id)
                wait_for_condition(lambda: dummy_handler == dummy_handler_alt,
                                   timeout=10)
                wait_for_condition(lambda: dummy_handler is not None,
                                   timeout=10)
                wait_for_condition(
                    lambda: len(dummy_handler.handled_messages) == 1,
                    timeout=10)
                wait_for_condition(
                    lambda: dummy_handler.handled_messages[0] ==
                    expected_message,
                    timeout=10,
                )
    finally:
        Path(temp).rmdir()
    async def test_end_to_end_aea_aca(self):
        """Test the end to end aea aca interaction."""
        # AEA components
        wallet = Wallet({DEFAULT_LEDGER: DEFAULT_PRIVATE_KEY_FILE})
        identity = Identity(
            name="my_aea_1",
            address=wallet.addresses.get(DEFAULT_LEDGER),
            default_address_key=DEFAULT_LEDGER,
        )
        configuration = ConnectionConfig(
            host=self.aca_admin_address,
            port=self.aca_admin_port,
            connection_id=HTTPClientConnection.connection_id,
        )
        http_client_connection = HTTPClientConnection(
            configuration=configuration,
            identity=identity,
        )
        resources = Resources()
        resources.add_connection(http_client_connection)

        # create AEA
        aea = AEA(identity, wallet, resources)

        # Add http protocol to AEA resources
        http_protocol_configuration = ProtocolConfig.from_json(
            yaml.safe_load(
                open(
                    os.path.join(
                        self.cwd,
                        "packages",
                        "fetchai",
                        "protocols",
                        "http",
                        "protocol.yaml",
                    ))))
        http_protocol = Protocol(http_protocol_configuration,
                                 HttpMessage.serializer())
        resources.add_protocol(http_protocol)

        # Request message & envelope
        request_http_message = HttpMessage(
            dialogue_reference=("", ""),
            target=0,
            message_id=1,
            performative=HttpMessage.Performative.REQUEST,
            method="GET",
            url="http://{}:{}/status".format(self.aca_admin_address,
                                             self.aca_admin_port),
            headers="",
            version="",
            body=b"",
        )
        request_http_message.to = "ACA"
        request_envelope = Envelope(
            to="ACA",
            sender="AEA",
            protocol_id=HttpMessage.protocol_id,
            message=request_http_message,
        )

        # add a simple skill with handler
        skill_context = SkillContext(aea.context)
        skill_config = SkillConfig(name="simple_skill",
                                   author="fetchai",
                                   version="0.1.0")
        aea_handler = AEAHandler(skill_context=skill_context,
                                 name="aea_handler")
        simple_skill = Skill(skill_config,
                             skill_context,
                             handlers={aea_handler.name: aea_handler})
        resources.add_skill(simple_skill)

        # add error skill to AEA
        error_skill = Skill.from_dir(os.path.join(AEA_DIR, "skills", "error"),
                                     agent_context=aea.context)
        resources.add_skill(error_skill)

        # start AEA thread
        t_aea = Thread(target=aea.start)
        try:
            t_aea.start()
            time.sleep(1.0)
            aea.outbox.put(request_envelope)
            time.sleep(5.0)
            assert (aea_handler.handled_message.performative ==
                    HttpMessage.Performative.RESPONSE)
            assert aea_handler.handled_message.version == ""
            assert aea_handler.handled_message.status_code == 200
            assert aea_handler.handled_message.status_text == "OK"
            assert aea_handler.handled_message.headers is not None
            assert aea_handler.handled_message.version is not None
        finally:
            aea.stop()
            t_aea.join()
Exemple #26
0
def run():
    # Create a private key
    create_private_key(CosmosCrypto.identifier)

    # Set up the wallet, identity and (empty) resources
    wallet = Wallet(
        private_key_paths={CosmosCrypto.identifier: COSMOS_PRIVATE_KEY_FILE},
        connection_private_key_paths={CosmosCrypto.identifier: COSMOS_PRIVATE_KEY_FILE},
    )
    identity = Identity("my_aea", address=wallet.addresses.get(CosmosCrypto.identifier))
    resources = Resources()

    # specify the default routing for some protocols
    default_routing = {
        PublicId.from_str("fetchai/ledger_api:0.1.0"): LedgerConnection.connection_id,
        PublicId.from_str("fetchai/oef_search:0.3.0"): SOEFConnection.connection_id,
    }
    default_connection = SOEFConnection.connection_id

    # create the AEA
    my_aea = AEA(
        identity,
        wallet,
        resources,
        default_connection=default_connection,
        default_routing=default_routing,
    )

    # Add the default protocol (which is part of the AEA distribution)
    default_protocol = Protocol.from_dir(os.path.join(AEA_DIR, "protocols", "default"))
    resources.add_protocol(default_protocol)

    # Add the signing protocol (which is part of the AEA distribution)
    signing_protocol = Protocol.from_dir(os.path.join(AEA_DIR, "protocols", "signing"))
    resources.add_protocol(signing_protocol)

    # Add the ledger_api protocol
    ledger_api_protocol = Protocol.from_dir(
        os.path.join(os.getcwd(), "packages", "fetchai", "protocols", "ledger_api",)
    )
    resources.add_protocol(ledger_api_protocol)

    # Add the oef_search protocol
    oef_protocol = Protocol.from_dir(
        os.path.join(os.getcwd(), "packages", "fetchai", "protocols", "oef_search",)
    )
    resources.add_protocol(oef_protocol)

    # Add the fipa protocol
    fipa_protocol = Protocol.from_dir(
        os.path.join(os.getcwd(), "packages", "fetchai", "protocols", "fipa",)
    )
    resources.add_protocol(fipa_protocol)

    # Add the LedgerAPI connection
    configuration = ConnectionConfig(connection_id=LedgerConnection.connection_id)
    ledger_api_connection = LedgerConnection(
        configuration=configuration, identity=identity
    )
    resources.add_connection(ledger_api_connection)

    # Add the P2P connection
    configuration = ConnectionConfig(
        connection_id=P2PLibp2pConnection.connection_id,
        delegate_uri="127.0.0.1:11001",
        entry_peers=[ENTRY_PEER_ADDRESS],
        local_uri="127.0.0.1:9001",
        log_file="libp2p_node.log",
        public_uri="127.0.0.1:9001",
    )
    p2p_connection = P2PLibp2pConnection(
        configuration=configuration,
        identity=identity,
        crypto_store=wallet.connection_cryptos,
    )
    resources.add_connection(p2p_connection)

    # Add the SOEF connection
    configuration = ConnectionConfig(
        api_key=API_KEY,
        soef_addr=SOEF_ADDR,
        soef_port=SOEF_PORT,
        restricted_to_protocols={PublicId.from_str("fetchai/oef_search:0.3.0")},
        connection_id=SOEFConnection.connection_id,
        delegate_uri="127.0.0.1:11001",
        entry_peers=[ENTRY_PEER_ADDRESS],
        local_uri="127.0.0.1:9001",
        log_file="libp2p_node.log",
        public_uri="127.0.0.1:9001",
    )
    soef_connection = SOEFConnection(configuration=configuration, identity=identity)
    resources.add_connection(soef_connection)

    # Add the error and weather_client skills
    error_skill = Skill.from_dir(
        os.path.join(AEA_DIR, "skills", "error"), agent_context=my_aea.context
    )
    weather_skill = Skill.from_dir(
        os.path.join(ROOT_DIR, "packages", "fetchai", "skills", "weather_client"),
        agent_context=my_aea.context,
    )

    strategy = cast(Strategy, weather_skill.models.get("strategy"))
    strategy._is_ledger_tx = False

    for skill in [error_skill, weather_skill]:
        resources.add_skill(skill)

    # Run the AEA
    try:
        logger.info("STARTING AEA NOW!")
        my_aea.start()
    except KeyboardInterrupt:
        logger.info("STOPPING AEA NOW!")
        my_aea.stop()
    async def test_end_to_end_aea_aca(self):
        # AEA components
        ledger_apis = LedgerApis({}, FetchAICrypto.identifier)
        wallet = Wallet({FetchAICrypto.identifier: FETCHAI_PRIVATE_KEY_FILE})
        identity = Identity(
            name="my_aea_1",
            address=wallet.addresses.get(FetchAICrypto.identifier),
            default_address_key=FetchAICrypto.identifier,
        )
        http_client_connection = HTTPClientConnection(
            address=self.aea_address,
            provider_address=self.aca_admin_address,
            provider_port=self.aca_admin_port,
        )
        resources = Resources()

        # create AEA
        aea = AEA(identity, [http_client_connection], wallet, ledger_apis,
                  resources)

        # Add http protocol to AEA resources
        http_protocol_configuration = ProtocolConfig.from_json(
            yaml.safe_load(
                open(
                    os.path.join(
                        self.cwd,
                        "packages",
                        "fetchai",
                        "protocols",
                        "http",
                        "protocol.yaml",
                    ))))
        http_protocol = Protocol(http_protocol_configuration, HttpSerializer())
        resources.add_protocol(http_protocol)

        # Request message & envelope
        request_http_message = HttpMessage(
            dialogue_reference=("", ""),
            target=0,
            message_id=1,
            performative=HttpMessage.Performative.REQUEST,
            method="GET",
            url="http://{}:{}/status".format(self.aca_admin_address,
                                             self.aca_admin_port),
            headers="",
            version="",
            bodyy=b"",
        )
        request_envelope = Envelope(
            to="ACA",
            sender="AEA",
            protocol_id=HTTP_PROTOCOL_PUBLIC_ID,
            message=HttpSerializer().encode(request_http_message),
        )

        # add a simple skill with handler
        skill_context = SkillContext(aea.context)
        skill_config = SkillConfig(name="simple_skill",
                                   author="fetchai",
                                   version="0.1.0")
        aea_handler = AEAHandler(skill_context=skill_context,
                                 name="aea_handler")
        simple_skill = Skill(skill_config,
                             skill_context,
                             handlers={aea_handler.name: aea_handler})
        resources.add_skill(simple_skill)

        # add error skill to AEA
        error_skill = Skill.from_dir(os.path.join(AEA_DIR, "skills", "error"))
        resources.add_skill(error_skill)

        # start AEA thread
        t_aea = Thread(target=aea.start)
        try:
            t_aea.start()
            time.sleep(1.0)
            aea.outbox.put(request_envelope)
            time.sleep(5.0)
            assert (aea_handler.handled_message.performative ==
                    HttpMessage.Performative.RESPONSE)
            assert aea_handler.handled_message.version == ""
            assert aea_handler.handled_message.status_code == 200
            assert aea_handler.handled_message.status_text == "OK"
            assert aea_handler.handled_message.headers is not None
            assert aea_handler.handled_message.version is not None
        finally:
            aea.stop()
            t_aea.join()
Exemple #28
0
 def test_protocol_load_positive(self):
     """Test protocol loaded correctly."""
     default_protocol = Protocol.from_dir(
         Path(AEA_DIR, "protocols", "default"))
     assert str(default_protocol.public_id) == str(
         DEFAULT_PROTOCOL), "Protocol not loaded correctly."
Exemple #29
0
def run():
    # Create a private key
    _create_fetchai_private_key()

    # Ensure the input and output files do not exist initially
    if os.path.isfile(INPUT_FILE):
        os.remove(INPUT_FILE)
    if os.path.isfile(OUTPUT_FILE):
        os.remove(OUTPUT_FILE)

    # Set up the Wallet, stub connection, ledger and (empty) resources
    wallet = Wallet({FETCHAI: FETCHAI_PRIVATE_KEY_FILE})
    stub_connection = StubConnection(
        input_file_path=INPUT_FILE, output_file_path=OUTPUT_FILE
    )
    ledger_apis = LedgerApis({"fetchai": {"network": "testnet"}}, "fetchai")
    resources = Resources()
    # Create an identity
    identity = Identity(
        name="my_aea",
        address=wallet.addresses.get(FETCHAI),
        default_address_key=FETCHAI,
    )

    # Create our AEA
    my_aea = AEA(identity, [stub_connection], wallet, ledger_apis, resources)

    # Add the default protocol (which is part of the AEA distribution)
    default_protocol = Protocol.from_dir(os.path.join(AEA_DIR, "protocols", "default"))
    resources.add_protocol(default_protocol)

    # Add the error skill (from the local packages dir) and the echo skill (which is part of the AEA distribution)
    echo_skill = Skill.from_dir(
        os.path.join(ROOT_DIR, "packages", "fetchai", "skills", "echo"), my_aea.context,
    )
    resources.add_skill(echo_skill)
    error_skill = Skill.from_dir(
        os.path.join(AEA_DIR, "skills", "error"), my_aea.context
    )
    resources.add_skill(error_skill)

    # Set the AEA running in a different thread
    try:
        t = Thread(target=my_aea.start)
        t.start()

        # Wait for everything to start up
        time.sleep(4)

        # Create a message inside an envelope and get the stub connection to pass it on to the echo skill
        message_text = (
            "my_aea,other_agent,fetchai/default:0.1.0,\x08\x01*\x07\n\x05hello"
        )
        with open(INPUT_FILE, "w") as f:
            f.write(message_text)
            print("input message: " + message_text)

        # Wait for the envelope to get processed
        time.sleep(4)

        # Read the output envelope generated by the echo skill
        with open(OUTPUT_FILE, "r") as f:
            print("output message: " + f.readline())
    finally:
        # Shut down the AEA
        my_aea.stop()
        t.join()
        t = None
Exemple #30
0
def run():
    # Create a private key
    _create_fetchai_private_key()

    # Set up the wallet, identity, oef connection, ledger and (empty) resources
    wallet = Wallet({FETCHAI: FETCHAI_PRIVATE_KEY_FILE})
    identity = Identity("my_aea", address=wallet.addresses.get(FETCHAI))
    oef_connection = OEFConnection(address=identity.address,
                                   oef_addr=HOST,
                                   oef_port=PORT)
    ledger_apis = LedgerApis({}, FETCHAI)
    resources = Resources()

    # create the AEA
    my_aea = AEA(
        identity,
        [oef_connection],
        wallet,
        ledger_apis,
        resources,  # stub_connection,
    )

    # Add the default protocol (which is part of the AEA distribution)
    default_protocol = Protocol.from_dir(
        os.path.join(AEA_DIR, "protocols", "default"))
    resources.add_protocol(default_protocol)

    # Add the oef protocol (which is a package)
    oef_protocol = Protocol.from_dir(
        os.path.join(
            os.getcwd(),
            "packages",
            "fetchai",
            "protocols",
            "oef_search",
        ))
    resources.add_protocol(oef_protocol)

    # Add the fipa protocol (which is a package)
    fipa_protocol = Protocol.from_dir(
        os.path.join(
            os.getcwd(),
            "packages",
            "fetchai",
            "protocols",
            "fipa",
        ))
    resources.add_protocol(fipa_protocol)

    # Add the error and weather_station skills
    error_skill = Skill.from_dir(os.path.join(AEA_DIR, "skills", "error"),
                                 my_aea.context)
    weather_skill = Skill.from_dir(
        os.path.join(ROOT_DIR, "packages", "fetchai", "skills",
                     "weather_client"),
        my_aea.context,
    )

    strategy = cast(Strategy, weather_skill.models.get("strategy"))
    strategy.is_ledger_tx = False
    strategy.max_buyer_tx_fee = 100
    strategy.max_row_price = 40

    for skill in [error_skill, weather_skill]:
        resources.add_skill(skill)

    # Set the AEA running in a different thread
    try:
        logger.info("STARTING AEA NOW!")
        t = Thread(target=my_aea.start)
        t.start()

        # Let it run long enough to interact with the weather station
        time.sleep(25)
    finally:
        # Shut down the AEA
        logger.info("STOPPING AEA NOW!")
        my_aea.stop()
        t.join()