xor.go 1.43 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3 4 5 6
package keyspace

import (
	"bytes"
	"crypto/sha256"
	"math/big"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7

George Antoniadis's avatar
George Antoniadis committed
8
	u "github.com/ipfs/go-ipfs-util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
)

// XORKeySpace is a KeySpace which:
// - normalizes identifiers using a cryptographic hash (sha256)
// - measures distance by XORing keys together
var XORKeySpace = &xorKeySpace{}
var _ KeySpace = XORKeySpace // ensure it conforms

type xorKeySpace struct{}

// Key converts an identifier into a Key in this space.
func (s *xorKeySpace) Key(id []byte) Key {
	hash := sha256.Sum256(id)
	key := hash[:]
	return Key{
		Space:    s,
		Original: id,
26
		Bytes:    key,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
27 28 29 30 31
	}
}

// Equal returns whether keys are equal in this key space
func (s *xorKeySpace) Equal(k1, k2 Key) bool {
32
	return bytes.Equal(k1.Bytes, k2.Bytes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
33 34 35 36 37
}

// Distance returns the distance metric in this key space
func (s *xorKeySpace) Distance(k1, k2 Key) *big.Int {
	// XOR the keys
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38
	k3 := u.XOR(k1.Bytes, k2.Bytes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
39 40 41 42 43 44 45 46

	// interpret it as an integer
	dist := big.NewInt(0).SetBytes(k3)
	return dist
}

// Less returns whether the first key is smaller than the second.
func (s *xorKeySpace) Less(k1, k2 Key) bool {
47 48
	a := k1.Bytes
	b := k2.Bytes
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
	for i := 0; i < len(a); i++ {
		if a[i] != b[i] {
			return a[i] < b[i]
		}
	}
	return true
}

// ZeroPrefixLen returns the number of consecutive zeroes in a byte slice.
func ZeroPrefixLen(id []byte) int {
	for i := 0; i < len(id); i++ {
		for j := 0; j < 8; j++ {
			if (id[i]>>uint8(7-j))&0x1 != 0 {
				return i*8 + j
			}
		}
	}
	return len(id) * 8
}