Fund verified rebellion rewards and prepare a gated current reset review
This commit is contained in:
parent
14b2daf099
commit
3cd9efcfa6
9 changed files with 232 additions and 4 deletions
13
docs/design/ALPHA-RESET-CURRENT-REVIEW.md
Normal file
13
docs/design/ALPHA-RESET-CURRENT-REVIEW.md
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
# Current alpha reset review — ticket 409
|
||||
|
||||
This ticket authorizes preparation only. `node ops/prepare-alpha-reset.mjs` emits a dated current inventory and a separately hashed proposed manifest. It accepts no arguments and has no execution, key-issuance, archive, deletion or balance-write route. Each database is read in its own read-only repeatable-read transaction. Schema initializers are not called. A later executor must reject stale inventory and obtain explicit confirmation of the exact scope/hash.
|
||||
|
||||
The inventory records current account balances/reservations, unresolved orders, auction holds/auctions, deed purchases, credit obligations/instalments/actions, reward jobs, project jobs, payroll items, standing instructions and financial policy versions. It also records actual institutions, organisations, current/legacy deed relationships, archived clans, claims, founding-key state and separate kit/non-kit listings. Secret key codes/hashes, credentials and raw claim snapshots are excluded. Currency values retain database precision.
|
||||
|
||||
All current organisations are provisionally retained pending review of the latest owner exceptions. The manifest separately identifies protected institutions from their registries and the owner's complete descendant network, including purchased clans and company subsidiaries. Authoritative key relations take precedence over legacy deed links. Previously archived clans remain archived; the report does not repeat their archive. There are no roster, charter, homeblock or claim mutations. Kits are explicitly retained; other open listings are listed for review rather than assumed to be disposable test data.
|
||||
|
||||
The prior intent to zero DM balances, including system reserves, is represented as exact current account IDs for a future confirmed operation. It is not executed or authorized by this report. Existing obligations must first be individually reconciled through their existing adapters. No blanket cancellation, ledger rewrite or private creditor loss is proposed. A funded new budget and economic reference remain explicit unapproved inputs, never a fabricated default or test-history/zero-denominator baseline.
|
||||
|
||||
Founding-key history, used/revoked states, existing contracts and financial audit remain intact. There is no automatic entitlement reactivation or replacement issuance. Any later replacement must use the existing instrument lifecycle and reject duplicate live entitlements. Staging deletion scope is empty. A review run is not proof of a completed reset.
|
||||
|
||||
The historical `alpha-reset-plan.mjs` proposal is not consumed by this command and does not establish the current approved scope. Nothing runs at startup or deployment. The report is an administrative review artifact, not a new control panel.
|
||||
13
docs/design/QUEST-REWARD-FUNDING.md
Normal file
13
docs/design/QUEST-REWARD-FUNDING.md
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
# Funded rebellion rewards
|
||||
|
||||
The existing verified rebellion claim creates Reputation XP and one durable monetary job. The fixed reward remains 25,000 DM for Emperor or 5,000 DM for another compatible office, with the existing first-success and counter-challenge policy. XP belongs to the incoming holder; money belongs to the winning clan.
|
||||
|
||||
`REBELLION_REWARD_FUND=website-treasury` selects the existing funded Website Bank Treasury (`sys_web_treasury`), using the official DuneRealms account as the recorded service actor. It does not use that account's personal Start balance. It does not debit a player, defeated ruler, office, tax reserve, capital issuer or compensation reserve. It cannot mint currency, overdraw funds or consume existing reservations. Insufficient available treasury funds retain the job for review/retry. Explicit legacy ordinary-account funding remains supported when this setting is absent.
|
||||
|
||||
This private consumer is not a new browser action, bank permission, ledger or scheduler. The existing central minute scheduler drains verified jobs. The consumer posts a `system` order through `PostbankPayments.post`, with the existing two balanced ledger entries and audit in one bank transaction. It has no API for arbitrary recipients or staff-entered reward amounts.
|
||||
|
||||
Before payment, the caller locks the actual consumed, unrevoked QST instruction and checks its owner, type, season, request scope, declared winning clan, holder, office, challenge and reward bonus against the durable rebellion receipt and policy. The consumer rechecks the current official service identity, locks the actual clan bank entity and treasury/recipient accounts, then checks available funds and account state. It pays only an active ordinary account of that exact clan. The quest UUID is the bank order UUID and immutable fingerprint reference. Concurrent attempts and a crash after the bank commit recover the same posted order; they never issue another payment. A conflicting receipt remains for review.
|
||||
|
||||
The central and bank databases do not share a transaction. Recovery therefore relies on the existing durable bank order and unique quest reference, rather than a claim of cross-database atomicity. Once bank payment is durable it is not reversed by a later source revocation. Historical payments remain history.
|
||||
|
||||
No real rebellion, capture, office transfer or payout is manufactured for deployment verification. The game producer remains future integration; isolated signed-key fixtures exercise the full existing office/XP/reward chain, funding failures, revocation, concurrency and lost acknowledgements. Live verification checks source publication, the explicit selected funding setting, the current funded treasury and the absence/presence of real pending jobs without creating them.
|
||||
|
|
@ -465,7 +465,7 @@ export async function startPanel(settings=process.env){
|
|||
const bankDatabase=await openPostbankDatabase(settings);
|
||||
const db=await openDatabase(settings);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
|
||||
await initializeInternalMailAccess(db);const stopElectionClock=startElectionClock(db);const stopOfficeLedger=startOfficeLedger(db);
|
||||
const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:[{key:'starter_kit_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>starterKitDelivery.drain()},...(boardRuntime?[{key:'board_keys',slot:now=>Math.floor(now/60000)*60000,run:()=>boardRuntime.drain()}]:[]),...(bankDatabase?[{key:'rebellion_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createRebellionRewards(db,bankDatabase,{sourceAccount:settings.REBELLION_REWARD_SOURCE_ACCOUNT,sourceOwnerId:settings.REBELLION_REWARD_SOURCE_OWNER_ID}).drain()},...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[])]});
|
||||
const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:[{key:'starter_kit_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>starterKitDelivery.drain()},...(boardRuntime?[{key:'board_keys',slot:now=>Math.floor(now/60000)*60000,run:()=>boardRuntime.drain()}]:[]),...(bankDatabase?[{key:'rebellion_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createRebellionRewards(db,bankDatabase,{sourceAccount:settings.REBELLION_REWARD_SOURCE_ACCOUNT,sourceOwnerId:settings.REBELLION_REWARD_SOURCE_OWNER_ID,useWebsiteTreasury:settings.REBELLION_REWARD_FUND==='website-treasury'}).drain()},...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[])]});
|
||||
const security={'X-Robots-Tag':'noindex, nofollow, noarchive','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':"default-src 'self'; script-src 'self' https://www.dunerealms.com; style-src 'self' https://www.dunerealms.com https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://www.dunerealms.com; img-src 'self' data: https://www.dunerealms.com https://support.dunerealms.com; frame-src 'self' https://luckperms.net https://www.dunerealms.com https://support.dunerealms.com https://forums.dunerealms.com https://clans.dunerealms.com https://corp.dunerealms.com https://wiki.dunerealms.com; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'self' https://www.dunerealms.com https://dunerealms.com https://clans.dunerealms.com"};
|
||||
const server=createServer(async(req,res)=>{try{
|
||||
req.setTimeout(req.url==='/api/internal-mail/messages/send'?120000:30000);const bodyLimit=panelBodyLimit(req.method,req.url);let length=0;const chunks=[];for await(const chunk of req){length+=chunk.length;if(length>bodyLimit){res.writeHead(413,{...security,'Content-Type':'application/json'});res.end(JSON.stringify({message:'The upload exceeds the permitted request size.'}));return;}chunks.push(chunk);}
|
||||
|
|
|
|||
33
website/node/alpha-reset-review.mjs
Normal file
33
website/node/alpha-reset-review.mjs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import {createHash} from 'node:crypto';
|
||||
const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
const sorted=values=>[...new Set(values)].sort();
|
||||
|
||||
// Deliberately separate from the historical broad reset proposal. This current
|
||||
// review has no executor and cannot authorize a key, mutation or startup reset.
|
||||
export function buildAlphaResetReview(inventory,{ownerId,release,observedAt}={}){
|
||||
if(!ownerId||!release||!Number.isSafeInteger(observedAt))throw TypeError('Current inventory identity required');
|
||||
for(const field of ['clans','companies','relations','clanInstitutions','companyInstitutions','claims','foundingKeys','accounts','orders','auctionHolds','auctions','deedPurchases','loans','creditActions','creditInstalments','questRewards','polRewards','listings','kitListings','projectJobs','payrollItems','additionalPayrollItems'])if(!Array.isArray(inventory[field]))throw TypeError('Incomplete current inventory: '+field);
|
||||
const ownClanIds=inventory.clans.filter(c=>c.owner_id===ownerId).map(c=>c.id),ownCompanyIds=inventory.companies.filter(c=>c.owner_account_id===ownerId||c.founded_by===ownerId).map(c=>c.id);
|
||||
const protectedObjects=new Set([...inventory.clanInstitutions.map(r=>'clan:'+r.clan_id),...inventory.companyInstitutions.map(r=>'company:'+r.company_id)]);
|
||||
const ownerNetwork=new Set([...ownClanIds.map(id=>'clan:'+id),...ownCompanyIds.map(id=>'company:'+id)]);
|
||||
let changed=true;while(changed){changed=false;for(const r of inventory.relations){const parent=r.parent_kind+':'+r.parent_id,child=r.child_kind+':'+r.child_id;if(ownerNetwork.has(parent)&&!ownerNetwork.has(child)){ownerNetwork.add(child);changed=true;}}}
|
||||
const unresolved={orders:inventory.orders.filter(r=>!['posted','failed','cancelled','rejected'].includes(r.state)),auctionHolds:inventory.auctionHolds.filter(r=>!['released','settled','cancelled'].includes(r.state)),auctions:inventory.auctions.filter(r=>!['completed','cancelled','closed','settled'].includes(r.state)),deedPurchases:inventory.deedPurchases.filter(r=>!['posted','cancelled','failed'].includes(r.state)),loans:inventory.loans.filter(r=>!['repaid','closed','cancelled','rejected','expired'].includes(r.state)),creditActions:inventory.creditActions.filter(r=>!['posted','completed','cancelled','failed','rejected'].includes(r.state)),creditInstalments:inventory.creditInstalments.filter(r=>r.state!=='paid'),questRewards:inventory.questRewards.filter(r=>!['delivered','paid','cancelled'].includes(r.state)),polRewards:inventory.polRewards.filter(r=>!['delivered','paid','cancelled'].includes(r.state)),reservations:inventory.accounts.filter(r=>BigInt(r.reserved_minor)!==0n)};
|
||||
unresolved.projectJobs=inventory.projectJobs.filter(r=>!['completed','applied','cancelled','failed'].includes(r.state));unresolved.payrollItems=inventory.payrollItems;unresolved.additionalPayrollItems=inventory.additionalPayrollItems;
|
||||
const obligations=Object.fromEntries(Object.entries(unresolved).map(([kind,rows])=>[kind,{count:rows.length,rows}]));
|
||||
const proposed={
|
||||
// Preserve all organisations by default. Latest owner exceptions, descendants
|
||||
// and previously archived objects are explicit, never inferred from names.
|
||||
preserveOrganisations:sorted([...inventory.clans.map(r=>'clan:'+r.id),...inventory.companies.map(r=>'company:'+r.id)]),
|
||||
protectedObjects:sorted(protectedObjects),ownerNetwork:sorted(ownerNetwork),
|
||||
alreadyArchivedClanIds:sorted(inventory.clans.filter(r=>!Number(r.active)).map(r=>r.id)),
|
||||
archiveClanIds:[],deleteCompanyIds:[],charterChanges:[],rosterChanges:[],homeBlockChanges:[],claimChanges:[],
|
||||
retainKitListingIds:sorted(inventory.kitListings.map(r=>r.id)),
|
||||
nonKitListingIdsForReview:sorted(inventory.listings.filter(r=>r.state==='open').map(r=>r.id)),
|
||||
closeListingIds:[],balanceZeroAccountIds:sorted(inventory.accounts.map(r=>String(r.id))),
|
||||
foundingEntitlementChanges:[],newBudget:null,newEconomicReference:null,
|
||||
preserveAllHistoricalKeys:true,preserveContractsAndFinancialAudit:true,stagingDeletionIds:[]
|
||||
};
|
||||
return {schemaVersion:1,ticketId:409,release,observedAt,readOnly:true,executionAuthorized:false,executable:false,inventoryHash:hash(inventory),proposedManifestHash:hash(proposed),inventory,obligations,proposed,
|
||||
gates:['Confirm this exact manifest hash and the current owner exceptions before any execution.','Re-inventory and reject any stale manifest before issuing a reset key.','Resolve each current obligation through its existing domain adapter; no blanket reservation cancellation.','Approve a funded new budget and economic reference; no test-history or zero-denominator baseline.','No automatic entitlement reactivation. Any later replacement must preserve history and enforce one live entitlement.','No reset at startup, deployment or review generation. No additional staging deletion.'],
|
||||
snapshotConsistency:'Each database is a separate read-only repeatable-read snapshot. The report does not claim a cross-database atomic snapshot; the final execution gate requires fresh reconciliation.'};
|
||||
}
|
||||
30
website/node/quest-treasury-payments.mjs
Normal file
30
website/node/quest-treasury-payments.mjs
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import {createHash} from 'node:crypto';
|
||||
import {PostbankPayments} from './postbank-payments.mjs';
|
||||
import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
|
||||
import {OFFICIAL_ACCOUNT} from './official-account.mjs';
|
||||
|
||||
export const QUEST_TREASURY='sys_web_treasury';
|
||||
const accounts='SELECT a.*,c.entity_id,e.kind,e.external_key,e.active AS entity_active,p.state AS 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';
|
||||
// Private domain consumer, not a staff/browser transfer permission. Its caller
|
||||
// holds the actual consumed quest instruction lock until this bank commit.
|
||||
export function createQuestTreasuryPayments(bank,{authorize,clock=Date.now}={}){
|
||||
if(typeof authorize!=='function')throw TypeError('A current verified quest authorizer is required');
|
||||
const payments=new PostbankPayments(bank,async()=>({}),{clock});
|
||||
return Object.freeze({async pay({keyId,clanId,amountMinor,memo}){
|
||||
if(!/^[a-f0-9-]{36}$/i.test(keyId||'')||!/^[a-f0-9-]{36}$/i.test(clanId||'')||!Number.isSafeInteger(amountMinor)||amountMinor<1||amountMinor>15000000||memo!=='Rebellion reward '+keyId)throw Error('Invalid bound quest reward');
|
||||
const fingerprint=createHash('sha256').update(JSON.stringify([QUEST_TREASURY,keyId,clanId,amountMinor,memo])).digest('hex');
|
||||
return bank.transaction(async tx=>{
|
||||
const entity=await tx.first("SELECT id FROM pb_entities WHERE kind='clan' AND external_key=? FOR UPDATE",[clanId]);if(!entity)throw Error('Winning clan bank entity unavailable');
|
||||
await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[entity.id]);
|
||||
const rows=await tx.query(accounts+' WHERE a.system_key=? OR c.entity_id=? ORDER BY a.id FOR UPDATE',[QUEST_TREASURY,entity.id]),source=rows.find(r=>r.system_key===QUEST_TREASURY);
|
||||
if(!await authorize())throw Error('Verified quest authorization expired');
|
||||
const prior=await tx.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[keyId]);
|
||||
if(prior){const target=rows.find(r=>String(r.id)===String(prior.target_id));if(prior.actor_id!==OFFICIAL_ACCOUNT.id||prior.fingerprint!==fingerprint||prior.mode!=='system'||prior.state!=='posted'||prior.memo!==memo||Number(prior.amount_minor)!==amountMinor||String(prior.source_id)!==String(source?.id)||target?.kind!=='clan'||target.external_key!==clanId)throw Error('Quest payment reference conflict');return prior;}
|
||||
const target=rows.find(ordinaryPaymentAccount);
|
||||
if(!source||source.state!=='active'||source.type_code!=='979'||!target||BigInt(source.balance_minor)-BigInt(source.reserved_minor)<BigInt(amountMinor))throw Error('Quest treasury or recipient is unavailable or unfunded');
|
||||
await tx.query('INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)',[keyId,OFFICIAL_ACCOUNT.id,source.id,target.id,fingerprint,String(amountMinor),memo,'system','queued',clock()]);
|
||||
await payments.post(tx,{id:keyId,actor_id:OFFICIAL_ACCOUNT.id,amount_minor:String(amountMinor)},{...source,entity_id:null},target,false);
|
||||
return tx.first('SELECT * FROM pb_orders WHERE id=?',[keyId]);
|
||||
});
|
||||
}});
|
||||
}
|
||||
|
|
@ -2,6 +2,8 @@ import {PostbankPayments} from './postbank-payments.mjs';
|
|||
import {createPostbankAuthority} from './postbank-authority.mjs';
|
||||
import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
|
||||
import {rebellionQuest} from './rebellion-quest-policy.mjs';
|
||||
import {createQuestTreasuryPayments} from './quest-treasury-payments.mjs';
|
||||
import {OFFICIAL_ACCOUNT} from './official-account.mjs';
|
||||
const accountSQL='SELECT a.*,c.entity_id,e.kind,e.external_key,e.active AS entity_active,p.state AS package_state FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id LEFT JOIN pb_packages p ON p.id=a.package_id';
|
||||
const jobs='jarvis_pol_quest_reward_jobs';
|
||||
const fail=message=>{throw Error(message);};
|
||||
|
|
@ -9,18 +11,29 @@ const first=async(db,sql,args)=>(await db.query(sql,args))[0]||null;
|
|||
|
||||
// No reward minting. A configured fund owner pays through the existing standard
|
||||
// bank queue, with the quest key as the durable payment reference across crashes.
|
||||
export function createRebellionRewards(central,bank,{sourceAccount,sourceOwnerId,authority=createPostbankAuthority(central,{bank}),payments=null}={}){
|
||||
export function createRebellionRewards(central,bank,{sourceAccount,sourceOwnerId,useWebsiteTreasury=false,authority=createPostbankAuthority(central,{bank}),payments=null}={}){
|
||||
const owner=async()=>await first(central,"SELECT id,username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[sourceOwnerId]);
|
||||
payments||=new PostbankPayments(bank,authority,{resolveUser:async id=>first(central,"SELECT id,username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[id])});
|
||||
async function process(keyId){return central.transaction(async tx=>{
|
||||
const job=await tx.first(`SELECT * FROM ${jobs} WHERE key_id=? FOR UPDATE`,[keyId]);if(!job||!['awaiting_funding','submitted'].includes(job.state))return 'unchanged';
|
||||
const reward=await tx.first('SELECT * FROM jarvis_rebellion_rewards WHERE quest_key_id=?',[keyId]);
|
||||
const instruction=await tx.first("SELECT i.*,k.used_at,k.revoked_at FROM jarvis_generated_instructions i JOIN organisation_keys k ON k.id=i.key_id WHERE i.key_id=? AND i.action_id='politics.rebellion'",[keyId]);
|
||||
const instruction=await tx.first("SELECT i.*,k.used_at,k.revoked_at,k.key_type,k.scope_id,k.account_id key_account FROM jarvis_generated_instructions i JOIN organisation_keys k ON k.id=i.key_id WHERE i.key_id=? AND i.action_id='politics.rebellion' FOR UPDATE",[keyId]);
|
||||
if(!reward||!instruction||instruction.state!=='applied'||instruction.used_at==null||instruction.revoked_at!=null)fail('Verified completed rebellion key required');
|
||||
const {declaration:d,receipt}=JSON.parse(instruction.manifest_json),base=rebellionQuest(reward.office_key).reward,multiplier=(d.rewardMultiplier||1)+(reward.bonus_marker==='inaugural'?5:0),policy={reputationXP:base.reputationXP*multiplier,amountMinor:base.amountMinor*multiplier};
|
||||
if((reward.challenge_key_id||'00000000-0000-4000-8000-000000000000')!==(d.counterChallengeOf||'00000000-0000-4000-8000-000000000000')||!!receipt?.firstSuccessBonus!==(reward.bonus_marker==='inaugural'))fail('Rebellion bonus bindings changed');
|
||||
if(!receipt||receipt.questKeyId!==keyId||d.attackerClanId!==reward.clan_id||d.officeKey!==reward.office_key||d.winnerId!==reward.winner_id||job.account_id!==reward.winner_id||job.season_id!==reward.season_id||d.seasonId!==reward.season_id||Number(reward.amount_minor)!==policy.amountMinor||Number(reward.xp)!==policy.reputationXP)fail('Rebellion reward bindings changed');
|
||||
if(instruction.key_type!=='quest'||instruction.key_account!==reward.winner_id||instruction.account_id!==reward.winner_id||instruction.scope_id!==reward.season_id+':REBELLION_'+instruction.request_id)fail('Rebellion quest identity changed');
|
||||
const reference='Rebellion reward '+keyId;
|
||||
if(useWebsiteTreasury){
|
||||
const treasury=createQuestTreasuryPayments(bank,{authorize:async()=>{
|
||||
const actor=await tx.first("SELECT id,username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[OFFICIAL_ACCOUNT.id]);
|
||||
const key=await tx.first('SELECT used_at,revoked_at FROM organisation_keys WHERE id=? FOR UPDATE',[keyId]);
|
||||
return actor?.username===OFFICIAL_ACCOUNT.username&&actor.role==='official_account'&&key?.used_at!=null&&key.revoked_at==null;
|
||||
}});
|
||||
await treasury.pay({keyId,clanId:reward.clan_id,amountMinor:policy.amountMinor,memo:reference});
|
||||
await tx.query(`UPDATE ${jobs} SET state='paid' WHERE key_id=?`,[keyId]);receipt.rewardState='paid';
|
||||
await tx.query('UPDATE jarvis_generated_instructions SET manifest_json=? WHERE key_id=?',[JSON.stringify({declaration:d,receipt}),keyId]);return 'paid';
|
||||
}
|
||||
let order=await bank.first('SELECT * FROM pb_orders WHERE id=?',[keyId]);
|
||||
if(order){
|
||||
const target=await bank.first(accountSQL+' WHERE a.id=?',[order.target_id]);
|
||||
|
|
@ -38,7 +51,7 @@ export function createRebellionRewards(central,bank,{sourceAccount,sourceOwnerId
|
|||
await tx.query('UPDATE jarvis_generated_instructions SET manifest_json=? WHERE key_id=?',[JSON.stringify({declaration:d,receipt}),keyId]);return state;
|
||||
});}
|
||||
return Object.freeze({async drain(){
|
||||
if(!/^\d{1,12}$/.test(String(sourceAccount||''))||!/^[a-f0-9-]{36}$/i.test(sourceOwnerId||''))return {state:'awaiting-funding-configuration',attempted:0};
|
||||
if(!useWebsiteTreasury&&(!/^\d{1,12}$/.test(String(sourceAccount||''))||!/^[a-f0-9-]{36}$/i.test(sourceOwnerId||'')))return {state:'awaiting-funding-configuration',attempted:0};
|
||||
const pending=await central.query(`SELECT key_id FROM ${jobs} WHERE state IN ('awaiting_funding','submitted') ORDER BY created_at,key_id LIMIT 25`),results=[];
|
||||
for(const job of pending){try{results.push({keyId:job.key_id,state:await process(job.key_id)});}catch{results.push({keyId:job.key_id,state:'awaiting-funding-or-review'});}}
|
||||
return {attempted:pending.length,results};
|
||||
|
|
|
|||
53
website/ops/prepare-alpha-reset.mjs
Normal file
53
website/ops/prepare-alpha-reset.mjs
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import {readFileSync,realpathSync} from 'node:fs';
|
||||
import {pathToFileURL} from 'node:url';
|
||||
import {createHash} from 'node:crypto';
|
||||
import {buildAlphaResetReview} from '../node/alpha-reset-review.mjs';
|
||||
import {OFFICIAL_ACCOUNT} from '../node/official-account.mjs';
|
||||
|
||||
// SELECT-only inventory. Never calls a schema initializer or domain executor.
|
||||
export async function collectAlphaResetInventory(site,bank){
|
||||
const read=async(db,sql)=>{if(!/^SELECT /i.test(sql))throw Error('Read-only inventory required');return db.query(sql);};
|
||||
const central={
|
||||
clans:'SELECT id,name,owner_id,active,version FROM site_clans ORDER BY id',
|
||||
companies:'SELECT c.id,c.name,c.founded_by,c.status,d.owner_account_id,d.charter_kind,d.version FROM corrino_companies c LEFT JOIN site_company_deeds d ON d.company_id=c.id ORDER BY c.id',
|
||||
relations:'SELECT child_kind,child_id,parent_kind,parent_id,key_id FROM jarvis_entity_relations ORDER BY child_kind,child_id',
|
||||
clanInstitutions:'SELECT clan_id,institution_key FROM site_clan_institutions ORDER BY clan_id',
|
||||
companyInstitutions:'SELECT company_id,institution_key FROM site_company_institutions ORDER BY company_id',
|
||||
claims:'SELECT organisation_kind,organisation_id,revision,snapshot_json FROM site_claim_registry ORDER BY organisation_kind,organisation_id',
|
||||
foundingKeys:"SELECT id,account_id,key_type,scope_id,used_at,revoked_at FROM organisation_keys WHERE key_type IN ('clan-founding','company-founding') ORDER BY id",
|
||||
questRewards:'SELECT key_id,account_id,season_id,state FROM jarvis_quest_reward_jobs ORDER BY key_id',
|
||||
polRewards:'SELECT key_id,account_id,season_id,state FROM jarvis_pol_quest_reward_jobs ORDER BY key_id',
|
||||
projectJobs:'SELECT id,project_id,kind,state FROM jarvis_project_jobs ORDER BY id',
|
||||
kitListings:'SELECT id,blueprint_id,blueprint_version,active,published FROM site_kit_listings ORDER BY id'
|
||||
};
|
||||
const financial={
|
||||
accounts:'SELECT a.id,a.account_number,a.system_key,a.balance_minor,a.reserved_minor,a.state,e.kind,e.external_key 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 ORDER BY a.id',
|
||||
orders:"SELECT id,source_id,target_id,amount_minor,mode,state FROM pb_orders WHERE state NOT IN ('posted','failed','cancelled','rejected') ORDER BY id",
|
||||
auctionHolds:'SELECT id,auction_id,source_id,amount_minor,state FROM pb_auction_holds ORDER BY id',
|
||||
auctions:'SELECT id,office_key,state,highest_minor,hold_id,winner_id FROM jarvis_office_auctions ORDER BY id',
|
||||
deedPurchases:'SELECT id,listing_id,key_id,parent_kind,parent_id,source_account,recipient_account,price_minor,state FROM jarvis_deed_purchases ORDER BY id',
|
||||
loans:"SELECT id,account_id,state,outstanding_minor,collateral_minor,treasury_hold_minor,borrower_hold_minor FROM pb_credit_loans WHERE state NOT IN ('closed','repaid','cancelled','rejected','expired') ORDER BY id",
|
||||
creditActions:"SELECT id,loan_id,kind,amount_minor,state FROM pb_credit_actions WHERE state NOT IN ('posted','completed','failed','cancelled','rejected') ORDER BY id",
|
||||
creditInstalments:"SELECT loan_id,sequence_no,state,principal_minor,interest_minor,paid_principal,paid_interest FROM pb_credit_instalments WHERE state<>'paid' ORDER BY loan_id,sequence_no",
|
||||
listings:'SELECT id,definition_id,organisation_kind,organisation_id,revision,state FROM jarvis_listings ORDER BY id'
|
||||
};
|
||||
const inventory={};for(const [field,sql]of Object.entries(central))inventory[field]=await read(site,sql);for(const [field,sql]of Object.entries(financial))inventory[field]=await read(bank,sql);
|
||||
for(const row of inventory.claims){const snapshot=JSON.parse(row.snapshot_json);row.snapshotHash=createHash('sha256').update(row.snapshot_json).digest('hex');row.homeBlock=snapshot.homeBlock?{id:snapshot.homeBlock.id||null,worldUuid:snapshot.homeBlock.worldUuid||null}:null;delete row.snapshot_json;}
|
||||
const fallbackClans=await read(site,'SELECT clan_id,parent_clan_id FROM site_clan_deeds WHERE parent_clan_id IS NOT NULL ORDER BY clan_id'),fallbackCompanies=await read(site,'SELECT company_id,parent_company_id FROM site_company_relations WHERE parent_company_id IS NOT NULL ORDER BY company_id');
|
||||
for(const [kind,rows]of [['clan',fallbackClans],['company',fallbackCompanies]])for(const r of rows)if(!inventory.relations.some(x=>x.child_kind===kind&&x.child_id===r[kind+'_id']))inventory.relations.push({child_kind:kind,child_id:r[kind+'_id'],parent_kind:kind,parent_id:r['parent_'+kind+'_id'],key_id:null});
|
||||
inventory.payrollItems=await read(bank,"SELECT period,actor_id,account_id,order_id,amount_minor,state FROM pb_payroll_items WHERE state NOT IN ('posted','paid','cancelled','failed') ORDER BY period,actor_id");
|
||||
inventory.additionalPayrollItems=await read(bank,"SELECT period,actor_id,account_id,order_id,amount_minor,state FROM pb_payroll_additional_items WHERE state NOT IN ('posted','paid','cancelled','failed') ORDER BY period,actor_id");
|
||||
inventory.standingInstructions=await read(bank,'SELECT instruction_key,source_key,target_key,amount_minor,enabled,version FROM pb_standing_instructions ORDER BY instruction_key');
|
||||
inventory.financialPolicyVersions=await read(bank,'SELECT policy_key,version,updated_at FROM pb_financial_policies ORDER BY policy_key');
|
||||
inventory.ledgerSummary=await read(bank,'SELECT COUNT(*) entries,COALESCE(SUM(amount_minor),0) signed_total_minor FROM pb_entries');
|
||||
return inventory;
|
||||
}
|
||||
if(process.argv[1]&&import.meta.url===pathToFileURL(realpathSync(process.argv[1])).href){
|
||||
if(process.argv.length!==2)throw Error('This command accepts no execution or mutation options');
|
||||
process.loadEnvFile('/home/dunerealms/.config/dunerealms.env');const {default:mysql}=await import('mysql2/promise'),e=process.env;
|
||||
const root=realpathSync('/home/dunerealms/apps/dunerealms/current'),config=e.POSTBANK_DB_CONFIG?JSON.parse(readFileSync(e.POSTBANK_DB_CONFIG)):null;if(!config)throw Error('Explicit current bank configuration required');
|
||||
const site=await mysql.createConnection({host:e.DB_HOST||'127.0.0.1',port:Number(e.DB_PORT||3306),user:e.DB_USER,password:e.DB_PASSWORD,database:e.DB_NAME,supportBigNumbers:true,bigNumberStrings:true}),bank=await mysql.createConnection({...config,supportBigNumbers:true,bigNumberStrings:true});
|
||||
try{for(const db of [site,bank]){await db.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ');await db.query('START TRANSACTION WITH CONSISTENT SNAPSHOT, READ ONLY');}
|
||||
const reader=db=>({query:async sql=>(await db.query(sql))[0]});const inventory=await collectAlphaResetInventory(reader(site),reader(bank));console.log(JSON.stringify(buildAlphaResetReview(inventory,{ownerId:OFFICIAL_ACCOUNT.ownerId,release:root.split('/').at(-1),observedAt:Date.now()})));
|
||||
}finally{await site.rollback();await bank.rollback();await site.end();await bank.end();}
|
||||
}
|
||||
23
website/tests/alpha-reset-review.test.mjs
Normal file
23
website/tests/alpha-reset-review.test.mjs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';
|
||||
import {buildAlphaResetReview} from '../node/alpha-reset-review.mjs';
|
||||
import {collectAlphaResetInventory} from '../ops/prepare-alpha-reset.mjs';
|
||||
function input(){return Object.fromEntries(['clans','companies','relations','clanInstitutions','companyInstitutions','claims','foundingKeys','accounts','orders','auctionHolds','auctions','deedPurchases','loans','creditActions','creditInstalments','questRewards','polRewards','listings','kitListings','projectJobs','payrollItems','additionalPayrollItems'].map(k=>[k,[]]));}
|
||||
const options={ownerId:'owner',release:'verified-release',observedAt:123};
|
||||
test('current reset review retains protected institutions, archived clans and acquired owner-network descendants without widening mutation scope',()=>{
|
||||
const i=input();i.clans=[{id:'owned',owner_id:'owner',active:1},{id:'acquired',owner_id:'another',active:1},{id:'archived',active:0},{id:'protected',active:1}];i.companies=[{id:'unicorp',owner_account_id:'owner'},{id:'subsidiary',owner_account_id:'other'}];
|
||||
i.relations=[{child_kind:'clan',child_id:'acquired',parent_kind:'clan',parent_id:'owned'},{child_kind:'company',child_id:'subsidiary',parent_kind:'company',parent_id:'unicorp'}];i.clanInstitutions=[{clan_id:'protected',institution_key:'verified-registry'}];
|
||||
const before=JSON.stringify(i),r=buildAlphaResetReview(i,options);assert.equal(r.executable,false);assert.equal(r.executionAuthorized,false);assert.equal(JSON.stringify(i),before);assert.deepEqual(r.proposed.ownerNetwork,['clan:acquired','clan:owned','company:subsidiary','company:unicorp']);assert.deepEqual(r.proposed.protectedObjects,['clan:protected']);assert.deepEqual(r.proposed.alreadyArchivedClanIds,['archived']);
|
||||
for(const key of ['archiveClanIds','deleteCompanyIds','charterChanges','rosterChanges','homeBlockChanges','claimChanges','closeListingIds','foundingEntitlementChanges','stagingDeletionIds'])assert.deepEqual(r.proposed[key],[]);
|
||||
assert.equal(r.proposed.newBudget,null);assert.equal(r.proposed.newEconomicReference,null);
|
||||
});
|
||||
test('review inventories reservations and outstanding obligations precisely, including system balances without numeric truncation',()=>{
|
||||
const i=input();i.accounts=[{id:'9007199254740993',system_key:'sys_web_treasury',balance_minor:'9223372036854775807',reserved_minor:'5'}];i.orders=[{id:'pending',state:'queued'},{id:'old',state:'posted'}];i.polRewards=[{key_id:'claim',state:'awaiting_funding'}];i.foundingKeys=[{id:'used',used_at:123}];i.listings=[{id:'live',state:'open'},{id:'historic',state:'closed'}];i.kitListings=[{id:'kit',active:1}];
|
||||
const r=buildAlphaResetReview(i,options);assert.equal(r.obligations.orders.count,1);assert.equal(r.obligations.reservations.count,1);assert.equal(r.obligations.polRewards.count,1);assert.deepEqual(r.proposed.balanceZeroAccountIds,['9007199254740993']);assert.deepEqual(r.proposed.retainKitListingIds,['kit']);assert.deepEqual(r.proposed.nonKitListingIdsForReview,['live']);assert.equal(r.inventory.foundingKeys[0].used_at,123);assert.equal(r.proposed.preserveAllHistoricalKeys,true);
|
||||
assert.notEqual(buildAlphaResetReview({...i,accounts:[]},options).inventoryHash,r.inventoryHash);
|
||||
assert.equal(buildAlphaResetReview(i,options).proposedManifestHash,r.proposedManifestHash);
|
||||
assert.throws(()=>buildAlphaResetReview({...i,orders:null},options),/Incomplete/);
|
||||
});
|
||||
test('collector uses SELECT only, authoritative relations before legacy fallback, and removes raw claim snapshots',async()=>{
|
||||
const sqls=[],reader={async query(sql){sqls.push(sql);assert.match(sql,/^SELECT /);if(sql.includes('FROM jarvis_entity_relations'))return [{child_kind:'clan',child_id:'child',parent_kind:'clan',parent_id:'current'}];if(sql.includes('FROM site_clan_deeds'))return [{clan_id:'child',parent_clan_id:'stale'},{clan_id:'legacy',parent_clan_id:'parent'}];if(sql.includes('FROM site_claim_registry'))return [{organisation_id:'child',snapshot_json:JSON.stringify({homeBlock:{id:'home',worldUuid:'world'},privateExtra:'not-in-report'})}];return [];}};
|
||||
const i=await collectAlphaResetInventory(reader,reader);assert.ok(sqls.length>20);assert.equal(i.relations.length,2);assert.equal(i.relations[0].parent_id,'current');assert.equal(i.relations[1].parent_id,'parent');assert.equal(i.claims[0].snapshot_json,undefined);assert.equal(i.claims[0].snapshotHash.length,64);assert.deepEqual(i.claims[0].homeBlock,{id:'home',worldUuid:'world'});
|
||||
});
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
|
||||
import {fixture} from './rebellion-fixture.mjs';import {BankFixture} from './postbank-fixture.mjs';
|
||||
import {PostbankService} from '../node/postbank-service.mjs';import {PostbankPayments} from '../node/postbank-payments.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';import {createRebellionRewards} from '../node/rebellion-rewards.mjs';
|
||||
import {OFFICIAL_ACCOUNT} from '../node/official-account.mjs';
|
||||
import {createQuestTreasuryPayments} from '../node/quest-treasury-payments.mjs';
|
||||
async function setup(){
|
||||
const f=await fixture(),bank=new BankFixture(),fund=f.people.Other,entities=[{id:randomUUID(),kind:'person',key:fund.id,name:'Quest fund'},{id:randomUUID(),kind:'clan',key:f.attacker,name:'Winning clan'}];let allowed=true;
|
||||
const authority=async user=>({entities:entities.map(e=>({...e,canView:true,canActivate:true,canPay:allowed&&user.id===fund.id&&e.key===fund.id})),readAdmin:false,manageAdmin:false});
|
||||
|
|
@ -33,3 +35,51 @@ test('missing funding configuration or expired debit authority cannot mint a rew
|
|||
assert.equal((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,0);
|
||||
}finally{f.close();}
|
||||
});
|
||||
|
||||
async function treasurySetup(){
|
||||
const f=await setup();await f.db.query('INSERT INTO site_accounts(id,username,role) VALUES(?,?,?)',[OFFICIAL_ACCOUNT.id,OFFICIAL_ACCOUNT.username,'official_account']);
|
||||
const treasury=await f.bank.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES('sys_web_treasury','979','Website treasury',18000000,1000000,'active',1)");
|
||||
return {...f,treasuryId:treasury.insertId,worker:createRebellionRewards(f.db,f.bank,{useWebsiteTreasury:true})};
|
||||
}
|
||||
test('funded official quest consumer posts once from existing website reserves and recovers a lost central acknowledgement',async()=>{
|
||||
const f=await treasurySetup();try{
|
||||
const before=await f.bank.first('SELECT SUM(balance_minor) total FROM pb_accounts');
|
||||
assert.equal((await f.worker.drain()).results[0].state,'paid');
|
||||
assert.equal((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,18000000,'personal fund untouched');
|
||||
assert.equal((await f.bank.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.treasuryId])).reserved_minor,1000000,'existing reservations untouched');
|
||||
await f.db.query("UPDATE jarvis_pol_quest_reward_jobs SET state='awaiting_funding' WHERE key_id=?",[f.quest.keyId]);
|
||||
await Promise.all([f.worker.drain(),f.worker.drain()]);
|
||||
assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,1);
|
||||
assert.deepEqual({...await f.bank.first('SELECT COUNT(*) n,SUM(amount_minor) net FROM pb_entries')},{n:2,net:0});
|
||||
assert.equal((await f.bank.first('SELECT SUM(balance_minor) total FROM pb_accounts')).total,before.total);
|
||||
const order=await f.bank.first('SELECT * FROM pb_orders');assert.equal(order.actor_id,OFFICIAL_ACCOUNT.id);assert.equal(order.mode,'system');assert.equal(order.state,'posted');
|
||||
assert.equal((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,15000000);
|
||||
}finally{f.close();}
|
||||
});
|
||||
test('treasury payout rejects unavailable funds, revoked proof, wrong service identity, recipient freeze and atomic ledger failure',async()=>{
|
||||
for(const failure of ['funds','proof','identity','recipient','ledger']){const f=await treasurySetup();try{
|
||||
if(failure==='funds')await f.bank.query('UPDATE pb_accounts SET balance_minor=15000000 WHERE id=?',[f.treasuryId]);
|
||||
if(failure==='proof')await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[f.quest.keyId]);
|
||||
if(failure==='identity')await f.db.query("UPDATE site_accounts SET role='player' WHERE id=?",[OFFICIAL_ACCOUNT.id]);
|
||||
if(failure==='recipient')await f.bank.query("UPDATE pb_accounts SET state='blocked' WHERE id=?",[f.target.id]);
|
||||
if(failure==='ledger')f.bank.sqlite.exec("CREATE TRIGGER fail_quest_audit BEFORE INSERT ON pb_audit BEGIN SELECT RAISE(ABORT,'injected failure'); END;");
|
||||
assert.equal((await f.worker.drain()).results[0].state,'awaiting-funding-or-review');
|
||||
assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,0);
|
||||
assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_entries')).n,0);
|
||||
assert.equal((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,0);
|
||||
}finally{f.close();}}
|
||||
});
|
||||
test('treasury consumer requires a private current authorizer and rejects conflicting durable payment receipts',async()=>{
|
||||
assert.throws(()=>createQuestTreasuryPayments({}),/authorizer/);
|
||||
const f=await treasurySetup();try{
|
||||
await f.worker.drain();await f.bank.query("UPDATE pb_orders SET fingerprint='tampered' WHERE id=?",[f.quest.keyId]);
|
||||
await f.db.query("UPDATE jarvis_pol_quest_reward_jobs SET state='awaiting_funding' WHERE key_id=?",[f.quest.keyId]);
|
||||
assert.equal((await f.worker.drain()).results[0].state,'awaiting-funding-or-review');assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_entries')).n,2);
|
||||
}finally{f.close();}
|
||||
});
|
||||
test('money cannot follow a modified key owner, key type, scope or reward beneficiary',async()=>{
|
||||
for(const column of ['account_id','key_type','scope_id']){const f=await treasurySetup();try{
|
||||
await f.db.query('UPDATE organisation_keys SET '+column+'=? WHERE id=?',[column==='account_id'?f.people.Other.id:column==='key_type'?'quest-milestone':'S01:WRONG',f.quest.keyId]);
|
||||
assert.equal((await f.worker.drain()).results[0].state,'awaiting-funding-or-review');assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,0);
|
||||
}finally{f.close();}}
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff