lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

commerce_wire_oracle.mjs (8870B)


      1 // Independently authored synthetic profile bytes. No Rust output is read here.
      2 import { createHash } from 'node:crypto';
      3 import { readFileSync, writeFileSync } from 'node:fs';
      4 import assert from 'node:assert/strict';
      5 
      6 const termsSuite=JSON.parse(readFileSync(new URL('../fixtures/terms_wire.v1.json',import.meta.url),'utf8'));
      7 const terms=index=>JSON.parse(termsSuite.vectors[index].wire);
      8 const id=byte=>byte.toString(16).padStart(2,'0').repeat(32);
      9 const hash=value=>createHash('sha256').update(value).digest('hex');
     10 const seller=terms(0).seller,buyer=terms(0).buyer;
     11 const authority={executor_id:id(30),generation:'1'};
     12 const lines=[{line_id:id(5),amount:'1'}];
     13 const reason='Private reason \0 🥬 Å A\u030a';
     14 const window={start:'300',end:'400',timezone:'Etc/UTC'};
     15 const resolution={issues:[id(8)],accepted_receipts:[id(9)],release_residual:lines,summary:reason};
     16 const parents=[3,6,7,8,9,10,11,12].map(id);
     17 function canonical(value) {
     18   if(value===null||typeof value==='string'||typeof value==='boolean')return JSON.stringify(value);
     19   if(typeof value==='number'){assert(Number.isSafeInteger(value)&&value>=0);return JSON.stringify(value);}
     20   if(Array.isArray(value))return '['+value.map(canonical).join(',')+']';
     21   const keys=Object.keys(value).sort();assert(keys.every(key=>/^[\x00-\x7f]*$/.test(key)));
     22   return '{'+keys.map(key=>JSON.stringify(key)+':'+canonical(value[key])).join(',')+'}';
     23 }
     24 function header(type,payload,author) {
     25   return {profile:'radroots.commerce',version:1,type,thread_id:id(20),order_id:type==='quote'?null:id(21),
     26     author,buyer,seller,created_at:'450',author_sequence:'1',author_previous:null,parents,payload};
     27 }
     28 function encode(body,name=body.type) {
     29   const without=canonical(body);
     30   const record_id=hash(Buffer.concat([Buffer.from('radroots.record.v1\0'),Buffer.from(without)]));
     31   const wire=canonical({...body,record_id});
     32   return {name,type:body.type,required_parents:requiredParents(body),canonical_without_id:without,record_id,wire,utf8_bytes:Buffer.byteLength(wire),
     33     raw_preimage_sha256:hash(without),terms_domain_digest:hash(Buffer.concat([Buffer.from('radroots.terms.v1\0'),Buffer.from(without)]))};
     34 }
     35 function requiredParents(body) {
     36   const fields={quote:['in_reply_to'],request:['quote'],decline:['request'],terms_proposed:['base_agreement'],
     37     terms_authorized:['proposal'],terms_rejected:['proposal'],agreement_committed:['base_agreement','authorization'],
     38     withdrawal_requested:['authorization'],withdrawal_acknowledged:['withdrawal'],cancellation_proposed:['agreement'],
     39     cancellation_authorized:['proposal'],residual_released:['proposal','authorization','agreement'],ready:['agreement'],
     40     handover:['agreement'],receipt:['handover','supersedes'],issue:[],resolution_proposed:['agreement'],
     41     resolution_authorized:['proposal'],resolution_committed:['proposal','authorization']};
     42   const payload=body.payload;
     43   const refs=fields[body.type].map(field=>payload[field]);
     44   if(payload.terms)refs.push(...payload.terms.lines.map(line=>line.source.event_id));
     45   if(body.type==='issue')refs.push(...payload.source_records);
     46   if(body.type==='resolution_proposed')refs.push(...payload.resolution.issues,...payload.resolution.accepted_receipts);
     47   refs.push(body.author_previous);
     48   return [...new Set(refs.filter(value=>value!==null))].sort();
     49 }
     50 const payloads=[
     51   ['quote',{terms:terms(0),expires_at:'600',in_reply_to:id(6)},seller],
     52   ['request',{terms:terms(1),expires_at:'600',quote:id(6)},buyer],
     53   ['decline',{request:id(6),reason},seller],
     54   ['terms_proposed',{base_agreement:id(7),terms:terms(2),expires_at:'600',reason},buyer],
     55   ['terms_authorized',{proposal:id(6),terms_digest:termsSuite.vectors[2].terms_digest,expires_at:'600'},seller],
     56   ['terms_rejected',{proposal:id(6),reason},seller],
     57   ['agreement_committed',{base_agreement:id(7),authorization:id(6),terms_digest:termsSuite.vectors[2].terms_digest,authority,seller_sequence:'1'},seller],
     58   ['withdrawal_requested',{authorization:id(6),reason},buyer],
     59   ['withdrawal_acknowledged',{withdrawal:id(6),seller_sequence:'1'},seller],
     60   ['cancellation_proposed',{agreement:id(7),residual:lines,reason,expires_at:'600'},buyer],
     61   ['cancellation_authorized',{proposal:id(6),expires_at:'600'},seller],
     62   ['residual_released',{proposal:id(6),authorization:id(8),agreement:id(7),residual:lines,authority,seller_sequence:'1'},seller],
     63   ['ready',{agreement:id(7),fulfillment_group:id(4),lines,window},seller],
     64   ['handover',{agreement:id(7),fulfillment_group:id(4),lines,measurements:[{line_id:id(5),quantity:{amount:'500',unit:'g'},line_total:{currency:'CAD',minor:'439',exponent:2}}],occurred_at:'440',authority,seller_sequence:'1'},seller],
     65   ['receipt',{handover:id(6),lines:[{line_id:id(5),amount:'0'}],supersedes:id(9),occurred_at:'440',note:reason},buyer],
     66   ['issue',{code:'quality',description:reason,lines,source_records:[id(8)]},buyer],
     67   ['resolution_proposed',{agreement:id(7),resolution,expires_at:'600'},buyer],
     68   ['resolution_authorized',{proposal:id(6),expires_at:'600'},seller],
     69   ['resolution_committed',{proposal:id(6),authorization:id(8),authority,seller_sequence:'1'},seller],
     70 ];
     71 assert.equal(payloads.length,19);
     72 const vectors=payloads.map(([type,payload,author])=>encode(header(type,payload,author)));
     73 for(const [type,field] of [['quote','in_reply_to'],['request','quote'],['terms_proposed','base_agreement'],['agreement_committed','base_agreement'],['receipt','supersedes']]) {
     74   const [,payload,author]=payloads.find(row=>row[0]===type);
     75   const body=header(type,structuredClone(payload),author);body.payload[field]=null;
     76   vectors.push(encode(body,type+'_explicit_null'));
     77 }
     78 const previous=header('decline',{request:id(6),reason},seller);previous.author_sequence='2';previous.author_previous=id(12);
     79 vectors.push(encode(previous,'decline_previous_author_record'));
     80 const observed=header('receipt',{handover:id(6),lines:[{line_id:id(5),amount:'1'},{line_id:id(6),amount:'0'}],supersedes:null,occurred_at:'440',note:reason},buyer);
     81 vectors.push(encode(observed,'receipt_two_lines'));
     82 const reversed=structuredClone(observed);reversed.payload.lines.reverse();vectors.push(encode(reversed,'receipt_two_lines_reversed'));
     83 const [,handoverPayload,handoverAuthor]=payloads.find(row=>row[0]==='handover');
     84 const measured=header('handover',structuredClone(handoverPayload),handoverAuthor);
     85 measured.payload.lines.push({line_id:id(6),amount:'1'});
     86 measured.payload.measurements.push({line_id:id(6),quantity:{amount:'1',unit:'kg'},line_total:{currency:'CAD',minor:'878',exponent:2}});
     87 vectors.push(encode(measured,'handover_two_measurements'));
     88 const measuredReversed=structuredClone(measured);measuredReversed.payload.measurements.reverse();
     89 vectors.push(encode(measuredReversed,'handover_two_measurements_reversed'));
     90 for(const unit of ['kg','mL','L','each']) {
     91   const [,payload,author]=payloads.find(row=>row[0]==='handover');const body=header('handover',structuredClone(payload),author);
     92   body.payload.measurements[0].quantity.unit=unit;vectors.push(encode(body,'handover_unit_'+unit));
     93 }
     94 for(const code of ['shortage','substitution','collection','excess','other']) {
     95   const [,payload,author]=payloads.find(row=>row[0]==='issue');const body=header('issue',structuredClone(payload),author);
     96   body.payload.code=code;vectors.push(encode(body,'issue_code_'+code));
     97 }
     98 const limitTerms=termsSuite.vectors.find(v=>v.name==='exact_content_limit');assert(limitTerms);
     99 const large=header('quote',{terms:JSON.parse(limitTerms.wire),expires_at:'600',in_reply_to:id(6)},seller);
    100 let excess=encode(large).utf8_bytes-16384;
    101 assert(excess>0);
    102 for(const group of large.payload.terms.fulfillment){const remove=Math.min(excess,group.terms.instructions.length);group.terms.instructions=group.terms.instructions.slice(remove);excess-=remove;}
    103 assert.equal(excess,0);
    104 const exact=encode(large,'exact_private_record_limit');assert.equal(exact.utf8_bytes,16384);vectors.push(exact);
    105 const overflow=structuredClone(large);
    106 overflow.payload.terms.fulfillment.find(group=>group.terms.instructions.length<2048).terms.instructions+='a';
    107 const invalid=encode(overflow,'private_record_limit_plus_one');assert.equal(invalid.utf8_bytes,16385);
    108 const output=JSON.stringify({schema:'radroots.commerce.record.vectors.v1',producer:'independent ECMAScript canonicalization and Node.js SHA-256; synthetic data only',scope:'Closed complete record bytes/hash claims only; no authenticated parent history, consent, stock, physical truth, nested crypto or issuance qualification.',vectors,invalid:[{...invalid,expected:'limit_exceeded'}]},null,2)+'\n';
    109 const target=new URL('../fixtures/commerce_wire.v1.json',import.meta.url);
    110 if(process.argv.includes('--write'))writeFileSync(target,output);
    111 else if(process.argv.includes('--check'))assert.equal(readFileSync(target,'utf8'),output,'Commerce fixture is stale');
    112 else throw new Error('Use --write or --check');