app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

head-state.test.ts (12229B)


      1 import { afterAll, describe, expect, it } from 'vitest';
      2 import { readFileSync } from 'node:fs';
      3 import { finalizeEvent } from 'applesauce-core/helpers';
      4 import {
      5   verifyEnvelope,
      6   type VerifiedEnvelope
      7 } from '../../src/lib/nostr/verified-envelope.ts';
      8 import {
      9   createPublicHeadCandidate,
     10   publicHeadSnapshot
     11 } from '../../src/lib/catalog/heads.ts';
     12 import { assessFutureTimestamp } from '../../src/lib/catalog/clock-policy.ts';
     13 import {
     14   createFoodHeadState,
     15   advanceFoodHeadState,
     16   refreshFoodHeadState,
     17   foodHeadStateSnapshot,
     18   foodHeadStateHead,
     19   type FoodHeadState
     20 } from '../../src/lib/catalog/head-state.ts';
     21 
     22 const corpus = JSON.parse(
     23   readFileSync(
     24     new URL(
     25       '../../../contracts/interop/food_availability/corpus.v1.json',
     26       import.meta.url
     27     ),
     28     'utf8'
     29   )
     30 ) as { vectors: { id: string; signed_wires: Record<string, string> }[] };
     31 const base = JSON.parse(
     32   corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires.previous
     33 ) as { tags: string[][]; content: string; created_at: number };
     34 const keys: Uint8Array[] = [];
     35 afterAll(() => {
     36   for (const key of keys) key.fill(0);
     37 });
     38 function fixture() {
     39   const key = crypto.getRandomValues(new Uint8Array(32));
     40   keys.push(key);
     41   const signed = (
     42     time = base.created_at,
     43     tags = base.tags,
     44     content = base.content,
     45     kind = 30402
     46   ) =>
     47     JSON.stringify(
     48       finalizeEvent({ kind, created_at: time, tags, content }, key)
     49     );
     50   const proof = (raw: string) => {
     51     const result = verifyEnvelope(raw);
     52     if (!result.ok) throw new Error('Invalid signed test event');
     53     return result.value;
     54   };
     55   const candidate = (raw: string) => {
     56     const value = createPublicHeadCandidate(proof(raw));
     57     if (!value) throw new Error('Expected public head');
     58     return value;
     59   };
     60   let now = base.created_at;
     61   let calls = 0;
     62   const clock = {
     63     nowSeconds: () => {
     64       calls++;
     65       return now;
     66     }
     67   };
     68   const state = createFoodHeadState(candidate(signed()), clock);
     69   return {
     70     signed,
     71     proof,
     72     candidate,
     73     state,
     74     clock,
     75     setNow: (v: number) => {
     76       now = v;
     77     },
     78     calls: () => calls
     79   };
     80 }
     81 function status(value: string) {
     82   return base.tags.map((t) => (t[0] === 'status' ? ['status', value] : [...t]));
     83 }
     84 describe('verified food head display uncertainty', () => {
     85   it('reserves a new winner before its clock callback and never overwrites a still newer accepted head', () => {
     86     const f = fixture();
     87     const newer = f.proof(f.signed(base.created_at + 2, status('unknown')));
     88     let armed = false;
     89     let entered = false;
     90     const clock = {
     91       nowSeconds: () => {
     92         if (armed && !entered) {
     93           entered = true;
     94           advanceFoodHeadState(state, newer);
     95         }
     96         return base.created_at;
     97       }
     98     };
     99     const state: FoodHeadState = createFoodHeadState(
    100       foodHeadStateHead(f.state),
    101       clock
    102     );
    103     armed = true;
    104     advanceFoodHeadState(state, f.proof(f.signed(base.created_at + 1)));
    105     expect(foodHeadStateSnapshot(state)).toMatchObject({
    106       display: 'unsupported',
    107       head: { created_at: base.created_at + 2 }
    108     });
    109     expect(foodHeadStateSnapshot(state).food).toBeUndefined();
    110     expect(publicHeadSnapshot(foodHeadStateHead(state)).created_at).toBe(
    111       base.created_at + 2
    112     );
    113   });
    114   it('cannot publish an older focused assessment after clock callback accepts a newer unsupported winner', () => {
    115     const f = fixture();
    116     const newer = f.proof(f.signed(base.created_at + 2, status('unknown')));
    117     let armed = false;
    118     let entered = false;
    119     const clock = {
    120       nowSeconds: () => {
    121         if (armed && !entered) {
    122           entered = true;
    123           expect(advanceFoodHeadState(state, newer)).toBe('applied');
    124         }
    125         return base.created_at;
    126       }
    127     };
    128     const state: FoodHeadState = createFoodHeadState(
    129       foodHeadStateHead(f.state),
    130       clock
    131     );
    132     armed = true;
    133     refreshFoodHeadState(state);
    134     expect(foodHeadStateSnapshot(state)).toMatchObject({
    135       display: 'unsupported',
    136       head: { created_at: base.created_at + 2 }
    137     });
    138     expect(foodHeadStateSnapshot(state).food).toBeUndefined();
    139     expect(publicHeadSnapshot(foodHeadStateHead(state)).created_at).toBe(
    140       base.created_at + 2
    141     );
    142   });
    143   it('projects the focused known head without claiming assured stock', () => {
    144     const f = fixture();
    145     const view = foodHeadStateSnapshot(f.state);
    146     expect(view.display).toBe('focused_known');
    147     expect(view.food?.status).toBe('active');
    148     expect(view.clockDirection).toBe('initial');
    149     expect(view.head).toEqual(publicHeadSnapshot(foodHeadStateHead(f.state)));
    150   });
    151   it('keeps a newer unsupported status and never returns the older active projection', () => {
    152     const f = fixture();
    153     const raw = f.signed(base.created_at + 1, status('unknown'));
    154     expect(advanceFoodHeadState(f.state, f.proof(raw))).toBe('applied');
    155     const view = foodHeadStateSnapshot(f.state);
    156     expect(view.display).toBe('unsupported');
    157     expect(view.food).toBeUndefined();
    158     expect(view.head.id).toBe((JSON.parse(raw) as { id: string }).id);
    159     expect(view.unsupportedReason).toBe('food_status_invalid');
    160   });
    161   it('blocks generic operational and ambiguous newer heads before focused filtering', () => {
    162     for (const tags of [
    163       base.tags.filter((t) => !t[0].startsWith('radroots:')),
    164       [
    165         ['d', base.tags.find((t) => t[0] === 'd')![1]],
    166         ['radroots:primary_bin', 'stock']
    167       ],
    168       [...base.tags, ['radroots:primary_bin', 'stock']]
    169     ]) {
    170       const f = fixture();
    171       advanceFoodHeadState(
    172         f.state,
    173         f.proof(f.signed(base.created_at + 1, tags))
    174       );
    175       expect(foodHeadStateSnapshot(f.state).classification).toBe('unsupported');
    176       expect(foodHeadStateSnapshot(f.state).food).toBeUndefined();
    177     }
    178   });
    179   it('cannot let a bad signature or forged proof suppress good evidence', () => {
    180     const f = fixture();
    181     const before = foodHeadStateSnapshot(f.state);
    182     const raw = JSON.parse(
    183       f.signed(base.created_at + 1, status('unknown'))
    184     ) as { sig: string };
    185     raw.sig = '0'.repeat(128);
    186     expect(verifyEnvelope(JSON.stringify(raw)).ok).toBe(false);
    187     expect(
    188       advanceFoodHeadState(f.state, raw as unknown as VerifiedEnvelope)
    189     ).toBe('ignored');
    190     expect(foodHeadStateSnapshot(f.state)).toEqual(before);
    191   });
    192   it('does not resurrect an older focused head arriving after unsupported evidence', () => {
    193     const f = fixture();
    194     advanceFoodHeadState(
    195       f.state,
    196       f.proof(f.signed(base.created_at + 1, status('unknown')))
    197     );
    198     const before = foodHeadStateSnapshot(f.state);
    199     expect(advanceFoodHeadState(f.state, f.proof(f.signed()))).toBe('older');
    200     expect(foodHeadStateSnapshot(f.state)).toEqual(before);
    201   });
    202   it('uses strict greater-than-five-minute quarantine with fractional wall clock support', () => {
    203     expect(assessFutureTimestamp(1300, 1000)).toBe('within_policy');
    204     expect(assessFutureTimestamp(1301, 1000)).toBe('future_quarantined');
    205     expect(assessFutureTimestamp(1301, 1000.5)).toBe('future_quarantined');
    206     expect(assessFutureTimestamp(Number.MAX_SAFE_INTEGER, 0)).toBe(
    207       'future_quarantined'
    208     );
    209   });
    210   it('quarantines the protocol winner without changing its signed timestamp', () => {
    211     const f = fixture();
    212     const raw = f.signed(base.created_at + 301);
    213     advanceFoodHeadState(f.state, f.proof(raw));
    214     const view = foodHeadStateSnapshot(f.state);
    215     expect(view.display).toBe('future_quarantined');
    216     expect(view.classification).toBe('focused');
    217     expect(view.food).toBeUndefined();
    218     expect(view.head.created_at).toBe(base.created_at + 301);
    219   });
    220   it('explicit refresh exposes forward and backward clock transitions without changing winner', () => {
    221     const f = fixture();
    222     advanceFoodHeadState(f.state, f.proof(f.signed(base.created_at + 301)));
    223     const id = foodHeadStateSnapshot(f.state).head.id;
    224     f.setNow(base.created_at + 1);
    225     refreshFoodHeadState(f.state);
    226     expect(foodHeadStateSnapshot(f.state)).toMatchObject({
    227       display: 'focused_known',
    228       clockDirection: 'forward'
    229     });
    230     f.setNow(base.created_at);
    231     refreshFoodHeadState(f.state);
    232     expect(foodHeadStateSnapshot(f.state)).toMatchObject({
    233       display: 'future_quarantined',
    234       clockDirection: 'backward'
    235     });
    236     expect(foodHeadStateSnapshot(f.state).head.id).toBe(id);
    237   });
    238   it('cannot restore an older current view while the winner is quarantined', () => {
    239     const f = fixture();
    240     advanceFoodHeadState(f.state, f.proof(f.signed(base.created_at + 301)));
    241     expect(advanceFoodHeadState(f.state, f.proof(f.signed()))).toBe('older');
    242     expect(foodHeadStateSnapshot(f.state).display).toBe('future_quarantined');
    243     expect(foodHeadStateSnapshot(f.state).food).toBeUndefined();
    244   });
    245   it('retains incompatible evidence while future and still denies food after clock catches up', () => {
    246     const f = fixture();
    247     advanceFoodHeadState(
    248       f.state,
    249       f.proof(f.signed(base.created_at + 301, status('unknown')))
    250     );
    251     expect(foodHeadStateSnapshot(f.state)).toMatchObject({
    252       display: 'future_quarantined',
    253       classification: 'unsupported'
    254     });
    255     f.setNow(base.created_at + 1);
    256     refreshFoodHeadState(f.state);
    257     expect(foodHeadStateSnapshot(f.state).display).toBe('unsupported');
    258     expect(foodHeadStateSnapshot(f.state).food).toBeUndefined();
    259   });
    260   it('unavailable clock preserves the new winner and fails closed for display', () => {
    261     const f = fixture();
    262     f.setNow(NaN);
    263     advanceFoodHeadState(f.state, f.proof(f.signed(base.created_at + 1)));
    264     expect(foodHeadStateSnapshot(f.state)).toMatchObject({
    265       display: 'clock_unavailable',
    266       clockDirection: 'unavailable',
    267       assessedAtSeconds: null
    268     });
    269     expect(foodHeadStateSnapshot(f.state).head.created_at).toBe(
    270       base.created_at + 1
    271     );
    272     expect(foodHeadStateSnapshot(f.state).food).toBeUndefined();
    273     f.setNow(base.created_at + 1);
    274     refreshFoodHeadState(f.state);
    275     expect(foodHeadStateSnapshot(f.state).display).toBe('focused_known');
    276   });
    277   it('clock throwing or invalid numeric samples never manufacture a display time', () => {
    278     const f = fixture();
    279     const state = createFoodHeadState(foodHeadStateHead(f.state), {
    280       nowSeconds: () => {
    281         throw new Error('clock failure');
    282       }
    283     });
    284     expect(foodHeadStateSnapshot(state).display).toBe('clock_unavailable');
    285     for (const now of [NaN, Infinity, -1, Number.MAX_SAFE_INTEGER + 1])
    286       expect(assessFutureTimestamp(base.created_at, now)).toBe(
    287         'clock_unavailable'
    288       );
    289   });
    290   it('duplicates and other coordinates do not sample clock or replace state', () => {
    291     const f = fixture();
    292     const before = foodHeadStateSnapshot(f.state),
    293       calls = f.calls();
    294     expect(advanceFoodHeadState(f.state, f.proof(f.signed()))).toBe(
    295       'duplicate'
    296     );
    297     const tags = base.tags.map((t) => (t[0] === 'd' ? ['d', 'other'] : t));
    298     expect(
    299       advanceFoodHeadState(
    300         f.state,
    301         f.proof(f.signed(base.created_at + 1, tags))
    302       )
    303     ).toBe('coordinate_mismatch');
    304     expect(f.calls()).toBe(calls);
    305     expect(foodHeadStateSnapshot(f.state)).toEqual(before);
    306   });
    307   it('protects detached projection and head metadata from mutation and rejects forged owners', () => {
    308     const f = fixture();
    309     const view = foodHeadStateSnapshot(f.state);
    310     if (!view.food) throw new Error('Expected focused food');
    311     (view.food as { title: string }).title = 'mutated';
    312     (view.head as { created_at: number }).created_at = 0;
    313     expect(foodHeadStateSnapshot(f.state).food?.title).not.toBe('mutated');
    314     expect(foodHeadStateSnapshot(f.state).head.created_at).toBe(
    315       base.created_at
    316     );
    317     expect(() => foodHeadStateSnapshot({} as FoodHeadState)).toThrow(
    318       'food_head_state_invalid'
    319     );
    320   });
    321   it('does not treat public metadata coordinates as food state', () => {
    322     const f = fixture();
    323     for (const kind of [0, 10050])
    324       expect(() =>
    325         createFoodHeadState(
    326           f.candidate(f.signed(base.created_at, [], '{}', kind)),
    327           f.clock
    328         )
    329       ).toThrow('food_head_kind_invalid');
    330   });
    331 });