Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(core): context stage 1 #349

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 20 additions & 19 deletions python/src/uagents/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
parse_endpoint_config,
)
from uagents.context import (
AgentRepresentation,
Context,
EventCallback,
IntervalCallback,
Expand Down Expand Up @@ -256,15 +257,15 @@ def __init__(
self.protocols: Dict[str, Protocol] = {}

self._ctx = Context(
self._identity.address,
self.identifier,
self._name,
self._storage,
self._resolver,
self._identity,
self._wallet,
self._ledger,
self._queries,
agent=AgentRepresentation(
address=self.address,
name=self._name,
signing_callback=self._identity.sign_digest,
),
storage=self._storage,
resolve=self._resolver,
ledger=self._ledger,
queries=self._queries,
replies=self._replies,
interval_messages=self._interval_messages,
wallet_messaging_client=self._wallet_messaging_client,
Expand Down Expand Up @@ -928,18 +929,18 @@ async def _process_message_queue(self):
continue

context = Context(
self._identity.address,
self.identifier,
self._name,
self._storage,
self._resolver,
self._identity,
self._wallet,
self._ledger,
self._queries,
agent=AgentRepresentation(
address=self._identity.address,
name=self._name,
signing_callback=self._identity.sign_digest,
),
storage=self._storage,
resolve=self._resolver,
ledger=self._ledger,
queries=self._queries,
session=session,
replies=self._replies,
interval_messages=self._interval_messages,
interval_messages=None,
message_received=MsgDigest(
message=message, schema_digest=schema_digest
),
Expand Down
184 changes: 114 additions & 70 deletions python/src/uagents/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@
import aiohttp
import requests
from cosmpy.aerial.client import LedgerClient
from cosmpy.aerial.wallet import LocalWallet
from pydantic import ValidationError
from typing_extensions import deprecated
from uagents.config import (
ALMANAC_API_URL,
DEFAULT_ENVELOPE_TIMEOUT_SECONDS,
DEFAULT_SEARCH_LIMIT,
TESTNET_PREFIX,
)
from uagents.crypto import Identity
from uagents.dispatch import JsonStr, dispatcher
Expand Down Expand Up @@ -89,6 +89,87 @@ class MsgStatus:
endpoint: str


class AgentRepresentation:
"""
Represents an agent in the context of a message.

Attributes:
_address (str): The address of the agent.
_name (Optional[str]): The name of the agent.
_signing_callback (Callable): The callback for signing messages.

Properties:
name (str): The name of the agent.
address (str): The address of the agent.
identifier (str): The agent's address and network prefix.

Methods:
sign_digest(data: bytes) -> str: Sign the provided data with the agent's identity.
"""

def __init__(
self,
address: str,
name: Optional[str],
signing_callback: Callable,
):
"""
Initialize the AgentRepresentation instance.

Args:
address (str): The address of the context.
name (Optional[str]): The optional name associated with the context.
signing_callback (Callable): The callback for signing messages.
"""
self._address = address
self._name = name
self._signing_callback = signing_callback

@property
def name(self) -> str:
"""
Get the name associated with the context or a truncated address if name is None.

Returns:
str: The name or truncated address.
"""
if self._name is not None:
return self._name
return self._address[:10]

@property
def address(self) -> str:
"""
Get the address of the context.

Returns:
str: The address of the context.
"""
return self._address

@property
def identifier(self) -> str:
"""
Get the address of the agent used for communication including the network prefix.

Returns:
str: The agent's address and network prefix.
"""
return TESTNET_PREFIX + "://" + self._address

def sign_digest(self, data: bytes) -> str:
"""
Sign the provided data with the callback of the agent's identity.

Args:
data (bytes): The data to sign.

Returns:
str: The signature of the data.
"""
return self._signing_callback(data)


ERROR_MESSAGE_DIGEST = Model.build_schema_digest(ErrorMessage)


Expand All @@ -103,52 +184,42 @@ class Context:

Attributes:
storage (KeyValueStore): The key-value store for storage operations.
wallet (LocalWallet): The agent's wallet for transacting on the ledger.
ledger (LedgerClient): The client for interacting with the blockchain ledger.
_name (Optional[str]): The name of the agent.
_address (str): The address of the agent.
_resolver (Resolver): The resolver for address-to-endpoint resolution.
_identity (Identity): The agent's identity.
_queries (Dict[str, asyncio.Future]): Dictionary mapping query senders to their
response Futures.
response Futures.
_session (Optional[uuid.UUID]): The session UUID.
_replies (Optional[Dict[str, Dict[str, Type[Model]]]]): Dictionary of allowed reply digests
for each type of incoming message.
for each type of incoming message.
_interval_messages (Optional[Set[str]]): Set of message digests that may be sent by
interval tasks.
interval tasks.
_message_received (Optional[MsgDigest]): The message digest received.
_protocols (Optional[Dict[str, Protocol]]): Dictionary mapping all supported protocol
digests to their corresponding protocols.
digests to their corresponding protocols.
_logger (Optional[logging.Logger]): The optional logger instance.

Properties:
name (str): The name of the agent.
address (str): The address of the agent.
logger (logging.Logger): The logger instance.
protocols (Optional[Dict[str, Protocol]]): Dictionary mapping all supported protocol
digests to their corresponding protocols.
digests to their corresponding protocols.
session (uuid.UUID): The session UUID.

Methods:
get_message_protocol(message_schema_digest): Get the protocol digest associated
with a message schema digest.
with a message schema digest.
send(destination, message, timeout): Send a message to a destination.
send_raw(destination, json_message, schema_digest, message_type, timeout): Send a message
with the provided schema digest to a destination.
send_raw(destination, json_message, schema_digest, message_type, timeout):
Send a message with the provided schema digest to a destination.
broadcast(destination_protocol, message, limit, timeout): Broadcast a message
to agents with a specific protocol.
to agents with a specific protocol.

"""

def __init__(
self,
address: str,
identifier: str,
name: Optional[str],
agent: AgentRepresentation,
storage: KeyValueStore,
resolve: Resolver,
identity: Identity,
wallet: LocalWallet,
ledger: LedgerClient,
queries: Dict[str, asyncio.Future],
session: Optional[uuid.UUID] = None,
Expand All @@ -163,32 +234,24 @@ def __init__(
Initialize the Context instance.

Args:
address (str): The address of the context.
name (Optional[str]): The optional name associated with the context.
storage (KeyValueStore): The key-value store for storage operations.
resolve (Resolver): The resolver for name-to-address resolution.
identity (Identity): The identity associated with the context.
wallet (LocalWallet): The local wallet instance for managing identities.
ledger (LedgerClient): The ledger client for interacting with distributed ledgers.
queries (Dict[str, asyncio.Future]): Dictionary mapping query senders to their response
Futures.
queries (Dict[str, asyncio.Future]): Dictionary mapping query senders to their
response Futures.
session (Optional[uuid.UUID]): The optional session UUID.
replies (Optional[Dict[str, Dict[str, Type[Model]]]]): Dictionary of allowed replies
for each type of incoming message.
for each type of incoming message.
interval_messages (Optional[Set[str]]): The optional set of interval messages.
message_received (Optional[MsgDigest]): The optional message digest received.
wallet_messaging_client (Optional[Any]): The optional wallet messaging client.
protocols (Optional[Dict[str, Protocol]]): The optional dictionary of protocols.
logger (Optional[logging.Logger]): The optional logger instance.
"""
self.agent = agent
self.storage = storage
self.wallet = wallet
self.ledger = ledger
self._name = name
self._address = str(address)
self._identifier = str(identifier)
self._resolver = resolve
self._identity = identity
self._queries = queries
self._session = session or None
self._replies = replies
Expand All @@ -199,38 +262,6 @@ def __init__(
self._logger = logger
self._outbound_messages: Dict[str, Tuple[JsonStr, str]] = {}

@property
def name(self) -> str:
"""
Get the name associated with the context or a truncated address if name is None.

Returns:
str: The name or truncated address.
"""
if self._name is not None:
return self._name
return self._address[:10]

@property
def address(self) -> str:
"""
Get the address of the context.

Returns:
str: The address of the context.
"""
return self._address

@property
def identifier(self) -> str:
"""
Get the address of the agent used for communication including the network prefix.

Returns:
str: The agent's address and network prefix.
"""
return self._identifier

@property
def logger(self) -> logging.Logger:
"""
Expand Down Expand Up @@ -271,6 +302,19 @@ def outbound_messages(self) -> Dict[str, Tuple[JsonStr, str]]:
"""
return self._outbound_messages

@property
@deprecated("Please use `ctx.agent.address` instead.")
def address(self) -> str:
"""
Get the agent address associated with the context.
This is a deprecated property and will be removed in a future release.
Please use the `ctx.agent.address` property instead.

Returns:
str: The agent address.
"""
return self.agent.address

def get_message_protocol(self, message_schema_digest) -> Optional[str]:
"""
Get the protocol digest associated with a given message schema digest.
Expand Down Expand Up @@ -485,7 +529,7 @@ async def send_raw(
# Handle local dispatch of messages
if dispatcher.contains(destination_address):
await dispatcher.dispatch(
self.address,
self.agent.address,
destination_address,
schema_digest,
json_message,
Expand Down Expand Up @@ -514,7 +558,7 @@ async def send_raw(
self._outbound_messages[destination_address] = (json_message, schema_digest)

result = await self.send_raw_exchange_envelope(
self._identity,
self.agent,
destination,
self._resolver,
schema_digest,
Expand All @@ -533,7 +577,7 @@ async def send_raw(

@staticmethod
async def send_raw_exchange_envelope(
sender: Identity,
sender: AgentRepresentation,
destination: str,
resolver: Resolver,
schema_digest: str,
Expand All @@ -548,7 +592,7 @@ async def send_raw_exchange_envelope(
Standalone function to send a raw exchange envelope to an agent.

Args:
sender (Identity): The sender identity.
sender (AgentRepresentation): The representation of an agent.
destination (str): The destination address to send the message to.
resolver (Resolver): The resolver for address-to-endpoint resolution.
schema_digest (str): The schema digest of the message.
Expand Down Expand Up @@ -593,7 +637,7 @@ async def send_raw_exchange_envelope(
expires=expires,
)
env.encode_payload(json_message)
env.sign(sender)
env.sign(sender.sign_digest)

headers = {"content-type": "application/json"}
if sync:
Expand Down
1 change: 1 addition & 0 deletions python/src/uagents/crypto/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ def from_string(private_key_hex: str) -> "Identity":

return Identity(signing_key)

# this is not the real private key but a signing key derived from the private key
@property
def private_key(self) -> str:
"""Property to access the private key of the identity."""
Expand Down
Loading
Loading