Ejemplo n.º 1
0
def verify_or_create_private_keys(ctx: Context) -> None:
    """
    Verify or create private keys.

    :param ctx: Context
    """
    path = Path(DEFAULT_AEA_CONFIG_FILE)
    agent_loader = ConfigLoader("aea-config_schema.json", AgentConfig)
    fp = path.open(mode="r", encoding="utf-8")
    aea_conf = agent_loader.load(fp)

    for identifier, _value in aea_conf.private_key_paths.read_all():
        if identifier not in registry.supported_crypto_ids:
            ValueError("Unsupported identifier in private key paths.")

    for identifier, private_key_path in IDENTIFIER_TO_KEY_FILES.items():
        config_private_key_path = aea_conf.private_key_paths.read(identifier)
        if config_private_key_path is None:
            create_private_key(identifier)
            aea_conf.private_key_paths.update(identifier, private_key_path)
        else:
            try:
                _try_validate_private_key_path(identifier, private_key_path)
            except FileNotFoundError:  # pragma: no cover
                raise click.ClickException(
                    "File {} for private key {} not found.".format(
                        repr(private_key_path), identifier,
                    )
                )

    # update aea config
    path = Path(DEFAULT_AEA_CONFIG_FILE)
    fp = path.open(mode="w", encoding="utf-8")
    agent_loader.dump(aea_conf, fp)
    ctx.agent_config = aea_conf
Ejemplo n.º 2
0
 def setup_class(cls):
     """Set the test up."""
     cls.cwd = os.getcwd()
     cls.t = tempfile.mkdtemp()
     os.chdir(cls.t)
     cls.private_key_path_1 = os.path.join(cls.t, DEFAULT_PRIVATE_KEY_FILE + "_1")
     cls.private_key_path_2 = os.path.join(cls.t, DEFAULT_PRIVATE_KEY_FILE + "_2")
     create_private_key(DEFAULT_LEDGER, cls.private_key_path_1)
     create_private_key(DEFAULT_LEDGER, cls.private_key_path_2)
Ejemplo n.º 3
0
 def setup_class(cls):
     """Set the test up."""
     cls.cwd = os.getcwd()
     cls.t = tempfile.mkdtemp()
     shutil.copytree(Path(ROOT_DIR, "packages"), Path(cls.t, "packages"))
     os.chdir(cls.t)
     cls.private_key_path_1 = os.path.join(cls.t, DEFAULT_PRIVATE_KEY_FILE + "_1")
     cls.private_key_path_2 = os.path.join(cls.t, DEFAULT_PRIVATE_KEY_FILE + "_2")
     create_private_key(DEFAULT_LEDGER, cls.private_key_path_1)
     create_private_key(DEFAULT_LEDGER, cls.private_key_path_2)
Ejemplo n.º 4
0
 def setup_class(cls):
     """Set the test up."""
     cls.runner = CliRunner()
     cls.cwd = os.getcwd()
     cls.t = tempfile.mkdtemp()
     os.chdir(cls.t)
     cls.private_key_path_1 = os.path.join(cls.t,
                                           FetchAICrypto.identifier + "1")
     cls.private_key_path_2 = os.path.join(cls.t,
                                           FetchAICrypto.identifier + "2")
     create_private_key("fetchai", cls.private_key_path_1)
     create_private_key("fetchai", cls.private_key_path_2)
Ejemplo n.º 5
0
def _generate_private_key(type_: str) -> None:
    """
    Generate private key.

    :param type_: type.

    :return: None
    """
    types = list(IDENTIFIER_TO_KEY_FILES.keys()) if type_ == "all" else [type_]
    for type_ in types:
        private_key_file = IDENTIFIER_TO_KEY_FILES[type_]
        if _can_write(private_key_file):
            create_private_key(type_)
