Skip to content

unaiverse.networking.node.profile

A node describes itself to the UNaIVERSE server and to its peers with a profile. The profile has three parts with different lifetimes. The static part comes from the account and the server (the id, the name and the type of the node, its owner, its access lists). The dynamic part describes the running process (the machine, the network addresses, the streams, the current connections) and changes while the node runs. The CV is the list of badges that worlds assigned to the node.

NodeProfile holds the three parts in one dictionary. Every node builds its own profile in the constructor of Node from the static part fetched from the server, the peer ids and addresses of its two network identities and its CV. It offers the whole profile to every peer in the handshake of a Session. On the other side, the peer turns the offered dictionary back into a NodeProfile with NodeProfile.from_dict. The profiles of the peers that an agent knows are the values of agent.all_agents and the profile of the world that an agent is in is agent.world_profile (see Agents).

Application code mostly reads profiles. A world reads the profile of a joining agent in assign_role (see Worlds) and an action reads the profile of a peer to decide how to treat it:

profile = agent.all_agents[peer_id]
static = profile.get_static_profile()
dynamic = profile.get_dynamic_profile()
print(f"{static['nickname']}/{static['node_name']}", dynamic["connections"]["role"])

The three parts

The static part has these fields. A field that the server does not send stays None. The fields that the server sends beyond this list are kept as they arrive.

Field Type Meaning
node_id str The id of the node. Required.
node_type str "agent", "world" or the type of a human node. Required.
node_name str The name of the node on its account. Required.
node_description str The description written by the owner.
created_utc str The creation time of the node on the server.
nickname str The nickname of the owner account. It is the owner part of owner/name.
name, surname, title str The public identity of the owner.
organization, email str Legacy fields that current servers no longer send.
max_nr_connections int The maximum number of connections of the node. It sizes the connection pools.
allowed_node_ids list of str The node ids that may connect. The list exists only when the owner restricted access.
world_masters_node_ids list of str World nodes only. The node ids that join as world masters.
certified bool Whether the node is certified.
inspector_node_id str The node id of the inspector that may attach to this node.
location_method str "manual" (the default) or a method that derives the location from the public IP address.
location dict The location written by the owner (default {}).

The dynamic part has these fields.

Field Type Meaning
timestamp str The ISO 8601 UTC time at which the machine fields were read.
os str The platform string of the machine (platform.platform()).
cpu_cores, logical_cpus int The physical and logical CPU cores.
memory_gb, memory_avail, memory_used float Total, available and used memory in GB.
public_ip_address str The public IP address. It is 'Public IP not available.' when no lookup service answered.
guessed_location dict The static location when location_method is "manual". Otherwise the result of a geolocation lookup of the public IP address.
peer_id, peer_addresses str, list of str The identity and the addresses of the node on the public network.
private_peer_id, private_peer_addresses str, list of str The identity and the addresses of the node on the world network.
is_relay bool True for a world node whose world network is publicly reachable and therefore offers a relay to its members.
max_message_size int The largest message in bytes that the node accepts (0 means no limit).
accept_files, max_file_size bool, int Whether the node accepts files and the largest file in bytes (0 means no limit).
proc_inputs, proc_outputs, streams list The descriptions of the processor inputs, the processor outputs and the streams of the hosted entity.
connections dict public_agents, world_agents and world_masters (lists of dicts that describe the connected peers), world_peer_id (the world the node is in) and role (the role name of the node).
world_summary dict World nodes only. world_title, the lists world_agents and world_masters of the confirmed members, their counts world_agents_count, world_masters_count, total_agents and the badge and stream counters.
hidden bool or None The visibility asked for in the constructor of Node. None leaves the visibility on the server untouched.
tmp_<option> any The options of a join request (see Node.run_async). They exist only in a profile offered to a world.

The CV is a list of dicts, one per badge, each with at least the key last_edit_utc.

NodeProfile

