Open History to see the last commit
1/*
2 * Implementation of murmur hash based on the Composites polyfill implementation:
3 * https://github.com/tc39/proposal-composites
4 */
5
6const RANDOM_SEED = randomHash()
7const STRING_MARKER = randomHash()
8const BIG_INT_MARKER = randomHash()
9const NEG_BIG_INT_MARKER = randomHash()
10const SYMBOL_MARKER = randomHash()
11
12type SymbolIdStore = {
13 get: (key: symbol) => number | undefined
14 set: (key: symbol, value: number) => unknown
15}
16
17const symbolIds = createSymbolIdStore()
18const registeredSymbolIds = new Map<string, number>()
19let nextSymbolId = 0
20
21export function getSymbolIdentity(symbol: symbol): number {
22 const registeredKey = Symbol.keyFor(symbol)
23 if (registeredKey !== undefined) {
24 let id = registeredSymbolIds.get(registeredKey)
25 if (id === undefined) {
26 id = ++nextSymbolId
27 registeredSymbolIds.set(registeredKey, id)
28 }
29 return id
30 }
31
32 let id = symbolIds.get(symbol)
33 if (id === undefined) {
34 id = ++nextSymbolId
35 symbolIds.set(symbol, id)
36 }
37 return id
38}
39
40function createSymbolIdStore(): SymbolIdStore {
41 const weakIds = new WeakMap<object, number>() as unknown as SymbolIdStore
42 const probe = Symbol()
43
44 try {
45 weakIds.set(probe, 0)
46 if (weakIds.get(probe) === 0) return weakIds
47 } catch {
48 // Older runtimes reject symbols as weak keys. Retain them rather than
49 // merge distinct symbols and corrupt differential state.
50 }
51
52 return new Map<symbol, number>()
53}
54
55export type Hash = number
56
57export function randomHash() {
58 return (Math.random() * (2 ** 31 - 1)) >>> 0
59}
60
61export interface Hasher {
62 update: (val: symbol | string | number | bigint) => void
63 digest: () => number
64}
65
66// Allocate this once, outside the hot path
67const dv = new DataView(new ArrayBuffer(8))
68
69/**
70 * This implementation of Murmur hash uses a random initial seed and random markers.
71 * This means that hashes aren't deterministic across app restarts.
72 * This is intentional in the composites polyfill to be resistent to hash-flooding attacks
73 * where malicious users would precompute lots of different objects whose hashes collide with each other.
74 *
75 * Currently, for ts/db-ivm this is fine because we don't persist client state.
76 * However, when we will introduce persistence we will either need to store the seeds or remove the randomness
77 * to ensure deterministic hashes across app restarts.
78 */
79export class MurmurHashStream implements Hasher {
80 private hash: number = RANDOM_SEED
81 private length = 0
82 private carry = 0
83 private carryBytes = 0
84
85 private _mix(k1: number): void {
86 k1 = Math.imul(k1, 0xcc9e2d51)
87 k1 = (k1 << 15) | (k1 >>> 17)
88 k1 = Math.imul(k1, 0x1b873593)
89 this.hash ^= k1
90 this.hash = (this.hash << 13) | (this.hash >>> 19)
91 this.hash = Math.imul(this.hash, 5) + 0xe6546b64
92 }
93
94 writeByte(byte: number): void {
95 this.carry |= (byte & 0xff) << (8 * this.carryBytes)
96 this.carryBytes++
97 this.length++
98
99 if (this.carryBytes === 4) {
100 this._mix(this.carry >>> 0)
101 this.carry = 0
102 this.carryBytes = 0
103 }
104 }
105
106 /** Write four bytes, low byte first, as four `writeByte` calls would. */
107 private writeWord(word: number): void {
108 this.length += 4
109 if (this.carryBytes === 0) {
110 this._mix(word >>> 0)
111 return
112 }
113 // The carry's bytes come first. The word's low bytes complete that block,
114 // and its high bytes become the new carry, which keeps its byte count.
115 const shift = 8 * this.carryBytes
116 this._mix((this.carry | (word << shift)) >>> 0)
117 this.carry = word >>> (32 - shift)
118 }
119
120 update(chunk: symbol | string | number | bigint): void {
121 switch (typeof chunk) {
122 case `symbol`: {
123 this.update(SYMBOL_MARKER)
124 this.update(getSymbolIdentity(chunk))
125 return
126 }
127 case `string`:
128 this.update(STRING_MARKER)
129 {
130 // Each code unit is two bytes, so a pair of them is one word.
131 const pairs = chunk.length - (chunk.length % 2)
132 for (let i = 0; i < pairs; i += 2) {
133 this.writeWord(
134 chunk.charCodeAt(i) | (chunk.charCodeAt(i + 1) << 16),
135 )
136 }
137 if (pairs < chunk.length) {
138 const code = chunk.charCodeAt(pairs)
139 this.writeByte(code & 0xff)
140 this.writeByte((code >>> 8) & 0xff)
141 }
142 }
143 return
144 case `number`:
145 dv.setFloat64(0, chunk, true) // fixed little-endian
146 this.writeWord(dv.getUint32(0, true))
147 this.writeWord(dv.getUint32(4, true))
148 return
149 case `bigint`: {
150 let value = chunk
151 if (value < 0n) {
152 value = -value
153 this.update(NEG_BIG_INT_MARKER)
154 } else {
155 this.update(BIG_INT_MARKER)
156 }
157 while (value > 0n) {
158 this.writeByte(Number(value & 0xffn))
159 value >>= 8n
160 }
161 if (chunk === 0n) this.writeByte(0)
162 return
163 }
164 default:
165 throw new TypeError(`Unsupported input type: ${typeof chunk}`)
166 }
167 }
168
169 digest(): number {
170 if (this.carryBytes > 0) {
171 let k1 = this.carry >>> 0
172 k1 = Math.imul(k1, 0xcc9e2d51)
173 k1 = (k1 << 15) | (k1 >>> 17)
174 k1 = Math.imul(k1, 0x1b873593)
175 this.hash ^= k1
176 }
177
178 this.hash ^= this.length
179 this.hash ^= this.hash >>> 16
180 this.hash = Math.imul(this.hash, 0x85ebca6b)
181 this.hash ^= this.hash >>> 13
182 this.hash = Math.imul(this.hash, 0xc2b2ae35)
183 this.hash ^= this.hash >>> 16
184
185 return this.hash >>> 0
186 }
187}