feat: implement CH5 cube renewal, SQL fence routing, and transactional crafting

This commit is contained in:
shen
2026-10-23 20:17:22 -07:00
parent 6924dc9b49
commit b5e06c9a43
135 changed files with 8493 additions and 56 deletions
+153
View File
@@ -0,0 +1,153 @@
#pragma once
#include "cube_recipe.h"
#include "economy.h"
#include <array>
#include <functional>
// Candidate DB-side batch contract. Not a client packet or permission to mutate
// a live actor. A DB coordinator must first establish the matching durable fence.
namespace PortCube {
struct Item {
PortEconomy::Reward value;
uint16_t cell=0;
bool usable=true;
};
struct Batch {
uint32_t account=0,player=0;
uint64_t epoch=0,gold=0;
std::string owner,token;
Recipe recipe;
unsigned attempts=0;
std::vector<Item> inventory;
// Factory-created templates with reserved, never-reused IDs. No item rows
// have been created yet; count=1 is replaced only by successful output.
std::vector<PortEconomy::Reward> rewards;
};
inline bool Identity(const std::string& s) {
if(s.size()!=32||s==std::string(32,'0'))return false;
return std::all_of(s.begin(),s.end(),[](char c){return (c>='0'&&c<='9')||(c>='a'&&c<='f');});
}
inline bool Validate(const Batch& b) {
Recipe recipe=b.recipe;
if(!b.account||!b.player||!b.epoch||!Identity(b.owner)||!Identity(b.token)||
b.gold>uint64_t(PortEconomy::GoldLimit)||!Normalize(recipe)||recipe.id>MaxRecipes||recipe.copy||
!b.attempts||b.attempts>MaxAttempts||b.inventory.size()>225)return false;
// Only canonical normalized recipes are accepted. No uninitialized copy
// semantics, duplicate requirements or reordered NPCs enter the journal.
if(recipe.npcs!=b.recipe.npcs||recipe.materials.size()!=b.recipe.materials.size()||
!std::equal(recipe.materials.begin(),recipe.materials.end(),b.recipe.materials.begin(),
[](const Material& a,const Material& c){return a.vnum==c.vnum&&a.count==c.count;}))return false;
const uint64_t maximum=uint64_t(recipe.rewardCount)*b.attempts;
const unsigned stacks=recipe.stackable?unsigned((maximum+1999)/2000):unsigned(maximum);
if(b.rewards.size()!=stacks||stacks>100)return false;
std::set<uint32_t> ids;int last=-1;
for(const auto& i:b.inventory) {
if(!i.value.id||!i.value.vnum||!i.value.count||i.value.count>2000||i.cell>=225||
int(i.cell)<=last||!ids.insert(i.value.id).second)return false;
last=i.cell;
}
for(const auto& r:b.rewards)if(!r.id||r.vnum!=recipe.reward||r.count!=1||!ids.insert(r.id).second)return false;
return true;
}
// Explicit little-endian bounded codec, never sizeof(Batch) or padded structs.
// It is deliberately separate from the legacy client/game protocol.
struct Writer {
std::string data;
void n(uint64_t value,unsigned bytes){for(unsigned i=0;i<bytes;++i){data+=char(value&255);value>>=8;}}
void s(const std::string& text){n(text.size(),2);data+=text;}
void reward(const PortEconomy::Reward& r){
n(r.id,4);n(r.vnum,4);n(r.count,4);
for(auto x:r.sockets)n(uint32_t(x),4);
for(unsigned i=0;i<7;++i){n(r.types[i],1);n(uint16_t(r.values[i]),2);}
for(auto x:r.extra)n(x,1);
}
void items(const std::vector<Item>& rows){n(rows.size(),2);for(const auto& i:rows){reward(i.value);n(i.cell,2);n(i.usable,1);}}
};
struct Reader {
const std::string& data;size_t at=0;bool ok=true;
explicit Reader(const std::string& value):data(value){}
uint64_t n(unsigned bytes){
if(!ok||bytes>8||at>data.size()||bytes>data.size()-at){ok=false;return 0;}
uint64_t value=0;for(unsigned i=0;i<bytes;++i)value|=uint64_t(uint8_t(data[at++]))<<(8*i);return value;
}
std::string s(unsigned maximum){const auto count=n(2);if(!ok||count>maximum||count>data.size()-at){ok=false;return {};}
std::string value=data.substr(at,size_t(count));at+=size_t(count);return value;}
PortEconomy::Reward reward(){
PortEconomy::Reward r;r.id=uint32_t(n(4));r.vnum=uint32_t(n(4));r.count=uint32_t(n(4));
for(auto& x:r.sockets){uint32_t bits=uint32_t(n(4));std::memcpy(&x,&bits,4);}
for(unsigned i=0;i<7;++i){r.types[i]=uint8_t(n(1));uint16_t bits=uint16_t(n(2));std::memcpy(&r.values[i],&bits,2);}
for(auto& x:r.extra)x=uint8_t(n(1));return r;
}
std::vector<Item> items(){
const auto count=n(2);if(count>225){ok=false;return {};}
std::vector<Item> rows;for(unsigned i=0;i<count&&ok;++i){Item item;item.value=reward();item.cell=uint16_t(n(2));auto usable=n(1);if(usable>1)ok=false;item.usable=usable!=0;rows.push_back(item);}return rows;
}
};
inline std::string Encode(const Batch& b) {
Writer w;w.n(1,4);w.n(b.account,4);w.n(b.player,4);w.n(b.epoch,8);w.n(b.gold,8);w.s(b.owner);w.s(b.token);
const auto& r=b.recipe;w.n(r.id,4);w.n(r.reward,4);w.n(r.rewardCount,4);w.n(r.gold,4);w.n(r.percent,1);w.n(r.stackable,1);w.n(r.copy,1);w.s(r.category);
w.n(r.npcs.size(),1);for(auto n:r.npcs)w.n(n,4);
w.n(r.materials.size(),1);for(auto m:r.materials){w.n(m.vnum,4);w.n(m.count,4);}
w.n(b.attempts,1);w.items(b.inventory);w.n(b.rewards.size(),1);for(const auto& item:b.rewards)w.reward(item);
return w.data;
}
inline bool Decode(const std::string& data,Batch& out) {
if(data.size()>40000)return false;
Reader r(data);Batch b;if(r.n(4)!=1)return false;
b.account=uint32_t(r.n(4));b.player=uint32_t(r.n(4));b.epoch=r.n(8);b.gold=r.n(8);b.owner=r.s(32);b.token=r.s(32);
auto& recipe=b.recipe;recipe.id=uint32_t(r.n(4));recipe.reward=uint32_t(r.n(4));recipe.rewardCount=uint32_t(r.n(4));recipe.gold=uint32_t(r.n(4));recipe.percent=unsigned(r.n(1));
auto stack=r.n(1),copy=r.n(1);if(stack>1||copy>1)return false;recipe.stackable=stack!=0;recipe.copy=copy!=0;recipe.category=r.s(24);
auto count=r.n(1);if(count>128)return false;for(unsigned i=0;i<count&&r.ok;++i)recipe.npcs.push_back(uint32_t(r.n(4)));
count=r.n(1);if(count>5)return false;for(unsigned i=0;i<count&&r.ok;++i){Material m;m.vnum=uint32_t(r.n(4));m.count=uint32_t(r.n(4));recipe.materials.push_back(m);}
b.attempts=unsigned(r.n(1));b.inventory=r.items();count=r.n(1);if(count>100)return false;for(unsigned i=0;i<count&&r.ok;++i)b.rewards.push_back(r.reward());
if(!r.ok||r.at!=data.size()||!Validate(b)||Encode(b)!=data)return false;out=std::move(b);return true;
}
struct Proto {unsigned size=0;bool stackable=false;};
using Lookup=std::function<Proto(uint32_t)>;
struct Settlement {
std::string result="invalid";
unsigned successes=0;
uint64_t fee=0;
std::vector<Take> takes;
std::vector<Item> awards;
};
inline Settlement SettlePlan(const Batch& b,const std::string& rolls,const Lookup& lookup) {
Settlement s;if(!Validate(b)||rolls.size()!=b.attempts)return s;
for(unsigned char roll:rolls){if(roll<1||roll>100)return s;s.successes+=roll<=b.recipe.percent;}
const auto reward=lookup(b.recipe.reward);
if(reward.size<1||reward.size>3||reward.stackable!=b.recipe.stackable){s.result="item_proto";return s;}
std::vector<Input> inputs;for(const auto& i:b.inventory)inputs.push_back({i.value.id,i.value.vnum,i.value.count,i.cell,i.usable});
const auto p=Preview(b.recipe,b.attempts,inputs,int64_t(b.gold));
if(!p.valid)return s;
if(!p.materialsOK){s.result="materials_missing";return s;}
if(!p.goldOK){s.result="gold_missing";return s;}
auto inventory=b.inventory;
auto occupy=[&](const std::vector<Item>& rows,std::array<bool,225>& used)->bool {
for(const auto& i:rows) {
if(!i.value.count)continue;const auto proto=lookup(i.value.vnum);
if(proto.size<1||proto.size>3||(!proto.stackable&&i.value.count!=1)||(i.cell%45)/5+proto.size>9)return false;
for(unsigned j=0;j<proto.size;++j){const unsigned at=i.cell+5*j;if(at>=225||used[at])return false;used[at]=true;}
}
return true;
};
std::array<bool,225> used={};
if(!occupy(inventory,used)){s.result="inventory_invalid";return s;}
for(const auto& take:p.takes)for(auto& i:inventory)if(i.value.id==take.id)i.value.count-=take.count;
used.fill(false);if(!occupy(inventory,used))return s;
uint64_t remaining=uint64_t(b.recipe.rewardCount)*s.successes;unsigned next=0;
while(remaining) {
unsigned cell=225;
for(unsigned at=0;at<225;++at) {
if((at%45)/5+reward.size>9)continue;bool free=true;
for(unsigned j=0;j<reward.size;++j)if(used[at+5*j])free=false;
if(free){cell=at;break;}
}
if(cell==225){s.awards.clear();s.result="capacity_full";return s;}
Item item;item.value=b.rewards[next++];item.value.count=uint32_t(std::min(remaining,uint64_t(reward.stackable?2000:1)));item.cell=uint16_t(cell);
for(unsigned j=0;j<reward.size;++j)used[cell+5*j]=true;
remaining-=item.value.count;s.awards.push_back(item);
}
s.result="ok";s.fee=p.gold;s.takes=p.takes;return s;
}
}
+30
View File
@@ -0,0 +1,30 @@
#pragma once
#include "cube_handshake.h"
namespace PortCube {
class CraftFlow {
public:
enum Stage {Idle,WaitPrepare,WaitExecute,Complete,Held};
private:
Handshake identity;Stage stage=Idle;CraftReceipt receipt;
public:
Stage State()const{return stage;}
const CraftReceipt& Receipt()const{return receipt;}
bool MayRetry()const{return stage==WaitPrepare||stage==WaitExecute;}
bool Start(const Handshake& bound,bool cleanFrozen,bool sourceAcknowledged) {
auto f=bound;f.message=Message::Prepare;f.status=Status::None;f.body.clear();
if(stage!=Idle||!cleanFrozen||!sourceAcknowledged||!ValidHandshake(f))return false;identity=std::move(f);stage=WaitPrepare;return true;
}
Handshake Request()const{auto f=identity;f.message=stage==WaitExecute?Message::Execute:Message::Prepare;return f;}
void Invalidate(){if(stage!=Idle)stage=Held;}
bool Answer(const Handshake& f,const Batch& b,const Lookup& lookup) {
if(b.account!=identity.account||b.player!=identity.player||b.epoch!=identity.epoch||b.owner!=identity.owner||b.token!=identity.token)return false;
if(!ValidHandshake(f)||f.message!=Message::CraftAnswer||!SameIdentity(identity,f)||f.cookie!=identity.cookie||!MayRetry()&&stage!=Complete)return false;
if(f.status==Status::Held)return MayRetry();
if(f.status==Status::Prepared){if(stage==WaitPrepare){stage=WaitExecute;return true;}return stage==WaitExecute;}
if(f.status!=Status::Complete||stage==WaitPrepare)return false;
CraftReceipt result;if(!DecodeCraftReceipt(f.body,result)||!ValidateCraftReceipt(b,result,lookup))return false;
if(stage==Complete){if(EncodeCraftReceipt(receipt)==f.body)return true;stage=Held;return false;}
receipt=std::move(result);stage=Complete;return true; // never authorizes local assets, saves, ACK or thaw
}
};
}
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include "cube_batch.h"
namespace PortCube {
// Transport-independent correlation core. The runtime adapter must bind session
// to the actual game peer/character generation and not accept it from a client.
class Drain {
std::string identity;
uint64_t session=0,mainEpoch=0,asyncEpoch=0;
unsigned pass=0;
bool asyncDone=false,failed=false;
public:
bool Start(const Batch& batch,uint64_t ownerSession,uint64_t main,uint64_t async) {
if(!identity.empty()||!Validate(batch)||!ownerSession)return false;
identity=Encode(batch);session=ownerSession;mainEpoch=main;asyncEpoch=async;return true;
}
// Return 1 only for the FIRST main barrier: adapter must enqueue the second
// main FIFO barrier and the async FIFO barrier after processing that callback.
// Numbered passes prevent a duplicate first callback completing the drain.
unsigned Main(const Batch& b,uint64_t sourceSession,unsigned number,bool error) {
if(identity!=Encode(b)||sourceSession!=session||number!=pass+1||number>2)return 0;
failed|=error;pass=number;return pass==1?1:2;
}
bool Async(const Batch& b,uint64_t sourceSession,bool error) {
if(identity!=Encode(b)||sourceSession!=session||pass<1||asyncDone)return false;
failed|=error;asyncDone=true;return true;
}
bool Matches(const Batch& b,uint64_t sourceSession)const{return !identity.empty()&&identity==Encode(b)&&sourceSession==session;}
bool Complete()const{return pass==2&&asyncDone;}
bool Clean(uint64_t main,uint64_t async)const{return Complete()&&!failed&&main==mainEpoch&&async==asyncEpoch;}
};
}
+172
View File
@@ -0,0 +1,172 @@
#pragma once
#include "cube_store.h"
#include "cube_drain.h"
#include "cube_gold_intent.h"
#include "cube_owner_types.h"
namespace PortCube {
// DB-side lifecycle, not an actor-freeze implementation. Only a trusted runtime
// coordinator may call these methods after binding the session and all owners.
template<class DB> class FenceStore {
DB& db;Lookup lookup;
using Rows=PortEconomy::Rows;
static std::string N(uint64_t n){return std::to_string(n);}
static std::string X(const std::string& s){return "X'"+PortEconomy::Hex(s.data(),s.size())+"'";}
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 Lock(const Batch& b,Rows& rows) {
if(!Run("INSERT INTO port_economy_account_lock(account) VALUES("+N(b.account)+") ON DUPLICATE KEY UPDATE account=VALUES(account)")||
!Q("SELECT account FROM port_economy_account_lock WHERE account="+N(b.account)+" FOR UPDATE",rows)||rows.size()!=1)return false;
return Q("SELECT account,epoch,owner,request,phase,body,image,drain_state FROM port_cube_fences WHERE pid="+N(b.player)+" FOR UPDATE",rows);
}
bool Same(const Batch& b,const Rows& rows)const {
return rows.size()==1&&rows[0].size()==8&&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);
}
static bool Signed(const std::string& s,int64_t low,int64_t high,int64_t& out) {
if(s.empty())return false;const bool negative=s[0]=='-';uint64_t n=0;
if(!PortEconomy::Number(negative?s.substr(1):s,n,uint64_t(negative?-low:high)))return false;
out=negative?-int64_t(n):int64_t(n);return out>=low&&out<=high&&std::to_string(out)==s;
}
bool Image(const Batch& b,std::string& image) {
Rows rows;uint64_t gold=0;
if(!Q("SELECT gold FROM player WHERE id="+N(b.player)+" AND account_id="+N(b.account)+" FOR UPDATE",rows)||rows.size()!=1||rows[0].size()!=1||!PortEconomy::Number(rows[0][0],gold,PortEconomy::GoldLimit))return false;
std::string columns="id,vnum,count,pos";for(unsigned i=0;i<3;++i)columns+=",socket"+N(i);
for(unsigned i=0;i<7;++i)columns+=",attrtype"+N(i)+",attrvalue"+N(i);columns+=",port_extra";
if(!Q("SELECT "+columns+" FROM item WHERE owner_id="+N(b.player)+" AND window='INVENTORY' AND pos<225 ORDER BY pos,id FOR UPDATE",rows)||rows.size()>225)return false;
std::vector<Item> items;std::set<uint32_t> ids;std::array<bool,225> used={};int last=-1;
for(const auto& row:rows) {
if(row.size()!=22)return false;
Item i;uint64_t n=0;int64_t signedValue=0;
auto number=[&](unsigned field,uint64_t max)->bool {return PortEconomy::Number(row[field],n,max);};
if(!number(0,UINT32_MAX)||!n)return false;i.value.id=uint32_t(n);
if(!number(1,UINT32_MAX)||!n)return false;i.value.vnum=uint32_t(n);
if(!number(2,2000)||!n)return false;i.value.count=uint32_t(n);
if(!number(3,224))return false;i.cell=uint16_t(n);
if(int(i.cell)<=last||!ids.insert(i.value.id).second)return false;last=i.cell;
for(unsigned j=0;j<3;++j){if(!Signed(row[4+j],INT32_MIN,INT32_MAX,signedValue))return false;i.value.sockets[j]=int32_t(signedValue);}
for(unsigned j=0;j<7;++j){if(!number(7+2*j,255))return false;i.value.types[j]=uint8_t(n);if(!Signed(row[8+2*j],INT16_MIN,INT16_MAX,signedValue))return false;i.value.values[j]=int16_t(signedValue);}
if(row[21].size()!=69)return false;std::memcpy(i.value.extra,row[21].data(),69);
const auto proto=lookup(i.value.vnum);if(proto.size<1||proto.size>3||(!proto.stackable&&i.value.count!=1)||(i.cell%45)/5+proto.size>9)return false;
for(unsigned j=0;j<proto.size;++j){const unsigned cell=i.cell+5*j;if(cell>=225||used[cell])return false;used[cell]=true;}
items.push_back(i);
}
Writer w;w.n(gold,8);w.items(items);image=std::move(w.data);return true;
}
public:
enum Result { Retry, Refused, Done };
FenceStore(DB& database,Lookup proto):db(database),lookup(std::move(proto)){}
// cachedIds must include ALL owned dirty item IDs captured by the DB adapter
// before eviction, not merely the normal-inventory recipe inputs.
Result Begin(const Batch& b,const std::vector<uint32_t>& cachedIds,const std::function<bool(bool)>& ownership={}) {
if(!Validate(b)||cachedIds.size()>4096)return Refused;
BatchStore<DB> ready(db,lookup);if(!ready.Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows;
if(!Lock(b,rows))return Retry;
if(Same(b,rows))return !ownership||ownership(true)?Done:Refused; // never invent missing ownership on replay
if(!rows.empty()) {
uint64_t previous=0;if(rows.size()!=1||rows[0].size()!=8||rows[0][4]!="RELEASED"||rows[0][3]==b.token||!PortEconomy::Number(rows[0][1],previous)||b.epoch<=previous)return Refused;
}
if(!Q("SELECT token FROM port_economy_pending WHERE pid="+N(b.player)+" FOR UPDATE",rows))return Retry;if(!rows.empty())return Refused;
if(!Q("SELECT token FROM port_cube_requests WHERE token='"+b.token+"' FOR UPDATE",rows))return Retry;if(!rows.empty())return Refused;
// The drain itself can survive a restart before Prepare. Reserve every
// reward ID now, not only after RNG preparation, so boot cannot reuse it.
for(const auto& reward:b.rewards) {
if(!Q("SELECT id FROM item WHERE id="+N(reward.id)+" UNION ALL SELECT id FROM port_economy_custody WHERE id="+N(reward.id)+" UNION ALL SELECT id FROM port_economy_item_reservations WHERE id="+N(reward.id),rows))return Retry;
if(!rows.empty())return Refused;
if(!Change("INSERT INTO port_economy_item_reservations(id,request) VALUES("+N(reward.id)+",'"+b.token+"')"))return Retry;
}
std::set<uint32_t> ids;
for(auto id:cachedIds){if(!id)return Refused;ids.insert(id);}
for(const auto& i:b.inventory)ids.insert(i.value.id);for(const auto& i:b.rewards)ids.insert(i.id);
if(!Q("SELECT id FROM item WHERE owner_id="+N(b.player)+" AND window NOT IN ('MALL','SAFEBOX') FOR UPDATE",rows))return Retry;
if(rows.size()>4096)return Refused;
for(const auto& row:rows){uint64_t id=0;if(row.size()!=1||!PortEconomy::Number(row[0],id,UINT32_MAX)||!id)return Retry;ids.insert(uint32_t(id));}
const auto body=Encode(b);
if(!Run("DELETE FROM port_cube_fences WHERE pid="+N(b.player)+" AND phase='RELEASED'")||
!Change("INSERT INTO port_cube_fences(pid,account,epoch,owner,request,phase,body,image,drain_state) VALUES("+N(b.player)+","+N(b.account)+","+N(b.epoch)+",'"+b.owner+"','"+b.token+"','DRAINING',"+X(body)+",X'',0)"))return Retry;
for(auto id:ids)if(!Change("INSERT INTO port_cube_item_fences(id,pid,epoch,request) VALUES("+N(id)+","+N(b.player)+","+N(b.epoch)+",'"+b.token+"')"))return Retry;
if(ownership&&!ownership(false))return Refused;
return db.Commit()?Done:Retry;
}
Result FinishDrain(const Batch& b,const Drain& drain,uint64_t session,uint64_t main,uint64_t async,bool stillOwner) {
if(!Validate(b)||!drain.Matches(b,session)||!drain.Complete())return Refused;
BatchStore<DB> ready(db,lookup);if(!ready.Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows;
if(!Lock(b,rows))return Retry;if(!Same(b,rows))return Refused;
const char* phase=stillOwner&&drain.Clean(main,async)?"FROZEN":"ABORTED";
if(rows[0][4]==phase&&rows[0][7]==(std::string(phase)=="FROZEN"?"1":"2"))return Done;
if(rows[0][4]!="DRAINING")return Refused;
if(!Change("UPDATE port_cube_fences SET phase='"+std::string(phase)+"',drain_state="+(phase==std::string("FROZEN")?"1":"2")+" WHERE pid="+N(b.player)+" AND phase='DRAINING'"))return Retry;
return db.Commit()?Done:Retry;
}
Result AbortUnprepared(const Batch& b) {
if(!Validate(b))return Refused;BatchStore<DB> ready(db,lookup);
if(!ready.Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows;
if(!Lock(b,rows))return Retry;if(!Same(b,rows))return Refused;
if(rows[0][4]=="ABORTED"&&rows[0][7]=="2")return Done;
if(rows[0][4]!="FROZEN"||rows[0][7]!="1")return Refused;
if(!Q("SELECT token FROM port_cube_requests WHERE token='"+b.token+"' FOR UPDATE",rows))return Retry;
if(!rows.empty())return Refused; // an ambiguous prepare must be queried, not cancelled blindly
if(!Change("UPDATE port_cube_fences SET phase='ABORTED',drain_state=2 WHERE pid="+N(b.player)+" AND phase='FROZEN'")||!db.Commit())return Retry;
return Done;
}
Result Recover(uint32_t account,uint32_t player,Batch& batch,std::string& phase,std::string& image) {
batch={};phase.clear();image.clear();if(!account||!player)return Refused;
BatchStore<DB> ready(db,lookup);if(!ready.Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows;
if(!Q("SELECT account,epoch,owner,request,phase,body,image,drain_state FROM port_cube_fences WHERE pid="+N(player)+" AND account="+N(account)+" FOR UPDATE",rows))return Retry;
if(rows.empty())return Refused;
if(rows.size()!=1||rows[0].size()!=8||!Decode(rows[0][5],batch)||batch.account!=account||batch.player!=player||!Same(batch,rows)||rows[0][6].size()>40000)return Retry;
const std::set<std::string> states={"DRAINING","FROZEN","ABORTED","RESYNC","RELEASED"};
const auto& stage=rows[0][4];const auto& drained=rows[0][7];
if(!states.count(stage)||(stage=="DRAINING"&&drained!="0")||(stage=="FROZEN"&&drained!="1")||(stage=="ABORTED"&&drained!="2")||((stage=="RESYNC"||stage=="RELEASED")&&drained!="1"&&drained!="2"))return Retry;
phase=stage;image=rows[0][6];return Done;
}
Result Resync(const Batch& b,std::string& image,const std::function<bool(const std::string&)>& ownership={}) {
image.clear();if(!Validate(b))return Refused;
BatchStore<DB> ready(db,lookup);if(!ready.Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows;
if(!Lock(b,rows))return Retry;if(!Same(b,rows))return Refused;
const auto phase=rows[0][4],drained=rows[0][7],saved=rows[0][6];
if(!ownership){const int owner=OwnerReleaseStatus(db,b);if(owner<0)return Retry;if(!owner)return Refused;}
if(phase!="ABORTED"&&phase!="FROZEN"&&phase!="RESYNC")return Refused;
if(!Q("SELECT state FROM port_cube_requests WHERE token='"+b.token+"' AND account="+N(b.account)+" AND pid="+N(b.player)+" FOR UPDATE",rows))return Retry;
if(drained!="1"&&drained!="2")return Refused;
if((drained=="2"&&!rows.empty())||(drained=="1"&&(rows.size()!=1||rows[0].size()!=1||rows[0][0]!="DONE")))return Refused;
{const int clear=GoldIntentsStatus(db,b);if(clear<0)return Retry;if(!clear)return Refused;}
std::string current;if(!Image(b,current))return Retry;
if(ownership&&!ownership(current))return Refused;
if(ownership&&phase=="RESYNC"&&saved!=current)return Refused; // never replace an owner's previously issued image
if(!Run("UPDATE port_cube_fences SET phase='RESYNC',image="+X(current)+" WHERE pid="+N(b.player))||!db.Commit())return Retry;
image=std::move(current);return Done;
}
// ACK is the exact canonical image, not an FNV hash or a timeout. The game
// adapter must verify it has applied that image to this still-frozen owner.
Result Release(const Batch& b,const std::string& acknowledged,const std::function<bool(bool)>& ownership={}) {
if(!Validate(b)||acknowledged.empty()||acknowledged.size()>40000)return Refused;
BatchStore<DB> ready(db,lookup);if(!ready.Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows;
if(!Lock(b,rows))return Retry;if(!Same(b,rows)||rows[0][6]!=acknowledged)return Refused;
if(!ownership){const int owner=OwnerReleaseStatus(db,b);if(owner<0)return Retry;if(!owner)return Refused;}
if(rows[0][4]=="RELEASED")return !ownership||ownership(true)?Done:Refused;
if(rows[0][4]!="RESYNC")return Refused;
{const int clear=GoldIntentsStatus(db,b);if(clear<0)return Retry;if(!clear)return Refused;}
std::string current;if(!Image(b,current))return Retry;if(current!=acknowledged)return Refused;
// Trusted coordinator callback shares this account transaction. It must
// validate current ownership and atomically archive/retire the lease.
if(ownership&&!ownership(false))return Refused;
if(!Run("DELETE FROM port_cube_item_fences WHERE pid="+N(b.player)+" AND epoch="+N(b.epoch)+" AND request='"+b.token+"'")||
!Change("UPDATE port_cube_fences SET phase='RELEASED' WHERE pid="+N(b.player)+" AND phase='RESYNC'")||!db.Commit())return Retry;
return Done;
}
// Resume preflight only. A historical Release replay does not reread current
// assets; this check MUST lock and validate the current image anew, on the
// same pinned connection/account transaction as the authority callback.
Result CheckReleasedImage(const Batch& b,const std::string& expected,const std::function<bool()>& authority) {
if(!Validate(b)||expected.empty()||expected.size()>40000||!authority)return Refused;
BatchStore<DB> ready(db,lookup);if(!ready.Ready()||!db.Begin())return Retry;Guard guard{db};Rows rows;
if(!Lock(b,rows))return Retry;
if(!Same(b,rows)||rows[0][4]!="RELEASED"||rows[0][6]!=expected||rows[0][7]!="1")return Refused;
{const int clear=GoldIntentsStatus(db,b);if(clear<0)return Retry;if(!clear)return Refused;}
std::string current;if(!Image(b,current))return Retry;if(current!=expected||!authority())return Refused;
return db.Commit()?Done:Retry;
}
};
}
+94
View File
@@ -0,0 +1,94 @@
#pragma once
#include "cube_store.h"
#include "cube_gold_source.h"
namespace PortCube {
// Positive reward intents ONLY. Not a generic PointChange replacement, item
// snapshot, permission to mint currency, or proof a source event is legitimate.
constexpr unsigned GoldIntentLimit=1024,GoldIntentBytes=129;
static_assert(GoldIntentLimit==GoldSourceLimit,"source manifest covers every intent sequence");
struct GoldIntent {
uint32_t account=0,player=0,sequence=0;
uint64_t epoch=0,amount=0;
uint8_t source=0; // trusted producer registry: 1 combat, 2 quest, 3 delivery
std::string owner,request,event;
};
inline bool ValidGoldIntent(const GoldIntent& i) {
return i.account&&i.player&&i.epoch&&i.sequence&&i.sequence<=GoldIntentLimit&&
i.amount&&i.amount<=uint64_t(PortEconomy::GoldLimit)&&i.source>=1&&i.source<=3&&
Identity(i.owner)&&Identity(i.request)&&Identity(i.event);
}
inline bool Matches(const GoldIntent& i,const Batch& b) {
return i.account==b.account&&i.player==b.player&&i.epoch==b.epoch&&i.owner==b.owner&&i.request==b.token;
}
inline std::string EncodeGoldIntent(const GoldIntent& i) {
if(!ValidGoldIntent(i))return {};
Writer w;w.n(1,4);w.n(i.account,4);w.n(i.player,4);w.n(i.epoch,8);w.n(i.sequence,4);w.n(i.amount,8);w.n(i.source,1);
w.data+=i.owner;w.data+=i.request;w.data+=i.event;return w.data;
}
inline bool DecodeGoldIntent(const std::string& bytes,GoldIntent& i) {
i={};if(bytes.size()!=GoldIntentBytes)return false;Reader r(bytes);if(r.n(4)!=1)return false;
GoldIntent out;out.account=uint32_t(r.n(4));out.player=uint32_t(r.n(4));out.epoch=r.n(8);out.sequence=uint32_t(r.n(4));out.amount=r.n(8);out.source=uint8_t(r.n(1));
out.owner=bytes.substr(r.at,32);out.request=bytes.substr(r.at+32,32);out.event=bytes.substr(r.at+64,32);
if(!r.ok||!ValidGoldIntent(out)||EncodeGoldIntent(out)!=bytes)return false;i=std::move(out);return true;
}
template<class DB> int GoldSchema(DB& db) {
PortEconomy::Rows rows;
const std::string names="('port_cube_gold_version','port_cube_gold_intents','port_cube_gold_sources')";
if(!db.Query("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME IN "+names,rows)||db.warnings||rows.size()!=1||rows[0].size()!=1)return -1;
if(rows[0][0]=="0")return 0;
if(rows[0][0]!="3"||!db.Query("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN "+names,rows)||db.warnings||rows.size()!=1||rows[0].size()!=1||rows[0][0]!="3")return -1;
if(!db.Query("SELECT version FROM port_cube_gold_version WHERE id=1",rows)||db.warnings||rows.size()!=1||rows[0].size()!=1||rows[0][0]!="2")return -1;
return 1;
}
struct GoldRecord {GoldIntent intent;bool applied=false;uint64_t before=0,after=0;};
// Caller holds the account lock. No inferred deltas from a stale game snapshot.
template<class DB> bool GoldRecords(DB& db,const Batch& b,std::vector<GoldRecord>& records) {
records.clear();PortEconomy::Rows rows;
if(!db.Query("SELECT event,seq,account,pid,body,state,before_gold,after_gold FROM port_cube_gold_intents WHERE request='"+b.token+"' ORDER BY seq FOR UPDATE",rows)||db.warnings||rows.size()>GoldIntentLimit)return false;
bool pending=false;std::set<std::string> ids;uint64_t previous=0;
for(const auto& row:rows) {
GoldRecord record;if(row.size()!=8||!DecodeGoldIntent(row[4],record.intent)||!Matches(record.intent,b))return false;
const auto& i=record.intent;
if(i.sequence!=records.size()+1||row[0]!=i.event||row[1]!=std::to_string(i.sequence)||row[2]!=std::to_string(i.account)||row[3]!=std::to_string(i.player)||!ids.insert(i.event).second)return false;
if(!PortEconomy::Number(row[6],record.before,PortEconomy::GoldLimit)||!PortEconomy::Number(row[7],record.after,PortEconomy::GoldLimit))return false;
record.applied=row[5]=="APPLIED";
if(record.applied) {
if(pending||record.before>uint64_t(PortEconomy::GoldLimit)-i.amount||record.after!=record.before+i.amount||(!records.empty()&&record.before!=previous))return false;
previous=record.after;
} else {if(row[5]!="QUEUED"||record.before||record.after)return false;pending=true;}
records.push_back(std::move(record));
}
return true;
}
template<class DB> int GoldCreditBase(DB& db,const Batch& b,uint64_t& base) {
PortEconomy::Rows rows;typename BatchStore<DB>::Receipt receipt;
if(!db.Query("SELECT body,rolls,state,result,successes,fee,awards FROM port_cube_requests WHERE token='"+b.token+"' AND account="+std::to_string(b.account)+" AND pid="+std::to_string(b.player)+" FOR UPDATE",rows)||db.warnings)return -1;
if(rows.size()!=1||!BatchStore<DB>::DoneReceipt(b,rows[0],receipt)||receipt.fee>b.gold)return 0;
base=b.gold-receipt.fee;return 1;
}
template<class DB> int GoldIntentsStatus(DB& db,const Batch& b) {
const int schema=GoldSchema(db);if(schema==0)return 1;if(schema<0)return -1;
std::vector<GoldRecord> records;if(!GoldRecords(db,b,records))return -1;
// Even zero credits need an explicit closed-source proof. SQL emptiness
// cannot exclude a local durable intent whose delivery has not arrived.
PortEconomy::Rows seals;
if(!db.Query("SELECT account,pid,epoch,owner,session,cookie,handle,manifest FROM port_cube_gold_sources WHERE request='"+b.token+"' FOR UPDATE",seals)||db.warnings)return -1;
if(seals.empty())return 0;
if(seals.size()!=1||seals[0].size()!=8)return -1;
const auto& row=seals[0];GoldSourceSeal seal;static_cast<GoldSourceBinding&>(seal)=GoldSourceFor(b,0,0,0);
uint64_t cookie=0,handle=0;
if(row[0]!=std::to_string(b.account)||row[1]!=std::to_string(b.player)||row[2]!=std::to_string(b.epoch)||row[3]!=b.owner||
!PortEconomy::Number(row[4],seal.session)||!PortEconomy::Number(row[5],cookie,UINT32_MAX)||!PortEconomy::Number(row[6],handle,UINT32_MAX))return -1;
seal.cookie=uint32_t(cookie);seal.handle=uint32_t(handle);
if(EncodeGoldSourceBinding(seal).empty()||!DecodeGoldManifest(row[7],seal.events)||seal.events.size()!=records.size())return -1;
for(size_t n=0;n<records.size();++n)if(records[n].intent.event!=seal.events[n])return -1;
for(const auto& record:records)if(!record.applied)return 0;
if(!records.empty()) {
uint64_t base=0,current=0;PortEconomy::Rows rows;
const int ready=GoldCreditBase(db,b,base);if(ready<0)return -1;if(!ready||records.front().before!=base)return 0;
if(!db.Query("SELECT gold FROM player WHERE id="+std::to_string(b.player)+" AND account_id="+std::to_string(b.account)+" FOR UPDATE",rows)||db.warnings)return -1;
if(rows.size()!=1||rows[0].size()!=1||!PortEconomy::Number(rows[0][0],current,PortEconomy::GoldLimit)||current!=records.back().after)return 0;
}
return 1;
}
}
+189
View File
@@ -0,0 +1,189 @@
#pragma once
#include "cube_gold_intent.h"
#include <cerrno>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <tuple>
#include <unistd.h>
namespace PortCube {
// Core-private, bounded append-only journal. ACK means DB has the immutable
// intent, NOT that currency is applied or the actor may thaw. Keep ACK history
// so a restarted writer cannot reuse a sequence. No automatic compaction yet.
struct GoldDelivery {
GoldIntent intent;
uint64_t session=0;
uint32_t cookie=0,handle=0,ground=0,vnum=0,map=0;
};
constexpr size_t GoldDeliveryBytes=GoldIntentBytes+28;
inline std::string EncodeGoldDelivery(const GoldDelivery& d) {
const auto body=EncodeGoldIntent(d.intent);
if(body.empty()||d.intent.source!=1||!d.session||!d.cookie||!d.handle||!d.ground||!d.vnum||!d.map)return {};
Writer w;w.data=body;w.n(d.session,8);w.n(d.cookie,4);w.n(d.handle,4);w.n(d.ground,4);w.n(d.vnum,4);w.n(d.map,4);return w.data;
}
inline bool DecodeGoldDelivery(const std::string& body,GoldDelivery& d) {
d={};if(body.size()!=GoldDeliveryBytes)return false;GoldDelivery out;
if(!DecodeGoldIntent(body.substr(0,GoldIntentBytes),out.intent))return false;
Reader r(body);r.at=GoldIntentBytes;out.session=r.n(8);out.cookie=uint32_t(r.n(4));out.handle=uint32_t(r.n(4));
out.ground=uint32_t(r.n(4));out.vnum=uint32_t(r.n(4));out.map=uint32_t(r.n(4));
if(!r.ok||r.at!=body.size()||EncodeGoldDelivery(out)!=body)return false;d=std::move(out);return true;
}
inline GoldSourceBinding GoldSourceFor(const GoldDelivery& d) {
GoldSourceBinding s;s.account=d.intent.account;s.player=d.intent.player;s.epoch=d.intent.epoch;s.owner=d.intent.owner;s.request=d.intent.request;
s.session=d.session;s.cookie=d.cookie;s.handle=d.handle;return s;
}
class GoldOutbox {
struct Record {GoldDelivery delivery;bool acknowledged=false;};
struct Closing {GoldSourceBinding binding;unsigned count=0;bool acknowledged=false;};
int fd=-1,lock=-1,directory=-1;bool healthy=false;size_t bytes=0;
std::string error;std::map<std::string,Record> records;
std::map<std::string,Closing> sources;
static uint32_t Hash(const std::string& body){uint32_t h=2166136261u;for(unsigned char c:body){h^=c;h*=16777619u;}return h;}
bool Fail(const char* reason){healthy=false;error=reason;return false;}
static bool PrivateFile(int f){struct stat s={};return fstat(f,&s)==0&&S_ISREG(s.st_mode)&&s.st_nlink==1&&s.st_uid==geteuid()&&!(s.st_mode&0022);}
static bool WriteAll(int f,const std::string& body) {
size_t at=0;while(at<body.size()){const auto n=write(f,body.data()+at,body.size()-at);if(n<0&&errno==EINTR)continue;if(n<=0)return false;at+=size_t(n);}return true;
}
static std::string ClosingBody(const Closing& c) {
const auto binding=EncodeGoldSourceBinding(c.binding);if(binding.empty()||c.count>GoldSourceLimit)return {};
Writer w;w.data=binding;w.n(c.count,4);w.data.resize(GoldDeliveryBytes,'\0');return w.data;
}
static bool DecodeClosing(const std::string& body,Closing& c) {
c={};if(body.size()!=GoldDeliveryBytes)return false;Closing out;
if(!DecodeGoldSourceBinding(body.substr(0,GoldSourceBindingBytes),out.binding))return false;
Reader r(body);r.at=GoldSourceBindingBytes;out.count=unsigned(r.n(4));if(!r.ok||ClosingBody(out)!=body)return false;c=std::move(out);return true;
}
bool SourceImage(const GoldSourceBinding& binding,bool requireAck,GoldSourceSeal& seal)const {
seal={};if(EncodeGoldSourceBinding(binding).empty())return false;static_cast<GoldSourceBinding&>(seal)=binding;
std::vector<std::pair<unsigned,std::string>> ordered;
for(const auto& entry:records)if(entry.second.delivery.intent.request==binding.request) {
const auto& r=entry.second;
if((requireAck&&!r.acknowledged)||EncodeGoldSourceBinding(GoldSourceFor(r.delivery))!=EncodeGoldSourceBinding(binding))return false;
ordered.emplace_back(r.delivery.intent.sequence,r.delivery.intent.event);
}
std::sort(ordered.begin(),ordered.end());for(const auto& e:ordered){if(e.first!=seal.events.size()+1)return false;seal.events.push_back(e.second);}
return !EncodeGoldManifest(seal.events).empty();
}
bool AppendBody(unsigned op,const std::string& body) {
Writer w;w.data="CGO1";w.n(op,1);w.data+=body;w.n(Hash(w.data),4);const auto& frame=w.data;
if(!healthy||frame.size()!=FrameBytes||bytes>MaxBytes-frame.size())return Fail("gold outbox unavailable/full; retain hold and journal");
if(!WriteAll(fd,frame)||fsync(fd)!=0)return Fail("gold outbox write/sync uncertain; quarantine source and retain journal");
bytes+=frame.size();return true;
}
bool Append(unsigned op,const GoldDelivery& d){return AppendBody(op,EncodeGoldDelivery(d));}
bool Admit(const GoldDelivery& d)const {
if(EncodeGoldDelivery(d).empty()||records.size()>=MaxRecords||sources.count(d.intent.request))return false;
unsigned sequence=1;
for(const auto& entry:records)if(entry.second.delivery.intent.request==d.intent.request) {
const auto& i=entry.second.delivery.intent;
if(i.account!=d.intent.account||i.player!=d.intent.player||i.epoch!=d.intent.epoch||i.owner!=d.intent.owner)return false;
if(EncodeGoldSourceBinding(GoldSourceFor(entry.second.delivery))!=EncodeGoldSourceBinding(GoldSourceFor(d)))return false;
++sequence;
}
return d.intent.sequence==sequence;
}
public:
static constexpr size_t MaxRecords=8192,MaxBytes=16*1024*1024,FrameBytes=4+1+GoldDeliveryBytes+4;
GoldOutbox()=default;GoldOutbox(const GoldOutbox&)=delete;GoldOutbox& operator=(const GoldOutbox&)=delete;
~GoldOutbox(){if(fd>=0)close(fd);if(lock>=0)close(lock);if(directory>=0)close(directory);}
bool Ready()const{return healthy;}
const std::string& Error()const{return error;}
bool Open(const std::string& path) {
if(fd>=0||lock>=0||directory>=0)return Fail("gold outbox already opened");
const auto slash=path.rfind('/');const std::string dir=slash==std::string::npos?".":slash==0?"/":path.substr(0,slash);
const std::string name=slash==std::string::npos?path:path.substr(slash+1);
if(name.empty()||name=="."||name=="..")return Fail("invalid gold outbox path");
if(mkdir(dir.c_str(),0700)!=0&&errno!=EEXIST)return Fail("cannot create gold outbox directory");
directory=open(dir.c_str(),O_RDONLY|O_DIRECTORY|O_NOFOLLOW);
if(directory<0)return Fail("cannot open gold outbox directory");
lock=openat(directory,(name+".lock").c_str(),O_RDWR|O_CREAT|O_NOFOLLOW,0600);
if(lock<0||!PrivateFile(lock)||flock(lock,LOCK_EX|LOCK_NB)!=0)return Fail("gold outbox already owned/unsafe lock");
fd=openat(directory,name.c_str(),O_RDWR|O_CREAT|O_APPEND|O_NOFOLLOW,0600);
if(fd<0||!PrivateFile(fd)||flock(fd,LOCK_EX|LOCK_NB)!=0)return Fail("unsafe/owned gold outbox file");
struct stat info={};if(fstat(fd,&info)!=0||info.st_size<0||uint64_t(info.st_size)>MaxBytes)return Fail("gold outbox size invalid");
bytes=size_t(info.st_size);
if(fsync(fd)!=0||fsync(lock)!=0||fsync(directory)!=0)return Fail("cannot persist gold outbox directory entries");
if(bytes%FrameBytes)return Fail("torn gold outbox; retain bytes for repair");
for(size_t at=0;at<bytes;at+=FrameBytes) {
std::string frame(FrameBytes,'\0');size_t got=0;
while(got<frame.size()){const auto n=pread(fd,&frame[got],frame.size()-got,off_t(at+got));if(n<0&&errno==EINTR)continue;if(n<=0)return Fail("cannot read gold outbox");got+=size_t(n);}
Reader checksum(frame);checksum.at=FrameBytes-4;
if(frame.substr(0,4)!="CGO1"||checksum.n(4)!=Hash(frame.substr(0,FrameBytes-4)))return Fail("corrupt gold outbox; retain bytes for repair");
const unsigned op=uint8_t(frame[4]);const auto body=frame.substr(5,GoldDeliveryBytes);
if(op==3||op==4) {
Closing c;GoldSourceSeal seal;
if(!DecodeClosing(body,c)||!SourceImage(c.binding,op==4,seal)||seal.events.size()!=c.count)return Fail("corrupt source close proof");
auto it=sources.find(c.binding.request);
if(op==3) {
if(it!=sources.end()||sources.size()>=MaxRecords)return Fail("duplicate/overfull source close");
sources.emplace(c.binding.request,c);
} else {
if(it==sources.end()||it->second.acknowledged||ClosingBody(it->second)!=body)return Fail("unknown/conflicting source close ACK");
it->second.acknowledged=true;
}
continue;
}
GoldDelivery d;if(!DecodeGoldDelivery(body,d))return Fail("corrupt gold delivery body");auto it=records.find(d.intent.event);
if(op==1) {
if(it!=records.end()||!Admit(d))return Fail("conflicting/out-of-order gold outbox claim");
records.emplace(d.intent.event,Record{d,false});
} else if(op==2) {
if(it==records.end()||it->second.acknowledged||EncodeGoldDelivery(it->second.delivery)!=EncodeGoldDelivery(d))return Fail("unknown/conflicting gold outbox ACK");
it->second.acknowledged=true;
} else return Fail("unknown gold outbox operation");
}
healthy=true;return true;
}
unsigned Next(const std::string& request)const {unsigned n=1;for(const auto& r:records)if(r.second.delivery.intent.request==request)++n;return n;}
uint64_t Total(const std::string& request)const {
uint64_t total=0;for(const auto& r:records)if(r.second.delivery.intent.request==request) {
if(total>uint64_t(PortEconomy::GoldLimit)-r.second.delivery.intent.amount)return uint64_t(PortEconomy::GoldLimit);
total+=r.second.delivery.intent.amount;
}return total;
}
const GoldDelivery* Find(const std::string& event)const {auto it=records.find(event);return it==records.end()?nullptr:&it->second.delivery;}
bool Claim(const GoldDelivery& d) {
if(!healthy||EncodeGoldDelivery(d).empty())return false;auto it=records.find(d.intent.event);
if(it!=records.end())return EncodeGoldDelivery(it->second.delivery)==EncodeGoldDelivery(d);
if(!Admit(d)){error="gold outbox capacity/sequence/identity refused before writing";return false;}
if(!Append(1,d))return false;records.emplace(d.intent.event,Record{d,false});return true;
}
bool Acknowledge(const GoldDelivery& d) {
auto it=records.find(d.intent.event);
if(!healthy||it==records.end()||EncodeGoldDelivery(it->second.delivery)!=EncodeGoldDelivery(d))return false;
if(it->second.acknowledged)return true;
if(!Append(2,d))return false;it->second.acknowledged=true;return true;
}
bool IsClosing(const std::string& request)const{return sources.count(request)!=0;}
bool CloseSource(const GoldSourceBinding& binding) {
if(!healthy)return false;GoldSourceSeal seal;if(!SourceImage(binding,false,seal))return false;
auto it=sources.find(binding.request);Closing c{binding,unsigned(seal.events.size()),false};
if(it!=sources.end())return ClosingBody(it->second)==ClosingBody(c);
if(sources.size()>=MaxRecords)return false;
// Stop new claims DURABLY before waiting for existing delivery ACKs.
if(!AppendBody(3,ClosingBody(c)))return false;sources.emplace(binding.request,std::move(c));return true;
}
bool AcknowledgeSource(const GoldSourceSeal& seal) {
if(!healthy)return false;auto it=sources.find(seal.request);GoldSourceSeal expected;
if(it==sources.end()||EncodeGoldSourceBinding(seal)!=EncodeGoldSourceBinding(it->second.binding)||!SourceImage(seal,true,expected)||
seal.events!=expected.events||seal.events.size()!=it->second.count)return false;
if(it->second.acknowledged)return true;
if(!AppendBody(4,ClosingBody(it->second)))return false;it->second.acknowledged=true;return true;
}
bool SourceAcknowledged(const GoldSourceBinding& binding)const {
auto it=sources.find(binding.request);return healthy&&it!=sources.end()&&it->second.acknowledged&&EncodeGoldSourceBinding(binding)==EncodeGoldSourceBinding(it->second.binding);
}
std::vector<GoldSourceSeal> PendingSources()const {
std::vector<GoldSourceSeal> out;if(!healthy)return out;
for(const auto& entry:sources)if(!entry.second.acknowledged) {
GoldSourceSeal seal;if(SourceImage(entry.second.binding,true,seal)&&seal.events.size()==entry.second.count)out.push_back(std::move(seal));
}return out;
}
std::vector<GoldDelivery> Pending()const {
std::vector<GoldDelivery> out;if(!healthy)return out;
for(const auto& r:records)if(!r.second.acknowledged)out.push_back(r.second.delivery);
std::sort(out.begin(),out.end(),[](const auto& a,const auto& b){return std::tie(a.intent.account,a.intent.player,a.intent.request,a.intent.sequence)<std::tie(b.intent.account,b.intent.player,b.intent.request,b.intent.sequence);});return out;
}
};
}
+37
View File
@@ -0,0 +1,37 @@
#pragma once
#include "cube_batch.h"
namespace PortCube {
constexpr unsigned GoldSourceLimit=1024,GoldSourceBindingBytes=96;
struct GoldSourceBinding {
uint32_t account=0,player=0,cookie=0,handle=0;
uint64_t epoch=0,session=0;
std::string owner,request;
};
struct GoldSourceSeal : GoldSourceBinding {std::vector<std::string> events;};
inline std::string EncodeGoldSourceBinding(const GoldSourceBinding& s) {
if(!s.account||!s.player||!s.epoch||!s.session||!s.cookie||!s.handle||!Identity(s.owner)||!Identity(s.request))return {};
Writer w;w.n(s.account,4);w.n(s.player,4);w.n(s.epoch,8);w.data+=s.owner;w.data+=s.request;w.n(s.session,8);w.n(s.cookie,4);w.n(s.handle,4);return w.data;
}
inline bool DecodeGoldSourceBinding(const std::string& body,GoldSourceBinding& s) {
s={};if(body.size()!=GoldSourceBindingBytes)return false;Reader r(body);GoldSourceBinding out;
out.account=uint32_t(r.n(4));out.player=uint32_t(r.n(4));out.epoch=r.n(8);out.owner=body.substr(r.at,32);out.request=body.substr(r.at+32,32);r.at+=64;
out.session=r.n(8);out.cookie=uint32_t(r.n(4));out.handle=uint32_t(r.n(4));
if(!r.ok||r.at!=body.size()||EncodeGoldSourceBinding(out)!=body)return false;s=std::move(out);return true;
}
inline bool Matches(const GoldSourceBinding& s,const Batch& b) {
return s.account==b.account&&s.player==b.player&&s.epoch==b.epoch&&s.owner==b.owner&&s.request==b.token;
}
inline std::string EncodeGoldManifest(const std::vector<std::string>& events) {
if(events.size()>GoldSourceLimit)return {};std::set<std::string> seen;Writer w;w.n(events.size(),4);
for(const auto& e:events){if(!Identity(e)||!seen.insert(e).second)return {};w.data+=e;}return w.data;
}
inline bool DecodeGoldManifest(const std::string& body,std::vector<std::string>& events) {
events.clear();if(body.size()<4||body.size()>4+32*GoldSourceLimit)return false;Reader r(body);const auto count=r.n(4);
if(count>GoldSourceLimit||body.size()!=4+32*count)return false;
std::vector<std::string> out;for(size_t n=0;n<count;++n)out.push_back(body.substr(4+n*32,32));
if(EncodeGoldManifest(out)!=body)return false;events=std::move(out);return true;
}
inline GoldSourceBinding GoldSourceFor(const Batch& b,uint64_t session,uint32_t cookie,uint32_t handle) {
GoldSourceBinding s;s.account=b.account;s.player=b.player;s.epoch=b.epoch;s.owner=b.owner;s.request=b.token;s.session=session;s.cookie=cookie;s.handle=handle;return s;
}
}
+117
View File
@@ -0,0 +1,117 @@
#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 DB> 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<DB> 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<GoldRecord> 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<std::string> 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<GoldRecord> records;if(!GoldRecords(db,b,records))return Blocked;
if(records.size()!=seal.events.size())return Blocked;
for(size_t n=0;n<records.size();++n)if(records[n].intent.event!=seal.events[n])return Refused;
if(!Change("INSERT INTO port_cube_gold_sources(request,account,pid,epoch,owner,session,cookie,handle,manifest) VALUES('"+b.token+"',"+N(b.account)+","+N(b.player)+","+N(b.epoch)+",'"+b.owner+"',"+N(seal.session)+","+N(seal.cookie)+","+N(seal.handle)+",X'"+PortEconomy::Hex(manifest.data(),manifest.size())+"')"))return Retry;
return db.Commit()?Stored:Retry;
}
// Recover accepted intents after process restart without caller-supplied
// amounts or replacing persisted data. Pure read: does not credit anything.
Result Pending(const Batch& b,std::vector<GoldIntent>& 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<GoldRecord> 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<bool(const GoldIntent&)>& 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<GoldRecord> 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;
}
};
}
+162
View File
@@ -0,0 +1,162 @@
#pragma once
#include "cube_batch.h"
#include "cube_mutation.h"
#include "cube_gold_intent.h"
#include "cube_owner_types.h"
#include "cube_image.h"
#include "cube_receipt.h"
namespace PortCube {
// Internal game/DB only. Neither this header nor the catalogue advertises a
// crafting capability. Keep BOTH gates closed until the mutation audit and the
// settlement/resync/thaw path are complete. There is no command to toggle them.
constexpr uint8_t HandshakeHeader=78;
constexpr bool HandshakeEnabled=false,ActorMutationAuditComplete=false;
enum class Message : uint8_t { Arm=1,Submit=2,Poll=3,Cancel=4,Answer=5,Invalidate=6,GoldEnqueue=7,GoldAck=8,GoldClose=9,GoldCloseAck=10,RecoveryClaim=11,RecoveryAnswer=12,RecoveryImageRequest=13,RecoveryImageAnswer=14,Prepare=15,Execute=16,CraftAnswer=17,LiveImageRequest=18,LiveImageAnswer=19,LiveImageAck=20,LiveImageAckAnswer=21,LiveReleaseRequest=22,LiveReleaseAnswer=23,LiveResumeCheckRequest=24,LiveResumeCheckAnswer=25 };
enum class Status : uint8_t { None=0,Denied=1,Armed=2,Draining=3,Frozen=4,Aborted=5,Held=6,Cancelled=7,GoldStored=8,GoldApplied=9,GoldClosed=10,RecoveryGranted=11,RecoveryClear=12,RecoveryImageReady=13,Prepared=14,Complete=15,LiveImageReady=16,LiveImageAcknowledged=17,LiveReleased=18,LiveResumeChecked=19 };
struct Handshake {
Message message=Message::Arm;Status status=Status::None;
uint32_t account=0,player=0,cookie=0;
uint64_t session=0,epoch=0;
std::string owner,token,body;
};
constexpr unsigned HandshakeFixed=102,HandshakeMaximum=HandshakeFixed+40000;
inline bool SameIdentity(const Handshake& a,const Handshake& b) {
return a.account==b.account&&a.player==b.player&&a.session==b.session&&a.epoch==b.epoch&&a.owner==b.owner&&a.token==b.token;
}
inline bool ValidHandshake(const Handshake& f) {
if(f.message==Message::RecoveryImageRequest||f.message==Message::RecoveryImageAnswer) {
OwnerGrant g;std::string image;
if(f.message==Message::RecoveryImageAnswer&&f.status==Status::RecoveryImageReady){if(!DecodeRecoveryImage(f.body,g,image))return false;}
else if(!DecodeOwnerGrant(f.body,g)||!(f.message==Message::RecoveryImageRequest?f.status==Status::None:f.status==Status::Held))return false;
const auto& b=g.binding;return b.account==f.account&&b.player==f.player&&b.session==f.session&&b.cookie==f.cookie&&b.epoch==f.epoch&&b.owner==f.owner&&b.request==f.token;
}
if(f.message==Message::RecoveryClaim||f.message==Message::RecoveryAnswer) {
if(!f.account||!f.player||!f.session)return false;
if(f.message==Message::RecoveryAnswer&&f.status==Status::RecoveryGranted) {
OwnerGrant g;return DecodeOwnerGrant(f.body,g)&&g.binding.account==f.account&&g.binding.player==f.player&&g.binding.session==f.session&&g.binding.epoch==f.epoch&&g.binding.owner==f.owner&&g.binding.request==f.token&&g.binding.cookie==f.cookie;
}
return !f.epoch&&!f.cookie&&f.owner==std::string(32,'0')&&f.token==std::string(32,'0')&&f.body.empty()&&
(f.message==Message::RecoveryClaim?f.status==Status::None:(f.status==Status::Held||f.status==Status::RecoveryClear));
}
if(!f.account||!f.player||!f.session||!f.epoch||!Identity(f.owner)||!Identity(f.token)||f.body.size()>40000)return false;
if(f.message==Message::LiveResumeCheckRequest||f.message==Message::LiveResumeCheckAnswer) {
InventoryImage image;if(!f.cookie)return false;
if(f.message==Message::LiveResumeCheckAnswer&&f.status==Status::Held)return f.body.empty();
return f.status==(f.message==Message::LiveResumeCheckRequest?Status::None:Status::LiveResumeChecked)&&DecodeInventoryImage(f.body,image);
}
if(f.message==Message::LiveReleaseRequest||f.message==Message::LiveReleaseAnswer) {
InventoryImage image;if(!f.cookie)return false;
if(f.message==Message::LiveReleaseAnswer&&f.status==Status::Held)return f.body.empty();
return f.status==(f.message==Message::LiveReleaseRequest?Status::None:Status::LiveReleased)&&DecodeInventoryImage(f.body,image);
}
if(f.message==Message::LiveImageAck||f.message==Message::LiveImageAckAnswer) {
InventoryImage image;if(!f.cookie)return false;
if(f.message==Message::LiveImageAckAnswer&&f.status==Status::Held)return f.body.empty();
return f.status==(f.message==Message::LiveImageAck?Status::None:Status::LiveImageAcknowledged)&&DecodeInventoryImage(f.body,image);
}
if(f.message==Message::LiveImageRequest)return f.status==Status::None&&f.cookie&&f.body.empty();
if(f.message==Message::LiveImageAnswer){InventoryImage image;return f.cookie&&(f.status==Status::Held?f.body.empty():f.status==Status::LiveImageReady&&DecodeInventoryImage(f.body,image));}
if(f.message==Message::Prepare||f.message==Message::Execute)return f.status==Status::None&&f.cookie&&f.body.empty();
if(f.message==Message::CraftAnswer) {
if(!f.cookie)return false;if(f.status==Status::Held||f.status==Status::Prepared)return f.body.empty();
CraftReceipt receipt;return f.status==Status::Complete&&DecodeCraftReceipt(f.body,receipt);
}
if(f.message==Message::GoldClose||f.message==Message::GoldCloseAck) {
std::vector<std::string> events;if(!f.cookie||!DecodeGoldManifest(f.body,events))return false;
return f.message==Message::GoldClose?f.status==Status::None:f.status==Status::GoldClosed;
}
if(f.message==Message::GoldEnqueue||f.message==Message::GoldAck) {
GoldIntent i;if(!f.cookie||!DecodeGoldIntent(f.body,i)||i.source!=1||i.account!=f.account||i.player!=f.player||i.epoch!=f.epoch||i.owner!=f.owner||i.request!=f.token)return false;
return f.message==Message::GoldEnqueue?f.status==Status::None:(f.status==Status::GoldStored||f.status==Status::GoldApplied);
}
if(f.message==Message::Answer) {
if(!f.body.empty()||f.status<Status::Denied||f.status>Status::Cancelled)return false;
return (f.status!=Status::Armed&&f.status!=Status::Draining&&f.status!=Status::Frozen&&f.status!=Status::Aborted)||f.cookie;
}
if(f.status!=Status::None)return false;
if(f.message==Message::Arm) {
Batch b;if(f.cookie||!Decode(f.body,b))return false;
return b.account==f.account&&b.player==f.player&&b.epoch==f.epoch&&b.owner==f.owner&&b.token==f.token;
}
return (f.message==Message::Submit||f.message==Message::Poll||f.message==Message::Cancel||f.message==Message::Invalidate)&&f.cookie&&f.body.empty();
}
inline bool IsDbHandshakeReply(Message m){return m==Message::Answer||m==Message::GoldAck||m==Message::GoldCloseAck||m==Message::RecoveryAnswer||m==Message::RecoveryImageAnswer||m==Message::CraftAnswer||m==Message::LiveImageAnswer||m==Message::LiveImageAckAnswer||m==Message::LiveReleaseAnswer||m==Message::LiveResumeCheckAnswer;}
inline std::string EncodeHandshake(const Handshake& f) {
if(!ValidHandshake(f))return {};
Writer w;w.n(HandshakeFixed+f.body.size(),4);w.n(1,1);w.n(unsigned(f.message),1);w.n(unsigned(f.status),1);w.n(0,1);
w.n(f.account,4);w.n(f.player,4);w.n(f.cookie,4);w.n(f.session,8);w.n(f.epoch,8);
w.data+=f.owner;w.data+=f.token;w.n(f.body.size(),2);w.data+=f.body;return w.data;
}
// Safe before dereferencing any frame payload, including DB's unaligned 9-byte
// outer packet prefix. No struct cast, native long, padding or host byte order.
inline bool DecodeHandshake(const char* data,size_t length,Handshake& f) {
f={};if(!data||length<HandshakeFixed||length>HandshakeMaximum)return false;
const std::string bytes(data,length);Reader r(bytes);
if(r.n(4)!=length||r.n(1)!=1)return false;
Handshake out;out.message=Message(r.n(1));out.status=Status(r.n(1));if(r.n(1)!=0)return false;
out.account=uint32_t(r.n(4));out.player=uint32_t(r.n(4));out.cookie=uint32_t(r.n(4));out.session=r.n(8);out.epoch=r.n(8);
if(!r.ok||r.at+64>bytes.size())return false;
out.owner=bytes.substr(r.at,32);out.token=bytes.substr(r.at+32,32);r.at+=64;
out.body=r.s(40000);
if(!r.ok||r.at!=bytes.size()||!ValidHandshake(out))return false;f=std::move(out);return true;
}
inline Handshake ArmFrame(const Batch& b,uint64_t session) {
Handshake f;f.account=b.account;f.player=b.player;f.session=session;f.epoch=b.epoch;f.owner=b.owner;f.token=b.token;f.body=Encode(b);return f;
}
// Transport-independent preparation state machine. This does NOT pause events
// or mutate assets. The game adapter must retain a real freeze throughout every
// non-Idle state. No timeout or negative/unknown reply is permission to thaw.
class ActorHandshake {
public:
enum Stage { Idle,WaitArm,WaitDrain,Held,WaitCancel };
private:
Stage stage=Idle;Handshake arm;uint64_t deadline=0;bool submitted=false;uint32_t mutations=0;
public:
Stage State()const{return stage;}
bool BlocksActions()const{return stage!=Idle;}
bool Submitted()const{return submitted;}
uint32_t Invalidated()const{return mutations;}
void Invalidate(uint32_t reason) {
if(stage==Idle||!reason)return;
mutations|=reason;
// Before cookie arrival keep accepting that Arm ACK only to cancel it.
// After Submit, nothing can pretend this was a never-submitted batch.
if(submitted)stage=Held;
}
const Handshake& IdentityFrame()const{return arm;}
bool Start(const Batch& b,uint64_t session,uint64_t now,bool auditedFreeze) {
if(stage!=Idle||!auditedFreeze)return false;
auto f=ArmFrame(b,session);if(!ValidHandshake(f))return false;
arm=std::move(f);stage=WaitArm;deadline=now;submitted=false;mutations=0;return true;
}
Handshake Request(Message message)const {
Handshake f=arm;f.body.clear();f.message=message;f.status=Status::None;return f;
}
bool Armed(const Handshake& answer,uint64_t now) {
if(stage!=WaitArm||!ValidHandshake(answer)||answer.message!=Message::Answer||answer.status!=Status::Armed||!SameIdentity(arm,answer)||(arm.cookie&&arm.cookie!=answer.cookie))return false;
arm.cookie=answer.cookie;deadline=now;return true;
}
bool Submit(bool snapshotUnchanged,uint64_t now) {
if(stage!=WaitArm||!arm.cookie||!snapshotUnchanged||mutations)return false;
// Mark BEFORE enqueue: a lost/disconnected send cannot be cancelled or
// timed out as if the DB could not have seen it.
submitted=true;stage=WaitDrain;deadline=now;return true;
}
bool Cancel() {
if(stage!=WaitArm||!arm.cookie||submitted)return false;stage=WaitCancel;return true;
}
bool Answer(const Handshake& answer) {
if(stage==Idle||!ValidHandshake(answer)||answer.message!=Message::Answer||!SameIdentity(arm,answer)||answer.cookie!=arm.cookie||!arm.cookie)return false;
if(stage==WaitCancel&&answer.status==Status::Cancelled&&!submitted){stage=Idle;arm={};return true;}
if(answer.status==Status::Held||answer.status==Status::Aborted||answer.status==Status::Frozen){stage=Held;return true;}
return false; // Denied/unknown/late Armed never authorize thaw
}
bool TimedOut(uint64_t now,uint64_t interval=10) {
if(stage==Idle||now<deadline||now-deadline<interval)return false;
stage=Held;return true;
}
void LostTransport(){if(stage!=Idle)stage=Held;}
};
}
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include "cube_owner_types.h"
namespace PortCube {
// Existing fence image: gold8 + count2 + at most225*(reward114+cell2+usable1).
constexpr unsigned InventoryImageMaximum=26335,RecoveryImageMaximum=OwnerGrantBytes+2+InventoryImageMaximum;
struct InventoryImage {uint64_t gold=0;std::vector<Item> items;};
inline std::string EncodeInventoryImage(const InventoryImage& i){Writer w;w.n(i.gold,8);w.items(i.items);return w.data;}
inline bool DecodeInventoryImage(const std::string& bytes,InventoryImage& out,const Lookup& lookup={}) {
out={};if(bytes.size()<10||bytes.size()>InventoryImageMaximum)return false;
Reader r(bytes);InventoryImage image;image.gold=r.n(8);image.items=r.items();
if(!r.ok||r.at!=bytes.size()||image.gold>uint64_t(PortEconomy::GoldLimit))return false;
int last=-1;std::set<uint32_t> ids;std::array<bool,225> used={};
for(const auto& item:image.items) {
const auto& v=item.value;
if(!v.id||!v.vnum||!v.count||v.count>2000||!item.usable||item.cell>=225||int(item.cell)<=last||!ids.insert(v.id).second)return false;last=item.cell;
if(lookup) {
const auto p=lookup(v.vnum);
if(p.size<1||p.size>3||(!p.stackable&&v.count!=1)||(item.cell%45)/5+p.size>9)return false;
for(unsigned n=0;n<p.size;++n){const auto at=item.cell+5*n;if(at>=225||used[at])return false;used[at]=true;}
}
}
if(EncodeInventoryImage(image)!=bytes)return false;out=std::move(image);return true;
}
inline std::string EncodeRecoveryImage(const OwnerGrant& grant,const std::string& image) {
InventoryImage decoded;const auto body=EncodeOwnerGrant(grant);
if(body.empty()||!DecodeInventoryImage(image,decoded))return {};Writer w;w.data=body;w.s(image);return w.data;
}
inline bool DecodeRecoveryImage(const std::string& bytes,OwnerGrant& grant,std::string& image) {
grant={};image.clear();if(bytes.size()<OwnerGrantBytes+12||bytes.size()>RecoveryImageMaximum)return false;
OwnerGrant g;if(!DecodeOwnerGrant(bytes.substr(0,OwnerGrantBytes),g))return false;
Reader r(bytes);r.at=OwnerGrantBytes;auto data=r.s(InventoryImageMaximum);InventoryImage decoded;
if(!r.ok||r.at!=bytes.size()||!DecodeInventoryImage(data,decoded))return false;
grant=std::move(g);image=std::move(data);return true;
}
}
+44
View File
@@ -0,0 +1,44 @@
#pragma once
#include "cube_fence.h"
#include "cube_owner.h"
namespace PortCube {
// Optional additive schema. An ACK records an exact applied image; it does not
// release a lease, an item fence, or an actor. Never install tables at startup.
template<class DB> bool ImageAckSchema(DB& db) {
PortEconomy::Rows rows;
const std::string names="('port_cube_image_ack_version','port_cube_image_acks')";
auto q=[&](const std::string& sql){return db.Query(sql,rows)&&!db.warnings&&rows.size()==1&&rows[0].size()==1;};
return q("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME IN "+names)&&rows[0][0]=="2"&&
q("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN "+names)&&rows[0][0]=="2"&&
q("SELECT version FROM port_cube_image_ack_version WHERE id=1")&&rows[0][0]=="1";
}
template<class DB> class ImageAckStore {
DB& db;Lookup lookup;
static std::string X(const std::string& s){return "X'"+PortEconomy::Hex(s.data(),s.size())+"'";}
public:
enum Result {Retry,Refused,Stored};
ImageAckStore(DB& d,Lookup p):db(d),lookup(std::move(p)){}
Result AcknowledgeLive(const Batch& b,const OwnerGrant& grant,const std::string& image) {
InventoryImage decoded;
if(!Validate(b)||!Valid(grant)||!Matches(grant.binding,b)||!DecodeInventoryImage(image,decoded,lookup))return Refused;
if(!ImageAckSchema(db))return Retry;
OwnerStore<DB> owner(db,lookup);FenceStore<DB> fence(db,lookup);std::string current;
// Resync holds the account, fence and current SQL inventory on the same
// pinned transaction. Callback writes roll back with its COMMIT failure.
const auto result=fence.Resync(b,current,[&](const std::string& actual)->bool {
if(actual!=image||!owner.LiveImageWithin(b,grant,image))return false;
PortEconomy::Rows rows;
auto q=[&](const std::string& sql){return db.Query(sql,rows)&&!db.warnings;};
// ACK cannot create the initial issued image or acknowledge a
// changed saved image, even when the current SQL happens to match.
if(!q("SELECT phase,image FROM port_cube_fences WHERE pid="+std::to_string(b.player)+" FOR UPDATE")||
rows.size()!=1||rows[0]!=std::vector<std::string>{"RESYNC",image})return false;
const auto body=Encode(b),binding=EncodeOwnerGrant(grant);
if(!q("SELECT body,owner_grant,image FROM port_cube_image_acks WHERE request='"+b.token+"' FOR UPDATE"))return false;
if(!rows.empty())return rows.size()==1&&rows[0]==std::vector<std::string>{body,binding,image};
return q("INSERT INTO port_cube_image_acks(request,body,owner_grant,image) VALUES('"+b.token+"',"+X(body)+","+X(binding)+","+X(image)+")")&&db.affected==1;
});
return result==FenceStore<DB>::Done?Stored:result==FenceStore<DB>::Retry?Retry:Refused;
}
};
}
+37
View File
@@ -0,0 +1,37 @@
#pragma once
#include <cstdint>
#include <vector>
#include <utility>
namespace PortCube {
// Legacy game allocation uses an exclusive upper bound. DB range collision
// checks are inclusive, so even touching ranges are rejected for handoff.
struct ItemIDRange { uint32_t minimum=0, maximum=0, usable=0; };
struct ItemIDPlan {
std::vector<uint32_t> ids;
uint32_t next=0;
bool spare=false;
};
inline bool ValidItemIDRange(const ItemIDRange& r) {
return r.minimum && r.minimum<=r.usable && r.usable<r.maximum;
}
inline bool PlanItemIDs(const ItemIDRange& active,uint32_t next,
const ItemIDRange& spare,unsigned count,ItemIDPlan& out) {
// No partial output, wraparound, allocation of the sentinel maximum, or
// speculative switch when all IDs already fit in the active range.
if(!count||count>100||!ValidItemIDRange(active)||
next<active.usable||next>active.maximum)return false;
const uint64_t available=uint64_t(active.maximum)-next;
const bool switchRange=count>available;
if(switchRange && (!ValidItemIDRange(spare)||
!(active.maximum<spare.minimum||spare.maximum<active.minimum)||
uint64_t(count)-available>uint64_t(spare.maximum)-spare.usable))return false;
ItemIDPlan plan;plan.ids.reserve(count);
uint32_t cursor=next;
for(unsigned i=0;i<count;++i) {
if(!plan.spare&&cursor==active.maximum){plan.spare=true;cursor=spare.usable;}
plan.ids.push_back(cursor++);
}
plan.next=cursor;out=std::move(plan);return true;
}
}
+79
View File
@@ -0,0 +1,79 @@
#pragma once
#include "cube_craft.h"
namespace PortCube {
inline bool CraftImage(const Batch& b,const CraftReceipt& receipt,uint64_t credits,const Lookup& lookup,std::string& out) {
if(receipt.result!="ok"||!ValidateCraftReceipt(b,receipt,lookup)||receipt.fee>b.gold||
credits>uint64_t(PortEconomy::GoldLimit)-(b.gold-receipt.fee))return false;
std::string rolls(b.attempts,char(100));for(unsigned i=0;i<receipt.successes;++i)rolls[i]=1;
const auto plan=SettlePlan(b,rolls,lookup);if(plan.result!="ok")return false;
InventoryImage image;image.gold=b.gold-receipt.fee+credits;image.items=b.inventory;
for(auto& item:image.items){item.usable=true;for(const auto& take:plan.takes)if(take.id==item.value.id){if(take.count>item.value.count)return false;item.value.count-=take.count;}}
image.items.erase(std::remove_if(image.items.begin(),image.items.end(),[](const Item& i){return !i.value.count;}),image.items.end());
image.items.insert(image.items.end(),receipt.awards.begin(),receipt.awards.end());
std::sort(image.items.begin(),image.items.end(),[](const Item& a,const Item& c){return a.cell<c.cell;});
const auto bytes=EncodeInventoryImage(image);InventoryImage decoded;if(!DecodeInventoryImage(bytes,decoded,lookup))return false;out=bytes;return true;
}
// Transport state only: adapter must apply/read back and remain held throughout.
class LiveImageFlow {
public: enum Stage {Idle,Waiting,Ready,Held,Applied,AckWaiting,Acknowledged};
private: Stage stage=Idle;Handshake identity;std::string expected;
public:
Stage State()const{return stage;}bool MayRetry()const{return stage==Waiting;}
const std::string& Image()const{return expected;}
void Invalidate(){stage=Held;}
bool Start(const Handshake& bound,const Batch& b,const CraftReceipt& receipt,uint64_t credits,const Lookup& lookup,bool sealed) {
auto f=bound;f.message=Message::LiveImageRequest;f.status=Status::None;f.body.clear();
if(stage!=Idle||!sealed||!ValidHandshake(f)||f.account!=b.account||f.player!=b.player||f.epoch!=b.epoch||f.owner!=b.owner||f.token!=b.token||!CraftImage(b,receipt,credits,lookup,expected))return false;
identity=std::move(f);stage=Waiting;return true;
}
Handshake Request()const{return identity;}
bool MarkApplied(const std::string& readback) {
if(stage!=Ready||readback!=expected){stage=Held;return false;}stage=Applied;return true;
}
bool BeginAcknowledge(const std::string& readback) {
if(stage!=Applied||readback!=expected){stage=Held;return false;}stage=AckWaiting;return true;
}
bool MayAcknowledge()const{return stage==AckWaiting;}
Handshake Acknowledgement()const {
auto f=identity;f.message=Message::LiveImageAck;f.body=expected;return f;
}
bool Answer(const Handshake& f) {
if(!ValidHandshake(f)||!SameIdentity(f,identity)||f.cookie!=identity.cookie)return false;
if(f.message==Message::LiveImageAckAnswer) {
if(stage!=AckWaiting&&stage!=Acknowledged)return false;
if(f.status==Status::Held)return stage==AckWaiting;
if(f.status!=Status::LiveImageAcknowledged)return false;
if(f.body!=expected){stage=Held;return false;}stage=Acknowledged;return true;
}
if((stage!=Waiting&&stage!=Ready&&stage!=Applied&&stage!=AckWaiting&&stage!=Acknowledged)||f.message!=Message::LiveImageAnswer)return false;
if(f.status==Status::Held)return stage==Waiting;
if(f.status!=Status::LiveImageReady)return false;
if(f.body!=expected){stage=Held;return false;}if(stage==Waiting)stage=Ready;return true;
}
};
// Terminal SQL transport only. A Released result retains both actor and DB
// memory holds; it is NOT a resume grant or permission to enable item saves.
class LiveReleaseFlow {
public: enum Stage {Idle,Waiting,Released,Held};
private: Stage stage=Idle;Handshake request;
public:
Stage State()const{return stage;}
bool MayRetry()const{return stage==Waiting;}
void Invalidate(){stage=Held;}
bool Start(const LiveImageFlow& image,bool locallyReady) {
if(stage!=Idle||!locallyReady||image.State()!=LiveImageFlow::Acknowledged)return false;
auto f=image.Acknowledgement();f.message=Message::LiveReleaseRequest;
if(!ValidHandshake(f))return false;
request=std::move(f);stage=Waiting;return true;
}
Handshake Request()const{return request;}
bool Answer(const Handshake& f) {
if((stage!=Waiting&&stage!=Released)||!ValidHandshake(f)||f.message!=Message::LiveReleaseAnswer||
!SameIdentity(f,request)||f.cookie!=request.cookie)return false;
if(f.status==Status::Held)return stage==Waiting;
if(f.status!=Status::LiveReleased)return false;
if(f.body!=request.body){stage=Held;return false;}
stage=Released;return true;
}
};
}
+9
View File
@@ -0,0 +1,9 @@
#pragma once
#include <cstdint>
namespace PortCube {
// Preparation admission is conservative, not a change to expiry/reward rules.
// No bit grants permission to pause arbitrary timers or drop a mutation.
enum Hazard : uint32_t { ItemClock=1,ItemBusy=2,QuestTimer=4,QuestRunning=8,
Switcher=16,Party=32,Combat=64,LifeCycle=128,MissingState=256 };
enum Mutation : uint32_t { ItemWrite=1,GoldWrite=2,QuestWrite=4,ContextChanged=8,LifecycleWrite=16 };
}
+203
View File
@@ -0,0 +1,203 @@
#pragma once
#include "cube_owner_types.h"
#include "cube_gold_store.h"
#include "cube_image.h"
#include <cerrno>
#include <fcntl.h>
#include <unistd.h>
namespace PortCube {
inline std::string OwnerBootNonce() {
unsigned char bytes[16];const int fd=open("/dev/urandom",O_RDONLY);if(fd<0)return {};size_t at=0;
while(at<sizeof(bytes)){auto n=read(fd,bytes+at,sizeof(bytes)-at);if(n<0&&errno==EINTR)continue;if(n<=0){close(fd);return {};}at+=size_t(n);}close(fd);
const auto s=PortEconomy::Hex(bytes,sizeof(bytes));return Identity(s)?s:std::string{};
}
// DB-main/direct-session authority. A connection-scoped MySQL advisory lock
// fences competing brokers; each new boot OR SQL connection advances generation.
// There is no wall-clock expiry, auto-adoption, currency write or thaw here.
template<class DB> class OwnerStore {
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& s,Rows& r){return db.Query(s,r)&&!db.warnings;}
bool Run(const std::string& s){Rows r;return Q(s,r);}
bool Change(const std::string& s){return Run(s)&&db.affected==1;}
struct Guard {DB& db;~Guard(){db.Rollback();}};
bool Account(uint32_t id){Rows r;return Run("INSERT INTO port_economy_account_lock(account) VALUES("+N(id)+") ON DUPLICATE KEY UPDATE account=VALUES(account)")&&Q("SELECT account FROM port_economy_account_lock WHERE account="+N(id)+" FOR UPDATE",r)&&r.size()==1;}
bool Session(uint64_t& connection,uint64_t& holder) {
Rows r;holder=0;
if(!Q("SELECT CONNECTION_ID(),IS_USED_LOCK(CONCAT('m2_cube:',DATABASE()))",r)||r.size()!=1||r[0].size()!=2||!PortEconomy::Number(r[0][0],connection)||!connection)return false;
return r[0][1].empty()||PortEconomy::Number(r[0][1],holder);
}
bool LeaderRow(const OwnerLeader& l) {
uint64_t connection=0,holder=0;Rows r;
return Valid(l)&&Session(connection,holder)&&connection==l.connection&&holder==connection&&
Q("SELECT generation,boot,connection_id FROM port_cube_owner_broker WHERE id=1 FOR UPDATE",r)&&r.size()==1&&r[0]==std::vector<std::string>{N(l.generation),l.boot,N(l.connection)};
}
bool LeaseRows(const Batch& b,Rows& r){return Q("SELECT account,pid,body,revision,generation,boot,connection_id,peer,binding,original_peer,original_binding,phase,revoked_generation,reason FROM port_cube_owner_leases WHERE request='"+b.token+"' FOR UPDATE",r);}
static bool DecodeLease(const Batch& b,const Rows& rows,OwnerGrant& active,GoldSourceBinding& original,uint32_t& originalPeer,std::string& phase,uint64_t& revoked) {
active={};original={};originalPeer=0;revoked=0;
if(rows.size()!=1||rows[0].size()!=14)return false;const auto& r=rows[0];uint64_t peer=0,oldPeer=0,reason=0;
if(r[0]!=N(b.account)||r[1]!=N(b.player)||r[2]!=Encode(b)||!PortEconomy::Number(r[3],active.revision)||!PortEconomy::Number(r[4],active.leader.generation)||
!PortEconomy::Number(r[6],active.leader.connection)||!PortEconomy::Number(r[7],peer,UINT32_MAX)||!PortEconomy::Number(r[9],oldPeer,UINT32_MAX)||
!DecodeGoldSourceBinding(r[8],active.binding)||!DecodeGoldSourceBinding(r[10],original)||!Matches(active.binding,b)||!Matches(original,b)||
!PortEconomy::Number(r[12],revoked)||!PortEconomy::Number(r[13],reason,3))return false;
active.peer=uint32_t(peer);active.leader.boot=r[5];originalPeer=uint32_t(oldPeer);phase=r[11];
return Valid(active)&&originalPeer&&(phase=="LIVE"||phase=="REVOKED"||phase=="ADOPTED")&&((phase=="REVOKED")==bool(revoked))&&((phase=="REVOKED")==bool(reason));
}
static bool Same(const OwnerGrant& a,const OwnerGrant& b){return SameOwnerGrant(a,b);}
public:
enum Result {Retry,Refused,Busy,Acquired,Revoked,Adopted};
OwnerStore(DB& d,Lookup p):db(d),lookup(std::move(p)){}
bool Ready(){GoldIntentStore<DB> gold(db,lookup);return gold.Ready()&&OwnerSchema(db)==1;}
Result Acquire(std::string boot,OwnerLeader& leader) {
leader={};if(!Identity(boot))return Refused;if(!Ready())return Retry;
uint64_t connection=0,holder=0;if(!Session(connection,holder))return Retry;
Rows rows;
if(holder!=connection) {
if(!Q("SELECT GET_LOCK(CONCAT('m2_cube:',DATABASE()),0)",rows)||rows.size()!=1||rows[0].size()!=1)return Retry;
if(rows[0][0]!="1")return Busy;
}
if(!db.Begin())return Retry;Guard guard{db};
if(!Q("SELECT generation,boot,connection_id FROM port_cube_owner_broker WHERE id=1 FOR UPDATE",rows)||rows.size()!=1||rows[0].size()!=3)return Retry;
uint64_t generation=0,oldConnection=0;
if(!PortEconomy::Number(rows[0][0],generation)||!PortEconomy::Number(rows[0][2],oldConnection))return Refused;
if(generation&&(!Identity(rows[0][1])||!oldConnection))return Refused;
if(!generation&&(rows[0][1]!=std::string(32,'0')||oldConnection))return Refused;
if(generation&&rows[0][1]==boot&&oldConnection==connection){leader={boot,generation,connection};return Acquired;}
if(generation==UINT64_MAX)return Refused;
if(!Change("UPDATE port_cube_owner_broker SET generation="+N(generation+1)+",boot='"+boot+"',connection_id="+N(connection)+" WHERE id=1 AND generation="+N(generation))||!db.Commit())return Retry;
leader={boot,generation+1,connection};return Acquired;
}
bool Current(const OwnerLeader& l){if(!Ready()||!db.Begin())return false;Guard g{db};return LeaderRow(l);}
// Called INSIDE FenceStore::Begin's account transaction, after item locks.
// Replay can only validate an existing identical row, never invent one.
bool BindWithin(const Batch& b,const OwnerGrant& grant,bool replay) {
if(!Validate(b)||!Valid(grant)||grant.revision!=1||!Matches(grant.binding,b)||!LeaderRow(grant.leader))return false;
Rows rows;if(!LeaseRows(b,rows))return false;
if(!rows.empty()) {
OwnerGrant existing;GoldSourceBinding original;uint32_t peer=0;std::string phase;uint64_t revoked=0;
return DecodeLease(b,rows,existing,original,peer,phase,revoked)&&phase=="LIVE"&&Same(existing,grant)&&peer==grant.peer&&EncodeGoldSourceBinding(original)==EncodeGoldSourceBinding(grant.binding);
}
if(replay)return false;
if(!Q("SELECT request FROM port_cube_owner_leases WHERE account="+N(b.account)+" OR pid="+N(b.player)+" FOR UPDATE",rows)||!rows.empty())return false;
const auto body=Encode(b),binding=EncodeGoldSourceBinding(grant.binding);
return Change("INSERT INTO port_cube_owner_leases(request,account,pid,body,revision,generation,boot,connection_id,peer,binding,original_peer,original_binding,phase,revoked_generation,reason) VALUES('"+b.token+"',"+N(b.account)+","+N(b.player)+",X'"+PortEconomy::Hex(body.data(),body.size())+"',1,"+N(grant.leader.generation)+",'"+grant.leader.boot+"',"+N(grant.leader.connection)+","+N(grant.peer)+",X'"+PortEconomy::Hex(binding.data(),binding.size())+"',"+N(grant.peer)+",X'"+PortEconomy::Hex(binding.data(),binding.size())+"','LIVE',0,0)");
}
bool Check(const Batch& b,const OwnerGrant& grant) {
if(!Ready()||!db.Begin())return false;Guard guard{db};if(!Account(b.account)||!LeaderRow(grant.leader))return false;
Rows rows;OwnerGrant active;GoldSourceBinding original;uint32_t peer=0;std::string phase;uint64_t revoked=0;
return LeaseRows(b,rows)&&DecodeLease(b,rows,active,original,peer,phase,revoked)&&phase!="REVOKED"&&Same(active,grant);
}
// Called inside Prepare/Execute after the account lock, never via a separate
// reconnectable preflight. The original live source must be sealed first.
bool CraftWithin(const Batch& b,const OwnerGrant& grant) {
if(!Validate(b)||!Valid(grant)||!Matches(grant.binding,b)||!Ready()||!LeaderRow(grant.leader))return false;
Rows rows;OwnerGrant active;GoldSourceBinding original;uint32_t peer=0;std::string phase;uint64_t revoked=0;
if(!LeaseRows(b,rows)||!DecodeLease(b,rows,active,original,peer,phase,revoked)||phase!="LIVE"||!Same(active,grant)||peer!=grant.peer||EncodeGoldSourceBinding(original)!=EncodeGoldSourceBinding(grant.binding))return false;
if(!Q("SELECT account,epoch,owner,request,phase,body,drain_state FROM port_cube_fences WHERE pid="+N(b.player)+" FOR UPDATE",rows)||rows.size()!=1||rows[0]!=std::vector<std::string>{N(b.account),N(b.epoch),b.owner,b.token,"FROZEN",Encode(b),"1"})return false;
std::vector<GoldRecord> records;if(!GoldRecords(db,b,records))return false;
std::vector<std::string> events;for(const auto& record:records)events.push_back(record.intent.event);
const std::vector<std::string> proof={N(b.account),N(b.player),N(b.epoch),b.owner,N(original.session),N(original.cookie),N(original.handle),EncodeGoldManifest(events)};
return Q("SELECT account,pid,epoch,owner,session,cookie,handle,manifest FROM port_cube_gold_sources WHERE request='"+b.token+"' FOR UPDATE",rows)&&rows.size()==1&&rows[0]==proof;
}
// Inside Fence.Resync's account transaction on the SAME pinned connection.
// A grant alone is insufficient: recheck original source, verified receipt,
// current wallet (including zero-credit batches), and all surviving ID locks.
private:
bool OwnedImageWithin(const Batch& b,const OwnerGrant& grant,const std::string& image,bool live,bool released=false) {
if(!Validate(b)||!Valid(grant)||!Matches(grant.binding,b)||!Ready()||!LeaderRow(grant.leader))return false;
Rows rows;OwnerGrant active;GoldSourceBinding original;uint32_t peer=0;std::string phase;uint64_t revoked=0;
if(released) {
if(!ReleasedWithin(b,grant))return false;
original=grant.binding;peer=grant.peer;
} else {
if(!LeaseRows(b,rows)||!DecodeLease(b,rows,active,original,peer,phase,revoked)||phase!=(live?"LIVE":"ADOPTED")||!Same(active,grant))return false;
if(live&&(peer!=grant.peer||EncodeGoldSourceBinding(original)!=EncodeGoldSourceBinding(grant.binding)))return false;
}
std::vector<GoldRecord> records;if(!GoldRecords(db,b,records))return false;
std::vector<std::string> events;for(const auto& record:records){if(!record.applied)return false;events.push_back(record.intent.event);}
const std::vector<std::string> proof={N(b.account),N(b.player),N(b.epoch),b.owner,N(original.session),N(original.cookie),N(original.handle),EncodeGoldManifest(events)};
if(!Q("SELECT account,pid,epoch,owner,session,cookie,handle,manifest FROM port_cube_gold_sources WHERE request='"+b.token+"' FOR UPDATE",rows)||rows.size()!=1||rows[0]!=proof)return false;
typename BatchStore<DB>::Receipt receipt;
if(!Q("SELECT body,rolls,state,result,successes,fee,awards FROM port_cube_requests WHERE token='"+b.token+"' AND account="+N(b.account)+" AND pid="+N(b.player)+" FOR UPDATE",rows)||rows.size()!=1||!BatchStore<DB>::DoneReceipt(b,rows[0],receipt)||receipt.result!="ok")return false;
const auto plan=SettlePlan(b,rows[0][1],lookup);Writer planned,awarded;planned.items(plan.awards);awarded.items(receipt.awards);
if(plan.result!="ok"||plan.fee!=receipt.fee||plan.successes!=receipt.successes||planned.data!=awarded.data)return false;
uint64_t gold=b.gold-receipt.fee;
for(const auto& record:records){if(record.before!=gold)return false;gold=record.after;}
if(!Q("SELECT gold FROM player WHERE id="+N(b.player)+" AND account_id="+N(b.account)+" FOR UPDATE",rows)||rows.size()!=1||rows[0]!=std::vector<std::string>{N(gold)})return false;
if(!Q("SELECT id,pid,epoch,request FROM port_cube_item_fences WHERE pid="+N(b.player)+" FOR UPDATE",rows)||rows.size()>8517)return false;
if(released&&!rows.empty())return false;
std::set<uint32_t> locks;
for(const auto& row:rows){uint64_t id=0;if(row.size()!=4||!PortEconomy::Number(row[0],id,UINT32_MAX)||!id||row[1]!=N(b.player)||row[2]!=N(b.epoch)||row[3]!=b.token||!locks.insert(uint32_t(id)).second)return false;}
for(const auto& item:b.inventory)if(!released&&!locks.count(item.value.id))return false;
std::set<uint32_t> reserved;for(const auto& reward:b.rewards){if(!released&&!locks.count(reward.id))return false;reserved.insert(reward.id);}
if(!Q("SELECT id,request FROM port_economy_item_reservations WHERE request='"+b.token+"' FOR UPDATE",rows)||rows.size()!=reserved.size())return false;
for(const auto& row:rows){uint64_t id=0;if(row.size()!=2||!PortEconomy::Number(row[0],id,UINT32_MAX)||row[1]!=b.token||!reserved.erase(uint32_t(id)))return false;}
if(!reserved.empty()||!Q("SELECT id FROM item WHERE owner_id="+N(b.player)+" AND window NOT IN ('MALL','SAFEBOX') FOR UPDATE",rows)||rows.size()>4096)return false;
for(const auto& row:rows){uint64_t id=0;if(row.size()!=1||!PortEconomy::Number(row[0],id,UINT32_MAX)||!id||(!released&&!locks.count(uint32_t(id))))return false;}
InventoryImage expected;expected.gold=gold;expected.items=b.inventory;
for(auto& item:expected.items){item.usable=true;for(const auto& take:plan.takes)if(take.id==item.value.id){if(take.count>item.value.count)return false;item.value.count-=take.count;}}
expected.items.erase(std::remove_if(expected.items.begin(),expected.items.end(),[](const Item& item){return !item.value.count;}),expected.items.end());
expected.items.insert(expected.items.end(),receipt.awards.begin(),receipt.awards.end());std::sort(expected.items.begin(),expected.items.end(),[](const Item& a,const Item& c){return a.cell<c.cell;});
InventoryImage decoded;return DecodeInventoryImage(image,decoded,lookup)&&EncodeInventoryImage(expected)==image;
}
public:
bool ImageWithin(const Batch& b,const OwnerGrant& grant,const std::string& image){return OwnedImageWithin(b,grant,image,false);}
bool LiveImageWithin(const Batch& b,const OwnerGrant& grant,const std::string& image){return OwnedImageWithin(b,grant,image,true);}
// Caller holds a released fence/account transaction and checks exact
// terminal history. No lease resurrection, save permission or asset writes.
bool ReleasedImageWithin(const Batch& b,const OwnerGrant& grant,const std::string& image){return OwnedImageWithin(b,grant,image,true,true);}
// Historical terminal reply only, inside the caller's account transaction.
// Exact durable receipt is checked by that caller; never clear a newer hold.
bool ReleasedWithin(const Batch& b,const OwnerGrant& grant) {
if(!Validate(b)||!Valid(grant)||!Matches(grant.binding,b)||!Ready()||!LeaderRow(grant.leader))return false;
Rows rows;return Q("SELECT request FROM port_cube_owner_leases WHERE account="+N(b.account)+" OR pid="+N(b.player)+" OR request='"+b.token+"' FOR UPDATE",rows)&&rows.empty();
}
bool Inspect(const Batch& b,const OwnerLeader& l,OwnerGrant& active,std::string& phase,uint64_t& revoked) {
active={};phase.clear();revoked=0;
if(!Validate(b)||!Ready()||!db.Begin())return false;Guard guard{db};
if(!Account(b.account)||!LeaderRow(l))return false;
Rows rows;GoldSourceBinding original;uint32_t peer=0;
return LeaseRows(b,rows)&&DecodeLease(b,rows,active,original,peer,phase,revoked);
}
// reason 1/2 is a trusted DB peer-gone/account-owner-ended callback, not a
// packet/client boolean. reason 3 requires a strictly newer broker generation.
Result Revoke(const Batch& b,const OwnerLeader& l,unsigned reason,const OwnerGrant* lost,OwnerGrant& revokedGrant) {
revokedGrant={};if(!Validate(b)||!Valid(l)||reason<1||reason>3||(reason!=3&&(!lost||!Valid(*lost))))return Refused;
if(!Ready()||!db.Begin())return Retry;Guard guard{db};if(!Account(b.account)||!LeaderRow(l))return Retry;
Rows rows;OwnerGrant active;GoldSourceBinding original;uint32_t peer=0;std::string phase;uint64_t revoked=0;
if(!LeaseRows(b,rows)||!DecodeLease(b,rows,active,original,peer,phase,revoked))return Refused;
if(reason==3){if(active.leader.generation>=l.generation)return Refused;}
else {auto expected=*lost;if(phase=="REVOKED"&&lost->revision!=UINT64_MAX&&active.revision==lost->revision+1)expected.revision=active.revision;
if(!Same(active,expected)||active.leader.boot!=l.boot||active.leader.generation!=l.generation||active.leader.connection!=l.connection)return Refused;}
if(phase=="REVOKED"&&revoked==l.generation){revokedGrant=active;return Revoked;}
if(active.revision==UINT64_MAX)return Refused;
if(!Change("UPDATE port_cube_owner_leases SET phase='REVOKED',revision="+N(active.revision+1)+",revoked_generation="+N(l.generation)+",reason="+N(reason)+" WHERE request='"+b.token+"' AND revision="+N(active.revision))||!db.Commit())return Retry;
active.revision++;revokedGrant=active;return Revoked;
}
Result Adopt(const Batch& b,const OwnerLeader& l,uint64_t revokedRevision,uint32_t peer,const GoldSourceBinding& target,OwnerGrant& grant) {
grant={};if(!Validate(b)||!Valid(l)||!revokedRevision||revokedRevision==UINT64_MAX||!peer||!Matches(target,b)||EncodeGoldSourceBinding(target).empty())return Refused;
if(!Ready()||!db.Begin())return Retry;Guard guard{db};if(!Account(b.account)||!LeaderRow(l))return Retry;
Rows rows;OwnerGrant active;GoldSourceBinding original;uint32_t originalPeer=0;std::string phase;uint64_t revoked=0;
if(!LeaseRows(b,rows)||!DecodeLease(b,rows,active,original,originalPeer,phase,revoked))return Refused;
OwnerGrant expected{l,target,peer,revokedRevision+1};
if(phase=="ADOPTED") {if(!Same(active,expected))return Refused;grant=active;return Adopted;}
if(phase!="REVOKED"||revoked!=l.generation||active.revision!=revokedRevision)return Refused;
if(target.session==original.session||target.session==active.binding.session)return Refused;
if(!Q("SELECT account,epoch,owner,request,phase,body,drain_state FROM port_cube_fences WHERE pid="+N(b.player)+" FOR UPDATE",rows)||rows.size()!=1||rows[0].size()!=7)return Refused;
const auto fence=rows[0];
if(fence[0]!=N(b.account)||fence[1]!=N(b.epoch)||fence[2]!=b.owner||fence[3]!=b.token||fence[5]!=Encode(b)||fence[6]!="1"||(fence[4]!="FROZEN"&&fence[4]!="RESYNC"))return Refused;
std::vector<GoldRecord> records;if(!GoldRecords(db,b,records))return Refused;
std::vector<std::string> events;for(const auto& r:records)events.push_back(r.intent.event);
const std::vector<std::string> proof={N(b.account),N(b.player),N(b.epoch),b.owner,N(original.session),N(original.cookie),N(original.handle),EncodeGoldManifest(events)};
if(!Q("SELECT account,pid,epoch,owner,session,cookie,handle,manifest FROM port_cube_gold_sources WHERE request='"+b.token+"' FOR UPDATE",rows)||rows.size()!=1||rows[0]!=proof)return Refused;
uint64_t expectedGold=0;if(GoldCreditBase(db,b,expectedGold)!=1)return Refused;
bool pending=false;uint64_t future=expectedGold;
for(const auto& r:records)if(r.applied){if(pending||r.before!=expectedGold)return Refused;expectedGold=future=r.after;}else{pending=true;if(future>uint64_t(PortEconomy::GoldLimit)-r.intent.amount)return Refused;future+=r.intent.amount;}
if(fence[4]=="RESYNC"&&pending)return Refused;
if(!Q("SELECT gold FROM player WHERE id="+N(b.player)+" AND account_id="+N(b.account)+" FOR UPDATE",rows)||rows.size()!=1||rows[0].size()!=1||rows[0][0]!=N(expectedGold))return Refused;
const auto binding=EncodeGoldSourceBinding(target);
if(!Change("UPDATE port_cube_owner_leases SET phase='ADOPTED',revision="+N(expected.revision)+",generation="+N(l.generation)+",boot='"+l.boot+"',connection_id="+N(l.connection)+",peer="+N(peer)+",binding=X'"+PortEconomy::Hex(binding.data(),binding.size())+"',revoked_generation=0,reason=0 WHERE request='"+b.token+"' AND revision="+N(revokedRevision)+" AND phase='REVOKED'")||!db.Commit())return Retry;
grant=std::move(expected);return Adopted; // still held; no image/currency/load/thaw side effect
}
};
}
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include "cube_gold_source.h"
#include "economy_store.h"
namespace PortCube {
struct OwnerLeader {std::string boot;uint64_t generation=0,connection=0;};
inline bool Valid(const OwnerLeader& l){return Identity(l.boot)&&l.generation&&l.connection;}
struct OwnerGrant {OwnerLeader leader;GoldSourceBinding binding;uint32_t peer=0;uint64_t revision=0;};
inline bool Valid(const OwnerGrant& g){return Valid(g.leader)&&g.peer&&g.revision&&!EncodeGoldSourceBinding(g.binding).empty();}
inline bool SameOwnerGrant(const OwnerGrant& a,const OwnerGrant& b){return a.leader.boot==b.leader.boot&&a.leader.generation==b.leader.generation&&a.leader.connection==b.leader.connection&&a.peer==b.peer&&a.revision==b.revision&&EncodeGoldSourceBinding(a.binding)==EncodeGoldSourceBinding(b.binding);}
constexpr unsigned OwnerGrantBytes=160;
inline std::string EncodeOwnerGrant(const OwnerGrant& g) {
if(!Valid(g))return {};Writer w;w.data="CRG1";w.data+=g.leader.boot;w.n(g.leader.generation,8);w.n(g.leader.connection,8);w.n(g.peer,4);w.n(g.revision,8);w.data+=EncodeGoldSourceBinding(g.binding);return w.data;
}
inline bool DecodeOwnerGrant(const std::string& body,OwnerGrant& grant) {
grant={};if(body.size()!=OwnerGrantBytes||body.substr(0,4)!="CRG1")return false;
Reader r(body);OwnerGrant g;r.at=4;g.leader.boot=body.substr(r.at,32);r.at+=32;
g.leader.generation=r.n(8);g.leader.connection=r.n(8);g.peer=uint32_t(r.n(4));g.revision=r.n(8);
if(!r.ok||!DecodeGoldSourceBinding(body.substr(r.at),g.binding)||EncodeOwnerGrant(g)!=body)return false;grant=std::move(g);return true;
}
template<class DB> int OwnerSchema(DB& db) {
PortEconomy::Rows rows;const std::string names="('port_cube_owner_version','port_cube_owner_broker','port_cube_owner_leases')";
auto query=[&](const std::string& s){return db.Query(s,rows)&&!db.warnings&&rows.size()==1&&rows[0].size()==1;};
if(!query("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME IN "+names))return -1;
if(rows[0][0]=="0")return 0;
if(rows[0][0]!="3"||!query("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN "+names)||rows[0][0]!="3")return -1;
if(!query("SELECT version FROM port_cube_owner_version WHERE id=1")||rows[0][0]!="1")return -1;return 1;
}
// No legacy/old-owner image ACK can remove item fences for a registered owner.
// The adopted-owner image/thaw protocol is a separate required implementation.
template<class DB> int OwnerReleaseStatus(DB& db,const Batch& b) {
const int schema=OwnerSchema(db);if(schema<0)return -1;if(!schema)return 1;PortEconomy::Rows rows;
if(!db.Query("SELECT request FROM port_cube_owner_leases WHERE request='"+b.token+"' OR pid="+std::to_string(b.player)+" FOR UPDATE",rows)||db.warnings)return -1;
return rows.empty()?1:0;
}
}
+69
View File
@@ -0,0 +1,69 @@
#pragma once
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstring>
#include <set>
#include <string>
#include <vector>
// PORT: GC93 bounded LE presentation only. Never a craft request or thaw ACK.
namespace PortCubeView {
constexpr unsigned Slots=225,Quickslots=36,Maximum=32768;
constexpr int64_t GoldLimit=2000000000000000LL;
struct Quickslot {uint8_t type=0;uint16_t cell=0;};
inline bool operator==(const Quickslot& a,const Quickslot& b){return a.type==b.type&&a.cell==b.cell;}
struct Item {
uint16_t cell=0,count=0;uint32_t id=0,vnum=0,flags=0,anti=0;
int32_t sockets[3]={};uint8_t types[7]={};int16_t values[7]={};uint8_t extra[69]={};
};
struct Frame {uint64_t epoch=0,gold=0;std::vector<Item> items;std::array<Quickslot,Quickslots> quickslots={};};
inline bool Valid(const Frame& f) {
if(!f.epoch||f.gold>uint64_t(GoldLimit)||f.items.size()>Slots)return false;
int last=-1;std::set<uint32_t> ids;
for(const auto& i:f.items)if(i.cell>=Slots||int(i.cell)<=last||!i.id||!i.vnum||!i.count||i.count>2000||!ids.insert(i.id).second)return false;else last=i.cell;
for(const auto& q:f.quickslots)if(q.type>3||(!q.type&&q.cell))return false;
return true;
}
struct Writer {std::string bytes;void n(uint64_t v,unsigned width){for(unsigned j=0;j<width;++j)bytes+=char(v>>(8*j));}};
struct Reader {const std::string& bytes;size_t at=0;bool ok=true;uint64_t n(unsigned width){if(at+width>bytes.size()){ok=false;return 0;}uint64_t v=0;for(unsigned j=0;j<width;++j)v|=uint64_t(uint8_t(bytes[at++]))<<(8*j);return v;}};
inline std::string Encode(const Frame& f) {
if(!Valid(f))return {};Writer w;w.n(11,1);w.bytes+="CCP1";w.n(f.epoch,8);w.n(f.gold,8);w.n(f.items.size(),2);w.n(Quickslots,1);
for(const auto& q:f.quickslots){w.n(q.type,1);w.n(q.cell,2);}
for(const auto& i:f.items) {
w.n(i.cell,2);w.n(i.count,2);w.n(i.id,4);w.n(i.vnum,4);w.n(i.flags,4);w.n(i.anti,4);
for(auto v:i.sockets)w.n(uint32_t(v),4);
for(unsigned j=0;j<7;++j){w.n(i.types[j],1);w.n(uint16_t(i.values[j]),2);}
w.bytes.append(reinterpret_cast<const char*>(i.extra),69);
}
return w.bytes.size()+5<=Maximum?w.bytes:std::string{};
}
inline bool Decode(const std::string& bytes,Frame& out) {
out={};if(bytes.size()<132||bytes.size()+5>Maximum||uint8_t(bytes[0])!=11||bytes.substr(1,4)!="CCP1")return false;
Reader r{bytes};r.at=5;Frame f;f.epoch=r.n(8);f.gold=r.n(8);const auto count=r.n(2);
if(count>Slots||r.n(1)!=Quickslots||bytes.size()!=132+122*count)return false;
for(auto& q:f.quickslots){q.type=uint8_t(r.n(1));q.cell=uint16_t(r.n(2));}
for(unsigned j=0;j<count;++j) {
Item i;i.cell=uint16_t(r.n(2));i.count=uint16_t(r.n(2));i.id=uint32_t(r.n(4));i.vnum=uint32_t(r.n(4));i.flags=uint32_t(r.n(4));i.anti=uint32_t(r.n(4));
for(auto& v:i.sockets){uint32_t bits=uint32_t(r.n(4));std::memcpy(&v,&bits,4);}
for(unsigned k=0;k<7;++k){i.types[k]=uint8_t(r.n(1));uint16_t bits=uint16_t(r.n(2));std::memcpy(&i.values[k],&bits,2);}
for(auto& v:i.extra)v=uint8_t(r.n(1));f.items.push_back(i);
}
if(!r.ok||r.at!=bytes.size()||!Valid(f)||Encode(f)!=bytes)return false;out=std::move(f);return true;
}
// Snapshot old bindings ONCE before installing any new items. Never bind a
// consumed item's shortcut to a new reward merely reusing the same cell.
inline bool Rebind(const std::vector<Item>& before,const Frame& after,const std::array<Quickslot,Quickslots>& original,std::array<Quickslot,Quickslots>& result) {
if(!Valid(after))return false;std::set<uint16_t> cells;std::set<uint32_t> ids;
for(const auto& i:before)if(i.cell>=Slots||!i.id||!cells.insert(i.cell).second||!ids.insert(i.id).second)return false;
auto plan=original;
for(auto& q:plan) {
if(q.type>3||(!q.type&&q.cell))return false;if(q.type!=1||q.cell>=Slots)continue;
const auto old=std::find_if(before.begin(),before.end(),[&](const Item& i){return i.cell==q.cell;});
const auto next=old==before.end()?after.items.end():std::find_if(after.items.begin(),after.items.end(),[&](const Item& i){return i.id==old->id;});
if(next==after.items.end())q={};else q.cell=next->cell;
}
result=plan;return true;
}
inline std::string Packet(const Frame& f){const auto body=Encode(f);if(body.empty())return {};Writer w;w.n(93,1);w.n(body.size()+5,4);return w.bytes+body;}
}
+21
View File
@@ -0,0 +1,21 @@
#pragma once
#include <cerrno>
#include <fcntl.h>
#include <unistd.h>
namespace PortCube {
class CraftEntropy {
int fd=-1;
public:
CraftEntropy():fd(open("/dev/urandom",O_RDONLY|O_CLOEXEC)){}
CraftEntropy(const CraftEntropy&)=delete;CraftEntropy& operator=(const CraftEntropy&)=delete;
~CraftEntropy(){if(fd>=0)close(fd);}
unsigned Draw() {
if(fd<0)return 0;
for(unsigned attempts=0;attempts<1024;++attempts) {
unsigned char byte=0;ssize_t n;do{n=read(fd,&byte,1);}while(n<0&&errno==EINTR);
if(n!=1)return 0;if(byte<200)return unsigned(byte)%100+1; // unbiased two samples per outcome
}
return 0; // no deterministic fallback or unbounded source failure loop
}
};
}
+30
View File
@@ -0,0 +1,30 @@
#pragma once
#include "cube_batch.h"
namespace PortCube {
struct CraftReceipt {std::string result;unsigned successes=0;uint64_t fee=0;std::vector<Item> awards;};
inline unsigned CraftCode(const std::string& name) {
const std::vector<std::string> names={"ok","gold_changed","inventory_changed","materials_missing","gold_missing","capacity_full","item_proto","inventory_invalid"};
const auto found=std::find(names.begin(),names.end(),name);return found==names.end()?0:unsigned(found-names.begin())+1;
}
inline std::string EncodeCraftReceipt(const CraftReceipt& receipt) {
const auto code=CraftCode(receipt.result);
if(!code||receipt.successes>100||receipt.fee>uint64_t(PortEconomy::GoldLimit)||receipt.awards.size()>100||
(code!=1&&(receipt.successes||receipt.fee||!receipt.awards.empty())))return {};
std::set<uint32_t> ids;std::set<uint16_t> cells;
for(const auto& item:receipt.awards)if(!item.value.id||!item.value.vnum||!item.value.count||item.value.count>2000||!item.usable||item.cell>=225||!ids.insert(item.value.id).second||!cells.insert(item.cell).second)return {};
Writer w;w.data="CCR1";w.n(code,1);w.n(receipt.successes,1);w.n(receipt.fee,8);w.items(receipt.awards);return w.data;
}
inline bool DecodeCraftReceipt(const std::string& bytes,CraftReceipt& out) {
out={};if(bytes.size()<16||bytes.size()>11716||bytes.substr(0,4)!="CCR1")return false;Reader r(bytes);r.at=4;
const auto code=r.n(1);const std::vector<std::string> names={"ok","gold_changed","inventory_changed","materials_missing","gold_missing","capacity_full","item_proto","inventory_invalid"};
if(!code||code>names.size())return false;CraftReceipt receipt;receipt.result=names[size_t(code)-1];receipt.successes=unsigned(r.n(1));receipt.fee=r.n(8);receipt.awards=r.items();
if(!r.ok||r.at!=bytes.size()||EncodeCraftReceipt(receipt)!=bytes)return false;out=std::move(receipt);return true;
}
inline bool ValidateCraftReceipt(const Batch& b,const CraftReceipt& receipt,const Lookup& lookup) {
if(!Validate(b)||EncodeCraftReceipt(receipt).empty())return false;if(receipt.result!="ok")return true;
if(receipt.successes>b.attempts||(!b.recipe.percent&&receipt.successes)||(b.recipe.percent==100&&receipt.successes!=b.attempts))return false;
std::string rolls(b.attempts,char(100));for(unsigned n=0;n<receipt.successes;++n)rolls[n]=char(1);
const auto plan=SettlePlan(b,rolls,lookup);Writer actual,expected;actual.items(receipt.awards);expected.items(plan.awards);
return plan.result=="ok"&&plan.successes==receipt.successes&&plan.fee==receipt.fee&&actual.data==expected.data;
}
}
+75
View File
@@ -0,0 +1,75 @@
#pragma once
#include <algorithm>
#include <cstdint>
#include <iomanip>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <vector>
// PORT: read-only normalization and consumption planning. No inventory mutation,
// RNG, durable receipt, or implicit permission to craft lives in this layer.
namespace PortCube {
constexpr unsigned MaxAttempts=100,MaxRecipes=4096;
struct Material {uint32_t vnum=0,count=0;};
struct Recipe {
uint32_t id=0,reward=0,rewardCount=0,gold=0;
unsigned percent=0;bool stackable=false,copy=false;
std::string category="WORLDARD";
std::vector<uint32_t> npcs;
std::vector<Material> materials;
};
inline bool Normalize(Recipe& r) {
if(!r.id||!r.reward||!r.rewardCount||r.rewardCount>2000||(!r.stackable&&r.rewardCount!=1)||
r.percent>100||r.npcs.empty()||r.npcs.size()>128||r.materials.empty()||r.materials.size()>5||
r.category.empty()||r.category.size()>24)return false;
for(char c:r.category)if(!((c>='a'&&c<='z')||(c>='A'&&c<='Z')||(c>='0'&&c<='9')||c=='_'))return false;
for(auto npc:r.npcs)if(!npc||npc>65535)return false;
std::sort(r.npcs.begin(),r.npcs.end());r.npcs.erase(std::unique(r.npcs.begin(),r.npcs.end()),r.npcs.end());
std::vector<Material> merged;
for(auto m:r.materials) {
if(!m.vnum||!m.count||m.count>2000)return false;
auto it=std::find_if(merged.begin(),merged.end(),[&](const Material& a){return a.vnum==m.vnum;});
if(it==merged.end())merged.push_back(m);
else {if(it->count>2000-m.count)return false;it->count+=m.count;}
}
r.materials=merged;return true;
}
inline std::string Fingerprint(const std::string& text) {
uint64_t hash=14695981039346656037ULL;
for(unsigned char c:text){hash^=c;hash*=1099511628211ULL;}
std::ostringstream s;s<<std::hex<<std::setw(16)<<std::setfill('0')<<hash;return s.str();
}
inline std::string Revision(const Recipe& r) {
std::ostringstream s;s<<r.id<<':'<<r.reward<<':'<<r.rewardCount<<':'<<r.gold<<':'<<r.percent<<':'<<r.stackable<<':'<<r.copy<<':'<<r.category;
for(auto n:r.npcs)s<<":n"<<n;
for(auto m:r.materials)s<<":m"<<m.vnum<<','<<m.count;
return Fingerprint(s.str()); // staleness fingerprint, not a cryptographic authorization token
}
struct Input {uint32_t id=0,vnum=0,count=0;uint16_t cell=0;bool usable=true;};
struct Take {uint32_t id=0,vnum=0,count=0,before=0;uint16_t cell=0;};
struct Plan {
bool valid=false,materialsOK=false,goldOK=false;
uint64_t gold=0,rewardMaximum=0;
std::vector<uint64_t> needed,available;
std::vector<Take> takes;
};
inline Plan Preview(Recipe recipe,unsigned attempts,std::vector<Input> inputs,int64_t gold) {
Plan p;if(!Normalize(recipe)||!attempts||attempts>MaxAttempts||gold<0||inputs.size()>225)return p;
std::set<uint32_t> ids;std::set<uint16_t> cells;
for(auto i:inputs)if(!i.id||!i.vnum||!i.count||i.count>2000||i.cell>=225||!ids.insert(i.id).second||!cells.insert(i.cell).second)return p;
std::sort(inputs.begin(),inputs.end(),[](const Input& a,const Input& b){return a.cell<b.cell;});
p.gold=uint64_t(recipe.gold)*attempts;p.rewardMaximum=uint64_t(recipe.rewardCount)*attempts;
p.goldOK=uint64_t(gold)>=p.gold;p.materialsOK=true;
for(auto m:recipe.materials) {
const uint64_t need=uint64_t(m.count)*attempts;uint64_t available=0,left=need;
for(auto i:inputs)if(i.usable&&i.vnum==m.vnum) {
available+=i.count;const auto count=static_cast<uint32_t>(std::min(left,uint64_t(i.count)));
if(count)p.takes.push_back({i.id,i.vnum,count,i.count,i.cell});left-=count;
}
p.needed.push_back(need);p.available.push_back(available);p.materialsOK&=available>=need;
}
p.valid=true;return p;
}
}
+50
View File
@@ -0,0 +1,50 @@
#pragma once
#include "cube_handshake.h"
namespace PortCube {
inline Handshake RecoveryRequest(uint32_t account,uint32_t player,uint64_t session) {
Handshake f;f.message=Message::RecoveryClaim;f.account=account;f.player=player;f.session=session;f.owner=f.token=std::string(32,'0');return f;
}
// This pre-load coordinator never grants actor action permission. Clear only
// authorizes a normal load request, whose DB guards must still run again.
class RecoveryFlow {
public:
enum Stage {Idle,Waiting,Held,Granted,Clear,Loading,ImageReady};
private:
Handshake request;OwnerGrant grant;Stage stage=Idle;bool lost=false;std::string image;
public:
Stage State()const{return stage;}
const OwnerGrant& Grant()const{return grant;}
const Handshake& Request()const{return request;}
const std::string& Image()const{return image;}
bool MayRequestImage()const{return !lost&&stage==Granted;}
Handshake ImageRequest()const {
Handshake f=request;f.message=Message::RecoveryImageRequest;const auto& b=grant.binding;
f.cookie=b.cookie;f.epoch=b.epoch;f.owner=b.owner;f.token=b.request;f.body=EncodeOwnerGrant(grant);return f;
}
bool Start(uint32_t account,uint32_t player,uint64_t session) {
auto f=RecoveryRequest(account,player,session);if(stage!=Idle||!ValidHandshake(f))return false;request=std::move(f);stage=Waiting;return true;
}
bool MayRetry()const{return !lost&&(stage==Waiting||stage==Held);}
void LostTransport(){if(stage!=Idle){lost=true;stage=Held;image.clear();}}
bool Answer(uint32_t handle,const Handshake& f) {
if(lost||stage==Idle||stage==Loading||!ValidHandshake(f)||f.account!=request.account||f.player!=request.player||f.session!=request.session)return false;
if(f.message==Message::RecoveryImageAnswer) {
if(stage!=Granted&&stage!=ImageReady)return false;
OwnerGrant g;std::string data;
if(f.status==Status::Held){return stage==Granted&&DecodeOwnerGrant(f.body,g)&&g.binding.handle==handle&&SameOwnerGrant(g,grant);}
if(!DecodeRecoveryImage(f.body,g,data)||g.binding.handle!=handle||!SameOwnerGrant(g,grant))return false;
if(stage==ImageReady){if(data==image)return true;LostTransport();return false;}
image=std::move(data);stage=ImageReady;return true;
}
if(f.message!=Message::RecoveryAnswer)return false;
if(f.status==Status::RecoveryGranted) {
OwnerGrant g;if(!DecodeOwnerGrant(f.body,g)||g.binding.handle!=handle)return false;
if(stage==Granted||stage==ImageReady)return SameOwnerGrant(g,grant);
if(stage==Clear)return false;grant=std::move(g);stage=Granted;return true;
}
if(stage==Granted||stage==Clear||stage==ImageReady)return false;
stage=f.status==Status::RecoveryClear?Clear:Held;return true;
}
bool TakeClear(){if(lost||stage!=Clear)return false;stage=Loading;return true;}
};
}
+60
View File
@@ -0,0 +1,60 @@
#pragma once
#include "cube_image_ack.h"
namespace PortCube {
template<class DB> bool ReleaseSchema(DB& db) {
PortEconomy::Rows rows;const std::string names="('port_cube_release_version','port_cube_releases')";
auto q=[&](const std::string& sql){return db.Query(sql,rows)&&!db.warnings&&rows.size()==1&&rows[0].size()==1;};
return q("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME IN "+names)&&rows[0][0]=="2"&&
q("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN "+names)&&rows[0][0]=="2"&&
q("SELECT version FROM port_cube_release_version WHERE id=1")&&rows[0][0]=="1";
}
// Terminal SQL decision, NOT actor readiness or permission to thaw. The runtime
// keeps its save/load gate until an independently verified resume handoff.
template<class DB> class ReleaseStore {
DB& db;Lookup lookup;
static std::string X(const std::string& s){return "X'"+PortEconomy::Hex(s.data(),s.size())+"'";}
public:
enum Result {Retry,Refused,Released};
ReleaseStore(DB& d,Lookup p):db(d),lookup(std::move(p)){}
enum CheckResult {CheckRetry,CheckRefused,Checked};
CheckResult CheckResumeLive(const Batch& b,const OwnerGrant& grant,const std::string& image) {
InventoryImage decoded;
if(!Validate(b)||!Valid(grant)||!Matches(grant.binding,b)||!DecodeInventoryImage(image,decoded,lookup))return CheckRefused;
if(!ImageAckSchema(db)||!ReleaseSchema(db))return CheckRetry;
OwnerStore<DB> owner(db,lookup);FenceStore<DB> fence(db,lookup);
const auto result=fence.CheckReleasedImage(b,image,[&]()->bool{
PortEconomy::Rows rows;const std::vector<std::string> exact={Encode(b),EncodeOwnerGrant(grant),image};
auto q=[&](const std::string& sql){return db.Query(sql,rows)&&!db.warnings;};
if(!q("SELECT body,owner_grant,image FROM port_cube_image_acks WHERE request='"+b.token+"' FOR UPDATE")||rows.size()!=1||rows[0]!=exact)return false;
if(!q("SELECT body,owner_grant,image FROM port_cube_releases WHERE request='"+b.token+"' FOR UPDATE")||rows.size()!=1||rows[0]!=exact)return false;
if(!q("SELECT id FROM port_cube_item_fences WHERE pid="+std::to_string(b.player)+" OR request='"+b.token+"' FOR UPDATE")||!rows.empty())return false;
return owner.ReleasedImageWithin(b,grant,image);
});
return result==FenceStore<DB>::Done?Checked:result==FenceStore<DB>::Retry?CheckRetry:CheckRefused;
}
Result ReleaseLive(const Batch& b,const OwnerGrant& grant,const std::string& image) {
InventoryImage decoded;
if(!Validate(b)||!Valid(grant)||!Matches(grant.binding,b)||!DecodeInventoryImage(image,decoded,lookup))return Refused;
if(!ImageAckSchema(db)||!ReleaseSchema(db))return Retry;
OwnerStore<DB> owner(db,lookup);FenceStore<DB> fence(db,lookup);
const auto result=fence.Release(b,image,[&](bool replay)->bool {
PortEconomy::Rows rows;auto q=[&](const std::string& sql){return db.Query(sql,rows)&&!db.warnings;};
const std::vector<std::string> exact={Encode(b),EncodeOwnerGrant(grant),image};
if(!q("SELECT body,owner_grant,image FROM port_cube_image_acks WHERE request='"+b.token+"' FOR UPDATE")||rows.size()!=1||rows[0]!=exact)return false;
if(replay&&!owner.ReleasedWithin(b,grant))return false;
if(!replay&&!owner.LiveImageWithin(b,grant,image))return false;
if(!replay&&(!q("SELECT id FROM port_cube_item_fences WHERE request='"+b.token+"' AND pid<>"+std::to_string(b.player)+" FOR UPDATE")||!rows.empty()))return false;
if(!q("SELECT body,owner_grant,image FROM port_cube_releases WHERE request='"+b.token+"' FOR UPDATE"))return false;
if(replay) {
if(rows.size()!=1||rows[0]!=exact)return false;
// A terminal replay cannot bless a partially removed fence.
return q("SELECT id FROM port_cube_item_fences WHERE pid="+std::to_string(b.player)+" OR request='"+b.token+"' FOR UPDATE")&&rows.empty();
}
if(!rows.empty())return false; // terminal history with LIVE lease is inconsistent
if(!q("INSERT INTO port_cube_releases(request,body,owner_grant,image) VALUES('"+b.token+"',"+X(exact[0])+","+X(exact[1])+","+X(image)+")")||db.affected!=1)return false;
return q("DELETE FROM port_cube_owner_leases WHERE request='"+b.token+"' AND phase='LIVE' AND revision="+std::to_string(grant.revision))&&db.affected==1;
});
return result==FenceStore<DB>::Done?Released:result==FenceStore<DB>::Retry?Retry:Refused;
}
};
}
+169
View File
@@ -0,0 +1,169 @@
#pragma once
#include "cube_batch.h"
#include "economy_store.h"
namespace PortCube {
// Candidate DB transaction engine. Nothing calls it from the live game yet.
// Shared economy ID tombstones ensure prepared factory IDs cannot be recycled
// by the existing DB restart high-water algorithm, even after a rejected batch.
template<class DB> class BatchStore {
DB& db;Lookup lookup;
using Rows=PortEconomy::Rows;
static std::string N(uint64_t value){return std::to_string(value);}
// Silent truncation is an error even on a non-strict MySQL connection.
bool Q(const std::string& sql,Rows& rows){return db.Query(sql,rows)&&db.warnings==0;}
bool Run(const std::string& sql){Rows rows;return Q(sql,rows);}
bool Change(const std::string& sql){return Run(sql)&&db.affected==1;}
bool One(const std::string& sql,Rows& rows){return Q(sql,rows)&&rows.size()==1;}
struct Guard {DB& db;~Guard(){db.Rollback();}};
bool LockAccount(uint32_t account){Rows rows;return Run("INSERT INTO port_economy_account_lock(account) VALUES("+N(account)+") ON DUPLICATE KEY UPDATE account=VALUES(account)")&&One("SELECT account FROM port_economy_account_lock WHERE account="+N(account)+" FOR UPDATE",rows);}
int Fence(const Batch& b) {
Rows rows;
if(!Q("SELECT epoch,owner,request,phase,body,drain_state FROM port_cube_fences WHERE pid="+N(b.player)+" AND account="+N(b.account)+" FOR UPDATE",rows))return -1;
if(rows.size()!=1||rows[0].size()!=6||rows[0][0]!=N(b.epoch)||rows[0][1]!=b.owner||rows[0][2]!=b.token||rows[0][3]!="FROZEN"||rows[0][4]!=Encode(b)||rows[0][5]!="1")return 0;
if(!Q("SELECT id,epoch,request FROM port_cube_item_fences WHERE pid="+N(b.player)+" FOR UPDATE",rows))return -1;
std::set<uint32_t> locked;
for(const auto& row:rows){uint64_t id=0;if(row.size()!=3||!PortEconomy::Number(row[0],id,UINT32_MAX)||!id||row[1]!=N(b.epoch)||row[2]!=b.token||!locked.insert(uint32_t(id)).second)return 0;}
for(const auto& item:b.inventory)if(!locked.count(item.value.id))return 0;
for(const auto& item:b.rewards)if(!locked.count(item.id))return 0;
if(!Q("SELECT token FROM port_economy_pending WHERE pid="+N(b.player)+" FOR UPDATE",rows))return -1;
return rows.empty()?1:0;
}
static std::string Columns() {
std::string s="id,vnum,count,pos";
for(unsigned i=0;i<3;++i)s+=",socket"+N(i);
for(unsigned i=0;i<7;++i)s+=",attrtype"+N(i)+",attrvalue"+N(i);
return s+",port_extra";
}
static std::vector<std::string> ItemRow(const Item& i) {
const auto& item=i.value;std::vector<std::string> row={N(item.id),N(item.vnum),N(item.count),N(i.cell)};
for(auto socket:item.sockets)row.push_back(std::to_string(socket));
for(unsigned n=0;n<7;++n){row.push_back(N(item.types[n]));row.push_back(std::to_string(item.values[n]));}
row.emplace_back(reinterpret_cast<const char*>(item.extra),sizeof(item.extra));return row;
}
bool Inventory(const Batch& b,bool& matches) {
Rows rows;if(!Q("SELECT "+Columns()+" FROM item WHERE owner_id="+N(b.player)+" AND window='INVENTORY' AND pos<225 ORDER BY pos,id FOR UPDATE",rows))return false;
matches=rows.size()==b.inventory.size();
for(unsigned i=0;matches&&i<rows.size();++i)matches=rows[i]==ItemRow(b.inventory[i]);
return true;
}
bool Insert(uint32_t player,const Item& i) {
const auto row=ItemRow(i);std::string values;
for(unsigned n=0;n+1<row.size();++n){if(n)values+=',';values+=row[n];}
values+=",X'"+PortEconomy::Hex(row.back().data(),row.back().size())+"'";
return Change("INSERT INTO item("+Columns()+",owner_id,window) VALUES("+values+","+N(player)+",'INVENTORY')");
}
public:
enum Result { Retry, Rejected, Prepared, Complete, Blocked };
struct Receipt {std::string result;unsigned successes=0;uint64_t fee=0;std::vector<Item> awards;};
BatchStore(DB& database,Lookup proto):db(database),lookup(std::move(proto)){}
// Read-only validation shared with deferred-credit recovery. Never execute
// PREPARED just to inspect a receipt; callers must hold the account lock.
static bool DoneReceipt(const Batch& b,const std::vector<std::string>& saved,Receipt& receipt) {
receipt={};if(!Validate(b)||saved.size()!=7||saved[0]!=Encode(b)||saved[2]!="DONE")return false;
uint64_t successes=0,fee=0;Reader r(saved[6]);auto awards=r.items();
if(!PortEconomy::Number(saved[4],successes,b.attempts)||!PortEconomy::Number(saved[5],fee,PortEconomy::GoldLimit)||!r.ok||r.at!=saved[6].size())return false;
const std::set<std::string> results={"ok","gold_changed","inventory_changed","materials_missing","gold_missing","capacity_full","item_proto","inventory_invalid"};
if(!results.count(saved[3])||saved[1].size()!=b.attempts)return false;
unsigned rolled=0;for(unsigned char roll:saved[1]){if(roll<1||roll>100)return false;rolled+=roll<=b.recipe.percent;}
if(saved[3]!="ok") {if(successes||fee||!awards.empty())return false;}
else {
if(successes!=rolled||fee!=uint64_t(b.recipe.gold)*b.attempts||fee>b.gold)return false;
uint64_t remaining=successes*b.recipe.rewardCount;std::set<unsigned> cells;
if(awards.size()>b.rewards.size())return false;
for(unsigned n=0;n<awards.size();++n) {
if(!remaining||awards[n].cell>=225||!awards[n].usable||!cells.insert(awards[n].cell).second)return false;
auto expected=b.rewards[n];expected.count=uint32_t(std::min(remaining,uint64_t(b.recipe.stackable?2000:1)));
Writer actual,image;actual.reward(awards[n].value);image.reward(expected);
if(actual.data!=image.data)return false;remaining-=expected.count;
}
if(remaining)return false;
}
receipt={saved[3],unsigned(successes),fee,std::move(awards)};return true;
}
bool Ready() {
Rows rows;
if(!One("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN ('player','item','port_cube_version','port_cube_requests','port_cube_fences','port_cube_item_fences','port_economy_account_lock','port_economy_item_reservations','port_economy_custody','port_economy_pending','port_economy_version')",rows)||rows[0][0]!="11"||
!One("SELECT version FROM port_cube_version WHERE id=1",rows)||rows[0][0]!="2"||
!One("SELECT version FROM port_economy_version WHERE id=1",rows)||rows[0][0]!="1")return false;
// Do not silently discard a future item column. All item state must be
// covered by both the snapshot comparison and the reward factory image.
if(!Q("SHOW COLUMNS FROM item",rows))return false;
std::set<std::string> expected={"id","owner_id","window","pos","count","vnum","port_extra"};
for(unsigned i=0;i<3;++i)expected.insert("socket"+N(i));
for(unsigned i=0;i<7;++i){expected.insert("attrtype"+N(i));expected.insert("attrvalue"+N(i));}
for(const auto& row:rows) {
if(row.empty()||!expected.erase(row[0]))return false;
if(row[0]=="port_extra"&&(row.size()<3||(row[1]!="varbinary(69)"&&row[1]!="binary(69)")||row[2]!="NO"))return false;
}
return expected.empty();
}
// Draw callback is DB-side trusted RNG, called ONLY for a newly accepted
// identity. Every draw is durable before any asset mutation is attempted.
Result Prepare(const Batch& b,const std::function<unsigned()>& draw,const std::function<bool()>& authorize={}) {
if(!Validate(b))return Rejected;
if(!Ready()||!db.Begin())return Retry;
Guard guard{db};
Rows rows;const auto body=Encode(b);
auto stop=[](Result result){return result;};
if(!LockAccount(b.account))return stop(Retry);
if(authorize&&!authorize())return stop(Blocked);
if(!Q("SELECT body,state FROM port_cube_requests WHERE token='"+b.token+"' FOR UPDATE",rows))return stop(Retry);
if(!rows.empty()) {
if(rows.size()!=1||rows[0].size()!=2||rows[0][0]!=body||(rows[0][1]!="PREPARED"&&rows[0][1]!="DONE"))return stop(Rejected);
// Even DONE requests replay without drawing or touching assets.
return stop(Prepared);
}
const int fence=Fence(b);if(fence<=0)return stop(fence<0?Retry:Blocked);
for(const auto& reward:b.rewards) {
if(!Q("SELECT id FROM item WHERE id="+N(reward.id)+" UNION ALL SELECT id FROM port_economy_custody WHERE id="+N(reward.id),rows))return stop(Retry);
if(!rows.empty())return stop(Rejected);
if(!Q("SELECT request FROM port_economy_item_reservations WHERE id="+N(reward.id)+" FOR UPDATE",rows))return stop(Retry);
if(rows.empty()) {if(!Change("INSERT INTO port_economy_item_reservations(id,request) VALUES("+N(reward.id)+",'"+b.token+"')"))return stop(Retry);}
else if(rows.size()!=1||rows[0].size()!=1||rows[0][0]!=b.token)return stop(Rejected);
}
std::string rolls;for(unsigned i=0;i<b.attempts;++i){const auto roll=draw();if(roll<1||roll>100)return stop(Rejected);rolls+=char(roll);}
if(!Change("INSERT INTO port_cube_requests(token,account,pid,body,rolls,state,result,successes,fee,awards) VALUES('"+b.token+"',"+N(b.account)+","+N(b.player)+",X'"+PortEconomy::Hex(body.data(),body.size())+"',X'"+PortEconomy::Hex(rolls.data(),rolls.size())+"','PREPARED','prepared',0,0,X'0000')")||!db.Commit())return stop(Retry);
return Prepared;
}
// Identity-only recovery loads the complete immutable request and fixed RNG
// from storage. A disconnected caller cannot supply a replacement snapshot.
Result Execute(const std::string& token,uint32_t account,uint32_t player,Receipt& receipt,const std::function<bool(const Batch&)>& authorize={}) {
receipt={};if(!Identity(token)||!account||!player)return Rejected;
if(!Ready()||!db.Begin())return Retry;
Guard guard{db};
auto stop=[](Result result){return result;};Rows rows;
if(!LockAccount(account)||!Q("SELECT body,rolls,state,result,successes,fee,awards FROM port_cube_requests WHERE token='"+token+"' AND account="+N(account)+" AND pid="+N(player)+" FOR UPDATE",rows))return stop(Retry);
if(rows.empty())return stop(Rejected);
if(rows.size()!=1||rows[0].size()!=7)return stop(Retry);
const auto saved=rows[0];Batch b;uint64_t fee=0;
if(!Decode(saved[0],b)||b.token!=token||b.account!=account||b.player!=player)return stop(Retry);
if(authorize&&!authorize(b))return stop(Blocked);
if(saved[2]=="DONE") {
return stop(DoneReceipt(b,saved,receipt)?Complete:Retry);
}
if(saved[2]!="PREPARED")return stop(Retry);
const int fence=Fence(b);if(fence<=0)return stop(fence<0?Retry:Blocked);
if(!One("SELECT gold FROM player WHERE id="+N(player)+" AND account_id="+N(account)+" FOR UPDATE",rows)||rows[0].size()!=1||!PortEconomy::Number(rows[0][0],fee,PortEconomy::GoldLimit))return stop(Retry);
Settlement plan;
if(fee!=b.gold)plan.result="gold_changed";
else {
bool matches=false;if(!Inventory(b,matches))return stop(Retry);
if(!matches)plan.result="inventory_changed";
else plan=SettlePlan(b,saved[1],lookup);
}
if(plan.result=="invalid")return stop(Retry); // corrupt persisted input: quarantine, never charge
if(plan.result=="ok") {
for(const auto& take:plan.takes) {
const std::string where=" WHERE id="+N(take.id)+" AND owner_id="+N(player)+" AND window='INVENTORY' AND count="+N(take.before);
if(!Change(take.count==take.before?"DELETE FROM item"+where:"UPDATE item SET count=count-"+N(take.count)+where))return stop(Retry);
}
if(plan.fee&&!Change("UPDATE player SET gold=gold-"+N(plan.fee)+" WHERE id="+N(player)+" AND account_id="+N(account)+" AND gold="+N(b.gold)))return stop(Retry);
for(const auto& award:plan.awards)if(!Insert(player,award))return stop(Retry);
} else {plan.successes=0;plan.fee=0;plan.awards.clear();}
Writer awards;awards.items(plan.awards);
if(!Change("UPDATE port_cube_requests SET state='DONE',result='"+plan.result+"',successes="+N(plan.successes)+",fee="+N(plan.fee)+",awards=X'"+PortEconomy::Hex(awards.data.data(),awards.data.size())+"' WHERE token='"+token+"' AND state='PREPARED'")||!db.Commit())return stop(Retry);
receipt={plan.result,plan.successes,plan.fee,std::move(plan.awards)};return Complete;
}
};
}
+3 -3
View File
@@ -13,7 +13,7 @@ class Mysql {
unsigned previousTimeout=0;
unsigned long thread=0;
public:
uint64_t affected=0,inserted=0;
uint64_t affected=0,inserted=0,warnings=0;
std::function<void(const std::string&)> afterStatement;
explicit Mysql(MYSQL* handle):connection(handle) {
// Reconnect only BEFORE entering the pinned transaction scope. Without
@@ -28,7 +28,7 @@ public:
}
~Mysql(){Rollback();if(previousTimeout){Rows rows;Query("SET SESSION innodb_lock_wait_timeout="+std::to_string(previousTimeout),rows);}my_bool reconnect=true;mysql_options(connection,MYSQL_OPT_RECONNECT,&reconnect);}
bool Query(const std::string& sql,Rows& rows) {
rows.clear();affected=0;inserted=0;
rows.clear();affected=0;inserted=0;warnings=0;
if(!pinned || mysql_thread_id(connection)!=thread || mysql_real_query(connection,sql.data(),static_cast<unsigned long>(sql.size())))return false;
MYSQL_RES* result=mysql_store_result(connection);
if(result) {
@@ -40,7 +40,7 @@ public:
}
const bool ok=mysql_errno(connection)==0;mysql_free_result(result);if(!ok)return false;
} else if(mysql_field_count(connection))return false;
affected=mysql_affected_rows(connection);inserted=mysql_insert_id(connection);
affected=mysql_affected_rows(connection);inserted=mysql_insert_id(connection);warnings=mysql_warning_count(connection);
if(afterStatement)afterStatement(sql);
return mysql_thread_id(connection)==thread;
}
+49
View File
@@ -0,0 +1,49 @@
#pragma once
#include <array>
#include <cstdint>
#include <cstddef>
#include <deque>
#include <map>
// DB-main-thread-only ownership router for results from the SAME player async
// FIFO. SQL worker threads never access this registry. Tokens are opaque integers
// in pvUserData, never pointers to an actor, ticket object or reclaimed memory.
namespace PortSQLFence {
enum Kind : unsigned { Economy=0, Cube=1 };
template<class Message> class Router {
struct Ticket {Kind kind;uint32_t logical;};
uint32_t next=0,maximum;
std::size_t capacity;
uint64_t failures=0;
std::map<uint32_t,Ticket> pending;
std::array<std::deque<Message*>,2> ready;
void Fault(){if(failures!=UINT64_MAX)++failures;}
public:
explicit Router(uint32_t maxToken=UINT32_MAX,std::size_t limit=8192):maximum(maxToken),capacity(limit){}
~Router(){Clear();}
Router(const Router&)=delete;Router& operator=(const Router&)=delete;
uint32_t Reserve(Kind kind,uint32_t logical) {
if(unsigned(kind)>1||!logical||next>=maximum||pending.size()+ready[0].size()+ready[1].size()>=capacity)return 0;
const auto token=++next;pending.emplace(token,Ticket{kind,logical});return token;
}
bool Complete(Message* message) {
if(!message){Fault();return false;}
const auto raw=reinterpret_cast<uintptr_t>(message->pvUserData);
auto it=raw<=UINT32_MAX?pending.find(uint32_t(raw)):pending.end();
if(it==pending.end()){delete message;Fault();return false;}
const auto ticket=it->second;pending.erase(it);
message->pvUserData=reinterpret_cast<void*>(uintptr_t(ticket.logical));
ready[unsigned(ticket.kind)].push_back(message);return true;
}
Message* Pop(Kind kind) {
if(unsigned(kind)>1||ready[unsigned(kind)].empty())return nullptr;
auto* message=ready[unsigned(kind)].front();ready[unsigned(kind)].pop_front();return message;
}
uint64_t Failures()const{return failures;}
void Clear() {
pending.clear();for(auto& queue:ready){for(auto* message:queue)delete message;queue.clear();}
// Never recycle a token during this DB process, even on connection reset.
Fault();
}
};
}
+10 -2
View File
@@ -1313,6 +1313,7 @@ void CClientManager::QUERY_SETUP(CPeer * peer, DWORD dwHandle, const char * c_pD
void CClientManager::QUERY_ITEM_FLUSH(CPeer * pkPeer, const char * c_pData)
{
DWORD dwID = *(DWORD *) c_pData;
if(!CubePeerMayWriteItem(pkPeer,dwID)||!CubeItemWritable(dwID))return; // PORT: bind ID-only flush to the held actor's peer
if (g_log)
sys_log(0, "HEADER_GD_ITEM_FLUSH: %u", dwID);
@@ -1326,7 +1327,7 @@ void CClientManager::QUERY_ITEM_FLUSH(CPeer * pkPeer, const char * c_pData)
void CClientManager::QUERY_ITEM_SAVE(CPeer * pkPeer, const char * c_pData)
{
TPlayerItem * p = (TPlayerItem *) c_pData;
if(!EconomyItemWritable(p->id))return;
if(!CubePeerMayWriteItem(pkPeer,p->id)||!EconomyItemWritable(p->id))return;
if(p->window!=SAFEBOX && p->window!=MALL && !EconomySaveAllowed(pkPeer,p->owner))return;
// 창고면 캐쉬하지 않고, 캐쉬에 있던 것도 빼버려야 한다.
@@ -1638,7 +1639,7 @@ void CClientManager::QUERY_ITEM_DESTROY(CPeer * pkPeer, const char * c_pData)
c_pData += sizeof(DWORD);
DWORD dwPID = *(DWORD *) c_pData;
if(!EconomyItemWritable(dwID) || (dwPID && !EconomySaveAllowed(pkPeer,dwPID)))return;
if(!CubePeerMayWriteItem(pkPeer,dwID) || !EconomyItemWritable(dwID) || (dwPID && !EconomySaveAllowed(pkPeer,dwPID)))return;
if (!DeleteItemCache(dwID))
{
@@ -1798,6 +1799,7 @@ void CClientManager::InsertLoginData(CLoginData * pkLD)
void CClientManager::DeleteLoginData(CLoginData * pkLD)
{
CubeAccountGone(pkLD->GetAccountRef().id,pkLD->GetConnectedPeerHandle()); // before auth replacement can reuse the same peer/account
m_map_pkLoginData.erase(pkLD->GetKey());
m_map_pkLoginDataByLogin.erase(pkLD->GetAccountRef().login);
m_map_pkLoginDataByAID.erase(pkLD->GetAccountRef().id);
@@ -2378,6 +2380,8 @@ void CClientManager::ProcessPackets(CPeer * peer)
switch (header)
{
case PortCube::HandshakeHeader:
CubeHandshakeRequest(peer,dwHandle,data,dwLength);break;
case 77:
EconomyRequest(peer,dwHandle,data,dwLength);break;
case 76:
@@ -2395,6 +2399,7 @@ void CClientManager::ProcessPackets(CPeer * peer)
case HEADER_GD_LOGOUT:
//sys_log(0, "HEADER_GD_LOGOUT (handle: %d length: %d)", dwHandle, dwLength);
CubeAccountLogout(peer,data,dwLength); // mark before login removal/reuse; no synchronous SQL
QUERY_LOGOUT(peer, dwHandle, data);
break;
@@ -2859,6 +2864,7 @@ void CClientManager::AddPeer(socket_t fd)
void CClientManager::RemovePeer(CPeer * pPeer)
{
CubePeerGone(pPeer->GetHandle());
if (m_pkAuthPeer == pPeer)
{
m_pkAuthPeer = NULL;
@@ -2924,6 +2930,7 @@ int CClientManager::AnalyzeQueryResult(SQLMsg * msg)
{
CQueryInfo * qi = (CQueryInfo *) msg->pvUserData;
if(qi->iType==QID_ECONOMY_FENCE) { EconomyMainFence(qi->dwIdent,msg->uiSQLErrno!=0);delete qi;return true; }
if(qi->iType==PortCube::MainFirst||qi->iType==PortCube::MainSecond) { CubeMainFence(qi->dwIdent,qi->iType==PortCube::MainFirst?1:2,msg->uiSQLErrno!=0);delete qi;return true; }
CPeer * peer = GetPeer(qi->dwIdent);
#ifdef _TEST
@@ -3070,6 +3077,7 @@ int CClientManager::Process()
{
++thecore_heart->pulse;
EconomyTick();
CubeDrainTick();
/*
//30분마다 변경
+33 -1
View File
@@ -12,6 +12,7 @@
#include "Peer.h"
#include "DBManager.h"
#include "LoginData.h"
#include "CubeRuntime.h"
class CPlayerTableCache;
class CItemCache;
@@ -30,11 +31,19 @@ size_t CreatePlayerSaveQuery(char * pszQuery, size_t querySize, TPlayerTable * p
class CClientManager : public CNetBase, public singleton<CClientManager>
{
struct EconomyFence { DWORD account=0; bool primed=false,mainDone=false,asyncDone=false,failed=false; uint64_t mainFailures=0,asyncFailures=0; time_t nextAttempt=0; DWORD peer=0,handle=0; TPlayerLoadPacket load={}; };
struct EconomyFence { DWORD account=0; bool primed=false,mainDone=false,asyncDone=false,asyncQueued=false,failed=false; uint64_t mainFailures=0,asyncFailures=0,routerFailures=0; time_t nextAttempt=0; DWORD peer=0,handle=0; TPlayerLoadPacket load={}; };
std::map<DWORD,std::pair<uint64_t,uint64_t>> m_economyEnqueueEpoch;
std::map<DWORD,EconomyFence> m_economyFences;
std::map<DWORD,DWORD> m_economyOwners;
std::set<DWORD> m_economyClosed;
DWORD m_cubeCookie=0;
uint64_t m_cubeWorkCursor=0;
std::map<DWORD,PortCube::RuntimeDrain> m_cubeDrains;
std::string m_cubeOwnerBoot;
bool CubeDrainOwner(const PortCube::RuntimeDrain&,bool=false);
bool CubeAuthorityCheck(const PortCube::RuntimeDrain&,bool);
void CubeAuthorityRevoke(PortCube::RuntimeDrain&,unsigned);
void CubeDrainFinalize(PortCube::RuntimeDrain&);
public:
void EconomyRequest(CPeer*,DWORD,const char*,DWORD);
bool EconomyBeforeLoad(CPeer*,DWORD,TPlayerLoadPacket*);
@@ -43,6 +52,29 @@ class CClientManager : public CNetBase, public singleton<CClientManager>
bool EconomySaveAllowed(CPeer*,DWORD);
bool EconomyItemWritable(DWORD);
bool EconomyCanDelete(DWORD);
bool CubePlayerWritable(DWORD);
bool CubeAccountLoadable(DWORD,DWORD);
bool CubeItemWritable(DWORD);
bool CubePeerMayWriteItem(CPeer*,DWORD);
DWORD CubeDrainArm(CPeer*,DWORD,uint64_t,const PortCube::Batch&);
bool CubeDrainSubmit(CPeer*,DWORD,uint64_t,DWORD);
void CubeMainFence(DWORD,unsigned,bool);
void CubeDrainTick();
bool CubeMemoryLoadable(DWORD,DWORD);
bool CubePeerMaySave(CPeer*,DWORD);
void CubePeerGone(DWORD);
void CubeAccountLogout(CPeer*,const char*,DWORD);
void CubeAccountGone(DWORD,DWORD);
void CubeHandshakeRequest(CPeer*,DWORD,const char*,DWORD);
void CubeHandshakeRoute(CPeer*,DWORD,const PortCube::Handshake&);
void CubeLiveResumeCheckRoute(CPeer*,DWORD,const PortCube::Handshake&);
bool CubeRecoveryClaim(CPeer*,DWORD,DWORD,DWORD,uint64_t,PortCube::OwnerGrant&);
void CubeRecoveryRoute(CPeer*,DWORD,const PortCube::Handshake&);
void CubeRecoveryImageRoute(CPeer*,DWORD,const PortCube::Handshake&);
void CubeCraftRoute(CPeer*,DWORD,const PortCube::Handshake&);
void CubeLiveImageRoute(CPeer*,DWORD,const PortCube::Handshake&);
void CubeLiveImageAckRoute(CPeer*,DWORD,const PortCube::Handshake&);
void CubeLiveReleaseRoute(CPeer*,DWORD,const PortCube::Handshake&);
typedef std::list<CPeer *> TPeerList;
typedef std::unordered_map<DWORD, CPlayerTableCache *> TPlayerTableCacheMap;
typedef std::unordered_map<DWORD, CItemCache *> TItemCacheMap;
+180
View File
@@ -0,0 +1,180 @@
#include "stdafx.h"
#include "ClientManager.h"
#include "Cache.h"
#include "Main.h"
#include <memory>
namespace {
using CubeQuery=std::unique_ptr<SQLMsg>;
CubeQuery cubeQuery(const std::string& sql){return CubeQuery(CDBManager::instance().DirectQuery(sql.c_str()));}
bool cubeValid(const CubeQuery& q){return q&&!q->uiSQLErrno&&q->Get();}
// No table installation at runtime. Cache only a completely absent schema;
// migrations require coordinated restart. Partial/failed discovery fails closed.
int cubeSchema() {
static int state=-1;if(state>=0)return state;
auto q=cubeQuery("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME IN ('port_cube_version','port_cube_fences','port_cube_item_fences')");
if(!cubeValid(q)||q->Get()->uiNumRows!=1)return -1;
MYSQL_ROW row=mysql_fetch_row(q->Get()->pSQLResult);if(!row||!row[0])return -1;
const std::string count=row[0];
if(count=="0")return state=0;
if(count=="3") {
auto version=cubeQuery("SELECT version FROM port_cube_version WHERE id=1");
if(!cubeValid(version)||version->Get()->uiNumRows!=1)return -1;
MYSQL_ROW value=mysql_fetch_row(version->Get()->pSQLResult);
if(value&&value[0]&&std::string(value[0])=="2")return state=1;
}
return -1; // includes the older two-table v1 candidate: do not ignore fences
}
bool cubeClear(const std::string& predicate) {
const int installed=cubeSchema();if(installed==0)return true;if(installed<0)return false;
auto q=cubeQuery("SELECT pid FROM port_cube_fences WHERE phase<>'RELEASED' AND ("+predicate+") LIMIT 1");
return cubeValid(q)&&q->Get()->uiNumRows==0;
}
// Modern terminal release is not a completed resume. Keep the SQL quarantine
// across DB restart, when m_cubeDrains no longer carries its memory hold.
// No resume activation receipt exists yet; do not infer one from RELEASED.
int cubeTerminalSchema() {
static int installed=-1;if(installed>=0)return installed;
const std::string names="('port_cube_release_version','port_cube_releases')";
auto scalar=[](const std::string& sql,const std::string& expected)->bool{auto q=cubeQuery(sql);if(!cubeValid(q)||q->Get()->uiNumRows!=1)return false;MYSQL_ROW row=mysql_fetch_row(q->Get()->pSQLResult);return row&&row[0]&&std::string(row[0])==expected;};
auto q=cubeQuery("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME IN "+names);
if(!cubeValid(q)||q->Get()->uiNumRows!=1)return -1;MYSQL_ROW row=mysql_fetch_row(q->Get()->pSQLResult);if(!row||!row[0])return -1;
const std::string count=row[0];if(count=="0")return installed=0;
if(count!="2"||!scalar("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN "+names,"2")||!scalar("SELECT version FROM port_cube_release_version WHERE id=1","1"))return -1;
return installed=1;
}
bool cubeTerminalClear(const std::string& predicate) {
const int schema=cubeTerminalSchema();if(schema==0)return true;if(schema<0)return false;
auto q=cubeQuery("SELECT pid FROM port_cube_fences WHERE phase='RELEASED' AND request IN (SELECT request FROM port_cube_releases) AND ("+predicate+") LIMIT 1");
return cubeValid(q)&&q->Get()->uiNumRows==0;
}
bool cubeGoldClear(const std::string& predicate) {
// Coordinated restart on installation/removal, as with the base Cube gate.
static int installed=-1;
if(installed<0) {
auto q=cubeQuery("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME IN ('port_cube_gold_version','port_cube_gold_intents','port_cube_gold_sources')");
if(!cubeValid(q)||q->Get()->uiNumRows!=1)return false;
MYSQL_ROW row=mysql_fetch_row(q->Get()->pSQLResult);if(!row||!row[0])return false;
if(std::string(row[0])=="0")installed=0;
else if(std::string(row[0])=="3") {
auto engine=cubeQuery("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN ('port_cube_gold_version','port_cube_gold_intents','port_cube_gold_sources')");
if(!cubeValid(engine)||engine->Get()->uiNumRows!=1)return false;
MYSQL_ROW e=mysql_fetch_row(engine->Get()->pSQLResult);if(!e||!e[0]||std::string(e[0])!="3")return false;
auto version=cubeQuery("SELECT version FROM port_cube_gold_version WHERE id=1");
if(!cubeValid(version)||version->Get()->uiNumRows!=1)return false;
MYSQL_ROW v=mysql_fetch_row(version->Get()->pSQLResult);if(!v||!v[0]||std::string(v[0])!="2")return false;
installed=1;
} else return false;
}
if(!installed)return true;
auto q=cubeQuery("SELECT pid FROM port_cube_gold_intents WHERE state='QUEUED' AND ("+predicate+") LIMIT 1");
return cubeValid(q)&&q->Get()->uiNumRows==0;
}
bool cubeOwnerClear(const std::string& predicate) {
static int installed=-1;
const std::string names="('port_cube_owner_version','port_cube_owner_broker','port_cube_owner_leases')";
auto scalar=[](const std::string& sql,const std::string& expected)->bool {
auto q=cubeQuery(sql);if(!cubeValid(q)||q->Get()->uiNumRows!=1)return false;
MYSQL_ROW row=mysql_fetch_row(q->Get()->pSQLResult);return row&&row[0]&&std::string(row[0])==expected;
};
if(installed<0) {
auto q=cubeQuery("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME IN "+names);
if(!cubeValid(q)||q->Get()->uiNumRows!=1)return false;
MYSQL_ROW row=mysql_fetch_row(q->Get()->pSQLResult);if(!row||!row[0])return false;
if(std::string(row[0])=="0")installed=0;
else if(std::string(row[0])=="3"&&scalar("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN "+names,"3")&&
scalar("SELECT version FROM port_cube_owner_version WHERE id=1","1"))installed=1;
else return false;
}
if(!installed)return true;
// Includes REVOKED and ADOPTED. Neither is a normal-load/thaw receipt.
auto q=cubeQuery("SELECT pid FROM port_cube_owner_leases WHERE "+predicate+" LIMIT 1");
return cubeValid(q)&&q->Get()->uiNumRows==0;
}
}
bool CClientManager::CubePeerMayWriteItem(CPeer* peer,DWORD id) {
if(*GetTablePostfix())return true;
if(!id)return false;
bool protectedActor=false;
auto allowed=[&](DWORD pid)->bool {
for(const auto& entry:m_cubeDrains)if(!entry.second.cancelled&&entry.second.batch.player==pid)
return CubePeerMaySave(peer,pid);
return true;
};
for(const auto& entry:m_cubeDrains) {
const auto& c=entry.second;if(c.cancelled)continue;protectedActor=true;
// Includes consumed inputs and not-yet-created reserved rewards. Never
// trust a packet's claimed owner or lack of a current SQL item row.
for(const auto& item:c.batch.inventory)if(item.value.id==id&&!allowed(c.batch.player))return false;
for(const auto& reward:c.batch.rewards)if(reward.id==id&&!allowed(c.batch.player))return false;
}
if(!protectedActor)return true; // no extra SQL or cache access on baseline
if(auto* cache=GetItemCache(id)) {
const auto* item=cache->Get(false);
if(!item||item->id!=id)return false;
if(item->window!=SAFEBOX&&item->window!=MALL&&!allowed(item->owner))return false;
}
// Check BOTH cached and persisted ownership. A stale cache or a forged
// SAFEBOX/MALL destination cannot conceal a protected ordinary SQL owner.
auto owner=cubeQuery("SELECT owner_id FROM item WHERE id="+std::to_string(id)+" AND window NOT IN ('MALL','SAFEBOX')");
if(!cubeValid(owner)||owner->Get()->uiNumRows>1)return false;
if(owner->Get()->uiNumRows){MYSQL_ROW row=mysql_fetch_row(owner->Get()->pSQLResult);uint64_t pid=0;if(!row||!row[0]||!PortEconomy::Number(row[0],pid,UINT32_MAX)||!pid||!allowed(DWORD(pid)))return false;}
return true;
}
bool CClientManager::CubePlayerWritable(DWORD pid) {
if(*GetTablePostfix())return true;
if(!cubeTerminalClear("pid="+std::to_string(pid)))return false;
if(!pid||!cubeOwnerClear("pid="+std::to_string(pid)))return false;
if(!pid||!cubeGoldClear("pid="+std::to_string(pid)))return false;
if(!pid||!cubeClear("pid="+std::to_string(pid)))return false;
if(cubeSchema()==0)return true;
auto q=cubeQuery("SELECT pid FROM port_cube_item_fences WHERE pid="+std::to_string(pid)+" LIMIT 1");
return cubeValid(q)&&q->Get()->uiNumRows==0;
}
bool CClientManager::CubeAccountLoadable(DWORD account,DWORD pid) {
if(*GetTablePostfix())return true;
if(!cubeTerminalClear("account="+std::to_string(account)+" OR pid="+std::to_string(pid)))return false;
if(!account||!pid||!cubeOwnerClear("account="+std::to_string(account)+" OR pid="+std::to_string(pid)))return false;
if(!account||!pid||!cubeGoldClear("account="+std::to_string(account)+" OR pid="+std::to_string(pid)))return false;
// Also stop selecting another character on an account with a held owner.
if(!account||!pid||!cubeClear("account="+std::to_string(account)+" OR pid="+std::to_string(pid)))return false;
if(cubeSchema()==0)return true;
auto q=cubeQuery("SELECT f.pid FROM port_cube_item_fences f LEFT JOIN player p ON p.id=f.pid WHERE f.pid="+std::to_string(pid)+" OR p.account_id="+std::to_string(account)+" LIMIT 1");
return cubeValid(q)&&q->Get()->uiNumRows==0;
}
bool CClientManager::CubeItemWritable(DWORD id) {
if(*GetTablePostfix())return true;
const int installed=cubeSchema();if(installed==0)return true;if(installed<0||!id)return false;
const int terminal=cubeTerminalSchema();if(terminal<0)return false;
if(terminal) {
auto reservation=cubeQuery("SELECT f.pid FROM port_cube_fences f JOIN port_cube_releases r ON r.request=f.request JOIN port_economy_item_reservations i ON i.request=f.request WHERE f.phase='RELEASED' AND i.id="+std::to_string(id)+" LIMIT 1");
if(!cubeValid(reservation)||reservation->Get()->uiNumRows)return false;
auto owner=cubeQuery("SELECT owner_id FROM item WHERE id="+std::to_string(id)+" AND window NOT IN ('MALL','SAFEBOX')");
if(!cubeValid(owner)||owner->Get()->uiNumRows>1)return false;
if(owner->Get()->uiNumRows){MYSQL_ROW row=mysql_fetch_row(owner->Get()->pSQLResult);uint64_t pid=0;if(!row||!row[0]||!PortEconomy::Number(row[0],pid,UINT32_MAX)||!pid||!cubeTerminalClear("pid="+std::to_string(pid)))return false;}
}
// SQL RELEASED is not the save/resume handoff. ID-only legacy destroy and
// flush packets cannot bypass a still-held playing context after SQL locks
// retire. Batch IDs include consumed inputs and unissued reserved rewards.
bool held=false;
for(const auto& entry:m_cubeDrains) {
const auto& c=entry.second;if(!c.began||c.cancelled)continue;held=true;
for(const auto& item:c.batch.inventory)if(item.value.id==id)return false;
for(const auto& reward:c.batch.rewards)if(reward.id==id)return false;
}
if(held) {
auto owner=cubeQuery("SELECT owner_id FROM item WHERE id="+std::to_string(id)+" AND window NOT IN ('MALL','SAFEBOX')");
if(!cubeValid(owner)||owner->Get()->uiNumRows>1)return false;
if(owner->Get()->uiNumRows) {
MYSQL_ROW row=mysql_fetch_row(owner->Get()->pSQLResult);uint64_t pid=0;
if(!row||!row[0]||!PortEconomy::Number(row[0],pid,UINT32_MAX)||!pid)return false;
for(const auto& entry:m_cubeDrains)if(entry.second.began&&!entry.second.cancelled&&entry.second.batch.player==pid)return false;
}
}
// No JOIN against item: consumed input IDs no longer have an item row, and
// owner-less legacy destroy packets must still be denied until resync ACK.
auto q=cubeQuery("SELECT id FROM port_cube_item_fences WHERE id="+std::to_string(id)+" LIMIT 1");
return cubeValid(q)&&q->Get()->uiNumRows==0;
}
+6
View File
@@ -0,0 +1,6 @@
#include "stdafx.h"
#include "../../common/economy_mysql.h"
#include "../../common/cube_gold_store.h"
// Compile the complete candidate against the real pinned MySQL adapter. No
// runtime caller or producer registration is installed by this instantiation.
template class PortCube::GoldIntentStore<PortEconomy::Mysql>;
+536
View File
@@ -0,0 +1,536 @@
#include "stdafx.h"
#include "ClientManager.h"
#include "Cache.h"
#include "Main.h"
#include "../../common/cube_fence.h"
#include "../../common/cube_gold_store.h"
#include "../../common/cube_owner.h"
#include "../../common/cube_image_ack.h"
#include "../../common/cube_release.h"
#include "../../common/cube_random.h"
#include "../../common/economy_mysql.h"
#include <algorithm>
#include <memory>
bool CClientManager::CubeDrainOwner(const PortCube::RuntimeDrain& context,bool lifecycleOnly) {
auto* peer=GetPeer(context.peer);
auto* login=GetLoginDataByAID(context.batch.account);
if((context.ownerLost&&!lifecycleOnly)||!peer||!peer->GetChannel()||!login||login->IsPlay()==context.recovery||login->GetConnectedPeerHandle()!=context.peer)return false;
for(const auto& player:login->GetAccountRef().players)if(player.dwID==context.batch.player)return true;
return false;
}
bool CClientManager::CubeAuthorityCheck(const PortCube::RuntimeDrain& c,bool lease) {
auto& db=CDBManager::instance();PortEconomy::Mysql mysql(db.DirectHandle());
PortCube::OwnerStore<PortEconomy::Mysql> owner(mysql,[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?PortCube::Proto{}:PortCube::Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};});
return lease?owner.Check(c.batch,c.ownership):owner.Current(c.ownership.leader);
}
void CClientManager::CubeAuthorityRevoke(PortCube::RuntimeDrain& c,unsigned reason) {
if(!c.began||c.revocationDone)return;auto& db=CDBManager::instance();PortEconomy::Mysql mysql(db.DirectHandle());
auto lookup=[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?PortCube::Proto{}:PortCube::Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};};
PortCube::OwnerStore<PortEconomy::Mysql> owner(mysql,lookup);
PortCube::OwnerGrant receipt;const auto result=owner.Revoke(c.batch,c.ownership.leader,reason,&c.ownership,receipt);
c.revocationDone=result==PortCube::OwnerStore<PortEconomy::Mysql>::Revoked;
if(!c.revocationDone&&!c.recovery&&result==PortCube::OwnerStore<PortEconomy::Mysql>::Refused) {
// Release COMMIT can precede peer loss and its reply. Only exact durable
// terminal proof retires revocation work; token/empty lease is not proof.
PortCube::Batch saved;std::string phase,image;PortCube::FenceStore<PortEconomy::Mysql> fence(mysql,lookup);
PortCube::ReleaseStore<PortEconomy::Mysql> release(mysql,lookup);
if(fence.Recover(c.batch.account,c.batch.player,saved,phase,image)==PortCube::FenceStore<PortEconomy::Mysql>::Done&&
phase=="RELEASED"&&PortCube::Encode(saved)==PortCube::Encode(c.batch)&&release.ReleaseLive(c.batch,c.ownership,image)==PortCube::ReleaseStore<PortEconomy::Mysql>::Released) {
c.phase="RELEASED";c.revocationDone=true; // memory save/load hold remains
}
}
if(!c.revocationDone&&c.recovery&&result==PortCube::OwnerStore<PortEconomy::Mysql>::Refused) {
// A Retry may have occurred before adoption committed. Retire only
// after reading durable proof that this proposed grant is NOT current.
std::string phase;uint64_t revoked=0;
if(owner.Inspect(c.batch,c.ownership.leader,receipt,phase,revoked)&&!PortCube::SameOwnerGrant(receipt,c.ownership)&&
(receipt.revision>=c.ownership.revision||(phase=="REVOKED"&&receipt.revision!=UINT64_MAX&&receipt.revision+1==c.ownership.revision)))c.revocationDone=true;
}
if(!c.revocationDone)c.nextRevocation=time(nullptr)+5;
}
// Recovery preparation only. The gated internal game/DB route may call this;
// no normal player load, currency write, image ACK or thaw is authorized here.
bool CClientManager::CubeRecoveryClaim(CPeer* peer,DWORD handle,DWORD account,DWORD pid,uint64_t session,PortCube::OwnerGrant& grant) {
using namespace PortCube;grant={};
if(*GetTablePostfix()||!peer||!peer->GetChannel()||!handle||!account||!pid||!session)return false;
auto* login=GetLoginDataByAID(account);
if(!login||login->IsPlay()||login->GetConnectedPeerHandle()!=peer->GetHandle()||GetPeer(peer->GetHandle())!=peer)return false;
bool member=false;for(const auto& player:login->GetAccountRef().players)if(player.dwID==pid)member=true;
if(!member)return false;
auto lookup=[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};};
auto& db=CDBManager::instance();PortEconomy::Mysql mysql(db.DirectHandle());OwnerStore<PortEconomy::Mysql> owner(mysql,lookup);
if(m_cubeOwnerBoot.empty())m_cubeOwnerBoot=OwnerBootNonce();
OwnerLeader leader;if(owner.Acquire(m_cubeOwnerBoot,leader)!=OwnerStore<PortEconomy::Mysql>::Acquired)return false;
Batch batch;std::string phase,image;FenceStore<PortEconomy::Mysql> fence(mysql,lookup);
if(fence.Recover(account,pid,batch,phase,image)!=FenceStore<PortEconomy::Mysql>::Done)return false;
OwnerGrant active;uint64_t revoked=0;
if(!owner.Inspect(batch,leader,active,phase,revoked))return false;
auto remember=[&](const OwnerGrant& held)->bool {
auto found=m_cubeDrains.find(held.binding.cookie);
if(found!=m_cubeDrains.end())return found->second.recovery&&!found->second.ownerLost&&!found->second.revocationReason&&PortCube::SameOwnerGrant(found->second.ownership,held)&&PortCube::Encode(found->second.batch)==PortCube::Encode(batch);
if(m_cubeDrains.size()>=128)return false;
RuntimeDrain c;c.batch=batch;c.ownership=held;c.peer=held.peer;c.handle=held.binding.handle;c.session=held.binding.session;
c.began=c.queued=c.finished=c.recovery=true;c.phase="ADOPTED";c.created=time(nullptr);
m_cubeDrains.emplace(held.binding.cookie,std::move(c));m_cubeCookie=std::max(m_cubeCookie,held.binding.cookie);return true;
};
// Lost adoption ACK: return the exact persisted grant, never a fresh cookie.
if(phase=="ADOPTED"&&active.leader.boot==leader.boot&&active.leader.generation==leader.generation&&active.leader.connection==leader.connection&&
active.peer==peer->GetHandle()&&active.binding.handle==handle&&active.binding.session==session){if(!remember(active))return false;grant=active;return true;}
if(active.leader.generation<leader.generation) {
OwnerGrant receipt;if(owner.Revoke(batch,leader,3,nullptr,receipt)!=OwnerStore<PortEconomy::Mysql>::Revoked)return false;
active=receipt;phase="REVOKED";revoked=leader.generation;
}
if(phase!="REVOKED"||revoked!=leader.generation||active.revision==UINT64_MAX||session==active.binding.session)return false;
OwnerGrant proposal;
for(const auto& entry:m_cubeDrains) {
const auto& c=entry.second;
if(c.recovery&&c.batch.token==batch.token&&c.peer==peer->GetHandle()&&c.handle==handle&&c.session==session&&c.ownership.revision==active.revision+1&&
c.ownership.leader.boot==leader.boot&&c.ownership.leader.generation==leader.generation&&c.ownership.leader.connection==leader.connection) {
if(c.ownerLost||c.revocationReason)return false;proposal=c.ownership;break;
}
}
if(!Valid(proposal)) {
if(m_cubeDrains.size()>=128||m_cubeCookie==UINT32_MAX)return false;
proposal={leader,GoldSourceFor(batch,session,++m_cubeCookie,handle),peer->GetHandle(),active.revision+1};
}
const auto result=owner.Adopt(batch,leader,active.revision,peer->GetHandle(),proposal.binding,grant);
if(result==OwnerStore<PortEconomy::Mysql>::Refused)return false;
// Also retain a Retry proposal: COMMIT may have succeeded before its ACK
// was lost. A peer close must be able to revoke it before a client retry.
if(!remember(proposal)){grant={};return false;}
return result==OwnerStore<PortEconomy::Mysql>::Adopted;
}
DWORD CClientManager::CubeDrainArm(CPeer* peer,DWORD handle,uint64_t session,const PortCube::Batch& batch) {
if(*GetTablePostfix()||!peer||!handle||!session||!PortCube::Validate(batch)||m_cubeDrains.size()>=128||m_cubeCookie==UINT32_MAX)return 0;
PortCube::RuntimeDrain context;context.batch=batch;context.peer=peer->GetHandle();context.handle=handle;context.session=session;
if(!CubeDrainOwner(context)||!CubeMemoryLoadable(batch.account,batch.player)||!CubePlayerWritable(batch.player)||m_economyFences.count(batch.player)||m_economyClosed.count(batch.player))return 0;
auto& db=CDBManager::instance();
PortEconomy::Mysql mysql(db.DirectHandle());
// A modern live owner may produce deferred gold. Do not Arm a source whose
// durable enqueue/closure schema is missing, even if the base store exists.
PortCube::OwnerStore<PortEconomy::Mysql> store(mysql,[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?PortCube::Proto{}:PortCube::Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};});
if(!store.Ready())return 0;
if(m_cubeOwnerBoot.empty())m_cubeOwnerBoot=PortCube::OwnerBootNonce();
PortCube::OwnerLeader leader;if(store.Acquire(m_cubeOwnerBoot,leader)!=PortCube::OwnerStore<PortEconomy::Mysql>::Acquired)return 0;
// Capture BEFORE the final-save handoff, not after eviction or first barrier.
context.main=db.EconomyFailures(false);context.async=db.EconomyFailures(true);context.router=db.SQLFenceFailures();context.created=time(nullptr);
const DWORD cookie=++m_cubeCookie;context.ownership={leader,PortCube::GoldSourceFor(batch,session,cookie,handle),peer->GetHandle(),1};
m_cubeDrains.emplace(cookie,std::move(context));return cookie;
}
bool CClientManager::CubeMemoryLoadable(DWORD account,DWORD pid) {
for(const auto& entry:m_cubeDrains)if(!entry.second.cancelled&&(entry.second.batch.account==account||entry.second.batch.player==pid))return false;
return true;
}
bool CClientManager::CubePeerMaySave(CPeer* peer,DWORD pid) {
for(const auto& entry:m_cubeDrains)if(!entry.second.cancelled&&entry.second.batch.player==pid)
return !entry.second.began&&peer&&GetPeer(peer->GetHandle())==peer&&peer->GetHandle()==entry.second.peer&&CubeDrainOwner(entry.second);
return true;
}
void CClientManager::CubePeerGone(DWORD peer) {
for(auto& entry:m_cubeDrains)if(entry.second.peer==peer){entry.second.ownerLost=true;entry.second.revocationReason=1;}
}
void CClientManager::CubeAccountGone(DWORD account,DWORD peer) {
if(!account||!peer)return;
for(auto& entry:m_cubeDrains)if(entry.second.peer==peer&&entry.second.batch.account==account){entry.second.ownerLost=true;entry.second.revocationReason=2;}
}
void CClientManager::CubeAccountLogout(CPeer* peer,const char* data,DWORD length) {
if(!peer||!data||length!=sizeof(TLogoutPacket))return;
TLogoutPacket packet;std::memcpy(&packet,data,sizeof(packet));
if(!packet.login[0]||!std::memchr(packet.login,0,sizeof(packet.login)))return;
auto* login=GetLoginDataByLogin(packet.login);
if(!login||login->GetConnectedPeerHandle()!=peer->GetHandle())return;
CubeAccountGone(login->GetAccountRef().id,peer->GetHandle());
}
bool CClientManager::CubeDrainSubmit(CPeer* peer,DWORD handle,uint64_t session,DWORD cookie) {
auto it=m_cubeDrains.find(cookie);if(it==m_cubeDrains.end())return false;auto& c=it->second;
if(!peer||peer->GetHandle()!=c.peer||handle!=c.handle||session!=c.session||!CubeDrainOwner(c)||c.finished||c.cancelled)return false;
if(!CubeAuthorityCheck(c,c.queued))return false;
if(c.queued)return true;
auto* player=GetPlayerCache(c.batch.player);auto* items=GetItemCacheSet(c.batch.player);
if(!player||!items||player->Get(false)->gold!=c.batch.gold)return false;
std::vector<uint32_t> ids;std::vector<PortCube::Item> snapshot;
for(auto* cache:*items) {
const auto* item=cache->Get(false);
if(!item->id||item->owner!=c.batch.player||ids.size()>=4096)return false;
ids.push_back(item->id); // include gear and dirty tombstones before eviction
if(!item->vnum||item->window!=INVENTORY||item->pos>=225)continue;
PortCube::Item image;image.usable=false;image.cell=item->pos;image.value.id=item->id;image.value.vnum=item->vnum;image.value.count=item->count;
for(unsigned j=0;j<3;++j){if(item->alSockets[j]<INT32_MIN||item->alSockets[j]>INT32_MAX)return false;image.value.sockets[j]=int32_t(item->alSockets[j]);}
for(unsigned j=0;j<7;++j){image.value.types[j]=item->aAttr[j].bType;image.value.values[j]=item->aAttr[j].sValue;}
static_assert(sizeof(item->extra)==69,"Cube requires the exact extra-item image");
std::memcpy(image.value.extra,&item->extra,69);snapshot.push_back(image);
}
std::sort(ids.begin(),ids.end());if(std::adjacent_find(ids.begin(),ids.end())!=ids.end())return false;
std::sort(snapshot.begin(),snapshot.end(),[](const PortCube::Item& a,const PortCube::Item& b){return a.cell<b.cell;});
auto expected=c.batch.inventory;
// usable describes runtime event/lock ownership, not a SQL column. Game must
// validate it while frozen; equality here validates only the persisted image.
for(auto& image:expected)image.usable=false;
PortCube::Writer actual,wanted;actual.items(snapshot);wanted.items(expected);
if(actual.data!=wanted.data)return false;
auto& db=CDBManager::instance();PortEconomy::Mysql mysql(db.DirectHandle());
PortCube::FenceStore<PortEconomy::Mysql> store(mysql,[&](uint32_t v){auto p=m_map_itemTableByVnum.find(v);return p==m_map_itemTableByVnum.end()?PortCube::Proto{}:PortCube::Proto{unsigned(p->second->bSize),bool(p->second->dwFlags&ITEM_FLAG_STACKABLE)};});
// A lost commit ACK may already have installed the fence. Never expire or
// accept ordinary saves again after entering Begin, including Retry/Refused.
c.began=true;
PortCube::OwnerStore<PortEconomy::Mysql> owner(mysql,[&](uint32_t v){auto p=m_map_itemTableByVnum.find(v);return p==m_map_itemTableByVnum.end()?PortCube::Proto{}:PortCube::Proto{unsigned(p->second->bSize),bool(p->second->dwFlags&ITEM_FLAG_STACKABLE)};});
if(store.Begin(c.batch,ids,[&](bool replay){return owner.BindWithin(c.batch,c.ownership,replay);})!=PortCube::FenceStore<PortEconomy::Mysql>::Done)return false;
PortCube::Batch recovered;std::string phase,image;
if(store.Recover(c.batch.account,c.batch.player,recovered,phase,image)!=PortCube::FenceStore<PortEconomy::Mysql>::Done||PortCube::Encode(recovered)!=PortCube::Encode(c.batch)||phase!="DRAINING")return false;
if(!c.proof.Start(c.batch,c.session,c.main,c.async))return false;
// Flush directly, not via peer QUERY_ITEM_FLUSH, whose ingress is now gated.
FlushItemCacheSet(c.batch.player);FlushPlayerCacheSet(c.batch.player);DeleteLogoutPlayer(c.batch.player);
c.queued=true;c.phase="DRAINING";
db.ReturnQuery("SELECT 1",PortCube::MainFirst,cookie,nullptr);return true;
}
void CClientManager::CubeMainFence(DWORD cookie,unsigned pass,bool failed) {
auto it=m_cubeDrains.find(cookie);if(it==m_cubeDrains.end()||!it->second.queued||it->second.finished)return;auto& c=it->second;
if(c.proof.Main(c.batch,c.session,pass,failed)==1) {
c.phase="FIRST";
auto& db=CDBManager::instance();db.ReturnQuery("SELECT 1",PortCube::MainSecond,cookie,nullptr);
c.asyncQueued=db.CubeAsyncFence(cookie);
}
}
void CClientManager::CubeDrainTick() {
auto& db=CDBManager::instance();
while(SQLMsg* raw=db.PopCubeAsyncFence()) {
std::unique_ptr<SQLMsg> msg(raw);const auto cookie=uint32_t(reinterpret_cast<uintptr_t>(msg->pvUserData));
auto it=m_cubeDrains.find(cookie);if(it!=m_cubeDrains.end()&&it->second.queued&&!it->second.finished) {
auto& c=it->second;c.proof.Async(c.batch,c.session,msg->uiSQLErrno!=0);
}
}
// One joint queue: a persistent failing revoke must not starve a different
// actor's drain (or vice versa). Keys also distinguish two jobs on one hold.
struct Work {uint64_t key;DWORD cookie;bool revoke;};std::vector<Work> work;
const auto now=time(nullptr);
for(auto it=m_cubeDrains.begin();it!=m_cubeDrains.end();) {
const auto cookie=it->first;auto& c=it->second;
if(!CubeDrainOwner(c,true)){c.ownerLost=true;if(!c.revocationReason)c.revocationReason=2;}
if(!c.began&&(c.ownerLost||now-c.created>=60)){it=m_cubeDrains.erase(it);continue;}++it;
if(c.began&&c.revocationReason&&!c.revocationDone&&c.nextRevocation<=now)work.push_back({uint64_t(cookie)*2,cookie,true});
if(!c.queued||c.finished||c.nextAttempt>now)continue;
if(c.phase=="FIRST"&&!c.asyncQueued)c.asyncQueued=db.CubeAsyncFence(cookie);
if(c.proof.Complete())work.push_back({uint64_t(cookie)*2+1,cookie,false});
}
const auto start=std::upper_bound(work.begin(),work.end(),m_cubeWorkCursor,[](uint64_t key,const Work& item){return key<item.key;});
const size_t offset=size_t(start-work.begin());
for(size_t n=0;n<work.size()&&n<2;++n) {
const auto& item=work[(offset+n)%work.size()];auto& c=m_cubeDrains.find(item.cookie)->second;m_cubeWorkCursor=item.key;
if(item.revoke)CubeAuthorityRevoke(c,c.revocationReason);else CubeDrainFinalize(c);
}
for(auto it=m_cubeDrains.begin();it!=m_cubeDrains.end();) {
if(it->second.recovery&&it->second.revocationDone)it=m_cubeDrains.erase(it);else ++it;
} // only obsolete in-memory recovery slots retire; SQL holds survive
}
void CClientManager::CubeDrainFinalize(PortCube::RuntimeDrain& c) {
auto& db=CDBManager::instance();
// An old DB connection/generation may still have queued callbacks.
// Do not let it finalize a drain after authority has moved elsewhere.
PortEconomy::Mysql mysql(db.DirectHandle());
PortCube::OwnerStore<PortEconomy::Mysql> authority(mysql,[&](uint32_t v){auto p=m_map_itemTableByVnum.find(v);return p==m_map_itemTableByVnum.end()?PortCube::Proto{}:PortCube::Proto{unsigned(p->second->bSize),bool(p->second->dwFlags&ITEM_FLAG_STACKABLE)};});
if(!(c.ownerLost?authority.Current(c.ownership.leader):authority.Check(c.batch,c.ownership))){c.nextAttempt=time(nullptr)+5;return;}
PortCube::FenceStore<PortEconomy::Mysql> store(mysql,[&](uint32_t v){auto p=m_map_itemTableByVnum.find(v);return p==m_map_itemTableByVnum.end()?PortCube::Proto{}:PortCube::Proto{unsigned(p->second->bSize),bool(p->second->dwFlags&ITEM_FLAG_STACKABLE)};});
const bool owner=!c.ownerLost&&db.SQLFenceFailures()==c.router;
auto result=store.FinishDrain(c.batch,c.proof,c.session,db.EconomyFailures(false),db.EconomyFailures(true),owner);
if(result==PortCube::FenceStore<PortEconomy::Mysql>::Done) {
c.finished=true;c.phase=owner&&c.proof.Clean(db.EconomyFailures(false),db.EconomyFailures(true))?"FROZEN":"ABORTED";
} else {
// FinishDrain may have committed despite a lost COMMIT ACK. Read
// its original durable outcome, never infer a downgrade or unlock.
PortCube::Batch recovered;std::string phase,image;
if(store.Recover(c.batch.account,c.batch.player,recovered,phase,image)==PortCube::FenceStore<PortEconomy::Mysql>::Done&&
PortCube::Encode(recovered)==PortCube::Encode(c.batch)&&(phase=="FROZEN"||phase=="ABORTED")) {
c.finished=true;c.phase=phase;
} else c.nextAttempt=time(nullptr)+5;
}
// Deliberately retain both FROZEN and ABORTED holds. Settlement/image
// application and exact resync ACK must be wired before any release.
}
void CClientManager::CubeHandshakeRequest(CPeer* peer,DWORD handle,const char* data,DWORD length) {
PortCube::Handshake f;
if(!peer||!peer->GetChannel()||!handle||!PortCube::DecodeHandshake(data,length,f)||PortCube::IsDbHandshakeReply(f.message))return;
if(f.message==PortCube::Message::LiveResumeCheckRequest) {
if(PortCube::HandshakeEnabled&&PortCube::ActorMutationAuditComplete){CubeLiveResumeCheckRoute(peer,handle,f);return;}
f.message=PortCube::Message::LiveResumeCheckAnswer;f.status=PortCube::Status::Held;f.body.clear();
const auto bytes=PortCube::EncodeHandshake(f);peer->EncodeHeader(PortCube::HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());return;
}
if(f.message==PortCube::Message::LiveReleaseRequest) {
if(PortCube::HandshakeEnabled&&PortCube::ActorMutationAuditComplete){CubeLiveReleaseRoute(peer,handle,f);return;}
f.message=PortCube::Message::LiveReleaseAnswer;f.status=PortCube::Status::Held;f.body.clear();
const auto bytes=PortCube::EncodeHandshake(f);peer->EncodeHeader(PortCube::HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());return;
}
if(f.message==PortCube::Message::LiveImageAck) {
if(PortCube::HandshakeEnabled&&PortCube::ActorMutationAuditComplete){CubeLiveImageAckRoute(peer,handle,f);return;}
f.message=PortCube::Message::LiveImageAckAnswer;f.status=PortCube::Status::Held;f.body.clear();
const auto bytes=PortCube::EncodeHandshake(f);peer->EncodeHeader(PortCube::HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());return;
}
if(f.message==PortCube::Message::LiveImageRequest) {
if(PortCube::HandshakeEnabled&&PortCube::ActorMutationAuditComplete){CubeLiveImageRoute(peer,handle,f);return;}
f.message=PortCube::Message::LiveImageAnswer;f.status=PortCube::Status::Held;
const auto bytes=PortCube::EncodeHandshake(f);peer->EncodeHeader(PortCube::HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());return;
}
if(f.message==PortCube::Message::Prepare||f.message==PortCube::Message::Execute) {
if(PortCube::HandshakeEnabled&&PortCube::ActorMutationAuditComplete){CubeCraftRoute(peer,handle,f);return;}
f.message=PortCube::Message::CraftAnswer;f.status=PortCube::Status::Held;
const auto bytes=PortCube::EncodeHandshake(f);peer->EncodeHeader(PortCube::HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());return;
}
if(f.message==PortCube::Message::RecoveryClaim||f.message==PortCube::Message::RecoveryImageRequest) {
const bool image=f.message==PortCube::Message::RecoveryImageRequest;
if(PortCube::HandshakeEnabled&&PortCube::ActorMutationAuditComplete){if(image)CubeRecoveryImageRoute(peer,handle,f);else CubeRecoveryRoute(peer,handle,f);return;}
f.message=image?PortCube::Message::RecoveryImageAnswer:PortCube::Message::RecoveryAnswer;f.status=PortCube::Status::Held;
const auto bytes=PortCube::EncodeHandshake(f);peer->EncodeHeader(PortCube::HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());return;
}
// Closed at the actual ingress, not merely at a UI button. In particular,
// receiving a syntactically valid Arm does not prove the actor was frozen.
if(!PortCube::HandshakeEnabled) {
f.message=PortCube::Message::Answer;f.status=PortCube::Status::Held;f.body.clear();
const auto bytes=PortCube::EncodeHandshake(f);peer->EncodeHeader(PortCube::HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());return;
}
CubeHandshakeRoute(peer,handle,f);
}
void CClientManager::CubeRecoveryRoute(CPeer* peer,DWORD handle,const PortCube::Handshake& request) {
using namespace PortCube;if(!peer||!handle||!peer->GetChannel()||!ValidHandshake(request)||request.message!=Message::RecoveryClaim)return;
auto reply=request;reply.message=Message::RecoveryAnswer;reply.status=Status::Held;
auto* login=GetLoginDataByAID(request.account);bool member=false;
if(login&&!login->IsPlay()&&GetPeer(peer->GetHandle())==peer&&login->GetConnectedPeerHandle()==peer->GetHandle())
for(const auto& player:login->GetAccountRef().players)if(player.dwID==request.player)member=true;
if(member&&!*GetTablePostfix()) {
if(CubeMemoryLoadable(request.account,request.player)&&CubeAccountLoadable(request.account,request.player))reply.status=Status::RecoveryClear;
else {
OwnerGrant grant;
if(CubeRecoveryClaim(peer,handle,request.account,request.player,request.session,grant)) {
reply.status=Status::RecoveryGranted;reply.cookie=grant.binding.cookie;reply.epoch=grant.binding.epoch;reply.owner=grant.binding.owner;reply.token=grant.binding.request;reply.body=EncodeOwnerGrant(grant);
}
}
}
const auto bytes=EncodeHandshake(reply);if(bytes.empty())return;
peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());
}
void CClientManager::CubeRecoveryImageRoute(CPeer* peer,DWORD handle,const PortCube::Handshake& request) {
using namespace PortCube;
if(!peer||!peer->GetChannel()||!handle||!ValidHandshake(request)||request.message!=Message::RecoveryImageRequest)return;
auto reply=request;reply.message=Message::RecoveryImageAnswer;reply.status=Status::Held;
OwnerGrant grant;DecodeOwnerGrant(request.body,grant);auto found=m_cubeDrains.find(request.cookie);
if(!*GetTablePostfix()&&found!=m_cubeDrains.end()&&GetPeer(peer->GetHandle())==peer) {
const auto& c=found->second;
if(c.recovery&&c.peer==peer->GetHandle()&&c.handle==handle&&grant.binding.handle==handle&&SameOwnerGrant(c.ownership,grant)&&CubeDrainOwner(c)) {
auto lookup=[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};};
PortEconomy::Mysql mysql(CDBManager::instance().DirectHandle());OwnerStore<PortEconomy::Mysql> owner(mysql,lookup);FenceStore<PortEconomy::Mysql> fence(mysql,lookup);std::string image;
if(fence.Resync(c.batch,image,[&](const std::string& current){return owner.ImageWithin(c.batch,grant,current);})==FenceStore<PortEconomy::Mysql>::Done) {
const auto body=EncodeRecoveryImage(grant,image);
if(!body.empty()){reply.body=body;reply.status=Status::RecoveryImageReady;}
}
}
}
const auto bytes=EncodeHandshake(reply);if(bytes.empty())return;peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());
}
void CClientManager::CubeCraftRoute(CPeer* peer,DWORD handle,const PortCube::Handshake& request) {
using namespace PortCube;
if(!peer||!peer->GetChannel()||!handle||!ValidHandshake(request)||(request.message!=Message::Prepare&&request.message!=Message::Execute))return;
auto reply=request;reply.message=Message::CraftAnswer;reply.status=Status::Held;
auto found=m_cubeDrains.find(request.cookie);
if(!*GetTablePostfix()&&found!=m_cubeDrains.end()&&GetPeer(peer->GetHandle())==peer) {
const auto& c=found->second;
if(!c.recovery&&c.queued&&c.finished&&c.phase=="FROZEN"&&c.peer==peer->GetHandle()&&c.handle==handle&&c.session==request.session&&
c.batch.account==request.account&&c.batch.player==request.player&&c.batch.epoch==request.epoch&&c.batch.owner==request.owner&&c.batch.token==request.token&&CubeDrainOwner(c)) {
auto lookup=[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};};
PortEconomy::Mysql mysql(CDBManager::instance().DirectHandle());OwnerStore<PortEconomy::Mysql> owner(mysql,lookup);BatchStore<PortEconomy::Mysql> store(mysql,lookup);
if(request.message==Message::Prepare) {
CraftEntropy entropy;
if(store.Prepare(c.batch,[&](){return entropy.Draw();},[&](){return owner.CraftWithin(c.batch,c.ownership);})==BatchStore<PortEconomy::Mysql>::Prepared)reply.status=Status::Prepared;
} else {
BatchStore<PortEconomy::Mysql>::Receipt result;
if(store.Execute(c.batch.token,c.batch.account,c.batch.player,result,[&](const Batch& saved){return Encode(saved)==Encode(c.batch)&&owner.CraftWithin(saved,c.ownership);})==BatchStore<PortEconomy::Mysql>::Complete) {
CraftReceipt receipt{result.result,result.successes,result.fee,result.awards};reply.body=EncodeCraftReceipt(receipt);if(!reply.body.empty())reply.status=Status::Complete;
}
}
}
}
const auto bytes=EncodeHandshake(reply);if(bytes.empty())return;peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());
}
void CClientManager::CubeLiveImageRoute(CPeer* peer,DWORD handle,const PortCube::Handshake& request) {
using namespace PortCube;
if(!peer||!peer->GetChannel()||!handle||!ValidHandshake(request)||request.message!=Message::LiveImageRequest)return;
auto reply=request;reply.message=Message::LiveImageAnswer;reply.status=Status::Held;
auto found=m_cubeDrains.find(request.cookie);
if(!*GetTablePostfix()&&found!=m_cubeDrains.end()&&GetPeer(peer->GetHandle())==peer) {
auto& c=found->second;
if(!c.recovery&&c.queued&&c.finished&&(c.phase=="FROZEN"||c.phase=="RESYNC")&&c.peer==peer->GetHandle()&&c.handle==handle&&c.session==request.session&&
c.batch.account==request.account&&c.batch.player==request.player&&c.batch.epoch==request.epoch&&c.batch.owner==request.owner&&c.batch.token==request.token&&CubeDrainOwner(c)) {
auto lookup=[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};};
PortEconomy::Mysql mysql(CDBManager::instance().DirectHandle());OwnerStore<PortEconomy::Mysql> owner(mysql,lookup);FenceStore<PortEconomy::Mysql> fence(mysql,lookup);GoldIntentStore<PortEconomy::Mysql> gold(mysql,lookup);
std::vector<GoldIntent> pending;bool credited=gold.Pending(c.batch,pending)==GoldIntentStore<PortEconomy::Mysql>::Stored;
for(size_t n=0;credited&&n<std::min(size_t(2),pending.size());++n) {
typename GoldIntentStore<PortEconomy::Mysql>::Receipt receipt;
credited=gold.Apply(pending[n].event,c.batch.account,c.batch.player,receipt,[&](const GoldIntent& intent){return Matches(intent,c.batch)&&owner.CraftWithin(c.batch,c.ownership);})==GoldIntentStore<PortEconomy::Mysql>::Applied;
}
std::string image;
if(credited&&pending.size()<=2&&fence.Resync(c.batch,image,[&](const std::string& current){return owner.LiveImageWithin(c.batch,c.ownership,current);})==FenceStore<PortEconomy::Mysql>::Done) {
reply.body=std::move(image);reply.status=Status::LiveImageReady;c.phase="RESYNC";
}
}
}
const auto bytes=EncodeHandshake(reply);if(bytes.empty())return;peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());
}
void CClientManager::CubeLiveImageAckRoute(CPeer* peer,DWORD handle,const PortCube::Handshake& request) {
using namespace PortCube;
if(!peer||!peer->GetChannel()||!handle||!ValidHandshake(request)||request.message!=Message::LiveImageAck)return;
auto reply=request;reply.message=Message::LiveImageAckAnswer;reply.status=Status::Held;reply.body.clear();
const auto found=m_cubeDrains.find(request.cookie);
if(!*GetTablePostfix()&&found!=m_cubeDrains.end()&&GetPeer(peer->GetHandle())==peer) {
const auto& c=found->second;
if(!c.recovery&&c.queued&&c.finished&&c.phase=="RESYNC"&&c.peer==peer->GetHandle()&&c.handle==handle&&c.session==request.session&&
c.batch.account==request.account&&c.batch.player==request.player&&c.batch.epoch==request.epoch&&c.batch.owner==request.owner&&c.batch.token==request.token&&CubeDrainOwner(c)) {
auto lookup=[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};};
PortEconomy::Mysql mysql(CDBManager::instance().DirectHandle());ImageAckStore<PortEconomy::Mysql> ack(mysql,lookup);
if(ack.AcknowledgeLive(c.batch,c.ownership,request.body)==ImageAckStore<PortEconomy::Mysql>::Stored) {
reply.status=Status::LiveImageAcknowledged;reply.body=request.body;
}
}
}
const auto bytes=EncodeHandshake(reply);if(bytes.empty())return;peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());
}
void CClientManager::CubeLiveReleaseRoute(CPeer* peer,DWORD handle,const PortCube::Handshake& request) {
using namespace PortCube;
if(!peer||!peer->GetChannel()||!handle||!ValidHandshake(request)||request.message!=Message::LiveReleaseRequest)return;
auto reply=request;reply.message=Message::LiveReleaseAnswer;reply.status=Status::Held;reply.body.clear();
const auto found=m_cubeDrains.find(request.cookie);
if(!*GetTablePostfix()&&found!=m_cubeDrains.end()&&GetPeer(peer->GetHandle())==peer) {
auto& c=found->second;
if(!c.recovery&&c.queued&&c.finished&&(c.phase=="RESYNC"||c.phase=="RELEASED")&&c.peer==peer->GetHandle()&&c.handle==handle&&c.session==request.session&&
c.batch.account==request.account&&c.batch.player==request.player&&c.batch.epoch==request.epoch&&c.batch.owner==request.owner&&c.batch.token==request.token&&CubeDrainOwner(c)) {
auto lookup=[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};};
PortEconomy::Mysql mysql(CDBManager::instance().DirectHandle());ReleaseStore<PortEconomy::Mysql> release(mysql,lookup);
if(release.ReleaseLive(c.batch,c.ownership,request.body)==ReleaseStore<PortEconomy::Mysql>::Released) {
c.phase="RELEASED";c.revocationDone=true;reply.status=Status::LiveReleased;reply.body=request.body;
}
}
}
const auto bytes=EncodeHandshake(reply);if(bytes.empty())return;peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());
}
void CClientManager::CubeLiveResumeCheckRoute(CPeer* peer,DWORD handle,const PortCube::Handshake& request) {
using namespace PortCube;
if(!peer||!peer->GetChannel()||!handle||!ValidHandshake(request)||request.message!=Message::LiveResumeCheckRequest)return;
auto reply=request;reply.message=Message::LiveResumeCheckAnswer;reply.status=Status::Held;reply.body.clear();
const auto found=m_cubeDrains.find(request.cookie);
if(!*GetTablePostfix()&&found!=m_cubeDrains.end()&&GetPeer(peer->GetHandle())==peer) {
const auto& c=found->second;
if(!c.recovery&&c.queued&&c.finished&&c.phase=="RELEASED"&&c.revocationDone&&c.peer==peer->GetHandle()&&c.handle==handle&&c.session==request.session&&
c.batch.account==request.account&&c.batch.player==request.player&&c.batch.epoch==request.epoch&&c.batch.owner==request.owner&&c.batch.token==request.token&&CubeDrainOwner(c)) {
auto lookup=[&](uint32_t v){auto it=m_map_itemTableByVnum.find(v);return it==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(it->second->bSize),bool(it->second->dwFlags&ITEM_FLAG_STACKABLE)};};
PortEconomy::Mysql mysql(CDBManager::instance().DirectHandle());ReleaseStore<PortEconomy::Mysql> release(mysql,lookup);
if(release.CheckResumeLive(c.batch,c.ownership,request.body)==ReleaseStore<PortEconomy::Mysql>::Checked){reply.status=Status::LiveResumeChecked;reply.body=request.body;}
}
}
// Read-only preflight: no context erasure, save/load grant or actor thaw.
const auto bytes=EncodeHandshake(reply);if(bytes.empty())return;peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());
}
void CClientManager::CubeHandshakeRoute(CPeer* peer,DWORD handle,const PortCube::Handshake& f) {
using namespace PortCube;
if(f.message==Message::LiveResumeCheckRequest){CubeLiveResumeCheckRoute(peer,handle,f);return;}
if(f.message==Message::LiveReleaseRequest){CubeLiveReleaseRoute(peer,handle,f);return;}
if(f.message==Message::LiveImageAck){CubeLiveImageAckRoute(peer,handle,f);return;}
if(f.message==Message::LiveImageRequest){CubeLiveImageRoute(peer,handle,f);return;}
if(f.message==Message::Prepare||f.message==Message::Execute){CubeCraftRoute(peer,handle,f);return;}
if(f.message==Message::RecoveryClaim){CubeRecoveryRoute(peer,handle,f);return;}
if(f.message==Message::RecoveryImageRequest){CubeRecoveryImageRoute(peer,handle,f);return;}
if(!peer||!handle||!peer->GetChannel()||!ValidHandshake(f)||IsDbHandshakeReply(f.message))return;
RuntimeDrain binding;binding.batch.account=f.account;binding.batch.player=f.player;binding.peer=peer->GetHandle();
if(!CubeDrainOwner(binding))return; // authenticated core AND current account ownership
auto send=[&](Status status,DWORD cookie) {
Handshake reply=f;reply.message=Message::Answer;reply.status=status;reply.cookie=cookie;reply.body.clear();
const auto bytes=EncodeHandshake(reply);if(bytes.empty())return;
peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());
};
auto matches=[&](const RuntimeDrain& c) {
return c.peer==peer->GetHandle()&&c.handle==handle&&c.session==f.session&&c.batch.account==f.account&&c.batch.player==f.player&&
c.batch.epoch==f.epoch&&c.batch.owner==f.owner&&c.batch.token==f.token;
};
auto status=[&](const RuntimeDrain& c) {
if(c.cancelled)return Status::Cancelled;
if(!CubeDrainOwner(c))return Status::Held;
if(c.finished)return c.phase=="FROZEN"?Status::Frozen:c.phase=="ABORTED"?Status::Aborted:Status::Held;
if(c.queued)return Status::Draining;
return c.began?Status::Held:Status::Armed;
};
if(f.message==Message::Arm) {
for(const auto& entry:m_cubeDrains)if(matches(entry.second)) {
// Exact retry returns the original cookie; changed body is not a
// second Arm and must not release or replace the first hold.
send(Encode(entry.second.batch)==f.body&&CubeAuthorityCheck(entry.second,entry.second.queued)?status(entry.second):Status::Held,entry.first);return;
}
Batch b;if(!Decode(f.body,b))return;
const auto cookie=CubeDrainArm(peer,handle,f.session,b);
send(cookie?Status::Armed:Status::Held,cookie);return;
}
auto it=m_cubeDrains.find(f.cookie);
if(it==m_cubeDrains.end()||!matches(it->second)){send(Status::Held,f.cookie);return;}
auto& c=it->second;
if(c.cancelled){send(Status::Cancelled,f.cookie);return;}
if(!CubeAuthorityCheck(c,c.queued)){c.ownerLost=true;send(Status::Held,f.cookie);return;}
if(f.message==Message::GoldClose) {
if(!c.began||!CubeDrainOwner(c)){send(Status::Held,f.cookie);return;}
GoldSourceSeal seal;static_cast<GoldSourceBinding&>(seal)=GoldSourceFor(c.batch,f.session,f.cookie,handle);
if(!DecodeGoldManifest(f.body,seal.events))return;
auto& db=CDBManager::instance();PortEconomy::Mysql mysql(db.DirectHandle());
OwnerStore<PortEconomy::Mysql> authority(mysql,[&](uint32_t v){auto p=m_map_itemTableByVnum.find(v);return p==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(p->second->bSize),bool(p->second->dwFlags&ITEM_FLAG_STACKABLE)};});
if(!authority.Check(c.batch,c.ownership)){send(Status::Held,f.cookie);return;}
GoldIntentStore<PortEconomy::Mysql> store(mysql,[&](uint32_t v){auto p=m_map_itemTableByVnum.find(v);return p==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(p->second->bSize),bool(p->second->dwFlags&ITEM_FLAG_STACKABLE)};});
if(store.CloseSource(c.batch,seal)!=GoldIntentStore<PortEconomy::Mysql>::Stored){send(Status::Held,f.cookie);return;}
auto reply=f;reply.message=Message::GoldCloseAck;reply.status=Status::GoldClosed;const auto bytes=EncodeHandshake(reply);
if(bytes.empty())return;peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());return;
}
if(f.message==Message::GoldEnqueue) {
// Original authenticated peer/login/handle/session/cookie AND immutable
// batch, not a client-provided amount on an unowned player. DB restart
// loses this binding: keep the source outbox pending, never adopt it.
GoldIntent i;
if(!c.began||!CubeDrainOwner(c)||!DecodeGoldIntent(f.body,i)||!Matches(i,c.batch)){send(Status::Held,f.cookie);return;}
auto& db=CDBManager::instance();PortEconomy::Mysql mysql(db.DirectHandle());
OwnerStore<PortEconomy::Mysql> authority(mysql,[&](uint32_t v){auto p=m_map_itemTableByVnum.find(v);return p==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(p->second->bSize),bool(p->second->dwFlags&ITEM_FLAG_STACKABLE)};});
if(!authority.Check(c.batch,c.ownership)){send(Status::Held,f.cookie);return;}
GoldIntentStore<PortEconomy::Mysql> store(mysql,[&](uint32_t v){auto p=m_map_itemTableByVnum.find(v);return p==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(p->second->bSize),bool(p->second->dwFlags&ITEM_FLAG_STACKABLE)};});
const auto result=store.Enqueue(c.batch,i);
if(result!=GoldIntentStore<PortEconomy::Mysql>::Stored&&result!=GoldIntentStore<PortEconomy::Mysql>::Applied){send(Status::Held,f.cookie);return;}
auto reply=f;reply.message=Message::GoldAck;reply.status=result==GoldIntentStore<PortEconomy::Mysql>::Stored?Status::GoldStored:Status::GoldApplied;
const auto bytes=EncodeHandshake(reply);if(bytes.empty())return;
peer->EncodeHeader(HandshakeHeader,handle,bytes.size());peer->Encode(bytes.data(),bytes.size());return;
}
if(f.message==Message::Invalidate) {
// Sticky poison. Never turn an invalidated actor snapshot into a clean
// FROZEN proof, even if its ordinary values later return to the same bytes.
c.ownerLost=true;
if(c.began) {
auto& db=CDBManager::instance();PortEconomy::Mysql mysql(db.DirectHandle());
FenceStore<PortEconomy::Mysql> store(mysql,[&](uint32_t v){auto p=m_map_itemTableByVnum.find(v);return p==m_map_itemTableByVnum.end()?Proto{}:Proto{unsigned(p->second->bSize),bool(p->second->dwFlags&ITEM_FLAG_STACKABLE)};});
// The store refuses to abort an already accepted/ambiguous Prepare.
// Retain that hold for receipt recovery instead of inventing refunds.
if(store.AbortUnprepared(c.batch)==FenceStore<PortEconomy::Mysql>::Done)c.phase="ABORTED";
}
send(Status::Held,f.cookie);return;
}
if(f.message==Message::Cancel) {
// No SQL Begin attempt: no accepted/ambiguous durable ownership exists.
// Keep a short tombstone so lost cancellation ACK can be replayed.
if(!c.began&&!c.ownerLost){c.cancelled=true;c.created=time(nullptr);send(Status::Cancelled,f.cookie);}
else send(Status::Held,f.cookie);
return;
}
if(f.message==Message::Submit&&!c.finished&&!c.queued)CubeDrainSubmit(peer,handle,f.session,f.cookie);
send(status(c),f.cookie); // Submit refusal is a hold, never an unlock ACK
}
+26
View File
@@ -0,0 +1,26 @@
#pragma once
#include "../../common/cube_drain.h"
#include "../../common/cube_handshake.h"
#include "../../common/cube_owner_types.h"
#include <ctime>
namespace PortCube {
// Internal DB adapter. Header78 dispatch is compiled but ingress is hard-gated
// off in cube_handshake.h. A game coordinator MUST quiesce the actor before Arm,
// send final saves after Arm ACK, and submit on the same peer FIFO. These APIs
// and the game preparation state machine do not themselves stop asset events.
constexpr int MainFirst=101,MainSecond=102;
struct RuntimeDrain {
Batch batch;Drain proof;
uint64_t session=0,main=0,async=0,router=0;
uint32_t peer=0,handle=0;
bool began=false,queued=false,asyncQueued=false,ownerLost=false,finished=false,cancelled=false;
std::time_t created=0,nextAttempt=0;
std::string phase;
OwnerGrant ownership;
bool revocationDone=false;
unsigned revocationReason=0; // trusted peer/account lifecycle, not Invalidate
bool recovery=false; // held pre-load adoption, not a playing actor
std::time_t nextRevocation=0;
};
}
+1
View File
@@ -52,6 +52,7 @@ void CDBManager::Clear()
}
}
PortSQLFence::PlayerRouter().Clear();
Initialize();
}
+6 -2
View File
@@ -8,6 +8,7 @@
#include <mysql/mysql.h>
#include "../../libsql/AsyncSQL.h"
#include "SQLFences.h"
#define SQL_SAFE_LENGTH(size) (size * 2 + 1)
#define QUERY_SAFE_LENGTH(size) (1024 + SQL_SAFE_LENGTH(size))
@@ -46,8 +47,11 @@ class CDBManager : public singleton<CDBManager>
void ReturnQuery(const char * c_pszQuery, int iType, DWORD dwIdent, void * pvData, int iSlot = SQL_PLAYER);
void AsyncQuery(const char * c_pszQuery, int iSlot = SQL_PLAYER);
void EconomyAsyncFence(DWORD pid) { m_asyncSQL[SQL_PLAYER]->ReturnQuery("SELECT 1",reinterpret_cast<void*>(static_cast<uintptr_t>(pid))); }
SQLMsg* PopEconomyAsyncFence() { SQLMsg* message=nullptr;return m_asyncSQL[SQL_PLAYER]->PopResult(&message)?message:nullptr; }
bool EconomyAsyncFence(DWORD pid) { return PortSQLFence::Queue(m_asyncSQL[SQL_PLAYER],PortSQLFence::Economy,pid); }
SQLMsg* PopEconomyAsyncFence() { return PortSQLFence::Pop(m_asyncSQL[SQL_PLAYER],PortSQLFence::Economy); }
bool CubeAsyncFence(DWORD cookie) { return PortSQLFence::Queue(m_asyncSQL[SQL_PLAYER],PortSQLFence::Cube,cookie); }
SQLMsg* PopCubeAsyncFence() { return PortSQLFence::Pop(m_asyncSQL[SQL_PLAYER],PortSQLFence::Cube); }
uint64_t SQLFenceFailures() { return PortSQLFence::PlayerRouter().Failures(); }
uint64_t EconomyFailures(bool async) { return (async?m_asyncSQL[SQL_PLAYER]:m_mainSQL[SQL_PLAYER])->FailureEpoch(); }
MYSQL* DirectHandle(int slot=SQL_PLAYER) { return m_directSQL[slot]->GetSQLHandle(); }
SQLMsg * DirectQuery(const char * c_pszQuery, int iSlot = SQL_PLAYER);
+14 -3
View File
@@ -56,6 +56,7 @@ void CClientManager::EconomyRequest(CPeer* peer,DWORD handle,const char* data,DW
if(mysql.Query("SELECT amount FROM port_economy_credit WHERE pid="+std::to_string(r.player),rows))send("Unclaimed proceeds: "+(rows.empty()?std::string("0"):rows[0][0]),true);
return;
}
if(!CubeMemoryLoadable(r.account,r.player)||!CubePlayerWritable(r.player)){send("Character assets are awaiting Cube reconciliation.",false);return;}
if(r.operation==PortEconomy::List) {
auto it=m_map_itemTableByVnum.find(r.itemVnum);
if(it==m_map_itemTableByVnum.end() || (it->second->dwAntiFlags&(ITEM_ANTIFLAG_GIVE|ITEM_ANTIFLAG_MYSHOP)) || it->second->bType==ITEM_QUEST) {send("This item cannot be listed.",false);return;}
@@ -74,6 +75,8 @@ void CClientManager::EconomyRequest(CPeer* peer,DWORD handle,const char* data,DW
}
bool CClientManager::EconomyBeforeLoad(CPeer* peer,DWORD handle,TPlayerLoadPacket* packet) {
if(!CubeMemoryLoadable(packet->account_id,packet->player_id))return false;
if(!CubeAccountLoadable(packet->account_id,packet->player_id))return false;
if(*GetTablePostfix())return true;
const int installed=schema();if(installed==0)return true;if(installed<0)return false;
// Existing ownership checks must run before evicting or fencing any cache.
@@ -90,6 +93,7 @@ bool CClientManager::EconomyBeforeLoad(CPeer* peer,DWORD handle,TPlayerLoadPacke
auto epoch=m_economyEnqueueEpoch.find(packet->player_id);
fence.mainFailures=epoch==m_economyEnqueueEpoch.end()?database.EconomyFailures(false):epoch->second.first;
fence.asyncFailures=epoch==m_economyEnqueueEpoch.end()?database.EconomyFailures(true):epoch->second.second;
fence.routerFailures=database.SQLFenceFailures();
m_economyFences[packet->player_id]=fence;
// Eviction sends every dirty snapshot before the two FIFO barriers. Never
// settle on a cached player, including caches still awaiting logout timeout.
@@ -107,11 +111,13 @@ void CClientManager::EconomyMainFence(DWORD pid,bool failed) {
// A second main barrier and an async barrier follow those callbacks.
it->second.primed=true;
CDBManager::instance().ReturnQuery("SELECT 1",QID_ECONOMY_FENCE,pid,nullptr);
CDBManager::instance().EconomyAsyncFence(pid);
it->second.asyncQueued=CDBManager::instance().EconomyAsyncFence(pid);
} else it->second.mainDone=true;
}
void CClientManager::EconomyTick() {
auto& database=CDBManager::instance();
for(auto& entry:m_economyFences)if(entry.second.primed&&!entry.second.asyncQueued)
entry.second.asyncQueued=database.EconomyAsyncFence(entry.first);
while(SQLMsg* raw=database.PopEconomyAsyncFence()) {
Query q(raw);DWORD pid=static_cast<DWORD>(reinterpret_cast<uintptr_t>(q->pvUserData));
auto it=m_economyFences.find(pid);if(it!=m_economyFences.end()){it->second.asyncDone=true;it->second.failed|=q->uiSQLErrno!=0;}
@@ -121,10 +127,10 @@ void CClientManager::EconomyTick() {
if(fence.nextAttempt>time(nullptr)){++it;continue;}
if(!fence.mainDone||!fence.asyncDone){++it;continue;}
auto* login=GetLoginDataByAID(fence.account);
if(login&&login->IsPlay()){++it;continue;}
if((login&&login->IsPlay())||!CubeMemoryLoadable(fence.account,it->first)||!CubePlayerWritable(it->first)){++it;continue;}
PortEconomy::Mysql mysql(database.DirectHandle());
PortEconomy::Store<PortEconomy::Mysql> store(mysql,[&](uint32_t vnum){auto p=m_map_itemTableByVnum.find(vnum);return p==m_map_itemTableByVnum.end()?0u:unsigned(p->second->bSize);});
const bool failed=fence.failed||database.EconomyFailures(false)!=fence.mainFailures||database.EconomyFailures(true)!=fence.asyncFailures;
const bool failed=fence.failed||database.EconomyFailures(false)!=fence.mainFailures||database.EconomyFailures(true)!=fence.asyncFailures||database.SQLFenceFailures()!=fence.routerFailures;
bool done=failed?store.Abort(it->first,fence.account):store.Settle(it->first,fence.account)!=PortEconomy::Store<PortEconomy::Mysql>::Retry;
if(done) {
m_economyEnqueueEpoch.erase(it->first);
@@ -136,11 +142,14 @@ void CClientManager::EconomyTick() {
}
bool CClientManager::EconomySaveAllowed(CPeer* peer,DWORD pid) {
if(!CubePeerMaySave(peer,pid))return false;
if(!CubePlayerWritable(pid))return false;
if(m_economyClosed.count(pid))return false;
auto it=m_economyOwners.find(pid);if(it==m_economyOwners.end())return true;
return owns(GetLoginDataByAID(it->second),peer,pid,true);
}
bool CClientManager::EconomyItemWritable(DWORD id) {
if(!CubeItemWritable(id))return false;
if(*GetTablePostfix())return true;
const int installed=schema();if(installed==0)return true;if(installed<0)return false;
auto q=query("SELECT id FROM port_economy_custody WHERE id="+std::to_string(id));
@@ -152,6 +161,8 @@ bool CClientManager::EconomyItemWritable(DWORD id) {
// or a migrated catalogue outside the tables that legacy deletion cleans up.
// Catalogue users need an explicit audited retirement, not an implicit reset.
bool CClientManager::EconomyCanDelete(DWORD pid) {
if(!CubeMemoryLoadable(0,pid))return false;
if(!CubePlayerWritable(pid))return false;
if(*GetTablePostfix())return true;
const int installed=schema();if(installed==0)return true;if(installed<0)return false;
if(m_economyFences.count(pid)||m_economyClosed.count(pid))return false;
+10 -1
View File
@@ -112,7 +112,16 @@ bool CItemIDRangeManager::BuildRange(DWORD dwMin, DWORD dwMax, TItemIDRangeTable
std::string sources="SELECT id FROM item"+bounds;
if(hasLegacy)sources+=" UNION ALL SELECT id FROM offline_shop_item"+bounds;
if(valid)sources+=" UNION ALL SELECT id FROM port_economy_custody"+bounds+" UNION ALL SELECT id FROM port_economy_item_reservations"+bounds;
snprintf(szQuery,sizeof(szQuery),"SELECT MAX(id) FROM (%s) AS allocated_ids",sources.c_str());
// PORT: a durable Cube drain may hold dirty cached IDs that are not in
// item yet. They must not be reissued while that owner awaits resync.
auto* cube=CDBManager::instance().DirectQuery("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='port_cube_item_fences'");
if(!cube||cube->uiSQLErrno||!cube->Get()||cube->Get()->uiNumRows!=1||!cube->Get()->pSQLResult){delete cube;return false;}
row=mysql_fetch_row(cube->Get()->pSQLResult);
const bool hasCube=row&&row[0]&&!strcmp(row[0],"1"),noCube=row&&row[0]&&!strcmp(row[0],"0");
delete cube;if(!hasCube&&!noCube)return false;
if(hasCube)sources+=" UNION ALL SELECT id FROM port_cube_item_fences"+bounds;
const int length=snprintf(szQuery,sizeof(szQuery),"SELECT MAX(id) FROM (%s) AS allocated_ids",sources.c_str());
if(length<0||size_t(length)>=sizeof(szQuery))return false;
}
pMsg = CDBManager::instance().DirectQuery(szQuery);
if(!pMsg || pMsg->uiSQLErrno || !pMsg->Get() || pMsg->Get()->uiNumRows!=1 || !pMsg->Get()->pSQLResult){delete pMsg;return false;}
+21 -1
View File
@@ -39,7 +39,7 @@ SRCS = Config.cpp NetBase.cpp Peer.cpp PeerBase.cpp Main.cpp Lock.cpp DBManager.
ClientManagerBoot.cpp ClientManagerParty.cpp ClientManagerGuild.cpp GuildManager.cpp HB.cpp \
PrivManager.cpp MoneyLog.cpp ItemAwardManager.cpp ClientManagerEventFlag.cpp Marriage.cpp \
Monarch.cpp BlockCountry.cpp ItemIDRangeManager.cpp ClientManagerHorseName.cpp ClientManagerOfflineshop.cpp version.cpp \
AuctionManager.cpp ProtoReader.cpp CsvReader.cpp Ava2ItemShop.cpp Economy.cpp
AuctionManager.cpp ProtoReader.cpp CsvReader.cpp Ava2ItemShop.cpp Economy.cpp Cube.cpp CubeRuntime.cpp CubeGold.cpp
OBJS = $(SRCS:%.cpp=$(OBJDIR)/%.o)
@@ -72,3 +72,23 @@ dep:
makedepend -fDepend $(INCDIR) -I/usr/include/c++/3.3 -I/usr/include/c++/4.2 -p$(OBJDIR)/ $(SRCS) 2> /dev/null
sinclude Depend
# PORT: handwritten economy headers are not present in the legacy Depend file.
$(OBJDIR)/Economy.o: ../../common/economy.h ../../common/economy_store.h ../../common/economy_mysql.h ../../common/economy_view.h
# ClientManager layout and DB result ownership affect every DB translation unit.
$(OBJS): ClientManager.h DBManager.h SQLFences.h CubeRuntime.h ../../common/sql_fence_router.h ../../common/cube_batch.h ../../common/cube_recipe.h ../../common/cube_drain.h
$(OBJDIR)/CubeRuntime.o: ../../common/cube_fence.h ../../common/cube_store.h ../../common/economy_mysql.h
$(OBJS): ../../common/cube_handshake.h
$(OBJS): ../../common/cube_mutation.h
$(OBJDIR)/CubeGold.o: ../../common/cube_gold_store.h ../../common/cube_gold_intent.h ../../common/cube_store.h ../../common/economy_mysql.h
$(OBJDIR)/CubeRuntime.o: ../../common/cube_gold_intent.h
$(OBJDIR)/CubeRuntime.o: ../../common/cube_gold_store.h
$(OBJS): ../../common/cube_gold_source.h
$(OBJS): ../../common/cube_owner_types.h
$(OBJDIR)/CubeRuntime.o: ../../common/cube_owner.h
$(OBJDIR)/CubeRuntime.o: ../../common/cube_image_ack.h
$(OBJDIR)/CubeRuntime.o: ../../common/cube_release.h
$(OBJS): ../../common/cube_image.h
$(OBJS): ../../common/cube_receipt.h
$(OBJDIR)/CubeRuntime.o: ../../common/cube_random.h
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include "../../common/sql_fence_router.h"
// Include after libsql/AsyncSQL.h. Every return-query on the PLAYER async queue
// must register here; regular fire-and-forget AsyncQuery has no result message.
namespace PortSQLFence {
// Process-lifetime registry avoids static-destruction order against the DB
// singleton. CDBManager::Clear drains ownership explicitly after SQL shutdown.
inline Router<SQLMsg>& PlayerRouter(){static auto* router=new Router<SQLMsg>;return *router;}
inline bool Queue(CAsyncSQL* sql,Kind kind,uint32_t logical) {
if(!sql)return false;const auto ticket=PlayerRouter().Reserve(kind,logical);if(!ticket)return false;
sql->ReturnQuery("SELECT 1",reinterpret_cast<void*>(uintptr_t(ticket)));return true;
}
inline SQLMsg* Pop(CAsyncSQL* sql,Kind kind) {
if(sql){SQLMsg* message=nullptr;unsigned budget=1024;while(budget--&&sql->PopResult(&message))PlayerRouter().Complete(message);}
return PlayerRouter().Pop(kind);
}
}
+31 -1
View File
@@ -53,7 +53,7 @@ TARGET = $(BINDIR)/game
CFILE = minilzo.c
CPPFILE = BattleArena.cpp FSM.cpp MarkConvert.cpp MarkImage.cpp MarkManager.cpp OXEvent.cpp TrafficProfiler.cpp ani.cpp\
CPPFILE = port_cube_actor.cpp port_cube_recovery.cpp port_cube_factory.cpp port_cube_apply.cpp port_cube_publish.cpp port_cube_restore.cpp BattleArena.cpp FSM.cpp MarkConvert.cpp MarkImage.cpp MarkManager.cpp OXEvent.cpp TrafficProfiler.cpp ani.cpp\
arena.cpp banword.cpp battle.cpp blend_item.cpp block_country.cpp buffer_manager.cpp building.cpp castle.cpp\
char.cpp char_affect.cpp char_battle.cpp char_change_empire.cpp char_horse.cpp char_item.cpp char_manager.cpp\
char_quickslot.cpp char_resist.cpp char_skill.cpp char_state.cpp PetSystem.cpp cmd.cpp cmd_emotion.cpp cmd_general.cpp\
@@ -148,3 +148,33 @@ $(OBJDIR)/cmd_general.o: port_features.h port_rank_runtime.h
$(OBJDIR)/char_battle.o $(OBJDIR)/char_skill.o: port_magic_reduction.h
$(OBJDIR)/char_battle.o: port_quiver.h
$(OBJDIR)/char.o: port_quiver.h port_quiver_sync.inc
$(OBJDIR)/cube.o: port_cube_catalog.inc ../../common/cube_recipe.h cube.h
$(OBJDIR)/port_cube_actor.o $(OBJDIR)/input_db.o: port_cube_actor.h ../../common/cube_handshake.h ../../common/cube_batch.h
$(OBJDIR)/char.o $(OBJDIR)/char_item.o $(OBJDIR)/main.o: port_cube_actor.h
$(OBJDIR)/item_manager.o: port_cube_flush.inc item_manager.h
$(OBJDIR)/cube.o: ../../common/cube_batch.h
$(OBJDIR)/port_cube_actor.o $(OBJDIR)/char.o $(OBJDIR)/item.o: ../../common/cube_mutation.h
$(OBJDIR)/item.o: port_cube_item.inc port_cube_actor.h
$(OBJDIR)/questpc.o $(OBJDIR)/questmanager.o: port_cube_quest.h questpc.h
$(OBJDIR)/port_cube_actor.o: questpc.h port_switchbot.h item.h
$(OBJDIR)/port_cube_actor.o: ../../common/cube_gold_outbox.h ../../common/cube_gold_intent.h ../../common/cube_store.h
$(OBJDIR)/port_cube_actor.o $(OBJDIR)/input_db.o: ../../common/cube_gold_source.h
$(OBJDIR)/port_switchbot.o $(OBJDIR)/cube.o: port_cube_actor.h
$(CPPOBJS) $(MAINOBJ): char.h item.h questpc.h questmanager.h
$(OBJDIR)/port_cube_recovery.o $(OBJDIR)/input_db.o $(OBJDIR)/input_login.o $(OBJDIR)/main.o: port_cube_recovery.h ../../common/cube_recovery.h ../../common/cube_owner_types.h
$(OBJDIR)/port_cube_actor.o: ../../common/cube_owner_types.h
$(OBJDIR)/port_cube_actor.o $(OBJDIR)/port_cube_recovery.o $(OBJDIR)/input_db.o: ../../common/cube_image.h
$(OBJDIR)/port_cube_actor.o: ../../common/cube_craft.h ../../common/cube_receipt.h
$(OBJDIR)/item_manager_idrange.o: port_cube_ids.h ../../common/cube_item_ids.h
$(OBJDIR)/port_cube_factory.o $(OBJDIR)/item_manager.o: port_cube_factory.h
$(OBJDIR)/port_cube_actor.o: port_cube_factory.h
$(OBJDIR)/port_cube_actor.o: ../../common/cube_live_image.h
$(OBJDIR)/port_cube_recovery.o: ../../common/cube_handshake.h
$(OBJDIR)/port_cube_actor.o $(OBJDIR)/port_cube_publish.o $(OBJDIR)/item.o: ../../common/cube_presentation.h
$(OBJDIR)/port_cube_actor.o $(OBJDIR)/port_cube_publish.o: port_cube_publish.h
$(OBJDIR)/port_cube_actor.o $(OBJDIR)/port_cube_restore.o: port_cube_restore.h
$(OBJDIR)/item.o: port_cube_lifecycle.inc event_queue.h event.h
$(OBJDIR)/port_cube_apply.o $(OBJDIR)/port_cube_actor.o: port_cube_apply.h
$(OBJDIR)/item_manager.o: port_cube_registry.inc
$(OBJDIR)/port_cube_factory.o: port_cube_ids.h ../../common/economy.h
$(OBJDIR)/port_cube_recovery.o $(OBJDIR)/input_db.o: ../../common/cube_receipt.h
+6
View File
@@ -5,6 +5,8 @@
#include "char.h"
#include "port_gaya.h"
#include "port_cube_actor.h"
#include "../../common/cube_mutation.h"
#ifdef ENABLE_OFFLINESHOP_SYSTEM
#include "offline_shop.h"
#endif
@@ -431,6 +433,7 @@ void CHARACTER::Create(const char * c_pszName, DWORD vid, bool isPC)
void CHARACTER::Destroy()
{
PortCubeActorForget(this);
PortGayaForgetPlayer(GetPlayerID());
CloseMyShop();
@@ -1370,6 +1373,7 @@ void CHARACTER::FlushDelayedSaveItem()
void CHARACTER::Disconnect(const char * c_pszReason)
{
PortCubeAssetMutation(this,PortCube::LifecycleWrite);
assert(GetDesc() != NULL);
sys_log(0, "DISCONNECT: %s (%s)", GetName(), c_pszReason ? c_pszReason : "unset" );
@@ -3135,6 +3139,7 @@ void CHARACTER::CheckMaximumPoints()
void CHARACTER::PointChange(BYTE type, int64_t amount, bool bAmount, bool bBroadcast)
{
if(type==POINT_GOLD&&amount)PortCubeAssetMutation(this,PortCube::GoldWrite);
int val = 0;
//sys_log(0, "PointChange %d %d | %d -> %d cHP %d mHP %d", type, amount, GetPoint(type), GetPoint(type)+amount, GetHP(), GetMaxHP());
@@ -5397,6 +5402,7 @@ bool CHARACTER::WarpSet(long x, long y, long lPrivateMapIndex)
bool CHARACTER::WarpSet(long x, long y, long lPrivateMapIndex, BYTE targetChannel)
{
PortCubeAssetMutation(this,PortCube::LifecycleWrite);
if (!IsPC())
return false;
+5
View File
@@ -15,6 +15,8 @@
#include "mining.h"
class CBuffOnAttributes;
namespace PortCube {struct InventoryImage;}
namespace PortCubeView {struct Frame;}
class CPetSystem;
#ifdef ENABLE_OFFLINESHOP_SYSTEM
class COfflineShop;
@@ -1128,6 +1130,8 @@ class CHARACTER : public CEntity, public CFSM, public CHorseRider
void ClearItem();
void SetItem(TItemPos Cell, LPITEM item);
bool PortCubeInstallImage(const PortCube::InventoryImage&,const std::vector<LPITEM>& before,const std::vector<LPITEM>& restored);
bool PortCubePublishFrame(const PortCubeView::Frame&,const PortCubeView::Frame& original);
LPITEM GetItem(TItemPos Cell) const;
LPITEM GetInventoryItem(WORD wCell) const;
#ifdef ENABLE_SPECIAL_STORAGE
@@ -1993,6 +1997,7 @@ class CHARACTER : public CEntity, public CFSM, public CHorseRider
// by mhh
LPITEM* GetCubeItem() { return m_pointsInstant.pCubeItems; }
bool IsCubeOpen () const { return (m_pointsInstant.pCubeNpc?true:false); }
LPCHARACTER GetCubeNpc() const { return m_pointsInstant.pCubeNpc; } // PORT: read-only catalogue context
void SetCubeNpc(LPCHARACTER npc) { m_pointsInstant.pCubeNpc = npc; }
bool CanDoCube() const;
+6 -2
View File
@@ -1,4 +1,5 @@
#include "stdafx.h"
#include "port_cube_actor.h"
#include "../../common/gold_bounds.h"
#include <stack>
@@ -216,6 +217,7 @@ static bool FN_check_item_sex(LPCHARACTER ch, LPITEM item)
/////////////////////////////////////////////////////////////////////////////
bool CHARACTER::CanHandleItem(bool bSkipCheckRefine, bool bSkipObserver)
{
if(PortCubeActorHeld(this))return false;
if (!bSkipObserver)
if (m_bIsObserver)
return false;
@@ -6795,12 +6797,14 @@ bool CHARACTER::PickupItem(DWORD dwVID)
// 만약 주으려 하는 아이템이 엘크라면
if (item->GetType() == ITEM_ELK)
{
if(!GiveGold(item->GetCount()))return false;
const auto cubeGold=PortCubeDeferGroundGold(this,item);
if(cubeGold==PortCubeGoldPickup::Blocked)return false;
if(cubeGold==PortCubeGoldPickup::Ordinary&&!GiveGold(item->GetCount()))return false;
item->RemoveFromGround();
M2_DESTROY_ITEM(item);
Save();
if(cubeGold==PortCubeGoldPickup::Ordinary)Save();
}
// 평범한 아이템이라면
else
+17 -1
View File
@@ -8,6 +8,7 @@
#define _cube_cpp_
#include "stdafx.h"
#include "port_cube_actor.h"
#include "constants.h"
#include "utils.h"
#include "log.h"
@@ -397,8 +398,11 @@ bool Cube_load (const char *file)
continue;
// set value1, value2
if ((v = strtok(NULL, delim)))
const char* port_value = NULL;
if ((v = strtok(NULL, delim))) {
port_value = v;
str_to_number(value1, v);
}
if ((v = strtok(NULL, delim)))
str_to_number(value2, v);
@@ -429,6 +433,14 @@ bool Cube_load (const char *file)
{
cube_data->percent = value1;
}
else TOKEN("category")
{
cube_data->portCategory = port_value ? port_value : "";
}
else TOKEN("copy")
{
cube_data->portCopy = value1 > 0;
}
else TOKEN("gold")
{
// 제조에 필요한 금액
@@ -509,6 +521,7 @@ static bool FN_update_cube_status(LPCHARACTER ch)
// return new item
bool Cube_make (LPCHARACTER ch)
{
if(PortCubeActorHeld(ch))return false;
// 주어진 아이템을 필요로하는 조합을 찾는다. (큐브데이타로 칭함)
// 큐브 데이타가 있다면 아이템의 재료를 체크한다.
// 새로운 아이템을 만든다.
@@ -980,3 +993,6 @@ void Cube_request_material_info(LPCHARACTER ch, int requestStartIndex, int reque
}
// PORT: current loaded Cube catalogue and read-only batch preflight.
#include "port_cube_catalog.inc"
+2
View File
@@ -31,6 +31,8 @@ struct CUBE_DATA
std::vector<CUBE_VALUE> reward;
int percent;
unsigned int gold; // 제조시 필요한 금액
std::string portCategory = "WORLDARD";
bool portCopy = false;
CUBE_DATA();
+7 -1
View File
@@ -7,6 +7,7 @@
#include "stdafx.h"
#include "event_queue.h"
#include <memory>
extern void ContinueOnFatalError();
extern void ShutdownOnFatalError();
@@ -21,6 +22,8 @@ static CEventQueue cxx_q;
/* 이벤트를 생성하고 리턴한다 */
LPEVENT event_create_ex(TEVENTFUNC func, event_info_data* info, long when)
{
// PORT: ownership starts on entry, including event/node allocation failure.
std::unique_ptr<event_info_data> pendingInfo(info);
LPEVENT new_event = NULL;
/* 반드시 다음 pulse 이상의 시간이 지난 후에 부르도록 한다. */
@@ -36,7 +39,7 @@ LPEVENT event_create_ex(TEVENTFUNC func, event_info_data* info, long when)
assert(NULL != new_event);
new_event->func = func;
new_event->info = info;
new_event->info = pendingInfo.release();
new_event->q_el = cxx_q.Enqueue(new_event, when, thecore_heart->pulse);
new_event->is_processing = FALSE;
new_event->is_force_to_end = FALSE;
@@ -120,6 +123,9 @@ int event_process(int pulse)
LPEVENT the_event = pElem->pvData;
long processing_time = event_processing_time(the_event);
// The callback may cancel itself while destroying its owning item.
// Detach the dequeued node before Delete makes that pointer invalid.
the_event->q_el = NULL;
cxx_q.Delete(pElem);
/*
+11
View File
@@ -7,6 +7,7 @@
#include "stdafx.h"
#include "event_queue.h"
#include <memory>
CEventQueue::CEventQueue()
{
@@ -41,7 +42,17 @@ TQueueElement * CEventQueue::Enqueue(LPEVENT pvData, int duration, int pulse)
pElem->iKey = duration + pulse;
pElem->bCancel = FALSE;
// PORT: vector insertion may throw. Do not leak the node/event reference.
auto discard=[&](TQueueElement* node){
#ifdef M2_USE_POOL
pool_.Destroy(node);
#else
M2_DELETE(node);
#endif
};
std::unique_ptr<TQueueElement,decltype(discard)> pending(pElem,discard);
m_pq_queue.push(pElem);
pending.release();
return pElem;
}
+2 -2
View File
@@ -104,8 +104,8 @@ bool CHARACTER::ExchangeStart(LPCHARACTER victim)
SetExchangeTime();
victim->SetExchangeTime();
exchange_packet(victim, EXCHANGE_SUBHEADER_GC_START, 0, GetVID(), NPOS, 0);
exchange_packet(this, EXCHANGE_SUBHEADER_GC_START, 0, victim->GetVID(), NPOS, 0);
exchange_packet(victim, EXCHANGE_SUBHEADER_GC_START, 0, GetVID(), NPOS, GetLevel());
exchange_packet(this, EXCHANGE_SUBHEADER_GC_START, 0, victim->GetVID(), NPOS, victim->GetLevel());
return true;
}
+18 -1
View File
@@ -1,6 +1,9 @@
#include "stdafx.h"
#include "ava2_itemshop.h"
#include "port_economy.h"
#include "port_cube_actor.h"
#include "port_cube_recovery.h"
#include "../../common/cube_handshake.h"
#include "../../common/ava2_itemshop.h"
#include "new_mob_timer.h"
#include "ava2_track.h"
@@ -2253,6 +2256,14 @@ void CInputDB::ReloadAdmin(const char * c_pData )
////////////////////////////////////////////////////////////////////
int CInputDB::Analyze(LPDESC d, BYTE bHeader, const char * c_pData)
{
if(bHeader==PortCube::HandshakeHeader) {
// Process validated the complete bounded frame before this call.
const auto* p=reinterpret_cast<const unsigned char*>(c_pData);
const uint32_t size=uint32_t(p[0])|(uint32_t(p[1])<<8)|(uint32_t(p[2])<<16)|(uint32_t(p[3])<<24);
PortCube::Handshake frame;
if(PortCube::DecodeHandshake(c_pData,size,frame)&&(frame.message==PortCube::Message::RecoveryAnswer||frame.message==PortCube::Message::RecoveryImageAnswer))PortCubeRecoveryReply(m_dwHandle,c_pData,size);
else PortCubeActorReply(m_dwHandle,c_pData,size);return 0;
}
switch (bHeader)
{
case HEADER_DG_BOOT:
@@ -2649,6 +2660,8 @@ bool CInputDB::Process(LPDESC d, const void * orig, int bytes, int & r_iBytesPro
m_dwHandle = *((DWORD *) (c_pData + 1)); // 4
iSize = *((DWORD *) (c_pData + 5)); // 4
if(bHeader==PortCube::HandshakeHeader&&(iSize<int(PortCube::HandshakeFixed)||iSize>int(PortCube::HandshakeMaximum))){d->SetPhase(PHASE_CLOSE);return true;}
sys_log(1, "DBCLIENT: header %d handle %d size %d bytes %d", bHeader, m_dwHandle, iSize, bytes);
if (m_iBufferLeft - 9 < iSize)
@@ -2657,6 +2670,10 @@ bool CInputDB::Process(LPDESC d, const void * orig, int bytes, int & r_iBytesPro
const char * pRealData = (c_pData + 9);
if(bHeader==77 && iSize!=int(sizeof(PortEconomy::Reply))){d->SetPhase(PHASE_CLOSE);return true;}
if(bHeader==PortCube::HandshakeHeader) {
PortCube::Handshake frame;
if(iSize<0||!PortCube::DecodeHandshake(pRealData,size_t(iSize),frame)||!PortCube::IsDbHandshakeReply(frame.message)){d->SetPhase(PHASE_CLOSE);return true;}
}
if (bHeader==76 && (iSize<int(sizeof(Ava2ShopReply))+1 || iSize>32775 || reinterpret_cast<const Ava2ShopReply*>(pRealData)->size!=iSize-sizeof(Ava2ShopReply))) { d->SetPhase(PHASE_CLOSE);return true; }
if (Analyze(d, bHeader, pRealData) < 0)
@@ -2826,4 +2843,4 @@ void CInputDB::RespondChannelStatus(LPDESC desc, const char* pcData)
BYTE bSuccess = 1;
desc->Packet(&bSuccess, sizeof(bSuccess));
desc->SetChannelStatusRequested(false);
}
}
+2
View File
@@ -4,6 +4,7 @@
#include "config.h"
#include "utils.h"
#include "input.h"
#include "port_cube_recovery.h"
#include "desc_client.h"
#include "desc_manager.h"
#include "char.h"
@@ -268,6 +269,7 @@ void CInputLogin::CharacterSelect(LPDESC d, const char * data)
return;
}
if(PortCubeRecoverySelect(d,c_r.players[pinfo->index].dwID,pinfo->index))return;
TPlayerLoadPacket player_load_packet;
player_load_packet.account_id = c_r.id;
+50 -9
View File
@@ -1,4 +1,8 @@
#include "stdafx.h"
#include "port_cube_actor.h"
#include "../../common/cube_mutation.h"
#include "../../common/economy.h"
#include "../../common/cube_presentation.h"
#include "port_attr_lock.h"
#include "utils.h"
#include "config.h"
@@ -24,6 +28,8 @@
#include "../../common/VnumHelper.h"
#include "PetSystem.h"
#include <cmath>
#include <memory>
#include "event_queue.h"
CItem::CItem(DWORD dwVnum)
: m_dwVnum(dwVnum), m_bWindow(0), m_dwID(0), m_bEquipped(false), m_dwVID(0), m_wCell(0), m_dwCount(0), m_lFlag(0), m_dwLastOwnerPID(0),
@@ -69,6 +75,7 @@ void CItem::Initialize()
m_bSkipSave = false;
m_deferChestUpdate = false;
m_portCubeTemplate = false;
m_dwLastOwnerPID = 0;
}
@@ -211,6 +218,7 @@ void CItem::AddFlag(long bit)
void CItem::UpdatePacket()
{
if(m_portCubeTemplate)return;
if(m_deferChestUpdate) return;
if (!m_pOwner || !m_pOwner->GetDesc())
return;
@@ -412,7 +420,17 @@ bool CItem::AddToCharacter(LPCHARACTER ch, TItemPos Cell)
if (ch->GetDesc())
m_dwLastOwnerPID = ch->GetPlayerID();
// AVA2 sash: a fresh sash gets the starting absorption of its grade
PortCubeInitNewAttach();
event_cancel(&m_pkDestroyEvent);
ch->SetItem(TItemPos(window_type, pos), this);
m_pOwner = ch;
Save();
return true;
}
void CItem::PortCubeInitNewAttach()
{
// Shared with the new Cube template factory; persisted restore skips this.
if (GetType() == ITEM_COSTUME && GetSubType() == COSTUME_SASH && GetSocket(SASH_ABSORPTION_SOCKET) == 0)
{
long lVal;
@@ -426,13 +444,22 @@ bool CItem::AddToCharacter(LPCHARACTER ch, TItemPos Cell)
SetSocket(SASH_ABSORPTION_SOCKET, lVal);
}
event_cancel(&m_pkDestroyEvent);
}
ch->SetItem(TItemPos(window_type, pos), this);
m_pOwner = ch;
Save();
return true;
bool CItem::PortCubeRestoreMetadata(const PortEconomy::Reward& r)
{
if(!m_portCubeTemplate||m_pOwner||GetSectree()||r.id!=GetID()||r.vnum!=GetOriginalVnum()||
!r.count||r.count>ITEM_MAX_COUNT||(!IsStackable()&&r.count!=1))return false;
m_dwCount=r.count;
for(unsigned i=0;i<3;++i)m_alSockets[i]=r.sockets[i];
for(unsigned i=0;i<7;++i){m_aAttr[i].bType=r.types[i];m_aAttr[i].sValue=r.values[i];}
static_assert(sizeof(m_portExtra)==sizeof(r.extra),"exact restored extra metadata");
std::memcpy(&m_portExtra,r.extra,sizeof(r.extra));return true;
}
void CItem::PortCubeAttachRestored(LPCHARACTER owner,WORD cell)
{
m_pOwner=owner;m_dwLastOwnerPID=owner->GetPlayerID();m_wCell=cell;
m_bWindow=INVENTORY;m_portCubeTemplate=false;m_bSkipSave=true;
}
LPITEM CItem::RemoveFromGround()
@@ -1254,12 +1281,19 @@ void CItem::SetExchanging(bool bOn)
void CItem::Save()
{
// Unowned factory metadata is not an actor mutation or a delayed save.
if(m_portCubeTemplate)return;
// Mutation notification is not a veto: preserve the original save/expiry.
if(GetOwner())PortCubeAssetMutation(GetOwner(),PortCube::ItemWrite);
else PortCubeAssetMutationByPID(GetLastOwnerPID(),PortCube::ItemWrite);
if (m_bSkipSave)
return;
ITEM_MANAGER::instance().DelayedSave(this);
}
#include "port_cube_item.inc"
bool CItem::CreateSocket(BYTE bSlot, BYTE bGold)
{
assert(bSlot < ITEM_SOCKET_MAX_NUM);
@@ -1294,7 +1328,7 @@ void CItem::SetSocket(int i, long v, bool bLog)
m_alSockets[i] = v;
UpdatePacket();
Save();
if (bLog)
if (bLog && !m_portCubeTemplate)
LogManager::instance().ItemLog(i, v, 0, GetID(), "SET_SOCKET", "", "", GetOriginalVnum());
}
@@ -1645,7 +1679,7 @@ void CItem::SetTimerBasedOnWearExpireEvent(LPEVENT pkEvent)
EVENTFUNC(real_time_expire_event)
{
const item_vid_event_info* info = reinterpret_cast<const item_vid_event_info*>(event->info);
const item_vid_event_info* info = dynamic_cast<const item_vid_event_info*>(event->info); // PORT: prepared clock info is a checked subtype.
if (NULL == info)
return 0;
@@ -2262,6 +2296,8 @@ int CItem::GetLevelLimit()
return 0;
}
#include "port_cube_lifecycle.inc"
bool CItem::OnAfterCreatedItem()
{
// 아이템을 한 번이라도 사용했다면, 그 이후엔 사용 중이지 않아도 시간이 차감되는 방식
@@ -2394,6 +2430,11 @@ void PortItemExtraSend(CHARACTER* owner,CItem* item,BYTE window,WORD cell)
if(!owner || !item || !owner->GetDesc())return;
const char* version=strstr(owner->GetDesc()->GetClientVersion(),"mt");
if(!version || atoi(version+2)<20261022)return;
if(atoi(version+2)>=20261025) {
PortCubeView::Writer w;w.n(93,1);w.n(88,4);w.n(12,1);w.n(window,1);w.n(cell,2);w.n(item->GetVnum(),4);w.n(item->GetID(),4);w.n(item->GetCount(),2);
static_assert(sizeof(item->GetPortExtra())==69,"full count companion extra");w.bytes.append(reinterpret_cast<const char*>(&item->GetPortExtra()),69);
owner->GetDesc()->Packet(w.bytes.data(),w.bytes.size());return;
}
#pragma pack(push,1)
struct Packet { uint8_t header;uint32_t size;uint8_t op,window;uint16_t cell;uint32_t vnum,id;PortItemExtra extra; };
#pragma pack(pop)
+13
View File
@@ -2,6 +2,7 @@
#define __INC_METIN_II_GAME_ITEM_H__
#include "entity.h"
namespace PortEconomy {struct Reward;}
class CItem : public CEntity
{
@@ -150,6 +151,17 @@ class CItem : public CEntity
void SetSkipSave(bool b) { m_bSkipSave = b; }
bool GetSkipSave() { return m_bSkipSave; }
bool PortCubeIsTemplate() const { return m_portCubeTemplate; }
void PortCubeMarkTemplate() { m_portCubeTemplate=true; m_bSkipSave=true; }
void PortCubeInitNewAttach();
bool PortCubeRestoreMetadata(const PortEconomy::Reward&);
void PortCubeAttachRestored(LPCHARACTER,WORD);
bool PortCubeHasPendingMutation() const;
unsigned PortCubeRestoreEventMask();
bool PortCubeRestoreEligible(bool savingEnabled=false);
bool PortCubeRestoreEventsReady(bool savingEnabled=false);
bool PortCubePrepareRestoreEvents();
void PortCubeCancelRestoreEvents();
bool IsOwnership(LPCHARACTER ch);
void SetOwnership(LPCHARACTER ch, int iSec = 10);
@@ -327,6 +339,7 @@ class CItem : public CEntity
bool m_bSkipSave;
bool m_deferChestUpdate = false;
bool m_portCubeTemplate = false;
bool m_isLocked;
+2 -2
View File
@@ -332,7 +332,7 @@ void CItem::SetAttribute(int i, BYTE bType, short sValue)
UpdatePacket();
Save();
if (bType)
if (bType && !PortCubeIsTemplate())
{
const char * pszIP = NULL;
@@ -361,7 +361,7 @@ void CItem::SetForceAttribute(int i, BYTE bType, short sValue)
UpdatePacket();
Save();
if (bType)
if (bType && !PortCubeIsTemplate())
{
const char * pszIP = NULL;
+24 -11
View File
@@ -17,6 +17,7 @@
#include "locale_service.h"
#include "item.h"
#include "item_manager.h"
#include "port_cube_factory.h"
#include "mob_manager.h"
#include "port_calendar_runtime.h"
@@ -148,6 +149,11 @@ bool ITEM_MANAGER::Initialize(TItemTable * table, int size)
LPITEM ITEM_MANAGER::CreateItem(DWORD vnum, DWORD count, DWORD id, bool bTryMagic, int iRarePct, bool bSkipSave)
{
PortCubeFactorySlot* cubeSlot=PortCubeCurrentFactorySlot();
if(cubeSlot) {
if(cubeSlot->entered||!cubeSlot->id||cubeSlot->vnum!=vnum||id!=(cubeSlot->restoring?cubeSlot->id:0)||count!=cubeSlot->count||bTryMagic||!bSkipSave)return NULL;
cubeSlot->entered=true;
}
if (0 == vnum)
return NULL;
@@ -188,9 +194,11 @@ LPITEM ITEM_MANAGER::CreateItem(DWORD vnum, DWORD count, DWORD id, bool bTryMagi
LPITEM item = NULL;
//id로 검사해서 존재한다면 -- 리턴!
if (m_map_pkItemByID.find(id) != m_map_pkItemByID.end())
const DWORD lookupID=cubeSlot?cubeSlot->id:id;
if (m_map_pkItemByID.find(lookupID) != m_map_pkItemByID.end() &&
!(cubeSlot&&cubeSlot->restoring&&cubeSlot->replacement==m_map_pkItemByID.find(lookupID)->second))
{
item = m_map_pkItemByID[id];
item = m_map_pkItemByID[lookupID];
LPCHARACTER owner = item->GetOwner();
sys_err("ITEM_ID_DUP: %u %s owner %p", id, item->GetName(), get_pointer(owner));
return NULL;
@@ -207,6 +215,7 @@ LPITEM ITEM_MANAGER::CreateItem(DWORD vnum, DWORD count, DWORD id, bool bTryMagi
//초기화 하고. 테이블 셋하고
item->Initialize();
if(cubeSlot){cubeSlot->item=item;item->PortCubeMarkTemplate();}
item->SetProto(table);
item->SetMaskVnum(dwMaskVnum);
@@ -221,7 +230,7 @@ LPITEM ITEM_MANAGER::CreateItem(DWORD vnum, DWORD count, DWORD id, bool bTryMagi
}
else
{
item->SetID(GetNewID());
item->SetID(cubeSlot?cubeSlot->id:GetNewID());
if (item->GetType() == ITEM_UNIQUE) // 유니크 아이템은 생성시에 소켓에 남은시간을 기록한다.
{
@@ -273,7 +282,7 @@ LPITEM ITEM_MANAGER::CreateItem(DWORD vnum, DWORD count, DWORD id, bool bTryMagi
else
count = 1;
item->SetVID(++m_dwVIDCount);
if(!cubeSlot)item->SetVID(++m_dwVIDCount);
if (bSkipSave == false)
m_VIDMap.insert(ITEM_VID_MAP::value_type(item->GetVID(), item));
@@ -284,9 +293,9 @@ LPITEM ITEM_MANAGER::CreateItem(DWORD vnum, DWORD count, DWORD id, bool bTryMagi
if (!item->SetCount(count))
return NULL;
item->SetSkipSave(false);
if(!cubeSlot)item->SetSkipSave(false);
if (item->GetType() == ITEM_UNIQUE && item->GetValue(2) != 0)
if (!cubeSlot && item->GetType() == ITEM_UNIQUE && item->GetValue(2) != 0)
item->StartUniqueExpireEvent();
for (int i=0 ; i < ITEM_LIMIT_MAX_NUM ; i++)
@@ -303,7 +312,7 @@ LPITEM ITEM_MANAGER::CreateItem(DWORD vnum, DWORD count, DWORD id, bool bTryMagi
item->SetSocket(0, time(0) + 60*60*24*7);
}
item->StartRealTimeExpireEvent();
if(!cubeSlot)item->StartRealTimeExpireEvent();
}
// 기존 유니크 아이템처럼 착용시에만 사용가능 시간이 차감되는 방식
@@ -313,7 +322,7 @@ LPITEM ITEM_MANAGER::CreateItem(DWORD vnum, DWORD count, DWORD id, bool bTryMagi
// 아이템몰로 지급하는 경우에는 이 로직에 들어오기 전에 Socket0 값이 세팅이 되어 있어야 한다.
if (true == item->IsEquipped())
{
item->StartTimerBasedOnWearExpireEvent();
if(!cubeSlot)item->StartTimerBasedOnWearExpireEvent();
}
else if(0 == id)
{
@@ -439,6 +448,7 @@ void ITEM_MANAGER::FlushDelayedSave(LPITEM item)
void ITEM_MANAGER::SaveSingleItem(LPITEM item)
{
if(!item||item->PortCubeIsTemplate())return;
if (!item->GetOwner())
{
DWORD dwID = item->GetID();
@@ -551,7 +561,7 @@ void ITEM_MANAGER::DestroyItem(LPITEM item, const char* file, size_t line)
DWORD dwID = item->GetID();
sys_log(2, "ITEM_DESTROY %s:%u", item->GetName(), dwID);
if (!item->GetSkipSave() && dwID)
if (!item->PortCubeIsTemplate() && !item->GetSkipSave() && dwID)
{
DWORD dwOwnerID = item->GetLastOwnerPID();
@@ -564,10 +574,10 @@ void ITEM_MANAGER::DestroyItem(LPITEM item, const char* file, size_t line)
sys_log(2, "ITEM_DESTROY_SKIP %s:%u (skip=%d)", item->GetName(), dwID, item->GetSkipSave());
}
if (dwID)
if (dwID && !item->PortCubeIsTemplate())
m_map_pkItemByID.erase(dwID);
m_VIDMap.erase(item->GetVID());
if(!item->PortCubeIsTemplate())m_VIDMap.erase(item->GetVID());
#ifdef M2_USE_POOL
pool_.Destroy(item);
@@ -1801,3 +1811,6 @@ void ITEM_MANAGER::CopyAllAttrTo(LPITEM pkOldItem, LPITEM pkNewItem)
}
#include "port_wiki_queries.inc"
#include "port_cube_flush.inc"
#include "port_cube_registry.inc"
+2
View File
@@ -390,6 +390,7 @@ class ITEM_MANAGER : public singleton<ITEM_MANAGER>
void GracefulShutdown();
DWORD GetNewID();
bool PortCubeSwapRegistry(const std::vector<LPITEM>& before,const std::vector<LPITEM>& after);
bool SetMaxItemID(TItemIDRangeTable range); // 최대 고유 아이디를 지정
bool SetMaxSpareItemID(TItemIDRangeTable range);
@@ -399,6 +400,7 @@ class ITEM_MANAGER : public singleton<ITEM_MANAGER>
void DelayedSave(LPITEM item);
void FlushDelayedSave(LPITEM item); // Delayed 리스트에 있다면 지우고 저장한다. 끊김 처리시 사용 됨.
void SaveSingleItem(LPITEM item);
void FlushDelayedSaveForPlayer(DWORD pid);
LPITEM CreateItem(DWORD vnum, DWORD count = 1, DWORD dwID = 0, bool bTryMagic = false, int iRarePct = -1, bool bSkipSave = false);
#ifndef DEBUG_ALLOC
@@ -2,6 +2,32 @@
#include "stdafx.h"
#include "desc_client.h"
#include "item_manager.h"
#include "port_cube_ids.h"
#include "../../common/cube_item_ids.h"
namespace {
// A synchronous, non-reentrant bridge into the existing member's private ID
// cursor. No callbacks/event dispatch occur before this scope is cleared.
struct CubeIDRequest {
unsigned count;
std::vector<uint32_t> ids;
};
CubeIDRequest* cubeIDRequest=nullptr;
struct CubeIDScope {
explicit CubeIDScope(CubeIDRequest& request){cubeIDRequest=&request;}
~CubeIDScope(){cubeIDRequest=nullptr;}
};
}
bool PortCubeReserveItemIDs(unsigned count,std::vector<uint32_t>& ids)
{
if(!count||count>100||cubeIDRequest)return false;
CubeIDRequest request{count,{}};
CubeIDScope scope(request);
if(!ITEM_MANAGER::instance().GetNewID()||request.ids.size()!=count)return false;
ids.swap(request.ids);
return true;
}
int touch(const char *path)
{
@@ -19,6 +45,28 @@ int touch(const char *path)
DWORD ITEM_MANAGER::GetNewID()
{
if(cubeIDRequest)
{
PortCube::ItemIDPlan plan;
const PortCube::ItemIDRange active{m_ItemIDRange.dwMin,m_ItemIDRange.dwMax,m_ItemIDRange.dwUsableItemIDMin};
const PortCube::ItemIDRange spare{m_ItemIDSpareRange.dwMin,m_ItemIDSpareRange.dwMax,m_ItemIDSpareRange.dwUsableItemIDMin};
if(!PortCube::PlanItemIDs(active,m_dwCurrentID,spare,cubeIDRequest->count,plan))return 0;
for(auto id:plan.ids)if(m_map_pkItemByID.find(id)!=m_map_pkItemByID.end())return 0;
if(plan.spare&&!db_clientdesc)return 0;
const DWORD oldMaximum=m_ItemIDRange.dwMax;
if(plan.spare)
{
m_ItemIDRange=m_ItemIDSpareRange;
m_ItemIDSpareRange.dwMin=0;
m_ItemIDSpareRange.dwMax=0;
m_ItemIDSpareRange.dwUsableItemIDMin=0;
}
m_dwCurrentID=plan.next;
cubeIDRequest->ids.swap(plan.ids);
// The reservation is already consumed before requesting another spare.
if(plan.spare)db_clientdesc->DBPacket(HEADER_GD_REQ_SPARE_ITEM_ID_RANGE,0,&oldMaximum,sizeof(DWORD));
return cubeIDRequest->ids.front();
}
assert(m_dwCurrentID != 0);
if ( m_dwCurrentID >= m_ItemIDRange.dwMax )
+4
View File
@@ -1,5 +1,7 @@
#include "stdafx.h"
#include "new_mob_timer.h"
#include "port_cube_actor.h"
#include "port_cube_recovery.h"
#include "constants.h"
#include "config.h"
#include "event.h"
@@ -970,6 +972,8 @@ int idle()
t = get_dword_time();
CHARACTER_MANAGER::instance().Update(thecore_heart->pulse);
PortCubeActorTick();
PortCubeRecoveryTick();
db_clientdesc->Update(t);
s_dwProfiler[PROF_CHR_UPDATE] += (get_dword_time() - t);
+419
View File
@@ -0,0 +1,419 @@
#include "stdafx.h"
#include "port_cube_actor.h"
#include "port_cube_factory.h"
#include "port_cube_apply.h"
#include "port_cube_publish.h"
#include "port_cube_restore.h"
#include "../../common/cube_handshake.h"
#include "../../common/cube_craft.h"
#include "../../common/cube_live_image.h"
#include "../../common/cube_gold_outbox.h"
#include "char.h"
#include "char_manager.h"
#include "desc.h"
#include "desc_client.h"
#include "desc_manager.h"
#include "item.h"
#include "item_manager.h"
#include "questmanager.h"
#include "questpc.h"
#include "port_switchbot.h"
#include "config.h"
#include <map>
#include <set>
#include <ctime>
namespace {
struct Snapshot {std::string seal;std::vector<PortCube::Item> ordinary;std::vector<LPITEM> items;};
struct Owner {uint32_t vid=0,handle=0;PortCube::Batch batch;PortCube::ActorHandshake flow;std::string seal;uint64_t next=0;PortCube::CraftFlow craft;bool frozen=false;PortCube::LiveImageFlow image;std::string appliedSeal;std::array<PortCubeView::Quickslot,PortCubeView::Quickslots> quickslots={};bool quickslotsCaptured=false,published=false;PortCubeRestorePlan restore;PortCube::LiveReleaseFlow release;};
std::map<uint32_t,Owner> owners;
PortCube::GoldOutbox goldOutbox;
bool goldOpened=false;
std::set<uint32_t> uncertainGround;
bool goldReady() {
if(!goldOpened){goldOpened=true;if(!goldOutbox.Open("cube-gold-outbox/journal"))sys_err("CUBE_GOLD: %s",goldOutbox.Error().c_str());}
return goldOutbox.Ready();
}
std::string goldEvent() {
unsigned char random[16];const int fd=open("/dev/urandom",O_RDONLY);if(fd<0)return {};
size_t at=0;while(at<sizeof(random)){const auto n=read(fd,random+at,sizeof(random)-at);if(n<0&&errno==EINTR)continue;if(n<=0){close(fd);return {};}at+=size_t(n);}close(fd);
const auto event=PortEconomy::Hex(random,sizeof(random));return PortCube::Identity(event)?event:std::string{};
}
PortCube::Handshake goldFrame(const PortCube::GoldDelivery& d) {
PortCube::Handshake f;f.message=PortCube::Message::GoldEnqueue;f.account=d.intent.account;f.player=d.intent.player;f.epoch=d.intent.epoch;
f.owner=d.intent.owner;f.token=d.intent.request;f.cookie=d.cookie;f.session=d.session;f.body=PortCube::EncodeGoldIntent(d.intent);return f;
}
PortCube::Handshake goldCloseFrame(const PortCube::GoldSourceSeal& s) {
PortCube::Handshake f;f.message=PortCube::Message::GoldClose;f.account=s.account;f.player=s.player;f.epoch=s.epoch;
f.owner=s.owner;f.token=s.request;f.cookie=s.cookie;f.session=s.session;f.body=PortCube::EncodeGoldManifest(s.events);return f;
}
bool capture(LPCHARACTER ch,Snapshot& out) {
if(!ch||ch->GetGold()<0)return false;
std::map<uint32_t,LPITEM> seen;PortCube::Writer seal;seal.n(uint64_t(ch->GetGold()),8);
auto window=[&](unsigned type,unsigned count)->bool {
for(unsigned cell=0;cell<count;++cell) {
auto* item=ch->GetItem(TItemPos(type,cell));if(!item)continue;
if(!item->GetID()||item->GetOwner()!=ch||seen.size()>=4096)return false;
auto previous=seen.find(item->GetID());if(previous!=seen.end()){if(previous->second!=item)return false;continue;}seen[item->GetID()]=item;
PortCube::Item image;image.cell=item->GetCell();image.value.id=item->GetID();image.value.vnum=item->GetOriginalVnum();image.value.count=item->GetCount();
image.usable=!item->isLocked()&&!item->IsExchanging()&&!item->IsEquipped();
for(unsigned j=0;j<3;++j){const auto n=item->GetSocket(j);if(n<INT32_MIN||n>INT32_MAX)return false;image.value.sockets[j]=int32_t(n);}
for(unsigned j=0;j<7;++j){image.value.types[j]=item->GetAttributes()[j].bType;image.value.values[j]=item->GetAttributes()[j].sValue;}
static_assert(sizeof(item->GetPortExtra())==69,"exact Cube extra metadata");std::memcpy(image.value.extra,&item->GetPortExtra(),69);
seal.n(item->GetWindow(),1);seal.n(image.cell,2);seal.n(image.usable,1);seal.reward(image.value);
if(item->GetWindow()==INVENTORY&&image.cell<INVENTORY_MAX_NUM)out.ordinary.push_back(image);
out.items.push_back(item);
}return true;
};
if(!window(INVENTORY,INVENTORY_AND_EQUIP_SLOT_MAX)||!window(DRAGON_SOUL_INVENTORY,DRAGON_SOUL_INVENTORY_MAX_NUM)||!window(SWITCHBOT,SWITCHBOT_SLOT_COUNT))return false;
#ifdef ENABLE_SPECIAL_STORAGE
for(unsigned type=UPGRADE_INVENTORY;type<=COSTUME_INVENTORY;++type)if(!window(type,SPECIAL_INVENTORY_MAX_NUM))return false;
#endif
std::sort(out.ordinary.begin(),out.ordinary.end(),[](const auto& a,const auto& b){return a.cell<b.cell;});out.seal=std::move(seal.data);return true;
}
bool matches(LPCHARACTER ch,const Owner& o) {
return ch&&uint32_t(ch->GetVID())==o.vid&&ch->GetDesc()&&ch->GetDesc()->GetHandle()==o.handle&&
ch->GetDesc()->GetAccountTable().id==o.batch.account&&ch->GetPlayerID()==o.batch.player;
}
bool connected(){return db_clientdesc&&db_clientdesc->IsPhase(PHASE_DBCLIENT);}
void send(const Owner& o,const PortCube::Handshake& f) {
const auto bytes=PortCube::EncodeHandshake(f);if(connected()&&!bytes.empty())db_clientdesc->DBPacket(PortCube::HandshakeHeader,o.handle,bytes.data(),bytes.size());
}
bool applyImage(LPCHARACTER ch,Owner& o) {
if(!PortCube::HandshakeEnabled||!PortCube::ActorMutationAuditComplete||!matches(ch,o)||!connected()||
!o.frozen||!o.flow.Submitted()||o.flow.Invalidated()||o.craft.State()!=PortCube::CraftFlow::Complete||o.image.State()!=PortCube::LiveImageFlow::Ready)return false;
try {
Snapshot before;if(!capture(ch,before)||before.seal!=o.seal)return false;
auto lookup=[](uint32_t v){const auto* p=ITEM_MANAGER::instance().GetTable(v);return p?PortCube::Proto{unsigned(p->bSize),bool(p->dwFlags&ITEM_FLAG_STACKABLE)}:PortCube::Proto{};};
PortCube::InventoryImage image;if(!PortCube::DecodeInventoryImage(o.image.Image(),image,lookup))return false;
// Preserve every non-ordinary window byte from the original full seal.
PortCube::Reader old(before.seal);old.n(8);std::string other;unsigned count=0;
while(old.ok&&old.at<old.data.size()) {
if(++count>4096)return false;const auto start=old.at;
const auto window=old.n(1),cell=old.n(2);old.n(1);old.reward();if(!old.ok)return false;
if(window!=INVENTORY||cell>=INVENTORY_MAX_NUM)other+=old.data.substr(start,old.at-start);
}
if(!old.ok)return false;
PortCube::Writer expected;expected.n(image.gold,8);
for(const auto& item:image.items){expected.n(INVENTORY,1);expected.n(item.cell,2);expected.n(1,1);expected.reward(item.value);}
expected.data+=other;
std::array<PortCubeView::Quickslot,PortCubeView::Quickslots> slots={};
for(unsigned n=0;n<slots.size();++n){TQuickslot* slot=nullptr;if(!ch->GetQuickslot(n,&slot)||!slot||slot->type>3||(!slot->type&&slot->pos))return false;slots[n]={slot->type,slot->pos};}
if(!PortCubeInstallAuthoritative(ch,image))return false;
Snapshot after;if(!capture(ch,after)||after.seal!=expected.data)return false;
PortCube::InventoryImage readback;readback.gold=ch->GetGold();readback.items=after.ordinary;
if(!o.image.MarkApplied(PortCube::EncodeInventoryImage(readback)))return false;
o.appliedSeal=std::move(after.seal);o.quickslots=slots;o.quickslotsCaptured=true;return true;
} catch(...) {return false;}
}
bool prepareImageAck(LPCHARACTER ch,Owner& o) {
if(!PortCube::HandshakeEnabled||!PortCube::ActorMutationAuditComplete||!matches(ch,o)||!connected()||
!o.frozen||!o.flow.Submitted()||o.flow.Invalidated()||o.craft.State()!=PortCube::CraftFlow::Complete||
(o.image.State()!=PortCube::LiveImageFlow::Applied&&!o.image.MayAcknowledge()))return false;
try {
Snapshot current;PortCube::InventoryImage readback;
if(o.appliedSeal.empty()||!capture(ch,current)||current.seal!=o.appliedSeal)return false;
readback.gold=ch->GetGold();readback.items=current.ordinary;
const auto bytes=PortCube::EncodeInventoryImage(readback);
return bytes==o.image.Image()&&(o.image.MayAcknowledge()||o.image.BeginAcknowledge(bytes));
} catch(...) {return false;}
}
bool releaseReady(LPCHARACTER ch,const Owner& o) {
if(!PortCube::HandshakeEnabled||!PortCube::ActorMutationAuditComplete||!matches(ch,o)||!connected()||
!o.frozen||!o.flow.Submitted()||o.flow.Invalidated()||o.craft.State()!=PortCube::CraftFlow::Complete||
o.image.State()!=PortCube::LiveImageFlow::Acknowledged||!o.quickslotsCaptured||!o.published||
!o.restore.Prepared()||o.restore.Enabled())return false;
try {
Snapshot current;PortCube::InventoryImage readback;
if(o.appliedSeal.empty()||!capture(ch,current)||current.seal!=o.appliedSeal||!PortCubeRestoredInventoryReady(ch,o.restore))return false;
readback.gold=ch->GetGold();readback.items=current.ordinary;
if(PortCube::EncodeInventoryImage(readback)!=o.image.Image())return false;
// The all-window asset seal does not include shortcuts. Rebuild the
// published identity plan separately; do not send another view packet.
std::vector<PortCubeView::Item> before;PortCubeView::Frame after;after.epoch=o.batch.epoch;after.gold=readback.gold;
for(const auto& i:o.batch.inventory){PortCubeView::Item row;row.cell=i.cell;row.id=i.value.id;before.push_back(row);}
for(const auto& i:readback.items){PortCubeView::Item row;row.cell=i.cell;row.id=i.value.id;row.vnum=i.value.vnum;row.count=i.value.count;after.items.push_back(row);}
std::array<PortCubeView::Quickslot,PortCubeView::Quickslots> expected;
if(!PortCubeView::Rebind(before,after,o.quickslots,expected))return false;
for(unsigned n=0;n<expected.size();++n){TQuickslot* slot=nullptr;if(!ch->GetQuickslot(n,&slot)||!slot||!(PortCubeView::Quickslot{slot->type,slot->pos}==expected[n]))return false;}
return true;
} catch(...) {return false;}
}
bool acceptRelease(LPCHARACTER ch,Owner& o,const PortCube::Handshake& f) {
if(!releaseReady(ch,o)){o.release.Invalidate();return false;}
return o.release.Answer(f); // terminal SQL proof only; no save-enable/thaw
}
}
PortCubeGoldPickup PortCubeDeferGroundGold(CHARACTER* ch,CItem* item) {
// Check quarantine before actor ownership: another player must not collect
// a pile whose source write may already be durable. No automatic timeout.
if(!ch||!item||uncertainGround.count(uint32_t(item->GetVID())))return PortCubeGoldPickup::Blocked;
auto found=owners.find(ch->GetPlayerID());
if(found==owners.end()||!found->second.flow.BlocksActions())return PortCubeGoldPickup::Ordinary;
const auto& o=found->second;const auto& arm=o.flow.IdentityFrame();
if(!PortCube::HandshakeEnabled||!PortCube::ActorMutationAuditComplete||!matches(ch,o)||!o.flow.Submitted()||!arm.cookie||
ch->GetParty()||ch->IsObserverMode()||ch->IsWarping()||ch->IsDead()||ch->IsStun()||item->GetType()!=ITEM_ELK||!item->GetSectree()||
!item->DistanceValid(ch)||!item->IsOwnership(ch)||!item->GetCount()||ch->GetMapIndex()<=0||!goldReady())return PortCubeGoldPickup::Blocked;
if(goldOutbox.IsClosing(o.batch.token))return PortCubeGoldPickup::Blocked;
const auto total=goldOutbox.Total(o.batch.token),amount=uint64_t(item->GetCount());
// Conservative pre-craft headroom; never spend a not-yet-confirmed fee twice.
if(o.batch.gold>uint64_t(PortEconomy::GoldLimit)-total||amount>uint64_t(PortEconomy::GoldLimit)-total-o.batch.gold)return PortCubeGoldPickup::Blocked;
PortCube::GoldDelivery d;d.intent.account=o.batch.account;d.intent.player=o.batch.player;d.intent.epoch=o.batch.epoch;
d.intent.owner=o.batch.owner;d.intent.request=o.batch.token;d.intent.sequence=goldOutbox.Next(o.batch.token);d.intent.amount=amount;d.intent.source=1;d.intent.event=goldEvent();
d.session=arm.session;d.cookie=arm.cookie;d.handle=o.handle;d.ground=uint32_t(item->GetVID());d.vnum=item->GetOriginalVnum();d.map=uint32_t(ch->GetMapIndex());
if(PortCube::EncodeGoldDelivery(d).empty())return PortCubeGoldPickup::Blocked;
uncertainGround.insert(d.ground);
if(!goldOutbox.Claim(d)) {
if(goldOutbox.Ready())uncertainGround.erase(d.ground); // pure refusal, no ambiguous write
sys_err("CUBE_GOLD: source held pid=%u vid=%u: %s",d.intent.player,d.ground,goldOutbox.Error().c_str());return PortCubeGoldPickup::Blocked;
}
uncertainGround.erase(d.ground);
// Caller now removes this exact pile synchronously, but MUST NOT GiveGold.
// A process crash before removal loses the ephemeral pile, not this intent.
return PortCubeGoldPickup::Deferred;
}
bool PortCubeBegin(CHARACTER* ch,const PortCube::Batch& b,uint64_t session) {
// Preparation is implemented, NOT a claim of full mutation quiescence.
// Do not expose a client command or bypass either gate to test on real assets.
if(!PortCube::HandshakeEnabled||!PortCube::ActorMutationAuditComplete)return false;
if(*get_table_postfix()||!ch||!ch->IsPC()||!ch->GetDesc()||!PortCubePresentationSupported(ch)||!connected()||!ch->IsItemLoaded()||!PortCubeRecipeAllowed(ch,b.recipe)||
ch->GetPlayerID()!=b.player||ch->GetDesc()->GetAccountTable().id!=b.account||owners.count(b.player)||owners.size()>=128||!PortCube::Validate(b))return false;
auto* pc=quest::CQuestManager::instance().PortCubeFindPC(b.player);
if(!pc||!pc->IsLoaded()||pc->IsRunning()||ch->IsWarping()||ch->IsDead()||ch->IsStun()||ch->GetExchange()||ch->GetShop()||ch->GetMyShop()||
ch->IsOpenSafebox()||ch->GetMall()||ch->IsSashWindowOpen()||ch->DragonSoul_RefineWindow_GetOpener())return false;
if(PortCubeAdmission(ch))return false;
Snapshot snapshot;if(!capture(ch,snapshot)||uint64_t(ch->GetGold())!=b.gold)return false;
for(auto* item:snapshot.items)if(item->PortCubeHasPendingMutation()||item->isLocked()||item->IsExchanging()||item->GetSkipSave())return false;
PortCube::Writer actual,wanted;actual.items(snapshot.ordinary);wanted.items(b.inventory);if(actual.data!=wanted.data)return false;
Owner owner;owner.vid=ch->GetVID();owner.handle=ch->GetDesc()->GetHandle();owner.batch=b;owner.seal=snapshot.seal;
if(!owner.flow.Start(b,session,time(nullptr),PortCube::ActorMutationAuditComplete))return false;
owners.emplace(b.player,std::move(owner));send(owners.at(b.player),owners.at(b.player).flow.IdentityFrame());return true;
}
bool PortCubeStart(CHARACTER* ch,unsigned recipeId,const std::string& revision,unsigned attempts) {
if(!PortCube::HandshakeEnabled||!PortCube::ActorMutationAuditComplete)return false;
if(*get_table_postfix()||!ch||!ch->IsPC()||!ch->GetDesc()||!PortCubePresentationSupported(ch)||
!connected()||!ch->IsItemLoaded()||!attempts||attempts>PortCube::MaxAttempts)return false;
auto previous=owners.find(ch->GetPlayerID());
if(previous!=owners.end()) {
// A repeated action can only refer to the immutable original batch.
// It does not re-run the factory, draw another outcome, or send Arm
// after Submit. The existing owner Tick handles transport retries.
const auto& o=previous->second;
return matches(ch,o)&&o.flow.BlocksActions()&&!o.flow.Invalidated()&&
o.batch.recipe.id==recipeId&&PortCube::Revision(o.batch.recipe)==revision&&o.batch.attempts==attempts;
}
if(owners.size()>=128||PortCubeAdmission(ch)||ch->GetExchange()||ch->GetShop()||ch->GetMyShop()||
ch->IsOpenSafebox()||ch->GetMall()||ch->IsSashWindowOpen()||ch->DragonSoul_RefineWindow_GetOpener())return false;
PortCube::Batch batch;
if(!PortCubeResolveRecipe(ch,recipeId,revision,batch.recipe))return false;
Snapshot snapshot;if(!capture(ch,snapshot))return false;
for(auto* item:snapshot.items)if(item->PortCubeHasPendingMutation()||item->isLocked()||item->IsExchanging()||item->GetSkipSave())return false;
batch.account=ch->GetDesc()->GetAccountTable().id;batch.player=ch->GetPlayerID();
batch.gold=uint64_t(ch->GetGold());batch.attempts=attempts;batch.inventory=snapshot.ordinary;
std::vector<PortCube::Input> inputs;
for(const auto& i:batch.inventory)inputs.push_back({i.value.id,i.value.vnum,i.value.count,i.cell,i.usable});
const auto preview=PortCube::Preview(batch.recipe,attempts,inputs,ch->GetGold());
if(!batch.account||batch.gold>uint64_t(PortEconomy::GoldLimit)||!preview.valid||!preview.materialsOK||!preview.goldOK)return false;
batch.owner=goldEvent();batch.token=goldEvent();const auto nonce=goldEvent();
if(!PortCube::Identity(batch.owner)||!PortCube::Identity(batch.token)||!PortCube::Identity(nonce))return false;
const uint64_t session=std::stoull(nonce.substr(0,16),nullptr,16);if(!session)return false;
// DB still enforces epoch > the previous RELEASED fence. Clock rollback
// across cores/restarts can refuse a new batch, never supersede a hold.
timespec now{};if(clock_gettime(CLOCK_REALTIME,&now)||now.tv_sec<0||now.tv_nsec<0||now.tv_nsec>=1000000000L||
uint64_t(now.tv_sec)>(uint64_t(INT64_MAX)-uint64_t(now.tv_nsec))/1000000000ULL)return false;
static uint64_t lastEpoch=0;
const auto candidate=uint64_t(now.tv_sec)*1000000000ULL+uint64_t(now.tv_nsec);
if(lastEpoch>=uint64_t(INT64_MAX))return false;
batch.epoch=std::max(candidate,lastEpoch+1);lastEpoch=batch.epoch;
const auto maximum=uint64_t(batch.recipe.rewardCount)*attempts;
const auto slots=batch.recipe.stackable?(maximum+1999)/2000:maximum;
if(!slots||slots>100||!PortCubeBuildRewardTemplates(batch.recipe.reward,unsigned(slots),batch.rewards))return false;
const auto lookup=[](uint32_t vnum)->PortCube::Proto {
const auto* table=ITEM_MANAGER::instance().GetTable(vnum);
return table?PortCube::Proto{table->bSize,(table->dwFlags&ITEM_FLAG_STACKABLE)!=0}:PortCube::Proto{};
};
// All-success is the maximum physically possible output for percent>0.
// A zero-percent recipe has no possible awards but still pays its costs.
if(PortCube::SettlePlan(batch,std::string(attempts,'\1'),lookup).result!="ok")return false;
return PortCubeBegin(ch,batch,session); // rechecks canonical recipe and live snapshot
}
bool PortCubeActorHeld(const CHARACTER* ch) {
if(!ch)return false;auto it=owners.find(ch->GetPlayerID());return it!=owners.end()&&uint32_t(ch->GetVID())==it->second.vid&&it->second.flow.BlocksActions();
}
void PortCubeAssetMutation(CHARACTER* ch,uint32_t reason) {
if(!ch||!reason)return;auto it=owners.find(ch->GetPlayerID());
if(it!=owners.end()&&uint32_t(ch->GetVID())==it->second.vid)it->second.flow.Invalidate(reason);
}
void PortCubeAssetMutationByPID(uint32_t pid,uint32_t reason) {
if(!pid||!reason||!owners.count(pid))return;
PortCubeAssetMutation(CHARACTER_MANAGER::instance().FindByPID(pid),reason);
}
uint32_t PortCubeAdmission(CHARACTER* ch) {
using namespace PortCube;
if(!ch||!ch->IsPC()||!ch->GetDesc()||!ch->IsItemLoaded())return MissingState;
uint32_t hazards=0;auto* pc=quest::CQuestManager::instance().PortCubeFindPC(ch->GetPlayerID());
if(!pc||!pc->IsLoaded())hazards|=MissingState;
else {if(pc->IsRunning())hazards|=QuestRunning;if(pc->PortCubeHasTimers())hazards|=QuestTimer;}
if(ch->GetParty())hazards|=Party;
if(ch->GetVictim())hazards|=Combat;
if(ch->IsWarping()||ch->IsDead()||ch->IsStun())hazards|=LifeCycle;
for(unsigned slot=0;slot<SWITCHBOT_SLOT_COUNT_REAL;++slot)if(CSwitchbotManager::instance().IsActive(ch->GetPlayerID(),slot))hazards|=Switcher;
Snapshot snapshot;if(!capture(ch,snapshot))return hazards|MissingState;
for(auto* item:snapshot.items) {
if(item->PortCubeHasPendingMutation())hazards|=ItemClock;
if(item->isLocked()||item->IsExchanging()||item->GetSkipSave())hazards|=ItemBusy;
}
return hazards;
}
void PortCubeActorForget(CHARACTER* ch) {
if(!ch)return;auto it=owners.find(ch->GetPlayerID());if(it==owners.end()||uint32_t(ch->GetVID())!=it->second.vid)return;
// Never let a reused player ID/VID adopt this in-memory session. DB keeps
// any durable hold; new-owner recovery is a separate, still-required path.
it->second.flow.LostTransport();owners.erase(it);
}
void PortCubeActorReply(unsigned handle,const char* data,size_t size) {
PortCube::Handshake f;if(!PortCube::DecodeHandshake(data,size,f))return;
if(f.message==PortCube::Message::GoldCloseAck) {
if(!PortCube::HandshakeEnabled||!PortCube::ActorMutationAuditComplete||!connected()||!goldReady())return;
PortCube::GoldSourceSeal seal;seal.account=f.account;seal.player=f.player;seal.epoch=f.epoch;seal.owner=f.owner;seal.request=f.token;
seal.session=f.session;seal.cookie=f.cookie;seal.handle=handle;if(!PortCube::DecodeGoldManifest(f.body,seal.events))return;
if(!goldOutbox.AcknowledgeSource(seal))sys_err("CUBE_GOLD: close ACK held: %s",goldOutbox.Error().c_str());
return; // durable closure is not an authority-image ACK or thaw
}
if(f.message==PortCube::Message::GoldAck) {
if(!PortCube::HandshakeEnabled||!PortCube::ActorMutationAuditComplete||!connected()||!goldReady())return;
PortCube::GoldIntent i;if(!PortCube::DecodeGoldIntent(f.body,i))return;
const auto* d=goldOutbox.Find(i.event);
if(!d||d->handle!=handle||d->cookie!=f.cookie||d->session!=f.session||PortCube::EncodeGoldIntent(d->intent)!=f.body)return;
if(!goldOutbox.Acknowledge(*d))sys_err("CUBE_GOLD: ACK held: %s",goldOutbox.Error().c_str());
return; // never feed an intent ACK into the actor thaw state machine
}
if(f.message!=PortCube::Message::Answer&&f.message!=PortCube::Message::CraftAnswer&&f.message!=PortCube::Message::LiveImageAnswer&&f.message!=PortCube::Message::LiveImageAckAnswer&&f.message!=PortCube::Message::LiveReleaseAnswer)return;
auto it=owners.find(f.player);if(it==owners.end()||it->second.handle!=handle)return;auto& o=it->second;
auto* desc=DESC_MANAGER::instance().FindByHandle(handle);auto* ch=desc?desc->GetCharacter():nullptr;
if(!matches(ch,o)||!connected()){o.flow.LostTransport();o.craft.Invalidate();o.image.Invalidate();o.release.Invalidate();return;}
if(f.message==PortCube::Message::LiveReleaseAnswer){acceptRelease(ch,o,f);return;}
if(f.message==PortCube::Message::LiveImageAckAnswer) {
if(!PortCube::HandshakeEnabled||!PortCube::ActorMutationAuditComplete||o.flow.Invalidated()){o.image.Invalidate();return;}
if(o.image.MayAcknowledge()&&!prepareImageAck(ch,o)){o.image.Invalidate();return;}
if(o.frozen)o.image.Answer(f);
return; // durable ACK is not a thaw authorization
}
if(f.message==PortCube::Message::LiveImageAnswer) {
if(!PortCube::HandshakeEnabled||!PortCube::ActorMutationAuditComplete||o.flow.Invalidated()){o.image.Invalidate();return;}
if(o.image.Answer(f)&&o.image.State()==PortCube::LiveImageFlow::Ready&&!applyImage(ch,o))o.image.Invalidate();
return; // applied only to the still-held original actor; no ACK or thaw
}
if(f.message==PortCube::Message::CraftAnswer) {
if(!PortCube::HandshakeEnabled||!PortCube::ActorMutationAuditComplete||o.flow.Invalidated()){o.craft.Invalidate();return;}
auto lookup=[](uint32_t v){const auto* p=ITEM_MANAGER::instance().GetTable(v);return p?PortCube::Proto{unsigned(p->bSize),bool(p->dwFlags&ITEM_FLAG_STACKABLE)}:PortCube::Proto{};};
if(o.craft.Answer(f,o.batch,lookup)&&o.craft.MayRetry()&&f.status==PortCube::Status::Prepared)o.next=0;
if(o.craft.State()==PortCube::CraftFlow::Held)o.image.Invalidate();
return; // receipt is not a local asset update, resync ACK or thaw
}
const auto now=uint64_t(time(nullptr));
if(o.flow.Armed(f,now)) {
Snapshot before;
if(o.flow.Invalidated()||PortCubeAdmission(ch)||!capture(ch,before)||before.seal!=o.seal){o.flow.Invalidate(PortCube::ContextChanged);if(o.flow.Cancel())send(o,o.flow.Request(PortCube::Message::Cancel));return;}
// Final ordinary saves follow the Arm ACK, BEFORE Submit/DRAINING. Force
// every owned item, not just dirty normal inventory; include detached
// pending destroy snapshots so a later heartbeat cannot cross the fence.
if(!CHARACTER_MANAGER::instance().FlushDelayedSave(ch))ch->SaveReal();
ITEM_MANAGER::instance().FlushDelayedSaveForPlayer(f.player);
for(auto* item:before.items)ITEM_MANAGER::instance().SaveSingleItem(item);
Snapshot after;
if(o.flow.Invalidated()||PortCubeAdmission(ch)||!capture(ch,after)||after.seal!=o.seal){o.flow.Invalidate(PortCube::ContextChanged);if(o.flow.Cancel())send(o,o.flow.Request(PortCube::Message::Cancel));return;}
if(o.flow.Submit(true,now))send(o,o.flow.Request(PortCube::Message::Submit));
return;
}
if(o.flow.Answer(f)) {
o.frozen=f.status==PortCube::Status::Frozen;
if(o.flow.State()==PortCube::ActorHandshake::Idle){owners.erase(it);return;}
if(f.status==PortCube::Status::Frozen&&o.flow.Submitted()&&PortCube::HandshakeEnabled&&PortCube::ActorMutationAuditComplete&&goldReady()) {
const auto& arm=o.flow.IdentityFrame();const auto binding=PortCube::GoldSourceFor(o.batch,arm.session,arm.cookie,o.handle);
if(!goldOutbox.CloseSource(binding))sys_err("CUBE_GOLD: cannot close source: %s",goldOutbox.Error().c_str());
}
}
}
void PortCubeActorTick() {
const auto now=uint64_t(time(nullptr));
if(PortCube::HandshakeEnabled&&PortCube::ActorMutationAuditComplete&&connected()&&goldReady()) {
static uint64_t next=0;static size_t cursor=0;
if(now>=next) {
next=now+3;std::vector<std::pair<unsigned,PortCube::Handshake>> pending;
for(const auto& d:goldOutbox.Pending())pending.emplace_back(d.handle,goldFrame(d));
for(const auto& s:goldOutbox.PendingSources())pending.emplace_back(s.handle,goldCloseFrame(s));
for(size_t n=0;n<std::min(size_t(2),pending.size());++n) {
const auto& job=pending[cursor++%pending.size()];const auto bytes=PortCube::EncodeHandshake(job.second);
if(!bytes.empty())db_clientdesc->DBPacket(PortCube::HandshakeHeader,job.first,bytes.data(),bytes.size());
}
}
}
std::vector<uint32_t> craftReady;static uint32_t craftCursor=0;
for(auto& entry:owners) {
auto& o=entry.second;auto* ch=CHARACTER_MANAGER::instance().FindByPID(entry.first);
if(!matches(ch,o)||!connected()){o.flow.LostTransport();o.craft.Invalidate();o.image.Invalidate();o.release.Invalidate();continue;}
if(o.flow.Invalidated()){o.craft.Invalidate();o.image.Invalidate();o.release.Invalidate();}
if(o.flow.State()==PortCube::ActorHandshake::WaitArm) {
Snapshot current;
if(PortCubeAdmission(ch)||!capture(ch,current)||current.seal!=o.seal)o.flow.Invalidate(PortCube::ContextChanged);
if(o.flow.Invalidated()&&o.flow.IdentityFrame().cookie)o.flow.Cancel();
}
o.flow.TimedOut(now);if(o.next>now)continue;
const auto& arm=o.flow.IdentityFrame();
if(PortCube::HandshakeEnabled&&PortCube::ActorMutationAuditComplete&&o.frozen&&o.flow.Submitted()&&!o.flow.Invalidated()&&goldReady()) {
if(o.craft.State()==PortCube::CraftFlow::Idle)o.craft.Start(o.flow.Request(PortCube::Message::Poll),true,goldOutbox.SourceAcknowledged(PortCube::GoldSourceFor(o.batch,arm.session,arm.cookie,o.handle)));
if(o.craft.MayRetry()){craftReady.push_back(entry.first);continue;}
if(o.craft.State()==PortCube::CraftFlow::Complete) {
if(o.image.State()==PortCube::LiveImageFlow::Idle&&o.craft.Receipt().result=="ok") {
auto lookup=[](uint32_t v){const auto* p=ITEM_MANAGER::instance().GetTable(v);return p?PortCube::Proto{unsigned(p->bSize),bool(p->dwFlags&ITEM_FLAG_STACKABLE)}:PortCube::Proto{};};
if(!o.image.Start(o.flow.Request(PortCube::Message::Poll),o.batch,o.craft.Receipt(),goldOutbox.Total(o.batch.token),lookup,goldOutbox.SourceAcknowledged(PortCube::GoldSourceFor(o.batch,arm.session,arm.cookie,o.handle))))o.image.Invalidate();
}
if(o.image.State()==PortCube::LiveImageFlow::Applied||o.image.MayAcknowledge()) {
// Recheck full actor data on every ACK retry, not only at
// initial installation. Failure stays held, never unlocks.
if(!prepareImageAck(ch,o))o.image.Invalidate();
}
if(o.image.MayRetry()||o.image.MayAcknowledge())craftReady.push_back(entry.first);
else if(o.image.State()==PortCube::LiveImageFlow::Acknowledged&&o.quickslotsCaptured&&(!o.published||!o.restore.Prepared()))craftReady.push_back(entry.first);
else if(o.image.State()==PortCube::LiveImageFlow::Acknowledged&&(o.release.State()==PortCube::LiveReleaseFlow::Idle||o.release.MayRetry()))craftReady.push_back(entry.first);
continue;
}
}
o.next=now+2;
if(!arm.cookie&&o.flow.State()==PortCube::ActorHandshake::WaitArm)send(o,arm);
else if(arm.cookie)send(o,o.flow.Request(o.flow.State()==PortCube::ActorHandshake::WaitCancel?PortCube::Message::Cancel:
o.flow.Submitted()&&o.flow.Invalidated()?PortCube::Message::Invalidate:
o.flow.State()==PortCube::ActorHandshake::WaitDrain?PortCube::Message::Submit:PortCube::Message::Poll));
}
const auto offset=size_t(std::upper_bound(craftReady.begin(),craftReady.end(),craftCursor)-craftReady.begin());
for(size_t n=0;n<craftReady.size()&&n<2;++n){
const auto pid=craftReady[(offset+n)%craftReady.size()];craftCursor=pid;auto& o=owners.at(pid);o.next=now+2;
if(o.image.State()==PortCube::LiveImageFlow::Acknowledged&&o.published&&o.restore.Prepared()) {
auto* ch=CHARACTER_MANAGER::instance().FindByPID(pid);
try {
if(!releaseReady(ch,o)){o.release.Invalidate();continue;}
if(o.release.State()==PortCube::LiveReleaseFlow::Idle&&!o.release.Start(o.image,true)){o.release.Invalidate();continue;}
if(o.release.MayRetry())send(o,o.release.Request());
} catch(...) {o.release.Invalidate();}
continue; // SQL release is not DB resume or actor thaw
}
if(o.image.State()==PortCube::LiveImageFlow::Acknowledged&&(!o.published||!o.restore.Prepared())) {
auto* ch=CHARACTER_MANAGER::instance().FindByPID(pid);
try {
Snapshot before,after;
if(!matches(ch,o)||!capture(ch,before)||before.seal!=o.appliedSeal)o.image.Invalidate();
else if(!o.published) {
if(!PortCubePublishAuthoritative(ch,o.batch,o.image.Image(),o.quickslots)||!capture(ch,after)||after.seal!=o.appliedSeal)o.image.Invalidate();
else o.published=true;
} else if(!PortCubePrepareRestoredInventory(ch,o.restore)||!capture(ch,after)||after.seal!=o.appliedSeal)o.image.Invalidate();
} catch(...) {o.image.Invalidate();}
continue; // publication/event preparation is not release, save-enable or thaw
}
send(o,o.image.MayAcknowledge()?o.image.Acknowledgement():o.image.MayRetry()?o.image.Request():o.craft.Request());
}
}
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <string>
class CHARACTER;
class CItem;
namespace PortCube {struct Batch;struct Recipe;}
enum class PortCubeGoldPickup { Ordinary,Deferred,Blocked };
PortCubeGoldPickup PortCubeDeferGroundGold(CHARACTER*,CItem*);
bool PortCubeRecipeAllowed(CHARACTER*,const PortCube::Recipe&);
bool PortCubeResolveRecipe(CHARACTER*,unsigned id,const std::string& revision,PortCube::Recipe&);
// Internal trusted construction only; both hard gates still apply. Callers
// supply no identity, gold, inventory, RNG outcomes, IDs or reward metadata.
bool PortCubeStart(CHARACTER*,unsigned recipe,const std::string& revision,unsigned attempts);
bool PortCubeBegin(CHARACTER*,const PortCube::Batch&,uint64_t session);
bool PortCubeActorHeld(const CHARACTER*);
uint32_t PortCubeAdmission(CHARACTER*);
void PortCubeAssetMutation(CHARACTER*,uint32_t reason);
void PortCubeAssetMutationByPID(uint32_t pid,uint32_t reason);
void PortCubeActorForget(CHARACTER*);
void PortCubeActorTick();
void PortCubeActorReply(unsigned handle,const char*,size_t);
+63
View File
@@ -0,0 +1,63 @@
#include "stdafx.h"
#include "char.h"
#include "item.h"
#include "item_manager.h"
#include "port_cube_actor.h"
#include "port_cube_apply.h"
#include "port_cube_factory.h"
#include "../../common/cube_image.h"
#include "utils.h"
bool CHARACTER::PortCubeInstallImage(const PortCube::InventoryImage& image,const std::vector<LPITEM>& before,const std::vector<LPITEM>& restored)
{
static_assert(INVENTORY_MAX_NUM==225,"Cube normal inventory contract");
if(!PortCubeActorHeld(this)||image.items.size()!=restored.size()||image.gold>uint64_t(PortEconomy::GoldLimit))return false;
size_t next=0;std::array<WORD,225> grid={};
for(unsigned cell=0;cell<225;++cell)if(auto* item=m_pointsInstant.pItems[cell]) {
if(next>=before.size()||before[next++]!=item||item->GetCell()!=cell||item->GetWindow()!=INVENTORY||
item->GetOwner()!=this||item->isLocked()||item->IsExchanging()||item->GetSkipSave()||item->PortCubeHasPendingMutation())return false;
}
if(next!=before.size())return false;
for(size_t i=0;i<restored.size();++i) {
auto* item=restored[i];const auto& row=image.items[i];
if(!item||!item->PortCubeIsTemplate()||item->GetOwner()||item->GetSectree()||item->IsDragonSoul()||
item->GetID()!=row.value.id||item->GetOriginalVnum()!=row.value.vnum||item->GetCount()!=row.value.count||
row.cell>=225||item->GetSize()<1||item->GetSize()>3||(row.cell%45)/5+item->GetSize()>9)return false;
for(unsigned n=0;n<item->GetSize();++n){const auto at=row.cell+5*n;if(at>=225||grid[at])return false;grid[at]=row.cell+1;}
}
if(!ITEM_MANAGER::instance().PortCubeSwapRegistry(before,restored))return false;
// These are logical selections, not owned inventory windows. Rebind only
// references to replaced ordinary objects by permanent ID; consumed items
// become null. Do this before retiring any old object.
auto remap=[&](LPITEM& selected){if(selected)for(auto* item:before)if(selected==item){selected=ITEM_MANAGER::instance().Find(item->GetID());break;}};
for(auto& selected:m_pointsInstant.pCubeItems)remap(selected);
for(auto& selected:m_pointsInstant.pSashMaterials)remap(selected);
remap(m_pQuestItem);
for(unsigned cell=0;cell<225;++cell){m_pointsInstant.pItems[cell]=nullptr;m_pointsInstant.bItemGrid[cell]=grid[cell];}
for(auto* item:before){item->SetCell(nullptr,0);item->SetWindow(RESERVED_WINDOW);item->PortCubeMarkTemplate();}
for(size_t i=0;i<restored.size();++i){const auto cell=image.items[i].cell;m_pointsInstant.pItems[cell]=restored[i];restored[i]->PortCubeAttachRestored(this,cell);}
SetGold(int64_t(image.gold));return true;
}
bool PortCubeInstallAuthoritative(CHARACTER* ch,const PortCube::InventoryImage& image)
{
if(!ch||!PortCubeActorHeld(ch))return false;
auto lookup=[](uint32_t v){const auto* p=ITEM_MANAGER::instance().GetTable(v);return p?PortCube::Proto{unsigned(p->bSize),bool(p->dwFlags&ITEM_FLAG_STACKABLE)}:PortCube::Proto{};};
struct Stage {std::vector<LPITEM> items;bool installed=false;~Stage(){if(!installed)for(auto* item:items)M2_DESTROY_ITEM(item);}} stage;
std::vector<LPITEM> before;
try {
PortCube::InventoryImage checked;if(!PortCube::DecodeInventoryImage(PortCube::EncodeInventoryImage(image),checked,lookup))return false;
before.reserve(225);stage.items.reserve(image.items.size());
std::map<uint32_t,LPITEM> old;
for(unsigned cell=0;cell<225;++cell)if(auto* item=ch->GetInventoryItem(cell)){before.push_back(item);if(!old.emplace(item->GetID(),item).second)return false;}
for(const auto& row:image.items) {
const auto found=old.find(row.value.id);
auto* item=PortCubeRestoreItem(row.value,found==old.end()?nullptr:found->second);
if(!item)return false;stage.items.push_back(item);
}
if(!ch->PortCubeInstallImage(image,before,stage.items))return false;
stage.installed=true;
} catch(...) {return false;}
for(auto* item:before)M2_DESTROY_ITEM(item);
return true;
}
+5
View File
@@ -0,0 +1,5 @@
#pragma once
class CHARACTER;
namespace PortCube {struct InventoryImage;}
// Internal game-main-thread application; still no UI refresh, ACK or thaw.
bool PortCubeInstallAuthoritative(CHARACTER*,const PortCube::InventoryImage&);
+104
View File
@@ -0,0 +1,104 @@
// PORT: included by cube.cpp, using the SAME loaded recipes as classic Cube.
#include "../../common/cube_recipe.h"
#include "../../common/cube_batch.h"
#include <set>
#include <cstdlib>
static bool PortCubeContext(LPCHARACTER ch,unsigned npcRace)
{
if(!ch||!ch->IsPC()||!ch->GetDesc()||!ch->IsItemLoaded()||!ch->IsCubeOpen()||!ch->CanDoCube()||
ch->IsDead()||ch->IsStun()||ch->GetExchange()||ch->GetMyShop()||ch->GetShop()||ch->GetShopOwner()||
ch->IsOpenSafebox()||ch->GetMall())return false;
LPCHARACTER npc=ch->GetCubeNpc();
if(!npc||npc!=ch->GetQuestNPC()||npc->GetRaceNum()!=npcRace||npc->GetMapIndex()!=ch->GetMapIndex())return false;
const auto dx=std::llabs(int64_t(ch->GetX())-npc->GetX()),dy=std::llabs(int64_t(ch->GetY())-npc->GetY());
return dx<CUBE_MAX_DISTANCE&&dy<CUBE_MAX_DISTANCE&&DISTANCE_APPROX(int(dx),int(dy))<CUBE_MAX_DISTANCE;
}
static bool PortCubeRecipes(unsigned npc,std::vector<PortCube::Recipe>& recipes)
{
if(s_cube_proto.size()>PortCube::MaxRecipes)return false;
for(unsigned i=0;i<s_cube_proto.size();++i) {
const auto* src=s_cube_proto[i];
if(!src||std::find(src->npc_vnum.begin(),src->npc_vnum.end(),npc)==src->npc_vnum.end())continue;
if(src->reward.size()!=1||src->percent<0)return false;
const auto* reward=ITEM_MANAGER::instance().GetTable(src->reward[0].vnum);
if(!reward)return false;
PortCube::Recipe r;r.id=i+1;r.reward=src->reward[0].vnum;r.rewardCount=src->reward[0].count;
r.gold=src->gold;r.percent=src->percent;r.stackable=(reward->dwFlags&ITEM_FLAG_STACKABLE)!=0;
r.category=src->portCategory;r.copy=src->portCopy;
for(auto n:src->npc_vnum)r.npcs.push_back(n);
for(auto m:src->item){if(m.count<=0||!ITEM_MANAGER::instance().GetTable(m.vnum))return false;r.materials.push_back({m.vnum,unsigned(m.count)});}
if(!PortCube::Normalize(r))return false;
recipes.push_back(r);
}
return true;
}
bool PortCubeRecipeAllowed(LPCHARACTER ch,const PortCube::Recipe& recipe)
{
if(!ch||!ch->GetCubeNpc()||!PortCubeContext(ch,ch->GetCubeNpc()->GetRaceNum()))return false;
std::vector<PortCube::Recipe> recipes;
if(!PortCubeRecipes(ch->GetCubeNpc()->GetRaceNum(),recipes))return false;
for(const auto& current:recipes)if(current.id==recipe.id) {
PortCube::Batch expected,actual;expected.recipe=current;actual.recipe=recipe;
// Compare canonical bytes, not just the non-cryptographic UI fingerprint.
return !current.copy&&PortCube::Encode(expected)==PortCube::Encode(actual);
}
return false;
}
bool PortCubeResolveRecipe(LPCHARACTER ch,unsigned id,const std::string& revision,PortCube::Recipe& out)
{
if(!ch||!ch->GetCubeNpc()||!PortCubeContext(ch,ch->GetCubeNpc()->GetRaceNum()))return false;
std::vector<PortCube::Recipe> recipes;
if(!PortCubeRecipes(ch->GetCubeNpc()->GetRaceNum(),recipes))return false;
for(const auto& recipe:recipes)if(recipe.id==id&&!recipe.copy&&PortCube::Revision(recipe)==revision){out=recipe;return true;}
return false;
}
void PortCubeQuery(LPCHARACTER ch,unsigned request,unsigned subject,unsigned offset,bool check)
{
auto error=[&](const char* reason){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u %s",request,reason);};
LPCHARACTER npc=ch?ch->GetCubeNpc():NULL;
if(!ch)return;
if(!npc){error("cube_context");return;}
const unsigned race=npc->GetRaceNum();
if(!PortCubeContext(ch,race)||(!check&&subject!=race)){error("cube_context");return;}
std::vector<PortCube::Recipe> recipes;
if(!PortCubeRecipes(race,recipes)){error("cube_catalog_invalid");return;}
std::string all;for(const auto& r:recipes)all+=std::to_string(r.id)+":"+PortCube::Revision(r)+";";
const auto catalogRevision=PortCube::Fingerprint(all);
if(check) {
if(!offset||offset>PortCube::MaxAttempts){error("invalid");return;}
auto it=std::find_if(recipes.begin(),recipes.end(),[&](const auto& r){return r.id==subject;});
if(it==recipes.end()){error("cube_recipe_missing");return;}
std::vector<PortCube::Input> inputs;std::set<DWORD> seen;
for(unsigned cell=0;cell<INVENTORY_MAX_NUM;++cell) {
LPITEM item=ch->GetInventoryItem(cell);if(!item||!seen.insert(item->GetID()).second)continue;
inputs.push_back({item->GetID(),item->GetOriginalVnum(),item->GetCount(),static_cast<uint16_t>(cell),
!item->IsEquipped()&&!item->isLocked()&&!item->IsExchanging()&&item->GetOwner()==ch});
}
const auto plan=PortCube::Preview(*it,offset,inputs,ch->GetGold());
if(!plan.valid){error("cube_inventory_invalid");return;}
const auto revision=PortCube::Revision(*it);const auto version=std::stoull(revision,NULL,16);
std::vector<std::pair<std::string,int64_t>> values={{"revision_hi",version>>32},{"revision_lo",version&0xffffffffu},
{"attempts",offset},{"gold_required",plan.gold},{"gold_available",ch->GetGold()},
{"materials_ok",plan.materialsOK},{"gold_ok",plan.goldOK},{"mutation_enabled",0},
{"reward_maximum",plan.rewardMaximum},{"capacity_reserved",0},{"copy_required",it->copy}};
for(unsigned i=0;i<it->materials.size();++i) {
const auto n=std::to_string(i+1);values.push_back({"material"+n,it->materials[i].vnum});
values.push_back({"needed"+n,plan.needed[i]});values.push_back({"available"+n,plan.available[i]});
}
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 begin %u cubecheck %u %u %u 0 %lld",request,subject,offset,unsigned(values.size()),(long long)get_global_time());
for(unsigned i=0;i<values.size();++i)ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 stat %u %u %s %lld",request,i,values[i].first.c_str(),(long long)values[i].second);
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 end %u %u",request,unsigned(values.size()));return;
}
if(offset>recipes.size()){error("offset");return;}
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 begin %u cube %u %u %u 0 %lld",request,subject,offset,unsigned(recipes.size()),(long long)get_global_time());
unsigned sent=0;
for(unsigned i=offset;i<recipes.size()&&sent<8;++i,++sent) {
const auto& r=recipes[i];std::ostringstream row;
row<<"MTF1 recipe "<<request<<' '<<i<<' '<<r.id<<' '<<catalogRevision<<' '<<PortCube::Revision(r)<<' '<<r.reward<<' '<<r.rewardCount<<' '<<r.stackable<<' '<<r.gold<<' '<<r.percent<<' '<<r.copy<<' ';
static const char digits[]="0123456789abcdef";for(unsigned char c:r.category)row<<digits[c>>4]<<digits[c&15];
row<<' '<<r.materials.size();for(auto m:r.materials)row<<' '<<m.vnum<<' '<<m.count;
ch->ChatPacket(CHAT_TYPE_COMMAND,"%s",row.str().c_str());
}
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 end %u %u",request,sent);
}
+68
View File
@@ -0,0 +1,68 @@
#include "stdafx.h"
#include "port_cube_factory.h"
#include "port_cube_ids.h"
#include "char.h"
#include "item.h"
#include "item_manager.h"
#include "utils.h"
#include "unique_item.h"
#include "skill.h"
namespace {
PortCubeFactorySlot* activeSlot=nullptr;
struct SlotScope {
PortCubeFactorySlot& slot;
explicit SlotScope(PortCubeFactorySlot& value):slot(value){activeSlot=&slot;}
~SlotScope(){if(slot.item)M2_DESTROY_ITEM(slot.item);activeSlot=nullptr;}
};
}
PortCubeFactorySlot* PortCubeCurrentFactorySlot(){return activeSlot;}
bool PortCubeBuildRewardTemplates(uint32_t vnum,unsigned slots,
std::vector<PortEconomy::Reward>& out)
{
if(activeSlot||!vnum||!slots||slots>100)return false;
auto& manager=ITEM_MANAGER::instance();
const auto* proto=manager.GetTable(vnum);
if(!proto||proto->bType==ITEM_ELK)return false;
// The legacy skill-book initializer retries random candidates indefinitely.
// Refuse a broken/empty skill catalogue before burning IDs or allocating.
if(vnum==50300||vnum==ITEM_SKILLFORGET_VNUM||vnum==ITEM_SKILLFORGET2_VNUM) {
const unsigned first=vnum==ITEM_SKILLFORGET2_VNUM?112:1;
const unsigned last=vnum==ITEM_SKILLFORGET2_VNUM?119:111;
bool found=false;
for(unsigned skill=first;skill<=last;++skill)if(CSkillManager::instance().Get(skill)){found=true;break;}
if(!found)return false;
}
std::vector<uint32_t> ids;
if(!PortCubeReserveItemIDs(slots,ids))return false;
std::vector<PortEconomy::Reward> images;images.reserve(slots);
for(auto id:ids) {
PortCubeFactorySlot slot;slot.id=id;slot.vnum=vnum;SlotScope scope(slot);
// AVA2 WORLDARD's active factory uses the defaults, not TryMagic=true.
auto* item=manager.CreateItem(vnum,1,0,false,-1,true);
if(item)item->PortCubeInitNewAttach();
if(!item||item!=slot.item||!item->PortCubeIsTemplate()||
item->GetOwner()||item->GetSectree()||item->GetVID()||
!item->GetSkipSave()||item->GetID()!=id||
item->GetOriginalVnum()!=vnum||item->GetCount()!=1)return false;
PortEconomy::Reward image;image.id=id;image.vnum=vnum;image.count=1;
for(unsigned i=0;i<3;++i)image.sockets[i]=item->GetSocket(i);
for(unsigned i=0;i<7;++i){image.types[i]=item->GetAttributeType(i);image.values[i]=item->GetAttributeValue(i);}
static_assert(sizeof(item->GetPortExtra())==sizeof(image.extra),"full template extra metadata");
std::memcpy(image.extra,&item->GetPortExtra(),sizeof(image.extra));
images.push_back(image);
}
out.swap(images);return true;
}
CItem* PortCubeRestoreItem(const PortEconomy::Reward& image,CItem* replacement)
{
if(activeSlot||!image.id||!image.vnum||!image.count||image.count>2000)return nullptr;
PortCubeFactorySlot slot;slot.id=image.id;slot.vnum=image.vnum;slot.restoring=true;slot.count=image.count;slot.replacement=replacement;
SlotScope scope(slot);
auto* item=ITEM_MANAGER::instance().CreateItem(image.vnum,image.count,image.id,false,-1,true);
if(!item||item!=slot.item||!item->PortCubeIsTemplate()||item->GetOwner()||item->GetSectree()||item->GetVID()||
!item->GetSkipSave()||!item->PortCubeRestoreMetadata(image))return nullptr;
slot.item=nullptr;return item;
}
+24
View File
@@ -0,0 +1,24 @@
#pragma once
#include "../../common/economy.h"
#include <vector>
class CItem;
// Internal synchronous factory bridge, never a client packet or asset grant.
// CreateItem consumes this single-use slot while preserving new-item semantics.
struct PortCubeFactorySlot {
uint32_t id=0,vnum=0;
bool entered=false;
CItem* item=nullptr;
bool restoring=false;
uint32_t count=1;
CItem* replacement=nullptr;
};
PortCubeFactorySlot* PortCubeCurrentFactorySlot();
// Game-main-thread only; output unchanged on failure. Returns full immutable
// metadata initialized by the real modern-Cube CreateItem defaults, with count
// 1 (the settlement computes actual stack counts). IDs remain consumed even
// on failure. No item is registered, saved, delivered, or returned to callers.
bool PortCubeBuildRewardTemplates(uint32_t vnum,unsigned slots,
std::vector<PortEconomy::Reward>& out);
CItem* PortCubeRestoreItem(const PortEconomy::Reward&,CItem* replacement);
+13
View File
@@ -0,0 +1,13 @@
// Included in the original-encoding item_manager.cpp; no encoding rewrite.
void ITEM_MANAGER::FlushDelayedSaveForPlayer(DWORD pid)
{
// Cover dirty special bags and detached pending destroys too. Last-owner
// identity never authorizes flushing an item now owned by another player.
if(!pid)return;
for(auto it=m_set_pkItemForDelayedSave.begin();it!=m_set_pkItemForDelayedSave.end();) {
LPITEM item=*it;auto* owner=item->GetOwner();
if((owner&&owner->GetPlayerID()==pid)||(!owner&&item->GetLastOwnerPID()==pid)) {
it=m_set_pkItemForDelayedSave.erase(it);SaveSingleItem(item);
} else ++it;
}
}
+10
View File
@@ -0,0 +1,10 @@
#pragma once
#include <cstdint>
#include <vector>
// Game-main-thread only. Reserves 1..100 permanent IDs from ITEM_MANAGER's
// actual cursor. No item creation, DB row, asset write or permission to craft.
// Failure leaves both output and cursor unchanged; successful IDs are burned
// in this process even if the caller later abandons the batch. The Cube fence
// must durably reserve them before any Execute, recovery or external exposure.
bool PortCubeReserveItemIDs(unsigned count,std::vector<uint32_t>& ids);
+15
View File
@@ -0,0 +1,15 @@
// Read-only admission: never cancel/reset an expiry event to admit a batch.
bool CItem::PortCubeHasPendingMutation() const
{
if(!m_pProto||m_pkDestroyEvent||m_pkExpireEvent||m_pkUniqueExpireEvent||
m_pkTimerBasedOnWearExpireEvent||m_pkRealTimeExpireEvent||
m_pkAccessorySocketExpireEvent||m_pkOwnershipEvent)return true;
// Include not-yet-started first-use/wear clocks and unique items. This is a
// conservative candidate restriction, not a claim every unique item expires.
if(m_pProto->bType==ITEM_UNIQUE)return true;
for(unsigned i=0;i<ITEM_LIMIT_MAX_NUM;++i) {
const auto type=m_pProto->aLimits[i].bType;
if(type==LIMIT_REAL_TIME||type==LIMIT_REAL_TIME_START_FIRST_USE||type==LIMIT_TIMER_BASED_ON_WEAR)return true;
}
return false;
}
@@ -0,0 +1,86 @@
// Prepared events delegate to the original callbacks only after BOTH the
// actor hold and skip-save end. Preparation never resets persisted sockets.
namespace {
constexpr unsigned CubeRealClock=1,CubeUniqueClock=2;
struct CubeRealClockInfo: item_vid_event_info {DWORD id=0;};
struct CubeUniqueClockInfo: item_event_info {DWORD id=0,vid=0;bool first=true;};
bool cubeClockPaused(LPITEM item){return item->GetSkipSave()||(item->GetOwner()&&PortCubeActorHeld(item->GetOwner()));}
EVENTFUNC(cube_restored_real_event) {
auto* info=dynamic_cast<CubeRealClockInfo*>(event->info);if(!info)return 0;
auto* item=ITEM_MANAGER::instance().FindByVID(info->item_vid);
if(!item||item->GetID()!=info->id)return 0;
if(cubeClockPaused(item))return PASSES_PER_SEC(1);
return real_time_expire_event(event,processing_time);
}
EVENTFUNC(cube_restored_unique_event) {
auto* info=dynamic_cast<CubeUniqueClockInfo*>(event->info);
if(!info||!info->item||info->item->GetID()!=info->id||info->item->GetVID()!=info->vid)return 0;
auto* item=info->item;if(cubeClockPaused(item))return PASSES_PER_SEC(1);
if(info->first) {
info->first=false;
if(item->GetVnum()==UNIQUE_ITEM_HIDE_ALIGNMENT_TITLE&&item->GetOwner())item->GetOwner()->ShowAlignment(false);
item->SetSocket(ITEM_SOCKET_UNIQUE_SAVE_TIME,0);
}
return unique_expire_event(event,processing_time);
}
bool cubeQueued(const LPEVENT& e,TEVENTFUNC callback) {
return e&&e->func==callback&&e->info&&e->q_el&&!e->is_processing&&!e->is_force_to_end&&!e->q_el->bCancel;
}
}
unsigned CItem::PortCubeRestoreEventMask()
{
if(!m_pProto)return 0;unsigned mask=0;
for(unsigned n=0;n<ITEM_LIMIT_MAX_NUM;++n)if(m_pProto->aLimits[n].bType==LIMIT_REAL_TIME)mask|=CubeRealClock;
if(m_pProto->cLimitRealTimeFirstUseIndex!=-1&&GetSocket(1)!=0)mask|=CubeRealClock;
if(GetType()==ITEM_UNIQUE&&GetValue(2)!=0&&!IsRealTimeItem())mask|=CubeUniqueClock;
return mask;
}
bool CItem::PortCubeRestoreEligible(bool savingEnabled)
{
if(!m_pProto||m_portCubeTemplate||!m_pOwner||!m_dwID||!m_dwVID||m_bWindow!=INVENTORY||m_wCell>=INVENTORY_MAX_NUM||m_bEquipped||
m_bSkipSave==savingEnabled||isLocked()||IsExchanging()||GetSectree()||m_pkDestroyEvent||m_pkExpireEvent||m_pkTimerBasedOnWearExpireEvent||m_pkAccessorySocketExpireEvent||m_pkOwnershipEvent)return false;
const auto mask=PortCubeRestoreEventMask();
if(m_pkRealTimeExpireEvent&&(!(mask&CubeRealClock)||!cubeQueued(m_pkRealTimeExpireEvent,cube_restored_real_event)))return false;
if(m_pkUniqueExpireEvent&&(!(mask&CubeUniqueClock)||!cubeQueued(m_pkUniqueExpireEvent,cube_restored_unique_event)))return false;
return true;
}
bool CItem::PortCubeRestoreEventsReady(bool savingEnabled)
{
if(!PortCubeRestoreEligible(savingEnabled))return false;const auto mask=PortCubeRestoreEventMask();
if(mask&CubeRealClock) {
if(!cubeQueued(m_pkRealTimeExpireEvent,cube_restored_real_event))return false;
auto* info=dynamic_cast<CubeRealClockInfo*>(m_pkRealTimeExpireEvent->info);
if(!info||info->id!=GetID()||info->item_vid!=GetVID())return false;
}
if(mask&CubeUniqueClock) {
if(!cubeQueued(m_pkUniqueExpireEvent,cube_restored_unique_event))return false;
auto* info=dynamic_cast<CubeUniqueClockInfo*>(m_pkUniqueExpireEvent->info);
if(!info||info->item!=this||info->id!=GetID()||info->vid!=GetVID())return false;
}
return true;
}
void CItem::PortCubeCancelRestoreEvents()
{
if(m_pkRealTimeExpireEvent&&m_pkRealTimeExpireEvent->func==cube_restored_real_event)event_cancel(&m_pkRealTimeExpireEvent);
if(m_pkUniqueExpireEvent&&m_pkUniqueExpireEvent->func==cube_restored_unique_event)event_cancel(&m_pkUniqueExpireEvent);
}
bool CItem::PortCubePrepareRestoreEvents()
{
if(!PortCubeRestoreEligible()||!PortCubeActorHeld(GetOwner()))return false;
if(PortCubeRestoreEventsReady())return true;
try {
const auto mask=PortCubeRestoreEventMask();
if((mask&CubeRealClock)&&!m_pkRealTimeExpireEvent) {
std::unique_ptr<CubeRealClockInfo> info(AllocEventInfo<CubeRealClockInfo>());info->id=GetID();info->item_vid=GetVID();
m_pkRealTimeExpireEvent=event_create(cube_restored_real_event,info.release(),PASSES_PER_SEC(1));
}
if((mask&CubeUniqueClock)&&!m_pkUniqueExpireEvent) {
std::unique_ptr<CubeUniqueClockInfo> info(AllocEventInfo<CubeUniqueClockInfo>());info->item=this;info->id=GetID();info->vid=GetVID();
// Original first-check remainder, clamped BEFORE multiplication.
long seconds=GetSocket(ITEM_SOCKET_UNIQUE_SAVE_TIME);if(!seconds)seconds=60;seconds=std::max(0L,std::min(60L,seconds));
m_pkUniqueExpireEvent=event_create(cube_restored_unique_event,info.release(),PASSES_PER_SEC(seconds));
}
if(PortCubeRestoreEventsReady())return true;
PortCubeCancelRestoreEvents();return false;
} catch(...) {PortCubeCancelRestoreEvents();return false;}
}
+58
View File
@@ -0,0 +1,58 @@
#include "stdafx.h"
#include "char.h"
#include "item.h"
#include "item_manager.h"
#include "desc.h"
#include "port_cube_actor.h"
#include "port_cube_publish.h"
#include "../../common/cube_image.h"
#include <cstdlib>
bool PortCubePresentationSupported(CHARACTER* ch)
{
if(!ch||!ch->GetDesc()||!ch->GetDesc()->IsPhase(PHASE_GAME))return false;
const char* version=strstr(ch->GetDesc()->GetClientVersion(),"mt");return version&&atoi(version+2)>=20261025;
}
bool CHARACTER::PortCubePublishFrame(const PortCubeView::Frame& frame,const PortCubeView::Frame& original)
{
static_assert(QUICKSLOT_MAX_NUM==PortCubeView::Quickslots,"presentation quickslots");
if(!PortCubeActorHeld(this)||!PortCubePresentationSupported(this)||!PortCubeView::Valid(frame)||frame.gold!=uint64_t(GetGold()))return false;
unsigned row=0;
for(unsigned cell=0;cell<PortCubeView::Slots;++cell)if(auto* item=GetInventoryItem(cell)) {
if(row>=frame.items.size())return false;const auto& view=frame.items[row++];
if(view.cell!=cell||view.id!=item->GetID()||view.vnum!=item->GetVnum()||view.count!=item->GetCount()||
view.flags!=item->GetFlag()||view.anti!=item->GetAntiFlag()||item->GetOwner()!=this||item->GetWindow()!=INVENTORY||item->GetCell()!=cell||item->PortCubeIsTemplate())return false;
for(unsigned n=0;n<3;++n)if(view.sockets[n]!=item->GetSocket(n))return false;
for(unsigned n=0;n<7;++n)if(view.types[n]!=item->GetAttributes()[n].bType||view.values[n]!=item->GetAttributes()[n].sValue)return false;
if(std::memcmp(view.extra,&item->GetPortExtra(),69))return false;
}
if(row!=frame.items.size())return false;
bool old=true,published=true;
for(unsigned n=0;n<PortCubeView::Quickslots;++n) {
const PortCubeView::Quickslot current{m_quickslot[n].type,m_quickslot[n].pos};old=old&&(current==original.quickslots[n]);published=published&&(current==frame.quickslots[n]);
}
if(!old&&!published)return false;
const auto packet=PortCubeView::Packet(frame);if(packet.empty())return false; // all allocation before mutation/enqueue
for(unsigned n=0;n<PortCubeView::Quickslots;++n){m_quickslot[n].type=frame.quickslots[n].type;m_quickslot[n].pos=frame.quickslots[n].cell;}
GetDesc()->Packet(packet.data(),packet.size());return GetDesc()&&GetDesc()->IsPhase(PHASE_GAME);
}
bool PortCubePublishAuthoritative(CHARACTER* ch,const PortCube::Batch& batch,const std::string& bytes,const std::array<PortCubeView::Quickslot,PortCubeView::Quickslots>& slots)
{
if(!ch||!PortCubeActorHeld(ch))return false;
auto lookup=[](uint32_t v){const auto* p=ITEM_MANAGER::instance().GetTable(v);return p?PortCube::Proto{unsigned(p->bSize),bool(p->dwFlags&ITEM_FLAG_STACKABLE)}:PortCube::Proto{};};
PortCube::InventoryImage image;if(!PortCube::DecodeInventoryImage(bytes,image,lookup))return false;
PortCubeView::Frame frame,original;frame.epoch=batch.epoch;frame.gold=image.gold;original.quickslots=slots;
std::vector<PortCubeView::Item> before;
for(const auto& i:batch.inventory){PortCubeView::Item row;row.cell=i.cell;row.id=i.value.id;before.push_back(row);}
for(const auto& i:image.items) {
auto* item=ch->GetInventoryItem(i.cell);if(!item||item->GetID()!=i.value.id||item->GetOriginalVnum()!=i.value.vnum)return false;
PortCubeView::Item row;row.cell=i.cell;row.id=i.value.id;row.vnum=item->GetVnum();row.count=i.value.count;row.flags=item->GetFlag();row.anti=item->GetAntiFlag();
for(unsigned n=0;n<3;++n)row.sockets[n]=i.value.sockets[n];
for(unsigned n=0;n<7;++n){row.types[n]=i.value.types[n];row.values[n]=i.value.values[n];}
std::memcpy(row.extra,i.value.extra,69);frame.items.push_back(row);
}
if(!PortCubeView::Rebind(before,frame,slots,frame.quickslots))return false;
return ch->PortCubePublishFrame(frame,original);
}
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include "../../common/cube_presentation.h"
class CHARACTER;
namespace PortCube {struct Batch;}
bool PortCubePresentationSupported(CHARACTER*);
// A presentation enqueue, not a client ACK, event activation, release or thaw.
bool PortCubePublishAuthoritative(CHARACTER*,const PortCube::Batch&,const std::string&,const std::array<PortCubeView::Quickslot,PortCubeView::Quickslots>&);
+6
View File
@@ -0,0 +1,6 @@
#pragma once
#include "port_cube_actor.h"
#include "../../common/cube_mutation.h"
// Notify before running a script/changing a flag; do not suppress the script or
// postpone its timer. Preparation is cancelled/poisoned, not its legitimate work.
inline void PortCubeQuestMutation(unsigned pid) {PortCubeAssetMutationByPID(pid,PortCube::QuestWrite);}
@@ -0,0 +1,89 @@
#include "stdafx.h"
#include "port_cube_recovery.h"
#include "../../common/cube_recovery.h"
#include "desc.h"
#include "desc_client.h"
#include "desc_manager.h"
#include "config.h"
#include "item_manager.h"
#include <cerrno>
#include <fcntl.h>
#include <unistd.h>
#include <ctime>
#include <map>
namespace {
struct Pending {LPDESC desc=nullptr;unsigned handshake=0,index=0;PortCube::RecoveryFlow flow;std::time_t next=0;};
std::map<unsigned,Pending> pending;unsigned cursor=0;
bool enabled(){return PortCube::HandshakeEnabled&&PortCube::ActorMutationAuditComplete;}
bool connected(){return db_clientdesc&&db_clientdesc->IsPhase(PHASE_DBCLIENT);}
bool matches(unsigned handle,const Pending& p) {
auto* d=DESC_MANAGER::instance().FindByHandle(handle);const auto& f=p.flow.Request();
if(!d||d!=p.desc||d->GetHandshake()!=p.handshake||!d->IsPhase(PHASE_SELECT)||d->GetCharacter()||p.index>=PLAYER_PER_ACCOUNT)return false;
const auto& account=d->GetAccountTable();return account.id==f.account&&account.players[p.index].dwID==f.player&&!account.players[p.index].bChangeName;
}
uint64_t nonce() {
unsigned char bytes[8];const int fd=open("/dev/urandom",O_RDONLY);if(fd<0)return 0;size_t at=0;
while(at<sizeof(bytes)){const auto n=read(fd,bytes+at,sizeof(bytes)-at);if(n<0&&errno==EINTR)continue;if(n<=0){close(fd);return 0;}at+=size_t(n);}close(fd);
uint64_t value=0;for(unsigned n=0;n<8;++n)value|=uint64_t(bytes[n])<<(8*n);return value;
}
void send(unsigned handle,Pending& p) {
const auto bytes=PortCube::EncodeHandshake(p.flow.MayRequestImage()?p.flow.ImageRequest():p.flow.Request());
if(connected()&&!bytes.empty())db_clientdesc->DBPacket(PortCube::HandshakeHeader,handle,bytes.data(),bytes.size());
p.next=time(nullptr)+3;
}
}
bool PortCubeRecoverySelect(DESC* d,unsigned player,unsigned index) {
if(!enabled()||*get_table_postfix())return false; // unchanged classic path
if(!d||!d->GetHandle()||!d->IsPhase(PHASE_SELECT)||d->GetCharacter()||index>=PLAYER_PER_ACCOUNT||!player)return true;
const auto& account=d->GetAccountTable();if(!account.id||account.players[index].dwID!=player)return true;
auto found=pending.find(d->GetHandle());
if(found!=pending.end()) {
if(matches(found->first,found->second))return true; // no parallel selection/replacement
pending.erase(found); // old descriptor identity cannot adopt a new grant
}
if(!connected()||pending.size()>=128)return true;
const auto session=nonce();if(!session)return true;
for(const auto& entry:pending)if(entry.second.flow.Request().session==session)return true;
Pending p;p.desc=d;p.handshake=d->GetHandshake();p.index=index;
if(!p.flow.Start(account.id,player,session))return true;
auto inserted=pending.emplace(d->GetHandle(),std::move(p));send(inserted.first->first,inserted.first->second);return true;
}
void PortCubeRecoveryTick() {
if(!enabled())return;
std::vector<unsigned> ready;const auto now=time(nullptr);
for(auto it=pending.begin();it!=pending.end();) {
auto& p=it->second;
if(!matches(it->first,p)){it=pending.erase(it);continue;}
if(!connected())p.flow.LostTransport();
if((p.flow.MayRetry()||p.flow.MayRequestImage())&&p.next<=now)ready.push_back(it->first);++it;
}
const auto offset=size_t(std::upper_bound(ready.begin(),ready.end(),cursor)-ready.begin());
for(size_t n=0;n<ready.size()&&n<2;++n){const auto handle=ready[(offset+n)%ready.size()];cursor=handle;send(handle,pending.find(handle)->second);}
}
void PortCubeRecoveryReply(unsigned handle,const char* data,size_t size) {
if(!enabled()||!connected())return;PortCube::Handshake f;
if(!PortCube::DecodeHandshake(data,size,f)||(f.message!=PortCube::Message::RecoveryAnswer&&f.message!=PortCube::Message::RecoveryImageAnswer))return;
auto it=pending.find(handle);if(it==pending.end()||!matches(handle,it->second)||!it->second.flow.Answer(handle,f))return;
auto& p=it->second;
if(p.flow.State()==PortCube::RecoveryFlow::ImageReady) {
PortCube::InventoryImage image;
auto lookup=[](uint32_t v){const auto* item=ITEM_MANAGER::instance().GetTable(v);return item?PortCube::Proto{unsigned(item->bSize),bool(item->dwFlags&ITEM_FLAG_STACKABLE)}:PortCube::Proto{};};
if(!PortCube::DecodeInventoryImage(p.flow.Image(),image,lookup))p.flow.LostTransport();
return; // retain bytes only; no actor/item creation, currency mutation or ACK
}
if(p.flow.MayRequestImage()){if(f.message==PortCube::Message::RecoveryAnswer)p.next=0;return;}
if(!p.flow.TakeClear())return;
TPlayerLoadPacket load={};load.account_id=f.account;load.player_id=f.player;load.account_index=p.index;
// This is still a classic guarded load, NOT an image ACK or owner release.
db_clientdesc->DBPacket(HEADER_GD_PLAYER_LOAD,handle,&load,sizeof(load));
}
bool PortCubeRecoveryGrant(DESC* d,PortCube::OwnerGrant& grant) {
grant={};if(!enabled()||!connected()||!d)return false;auto it=pending.find(d->GetHandle());
if(it==pending.end()||!matches(it->first,it->second)||(it->second.flow.State()!=PortCube::RecoveryFlow::Granted&&it->second.flow.State()!=PortCube::RecoveryFlow::ImageReady))return false;
grant=it->second.flow.Grant();return true;
}
bool PortCubeRecoveryImage(DESC* d,PortCube::OwnerGrant& grant,std::string& image) {
image.clear();if(!PortCubeRecoveryGrant(d,grant))return false;auto it=pending.find(d->GetHandle());
if(it->second.flow.State()!=PortCube::RecoveryFlow::ImageReady){grant={};return false;}image=it->second.flow.Image();return true;
}
+10
View File
@@ -0,0 +1,10 @@
#pragma once
#include <cstddef>
#include <string>
class DESC;
namespace PortCube {struct OwnerGrant;}
bool PortCubeRecoverySelect(DESC*,unsigned player,unsigned index);
void PortCubeRecoveryTick();
void PortCubeRecoveryReply(unsigned handle,const char*,size_t);
bool PortCubeRecoveryGrant(DESC*,PortCube::OwnerGrant&);
bool PortCubeRecoveryImage(DESC*,PortCube::OwnerGrant&,std::string&);
@@ -0,0 +1,25 @@
// Main-thread only: allocate temporary map nodes before touching live pointers.
bool ITEM_MANAGER::PortCubeSwapRegistry(const std::vector<LPITEM>& before,const std::vector<LPITEM>& after)
{
if(before.size()>225||after.size()>225||after.size()>uint64_t(UINT32_MAX)-m_dwVIDCount)return false;
std::set<DWORD> oldIDs,oldVIDs;
ITEM_VID_MAP stagedVIDs;std::map<DWORD,LPITEM> stagedIDs;
try {
for(auto* item:before) {
if(!item||!item->GetID()||!item->GetVID()||item->PortCubeIsTemplate()||
!oldIDs.insert(item->GetID()).second||!oldVIDs.insert(item->GetVID()).second||
Find(item->GetID())!=item||FindByVID(item->GetVID())!=item)return false;
}
DWORD vid=m_dwVIDCount;
for(auto* item:after) {
if(!item||!item->GetID()||!item->PortCubeIsTemplate()||item->GetOwner()||item->GetSectree()||item->GetVID()||
(Find(item->GetID())&&!oldIDs.count(item->GetID()))||!stagedIDs.emplace(item->GetID(),item).second)return false;
if(!stagedVIDs.emplace(++vid,item).second||FindByVID(vid))return false;
}
} catch(...) {return false;}
// Compatible std::allocator nodes and integral std::less comparisons: node
// transfer below allocates nothing and invokes no actor/SQL/event callback.
for(auto* item:before){m_set_pkItemForDelayedSave.erase(item);m_map_pkItemByID.erase(item->GetID());m_VIDMap.erase(item->GetVID());}
for(const auto& entry:stagedVIDs)entry.second->SetVID(entry.first);
m_dwVIDCount+=after.size();m_map_pkItemByID.merge(stagedIDs);m_VIDMap.merge(stagedVIDs);return true;
}
+59
View File
@@ -0,0 +1,59 @@
#include "stdafx.h"
#include "char.h"
#include "item.h"
#include "item_manager.h"
#include "port_cube_actor.h"
#include "port_cube_restore.h"
namespace {
bool restoreMetadata(CItem* item,PortEconomy::Reward& image) {
image.id=item->GetID();image.vnum=item->GetOriginalVnum();image.count=item->GetCount();
if(!image.id||!image.vnum||!image.count||image.count>2000)return false;
for(unsigned n=0;n<3;++n){const auto value=item->GetSocket(n);if(value<INT32_MIN||value>INT32_MAX)return false;image.sockets[n]=int32_t(value);}
for(unsigned n=0;n<7;++n){image.types[n]=item->GetAttributeType(n);image.values[n]=item->GetAttributeValue(n);}
static_assert(sizeof(item->GetPortExtra())==69,"restore full metadata");std::memcpy(image.extra,&item->GetPortExtra(),69);return true;
}
bool sameRestore(const PortEconomy::Reward& a,const PortEconomy::Reward& b) {
if(a.id!=b.id||a.vnum!=b.vnum||a.count!=b.count||std::memcmp(a.extra,b.extra,69))return false;
for(unsigned n=0;n<3;++n)if(a.sockets[n]!=b.sockets[n])return false;
for(unsigned n=0;n<7;++n)if(a.types[n]!=b.types[n]||a.values[n]!=b.values[n])return false;return true;
}
}
bool PortCubeRestoredInventoryReady(CHARACTER* ch,const PortCubeRestorePlan& plan)
{
if(!ch||!PortCubeActorHeld(ch)||!plan.prepared||ch->GetPlayerID()!=plan.pid||uint32_t(ch->GetVID())!=plan.vid)return false;
unsigned next=0;
for(unsigned cell=0;cell<225;++cell)if(auto* item=ch->GetInventoryItem(cell)) {
if(next>=plan.items.size())return false;const auto& binding=plan.items[next++];
if(item!=binding.item||cell!=binding.cell||ITEM_MANAGER::instance().Find(binding.image.id)!=item||ITEM_MANAGER::instance().FindByVID(binding.vid)!=item||
item->GetVID()!=binding.vid||item->GetOwner()!=ch||item->GetCell()!=cell||!item->PortCubeRestoreEventsReady(plan.enabled))return false;
PortEconomy::Reward current;if(!restoreMetadata(item,current)||!sameRestore(binding.image,current))return false;
}
return next==plan.items.size();
}
bool PortCubePrepareRestoredInventory(CHARACTER* ch,PortCubeRestorePlan& plan)
{
if(!ch||!PortCubeActorHeld(ch))return false;
if(plan.prepared)return !plan.enabled&&PortCubeRestoredInventoryReady(ch,plan);
PortCubeRestorePlan stage;stage.pid=ch->GetPlayerID();stage.vid=ch->GetVID();
auto cancel=[&](){for(auto& b:stage.items)if(ITEM_MANAGER::instance().Find(b.image.id)==b.item&&ITEM_MANAGER::instance().FindByVID(b.vid)==b.item)b.item->PortCubeCancelRestoreEvents();};
try {
stage.items.reserve(225);
for(unsigned cell=0;cell<225;++cell)if(auto* item=ch->GetInventoryItem(cell)) {
PortCubeRestorePlan::Binding binding;binding.item=item;binding.vid=item->GetVID();binding.cell=cell;
if(item->GetOwner()!=ch||item->GetCell()!=cell||!item->PortCubeRestoreEligible()||!restoreMetadata(item,binding.image)||
ITEM_MANAGER::instance().Find(binding.image.id)!=item||ITEM_MANAGER::instance().FindByVID(binding.vid)!=item)return false;
stage.items.push_back(binding);
}
for(auto& b:stage.items)if(!b.item->PortCubePrepareRestoreEvents()){cancel();return false;}
stage.prepared=true;if(!PortCubeRestoredInventoryReady(ch,stage)){cancel();return false;}
plan=std::move(stage);return true;
} catch(...) {cancel();return false;}
}
bool PortCubeEnableRestoredInventory(CHARACTER* ch,PortCubeRestorePlan& plan)
{
if(!PortCubeRestoredInventoryReady(ch,plan))return false;
if(plan.enabled)return true;
// No allocation, callbacks, Save or packets after validation starts commit.
for(const auto& b:plan.items)b.item->SetSkipSave(false);
plan.enabled=true;return true;
}
+27
View File
@@ -0,0 +1,27 @@
#pragma once
#include "../../common/economy.h"
#include <vector>
class CHARACTER;
class CItem;
class PortCubeRestorePlan {
public:
PortCubeRestorePlan()=default;
PortCubeRestorePlan(const PortCubeRestorePlan&)=delete;
PortCubeRestorePlan& operator=(const PortCubeRestorePlan&)=delete;
PortCubeRestorePlan(PortCubeRestorePlan&&)=default;
PortCubeRestorePlan& operator=(PortCubeRestorePlan&&)=default;
bool Prepared()const{return prepared;}
bool Enabled()const{return enabled;}
private:
struct Binding {CItem* item=nullptr;uint32_t vid=0;uint16_t cell=0;PortEconomy::Reward image;};
uint32_t pid=0,vid=0;bool prepared=false,enabled=false;std::vector<Binding> items;
friend bool PortCubePrepareRestoredInventory(CHARACTER*,PortCubeRestorePlan&);
friend bool PortCubeRestoredInventoryReady(CHARACTER*,const PortCubeRestorePlan&);
friend bool PortCubeEnableRestoredInventory(CHARACTER*,PortCubeRestorePlan&);
};
// Preparation is safe while held; failure cancels only these prepared events.
bool PortCubePrepareRestoredInventory(CHARACTER*,PortCubeRestorePlan&);
bool PortCubeRestoredInventoryReady(CHARACTER*,const PortCubeRestorePlan&);
// Trusted final handoff primitive: caller MUST first authenticate DB resume.
// No runtime caller yet. Clears flags while still held; does not thaw or save.
bool PortCubeEnableRestoredInventory(CHARACTER*,PortCubeRestorePlan&);
+3 -1
View File
@@ -8,6 +8,7 @@ static void PortTrackTravel(LPCHARACTER ch,unsigned request,unsigned boss);
// Own-player read-only protocol v1. Capability bits: drops, chests, stats, reverse sources, dungeon snapshots; 256 = world bosses.
void PortBossQuery(LPCHARACTER ch,unsigned request);
static void PortRankQuery(LPCHARACTER ch,unsigned request,unsigned index);
void PortCubeQuery(LPCHARACTER ch,unsigned request,unsigned subject,unsigned offset,bool check);
static bool PortFeatureNumber(const std::string& text,unsigned& value) {
if (text.empty() || text.size()>10) return false;
unsigned long long result=0;
@@ -47,7 +48,7 @@ ACMD(do_port_features) {
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u rate",request);return;
}
ch->m_portFeatureLastQuery=get_dword_time();
if(kind=="cap" && args.size()==3) {ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 cap %u 1 4031 %lld",request,(long long)get_global_time());return;}
if(kind=="cap" && args.size()==3) {ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 cap %u 1 8127 %lld",request,(long long)get_global_time());return;}
if(kind=="quiver" && args.size()==3) {
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 begin %u quiver 0 0 0 0 %lld",request,(long long)get_global_time());
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 end %u 0",request);
@@ -72,6 +73,7 @@ ACMD(do_port_features) {
if(subject>=10 || offset){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u invalid",request);return;}
PortRankQuery(ch,request,subject);return;
}
if(kind=="cube"||kind=="cubecheck") {PortCubeQuery(ch,request,subject,offset,kind=="cubecheck");return;}
if(kind=="calendar" && subject==1) {PortCalendarQuery(ch,request,offset);return;}
if(kind=="travel" && !offset) {PortTrackTravel(ch,request,subject);return;}
std::vector<PortWikiRow> rows;
+5
View File
@@ -19,6 +19,7 @@
// 9 = talismans (port_pendant.cpp), whose pools are not in item_attr.
#include "stdafx.h"
#include "port_attr_lock.h"
#include "port_cube_actor.h"
#include "constants.h"
#include "port_switchbot.h"
#include "desc.h"
@@ -345,6 +346,9 @@ void CSwitchbot::FinishSlot(LPCHARACTER ch, BYTE slot, LPITEM item, bool finishe
void CSwitchbot::SwitchItems()
{
// Defer a whole roll before touching active/finished flags, RNG or payment.
// The regular event remains scheduled; no scroll or result is discarded.
if(PortCubeActorHeld(CHARACTER_MANAGER::instance().FindByPID(m_table.player_id)))return;
for (BYTE bSlot = 0; bSlot < SWITCHBOT_SLOT_COUNT_REAL; ++bSlot)
{
if (!m_table.active[bSlot])
@@ -530,6 +534,7 @@ void CSwitchbotManager::UnregisterItem(DWORD player_id, WORD wCell)
void CSwitchbotManager::Start(DWORD player_id, BYTE slot, const std::vector<TSwitchbotAttributeAlternativeTable>& vec_alternatives)
{
if(PortCubeActorHeld(CHARACTER_MANAGER::instance().FindByPID(player_id)))return;
if (!ValidPosition(slot))
return;
+2
View File
@@ -1,4 +1,5 @@
#include "stdafx.h"
#include "port_cube_quest.h"
#include <fstream>
#include "constants.h"
#include "buffer_manager.h"
@@ -1575,6 +1576,7 @@ namespace quest
bool CQuestManager::ExecuteQuestScript(PC& pc, const string& quest_name, const int state, const char* code, const int code_size, vector<AArgScript*>* pChatScripts, bool bUseCache)
{
PortCubeQuestMutation(pc.GetID());
// 실행공간을 생성
QuestState qs = CQuestManager::instance().OpenState(quest_name, state);
if (pChatScripts)
+2 -1
View File
@@ -50,7 +50,8 @@ namespace quest
bool RunState(QuestState& qs);
PC * GetPC(unsigned int pc);
PC * GetPCForce(unsigned int pc); // 현재 PC를 바꾸지 않고 PC 포인터를 가져온다.
PC * GetPCForce(unsigned int pc);
PC* PortCubeFindPC(unsigned pid) { auto it=m_mapPC.find(pid); return it==m_mapPC.end()?nullptr:&it->second; } // 현재 PC를 바꾸지 않고 PC 포인터를 가져온다.
unsigned int GetCurrentNPCRace();
const string & GetCurrentQuestName();
+5
View File
@@ -1,4 +1,5 @@
#include "stdafx.h"
#include "port_cube_quest.h"
#include "constants.h"
#include "questmanager.h"
#include "packet.h"
@@ -52,6 +53,8 @@ namespace quest
void PC::SetFlag(const string& name, int value, bool bSkipSave)
{
auto before=m_FlagMap.find(name);
if((before==m_FlagMap.end()&&value!=0)||(before!=m_FlagMap.end()&&before->second!=value))PortCubeQuestMutation(m_dwID);
if ( test_server )
sys_log(0, "QUEST Setting flag %s %d", name.c_str(),value);
else
@@ -78,6 +81,7 @@ namespace quest
bool PC::DeleteFlag(const string & name)
{
if(m_FlagMap.find(name)!=m_FlagMap.end())PortCubeQuestMutation(m_dwID);
TFlagMap::iterator it = m_FlagMap.find(name);
if (it != m_FlagMap.end())
@@ -167,6 +171,7 @@ namespace quest
void PC::AddTimer(const string & name, LPEVENT pEvent)
{
PortCubeQuestMutation(m_dwID);
RemoveTimer(name);
m_TimerMap.insert(make_pair(name, pEvent));
sys_log(0, "QUEST add timer %p %d", get_pointer(pEvent), m_TimerMap.size());
+1
View File
@@ -106,6 +106,7 @@ namespace quest
void RemoveTimerNotCancel(const string& name);
void AddTimer(const string& name, LPEVENT pEvent);
void ClearTimer();
bool PortCubeHasTimers() const { return !m_TimerMap.empty(); }
void SetCurrentQuestStartFlag();
void SetCurrentQuestDoneFlag();
@@ -0,0 +1,38 @@
#include <cstdlib>
#include <new>
static bool watch=false;static size_t allocationSeen=0,failAllocation=0;
void* operator new(size_t size){if(watch&&++allocationSeen==failAllocation)throw std::bad_alloc();if(auto* p=std::malloc(size?size:1))return p;throw std::bad_alloc();}
void operator delete(void* p)noexcept{std::free(p);}
void operator delete(void* p,size_t)noexcept{std::free(p);}
void* operator new[](size_t n){return ::operator new(n);}void operator delete[](void* p)noexcept{::operator delete(p);}
void operator delete[](void* p,size_t)noexcept{::operator delete(p);}
static CHARACTER actor;
static void clean(){auto& m=ITEM_MANAGER::instance();while(!m.m_map_pkItemByID.empty()){auto* item=m.m_map_pkItemByID.begin()->second;item->SetCell(nullptr,0);item->SetSkipSave(true);m.DestroyItem(item);}m.m_VIDMap.clear();m.m_set_pkItemForDelayedSave.clear();actor=CHARACTER{};}
static PortCube::InventoryImage setup(){clean();auto& m=ITEM_MANAGER::instance();m.tables[30006].flags=1;m.tables[19].bSize=3;m.tables[19].sAddonType=1;m.tables[18].bType=ITEM_COSTUME;m.tables[18].bSubType=COSTUME_SASH;m.tables[18].values[0]=4;
auto* material=m.CreateItem(30006,10);assert(material);material->SetCell(&actor,0);material->SetWindow(INVENTORY);actor.m_pointsInstant.pItems[0]=material;actor.m_pointsInstant.bItemGrid[0]=1;
auto* side=m.CreateItem(30006,1);side->SetCell(&actor,300);side->SetWindow(2);actor.m_pointsInstant.pItems[300]=side;actor.m_pointsInstant.bItemGrid[300]=301;
actor.m_pointsInstant.pCubeItems[0]=material;actor.m_pointsInstant.pCubeItems[1]=side;actor.m_pointsInstant.pSashMaterials[0]=material;actor.m_pQuestItem=material;
m.m_set_pkItemForDelayedSave.clear();PortCube::InventoryImage image;image.gold=760;
for(unsigned n=0;n<3;++n){PortCube::Item item;item.cell=n;item.value.id=n?899+n:material->GetID();item.value.vnum=n==0?30006:n==1?19:18;item.value.count=n?1:4;item.value.sockets[0]=n==2?17:-123;item.value.types[0]=9;item.value.values[0]=-321;for(unsigned j=0;j<69;++j)item.value.extra[j]=uint8_t(j+17);image.items.push_back(item);}
saves=packets=logs=timers=draws=0;return image;
}
static void checkApplied(const PortCube::InventoryImage& image,CItem* side,unsigned savedCursor){auto& m=ITEM_MANAGER::instance();assert(actor.gold==760&&actor.m_pointsInstant.pItems[300]==side&&actor.m_pointsInstant.bItemGrid[300]==301&&m.Find(side->GetID())==side);
assert(!saves&&!packets&&!logs&&!timers&&!draws&&cursor==savedCursor&&m.m_map_pkItemByID.size()==4&&m.m_set_pkItemForDelayedSave.empty());
for(const auto& row:image.items){auto* item=actor.GetInventoryItem(row.cell);assert(item&&item->GetOwner()==&actor&&item->GetCell()==row.cell&&item->GetWindow()==INVENTORY&&!item->PortCubeIsTemplate()&&item->GetSkipSave()&&m.Find(row.value.id)==item&&m.FindByVID(item->GetVID())==item&&item->GetCount()==row.value.count);assert(item->GetSocket(0)==row.value.sockets[0]&&item->GetAttributeValue(0)==-321&&std::memcmp(&item->GetPortExtra(),row.value.extra,69)==0);}
assert(actor.m_pointsInstant.bItemGrid[1]==2&&actor.m_pointsInstant.bItemGrid[6]==2&&actor.m_pointsInstant.bItemGrid[11]==2&&actor.GetInventoryItem(6)==nullptr);
assert(actor.m_pQuestItem==actor.GetInventoryItem(0)&&actor.m_pointsInstant.pCubeItems[0]==actor.GetInventoryItem(0)&&actor.m_pointsInstant.pCubeItems[1]==side&&actor.m_pointsInstant.pSashMaterials[0]==actor.GetInventoryItem(0));
}
int main(){auto image=setup();auto* old=actor.GetInventoryItem(0);auto* side=actor.GetInventoryItem(300);const auto savedCursor=cursor;
watch=true;allocationSeen=0;assert(PortCubeInstallAuthoritative(&actor,image));watch=false;const auto total=allocationSeen;assert(total>10);checkApplied(image,side,savedCursor);assert(actor.GetInventoryItem(0)!=old);
// Every allocation site must fail before publication; source pointers, gold,
// registry and the other window remain untouched. Failed staging is destroyed.
for(size_t at=1;at<=total;++at){image=setup();old=actor.GetInventoryItem(0);side=actor.GetInventoryItem(300);const auto id=old->GetID(),vid=old->GetVID();watch=true;allocationSeen=0;failAllocation=at;const bool ok=PortCubeInstallAuthoritative(&actor,image);watch=false;assert(!ok&&actor.gold==1000&&actor.GetInventoryItem(0)==old&&old->GetCount()==10&&actor.GetInventoryItem(300)==side&&ITEM_MANAGER::instance().Find(id)==old&&ITEM_MANAGER::instance().FindByVID(vid)==old&&ITEM_MANAGER::instance().m_map_pkItemByID.size()==2&&!PortCubeCurrentFactorySlot()&&!saves&&!packets&&!logs&&!timers&&!draws);}
failAllocation=0;image=setup();old=actor.GetInventoryItem(0);held=false;assert(!PortCubeInstallAuthoritative(&actor,image)&&actor.GetInventoryItem(0)==old);held=true;
old->locked=true;assert(!PortCubeInstallAuthoritative(&actor,image)&&actor.GetInventoryItem(0)==old&&actor.gold==1000);old->locked=false;
auto invalid=image;invalid.items[1].cell=0;assert(!PortCubeInstallAuthoritative(&actor,invalid)&&actor.GetInventoryItem(0)==old);
ITEM_MANAGER::instance().m_dwVIDCount=UINT32_MAX;assert(!PortCubeInstallAuthoritative(&actor,image)&&actor.GetInventoryItem(0)==old);ITEM_MANAGER::instance().m_dwVIDCount=100;
// A different live object owns an output ID: reject instead of deleting it.
auto* foreign=ITEM_MANAGER::instance().CreateItem(30006,1,900);assert(foreign);assert(!PortCubeInstallAuthoritative(&actor,image)&&ITEM_MANAGER::instance().Find(900)==foreign&&actor.GetInventoryItem(0)==old);
image=setup();side=actor.GetInventoryItem(300);image.items.clear();assert(PortCubeInstallAuthoritative(&actor,image)&&!actor.GetInventoryItem(0)&&!actor.m_pQuestItem&&!actor.m_pointsInstant.pCubeItems[0]&&!actor.m_pointsInstant.pSashMaterials[0]&&actor.m_pointsInstant.pCubeItems[1]==side);
clean();assert(allocations==destroys);
puts("PASS actual restore factory/registry/CHARACTER install: exact metadata, no RNG/IDs/save/packets/timers, same-ID replacement, physical grid and other-window preservation; every allocation failure before publication, locked/overlap/VID overflow/foreign ID refusal; explicit held actor/platform substitutes");}
@@ -0,0 +1,339 @@
#include "src/server/common/cube_store.h"
#include "src/server/common/cube_fence.h"
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <sys/wait.h>
#include <spawn.h>
#include <unistd.h>
#ifdef PORT_CUBE_MYSQL
#include "src/server/common/economy_mysql.h"
#else
#include <sqlite3.h>
#endif
using namespace PortCube;
using Rows=PortEconomy::Rows;
static std::string address;
static std::string executable;
extern char** environ;
static pid_t spawnWorker(const std::string& mode,const std::string& extra=""){
std::vector<char*> args={const_cast<char*>(executable.c_str()),const_cast<char*>(address.c_str()),const_cast<char*>(mode.c_str())};
if(!extra.empty())args.push_back(const_cast<char*>(extra.c_str()));args.push_back(nullptr);
pid_t child=0;assert(posix_spawn(&child,executable.c_str(),nullptr,nullptr,args.data(),environ)==0);return child;
}
struct TestDB {
uint64_t affected=0,inserted=0,warnings=0;
bool active=false,engine=true,extra=true,ambiguous=false,rejectCommit=false;
unsigned cubeTables=3;
int statements=0,failAt=0,warnAt=0;
std::function<void(const std::string&)> after;
#ifdef PORT_CUBE_MYSQL
MYSQL handle;PortEconomy::Mysql* db;
TestDB(){mysql_init(&handle);assert(mysql_real_connect(&handle,"localhost","root","","cube_batch_test",0,address.c_str(),0));db=new PortEconomy::Mysql(&handle);}
~TestDB(){delete db;mysql_close(&handle);}
bool Native(const std::string& sql,Rows& rows){bool ok=db->Query(sql,rows);affected=db->affected;inserted=db->inserted;warnings=db->warnings;return ok;}
bool Begin(){if(active)return false;active=db->Begin();return active;}
bool Commit(){if(rejectCommit){rejectCommit=false;return false;}bool ok=db->Commit();if(ok){active=false;if(after)after("COMMIT");}if(ambiguous&&ok){ambiguous=false;return false;}return ok;}
void Rollback(){if(active){db->Rollback();active=false;}}
#else
sqlite3* db=nullptr;
// Explicit SQLite-only substitutes for connection-scoped MySQL authority.
// Real advisory-lock competition is exercised by the MySQL owner probe.
uint64_t ownerConnection=1,ownerHolder=0;
TestDB(){assert(sqlite3_open(address.c_str(),&db)==SQLITE_OK);sqlite3_busy_timeout(db,5000);}
~TestDB(){Rollback();sqlite3_close(db);}
static void replace(std::string& text,const std::string& from,const std::string& to){size_t pos;while((pos=text.find(from))!=std::string::npos)text.replace(pos,from.size(),to);}
bool Native(std::string sql,Rows& rows){
rows.clear();affected=inserted=warnings=0;
if(sql=="SELECT CONNECTION_ID(),IS_USED_LOCK(CONCAT('m2_cube:',DATABASE()))"){rows={{std::to_string(ownerConnection),ownerHolder?std::to_string(ownerHolder):""}};return true;}
if(sql=="SELECT GET_LOCK(CONCAT('m2_cube:',DATABASE()),0)"){const bool ok=!ownerHolder||ownerHolder==ownerConnection;if(ok)ownerHolder=ownerConnection;rows={{ok?"1":"0"}};return true;}
if(sql=="SELECT RELEASE_LOCK(CONCAT('m2_cube:',DATABASE()))"){const bool ok=ownerHolder==ownerConnection;if(ok)ownerHolder=0;rows={{ok?"1":"0"}};return true;}
if(sql.find("information_schema.tables")!=std::string::npos){
if(sql.find("('port_cube_release_version','port_cube_releases')")!=std::string::npos) {
if(!Native("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name IN ('port_cube_release_version','port_cube_releases')",rows))return false;
if(sql.find("ENGINE='InnoDB'")!=std::string::npos&&!engine&&rows[0][0]=="2")rows[0][0]="1";
return true;
}
if(sql.find("('port_cube_image_ack_version','port_cube_image_acks')")!=std::string::npos) {
if(!Native("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name IN ('port_cube_image_ack_version','port_cube_image_acks')",rows))return false;
if(sql.find("ENGINE='InnoDB'")!=std::string::npos&&!engine&&rows[0][0]=="2")rows[0][0]="1";
return true;
}
if(sql.find("('port_cube_owner_version','port_cube_owner_broker','port_cube_owner_leases')")!=std::string::npos) {
if(!Native("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name IN ('port_cube_owner_version','port_cube_owner_broker','port_cube_owner_leases')",rows))return false;
if(sql.find("ENGINE='InnoDB'")!=std::string::npos&&!engine&&rows[0][0]=="3")rows[0][0]="2";
return true;
}
if(sql.find("('port_cube_gold_version','port_cube_gold_intents','port_cube_gold_sources')")!=std::string::npos) {
if(!Native("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name IN ('port_cube_gold_version','port_cube_gold_intents','port_cube_gold_sources')",rows))return false;
if(sql.find("ENGINE='InnoDB'")!=std::string::npos&&!engine&&rows[0][0]=="3")rows[0][0]="2";
return true;
}
rows={{sql.find("TABLE_NAME IN ('port_cube_version','port_cube_fences','port_cube_item_fences')")!=std::string::npos?std::to_string(cubeTables):(engine?"11":"10")}};return true;
}
if(sql=="SHOW COLUMNS FROM item"){
Rows columns;if(!Native("PRAGMA table_info(item)",columns))return false;
for(const auto& column:columns)rows.push_back({column[1],column[1]=="port_extra"?(extra?"varbinary(69)":"varbinary(10)"):column[2],"NO"});return true;
}
replace(sql," FOR UPDATE","");replace(sql,"ON DUPLICATE KEY UPDATE account=VALUES(account)","ON CONFLICT(account) DO NOTHING");
sqlite3_stmt* statement=nullptr;
if(sqlite3_prepare_v2(db,sql.c_str(),-1,&statement,nullptr)!=SQLITE_OK){std::cerr<<sqlite3_errmsg(db)<<" SQL "<<sql.substr(0,100)<<"\n";return false;}
int rc;while((rc=sqlite3_step(statement))==SQLITE_ROW){std::vector<std::string> row;for(int i=0;i<sqlite3_column_count(statement);++i){const char* p=static_cast<const char*>(sqlite3_column_blob(statement,i));row.emplace_back(p?std::string(p,sqlite3_column_bytes(statement,i)):std::string());}rows.push_back(row);}
sqlite3_finalize(statement);if(rc!=SQLITE_DONE)return false;affected=uint64_t(sqlite3_changes(db));inserted=uint64_t(sqlite3_last_insert_rowid(db));return true;
}
bool Begin(){if(active)return false;Rows rows;active=Native("BEGIN IMMEDIATE",rows);return active;}
bool Commit(){if(rejectCommit){rejectCommit=false;return false;}Rows rows;bool ok=Native("COMMIT",rows);if(ok){active=false;if(after)after("COMMIT");}if(ambiguous&&ok){ambiguous=false;return false;}return ok;}
void Rollback(){if(active){Rows rows;Native("ROLLBACK",rows);active=false;}}
#endif
bool Query(const std::string& sql,Rows& rows){
++statements;if(failAt==statements){rows.clear();return false;}
bool ok=Native(sql,rows);if(warnAt==statements)warnings=1;if(ok&&after)after(sql);return ok;
}
};
using Store=BatchStore<TestDB>;
static Proto proto(uint32_t vnum){return {vnum==333?3u:vnum==999?0u:1u,vnum!=19};}
static void sql(TestDB& db,const std::string& query){Rows rows;if(!db.Query(query,rows)){std::cerr<<query<<"\n";std::abort();}}
static std::string value(TestDB& db,const std::string& query){Rows rows;assert(db.Query(query,rows)&&rows.size()==1&&rows[0].size()==1);return rows[0][0];}
static uint64_t number(TestDB& db,const std::string& query){uint64_t n=0;assert(PortEconomy::Number(value(db,query),n));return n;}
static std::string hex(const void* data,size_t n){return PortEconomy::Hex(data,n);}
static Batch batch(){
Batch b;b.account=1;b.player=1;b.epoch=3;b.gold=1000;b.owner=std::string(32,'a');b.token=std::string(32,'b');b.attempts=3;
b.recipe.id=1;b.recipe.reward=19;b.recipe.rewardCount=1;b.recipe.gold=100;b.recipe.percent=50;b.recipe.npcs={20383};b.recipe.materials={{30006,2}};
Item item;item.value.id=10;item.value.vnum=30006;item.value.count=10;item.value.sockets[0]=-123;item.value.types[0]=255;item.value.values[0]=-321;item.value.extra[0]=1;item.value.extra[68]=255;b.inventory.push_back(item);
for(unsigned i=0;i<3;++i){PortEconomy::Reward r;r.id=100+i;r.vnum=19;r.count=1;r.sockets[0]=77;r.extra[0]=9;b.rewards.push_back(r);}return b;
}
static void initialize(TestDB& db,bool cube=true){
const std::string engine=
#ifdef PORT_CUBE_MYSQL
" ENGINE=InnoDB";
#else
"";
#endif
sql(db,"CREATE TABLE IF NOT EXISTS player(id INT PRIMARY KEY,account_id INT,gold BIGINT)"+engine);
std::string item="CREATE TABLE IF NOT EXISTS item(id INT PRIMARY KEY,owner_id INT,window VARCHAR(16),pos INT,count INT,vnum INT";
for(unsigned i=0;i<3;++i)item+=",socket"+std::to_string(i)+" INT NOT NULL DEFAULT 0";
for(unsigned i=0;i<7;++i)item+=",attrtype"+std::to_string(i)+" INT NOT NULL DEFAULT 0,attrvalue"+std::to_string(i)+" INT NOT NULL DEFAULT 0";
sql(db,item+",port_extra VARBINARY(69) NOT NULL)"+engine);
std::string custody=item;custody.replace(custody.find("item("),5,"port_economy_custody(");sql(db,custody+",port_extra VARBINARY(69) NOT NULL)"+engine);
sql(db,"CREATE TABLE IF NOT EXISTS port_economy_version(id INT PRIMARY KEY,version INT)"+engine);
if(cube)sql(db,"CREATE TABLE IF NOT EXISTS port_cube_version(id INT PRIMARY KEY,version INT)"+engine);
sql(db,"CREATE TABLE IF NOT EXISTS port_economy_account_lock(account INT PRIMARY KEY)"+engine);
sql(db,"CREATE TABLE IF NOT EXISTS port_economy_pending(pid INT PRIMARY KEY,token VARCHAR(32))"+engine);
sql(db,"CREATE TABLE IF NOT EXISTS port_economy_item_reservations(id INT PRIMARY KEY,request VARCHAR(32))"+engine);
if(cube){sql(db,"CREATE TABLE IF NOT EXISTS port_cube_fences(pid INT PRIMARY KEY,account INT,epoch BIGINT,owner VARCHAR(32),request VARCHAR(32) UNIQUE,phase VARCHAR(16),body MEDIUMBLOB NOT NULL,image MEDIUMBLOB NOT NULL,drain_state INT NOT NULL DEFAULT 0)"+engine);
sql(db,"CREATE TABLE IF NOT EXISTS port_cube_item_fences(id INT PRIMARY KEY,pid INT NOT NULL,epoch BIGINT NOT NULL,request VARCHAR(32) NOT NULL)"+engine);
sql(db,"CREATE TABLE IF NOT EXISTS port_cube_requests(token VARCHAR(32) PRIMARY KEY,account INT,pid INT,body MEDIUMBLOB,rolls VARBINARY(100),state VARCHAR(16),result VARCHAR(64),successes INT,fee BIGINT,awards MEDIUMBLOB)"+engine);}
}
static void initializeGoldAddon(TestDB& db) {
const std::string engine=
#ifdef PORT_CUBE_MYSQL
" ENGINE=InnoDB";
#else
"";
#endif
sql(db,"CREATE TABLE IF NOT EXISTS port_cube_gold_version(id INT PRIMARY KEY,version INT NOT NULL)"+engine);
sql(db,"CREATE TABLE IF NOT EXISTS port_cube_gold_intents(event VARCHAR(32) PRIMARY KEY,request VARCHAR(32) NOT NULL,seq INT NOT NULL,account INT NOT NULL,pid INT NOT NULL,body VARBINARY(129) NOT NULL,state VARCHAR(16) NOT NULL,before_gold BIGINT NOT NULL,after_gold BIGINT NOT NULL,UNIQUE(request,seq))"+engine);
sql(db,"CREATE TABLE IF NOT EXISTS port_cube_gold_sources(request VARCHAR(32) PRIMARY KEY,account INT NOT NULL,pid INT NOT NULL,epoch BIGINT NOT NULL,owner VARCHAR(32) NOT NULL,session BIGINT NOT NULL,cookie INT NOT NULL,handle INT NOT NULL,manifest VARBINARY(32772) NOT NULL)"+engine);
sql(db,"DELETE FROM port_cube_gold_version");sql(db,"INSERT INTO port_cube_gold_version VALUES(1,2)");
}
static void initializeOwnerAddon(TestDB& db) {
const std::string engine=
#ifdef PORT_CUBE_MYSQL
" ENGINE=InnoDB";
#else
"";
#endif
sql(db,"CREATE TABLE IF NOT EXISTS port_cube_owner_version(id INT PRIMARY KEY,version INT NOT NULL)"+engine);
sql(db,"CREATE TABLE IF NOT EXISTS port_cube_owner_broker(id INT PRIMARY KEY,generation BIGINT NOT NULL,boot VARCHAR(32) NOT NULL,connection_id BIGINT NOT NULL)"+engine);
sql(db,"CREATE TABLE IF NOT EXISTS port_cube_owner_leases(request VARCHAR(32) PRIMARY KEY,account INT NOT NULL UNIQUE,pid INT NOT NULL UNIQUE,body MEDIUMBLOB NOT NULL,revision BIGINT NOT NULL,generation BIGINT NOT NULL,boot VARCHAR(32) NOT NULL,connection_id BIGINT NOT NULL,peer INT NOT NULL,binding VARBINARY(96) NOT NULL,original_peer INT NOT NULL,original_binding VARBINARY(96) NOT NULL,phase VARCHAR(16) NOT NULL,revoked_generation BIGINT NOT NULL,reason INT NOT NULL)"+engine);
if(!number(db,"SELECT COUNT(*) FROM port_cube_owner_version"))sql(db,"INSERT INTO port_cube_owner_version VALUES(1,1)");
if(!number(db,"SELECT COUNT(*) FROM port_cube_owner_broker"))sql(db,"INSERT INTO port_cube_owner_broker VALUES(1,0,'00000000000000000000000000000000',0)");
}
static int draws=0;
static void initializeImageAckAddon(TestDB& db) {
const std::string engine=
#ifdef PORT_CUBE_MYSQL
" ENGINE=InnoDB";
#else
"";
#endif
sql(db,"CREATE TABLE IF NOT EXISTS port_cube_image_ack_version(id INT PRIMARY KEY,version INT NOT NULL)"+engine);
sql(db,"CREATE TABLE IF NOT EXISTS port_cube_image_acks(request VARCHAR(32) PRIMARY KEY,body MEDIUMBLOB NOT NULL,owner_grant VARBINARY(160) NOT NULL,image MEDIUMBLOB NOT NULL)"+engine);
if(!number(db,"SELECT COUNT(*) FROM port_cube_image_ack_version"))sql(db,"INSERT INTO port_cube_image_ack_version VALUES(1,1)");
}
static void initializeReleaseAddon(TestDB& db) {
const std::string engine=
#ifdef PORT_CUBE_MYSQL
" ENGINE=InnoDB";
#else
"";
#endif
sql(db,"CREATE TABLE IF NOT EXISTS port_cube_release_version(id INT PRIMARY KEY,version INT NOT NULL)"+engine);
sql(db,"CREATE TABLE IF NOT EXISTS port_cube_releases(request VARCHAR(32) PRIMARY KEY,body MEDIUMBLOB NOT NULL,owner_grant VARBINARY(160) NOT NULL,image MEDIUMBLOB NOT NULL)"+engine);
if(!number(db,"SELECT COUNT(*) FROM port_cube_release_version"))sql(db,"INSERT INTO port_cube_release_version VALUES(1,1)");
}
static void reset(TestDB& db,const Batch& b){
draws=0;
db.failAt=db.warnAt=0;db.after={};db.ambiguous=db.rejectCommit=false;db.Rollback();
for(const char* table:{"port_cube_requests","port_cube_item_fences","port_cube_fences","port_economy_item_reservations","port_economy_pending","port_economy_account_lock","port_cube_version","port_economy_version","port_economy_custody","item","player"})sql(db,std::string("DELETE FROM ")+table);
sql(db,"INSERT INTO port_cube_version VALUES(1,2)");sql(db,"INSERT INTO port_economy_version VALUES(1,1)");sql(db,"INSERT INTO player VALUES(1,1,"+std::to_string(b.gold)+")");
const auto body=Encode(b);
sql(db,"INSERT INTO port_cube_fences VALUES(1,1,"+std::to_string(b.epoch)+",'"+b.owner+"','"+b.token+"','FROZEN',X'"+hex(body.data(),body.size())+"',X'',1)");
auto lock=[&](uint32_t id){sql(db,"INSERT INTO port_cube_item_fences VALUES("+std::to_string(id)+",1,"+std::to_string(b.epoch)+",'"+b.token+"')");};
for(const auto& i:b.inventory)lock(i.value.id);for(const auto& r:b.rewards)lock(r.id);
for(const auto& i:b.inventory){
const auto& r=i.value;std::string columns="id,owner_id,window,pos,count,vnum",values=std::to_string(r.id)+",1,'INVENTORY',"+std::to_string(i.cell)+","+std::to_string(r.count)+","+std::to_string(r.vnum);
for(unsigned n=0;n<3;++n){columns+=",socket"+std::to_string(n);values+=","+std::to_string(r.sockets[n]);}
for(unsigned n=0;n<7;++n){columns+=",attrtype"+std::to_string(n)+",attrvalue"+std::to_string(n);values+=","+std::to_string(r.types[n])+","+std::to_string(r.values[n]);}
sql(db,"INSERT INTO item("+columns+",port_extra) VALUES("+values+",X'"+hex(r.extra,69)+"')");
}
}
static unsigned draw(){return ++draws%2?25u:75u;}
static void unchanged(TestDB& db,const Batch& b){assert(number(db,"SELECT gold FROM player WHERE id=1")==b.gold);assert(number(db,"SELECT count FROM item WHERE id=10")==b.inventory[0].value.count);assert(number(db,"SELECT COUNT(*) FROM item WHERE id IN(100,101,102)")==0);}
static void basic(TestDB& db){
auto b=batch();Batch decoded;assert(Decode(Encode(b),decoded)&&Encode(b)==Encode(decoded));
for(size_t n=0;n<Encode(b).size();++n)assert(!Decode(Encode(b).substr(0,n),decoded));
assert(!Decode(Encode(b)+"x",decoded));auto invalid=b;invalid.recipe.copy=true;assert(!Validate(invalid));
Store store(db,proto);Store::Receipt receipt;reset(db,b);assert(store.Ready());
#ifdef PORT_CUBE_MYSQL
sql(db,"ALTER TABLE item ENGINE=MyISAM");assert(!store.Ready());sql(db,"ALTER TABLE item ENGINE=InnoDB");assert(store.Ready());
sql(db,"UPDATE port_cube_version SET version=3");assert(!store.Ready());sql(db,"UPDATE port_cube_version SET version=2");
sql(db,"ALTER TABLE item ADD COLUMN unknown_state INT");assert(!store.Ready());sql(db,"ALTER TABLE item DROP COLUMN unknown_state");assert(store.Ready());
#endif
sql(db,"UPDATE port_cube_fences SET phase='RESYNC'");draws=0;assert(store.Prepare(b,draw)==Store::Blocked&&draws==0);unchanged(db,b);
sql(db,"UPDATE port_cube_fences SET phase='FROZEN'");assert(store.Prepare(b,draw)==Store::Prepared&&draws==3);assert(store.Prepare(b,draw)==Store::Prepared&&draws==3);unchanged(db,b);
auto changed=b;changed.attempts=2;changed.rewards.pop_back();assert(store.Prepare(changed,draw)==Store::Rejected&&draws==3);
assert(store.Execute(b.token,2,1,receipt)==Store::Rejected);assert(store.Execute(b.token,1,1,receipt)==Store::Complete&&receipt.result=="ok"&&receipt.successes==2&&receipt.fee==300&&receipt.awards.size()==2);
assert(number(db,"SELECT gold FROM player WHERE id=1")==700);assert(number(db,"SELECT count FROM item WHERE id=10")==4);assert(number(db,"SELECT COUNT(*) FROM item WHERE id>=100")==2);
assert(number(db,"SELECT socket0 FROM item WHERE id=100")==77);assert(value(db,"SELECT hex(port_extra) FROM item WHERE id=100").substr(0,2)=="09");
assert(value(db,"SELECT port_extra FROM item WHERE id=10")==std::string(reinterpret_cast<const char*>(b.inventory[0].value.extra),69));
assert(value(db,"SELECT socket0 FROM item WHERE id=10")=="-123"&&value(db,"SELECT attrvalue0 FROM item WHERE id=10")=="-321");
sql(db,"DELETE FROM port_cube_fences");assert(store.Execute(b.token,1,1,receipt)==Store::Complete&&receipt.successes==2);assert(store.Prepare(b,draw)==Store::Prepared&&draws==3);
assert(number(db,"SELECT gold FROM player WHERE id=1")==700&&number(db,"SELECT COUNT(*) FROM item WHERE id>=100")==2);
// All-fail is a successful paid batch, not a refund or leaked item object.
b.recipe.percent=0;reset(db,b);assert(store.Prepare(b,draw)==Store::Prepared);assert(store.Execute(b.token,1,1,receipt)==Store::Complete&&receipt.result=="ok"&&receipt.successes==0&&receipt.awards.empty()&&receipt.fee==300);assert(number(db,"SELECT count FROM item WHERE id=10")==4&&number(db,"SELECT gold FROM player")==700&&number(db,"SELECT COUNT(*) FROM item WHERE id>=100")==0);
b=batch();reset(db,b);assert(store.Prepare(b,draw)==Store::Prepared);sql(db,"UPDATE item SET socket0=1 WHERE id=10");assert(store.Execute(b.token,1,1,receipt)==Store::Complete&&receipt.result=="inventory_changed"&&receipt.fee==0);unchanged(db,b);
reset(db,b);assert(store.Prepare(b,draw)==Store::Prepared);sql(db,"UPDATE port_cube_fences SET epoch=4");assert(store.Execute(b.token,1,1,receipt)==Store::Blocked);unchanged(db,b);sql(db,"UPDATE port_cube_fences SET epoch=3");
sql(db,"INSERT INTO port_economy_pending VALUES(1,'other')");assert(store.Execute(b.token,1,1,receipt)==Store::Blocked);unchanged(db,b);
// Full grid remains full after partial consumption: reject without charging.
b.inventory[0].value.count=100;for(unsigned i=1;i<225;++i){Item item;item.cell=uint16_t(i);item.value.id=1000+i;item.value.vnum=30007;item.value.count=1;b.inventory.push_back(item);}reset(db,b);assert(store.Prepare(b,[]{return 1;})==Store::Prepared);assert(store.Execute(b.token,1,1,receipt)==Store::Complete&&receipt.result=="capacity_full");unchanged(db,b);
// Zero fee and full consumption free a grid cell for successful output.
b=batch();b.attempts=1;b.rewards.resize(1);b.recipe.gold=0;b.inventory[0].value.count=2;reset(db,b);assert(store.Prepare(b,[]{return 1;})==Store::Prepared);assert(store.Execute(b.token,1,1,receipt)==Store::Complete&&receipt.fee==0&&receipt.awards[0].cell==0);assert(number(db,"SELECT COUNT(*) FROM item WHERE id=10")==0&&number(db,"SELECT gold FROM player")==1000);
// Rollback of accepted RNG callback exceptions leaves no partial intent.
b=batch();reset(db,b);try{store.Prepare(b,[]{throw std::runtime_error("rng");return 1u;});assert(false);}catch(const std::runtime_error&){}assert(!db.active);assert(number(db,"SELECT COUNT(*) FROM port_cube_requests")==0&&number(db,"SELECT COUNT(*) FROM port_economy_item_reservations")==0);unchanged(db,b);
puts("PASS batch codec, fixed outcomes, paid failures, exact successful rewards, grid/copy/state/fence rejection");
}
static void faults(TestDB& db){
const auto b=batch();Store store(db,proto);Store::Receipt receipt;
reset(db,b);db.statements=0;assert(store.Prepare(b,draw)==Store::Prepared);const int prepareCount=db.statements;
for(int fault=1;fault<=prepareCount;++fault){reset(db,b);db.statements=0;db.failAt=fault;auto result=store.Prepare(b,draw);db.failAt=0;assert(result==Store::Retry);unchanged(db,b);assert(number(db,"SELECT COUNT(*) FROM port_cube_requests")==0&&number(db,"SELECT COUNT(*) FROM port_economy_item_reservations")==0);assert(store.Prepare(b,draw)==Store::Prepared);}
reset(db,b);assert(store.Prepare(b,draw)==Store::Prepared);db.statements=0;assert(store.Execute(b.token,1,1,receipt)==Store::Complete);const int count=db.statements;
for(int fault=1;fault<=count;++fault){reset(db,b);assert(store.Prepare(b,draw)==Store::Prepared);db.statements=0;db.failAt=fault;auto result=store.Execute(b.token,1,1,receipt);db.failAt=0;assert(result==Store::Retry);unchanged(db,b);assert(value(db,"SELECT state FROM port_cube_requests")=="PREPARED");assert(store.Execute(b.token,1,1,receipt)==Store::Complete);assert(number(db,"SELECT gold FROM player")==700);}
reset(db,b);assert(store.Prepare(b,draw)==Store::Prepared);db.ambiguous=true;assert(store.Execute(b.token,1,1,receipt)==Store::Retry);assert(store.Execute(b.token,1,1,receipt)==Store::Complete);assert(number(db,"SELECT gold FROM player")==700&&number(db,"SELECT count FROM item WHERE id=10")==4);
reset(db,b);db.ambiguous=true;draws=0;assert(store.Prepare(b,draw)==Store::Retry&&draws==3);assert(store.Prepare(b,draw)==Store::Prepared&&draws==3);
reset(db,b);db.rejectCommit=true;assert(store.Prepare(b,draw)==Store::Retry);assert(number(db,"SELECT COUNT(*) FROM port_cube_requests")==0&&number(db,"SELECT COUNT(*) FROM port_economy_item_reservations")==0);unchanged(db,b);
assert(store.Prepare(b,draw)==Store::Prepared);db.rejectCommit=true;assert(store.Execute(b.token,1,1,receipt)==Store::Retry);unchanged(db,b);assert(store.Execute(b.token,1,1,receipt)==Store::Complete);
// SQL warning after a tentative item write is an error, not silent loss.
reset(db,b);assert(store.Prepare(b,draw)==Store::Prepared);db.statements=0;int update=0;db.after=[&](const std::string& q){if(q.find("UPDATE item SET count=")==0)update=db.statements;};assert(store.Execute(b.token,1,1,receipt)==Store::Complete);db.after={};assert(update);
reset(db,b);assert(store.Prepare(b,draw)==Store::Prepared);db.statements=0;db.warnAt=update;assert(store.Execute(b.token,1,1,receipt)==Store::Retry);db.warnAt=0;unchanged(db,b);
#ifdef PORT_CUBE_MYSQL
auto overflow=b;overflow.rewards[0].sockets[0]=1000;reset(db,overflow);assert(store.Prepare(overflow,draw)==Store::Prepared);
const auto mode=value(db,"SELECT @@session.sql_mode");sql(db,"SET SESSION sql_mode=''");sql(db,"ALTER TABLE item MODIFY socket0 TINYINT NOT NULL DEFAULT 0");
assert(store.Execute(overflow.token,1,1,receipt)==Store::Retry);unchanged(db,overflow);
sql(db,"ALTER TABLE item MODIFY socket0 INT NOT NULL DEFAULT 0");sql(db,"SET SESSION sql_mode='"+mode+"'");
assert(store.Execute(overflow.token,1,1,receipt)==Store::Complete);assert(number(db,"SELECT socket0 FROM item WHERE id=100")==1000);
#endif
puts("PASS every SQL failure boundary, ambiguous prepare/commit recovery, warning rollback");
}
static void bounds(TestDB& db){
auto b=batch();Store store(db,proto);Store::Receipt receipt;
b.recipe.reward=200;b.recipe.rewardCount=2000;b.recipe.stackable=true;for(auto& r:b.rewards)r.vnum=200;
reset(db,b);assert(store.Prepare(b,draw)==Store::Prepared);assert(store.Execute(b.token,1,1,receipt)==Store::Complete&&receipt.successes==2&&receipt.awards.size()==2);assert(number(db,"SELECT SUM(count) FROM item WHERE vnum=200")==4000);
b=batch();b.recipe.gold=UINT32_MAX;b.gold=uint64_t(UINT32_MAX)*3+1000;reset(db,b);assert(store.Prepare(b,draw)==Store::Prepared);assert(store.Execute(b.token,1,1,receipt)==Store::Complete&&receipt.fee==uint64_t(UINT32_MAX)*3);assert(number(db,"SELECT gold FROM player")==1000);
b=batch();b.inventory[0].value.count=4;auto second=b.inventory[0];second.cell=5;second.value.id=11;b.inventory.push_back(second);
reset(db,b);assert(store.Prepare(b,draw)==Store::Prepared);assert(store.Execute(b.token,1,1,receipt)==Store::Complete);assert(number(db,"SELECT COUNT(*) FROM item WHERE id=10")==0&&number(db,"SELECT count FROM item WHERE id=11")==2);
b=batch();b.inventory[0].usable=false;reset(db,b);assert(store.Prepare(b,draw)==Store::Prepared);assert(store.Execute(b.token,1,1,receipt)==Store::Complete&&receipt.result=="materials_missing");unchanged(db,b);
b=batch();b.gold=299;reset(db,b);assert(store.Prepare(b,draw)==Store::Prepared);assert(store.Execute(b.token,1,1,receipt)==Store::Complete&&receipt.result=="gold_missing");unchanged(db,b);
b=batch();reset(db,b);assert(store.Prepare(b,draw)==Store::Prepared);sql(db,"UPDATE player SET gold=777");assert(store.Execute(b.token,1,1,receipt)==Store::Complete&&receipt.result=="gold_changed");assert(number(db,"SELECT gold FROM player")==777&&number(db,"SELECT count FROM item WHERE id=10")==10);
reset(db,b);auto another=b;another.token=std::string(32,'c');assert(store.Prepare(another,draw)==Store::Blocked&&draws==0);sql(db,"UPDATE port_cube_fences SET owner='wrong'");assert(store.Prepare(b,draw)==Store::Blocked&&draws==0);unchanged(db,b);
reset(db,b);assert(store.Prepare(b,draw)==Store::Prepared);sql(db,"UPDATE port_cube_requests SET rolls=X'000000'");assert(store.Execute(b.token,1,1,receipt)==Store::Retry);unchanged(db,b);
reset(db,b);assert(store.Prepare(b,draw)==Store::Prepared);sql(db,"UPDATE port_cube_requests SET body=X'00'");assert(store.Execute(b.token,1,1,receipt)==Store::Retry);unchanged(db,b);
reset(db,b);assert(store.Prepare(b,draw)==Store::Prepared);assert(store.Execute(b.token,1,1,receipt)==Store::Complete);sql(db,"UPDATE port_cube_requests SET fee=301");assert(store.Execute(b.token,1,1,receipt)==Store::Retry);assert(number(db,"SELECT gold FROM player")==700);sql(db,"UPDATE port_cube_requests SET fee=300,awards=X'0000'");assert(store.Execute(b.token,1,1,receipt)==Store::Retry);assert(number(db,"SELECT gold FROM player")==700);
#ifndef PORT_CUBE_MYSQL
reset(db,b);db.engine=false;assert(!store.Ready()&&store.Prepare(b,draw)==Store::Retry);db.engine=true;db.extra=false;assert(!store.Ready()&&store.Prepare(b,draw)==Store::Retry);db.extra=true;unchanged(db,b);
#endif
// Physical height validation must reject overlap, not create phantom cells.
b=batch();Item tall;tall.value.id=20;tall.value.vnum=333;tall.value.count=1;tall.cell=1;b.inventory.push_back(tall);tall.value.id=21;tall.cell=6;b.inventory.push_back(tall);reset(db,b);assert(store.Prepare(b,draw)==Store::Prepared);assert(store.Execute(b.token,1,1,receipt)==Store::Complete&&receipt.result=="inventory_invalid");unchanged(db,b);
puts("PASS stack splitting, uint64 fees, multi-stack consumption, locked/missing inputs, corrupt journal and grid overlap");
}
static void crash(TestDB& db){
const auto b=batch();Store store(db,proto);Store::Receipt receipt;
for(int point=0;point<3;++point){
reset(db,b);assert(store.Prepare(b,[]{return 1;})==Store::Prepared);
const pid_t child=spawnWorker("crash",std::to_string(point));
int status=0;assert(waitpid(child,&status,0)==child&&WIFEXITED(status)&&WEXITSTATUS(status)==77);
assert(store.Execute(b.token,1,1,receipt)==Store::Complete&&receipt.successes==3);assert(number(db,"SELECT gold FROM player")==700&&number(db,"SELECT count FROM item WHERE id=10")==4&&number(db,"SELECT COUNT(*) FROM item WHERE id>=100")==3);
assert(store.Execute(b.token,1,1,receipt)==Store::Complete);assert(number(db,"SELECT gold FROM player")==700);
}
puts("PASS process exit after material write, receipt write, commit; identity-only exactly-once recovery");
reset(db,b);assert(store.Prepare(b,[]{return 1;})==Store::Prepared);
pid_t children[2];for(auto& child:children)child=spawnWorker("repeat");
for(auto child:children){int status=0;assert(waitpid(child,&status,0)==child&&WIFEXITED(status)&&WEXITSTATUS(status)==0);}
assert(number(db,"SELECT gold FROM player")==700&&number(db,"SELECT count FROM item WHERE id=10")==4&&number(db,"SELECT COUNT(*) FROM item WHERE id>=100")==3);
puts("PASS simultaneous duplicate batch execution across two processes");
}
static void removeFence(TestDB& db){sql(db,"DELETE FROM port_cube_item_fences");sql(db,"DELETE FROM port_cube_fences");}
static void barriers(Drain& d,const Batch& b,bool failed=false){assert(d.Start(b,17,11,22));assert(!d.Async(b,17,false));assert(d.Main(b,17,2,false)==0);assert(d.Main(b,18,1,false)==0);assert(d.Main(b,17,1,false)==1);assert(d.Main(b,17,1,false)==0);assert(d.Async(b,17,false));assert(!d.Async(b,17,false));assert(d.Main(b,17,2,failed)==2);assert(d.Complete());}
static void fenceTests(TestDB& db){
using F=FenceStore<TestDB>;auto b=batch();F fence(db,proto);Store store(db,proto);Store::Receipt receipt;std::string image,phase;Batch recovered;
reset(db,b);removeFence(db);db.ambiguous=true;assert(fence.Begin(b,{9000})==F::Retry);assert(fence.Begin(b,{9000})==F::Done);assert(value(db,"SELECT phase FROM port_cube_fences")=="DRAINING");assert(number(db,"SELECT COUNT(*) FROM port_cube_item_fences WHERE id=9000")==1);assert(number(db,"SELECT MAX(id) FROM port_cube_item_fences")==9000);assert(number(db,"SELECT COUNT(*) FROM port_economy_item_reservations")==3);
assert(store.Prepare(b,draw)==Store::Blocked&&draws==0);assert(fence.AbortUnprepared(b)==F::Refused);assert(fence.Recover(2,1,recovered,phase,image)==F::Refused);
assert(fence.Recover(1,1,recovered,phase,image)==F::Done&&Encode(recovered)==Encode(b)&&phase=="DRAINING"&&image.empty());
Drain drain;assert(drain.Start(b,17,11,22));assert(fence.FinishDrain(b,drain,17,11,22,true)==F::Refused);
assert(drain.Main(b,17,1,false)==1);assert(drain.Async(b,17,false));assert(fence.FinishDrain(b,drain,17,11,22,true)==F::Refused);assert(drain.Main(b,17,2,false)==2);
db.ambiguous=true;assert(fence.FinishDrain(b,drain,17,11,22,true)==F::Retry);assert(fence.FinishDrain(b,drain,17,11,22,true)==F::Done);
assert(fence.Begin(b,{})==F::Done&&value(db,"SELECT phase FROM port_cube_fences")=="FROZEN");
assert(store.Prepare(b,draw)==Store::Prepared);assert(fence.AbortUnprepared(b)==F::Refused);assert(fence.Resync(b,image)==F::Refused);
assert(store.Execute(b.token,1,1,receipt)==Store::Complete);db.ambiguous=true;assert(fence.Resync(b,image)==F::Retry&&image.empty());assert(fence.Resync(b,image)==F::Done);
Reader decoded(image);assert(decoded.n(8)==700);const auto items=decoded.items();assert(decoded.ok&&decoded.at==image.size()&&items.size()==3&&items[0].value.count==4);
assert(store.Prepare(b,draw)==Store::Prepared); // identity replay only; no new draw or asset mutation
assert(fence.Release(b,image+"x")==F::Refused);sql(db,"UPDATE player SET gold=699");assert(fence.Release(b,image)==F::Refused);assert(value(db,"SELECT phase FROM port_cube_fences")=="RESYNC");sql(db,"UPDATE player SET gold=700");
auto wrong=b;wrong.epoch++;assert(fence.Release(wrong,image)==F::Refused);db.ambiguous=true;assert(fence.Release(b,image)==F::Retry);assert(fence.Release(b,image)==F::Done);assert(number(db,"SELECT COUNT(*) FROM port_cube_item_fences")==0&&value(db,"SELECT phase FROM port_cube_fences")=="RELEASED");assert(number(db,"SELECT COUNT(*) FROM port_economy_item_reservations")==3);
auto next=b;next.epoch++;next.token=std::string(32,'c');next.gold=700;next.inventory=items;for(unsigned i=0;i<next.rewards.size();++i)next.rewards[i].id=200+i;
assert(Validate(next)&&fence.Begin(next,{})==F::Done);assert(fence.Release(b,image)==F::Refused);assert(fence.FinishDrain(next,drain,17,11,22,true)==F::Refused);
// Failed SQL epochs or lost owner cannot advance to FROZEN or deduct.
for(unsigned reason=0;reason<3;++reason){reset(db,b);removeFence(db);assert(fence.Begin(b,{})==F::Done);Drain d;barriers(d,b,reason==0);assert(fence.FinishDrain(b,d,17,reason==1?12:11,22,reason!=2)==F::Done);assert(value(db,"SELECT phase FROM port_cube_fences")=="ABORTED");assert(store.Prepare(b,draw)==Store::Blocked&&draws==0);assert(fence.Resync(b,image)==F::Done);assert(fence.Resync(b,image)==F::Done);assert(fence.Release(b,image)==F::Done);unchanged(db,b);}
// Before any durable prepare, changed context can be refused without cost.
reset(db,b);assert(fence.AbortUnprepared(b)==F::Done);assert(fence.AbortUnprepared(b)==F::Done);assert(fence.Resync(b,image)==F::Done&&fence.Release(b,image)==F::Done);unchanged(db,b);
// Missing item locks or a changed frozen body must never authorize crafting.
reset(db,b);sql(db,"DELETE FROM port_cube_item_fences WHERE id=10");assert(store.Prepare(b,draw)==Store::Blocked&&draws==0);unchanged(db,b);
reset(db,b);sql(db,"UPDATE port_cube_fences SET body=X'00'");assert(store.Prepare(b,draw)==Store::Blocked&&draws==0);unchanged(db,b);
puts("PASS correlated two-main/async drain, owner/failure abort, durable item locks, canonical resync ACK and monotonic release");
// Inject a failure at every SQL statement in each lifecycle operation.
for(unsigned operation=0;operation<4;++operation){
auto setup=[&](){reset(db,b);if(operation==0)removeFence(db);if(operation>=1){assert(store.Prepare(b,draw)==Store::Prepared);assert(store.Execute(b.token,1,1,receipt)==Store::Complete);}if(operation>=2)assert(fence.Resync(b,image)==F::Done);};
auto action=[&](){if(operation==0)return fence.Begin(b,{});if(operation==1)return fence.Resync(b,image);if(operation==2)return fence.Release(b,image);return fence.Recover(1,1,recovered,phase,image);};
setup();db.statements=0;assert(action()==F::Done);const int count=db.statements;
for(int at=1;at<=count;++at){setup();db.statements=0;db.failAt=at;assert(action()==F::Retry);db.failAt=0;assert(!db.active);if(operation==0){assert(number(db,"SELECT COUNT(*) FROM port_cube_fences")==0);unchanged(db,b);}else {assert(number(db,"SELECT gold FROM player")==700);assert(value(db,"SELECT phase FROM port_cube_fences")!="RELEASED");}}
}
// A second process can reconstruct persisted DRAINING after loss of adapter
// memory; absent old-owner proof, the new correlation must abort, not charge.
reset(db,b);removeFence(db);assert(fence.Begin(b,{})==F::Done);
const pid_t child=spawnWorker("recover-drain");int status=0;assert(waitpid(child,&status,0)==child&&WIFEXITED(status)&&WEXITSTATUS(status)==77);assert(value(db,"SELECT phase FROM port_cube_fences")=="ABORTED");assert(fence.Resync(b,image)==F::Done&&fence.Release(b,image)==F::Done);unchanged(db,b);
puts("PASS lifecycle SQL failure boundaries and separate-process fail-closed drain recovery");
}
int main(int argc,char** argv){
assert(argc>=2&&argc<=4);executable=argv[0];address=argv[1];TestDB db;
if(argc>=3){const std::string mode=argv[2];
if(mode=="base"){initialize(db,false);return 0;}
if(mode=="fence"){initialize(db);fenceTests(db);return 0;}
Store s(db,proto);Store::Receipt receipt;const auto b=batch();
if(mode=="repeat")return s.Execute(b.token,1,1,receipt)==Store::Complete?0:1;
if(mode=="crash") {assert(argc==4);const int point=std::stoi(argv[3]);db.after=[&](const std::string& q){if((point==0&&q.find("UPDATE item SET count=")==0)||(point==1&&q.find("UPDATE port_cube_requests SET state='DONE'")==0)||(point==2&&q=="COMMIT"))_exit(77);};s.Execute(b.token,1,1,receipt);return 78;}
assert(mode=="recover-drain");FenceStore<TestDB> f(db,proto);Batch old;std::string phase,image;
assert(f.Recover(1,1,old,phase,image)==FenceStore<TestDB>::Done&&phase=="DRAINING");Drain d;barriers(d,old);assert(f.FinishDrain(old,d,17,11,22,false)==FenceStore<TestDB>::Done);return 77;
}
initialize(db);basic(db);faults(db);bounds(db);crash(db);return 0;
}
@@ -0,0 +1,49 @@
#define PORT_CUBE_OWNER_EMBED
#include "cube_owner_probe.cpp"
#include "src/server/common/cube_receipt.h"
static Store::Result prepareLive(TestDB& db,const Batch& b,const OwnerGrant& grant) {
O owner(db,proto);Store store(db,proto);return store.Prepare(b,draw,[&](){return owner.CraftWithin(b,grant);});
}
static Store::Result executeLive(TestDB& db,const Batch& b,const OwnerGrant& grant,Store::Receipt& receipt) {
O owner(db,proto);Store store(db,proto);return store.Execute(b.token,b.account,b.player,receipt,[&](const Batch& saved){return Encode(saved)==Encode(b)&&owner.CraftWithin(saved,grant);});
}
int main(int argc,char** argv) {
assert(argc==2||argc==3);address=argv[1];executable=argv[0];TestDB db;const auto b=batch();O owner(db,proto);OwnerLeader leader;Store::Receipt receipt;
if(argc==3) {
assert(owner.Acquire(std::string(32,'e'),leader)==O::Acquired);frozen(db,b,leader,false,true);const auto grant=original(b,leader);const std::string mode=argv[2];
if(mode=="execute-write"||mode=="execute-commit")assert(prepareLive(db,b,grant)==Store::Prepared);
db.after=[&](const std::string& q){if((mode=="prepare-write"&&q.find("INSERT INTO port_cube_requests")==0)||(mode=="execute-write"&&q.find("UPDATE item SET count=count-")==0)||((mode=="prepare-commit"||mode=="execute-commit")&&q=="COMMIT"))_Exit(96);};
if(mode.find("prepare")==0)prepareLive(db,b,grant);else executeLive(db,b,grant,receipt);assert(false);
}
initialize(db);initializeGoldAddon(db);initializeOwnerAddon(db);reset(db,b);assert(owner.Acquire(std::string(32,'d'),leader)==O::Acquired);auto grant=original(b,leader);
frozen(db,b,leader,false,false);assert(prepareLive(db,b,grant)==Store::Blocked&&draws==0&&number(db,"SELECT COUNT(*) FROM port_cube_requests")==0);
G gold(db,proto);assert(gold.CloseSource(b,source(b))==G::Stored);db.ambiguous=true;assert(prepareLive(db,b,grant)==Store::Retry&&draws==3);
const auto rolls=value(db,"SELECT rolls FROM port_cube_requests");assert(prepareLive(db,b,grant)==Store::Prepared&&draws==3&&number(db,"SELECT gold FROM player")==1000);
auto wrong=grant;wrong.revision++;assert(executeLive(db,b,wrong,receipt)==Store::Blocked&&number(db,"SELECT gold FROM player")==1000);
db.ambiguous=true;assert(executeLive(db,b,grant,receipt)==Store::Retry);assert(executeLive(db,b,grant,receipt)==Store::Complete&&receipt.successes==2&&receipt.fee==300);
const auto encoded=EncodeCraftReceipt({receipt.result,receipt.successes,receipt.fee,receipt.awards});CraftReceipt decoded;assert(DecodeCraftReceipt(encoded,decoded)&&ValidateCraftReceipt(b,decoded,proto));
assert(executeLive(db,b,grant,receipt)==Store::Complete&&EncodeCraftReceipt({receipt.result,receipt.successes,receipt.fee,receipt.awards})==encoded&&number(db,"SELECT gold FROM player")==700&&number(db,"SELECT count FROM item WHERE id=10")==4&&draws==3&&value(db,"SELECT rolls FROM port_cube_requests")==rolls);
puts("PASS live-owner source-sealed Prepare/Execute: durable fixed rolls, original receipt replay, ambiguous commits and one atomic charge/award");
for(unsigned operation=0;operation<2;++operation) {
auto setup=[&](){frozen(db,b,leader,false,true);if(operation)assert(prepareLive(db,b,grant)==Store::Prepared);};
auto action=[&](){return operation?executeLive(db,b,grant,receipt):prepareLive(db,b,grant);};const auto expected=operation?Store::Complete:Store::Prepared;
setup();db.statements=0;assert(action()==expected);const auto count=db.statements;
for(unsigned warning=0;warning<2;++warning)for(int at=1;at<=count;++at) {
setup();db.statements=0;if(warning)db.warnAt=at;else db.failAt=at;assert(action()!=expected);db.failAt=db.warnAt=0;
assert(number(db,"SELECT gold FROM player")==1000&&number(db,"SELECT count FROM item WHERE id=10")==10&&number(db,"SELECT COUNT(*) FROM item WHERE id>=100")==0);
assert(number(db,"SELECT COUNT(*) FROM port_cube_requests")==operation);if(operation)assert(value(db,"SELECT state FROM port_cube_requests")=="PREPARED");assert(action()==expected);
}
}
frozen(db,b,leader,false,true);assert(prepareLive(db,b,grant)==Store::Prepared);OwnerGrant revoked;assert(owner.Revoke(b,leader,1,&grant,revoked)==O::Revoked&&executeLive(db,b,grant,receipt)==Store::Blocked);
frozen(db,b,leader,false,true);assert(prepareLive(db,b,grant)==Store::Prepared);sql(db,"UPDATE player SET gold=1001");assert(executeLive(db,b,grant,receipt)==Store::Complete&&receipt.result=="gold_changed"&&receipt.fee==0&&receipt.awards.empty());
assert(executeLive(db,b,grant,receipt)==Store::Complete&&number(db,"SELECT gold FROM player")==1001&&number(db,"SELECT count FROM item WHERE id=10")==10);
puts("PASS every authorized prepare/execute SQL failure/warning, original-owner revoke refusal, non-ok DONE replay without refund/retry charge");
for(const auto& mode:{"prepare-write","prepare-commit","execute-write","execute-commit"}) {
sql(db,"SELECT RELEASE_LOCK(CONCAT('m2_cube:',DATABASE()))");const auto child=spawnWorker(mode);int status=0;assert(waitpid(child,&status,0)==child&&WIFEXITED(status)&&WEXITSTATUS(status)==96);
const bool paid=std::string(mode)=="execute-commit",prepared=std::string(mode)!="prepare-write";
assert(number(db,"SELECT gold FROM player")==uint64_t(paid?700:1000)&&number(db,"SELECT COUNT(*) FROM port_cube_requests")==prepared);
assert(owner.Acquire(std::string(32,'d'),leader)==O::Acquired);const auto replacement=original(b,leader);
assert(prepareLive(db,b,replacement)==Store::Blocked&&executeLive(db,b,replacement,receipt)!=Store::Complete); // newer broker alone is NOT a live owner or automatic retry permission
}
puts("PASS process exits before/after Prepare and Execute COMMIT: durable prepared/done states, no generation-based automatic execution/redraw/thaw");
}
@@ -0,0 +1,51 @@
int main(){auto& m=ITEM_MANAGER::instance();std::vector<PortEconomy::Reward> output(1);output[0].id=77;
assert(!PortCubeBuildRewardTemplates(0,1,output)&&!PortCubeBuildRewardTemplates(10,0,output)&&!PortCubeBuildRewardTemplates(10,101,output));
m.tables[10].sAddonType=1;m.tables[10].bGainSocketPct=2;
m.tables[11].bType=ITEM_UNIQUE;m.tables[11].values[2]=0;
m.tables[12].bType=ITEM_UNIQUE;m.tables[12].values[2]=1;
m.tables[13].limits[0]={LIMIT_REAL_TIME,60};
m.tables[14].limits[0]={LIMIT_TIMER_BASED_ON_WEAR,0};
m.tables[15].bType=ITEM_BLEND;m.tables[16].bType=ITEM_DS;
m.tables[17].bType=ITEM_ELK;m.tables[50300];m.tables[ITEM_AUTO_HP_RECOVERY_S];
m.tables[18].bType=ITEM_COSTUME;m.tables[18].bSubType=COSTUME_SASH;m.tables[18].values[0]=4;
CItem sentinel(999);m.m_VIDMap[0]=&sentinel;
for(auto v:{10u,11u,12u,13u,14u,15u,16u,18u,50300u,unsigned(ITEM_AUTO_HP_RECOVERY_S)}) {
saves=packets=logs=timers=magic=draws=0;const auto beforeAlloc=allocations,beforeDestroy=destroys;const auto next=cursor;
assert(PortCubeBuildRewardTemplates(v,2,output)&&!PortCubeCurrentFactorySlot()&&output.size()==2);
assert(output[0].id==next&&output[1].id==next+1&&cursor==next+2&&output[0].count==1&&output[0].vnum==v);
assert(!saves&&!packets&&!logs&&!timers&&!magic&&allocations==beforeAlloc+2&&destroys==beforeDestroy+2);
assert(m.m_map_pkItemByID.empty()&&m.m_VIDMap.size()==1&&m.m_VIDMap[0]==&sentinel&&m.m_dwVIDCount==0&&m.m_set_pkItemForDelayedSave.empty());
if(v==10){assert(output[0].types[0]==7&&output[0].values[0]==4&&output[0].sockets[0]==1&&output[0].sockets[1]==1);Extra extra;std::memcpy(&extra,output[0].extra,sizeof(extra));assert(extra.types[1]==8&&extra.values[1]==19);}
if(v==11)assert(output[0].sockets[2]==7);
if(v==12)assert(output[0].sockets[2]==123463);
if(v==13)assert(output[0].sockets[0]>60);
if(v==14)assert(output[0].sockets[0]==36000);
if(v==15)assert(output[0].sockets[0]==11&&output[0].sockets[2]==13);
if(v==16)assert(output[0].types[0]==13&&output[0].values[0]==14&&output[0].sockets[0]==15);
if(v==18)assert(output[0].sockets[0]==11&&draws==2);
if(v==50300)assert(output[0].sockets[0]==1);
if(v==unsigned(ITEM_AUTO_HP_RECOVERY_S))assert(output[0].sockets[2]==7);
}
const auto saved=PortEconomy::Hex(output.data(),output.size()*sizeof(output[0]));
failCount=true;auto beforeDestroy=destroys;assert(!PortCubeBuildRewardTemplates(10,2,output)&&destroys==beforeDestroy+1&&!PortCubeCurrentFactorySlot());failCount=false;
assert(PortEconomy::Hex(output.data(),output.size()*sizeof(output[0]))==saved);
failLookupAt=lookupCount+2;assert(!PortCubeBuildRewardTemplates(10,2,output)&&!PortCubeCurrentFactorySlot());failLookupAt=0;
assert(PortEconomy::Hex(output.data(),output.size()*sizeof(output[0]))==saved);
failLookupAt=lookupCount+3;beforeDestroy=destroys;assert(!PortCubeBuildRewardTemplates(10,2,output)&&destroys==beforeDestroy+1&&!PortCubeCurrentFactorySlot());failLookupAt=0;
assert(PortEconomy::Hex(output.data(),output.size()*sizeof(output[0]))==saved);
throwAddon=true;beforeDestroy=destroys;try{PortCubeBuildRewardTemplates(10,2,output);assert(false);}catch(const std::runtime_error&){}throwAddon=false;
assert(destroys==beforeDestroy+1&&!PortCubeCurrentFactorySlot()&&PortEconomy::Hex(output.data(),output.size()*sizeof(output[0]))==saved);
assert(!PortCubeBuildRewardTemplates(17,1,output));
skills=false;const auto beforeReserve=reserveCalls;assert(!PortCubeBuildRewardTemplates(50300,1,output)&&reserveCalls==beforeReserve);skills=true;
PortEconomy::Reward persisted;persisted.id=800;persisted.vnum=18;persisted.count=1;persisted.sockets[0]=17;persisted.extra[68]=255;
const auto priorDraws=draws,priorCursor=cursor;auto* restored=PortCubeRestoreItem(persisted,nullptr);assert(restored&&restored->GetSocket(0)==17&&restored->GetPortExtra().name[24]==char(255)&&draws==priorDraws&&cursor==priorCursor);m.DestroyItem(restored);
// The ordinary factory still allocates/registers, saves/logs and starts clocks.
auto* ordinary=m.CreateItem(12);assert(ordinary&&!ordinary->PortCubeIsTemplate()&&ordinary->GetVID()&&timers&&saves&&logs);
assert(m.m_map_pkItemByID.count(ordinary->GetID())&&m.m_VIDMap.count(ordinary->GetVID()));
m.DestroyItem(ordinary);assert(m.m_map_pkItemByID.empty()&&m.m_VIDMap.size()==1&&packets);
// No reentrant facade and no use of the template bridge with an explicit ID.
PortCubeFactorySlot slot;slot.id=800;slot.vnum=10;{SlotScope scope(slot);assert(!PortCubeBuildRewardTemplates(10,1,output));assert(!m.CreateItem(10,1,800,false,-1,true)&&!slot.item);}
slot={};slot.id=800;slot.vnum=10;m.m_map_pkItemByID[800]=&sentinel;{SlotScope scope(slot);assert(!m.CreateItem(10,1,0,false,-1,true)&&!slot.item&&m.m_map_pkItemByID[800]==&sentinel);}m.m_map_pkItemByID.clear();
assert(!PortCubeCurrentFactorySlot());
puts("PASS actual CreateItem/DestroyItem/Save/socket/attribute bodies: new-item addon/socket/unique/clock/blend/skill/DS metadata, complete extra bytes, no save/log/timer/registry/VID side effects, failure/exception cleanup, ordinary path unchanged; explicit platform/primitive substitutes");
}
@@ -0,0 +1,76 @@
// FreeBSD-only offline link probe. Links the real game objects, replacing only
// the executable main symbol. Synthetic in-memory proto, no sockets or DB.
#include "stdafx.h"
#include "char.h"
#include "item.h"
#include "item_manager.h"
#include "item_addon.h"
#include "skill.h"
#include "unique_item.h"
#include "desc_client.h"
#include "port_cube_factory.h"
#include "port_cube_ids.h"
#include "event.h"
#include "utils.h"
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <ctime>
struct NativeItemManager:ITEM_MANAGER {
size_t Delayed()const{return m_set_pkItemForDelayedSave.size();}
void DropTemplate(LPITEM item){assert(item->PortCubeIsTemplate()&&!item->GetOwner());assert(Find(item->GetID())==item);m_map_pkItemByID.erase(item->GetID());m_VIDMap.erase(item->GetVID());M2_DESTROY_ITEM(item);}
};
int main()
{
assert(!db_clientdesc&&!event_count());
NativeItemManager manager;CItemAddonManager addons;CSkillManager skills;
std::vector<TItemTable> tables(10);
for(unsigned i=0;i<6;++i){tables[i].dwVnum=10000+i;tables[i].bSize=1;tables[i].bType=ITEM_USE;}
tables[0].bType=ITEM_WEAPON;tables[0].bSubType=WEAPON_SWORD;
tables[0].sAddonType=-1;tables[0].bGainSocketPct=2;
tables[1].bType=ITEM_UNIQUE;tables[1].alValues[0]=600;
tables[2].bType=ITEM_UNIQUE;tables[2].alValues[0]=600;tables[2].alValues[2]=1;
tables[3].aLimits[0].bType=LIMIT_REAL_TIME;tables[3].aLimits[0].lValue=60;
tables[4].aLimits[0].bType=LIMIT_TIMER_BASED_ON_WEAR;tables[4].aLimits[0].lValue=60;
tables[5].bType=ITEM_ELK;
tables[6].dwVnum=ITEM_AUTO_HP_RECOVERY_S;tables[6].bType=ITEM_USE;tables[6].bSize=1;tables[6].alValues[0]=7;
tables[7].dwVnum=50300;tables[7].bType=ITEM_USE;tables[7].bSize=1;
tables[8].dwVnum=10006;tables[8].bType=ITEM_USE;tables[8].bSize=1;tables[8].dwFlags=ITEM_FLAG_STACKABLE;
tables[9].dwVnum=10007;tables[9].bType=ITEM_COSTUME;tables[9].bSubType=COSTUME_SASH;tables[9].bSize=1;tables[9].alValues[0]=4;
std::sort(tables.begin(),tables.end(),[](const auto& a,const auto& b){return a.dwVnum<b.dwVnum;});
assert(manager.Initialize(tables.data(),tables.size()));
TItemIDRangeTable range{};range.dwMin=1000;range.dwMax=2000;range.dwUsableItemIDMin=1000;
assert(manager.SetMaxItemID(range));
uint32_t next=1000;
for(uint32_t vnum:{10000u,10001u,10002u,10003u,10004u,10007u,uint32_t(ITEM_AUTO_HP_RECOVERY_S)}) {
std::vector<PortEconomy::Reward> images;
assert(PortCubeBuildRewardTemplates(vnum,2,images)&&images.size()==2);
assert(!event_count()&&!PortCubeCurrentFactorySlot()&&!db_clientdesc);
for(const auto& image:images) {
assert(image.id==next++&&image.vnum==vnum&&image.count==1&&!manager.Find(image.id));
if(vnum==10000){assert(image.sockets[0]==1&&image.sockets[1]==1);bool addon=false;for(auto type:image.types)if(type==APPLY_NORMAL_HIT_DAMAGE_BONUS)addon=true;assert(addon);}
if(vnum==10001)assert(image.sockets[2]==600);
if(vnum==10002)assert(image.sockets[2]>600);
if(vnum==10003)assert(image.sockets[0]>60);
if(vnum==10004)assert(image.sockets[0]==60);
if(vnum==10007)assert(image.sockets[0]>=11&&image.sockets[0]<=19);
if(vnum==ITEM_AUTO_HP_RECOVERY_S)assert(image.sockets[2]==7);
}
}
std::vector<PortEconomy::Reward> untouched(1);untouched[0].id=77;
assert(!PortCubeBuildRewardTemplates(10005,1,untouched)&&untouched[0].id==77);
assert(!PortCubeBuildRewardTemplates(50300,1,untouched)&&untouched[0].id==77);
assert(!manager.FindByVID(0)&&!manager.FindByVID(1));
std::vector<uint32_t> after;assert(PortCubeReserveItemIDs(1,after)&&after[0]==next);
auto* old=manager.CreateItem(10006,10);assert(old&&manager.Delayed()==1);const auto oldID=old->GetID();
PortEconomy::Reward persisted;persisted.id=oldID;persisted.vnum=10006;persisted.count=4;persisted.sockets[0]=-123;persisted.extra[68]=255;
auto* restored=PortCubeRestoreItem(persisted,old);assert(restored&&restored->GetCount()==4&&restored->GetSocket(0)==-123&&restored->GetPortExtra().name[24]==char(255)&&manager.Find(oldID)==old);
manager.SaveSingleItem(restored);assert(!db_clientdesc); // template must never emit a DB delete/save
assert(manager.PortCubeSwapRegistry({old},{restored})&&manager.Find(oldID)==restored&&manager.FindByVID(restored->GetVID())==restored&&!manager.Delayed());
old->PortCubeMarkTemplate();M2_DESTROY_ITEM(old);assert(manager.Find(oldID)==restored);
manager.DropTemplate(restored);std::vector<uint32_t> nextID;assert(PortCubeReserveItemIDs(1,nextID)&&nextID[0]==oldID+1);
manager.Update();manager.GracefulShutdown();
assert(!db_clientdesc&&!event_count());
puts("PASS real FreeBSD game objects: actual addon/socket/clock/sash initialization, exact persisted same-ID restore, atomic registry replacement and old-object cleanup, no template SaveSingleItem/DB write/events or restore ID consumption; synthetic proto, no actor freeze/live acceptance");
}
@@ -0,0 +1,116 @@
// Explicit platform/item primitive substitutes for the real factory TU probe.
// Tests splice the real CreateItem, DestroyItem, Save and metadata setters.
#include <cassert>
#include <algorithm>
#include <cstdio>
#include <cstdint>
#include <cstring>
#include <map>
#include <set>
#include <unordered_set>
#include <vector>
#include <stdexcept>
#include "src/server/game/src/port_cube_factory.h"
#include "src/server/common/cube_image.h"
using DWORD=uint32_t;using BYTE=uint8_t;
using WORD=uint16_t;
constexpr unsigned INVENTORY=1,RESERVED_WINDOW=0,INVENTORY_MAX_NUM=225,ITEM_FLAG_STACKABLE=1;
constexpr unsigned ITEM_COSTUME=7,COSTUME_SASH=1,SASH_GRADE_VALUE_FIELD=0,SASH_ABSORPTION_SOCKET=0;
constexpr int SASH_GRADE_1_ABS=1,SASH_GRADE_2_ABS=5,SASH_GRADE_3_ABS=10,SASH_GRADE_4_ABS_MIN=11,SASH_GRADE_4_ABS_MAX_COMB=19;
constexpr int ITEM_ELK=1,ITEM_UNIQUE=2,ITEM_BLEND=3,ITEM_QUEST=4,ITEM_WEAPON=5,ITEM_DS=6;
constexpr int LIMIT_REAL_TIME=1,LIMIT_TIMER_BASED_ON_WEAR=2,ITEM_LIMIT_MAX_NUM=2,ITEM_SOCKET_MAX_NUM=3;
constexpr int ITEM_FLAG_MAKECOUNT=2,ITEM_MAX_COUNT=2000,ITEM_SOCKET_UNIQUE_REMAIN_TIME=2;
constexpr int ITEM_AUTO_HP_RECOVERY_S=101,ITEM_AUTO_HP_RECOVERY_M=102,ITEM_AUTO_HP_RECOVERY_L=103,ITEM_AUTO_HP_RECOVERY_X=104;
constexpr int ITEM_AUTO_SP_RECOVERY_S=105,ITEM_AUTO_SP_RECOVERY_M=106,ITEM_AUTO_SP_RECOVERY_L=107,ITEM_AUTO_SP_RECOVERY_X=108;
constexpr int REWARD_BOX_ITEM_AUTO_SP_RECOVERY_XS=109,REWARD_BOX_ITEM_AUTO_SP_RECOVERY_S=110,REWARD_BOX_ITEM_AUTO_HP_RECOVERY_XS=111,REWARD_BOX_ITEM_AUTO_HP_RECOVERY_S=112;
constexpr int FUCKING_BRAZIL_ITEM_AUTO_SP_RECOVERY_S=113,FUCKING_BRAZIL_ITEM_AUTO_HP_RECOVERY_S=114,ITEM_SKILLFORGET_VNUM=700,ITEM_SKILLFORGET2_VNUM=701;
constexpr int HEADER_GD_ITEM_DESTROY=1;
constexpr int MAX_NORM_ATTR_NUM=5,ITEM_ATTRIBUTE_MAX_NUM=7;
static unsigned saves=0,packets=0,logs=0,timers=0,allocations=0,destroys=0,draws=0,magic=0,reserveCalls=0;
static unsigned lookupCount=0,failLookupAt=0;static uint32_t cursor=1000;
static bool failCount=false,throwAddon=false,skills=true;
int number(int first,int){++draws;return first;}
int get_global_time(){return 123456;}
bool LC_IsKorea(){return false;}bool LC_IsYMIR(){return false;}
#define sys_err(...) ((void)0)
#define sys_log(...) ((void)0)
#define MINMAX(a,b,c) ((b)<(a)?(a):((b)>(c)?(c):(b)))
#define IS_SET(a,b) ((a)&(b))
#define itertype(c) decltype(c)::iterator
#define get_pointer(p) (p)
#define thecore_memcpy std::memcpy
#define M2_NEW new
#define M2_DELETE(p) delete (p)
#define M2_DESTROY_ITEM(p) ITEM_MANAGER::instance().DestroyItem(p)
struct Desc {const char* GetHostName(){return "mock";}};
struct CHARACTER {struct Points{CItem* pItems[400]={};WORD bItemGrid[400]={};CItem* pCubeItems[4]={};CItem* pSashMaterials[3]={};}m_pointsInstant;int64_t gold=1000;CItem* m_pQuestItem=nullptr;
const char* GetName(){return "mock";}unsigned GetPlayerID(){return 1;}Desc* GetDesc(){return nullptr;}
CItem* GetInventoryItem(unsigned cell){return m_pointsInstant.pItems[cell];}void SetGold(int64_t value){gold=value;}
bool PortCubeInstallImage(const PortCube::InventoryImage&,const std::vector<CItem*>&,const std::vector<CItem*>&);};
using LPCHARACTER=CHARACTER*;
struct CHARACTER_MANAGER {static CHARACTER_MANAGER& instance(){static CHARACTER_MANAGER m;return m;}CHARACTER* Find(unsigned){return nullptr;}};
struct LogManager {static LogManager& instance(){static LogManager m;return m;}template<class... T>void ItemLog(T...){++logs;}};
namespace PortCube {constexpr unsigned ItemWrite=1;}
void PortCubeAssetMutation(CHARACTER*,unsigned){++saves;}
void PortCubeAssetMutationByPID(unsigned,unsigned){++saves;}
struct DBDesc {void DBPacketHeader(unsigned,unsigned,unsigned){++packets;}void Packet(const void*,unsigned){++packets;}}dbDesc,*db_clientdesc=&dbDesc;
struct CSkillProto {};
struct CSkillManager {static CSkillManager& instance(){static CSkillManager m;return m;}CSkillProto* Get(unsigned){static CSkillProto p;return skills?&p:nullptr;}};
struct Limit {unsigned type=0;long value=0;};
struct TItemTable {unsigned bType=ITEM_WEAPON,bSubType=0,bSize=1;union{unsigned flags=0;unsigned dwFlags;};long values[3]={7,9,0};Limit limits[2];int sAddonType=0;unsigned bAlterToMagicItemPct=100,bGainSocketPct=0;};
struct Attr {BYTE bType=0;short sValue=0;};
#pragma pack(push,1)
struct Extra {int32_t sockets[5]={};BYTE types[8]={};int16_t values[8]={};char name[25]={};};
#pragma pack(pop)
struct CItem {
unsigned vnum,id=0,vid=0,m_dwCount=0,m_dwLastOwnerPID=0,m_wCell=0,m_bWindow=0;CHARACTER* m_pOwner=nullptr;
bool m_portCubeTemplate=false,m_bSkipSave=false,locked=false,exchanging=false,clock=false;const TItemTable* proto=nullptr;
long m_alSockets[3]={};Attr m_aAttr[7];Extra m_portExtra;
explicit CItem(unsigned value):vnum(value){++allocations;}~CItem(){++destroys;}
void Initialize(){id=vid=m_dwCount=0;m_portCubeTemplate=m_bSkipSave=false;}
void SetProto(const TItemTable* p){proto=p;}void SetMaskVnum(unsigned){}
void PortCubeMarkTemplate(){m_portCubeTemplate=true;m_bSkipSave=true;}bool PortCubeIsTemplate()const{return m_portCubeTemplate;}
unsigned GetType(){return proto->bType;}unsigned GetVnum(){return vnum;}unsigned GetOriginalVnum(){return vnum;}
unsigned GetSubType(){return proto->bSubType;}unsigned GetSize(){return proto->bSize;}
void SetCell(CHARACTER* owner,unsigned cell){m_pOwner=owner;m_wCell=cell;}unsigned GetCell(){return m_wCell;}
void SetWindow(unsigned w){m_bWindow=w;}unsigned GetWindow(){return m_bWindow;}
bool isLocked(){return locked;}bool IsExchanging(){return exchanging;}bool PortCubeHasPendingMutation(){return clock;}
void PortCubeInitNewAttach();bool PortCubeRestoreMetadata(const PortEconomy::Reward&);void PortCubeAttachRestored(CHARACTER*,WORD);
bool IsStackable(){return proto->flags&1;}unsigned GetFlag(){return proto->flags;}long GetValue(unsigned i){return proto->values[i];}
void SetID(unsigned value){id=value;}unsigned GetID(){return id;}void SetVID(unsigned value){vid=value;}unsigned GetVID(){return vid;}
void SetSkipSave(bool value){m_bSkipSave=value;}bool GetSkipSave(){return m_bSkipSave;}
void Save();void UpdatePacket(){if(!m_portCubeTemplate)++packets;}
bool SetCount(unsigned value){if(failCount)return false;m_dwCount=value;UpdatePacket();Save();return true;}unsigned GetCount(){return m_dwCount;}
void StartUniqueExpireEvent(){++timers;}void StartRealTimeExpireEvent(){++timers;}void StartTimerBasedOnWearExpireEvent(){++timers;}
unsigned GetLimitType(unsigned i){return proto->limits[i].type;}long GetLimitValue(unsigned i){return proto->limits[i].value;}
bool IsEquipped(){return false;}bool IsDragonSoul(){return GetType()==ITEM_DS;}
void SetSocket(int,long,bool=true);long GetSocket(unsigned i){return m_alSockets[i];}
void SetAttribute(int,BYTE,short);void SetForceAttribute(int,BYTE,short);
BYTE GetAttributeType(unsigned i){return m_aAttr[i].bType;}short GetAttributeValue(unsigned i){return m_aAttr[i].sValue;}
void ApplyAddon(int){if(throwAddon)throw std::runtime_error("addon");SetAttribute(0,7,number(4,6));SetForceAttribute(8,8,19);}
void AlterToMagicItem(){++magic;SetAttribute(1,9,10);}void AlterToSocketItem(int count){for(int i=0;i<std::min(count,3);++i)SetSocket(i,1);}
CHARACTER* GetOwner(){return m_pOwner;}void* GetSectree(){return nullptr;}unsigned GetLastOwnerPID(){return m_dwLastOwnerPID;}
void RemoveFromGround(){}void RemoveFromCharacter(){}const char* GetName(){return "mock";}
void SetSIGVnum(unsigned){}const Extra& GetPortExtra(){return m_portExtra;}
};
using LPITEM=CItem*;
struct CSpecialItemGroup {enum {QUEST=1,SPECIAL=2};unsigned m_bType=0;bool Contains(unsigned){return false;}};
struct ITEM_MANAGER {
using ITEM_VID_MAP=std::map<DWORD,LPITEM>;
ITEM_VID_MAP m_VIDMap;std::map<DWORD,LPITEM> m_map_pkItemByID;
std::map<DWORD,CSpecialItemGroup*> m_map_pkQuestItemGroup,m_map_pkSpecialItemGroup;
std::unordered_set<LPITEM> m_set_pkItemForDelayedSave;
std::map<DWORD,TItemTable> tables;unsigned m_dwVIDCount=0;
static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;}
unsigned GetMaskVnum(unsigned){return 0;}unsigned GetNewID(){return cursor++;}
TItemTable* GetTable(unsigned v){++lookupCount;if(lookupCount==failLookupAt)return nullptr;auto it=tables.find(v);return it==tables.end()?nullptr:&it->second;}
void DelayedSave(LPITEM item){++saves;m_set_pkItemForDelayedSave.insert(item);}
LPITEM CreateItem(DWORD,DWORD=1,DWORD=0,bool=false,int=-1,bool=false);void DestroyItem(LPITEM);
LPITEM Find(unsigned id){auto it=m_map_pkItemByID.find(id);return it==m_map_pkItemByID.end()?nullptr:it->second;}
LPITEM FindByVID(unsigned id){auto it=m_VIDMap.find(id);return it==m_VIDMap.end()?nullptr:it->second;}
bool PortCubeSwapRegistry(const std::vector<LPITEM>&,const std::vector<LPITEM>&);
};
bool PortCubeReserveItemIDs(unsigned count,std::vector<uint32_t>& out){++reserveCalls;out.clear();for(unsigned i=0;i<count;++i)out.push_back(cursor++);return true;}
bool Blend_Item_find(unsigned){return true;}
bool Blend_Item_set_value(LPITEM item){item->SetSocket(0,11);item->SetSocket(1,12);item->SetSocket(2,13);return true;}
struct DSManager {static DSManager& instance(){static DSManager m;return m;}bool DragonSoulItemInitialize(LPITEM item){item->SetForceAttribute(0,13,14);item->SetSocket(0,15);return true;}};
@@ -0,0 +1,96 @@
#define main cubeBaseMain
#include "cube_batch_probe.cpp"
#undef main
#include "src/server/common/cube_gold_store.h"
using G=GoldIntentStore<TestDB>;
static void initializeGold(TestDB& db) {
initializeGoldAddon(db);
}
static void resetGold(TestDB& db,const Batch& b) {
db.failAt=db.warnAt=0;db.after={};db.ambiguous=db.rejectCommit=false;db.Rollback();
sql(db,"DELETE FROM port_cube_gold_sources");sql(db,"DELETE FROM port_cube_gold_intents");reset(db,b);
}
static GoldIntent credit(const Batch& b,unsigned sequence=1,uint64_t amount=250) {
GoldIntent i;i.account=b.account;i.player=b.player;i.epoch=b.epoch;i.sequence=sequence;i.amount=amount;i.source=2;
i.owner=b.owner;i.request=b.token;i.event=std::string(31,'e')+char('0'+sequence);return i;
}
static void settle(TestDB& db,const Batch& b) {
Store store(db,proto);Store::Receipt receipt;
assert(store.Prepare(b,[]{return 1u;})==Store::Prepared);
assert(store.Execute(b.token,1,1,receipt)==Store::Complete&&receipt.fee==300);
}
static void waitWorker(pid_t child,int code) {int status=0;assert(waitpid(child,&status,0)==child&&WIFEXITED(status)&&WEXITSTATUS(status)==code);}
int main(int argc,char** argv) {
assert(argc==2||argc==3);address=argv[1];executable=argv[0];TestDB db;G gold(db,proto);G::Receipt receipt;
if(argc==3) {
Batch b;std::string phase,image;FenceStore<TestDB> fence(db,proto);
assert(fence.Recover(1,1,b,phase,image)==FenceStore<TestDB>::Done);
std::vector<GoldIntent> pending;assert(gold.Pending(b,pending)==G::Stored);
const auto i=credit(b);
const std::string mode=argv[2];
if(mode.find("crash-")==0)db.after=[&](const std::string& statement){
if((mode=="crash-wallet"&&statement.find("UPDATE player SET gold=gold+")==0)||
(mode=="crash-receipt"&&statement.find("UPDATE port_cube_gold_intents SET state='APPLIED'")==0)||
(mode=="crash-commit"&&statement=="COMMIT"))_Exit(79);
};
assert(gold.Apply(i.event,1,1,receipt)==G::Applied);return 77;
}
initialize(db);initializeGold(db);auto b=batch();auto i=credit(b);std::vector<GoldIntent> pending;FenceStore<TestDB> fence(db,proto);std::string image;
assert(EncodeGoldIntent(i).size()==GoldIntentBytes);GoldIntent decoded;
assert(DecodeGoldIntent(EncodeGoldIntent(i),decoded));for(unsigned n=0;n<GoldIntentBytes;++n)assert(!DecodeGoldIntent(EncodeGoldIntent(i).substr(0,n),decoded));
assert(!DecodeGoldIntent(EncodeGoldIntent(i)+"x",decoded));auto bad=i;bad.amount=0;assert(!ValidGoldIntent(bad));bad=i;bad.sequence=GoldIntentLimit+1;assert(!ValidGoldIntent(bad));
resetGold(db,b);assert(gold.Ready());assert(gold.Enqueue(b,i)==G::Stored&&gold.Enqueue(b,i)==G::Stored);
auto different=i;different.amount++;assert(gold.Enqueue(b,different)==G::Refused);
auto second=credit(b,2,400);assert(gold.Enqueue(b,second)==G::Stored);auto gap=credit(b,4);assert(gold.Enqueue(b,gap)==G::Refused);
assert(gold.Apply(i.event,1,1,receipt)==G::Blocked); // no craft result, no implicit Execute
settle(db,b);assert(fence.Resync(b,image)==FenceStore<TestDB>::Refused&&image.empty());
assert(gold.Apply(second.event,1,1,receipt)==G::Blocked);
assert(gold.Apply(i.event,2,1,receipt)==G::Refused);
db.ambiguous=true;assert(gold.Apply(i.event,1,1,receipt)==G::Retry);assert(number(db,"SELECT gold FROM player")==950);
assert(gold.Apply(i.event,1,1,receipt)==G::Applied&&receipt.before==700&&receipt.after==950);assert(gold.Enqueue(b,i)==G::Applied);
assert(gold.Pending(b,pending)==G::Stored&&pending.size()==1&&pending[0].event==second.event);
assert(fence.Resync(b,image)==FenceStore<TestDB>::Refused);
assert(gold.Apply(second.event,1,1,receipt)==G::Applied&&number(db,"SELECT gold FROM player")==1350);
assert(fence.Resync(b,image)==FenceStore<TestDB>::Refused); // SQL has no pending credit, source still open
GoldSourceSeal seal;static_cast<GoldSourceBinding&>(seal)=GoldSourceFor(b,8,7,6);seal.events={i.event,second.event};
assert(gold.CloseSource(b,seal)==G::Stored);
assert(gold.Enqueue(b,credit(b,3))==G::Blocked); // sealing closes new admission before Resync
assert(fence.Resync(b,image)==FenceStore<TestDB>::Done);
auto third=credit(b,3);assert(gold.Enqueue(b,third)==G::Blocked); // resync is a closed admission boundary
sql(db,"UPDATE port_cube_gold_intents SET state='QUEUED',before_gold=0,after_gold=0 WHERE seq=2");assert(fence.Release(b,image)==FenceStore<TestDB>::Refused);
sql(db,"UPDATE port_cube_gold_intents SET state='APPLIED',before_gold=950,after_gold=1350 WHERE seq=2");
assert(fence.Release(b,image)==FenceStore<TestDB>::Done);sql(db,"UPDATE player SET gold=1400");
assert(gold.Apply(i.event,1,1,receipt)==G::Applied&&number(db,"SELECT gold FROM player")==1400); // history replay never re-adds
assert(fence.Release(b,image)==FenceStore<TestDB>::Done); // release ACK retry after normal later wallet writes
puts("PASS durable positive intents, order/idempotency, immutable body, no implicit craft, resync/release barrier and historical replay");
resetGold(db,b);db.ambiguous=true;assert(gold.Enqueue(b,i)==G::Retry);assert(gold.Enqueue(b,i)==G::Stored&&number(db,"SELECT COUNT(*) FROM port_cube_gold_intents")==1);
settle(db,b);sql(db,"UPDATE player SET gold=701");assert(gold.Apply(i.event,1,1,receipt)==G::Blocked&&number(db,"SELECT gold FROM player")==701);sql(db,"UPDATE player SET gold=700");
sql(db,"UPDATE port_cube_requests SET successes=0");assert(gold.Apply(i.event,1,1,receipt)==G::Blocked);sql(db,"UPDATE port_cube_requests SET successes=3");
sql(db,"UPDATE port_cube_fences SET phase='ABORTED',drain_state=2");assert(gold.Apply(i.event,1,1,receipt)==G::Blocked);
sql(db,"UPDATE port_cube_fences SET phase='FROZEN',drain_state=1");
auto overflow=credit(b,2,PortEconomy::GoldLimit);assert(gold.Enqueue(b,overflow)==G::Stored);
assert(gold.Apply(i.event,1,1,receipt)==G::Applied);assert(gold.Apply(overflow.event,1,1,receipt)==G::Blocked);
assert(gold.Pending(b,pending)==G::Stored&&pending.size()==1);
sql(db,"UPDATE port_cube_gold_intents SET after_gold=951 WHERE seq=1");assert(gold.Pending(b,pending)==G::Blocked&&fence.Resync(b,image)!=FenceStore<TestDB>::Done);
sql(db,"UPDATE port_cube_gold_intents SET after_gold=950 WHERE seq=1");
sql(db,"UPDATE port_cube_gold_version SET version=1");assert(!gold.Ready());sql(db,"UPDATE port_cube_gold_version SET version=2");
#ifdef PORT_CUBE_MYSQL
sql(db,"ALTER TABLE port_cube_gold_intents ENGINE=MyISAM");assert(!gold.Ready());sql(db,"ALTER TABLE port_cube_gold_intents ENGINE=InnoDB");
#endif
puts("PASS stale wallet, corrupt receipt/journal, aborted drain, overflow and incompatible addon refused without losing accepted intent");
resetGold(db,b);db.statements=0;assert(gold.Enqueue(b,i)==G::Stored);const int enqueueCount=db.statements;
for(int at=1;at<=enqueueCount;++at){resetGold(db,b);db.statements=0;db.failAt=at;auto r=gold.Enqueue(b,i);db.failAt=0;assert(r!=G::Stored&&r!=G::Applied);assert(number(db,"SELECT COUNT(*) FROM port_cube_gold_intents")==0&&number(db,"SELECT gold FROM player")==1000);assert(gold.Enqueue(b,i)==G::Stored);}
resetGold(db,b);assert(gold.Enqueue(b,i)==G::Stored);settle(db,b);db.statements=0;assert(gold.Apply(i.event,1,1,receipt)==G::Applied);const int applyCount=db.statements;
for(unsigned warning=0;warning<2;++warning)for(int at=1;at<=applyCount;++at){resetGold(db,b);assert(gold.Enqueue(b,i)==G::Stored);settle(db,b);db.statements=0;if(warning)db.warnAt=at;else db.failAt=at;auto r=gold.Apply(i.event,1,1,receipt);db.failAt=db.warnAt=0;assert(r!=G::Applied&&number(db,"SELECT gold FROM player")==700&&value(db,"SELECT state FROM port_cube_gold_intents")=="QUEUED");assert(gold.Apply(i.event,1,1,receipt)==G::Applied);}
resetGold(db,b);assert(gold.Enqueue(b,i)==G::Stored);settle(db,b);db.rejectCommit=true;assert(gold.Apply(i.event,1,1,receipt)==G::Retry&&number(db,"SELECT gold FROM player")==700);assert(gold.Apply(i.event,1,1,receipt)==G::Applied);
puts("PASS every enqueue/apply SQL failure, warning rollback, rejected and ambiguous commit");
for(const auto& mode:{"crash-wallet","crash-receipt","crash-commit"}) {
resetGold(db,b);assert(gold.Enqueue(b,i)==G::Stored);settle(db,b);waitWorker(spawnWorker(mode),79);
assert(number(db,"SELECT gold FROM player")==(std::string(mode)=="crash-commit"?950:700));
waitWorker(spawnWorker("recover"),77);assert(number(db,"SELECT gold FROM player")==950&&value(db,"SELECT state FROM port_cube_gold_intents")=="APPLIED");
}
resetGold(db,b);assert(gold.Enqueue(b,i)==G::Stored);settle(db,b);const auto first=spawnWorker("recover"),other=spawnWorker("recover");waitWorker(first,77);waitWorker(other,77);assert(number(db,"SELECT gold FROM player")==950);
puts("PASS separate-process crash before/after receipt/COMMIT, restart pending lookup and concurrent duplicate application; no live reward producer");
}
@@ -0,0 +1,73 @@
#define PORT_CUBE_OWNER_EMBED
#include "cube_owner_probe.cpp"
#include "src/server/common/cube_image_ack.h"
using A=ImageAckStore<TestDB>;
static std::string issued(TestDB& db,const Batch& b,const OwnerLeader& leader) {
frozen(db,b,leader);sql(db,"DELETE FROM port_cube_image_acks");
O owner(db,proto);F fence(db,proto);std::string image;const auto grant=original(b,leader);
assert(fence.Resync(b,image,[&](const std::string& bytes){return owner.LiveImageWithin(b,grant,bytes);})==F::Done);return image;
}
#ifndef PORT_CUBE_ACK_EMBED
int main(int argc,char** argv) {
assert(argc==2||argc==3);address=argv[1];executable=argv[0];TestDB db;O owner(db,proto);A ack(db,proto);F fence(db,proto);const auto b=batch();OwnerLeader leader;
if(argc==3) {
// The child is a new broker: bind its own live job before injecting exit.
assert(owner.Acquire(std::string(32,'e'),leader)==O::Acquired);const auto image=issued(db,b,leader);
const std::string mode=argv[2];db.after=[&](const std::string& q){if((mode=="ack-insert"&&q.find("INSERT INTO port_cube_image_acks")==0)||(mode=="ack-commit"&&q=="COMMIT"))_Exit(95);};
ack.AcknowledgeLive(b,original(b,leader),image);assert(false);
}
initialize(db);initializeGoldAddon(db);initializeOwnerAddon(db);initializeImageAckAddon(db);
reset(db,b);
assert(owner.Acquire(std::string(32,'d'),leader)==O::Acquired);
auto image=issued(db,b,leader);auto grant=original(b,leader);
db.ambiguous=true;assert(ack.AcknowledgeLive(b,grant,image)==A::Retry);
assert(number(db,"SELECT COUNT(*) FROM port_cube_image_acks")==1&&ack.AcknowledgeLive(b,grant,image)==A::Stored);
assert(ack.AcknowledgeLive(b,grant,image)==A::Stored&&number(db,"SELECT COUNT(*) FROM port_cube_image_acks")==1);
assert(value(db,"SELECT owner_grant FROM port_cube_image_acks")==EncodeOwnerGrant(grant));
assert(value(db,"SELECT image FROM port_cube_image_acks")==image&&value(db,"SELECT phase FROM port_cube_fences")=="RESYNC"&&value(db,"SELECT phase FROM port_cube_owner_leases")=="LIVE");
assert(fence.Release(b,image)==F::Refused&&number(db,"SELECT COUNT(*) FROM port_cube_item_fences")>0&&number(db,"SELECT gold FROM player")==700);
puts("PASS durable exact LIVE image ACK with lost COMMIT reply and identical retry; no charge, release, lease deletion or item-fence removal");
for(unsigned problem=0;problem<12;++problem) {
image=issued(db,b,leader);grant=original(b,leader);auto target=grant;auto bytes=image;
if(problem==0)target.peer++;
if(problem==1)target.binding.session++;
if(problem==2)target.revision++;
if(problem==3)target.leader.generation++;
if(problem==4){InventoryImage parsed;assert(DecodeInventoryImage(bytes,parsed));parsed.gold++;bytes=EncodeInventoryImage(parsed);}
if(problem==5)sql(db,"UPDATE port_cube_fences SET image=X'00'");
if(problem==6)sql(db,"UPDATE player SET gold=701");
if(problem==7)sql(db,"UPDATE item SET socket0=1 WHERE id=100");
if(problem==8)sql(db,"UPDATE port_cube_fences SET phase='FROZEN'");
if(problem==9){OwnerGrant revoked;assert(owner.Revoke(b,leader,1,&grant,revoked)==O::Revoked);}
if(problem==10){assert(ack.AcknowledgeLive(b,grant,image)==A::Stored);sql(db,"UPDATE port_cube_image_acks SET owner_grant=X'00'");}
if(problem==11){OwnerGrant revoked,adopted;assert(owner.Revoke(b,leader,1,&grant,revoked)==O::Revoked);assert(owner.Adopt(b,leader,revoked.revision,6,GoldSourceFor(b,18,8,9),adopted)==O::Adopted);target=adopted;}
assert(ack.AcknowledgeLive(b,target,bytes)!=A::Stored&&number(db,"SELECT COUNT(*) FROM port_cube_item_fences")>0);
assert(number(db,"SELECT COUNT(*) FROM port_cube_image_acks")==unsigned(problem==10));
}
puts("PASS stale peer/session/revision/broker, changed current or saved image, absent issued phase, corrupt ACK history, revoked and adopted owner refusal");
image=issued(db,b,leader);grant=original(b,leader);db.statements=0;assert(ack.AcknowledgeLive(b,grant,image)==A::Stored);const auto count=db.statements;
for(unsigned warning=0;warning<2;++warning)for(int at=1;at<=count;++at) {
image=issued(db,b,leader);grant=original(b,leader);db.statements=0;if(warning)db.warnAt=at;else db.failAt=at;
assert(ack.AcknowledgeLive(b,grant,image)!=A::Stored);db.warnAt=db.failAt=0;
assert(number(db,"SELECT COUNT(*) FROM port_cube_image_acks")==0&&value(db,"SELECT phase FROM port_cube_fences")=="RESYNC");
assert(ack.AcknowledgeLive(b,grant,image)==A::Stored);
}
image=issued(db,b,leader);grant=original(b,leader);db.rejectCommit=true;assert(ack.AcknowledgeLive(b,grant,image)==A::Retry&&number(db,"SELECT COUNT(*) FROM port_cube_image_acks")==0);
sql(db,"UPDATE port_cube_image_ack_version SET version=2");assert(ack.AcknowledgeLive(b,grant,image)==A::Retry);sql(db,"UPDATE port_cube_image_ack_version SET version=1");
#ifdef PORT_CUBE_MYSQL
sql(db,"ALTER TABLE port_cube_image_acks ENGINE=MyISAM");assert(ack.AcknowledgeLive(b,grant,image)==A::Retry);sql(db,"ALTER TABLE port_cube_image_acks ENGINE=InnoDB");
#else
db.engine=false;assert(ack.AcknowledgeLive(b,grant,image)==A::Retry);db.engine=true;
#endif
sql(db,"DROP TABLE port_cube_image_ack_version");assert(ack.AcknowledgeLive(b,grant,image)==A::Retry);initializeImageAckAddon(db);
puts("PASS every ACK query failure/warning and rejected COMMIT rolls back; missing/unknown/nontransactional addon refused");
for(const auto& mode:{"ack-insert","ack-commit"}) {
sql(db,"SELECT RELEASE_LOCK(CONCAT('m2_cube:',DATABASE()))");
const auto child=spawnWorker(mode);int status=0;assert(waitpid(child,&status,0)==child&&WIFEXITED(status)&&WEXITSTATUS(status)==95);
assert(number(db,"SELECT COUNT(*) FROM port_cube_image_acks")==unsigned(std::string(mode)=="ack-commit"));
assert(value(db,"SELECT phase FROM port_cube_fences")=="RESYNC"&&value(db,"SELECT phase FROM port_cube_owner_leases")=="LIVE");
assert(owner.Acquire(std::string(32,'d'),leader)==O::Acquired);
}
puts("PASS process death before/after ACK COMMIT; durable history only, original hold retained");
}
#endif
@@ -0,0 +1,94 @@
#define PORT_CUBE_OWNER_EMBED
#include "cube_owner_probe.cpp"
#include "src/server/common/cube_image.h"
static F::Result imageFor(TestDB& db,const Batch& b,const OwnerGrant& grant,std::string& image) {
O owner(db,proto);F fence(db,proto);return fence.Resync(b,image,[&](const std::string& current){return owner.ImageWithin(b,grant,current);});
}
static F::Result liveImageFor(TestDB& db,const Batch& b,const OwnerGrant& grant,std::string& image) {
O owner(db,proto);F fence(db,proto);return fence.Resync(b,image,[&](const std::string& current){return owner.LiveImageWithin(b,grant,current);});
}
static OwnerGrant adopted(TestDB& db,const Batch& b,const OwnerLeader& leader,unsigned session=18) {
OwnerGrant old,grant;revoke(db,b,leader,old);O owner(db,proto);assert(owner.Adopt(b,leader,old.revision,6,GoldSourceFor(b,session,8,9),grant)==O::Adopted);return grant;
}
int main(int argc,char** argv) {
assert(argc==2||argc==3);address=argv[1];executable=argv[0];TestDB db;O owner(db,proto);F fence(db,proto);const auto b=batch();OwnerLeader leader;OwnerGrant grant;
if(argc==3) {
assert(owner.Acquire(std::string(32,'e'),leader)==O::Acquired);OwnerGrant old;assert(owner.Revoke(b,leader,3,nullptr,old)==O::Revoked);
assert(owner.Adopt(b,leader,old.revision,6,GoldSourceFor(b,19,9,9),grant)==O::Adopted);
const std::string mode=argv[2];db.after=[&](const std::string& q){if((mode=="image-write"&&q.find("UPDATE port_cube_fences SET phase='RESYNC'")==0)||(mode=="image-commit"&&q=="COMMIT"))_Exit(94);};
std::string image;imageFor(db,b,grant,image);assert(false);
}
initialize(db);initializeGoldAddon(db);initializeOwnerAddon(db);reset(db,b);assert(owner.Acquire(std::string(32,'d'),leader)==O::Acquired);
{
frozen(db,b,leader);auto live=original(b,leader);std::string image;
assert(imageFor(db,b,live,image)==F::Refused&&liveImageFor(db,b,live,image)==F::Done);
const auto saved=image;assert(liveImageFor(db,b,live,image)==F::Done&&image==saved&&fence.Release(b,image)==F::Refused);
auto wrong=live;wrong.peer++;assert(liveImageFor(db,b,wrong,image)==F::Refused);
OwnerGrant revoked;assert(owner.Revoke(b,leader,1,&live,revoked)==O::Revoked&&liveImageFor(db,b,live,image)==F::Refused);
OwnerGrant adoptedGrant;assert(owner.Adopt(b,leader,revoked.revision,6,GoldSourceFor(b,18,8,9),adoptedGrant)==O::Adopted);
assert(liveImageFor(db,b,adoptedGrant,image)==F::Refused&&imageFor(db,b,adoptedGrant,image)==F::Done&&image==saved);
frozen(db,b,leader);live=original(b,leader);db.statements=0;assert(liveImageFor(db,b,live,image)==F::Done);const auto statements=db.statements;
for(unsigned warning=0;warning<2;++warning)for(int at=1;at<=statements;++at){
frozen(db,b,leader);live=original(b,leader);db.statements=0;if(warning)db.warnAt=at;else db.failAt=at;
assert(liveImageFor(db,b,live,image)!=F::Done&&image.empty());db.warnAt=db.failAt=0;
assert(value(db,"SELECT phase FROM port_cube_fences")=="FROZEN"&&number(db,"SELECT gold FROM player")==700&&liveImageFor(db,b,live,image)==F::Done);
}
frozen(db,b,leader,true,false);live=original(b,leader);G gold(db,proto);GoldIntent intent;intent.account=1;intent.player=1;intent.epoch=b.epoch;intent.owner=b.owner;intent.request=b.token;intent.event=std::string(32,'f');intent.sequence=1;intent.source=1;intent.amount=50;
assert(gold.Enqueue(b,intent)==G::Stored);auto seal=source(b);seal.events={intent.event};assert(gold.CloseSource(b,seal)==G::Stored);
G::Receipt receipt;assert(gold.Apply(intent.event,1,1,receipt,[](const GoldIntent&){return false;})==G::Blocked&&number(db,"SELECT gold FROM player")==700);
assert(gold.Apply(intent.event,1,1,receipt,[&](const GoldIntent& savedIntent){return Matches(savedIntent,b)&&owner.CraftWithin(b,live);})==G::Applied&&receipt.after==750);
assert(gold.Apply(intent.event,1,1,receipt,[](const GoldIntent&){return false;})==G::Blocked&&number(db,"SELECT gold FROM player")==750);
assert(liveImageFor(db,b,live,image)==F::Done);InventoryImage parsed;assert(DecodeInventoryImage(image,parsed,proto)&&parsed.gold==750);
puts("PASS original LIVE image uses exact original peer/binding and all shared image proofs, no ADOPTED downgrade, revoke/adopt separation, every SQL failure/warning, transactional gold authority including historical replay; no release");
}
frozen(db,b,leader);grant=adopted(db,b,leader);std::string image;
assert(fence.Resync(b,image)==F::Refused&&image.empty()); // no legacy unowned downgrade for a registered lease
db.ambiguous=true;assert(imageFor(db,b,grant,image)==F::Retry&&image.empty());assert(imageFor(db,b,grant,image)==F::Done);
InventoryImage parsed;assert(DecodeInventoryImage(image,parsed,proto)&&parsed.gold==700&&parsed.items.size()==4);
const auto saved=image;assert(imageFor(db,b,grant,image)==F::Done&&image==saved&&fence.Release(b,image)==F::Refused);
auto wrong=grant;wrong.revision++;assert(imageFor(db,b,wrong,image)==F::Refused&&image.empty());
puts("PASS owner-bound image, lost COMMIT ACK replay, exact settlement and immutable image, no legacy release");
for(unsigned problem=0;problem<9;++problem) {
frozen(db,b,leader);grant=adopted(db,b,leader);
if(problem==0)sql(db,"UPDATE player SET gold=701");
if(problem==1)sql(db,"UPDATE item SET count=count+1 WHERE id=10");
if(problem==2)sql(db,"UPDATE item SET socket0=socket0+1 WHERE id=100");
if(problem==3)sql(db,"DELETE FROM port_cube_item_fences WHERE id=100");
if(problem==4)sql(db,"DELETE FROM port_economy_item_reservations WHERE id=102");
if(problem==5)sql(db,"UPDATE port_cube_gold_sources SET cookie=cookie+1");
if(problem==6)sql(db,"UPDATE port_cube_requests SET rolls=X'00'");
if(problem==7){OwnerGrant revoked;assert(owner.Revoke(b,leader,1,&grant,revoked)==O::Revoked);}
if(problem==8)sql(db,"UPDATE item SET port_extra=X'00' WHERE id=10");
assert(imageFor(db,b,grant,image)!=F::Done&&image.empty()&&value(db,"SELECT phase FROM port_cube_fences")=="FROZEN");
assert(number(db,"SELECT COUNT(*) FROM port_cube_item_fences")>0);
}
frozen(db,b,leader);grant=adopted(db,b,leader);assert(imageFor(db,b,grant,image)==F::Done);const auto first=image;
sql(db,"UPDATE port_cube_fences SET image=X'00'");assert(imageFor(db,b,grant,image)==F::Refused&&value(db,"SELECT image FROM port_cube_fences")==std::string(1,0));
puts("PASS zero-credit stale wallet, changed materials/reward metadata, missing item locks/reservations, original-source mismatch, corrupt receipt/revoked grant and altered saved image all refuse");
frozen(db,b,leader);grant=adopted(db,b,leader);db.statements=0;assert(imageFor(db,b,grant,image)==F::Done);const auto count=db.statements;
for(unsigned warning=0;warning<2;++warning)for(int at=1;at<=count;++at) {
frozen(db,b,leader);grant=adopted(db,b,leader);db.statements=0;if(warning)db.warnAt=at;else db.failAt=at;
assert(imageFor(db,b,grant,image)!=F::Done&&image.empty());db.failAt=db.warnAt=0;
assert(value(db,"SELECT phase FROM port_cube_fences")=="FROZEN"&&value(db,"SELECT image FROM port_cube_fences").empty()&&number(db,"SELECT gold FROM player")==700);
assert(imageFor(db,b,grant,image)==F::Done);
}
frozen(db,b,leader);grant=adopted(db,b,leader);db.rejectCommit=true;assert(imageFor(db,b,grant,image)==F::Retry&&value(db,"SELECT phase FROM port_cube_fences")=="FROZEN");
auto failed=b;failed.recipe.percent=0;frozen(db,failed,leader);grant=adopted(db,failed,leader);assert(imageFor(db,failed,grant,image)==F::Done&&DecodeInventoryImage(image,parsed,proto)&&parsed.gold==700&&parsed.items.size()==1&&parsed.items[0].value.count==4);
frozen(db,b,leader,false,true);Store craft(db,proto);Store::Receipt receipt;assert(craft.Prepare(b,[]{return 1u;})==Store::Prepared);sql(db,"UPDATE item SET count=11 WHERE id=10");assert(craft.Execute(b.token,1,1,receipt)==Store::Complete&&receipt.result=="inventory_changed");
grant=adopted(db,b,leader);assert(imageFor(db,b,grant,image)==F::Refused&&number(db,"SELECT gold FROM player")==1000); // non-ok DONE is not a reconciled recovery image
frozen(db,b,leader,true,false);G gold(db,proto);GoldIntent credit;credit.account=b.account;credit.player=b.player;credit.epoch=b.epoch;credit.owner=b.owner;credit.request=b.token;credit.event=std::string(32,'f');credit.sequence=1;credit.source=1;credit.amount=250;
assert(gold.Enqueue(b,credit)==G::Stored);auto closed=source(b);closed.events={credit.event};assert(gold.CloseSource(b,closed)==G::Stored);grant=adopted(db,b,leader);
assert(imageFor(db,b,grant,image)==F::Refused&&number(db,"SELECT gold FROM player")==700);G::Receipt credited;assert(gold.Apply(credit.event,1,1,credited)==G::Applied);
assert(imageFor(db,b,grant,image)==F::Done&&DecodeInventoryImage(image,parsed,proto)&&parsed.gold==950&&parsed.items.size()==4);
puts("PASS every image SQL failure/warning and rejected commit rolls back; zero-success paid crafting restores charged materials/wallet without invented awards");
for(const auto& mode:{"image-write","image-commit"}) {
frozen(db,b,leader);grant=adopted(db,b,leader);sql(db,"SELECT RELEASE_LOCK(CONCAT('m2_cube:',DATABASE()))");
const auto child=spawnWorker(mode);int status=0;assert(waitpid(child,&status,0)==child&&WIFEXITED(status)&&WEXITSTATUS(status)==94);
assert(value(db,"SELECT phase FROM port_cube_fences")==std::string(std::string(mode)=="image-commit"?"RESYNC":"FROZEN"));
assert(owner.Acquire(std::string(32,'d'),leader)==O::Acquired);OwnerGrant old;assert(owner.Revoke(b,leader,3,nullptr,old)==O::Revoked);
assert(owner.Adopt(b,leader,old.revision,6,GoldSourceFor(b,20,10,9),grant)==O::Adopted&&imageFor(db,b,grant,image)==F::Done&&image==first);
}
puts("PASS process exits after image write / COMMIT, newer broker revocation and exact re-read; source/receipt/ID fences persist, no thaw");
}
@@ -0,0 +1,97 @@
#define main cubeBaseMain
#include "cube_batch_probe.cpp"
#undef main
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>
static unsigned writes=0,syncs=0,failWrite=0,failSync=0,crashSync=0;
static bool shortWrite=false,interruptWrite=false;
static ssize_t OutboxWrite(int fd,const void* data,size_t size) {
++writes;if(interruptWrite){interruptWrite=false;errno=EINTR;return -1;}
if(writes==failWrite){errno=ENOSPC;return -1;}
return ::write(fd,data,shortWrite?std::max(size_t(1),size/2):size);
}
static int OutboxSync(int fd) {
++syncs;if(syncs==failSync){errno=EIO;return -1;}
const int result=::fsync(fd);if(result==0&&syncs==crashSync)_Exit(91);return result;
}
#define write OutboxWrite
#define fsync OutboxSync
#include "src/server/common/cube_gold_outbox.h"
#undef write
#undef fsync
#include "src/server/common/cube_gold_store.h"
#include "src/server/common/cube_handshake.h"
using G=GoldIntentStore<TestDB>;
static GoldDelivery delivery(const Batch& b,unsigned seq=1) {
GoldDelivery d;auto& i=d.intent;i.account=b.account;i.player=b.player;i.epoch=b.epoch;i.owner=b.owner;i.request=b.token;
i.event=std::string(31,'e')+char('0'+seq);i.sequence=seq;i.amount=250;i.source=1;
d.session=8;d.cookie=7;d.handle=6;d.ground=123+seq;d.vnum=1;d.map=1;return d;
}
static void faults(){writes=syncs=failWrite=failSync=crashSync=0;shortWrite=interruptWrite=false;}
static void waitWorker(pid_t child,int expected){int status=0;assert(waitpid(child,&status,0)==child&&WIFEXITED(status)&&WEXITSTATUS(status)==expected);}
int main(int argc,char** argv) {
assert(argc==2||argc==3);address=argv[1];executable=argv[0];auto b=batch();auto d=delivery(b);const auto path=address+".outbox";
if(argc==3) {
const std::string mode=argv[2];GoldOutbox out;assert(out.Open(path+"."+mode));faults();crashSync=1;
if(mode=="claim-crash")out.Claim(d);else out.Acknowledge(d);
assert(false);
}
{
GoldOutbox out;assert(out.Open(path));GoldOutbox second;assert(!second.Open(path));
assert(out.Claim(d)&&out.Claim(d)&&out.Pending().size()==1);
auto conflict=d;conflict.intent.amount++;assert(!out.Claim(conflict));
auto gap=delivery(b,3);assert(!out.Claim(gap));auto next=delivery(b,2);assert(out.Claim(next));
auto body=EncodeGoldDelivery(d);assert(body.size()==GoldDeliveryBytes);GoldDelivery decoded;
assert(DecodeGoldDelivery(body,decoded));for(size_t n=0;n<body.size();++n)assert(!DecodeGoldDelivery(body.substr(0,n),decoded));
assert(!DecodeGoldDelivery(body+"x",decoded));assert(!out.Acknowledge(conflict));assert(out.Acknowledge(d)&&out.Acknowledge(d));
assert(out.Next(b.token)==3&&out.Total(b.token)==500&&out.Pending().size()==1);
}
{GoldOutbox out;assert(out.Open(path)&&out.Pending().size()==1&&out.Pending()[0].intent.sequence==2&&out.Next(b.token)==3);}
// Successful short writes/EINTR are retried; failed partial append is never
// silently truncated or acknowledged on restart.
{GoldOutbox out;assert(out.Open(path+".short"));faults();shortWrite=true;interruptWrite=true;assert(out.Claim(d));faults();}
{GoldOutbox out;assert(out.Open(path+".torn"));faults();shortWrite=true;failWrite=2;assert(!out.Claim(d)&&!out.Ready());faults();}
{GoldOutbox out;assert(!out.Open(path+".torn")&&!out.Ready());}
{GoldOutbox out;assert(out.Open(path+".sync"));faults();failSync=1;assert(!out.Claim(d)&&!out.Ready());assert(!out.Claim(delivery(b,2)));faults();}
{GoldOutbox out;assert(out.Open(path+".sync")&&out.Pending().size()==1);}
{GoldOutbox out;assert(out.Open(path+".ack-sync"));assert(out.Claim(d));faults();failSync=1;assert(!out.Acknowledge(d)&&!out.Ready());faults();}
{GoldOutbox out;assert(out.Open(path+".ack-sync")&&out.Pending().empty()&&out.Next(b.token)==2);}
for(unsigned at=1;at<=3;++at){GoldOutbox out;faults();failSync=at;assert(!out.Open(path+".open-sync"+std::to_string(at)));faults();}
assert(symlink(path.c_str(),(path+".symlink").c_str())==0);
{GoldOutbox out;assert(!out.Open(path+".symlink"));}
assert(link(path.c_str(),(path+".hardlink").c_str())==0);
{GoldOutbox out;assert(!out.Open(path+".hardlink"));}
{GoldOutbox out;assert(out.Open(path+".corrupt")&&out.Claim(d));}
{const int f=open((path+".corrupt").c_str(),O_RDWR);assert(f>=0);const char bad='z';assert(pwrite(f,&bad,1,20)==1);close(f);}
{GoldOutbox out;assert(!out.Open(path+".corrupt"));struct stat s={};assert(stat((path+".corrupt").c_str(),&s)==0&&size_t(s.st_size)==GoldOutbox::FrameBytes);}
{const int f=open((path+".oversize").c_str(),O_RDWR|O_CREAT,0600);assert(f>=0&&ftruncate(f,GoldOutbox::MaxBytes+1)==0);close(f);}
{GoldOutbox out;assert(!out.Open(path+".oversize"));}
puts("PASS durable outbox codec, exclusive ownership, immutable events, sequence history, short/EINTR writes, torn tail, sync failures and unsafe links");
{GoldOutbox out;assert(out.Open(path+".claim-crash"));}
waitWorker(spawnWorker("claim-crash"),91);
{GoldOutbox out;assert(out.Open(path+".claim-crash")&&out.Pending().size()==1);}
{GoldOutbox out;assert(out.Open(path+".ack-crash")&&out.Claim(d));}
waitWorker(spawnWorker("ack-crash"),91);
{GoldOutbox out;assert(out.Open(path+".ack-crash")&&out.Pending().empty()&&out.Next(b.token)==2);}
puts("PASS separate-process source fsync / ACK fsync exits; restart recovers pending or acknowledged sequence without reissuing an event");
TestDB db;initialize(db);
initializeGoldAddon(db);sql(db,"DELETE FROM port_cube_gold_sources");sql(db,"DELETE FROM port_cube_gold_intents");reset(db,b);
G store(db,proto);G::Receipt receipt;
{GoldOutbox out;assert(out.Open(path+".pipeline")&&out.Claim(d));db.ambiguous=true;assert(store.Enqueue(b,d.intent)==G::Retry);assert(out.Pending().size()==1);}
{GoldOutbox out;assert(out.Open(path+".pipeline")&&out.Pending().size()==1);const auto saved=out.Pending()[0];assert(store.Enqueue(b,saved.intent)==G::Stored);assert(number(db,"SELECT COUNT(*) FROM port_cube_gold_intents")==1);assert(out.Acknowledge(saved));}
{GoldOutbox out;assert(out.Open(path+".pipeline")&&out.Pending().empty()&&out.Next(b.token)==2);}
{GoldOutbox out;assert(out.Open(path+".pipeline")&&out.CloseSource(GoldSourceFor(d)));auto seals=out.PendingSources();assert(seals.size()==1&&store.CloseSource(b,seals[0])==G::Stored&&out.AcknowledgeSource(seals[0]));}
Store craft(db,proto);Store::Receipt result;assert(craft.Prepare(b,[]{return 1u;})==Store::Prepared&&craft.Execute(b.token,1,1,result)==Store::Complete);
assert(store.Apply(d.intent.event,1,1,receipt)==G::Applied&&number(db,"SELECT gold FROM player")==950);
assert(store.Apply(d.intent.event,1,1,receipt)==G::Applied&&number(db,"SELECT gold FROM player")==950);
FenceStore<TestDB> fence(db,proto);std::string image;assert(fence.Resync(b,image)==FenceStore<TestDB>::Done&&fence.Release(b,image)==FenceStore<TestDB>::Done);
auto f=ArmFrame(b,d.session);f.message=Message::GoldEnqueue;f.cookie=d.cookie;f.body=EncodeGoldIntent(d.intent);
const auto wire=EncodeHandshake(f);Handshake decoded;assert(wire.size()==HandshakeFixed+GoldIntentBytes&&DecodeHandshake(wire.data(),wire.size(),decoded));
f.player++;assert(!ValidHandshake(f));f.player--;f.message=Message::GoldAck;f.status=Status::GoldStored;assert(ValidHandshake(f));
ActorHandshake actor;assert(actor.Start(b,d.session,1,true));assert(!actor.Answer(f)&&actor.BlocksActions());
puts("PASS source journal -> ambiguous SQL enqueue -> restart/retry -> durable ACK -> verified craft DONE -> single credit -> exact-image release; explicit SQL/actor substitutes, not live freeze acceptance");
}
@@ -0,0 +1,130 @@
#define main cubeBaseMain
#include "cube_batch_probe.cpp"
#undef main
#include "src/server/common/cube_owner.h"
#include "src/server/common/cube_gold_store.h"
using O=OwnerStore<TestDB>;
using F=FenceStore<TestDB>;
using G=GoldIntentStore<TestDB>;
static OwnerGrant original(const Batch& b,const OwnerLeader& l){return {l,GoldSourceFor(b,17,7,6),5,1};}
static GoldSourceSeal source(const Batch& b){GoldSourceSeal s;static_cast<GoldSourceBinding&>(s)=GoldSourceFor(b,17,7,6);return s;}
static void fresh(TestDB& db,const Batch& b) {
reset(db,b);sql(db,"DELETE FROM port_cube_owner_leases");sql(db,"DELETE FROM port_cube_gold_sources");sql(db,"DELETE FROM port_cube_gold_intents");removeFence(db);
}
static F::Result bind(TestDB& db,const Batch& b,const OwnerGrant& grant) {
O owner(db,proto);F fence(db,proto);return fence.Begin(b,{},[&](bool replay){return owner.BindWithin(b,grant,replay);});
}
static void frozen(TestDB& db,const Batch& b,const OwnerLeader& leader,bool done=true,bool close=true) {
fresh(db,b);assert(bind(db,b,original(b,leader))==F::Done);Drain d;barriers(d,b);F fence(db,proto);assert(fence.FinishDrain(b,d,17,11,22,true)==F::Done);
if(done){Store craft(db,proto);Store::Receipt receipt;assert(craft.Prepare(b,[]{return 1u;})==Store::Prepared&&craft.Execute(b.token,1,1,receipt)==Store::Complete);}
if(close){G gold(db,proto);assert(gold.CloseSource(b,source(b))==G::Stored);}
}
static void revoke(TestDB& db,const Batch& b,const OwnerLeader& l,OwnerGrant& receipt) {
O owner(db,proto);const auto old=original(b,l);assert(owner.Revoke(b,l,1,&old,receipt)==O::Revoked);
}
#ifndef PORT_CUBE_OWNER_EMBED
int main(int argc,char** argv) {
assert(argc==2||argc==3);address=argv[1];executable=argv[0];auto b=batch();TestDB db;O owner(db,proto);OwnerLeader leader;
if(argc==3) {
const std::string mode=argv[2];assert(owner.Acquire(std::string(32,'c'),leader)==O::Acquired);
db.after=[&](const std::string& q){if((mode=="lease-insert"&&q.find("INSERT INTO port_cube_owner_leases")==0)||(mode=="lease-commit"&&q=="COMMIT"))_Exit(92);};
bind(db,b,original(b,leader));assert(false);
}
initialize(db);initializeGoldAddon(db);initializeOwnerAddon(db);reset(db,b);assert(owner.Ready());
assert(owner.Acquire(std::string(32,'d'),leader)==O::Acquired&&owner.Current(leader));
const auto generation=leader.generation;OwnerLeader replay;
assert(owner.Acquire(leader.boot,replay)==O::Acquired&&replay.generation==generation);
#ifdef PORT_CUBE_MYSQL
{TestDB competitor;O other(competitor,proto);OwnerLeader next;
assert(other.Acquire(std::string(32,'e'),next)==O::Busy);
sql(db,"SELECT RELEASE_LOCK(CONCAT('m2_cube:',DATABASE()))");
assert(other.Acquire(std::string(32,'e'),next)==O::Acquired&&next.generation>generation&&!owner.Current(leader));
assert(owner.Acquire(std::string(32,'d'),replay)==O::Busy);}
assert(owner.Acquire(std::string(32,'d'),leader)==O::Acquired&&leader.generation>generation);
puts("PASS actual MySQL connection-scoped advisory lock: competing connection denied, disconnect releases, generation advances and old broker fails");
#else
db.ownerHolder=99;assert(owner.Acquire(leader.boot,replay)==O::Busy);db.ownerHolder=db.ownerConnection;
db.ownerConnection=2;db.ownerHolder=0;assert(!owner.Current(leader));assert(owner.Acquire(leader.boot,leader)==O::Acquired&&leader.generation>generation);
puts("PASS SQLite-only explicit connection/advisory substitute; no real MySQL lock claim");
#endif
fresh(db,b);const auto grant=original(b,leader);
db.ambiguous=true;assert(bind(db,b,grant)==F::Retry);assert(bind(db,b,grant)==F::Done&&owner.Check(b,grant));
auto changed=grant;changed.binding.cookie++;assert(bind(db,b,changed)==F::Refused);
sql(db,"DELETE FROM port_cube_owner_leases");assert(bind(db,b,grant)==F::Refused&&number(db,"SELECT COUNT(*) FROM port_cube_owner_leases")==0);
puts("PASS atomic Begin+lease, lost COMMIT acknowledgement, immutable binding replay and no invented missing owner on old fence");
frozen(db,b,leader);OwnerGrant revoked,adopted;revoke(db,b,leader,revoked);assert(!owner.Check(b,grant));
const auto target=GoldSourceFor(b,18,8,9);
assert(owner.Revoke(b,leader,1,&grant,revoked)==O::Revoked&&revoked.revision==2);
assert(owner.Adopt(b,leader,revoked.revision,6,grant.binding,adopted)==O::Refused);
db.ambiguous=true;assert(owner.Adopt(b,leader,2,6,target,adopted)==O::Retry);
assert(owner.Adopt(b,leader,2,6,target,adopted)==O::Adopted&&adopted.revision==3&&owner.Check(b,adopted));
auto wrong=target;wrong.session++;OwnerGrant denied;assert(owner.Adopt(b,leader,2,6,wrong,denied)==O::Refused);
F fence(db,proto);std::string image;auto ownedImage=[&](const std::string& current){return owner.ImageWithin(b,adopted,current);};
assert(fence.Resync(b,image)==F::Refused&&fence.Resync(b,image,ownedImage)==F::Done&&fence.Release(b,image)==F::Refused);
assert(number(db,"SELECT gold FROM player")==700&&number(db,"SELECT COUNT(*) FROM port_cube_item_fences")>0);
puts("PASS persisted revoke, fresh-session adoption, lost adoption ACK replay, no new payment/load/thaw and old release remains blocked");
frozen(db,b,leader,true,false);G gold(db,proto);GoldIntent credit;
credit.account=b.account;credit.player=b.player;credit.epoch=b.epoch;credit.owner=b.owner;credit.request=b.token;credit.amount=250;credit.source=1;
credit.sequence=1;credit.event=std::string(32,'1');assert(gold.Enqueue(b,credit)==G::Stored);
const auto first=credit.event;credit.sequence=2;credit.event=std::string(32,'2');assert(gold.Enqueue(b,credit)==G::Stored);
auto seal=source(b);seal.events={first,credit.event};assert(gold.CloseSource(b,seal)==G::Stored);
G::Receipt goldReceipt;assert(gold.Apply(first,1,1,goldReceipt)==G::Applied);revoke(db,b,leader,revoked);
assert(owner.Adopt(b,leader,revoked.revision,6,target,adopted)==O::Adopted&&number(db,"SELECT gold FROM player")==950);
assert(fence.Resync(b,image)==F::Refused); // adoption does not secretly settle queued rewards
assert(gold.Apply(credit.event,1,1,goldReceipt)==G::Applied&&fence.Resync(b,image,ownedImage)==F::Done&&fence.Release(b,image)==F::Refused);
puts("PASS exact original source and applied-prefix/pending-credit recovery: no implicit credit on adoption, no early resync or thaw");
frozen(db,b,leader);revoke(db,b,leader,revoked);assert(owner.Adopt(b,leader,revoked.revision,6,target,adopted)==O::Adopted);
const auto originalBinding=EncodeGoldSourceBinding(original(b,leader).binding);
for(unsigned session=19;session<=21;++session) {
const auto lost=adopted;
if(session==19)db.rejectCommit=true;else if(session==20)db.ambiguous=true;else db.warnAt=db.statements+1;
assert(owner.Revoke(b,leader,2,&lost,revoked)==O::Retry);db.warnAt=0;
assert(owner.Revoke(b,leader,2,&lost,revoked)==O::Revoked&&!owner.Check(b,lost));
const auto next=GoldSourceFor(b,session,session,session);
assert(owner.Adopt(b,leader,revoked.revision,6,next,adopted)==O::Adopted&&adopted.revision==lost.revision+2);
assert(value(db,"SELECT original_binding FROM port_cube_owner_leases")==originalBinding&&number(db,"SELECT gold FROM player")==700&&number(db,"SELECT COUNT(*) FROM port_cube_requests")==1);
}
assert(fence.Resync(b,image,ownedImage)==F::Done&&fence.Release(b,image)==F::Refused);
puts("PASS repeated adopted-owner logout/revoke/readopt with rejected/lost COMMIT and warning; original source immutable, same single settlement, still no thaw");
for(unsigned problem=0;problem<5;++problem) {
frozen(db,b,leader,problem!=0,problem!=1);revoke(db,b,leader,revoked);
if(problem==2)sql(db,"UPDATE player SET gold=gold+1");
if(problem==3)sql(db,"UPDATE port_cube_fences SET phase='ABORTED',drain_state=2");
if(problem==4)sql(db,"UPDATE port_cube_gold_sources SET cookie=cookie+1");
assert(owner.Adopt(b,leader,revoked.revision,6,target,adopted)!=O::Adopted);
assert(value(db,"SELECT phase FROM port_cube_owner_leases")=="REVOKED");
}
frozen(db,b,leader);const auto previous=leader;const auto previousGrant=original(b,leader);
assert(owner.Acquire(std::string(32,'f'),leader)==O::Acquired&&!owner.Check(b,previousGrant));
assert(owner.Revoke(b,leader,1,&previousGrant,revoked)==O::Refused);
assert(owner.Revoke(b,leader,3,nullptr,revoked)==O::Revoked&&owner.Adopt(b,leader,revoked.revision,6,target,adopted)==O::Adopted);
assert(owner.Revoke(b,leader,3,nullptr,revoked)==O::Refused);
puts("PASS absent DONE/source, mismatched wallet/binding, aborted drain and same-generation takeover refused; strictly newer broker can revoke original held owner");
for(unsigned operation=0;operation<3;++operation) {
auto setup=[&](){if(!operation)fresh(db,b);else frozen(db,b,leader);if(operation==2)revoke(db,b,leader,revoked);};
auto action=[&](){if(!operation)return int(bind(db,b,original(b,leader)))==int(F::Done);if(operation==1){const auto old=original(b,leader);return owner.Revoke(b,leader,1,&old,revoked)==O::Revoked;}return owner.Adopt(b,leader,2,6,target,adopted)==O::Adopted;};
setup();db.statements=0;assert(action());const auto count=db.statements;
for(unsigned warning=0;warning<2;++warning)for(int at=1;at<=count;++at) {
setup();db.statements=0;if(warning)db.warnAt=at;else db.failAt=at;assert(!action());db.failAt=db.warnAt=0;
if(!operation)assert(number(db,"SELECT COUNT(*) FROM port_cube_fences")==0&&number(db,"SELECT COUNT(*) FROM port_cube_owner_leases")==0&&number(db,"SELECT COUNT(*) FROM port_cube_item_fences")==0);
else assert(value(db,"SELECT phase FROM port_cube_owner_leases")==std::string(operation==1?"LIVE":"REVOKED"));
assert(action());
}
}
puts("PASS every binding/revocation/adoption SQL failure and warning boundary rolls back atomically and retries without new currency");
for(const auto& mode:{"lease-insert","lease-commit"}) {
fresh(db,b);sql(db,"SELECT RELEASE_LOCK(CONCAT('m2_cube:',DATABASE()))");
const auto child=spawnWorker(mode);int status=0;assert(waitpid(child,&status,0)==child&&WIFEXITED(status)&&WEXITSTATUS(status)==92);
const auto expected=std::string(mode)=="lease-commit"?1:0;
assert(number(db,"SELECT COUNT(*) FROM port_cube_owner_leases")==expected&&number(db,"SELECT COUNT(*) FROM port_cube_fences")==expected);
assert(owner.Acquire(std::string(32,'d'),leader)==O::Acquired);
}
sql(db,"UPDATE port_cube_owner_version SET version=2");assert(!owner.Ready());sql(db,"UPDATE port_cube_owner_version SET version=1");
puts("PASS process exit before/after owner transaction COMMIT preserves fence+lease together; unknown owner schema refused; no runtime gates enabled");
}
#endif
@@ -0,0 +1,57 @@
// Actual release readiness/acceptance helpers and state; explicit actor,
// snapshot, restoration-plan and transport boundaries (not a freeze proof).
#define main cubeBaseMain
#include "tests/features/fixtures/cube_batch_probe.cpp"
#undef main
#include "src/server/common/cube_live_image.h"
static bool audited=true,online=true,actorMatches=true,eventsReady=true,captureOK=true;
static InventoryImage current;static std::string currentSeal="applied";
struct TQuickslot{uint8_t type=0;uint16_t pos=0;};
struct CHARACTER{TQuickslot slots[36];int missing=-1;int64_t GetGold(){return current.gold;}bool GetQuickslot(unsigned n,TQuickslot** p){*p=&slots[n];return int(n)!=missing;}};
using LPCHARACTER=CHARACTER*;
struct RestorePlan{bool prepared=true,enabled=false;bool Prepared()const{return prepared;}bool Enabled()const{return enabled;}};
struct Owner{Batch batch;ActorHandshake flow;CraftFlow craft;LiveImageFlow image;LiveReleaseFlow release;bool frozen=true,quickslotsCaptured=true,published=true;RestorePlan restore;std::string appliedSeal="applied";std::array<PortCubeView::Quickslot,36> quickslots={};};
struct Snapshot{std::string seal;std::vector<Item> ordinary;};
bool capture(CHARACTER*,Snapshot& s){s.seal=currentSeal;s.ordinary=current.items;return captureOK;}
bool matches(CHARACTER*,const Owner&){return actorMatches;}bool connected(){return online;}
bool PortCubeRestoredInventoryReady(CHARACTER*,const RestorePlan&){return eventsReady;}
// ACTUAL_HELPERS_HERE
Owner ready(CHARACTER& ch){
Owner o;o.batch=batch();assert(o.flow.Start(o.batch,8,1,true));auto f=ArmFrame(o.batch,8);f.body.clear();f.cookie=7;f.message=Message::Answer;f.status=Status::Armed;
assert(o.flow.Armed(f,1)&&o.flow.Submit(true,1));f.status=Status::Frozen;assert(o.flow.Answer(f));
assert(o.craft.Start(o.flow.Request(Message::Poll),true,true));f.message=Message::CraftAnswer;f.status=Status::Prepared;assert(o.craft.Answer(f,o.batch,proto));
const auto plan=SettlePlan(o.batch,std::string("\1\144\1",3),proto);f.status=Status::Complete;f.body=EncodeCraftReceipt({plan.result,plan.successes,plan.fee,plan.awards});assert(o.craft.Answer(f,o.batch,proto));
assert(o.image.Start(o.flow.Request(Message::Poll),o.batch,o.craft.Receipt(),60,proto,true));f=o.image.Request();f.message=Message::LiveImageAnswer;f.status=Status::LiveImageReady;f.body=o.image.Image();assert(o.image.Answer(f)&&o.image.MarkApplied(f.body)&&o.image.BeginAcknowledge(f.body));
f.message=Message::LiveImageAckAnswer;f.status=Status::LiveImageAcknowledged;assert(o.image.Answer(f));assert(DecodeInventoryImage(o.image.Image(),current));
o.quickslots[0]={1,0};o.quickslots[1]={2,6};o.quickslots[2]={1,225};o.quickslots[3]={1,224};
ch.slots[0]={1,0};ch.slots[1]={2,6};ch.slots[2]={1,225}; // original empty224 clears
return o;
}
int main(){
CHARACTER ch;auto o=ready(ch);assert(releaseReady(&ch,o));
for(auto* flag:{&audited,&online,&actorMatches,&eventsReady,&captureOK,&o.frozen,&o.quickslotsCaptured,&o.published,&o.restore.prepared}){*flag=false;assert(!releaseReady(&ch,o));*flag=true;}
o.restore.enabled=true;assert(!releaseReady(&ch,o));o.restore.enabled=false;
currentSeal="changed-other-window";assert(!releaseReady(&ch,o));currentSeal=o.appliedSeal;
++current.gold;assert(!releaseReady(&ch,o));--current.gold;
++current.items[0].value.extra[68];assert(!releaseReady(&ch,o));--current.items[0].value.extra[68];
ch.slots[3]={1,224};assert(!releaseReady(&ch,o));ch.slots[3]={};
ch.slots[1].pos++;assert(!releaseReady(&ch,o));ch.slots[1].pos--;
ch.missing=35;assert(!releaseReady(&ch,o));ch.missing=-1;
// No early start, and no retry may regenerate image/identity after submission.
LiveImageFlow unconfirmed;LiveReleaseFlow denied;assert(!denied.Start(unconfirmed,true)&&!denied.Start(o.image,false));
assert(o.release.Start(o.image,releaseReady(&ch,o))&&!o.release.Start(o.image,true));auto request=o.release.Request();
assert(request.message==Message::LiveReleaseRequest&&request.body==o.image.Image()&&o.release.MayRetry());
const auto wire=EncodeHandshake(request);assert(!wire.empty()&&wire==EncodeHandshake(o.release.Request()));
auto f=request;f.message=Message::LiveReleaseAnswer;f.status=Status::LiveReleased;
for(unsigned field=0;field<7;++field){auto stale=f;switch(field){case 0:++stale.account;break;case 1:++stale.player;break;case 2:++stale.session;break;case 3:++stale.epoch;break;case 4:++stale.cookie;break;case 5:stale.owner=std::string(32,'e');break;case 6:stale.token=std::string(32,'f');break;}assert(!acceptRelease(&ch,o,stale)&&o.release.MayRetry());}
auto held=f;held.status=Status::Held;held.body.clear();assert(acceptRelease(&ch,o,held)&&o.release.MayRetry());
assert(acceptRelease(&ch,o,f)&&o.release.State()==LiveReleaseFlow::Released&&!o.release.MayRetry()&&o.flow.BlocksActions()&&!o.restore.enabled);
assert(acceptRelease(&ch,o,f)&&!acceptRelease(&ch,o,held)&&o.release.State()==LiveReleaseFlow::Released);
// Delayed positive answer must recheck current presentation/asset readiness.
ch.slots[0].pos++;assert(!acceptRelease(&ch,o,f)&&o.release.State()==LiveReleaseFlow::Held&&o.flow.BlocksActions()&&!o.restore.enabled);ch.slots[0].pos--;
auto altered=ready(ch);assert(altered.release.Start(altered.image,true));auto bad=altered.release.Request();bad.message=Message::LiveReleaseAnswer;bad.status=Status::LiveReleased;
InventoryImage conflict;assert(DecodeInventoryImage(bad.body,conflict));++conflict.gold;bad.body=EncodeInventoryImage(conflict);assert(!acceptRelease(&ch,altered,bad)&&altered.release.State()==LiveReleaseFlow::Held);
auto disconnected=ready(ch);assert(disconnected.release.Start(disconnected.image,true));online=false;assert(!acceptRelease(&ch,disconnected,f)&&disconnected.release.State()==LiveReleaseFlow::Held&&disconnected.flow.BlocksActions());
online=true;auto invalidated=ready(ch);invalidated.flow.Invalidate(PortCube::ContextChanged);assert(!releaseReady(&ch,invalidated)&&invalidated.flow.BlocksActions());
puts("PASS actual release readiness/acceptance and transport: full image/seal/registry-plan boundary, exact shortcuts, original identity retries, stale/conflicting/late answers, no save-enable/resume/thaw; explicit actor/DB boundary");
}
@@ -0,0 +1,90 @@
#define PORT_CUBE_ACK_EMBED
#include "cube_image_ack_probe.cpp"
#include "src/server/common/cube_release.h"
using R=ReleaseStore<TestDB>;
static std::string acknowledged(TestDB& db,const Batch& b,const OwnerLeader& leader) {
const auto image=issued(db,b,leader);sql(db,"DELETE FROM port_cube_releases");A ack(db,proto);
assert(ack.AcknowledgeLive(b,original(b,leader),image)==A::Stored);return image;
}
static void held(TestDB& db) {
assert(value(db,"SELECT phase FROM port_cube_fences")=="RESYNC"&&value(db,"SELECT phase FROM port_cube_owner_leases")=="LIVE");
assert(number(db,"SELECT COUNT(*) FROM port_cube_item_fences")>0&&number(db,"SELECT COUNT(*) FROM port_cube_releases")==0);
}
#ifndef PORT_CUBE_RELEASE_EMBED
int main(int argc,char** argv) {
assert(argc==2||argc==3);address=argv[1];executable=argv[0];TestDB db;O owner(db,proto);R release(db,proto);const auto b=batch();OwnerLeader leader;
if(argc==3) {
assert(owner.Acquire(std::string(32,'e'),leader)==O::Acquired);const auto image=acknowledged(db,b,leader);const std::string mode=argv[2];
db.after=[&](const std::string& q){if((mode=="receipt"&&q.find("INSERT INTO port_cube_releases")==0)||
(mode=="lease"&&q.find("DELETE FROM port_cube_owner_leases")==0)||(mode=="fences"&&q.find("DELETE FROM port_cube_item_fences")==0)||(mode=="commit"&&q=="COMMIT"))_Exit(96);};
release.ReleaseLive(b,original(b,leader),image);assert(false);
}
initialize(db);initializeGoldAddon(db);initializeOwnerAddon(db);initializeImageAckAddon(db);initializeReleaseAddon(db);reset(db,b);
assert(owner.Acquire(std::string(32,'d'),leader)==O::Acquired);auto image=acknowledged(db,b,leader);auto grant=original(b,leader);F fence(db,proto);
assert(fence.Release(b,image)==F::Refused);db.ambiguous=true;assert(release.ReleaseLive(b,grant,image)==R::Retry);
assert(value(db,"SELECT phase FROM port_cube_fences")=="RELEASED"&&number(db,"SELECT COUNT(*) FROM port_cube_owner_leases")==0&&number(db,"SELECT COUNT(*) FROM port_cube_item_fences")==0);
assert(release.ReleaseLive(b,grant,image)==R::Released&&release.ReleaseLive(b,grant,image)==R::Released&&number(db,"SELECT COUNT(*) FROM port_cube_releases")==1);
assert(value(db,"SELECT owner_grant FROM port_cube_releases")==EncodeOwnerGrant(grant)&&number(db,"SELECT gold FROM player")==700&&number(db,"SELECT COUNT(*) FROM item")==4);
assert(number(db,"SELECT COUNT(*) FROM port_economy_item_reservations")==3&&number(db,"SELECT COUNT(*) FROM port_cube_image_acks")==1);
puts("PASS atomic owner-aware release: immutable ACK/terminal receipt, lease+item-fence retirement, permanent ID tombstones retained; lost COMMIT reply and exact replay, no asset writes");
for(unsigned problem=0;problem<13;++problem) {
image=acknowledged(db,b,leader);grant=original(b,leader);auto target=grant;auto bytes=image;
if(problem==0)sql(db,"DELETE FROM port_cube_image_acks");
if(problem==1)sql(db,"UPDATE port_cube_image_acks SET owner_grant=X'00'");
if(problem==2)target.peer++;
if(problem==3)target.binding.session++;
if(problem==4)target.revision++;
if(problem==5)target.leader.generation++;
if(problem==6)sql(db,"UPDATE player SET gold=701");
if(problem==7)sql(db,"UPDATE item SET socket0=1 WHERE id=100");
if(problem==8)sql(db,"UPDATE port_cube_fences SET image=X'00'");
if(problem==9){OwnerGrant revoked;assert(owner.Revoke(b,leader,1,&grant,revoked)==O::Revoked);}
if(problem==10){OwnerGrant revoked,adopted;assert(owner.Revoke(b,leader,1,&grant,revoked)==O::Revoked);assert(owner.Adopt(b,leader,revoked.revision,6,GoldSourceFor(b,18,8,9),adopted)==O::Adopted);target=adopted;}
if(problem==11)sql(db,"UPDATE port_cube_fences SET phase='FROZEN'");
if(problem==12)sql(db,"INSERT INTO port_cube_item_fences VALUES(9000,2,3,'"+b.token+"')");
assert(release.ReleaseLive(b,target,bytes)!=R::Released&&number(db,"SELECT COUNT(*) FROM port_cube_releases")==0&&number(db,"SELECT COUNT(*) FROM port_cube_owner_leases")==1&&number(db,"SELECT COUNT(*) FROM port_cube_item_fences")>0);
}
image=acknowledged(db,b,leader);grant=original(b,leader);db.statements=0;assert(release.ReleaseLive(b,grant,image)==R::Released);const auto count=db.statements;
for(unsigned warning=0;warning<2;++warning)for(int at=1;at<=count;++at) {
image=acknowledged(db,b,leader);grant=original(b,leader);db.statements=0;if(warning)db.warnAt=at;else db.failAt=at;
assert(release.ReleaseLive(b,grant,image)!=R::Released);db.warnAt=db.failAt=0;held(db);assert(number(db,"SELECT gold FROM player")==700);
assert(release.ReleaseLive(b,grant,image)==R::Released);
}
image=acknowledged(db,b,leader);grant=original(b,leader);db.rejectCommit=true;assert(release.ReleaseLive(b,grant,image)==R::Retry);held(db);
puts("PASS absent/corrupt ACK, stale authority, revoked/adopted owner and changed SQL/image/phase refusal; every first-release SQL failure/warning and rejected COMMIT preserves all holds");
for(unsigned problem=0;problem<6;++problem) {
image=acknowledged(db,b,leader);grant=original(b,leader);assert(release.ReleaseLive(b,grant,image)==R::Released);
if(problem==0)sql(db,"DELETE FROM port_cube_releases");
if(problem==1)sql(db,"UPDATE port_cube_releases SET image=X'00'");
if(problem==2)sql(db,"DELETE FROM port_cube_image_acks");
if(problem==3)sql(db,"INSERT INTO port_cube_item_fences VALUES(9000,1,3,'"+b.token+"')");
if(problem==4){auto next=b;next.token=std::string(32,'c');next.epoch++;InventoryImage current;assert(DecodeInventoryImage(image,current,proto));next.inventory=current.items;next.gold=current.gold;for(auto& reward:next.rewards)reward.id+=1000;assert(bind(db,next,original(next,leader))==F::Done);}
if(problem==5){OwnerLeader newer;assert(owner.Acquire(std::string(32,'f'),newer)==O::Acquired);leader=newer;}
assert(release.ReleaseLive(b,grant,image)!=R::Released);
if(problem==4)assert(value(db,"SELECT phase FROM port_cube_fences")=="DRAINING"&&number(db,"SELECT COUNT(*) FROM port_cube_owner_leases")==1);
}
image=acknowledged(db,b,leader);grant=original(b,leader);assert(release.ReleaseLive(b,grant,image)==R::Released);
db.statements=0;assert(release.ReleaseLive(b,grant,image)==R::Released);const auto replayCount=db.statements;
for(unsigned warning=0;warning<2;++warning)for(int at=1;at<=replayCount;++at) {
db.statements=0;if(warning)db.warnAt=at;else db.failAt=at;assert(release.ReleaseLive(b,grant,image)!=R::Released);db.warnAt=db.failAt=0;
assert(number(db,"SELECT COUNT(*) FROM port_cube_releases")==1&&number(db,"SELECT COUNT(*) FROM port_cube_owner_leases")==0);
}
puts("PASS terminal replay requires exact ACK/history/current broker and no conflicting lease/fence; newer batch remains untouched; every replay query failure/warning refuses");
image=acknowledged(db,b,leader);grant=original(b,leader);
sql(db,"UPDATE port_cube_release_version SET version=2");assert(release.ReleaseLive(b,grant,image)==R::Retry);sql(db,"UPDATE port_cube_release_version SET version=1");
#ifdef PORT_CUBE_MYSQL
sql(db,"ALTER TABLE port_cube_releases ENGINE=MyISAM");assert(release.ReleaseLive(b,grant,image)==R::Retry);sql(db,"ALTER TABLE port_cube_releases ENGINE=InnoDB");
#else
db.engine=false;assert(release.ReleaseLive(b,grant,image)==R::Retry);db.engine=true;
#endif
sql(db,"DROP TABLE port_cube_release_version");assert(release.ReleaseLive(b,grant,image)==R::Retry);initializeReleaseAddon(db);held(db);
for(const auto& mode:{"receipt","lease","fences","commit"}) {
sql(db,"SELECT RELEASE_LOCK(CONCAT('m2_cube:',DATABASE()))");const auto child=spawnWorker(mode);int status=0;
assert(waitpid(child,&status,0)==child&&WIFEXITED(status)&&WEXITSTATUS(status)==96);const bool committed=std::string(mode)=="commit";
assert(number(db,"SELECT COUNT(*) FROM port_cube_releases")==unsigned(committed)&&number(db,"SELECT COUNT(*) FROM port_cube_owner_leases")==unsigned(!committed));
assert((number(db,"SELECT COUNT(*) FROM port_cube_item_fences")==0)==committed&&value(db,"SELECT phase FROM port_cube_fences")==std::string(committed?"RELEASED":"RESYNC"));
assert(owner.Acquire(std::string(32,'d'),leader)==O::Acquired);
}
puts("PASS missing/unknown/nontransactional release schema refusal; process exits after receipt, lease deletion, item-fence deletion or COMMIT leave one atomic outcome; no game thaw");
}
#endif
@@ -0,0 +1,35 @@
struct Setup {
CHARACTER ch;Proto proto[8];CItem item[8];
Setup(){
proto[1].aLimits[0].bType=LIMIT_REAL_TIME;
proto[2].aLimits[0].bType=LIMIT_REAL_TIME_START_FIRST_USE;proto[2].cLimitRealTimeFirstUseIndex=0;
proto[3]=proto[2];proto[4].bType=ITEM_UNIQUE;proto[4].values[2]=1;proto[5].bType=ITEM_UNIQUE;
proto[6].aLimits[0].bType=LIMIT_TIMER_BASED_ON_WEAR;proto[7].bType=ITEM_UNIQUE;proto[7].values[2]=1;proto[7].aLimits[0].bType=LIMIT_REAL_TIME;
for(unsigned n=0;n<8;++n){auto& i=item[n];i.m_pProto=&proto[n];i.m_pOwner=&ch;i.m_dwID=10+n;i.m_dwVID=100+n;i.m_wCell=n;i.extra.bytes[68]=255;ch.items[n]=&i;ITEM_MANAGER::instance().ids[i.GetID()]=&i;ITEM_MANAGER::instance().vids[i.GetVID()]=&i;}
item[1].sockets[0]=120;item[2].sockets[0]=120;item[3].sockets[0]=110;item[3].sockets[1]=3;
item[4].sockets[2]=130;item[4].sockets[1]=5;item[5].sockets[2]=10;item[5].sockets[1]=7;item[6].sockets[0]=60;item[7].sockets[0]=120;
}
void cancel(){for(auto& i:item)i.PortCubeCancelRestoreEvents();event_destroy();}
~Setup(){cancel();ITEM_MANAGER::instance().ids.clear();ITEM_MANAGER::instance().vids.clear();}
};
void advance(unsigned seconds){for(unsigned n=0;n<seconds*25;++n){++heart.pulse;wall=100+heart.pulse/25;event_process(heart.pulse);}}
struct Info:event_info_data{static unsigned deaths;int id;explicit Info(int i):id(i){}~Info(){++deaths;}};unsigned Info::deaths=0;std::vector<int> order;
EVENTFUNC(record){auto* i=dynamic_cast<Info*>(event->info);order.push_back(i->id);return 0;}
int main(int argc,char** argv){
if(argc==3&&std::strcmp(argv[1],"event-fail")==0){auto* info=new Info(1);failAt=std::strtoul(argv[2],nullptr,10);allocationCount=0;inject=true;bool failed=false;try{auto e=event_create(record,info,1);}catch(const std::bad_alloc&){failed=true;}inject=false;assert(failed&&Info::deaths==1&&!event_count());return 0;}
if(argc==3&&std::strcmp(argv[1],"prepare-fail")==0){Setup s;PortCubeRestorePlan plan;failAt=std::strtoul(argv[2],nullptr,10);allocationCount=0;inject=true;const bool ok=PortCubePrepareRestoredInventory(&s.ch,plan);inject=false;const auto count=allocationCount;
if(!failAt){assert(ok);std::printf("ALLOCATIONS %zu\n",count);}else{assert(!ok&&!plan.Prepared()&&!plan.Enabled());for(auto& i:s.item)assert(i.GetSkipSave());advance(120);assert(!event_count()&&!infoLive&&!saves&&!removals);assert(s.item[4].sockets[1]==5&&s.item[3].sockets[0]==110);}return 0;}
{auto a=event_create(record,new Info(1),1);auto b=event_create(record,new Info(2),1);heart.pulse=1;event_process(1);assert(order==std::vector<int>({1,2})&&!event_count());a=nullptr;b=nullptr;assert(Info::deaths==2);}
heart.pulse=0;wall=100;
{Setup s;PortCubeRestorePlan plan;assert(PortCubePrepareRestoredInventory(&s.ch,plan)&&plan.Prepared()&&!plan.Enabled()&&PortCubeRestoredInventoryReady(&s.ch,plan));
assert(s.item[1].m_pkRealTimeExpireEvent&&!s.item[2].m_pkRealTimeExpireEvent&&s.item[3].m_pkRealTimeExpireEvent&&s.item[4].m_pkUniqueExpireEvent&&!s.item[5].m_pkUniqueExpireEvent&&!s.item[6].m_pkTimerBasedOnWearExpireEvent&&s.item[7].m_pkRealTimeExpireEvent&&!s.item[7].m_pkUniqueExpireEvent);
const auto events=event_count();assert(PortCubePrepareRestoredInventory(&s.ch,plan)&&event_count()==events);advance(35);assert(!saves&&!removals&&s.item[4].sockets[1]==5&&s.item[5].sockets[2]==10&&s.item[6].sockets[0]==60&&PortCubeRestoredInventoryReady(&s.ch,plan));
held=false;advance(2);assert(!saves&&!removals);held=true;s.item[0].extra.bytes[68]=0;assert(!PortCubeEnableRestoredInventory(&s.ch,plan));for(auto& i:s.item)assert(i.GetSkipSave());s.item[0].extra.bytes[68]=255;
++s.ch.vid;assert(!PortCubeRestoredInventoryReady(&s.ch,plan));--s.ch.vid;assert(PortCubeEnableRestoredInventory(&s.ch,plan)&&PortCubeEnableRestoredInventory(&s.ch,plan)&&plan.Enabled());for(auto& i:s.item)assert(!i.GetSkipSave());advance(2);assert(!saves&&!removals);held=false;advance(1);
assert(removals==4&&saves==1&&s.item[4].sockets[1]==0&&s.item[5].sockets[2]==10&&s.item[6].sockets[0]==60&&!event_count()&&!infoLive);held=true;
}
heart.pulse=0;wall=100;saves=packets=removals=0;
{Setup s;s.item[1].sockets[0]=200;PortCubeRestorePlan plan;assert(PortCubePrepareRestoredInventory(&s.ch,plan)&&PortCubeEnableRestoredInventory(&s.ch,plan));held=false;advance(1);assert(s.item[1].sockets[0]==200&&!removals);s.ch.items[1]=nullptr;s.item[1].m_pOwner=nullptr;advance(101);assert(ITEM_MANAGER::instance().Find(s.item[1].GetID())==nullptr);held=true;}
assert(!event_count()&&!infoLive);
puts("PASS actual event queue/expiry callbacks/lifecycle/inventory plan: held+skip-save pauses, immutable deadlines, first-use/wear/unique rules, atomic save enable, identity/metadata checks, drop lifetime and stable ordering; explicit character/item/DB boundary, not resume authorization");
}
@@ -0,0 +1,64 @@
// Explicit character/item/DB boundary. Tests compile the actual event queue,
// original expiry callbacks, lifecycle methods and inventory restoration plan.
#include <algorithm>
#include <array>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstdint>
#include <cstring>
#include <list>
#include <map>
#include <memory>
#include <new>
#include <vector>
#include "src/server/common/economy.h"
#include "src/server/game/src/port_cube_restore.h"
static size_t failAt=0,allocationCount=0;static bool inject=false;
void* operator new(size_t n){if(inject&&++allocationCount==failAt)throw std::bad_alloc();if(auto* p=std::malloc(n?n:1))return p;throw std::bad_alloc();}
void operator delete(void* p)noexcept{std::free(p);}void operator delete(void* p,size_t)noexcept{std::free(p);}
#define M2_NEW new
#define FALSE 0
#define TRUE 1
#define M2_DELETE(p) delete (p)
#define sys_err(...) ((void)0)
#define sys_log(...) ((void)0)
using DWORD=uint32_t;using WORD=uint16_t;
#include "src/server/game/src/event.h"
#include "src/server/game/src/event_queue.h"
constexpr unsigned INVENTORY=1,INVENTORY_MAX_NUM=225,ITEM_UNIQUE=2,ITEM_LIMIT_MAX_NUM=2;
constexpr unsigned LIMIT_REAL_TIME=1,LIMIT_REAL_TIME_START_FIRST_USE=2,LIMIT_TIMER_BASED_ON_WEAR=3;
constexpr unsigned ITEM_SOCKET_UNIQUE_SAVE_TIME=1,ITEM_SOCKET_UNIQUE_REMAIN_TIME=2,UNIQUE_ITEM_HIDE_ALIGNMENT_TITLE=70038;
static int passes_per_sec=25;static int64_t wall=100;static unsigned saves=0,packets=0,removals=0,alignments=0,infoLive=0;static bool held=true;
#define PASSES_PER_SEC(x) ((x)*passes_per_sec)
#define MIN(a,b) ((a)<(b)?(a):(b))
struct Heart{int pulse=0;}heart,*thecore_heart=&heart;
void ContinueOnFatalError(){assert(false);}void ShutdownOnFatalError(){assert(false);}
int64_t get_global_time(){return wall;}
struct Proto{unsigned bType=1;struct Limit{unsigned bType=0;}aLimits[2];int cLimitRealTimeFirstUseIndex=-1;long values[3]={};};
struct CHARACTER{unsigned pid=1,vid=42;CItem* items[225]={};unsigned GetPlayerID(){return pid;}unsigned GetVID(){return vid;}CItem* GetInventoryItem(unsigned cell){return items[cell];}void ShowAlignment(bool){++alignments;}};
using LPCHARACTER=CHARACTER*;
bool PortCubeActorHeld(const CHARACTER*){return held;}
struct CItem{
Proto* m_pProto=nullptr;bool m_portCubeTemplate=false,m_bEquipped=false,m_bSkipSave=true,locked=false,exchange=false;CHARACTER* m_pOwner=nullptr;
DWORD m_dwID=0,m_dwVID=0;unsigned m_bWindow=1,m_wCell=0;long sockets[3]={};unsigned count=1,vnum=100;
struct Attr{uint8_t bType=0;int16_t sValue=0;}attrs[7];struct Extra{uint8_t bytes[69]={};}extra;
LPEVENT m_pkDestroyEvent,m_pkExpireEvent,m_pkUniqueExpireEvent,m_pkRealTimeExpireEvent,m_pkTimerBasedOnWearExpireEvent,m_pkAccessorySocketExpireEvent,m_pkOwnershipEvent;
DWORD GetID(){return m_dwID;}DWORD GetVID(){return m_dwVID;}unsigned GetVnum(){return vnum;}unsigned GetOriginalVnum(){return vnum;}unsigned GetCount(){return count;}
CHARACTER* GetOwner(){return m_pOwner;}unsigned GetWindow(){return m_bWindow;}unsigned GetCell(){return m_wCell;}void* GetSectree(){return nullptr;}
bool GetSkipSave(){return m_bSkipSave;}void SetSkipSave(bool value){m_bSkipSave=value;}bool isLocked(){return locked;}bool IsExchanging(){return exchange;}
unsigned GetType(){return m_pProto->bType;}long GetValue(unsigned n){return m_pProto->values[n];}Proto* GetProto(){return m_pProto;}
long GetSocket(unsigned n)const{return sockets[n];}void SetSocket(unsigned n,long value){sockets[n]=value;++saves;++packets;}
uint8_t GetAttributeType(unsigned n){return attrs[n].bType;}int16_t GetAttributeValue(unsigned n){return attrs[n].sValue;}const Extra& GetPortExtra(){return extra;}
bool IsRealTimeItem(){for(auto l:m_pProto->aLimits)if(l.bType==LIMIT_REAL_TIME)return true;return false;}
bool IsNewMountItem(){return false;}void ClearMountAttributeAndAffect(){}const char* GetName(){return "fixture";}
void SetUniqueExpireEvent(LPEVENT e){m_pkUniqueExpireEvent=e;}
unsigned PortCubeRestoreEventMask();bool PortCubeRestoreEligible(bool=false);bool PortCubeRestoreEventsReady(bool=false);bool PortCubePrepareRestoreEvents();void PortCubeCancelRestoreEvents();
};
using LPITEM=CItem*;
struct item_event_info:event_info_data{LPITEM item=nullptr;item_event_info(){++infoLive;}~item_event_info(){--infoLive;}};
struct item_vid_event_info:event_info_data{DWORD item_vid=0;item_vid_event_info(){++infoLive;}~item_vid_event_info(){--infoLive;}};
struct ITEM_MANAGER{std::map<DWORD,LPITEM> ids,vids;static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;}
LPITEM Find(DWORD id){auto it=ids.find(id);return it==ids.end()?nullptr:it->second;}LPITEM FindByVID(DWORD vid){auto it=vids.find(vid);return it==vids.end()?nullptr:it->second;}
void RemoveItem(LPITEM item,const char*){++removals;item->PortCubeCancelRestoreEvents();if(item->m_pOwner)item->m_pOwner->items[item->m_wCell]=nullptr;ids.erase(item->GetID());vids.erase(item->GetVID());}
};
@@ -0,0 +1,44 @@
#define PORT_CUBE_RELEASE_EMBED
#include "cube_release_probe.cpp"
#include "src/server/common/cube_handshake.h"
static void terminal(TestDB& db,const Batch& b,const OwnerLeader& leader,std::string& image,OwnerGrant& grant) {
image=acknowledged(db,b,leader);grant=original(b,leader);R release(db,proto);assert(release.ReleaseLive(b,grant,image)==R::Released);
}
int main(int argc,char** argv){
assert(argc==2);address=argv[1];TestDB db;initialize(db);initializeGoldAddon(db);initializeOwnerAddon(db);initializeImageAckAddon(db);initializeReleaseAddon(db);
const auto b=batch();reset(db,b);O owner(db,proto);R release(db,proto);OwnerLeader leader;assert(owner.Acquire(std::string(32,'d'),leader)==O::Acquired);std::string image;OwnerGrant grant;
terminal(db,b,leader,image,grant);assert(release.CheckResumeLive(b,grant,image)==R::Checked&&release.CheckResumeLive(b,grant,image)==R::Checked);
// Historical release replay can still be valid after current assets change;
// a resume preflight cannot treat that history as current image permission.
sql(db,"UPDATE player SET gold=701");assert(release.ReleaseLive(b,grant,image)==R::Released&&release.CheckResumeLive(b,grant,image)!=R::Checked);
for(unsigned problem=0;problem<16;++problem){
terminal(db,b,leader,image,grant);auto target=grant;
if(problem==0)sql(db,"UPDATE item SET socket0=5 WHERE id=100");
if(problem==1)sql(db,"DELETE FROM port_cube_releases");
if(problem==2)sql(db,"UPDATE port_cube_releases SET owner_grant=X'00'");
if(problem==3)sql(db,"DELETE FROM port_cube_image_acks");
if(problem==4)sql(db,"UPDATE port_cube_fences SET drain_state=2");
if(problem==5)sql(db,"UPDATE port_cube_fences SET phase='RESYNC'");
if(problem==6)sql(db,"UPDATE port_cube_requests SET rolls=X'646464'");
if(problem==7)sql(db,"DELETE FROM port_cube_gold_sources");
if(problem==8)sql(db,"DELETE FROM port_economy_item_reservations WHERE id=100");
if(problem==9)sql(db,"INSERT INTO port_cube_item_fences VALUES(9000,1,3,'"+b.token+"')");
if(problem==10)sql(db,"INSERT INTO port_cube_item_fences VALUES(9000,2,3,'"+b.token+"')");
if(problem==11)++target.binding.session;
if(problem==12)++target.peer;
if(problem==13)++target.leader.generation;
if(problem==14)++target.revision;
if(problem==15){auto next=b;next.token=std::string(32,'c');next.epoch++;InventoryImage current;assert(DecodeInventoryImage(image,current,proto));next.inventory=current.items;next.gold=current.gold;for(auto& reward:next.rewards)reward.id+=1000;assert(bind(db,next,original(next,leader))==F::Done);}
assert(release.CheckResumeLive(b,target,image)!=R::Checked);
}
terminal(db,b,leader,image,grant);db.statements=0;assert(release.CheckResumeLive(b,grant,image)==R::Checked);const auto count=db.statements;
for(unsigned warning=0;warning<2;++warning)for(int at=1;at<=count;++at){
db.statements=0;if(warning)db.warnAt=at;else db.failAt=at;assert(release.CheckResumeLive(b,grant,image)!=R::Checked);db.warnAt=db.failAt=0;
assert(release.CheckResumeLive(b,grant,image)==R::Checked&&number(db,"SELECT gold FROM player")==700&&number(db,"SELECT COUNT(*) FROM item")==4&&number(db,"SELECT COUNT(*) FROM port_cube_owner_leases")==0&&number(db,"SELECT COUNT(*) FROM port_cube_releases")==1);
}
db.rejectCommit=true;assert(release.CheckResumeLive(b,grant,image)==R::CheckRetry);db.ambiguous=true;assert(release.CheckResumeLive(b,grant,image)==R::CheckRetry);assert(release.CheckResumeLive(b,grant,image)==R::Checked);
auto frame=ArmFrame(b,17);frame.cookie=7;frame.message=Message::LiveResumeCheckRequest;frame.body=image;const auto wire=EncodeHandshake(frame);Handshake decoded;
assert(!wire.empty()&&DecodeHandshake(wire.data(),wire.size(),decoded)&&!IsDbHandshakeReply(frame.message));for(size_t n=0;n<wire.size();++n)assert(!DecodeHandshake(wire.data(),n,decoded));
frame.message=Message::LiveResumeCheckAnswer;frame.status=Status::LiveResumeChecked;assert(ValidHandshake(frame)&&IsDbHandshakeReply(frame.message));frame.body.clear();assert(!ValidHandshake(frame));frame.status=Status::Held;assert(ValidHandshake(frame));
puts("PASS actual resume preflight account transaction: current assets+terminal ACK/history+current broker+sealed source/fixed DONE/ID tombstones, corrupt/stale/newer state refusal, every query failure/warning and commit ambiguity; no save/load unlock or actor thaw");
}
@@ -0,0 +1,95 @@
#define main cubeBaseMain
#include "cube_batch_probe.cpp"
#undef main
#include <unistd.h>
static unsigned syncs=0,failSync=0,crashSync=0;
static int SourceSync(int fd){++syncs;if(syncs==failSync){errno=EIO;return -1;}const auto r=::fsync(fd);if(!r&&syncs==crashSync)_Exit(93);return r;}
#define fsync SourceSync
#include "src/server/common/cube_gold_outbox.h"
#undef fsync
#include "src/server/common/cube_gold_store.h"
#include "src/server/common/cube_handshake.h"
using G=GoldIntentStore<TestDB>;
static GoldDelivery delivery(const Batch& b,unsigned sequence=1) {
GoldDelivery d;auto& i=d.intent;i.account=b.account;i.player=b.player;i.epoch=b.epoch;i.owner=b.owner;i.request=b.token;
i.event=std::string(31,'e')+char('0'+sequence);i.sequence=sequence;i.amount=250;i.source=1;
d.session=8;d.cookie=7;d.handle=6;d.ground=100+sequence;d.vnum=1;d.map=1;return d;
}
static GoldSourceSeal source(const Batch& b,bool empty=false) {
GoldSourceSeal s;static_cast<GoldSourceBinding&>(s)=GoldSourceFor(b,8,7,6);if(!empty)s.events={delivery(b).intent.event};return s;
}
static void resetSource(TestDB& db,const Batch& b) {
db.Rollback();db.failAt=db.warnAt=0;db.ambiguous=db.rejectCommit=false;db.after={};
sql(db,"DELETE FROM port_cube_gold_sources");sql(db,"DELETE FROM port_cube_gold_intents");reset(db,b);
}
static void settle(TestDB& db,const Batch& b) {Store craft(db,proto);Store::Receipt r;assert(craft.Prepare(b,[]{return 1u;})==Store::Prepared&&craft.Execute(b.token,1,1,r)==Store::Complete);}
static void waitWorker(pid_t child,int expected){int status=0;assert(waitpid(child,&status,0)==child&&WIFEXITED(status)&&WEXITSTATUS(status)==expected);}
int main(int argc,char** argv) {
assert(argc==2||argc==3);address=argv[1];executable=argv[0];auto b=batch();const auto d=delivery(b);const auto seal=source(b);const auto path=address+".sources";
if(argc==3) {
const std::string mode=argv[2];
if(mode=="close-sync"||mode=="close-ack-sync") {
GoldOutbox out;assert(out.Open(path+"."+mode));syncs=0;crashSync=1;
if(mode=="close-sync")out.CloseSource(seal);else out.AcknowledgeSource(seal);assert(false);
}
TestDB db;G gold(db,proto);
if(mode=="sql-insert"||mode=="sql-commit")db.after=[&](const std::string& q){if((mode=="sql-insert"&&q.find("INSERT INTO port_cube_gold_sources")==0)||(mode=="sql-commit"&&q=="COMMIT"))_Exit(92);};
assert(gold.CloseSource(b,seal)==G::Stored);return 77;
}
TestDB db;initialize(db);initializeGoldAddon(db);G gold(db,proto);G::Receipt receipt;FenceStore<TestDB> fence(db,proto);std::string image;
resetSource(db,b);settle(db,b);assert(fence.Resync(b,image)==FenceStore<TestDB>::Refused);
{GoldOutbox out;assert(out.Open(path+".empty")&&out.CloseSource(source(b,true)));auto pending=out.PendingSources();assert(pending.size()==1&&pending[0].events.empty());assert(gold.CloseSource(b,pending[0])==G::Stored&&out.AcknowledgeSource(pending[0]));assert(out.SourceAcknowledged(pending[0]));}
assert(fence.Resync(b,image)==FenceStore<TestDB>::Done&&fence.Release(b,image)==FenceStore<TestDB>::Done);
{GoldOutbox out;assert(out.Open(path+".empty")&&out.IsClosing(b.token)&&out.SourceAcknowledged(source(b,true))&&out.PendingSources().empty());assert(!out.Claim(d));}
puts("PASS SQL emptiness is not closure; zero-reward source requires durable close, exact DB proof and local close ACK");
resetSource(db,b);
{GoldOutbox out;assert(out.Open(path+".late")&&out.Claim(d)&&out.CloseSource(seal));assert(out.PendingSources().empty()&&!out.Claim(delivery(b,2)));assert(gold.CloseSource(b,seal)==G::Blocked);}
db.ambiguous=true;assert(gold.Enqueue(b,d.intent)==G::Retry);
{GoldOutbox out;assert(out.Open(path+".late")&&out.IsClosing(b.token)&&out.PendingSources().empty());assert(gold.Enqueue(b,d.intent)==G::Stored&&out.Acknowledge(d));auto pending=out.PendingSources();assert(pending.size()==1&&pending[0].events==seal.events);db.ambiguous=true;assert(gold.CloseSource(b,pending[0])==G::Retry);assert(gold.CloseSource(b,pending[0])==G::Stored&&out.AcknowledgeSource(pending[0]));}
{GoldOutbox out;assert(out.Open(path+".late")&&out.SourceAcknowledged(seal)&&out.PendingSources().empty());auto stale=seal;stale.session++;assert(!out.CloseSource(stale)&&!out.AcknowledgeSource(stale));}
assert(gold.Enqueue(b,delivery(b,2).intent)==G::Blocked&&gold.Enqueue(b,d.intent)==G::Stored);
auto conflict=seal;conflict.events={std::string(32,'f')};assert(gold.CloseSource(b,conflict)==G::Refused);conflict=seal;conflict.cookie++;assert(gold.CloseSource(b,conflict)==G::Refused);
settle(db,b);assert(fence.Resync(b,image)==FenceStore<TestDB>::Refused);assert(gold.Apply(d.intent.event,1,1,receipt)==G::Applied);
const auto manifest=EncodeGoldManifest(seal.events);sql(db,"UPDATE port_cube_gold_sources SET manifest=X'00000000'");assert(fence.Resync(b,image)!=FenceStore<TestDB>::Done);
sql(db,"UPDATE port_cube_gold_sources SET manifest=X'"+hex(manifest.data(),manifest.size())+"'");assert(fence.Resync(b,image)==FenceStore<TestDB>::Done&&fence.Release(b,image)==FenceStore<TestDB>::Done);
puts("PASS late local delivery drains before source proof; lost enqueue/close ACKs replay, post-close new events refused, pending credits/corrupt seals block image and release");
for(const auto& name:{"close-sync","close-ack-sync"}) {
GoldOutbox out;assert(out.Open(path+"."+name)&&out.Claim(d));
if(std::string(name)=="close-ack-sync")assert(out.CloseSource(seal)&&out.Acknowledge(d));
}
waitWorker(spawnWorker("close-sync"),93);
{GoldOutbox out;assert(out.Open(path+".close-sync")&&out.IsClosing(b.token)&&out.PendingSources().empty());assert(out.Acknowledge(d)&&out.PendingSources().size()==1);}
waitWorker(spawnWorker("close-ack-sync"),93);
{GoldOutbox out;assert(out.Open(path+".close-ack-sync")&&out.SourceAcknowledged(seal));}
{GoldOutbox out;assert(out.Open(path+".failed-close")&&out.Claim(d));syncs=0;failSync=1;assert(!out.CloseSource(seal)&&!out.Ready());failSync=0;}
{GoldOutbox out;assert(out.Open(path+".failed-close")&&out.IsClosing(b.token)&&!out.Claim(delivery(b,2)));}
puts("PASS close/close-ACK fsync process exits and failed sync preserve closure across restart, never reopen source or reuse a sequence");
resetSource(db,b);assert(gold.Enqueue(b,d.intent)==G::Stored);db.statements=0;assert(gold.CloseSource(b,seal)==G::Stored);const int count=db.statements;
for(unsigned warning=0;warning<2;++warning)for(int at=1;at<=count;++at) {
resetSource(db,b);assert(gold.Enqueue(b,d.intent)==G::Stored);db.statements=0;if(warning)db.warnAt=at;else db.failAt=at;
assert(gold.CloseSource(b,seal)!=G::Stored);db.failAt=db.warnAt=0;
assert(number(db,"SELECT COUNT(*) FROM port_cube_gold_sources")==0&&number(db,"SELECT gold FROM player")==1000);assert(gold.CloseSource(b,seal)==G::Stored);
}
resetSource(db,b);assert(gold.Enqueue(b,d.intent)==G::Stored);db.rejectCommit=true;assert(gold.CloseSource(b,seal)==G::Retry&&number(db,"SELECT COUNT(*) FROM port_cube_gold_sources")==0);
for(const auto& mode:{"sql-insert","sql-commit"}) {
resetSource(db,b);assert(gold.Enqueue(b,d.intent)==G::Stored);waitWorker(spawnWorker(mode),92);
assert(number(db,"SELECT COUNT(*) FROM port_cube_gold_sources")==(std::string(mode)=="sql-commit"?1:0));assert(gold.CloseSource(b,seal)==G::Stored);
}
resetSource(db,b);assert(gold.Enqueue(b,d.intent)==G::Stored);auto first=spawnWorker("close"),second=spawnWorker("close");waitWorker(first,77);waitWorker(second,77);assert(number(db,"SELECT COUNT(*) FROM port_cube_gold_sources")==1&&number(db,"SELECT gold FROM player")==1000);
puts("PASS every source-close SQL failure/warning boundary, rejected/lost commit, before/after-COMMIT process exits and concurrent duplicate sealing");
std::vector<std::string> events;for(unsigned n=1;n<=GoldSourceLimit;++n){char id[33];snprintf(id,sizeof(id),"%032x",n);events.emplace_back(id);}
const auto maximum=EncodeGoldManifest(events);std::vector<std::string> decoded;assert(maximum.size()==32772&&DecodeGoldManifest(maximum,decoded)&&events==decoded);
assert(!DecodeGoldManifest(maximum+"x",decoded));events.push_back(events.front());assert(EncodeGoldManifest(events).empty());events={d.intent.event,d.intent.event};assert(EncodeGoldManifest(events).empty());
auto frame=ArmFrame(b,8);frame.cookie=7;frame.message=Message::GoldClose;frame.body=maximum;const auto wire=EncodeHandshake(frame);Handshake received;
assert(wire.size()==32874&&DecodeHandshake(wire.data(),wire.size(),received));frame.message=Message::GoldCloseAck;frame.status=Status::GoldClosed;assert(ValidHandshake(frame));
ActorHandshake actor;assert(actor.Start(b,8,1,true)&&!actor.Answer(frame)&&actor.BlocksActions());
sql(db,"UPDATE port_cube_gold_version SET version=1");assert(!gold.Ready());sql(db,"UPDATE port_cube_gold_version SET version=2");
#ifdef PORT_CUBE_MYSQL
sql(db,"ALTER TABLE port_cube_gold_sources ENGINE=MyISAM");assert(!gold.Ready());sql(db,"ALTER TABLE port_cube_gold_sources ENGINE=InnoDB");
#endif
puts("PASS bounded exact ordered manifests and internal close wire, malformed/duplicate/oversize rejection, no actor thaw and explicit old-addon refusal");
}
+26 -5
View File
@@ -4,6 +4,7 @@
#include <cstdlib>
#include <iostream>
#include <sys/wait.h>
#include <spawn.h>
#include <unistd.h>
#ifdef PORT_ECONOMY_MYSQL
#include "src/server/common/economy_mysql.h"
@@ -12,6 +13,8 @@
#endif
using namespace PortEconomy;
static std::string address;
static std::string economyExecutable;
extern char** environ;
struct TestDB {
#ifdef PORT_ECONOMY_MYSQL
MYSQL handle;Mysql* db;
@@ -186,6 +189,25 @@ static void checkCrash(TestDB& db,unsigned mode) {
if(mode==9){assert(integer(db,"SELECT generation FROM port_economy_gaya WHERE pid=2")==RetiredGeneration);assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='points'")==0);assert(integer(db,"SELECT SUM(count) FROM item WHERE owner_id=2 AND window='MALL'")==2000);}
if(mode==8){assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='open_slot'")==18);assert(integer(db,"SELECT count FROM item WHERE id=50")==1);}
}
// exec a fresh image instead of opening SQLite/MySQL in a forked macOS ASan
// process (system logging/libsqlite runtime state is not fork-safe). Preserve
// the exact requests, query-boundary exits and concurrent-settlement assertions.
static bool EconomyWorkerRequested(int argc,char** argv){return argc==6&&std::string(argv[2])=="--economy-worker";}
static int EconomyWorkerMain(char** argv) {
address=argv[1];const std::string mode=argv[3],encoded=argv[4];assert(encoded.size()==2*sizeof(Request));Request r;
auto* bytes=reinterpret_cast<unsigned char*>(&r);
for(size_t n=0;n<sizeof(Request);++n){auto digit=[](char c)->unsigned{if(c>='0'&&c<='9')return unsigned(c-'0');assert(c>='a'&&c<='f');return unsigned(c-'a'+10);};bytes[n]=static_cast<unsigned char>((digit(encoded[2*n])<<4)|digit(encoded[2*n+1]));}
assert(Valid(r));TestDB worker;Store<TestDB> store(worker,itemSize);
if(mode=="crash") {unsigned count=0;const unsigned boundary=unsigned(std::stoul(argv[5]));worker.after=[&](const std::string&){if(++count==boundary)_exit(70);};store.Settle(r.player,r.account);return 71;}
if(mode=="buyer") {bool queued=false;for(unsigned retry=0;retry<20&&!queued;++retry){queued=store.Enqueue(r);if(!queued)usleep(10000);}if(!queued)return 80;}
else assert(mode=="settle");
for(unsigned retry=0;retry<20;++retry){if(store.Settle(r.player,r.account)!=Store<TestDB>::Retry)return 0;usleep(10000);}return mode=="buyer"?81:82;
}
static pid_t SpawnEconomyWorker(const char* mode,const Request& r,unsigned boundary=0) {
std::string encoded=Hex(&r,sizeof(r)),number=std::to_string(boundary),worker="--economy-worker",kind=mode;
char* args[]={const_cast<char*>(economyExecutable.c_str()),const_cast<char*>(address.c_str()),const_cast<char*>(worker.c_str()),const_cast<char*>(kind.c_str()),const_cast<char*>(encoded.c_str()),const_cast<char*>(number.c_str()),nullptr};
pid_t child=0;assert(posix_spawn(&child,economyExecutable.c_str(),nullptr,nullptr,args,environ)==0);return child;
}
static void crashes(TestDB& db){
const char* names[]={"list","buy","refund","claim","cancel","withdraw","Gaya buy","Gaya refresh","Gaya expand","Gaya retire"};
unsigned total=0;Store<TestDB> store(db,itemSize);
@@ -193,8 +215,7 @@ static void crashes(TestDB& db){
auto r=prepareCrash(db,mode);assert(store.Enqueue(r));unsigned boundaries=0;db.after=[&](const std::string&){++boundaries;};assert(store.Settle(r.player,r.account)==Store<TestDB>::Settled);db.after={};checkCrash(db,mode);
for(unsigned boundary=1;boundary<=boundaries;++boundary){
r=prepareCrash(db,mode);assert(store.Enqueue(r));
pid_t child=fork();assert(child>=0);
if(!child){TestDB worker;Store<TestDB> s(worker,itemSize);unsigned count=0;worker.after=[&](const std::string&){if(++count==boundary)_exit(70);};s.Settle(r.player,r.account);_exit(71);}
const auto child=SpawnEconomyWorker("crash",r,boundary);
int status=0;const auto waited=waitpid(child,&status,0);
if(waited!=child||!WIFEXITED(status)||WEXITSTATUS(status)!=70){std::cerr<<"crash probe mode="<<mode<<" boundary="<<boundary<<" waited="<<waited<<" status="<<status<<"\n";std::abort();}
auto result=store.Settle(r.player,r.account);assert(result==Store<TestDB>::Settled||result==Store<TestDB>::None);checkCrash(db,mode);
@@ -205,13 +226,13 @@ static void crashes(TestDB& db){
}
static void races(TestDB& db){
reset(db);uint64_t l=listing(db);Request a=req(Buy,2,2),b=req(Buy,3,3);a.reference=b.reference=l;a.price=b.price=750;
pid_t children[2];unsigned i=0;for(const auto& r:{a,b}){children[i]=fork();assert(children[i]>=0);if(!children[i++]){TestDB worker;Store<TestDB> s(worker,itemSize);bool queued=false;for(unsigned retry=0;retry<20&&!queued;++retry){queued=s.Enqueue(r);if(!queued)usleep(10000);}if(!queued)_exit(80);for(unsigned retry=0;retry<20;++retry){auto result=s.Settle(r.player,r.account);if(result!=Store<TestDB>::Retry)_exit(0);usleep(10000);}_exit(81);}}
pid_t children[2];unsigned i=0;for(const auto& r:{a,b})children[i++]=SpawnEconomyWorker("buyer",r);
for(auto child:children){int status;assert(waitpid(child,&status,0)==child);if(!WIFEXITED(status)||WEXITSTATUS(status)!=0)std::cerr<<"race child status="<<status<<"\n";assert(WIFEXITED(status)&&WEXITSTATUS(status)==0);}
assert(integer(db,"SELECT COUNT(*) FROM port_economy_orders WHERE state='READY'")==1);assert(integer(db,"SELECT SUM(gold) FROM player WHERE id IN(2,3)")==1250);
puts("PASS concurrent buyers: one reservation, one debit");
for(bool refund:{false,true}) {
reset(db);l=listing(db);uint64_t order=buy(db,l);Request delivery=req(refund?Refund:Claim,2,2,250);delivery.reference=order;Store<TestDB> store(db,itemSize);assert(store.Enqueue(delivery));
for(unsigned i=0;i<2;++i){children[i]=fork();assert(children[i]>=0);if(!children[i]){TestDB worker;Store<TestDB> s(worker,itemSize);for(unsigned retry=0;retry<20;++retry){if(s.Settle(2,2)!=Store<TestDB>::Retry)_exit(0);usleep(10000);}_exit(82);}}
for(unsigned i=0;i<2;++i)children[i]=SpawnEconomyWorker("settle",delivery);
for(auto child:children){int status;assert(waitpid(child,&status,0)==child&&WIFEXITED(status)&&WEXITSTATUS(status)==0);}
assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==0);
if(refund){assert(integer(db,"SELECT gold FROM player WHERE id=2")==1000);assert(integer(db,"SELECT COUNT(*) FROM port_economy_custody WHERE id=10")==1);}
@@ -219,7 +240,7 @@ static void races(TestDB& db){
}
puts("PASS concurrent settlement of the same claim/refund: one delivery or one refund");
}
int main(int argc,char** argv){assert(argc==2||argc==3);address=argv[1];TestDB db;
int main(int argc,char** argv){if(EconomyWorkerRequested(argc,argv))return EconomyWorkerMain(argv);assert(argc==2||argc==3);economyExecutable=argv[0];address=argv[1];TestDB db;
#ifndef PORT_ECONOMY_MYSQL
std::string item="id INTEGER PRIMARY KEY,owner_id INTEGER NOT NULL,window TEXT NOT NULL,pos INTEGER NOT NULL,count INTEGER NOT NULL,vnum INTEGER NOT NULL";
for(unsigned i=0;i<3;++i)item+=",socket"+std::to_string(i)+" INTEGER NOT NULL DEFAULT 0";
@@ -16,6 +16,7 @@ struct ViewDB:TestDB {
bool Commit(){if(failing=="COMMIT"){failed=true;return false;}return TestDB::Commit();}
};
int main(int argc,char** argv) {
if(EconomyWorkerRequested(argc,argv))return EconomyWorkerMain(argv);
assert(argc==2||argc==3);economy_base_main(2,argv);address=argv[1];ViewDB db;reset(db);
sql(db,"UPDATE item SET port_extra=X'"+std::string(138,'0')+"' WHERE id=10");
uint64_t id=listing(db);Request r=req(UiStatus);r.generation=123;r.reference=0;r.slot=0;memset(r.token,'0',32);r.token[32]=0;
@@ -0,0 +1,47 @@
// Actual libsql worker + actual SQLFences.h on a dedicated socket-only server.
#include "src/server/libsql/AsyncSQL.h"
#include "src/server/db/src/SQLFences.h"
#include <cassert>
#include <chrono>
#include <memory>
#include <thread>
#include <sys/stat.h>
int main(int argc,char** argv) {
assert(argc==2);const std::string socket=argv[1];struct stat info={};
assert(socket.find("/tmp/ch5-cube-mysql.")==0&&stat(socket.c_str(),&info)==0&&S_ISSOCK(info.st_mode));
// Legacy CAsyncSQL has no socket argument. Set libmysql's explicit default
// BEFORE construction/worker launch, then verify server identity read-only.
mysql_unix_port=argv[1];CAsyncSQL2 sql;
assert(sql.Setup("localhost","root","","cube_batch_test","utf8",false,0));
const auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(20);
while(!sql.IsConnected()&&std::chrono::steady_clock::now()<deadline)std::this_thread::sleep_for(std::chrono::milliseconds(5));
assert(sql.IsConnected());
// Identity validation itself travels through this same worker connection.
auto ticket=PortSQLFence::PlayerRouter().Reserve(PortSQLFence::Cube,1);assert(ticket);
sql.ReturnQuery("SELECT @@socket",reinterpret_cast<void*>(uintptr_t(ticket)));
auto wait=[&](PortSQLFence::Kind kind)->std::unique_ptr<SQLMsg>{
while(std::chrono::steady_clock::now()<deadline){if(auto* message=PortSQLFence::Pop(&sql,kind))return std::unique_ptr<SQLMsg>(message);std::this_thread::sleep_for(std::chrono::milliseconds(5));}
assert(false&&"worker FIFO timeout");return nullptr;
};
{auto message=wait(PortSQLFence::Cube);assert(!message->uiSQLErrno&&message->Get()->uiNumRows==1);auto row=mysql_fetch_row(message->Get()->pSQLResult);assert(row&&row[0]&&socket==row[0]);}
const auto failures=sql.FailureEpoch();
sql.AsyncQuery("SET @cube_fifo_probe=41");
ticket=PortSQLFence::PlayerRouter().Reserve(PortSQLFence::Cube,77);assert(ticket);
sql.ReturnQuery("SELECT @cube_fifo_probe",reinterpret_cast<void*>(uintptr_t(ticket)));
sql.AsyncQuery("SET @cube_fifo_probe=42");
ticket=PortSQLFence::PlayerRouter().Reserve(PortSQLFence::Economy,77);assert(ticket);
sql.ReturnQuery("SELECT @cube_fifo_probe",reinterpret_cast<void*>(uintptr_t(ticket)));
// Economy polls first and pumps both worker results; Cube must retain its own.
{auto message=wait(PortSQLFence::Economy);assert(!message->uiSQLErrno&&reinterpret_cast<uintptr_t>(message->pvUserData)==77);auto row=mysql_fetch_row(message->Get()->pSQLResult);assert(row&&row[0]&&std::string(row[0])=="42");}
{auto message=wait(PortSQLFence::Cube);assert(!message->uiSQLErrno&&reinterpret_cast<uintptr_t>(message->pvUserData)==77);auto row=mysql_fetch_row(message->Get()->pSQLResult);assert(row&&row[0]&&std::string(row[0])=="41");}
assert(sql.FailureEpoch()==failures);
sql.AsyncQuery("SELECT * FROM __deliberately_missing_cube_fifo_probe");
assert(PortSQLFence::Queue(&sql,PortSQLFence::Cube,88));
assert(PortSQLFence::Queue(&sql,PortSQLFence::Economy,88));
{auto message=wait(PortSQLFence::Cube);assert(!message->uiSQLErrno);}
{auto message=wait(PortSQLFence::Economy);assert(!message->uiSQLErrno);}
assert(sql.FailureEpoch()>failures); // successful barriers cannot hide failed writes
sql.Quit();PortSQLFence::PlayerRouter().Clear();
puts("PASS actual libsql threaded FIFO: exact isolated socket, interleaved Cube/Economy results, retained session order and failure epoch");
}

Some files were not shown because too many files have changed in this diff Show More