Esempio n. 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"),
        }
Esempio n. 2
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
Esempio n. 3
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
Esempio n. 4
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")
Esempio n. 5
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)
Esempio n. 6
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),
            ))
Esempio n. 7
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."
Esempio n. 8
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!"
 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!"
Esempio n. 10
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
Esempio n. 11
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
Esempio n. 12
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(),
    )
Esempio n. 13
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(),
    )
Esempio n. 14
0
def run():
    """Run demo."""

    # Create a private key
    create_private_key(FetchAICrypto.identifier, FETCHAI_PRIVATE_KEY_FILE)
    create_private_key(FetchAICrypto.identifier, FETCHAI_PRIVATE_KEY_FILE_CONNECTION)

    # Set up the wallet, identity and (empty) resources
    wallet = Wallet(
        private_key_paths={FetchAICrypto.identifier: FETCHAI_PRIVATE_KEY_FILE},
        connection_private_key_paths={
            FetchAICrypto.identifier: FETCHAI_PRIVATE_KEY_FILE_CONNECTION
        },
    )
    identity = Identity(
        "my_aea", address=wallet.addresses.get(FetchAICrypto.identifier)
    )
    resources = Resources()
    data_dir = os.getcwd()

    # specify the default routing for some protocols
    default_routing = {
        LedgerApiMessage.protocol_id: LedgerConnection.connection_id,
        OefSearchMessage.protocol_id: SOEFConnection.connection_id,
    }
    default_connection = P2PLibp2pConnection.connection_id

    state_update_protocol = Protocol.from_dir(
        os.path.join(os.getcwd(), "packages", "fetchai", "protocols", "state_update")
    )
    resources.add_protocol(state_update_protocol)

    # Add the default protocol (which is part of the AEA distribution)
    default_protocol = Protocol.from_dir(
        os.path.join(os.getcwd(), "packages", "fetchai", "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(os.getcwd(), "packages", "fetchai", "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, data_dir=data_dir, identity=identity
    )
    resources.add_connection(ledger_api_connection)

    # Add the P2P connection
    cert_path = ".certs/conn_cert.txt"
    cert_request = CertRequest(
        identifier="acn",
        ledger_id=FetchAICrypto.identifier,
        not_after="2022-01-01",
        not_before="2021-01-01",
        public_key="fetchai",
        save_path=cert_path,
    )
    public_key = wallet.connection_cryptos.public_keys.get(FetchAICrypto.identifier)
    message = cert_request.get_message(public_key)
    make_certificate(
        FetchAICrypto.identifier, FETCHAI_PRIVATE_KEY_FILE, message, cert_path
    )
    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",
        build_directory=os.getcwd(),
        build_entrypoint="check_dependencies.py",
        cert_requests=[cert_request],
    )
    configuration.directory = os.path.dirname(
        packages.fetchai.connections.p2p_libp2p.connection.__file__
    )

    AEABuilder.run_build_for_component_configuration(configuration)

    p2p_connection = P2PLibp2pConnection(
        configuration=configuration,
        data_dir=data_dir,
        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={OefSearchMessage.protocol_id},
        connection_id=SOEFConnection.connection_id,
    )
    soef_connection = SOEFConnection(
        configuration=configuration, data_dir=data_dir, identity=identity
    )
    resources.add_connection(soef_connection)

    # create the AEA
    my_aea = AEA(
        identity,
        wallet,
        resources,
        data_dir,
        default_connection=default_connection,
        default_routing=default_routing,
    )
    # Add the error and weather_client skills
    error_skill = Skill.from_dir(
        os.path.join(ROOT_DIR, "packages", "fetchai", "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()
Esempio n. 15
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()
Esempio n. 16
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."
Esempio n. 17
0
def run():
    # Create a private key
    create_private_key(FetchAICrypto.identifier)

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

    # specify the default routing for some protocols
    default_routing = {
        PublicId.from_str("fetchai/ledger_api:0.1.0"):
        LedgerConnection.connection_id
    }
    default_connection = OEFConnection.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 OEF connection
    configuration = ConnectionConfig(addr=HOST,
                                     port=PORT,
                                     connection_id=OEFConnection.connection_id)
    oef_connection = OEFConnection(configuration=configuration,
                                   identity=identity)
    resources.add_connection(oef_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()
Esempio n. 18
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()
Esempio n. 19
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
Esempio n. 20
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()