1
0
mirror of https://github.com/ipfs/kubo.git synced 2025-09-08 22:57:50 +08:00
Files
kubo/routing/kbucket/util.go
Jeromy d7dab3afea Use gx vendored go-ipfs-utils where possible
For the rest of the packages in util, move them to thirdparty
and update the references. util is gone!

License: MIT
Signed-off-by: Jeromy <jeromyj@gmail.com>
2016-02-12 17:21:40 -08:00

64 lines
1.5 KiB
Go

package kbucket
import (
"bytes"
"crypto/sha256"
"errors"
key "github.com/ipfs/go-ipfs/blocks/key"
ks "github.com/ipfs/go-ipfs/routing/keyspace"
u "gx/ipfs/QmZNVWh8LLjAavuQ2JXuFmuYH3C11xo988vSgp7UQrTRj1/go-ipfs-util"
peer "gx/ipfs/QmUBogf4nUefBjmYjn6jfsfPJRkmDGSeMhNj4usRKq69f4/go-libp2p/p2p/peer"
)
// Returned if a routing table query returns no results. This is NOT expected
// behaviour
var ErrLookupFailure = errors.New("failed to find any peer in table")
// ID for IpfsDHT is in the XORKeySpace
//
// The type dht.ID signifies that its contents have been hashed from either a
// peer.ID or a util.Key. This unifies the keyspace
type ID []byte
func (id ID) equal(other ID) bool {
return bytes.Equal(id, other)
}
func (id ID) less(other ID) bool {
a := ks.Key{Space: ks.XORKeySpace, Bytes: id}
b := ks.Key{Space: ks.XORKeySpace, Bytes: other}
return a.Less(b)
}
func xor(a, b ID) ID {
return ID(u.XOR(a, b))
}
func commonPrefixLen(a, b ID) int {
return ks.ZeroPrefixLen(u.XOR(a, b))
}
// ConvertPeerID creates a DHT ID by hashing a Peer ID (Multihash)
func ConvertPeerID(id peer.ID) ID {
hash := sha256.Sum256([]byte(id))
return hash[:]
}
// ConvertKey creates a DHT ID by hashing a local key (String)
func ConvertKey(id key.Key) ID {
hash := sha256.Sum256([]byte(id))
return hash[:]
}
// Closer returns true if a is closer to key than b is
func Closer(a, b peer.ID, key key.Key) bool {
aid := ConvertPeerID(a)
bid := ConvertPeerID(b)
tgt := ConvertKey(key)
adist := xor(aid, tgt)
bdist := xor(bid, tgt)
return adist.less(bdist)
}