util.go 1.4 KB
Newer Older
1 2 3 4 5
package dht

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

	peer "github.com/jbenet/go-ipfs/peer"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9
	ks "github.com/jbenet/go-ipfs/routing/keyspace"
10 11 12
	u "github.com/jbenet/go-ipfs/util"
)

13 14 15 16
// 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
17
// ID for IpfsDHT is in the XORKeySpace
18 19 20 21 22
//
// 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

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

27
func (id ID) less(other ID) bool {
28 29
	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
30
	return a.Less(b)
31 32 33
}

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

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

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

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

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

61
	return adist.less(bdist)
62
}