util.go 1.53 KB
Newer Older
1
package kbucket
2 3 4 5

import (
	"bytes"
	"crypto/sha256"
6
	"errors"
7

8
	key "github.com/ipfs/go-ipfs/blocks/key"
9
	ks "github.com/ipfs/go-ipfs/routing/keyspace"
10
	peer "gx/ipfs/QmSN2ELGRp4T9kjqiSsSNJRUeR9JKXzQEgwe1HH3tdSGbC/go-libp2p/p2p/peer"
11
	u "gx/ipfs/QmZNVWh8LLjAavuQ2JXuFmuYH3C11xo988vSgp7UQrTRj1/go-ipfs-util"
12 13
)

14 15 16 17
// 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")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18
// ID for IpfsDHT is in the XORKeySpace
19 20 21 22 23
//
// 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

24
func (id ID) equal(other ID) bool {
25 26 27
	return bytes.Equal(id, other)
}

28
func (id ID) less(other ID) bool {
29 30
	a := ks.Key{Space: ks.XORKeySpace, Bytes: id}
	b := ks.Key{Space: ks.XORKeySpace, Bytes: other}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
31
	return a.Less(b)
32 33 34
}

func xor(a, b ID) ID {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
35
	return ID(u.XOR(a, b))
36 37
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38
func commonPrefixLen(a, b ID) int {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
39
	return ks.ZeroPrefixLen(u.XOR(a, b))
40 41
}

Chas Leichner's avatar
Chas Leichner committed
42 43
// ConvertPeerID creates a DHT ID by hashing a Peer ID (Multihash)
func ConvertPeerID(id peer.ID) ID {
44
	hash := sha256.Sum256([]byte(id))
45 46 47
	return hash[:]
}

Chas Leichner's avatar
Chas Leichner committed
48
// ConvertKey creates a DHT ID by hashing a local key (String)
49
func ConvertKey(id key.Key) ID {
50 51 52
	hash := sha256.Sum256([]byte(id))
	return hash[:]
}
53

54
// Closer returns true if a is closer to key than b is
55
func Closer(a, b peer.ID, key key.Key) bool {
Chas Leichner's avatar
Chas Leichner committed
56 57 58
	aid := ConvertPeerID(a)
	bid := ConvertPeerID(b)
	tgt := ConvertKey(key)
59 60 61
	adist := xor(aid, tgt)
	bdist := xor(bid, tgt)

62
	return adist.less(bdist)
63
}