NodeProfile(static: dict, dynamic: dict, cv: list)
Source code in unaiverse/networking/node/profile.py
def __init__(self,
             static: dict,
             dynamic: dict,
             cv: list) -> None:
    """Initializes a NodeProfile from static, dynamic, and CV data.

    Args:
        static: Dictionary of static profile fields (e.g. node_id, node_type, name, nickname).
        dynamic: Dictionary of dynamic profile fields (e.g. os, memory, peer_id).  Only
            keys that are expected by the internal template are copied in.
        cv: List of CV entry dictionaries; entries are sorted by ``last_edit_utc`` before storage.

    Raises:
        ValueError: If ``static`` is empty or any required static key is missing.
    """

    # Checking provided data
    if not static:
        raise ValueError("Missing static profile data")

    # Forcing key order (important! otherwise the hash operation will not be consistent with the one on the server)
    cv = [{k: _cv[k] for k in sorted(_cv)} for _cv in sorted(cv, key=lambda x: x['last_edit_utc'])]

    self._profile_data: dict = \
        {
            'static': {
                'node_id': None,
                'node_type': None,
                'node_name': None,
                'node_description': None,
                'created_utc': None,
                'name': None,
                'surname': None,
                'title': None,
                'nickname': None,  # The owner's public identity
                'organization': None,  # Legacy: the server no longer sends it
                'email': None,  # Legacy: the server no longer sends it
                'max_nr_connections': None,
                'allowed_node_ids': None,
                'world_masters_node_ids': None,
                'certified': None,
                'inspector_node_id': None,
                'location_method': None,
                'location': None
            },
            'dynamic': {
                'os': None,
                'cpu_cores': None,
                'logical_cpus': None,
                'memory_gb': None,
                'memory_avail': None,
                'memory_used': None,
                'timestamp': None,
                'public_ip_address': None,
                'guessed_location': None,
                'peer_id': None,
                'peer_addresses': None,
                'private_peer_id': None,
                'private_peer_addresses': None,
                'is_relay': None,  # True when this node is a world offering a reachable relay to its members
                'max_message_size': None,  # The largest message this node takes (0: no limit; None: legacy)
                'accept_files': None,  # True when this node accepts files
                'max_file_size': None,  # The largest file it takes (0: no limit)
                'proc_inputs': None,
                'proc_outputs': None,
                'streams': None,
                'connections': {
                    'public_agents': None,  # List of dict
                    'world_agents': None,  # List of dict
                    'world_masters': None,  # List of dict
                    'world_peer_id': None,  # Str
                    'role': None  # Str
                },
                'world_summary': {
                    "world_title": None,
                    "world_agents": None,
                    "world_masters": None,
                    "world_agents_count": None,
                    "world_masters_count": None,
                    "total_agents": None,
                    "agent_badges_count": None,
                    "agent_badges": None,
                    "streams_count": None
                },
                "hidden": None
            },
            'cv': cv
        }

    # Backward compatibility
    if "location" not in static:
        static['location'] = {}
    if "location_method" not in static:
        static['location_method'] = "manual"

    # Only the keys the SDK cannot run without are required: every other template key
    # defaults to None, so a field the server stops sending degrades instead of
    # crashing the boot
    for k in ('node_id', 'node_type', 'node_name'):
        if k not in static:
            raise ValueError("Missing required static profile info: " + str(k))

    # Filling static profile info (there might be more information that the one shown above)
    for k, v in static.items():
        self._profile_data['static'][k] = v

    # Including the provided dynamic info, only considering the expected keys
    # (the provided "dynamic" argument will contain all or just a sub-portion of the expected keys)
    for k, v in dynamic.items():
        if k == 'connections' and v is not None and isinstance(v, dict):
            for kk, vv in v.items():
                if (kk in self._profile_data['dynamic']['connections'] and
                        self._profile_data['dynamic']['connections'][kk] is None):
                    self._profile_data['dynamic']['connections'][kk] = vv
        elif k == 'world_summary' and v is not None and isinstance(v, dict):
            for kk, vv in v.items():
                if (kk in self._profile_data['dynamic']['world_summary'] and
                        self._profile_data['dynamic']['world_summary'][kk] is None):
                    self._profile_data['dynamic']['world_summary'][kk] = vv
        elif k in self._profile_data['dynamic'] and self._profile_data['dynamic'][k] is None:
            self._profile_data['dynamic'][k] = v
        elif k.startswith('tmp_'):
            self._profile_data['dynamic'][k] = v

    # Internally required attributes
    self._profile_last_updated = None  # Will be set by calling _fill_missing_specs or check_and_update_specs
    self._geolocation_cache = {}  # Will be needed to avoid too many IP-related lookups

    # Filling the missing information (machine-level information, specs) that can be automatically extracted
    self._fill_missing_specs()

    # Flag
    self._connections_updated = False

