Implementing a Kademlia DHT in Kotlin - Part 1
This is the first in a series of articles on how to implement a Kademlia DHT in Kotlin.
We will be following the specification documents at:-
The first item to implement will be the
NodeIDs are binary numbers of length B = 160 bits. In basic Kademlia, each node chooses its own ID by some unspecified quasi-random procedure. It is important that nodeIDs be uniformly distributed; the network design relies upon this.
160 bits = 20 bytes we will therefore create a
ByteArray that will hold 20 random bytes:-
ThreadLocalRandom.current().nextInt(257) will return us a random
Int value between 0 and 256 which will be in the range -128 to 127 when converted to a signed
Next, we will create an extension method on
ByteArray which will easily allow us to return a hex encoded string:-
Once we have a hex encoded string at some point we will need convert it back into a
ByteArray. That can be done with the following code:-
Data being stored in or retrieved from a Kademlia network must also have a key of length B. These keys should also be uniformly distributed. There are several ways to guarantee this; the most common is to take a hash, such as the 160 bit SHA1 digest, of the value.