Algorithm-Kademlia
view release on metacpan or search on metacpan
lib/Algorithm/Kademlia.pod view on Meta::CPAN
=pod
=encoding utf-8
=head1 NAME
Algorithm::Kademlia - Pure Perl implementation of the Kademlia DHT algorithm
=head1 SYNOPSIS
use Algorithm::Kademlia qw[xor_distance xor_bucket_index];
my $local_id = pack( 'H*', '00' x 20 ); # 160-bit ID
my $rt = Algorithm::Kademlia::RoutingTable->new( local_id_bin => $local_id );
# Add a peer (handles Least-Recently-Seen eviction policy)
my $stale = $rt->add_peer( $peer_id, { addr => '127.0.0.1:4001' } );
if ($stale) {
# Bucket is full. The protocol requires you to ping the $stale node.
# If the ping fails:
# $rt->evict_peer($stale->{id});
# $rt->add_peer($peer_id, ...);
# If the ping succeeds:
# The new $peer_id is discarded (as $stale was moved to the tail).
}
# Storage for the DHT
my $storage = Algorithm::Kademlia::Storage->new( ttl => 3600 );
$storage->put($key_bin, $value_bin);
# State management for iterative lookups
my $search = Algorithm::Kademlia::Search->new(
target_id_bin => $target_key,
alpha => 3
);
$search->add_candidates($rt->find_closest($target_key));
while (!$search->is_finished) {
my @to_query = $search->next_to_query();
for my $node (@to_query) {
# ... Send FIND_NODE RPC to $node ...
# If response: $search->mark_responded($node->{id}, @found_peers);
# If failure: $search->mark_failed($node->{id});
}
}
my @results = $search->best_results();
=head1 DESCRIPTION
C<Algorithm::Kademlia> provides the mathematical and structural foundations for a Kademlia Distributed Hash Table
(DHT). It is designed to be protocol-agnostic, meaning it only handles the XOR-metric distance calculations, the
k-bucket routing table logic, and the search state management.
This module is suitable for building BitTorrent-compatible DHTs, libp2p Kademlia implementations, or custom
peer-to-peer storage systems.
=head1 FUNCTIONS
These are bitwise logic utilities for the Kademlia XOR metrics.
=head2 C<xor_distance( $id1, $id2 )>
Returns the bitwise XOR of two binary strings.
( run in 1.417 second using v1.01-cache-2.11-cpan-e1769b4cff6 )