head-selection.test.ts (9605B)
1 import { afterAll, describe, expect, it } from 'vitest'; 2 import { readFileSync } from 'node:fs'; 3 import { finalizeEvent, verifiedSymbol } from 'applesauce-core/helpers'; 4 import { 5 verifyEnvelope, 6 verifiedEnvelopeSnapshot, 7 type VerifiedEnvelope 8 } from '../../src/lib/nostr/verified-envelope.ts'; 9 import { readFoodEvent } from '../../src/lib/contracts/food-availability-v1/read.ts'; 10 import { 11 createPublicHeadCandidate, 12 selectPublicHead, 13 publicHeadSnapshot, 14 publicHeadKey, 15 publicHeadEnvelope, 16 type PublicHead 17 } from '../../src/lib/catalog/heads.ts'; 18 19 const keys: Uint8Array[] = []; 20 afterAll(() => { 21 for (const key of keys) key.fill(0); 22 }); 23 // Ephemeral test-only signing; only verified public wires enter the selector. 24 function author() { 25 const secret = crypto.getRandomValues(new Uint8Array(32)); 26 keys.push(secret); 27 return ( 28 created_at: number, 29 tags: string[][] = [['d', 'stock']], 30 content = 'Same title', 31 kind = 30402 32 ) => 33 JSON.stringify(finalizeEvent({ created_at, tags, content, kind }, secret)); 34 } 35 function proof(raw: string): VerifiedEnvelope { 36 const result = verifyEnvelope(raw); 37 if (!result.ok) throw new Error('Invalid signed test event'); 38 return result.value; 39 } 40 function head(raw: string): PublicHead { 41 const result = createPublicHeadCandidate(proof(raw)); 42 if (!result) throw new Error('Expected public head candidate'); 43 return result; 44 } 45 function fold(raws: string[]) { 46 const known = new Map<string, PublicHead>(); 47 for (const raw of raws) { 48 const candidate = head(raw), 49 key = publicHeadKey(candidate); 50 known.set(key, selectPublicHead(known.get(key), candidate).head); 51 } 52 return [...known.values()].map(publicHeadSnapshot); 53 } 54 describe('signature-verified public coordinate heads', () => { 55 it('owns frozen opaque candidates with exact original proof', () => { 56 const signed = author(), 57 value = proof(signed(10)); 58 const candidate = createPublicHeadCandidate(value)!; 59 expect(Object.keys(candidate)).toEqual([]); 60 expect(Object.isFrozen(candidate)).toBe(true); 61 expect(publicHeadEnvelope(candidate)).toBe(value); 62 expect(publicHeadSnapshot(candidate).id).toBe( 63 verifiedEnvelopeSnapshot(value)!.id 64 ); 65 expect(selectPublicHead(undefined, candidate)).toEqual({ 66 decision: 'applied', 67 head: candidate 68 }); 69 }); 70 it('selects the newest timestamp regardless of arrival order', () => { 71 const signed = author(), 72 old = signed(10), 73 newest = signed(20); 74 const expected = publicHeadSnapshot(head(newest)); 75 expect(fold([old, newest])).toEqual([expected]); 76 expect(fold([newest, old])).toEqual([expected]); 77 }); 78 it('uses the lower canonical event ID for equal timestamps in both orders', () => { 79 const signed = author(), 80 a = head(signed(10, [['d', 'stock']], 'a')), 81 b = head(signed(10, [['d', 'stock']], 'b')); 82 const [winner, loser] = 83 publicHeadSnapshot(a).id < publicHeadSnapshot(b).id ? [a, b] : [b, a]; 84 expect(selectPublicHead(loser, winner)).toEqual({ 85 decision: 'applied', 86 head: winner 87 }); 88 expect(selectPublicHead(winner, loser)).toEqual({ 89 decision: 'higher_id', 90 head: winner 91 }); 92 }); 93 it('retains one head across fresh duplicate observations', () => { 94 const signed = author(), 95 raw = signed(10), 96 a = head(raw), 97 b = head(raw); 98 expect(a).not.toBe(b); 99 expect(selectPublicHead(a, b)).toEqual({ decision: 'duplicate', head: a }); 100 expect(fold([raw, raw, raw])).toHaveLength(1); 101 }); 102 it('keeps distinct authors and identifiers despite identical titles', () => { 103 const a = author(), 104 b = author(); 105 const raws = [a(10), b(10), a(10, [['d', 'other']])]; 106 expect(fold(raws)).toHaveLength(3); 107 const current = head(raws[0]), 108 candidate = head(raws[1]); 109 expect(selectPublicHead(current, candidate)).toEqual({ 110 decision: 'coordinate_mismatch', 111 head: current 112 }); 113 expect(publicHeadKey(current)).not.toBe(publicHeadKey(candidate)); 114 }); 115 it('preserves raw Unicode, case, whitespace and colon identity', () => { 116 const signed = author(); 117 const ids = [ 118 'Stock', 119 'stock', 120 ' stock ', 121 'a:b', 122 '\ufeffstock', 123 'é', 124 'e\u0301' 125 ]; 126 const selected = fold( 127 ids.map((identifier) => signed(10, [['d', identifier]])) 128 ); 129 expect(selected.map((value) => value.identifier)).toEqual(ids); 130 expect(new Set(selected.map((value) => value.identifier)).size).toBe( 131 ids.length 132 ); 133 }); 134 it('uses the first d even when later d tags disagree', () => { 135 const signed = author(); 136 expect( 137 publicHeadSnapshot( 138 head( 139 signed(10, [ 140 ['d', 'first'], 141 ['d', 'second'] 142 ]) 143 ) 144 ).identifier 145 ).toBe('first'); 146 }); 147 it('uses the empty address for missing empty or malformed first d values', () => { 148 const signed = author(); 149 const cases = [[], [['d', '']], [['d']], [['d'], ['d', 'later']]]; 150 const candidates = cases.map((tags, index) => 151 head(signed(10 + index, tags)) 152 ); 153 expect(new Set(candidates.map(publicHeadKey)).size).toBe(1); 154 for (const candidate of candidates) 155 expect(publicHeadSnapshot(candidate).identifier).toBe(''); 156 }); 157 it('does not apply focused identifier limits before generic head selection', () => { 158 const signed = author(), 159 raw = signed(20, [['d', 'x'.repeat(300)]]); 160 expect(publicHeadSnapshot(head(raw)).identifier).toBe('x'.repeat(300)); 161 expect(readFoodEvent(raw).outcome).not.toBe('admitted'); 162 }); 163 it('supports approved replaceable public metadata without d identity', () => { 164 const signed = author(); 165 for (const kind of [0, 10050]) { 166 const a = head(signed(10, [['d', 'first']], '{}', kind)); 167 const b = head(signed(20, [['d', 'second']], '{}', kind)); 168 expect(publicHeadSnapshot(a).identifier).toBeNull(); 169 expect(publicHeadKey(a)).toBe(publicHeadKey(b)); 170 expect(selectPublicHead(a, b).head).toBe(b); 171 } 172 expect( 173 fold([signed(10, [], '{}', 0), signed(10, [], '', 10050), signed(10)]) 174 ).toHaveLength(3); 175 }); 176 it('excludes regular deletion, unapproved public, private and connection events', () => { 177 const signed = author(); 178 for (const kind of [5, 1, 1059, 22242, 30023]) 179 expect( 180 createPublicHeadCandidate(proof(signed(10, [], '', kind))) 181 ).toBeUndefined(); 182 }); 183 it('selects a verified incompatible newer product before focused filtering', () => { 184 const corpus = JSON.parse( 185 readFileSync( 186 new URL( 187 '../../../contracts/interop/food_availability/corpus.v1.json', 188 import.meta.url 189 ), 190 'utf8' 191 ) 192 ) as { 193 vectors: { id: string; signed_wires: Record<string, string> }[]; 194 }; 195 const wires = corpus.vectors.find((value) => 196 value.id.endsWith('_032') 197 )!.signed_wires; 198 const base = JSON.parse(wires.previous) as { 199 created_at: number; 200 tags: string[][]; 201 content: string; 202 }; 203 const signed = author(); 204 const oldRaw = signed(base.created_at, base.tags, base.content); 205 const nextRaw = signed( 206 base.created_at + 1, 207 [...base.tags, ['radroots:primary_bin', 'storage']], 208 base.content 209 ); 210 const old = head(oldRaw), 211 newest = head(nextRaw); 212 expect(selectPublicHead(old, newest).head).toBe(newest); 213 expect(readFoodEvent(oldRaw).outcome).toBe('admitted'); 214 expect(readFoodEvent(nextRaw).outcome).not.toBe('admitted'); 215 }); 216 it('rejects forged verification flags and invalid signatures without replacing a good head', () => { 217 const signed = author(), 218 raw = signed(10), 219 current = head(raw); 220 const invalid = JSON.parse(raw) as Record<string | symbol, unknown>; 221 invalid.sig = '0'.repeat(128); 222 invalid[verifiedSymbol] = true; 223 expect(verifyEnvelope(JSON.stringify(invalid)).ok).toBe(false); 224 expect( 225 createPublicHeadCandidate(invalid as unknown as VerifiedEnvelope) 226 ).toBeUndefined(); 227 expect( 228 createPublicHeadCandidate(Object.freeze({}) as VerifiedEnvelope) 229 ).toBeUndefined(); 230 expect(publicHeadSnapshot(current).id).toBe( 231 (JSON.parse(raw) as { id: string }).id 232 ); 233 }); 234 it('exposes detached snapshots and cannot forge either selection operand', () => { 235 const signed = author(), 236 candidate = head(signed(10)); 237 const copy = publicHeadSnapshot(candidate) as { 238 id: string; 239 identifier: string | null; 240 created_at: number; 241 }; 242 copy.id = '0'.repeat(64); 243 copy.identifier = 'changed'; 244 copy.created_at = 99; 245 expect(publicHeadSnapshot(candidate)).not.toMatchObject(copy); 246 expect(() => publicHeadSnapshot({} as PublicHead)).toThrow( 247 'public_head_invalid' 248 ); 249 expect(() => selectPublicHead(candidate, {} as PublicHead)).toThrow( 250 'public_head_invalid' 251 ); 252 expect(() => selectPublicHead({} as PublicHead, candidate)).toThrow( 253 'public_head_invalid' 254 ); 255 }); 256 it('preserves protocol ordering for future and maximum safe timestamps', () => { 257 const signed = author(), 258 a = head(signed(0)), 259 b = head(signed(Number.MAX_SAFE_INTEGER)); 260 expect(selectPublicHead(a, b).head).toBe(b); 261 expect(selectPublicHead(b, a)).toEqual({ decision: 'older', head: b }); 262 const view = verifiedEnvelopeSnapshot(publicHeadEnvelope(b))!; 263 view.tags[0][1] = 'changed'; 264 view.created_at = 0; 265 expect(publicHeadSnapshot(b).created_at).toBe(Number.MAX_SAFE_INTEGER); 266 expect(publicHeadSnapshot(b).identifier).toBe('stock'); 267 }); 268 });