Better understanding Kademlia's XOR Integer Metric

332 views Asked by At

I'm trying to better-grasp Kademlia's XOR distance metric so I've written a small dummy program to try and understand better. I'm also not using a 160-bit number as my key here, but rather a sha256 hash of some user identifier.

Here's my xor distance function. Is this more or less correct? I'm XORing each byte– appending that to a buffer rawBytes and converting that byte buffer into an integer.

func XorDistance(node string, otherNode string) uint64 {
    var rawBytes [32]byte
    for i := 0; i < 32; i++ {
        rawBytes[i] = node[i] ^ otherNode[i]
    }
    distance, _ := binary.Uvarint(rawBytes[:])
    return distance
}
1

There are 1 answers

3
Fred Qian On BEST ANSWER

It's not correct because

You have to use the math/big package for usage like that. Here is my revised version of your snippet:

func xorDistance(node string, otherNode string) *big.Int {
    var rawBytes [32]byte
    for i := 0; i < 32; i++ {
        rawBytes[i] = node[i] ^ otherNode[i]
    }
    return big.NewInt(0).SetBytes(rawBytes[:])
}