package lattice import ( "encoding/binary" "math/bits" "github.com/zeebo/xxh3" ) const ( fnvOffset64 uint64 = 14695981039346656037 fnvPrime64 uint64 = 1099511628211 ) // HashBytes is iskra/hash.mx HashBytes: FNV-1a truncated to 56 bits. This, not // SipHash, is what the word, segment and bigram keys in existing .iskr files // were made with. func HashBytes(data []byte) uint64 { h := fnvOffset64 for _, c := range data { h ^= uint64(c) h *= fnvPrime64 } return h >> 8 } // HashKey is iskradb/lattice.mx HashKey: the low 64 bits of SipHash-2-4-128 // under moxie's default key, ported from moxie's src/crypto/siphash. // // It is not the low half of standard SipHash-2-4: moxie's Sum128 XORs 0xee into // v1 at initialization and 0xee into v2 before the first finalization. Any // port that reaches for a siphash library gets different keys. func HashKey(data []byte) Key { lo, _ := sipSum128(0x736f6d6570736575, 0x646f72616e646f6d, data) return Key(lo) } func sipSum128(k0, k1 uint64, p []byte) (lo, hi uint64) { v0 := k0 ^ 0x736f6d6570736575 v1 := k1 ^ 0x646f72616e646f6d v2 := k0 ^ 0x6c7967656e657261 v3 := k1 ^ 0x7465646279746573 v1 ^= 0xee length := uint64(len(p)) blocks := len(p) / 8 for i := 0; i < blocks; i++ { m := binary.LittleEndian.Uint64(p[i*8:]) v3 ^= m v0, v1, v2, v3 = sipRound(v0, v1, v2, v3) v0, v1, v2, v3 = sipRound(v0, v1, v2, v3) v0 ^= m } last := length << 56 for i, c := range p[blocks*8:] { last |= uint64(c) << (uint(i) * 8) } v3 ^= last v0, v1, v2, v3 = sipRound(v0, v1, v2, v3) v0, v1, v2, v3 = sipRound(v0, v1, v2, v3) v0 ^= last v2 ^= 0xee for i := 0; i < 4; i++ { v0, v1, v2, v3 = sipRound(v0, v1, v2, v3) } lo = v0 ^ v1 ^ v2 ^ v3 v1 ^= 0xdd for i := 0; i < 4; i++ { v0, v1, v2, v3 = sipRound(v0, v1, v2, v3) } hi = v0 ^ v1 ^ v2 ^ v3 return } func sipRound(v0, v1, v2, v3 uint64) (r0, r1, r2, r3 uint64) { v0 += v1 v1 = bits.RotateLeft64(v1, 13) v1 ^= v0 v0 = bits.RotateLeft64(v0, 32) v2 += v3 v3 = bits.RotateLeft64(v3, 16) v3 ^= v2 v0 += v3 v3 = bits.RotateLeft64(v3, 21) v3 ^= v0 v2 += v1 v1 = bits.RotateLeft64(v1, 17) v1 ^= v2 v2 = bits.RotateLeft64(v2, 32) return v0, v1, v2, v3 } // HashWord is the go-ref word hash: xxh3 truncated to 56 bits. No moxie code // ever produced these keys, so nothing on disk was keyed with it. func HashWord(normalized []byte) uint64 { return xxh3.Hash(normalized) >> 8 }