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']); 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}; }