Ejemplo n.º 6
0
    def test_issue_certificates(self, *args):
        """Test agent alias issue certificates."""
        self.manager.start_manager()
        self.manager.add_project(self.project_public_id, local=True)

        cert_filename = "cert.txt"
        cert_path = os.path.join(self.manager.data_dir, self.agent_name,
                                 cert_filename)
        assert not os.path.exists(cert_filename)

        priv_key_path = os.path.abspath(
            os.path.join(self.working_dir, "priv_key.txt"))
        create_private_key("fetchai", priv_key_path)
        assert os.path.exists(priv_key_path)

        component_overrides = [{
            **StubConnection.connection_id.json,
            "type":
            "connection",
            "cert_requests": [{
                "identifier": "acn",
                "ledger_id": "fetchai",
                "not_after": "2022-01-01",
                "not_before": "2021-01-01",
                "public_key": "fetchai",
                "save_path": cert_filename,
            }],
        }]

        agent_overrides = {
            "private_key_paths": {
                "fetchai": priv_key_path
            },
            "connection_private_key_paths": {
                "fetchai": priv_key_path
            },
        }
        self.manager.add_agent(
            self.project_public_id,
            self.agent_name,
            agent_overrides=agent_overrides,
            component_overrides=component_overrides,
        )
        agent_alias = self.manager.get_agent_alias(self.agent_name)

        agent_alias.issue_certificates()

        assert os.path.exists(cert_path)
Ejemplo n.º 7
0
    def _create_private_key(self,
                            ledger: str,
                            replace: bool = False,
                            is_connection: bool = False) -> str:
        """
        Create new key for agent alias in working dir keys dir.

        If file exists, check `replace` option.
        """
        file_name = (f"{ledger}_connection_private.key"
                     if is_connection else f"{ledger}_private.key")
        filepath = os.path.join(self._data_dir, file_name)
        if os.path.exists(filepath) and not replace:
            return filepath
        create_private_key(ledger, filepath)
        return filepath
def run():
    # Create a private keys
    create_private_key(FetchAICrypto.identifier,
                       private_key_file=FETCHAI_PRIVATE_KEY_FILE_1)
    create_private_key(FetchAICrypto.identifier,
                       private_key_file=FETCHAI_PRIVATE_KEY_FILE_2)

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

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

    # Generate some wealth
    try_generate_testnet_wealth(FetchAICrypto.identifier,
                                wallet_1.addresses[FetchAICrypto.identifier])

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

    # Create the transaction and send it to the ledger.
    tx_nonce = ledger_apis.generate_tx_nonce(
        FetchAICrypto.identifier,
        wallet_2.addresses.get(FetchAICrypto.identifier),
        wallet_1.addresses.get(FetchAICrypto.identifier),
    )
    transaction = ledger_apis.get_transfer_transaction(
        identifier=FetchAICrypto.identifier,
        sender_address=wallet_1.addresses.get(FetchAICrypto.identifier),
        destination_address=wallet_2.addresses.get(FetchAICrypto.identifier),
        amount=1,
        tx_fee=1,
        tx_nonce=tx_nonce,
    )
    signed_transaction = wallet_1.sign_transaction(FetchAICrypto.identifier,
                                                   transaction)
    transaction_digest = ledger_apis.send_signed_transaction(
        FetchAICrypto.identifier, signed_transaction)

    logger.info("Transaction complete.")
    logger.info("The transaction digest is {}".format(transaction_digest))
Ejemplo n.º 9
0
def generate_key(click_context, type_):
    """Generate private keys."""
    def _can_write(path) -> bool:
        if Path(path).exists():
            value = click.confirm(
                "The file {} already exists. Do you want to overwrite it?".
                format(path),
                default=False,
            )
            return value
        else:
            return True

    types = list(IDENTIFIER_TO_KEY_FILES.keys()) if type_ == "all" else [type_]
    for type_ in types:
        private_key_file = IDENTIFIER_TO_KEY_FILES[type_]
        if _can_write(private_key_file):
            create_private_key(type_)
Ejemplo n.º 10
0
def _generate_private_key(type_: str, file: Optional[str] = None) -> None:
    """
    Generate private key.

    :param type_: type.
    :param file: path to file.

    :return: None
    """
    if type_ == "all" and file is not None:
        raise click.ClickException("Type all cannot be used in combination with file.")
    types = list(crypto_registry.supported_ids) if type_ == "all" else [type_]
    for type__ in types:
        private_key_file = (
            PRIVATE_KEY_PATH_SCHEMA.format(type__) if file is None else file
        )
        if _can_write(private_key_file):
            create_private_key(type__, private_key_file)
