web/website/node/economy-operations.mjs
2026-11-27 23:43:05 +00:00

41 lines
4.4 KiB
JavaScript

import {createHash} from 'node:crypto';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
export const ECONOMY_OPERATION_SCHEMA=`CREATE TABLE IF NOT EXISTS pb_economy_operations(id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,action_id VARCHAR(80) NOT NULL,manifest_hash CHAR(64) NOT NULL,receipt_json MEDIUMTEXT NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
export const economyHash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
export function economyId(value){const h=economyHash(value);return h.slice(0,8)+'-'+h.slice(8,12)+'-4'+h.slice(13,16)+'-a'+h.slice(17,20)+'-'+h.slice(20,32);}
const first=(db,sql,args=[])=>db.first?db.first(sql,args):db.prepare(sql).bind(...args).first();
// Central authority is consumed first; the separate bank commits one immutable
// receipt. If the reply is lost, the same key recovers that receipt without
// applying another reset or changing money received after the first commit.
export function createEconomyOperations(central,bank,keys,{authorize,clock=Date.now}={}){
if(!keys||typeof authorize!=='function')throw TypeError('Verified economic authority required');
return async({action,id,fields,apply})=>{
if(!['economy.reset-balances','economy.repay-loans','economy.federal-cycle'].includes(action)||typeof apply!=='function')throw TypeError('Unsupported economic operation');
const manifest={schema:1,action,id,fields},encoded=JSON.stringify(manifest),fingerprint=economyHash(manifest),load=store=>first(store,'SELECT * FROM jarvis_generated_instructions WHERE request_id=? AND action_id=?',[id,action]);
const previous=await load(central);if(previous&&previous.fields_json!==encoded)throw Error('Economic instruction reference conflict');
if(previous?.state==='applied')return {...JSON.parse(previous.manifest_json).receipt,replayed:true};
const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'economy-operation',scopeId:action+':'+id,authorize:async(tx,{keyId})=>{
await authorize(tx,manifest);const old=await load(tx);if(old){if(old.fields_json!==encoded)throw Error('Economic instruction changed');return;}
await tx.query("INSERT INTO jarvis_generated_instructions VALUES(?,?,?,?,1,?,?,'issued',?)",[keyId,id,STAFF_OFFICE_ACCOUNT_ID,action,encoded,JSON.stringify({manifest}),clock()]);
}});
let instruction=await load(central);if(instruction?.key_id!==grant.id||instruction.fields_json!==encoded)throw Error('Economic key binding changed');
if(instruction.state==='issued'){
const available=(await keys.list(STAFF_OFFICE_ACCOUNT_ID)).find(k=>k.id===grant.id&&k.status==='available');if(!available?.code)throw Error('Economic system key unavailable');
await keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'economy-operation',code:available.code,targetId:id,requestId:id,apply:async(tx,{keyId,scopeId})=>{
const locked=await load(tx);if(scopeId!==action+':'+id||locked?.key_id!==keyId||locked.fields_json!==encoded||locked.state!=='issued')throw Error('Economic key scope changed');await authorize(tx,manifest);
await tx.query("UPDATE jarvis_generated_instructions SET state='queued' WHERE key_id=?",[keyId]);
}});
}
instruction=await load(central);if(!['queued','applied'].includes(instruction?.state))throw Error('Economic operation is not authorised');
if(instruction.state==='applied')return {...JSON.parse(instruction.manifest_json).receipt,replayed:true};
const result=await bank.transaction(async tx=>{
const receipt=await tx.first('SELECT * FROM pb_economy_operations WHERE id=? FOR UPDATE',[id]);if(receipt){if(receipt.key_id!==grant.id||receipt.manifest_hash!==fingerprint)throw Error('Economic bank receipt conflict');return {...JSON.parse(receipt.receipt_json),replayed:true};}
// Recheck the consumed instrument before the first bank mutation.
const key=await first(central,'SELECT used_at,revoked_at FROM organisation_keys WHERE id=?',[grant.id]);if(key?.used_at==null||key.revoked_at!==null)throw Error('Consumed economic authority required');
await authorize(null,manifest);
const value=await apply(tx,{keyId:grant.id,id,manifest,now:clock()});
await tx.query('INSERT INTO pb_economy_operations VALUES(?,?,?,?,?,?)',[id,grant.id,action,fingerprint,JSON.stringify(value),clock()]);return value;
});
await central.query("UPDATE jarvis_generated_instructions SET state='applied',manifest_json=? WHERE key_id=? AND state='queued'",[JSON.stringify({manifest,receipt:result}),grant.id]);return result;
};
}