Holds the static part, the dynamic part and the CV of one node.

Argument Type Default Meaning
static dict required The static fields. Every key is copied (the keys outside the table above included). node_id, node_type and node_name are required.
dynamic dict required The dynamic fields. The constructor copies the keys of the table above and every key that starts with tmp_. The nested keys of connections and world_summary are copied one by one. Other keys are discarded.
cv list[dict] required The CV. The constructor sorts the entries by last_edit_utc and the keys of each entry alphabetically because the server computes the CV hash in this order.

When location and location_method are missing, the constructor writes location = {} and location_method = "manual" into the static dict of the caller. That dict therefore changes too. It then fills the dynamic fields that describe the machine (timestamp, os, the CPU and memory fields, public_ip_address and guessed_location) and are still None. The values come from the machine that runs the code.

Lookups on every construction

The filling runs whenever at least one dynamic field is None. Almost every profile has such a field and the profiles of remote peers built with from_dict are no exception. The filling reads the public IP address from external services that it tries in order with a timeout of 5 seconds each (api.ipify.org, icanhazip.com, ident.me, checkip.amazonaws.com). When location_method is not "manual" it also asks ip-api.com for the location of that address. These are blocking HTTP requests. A remote profile that lacks a machine field receives the value of the local machine.

Raises ValueError when static is empty or lacks one of the three required keys and KeyError when an entry of cv lacks last_edit_utc.

from_dict classmethod

from_dict(combined_data: dict) -> NodeProfile
Source code in unaiverse/networking/node/profile.py
@classmethod
def from_dict(cls, combined_data: dict) -> 'NodeProfile':
    """Creates a NodeProfile instance from a combined profile dictionary.

    Args:
        combined_data: A dictionary representing the node profile, typically loaded from
            JSON or received over the network.  Expected to contain a ``"static"`` key
            (with at least ``"node_id"``), a ``"dynamic"`` key, and a ``"cv"`` key
            (list of dicts).

    Returns:
        A new NodeProfile instance populated from the dictionary.

    Raises:
        ValueError: If ``"node_id"`` is absent from the ``"static"`` sub-dictionary.
        TypeError: If the ``"cv"`` data is present but not a list.
    """

    # Ensure essential 'node_id' is present
    static_combined_data = combined_data.get('static')
    if static_combined_data is None:
        raise ValueError("Input dictionary must contain a 'static' section.")
    static_combined_data: dict
    node_id = static_combined_data.get('node_id', None)
    if not node_id:
        raise ValueError("Input dictionary must contain a 'node_id'.")

    profile_instance = cls(
        static=combined_data['static'],
        dynamic=combined_data['dynamic'],
        cv=combined_data['cv']
    )

    return profile_instance

Builds a NodeProfile from a dictionary in the shape that get_all_profile returns. Profiles travel in this shape between nodes and inside the world grant.

Argument Type Default Meaning
combined_data dict required A dict with the keys static, dynamic and cv.

Returns a new NodeProfile. The constructor that builds it also runs the lookups described above.

Raises ValueError when static is missing or its node_id is missing or empty and KeyError when dynamic or cv is missing. The constructor raises the errors listed above.

