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();