Ejemplo n.º 11
0
def run():
    # Create a private keys
    create_private_key(
        CosmosCrypto.identifier, private_key_file=COSMOS_PRIVATE_KEY_FILE_1
    )
    create_private_key(
        CosmosCrypto.identifier, private_key_file=COSMOS_PRIVATE_KEY_FILE_2
    )

    # Set up the wallets
    wallet_1 = Wallet({CosmosCrypto.identifier: COSMOS_PRIVATE_KEY_FILE_1})
    wallet_2 = Wallet({CosmosCrypto.identifier: COSMOS_PRIVATE_KEY_FILE_2})

    # Generate some wealth
    try_generate_testnet_wealth(
        CosmosCrypto.identifier, wallet_1.addresses[CosmosCrypto.identifier]
    )

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

    # Create the transaction and send it to the ledger.
    tx_nonce = LedgerApis.generate_tx_nonce(
        CosmosCrypto.identifier,
        wallet_2.addresses.get(CosmosCrypto.identifier),
        wallet_1.addresses.get(CosmosCrypto.identifier),
    )
    transaction = LedgerApis.get_transfer_transaction(
        identifier=CosmosCrypto.identifier,
        sender_address=wallet_1.addresses.get(CosmosCrypto.identifier),
        destination_address=wallet_2.addresses.get(CosmosCrypto.identifier),
        amount=1,
        tx_fee=1,
        tx_nonce=tx_nonce,
    )
    signed_transaction = wallet_1.sign_transaction(CosmosCrypto.identifier, transaction)
    transaction_digest = LedgerApis.send_signed_transaction(
        CosmosCrypto.identifier, signed_transaction
    )

    logger.info("Transaction complete.")
    logger.info("The transaction digest is {}".format(transaction_digest))
Ejemplo n.º 12
0
def _generate_private_key(type_: str, file: Optional[str] = None) -> None:
    """
    Generate private key.

    :param type_: type.
    :param file: path to file.

    :return: None
    """
    if type_ == "all" and file is not None:
        raise click.ClickException(
            "Type all cannot be used in combination with file.")
    elif type_ == "all":
        types = list(IDENTIFIER_TO_KEY_FILES.keys())
    else:
        types = [type_]
    for type_ in types:
        private_key_file = IDENTIFIER_TO_KEY_FILES[
            type_] if file is None else file
        if _can_write(private_key_file):
            create_private_key(type_, private_key_file)
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()
Ejemplo 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()
Ejemplo n.º 15
0
def run():
    # Create a private key
    create_private_key(CosmosCrypto.identifier)

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

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

    # Add the echo skill (assuming it is present in the local directory 'packages')
    builder.add_skill("./packages/fetchai/skills/echo")

    # create skill and handler manually
    from aea.protocols.base import Message
    from aea.protocols.default.message import DefaultMessage
    from aea.skills.base import Handler

    class DummyHandler(Handler):
        """Dummy handler to handle messages."""

        SUPPORTED_PROTOCOL = DefaultMessage.protocol_id

        def setup(self) -> None:
            """Noop setup."""

        def teardown(self) -> None:
            """Noop teardown."""

        def handle(self, message: Message) -> None:
            """Handle incoming message."""
            self.context.logger.info("You got a message: {}".format(
                str(message)))

    config = SkillConfig(name="test_skill", author="fetchai")
    skill = Skill(configuration=config)
    dummy_handler = DummyHandler(name="dummy_handler",
                                 skill_context=skill.skill_context)
    skill.handlers.update({dummy_handler.name: dummy_handler})
    builder.add_component_instance(skill)

    # Create our AEA
    my_aea = builder.build()

    # 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.3.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
Ejemplo n.º 16
0
 def test__create_cosmos_private_key_positive(self, *mocks):
     """Test _create_cosmos_private_key positive result."""
     create_private_key(CosmosCrypto.identifier)
Ejemplo n.º 17
0
 def test__create_ethereum_private_key_positive(self, *mocks):
     """Test _create_ethereum_private_key positive result."""
     create_private_key(EthereumCrypto.identifier)
Ejemplo n.º 18
0
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()
Ejemplo n.º 19
0
 def test__create_ethereum_private_key_positive(self, *mocks):
     """Test _create_ethereum_private_key positive result."""
     create_private_key(EthereumCrypto.identifier,
                        ETHEREUM_PRIVATE_KEY_FILE)
Ejemplo n.º 20
0
 def test__create_cosmos_private_key_positive(self, *mocks):
     """Test _create_cosmos_private_key positive result."""
     create_private_key(CosmosCrypto.identifier, COSMOS_PRIVATE_KEY_FILE)
Ejemplo n.º 21
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()
Ejemplo n.º 22
0
 def _create_private_key(self, name, ledger) -> str:
     """Create new key for agent alias in working dir keys dir."""
     path = os.path.join(self._keys_dir, f"{name}_{ledger}_private.key")
     create_private_key(ledger, path)
     return path
Ejemplo n.º 23
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()