macula_routing_nodeid (macula v0.20.5)

View Source

Node ID utilities for Kademlia DHT. 256-bit node identifiers with XOR distance metric.

Summary

Types

32 bytes (256 bits)

Functions

Calculate bucket index for a node relative to local node. Returns leading zero count of XOR distance (0..255). Special case: distance 0 (same node) returns 256. Normalizes inputs to 32 bytes if needed.

Check if NodeA is closer to Target than NodeB. Normalizes inputs to 32 bytes if needed.

Compare distances of NodeA and NodeB to Target. Returns: less (A closer), equal (same distance), greater (B closer). Normalizes inputs to 32 bytes if needed.

Calculate XOR distance between two node IDs. Normalizes inputs to 32 bytes if needed.

Create node ID from binary (validates size).

Parse node ID from hex string. Crashes on invalid hex or wrong length - exposes bugs in validation logic.

Generate a random 256-bit node ID.

Count leading zero bits in binary.

Normalize any binary to a 32-byte node ID. If already 32 bytes, returns as-is. Otherwise, hashes with SHA-256.

Convert node ID to hex string.

Types

node_id/0

-type node_id() :: binary().

32 bytes (256 bits)

Functions

bucket_index(LocalNodeId, TargetNodeId)

-spec bucket_index(binary(), binary()) -> 0..256.

Calculate bucket index for a node relative to local node. Returns leading zero count of XOR distance (0..255). Special case: distance 0 (same node) returns 256. Normalizes inputs to 32 bytes if needed.

closer_to(Target, NodeA, NodeB)

-spec closer_to(binary(), binary(), binary()) -> boolean().

Check if NodeA is closer to Target than NodeB. Normalizes inputs to 32 bytes if needed.

compare(Target, NodeA, NodeB)

-spec compare(binary(), binary(), binary()) -> less | equal | greater.

Compare distances of NodeA and NodeB to Target. Returns: less (A closer), equal (same distance), greater (B closer). Normalizes inputs to 32 bytes if needed.

distance(NodeId1, NodeId2)

-spec distance(binary(), binary()) -> binary().

Calculate XOR distance between two node IDs. Normalizes inputs to 32 bytes if needed.

from_binary(Binary)

-spec from_binary(binary()) -> {ok, node_id()} | {error, invalid_size}.

Create node ID from binary (validates size).

from_hex(HexString)

-spec from_hex(string()) -> node_id().

Parse node ID from hex string. Crashes on invalid hex or wrong length - exposes bugs in validation logic.

generate()

-spec generate() -> node_id().

Generate a random 256-bit node ID.

leading_zeros(Binary)

-spec leading_zeros(binary()) -> 0..256.

Count leading zero bits in binary.

normalize(Binary)

-spec normalize(binary()) -> node_id().

Normalize any binary to a 32-byte node ID. If already 32 bytes, returns as-is. Otherwise, hashes with SHA-256.

to_hex(NodeId)

-spec to_hex(node_id()) -> string().

Convert node ID to hex string.