java.lang.Object
org.klomp.snark.dht.NodeInfoComparator
All Implemented Interfaces:
Serializable, Comparator<NodeInfo>

class NodeInfoComparatorextends Object implements Comparator<NodeInfo>, Serializable
Comparator for finding nodes closest to a target key in the DHT keyspace.

This comparator implements the Kademlia distance metric to determine which of two nodes is closer to a target key (either an info hash or node ID). The distance is calculated using XOR distance, which is the standard metric used in Kademlia-based DHTs.

The XOR distance metric has the important property that it forms a metric space, meaning it satisfies the triangle inequality and other mathematical properties that make it suitable for routing in distributed hash tables.

This comparator is primarily used for:
- Finding the k closest nodes to a target info hash
- Maintaining sorted lists of nodes by distance
- Selecting the best nodes for DHT queries and responses

  • Field Details

    • serialVersionUID

      private static final long serialVersionUID
      Pinned for serialized-form compatibility.
      See Also:
    • _base

      private final byte[] _base
      The target key (info hash or node ID) to measure distances against.
  • Constructor Details

    • NodeInfoComparator

      public NodeInfoComparator(SHA1Hash h)
      Creates a new comparator for measuring distance to the specified target key.
      Parameters:
      h - the target key (info hash or node ID) to compare distances against
  • Method Details

    • compare

      public int compare(NodeInfo lhs, NodeInfo rhs)
      Compares two nodes based on their XOR distance to the target key.

      The comparison calculates the XOR distance between each node's ID and the target key, then compares these distances lexicographically. The node with the smaller XOR distance is considered "closer" to the target.

      This method implements the standard Kademlia distance metric used throughout the DHT for routing and node selection.

      Specified by:
      compare in interface Comparator<NodeInfo>
      Parameters:
      lhs - the first node to compare
      rhs - the second node to compare
      Returns:
      negative value if lhs is closer to target, positive if rhs is closer, 0 if equal distance