#pragma once #include "cube_gold_intent.h" namespace PortCube { // Candidate deferred positive-credit backend; actual ingress remains disabled. // Sources must durably identify an event BEFORE acknowledging delivery; // do not divert an already-performed PointChange here or double-credit memory. template class GoldIntentStore { DB& db;Lookup lookup;using Rows=PortEconomy::Rows; static std::string N(uint64_t n){return std::to_string(n);} bool Q(const std::string& sql,Rows& rows){return db.Query(sql,rows)&&!db.warnings;} bool Run(const std::string& sql){Rows rows;return Q(sql,rows);} bool Change(const std::string& sql){return Run(sql)&&db.affected==1;} struct Guard {DB& db;~Guard(){db.Rollback();}}; bool Account(uint32_t account) { Rows rows;return Run("INSERT INTO port_economy_account_lock(account) VALUES("+N(account)+") ON DUPLICATE KEY UPDATE account=VALUES(account)")&& Q("SELECT account FROM port_economy_account_lock WHERE account="+N(account)+" FOR UPDATE",rows)&&rows.size()==1; } bool Fence(uint32_t account,uint32_t player,Rows& rows) { return Q("SELECT account,epoch,owner,request,phase,body,drain_state FROM port_cube_fences WHERE pid="+N(player)+" AND account="+N(account)+" FOR UPDATE",rows); } static bool Same(const Batch& b,const Rows& rows) { return rows.size()==1&&rows[0].size()==7&&rows[0][0]==N(b.account)&&rows[0][1]==N(b.epoch)&&rows[0][2]==b.owner&&rows[0][3]==b.token&&rows[0][5]==Encode(b); } public: enum Result {Retry,Refused,Stored,Applied,Blocked}; struct Receipt {uint64_t before=0,after=0;}; GoldIntentStore(DB& database,Lookup proto):db(database),lookup(std::move(proto)){} bool Ready(){BatchStore base(db,lookup);return base.Ready()&&GoldSchema(db)==1;} Result Enqueue(const Batch& b,const GoldIntent& i) { if(!Validate(b)||!ValidGoldIntent(i)||!Matches(i,b))return Refused; if(!Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows; if(!Account(b.account))return Retry; const auto body=EncodeGoldIntent(i); if(!Q("SELECT body,state,before_gold,after_gold FROM port_cube_gold_intents WHERE event='"+i.event+"' FOR UPDATE",rows))return Retry; if(!rows.empty()) { if(rows.size()!=1||rows[0].size()!=4||rows[0][0]!=body)return Refused; uint64_t before=0,after=0; if(!PortEconomy::Number(rows[0][2],before,PortEconomy::GoldLimit)||!PortEconomy::Number(rows[0][3],after,PortEconomy::GoldLimit))return Blocked; if(rows[0][1]=="QUEUED")return !before&&!after?Stored:Blocked; return rows[0][1]=="APPLIED"&&before<=uint64_t(PortEconomy::GoldLimit)-i.amount&&after==before+i.amount?Applied:Blocked; } if(!Fence(b.account,b.player,rows))return Retry; if(!Same(b,rows))return Blocked; const auto phase=rows[0][4]; if(phase!="DRAINING"&&phase!="FROZEN"&&phase!="ABORTED")return Blocked; if(!Q("SELECT request FROM port_cube_gold_sources WHERE request='"+b.token+"' FOR UPDATE",rows))return Retry; if(!rows.empty())return Blocked; // exact historical event replay above is still allowed std::vector records;if(!GoldRecords(db,b,records))return Blocked; if(i.sequence!=records.size()+1)return Refused; if(!Change("INSERT INTO port_cube_gold_intents(event,request,seq,account,pid,body,state,before_gold,after_gold) VALUES('"+i.event+"','"+i.request+"',"+N(i.sequence)+","+N(i.account)+","+N(i.player)+",X'"+PortEconomy::Hex(body.data(),body.size())+"','QUEUED',0,0)"))return Retry; return db.Commit()?Stored:Retry; } Result CloseSource(const Batch& b,const GoldSourceSeal& seal) { const auto manifest=EncodeGoldManifest(seal.events); if(!Validate(b)||!Matches(seal,b)||EncodeGoldSourceBinding(seal).empty()||manifest.empty())return Refused; if(!Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows; if(!Account(b.account))return Retry; const std::vector expected={N(b.account),N(b.player),N(b.epoch),b.owner,N(seal.session),N(seal.cookie),N(seal.handle),manifest}; if(!Q("SELECT account,pid,epoch,owner,session,cookie,handle,manifest FROM port_cube_gold_sources WHERE request='"+b.token+"' FOR UPDATE",rows))return Retry; if(!rows.empty())return rows.size()==1&&rows[0]==expected?Stored:Refused; if(!Fence(b.account,b.player,rows))return Retry; if(!Same(b,rows)||!((rows[0][4]=="FROZEN"&&rows[0][6]=="1")||(rows[0][4]=="ABORTED"&&rows[0][6]=="2")))return Blocked; std::vector records;if(!GoldRecords(db,b,records))return Blocked; if(records.size()!=seal.events.size())return Blocked; for(size_t n=0;n& pending) { pending.clear();if(!Validate(b))return Refused; if(!Ready()||!db.Begin())return Retry;Guard guard{db}; if(!Account(b.account))return Retry; std::vector records;if(!GoldRecords(db,b,records))return Blocked; for(const auto& record:records)if(!record.applied)pending.push_back(record.intent); return Stored; } // Only identity comes from recovery. The persisted event/body and the DONE // Cube receipt determine the amount and expected base. Never auto-settle a // PREPARED craft, overwrite a stale wallet or apply on an aborted drain. Result Apply(const std::string& event,uint32_t account,uint32_t player,Receipt& receipt, const std::function& authorize={}) { receipt={};if(!Identity(event)||!account||!player)return Refused; if(!Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows; if(!Account(account)||!Q("SELECT body,state,before_gold,after_gold FROM port_cube_gold_intents WHERE event='"+event+"' AND account="+N(account)+" AND pid="+N(player)+" FOR UPDATE",rows))return Retry; if(rows.empty())return Refused; GoldIntent intent; if(rows.size()!=1||rows[0].size()!=4||!DecodeGoldIntent(rows[0][0],intent)||intent.event!=event||intent.account!=account||intent.player!=player)return Blocked; if(authorize&&!authorize(intent))return Blocked; // same account transaction/pinned connection, including historical replay const auto saved=rows[0];uint64_t before=0,after=0; if(!PortEconomy::Number(saved[2],before,PortEconomy::GoldLimit)||!PortEconomy::Number(saved[3],after,PortEconomy::GoldLimit))return Blocked; if(saved[1]=="APPLIED") { if(before>uint64_t(PortEconomy::GoldLimit)-intent.amount||after!=before+intent.amount)return Blocked; receipt={before,after};return Applied; // historical replay, even after newer epochs } if(saved[1]!="QUEUED"||before||after)return Blocked; if(!Fence(account,player,rows))return Retry; Batch b;if(rows.size()!=1||rows[0].size()!=7||!Decode(rows[0][5],b)||!Same(b,rows)||!Matches(intent,b)||rows[0][4]!="FROZEN"||rows[0][6]!="1")return Blocked; std::vector records;if(!GoldRecords(db,b,records))return Blocked; uint64_t expected=0;const int base=GoldCreditBase(db,b,expected);if(base<0)return Retry;if(!base)return Blocked; unsigned next=1; for(const auto& record:records) { if(!record.applied)break; if(record.before!=expected)return Blocked;expected=record.after;++next; } if(intent.sequence!=next||next>records.size()||records[next-1].intent.event!=event)return Blocked; if(expected>uint64_t(PortEconomy::GoldLimit)-intent.amount)return Blocked; if(!Q("SELECT gold FROM player WHERE id="+N(player)+" AND account_id="+N(account)+" FOR UPDATE",rows))return Retry; uint64_t current=0;if(rows.size()!=1||rows[0].size()!=1||!PortEconomy::Number(rows[0][0],current,PortEconomy::GoldLimit)||current!=expected)return Blocked; const auto target=expected+intent.amount; if(!Change("UPDATE player SET gold=gold+"+N(intent.amount)+" WHERE id="+N(player)+" AND account_id="+N(account)+" AND gold="+N(expected))|| !Change("UPDATE port_cube_gold_intents SET state='APPLIED',before_gold="+N(expected)+",after_gold="+N(target)+" WHERE event='"+event+"' AND state='QUEUED'")||!db.Commit())return Retry; receipt={expected,target};return Applied; } }; }