dart_libp2p_kad_dht library

A Dart implementation of the libp2p Kademlia DHT.

This library provides a Dart implementation of the Kademlia Distributed Hash Table (DHT) for the libp2p network stack, based on the go-libp2p-kad-dht implementation.

Classes

AminoConstants
Protocol constants for the Amino DHT
DHT
DHT builder class that provides functional configuration similar to libp2p host configuration
DHTConfig
Configuration for the DHT
DHTHandlers
Handlers for DHT protocol messages
DHTOptions
Options for configuring the DHT
HasHost
Interface for objects that have a Host
IP
Simple IP address class for network operations
IpfsDHT
DHT is the main implementation of the Kademlia DHT for libp2p.
IpfsDHTv2
IpfsDHT v2 - A modular, maintainable implementation of the IPFS DHT
IPNet
IP network class for CIDR operations
MemoryProviderStore
A basic in-memory implementation of ProviderStore
Message
Represents a DHT message
MessageSenderWithDisconnect
Interface for a message sender that can disconnect from peers.
Peer
Represents a peer in the DHT
PeerQueried
Event emitted when a peer is successfully queried.
PeerQueryFailed
Event emitted when a query to a peer fails.
ProviderManager
ProviderManager adds and retrieves providers from a datastore, caching them in between for efficiency.
ProviderManagerOptions
Options for configuring a provider manager
ProviderRecord
A provider record with an expiration time
ProviderSet
ProviderSet maintains a list of providers for a key and the time they were added.
ProviderStore
ProviderStore represents a store that associates peers and their addresses to keys.
QueryEvent
Base class for all events emitted during a query operation.
QueryPeerset
QueryPeerset maintains the state of a Kademlia asynchronous lookup. The lookup state is a set of peers, each labeled with a peer state.
QueryResult
Represents the result of a completed query operation.
QueryRunner
A robust, event-driven query runner for Kademlia DHT lookups.
QueryTerminated
Event emitted when the query terminates.
Record
Record represents a DHT record that contains a value for a key. It contains a timestamp and public key that is used to verify the record.
RouterCache
Router cache
SimplePeerLatencyMetrics
Simple implementation of PeerLatencyMetrics that returns a default latency for all peers. In a real implementation, this would use the host's peerstore to get actual latency measurements.
SimpleProtocolMessenger
Simple concrete implementation of ProtocolMessenger for DHT v2

Enums

ConnectionType
Enum for different types of peer connections
DHTMode
Mode options for the DHT
MessageType
Enum for different types of DHT messages
PeerState
PeerState describes the state of a peer ID during the lifecycle of an individual lookup.
QueryTerminationReason
Enumeration of possible query termination reasons.

Extensions

DHTBootstrap on IpfsDHT
Extension methods for DHT bootstrap functionality

Constants

maxNBootstrappers → const int
Maximum number of bootstrappers to use at once
minRTRefreshThreshold → const int
Minimum number of peers in the routing table. If we drop below this and we see a new peer, we trigger a bootstrap round.
periodicBootstrapInterval → const Duration
Interval for periodic bootstrap operations
publicCIDR6 → const String
CIDR for public IPv6 addresses
routerCacheTime → const Duration
Cache duration for the router

Properties

defaultBootstrapPeers List<MultiAddr>
DefaultBootstrapPeers is a set of public DHT bootstrap peers provided by libp2p.
final
private4 List<IPNet>
Private IPv4 networks
final
protocols List<ProtocolID>
Protocols is a list containing all supported protocol IDs for Amino DHT. Currently, it only includes the main ProtocolID, but it's defined as a list to allow for potential future protocol versions or variants.
final
public6 IPNet?
Public IPv6 network
final
routerCache RouterCache
Global router cache
final
unroutable4 List<IPNet>
Unroutable IPv4 networks
final
unroutable6 List<IPNet>
Unroutable IPv6 networks
final

Functions

