app

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

food-qualified-matrix.test.ts (6853B)


      1 import assert from 'node:assert/strict';
      2 import { readFile } from 'node:fs/promises';
      3 import { after, test } from 'node:test';
      4 import { finalizeEvent } from 'applesauce-core/helpers';
      5 import {
      6   qualifiedDrafts,
      7   qualifiedTemplates
      8 } from './food-qualified-matrix.ts';
      9 import { checkFoodReplay } from './food-bidirectional.ts';
     10 import { readFoodEvent } from '../../src/lib/contracts/food-availability-v1/read.ts';
     11 import { verifyEnvelope } from '../../src/lib/nostr/verified-envelope.ts';
     12 import {
     13   createPublicHeadCandidate,
     14   selectPublicHead,
     15   publicHeadSnapshot
     16 } from '../../src/lib/catalog/heads.ts';
     17 
     18 const root = new URL(
     19   '../../../contracts/interop/food_availability/',
     20   import.meta.url
     21 );
     22 const inputs = await Promise.all(
     23   [
     24     'corpus.v1.json',
     25     'source_profile.v1.json',
     26     'provenance.v1.json',
     27     'oracle/src/main.rs'
     28   ].map(async (name) => [name, await readFile(new URL(name, root))] as const)
     29 );
     30 const receipt: unknown = JSON.parse(
     31   await readFile(
     32     new URL('./food-qualified-writer-rust.v1.json', import.meta.url),
     33     'utf8'
     34   )
     35 );
     36 const secret = crypto.getRandomValues(new Uint8Array(32));
     37 after(() => secret.fill(0));
     38 const signed = (
     39   tags: readonly (readonly string[])[],
     40   created_at: number,
     41   content: string
     42 ) =>
     43   JSON.stringify(
     44     finalizeEvent(
     45       { kind: 30402, tags: tags.map((row) => [...row]), created_at, content },
     46       secret
     47     )
     48   );
     49 function head(raw: string) {
     50   const proof = verifyEnvelope(raw);
     51   assert.equal(proof.ok, true);
     52   if (!proof.ok) throw new Error('Invalid signed test event');
     53   const candidate = createPublicHeadCandidate(proof.value);
     54   assert.ok(candidate);
     55   return candidate;
     56 }
     57 
     58 void test('separate sixteen boundary recipes replay actual pinned Rust consumption without changing original shared fixtures', () => {
     59   checkFoodReplay(receipt, qualifiedTemplates, inputs);
     60   assert.equal(qualifiedTemplates.length, 16);
     61   assert.notEqual(
     62     qualifiedDrafts[9].identifier,
     63     qualifiedDrafts[10].identifier
     64   );
     65   assert.equal(
     66     qualifiedDrafts[9].identifier.normalize('NFC'),
     67     qualifiedDrafts[10].identifier.normalize('NFC')
     68   );
     69 });
     70 
     71 void test('actual SDK signed boundary templates preserve exact decimals, Unicode, timestamps and unknown quantity in the reader', () => {
     72   for (const [index, row] of qualifiedTemplates.entries()) {
     73     const result = readFoodEvent(
     74       signed(row.wire_parts.tags, row.created_at, row.wire_parts.content)
     75     );
     76     assert.equal(result.outcome, 'admitted', row.id);
     77     if (result.outcome !== 'admitted') throw new Error(row.id);
     78     const draft = qualifiedDrafts[index];
     79     assert.equal(result.projection.identifier, draft.identifier);
     80     assert.equal(result.projection.title, draft.title);
     81     assert.equal(result.projection.location, draft.location);
     82     assert.equal(result.projection.content, row.wire_parts.content);
     83     assert.equal(result.projection.published_at, draft.published_at);
     84     assert.equal(result.projection.price.amount, draft.amount);
     85     assert.equal(result.projection.status, draft.status);
     86     assert.deepEqual(
     87       result.projection.quantity,
     88       draft.quantity === undefined
     89         ? null
     90         : { amount: draft.quantity, unit: draft.unit }
     91     );
     92   }
     93 });
     94 
     95 void test('complete raw marker intersections remain ambiguous before shape checks and incompatible newer heads suppress older food in both arrival orders', () => {
     96   const base = qualifiedTemplates[0];
     97   const core = base.wire_parts.tags.filter(
     98     (row) => !['radroots:price_unit', 'radroots:quantity'].includes(row[0])
     99   );
    100   const oldRaw = signed(
    101     base.wire_parts.tags,
    102     base.created_at,
    103     base.wire_parts.content
    104   );
    105   assert.equal(readFoodEvent(oldRaw).outcome, 'admitted');
    106   const old = head(oldRaw);
    107   let combinations = 0;
    108   for (const focused of ['radroots:price_unit', 'radroots:quantity'])
    109     for (const operational of [
    110       'radroots:primary_bin',
    111       'radroots:bin',
    112       'radroots:price'
    113     ])
    114       for (const focusedArity of [1, 2, 3])
    115         for (const operationalArity of [1, 2, 3]) {
    116           const marker = (name: string, length: number) =>
    117             [name, 'kg', 'extra'].slice(0, length);
    118           const raw = signed(
    119             [
    120               ...core,
    121               marker(focused, focusedArity),
    122               marker(operational, operationalArity)
    123             ],
    124             base.created_at + 1,
    125             base.wire_parts.content
    126           );
    127           const read = readFoodEvent(raw);
    128           assert.equal(read.outcome, 'rejected');
    129           if (read.outcome !== 'rejected')
    130             throw new Error('Mixed marker admitted');
    131           assert.equal(read.error.code, 'food_profile_ambiguous');
    132           const incompatible = head(raw);
    133           assert.equal(selectPublicHead(old, incompatible).head, incompatible);
    134           assert.equal(selectPublicHead(incompatible, old).head, incompatible);
    135           assert.equal(
    136             publicHeadSnapshot(incompatible).created_at,
    137             base.created_at + 1
    138           );
    139           combinations++;
    140         }
    141   assert.equal(combinations, 54);
    142 });
    143 
    144 void test('equal-time incompatible replacements use the lower actual event ID and never resurrect an older food view', () => {
    145   const base = qualifiedTemplates[0];
    146   const old = head(
    147     signed(base.wire_parts.tags, base.created_at, base.wire_parts.content)
    148   );
    149   const aRaw = signed(
    150     [...base.wire_parts.tags, ['radroots:bin']],
    151     base.created_at + 1,
    152     'First incompatible head'
    153   );
    154   const bRaw = signed(
    155     [...base.wire_parts.tags, ['radroots:primary_bin']],
    156     base.created_at + 1,
    157     'Second incompatible head'
    158   );
    159   for (const raw of [aRaw, bRaw])
    160     assert.notEqual(readFoodEvent(raw).outcome, 'admitted');
    161   const a = head(aRaw),
    162     b = head(bRaw);
    163   const winner = publicHeadSnapshot(a).id < publicHeadSnapshot(b).id ? a : b;
    164   for (const order of [
    165     [old, a, b],
    166     [b, old, a],
    167     [a, b, old]
    168   ]) {
    169     let current = order[0];
    170     for (const candidate of order.slice(1))
    171       current = selectPublicHead(current, candidate).head;
    172     assert.equal(current, winner);
    173   }
    174 });
    175 
    176 void test('maximum-safe signed envelope cannot launder fractional numeric source spelling through JSON rounding', () => {
    177   const base = qualifiedTemplates[5];
    178   const raw = signed(
    179     base.wire_parts.tags,
    180     base.created_at,
    181     base.wire_parts.content
    182   );
    183   assert.equal(verifyEnvelope(raw).ok, true);
    184   for (const spelling of [
    185     '9007199254740991.0',
    186     '9007199254740991.0000000001',
    187     '9.007199254740991e15'
    188   ]) {
    189     const altered = raw.replace(
    190       '"created_at":9007199254740991',
    191       `"created_at":${spelling}`
    192     );
    193     assert.notEqual(altered, raw);
    194     assert.equal(
    195       (JSON.parse(altered) as { created_at: number }).created_at,
    196       base.created_at
    197     );
    198     assert.equal(verifyEnvelope(altered).ok, false, spelling);
    199   }
    200 });