From 525be204dd1eb6f8b1f3b216d1156b9667a71148 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:36:17 +0100 Subject: [PATCH] Define strict Imperial raid intent and acknowledgement contract --- .../docs/PILLAGER-RAID-CONTRACT-20261129.md | 44 +++++++++++++++ website/node/imperial-raid-protocol.mjs | 55 +++++++++++++++++++ website/tests/imperial-raid-protocol.test.mjs | 29 ++++++++++ 3 files changed, 128 insertions(+) create mode 100644 website/docs/PILLAGER-RAID-CONTRACT-20261129.md create mode 100644 website/node/imperial-raid-protocol.mjs create mode 100644 website/tests/imperial-raid-protocol.test.mjs diff --git a/website/docs/PILLAGER-RAID-CONTRACT-20261129.md b/website/docs/PILLAGER-RAID-CONTRACT-20261129.md new file mode 100644 index 00000000..a5da29e0 --- /dev/null +++ b/website/docs/PILLAGER-RAID-CONTRACT-20261129.md @@ -0,0 +1,44 @@ +# Beta 1.0.2.0 — Imperial raid bridge contract + +Implementation in progress. The protocol validator is executable and tested, but this document alone does not register an endpoint, charge money, enable raids or prove deployment. No real payment is used for testing. The completed-release backup is verified at `unimatrixgit/serverplugins` main3485eec4 and `unimatrixgit/duneweb` main0097a856; all19/11 branches match DuneGit and both fresh full-history clones pass Git integrity checks. The previous backup and Claude branch are unchanged. + +## Authority and transport + +Use the existing authenticated native game bridge at `/internal/game/imperial-raids`. The connector supplies its actual canonical server. Initial scope is the loaded target Home Block on that same backend/world; crossworld requests fail with travel guidance. No remote world loading or interplanetary war system is implied. + +Every request is JSON with exactly `action`, `server` and the fields for that action below. UUIDs are lowercase canonical strings, account IDs and minor-unit monetary amounts are strings, input hashes are64 lowercase hexadecimal characters, times/durations are integer milliseconds. Unknown fields are rejected. The fixed policy is ten-minute warning, fifteen actual active raid minutes, base4 raiders plus1 per defender capped14, no newly invented minimum-defender requirement,24h ordering cooldown and6h target cooldown. Retaliation fees are2500000/3000000/3500000/4000000 minor units for chain levels0/1/2/3. Fee recipient is the existing Tax treasury, matching the supplied raid design. + +Context and preparation require a linked active personal actor, current clan-war authority and eligible CLAN bank debit authority. Do not fall back to an owner's personal account. Select the eligible account automatically only if exactly one exists; otherwise require an explicit selector. Friendly/protected/unavailable targets, conflicting wars, changed deeds/Home Blocks, cooldowns and insufficient funds fail closed. Native faction projection is a preflight, not the bank/deed authority. + +## Actions + +- `context`: `uuid, orderingClanId, targetClanId`. Returns `{ok:true,schema:1,context:{actorUuid,orderingClanId,targetClanId,orderingClanName,targetClanName,server,accounts:[{id,name,availableMinor}],uniqueSourceAccountId,feeMinor,currency:'DM',chainId,retaliationLevel,home,policy}}`. `uniqueSourceAccountId` is null unless exactly one eligible account exists. No debit or paid permit. +- `prepare`: `uuid, requestId, orderingClanId, targetClanId, sourceAccountId`. Returns `{ok:true,schema:1,state:'prepared',order:{id,requestId,inputHash,preflightNonce,preparedAt,expiresAt,actorUuid,orderingClanId,targetClanId,orderingClanName,targetClanName,sourceAccountId,feeMinor,currency:'DM',server,chainId,retaliationLevel,home,policy}}`. `id=requestId`, expiry is two minutes. `home={worldUuid,position:{x,y,z},claimRevision}` and public `policy={noticeMs,durationMs,baseRaiders,perDefender,maxRaiders,minDefendersOnline}`. Preparation cannot debit or spawn. +- `status`: exactly the same original intent fields as prepare. Reads the original request, never changes its target/account. A missing intent returns `state:'unknown',definitive:false` and cannot unlock an uncertain client reference. A prepared intent returns the original prepared order; a paid intent returns the original accepted receipt. +- `cancel_prepared`: exactly the same original intent fields as prepare. Atomically cancels an unpaid intent. If it has not arrived yet, create a cancellation tombstone for that original intent, so a delayed prepare cannot revive it. Cancellation does not require retained clan-debit rights, but requires the original linked actor and exact original binding. A different actor/target/account using the same ID conflicts. +- `accept`: `orderId,eventId,inputHash,preflightNonce,preflight`, where `preflight={worldUuid,position:{x,y,z},claimRevision,defendersOnline,spawnable:true,protected:false,observedAt}`. `protected` refers to actual raid exclusion/protected-target policy, not a blanket refusal of the target's own estate. Native preflight is current and within the prepared expiry; central rechecks every authority, current quote/chain/Home Block and available balance. Use the existing atomic Postbank posting and JARVIS key transaction; no separately committed debit. Accepted response is `{ok:true,schema:1,state:'accepted',charged:true,order:acceptedOrder}`; acceptedOrder extends the original order with `receiptKeyId,bankOrderId,acceptedAt`. Same event/order retries return the same receipt, never another charge. Changed event data conflicts. +- `poll`: no extra fields. Returns `{ok:true,schema:1,orders:[acceptedOrder,...]}` for this backend only. Never returns prepared orders as spawnable. The native journal deduplicates the same receipt across all warnings/starts/retries. +- `ack`: `orderId,eventId,phase,occurredAt`, where phase is `warning` or `started`. The event is durable and input-bound. Success echoes `{ok:true,schema:1,orderId,eventId,state}` with warning/started state. A generic success cannot clear the outbox. +- `outcome`: `orderId,eventId,outcome,startedAt,occurredAt,activeMillis`. Outcomes are `survived`, `commander_defeated`, `interrupted`, `spawn_failed`, `cancelled`. Success echoes `{ok:true,schema:1,orderId,eventId,state}`; terminal state is completed/failed/neutral. Original event and immutable order bindings are checked before acknowledgement. No unrecorded/empty party can produce a victory. + +The canonical intent hash is SHA256 of the UTF-8 JSON array `[server,uuid,requestId,orderingClanId,targetClanId,sourceAccountId]` in that exact order. Prepare/status/cancel share it, ignoring action. UUIDs are normalized before hashing. This is an input binding, not a replacement authentication credential. The accepted immutable order/key also seals the authoritative quoted fee, chain, account and Home Block; caller-provided values never replace those terms. + +## Unpaid rejection and safe resumption + +Definitive unpaid responses are exactly `{ok:true,schema:1,orderId,requestId,inputHash,state,definitive:true,charged:false,message?}`, where state is cancelled/rejected/expired. Both IDs equal the original request UUID. Native may unlock only after matching IDs and the original hash. A business rejection persists an unpaid tombstone; malformed input or transient backend failure is not silently reclassified as a definitive rejection. + +`cancel_prepared` is idempotent and wins races against a delayed preparation through the same order transaction lock. Expired preparations are recorded as unpaid expired. Once payment was accepted, cancellation cannot return an unpaid response; return the original accepted order instead. Never clear on generic409/503, generate a fresh request ID on timeout, or accept a generic `ok:true` as acknowledgement. The native pending intent is journaled before its first network request. + +## Spawn, terminal result and original-payment recovery + +`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. + +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. + +## Release gates + +Require transactional/replay/cancel-race tests, actor/deed/funding/Home Block changes, failed posting rollback, terminal/reward/refund/war idempotency, ordinary war regressions and actual retained-backend compatibility. Native and central source must both pass exact-head CI before any rollout. Existing private backups and source history copies are recovery inputs, not permission to replace working backends indiscriminately. No live financial transaction or raid is run as an agent test. diff --git a/website/node/imperial-raid-protocol.mjs b/website/node/imperial-raid-protocol.mjs new file mode 100644 index 00000000..b1027fd8 --- /dev/null +++ b/website/node/imperial-raid-protocol.mjs @@ -0,0 +1,55 @@ +import {createHash} from 'node:crypto'; +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 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; +const account=v=>typeof v==='string'&&/^[1-9]\d{0,11}$/.test(v); +const object=v=>v!==null&&typeof v==='object'&&!Array.isArray(v); +const exact=(v,fields)=>object(v)&&Object.keys(v).length===fields.length&&fields.every(k=>Object.hasOwn(v,k)); +const fail=message=>{throw Object.assign(Error(message),{status:400});}; +const intentFields=['uuid','requestId','orderingClanId','targetClanId','sourceAccountId']; +const fields=Object.freeze({ + context:['uuid','orderingClanId','targetClanId'], + prepare:intentFields,status:intentFields,cancel_prepared:intentFields, + accept:['orderId','eventId','inputHash','preflightNonce','preflight'], + poll:[],ack:['orderId','eventId','phase','occurredAt'], + outcome:['orderId','eventId','outcome','startedAt','occurredAt','activeMillis'] +}); +export function validateImperialRaidInput(value){ + if(!object(value)||!Object.hasOwn(fields,value.action)||!exact(value,['action','server',...fields[value.action]])||!NATIVE_SERVERS.includes(value.server)||value.server==='lobby')fail('Invalid Imperial raid request.'); + const input=structuredClone(value); + for(const k of ['uuid','requestId','orderingClanId','targetClanId','orderId','eventId','preflightNonce'])if(Object.hasOwn(input,k)){ + if(!uuid(input[k]))fail('Invalid Imperial raid reference.');input[k]=input[k].toLowerCase(); + } + if(Object.hasOwn(input,'sourceAccountId')&&!account(input.sourceAccountId))fail('Choose a current clan funding account.'); + if(input.action==='accept'){ + const p=input.preflight; + if(!digest(input.inputHash)||!exact(p,['worldUuid','position','claimRevision','defendersOnline','spawnable','protected','observedAt'])||!uuid(p.worldUuid)||!exact(p.position,['x','y','z'])||!Object.values(p.position).every(v=>Number.isFinite(v)&&Math.abs(v)<=30000000)||!Number.isSafeInteger(p.claimRevision)||p.claimRevision<1||!Number.isSafeInteger(p.defendersOnline)||p.defendersOnline<0||p.defendersOnline>5000||p.spawnable!==true||p.protected!==false||!time(p.observedAt))fail('A current safe native preflight is required.'); + p.worldUuid=p.worldUuid.toLowerCase(); + } + if(input.action==='ack'&&(!['warning','started'].includes(input.phase)||!time(input.occurredAt)))fail('Invalid raid acknowledgement.'); + if(input.action==='outcome'&&(!IMPERIAL_RAID_OUTCOMES.includes(input.outcome)||!time(input.startedAt)||!time(input.occurredAt)||!time(input.activeMillis)||input.activeMillis>IMPERIAL_RAID_POLICY.durationMs))fail('Invalid raid outcome.'); + return input; +} +// The same canonical intent binds prepare, status and cancellation. A cancel can +// therefore win a race against a delayed prepare without a paid operation. +export function imperialRaidIntent(input){ + const {server,uuid,requestId,orderingClanId,targetClanId,sourceAccountId}=input; + return {server,uuid,requestId,orderingClanId,targetClanId,sourceAccountId}; +} +export const imperialRaidInputHash=input=>createHash('sha256').update(JSON.stringify(Object.values(imperialRaidIntent(input)))).digest('hex'); +const canonical=value=>Array.isArray(value)?value.map(canonical):object(value)?Object.fromEntries(Object.keys(value).sort().map(k=>[k,canonical(value[k])])):value; +export const imperialRaidEventHash=input=>createHash('sha256').update(JSON.stringify(canonical(input))).digest('hex'); +export function imperialRaidFee(level){if(!Number.isSafeInteger(level)||level<0||level>IMPERIAL_RAID_POLICY.warAfter)throw TypeError('Invalid retaliation level');return (BigInt(IMPERIAL_RAID_POLICY.baseFeeMinor)+BigInt(IMPERIAL_RAID_POLICY.feeStepMinor)*BigInt(level)).toString();} +export function unpaidRaidResponse(orderId,inputHash,state,message=null){ + if(!uuid(orderId)||!digest(inputHash)||!unpaidFinalStates.has(state))throw TypeError('A definitive unpaid state is required'); + return {ok:true,schema:1,orderId,requestId:orderId,inputHash,state,definitive:true,charged:false,...(message?{message}:{} )}; +} +export function raidEventAcknowledgement(orderId,eventId,state){ + if(!uuid(orderId)||!uuid(eventId)||!['warning','started','completed','failed','neutral'].includes(state))throw TypeError('Bound raid acknowledgement required'); + return {ok:true,schema:1,orderId,eventId,state}; +} diff --git a/website/tests/imperial-raid-protocol.test.mjs b/website/tests/imperial-raid-protocol.test.mjs new file mode 100644 index 00000000..d599c6be --- /dev/null +++ b/website/tests/imperial-raid-protocol.test.mjs @@ -0,0 +1,29 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {validateImperialRaidInput,imperialRaidInputHash,imperialRaidEventHash,imperialRaidFee,unpaidRaidResponse,raidEventAcknowledgement} from '../node/imperial-raid-protocol.mjs'; +const id=n=>'00000000-0000-4000-8000-'+String(n).padStart(12,'0'); +const intent={server:'arrakis',uuid:id(1),requestId:id(2),orderingClanId:id(3),targetClanId:id(4),sourceAccountId:'12'}; +test('prepare, status and cancellation bind exactly the same original intent',()=>{ + const hashes=['prepare','status','cancel_prepared'].map(action=>imperialRaidInputHash(validateImperialRaidInput({action,...intent}))); + assert.equal(new Set(hashes).size,1); + for(const [key,value] of [['sourceAccountId','13'],['targetClanId',id(9)],['uuid',id(8)],['server','kaitain']])assert.notEqual(imperialRaidInputHash({...intent,[key]:value}),hashes[0]); +}); +test('reject unknown fields, lobby execution, numeric account IDs and malformed references',()=>{ + for(const input of [{action:'prepare',...intent,feeMinor:'1'},{action:'prepare',...intent,server:'lobby'},{action:'prepare',...intent,sourceAccountId:12},{action:'prepare',...intent,requestId:'new-ref'}])assert.throws(()=>validateImperialRaidInput(input)); +}); +test('accept requires the exact current native safety evidence, not a generic success boolean',()=>{ + const input={action:'accept',server:'arrakis',orderId:id(2),eventId:id(5),inputHash:imperialRaidInputHash(intent),preflightNonce:id(6),preflight:{worldUuid:id(7),position:{x:12,y:80,z:30},claimRevision:1,defendersOnline:0,spawnable:true,protected:false,observedAt:1000}}; + assert.equal(validateImperialRaidInput(input).preflight.spawnable,true); + assert.notEqual(imperialRaidEventHash(input),imperialRaidEventHash({...input,preflight:{...input.preflight,claimRevision:2}})); + for(const patch of [{protected:true},{spawnable:false},{claimRevision:0},{defendersOnline:-1},{position:{x:NaN,y:80,z:30}},{extra:true}])assert.throws(()=>validateImperialRaidInput({...input,preflight:{...input.preflight,...patch}})); +}); +test('retaliation fees use exact minor-unit amounts and stop at the war threshold',()=>{ + assert.deepEqual([0,1,2,3].map(imperialRaidFee),['2500000','3000000','3500000','4000000']);assert.throws(()=>imperialRaidFee(4)); +}); +test('only a bound definitive unpaid response can release a prepared reference',()=>{ + const r=unpaidRaidResponse(id(2),imperialRaidInputHash(intent),'cancelled');assert.equal(r.charged,false);assert.equal(r.definitive,true);assert.equal(r.orderId,id(2)); + assert.throws(()=>unpaidRaidResponse(id(2),imperialRaidInputHash(intent),'accepted'));assert.throws(()=>unpaidRaidResponse(id(2),'not-bound','cancelled')); +}); +test('acknowledgements bind both original order and original event',()=>{ + assert.deepEqual(raidEventAcknowledgement(id(2),id(5),'started'),{ok:true,schema:1,orderId:id(2),eventId:id(5),state:'started'});assert.throws(()=>raidEventAcknowledgement(id(2),'generic-ok','started')); +});