The node calls it on every profile that a peer offers in a handshake, on the world profile carried by a grant and on the profile kept by a Session that resumes. An offered profile that fails to parse makes the node reject the peer.

get_static_profile

get_static_profile() -> dict
Source code in unaiverse/networking/node/profile.py
def get_static_profile(self) -> dict:
    """Returns the static portion of the profile data.

    Returns:
        A dictionary containing static profile fields such as node_id, node_type,
        and user identity information.
    """
    return self._profile_data['static']

Returns the static part as a dict. The method returns the dict stored inside the profile and not a copy. Changing it therefore changes the profile.

get_dynamic_profile

get_dynamic_profile() -> dict
Source code in unaiverse/networking/node/profile.py
def get_dynamic_profile(self) -> dict:
    """Returns the dynamic portion of the profile data.

    Returns:
        A dictionary containing dynamic profile fields such as OS, CPU, memory,
        IP address, peer information, and connection state.
    """
    return self._profile_data['dynamic']

Returns the stored dynamic part as a dict and not a copy. The node relies on this to update its addresses and its connections in place.

get_cv

get_cv() -> list
Source code in unaiverse/networking/node/profile.py
def get_cv(self) -> list:
    """Returns the CV data associated with this node profile.

    Returns:
        A list of CV entry dictionaries, sorted by ``last_edit_utc``.
    """
    return self._profile_data['cv']

Returns the CV as the stored list of dicts. After the constructor the list is sorted by last_edit_utc. After update_cv it is in the order that the caller passed.

get_all_profile

get_all_profile() -> dict
Source code in unaiverse/networking/node/profile.py
def get_all_profile(self) -> dict:
    """Returns the complete profile data dictionary.

    Returns:
        A dictionary with keys ``"static"``, ``"dynamic"``, and ``"cv"``.
    """
    return self._profile_data

Returns the stored dict with the keys static, dynamic and cv. json.dumps of this dict is what the node offers to its peers and what a world puts in its grants.

update_cv

update_cv(new_cv: list[dict]) -> None
Source code in unaiverse/networking/node/profile.py
def update_cv(self, new_cv: list[dict]) -> None:
    """Replaces the stored CV data with a new list of CV entries.

    Args:
        new_cv: The new CV data as a list of dictionaries.
    """
    self._profile_data['cv'] = new_cv

Replaces the CV with new_cv (list[dict]) exactly as given. Unlike the constructor it sorts neither the entries nor their keys. Returns None.

The node calls it when a world announces new badges with a GET_CV_FROM_ROOT message. The node then downloads its CV from the server, stores it with this method and requests a new token that carries the new CV hash.

check_and_update_specs

check_and_update_specs(update_only: bool = True) -> bool
Source code in unaiverse/networking/node/profile.py
def check_and_update_specs(self, update_only: bool = True) -> bool:
    """Checks current system specs and updates the dynamic profile accordingly.

    Args:
        update_only: If True, unconditionally merges current specs into the dynamic
            profile without change detection.  If False, compares each spec field
            against the saved value and only merges when a change is detected
            (default: True).

    Returns:
        True if any spec field changed (only meaningful when ``update_only=False``),
        False otherwise.
    """

    current_specs = self._get_current_specs()
    specs_changed = False

    if update_only:
        self._profile_data['dynamic'] |= current_specs
    else:
        saved_specs = self._profile_data['dynamic'].copy()
        change_details = []

        # Compare current specs with saved specs (ignore timestamp for comparison)
        keys_to_compare = current_specs.keys()

        for key in keys_to_compare:
            if key == 'timestamp':
                continue

            saved_value = saved_specs.get(key)
            current_value = current_specs.get(key)

            # Handle float comparison with tolerance
            if isinstance(saved_value, float) and isinstance(current_value, float):
                if abs(current_value - saved_value) > 1e-6:  # Tolerance for float changes
                    change_details.append(f"{key}: from {saved_value:.2f} to {current_value:.2f}")
                    specs_changed = True

            elif saved_value != current_value:
                change_details.append(f"{key}: from {saved_value} to {current_value}")
                specs_changed = True

        # Comparing total resources (OS, CPU, total RAM/Disk) is more typical for 'specification' changes.
        if specs_changed:
            # Update the specification in the profile data with the new current specs
            self._profile_data['dynamic'] |= current_specs
            change_summary = ", ".join(change_details)
            log.print(f"Specs changed for '{self._profile_data['static']['node_id']}': {change_summary}")

    self._profile_last_updated = datetime.datetime.now(timezone.utc)  # Mark profile as checked/updated

    return specs_changed

