def setup_class(cls): """Set the test up.""" agent_name = "my_agent" 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(identity.address, LocalNode()) resources = Resources() cls.context_namespace = {"key1": 1, "key2": 2} cls.agent = AEA(identity, wallet, resources, **cls.context_namespace) resources.add_connection(connection) resources.add_component( Skill.from_dir(Path(CUR_PATH, "data", "dummy_skill"), agent_context=cls.agent.context)) for skill in resources.get_all_skills(): skill.skill_context.set_agent_context(cls.agent.context)
def setup_class(cls): """Test the initialisation of the AEA.""" eth_private_key_path = os.path.join(CUR_PATH, "data", "eth_private_key.txt") fet_private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") cls.wallet = Wallet( { EthereumCrypto.identifier: eth_private_key_path, FetchAICrypto.identifier: fet_private_key_path, } ) cls.connection = _make_dummy_connection() cls.identity = Identity( "name", addresses=cls.wallet.addresses, default_address_key=FetchAICrypto.identifier, ) cls.my_aea = AEA(cls.identity, cls.wallet, resources=Resources(),) cls.my_aea.resources.add_connection(cls.connection) cls.skill_context = SkillContext(cls.my_aea.context)
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" / DEFAULT_SKILL.name), agent_context=agent_context, )) resources.add_protocol( Protocol.from_dir( str(PACKAGES_DIR / "fetchai" / "protocols" / DEFAULT_PROTOCOL.name))) return AEA(identity, wallet, resources, runtime_mode=runtime_mode)
def _try_generate_wealth(click_context, type_, sync): ctx = cast(Context, click_context.obj) verify_or_create_private_keys(ctx) private_key_paths = { config_pair[0]: config_pair[1] for config_pair in ctx.agent_config.private_key_paths.read_all() } wallet = Wallet(private_key_paths) try: address = wallet.addresses[type_] testnet = TESTNETS[type_] click.echo( "Requesting funds for address {} on test network '{}'".format( address, testnet)) try_generate_testnet_wealth(type_, address) if sync: _wait_funds_release(ctx.agent_config, wallet, type_) except (AssertionError, ValueError) as e: # pragma: no cover raise click.ClickException(str(e))
def _try_generate_wealth(ctx, type_, sync): private_key_paths = { config_pair[0]: config_pair[1] for config_pair in ctx.agent_config.private_key_paths.read_all() } wallet = Wallet(private_key_paths) try: address = wallet.addresses[type_] testnet = TESTNETS[type_] click.echo( "Requesting funds for address {} on test network '{}'".format( address, testnet ) ) _try_generate_testnet_wealth(type_, address) if sync: _wait_funds_release(ctx.agent_config, wallet, type_) except (AssertionError, ValueError) as e: # pragma: no cover logger.error(str(e)) sys.exit(1)
def setup_class(cls): """Initialise the decision maker.""" cls._patch_logger() cls.multiplexer = Multiplexer([_make_dummy_connection()]) private_key_pem_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") eth_private_key_pem_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") cls.wallet = Wallet({ FetchAICrypto.identifier: private_key_pem_path, EthereumCrypto.identifier: eth_private_key_pem_path, }) cls.ledger_apis = LedgerApis( {FetchAICrypto.identifier: DEFAULT_FETCHAI_CONFIG}, FetchAICrypto.identifier) cls.agent_name = "test" cls.identity = Identity( cls.agent_name, addresses=cls.wallet.addresses, default_address_key=FetchAICrypto.identifier, ) cls.ownership_state = OwnershipState() cls.preferences = Preferences() cls.decision_maker_handler = DecisionMakerHandler( identity=cls.identity, wallet=cls.wallet, ledger_apis=cls.ledger_apis, ) cls.decision_maker = DecisionMaker(cls.decision_maker_handler) cls.multiplexer.connect() cls.tx_id = "transaction0" cls.tx_sender_addr = "agent_1" cls.tx_counterparty_addr = "pk" cls.info = {"some_info_key": "some_info_value"} cls.ledger_id = "fetchai" cls.decision_maker.start()
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", "fet_private_key.txt") wallet = Wallet({FETCHAI: private_key_path}) resources = Resources() identity = Identity(agent_name, address=wallet.addresses[FETCHAI]) 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._main_loop and agent._main_loop.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)
def test_react(): """Tests income messages.""" with LocalNode() as node: agent_name = "MyAgent" private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") wallet = Wallet({'default': private_key_pem_path}) ledger_apis = LedgerApis({}) public_key = wallet.public_keys['default'] connection = OEFLocalConnection(public_key, node) connections = [connection] msg = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello") message_bytes = DefaultSerializer().encode(msg) envelope = Envelope( to=public_key, sender=public_key, protocol_id="default", message=message_bytes) agent = AEA( agent_name, connections, wallet, ledger_apis, resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea")))) t = Thread(target=agent.start) try: t.start() time.sleep(0.1) agent.outbox.put(envelope) time.sleep(0.5) handler = agent.resources.handler_registry.fetch_by_skill('default', "dummy") assert msg in handler.handled_messages, "The message is not inside the handled_messages." except Exception: raise finally: agent.stop() t.join()
def _try_get_address(click_context, type_): """ Try to get address. :param click_context: click context object. :param type_: type. :return: address. """ ctx = cast(Context, click_context.obj) verify_or_create_private_keys(ctx) private_key_paths = { config_pair[0]: config_pair[1] for config_pair in ctx.agent_config.private_key_paths.read_all() } try: wallet = Wallet(private_key_paths) address = wallet.addresses[type_] return address except ValueError as e: # pragma: no cover raise click.ClickException(str(e))
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.resources = Resources(os.path.join(CUR_PATH, "data", "dummy_aea")) cls.aea = AEA(cls.agent_name, cls.connections, cls.wallet, cls.ledger_apis, cls.resources) cls.expected_message = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello") envelope = Envelope(to=cls.agent_name, sender=cls.agent_name, protocol_id="default", message=DefaultSerializer().encode(cls.expected_message)) cls.t = Thread(target=cls.aea.start) cls.t.start() time.sleep(0.5) cls.aea.outbox.put(envelope) time.sleep(0.5)
def setup_class(cls): """Set the test up.""" agent_name = "MyAgent" private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") wallet = Wallet({FETCHAI: private_key_path}) ledger_apis = LedgerApis({}, FETCHAI) resources = Resources(str(Path(CUR_PATH, "data", "dummy_aea"))) identity = Identity(agent_name, address=wallet.addresses[FETCHAI]) cls.input_file = tempfile.mkstemp()[1] cls.output_file = tempfile.mkstemp()[1] cls.agent = AEA( identity, [StubConnection(cls.input_file, cls.output_file)], wallet, ledger_apis, resources, is_programmatic=False, ) cls.t = Thread(target=cls.agent.start) cls.t.start() time.sleep(1.0)
async def test_cannot_connect_to_oef(): """Test the case when we can't connect to the OEF.""" private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") wallet = Wallet({'default': private_key_pem_path}) oef_connection = OEFConnection(public_key=wallet.public_keys['default'], oef_addr="a_fake_address", oef_port=10000) oef_connection.loop = asyncio.get_event_loop() patch = unittest.mock.patch.object(aea.connections.oef.connection.logger, 'warning') mocked_logger_warning = patch.__enter__() async def try_to_connect(): await oef_connection.connect() task = asyncio.ensure_future(try_to_connect(), loop=asyncio.get_event_loop()) await asyncio.sleep(1.0) mocked_logger_warning.assert_called_with( "Cannot connect to OEFChannel. Retrying in 5 seconds...") task.cancel() await asyncio.sleep(1.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 = DUMMY_SKILL_PUBLIC_ID 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)
async def test_cancelled_receive(network_node): """Test the case when a receive request is cancelled.""" private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") wallet = Wallet({'default': private_key_pem_path}) oef_connection = OEFConnection(public_key=wallet.public_keys['default'], oef_addr="127.0.0.1", oef_port=10000) oef_connection.loop = asyncio.get_event_loop() await oef_connection.connect() patch = unittest.mock.patch.object(aea.connections.oef.connection.logger, 'debug') mocked_logger_debug = patch.__enter__() async def receive(): await oef_connection.receive() task = asyncio.ensure_future(receive(), loop=asyncio.get_event_loop()) await asyncio.sleep(0.1) task.cancel() await asyncio.sleep(0.1) await oef_connection.disconnect() mocked_logger_debug.assert_called_once_with("Receive cancelled.")
def setup_class(cls): """Test the initialisation of the AEA.""" cls.node = LocalNode() private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") cls.wallet = Wallet({'default': private_key_pem_path}) cls.ledger_apis = LedgerApis({}) cls.agent_name = "Agent0" cls.public_key = cls.wallet.public_keys['default'] cls.connection = DummyConnection() cls.connections = [cls.connection] cls.my_aea = AEA(cls.agent_name, cls.connections, cls.wallet, cls.ledger_apis, timeout=2.0, resources=Resources( str(Path(CUR_PATH, "data/dummy_aea")))) cls.t = Thread(target=cls.my_aea.start) cls.t.start() time.sleep(0.5) cls.skill_context = SkillContext(cls.my_aea._context) cls.my_error_handler = ErrorHandler(skill_context=cls.skill_context)
def setup(cls): """Initialise the decision maker.""" cls._patch_logger() cls.wallet = Wallet({ COSMOS: COSMOS_PRIVATE_KEY_PATH, ETHEREUM: ETHEREUM_PRIVATE_KEY_PATH, FETCHAI: FETCHAI_PRIVATE_KEY_PATH, }) cls.agent_name = "test" cls.identity = Identity( cls.agent_name, addresses=cls.wallet.addresses, default_address_key=FETCHAI, ) cls.decision_maker_handler = DecisionMakerHandler( identity=cls.identity, wallet=cls.wallet) cls.decision_maker = DecisionMaker(cls.decision_maker_handler) cls.tx_sender_addr = "agent_1" cls.tx_counterparty_addr = "pk" cls.info = {"some_info_key": "some_info_value"} cls.ledger_id = FETCHAI cls.decision_maker.start()
def setup_class(cls, decision_maker_handler_class=None): """Test the initialisation of the AEA.""" cls.wallet = Wallet({ FETCHAI: FETCHAI_PRIVATE_KEY_PATH, ETHEREUM: ETHEREUM_PRIVATE_KEY_PATH }) cls.connection = _make_dummy_connection() resources = Resources() resources.add_connection(cls.connection) cls.identity = Identity( "name", addresses=cls.wallet.addresses, default_address_key=FETCHAI, ) cls.my_aea = AEA( cls.identity, cls.wallet, data_dir=MagicMock(), resources=resources, decision_maker_handler_class=decision_maker_handler_class, ) cls.skill_context = SkillContext(cls.my_aea.context, skill=MagicMock(contracts={}))
def test_wallet_init_bad_id(self): """Test Wallet init unsupported private key paths identifier.""" private_key_paths = {"unknown_id": "path1"} with self.assertRaises(AEAException): Wallet(private_key_paths)
def test_wallet_initialisation_error(): """Test the value error when we initialise the wallet.""" with pytest.raises(AEAException): Wallet({"Test": "test"})
async def test_handle(): """Tests handle method of an agent.""" with LocalNode() as node: agent_name = "MyAgent" private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") wallet = Wallet({FETCHAI: private_key_path}) ledger_apis = LedgerApis({}, FETCHAI) identity = Identity(agent_name, address=wallet.addresses[FETCHAI]) connection = OEFLocalConnection(identity.address, node, connection_id=DUMMY_SKILL_PUBLIC_ID) connections = [connection] resources = Resources(str(Path(CUR_PATH, "data", "dummy_aea"))) msg = DefaultMessage( dialogue_reference=("", ""), message_id=1, target=0, performative=DefaultMessage.Performative.BYTES, content=b"hello", ) msg.counterparty = agent_name message_bytes = DefaultSerializer().encode(msg) envelope = Envelope( to=identity.address, sender=identity.address, protocol_id=UNKNOWN_PROTOCOL_PUBLIC_ID, message=message_bytes, ) agent = AEA(identity, connections, wallet, ledger_apis, resources, is_programmatic=False) t = Thread(target=agent.start) try: t.start() time.sleep(2.0) dummy_skill = agent.resources.get_skill(DUMMY_SKILL_PUBLIC_ID) dummy_handler = dummy_skill.handlers["dummy"] expected_envelope = envelope agent.outbox.put(expected_envelope) time.sleep(2.0) assert len(dummy_handler.handled_messages) == 1 # DECODING ERROR msg = "hello".encode("utf-8") envelope = Envelope( to=identity.address, sender=identity.address, protocol_id=DefaultMessage.protocol_id, message=msg, ) expected_envelope = envelope agent.outbox.put(expected_envelope) time.sleep(2.0) assert len(dummy_handler.handled_messages) == 2 # UNSUPPORTED SKILL msg = FIPASerializer().encode( FIPAMessage( performative=FIPAMessage.Performative.ACCEPT, message_id=0, dialogue_reference=(str(0), ""), target=1, )) envelope = Envelope( to=identity.address, sender=identity.address, protocol_id=FIPAMessage.protocol_id, message=msg, ) expected_envelope = envelope agent.outbox.put(expected_envelope) time.sleep(2.0) assert len(dummy_handler.handled_messages) == 3 finally: agent.stop() t.join()
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()
def run(): # Create a private key create_private_key(FetchAICrypto.identifier, private_key_file=FETCHAI_PRIVATE_KEY_FILE_1) # Instantiate the builder and build the AEA # By default, the default protocol, error skill and stub connection are added builder = AEABuilder() builder.set_name("my_aea") builder.add_private_key(FetchAICrypto.identifier, FETCHAI_PRIVATE_KEY_FILE_1) builder.add_ledger_api_config(FetchAICrypto.identifier, {"network": "testnet"}) # Create our AEA my_aea = builder.build() # Generate some wealth for the default address try_generate_testnet_wealth(FetchAICrypto.identifier, my_aea.identity.address) # add a simple skill with handler skill_context = SkillContext(my_aea.context) skill_config = SkillConfig(name="simple_skill", author="fetchai", version="0.1.0") tx_handler = TransactionHandler(skill_context=skill_context, name="transaction_handler") simple_skill = Skill(skill_config, skill_context, handlers={tx_handler.name: tx_handler}) my_aea.resources.add_skill(simple_skill) # create a second identity create_private_key(FetchAICrypto.identifier, private_key_file=FETCHAI_PRIVATE_KEY_FILE_2) counterparty_wallet = Wallet( {FetchAICrypto.identifier: FETCHAI_PRIVATE_KEY_FILE_2}) counterparty_identity = Identity( name="counterparty_aea", addresses=counterparty_wallet.addresses, default_address_key=FetchAICrypto.identifier, ) # create tx message for decision maker to process fetchai_ledger_api = my_aea.context.ledger_apis.apis[ FetchAICrypto.identifier] tx_nonce = fetchai_ledger_api.generate_tx_nonce( my_aea.identity.address, counterparty_identity.address) tx_msg = TransactionMessage( performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT, skill_callback_ids=[skill_config.public_id], tx_id="transaction0", tx_sender_addr=my_aea.identity.address, tx_counterparty_addr=counterparty_identity.address, tx_amount_by_currency_id={"FET": -1}, tx_sender_fee=1, tx_counterparty_fee=0, tx_quantities_by_good_id={}, ledger_id=FetchAICrypto.identifier, info={"some_info_key": "some_info_value"}, tx_nonce=tx_nonce, ) my_aea.context.decision_maker_message_queue.put_nowait(tx_msg) # 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(20) finally: # Shut down the AEA logger.info("STOPPING AEA NOW!") my_aea.stop() t.join()
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()
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 = OEFLocalConnection( cls.agent_name, cls.node, connection_id=LOCAL_CONNECTION_PUBLIC_ID) cls.connections = [cls.connection] cls.temp = tempfile.mkdtemp(prefix="test_aea_resources") cls.resources = Resources(cls.temp) cls.aea = AEA( cls.identity, cls.connections, cls.wallet, cls.ledger_apis, resources=cls.resources, ) default_protocol_id = DefaultMessage.protocol_id cls.default_protocol_configuration = ProtocolConfig.from_json( yaml.safe_load( open(Path(AEA_DIR, "protocols", "default", "protocol.yaml")))) cls.default_protocol = Protocol(default_protocol_id, DefaultSerializer(), cls.default_protocol_configuration) cls.resources.protocol_registry.register(default_protocol_id, 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( 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), ))
def run(): # Create a private keys _create_fetchai_private_key(private_key_file=FETCHAI_PRIVATE_KEY_FILE_1) _create_fetchai_private_key(private_key_file=FETCHAI_PRIVATE_KEY_FILE_2) # Set up the wallets wallet_1 = Wallet({FETCHAI: FETCHAI_PRIVATE_KEY_FILE_1}) wallet_2 = Wallet({FETCHAI: FETCHAI_PRIVATE_KEY_FILE_2}) # Generate some wealth _try_generate_testnet_wealth(FETCHAI, wallet_1.addresses[FETCHAI]) # Set up the LedgerApis ledger_apis = LedgerApis({FETCHAI: {"network": "testnet"}}, FETCHAI) tx_handler = TransactionHandler(skill_context="skill_context", name="fake_skill") resources = Resources() resources.handler_registry.register( ( PublicId.from_str("fetchai/fake_skill:0.1.0"), PublicId.from_str("fetchai/internal:0.1.0"), ), tx_handler, ) stub_connection = StubConnection(input_file_path=INPUT_FILE, output_file_path=OUTPUT_FILE) identity_1 = Identity( name="my_aea", address=wallet_1.addresses.get(FETCHAI), default_address_key=FETCHAI, ) identity_2 = Identity( name="my_aea_2", address=wallet_2.addresses.get(FETCHAI), default_address_key=FETCHAI, ) # create the AEA my_aea = AEA(identity_1, [stub_connection], wallet_1, ledger_apis, resources) ledger_api = ledger_apis.apis[FETCHAI] tx_nonce = ledger_api.generate_tx_nonce(identity_1.addresses.get(FETCHAI), identity_2.addresses.get(FETCHAI)) tx_msg = TransactionMessage( performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT, skill_callback_ids=[PublicId("fetchai", "fake_skill", "0.1.0")], tx_id="transaction0", tx_sender_addr=identity_1.addresses.get(FETCHAI), tx_counterparty_addr=identity_2.addresses.get(FETCHAI), tx_amount_by_currency_id={"FET": -1}, tx_sender_fee=1, tx_counterparty_fee=0, tx_quantities_by_good_id={}, ledger_id=FETCHAI, info={"some_info_key": "some_info_value"}, tx_nonce=tx_nonce, ) my_aea.context.decision_maker_message_queue.put_nowait(tx_msg) # 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(20) finally: # Shut down the AEA logger.info("STOPPING AEA NOW!") my_aea.stop() t.join()
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()
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()
def test_wallet_init_bad_paths(self): """Test Wallet init with bad paths to private keys""" private_key_paths = {FetchAICrypto.identifier: "this_path_does_not_exists"} with self.assertRaises(FileNotFoundError): Wallet(private_key_paths)
def run(): # Create a private key create_private_key(CosmosCrypto.identifier, private_key_file=COSMOS_PRIVATE_KEY_FILE_1) # Instantiate the builder and build the AEA # By default, the default protocol, error skill and stub connection are added builder = AEABuilder() builder.set_name("my_aea") builder.add_private_key(CosmosCrypto.identifier, COSMOS_PRIVATE_KEY_FILE_1) # Create our AEA my_aea = builder.build() # add a simple skill with handler skill_context = SkillContext(my_aea.context) skill_config = SkillConfig(name="simple_skill", author="fetchai", version="0.1.0") signing_handler = SigningHandler(skill_context=skill_context, name="signing_handler") signing_dialogues_model = SigningDialogues(skill_context=skill_context, name="signing_dialogues") simple_skill = Skill( skill_config, skill_context, handlers={signing_handler.name: signing_handler}, models={signing_dialogues_model.name: signing_dialogues_model}, ) my_aea.resources.add_skill(simple_skill) # create a second identity create_private_key(CosmosCrypto.identifier, private_key_file=COSMOS_PRIVATE_KEY_FILE_2) counterparty_wallet = Wallet( {CosmosCrypto.identifier: COSMOS_PRIVATE_KEY_FILE_2}) counterparty_identity = Identity( name="counterparty_aea", addresses=counterparty_wallet.addresses, default_address_key=CosmosCrypto.identifier, ) # create signing message for decision maker to sign terms = Terms( ledger_id=CosmosCrypto.identifier, sender_address=my_aea.identity.address, counterparty_address=counterparty_identity.address, amount_by_currency_id={"FET": -1}, quantities_by_good_id={"some_service": 1}, nonce="some_nonce", fee_by_currency_id={"FET": 0}, ) signing_dialogues = cast(SigningDialogues, skill_context.signing_dialogues) stub_transaction = LedgerApis.get_transfer_transaction( terms.ledger_id, terms.sender_address, terms.counterparty_address, terms.sender_payable_amount, terms.sender_fee, terms.nonce, ) signing_msg = SigningMessage( performative=SigningMessage.Performative.SIGN_TRANSACTION, dialogue_reference=signing_dialogues. new_self_initiated_dialogue_reference(), skill_callback_ids=(str(skill_context.skill_id), ), raw_transaction=RawTransaction(CosmosCrypto.identifier, stub_transaction), terms=terms, skill_callback_info={"some_info_key": "some_info_value"}, ) signing_msg.counterparty = "decision_maker" signing_dialogue = cast(Optional[SigningDialogue], signing_dialogues.update(signing_msg)) assert signing_dialogue is not None my_aea.context.decision_maker_message_queue.put_nowait(signing_msg) # 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 decision maker time.sleep(1) finally: # Shut down the AEA logger.info("STOPPING AEA NOW!") my_aea.stop() t.join()
async def test_handle(): """Tests handle method of an agent.""" with LocalNode() as node: agent_name = "MyAgent" private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem") wallet = Wallet({'default': private_key_pem_path}) ledger_apis = LedgerApis({}) public_key = wallet.public_keys['default'] connection = OEFLocalConnection(public_key, node) connections = [connection] msg = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello") message_bytes = DefaultSerializer().encode(msg) envelope = Envelope( to=public_key, sender=public_key, protocol_id="unknown_protocol", message=message_bytes) agent = AEA( agent_name, connections, wallet, ledger_apis, resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea")))) t = Thread(target=agent.start) try: t.start() time.sleep(1.0) dummy_skill = agent.resources.get_skill("dummy") dummy_handler = dummy_skill.handlers[0] expected_envelope = envelope agent.outbox.put(expected_envelope) time.sleep(1.0) assert len(dummy_handler.handled_messages) == 1 # DECODING ERROR msg = "hello".encode("utf-8") envelope = Envelope( to=public_key, sender=public_key, protocol_id='default', message=msg) expected_envelope = envelope agent.outbox.put(expected_envelope) time.sleep(1.0) assert len(dummy_handler.handled_messages) == 2 # UNSUPPORTED SKILL msg = FIPASerializer().encode( FIPAMessage(performative=FIPAMessage.Performative.ACCEPT, message_id=0, dialogue_reference=(str(0), ''), target=1)) envelope = Envelope( to=public_key, sender=public_key, protocol_id="fipa", message=msg) expected_envelope = envelope agent.outbox.put(expected_envelope) time.sleep(1.0) assert len(dummy_handler.handled_messages) == 3 finally: agent.stop() t.join()