From 23b1879de2ae8ebe223860ff2a4bd52f9e6a38aa Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:55:27 +0100 Subject: [PATCH] Bind raid orders and recovery to atomic Postbank receipts --- .../docs/PILLAGER-RAID-CONTRACT-20261129.md | 4 +- website/node/imperial-raid-commerce.mjs | 98 ++++++++++ website/node/imperial-raid-jobs.mjs | 29 +++ website/node/imperial-raid-orders.mjs | 185 ++++++++++++++++++ website/node/imperial-raid-protocol.mjs | 2 +- website/node/organisation-keys.mjs | 2 +- website/tests/imperial-raid-commerce.test.mjs | 44 +++++ website/tests/imperial-raid-jobs.test.mjs | 12 ++ website/tests/imperial-raid-orders.test.mjs | 79 ++++++++ 9 files changed, 451 insertions(+), 4 deletions(-) create mode 100644 website/node/imperial-raid-commerce.mjs create mode 100644 website/node/imperial-raid-jobs.mjs create mode 100644 website/node/imperial-raid-orders.mjs create mode 100644 website/tests/imperial-raid-commerce.test.mjs create mode 100644 website/tests/imperial-raid-jobs.test.mjs create mode 100644 website/tests/imperial-raid-orders.test.mjs diff --git a/website/docs/PILLAGER-RAID-CONTRACT-20261129.md b/website/docs/PILLAGER-RAID-CONTRACT-20261129.md index a5da29e0..11d9bfa8 100644 --- a/website/docs/PILLAGER-RAID-CONTRACT-20261129.md +++ b/website/docs/PILLAGER-RAID-CONTRACT-20261129.md @@ -33,11 +33,11 @@ Definitive unpaid responses are exactly `{ok:true,schema:1,orderId,requestId,inp `acceptedAt+noticeMs` is the warning deadline, not evidence that a party exists. Start the active timer only after actual successful party and commander spawn, then report the stable started event. Victory requires the same recorded start, surviving commander and900000 active milliseconds. Commander defeat is failure. Post-accept spawn failure, restart/interruption or server cancellation is neutral; no victory for missing entities, unloaded areas or elapsed offline time. -The coordinator chooses full original-fee recovery for these neutral service failures. Queue one idempotent refund against the original posted bank order, original source and original Tax destination, for exactly its fee. Reuse existing Postbank posting in the reverse direction with a stable refund reference and a JARVIS recovery record. Never mint compensation, choose a different recipient, reset a balance or mark a refund paid before posting. If the original account/treasury cannot safely settle it, keep the refund queued for reconciliation. An acknowledged neutral outcome may include `refundState:'queued'|'posted'`; the central durable job owns that liability after native acknowledgement. Preserve cooldown/chain audit history rather than erase the paid order to enable free replay. +The coordinator chooses full original-fee recovery for these neutral service failures unless this order has already delivered its automatic war. Queue one idempotent refund against the original posted bank order, original source and original Tax destination, for exactly its fee. Reuse existing Postbank posting in the reverse direction with a stable refund reference and a JARVIS recovery record. Never mint compensation, choose a different recipient, reset a balance or mark a refund paid before posting. If the original account/treasury cannot safely settle it, keep the refund queued for reconciliation. An acknowledged neutral outcome may include `refundState:'queued'|'posted'`; the central durable job owns that liability after native acknowledgement. Preserve cooldown/chain audit history rather than erase the paid order to enable free replay. Only real completed/failed raids produce the ordering-clan quest result:1000 Reputation XP for survival,100 for commander defeat, zero Personal XP and zero currency. Rejection, spawn failure, cancellation and restart are neutral. Stable order/outcome identifiers prevent reward replay. Use the existing quest/Reputation authority and outbox, not a native reward command. -At the third paid retaliation, enqueue one stable chain-bound job that automates the ORIGINAL war declaration/campaign flow with NOW and both actual clan rosters. Skip manual date/roster input only. Ordinary scheduled wars retain their existing rules; do not invent a parallel war engine, fake consent/identities or truncate an entire clan to a random eight. War/quest/refund work is durable and retried after the accepting transaction; no nested key transaction or payment replay. +At the third paid retaliation, enqueue one stable chain-bound war job in `waiting_start`. Release it only after the matched actual STARTED acknowledgement, matching the supplied design's party-spawn threshold event. The job automates the ORIGINAL war declaration/campaign flow with NOW and both actual clan rosters. Skip manual date/roster input only. Ordinary scheduled wars retain their existing rules; do not invent a parallel war engine, fake consent/identities or truncate an entire clan to a random eight. A neutral result before a war is committed cancels its pending war job and permits the original-fee refund. War creation and the order's durable campaign receipt must commit atomically, serialized against neutral outcomes. Once that original war has actually launched, a later neutral raid interruption gives no automatic refund: respond `refundState:'not_due',refundReason:'war_started'`, retain the existing war and award no neutral quest reward. This prevents a failed-spawn or interruption from creating a free war. War/quest/refund work is durable and retried after the accepting transaction; no nested key transaction or payment replay. ## Release gates diff --git a/website/node/imperial-raid-commerce.mjs b/website/node/imperial-raid-commerce.mjs new file mode 100644 index 00000000..05e8dea7 --- /dev/null +++ b/website/node/imperial-raid-commerce.mjs @@ -0,0 +1,98 @@ +import {createHash} from 'node:crypto'; +import {atomicBankAccess} from './atomic-bank-access.mjs'; +import {boardReadStore} from './board-deed-source.mjs'; +import {clanWarAuthority} from './clan-deeds.mjs'; +import {readGameNativeState} from './game-native-state.mjs'; +import {clanWarBranch} from './war-rosters.mjs'; +import {createPostbankAuthority,entityId} from './postbank-authority.mjs'; +import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs'; +import {canDebitAccount} from './postbank-authorisations.mjs'; +import {PostbankPayments} from './postbank-payments.mjs'; +import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs'; +const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});}; +const accountsSQL='SELECT a.*,c.entity_id,e.active entity_active,p.state package_state FROM pb_accounts a LEFT JOIN pb_clients c ON c.client_number=a.client_number LEFT JOIN pb_entities e ON e.id=c.entity_id LEFT JOIN pb_packages p ON p.id=a.package_id'; +const tables=['jarvis_imperial_raid_guard','jarvis_imperial_raid_orders','jarvis_imperial_raid_clans','jarvis_imperial_raid_events','jarvis_imperial_raid_jobs','organisation_keys','organisation_key_events','codex_instance_editions','site_accounts','site_game_links','site_clans','site_clan_deeds','site_clan_charters','site_clan_members','site_claim_registry']; +export function raidRecoveryId(orderId){const h=createHash('sha256').update('imperial-raid-refund:'+orderId).digest('hex');return h.slice(0,8)+'-'+h.slice(8,12)+'-5'+h.slice(13,16)+'-8'+h.slice(17,20)+'-'+h.slice(20,32);} +export function createImperialRaidCommerce(raw,bank,keys,{clock=Date.now,verifyStorage,readState=readGameNativeState,warAuthority=clanWarAuthority,bankAuthority=createPostbankAuthority,verifyCampaigns=true}={}){ + const db=boardReadStore(raw,raw),banking=atomicBankAccess(db,bank,{verifyStorage,centralTables:tables,bankTables:verifyCampaigns?['jarvis_war_campaigns']:[]}); + const reader=tx=>{const r=boardReadStore(tx,raw);r.readSnapshot=undefined;return r;}; + async function resolveActor(tx,uuid,{lock=false}={}){ + const rows=await tx.query('SELECT a.id,a.username,a.role,a.password_hash FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE l.minecraft_uuid=?'+(lock?' FOR UPDATE':''),[uuid]); + if(rows.length!==1||String(rows[0].password_hash).startsWith('!')||['system_account','official','official_account','memorial'].includes(rows[0].role))fail('Link an active personal Minecraft account first.',403); + return rows[0]; + } + async function funding(tx,actor,clanId){ + const r=reader(tx),b=banking.view(r),rights=await bankAuthority(r,{bank:b,clock})(actor,{bank:b}); + return (await b.query(accountsSQL+' WHERE c.entity_id=? AND a.system_key IS NULL ORDER BY a.id',[entityId('clan',clanId)])).filter(a=>ordinaryPaymentAccount(a)&&canDebitAccount(rights,a.entity_id,a.id)); + } + async function resolveContext(tx,input,{lock=false}={}){ + const actor=await resolveActor(tx,input.uuid,{lock}); + if(lock){ + const ids=[input.orderingClanId,input.targetClanId].sort(); + await tx.query('SELECT id FROM site_clans WHERE id IN (?,?) ORDER BY id FOR UPDATE',ids); + await tx.query('SELECT clan_id FROM site_clan_deeds WHERE clan_id IN (?,?) ORDER BY clan_id FOR UPDATE',ids); + await tx.query('SELECT clan_id FROM site_clan_charters WHERE clan_id IN (?,?) ORDER BY clan_id FOR UPDATE',ids); + await tx.query('SELECT user_id FROM site_clan_members WHERE clan_id IN (?,?) ORDER BY clan_id,user_id FOR UPDATE',ids); + await tx.query("SELECT organisation_id FROM site_claim_registry WHERE organisation_kind='clan' AND organisation_id IN (?,?) ORDER BY organisation_id FOR UPDATE",ids); + } + const r=reader(tx),rights=await warAuthority(r,actor.id,input.orderingClanId); + if(!rights.canManageWar)fail('Current clan war authority is required.',403); + const state=await readState(r,{clock}),a=state.clans.find(c=>c.id===input.orderingClanId),b=state.clans.find(c=>c.id===input.targetClanId); + if(!a||!b||a.lifecycle!=='active'||b.lifecycle!=='active'||a.protected||b.protected||a.hidden||b.hidden)fail('Choose two active unprotected rival clans.'); + const branchA=new Set(clanWarBranch(state.clans,a.id).map(c=>c.id)),branchB=new Set(clanWarBranch(state.clans,b.id).map(c=>c.id)); + if([...branchA].some(id=>branchB.has(id)))fail('Members of the same clan hierarchy cannot order raids against each other.'); + if(b.homeServer!==input.server||!b.homeBlock||b.homeBlock.source!=='minecraft')fail('Travel to the target clan’s registered world before ordering this raid.'); + if((state.wars||[]).some(w=>(w.active||w.reserved)&&[w.attackerId,w.defenderId].some(id=>branchA.has(id)||branchB.has(id))))fail('A participating clan already has a scheduled or active war.'); + if(verifyCampaigns){ + const campaigns=await banking.view(r).query('SELECT snapshot_json FROM jarvis_war_campaigns WHERE ends_at>? ORDER BY starts_at,id LIMIT 501',[clock()]); + if(campaigns.length>500)fail('The war register requires reconciliation.'); + for(const row of campaigns){const c=JSON.parse(row.snapshot_json);if(c.cancelledAt==null&&!c.winnerSideId&&c.teams.some(t=>(t.clanIds||[t.id]).some(id=>branchA.has(id)||branchB.has(id))))fail('A participating clan already has a scheduled or active campaign.');} + } + const accounts=await funding(r,actor,a.id); + if(!accounts.length)fail('This clan needs a current authorised clan bank account. Personal accounts cannot fund Imperial raids.',403); + const charters=await r.query('SELECT clan_id,key_id FROM site_clan_charters WHERE clan_id IN (?,?) ORDER BY clan_id',[a.id,b.id]); + if(charters.length!==2)fail('Both current clan charters are required.'); + return {orderingClanName:a.name,targetClanName:b.name,home:{worldUuid:b.homeBlock.worldUuid.toLowerCase(),position:structuredClone(b.homeBlock.position),claimRevision:b.claimRevision},authority:{actorId:actor.id,orderingVersion:a.version,targetVersion:b.version,orderingOwnerUuid:a.ownerUuid,targetOwnerUuid:b.ownerUuid,charters},accounts:accounts.map(a=>({id:String(a.id),name:a.display_name,availableMinor:String(BigInt(a.balance_minor)-BigInt(a.reserved_minor))}))}; + } + async function issue(tx,scopeId,authorize){ + if(!keys)fail('JARVIS raid receipts are unavailable.',503); + const existing=await tx.first("SELECT id FROM organisation_keys WHERE account_id=? AND key_type='entity-state' AND scope_id=? FOR UPDATE",[STAFF_OFFICE_ACCOUNT_ID,scopeId]); + if(existing)fail('The original raid receipt requires reconciliation.'); + return keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId,transactionStore:reader(tx),authorize}); + } + async function charge(tx,p){ + const r=reader(tx),b=banking.view(r),actor=await resolveActor(r,p.actorUuid,{lock:true}); + if(actor.id!==p.actorId)fail('The original raid actor changed.',403); + const tax=await b.first("SELECT id FROM pb_accounts WHERE system_key='sys_tax_treasury'");if(!tax)fail('The existing Tax treasury is unavailable.',503); + const meta=await b.first(accountsSQL+' WHERE a.id=?',[p.sourceAccountId]);if(meta?.entity_id!==entityId('clan',p.orderingClanId))fail('The original clan bank account is required.',403); + await b.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[meta.entity_id]); + await b.query('SELECT id FROM pb_accounts WHERE id IN (?,?) ORDER BY id FOR UPDATE',[p.sourceAccountId,tax.id]); + await b.query('SELECT id FROM pb_account_authorisations WHERE account_id=? ORDER BY id FOR UPDATE',[p.sourceAccountId]); + const source=(await funding(r,actor,p.orderingClanId)).find(a=>String(a.id)===p.sourceAccountId),target=await b.first('SELECT * FROM pb_accounts WHERE id=?',[tax.id]),amount=BigInt(p.feeMinor); + if(!source||!target||target.state!=='active'||target.system_key!=='sys_tax_treasury'||BigInt(source.balance_minor)-BigInt(source.reserved_minor)9223372036854775807n)fail('Insufficient authorised clan funds or unavailable Tax treasury.'); + if(await b.first('SELECT id FROM pb_orders WHERE id=? FOR UPDATE',[p.id]))fail('This bank reference already belongs to another operation.'); + const key=await issue(r,'state:imperial-raid:'+p.id,async(_tx,{keyId})=>{ + await b.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[p.id,actor.id,source.id,target.id,p.inputHash,p.feeMinor,'Imperial raid '+p.id,clock()]); + await new PostbankPayments(bank,null,{clock}).post(b,{id:p.id,actor_id:actor.id,amount_minor:p.feeMinor},source,target,false); + }); + return {receiptKeyId:key.id,bankOrderId:p.id}; + } + async function refund(rawTx,row){ + const tx=reader(rawTx),b=banking.view(tx),p=JSON.parse(row.accepted_json),outcome=JSON.parse(row.outcome_json),refundId=raidRecoveryId(row.id),scope='state:imperial-raid-refund:'+row.id; + if(row.state!=='neutral'||row.war_campaign_id||!['spawn_failed','interrupted','cancelled'].includes(outcome.outcome)||p.bankOrderId!==row.id)fail('A bound refundable neutral paid raid is required.'); + const original=await b.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[p.bankOrderId]); + if(!original||original.state!=='posted'||String(original.source_id)!==p.sourceAccountId||String(original.amount_minor)!==p.feeMinor||original.fingerprint!==p.inputHash||original.actor_id!==row.actor_id)fail('The original posted raid payment requires reconciliation.'); + const previous=await b.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[refundId]),priorKey=await tx.first("SELECT id FROM organisation_keys WHERE account_id=? AND key_type='entity-state' AND scope_id=? AND revoked_at IS NULL",[STAFF_OFFICE_ACCOUNT_ID,scope]); + const fingerprint=createHash('sha256').update(JSON.stringify([row.id,row.terminal_event_id,p.bankOrderId,p.feeMinor,'neutral-refund'])).digest('hex'); + if(previous){if(!priorKey||previous.state!=='posted'||String(previous.source_id)!==String(original.target_id)||String(previous.target_id)!==String(original.source_id)||String(previous.amount_minor)!==p.feeMinor||previous.fingerprint!==fingerprint)fail('The original raid refund requires reconciliation.');return {refundState:'posted',refundOrderId:refundId,receiptKeyId:priorKey.id};} + await b.query('SELECT id FROM pb_accounts WHERE id IN (?,?) ORDER BY id FOR UPDATE',[original.source_id,original.target_id]); + const rows=await b.query(accountsSQL+' WHERE a.id IN (?,?) ORDER BY a.id',[original.source_id,original.target_id]),source=rows.find(a=>String(a.id)===String(original.target_id)),target=rows.find(a=>String(a.id)===String(original.source_id)),amount=BigInt(p.feeMinor); + if(!source||source.system_key!=='sys_tax_treasury'||source.state!=='active'||!target||target.state!=='active'||target.entity_id!==entityId('clan',p.orderingClanId)||BigInt(source.balance_minor)-BigInt(source.reserved_minor)9223372036854775807n)fail('Original raid refund remains queued; the original accounts cannot settle safely.'); + const key=await issue(tx,scope,async()=>{ + await b.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[refundId,STAFF_OFFICE_ACCOUNT_ID,source.id,target.id,fingerprint,p.feeMinor,'Imperial raid refund '+row.id,clock()]); + await new PostbankPayments(bank,null,{clock}).post(b,{id:refundId,actor_id:STAFF_OFFICE_ACCOUNT_ID,amount_minor:p.feeMinor},{...source,entity_id:source.entity_id??null},target,false); + }); + return {refundState:'posted',refundOrderId:refundId,receiptKeyId:key.id}; + } + return {ready:banking.ready,resolveActor,resolveContext,charge,refund,bankView:banking.view}; +} diff --git a/website/node/imperial-raid-jobs.mjs b/website/node/imperial-raid-jobs.mjs new file mode 100644 index 00000000..10b36cc2 --- /dev/null +++ b/website/node/imperial-raid-jobs.mjs @@ -0,0 +1,29 @@ +import {randomUUID} from 'node:crypto'; + +// Domain handlers run AFTER the lease transaction. Existing quest/key/war +// services may open their own transactions; none is nested beneath this lease. +// Every handler must bind its side effect to the original durable order ID. +export async function processImperialRaidJobs(db,handlers,{clock=Date.now,limit=20,leaseMs=30000,makeId=randomUUID}={}){ + if(!Number.isSafeInteger(limit)||limit<1||limit>100||!Number.isSafeInteger(leaseMs)||leaseMs<1000||leaseMs>300000)throw TypeError('Bounded raid recovery worker required'); + const now=clock(),rows=await db.query("SELECT order_id,kind FROM jarvis_imperial_raid_jobs WHERE state='queued' OR (state='processing' AND lease_until<=?) ORDER BY COALESCE(attempted_at,created_at),created_at,order_id,kind LIMIT "+limit,[now]); + const result={attempted:0,completed:0,deferred:0}; + for(const ref of rows){ + const token=makeId(),job=await db.transaction(async tx=>{ + const row=await tx.first('SELECT * FROM jarvis_imperial_raid_jobs WHERE order_id=? AND kind=? FOR UPDATE',[ref.order_id,ref.kind]); + if(!row||row.state!=='queued'&&!(row.state==='processing'&&Number(row.lease_until)<=clock()))return null; + await tx.query("UPDATE jarvis_imperial_raid_jobs SET state='processing',attempted_at=?,lease_token=?,lease_until=? WHERE order_id=? AND kind=?",[clock(),token,clock()+leaseMs,row.order_id,row.kind]);return row; + }); + if(!job)continue;result.attempted++; + try{ + const handler=handlers[job.kind];if(typeof handler!=='function')throw Error('Raid recovery adapter unavailable'); + const response=await handler(job,JSON.parse(job.payload_json)); + if(!response||response.done===false)throw Error('Raid recovery remains pending'); + const saved=await db.query("UPDATE jarvis_imperial_raid_jobs SET state='completed',completed_at=?,lease_token=NULL,lease_until=NULL,result_json=? WHERE order_id=? AND kind=? AND state='processing' AND lease_token=?",[clock(),JSON.stringify(response),job.order_id,job.kind,token]); + if(Number(saved.affectedRows||0)===1)result.completed++;else result.deferred++; + }catch{ + // No raw bank response, item payload, player ID or secret is logged here. + await db.query("UPDATE jarvis_imperial_raid_jobs SET state='queued',lease_token=NULL,lease_until=NULL WHERE order_id=? AND kind=? AND state='processing' AND lease_token=?",[job.order_id,job.kind,token]);result.deferred++; + } + } + return result; +} diff --git a/website/node/imperial-raid-orders.mjs b/website/node/imperial-raid-orders.mjs new file mode 100644 index 00000000..9cd7cc68 --- /dev/null +++ b/website/node/imperial-raid-orders.mjs @@ -0,0 +1,185 @@ +import {randomUUID} from 'node:crypto'; +import {IMPERIAL_RAID_POLICY as P,validateImperialRaidInput,imperialRaidIntent,imperialRaidInputHash,imperialRaidEventHash,imperialRaidFee,unpaidRaidResponse,raidEventAcknowledgement} from './imperial-raid-protocol.mjs'; + +export const IMPERIAL_RAID_SCHEMA=[ + `CREATE TABLE IF NOT EXISTS jarvis_imperial_raid_guard(id INTEGER PRIMARY KEY) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, + `CREATE TABLE IF NOT EXISTS jarvis_imperial_raid_orders(id CHAR(36) PRIMARY KEY,actor_id CHAR(36) NOT NULL,minecraft_uuid CHAR(36) NOT NULL,input_hash CHAR(64) NOT NULL,intent_json TEXT NOT NULL,state VARCHAR(16) NOT NULL,prepared_json TEXT NULL,accepted_json TEXT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,updated_at BIGINT NOT NULL,started_at BIGINT NULL,terminal_event_id CHAR(36) NULL,outcome_json TEXT NULL,war_campaign_id CHAR(36) NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, + `CREATE TABLE IF NOT EXISTS jarvis_imperial_raid_clans(clan_id CHAR(36) PRIMARY KEY,last_order_at BIGINT NULL,last_raided_at BIGINT NULL,revenge_against CHAR(36) NULL,revenge_until BIGINT NULL,revenge_level INTEGER NOT NULL DEFAULT 0,chain_id CHAR(36) NULL,active_order_id CHAR(36) NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, + `CREATE TABLE IF NOT EXISTS jarvis_imperial_raid_events(event_id CHAR(36) PRIMARY KEY,order_id CHAR(36) NOT NULL,event_hash CHAR(64) NOT NULL,response_json TEXT NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, + `CREATE TABLE IF NOT EXISTS jarvis_imperial_raid_jobs(order_id CHAR(36) NOT NULL,kind VARCHAR(16) NOT NULL,payload_json TEXT NOT NULL,state VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL,attempted_at BIGINT NULL,completed_at BIGINT NULL,lease_token CHAR(36) NULL,lease_until BIGINT NULL,result_json TEXT NULL,PRIMARY KEY(order_id,kind)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4` +]; +export const initializeImperialRaids=async db=>{for(const sql of IMPERIAL_RAID_SCHEMA)await db.query(sql);}; +export async function lockImperialRaidGuard(tx){ + await tx.query('INSERT INTO jarvis_imperial_raid_guard(id) VALUES(1) ON DUPLICATE KEY UPDATE id=VALUES(id)'); + await tx.first('SELECT id FROM jarvis_imperial_raid_guard WHERE id=1 FOR UPDATE'); +} +const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});}; +const publicPolicy=()=>Object.fromEntries(['noticeMs','durationMs','baseRaiders','perDefender','maxRaiders','minDefendersOnline'].map(k=>[k,P[k]])); +const paid=row=>!!row?.accepted_json; +const accepted=row=>({ok:true,schema:1,state:'accepted',charged:true,order:JSON.parse(row.accepted_json)}); +const finalUnpaid=row=>unpaidRaidResponse(row.id,row.input_hash,row.state,row.outcome_json?JSON.parse(row.outcome_json).message:null); +const parse=value=>value?JSON.parse(value):null; +const same=(a,b)=>imperialRaidEventHash(a)===imperialRaidEventHash(b); +const selectedAccount=(quote,id)=>{const account=quote.accounts.find(a=>String(a.id)===id);if(!account)fail('Choose a currently authorised clan bank account.');if(!/^\d+$/.test(account.availableMinor)||BigInt(account.availableMinor)typeof f==='function'))throw TypeError('Authoritative Imperial raid adapters required'); + async function locked(work){return db.transaction(async tx=>{ + await lockImperialRaidGuard(tx); + return work(tx); + });} + const order=(tx,id)=>tx.first('SELECT * FROM jarvis_imperial_raid_orders WHERE id=? FOR UPDATE',[id]); + async function bind(tx,input){ + const actor=await resolveActor(tx,input.uuid,{lock:true});if(!actor?.id)fail('Link an active personal Minecraft account first.',403); + const row=await order(tx,input.requestId),hash=imperialRaidInputHash(input); + if(row&&(row.actor_id!==actor.id||row.input_hash!==hash||row.minecraft_uuid!==input.uuid))fail('This raid reference belongs to a different original intent.'); + return {actor,row,hash}; + } + async function insert(tx,input,actor,hash,state,prepared=null,message=null){ + const now=clock();await tx.query('INSERT INTO jarvis_imperial_raid_orders(id,actor_id,minecraft_uuid,input_hash,intent_json,state,prepared_json,accepted_json,created_at,expires_at,updated_at,started_at,terminal_event_id,outcome_json) VALUES(?,?,?,?,?,?,?,NULL,?,?,?,NULL,NULL,?)',[input.requestId,actor.id,input.uuid,hash,JSON.stringify(imperialRaidIntent(input)),state,prepared?JSON.stringify(prepared):null,now,prepared?.expiresAt||now,now,message?JSON.stringify({message}):null]); + return order(tx,input.requestId); + } + async function expire(tx,row){ + if(row.state==='prepared'&&Number(row.expires_at)<=clock()){ + await tx.query("UPDATE jarvis_imperial_raid_orders SET state='expired',updated_at=? WHERE id=?",[clock(),row.id]);return {...row,state:'expired'}; + }return row; + } + async function rejectPrepared(tx,row,message){ + await tx.query("UPDATE jarvis_imperial_raid_orders SET state='rejected',outcome_json=?,updated_at=? WHERE id=?",[JSON.stringify({message}),clock(),row.id]); + return finalUnpaid({...row,state:'rejected',outcome_json:JSON.stringify({message})}); + } + async function clan(tx,id,create=false){ + if(create)await tx.query('INSERT INTO jarvis_imperial_raid_clans(clan_id) VALUES(?) ON DUPLICATE KEY UPDATE clan_id=VALUES(clan_id)',[id]); + return await tx.first('SELECT * FROM jarvis_imperial_raid_clans WHERE clan_id=?'+(create?' FOR UPDATE':''),[id])||{clan_id:id}; + } + async function quote(tx,input,{lock=false}={}){ + const context=await resolveContext(tx,input,{lock}),a=await clan(tx,input.orderingClanId,lock),b=await clan(tx,input.targetClanId,lock),now=clock(); + if(input.orderingClanId===input.targetClanId)fail('Choose a rival clan.'); + if(b.active_order_id)fail('This clan already has an active Imperial raid.'); + const retaliation=a.revenge_against===input.targetClanId&&Number(a.revenge_until)>now,level=retaliation?Number(a.revenge_level)+1:0; + if(!retaliation&&a.last_order_at!==null&&a.last_order_at!==undefined&&now-Number(a.last_order_at)now+10000||!same(evidence.position,p.home.position)||evidence.worldUuid!==p.home.worldUuid||evidence.claimRevision!==p.home.claimRevision) return rejectPrepared(tx,row,'The native Home Block preflight changed or expired.'); + let q; + try{ + const intent=parse(row.intent_json),actor=await resolveActor(tx,intent.uuid,{lock:true});if(actor?.id!==row.actor_id)fail('The original linked actor changed.',403); + q=await quote(tx,intent,{lock:true}); + if(q.feeMinor!==p.feeMinor||q.level!==p.retaliationLevel||(q.chainId&&q.chainId!==p.chainId)||!same(q.context.home,p.home)||!same(q.context.authority,parse(row.outcome_json)?.authority))fail('The clan authority, fee, chain or Home Block changed.'); + selectedAccount(q,p.sourceAccountId); + if(evidence.defendersOnline=P.warAfter?null:p.orderingClanId,q.level>=P.warAfter?null:now+P.revengeMs,q.level>=P.warAfter?0:q.level,p.chainId,p.targetClanId]); + if(q.level===P.warAfter)await queue(tx,row,'war',{orderId:row.id,chainId:p.chainId,orderingClanId:p.orderingClanId,targetClanId:p.targetClanId},'waiting_start'); + return saveEvent(tx,input,{ok:true,schema:1,state:'accepted',charged:true,order:resultOrder}); + } + async function acknowledge(tx,input){ + const row=await requirePaid(tx,input),prior=await eventReplay(tx,input);if(prior)return prior; + const p=parse(row.accepted_json); + if(input.occurredAtclock()+30000)fail('Raid acknowledgement time is invalid.'); + if(input.phase==='started'){ + if(input.occurredAtclock()+30000||started===null&&(input.startedAt!==0||input.activeMillis!==0)||started!==null&&(input.startedAt!==started||input.occurredAtinput.occurredAt-started+1000))fail('The original actual raid interval is required.'); + if(!neutral&&started===null)fail('A real party start must be acknowledged before a combat outcome.'); + if(input.outcome==='survived'&&input.activeMillis!==P.durationMs)fail('The commander must survive fifteen actual active minutes.'); + if(input.outcome==='spawn_failed'&&started!==null)fail('An already started raid must use interruption, not spawn failure.'); + const state=neutral?'neutral':input.outcome==='survived'?'completed':'failed'; + await tx.query('UPDATE jarvis_imperial_raid_orders SET state=?,terminal_event_id=?,outcome_json=?,updated_at=? WHERE id=?',[state,input.eventId,JSON.stringify(input),clock(),row.id]); + await tx.query('UPDATE jarvis_imperial_raid_clans SET active_order_id=NULL WHERE clan_id=? AND active_order_id=?',[p.targetClanId,row.id]); + if(neutral){ + if(!row.war_campaign_id){ + await tx.query("UPDATE jarvis_imperial_raid_jobs SET state='cancelled' WHERE order_id=? AND kind='war' AND state IN ('waiting_start','queued','processing')",[row.id]); + await queue(tx,row,'refund',{orderId:row.id,eventId:input.eventId,outcome:input.outcome}); + } + } + else await queue(tx,row,'quest',{orderId:row.id,eventId:input.eventId,actorId:row.actor_id,outcome:input.outcome,xp:state==='completed'?1000:100}); + return saveEvent(tx,input,{...raidEventAcknowledgement(row.id,input.eventId,state),...(neutral?(row.war_campaign_id?{refundState:'not_due',refundReason:'war_started'}:{refundState:'queued'}):{})}); + } + return Object.freeze({ + async execute(value){ + const input=validateImperialRaidInput(value); + if(input.action==='context'){ + const actor=await resolveActor(db,input.uuid);if(!actor?.id)fail('Link an active personal Minecraft account first.',403); + const q=await quote(db,input),c=q.context; + return {ok:true,schema:1,context:{actorUuid:input.uuid,orderingClanId:input.orderingClanId,targetClanId:input.targetClanId,orderingClanName:c.orderingClanName,targetClanName:c.targetClanName,server:input.server,accounts:q.accounts,uniqueSourceAccountId:q.accounts.length===1?String(q.accounts[0].id):null,feeMinor:q.feeMinor,currency:'DM',chainId:q.chainId,retaliationLevel:q.level,home:c.home,policy:publicPolicy()}}; + } + if(input.action==='poll'){ + const rows=await db.query("SELECT accepted_json FROM jarvis_imperial_raid_orders WHERE state IN ('accepted','warning','started') ORDER BY created_at,id LIMIT 501"); + if(rows.length>500)fail('The active raid register requires reconciliation.'); + return {ok:true,schema:1,orders:rows.map(r=>parse(r.accepted_json)).filter(p=>p?.server===input.server)}; + } + return locked(async tx=>{ + if(input.action==='prepare')return prepare(tx,input); + if(input.action==='accept')return accept(tx,input); + if(input.action==='ack')return acknowledge(tx,input); + if(input.action==='outcome')return outcome(tx,input); + const {actor,row:old,hash}=await bind(tx,input),row=old?await expire(tx,old):null; + if(paid(row))return accepted(row); + if(input.action==='cancel_prepared'){ + if(!row)return finalUnpaid(await insert(tx,input,actor,hash,'cancelled')); + if(row.state==='prepared')await tx.query("UPDATE jarvis_imperial_raid_orders SET state='cancelled',updated_at=? WHERE id=?",[clock(),row.id]); + return finalUnpaid({...row,state:row.state==='prepared'?'cancelled':row.state}); + } + if(!row)return {ok:true,schema:1,orderId:input.requestId,requestId:input.requestId,inputHash:hash,state:'unknown',definitive:false}; + return row.state==='prepared'?{ok:true,schema:1,state:'prepared',order:parse(row.prepared_json)}:finalUnpaid(row); + }); + } + }); +} diff --git a/website/node/imperial-raid-protocol.mjs b/website/node/imperial-raid-protocol.mjs index b1027fd8..c46b9044 100644 --- a/website/node/imperial-raid-protocol.mjs +++ b/website/node/imperial-raid-protocol.mjs @@ -3,7 +3,7 @@ import {NATIVE_SERVERS} from './native-server-scope.mjs'; export const IMPERIAL_RAID_POLICY=Object.freeze({noticeMs:600000,durationMs:900000,baseRaiders:4,perDefender:1,maxRaiders:14,minDefendersOnline:0,ordererCooldownMs:86400000,targetCooldownMs:21600000,revengeMs:86400000,preparedMs:120000,baseFeeMinor:'2500000',feeStepMinor:'500000',warAfter:3}); export const IMPERIAL_RAID_OUTCOMES=Object.freeze(['survived','commander_defeated','interrupted','spawn_failed','cancelled']); -export const unpaidFinalStates=new Set(['cancelled','rejected','expired']); +const unpaidFinalStates=new Set(['cancelled','rejected','expired']); const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v); const digest=v=>typeof v==='string'&&/^[a-f0-9]{64}$/.test(v); const time=v=>Number.isSafeInteger(v)&&v>=0; diff --git a/website/node/organisation-keys.mjs b/website/node/organisation-keys.mjs index 32eec77a..3cf64527 100644 --- a/website/node/organisation-keys.mjs +++ b/website/node/organisation-keys.mjs @@ -43,7 +43,7 @@ export function createOrganisationKeys(db,{secret,editions=null,foundingScope='o foundingScope, async inspect(code,{accountId=null,expectedType=null}={}){let parsed,keyType,hash;try{parsed=parseOrganisationCode(code);keyType=Object.keys(ORGANISATION_KEY_TYPES).find(k=>ORGANISATION_KEY_TYPES[k].prefix===parsed.prefix);if(!keyType)return{valid:false,state:'unsupported'};hash=hashOrganisationKey(code,keyType);}catch{return{valid:false,state:'invalid'};}const row=await readFirst(db,'SELECT id,account_id,key_type,expires_at,revoked_at,used_at FROM organisation_keys WHERE code_hash=?',[hash]);if(!row||accountId&&row.account_id!==accountId||expectedType&&row.key_type!==expectedType)return{valid:false,state:'invalid'};if(parsed.edition){if(!editions)return{valid:false,state:'unavailable'};const edition=await editions.read(row.id);if(['stage','version','season'].some(k=>edition[k]!==parsed.edition[k]))return{valid:false,state:'invalid'};}return{valid:true,type:row.key_type,purpose:type(row.key_type).purpose,state:row.revoked_at!=null?'revoked':row.used_at!=null?'used':row.expires_at!=null&&Number(row.expires_at)<=Date.now()?'expired':'available'};}, async issue({accountId,keyType,scopeId,expiresAt=null,authorize=null,transactionStore=null}){ - if(transactionStore&&(!(keyType==='organisation-action'||keyType==='entity-state'&&accountId===STAFF_OFFICE_ACCOUNT_ID&&/^state:(?:political-decision|political-review-publication|political-agreement-reply|political-ballot-vote|imperial-rally-vote|naib-council|world-trade|war-medal):[a-f0-9-]{36}$/i.test(scopeId))||typeof transactionStore.query!=='function'||typeof transactionStore.first!=='function'))throw TypeError('A scoped action transaction is required'); + if(transactionStore&&(!(keyType==='organisation-action'||keyType==='entity-state'&&accountId===STAFF_OFFICE_ACCOUNT_ID&&/^state:(?:political-decision|political-review-publication|political-agreement-reply|political-ballot-vote|imperial-rally-vote|naib-council|world-trade|war-medal|imperial-raid|imperial-raid-refund):[a-f0-9-]{36}$/i.test(scopeId))||typeof transactionStore.query!=='function'||typeof transactionStore.first!=='function'))throw TypeError('A scoped action transaction is required'); type(keyType); if(keyType==='economy-operation'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^economy\.(reset-balances|repay-loans|federal-cycle):[a-f0-9-]{36}$/i.test(scopeId)))throw TypeError('Economic keys require a scoped system authority adapter'); if(keyType==='kit-definition'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^kitset:[a-f0-9-]{36}:v[1-9]\d{0,5}$/i.test(scopeId)))throw TypeError('Kit definitions require a saved set and authority adapter'); diff --git a/website/tests/imperial-raid-commerce.test.mjs b/website/tests/imperial-raid-commerce.test.mjs new file mode 100644 index 00000000..2d0a8868 --- /dev/null +++ b/website/tests/imperial-raid-commerce.test.mjs @@ -0,0 +1,44 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {randomUUID} from 'node:crypto'; +import {BankFixture} from './postbank-fixture.mjs'; +import {createOrganisationKeys,initializeOrganisationKeys,STAFF_OFFICE_ACCOUNT_ID} from '../node/organisation-keys.mjs'; +import {entityId} from '../node/postbank-authority.mjs'; +import {createImperialRaidCommerce,raidRecoveryId} from '../node/imperial-raid-commerce.mjs'; +import {initializeImperialRaids,createImperialRaidOrders} from '../node/imperial-raid-orders.mjs'; +const id=n=>'00000000-0000-4000-8000-'+String(n).padStart(12,'0'); +async function fixture(){ + const db=new BankFixture(),query=db.query.bind(db);db.query=(sql,args=[])=>query(sql.replace(/\) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4/g,')').replace(/UNIQUE KEY \w+\(/g,'UNIQUE(').replace(/,INDEX \w+\([^)]*\)/g,''),args); + await initializeImperialRaids(db);await initializeOrganisationKeys(db);let now=1000000000; + for(const sql of ['CREATE TABLE site_accounts(id TEXT PRIMARY KEY,username TEXT,role TEXT,password_hash TEXT)','CREATE TABLE site_game_links(user_id TEXT,minecraft_uuid TEXT)','CREATE TABLE site_clans(id TEXT PRIMARY KEY)','CREATE TABLE site_clan_deeds(clan_id TEXT PRIMARY KEY)','CREATE TABLE site_clan_charters(clan_id TEXT PRIMARY KEY,key_id TEXT)','CREATE TABLE site_clan_members(user_id TEXT,clan_id TEXT)','CREATE TABLE site_claim_registry(organisation_kind TEXT,organisation_id TEXT)'])await db.query(sql); + await db.query("INSERT INTO site_accounts VALUES(?,'synthetic_owner','citizen','synthetic-active-hash')",[id(10)]);await db.query('INSERT INTO site_game_links VALUES(?,?)',[id(10),id(1)]); + for(const clan of [id(3),id(4)]){await db.query('INSERT INTO site_clans VALUES(?)',[clan]);await db.query('INSERT INTO site_clan_deeds VALUES(?)',[clan]);await db.query('INSERT INTO site_clan_charters VALUES(?,?)',[clan,randomUUID()]);} + const entity=entityId('clan',id(3));await db.query("INSERT INTO pb_entities VALUES(?,'clan',?,'Synthetic clan',1,0)",[entity,id(3)]);await db.query("INSERT INTO pb_clients VALUES('CL0000000001',?,0)",[entity]);await db.query("INSERT INTO pb_packages VALUES(?,'CL0000000001','pb_connect',0,'synthetic',?,0,'active')",[id(20),id(10)]); + await db.query("INSERT INTO pb_accounts(id,client_number,package_id,type_code,display_name,balance_minor,created_at) VALUES(1,'CL0000000001',?,'105','Synthetic clan account',10000000,0)",[id(20)]);await db.query("INSERT INTO pb_accounts(id,type_code,display_name,system_key,balance_minor,created_at) VALUES(2,'999','Synthetic Tax treasury','sys_tax_treasury',0,0)"); + const options={war:true,debit:true,protected:false,homeServer:'arrakis',version:1}; + const keys=createOrganisationKeys(db,{secret:'a'.repeat(64)}); + const commerce=createImperialRaidCommerce(db,db,keys,{clock:()=>now,verifyStorage:async()=>undefined,verifyCampaigns:false,warAuthority:async()=>({canManageWar:options.war}),bankAuthority:()=>async()=>({entities:[{id:entity,canPay:options.debit,canView:true}]}),readState:async()=>({wars:[],clans:[{id:id(3),name:'Ordering',lifecycle:'active',version:1,ownerUuid:id(1),members:[]},{id:id(4),name:'Target',lifecycle:'active',version:options.version,ownerUuid:id(9),protected:options.protected,members:[],claimRevision:1,homeServer:options.homeServer,homeBlock:{source:'minecraft',worldUuid:id(7),position:{x:12,y:80,z:30}}}]})}); + await commerce.ready();const service=createImperialRaidOrders(db,{...commerce,clock:()=>now}); + const intent=()=>({server:'arrakis',uuid:id(1),requestId:randomUUID(),orderingClanId:id(3),targetClanId:id(4),sourceAccountId:'1'}); + const accept=async()=>{const i=intent(),r=await service.execute({action:'prepare',...i});const response=await service.execute({action:'accept',server:'arrakis',orderId:r.order.id,eventId:randomUUID(),inputHash:r.order.inputHash,preflightNonce:r.order.preflightNonce,preflight:{...r.order.home,defendersOnline:0,spawnable:true,protected:false,observedAt:now}});return {intent:i,response};}; + const neutral=async p=>service.execute({action:'outcome',server:'arrakis',orderId:p.id,eventId:randomUUID(),outcome:'spawn_failed',startedAt:0,occurredAt:now,activeMillis:0}); + return{db,keys,commerce,service,intent,accept,neutral,options,close:()=>db.close()}; +} +test('accepted raid uses the existing bank posting and scoped JARVIS key, with no key secret in the native receipt',async()=>{ + const f=await fixture();try{const {response:r}=await f.accept();assert.equal(r.state,'accepted');assert.equal((await f.db.first('SELECT balance_minor b FROM pb_accounts WHERE id=1')).b,7500000);assert.equal((await f.db.first('SELECT balance_minor b FROM pb_accounts WHERE id=2')).b,2500000);const key=await f.db.first('SELECT * FROM organisation_keys WHERE id=?',[r.order.receiptKeyId]);assert.equal(key.account_id,STAFF_OFFICE_ACCOUNT_ID);assert.equal(key.scope_id,'state:imperial-raid:'+r.order.id);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,2);assert.equal(r.order.code,undefined);assert.equal(r.order.code_sealed,undefined);}finally{f.close();} +}); +test('war authority, clan debit rights, protected targets and target backend are independent required guards',async()=>{ + for(const patch of [{war:false},{debit:false},{protected:true},{homeServer:'caladan'}]){const f=await fixture();try{Object.assign(f.options,patch);const r=await f.service.execute({action:'prepare',...f.intent()});assert.equal(r.state,'rejected');assert.equal(r.charged,false);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.close();}} +}); +test('a missing current game link cannot order or cancel another actor’s request',async()=>{ + const f=await fixture();try{await assert.rejects(f.service.execute({action:'prepare',...f.intent(),uuid:id(99)}),e=>e.status===403);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,0);}finally{f.close();} +}); +test('neutral recovery reverses exactly the original fee once through the original accounts and receipt',async()=>{ + const f=await fixture();try{const {response:r}=await f.accept();await f.neutral(r.order);const row=await f.db.first('SELECT * FROM jarvis_imperial_raid_orders WHERE id=?',[r.order.id]);const refund=()=>f.db.transaction(tx=>f.commerce.refund(tx,row));const a=await refund(),b=await refund();assert.deepEqual(a,b);assert.equal(a.refundOrderId,raidRecoveryId(r.order.id));assert.equal((await f.db.first('SELECT balance_minor b FROM pb_accounts WHERE id=1')).b,10000000);assert.equal((await f.db.first('SELECT balance_minor b FROM pb_accounts WHERE id=2')).b,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,2);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,4);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,2);}finally{f.close();} +}); +test('an unavailable treasury cannot mint or falsely mark a recovery paid',async()=>{ + const f=await fixture();try{const {response:r}=await f.accept();await f.neutral(r.order);await f.db.query('UPDATE pb_accounts SET balance_minor=1 WHERE id=2');const row=await f.db.first('SELECT * FROM jarvis_imperial_raid_orders WHERE id=?',[r.order.id]);await assert.rejects(f.db.transaction(tx=>f.commerce.refund(tx,row)),e=>e.status===409);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,1);assert.equal((await f.db.first('SELECT state FROM jarvis_imperial_raid_jobs')).state,'queued');}finally{f.close();} +}); +test('a refund cannot be redirected to a different account or amount',async()=>{ + const f=await fixture();try{const {response:r}=await f.accept();await f.neutral(r.order);const row=await f.db.first('SELECT * FROM jarvis_imperial_raid_orders WHERE id=?',[r.order.id]);for(const patch of [{sourceAccountId:'2'},{feeMinor:'5000000'}]){const changed={...row,accepted_json:JSON.stringify({...r.order,...patch})};await assert.rejects(f.db.transaction(tx=>f.commerce.refund(tx,changed)),e=>e.status===409);}assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.close();} +}); diff --git a/website/tests/imperial-raid-jobs.test.mjs b/website/tests/imperial-raid-jobs.test.mjs new file mode 100644 index 00000000..b74107f2 --- /dev/null +++ b/website/tests/imperial-raid-jobs.test.mjs @@ -0,0 +1,12 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {BankFixture} from './postbank-fixture.mjs'; +import {initializeImperialRaids} from '../node/imperial-raid-orders.mjs'; +import {processImperialRaidJobs} from '../node/imperial-raid-jobs.mjs'; +const id=n=>'00000000-0000-4000-8000-'+String(n).padStart(12,'0'); +async function fixture(){const db=new BankFixture(),query=db.query.bind(db);db.query=(s,a=[])=>query(s.replace(/\) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4/g,')'),a);await initializeImperialRaids(db);const add=(n,state='queued')=>db.query('INSERT INTO jarvis_imperial_raid_jobs(order_id,kind,payload_json,state,created_at) VALUES(?,?,?,?,?)',[id(n),'quest',JSON.stringify({orderId:id(n)}),state,n]);return{db,add,close:()=>db.close()};} +test('two workers cannot hold the same unexpired lease',async()=>{const f=await fixture();try{await f.add(1);let calls=0;const handlers={quest:async()=>{calls++;await new Promise(resolve=>setTimeout(resolve,10));return {done:true};}};await Promise.all([1,2].map(()=>processImperialRaidJobs(f.db,handlers,{clock:()=>1000})));assert.equal(calls,1);assert.equal((await f.db.first('SELECT state FROM jarvis_imperial_raid_jobs')).state,'completed');}finally{f.close();}}); +test('twenty blocked jobs rotate behind the twenty-first eligible recovery',async()=>{const f=await fixture();try{for(let n=1;n<=21;n++)await f.add(n);const handlers={quest:async(_job,p)=>{if(p.orderId!==id(21))throw Error('dependency unavailable');return {done:true};}};await processImperialRaidJobs(f.db,handlers,{clock:()=>1000});const second=await processImperialRaidJobs(f.db,handlers,{clock:()=>2000});assert.equal(second.completed,1);assert.equal((await f.db.first('SELECT state FROM jarvis_imperial_raid_jobs WHERE order_id=?',[id(21)])).state,'completed');}finally{f.close();}}); +test('an expired processing lease is recoverable and waiting-start jobs remain held',async()=>{const f=await fixture();try{await f.add(1,'processing');await f.db.query('UPDATE jarvis_imperial_raid_jobs SET lease_until=10,lease_token=?',[id(90)]);await f.add(2,'waiting_start');const result=await processImperialRaidJobs(f.db,{quest:async()=>({done:true})},{clock:()=>1000});assert.equal(result.completed,1);assert.equal((await f.db.first('SELECT state FROM jarvis_imperial_raid_jobs WHERE order_id=?',[id(2)])).state,'waiting_start');}finally{f.close();}}); +test('a cancelled job cannot be overwritten by an in-flight worker acknowledgement',async()=>{const f=await fixture();try{await f.add(1);const result=await processImperialRaidJobs(f.db,{quest:async()=>{await f.db.query("UPDATE jarvis_imperial_raid_jobs SET state='cancelled' WHERE order_id=?",[id(1)]);return{done:true};}},{clock:()=>1000});assert.equal(result.completed,0);assert.equal((await f.db.first('SELECT state FROM jarvis_imperial_raid_jobs')).state,'cancelled');}finally{f.close();}}); +test('a worker losing its lease never clears the new owner’s pending recovery',async()=>{const f=await fixture();try{await f.add(1);const result=await processImperialRaidJobs(f.db,{quest:async()=>{await f.db.query('UPDATE jarvis_imperial_raid_jobs SET lease_token=?,lease_until=99999 WHERE order_id=?',[id(99),id(1)]);return{done:true};}},{clock:()=>1000});assert.equal(result.completed,0);assert.equal((await f.db.first('SELECT lease_token FROM jarvis_imperial_raid_jobs')).lease_token,id(99));}finally{f.close();}}); diff --git a/website/tests/imperial-raid-orders.test.mjs b/website/tests/imperial-raid-orders.test.mjs new file mode 100644 index 00000000..6e7da44d --- /dev/null +++ b/website/tests/imperial-raid-orders.test.mjs @@ -0,0 +1,79 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {randomUUID} from 'node:crypto'; +import {BankFixture} from './postbank-fixture.mjs'; +import {PostbankPayments} from '../node/postbank-payments.mjs'; +import {initializeImperialRaids,createImperialRaidOrders} from '../node/imperial-raid-orders.mjs'; +import {IMPERIAL_RAID_POLICY as P} from '../node/imperial-raid-protocol.mjs'; +const id=n=>'00000000-0000-4000-8000-'+String(n).padStart(12,'0'); +async function fixture(){ + const db=new BankFixture(),query=db.query.bind(db);db.query=(sql,args=[])=>query(sql.replace(/\) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4/g,')'),args);await initializeImperialRaids(db);let now=1000000000; + await db.query("INSERT INTO pb_accounts(id,type_code,display_name,balance_minor,system_key,created_at) VALUES(1,'105','Synthetic clan A',10000000,NULL,0),(2,'999','Synthetic Tax treasury',0,'sys_tax_treasury',0),(3,'105','Synthetic clan B',10000000,NULL,0)"); + await db.query('CREATE TABLE fixture_raid_keys(id TEXT PRIMARY KEY,order_id TEXT UNIQUE)'); + const options={allowed:true,version:1,revision:1,failAfterPost:false,badReceipt:false}; + const resolveActor=async(_tx,uuid)=>[id(1),id(8)].includes(uuid)?{id:uuid===id(1)?id(10):id(11)}:null; + const resolveContext=async(tx,input)=>{ + if(!options.allowed)throw Object.assign(Error('Current clan authority changed'),{status:403}); + if(input.uuid!==(input.orderingClanId===id(3)?id(1):id(8)))throw Object.assign(Error('Not this clan owner'),{status:403}); + const account=await tx.first('SELECT * FROM pb_accounts WHERE id=?',[input.orderingClanId===id(3)?1:3]); + return {orderingClanName:'Ordering clan',targetClanName:'Target clan',authority:{version:options.version},home:{worldUuid:id(7),position:{x:12,y:80,z:30},claimRevision:options.revision},accounts:[{id:String(account.id),name:account.display_name,availableMinor:String(account.balance_minor-account.reserved_minor)}]}; + }; + const charge=async(tx,p)=>{ + const source=await tx.first('SELECT * FROM pb_accounts WHERE id=?',[p.sourceAccountId]),tax=await tx.first('SELECT * FROM pb_accounts WHERE id=2');source.entity_id=id(40); + await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[p.id,p.actorId,source.id,tax.id,p.inputHash,p.feeMinor,'Synthetic Imperial raid',now]); + await new PostbankPayments(db,null,{clock:()=>now}).post(tx,{id:p.id,actor_id:p.actorId,amount_minor:p.feeMinor},source,tax,false); + if(options.failAfterPost)throw Error('Injected failure after real ledger posting'); + const key=randomUUID();await tx.query('INSERT INTO fixture_raid_keys VALUES(?,?)',[key,p.id]); + return {receiptKeyId:options.badReceipt?'unbound':key,bankOrderId:p.id}; + }; + const service=createImperialRaidOrders(db,{resolveActor,resolveContext,charge,clock:()=>now}); + const intent=(reverse=false)=>({server:'arrakis',uuid:reverse?id(8):id(1),requestId:randomUUID(),orderingClanId:reverse?id(4):id(3),targetClanId:reverse?id(3):id(4),sourceAccountId:reverse?'3':'1'}); + const prepare=input=>service.execute({action:'prepare',...input}); + const acceptInput=p=>({action:'accept',server:p.server,orderId:p.id,eventId:randomUUID(),inputHash:p.inputHash,preflightNonce:p.preflightNonce,preflight:{...p.home,defendersOnline:0,spawnable:true,protected:false,observedAt:now}}); + const accept=async input=>{const p=await prepare(input),a=acceptInput(p.order);return {p,a,result:await service.execute(a)};}; + const start=async p=>{now=p.acceptedAt+P.noticeMs;return service.execute({action:'ack',server:p.server,orderId:p.id,eventId:randomUUID(),phase:'started',occurredAt:now});}; + const terminal=(p,outcome='survived',activeMillis=P.durationMs)=>({action:'outcome',server:p.server,orderId:p.id,eventId:randomUUID(),outcome,startedAt:p.acceptedAt+P.noticeMs,occurredAt:now,activeMillis}); + return {db,options,service,intent,prepare,acceptInput,accept,start,terminal,clock:()=>now,setTime:n=>now=n,close:()=>db.close()}; +} +test('context and prepare never post a payment; a prepared original can be read unchanged',async()=>{ + const f=await fixture();try{const i=f.intent(),c=await f.service.execute({action:'context',server:i.server,uuid:i.uuid,orderingClanId:i.orderingClanId,targetClanId:i.targetClanId});assert.equal(c.context.uniqueSourceAccountId,'1');const p=await f.prepare(i);assert.equal(p.state,'prepared');assert.equal(p.order.id,i.requestId);assert.deepEqual(await f.service.execute({action:'status',...i}),p);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.close();} +}); +test('cancellation arriving before a delayed prepare leaves a durable unpaid tombstone',async()=>{ + const f=await fixture();try{const i=f.intent(),c=await f.service.execute({action:'cancel_prepared',...i});assert.equal(c.charged,false);assert.equal(c.definitive,true);assert.deepEqual(await f.prepare(i),c);assert.deepEqual(await f.service.execute({action:'status',...i}),c);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.close();} +}); +test('unknown status is not definitive, and changing original target/account/actor cannot cancel another intent',async()=>{ + const f=await fixture();try{const i=f.intent();assert.equal((await f.service.execute({action:'status',...i})).definitive,false);await f.prepare(i);for(const patch of [{sourceAccountId:'3'},{targetClanId:id(9)},{uuid:id(8)}])await assert.rejects(f.service.execute({action:'cancel_prepared',...i,...patch}),e=>e.status===409);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.close();} +}); +test('concurrent acceptance retries use the original bank order and exactly two ledger legs',async()=>{ + const f=await fixture();try{const i=f.intent(),p=await f.prepare(i),a=f.acceptInput(p.order),results=await Promise.all([1,2,3].map(()=>f.service.execute(a)));assert.deepEqual(results[0],results[1]);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,2);assert.equal((await f.db.first('SELECT COUNT(*) n FROM fixture_raid_keys')).n,1);assert.equal((await f.db.first('SELECT balance_minor b FROM pb_accounts WHERE id=1')).b,7500000);assert.equal((await f.db.first('SELECT balance_minor b FROM pb_accounts WHERE id=2')).b,2500000);assert.equal((await f.service.execute({action:'cancel_prepared',...i})).state,'accepted');}finally{f.close();} +}); +test('cancel/accept races cannot clear a paid receipt or debit a cancelled intent',async()=>{ + for(const cancelFirst of [true,false]){const f=await fixture();try{const i=f.intent(),p=await f.prepare(i),a=f.acceptInput(p.order),cancel={action:'cancel_prepared',...i};await Promise.all((cancelFirst?[cancel,a]:[a,cancel]).map(v=>f.service.execute(v)));const result=await f.service.execute({action:'status',...i});assert.equal(result.state,cancelFirst?'cancelled':'accepted');assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,cancelFirst?0:1);}finally{f.close();}} +}); +test('expired preparation and changed authority/home/funds are definitive unpaid rejections',async()=>{ + for(const mutation of ['expiry','authority','home','funds']){const f=await fixture();try{const i=f.intent(),p=await f.prepare(i),a=f.acceptInput(p.order);if(mutation==='expiry')f.setTime(f.clock()+P.preparedMs+1);if(mutation==='authority')f.options.allowed=false;if(mutation==='home')f.options.revision++;if(mutation==='funds')await f.db.query('UPDATE pb_accounts SET balance_minor=1 WHERE id=1');const r=await f.service.execute(a);assert.equal(r.charged,false);assert.equal(r.definitive,true);assert.equal(r.state,mutation==='expiry'?'expired':'rejected');assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.close();}} +}); +test('posting/key-binding failures roll back balance, entries, key and accepted state together',async()=>{ + for(const badReceipt of [false,true]){const f=await fixture();try{const i=f.intent(),p=await f.prepare(i);f.options.badReceipt=badReceipt;f.options.failAfterPost=!badReceipt;await assert.rejects(f.service.execute(f.acceptInput(p.order)));assert.equal((await f.db.first('SELECT balance_minor b FROM pb_accounts WHERE id=1')).b,10000000);for(const table of ['pb_orders','pb_entries','fixture_raid_keys'])assert.equal((await f.db.first('SELECT COUNT(*) n FROM '+table)).n,0);assert.equal((await f.service.execute({action:'status',...i})).state,'prepared');}finally{f.close();}} +}); +test('the same event ID with changed evidence conflicts without another debit',async()=>{ + const f=await fixture();try{const {a}=await f.accept(f.intent());await assert.rejects(f.service.execute({...a,preflight:{...a.preflight,defendersOnline:1}}),e=>e.status===409);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.close();} +}); +test('an empty party or short active duration cannot create a success quest',async()=>{ + const f=await fixture();try{const {result}=await f.accept(f.intent()),p=result.order;await assert.rejects(f.service.execute({...f.terminal(p),startedAt:0,activeMillis:0}),e=>e.status===409);await f.start(p);f.setTime(f.clock()+1000);await assert.rejects(f.service.execute(f.terminal(p,'survived',1000)),e=>e.status===409);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_imperial_raid_jobs')).n,0);}finally{f.close();} +}); +test('full survival and commander defeat queue exactly the approved Reputation result once',async()=>{ + for(const outcome of ['survived','commander_defeated']){const f=await fixture();try{const {result}=await f.accept(f.intent()),p=result.order;await f.start(p);f.setTime(f.clock()+(outcome==='survived'?P.durationMs:1000));const e=f.terminal(p,outcome,outcome==='survived'?P.durationMs:1000),r=await f.service.execute(e);assert.equal(r.orderId,p.id);assert.equal(r.eventId,e.eventId);assert.deepEqual(await f.service.execute(e),r);const jobs=await f.db.query('SELECT * FROM jarvis_imperial_raid_jobs');assert.equal(jobs.length,1);assert.equal(jobs[0].kind,'quest');const payload=JSON.parse(jobs[0].payload_json);assert.equal(payload.xp,outcome==='survived'?1000:100);assert.equal(payload.personalXP,undefined);assert.equal(payload.amountMinor,undefined);await assert.rejects(f.service.execute({...e,eventId:randomUUID()}),x=>x.status===409);}finally{f.close();}} +}); +test('post-accept spawn failure queues only an original-payment refund and no quest',async()=>{ + const f=await fixture();try{const {result}=await f.accept(f.intent()),p=result.order,e={...f.terminal(p,'spawn_failed',0),startedAt:0},r=await f.service.execute(e);assert.equal(r.state,'neutral');assert.equal(r.refundState,'queued');assert.deepEqual(await f.service.execute(e),r);const jobs=await f.db.query('SELECT * FROM jarvis_imperial_raid_jobs');assert.equal(jobs.length,1);assert.equal(jobs[0].kind,'refund');assert.equal(JSON.parse(jobs[0].payload_json).orderId,p.id);assert.equal((await f.db.first('SELECT balance_minor b FROM pb_accounts WHERE id=1')).b,7500000);}finally{f.close();} +}); +test('third paid retaliation queues one chain-bound original-war job at25/30/35/40k fees',async()=>{ + const f=await fixture();try{const orders=[];for(let n=0;n<4;n++){const {result}=await f.accept(f.intent(n%2===1)),p=result.order;orders.push(p);await f.start(p);f.setTime(f.clock()+1000);await f.service.execute(f.terminal(p,'commander_defeated',1000));}assert.deepEqual(orders.map(p=>p.feeMinor),['2500000','3000000','3500000','4000000']);assert.equal(new Set(orders.map(p=>p.chainId)).size,1);const jobs=await f.db.query("SELECT * FROM jarvis_imperial_raid_jobs WHERE kind='war'");assert.equal(jobs.length,1);assert.equal(JSON.parse(jobs[0].payload_json).chainId,orders[0].chainId);assert.equal((await f.db.first('SELECT balance_minor b FROM pb_accounts WHERE id=2')).b,13000000);assert.equal((await f.prepare(f.intent())).state,'rejected');}finally{f.close();} +}); +test('a third retaliation that never starts cancels escalation before queuing its original-fee recovery',async()=>{ + const f=await fixture();try{for(let n=0;n<3;n++){const {result}=await f.accept(f.intent(n%2===1)),p=result.order;await f.start(p);f.setTime(f.clock()+1000);await f.service.execute(f.terminal(p,'commander_defeated',1000));}const {result}=await f.accept(f.intent(true)),p=result.order;assert.equal((await f.db.first("SELECT state FROM jarvis_imperial_raid_jobs WHERE order_id=? AND kind='war'",[p.id])).state,'waiting_start');await f.service.execute({...f.terminal(p,'spawn_failed',0),startedAt:0});assert.equal((await f.db.first("SELECT state FROM jarvis_imperial_raid_jobs WHERE order_id=? AND kind='war'",[p.id])).state,'cancelled');assert.equal((await f.db.first("SELECT state FROM jarvis_imperial_raid_jobs WHERE order_id=? AND kind='refund'",[p.id])).state,'queued');}finally{f.close();} +}); +test('neutral interruption cannot refund an automatic war already committed for that order',async()=>{ + const f=await fixture();try{const {result}=await f.accept(f.intent()),p=result.order;await f.start(p);await f.db.query('UPDATE jarvis_imperial_raid_orders SET war_campaign_id=? WHERE id=?',[id(90),p.id]);f.setTime(f.clock()+1000);const r=await f.service.execute(f.terminal(p,'interrupted',1000));assert.equal(r.refundState,'not_due');assert.equal(r.refundReason,'war_started');assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_imperial_raid_jobs')).n,0);}finally{f.close();} +});