Commit c54128a5 authored by Steven Allen's avatar Steven Allen

handle paths as DHT keys

fixes ipfs/go-ipfs#4237
parent a68a53a0
......@@ -2,6 +2,8 @@ package dht
import (
"context"
"fmt"
"strings"
cid "github.com/ipfs/go-cid"
logging "github.com/ipfs/go-log"
......@@ -29,13 +31,39 @@ func toPeerInfos(ps []peer.ID) []*pstore.PeerInfo {
return out
}
func tryFormatLoggableKey(k string) (string, error) {
if len(k) == 0 {
return "", fmt.Errorf("loggableKey is empty")
}
var proto, cstr string
if k[0] == '/' {
// it's a path (probably)
protoEnd := strings.IndexByte(k[1:], '/')
if protoEnd < 0 {
return k, fmt.Errorf("loggableKey starts with '/' but is not a path: %x", k)
}
proto = k[1 : protoEnd+1]
cstr = k[protoEnd+2:]
} else {
proto = "provider"
cstr = k
}
c, err := cid.Cast([]byte(cstr))
if err != nil {
return "", fmt.Errorf("loggableKey could not cast key to a CID: %x %v", k, err)
}
return fmt.Sprintf("/%s/%s", proto, c.String()), nil
}
func loggableKey(k string) logging.LoggableMap {
cid, err := cid.Cast([]byte(k))
newKey, err := tryFormatLoggableKey(k)
if err != nil {
log.Errorf("loggableKey could not cast key: %x %v", k, err)
log.Error(err)
} else {
k = cid.String()
k = newKey
}
return logging.LoggableMap{
"key": k,
}
......
package dht
import (
"testing"
cid "github.com/ipfs/go-cid"
)
func TestLoggableKey(t *testing.T) {
c, err := cid.Decode("QmfUvYQhL2GinafMbPDYz7VFoZv4iiuLuR33aRsPurXGag")
if err != nil {
t.Fatal(err)
}
k, err := tryFormatLoggableKey("/proto/" + string(c.Bytes()))
if err != nil {
t.Errorf("failed to format key 1: %s", err)
}
if k != "/proto/"+c.String() {
t.Error("expected path to be preserved as a loggable key")
}
k, err = tryFormatLoggableKey(string(c.Bytes()))
if err != nil {
t.Errorf("failed to format key 2: %s", err)
}
if k != "/provider/"+c.String() {
t.Error("expected cid to be formatted as a loggable key")
}
for _, s := range []string{"bla bla", "/bla", "/bla/asdf", ""} {
if _, err := tryFormatLoggableKey(s); err == nil {
t.Errorf("expected to fail formatting: %s", s)
}
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment