Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

murmur3.gno

6.36 Kb · 176 lines
  1// Package murmur3 implements MurmurHash3 x86_32, Austin Appleby's
  2// non-cryptographic hash, as a pure, reusable package.
  3//
  4// The function reads the input four bytes at a time. Each block is scrambled
  5// by two odd constants and a rotate, mixed into the accumulator, and the
  6// accumulator is itself rotated and run through a multiply-add. The leftover
  7// one to three bytes take an abbreviated version of the same scramble, the
  8// length is folded in, and a final avalanche of shift-xor-multiply spreads
  9// every input bit over every output bit. That last stage is why flipping one
 10// letter changes the whole result rather than a corner of it.
 11//
 12// What it is for on chain: bucketing. Spreading keys over a fixed number of
 13// shards, sizing a sketch, picking a deterministic slot. [Bucket] is that use
 14// spelled out.
 15//
 16// What it is NOT for: anything an adversary chooses the input to. MurmurHash3
 17// is trivially invertible and collisions can be generated on demand, so a
 18// hash table keyed by caller-supplied strings can be driven into its worst
 19// case by anyone who wants to. It is not a commitment, not a signature, and
 20// not a substitute for a cryptographic digest.
 21//
 22// Correctness here rests on [Verification], the SMHasher self-test: it hashes
 23// 256 keys of growing length under 256 different seeds and hashes the results,
 24// which pins every constant, every tail branch and the byte order in one
 25// 32-bit number.
 26//
 27// A live demo of this package is at
 28// [r/moul/x/daily/murmur3demo](/r/moul/x/daily/murmur3demo/v0).
 29package murmur3
 30
 31import "math/bits"
 32
 33// The two block-scramble constants, and the two avalanche multipliers. Odd,
 34// and chosen by search rather than derived: changing any of them gives a
 35// different function, not a worse one, which is why [Verification] exists.
 36const (
 37	c1 = 0xcc9e2d51
 38	c2 = 0x1b873593
 39
 40	m1 = 0x85ebca6b
 41	m2 = 0xc2b2ae35
 42)
 43
 44// Sum32 returns the MurmurHash3 x86_32 hash of s with seed 0.
 45func Sum32(s string) uint32 { return Sum32Seed(s, 0) }
 46
 47// Sum32Seed returns the MurmurHash3 x86_32 hash of s under the given seed.
 48//
 49// The seed re-keys the entire function: the same input under two seeds gives
 50// two unrelated results. That is what makes a family of independent hashes out
 51// of one function, which is what a Bloom filter or a count-min sketch needs.
 52func Sum32Seed(s string, seed uint32) uint32 {
 53	h := seed
 54	n := len(s)
 55	nblocks := n / 4
 56
 57	for i := 0; i < nblocks; i++ {
 58		j := i * 4
 59		// Little-endian, which is the reference implementation's byte order
 60		// and part of what Verification pins.
 61		k := uint32(s[j]) | uint32(s[j+1])<<8 | uint32(s[j+2])<<16 | uint32(s[j+3])<<24
 62		h ^= scramble(k)
 63		h = bits.RotateLeft32(h, 13)
 64		h = h*5 + 0xe6546b64
 65	}
 66
 67	// The tail: one to three bytes that do not fill a block. They are
 68	// scrambled but never mixed into the rotate-multiply-add, so the tail
 69	// contributes less than a full block would. That asymmetry is in the
 70	// reference too.
 71	var k uint32
 72	switch n - nblocks*4 {
 73	case 3:
 74		k ^= uint32(s[nblocks*4+2]) << 16
 75		fallthrough
 76	case 2:
 77		k ^= uint32(s[nblocks*4+1]) << 8
 78		fallthrough
 79	case 1:
 80		k ^= uint32(s[nblocks*4])
 81		h ^= scramble(k)
 82	}
 83
 84	// Folding the length in is what keeps "a" and "a\x00" apart.
 85	h ^= uint32(n)
 86	return avalanche(h)
 87}
 88
 89// scramble applies the per-block mix shared by the main loop and the tail.
 90func scramble(k uint32) uint32 {
 91	k *= c1
 92	k = bits.RotateLeft32(k, 15)
 93	k *= c2
 94	return k
 95}
 96
 97// avalanche is the finalizer: it spreads every input bit across every output
 98// bit, so two inputs differing by one bit give results that look unrelated.
 99func avalanche(h uint32) uint32 {
100	h ^= h >> 16
101	h *= m1
102	h ^= h >> 13
103	h *= m2
104	h ^= h >> 16
105	return h
106}
107
108// Hex renders a hash as eight lowercase hex digits, zero-padded, which is how
109// Murmur results are conventionally shown.
110func Hex(h uint32) string {
111	const digits = "0123456789abcdef"
112	var b [8]byte
113	for i := 7; i >= 0; i-- {
114		b[i] = digits[h&0xF]
115		h >>= 4
116	}
117	return string(b[:])
118}
119
120// SumHex is Sum32 rendered with Hex.
121func SumHex(s string) string { return Hex(Sum32(s)) }
122
123// MaxBuckets is the largest shard count [Bucket] can spread over evenly: the
124// hash is 32 bits, so it names 2^32 slots and no more.
125const MaxBuckets = 1 << 32
126
127// Bucket returns a shard index in [0, n) for s, or -1 when n is not positive.
128//
129// This is the thing the hash is actually good for: a deterministic, evenly
130// spread slot for a key, with no storage and no ordering. Do not use it where
131// the key comes from someone with a reason to collide.
132//
133// The spread is even only up to [MaxBuckets] shards, and that ceiling is the
134// hash, not the arithmetic: 32 bits of output cannot name more than 2^32
135// distinct slots. An n above it is accepted and answered in range, but every
136// index from 2^32 upwards is unreachable, so roughly the top half of a
137// 2^33-way split would never receive a key. Nothing here rejects such an n,
138// because a shard count that large is a caller bug and a panic deep inside a
139// Render is a worse way to learn about it than a skewed table.
140//
141// The remainder is taken in uint64 rather than uint32 on purpose: gno's int is
142// 64-bit, so a caller may pass an n above 2^32, and narrowing the divisor
143// would turn 1<<32 into a divide by zero on a value the first line of this
144// comment promises to accept.
145//
146// For an n below the ceiling that does not divide 2^32 the low buckets are
147// very slightly favoured, by at most one key in 2^32. That bias is irrelevant
148// for spreading and would matter for sampling; this is the spreading function.
149func Bucket(s string, n int) int {
150	if n <= 0 {
151		return -1
152	}
153	return int(uint64(Sum32(s)) % uint64(n))
154}
155
156// Verification returns the SMHasher verification value for this hash, which is
157// 0xB0F57EE3 for a correct MurmurHash3 x86_32.
158//
159// The procedure is SMHasher's: hash the keys {0}, {0,1}, {0,1,2}, ... up to 255
160// bytes, the key of length i under seed 256-i, write each 32-bit result
161// little-endian into one buffer, then hash that buffer with seed 0. It is a
162// self-test rather than a hash of anything useful, and it is the reason this
163// package can claim to be the same function as everyone else's.
164func Verification() uint32 {
165	key := make([]byte, 256)
166	hashes := make([]byte, 256*4)
167	for i := 0; i < 256; i++ {
168		key[i] = byte(i)
169		h := Sum32Seed(string(key[:i]), uint32(256-i))
170		hashes[i*4] = byte(h)
171		hashes[i*4+1] = byte(h >> 8)
172		hashes[i*4+2] = byte(h >> 16)
173		hashes[i*4+3] = byte(h >> 24)
174	}
175	return Sum32(string(hashes))
176}