|
libwebsockets
Lightweight C library for HTML5 websockets
|
Libwebsockets provides an implementation of a Kademlia-based Distributed Hash Table (DHT) compatible with the BitTorrent DHT network. It is useful for decentralized node discovery, configuration fetching, and peer-to-peer metadata storage without relying on centralized infrastructure.
The DHT functionality is physically split into client and backend blocks to allow resource-constrained devices to participate as clients without maintaining full routing tables and storage on the device.
A vhost's "Distributed Hash Table": [{...}] block in lwsws JSON takes "v" (version string), "name", "port" (default 7682), "ipv6", "hash" (sha1, sha256, sha512 or blake3), "legacy" and "allow-private". "legacy" selects the original fixed 20-byte id wire encoding for peers that predate the multihash one; it is off by default and needs a sha1 hash. "allow-private" admits peers at private, loopback or link-local addresses, for a LAN deployment; by default only public addresses are kept, as BEP42 expects.
A node that is not given an id starts with a random one and, once a quorum of peers has told it its external address, replaces it with one bound to that address as BEP42 describes (the first 21 bits derive from the masked IP and a random byte that ends the id). Peers' ids are checked the same way when they enter the routing table: an id that is not bound to its address is still kept while a bucket has room, since a node may not know its address yet, but a bound one displaces it when the bucket is full, and no address may hold more than two entries in a bucket however many ids it presents. lws_dht_bep42_id() and lws_dht_bep42_check() are available to applications that supply their own ids.
To interact with the DHT, you must declare and configure an instance of lws_dht_info and pass it to lws_dht_create(), which allocates the active lws_dht_ctx tracking structural state.
When building exclusively as a client (LWS_WITH_DHT_BACKEND=0), certain hidden structural attributes used exclusively for routing tables and storage coordination inside lws_dht_ctx will be omitted from the build to minimize memory footprint.
A typical DHT client needs to formulate queries and dispatch them:
Libwebsockets allows deep interception of typical DHT lifecycles using structured external callbacks (lws_dht_cb_t). This provides custom logic for arbitrary events like resolving your consensus external IP, processing peer payloads, or implementing plugin-provided features.
You can easily handle payloads by placing your logic inside an LWS protocol handler or a standalone plugin. To intercept incoming announcements explicitly: