github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/routing/kbucket/util.go (about) 1 package kbucket 2 3 import ( 4 "bytes" 5 "crypto/sha256" 6 "errors" 7 8 key "github.com/ipfs/go-ipfs/blocks/key" 9 peer "github.com/ipfs/go-ipfs/p2p/peer" 10 ks "github.com/ipfs/go-ipfs/routing/keyspace" 11 u "github.com/ipfs/go-ipfs/util" 12 ) 13 14 // Returned if a routing table query returns no results. This is NOT expected 15 // behaviour 16 var ErrLookupFailure = errors.New("failed to find any peer in table") 17 18 // ID for IpfsDHT is in the XORKeySpace 19 // 20 // The type dht.ID signifies that its contents have been hashed from either a 21 // peer.ID or a util.Key. This unifies the keyspace 22 type ID []byte 23 24 func (id ID) equal(other ID) bool { 25 return bytes.Equal(id, other) 26 } 27 28 func (id ID) less(other ID) bool { 29 a := ks.Key{Space: ks.XORKeySpace, Bytes: id} 30 b := ks.Key{Space: ks.XORKeySpace, Bytes: other} 31 return a.Less(b) 32 } 33 34 func xor(a, b ID) ID { 35 return ID(u.XOR(a, b)) 36 } 37 38 func commonPrefixLen(a, b ID) int { 39 return ks.ZeroPrefixLen(u.XOR(a, b)) 40 } 41 42 // ConvertPeerID creates a DHT ID by hashing a Peer ID (Multihash) 43 func ConvertPeerID(id peer.ID) ID { 44 hash := sha256.Sum256([]byte(id)) 45 return hash[:] 46 } 47 48 // ConvertKey creates a DHT ID by hashing a local key (String) 49 func ConvertKey(id key.Key) ID { 50 hash := sha256.Sum256([]byte(id)) 51 return hash[:] 52 } 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 { 56 aid := ConvertPeerID(a) 57 bid := ConvertPeerID(b) 58 tgt := ConvertKey(key) 59 adist := xor(aid, tgt) 60 bdist := xor(bid, tgt) 61 62 return adist.less(bdist) 63 }