Reads the machine fields again (timestamp, os, the CPU and memory fields, public_ip_address, guessed_location) with the same lookups as the constructor and merges them into the dynamic part.

Argument Type Default Meaning
update_only bool True True merges the fresh values without comparing them. False compares each field with the stored value (floats with a tolerance of 1e-6, timestamp ignored), merges only when something changed and prints the changes.

Returns True when update_only=False and at least one field changed. In every other case it returns False. No code of the SDK calls this method.

mark_change_in_connections

mark_change_in_connections() -> None
Source code in unaiverse/networking/node/profile.py
def mark_change_in_connections(self) -> None:
    """Flags that a connection change has occurred since the last reset."""
    self._connections_updated = True

Raises the flag that says that the dynamic part changed since it was last sent to the server. Returns None. The node raises it when its connections, its addresses or the summary of its world change. The flag is a plain boolean and many changes before the next send count as one.

unmark_change_in_connections

unmark_change_in_connections() -> None
Source code in unaiverse/networking/node/profile.py
def unmark_change_in_connections(self) -> None:
    """Clears the connection-change flag."""
    self._connections_updated = False

Clears the flag of mark_change_in_connections. Returns None. The node clears it right before it sends the dynamic part to the server.

connections_changed

connections_changed() -> bool
Source code in unaiverse/networking/node/profile.py
def connections_changed(self) -> bool:
    """Returns whether a connection change has been recorded since the last reset.

    Returns:
        True if connections have changed, False otherwise.
    """
    return self._connections_updated

Returns the flag of mark_change_in_connections as a bool. The network task of the node reads it and sends the dynamic part to the server when it is True and at least 10 seconds (Custom.SEND_DYNAMIC_PROFILE_EVERY) have passed since the previous send.

verify_cv_hash

verify_cv_hash(cv_hash: str) -> tuple[bool, tuple[str, str]]
Source code in unaiverse/networking/node/profile.py
def verify_cv_hash(self, cv_hash: str) -> tuple[bool, tuple[str, str]]:
    """Verifies a CV hash against the hash computed from the stored CV data.

    Args:
        cv_hash: The hash string to verify.

    Returns:
        A tuple ``(match, (provided_hash, computed_hash))`` where ``match`` is True if
        the hashes are equal, and the second element contains both hash strings for
        diagnostic purposes.
    """
    cv = self._profile_data['cv']  # Should we sort keys?
    computed_hash = hashlib.blake2b(json.dumps(cv).encode("utf-8"),
                                    digest_size=16).hexdigest()
    return cv_hash == computed_hash, (cv_hash, computed_hash)

Checks that the stored CV is the one that the server attested.

Argument Type Default Meaning
cv_hash str required The expected digest, usually the cv_hash claim of the node token of the peer.

The method computes the 16-byte BLAKE2b digest of json.dumps(cv) (default separators, with the list and its dicts in the order in which they are stored) and compares its hex form with cv_hash.

Returns the tuple (match, (cv_hash, computed_hash)) where match is a bool. The second element carries both digests for diagnostics.

The decision policy of a node calls it on every offered profile whose token was verified. A mismatch means that the offered CV differs from the attested one and the peer is rejected with CV_HASH_MISMATCH.

match, (expected, computed) = profile.verify_cv_hash(claims.cv_hash)
if not match:
    print(f"CV changed after the token was issued: {expected} against {computed}")