Getting the CID from DHT related communication

This is a follow up on my question here How to listen to DHT communication where I was asking how to listen to DHT communication

Now I have been able to get to the point where I see the relevant log entries in peer B, when peer A adds content and announces it.

A snippet of the log entry looks like this:

{"level":"debug","ts":"2020-05-23T17:14:08.538Z","logger":"dht","caller":"go-libp2p-kad-dht@v0.7.10/handlers.go:347","msg":"adding provider%!(EXTRA string=from, peer.ID=PEERID, string=key, []uint8=[18 32 2 235 187 139 82 142 51 24 132 209 229 250 54 112 184 196 222 196 41 240 97 130 225 97 195 246 34 239 44 98 36 35])"}

I was able to use the module "github.com/multiformats/go-base32" to convert the []uint8 to string. Basically doing something like this:

fmt.Println(base32.RawStdEncoding.EncodeToString(theUnit8Value))
// prints CIQHB3C4SGQQNA63QXFP55NQEMVKCXUMXYD5RBAG4GCKEGBQYUQQW3Y

The problem is, I can’t seem to be able to retrieve the CID of the content added from the above.

Anyone knows how I can do this? Basically get an handle on CID based on the DHT announcement

Dug around a bit more and found a way to interpret the value. I figured out it would probably be in multihash, so I looked into the github.com/multiformats/go-multihash module.

Noticed it has a Cast function that takes a byte array and transfer into a MultiHash. Also saw that the Multihash has a B58String function.

So basically I just had to do something like:

cast, _ := mh.Cast(stuff)
fmt.Println(cast.B58String())   

And I got the value in the recognisable format.

@dadepo just wanted to make sure you were aware that this conversion will only generically work for CIDv0 data, since as you noticed the key for provider records being stored in the DHT is actually the multihash and not the full CID of the data. https://github.com/multiformats/cid

Depending on why you want to get the CID and what you’re trying to do with it there are potential options for dealing with CIDv1 as well.