addressFilter(List<MultiAddr> f(List<MultiAddr>)) DHTOption
AddressFilter allows to configure the address filtering function. This function is run before addresses are added to the peerstore. It is most useful to avoid adding localhost / local addresses.
bootstrapPeers(List<AddrInfo> bootstrappers) DHTOption
BootstrapPeers configures the bootstrapping nodes that we will connect to to seed and refresh our Routing Table if it becomes empty.
bootstrapPeersFunc(List<AddrInfo> getBootstrapPeers()) DHTOption
BootstrapPeersFunc configures the function that returns the bootstrapping nodes that we will connect to to seed and refresh our Routing Table if it becomes empty.
bucketSize(int size) DHTOption
BucketSize configures the bucket size (k in the Kademlia paper) of the routing table.
concurrency(int alpha) DHTOption
Concurrency configures the number of concurrent requests (alpha in the Kademlia paper) for a given query path.
datastore(dynamic ds) DHTOption
Datastore configures the DHT to use the specified datastore.
dhtMessageRetryBackoffFactor(double factor) DHTOption
DhtMessageRetryBackoffFactor configures the multiplicative factor for DHT message retry backoff.
dhtMessageRetryInitialBackoff(Duration delay) DHTOption
DhtMessageRetryInitialBackoff configures the initial delay before retrying a DHT message.
dhtMessageRetryMaxBackoff(Duration delay) DHTOption
DhtMessageRetryMaxBackoff configures the maximum delay between DHT message retries.
disableAutoRefresh() DHTOption
DisableAutoRefresh completely disables 'auto-refresh' on the DHT routing table. This means that we will neither refresh the routing table periodically nor when the routing table size goes below the minimum threshold.
disableProviders() DHTOption
DisableProviders disables storing and retrieving provider records.
disableValues() DHTOption
DisableValues disables storing and retrieving value records (including public keys).
enableOptimisticProvide() DHTOption
EnableOptimisticProvide enables an optimization that skips the last hops of the provide process. This works by using the network size estimator (which uses the keyspace density of queries) to optimistically send ADD_PROVIDER requests when we most likely have found the last hop. It will also run some ADD_PROVIDER requests asynchronously in the background after returning, this allows to optimistically return earlier if some threshold number of RPCs have succeeded. The number of background/in-flight queries can be configured with the OptimisticProvideJobsPoolSize option.
filterLocalhostAddrs(List<MultiAddr> addrs) List<MultiAddr>
Filters out localhost addresses from a list of multiaddrs
filterLocalhostInResponses(bool filter) DHTOption
FilterLocalhostInResponses configures whether to filter localhost addresses from FIND_NODE responses. This prevents advertising 127.0.0.1 addresses to remote peers, which are not useful for them.
getDefaultBootstrapPeerAddrInfos() List<AddrInfo>
GetDefaultBootstrapPeerAddrInfos returns the AddrInfo objects for the default bootstrap peers so we can use these for initializing the DHT by passing these to the bootstrapPeers(...) option.
hasValidConnectedness(Host host, PeerId id) bool
Checks if a peer has valid connectedness
inAddrRange(IP ip, List<IPNet> ipnets) bool
Checks if an IP is in any of the given IP networks
isEUI(IP ip) bool
Checks if an IPv6 address is an EUI-64 address
isLocalhostAddr(MultiAddr addr) bool
Checks if a multiaddr contains a localhost/loopback address
isPrivateAddr(MultiAddr addr) bool
isPrivateAddr follows the logic of manet.IsPrivateAddr, except that it uses a stricter definition of "public" for ipv6
isPublicAddr(MultiAddr addr) bool
isPublicAddr follows the logic of manet.IsPublicAddr, except it uses a stricter definition of "public" for ipv6: namely "is it in 2000::/3"?
isRelayAddr(MultiAddr addr) bool
Checks if a multiaddr is a relay address
lookupCheckConcurrency(int n) DHTOption
LookupCheckConcurrency configures maximal number of go routines that can be used to perform a lookup check operation, before adding a new node to the routing table.
maxDhtMessageRetries(int count) DHTOption
MaxDhtMessageRetries configures the maximum number of attempts for sending a DHT message.
maxPeersPerBucket(int count) DHTOption
MaxPeersPerBucket configures the maximum number of peers per k-bucket. This is particularly useful for controlling bootstrap server capacity.
maxRecordAge(Duration maxAge) DHTOption
MaxRecordAge specifies the maximum time that any node will hold onto a record ("PutValue record") from the time its received. This does not apply to any other forms of validity that the record may contain. For example, a record may contain an ipns entry with an EOL saying its valid until the year 2020 (a great time in the future). For that record to stick around it must be rebroadcasted more frequently than once every 'MaxRecordAge'
maxRoutingTableSize(int size) DHTOption
MaxRoutingTableSize configures the maximum size of the routing table. This limits the total number of peers across all buckets, which is useful for mobile devices with limited resources.
mode(DHTMode m) DHTOption
Mode configures which mode the DHT operates in (Client, Server, Auto).
namespacedValidator(String ns, Validator v) DHTOption
NamespacedValidator adds a validator namespaced under ns. This option fails if the DHT is not using a NamespacedValidator as its validator (it uses one by default but this can be overridden with the Validator option). Adding a namespaced validator without changing the Validator will result in adding a new validator in addition to the default public key and IPNS validators. The "pk" and "ipns" namespaces cannot be overridden here unless a new Validator has been set first.
onRequestHook(void f(dynamic ctx, Stream s, Message req)) DHTOption
OnRequestHook registers a callback function that will be invoked for every incoming DHT protocol message. Note: Ensure that the callback executes efficiently, as it will block the entire message handler.
optimisticProvideJobsPoolSize(int size) DHTOption
OptimisticProvideJobsPoolSize allows to configure the asynchronicity limit for in-flight ADD_PROVIDER RPCs. It makes sense to set it to a multiple of optProvReturnRatio * BucketSize. Check the description of EnableOptimisticProvide for more details.
privateQueryFilter(dynamic dht, AddrInfo peerInfo) bool
PrivateQueryFilter doesn't currently restrict which peers we are willing to query from the local DHT.
privateRoutingTableFilter(dynamic dht, PeerId peerId) bool
PrivateRoutingTableFilter allows a peer to be added to the routing table if the connections to that peer indicate that it is on a private network
privRTFilter(dynamic dht, List<Conn> conns) bool
Helper function for private routing table filter
protocolExtension(ProtocolID ext) DHTOption
ProtocolExtension adds an application specific protocol to the DHT protocol. For example, /ipfs/lan/kad/1.0.0 instead of /ipfs/kad/1.0.0. extension should be of the form /lan.
protocolPrefix(ProtocolID prefix) DHTOption
ProtocolPrefix sets an application specific prefix to be attached to all DHT protocols. For example, /myapp/kad/1.0.0 instead of /ipfs/kad/1.0.0. Prefix should be of the form /myapp.
providerStore(ProviderStore ps) DHTOption
ProviderStore sets the provider storage manager.
publicQueryFilter(dynamic dht, AddrInfo peerInfo) bool
PublicQueryFilter returns true if the peer is suspected of being publicly accessible
publicRoutingTableFilter(dynamic dht, PeerId peerId) Future<bool>
PublicRoutingTableFilter allows a peer to be added to the routing table if the connections to that peer indicate that it is on a public network
queryFilter(QueryFilterFunc filter) DHTOption
QueryFilter sets a function that approves which peers may be dialed in a query
refreshInterval(Duration interval) DHTOption
RefreshInterval configures the refresh interval for the routing table. This is a convenience function that sets the routingTableRefreshInterval.
resiliency(int beta) DHTOption
Resiliency configures the number of peers closest to a target that must have responded in order for a given query path to complete.
routingTableFilter(RouteTableFilterFunc filter) DHTOption
RoutingTableFilter sets a function that approves which peers may be added to the routing table. The host should already have at least one connection to the peer under consideration.
routingTableLatencyTolerance(Duration latency) DHTOption
RoutingTableLatencyTolerance sets the maximum acceptable latency for peers in the routing table's cluster.
routingTablePeerDiversityFilter(dynamic pg) DHTOption
RoutingTablePeerDiversityFilter configures the implementation of the diversity filter for the Routing Table.
routingTableRefreshPeriod(Duration period) DHTOption
RoutingTableRefreshPeriod sets the period for refreshing buckets in the routing table. The DHT will refresh buckets every period by:
routingTableRefreshQueryTimeout(Duration timeout) DHTOption
RoutingTableRefreshQueryTimeout sets the timeout for routing table refresh queries.
sameV6Net(IP a, IP b) bool
Checks if two IPv6 addresses are in the same network
toIP(MultiAddr addr) IP?
Extracts the IP address from a multiaddr
v1ProtocolOverride(ProtocolID proto) DHTOption
V1ProtocolOverride overrides the protocolID used for /kad/1.0.0 with another. This is an advanced feature, and should only be used to handle legacy networks that have not been using protocolIDs of the form /app/kad/1.0.0.
validator(Validator v) DHTOption
Validator configures the DHT to use the specified validator.
withCustomMessageSender(MessageSenderBuilder messageSenderBuilder) DHTOption
WithCustomMessageSender configures the MessageSender of the DHT to use the custom implementation of the MessageSender

Typedefs

DHTHandler = Future<Message> Function(PeerId peer, Message message)
Type definition for a DHT message handler function
DHTOption = FutureOr<void> Function(DHTConfig config)
Type definition for a DHT option function
MessageSenderBuilder = MessageSenderWithDisconnect Function(Host host, List<ProtocolID> protocols)
Type definition for a function that builds message senders
ProtocolID = String
Protocol identifier type
QueryFilterFunc = bool Function(dynamic dht, AddrInfo peerInfo)
Type definition for a function that filters peers for queries
QueryFunction = Future<List<AddrInfo>> Function(PeerId peer)
A function that queries a peer and returns a list of closer peers.
RouteTableFilterFunc = bool Function(dynamic dht, PeerId peerId)
Type definition for a function that filters peers for the routing table
StopFunction = bool Function(QueryPeerset peerset)
A function that determines when a query should stop.

Exceptions / Errors

MaxRetriesExceededException
Exception thrown when DHT message retries are exhausted.