feat(server): save economy hardening and CH5 continuation work

This commit is contained in:
shen
2026-10-22 06:22:23 -07:00
parent c979b53762
commit 5b7442ea37
142 changed files with 5850 additions and 1682 deletions
+255
View File
@@ -0,0 +1,255 @@
#include "src/server/common/economy_store.h"
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <sys/wait.h>
#include <unistd.h>
#ifdef PORT_ECONOMY_MYSQL
#include "src/server/common/economy_mysql.h"
#else
#include <sqlite3.h>
#endif
using namespace PortEconomy;
static std::string address;
struct TestDB {
#ifdef PORT_ECONOMY_MYSQL
MYSQL handle;Mysql* db;
TestDB(){mysql_init(&handle);assert(mysql_real_connect(&handle,"localhost","root","","economy_test",0,address.c_str(),0));db=new Mysql(&handle);}
~TestDB(){delete db;mysql_close(&handle);}
bool Query(const std::string& sql,Rows& rows){bool ok=db->Query(sql,rows);affected=db->affected;inserted=db->inserted;if(ok&&after)after(sql);return ok;}
bool Begin(){return db->Begin();}bool Commit(){bool ok=db->Commit();if(ok&&after)after("COMMIT");return ok;}void Rollback(){db->Rollback();}
#else
sqlite3* db=nullptr;
TestDB(){assert(sqlite3_open(address.c_str(),&db)==SQLITE_OK);sqlite3_busy_timeout(db,5000);}
~TestDB(){sqlite3_close(db);}
static void replace(std::string& s,const std::string& from,const std::string& to){size_t pos;while((pos=s.find(from))!=std::string::npos)s.replace(pos,from.size(),to);}
bool Query(std::string sql,Rows& rows){
rows.clear();affected=0;inserted=0;
if(sql.find("information_schema.tables")!=std::string::npos){rows={{"13"}};return true;}
if(sql=="SET TRANSACTION ISOLATION LEVEL REPEATABLE READ")return true;
if(sql.find("SHOW COLUMNS")!=std::string::npos){rows={{"fixture-schema"}};return true;}
replace(sql," FOR UPDATE","");replace(sql,"UNIX_TIMESTAMP()","strftime('%s','now')");
replace(sql,"ON DUPLICATE KEY UPDATE account=VALUES(account)","ON CONFLICT(account) DO NOTHING");
replace(sql,"ON DUPLICATE KEY UPDATE pid=VALUES(pid)","ON CONFLICT(pid) DO NOTHING");
replace(sql,"ON DUPLICATE KEY UPDATE lValue=VALUES(lValue)","ON CONFLICT(dwPID,szName,szState) DO UPDATE SET lValue=excluded.lValue");
replace(sql,"ON DUPLICATE KEY UPDATE generation=VALUES(generation),deadline=VALUES(deadline),offers=VALUES(offers)","ON CONFLICT(pid) DO UPDATE SET generation=excluded.generation,deadline=excluded.deadline,offers=excluded.offers");
sqlite3_stmt* statement=nullptr;
if(sqlite3_prepare_v2(db,sql.c_str(),-1,&statement,nullptr)!=SQLITE_OK){std::cerr<<sqlite3_errmsg(db)<<" SQL "<<sql.substr(0,160)<<"\n";return false;}
int rc;while((rc=sqlite3_step(statement))==SQLITE_ROW){std::vector<std::string> row;for(int i=0;i<sqlite3_column_count(statement);++i){const char* p=static_cast<const char*>(sqlite3_column_blob(statement,i));row.emplace_back(p?std::string(p,sqlite3_column_bytes(statement,i)):std::string());}rows.push_back(row);}
sqlite3_finalize(statement);if(rc!=SQLITE_DONE)return false;
affected=static_cast<uint64_t>(sqlite3_changes(db));inserted=static_cast<uint64_t>(sqlite3_last_insert_rowid(db));if(after)after(sql);return true;
}
bool Begin(){Rows rows;return Query("BEGIN IMMEDIATE",rows);}bool Commit(){Rows rows;return Query("COMMIT",rows);}void Rollback(){Rows rows;Query("ROLLBACK",rows);}
#endif
uint64_t affected=0,inserted=0;std::function<void(const std::string&)> after;
};
static unsigned itemSize(uint32_t vnum){return vnum==999?0u:vnum==333?3u:1u;}
static void sql(TestDB& db,const std::string& q){Rows rows;if(!db.Query(q,rows)){std::cerr<<"FAILED "<<q<<"\n";std::abort();}}
static std::string value(TestDB& db,const std::string& q){Rows rows;assert(db.Query(q,rows)&&rows.size()==1&&rows[0].size()==1);return rows[0][0];}
static uint64_t integer(TestDB& db,const std::string& q){uint64_t n=0;assert(Number(value(db,q),n));return n;}
static Request req(unsigned operation,uint32_t pid=2,uint32_t account=2,int64_t gold=1000){
static uint64_t token=1;Request r;r.operation=static_cast<uint8_t>(operation);r.player=pid;r.account=account;r.expectedGold=gold;
char text[33];snprintf(text,sizeof(text),"%032llx",static_cast<unsigned long long>(token++));memcpy(r.token,text,33);return r;
}
static void reset(TestDB& db){
for(const char* t:{"port_economy_pending","port_economy_requests","port_economy_listings","port_economy_orders","port_economy_credit","port_economy_gaya","port_economy_account_lock","port_economy_item_reservations","port_economy_custody","item","quest","player"})sql(db,std::string("DELETE FROM ")+t);
sql(db,"INSERT INTO player(id,account_id,gold) VALUES(1,1,100),(2,2,1000),(3,3,1000)");
sql(db,"INSERT INTO item(id,owner_id,window,pos,count,vnum,socket0,attrtype0,attrvalue0,port_extra) VALUES(10,1,'INVENTORY',0,5,100,123456,99,17,X'010203')");
}
static uint64_t settle(TestDB& db,Request r,const char* expected="ok"){
Store<TestDB> store(db,itemSize);if(!store.Enqueue(r)){std::cerr<<"enqueue operation "<<unsigned(r.operation)<<" token "<<r.token<<"\n";std::abort();}assert(store.Enqueue(r));assert(store.Settle(r.player,r.account)==Store<TestDB>::Settled);
if(store.Outcome()!=expected){std::cerr<<"EXPECTED "<<expected<<" got "<<store.Outcome()<<"\n";std::abort();}
assert(store.Settle(r.player,r.account)==Store<TestDB>::None);
assert(store.Enqueue(r));assert(store.Settle(r.player,r.account)==Store<TestDB>::None);return store.Reference();
}
static uint64_t listing(TestDB& db){auto r=req(List,1,1,100);r.item=10;r.itemVnum=100;r.itemCount=5;r.price=750;return settle(db,r);}
static uint64_t buy(TestDB& db,uint64_t listing){auto r=req(Buy);r.reference=listing;r.price=750;return settle(db,r);}
static Request gaya(TestDB& db){
sql(db,"INSERT INTO quest(dwPID,szName,szState,lValue) VALUES(2,'gem','points',500),(2,'gem','open_slot',18)");
Request r=req(GayaBuy);r.expectedGem=500;r.expectedOpen=18;r.deadline=100;r.slot=0;r.rewardCount=10;
for(auto& o:r.offers)o={200,2000,50,0};
for(unsigned i=0;i<10;++i)r.rewards[i]={1000+i,200,200};
return r;
}
static void basic(TestDB& db){
reset(db);Store<TestDB> store(db,itemSize);assert(store.Ready());
Request invalid=req(List);invalid.item=1;assert(!store.Enqueue(invalid));
#ifdef PORT_ECONOMY_MYSQL
sql(db,"ALTER TABLE item ENGINE=MyISAM");assert(!store.Ready());assert(!store.Enqueue(req(Withdraw,1,1,100)));assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==0);sql(db,"ALTER TABLE item ENGINE=InnoDB");assert(store.Ready());
sql(db,"ALTER TABLE port_economy_custody ADD COLUMN unexpected INT DEFAULT 0");assert(!store.Ready());sql(db,"ALTER TABLE port_economy_custody DROP COLUMN unexpected");assert(store.Ready());
sql(db,"UPDATE port_economy_version SET version=2 WHERE id=1");assert(!store.Ready());sql(db,"UPDATE port_economy_version SET version=1 WHERE id=1");assert(store.Ready());
puts("PASS readiness refuses MyISAM, partial custody migration and incompatible schema version");
#endif
Request immutable=req(List,1,1,100);immutable.item=10;immutable.itemVnum=100;immutable.itemCount=5;immutable.price=750;
assert(store.Enqueue(immutable));auto conflict=immutable;conflict.price=751;assert(!store.Enqueue(conflict));conflict=req(Withdraw,1,1,100);assert(!store.Enqueue(conflict));assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==1);assert(store.Settle(1,1)==Store<TestDB>::Settled);reset(db);
uint64_t l=listing(db);assert(l);assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10")==0);assert(integer(db,"SELECT COUNT(*) FROM port_economy_custody WHERE id=10")==1);
uint64_t o=buy(db,l);assert(o);assert(integer(db,"SELECT gold FROM player WHERE id=2")==250);
auto collision=req(Buy,3,3);collision.reference=l;collision.price=750;settle(db,collision,"listing_changed");assert(integer(db,"SELECT gold FROM player WHERE id=3")==1000);
auto refund=req(Refund,2,2,250);refund.reference=o;settle(db,refund);assert(integer(db,"SELECT gold FROM player WHERE id=2")==1000);
refund=req(Refund);refund.reference=o;settle(db,refund);assert(integer(db,"SELECT gold FROM player WHERE id=2")==1000);
o=buy(db,l);auto claim=req(Claim,2,2,250);claim.reference=o;settle(db,claim);
assert(value(db,"SELECT window FROM item WHERE id=10")=="MALL");assert(integer(db,"SELECT owner_id FROM item WHERE id=10")==2);assert(integer(db,"SELECT socket0 FROM item WHERE id=10")==123456);assert(integer(db,"SELECT attrvalue0 FROM item WHERE id=10")==17);assert(value(db,"SELECT hex(port_extra) FROM item WHERE id=10")=="010203");
assert(integer(db,"SELECT amount FROM port_economy_credit WHERE pid=1")==750);
claim=req(Claim,2,2,250);claim.reference=o;settle(db,claim);assert(integer(db,"SELECT amount FROM port_economy_credit WHERE pid=1")==750);
refund=req(Refund,2,2,250);refund.reference=o;settle(db,refund,"order_terminal");
auto withdraw=req(Withdraw,1,1,100);settle(db,withdraw);assert(integer(db,"SELECT gold FROM player WHERE id=1")==850);settle(db,req(Withdraw,1,1,850),"no_credit");
reset(db);l=listing(db);auto cancel=req(Cancel,1,1,100);cancel.reference=l;settle(db,cancel);assert(value(db,"SELECT window FROM item WHERE id=10")=="MALL");
// Wallet snapshot mismatch never mutates a listing or debits persisted funds.
reset(db);l=listing(db);auto stale=req(Buy,2,2,5000);stale.reference=l;stale.price=750;settle(db,stale,"wallet_changed");assert(integer(db,"SELECT gold FROM player WHERE id=2")==1000);
// Full mall after payment leaves a READY order refundable and its item in custody.
reset(db);l=listing(db);o=buy(db,l);
for(unsigned i=0;i<135;++i)sql(db,"INSERT INTO item(id,owner_id,window,pos,count,vnum) VALUES("+std::to_string(2000+i)+",2,'MALL',"+std::to_string(i)+",1,200)");
claim=req(Claim,2,2,250);claim.reference=o;settle(db,claim,"mall_full");assert(value(db,"SELECT state FROM port_economy_orders WHERE id="+std::to_string(o))=="READY");refund=req(Refund,2,2,250);refund.reference=o;settle(db,refund);
// Gaya wallet, offer and ten stable item IDs commit together.
reset(db);auto r=gaya(db);settle(db,r);assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='points'")==450);assert(integer(db,"SELECT SUM(count) FROM item WHERE owner_id=2 AND window='MALL'")==2000);assert(integer(db,"SELECT generation FROM port_economy_gaya WHERE pid=2")==1);
auto duplicate=r;memcpy(duplicate.token,req(GayaBuy).token,33);duplicate.expectedGem=450;assert(!store.Enqueue(duplicate));assert(integer(db,"SELECT SUM(count) FROM item WHERE owner_id=2 AND window='MALL'")==2000);
// Paid refresh consumes exactly one item in the same commit as the new catalogue.
sql(db,"INSERT INTO item(id,owner_id,window,pos,count,vnum) VALUES(50,2,'INVENTORY',5,2,39063),(51,2,'INVENTORY',6,1,39064)");
Request refresh=req(GayaRefresh);refresh.expectedGem=450;refresh.expectedOpen=18;refresh.generation=1;refresh.deadline=100;refresh.nextDeadline=200;refresh.item=50;refresh.itemCount=2;
memcpy(refresh.offers,r.offers,sizeof(r.offers));refresh.offers[0].bought=1;memcpy(refresh.nextOffers,r.offers,sizeof(r.offers));settle(db,refresh);assert(integer(db,"SELECT count FROM item WHERE id=50")==1);assert(integer(db,"SELECT deadline FROM port_economy_gaya WHERE pid=2")==200);
sql(db,"UPDATE quest SET lValue=17 WHERE dwPID=2 AND szState='open_slot'");Request expand=req(GayaExpand);expand.expectedGem=450;expand.expectedOpen=17;expand.item=51;expand.itemCount=1;settle(db,expand);assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=51")==0);assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='open_slot'")==18);
// A multi-stack delivery that runs out of space rolls back earlier stacks too.
reset(db);r=gaya(db);for(unsigned i=0;i<130;++i)sql(db,"INSERT INTO item(id,owner_id,window,pos,count,vnum) VALUES("+std::to_string(2000+i)+",2,'MALL',"+std::to_string(i)+",1,200)");settle(db,r,"mall_full");assert(integer(db,"SELECT COUNT(*) FROM item WHERE id>=1000 AND id<1010")==0);assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='points'")==500);assert(integer(db,"SELECT COUNT(*) FROM port_economy_gaya")==0);
// SQL failure after five tentative inserts rolls back all of them; the same
// durable request remains pending and succeeds once the fault is removed.
reset(db);r=gaya(db);assert(store.Enqueue(r));sql(db,"INSERT INTO item(id,owner_id,window,pos,count,vnum) VALUES(1005,3,'INVENTORY',1,1,200)");
assert(store.Settle(2,2)==Store<TestDB>::Retry);assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='points'")==500);assert(integer(db,"SELECT COUNT(*) FROM item WHERE id>=1000 AND id<1010")==1);assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==1);
sql(db,"DELETE FROM item WHERE id=1005");assert(store.Settle(2,2)==Store<TestDB>::Settled);assert(integer(db,"SELECT SUM(count) FROM item WHERE owner_id=2 AND window='MALL'")==2000);
// A reservation participates in the restart high-water mark even before a
// reward row exists, and survives an aborted economic request.
reset(db);r=gaya(db);assert(store.Enqueue(r));assert(integer(db,"SELECT MAX(id) FROM (SELECT id FROM item UNION ALL SELECT id FROM port_economy_custody UNION ALL SELECT id FROM port_economy_item_reservations) AS allocated_ids")==1009);
assert(store.Abort(2,2));assert(integer(db,"SELECT MAX(id) FROM port_economy_item_reservations")==1009);
// Abort after a failed save preserves every economic store.
reset(db);l=listing(db);r=req(Buy);r.reference=l;r.price=750;assert(store.Enqueue(r));assert(store.Abort(2,2));assert(integer(db,"SELECT gold FROM player WHERE id=2")==1000);assert(value(db,"SELECT result FROM port_economy_requests WHERE token='"+std::string(r.token)+"'")=="save_failed");
#ifdef PORT_ECONOMY_MYSQL
// Kill the pinned connection after the first reward statement. It must never
// auto-reconnect and continue the remaining statements in autocommit mode.
reset(db);r=gaya(db);assert(store.Enqueue(r));bool killed=false;TestDB killer;
db.after=[&](const std::string& sql){if(!killed&&sql.find("INSERT INTO item(")==0){killed=true;assert(mysql_kill(&killer.handle,mysql_thread_id(&db.handle))==0);}};
assert(store.Settle(2,2)==Store<TestDB>::Retry);db.after={};assert(killed);
delete db.db;db.db=new Mysql(&db.handle); // new coordinator attempt, same direct handle
assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='points'")==500);
assert(integer(db,"SELECT COUNT(*) FROM item WHERE owner_id=2 AND window='MALL'")==0);
assert(store.Settle(2,2)==Store<TestDB>::Settled);assert(integer(db,"SELECT SUM(count) FROM item WHERE owner_id=2 AND window='MALL'")==2000);
puts("PASS pinned connection loss: rollback; reconnect before next transaction; one debit/delivery");
#endif
// Explicit retirement keeps paid offers/slots, refuses residual assets and
// positive balance, and prevents every later Gaya mutation including expand.
reset(db);r=gaya(db);settle(db,r);
auto retire=req(GayaRetire);retire.expectedGem=450;retire.expectedOpen=18;
settle(db,retire,"gaya_balance_remaining");
sql(db,"UPDATE quest SET lValue=0 WHERE dwPID=2 AND szState='points'");
sql(db,"INSERT INTO port_economy_credit(pid,amount) VALUES(2,1)");
retire=req(GayaRetire);retire.expectedOpen=18;settle(db,retire,"assets_remaining");
sql(db,"DELETE FROM port_economy_credit WHERE pid=2");
auto snapshot=value(db,"SELECT hex(offers) FROM port_economy_gaya WHERE pid=2");
retire=req(GayaRetire);retire.expectedOpen=18;settle(db,retire);
assert(integer(db,"SELECT generation FROM port_economy_gaya WHERE pid=2")==RetiredGeneration);
assert(value(db,"SELECT hex(offers) FROM port_economy_gaya WHERE pid=2")==snapshot);
assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='open_slot'")==18);
retire=req(GayaRetire);retire.expectedOpen=18;settle(db,retire);
sql(db,"UPDATE quest SET lValue=17 WHERE dwPID=2 AND szState='open_slot'");
sql(db,"INSERT INTO item(id,owner_id,window,pos,count,vnum) VALUES(50,2,'INVENTORY',5,2,39064)");
auto blocked=req(GayaExpand);blocked.expectedOpen=17;blocked.item=50;blocked.itemCount=2;
settle(db,blocked,"gaya_retired");assert(integer(db,"SELECT count FROM item WHERE id=50")==2);
puts("PASS Gaya retirement: zero balance/assets, retained catalogue/paid slots, idempotent, no reactivation");
puts("PASS economy orders/refunds/claim/cancel/withdraw/Gaya/rollback/idempotency");
}
static Request prepareCrash(TestDB& db,unsigned mode) {
reset(db);
if(mode==0){auto r=req(List,1,1,100);r.item=10;r.itemVnum=100;r.itemCount=5;r.price=750;return r;}
if(mode==1){auto l=listing(db);auto r=req(Buy);r.reference=l;r.price=750;return r;}
if(mode==2||mode==3){auto l=listing(db);auto o=buy(db,l);auto r=req(mode==2?Refund:Claim,2,2,250);r.reference=o;return r;}
if(mode==4){auto r=req(Cancel,1,1,100);r.reference=listing(db);return r;}
if(mode==5){auto l=listing(db);auto o=buy(db,l);auto c=req(Claim,2,2,250);c.reference=o;settle(db,c);return req(Withdraw,1,1,100);}
if(mode==6)return gaya(db);
if(mode==7){
auto original=gaya(db);settle(db,original);
sql(db,"INSERT INTO item(id,owner_id,window,pos,count,vnum) VALUES(50,2,'INVENTORY',5,2,39063)");
auto r=req(GayaRefresh);r.expectedGem=450;r.expectedOpen=18;r.generation=1;r.deadline=100;r.nextDeadline=200;r.item=50;r.itemCount=2;
memcpy(r.offers,original.offers,sizeof(r.offers));r.offers[0].bought=1;memcpy(r.nextOffers,original.offers,sizeof(r.offers));return r;
}
if(mode==9){auto original=gaya(db);settle(db,original);sql(db,"UPDATE quest SET lValue=0 WHERE dwPID=2 AND szState='points'");auto r=req(GayaRetire);r.expectedOpen=18;return r;}
assert(mode==8);sql(db,"INSERT INTO quest(dwPID,szName,szState,lValue) VALUES(2,'gem','points',500),(2,'gem','open_slot',17)");sql(db,"INSERT INTO item(id,owner_id,window,pos,count,vnum) VALUES(50,2,'INVENTORY',5,2,39064)");auto r=req(GayaExpand);r.expectedGem=500;r.expectedOpen=17;r.item=50;r.itemCount=2;return r;
}
static void checkCrash(TestDB& db,unsigned mode) {
assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==0);
if(mode==0){assert(integer(db,"SELECT COUNT(*) FROM port_economy_custody WHERE id=10")==1);assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10")==0);assert(integer(db,"SELECT COUNT(*) FROM port_economy_listings WHERE state='OPEN'")==1);}
if(mode==1){assert(integer(db,"SELECT gold FROM player WHERE id=2")==250);assert(integer(db,"SELECT COUNT(*) FROM port_economy_orders WHERE state='READY'")==1);assert(integer(db,"SELECT SUM(price) FROM port_economy_orders WHERE state='READY'")==750);}
if(mode==2){assert(integer(db,"SELECT gold FROM player WHERE id=2")==1000);assert(integer(db,"SELECT COUNT(*) FROM port_economy_orders WHERE state='REFUNDED'")==1);assert(integer(db,"SELECT COUNT(*) FROM port_economy_custody WHERE id=10")==1);}
if(mode==3){assert(integer(db,"SELECT amount FROM port_economy_credit WHERE pid=1")==750);assert(integer(db,"SELECT gold FROM player WHERE id=2")==250);assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10 AND owner_id=2 AND window='MALL'")==1);}
if(mode==4)assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10 AND owner_id=1 AND window='MALL'")==1);
if(mode==5){assert(integer(db,"SELECT gold FROM player WHERE id=1")==850);assert(integer(db,"SELECT amount FROM port_economy_credit WHERE pid=1")==0);}
if(mode==6||mode==7){assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='points'")==450);assert(integer(db,"SELECT SUM(count) FROM item WHERE owner_id=2 AND window='MALL'")==2000);assert(integer(db,"SELECT generation FROM port_economy_gaya WHERE pid=2")== (mode==6?1:2));}
if(mode==7){assert(integer(db,"SELECT deadline FROM port_economy_gaya WHERE pid=2")==200);assert(integer(db,"SELECT count FROM item WHERE id=50")==1);}
if(mode==9){assert(integer(db,"SELECT generation FROM port_economy_gaya WHERE pid=2")==RetiredGeneration);assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='points'")==0);assert(integer(db,"SELECT SUM(count) FROM item WHERE owner_id=2 AND window='MALL'")==2000);}
if(mode==8){assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='open_slot'")==18);assert(integer(db,"SELECT count FROM item WHERE id=50")==1);}
}
static void crashes(TestDB& db){
const char* names[]={"list","buy","refund","claim","cancel","withdraw","Gaya buy","Gaya refresh","Gaya expand","Gaya retire"};
unsigned total=0;Store<TestDB> store(db,itemSize);
for(unsigned mode=0;mode<10;++mode) {
auto r=prepareCrash(db,mode);assert(store.Enqueue(r));unsigned boundaries=0;db.after=[&](const std::string&){++boundaries;};assert(store.Settle(r.player,r.account)==Store<TestDB>::Settled);db.after={};checkCrash(db,mode);
for(unsigned boundary=1;boundary<=boundaries;++boundary){
r=prepareCrash(db,mode);assert(store.Enqueue(r));
pid_t child=fork();assert(child>=0);
if(!child){TestDB worker;Store<TestDB> s(worker,itemSize);unsigned count=0;worker.after=[&](const std::string&){if(++count==boundary)_exit(70);};s.Settle(r.player,r.account);_exit(71);}
int status=0;const auto waited=waitpid(child,&status,0);
if(waited!=child||!WIFEXITED(status)||WEXITSTATUS(status)!=70){std::cerr<<"crash probe mode="<<mode<<" boundary="<<boundary<<" waited="<<waited<<" status="<<status<<"\n";std::abort();}
auto result=store.Settle(r.player,r.account);assert(result==Store<TestDB>::Settled||result==Store<TestDB>::None);checkCrash(db,mode);
}
total+=boundaries;printf("PASS %s process exit/replay at %u SQL boundaries\n",names[mode],boundaries);
}
printf("PASS economy whole-process exit/replay: %u SQL boundaries across ten operations (including COMMIT)\n",total);
}
static void races(TestDB& db){
reset(db);uint64_t l=listing(db);Request a=req(Buy,2,2),b=req(Buy,3,3);a.reference=b.reference=l;a.price=b.price=750;
pid_t children[2];unsigned i=0;for(const auto& r:{a,b}){children[i]=fork();assert(children[i]>=0);if(!children[i++]){TestDB worker;Store<TestDB> s(worker,itemSize);bool queued=false;for(unsigned retry=0;retry<20&&!queued;++retry){queued=s.Enqueue(r);if(!queued)usleep(10000);}if(!queued)_exit(80);for(unsigned retry=0;retry<20;++retry){auto result=s.Settle(r.player,r.account);if(result!=Store<TestDB>::Retry)_exit(0);usleep(10000);}_exit(81);}}
for(auto child:children){int status;assert(waitpid(child,&status,0)==child);if(!WIFEXITED(status)||WEXITSTATUS(status)!=0)std::cerr<<"race child status="<<status<<"\n";assert(WIFEXITED(status)&&WEXITSTATUS(status)==0);}
assert(integer(db,"SELECT COUNT(*) FROM port_economy_orders WHERE state='READY'")==1);assert(integer(db,"SELECT SUM(gold) FROM player WHERE id IN(2,3)")==1250);
puts("PASS concurrent buyers: one reservation, one debit");
for(bool refund:{false,true}) {
reset(db);l=listing(db);uint64_t order=buy(db,l);Request delivery=req(refund?Refund:Claim,2,2,250);delivery.reference=order;Store<TestDB> store(db,itemSize);assert(store.Enqueue(delivery));
for(unsigned i=0;i<2;++i){children[i]=fork();assert(children[i]>=0);if(!children[i]){TestDB worker;Store<TestDB> s(worker,itemSize);for(unsigned retry=0;retry<20;++retry){if(s.Settle(2,2)!=Store<TestDB>::Retry)_exit(0);usleep(10000);}_exit(82);}}
for(auto child:children){int status;assert(waitpid(child,&status,0)==child&&WIFEXITED(status)&&WEXITSTATUS(status)==0);}
assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==0);
if(refund){assert(integer(db,"SELECT gold FROM player WHERE id=2")==1000);assert(integer(db,"SELECT COUNT(*) FROM port_economy_custody WHERE id=10")==1);}
else {assert(integer(db,"SELECT amount FROM port_economy_credit WHERE pid=1")==750);assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10 AND owner_id=2 AND window='MALL'")==1);}
}
puts("PASS concurrent settlement of the same claim/refund: one delivery or one refund");
}
int main(int argc,char** argv){assert(argc==2||argc==3);address=argv[1];TestDB db;
#ifndef PORT_ECONOMY_MYSQL
std::string item="id INTEGER PRIMARY KEY,owner_id INTEGER NOT NULL,window TEXT NOT NULL,pos INTEGER NOT NULL,count INTEGER NOT NULL,vnum INTEGER NOT NULL";
for(unsigned i=0;i<3;++i)item+=",socket"+std::to_string(i)+" INTEGER NOT NULL DEFAULT 0";
for(unsigned i=0;i<7;++i)item+=",attrtype"+std::to_string(i)+" INTEGER NOT NULL DEFAULT 0,attrvalue"+std::to_string(i)+" INTEGER NOT NULL DEFAULT 0";
item+=",port_extra BLOB NOT NULL DEFAULT X''";
sql(db,"CREATE TABLE item("+item+")");sql(db,"CREATE TABLE port_economy_custody("+item+")");
for(const auto& definition:{"player(id INTEGER PRIMARY KEY,account_id INTEGER,gold INTEGER)","quest(dwPID INTEGER,szName TEXT,szState TEXT,lValue INTEGER,PRIMARY KEY(dwPID,szName,szState))","port_economy_version(id INTEGER PRIMARY KEY,version INTEGER)","port_economy_requests(token TEXT PRIMARY KEY,account INTEGER,pid INTEGER,body BLOB,state TEXT,result TEXT,reference INTEGER,created_at TEXT DEFAULT CURRENT_TIMESTAMP)","port_economy_pending(pid INTEGER PRIMARY KEY,token TEXT UNIQUE)","port_economy_item_reservations(id INTEGER PRIMARY KEY,request TEXT)","port_economy_account_lock(account INTEGER PRIMARY KEY)","port_economy_listings(id INTEGER PRIMARY KEY AUTOINCREMENT,owner INTEGER,account INTEGER,item INTEGER,price INTEGER,state TEXT,active_order INTEGER DEFAULT 0)","port_economy_orders(id INTEGER PRIMARY KEY AUTOINCREMENT,request TEXT UNIQUE,listing INTEGER,buyer INTEGER,account INTEGER,price INTEGER,state TEXT)","port_economy_credit(pid INTEGER PRIMARY KEY,amount INTEGER)","port_economy_gaya(pid INTEGER PRIMARY KEY,generation INTEGER,deadline INTEGER,offers BLOB)"})sql(db,std::string("CREATE TABLE ")+definition);
sql(db,"INSERT INTO port_economy_version VALUES(1,1)");
#endif
if(argc==3) {
const std::string mode=argv[2];Store<TestDB> store(db,itemSize);
if(mode=="recover") {
const auto result=store.Settle(2,2);assert(result==Store<TestDB>::Settled||result==Store<TestDB>::None);
assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='points'")==450);
assert(integer(db,"SELECT SUM(count) FROM item WHERE owner_id=2 AND window='MALL'")==2000);
assert(integer(db,"SELECT generation FROM port_economy_gaya WHERE pid=2")==1);
assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==0);puts("PASS real MySQL crash/restart: one debit, ten item IDs, one catalogue generation");return 0;
}
assert(mode=="before"||mode=="after");reset(db);auto r=gaya(db);assert(store.Enqueue(r));
db.after=[&](const std::string& sql){
if((mode=="before"&&sql.find("UPDATE port_economy_requests SET state='DONE'")==0)||(mode=="after"&&sql=="COMMIT")) {
puts("READY_FOR_ISOLATED_MYSQL_CRASH");fflush(stdout);for(;;)pause();
}
};
store.Settle(2,2);return 90;
}
basic(db);
#ifndef PORT_ECONOMY_NO_FORK
crashes(db);races(db);
#endif
return 0;
}
@@ -0,0 +1,53 @@
#define main economy_base_main
#include "economy_probe.cpp"
#undef main
#include "src/server/common/economy_view.h"
#include <fstream>
struct ViewDB:TestDB {
std::string failing;bool failed=false;
bool Query(const std::string& sql,Rows& rows) {
if(!failing.empty()&&sql.find(failing)!=std::string::npos){failed=true;rows.clear();return false;}
#ifndef PORT_ECONOMY_MYSQL
if(sql=="SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"){rows.clear();return true;}
#endif
return TestDB::Query(sql,rows);
}
bool Begin(){return TestDB::Begin();}
bool Commit(){if(failing=="COMMIT"){failed=true;return false;}return TestDB::Commit();}
};
int main(int argc,char** argv) {
assert(argc==2||argc==3);economy_base_main(2,argv);address=argv[1];ViewDB db;reset(db);
sql(db,"UPDATE item SET port_extra=X'"+std::string(138,'0')+"' WHERE id=10");
uint64_t id=listing(db);Request r=req(UiStatus);r.generation=123;r.reference=0;r.slot=0;memset(r.token,'0',32);r.token[32]=0;
Store<ViewDB> store(db,itemSize);assert(Valid(r)&&!store.Enqueue(r));
std::vector<std::string> frames;
assert(View(db,r,itemSize,frames));assert(frames.front()=="MTECON1 begin 123 0 0 1 0 0");assert(frames.back()=="MTECON1 end 123");
assert(frames[1].find("MTECON1 row 123 0 "+std::to_string(id)+" 750 1 0 100 5 1 123456 0 0")==0);
assert(frames[2].find("MTECON1 meta 123 0 631100")==0);
for(const auto& frame:frames)assert(frame.size()<240);
if(argc==3){std::ofstream output(argv[2]);for(const auto& frame:frames)output<<frame<<"\n";}
assert(integer(db,"SELECT gold FROM player WHERE id=2")==1000);
r.slot=1;assert(View(db,r,itemSize,frames)&&frames.front()=="MTECON1 begin 123 1 0 0 0 0");
r.player=1;r.account=1;r.slot=1;assert(View(db,r,itemSize,frames)&&frames.front()=="MTECON1 begin 123 1 0 1 0 0");
r.player=2;r.account=2;r.slot=2;auto order=buy(db,id);assert(View(db,r,itemSize,frames));assert(frames[1].find("MTECON1 row 123 0 "+std::to_string(order)+" 750 1 2 ")==0);
// A receipt never reveals a different account's result.
r.slot=0;std::string token=value(db,"SELECT request FROM port_economy_orders WHERE id="+std::to_string(order));memcpy(r.token,token.c_str(),33);
assert(View(db,r,itemSize,frames));bool result=false;for(auto& f:frames)if(f.find("MTECON1 result ")==0)result=true;assert(result);
r.player=3;r.account=3;assert(View(db,r,itemSize,frames));for(auto& f:frames)assert(f.find("MTECON1 result ")!=0);
// More than one page, bounded replies, exact 64-bit IDs/prices and a later
// page remain untruncated. SQL errors never emit half of a snapshot.
reset(db);r=req(UiStatus);r.generation=456;r.slot=0;
for(unsigned i=0;i<21;++i){
const auto item=std::to_string(100+i),listing=std::to_string(uint64_t(UINT32_MAX)+1+i);
sql(db,"INSERT INTO port_economy_custody(id,owner_id,window,pos,count,vnum) VALUES("+item+",1,'INVENTORY',0,1,100)");
sql(db,"INSERT INTO port_economy_listings(id,owner,account,item,price,state) VALUES("+listing+",1,1,"+item+",2000000000000000,'OPEN')");
}
assert(View(db,r,itemSize,frames));assert(frames.front()=="MTECON1 begin 456 0 0 20 1 0");
assert(frames[1].find("4294967316 2000000000000000")!=std::string::npos);
r.reference=1;assert(View(db,r,itemSize,frames)&&frames.front()=="MTECON1 begin 456 0 1 1 0 0");
db.failing="SELECT state,result";assert(!View(db,r,itemSize,frames)&&frames.empty()&&db.failed);db.failing="";
sql(db,"UPDATE port_economy_custody SET port_extra=X'01' WHERE id=100");assert(!View(db,r,itemSize,frames)&&frames.empty());
sql(db,"UPDATE port_economy_custody SET port_extra=X'' WHERE id=100");db.failing="COMMIT";assert(!View(db,r,itemSize,frames)&&frames.empty());db.failing="";
assert(View(db,r,itemSize,frames));assert(integer(db,"SELECT gold FROM player WHERE id=2")==1000);
puts("PASS UI snapshots: read-only, paging, metadata, 64-bit amounts/IDs, receipts, atomic error refusal");
}
+6 -1
View File
@@ -21,7 +21,11 @@ constants=source('game/src/constants.cpp')
table=constants[constants.index('aApplyInfo[MAX_APPLY_NUM]'):]
table=table[table.index('{')+1:table.index('};')]
rows=re.findall(r'\{\s*(POINT_[A-Z_]+)',table)
assert len(rows)==141 and rows[139:]==['POINT_ATTBONUS_STONE','POINT_ATTBONUS_BOSS'] and set(rows[92:123]+rows[129:139])=={'POINT_NONE'},len(rows)
assert len(rows)==141 and rows[139:]==['POINT_ATTBONUS_STONE','POINT_ATTBONUS_BOSS'] and set(rows[92:98]+rows[100:123]+rows[129:139])=={'POINT_NONE'},len(rows)
assert rows[98]=='POINT_RESIST_MAGIC_REDUCTION' and names[98]=='APPLY_RESIST_MAGIC_REDUCTION'
assert 'APPLY_RESIST_MAGIC_REDUCTION = 98,' in enum
assert rows[99]=='POINT_RESIST_HUMAN' and names[99]=='APPLY_RESIST_HUMAN'
assert 'APPLY_RESIST_HUMAN = 99,' in enum
ELEM=('ELEC','FIRE','ICE','WIND','EARTH','DARK')
# P7 talisman: APPLY_ENCHANT_* 123-128 (AVA2 names, ELECT for the db) -> POINT_ENCHANT_* 242-247
assert rows[123:129]==['POINT_ENCHANT_'+e for e in ELEM],rows[123:129]
@@ -32,6 +36,7 @@ char=source('game/src/char.cpp')
apply=char[char.index('void CHARACTER::ApplyPoint('):char.index('void CHARACTER::MotionPacketEncode(')]
assert all('case APPLY_ENCHANT_%s:'%e in apply for e in ELEM)
assert 'case APPLY_ATTBONUS_STONE:' in apply and 'case APPLY_ATTBONUS_BOSS:' in apply
assert 'case APPLY_RESIST_MAGIC_REDUCTION:' in apply
points=source('game/src/char.h')
assert all('POINT_ENCHANT_%s = %d,'%(e,242+i) in points for i,e in enumerate(ELEM)),'enchant points'
assert 'POINT_ATTBONUS_STONE = 240,' in points and 'POINT_ATTBONUS_BOSS = 241,' in points
@@ -0,0 +1,41 @@
"""Compile AVA2 text utilities and the legacy shop-label input guard."""
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[2]
class Arguments(unittest.TestCase):
def test_tab_compression_preserves_spaces_and_empty_edges(self):
source=(ROOT/'src/server/game/src/utils.cpp').read_text(encoding='latin1')
body=source[source.index('// AVA2 search files'):source.index('static int global_time_gap')]
code=r'''
#include <cassert>
#include <ctime>
#include <cstdint>
using WORD=uint16_t;using BYTE=uint8_t;
#define ENABLE_SHOP_SEARCH_SYSTEM
#define ENABLE_OFFLINESHOP_SYSTEM
#include "src/server/game/src/utils.h"
'''+body+r'''
int main(){
assert(getInjectText(nullptr));
assert(!getInjectText("SELECT dragon") && !getInjectText("\xe9\xbe\x99"));
assert(getInjectText("a'b") && getInjectText("a\\b") && getInjectText("a; DROP"));
assert(getInjectText("a\n") && getInjectText("a\x7f"));
std::string longLabel(256,'a');assert(getInjectText(longLabel.c_str()));
std::vector<std::string> args;
split_argument_special("1\t\tpet\t20",args,"\t");assert((args==std::vector<std::string>{"1","pet","20"}));
split_argument_special("\tlong pet name\t",args,"\t");assert((args==std::vector<std::string>{"","long pet name",""}));
split_argument_special(nullptr,args,"\t");assert(args.size()==1 && args[0].empty());
split_argument_special("\t\t",args,"\t");assert(args.size()==2 && args[0].empty() && args[1].empty());
split_argument_special("a|b||c;",args,"|;");assert((args==std::vector<std::string>{"a","b","c",""}));
split_argument_special("a b",args,"");assert(args.size()==1 && args[0]=="a b");
}
'''
with tempfile.TemporaryDirectory() as tmp:
src=Path(tmp)/'probe.cpp';exe=Path(tmp)/'probe';src.write_text(code)
subprocess.run(['c++','-std=c++23','-fsanitize=undefined,address','-fno-sanitize-recover=all','-I'+str(ROOT),str(src),'-o',str(exe)],check=True)
subprocess.run([str(exe)],check=True)
if __name__=='__main__':unittest.main()
+10 -6
View File
@@ -14,6 +14,7 @@ harness=r'''
#include <map>
#include <cassert>
using BYTE=uint8_t;using DWORD=uint32_t;
DWORD clockNow=1000;DWORD get_dword_time(){return clockNow;}
#define IS_SET(v,b) ((v)&(b))
enum {ITEM_WEAPON=1,ITEM_ARMOR,ITEM_NEW_RINGS,ITEM_COSTUME,ITEM_SKILLBOOK,ITEM_METIN,ITEM_GIFTBOX,ITEM_BELT};
enum {ARMOR_BODY=0,ARMOR_HEAD,ARMOR_SHIELD,ARMOR_WRIST,ARMOR_NECK,ARMOR_EAR,ARMOR_FOOTS,ARMOR_PENDANT};
@@ -25,7 +26,7 @@ struct Item {unsigned type=ITEM_GIFTBOX,sub=0,vnum=50100;bool ground=true,distan
bool GetSectree(){return ground;}bool DistanceValid(CHARACTER*){return distance;}bool IsOwnership(CHARACTER*){return owned;}
};using LPITEM=Item*;
struct Desc{bool closed=false;void SetPhase(int){closed=true;}};
struct CHARACTER {unsigned mode=1;bool dead=false,stun=false,warp=false,observer=false;Desc desc;std::vector<unsigned> picked;
struct CHARACTER {DWORD m_portPickupLastCommand=0;unsigned mode=1;bool dead=false,stun=false,warp=false,observer=false;Desc desc;std::vector<unsigned> picked;
unsigned GetPickUPMode(){return mode;}bool IsDead(){return dead;}bool IsStun(){return stun;}bool IsWarping(){return warp;}bool IsObserverMode(){return observer;}
Desc* GetDesc(){return &desc;}void PickupItem(unsigned v){picked.push_back(v);}bool CheckItemCanGet(LPITEM);
};using LPCHARACTER=CHARACTER*;
@@ -44,10 +45,13 @@ int main(){
char data[17];TPacketCGItemsPickUp p{235,3};memcpy(data,&p,5);unsigned vids[]={10,11,12};memcpy(data+5,vids,12);
assert(input.ItemsPickup(&ch,data,16)==-1&&ch.picked.empty());
assert(input.ItemsPickup(&ch,data,17)==12);assert((ch.picked==std::vector<unsigned>{10,11}));
ch.picked.clear();ch.mode=1|AUTOMATIC_PICK_UP_CHESTS;input.ItemsPickup(&ch,data,17);assert((ch.picked==std::vector<unsigned>{11}));
ch.picked.clear();ch.mode=1|AUTOMATIC_PICK_UP_STONES;input.ItemsPickup(&ch,data,17);assert((ch.picked==std::vector<unsigned>{10}));
ch.picked.clear();ch.mode=0;input.ItemsPickup(&ch,data,17);assert(ch.picked.empty());
ch.mode=1;ch.dead=true;input.ItemsPickup(&ch,data,17);assert(ch.picked.empty());ch.dead=false;
clockNow+=500;ch.picked.clear();ch.mode=1|AUTOMATIC_PICK_UP_CHESTS;input.ItemsPickup(&ch,data,17);assert((ch.picked==std::vector<unsigned>{11}));
clockNow+=500;ch.picked.clear();ch.mode=1|AUTOMATIC_PICK_UP_STONES;input.ItemsPickup(&ch,data,17);assert((ch.picked==std::vector<unsigned>{10}));
clockNow+=500;ch.picked.clear();ch.mode=0;input.ItemsPickup(&ch,data,17);assert((ch.picked==std::vector<unsigned>{10,11}));
ch.picked.clear();input.ItemsPickup(&ch,data,17);assert(ch.picked.empty());
clockNow+=499;input.ItemsPickup(&ch,data,17);assert(ch.picked.empty());
clockNow+=1;input.ItemsPickup(&ch,data,17);assert((ch.picked==std::vector<unsigned>{10,11}));ch.picked.clear();
ch.mode=1;ch.dead=true;input.ItemsPickup(&ch,data,17);assert(ch.picked.empty());ch.dead=false;clockNow+=500;
box.distance=false;stone.ground=false;input.ItemsPickup(&ch,data,17);assert(ch.picked.empty());
p.count=0xffffffff;memcpy(data,&p,5);assert(input.ItemsPickup(&ch,data,5)==0&&ch.desc.closed);
}
@@ -55,4 +59,4 @@ int main(){
with tempfile.TemporaryDirectory() as d:
p=Path(d)/'pickup.cpp';exe=Path(d)/'pickup';p.write_text(harness+enums+filters+handler+main)
subprocess.run(['c++','-std=c++11',str(p),'-o',str(exe)],check=True);subprocess.run([str(exe)],check=True)
print('AVA2 CG235: framing, count overflow, mode, ownership/distance, distinct chest/stone filters: PASS')
print('AVA2 CG235: framing, count overflow, UI-disabled autohunt, 500ms rate limit, ownership/distance, distinct chest/stone filters: PASS')
+3 -3
View File
@@ -16,11 +16,11 @@ using DWORD=uint32_t;using BYTE=uint8_t;using WORD=uint16_t;
const int SHOP_HOST_ITEM_MAX_NUM=40,HEADER_GC_SHOP=38,CHAT_TYPE_COMMAND=1;
enum {SHOP_SUBHEADER_GC_START,SHOP_SUBHEADER_GC_END,SHOP_SUBHEADER_GC_UPDATE_ITEM,SHOP_SUBHEADER_GC_UPDATE_PRICE,SHOP_SUBHEADER_GC_OK,SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY,SHOP_SUBHEADER_GC_SOLDOUT,SHOP_SUBHEADER_GC_INVENTORY_FULL,SHOP_SUBHEADER_GC_INVALID_POS,SHOP_SUBHEADER_GC_SOLD_OUT,SHOP_SUBHEADER_GC_START_EX,SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY_EX,SHOP_SUBHEADER_GC_START_ITEM_CURRENCY,SHOP_SUBHEADER_GC_NOT_ENOUGH_ITEM};
#pragma pack(push,1)
struct WireItem { DWORD vnum,price;BYTE count,display_pos;char rest[33]; };
struct WireItem { DWORD vnum;int64_t price;BYTE count,display_pos;char rest[33]; };
struct TPacketGCShopStart { DWORD owner_vid;WireItem items[40]; };
struct TPacketGCShop { BYTE header;WORD size;BYTE subheader; };
#pragma pack(pop)
static_assert(sizeof(WireItem)==43,"baseline item");
static_assert(sizeof(WireItem)==47,"baseline item");
struct TShopItemTable { DWORD vnum;BYTE count; };
struct Desc { std::string frame;void BufferedPacket(const void* p,size_t n){frame.assign((const char*)p,n);}void Packet(const void* p,size_t n){frame.append((const char*)p,n);} };
class CShop;
@@ -56,7 +56,7 @@ main=r'''
int main(){
Character c;c.items[90011]=30;
assert(Ava2OpenTicketShop(&c));assert(Ava2IsTicketShop(c.GetShop()));assert(c.GetShopOwner()==&c);
assert(c.desc.frame.size()==2048);
assert(c.desc.frame.size()==2208);
Ava2ShopStart start;memcpy(&start,c.desc.frame.data()+sizeof(TPacketGCShop),sizeof(start));
assert(start.shop.owner_vid==0 && start.shop.items[7].vnum==25170 && start.prices[0].vnum==90011 && start.prices[7].count==30);
assert(c.GetShop()->Buy(&c,0)==SHOP_SUBHEADER_GC_OK);assert(c.items[25163]==1 && c.items[90011]==20 && c.gold==123456);
+48
View File
@@ -0,0 +1,48 @@
"""Execute actual Cube_make with wide balances and unsigned proto fees."""
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[2]
class CubeGold(unittest.TestCase):
def test_unsigned_fee_debits_exactly_once_and_insufficient_balance_is_unchanged(self):
text=(ROOT/'src/server/game/src/cube.cpp').read_text(encoding='latin1')
actual='bool Cube_make'+text.split('bool Cube_make',1)[1].split('void Cube_show_list',1)[0]
harness=r'''
#include <cassert>
#include <cstdint>
#include <cstddef>
struct Item{unsigned GetID(){return 1;}};using LPITEM=Item*;
struct Character;using LPCHARACTER=Character*;
struct CUBE_VALUE{unsigned vnum=19,count=1;};
struct CUBE_DATA{uint32_t gold=50;int percent=100;unsigned removed=0;CUBE_VALUE value;
CUBE_VALUE* reward_value(){return &value;}void remove_material(LPCHARACTER){++removed;}} proto;
struct Character {int64_t balance=1000,delta=0;unsigned charges=0,rewards=0;Item item;
bool IsCubeOpen(){return true;}Character* GetQuestNPC(){return this;}LPITEM* GetCubeItem(){return nullptr;}
unsigned GetRaceNum(){return 1;}int64_t GetGold(){return balance;}
void ChatPacket(int,const char*,...){}void PointChange(int,int64_t n,bool){delta=n;balance+=n;++charges;}
Item* AutoGiveItem(unsigned,unsigned){++rewards;return &item;}
unsigned GetPlayerID(){return 1;}int GetX(){return 0;}int GetY(){return 0;}};
CUBE_DATA* FN_find_cube(LPITEM*,unsigned){return &proto;}
constexpr int POINT_GOLD=11,CHAT_TYPE_INFO=1,CHAT_TYPE_COMMAND=2;
#define LC_TEXT(s) "notice"
int roll=1;int number(int,int){return roll;}
struct LogManager{static LogManager& instance(){static LogManager m;return m;}void CubeLog(unsigned,int,int,unsigned,unsigned,unsigned,int){}};
'''
main=r'''
int main(){
for(uint32_t fee:{uint32_t(50),uint32_t(INT32_MAX)+1u,UINT32_MAX}) {
proto.gold=fee;proto.removed=0;Character ch;ch.balance=int64_t(fee)+123;
assert(Cube_make(&ch));assert(ch.balance==123 && ch.delta==-int64_t(fee) && ch.charges==1 && proto.removed==1 && ch.rewards==1);
ch={};ch.balance=int64_t(fee)-1;proto.removed=0;assert(!Cube_make(&ch));assert(ch.balance==int64_t(fee)-1 && ch.charges==0 && proto.removed==0 && ch.rewards==0);
}
proto.gold=50;proto.removed=0;roll=100;proto.percent=0;Character ch;
assert(!Cube_make(&ch));assert(ch.balance==950 && ch.charges==1 && proto.removed==1 && ch.rewards==0);
}
'''
with tempfile.TemporaryDirectory() as tmp:
p=Path(tmp);(p/'probe.cpp').write_text('#include <initializer_list>\n'+harness+actual+main)
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all',str(p/'probe.cpp'),'-o',str(p/'probe')],check=True)
subprocess.run([str(p/'probe')],check=True)
+58
View File
@@ -0,0 +1,58 @@
"""Run the actual DB config parser with bounded buffers and atomic rejection."""
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[2]
class ConfigRuntime(unittest.TestCase):
def test_tokens_lines_and_malformed_reload_preserve_active_config(self):
source=(ROOT/'src/server/db/src/Config.cpp').read_text(encoding='latin1')
source='\n'.join(line for line in source.splitlines() if not line.startswith('#include'))
stl=(ROOT/'src/server/common/stl.h').read_text(encoding='latin1')
lower=stl[stl.index('inline void stl_lowers'):stl.index('struct stringhash')]
code=r'''
#include <cassert>
#include <cstdio>
#include <cstring>
#include <cstdint>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <string>
using DWORD=uint32_t;using WORD=uint16_t;using BYTE=uint8_t;
#include <map>
#include <cctype>
#define itertype(v) decltype((v).begin())
// Singleton lifetime is outside the parser boundary exercised here.
template<class T> struct singleton {};
#include "src/server/common/utils.h"
#include "src/server/db/src/Config.h"
#define sys_log(...) ((void)0)
'''+lower+source+r'''
FILE* input(const std::string& s){FILE* f=tmpfile();assert(f);assert(fwrite(s.data(),1,s.size(),f)==s.size());rewind(f);return f;}
void file(const char* path,const std::string& text){std::ofstream out(path);out<<text;}
int main(int argc,char** argv){
const char* path=argv[1];CConfig config;
struct {char before='A';char text[4];char after='Z';} buffer;
auto f=input("abc");assert(config.GetWord(f,buffer.text,sizeof(buffer.text))&&!strcmp(buffer.text,"abc"));fclose(f);
f=input("abcd");assert(!config.GetWord(f,buffer.text,sizeof(buffer.text)));assert(buffer.before=='A'&&buffer.after=='Z');fclose(f);
// LoadFile resets the previous parser error, commits only a complete snapshot.
file(path,"NAME = \"dragon shop\"\nVALUE = 42\nITEM_ID_RANGE = 10 99\n");assert(config.LoadFile(path));
char name[32];DWORD value=0,a=0,b=0;assert(config.GetValue("NAME",name,sizeof(name))&&!strcmp(name,"dragon shop"));assert(config.GetValue("VALUE",&value)&&value==42);assert(config.GetTwoValue("ITEM_ID_RANGE",&a,&b)&&a==10&&b==99);
file(path,"BAD_RANGE = \"1 no\"\nMISSING_RANGE = 1\nHUGE_RANGE = \"1 4294967296\"\n");assert(config.LoadFile(path));
for(const char* key:{"BAD_RANGE","MISSING_RANGE","HUGE_RANGE"}){a=777;b=888;assert(!config.GetTwoValue(key,&a,&b)&&a==777&&b==888);}
// A line must be NUL-terminated, including when EOF ends the last line.
file(path,"ITEM_ID_RANGE = 1 2");assert(config.LoadFile(path));
f=input("xy\n");assert(config.GetLine(f,buffer.text,sizeof(buffer.text))&&!strcmp(buffer.text,"xy"));fclose(f);
f=input("xyz");assert(config.GetLine(f,buffer.text,sizeof(buffer.text))&&!strcmp(buffer.text,"xyz"));fclose(f);
for(const auto& bad:{std::string("NEW = safe\nBIG = ")+std::string(256,'x'),std::string("NEW = safe\nBIG = \"")+std::string(256,'x')+"\"",std::string("NEW = safe\nITEM_ID_RANGE = ")+std::string(256,'1'),std::string("NEW = safe\nBAD = \"unterminated"),std::string("NEW = safe\nBROKEN ="),std::string("NEW = safe\nBAD = a\0b",19)}){
file(path,bad);assert(!config.LoadFile(path));assert(!config.GetValue("NEW",name,sizeof(name)));assert(config.GetValue("VALUE",&value)&&value==42);
}
std::string unicode="DRAGON \xe9\xbe\x99";stl_lowers(unicode);assert(unicode=="dragon \xe9\xbe\x99");
}
'''
with tempfile.TemporaryDirectory() as tmp:
src=Path(tmp)/'probe.cpp';exe=src.with_suffix('');src.write_text(code)
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-Werror=implicit-int-conversion','-I'+str(ROOT),str(src),'-o',str(exe)],check=True)
subprocess.run([str(exe),str(Path(tmp)/'config')],check=True)
if __name__=='__main__':unittest.main()
+38 -59
View File
@@ -63,65 +63,44 @@ class DragonSoulAlchemyTest(unittest.TestCase):
self.assertIn('pDestItem->GiveMoreTime_Fix', fix_block)
self.assertIn('item->SetCount(item->GetCount() - 1);', fix_block)
def test_item_give_more_time_implementation(self):
"""Verify CItem::GiveMoreTime_Per and CItem::GiveMoreTime_Fix logic in item.cpp."""
source = (ROOT / 'src/server/game/src/item.cpp').read_text(encoding='latin1')
# Verify GiveMoreTime_Per
self.assertIn('int CItem::GiveMoreTime_Per(float fPercent)', source)
per_code = source.split('int CItem::GiveMoreTime_Per(float fPercent)', 1)[1].split('int CItem::GiveMoreTime_Fix', 1)[0]
self.assertIn('DWORD duration = DSManager::instance().GetDuration(this);', per_code)
self.assertIn('int remain_sec = GetSocket(ITEM_SOCKET_REMAIN_SEC);', per_code)
self.assertIn('int given_time = fPercent * duration / 100;', per_code)
self.assertIn('if (remain_sec == duration)', per_code)
self.assertIn('SetSocket(ITEM_SOCKET_REMAIN_SEC, duration);', per_code)
# Verify GiveMoreTime_Fix
self.assertIn('int CItem::GiveMoreTime_Fix(DWORD dwTime)', source)
fix_code = source.split('int CItem::GiveMoreTime_Fix(DWORD dwTime)', 1)[1].split('int\tCItem::GetDuration()', 1)[0]
self.assertIn('if (remain_sec == duration)', fix_code)
self.assertIn('SetSocket(ITEM_SOCKET_REMAIN_SEC, duration);', fix_code)
def test_time_charge_simulation(self):
"""Simulate GiveMoreTime_Per and GiveMoreTime_Fix numerical bounds."""
duration = 86400 # 24 hours
# Simulated GiveMoreTime_Per (50%)
def give_more_time_per(remain_sec, percent=50.0):
given = int(percent * duration / 100)
if remain_sec == duration:
return 0, remain_sec
if given + remain_sec >= duration:
return duration - remain_sec, duration
return given, remain_sec + given
# 1. 50% charge when remaining is 0: gives 43200s, total 43200s
added, new_remain = give_more_time_per(0, 50.0)
self.assertEqual(added, 43200)
self.assertEqual(new_remain, 43200)
# 2. 50% charge when remaining is 60000s: capped at 86400, gives 26400s
added, new_remain = give_more_time_per(60000, 50.0)
self.assertEqual(added, 26400)
self.assertEqual(new_remain, 86400)
# 3. Charge when already full: gives 0
added, new_remain = give_more_time_per(86400, 50.0)
self.assertEqual(added, 0)
self.assertEqual(new_remain, 86400)
# Simulated GiveMoreTime_Fix (86400s)
def give_more_time_fix(remain_sec, fix_time=86400):
if remain_sec == duration:
return 0, remain_sec
if fix_time + remain_sec >= duration:
return duration - remain_sec, duration
return fix_time, remain_sec + fix_time
# 1. Fixed charge 86400s when remaining is 1000s: capped at 86400, gives 85400s
added, new_remain = give_more_time_fix(1000, 86400)
self.assertEqual(added, 85400)
self.assertEqual(new_remain, 86400)
def test_actual_time_charge_methods_reject_corruption_and_cap_before_conversion(self):
import subprocess, tempfile
source=(ROOT/'src/server/game/src/item.cpp').read_bytes().decode('latin1')
body=source[source.index('int CItem::GiveMoreTime_Per('):source.index('int\tCItem::GetDuration()')]
harness=r"""
#include <cassert>
#include <cmath>
#include <cstdint>
#include <limits>
using DWORD=uint32_t;
constexpr int ITEM_SOCKET_REMAIN_SEC=0;
struct CItem {bool dragon=true;int64_t remaining=0;unsigned writes=0;
bool IsDragonSoul(){return dragon;}int64_t GetSocket(int){return remaining;}
void SetSocket(int,int value){remaining=value;++writes;}
int GiveMoreTime_Per(float);int GiveMoreTime_Fix(DWORD);
};
struct DSManager {uint32_t duration=86400;static DSManager& instance(){static DSManager m;return m;}uint32_t GetDuration(CItem*){return duration;}};
"""
main=r"""
int main(){
CItem i;auto& d=DSManager::instance();
assert(i.GiveMoreTime_Per(50)==43200&&i.remaining==43200);i.remaining=60000;assert(i.GiveMoreTime_Per(50)==26400&&i.remaining==86400);
unsigned writes=i.writes;assert(i.GiveMoreTime_Per(50)==0&&i.GiveMoreTime_Fix(86400)==0&&i.writes==writes);
i.remaining=1000;assert(i.GiveMoreTime_Fix(86400)==85400&&i.remaining==86400);
i.remaining=0;writes=i.writes;
for(float f:{-1.f,0.f,std::numeric_limits<float>::infinity(),std::numeric_limits<float>::quiet_NaN()})assert(i.GiveMoreTime_Per(f)==0&&i.writes==writes);
assert(i.GiveMoreTime_Per(.00001f)==0&&i.writes==writes);
assert(i.GiveMoreTime_Per(std::numeric_limits<float>::max())==86400&&i.remaining==86400);
for(int64_t remaining:{int64_t(-1),int64_t(INT32_MIN),int64_t(86401),int64_t(INT32_MAX)}){i.remaining=remaining;writes=i.writes;assert(i.GiveMoreTime_Per(50)==0&&i.GiveMoreTime_Fix(UINT32_MAX)==0&&i.remaining==remaining&&i.writes==writes);}
d.duration=INT32_MAX;i.remaining=INT32_MAX-10;assert(i.GiveMoreTime_Fix(UINT32_MAX)==10&&i.remaining==INT32_MAX);
for(uint32_t duration:{0u,UINT32_MAX}){d.duration=duration;i.remaining=0;writes=i.writes;assert(i.GiveMoreTime_Per(50)==0&&i.GiveMoreTime_Fix(86400)==0&&i.writes==writes);}
d.duration=86400;i.dragon=false;assert(i.GiveMoreTime_Per(50)==0&&i.GiveMoreTime_Fix(86400)==0);
}
"""
with tempfile.TemporaryDirectory() as tmp:
p=Path(tmp);(p/'test.cpp').write_text(harness+body+main)
subprocess.run(['c++','-std=c++17','-include','initializer_list','-fsanitize=address,undefined','-fno-sanitize-recover=all',str(p/'test.cpp'),'-o',str(p/'probe')],check=True)
subprocess.run([str(p/'probe')],check=True)
def test_dragon_bean_100500_refine_strength_mechanics(self):
"""Verify 100500 MATERIAL_DS_REFINE_HOLLY in DSManager::DoRefineStrength."""
+17
View File
@@ -0,0 +1,17 @@
"""Execute the production transaction store against SQLite (SQL dialect boundary).
The same C++ scenarios are separately run against isolated real MySQL/InnoDB.
"""
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
class EconomyTransactions(unittest.TestCase):
def test_orders_gaya_crash_replay_and_competing_buyers(self):
with tempfile.TemporaryDirectory() as tmp:
exe=Path(tmp)/'economy'
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-I'+str(ROOT),str(ROOT/'tests/features/fixtures/economy_probe.cpp'),'-lsqlite3','-o',str(exe)],check=True)
subprocess.run([str(exe),str(Path(tmp)/'economy.db')],check=True)
if __name__=='__main__':unittest.main()
+100
View File
@@ -0,0 +1,100 @@
"""Execute DB coordinator functions with explicit peer/cache/FIFO SQL boundaries."""
import re
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
class EconomyCoordinator(unittest.TestCase):
def test_ownership_logout_cache_eviction_two_barriers_and_stale_write_fences(self):
fixture=(ROOT/'tests/features/fixtures/economy_probe.cpp').read_text()
prefix,main=fixture.split('int main(int argc,char** argv)',1)
prefix=prefix.replace('rows={{"13"}};return true;', 'rows={{sql.find("AND TABLE_NAME=\'port_economy_version\'")!=std::string::npos?"1":"13"}};return true;')
init=main.split(' basic(db);',1)[0]
assert len(init)<len(main), 'fixture initialization boundary missing'
body=re.sub(r'^#include[^\n]*\n','',(ROOT/'src/server/db/src/Economy.cpp').read_text(),flags=re.M)
harness=r'''
using DWORD=uint32_t;
struct MYSQL_RES {Rows rows;std::vector<char*> values;size_t next=0;};using MYSQL_ROW=char**;
MYSQL_ROW mysql_fetch_row(MYSQL_RES* res){if(res->next>=res->rows.size())return nullptr;res->values.clear();for(auto& s:res->rows[res->next++])res->values.push_back(s.data());return res->values.data();}
struct SQLResult {uint64_t uiNumRows=0;MYSQL_RES* pSQLResult=nullptr;};
struct SQLMsg {unsigned uiSQLErrno=0;SQLResult result;MYSQL_RES res;void* pvUserData=nullptr;SQLResult* Get(){return &result;}};
struct CPeer {unsigned id=1;std::vector<Reply> replies;unsigned GetHandle(){return id;}unsigned GetChannel(){return 1;}void EncodeHeader(unsigned,unsigned,size_t){}void Encode(const void* data,size_t n){assert(n==sizeof(Reply));replies.push_back(*static_cast<const Reply*>(data));}};
struct Player {unsigned dwID=0;};struct Account {Player players[4];};
struct CLoginData {bool playing=true;unsigned peer=1;Account account;unsigned GetConnectedPeerHandle(){return peer;}bool IsPlay(){return playing;}Account& GetAccountRef(){return account;}};
struct TPlayerLoadPacket{unsigned account_id,player_id;};
struct Proto{unsigned bSize=1,dwAntiFlags=0,bType=0,dwFlags=1;};
constexpr unsigned ITEM_ANTIFLAG_GIVE=1,ITEM_ANTIFLAG_MYSHOP=2,ITEM_QUEST=18,ITEM_FLAG_STACKABLE=1,QID_ECONOMY_FENCE=100;
TestDB* activeDB=nullptr;
struct CDBManager {
std::vector<unsigned> mainQueue,asyncQueue;std::vector<SQLMsg*> completed;uint64_t failures[2]={};
static CDBManager& instance(){static CDBManager m;return m;}
TestDB* DirectHandle(){return activeDB;}
SQLMsg* DirectQuery(const char* sql){auto* msg=new SQLMsg;if(!activeDB->Query(sql,msg->res.rows))msg->uiSQLErrno=1;msg->result.uiNumRows=msg->res.rows.size();msg->result.pSQLResult=&msg->res;return msg;}
uint64_t EconomyFailures(bool async){return failures[async?1:0];}
void ReturnQuery(const char*,unsigned,unsigned pid,void*){mainQueue.push_back(pid);}
void EconomyAsyncFence(unsigned pid){asyncQueue.push_back(pid);}
SQLMsg* PopEconomyAsyncFence(){if(completed.empty())return nullptr;auto* p=completed.back();completed.pop_back();return p;}
void asyncDone(unsigned pid){assert(!asyncQueue.empty());asyncQueue.pop_back();auto* p=new SQLMsg;p->pvUserData=reinterpret_cast<void*>(static_cast<uintptr_t>(pid));completed.push_back(p);}
};
namespace PortEconomy {struct Mysql {
TestDB& ref;uint64_t affected=0,inserted=0;
explicit Mysql(TestDB* db):ref(*db){}
bool Query(const std::string& q,Rows& rows){bool ok=ref.Query(q,rows);affected=ref.affected;inserted=ref.inserted;return ok;}
bool Begin(){return ref.Begin();}bool Commit(){return ref.Commit();}void Rollback(){ref.Rollback();}
};}
const char* GetTablePostfix(){return "";}
static size_t TestCopyString(char* out,const char* text,size_t n){size_t length=strlen(text);if(n){size_t k=std::min(n-1,length);memcpy(out,text,k);out[k]=0;}return length;}
#define strlcpy TestCopyString
#define sys_log(...) ((void)0)
struct 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={};};
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;
std::map<DWORD,Proto*> m_map_itemTableByVnum;CLoginData login;unsigned itemFlushes=0,playerFlushes=0,logoutDeletes=0;
CPeer* connected=nullptr;unsigned resumed=0;CPeer* GetPeer(unsigned id){return connected&&connected->id==id?connected:nullptr;}void QUERY_PLAYER_LOAD(CPeer* peer,unsigned handle,TPlayerLoadPacket* p){assert(EconomyBeforeLoad(peer,handle,p));++resumed;}
CLoginData* GetLoginDataByAID(unsigned account){return account==1?&login:nullptr;}
void FlushItemCacheSet(unsigned){++itemFlushes;}void FlushPlayerCacheSet(unsigned){++playerFlushes;}void DeleteLogoutPlayer(unsigned){++logoutDeletes;}
void EconomyRequest(CPeer*,DWORD,const char*,DWORD);bool EconomyBeforeLoad(CPeer*,DWORD,TPlayerLoadPacket*);void EconomyTick();void EconomyMainFence(DWORD,bool);bool EconomySaveAllowed(CPeer*,DWORD);bool EconomyItemWritable(DWORD);bool EconomyCanDelete(DWORD);
};
'''
# Extra headers are boundaries used by the real coordinator.
prefix='#include "src/server/common/economy_view.h"\n#include <set>\n#include <map>\n#include <memory>\n#include <ctime>\n'+prefix
tests=r'''
activeDB=&db;reset(db);CClientManager manager;CPeer peer,wrong;manager.connected=&peer;wrong.id=99;manager.login.account.players[0].dwID=1;
Proto proto;manager.m_map_itemTableByVnum[100]=&proto;
Request r=req(List,1,1,100);r.item=10;r.itemVnum=100;r.itemCount=5;r.price=750;
manager.EconomyRequest(&wrong,1,reinterpret_cast<const char*>(&r),sizeof(r));assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==0);
manager.EconomyRequest(&peer,1,reinterpret_cast<const char*>(&r),sizeof(r));assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==1);assert(!manager.EconomyCanDelete(1));assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10")==1);
TPlayerLoadPacket load{1,1};assert(!manager.EconomyBeforeLoad(&peer,7,&load));assert(manager.itemFlushes==0); // still playing
manager.login.playing=false;assert(!manager.EconomyBeforeLoad(&wrong,7,&load));assert(manager.itemFlushes==0);
assert(!manager.EconomyBeforeLoad(&peer,7,&load));assert(manager.itemFlushes==1 && manager.playerFlushes==1 && manager.logoutDeletes==1);assert(!manager.EconomySaveAllowed(&peer,1));
auto& queues=CDBManager::instance();assert(queues.mainQueue.size()==1 && queues.asyncQueue.empty());manager.EconomyTick();assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10")==1);
manager.EconomyMainFence(1,false);assert(queues.mainQueue.size()==2 && queues.asyncQueue.size()==1);manager.EconomyTick();assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10")==1);
queues.asyncDone(1);manager.EconomyTick();assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10")==1); // second main fence not done
manager.EconomyMainFence(1,false);manager.EconomyTick();assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10")==0);assert(!manager.EconomyItemWritable(10));assert(!manager.EconomyCanDelete(1));assert(manager.resumed==1);assert(!manager.EconomySaveAllowed(&peer,1));
assert(manager.EconomyBeforeLoad(&peer,7,&load));assert(!manager.EconomySaveAllowed(&peer,1));manager.login.playing=true;assert(manager.EconomySaveAllowed(&peer,1));assert(!manager.EconomySaveAllowed(&wrong,1));
// A failed final async write aborts the durable intent instead of settling it.
reset(db);queues.mainQueue.clear();queues.asyncQueue.clear();r=req(List,1,1,100);r.item=10;r.itemVnum=100;r.itemCount=5;r.price=750;
manager.EconomyRequest(&peer,1,reinterpret_cast<const char*>(&r),sizeof(r));++queues.failures[1];manager.login.playing=false;assert(!manager.EconomyBeforeLoad(&peer,7,&load));manager.EconomyMainFence(1,false);queues.asyncDone(1);manager.EconomyMainFence(1,false);manager.EconomyTick();
assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10")==1);assert(integer(db,"SELECT COUNT(*) FROM port_economy_custody")==0);assert(value(db,"SELECT result FROM port_economy_requests WHERE token='"+std::string(r.token)+"'")=="save_failed");
assert(manager.EconomyCanDelete(1));sql(db,"INSERT INTO port_economy_gaya(pid,generation,deadline,offers) VALUES(1,1,100,X'')");assert(!manager.EconomyCanDelete(1));
sql(db,"UPDATE port_economy_gaya SET generation="+std::to_string(RetiredGeneration)+" WHERE pid=1");assert(manager.EconomyCanDelete(1));
sql(db,"INSERT INTO quest(dwPID,szName,szState,lValue) VALUES(1,'gem','points',1)");assert(!manager.EconomyCanDelete(1));
sql(db,"UPDATE quest SET lValue=0 WHERE dwPID=1");assert(manager.EconomyCanDelete(1));
// UI reads return correlated command frames and never queue a mutation.
manager.login.playing=true;r=req(UiStatus,1,1,100);r.generation=17;r.slot=0;memset(r.token,'0',32);r.token[32]=0;
peer.replies.clear();manager.EconomyRequest(&peer,1,reinterpret_cast<const char*>(&r),sizeof(r));
assert(!peer.replies.empty() && std::string(peer.replies.front().message).find("MTECON1 begin 17 ")==0);
assert(std::string(peer.replies.back().message)=="MTECON1 end 17");assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==0);
puts("PASS actual DB coordinator: ownership/logout/eviction/two FIFO barriers/stale saves/failure abort");
}
'''
with tempfile.TemporaryDirectory() as tmp:
src=Path(tmp)/'probe.cpp';exe=Path(tmp)/'probe'
src.write_text(prefix+harness+body+'int main(int argc,char** argv)'+init+tests)
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-I'+str(ROOT),str(src),'-lsqlite3','-o',str(exe)],check=True)
subprocess.run([str(exe),str(Path(tmp)/'economy.db')],check=True)
if __name__=='__main__':unittest.main()
+59
View File
@@ -0,0 +1,59 @@
"""Run actual game command/submission/reply functions, with session/socket boundaries."""
import pathlib,re,subprocess,tempfile,unittest
ROOT=pathlib.Path(__file__).resolve().parents[2]
class GameEconomyUI(unittest.TestCase):
def test_read_only_frames_receipts_and_mutation_handoff(self):
body=re.sub(r'^#include[^\n]*\n','',(ROOT/'src/server/game/src/port_economy.cpp').read_text(),flags=re.M)
harness=r'''
#include "src/server/common/economy.h"
#include <cassert>
#include <cerrno>
#include <cstdarg>
#include <ctime>
#include <fcntl.h>
#include <map>
#include <sstream>
#include <unistd.h>
#include <vector>
constexpr int PHASE_CLOSE=0,CHAT_TYPE_INFO=1,CHAT_TYPE_COMMAND=2,ITEM_QUEST=18;
constexpr unsigned ITEM_ANTIFLAG_GIVE=1,ITEM_ANTIFLAG_MYSHOP=2;
#define IS_SET(v,bits) ((v)&(bits))
struct Item {unsigned id=10,vnum=100,count=5;bool locked=false;
bool IsEquipped(){return false;}bool isLocked(){return locked;}bool IsExchanging(){return false;}unsigned GetAntiFlag(){return 0;}unsigned GetType(){return 0;}
unsigned GetID(){return id;}unsigned GetOriginalVnum(){return vnum;}unsigned GetCount(){return count;}};using LPITEM=Item*;using WORD=uint16_t;
struct CHARACTER;
struct Desc {unsigned handle=1,closed=0;struct Account{unsigned id=1;} account;CHARACTER* ch=nullptr;
unsigned GetHandle(){return handle;}Account& GetAccountTable(){return account;}void SetPhase(int){++closed;}CHARACTER* GetCharacter(){return ch;}};
struct CHARACTER {Desc desc;Item item;bool busy=false;std::vector<std::pair<int,std::string>> messages;
CHARACTER(){desc.ch=this;}bool IsPC(){return true;}Desc* GetDesc(){return &desc;}bool IsItemLoaded(){return true;}unsigned GetPlayerID(){return 1;}
int GetQuestFlag(const char*){return 0;}int64_t GetGold(){return 1000;}bool CanHandleItem(){return !busy;}bool IsWarping(){return false;}bool IsDead(){return false;}bool IsStun(){return false;}
bool GetExchange(){return false;}bool GetMyShop(){return false;}bool GetShop(){return false;}bool IsOpenSafebox(){return false;}bool GetMall(){return false;}bool IsCubeOpen(){return false;}
LPITEM GetInventoryItem(WORD cell){return cell==0?&item:nullptr;}
void ChatPacket(int type,const char* fmt,...){char out[1024];va_list ap;va_start(ap,fmt);vsnprintf(out,sizeof(out),fmt,ap);va_end(ap);messages.emplace_back(type,out);}
};using LPDESC=Desc*;
namespace quest {struct PC{bool IsLoaded(){return true;}bool IsRunning(){return false;}};struct CQuestManager{PC pc;static CQuestManager& instance(){static CQuestManager m;return m;}PC* GetPCForce(unsigned){return &pc;}};}
struct Database {std::vector<PortEconomy::Request> requests;void DBPacket(unsigned header,unsigned,const void* data,size_t n){assert(header==77&&n==sizeof(PortEconomy::Request));requests.push_back(*static_cast<const PortEconomy::Request*>(data));}} database;
Database* db_clientdesc=&database;
const char* get_table_postfix(){return "";}
Desc* live=nullptr;
struct DESC_MANAGER {static DESC_MANAGER& instance(){static DESC_MANAGER m;return m;}Desc* FindByHandle(unsigned handle){return live&&live->handle==handle?live:nullptr;}};
#define ACMD(name) void name(CHARACTER* ch,const char* argument,int cmd=0,int subcmd=0)
'''
main=r'''
int main(){CHARACTER ch;live=&ch.desc;
do_mt_economy(&ch,"ui 0 0 1 0 00000000000000000000000000000000");assert(database.requests.size()==1 && database.requests.back().operation==PortEconomy::UiStatus && !ch.desc.closed);
do_mt_economy(&ch,"ui 0 0 2 0 00000000000000000000000000000000");assert(database.requests.size()==1 && ch.messages.back().first==CHAT_TYPE_COMMAND);
do_mt_economy(&ch,"act aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa buy 4294967297 750");assert(database.requests.size()==2 && ch.desc.closed==1);
const auto request=database.requests.back();assert(request.reference==4294967297ULL && request.price==750 && request.expectedGold==1000 && request.player==1 && request.account==1 && std::string(request.token)==std::string(32,'a'));
do_mt_economy(&ch,"act bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb list 0 750 101 5");assert(database.requests.size()==2);
do_mt_economy(&ch,"act bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb list 0 750 100 5");assert(database.requests.size()==3 && database.requests.back().item==10);
do_mt_economy(&ch,"act zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz withdraw");assert(database.requests.size()==3);
ch.busy=true;do_mt_economy(&ch,"act cccccccccccccccccccccccccccccccc withdraw");assert(database.requests.size()==3);ch.busy=false;
PortEconomy::Reply reply={};reply.account=1;reply.player=1;reply.ok=1;strcpy(reply.message,"MTECON1 end 1");PortEconomyReply(1,reinterpret_cast<const char*>(&reply));assert(ch.messages.back().first==CHAT_TYPE_COMMAND);
auto count=ch.messages.size();reply.account=2;PortEconomyReply(1,reinterpret_cast<const char*>(&reply));assert(ch.messages.size()==count);
}
'''
with tempfile.TemporaryDirectory() as tmp:
p=pathlib.Path(tmp);(p/'probe.cpp').write_text(harness+body+main)
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-Werror=implicit-int-conversion','-Werror=shorten-64-to-32','-I'+str(ROOT),str(p/'probe.cpp'),'-o',str(p/'probe')],check=True)
subprocess.run([str(p/'probe')],check=True)
+48
View File
@@ -0,0 +1,48 @@
"""Legacy evidence is inventoried without manufacturing assets or refunds."""
import importlib.util
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location('reconcile', ROOT/'tools/economy/reconcile.py')
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
def snapshot(tables):
encoded={t:[{k:v.encode('utf-8', 'surrogateescape').hex() if v is not None else None
for k,v in row.items()} for row in rows] for t,rows in tables.items()}
result={'format':1,'encoding':'mysql-hex-all-columns','tables':encoded}
result['sha256']=m.digest(result)
return result
class Reconcile(unittest.TestCase):
def test_conflicts_balances_history_and_unproven_refunds(self):
item={'id':'10','owner_id':'1','count':'5','vnum':'100','price':'750','status':'0','port_extra':'\0'*69}
tables={t:[] for t in m.REQUIRED}
tables['player']=[{'id':'1','shop_money':'750'},{'id':'2','shop_money':'-1'}]
tables['offline_shop_item']=[item,dict(item,id='11',status='1'),dict(item,id='12',owner_id='99'),dict(item,id='13',port_extra=None)]
tables['item']=[{'id':'10'}]
tables['offline_shop_log_important']=[{'reason':'BUY','itemid':'11','price':'750'}]
report=m.audit(snapshot(tables));assets={a['key']:a for a in report['assets']}
self.assertIn('item_id_exists_elsewhere',assets['legacy-item:10']['reasons'])
self.assertIn('historical_order_requires_delivery_payment_evidence',assets['legacy-item:11']['reasons'])
self.assertIn('owner_missing_or_duplicate',assets['legacy-item:12']['reasons'])
self.assertIn('missing_or_invalid_full_item_metadata',assets['legacy-item:13']['reasons'])
self.assertEqual(assets['legacy-proceeds:1']['classification'],'proceeds_review')
self.assertEqual(assets['legacy-proceeds:2']['classification'],'quarantine')
self.assertEqual(report['automatic_refunds'],[]);self.assertEqual(report['automatic_writes'],[])
self.assertEqual(report['history_rows']['offline_shop_log_important'],1)
def test_valid_candidate_remains_review_only_and_snapshot_tamper_refused(self):
tables={t:[] for t in m.REQUIRED};tables['player']=[{'id':'1','shop_money':'0'}]
tables['offline_shop_item']=[{'id':'10','owner_id':'1','count':'5','vnum':'100','price':'750','status':'0','port_extra':'\0'*69}]
data=snapshot(tables);report=m.audit(data)
self.assertEqual(report['assets'][0]['classification'],'custody_review')
self.assertEqual(report['release_gate'],'BLOCKED_PENDING_RECONCILIATION')
data['tables']['item'].append({'id':'3130'})
with self.assertRaises(ValueError):m.audit(data)
def test_mysql_xml_null_binary_multiple_results(self):
text='<?xml version="1.0"?><resultset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><row><field name="x">00FF</field><field name="y" xsi:nil="true" /><field name="z" /></row></resultset><?xml version="1.0"?><resultset />'
self.assertEqual(m.xml_rows(text),[[{'x':'00FF','y':None,'z':''}],[]])
+12
View File
@@ -0,0 +1,12 @@
"""Actual production UI snapshot encoder plus transaction store with SQL adapter."""
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
class EconomyView(unittest.TestCase):
def test_atomic_bounded_snapshots_and_authoritative_receipts(self):
with tempfile.TemporaryDirectory() as tmp:
p=Path(tmp);exe=p/'view'
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-I'+str(ROOT),str(ROOT/'tests/features/fixtures/economy_view_probe.cpp'),'-lsqlite3','-o',str(exe)],check=True)
subprocess.run([str(exe),str(p/'view.db'),str(p/'frames')],check=True)
+2 -2
View File
@@ -49,14 +49,14 @@ int main() {
assert(!PortItemExtraRead("00",decoded));
hex[137]='g';assert(!PortItemExtraRead(hex.c_str(),decoded));
assert(!std::memcmp(&zero,&decoded,sizeof(zero)));
hex=std::string(138,'f');assert(PortItemExtraRead(hex.c_str(),decoded));
hex=std::string(138,'f');assert(!PortItemExtraRead(hex.c_str(),decoded));
assert(decoded.name[24]==0);
}
'''
with tempfile.TemporaryDirectory() as tmp:
cpp, exe = Path(tmp)/'extra.cpp', Path(tmp)/'extra'
cpp.write_text(source)
subprocess.run(['c++', '-std=c++17', '-I'+str(ROOT), str(cpp), '-o', str(exe)], check=True)
subprocess.run(['c++', '-std=c++17', '-Werror=implicit-int-conversion', '-I'+str(ROOT), str(cpp), '-o', str(exe)], check=True)
subprocess.run([str(exe)], check=True)
+81
View File
@@ -0,0 +1,81 @@
"""Execute catalogue I/O, corruption, writer exclusion and crash boundaries."""
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[2]
class GayaCatalogue(unittest.TestCase):
def test_atomic_snapshots_and_failures(self):
code=r'''
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <cerrno>
#include <cstdio>
static bool failWrite=false,failRename=false;static int syncs=0,failSyncAt=0,crashAt=0;
static ssize_t Write(int fd,const void* p,size_t n){if(failWrite){errno=ENOSPC;return -1;}return ::write(fd,p,n);}
static int Sync(int fd){++syncs;if(syncs==failSyncAt){errno=EIO;return -1;}int r=::fsync(fd);if(crashAt==1 && syncs==1)_exit(0);return r;}
static int Rename(int a,const char* b,int c,const char* d){if(failRename){errno=EIO;return -1;}int r=::renameat(a,b,c,d);if(crashAt==2 && r==0)_exit(0);return r;}
#define write Write
#define fsync Sync
#define renameat Rename
#include "src/server/common/gaya_catalog.h"
#undef write
#undef fsync
#undef renameat
#include <cassert>
#include <fstream>
#include <sys/wait.h>
struct Item{uint32_t itemVnum,itemCount;int itemPrice;bool itemBuyed;};
using Items=std::map<uint8_t,Item>;
std::string readFile(const std::string& path){std::ifstream f(path);return std::string((std::istreambuf_iterator<char>(f)),{});}
void writeFile(const std::string& path,const std::string& bytes){std::ofstream out(path);out<<bytes;}
int main(int argc,char** argv){
const std::string dir=argv[1],path=dir+"/1";mkdir(dir.c_str(),0700);
Items original={{0,{19,2000,50,false}},{26,{20,1,100,true}}},loaded;int refresh=99;
{PortGayaCatalogFile file;assert(file.Open(dir,1));assert(file.Load(loaded,refresh)==PortGayaCatalogFile::Missing && loaded.empty());assert(file.Save(original,200000));}
const std::string saved=readFile(path);assert(saved.find("gaya-v2 200000 ")==0);
{PortGayaCatalogFile file;assert(file.Open(dir,1));assert(file.Load(loaded,refresh)==PortGayaCatalogFile::Loaded);assert(loaded.size()==2 && loaded[0].itemCount==2000 && loaded[26].itemBuyed && refresh==200000);}
for(int fault=0;fault<4;++fault){
writeFile(path,saved);PortGayaCatalogFile file;assert(file.Open(dir,1));syncs=0;failWrite=fault==0;failSyncAt=fault==1?1:fault==3?2:0;failRename=fault==2;
auto next=original;next[0].itemBuyed=true;assert(!file.Save(next,300000));assert(!file.Ready());
failWrite=false;failSyncAt=0;failRename=false;
if(fault<3)assert(readFile(path)==saved); // before rename: last durable snapshot unchanged.
}
// A directory-fsync failure leaves a whole new file and pauses this writer.
{PortGayaCatalogFile file;assert(file.Open(dir,1));assert(file.Load(loaded,refresh)==PortGayaCatalogFile::Loaded && loaded[0].itemBuyed && refresh==300000);}
const std::string legacy="index-vnum-count-price-buyed\n";
const std::string good="0 19 2000 50 0\n26 20 1 100 1\n";
writeFile(path,legacy+good);
{PortGayaCatalogFile file;assert(file.Open(dir,1));assert(file.Load(loaded,refresh)==PortGayaCatalogFile::Loaded && refresh==0);assert(file.Save(loaded,200000));}
const std::string broken[]={"",legacy,legacy+good+"0 21 1 2 0\n",legacy+"256 19 1 1 0\n",legacy+"0 19 1 -1 0\n",legacy+"0 19 2001 1 0\n",legacy+"0 19 1 1 2\n",legacy+"0 19 1 1 0 junk\n",legacy+"0 19 1 1 0",legacy+"0 4294967296 1 1 0\n",legacy+"0 19 1 1 0\n\n",saved+"0 21 1 2 0\n"};
for(const auto& bytes:broken){
writeFile(path,bytes);PortGayaCatalogFile file;assert(file.Open(dir,1));Items before={{9,{99,1,99,false}}};refresh=77;
assert(file.Load(before,refresh)==PortGayaCatalogFile::Error && before.size()==1 && before[9].itemVnum==99 && refresh==77);
assert(readFile(path)==bytes && !file.Save(original,1));
}
writeFile(path,saved);
{PortGayaCatalogFile file;assert(file.Open(dir,1));assert(file.Save(original,200000));PortGayaCatalogFile competitor;assert(!competitor.Open(dir,1));assert(file.Save(original,200001));PortGayaCatalogFile afterRename;assert(!afterRename.Open(dir,1));}
for(int boundary=1;boundary<=2;++boundary){
writeFile(path,saved);pid_t child=fork();assert(child>=0);
if(child==0){PortGayaCatalogFile file;assert(file.Open(dir,1));syncs=0;crashAt=boundary;auto next=original;next[0].itemBuyed=true;file.Save(next,300000);_exit(9);}
int status=0;waitpid(child,&status,0);assert(WIFEXITED(status) && WEXITSTATUS(status)==0);
PortGayaCatalogFile file;assert(file.Open(dir,1));assert(file.Load(loaded,refresh)==PortGayaCatalogFile::Loaded);assert(loaded[0].itemBuyed==(boundary==2));
}
unlink(path.c_str());symlink("/does/not/exist",path.c_str());
{PortGayaCatalogFile file;assert(file.Open(dir,1));assert(file.Load(loaded,refresh)==PortGayaCatalogFile::Error);}
int next=123;
assert(PortGayaNextRefresh(100000,0,true,next) && next==118000);
assert(PortGayaNextRefresh(100000,90000,true,next) && next==108000);
assert(PortGayaNextRefresh(200000,90000,true,next) && next==216000); // many elapsed windows, still future.
assert(PortGayaNextRefresh(100000,110000,true,next) && next==110000);
assert(!PortGayaNextRefresh(INT32_MAX,1,true,next));assert(!PortGayaNextRefresh(1,-1,true,next));
}
'''
with tempfile.TemporaryDirectory() as tmp:
src=Path(tmp)/'probe.cpp';exe=Path(tmp)/'probe';src.write_text(code)
subprocess.run(['c++','-std=c++17','-fsanitize=undefined,address','-fno-sanitize-recover=all','-I'+str(ROOT),str(src),'-o',str(exe)],check=True)
subprocess.run([str(exe),str(Path(tmp)/'gem')],check=True)
if __name__=='__main__':unittest.main()
+2 -185
View File
@@ -1,8 +1,6 @@
#!/usr/bin/env python3
"""Verify Gaya market, items 39063/39064, and /gem command suite."""
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
@@ -15,194 +13,13 @@ class GayaMarketTest(unittest.TestCase):
# 39063: Refresh Gaya Market
self.assertIn('if(item->GetVnum()==39063)', special_block)
self.assertIn('RefreshGemALL();', special_block)
self.assertIn('item->SetCount(item->GetCount()-1);', special_block)
self.assertIn('return RefreshGemALL();', special_block)
self.assertNotIn('item->SetCount', special_block.split('if(item->GetVnum()==39063)',1)[1])
# 39064: Gaya Market Expansion
self.assertIn('if(item->GetVnum()==39064)', special_block)
self.assertIn('if(OpenGemSlot())', special_block)
def test_gaya_engine_harness(self):
harness = r'''
#include "src/server/game/src/port_gaya.h"
#include <map>
#include <string>
#include <vector>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <sys/stat.h>
struct DummyItem {
uint32_t vnum;
uint32_t count;
};
struct DummyChar {
uint32_t pid;
std::map<std::string, int> questFlags;
std::vector<std::string> commands;
std::vector<DummyItem> bag;
uint32_t GetPlayerID() const { return pid; }
int GetQuestFlag(const std::string& key) const {
auto it = questFlags.find(key);
return it == questFlags.end() ? 0 : it->second;
}
void SetQuestFlag(const std::string& key, int val) {
questFlags[key] = val;
}
void SetPoint(int, int) {}
void PointChange(int, int) {}
void ChatPacket(int, const char* fmt, ...) {
char buf[512];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
commands.push_back(buf);
}
void AutoGiveItem(uint32_t vnum, uint32_t count) {
bag.push_back({vnum, count});
}
};
// Implement standalone port_gaya harness
namespace {
std::string s_dir = "";
std::map<uint32_t, std::map<uint8_t, TGemItem>> s_items;
}
void SetDir(const std::string& d) { s_dir = d; }
bool TestOpenSlot(DummyChar* ch) {
int open = ch->GetQuestFlag("gem.open_slot");
if (open < 18) {
ch->SetQuestFlag("gem.open_slot", open + 1);
ch->ChatPacket(0, "GemUpdateSlotCount %d", open + 1);
return true;
}
return false;
}
void TestSaveItems(DummyChar* ch) {
mkdir(s_dir.c_str(), 0755);
char path[256];
snprintf(path, sizeof(path), "%s/%u", s_dir.c_str(), ch->GetPlayerID());
FILE* fp = fopen(path, "w+");
assert(fp != NULL);
fprintf(fp, "index-vnum-count-price-buyed\n");
for (const auto& kv : s_items[ch->GetPlayerID()]) {
fprintf(fp, "%u %u %u %d %u\n", kv.first, kv.second.itemVnum, kv.second.itemCount, kv.second.itemPrice, kv.second.itemBuyed ? 1 : 0);
}
fclose(fp);
}
void TestLoadItems(DummyChar* ch) {
char path[256];
snprintf(path, sizeof(path), "%s/%u", s_dir.c_str(), ch->GetPlayerID());
FILE* fp = fopen(path, "r");
if (!fp) return;
s_items[ch->GetPlayerID()].clear();
char line[256];
while (fgets(line, sizeof(line), fp)) {
unsigned slot = 0, vnum = 0, count = 0, buyed = 0;
int price = 0;
if (sscanf(line, "%u %u %u %d %u", &slot, &vnum, &count, &price, &buyed) == 5) {
TGemItem it;
it.itemVnum = vnum;
it.itemCount = count;
it.itemPrice = price;
it.itemBuyed = (buyed != 0);
s_items[ch->GetPlayerID()][(uint8_t)slot] = it;
}
}
fclose(fp);
}
void TestBuyItem(DummyChar* ch, uint8_t slot) {
auto& map = s_items[ch->GetPlayerID()];
auto it = map.find(slot);
if (it == map.end()) return;
if (slot >= 9) {
if (ch->GetQuestFlag("gem.open_slot") < (slot - 9) + 1)
return;
}
if (it->second.itemBuyed) return;
int points = ch->GetQuestFlag("gem.points");
if (points < it->second.itemPrice) return;
ch->SetQuestFlag("gem.points", points - it->second.itemPrice);
it->second.itemBuyed = true;
ch->AutoGiveItem(it->second.itemVnum, it->second.itemCount);
ch->ChatPacket(0, "GemSetBuyedSlot %d 1", slot);
TestSaveItems(ch);
}
int main(int argc, char** argv) {
assert(argc > 1);
SetDir(argv[1]);
DummyChar ch;
ch.pid = 42;
ch.SetQuestFlag("gem.points", 500);
// 1. Initial slot expansion
assert(ch.GetQuestFlag("gem.open_slot") == 0);
assert(TestOpenSlot(&ch));
assert(ch.GetQuestFlag("gem.open_slot") == 1);
// Max 18 additional slots (up to 18)
for (int i = 2; i <= 18; ++i) {
assert(TestOpenSlot(&ch));
assert(ch.GetQuestFlag("gem.open_slot") == i);
}
// Slot 19 should fail
assert(!TestOpenSlot(&ch));
assert(ch.GetQuestFlag("gem.open_slot") == 18);
// 2. Set up store items (slot 0 default, slot 9 locked without open_slot >= 1)
s_items[42][0] = {71084, 100, 50, false};
s_items[42][9] = {72319, 1, 20, false};
s_items[42][10] = {72320, 1, 20, false};
TestSaveItems(&ch);
// 3. Buy item from slot 0
TestBuyItem(&ch, 0);
assert(ch.GetQuestFlag("gem.points") == 450);
assert(s_items[42][0].itemBuyed == true);
assert(ch.bag.size() == 1 && ch.bag[0].vnum == 71084 && ch.bag[0].count == 100);
// Cannot buy already bought item
TestBuyItem(&ch, 0);
assert(ch.GetQuestFlag("gem.points") == 450);
assert(ch.bag.size() == 1);
// 4. Persistence round-trip: reload from disk
s_items[42].clear();
TestLoadItems(&ch);
assert(s_items[42].size() == 3);
assert(s_items[42][0].itemBuyed == true);
assert(s_items[42][9].itemVnum == 72319);
// 5. Unlocked slot 9 can be purchased
TestBuyItem(&ch, 9);
assert(ch.GetQuestFlag("gem.points") == 430);
assert(s_items[42][9].itemBuyed == true);
assert(ch.bag.size() == 2 && ch.bag[1].vnum == 72319);
puts("PASS: gaya slot expansion limit, purchase validation, persistence file io, balance deduction");
return 0;
}
'''
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / 'test_gaya.cpp'
exe = Path(tmp) / 'test_gaya'
gemdir = Path(tmp) / 'gem'
src.write_text(harness)
subprocess.run(['c++', '-std=c++17', '-I' + str(ROOT), str(src), '-o', str(exe)], check=True)
res = subprocess.run([str(exe), str(gemdir)], capture_output=True, text=True, check=True)
self.assertIn('PASS', res.stdout)
if __name__ == '__main__':
+109
View File
@@ -0,0 +1,109 @@
"""Execute the production Gaya unit; SQL, item factory and DB submission are boundaries."""
import re
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
class GayaRuntime(unittest.TestCase):
def test_durable_requests_never_mutate_wallet_items_or_paid_catalogue_in_game(self):
body=re.sub(r'^#include[^\n]*\n','',(ROOT/'src/server/game/src/port_gaya.cpp').read_text(),flags=re.M)
harness=r'''
#include "src/server/game/src/port_gaya.h"
#include "src/server/common/gaya_catalog.h"
#include "src/server/common/economy.h"
#include "src/server/common/utils.h"
#include <algorithm>
#include <cassert>
#include <climits>
#include <cstdarg>
#include <cstring>
#include <fstream>
#include <memory>
#include <vector>
#include <unistd.h>
using BYTE=uint8_t;
constexpr int POINT_GEM=248,CHAT_TYPE_COMMAND=1,CHAT_TYPE_INFO=2,DRAGON_SOUL_INVENTORY=2,INVENTORY=1,ER_NO_SUCH_TABLE=1146;
bool questLoaded=true,questRunning=false;
namespace quest {struct PC{bool IsLoaded(){return questLoaded;}bool IsRunning(){return questRunning;}};struct CQuestManager{PC pc;static CQuestManager& instance(){static CQuestManager m;return m;}PC* GetPCForce(unsigned){return &pc;}};}
struct PortItemExtra{uint8_t bytes[69]={};};
struct Attr{uint8_t bType=0;int16_t sValue=0;};
struct Item {unsigned id=0,vnum=0,count=1;bool skip=false,locked=false;PortItemExtra extra;Attr attrs[7];
unsigned GetID(){return id;}unsigned GetOriginalVnum(){return vnum;}unsigned GetCount(){return count;}
void SetSkipSave(bool v){skip=v;}bool isLocked(){return locked;}bool IsExchanging(){return false;}
int32_t GetSocket(unsigned i){return static_cast<int32_t>(i+10);}const Attr* GetAttributes(){return attrs;}
const PortItemExtra& GetPortExtra(){return extra;}
};using LPITEM=Item*;
struct CHARACTER {
unsigned pid=1;int balance=500,open=0,points=500,left=0,refreshItems=2;bool itemLoaded=true,busy=false;
Item consumable;std::vector<std::string> messages;
int GetQuestFlag(const char* k){return std::string(k)=="gem.points"?balance:std::string(k)=="gem.left_time"?left:open;}
void SetQuestFlag(const char* k,int n){if(std::string(k)=="gem.points")balance=n;else if(std::string(k)=="gem.left_time")left=n;else open=n;}
void SetPoint(int,int n){points=n;}void PointChange(int,int){}unsigned GetPlayerID(){return pid;}
void ChatPacket(int,const char* fmt,...){char out[1024];va_list ap;va_start(ap,fmt);vsnprintf(out,sizeof(out),fmt,ap);va_end(ap);messages.emplace_back(out);}
bool CanHandleItem(){return !busy;}bool IsDead(){return false;}bool IsStun(){return false;}bool IsWarping(){return false;}
bool GetExchange(){return false;}bool GetMyShop(){return false;}bool GetShop(){return false;}bool IsOpenSafebox(){return false;}bool IsCubeOpen(){return false;}
bool IsItemLoaded(){return itemLoaded;}bool IsPC(){return true;}bool GetDesc(){return true;}
int CountSpecifyItem(int){return refreshItems;}Item* FindSpecifyItem(unsigned vnum){consumable.id=vnum;return refreshItems?&consumable:nullptr;}
int GetGem()const;void ChangeGem(int);bool OpenGemSlot();bool RefreshGemALL(bool=false);void RefreshGemPlayer();void BuyGemItem(BYTE);
};
struct ITEM_MANAGER {bool failCreate=false;unsigned next=1000,created=0,destroyed=0;
static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;}
Item* CreateItem(unsigned vnum,unsigned count){if(failCreate)return nullptr;Item* i=new Item;i->id=next++;i->vnum=vnum;i->count=std::min(count,200u);++created;return i;}
void Destroy(Item* i){assert(i->skip);++destroyed;delete i;}
};
#define M2_DESTROY_ITEM(i) ITEM_MANAGER::instance().Destroy(i)
#define sys_err(...) ((void)0)
#define ACMD(name) void name(CHARACTER* ch,const char* argument,int cmd=0,int subcmd=0)
bool failRng=false;unsigned draws=0;int number(int low,int high){return !failRng && (++draws%101==0)?high:low;}
std::vector<PortEconomy::Request> requests;bool queueReady=true;
bool PortEconomySubmit(CHARACTER*,PortEconomy::Request& r){if(!queueReady)return false;requests.push_back(r);return true;}
using MYSQL_ROW=char**;
struct MYSQL_RES {char* row[3];unsigned long lengths[3];};
MYSQL_ROW mysql_fetch_row(MYSQL_RES* r){return r->row;}const unsigned long* mysql_fetch_lengths(MYSQL_RES* r){return r->lengths;}
std::string sqlGeneration="9";bool sqlCatalogue=false;unsigned sqlError=0;PortEconomy::Offer sqlOffers[27];
struct SQLResult {uint64_t uiNumRows=0;MYSQL_RES* pSQLResult=nullptr;};
struct SQLMsg {unsigned uiSQLErrno=0;SQLResult result;MYSQL_RES res;std::string generation=sqlGeneration,deadline="2000000000";
SQLResult* Get(){return &result;}
SQLMsg(){if(sqlError){uiSQLErrno=sqlError;return;}if(!sqlCatalogue){uiSQLErrno=ER_NO_SUCH_TABLE;return;}result.uiNumRows=1;result.pSQLResult=&res;res.row[0]=&generation[0];res.row[1]=&deadline[0];res.row[2]=reinterpret_cast<char*>(sqlOffers);res.lengths[0]=1;res.lengths[1]=10;res.lengths[2]=sizeof(sqlOffers);}
};
struct DBManager {static DBManager& instance(){static DBManager m;return m;}SQLMsg* DirectQuery(const char* q,...){auto* msg=new SQLMsg;if(std::string(q).find("information_schema")!=std::string::npos&&!sqlError){msg->uiSQLErrno=0;msg->generation=sqlCatalogue?"1":"0";msg->result.uiNumRows=1;msg->result.pSQLResult=&msg->res;msg->res.row[0]=msg->generation.data();}return msg;}};
'''
main=r'''
int main(int argc,char** argv){
std::string dir=argv[1];PortGayaSetDirectory(dir);CHARACTER ch;
assert(ch.RefreshGemALL(true));assert(s_playerGayaItems[1].size()==27 && requests.empty());
auto& offers=s_playerGayaItems[1];offers[0]={19,2000,50,false};assert(PortGayaSaveItems(&ch));int original=ch.left;
auto unchanged=[&](){assert(ch.balance==500 && ch.points==500 && !s_playerGayaItems[1][0].itemBuyed && ch.left==original);};
ch.itemLoaded=false;ch.BuyGemItem(0);assert(requests.empty());ch.itemLoaded=true;questLoaded=false;ch.BuyGemItem(0);assert(requests.empty());questLoaded=true;
questRunning=true;ch.BuyGemItem(0);assert(requests.empty());questRunning=false;ch.busy=true;ch.BuyGemItem(0);assert(requests.empty());ch.busy=false;
ITEM_MANAGER::instance().failCreate=true;ch.BuyGemItem(0);assert(requests.empty());ITEM_MANAGER::instance().failCreate=false;
do_gem(&ch,"buy 256");do_gem(&ch,"buy -1");do_gem(&ch,"buy 0 junk");ch.BuyGemItem(9);assert(requests.empty());
ch.BuyGemItem(0);unchanged();assert(requests.size()==1);const auto buy=requests.back();assert(buy.operation==PortEconomy::GayaBuy && buy.rewardCount==10 && buy.generation==0);
unsigned count=0;for(unsigned i=0;i<buy.rewardCount;++i){count+=buy.rewards[i].count;assert(buy.rewards[i].id && buy.rewards[i].vnum==19 && buy.rewards[i].sockets[0]==10);}assert(count==2000);
assert(ITEM_MANAGER::instance().created==ITEM_MANAGER::instance().destroyed);
requests.clear();queueReady=false;ch.BuyGemItem(0);unchanged();assert(requests.empty());queueReady=true;
// Paid refresh and slot expansion only queue intents; the DB consumes items.
do_gem(&ch,"refresh");assert(requests.size()==1 && requests.back().operation==PortEconomy::GayaRefresh && requests.back().item==39063);assert(ch.refreshItems==2);unchanged();
requests.clear();ch.open=17;assert(ch.OpenGemSlot());assert(ch.open==17 && requests.back().operation==PortEconomy::GayaExpand && requests.back().item==39064);
requests.clear();ch.open=18;assert(!ch.OpenGemSlot() && requests.empty());
// Committed SQL catalogue wins even when an old local file is corrupt.
PortGayaForgetPlayer(1);{std::ofstream out(dir+"/1");out<<"corrupt";}for(auto& offer:sqlOffers)offer={200,200,50,0};sqlOffers[0].bought=1;sqlCatalogue=true;
assert(PortGayaLoadItems(&ch));assert(s_databaseGeneration[1]==9 && s_playerGayaItems[1][0].itemBuyed && ch.left==2000000000);assert(!PortGayaSaveItems(&ch));
ch.BuyGemItem(0);assert(requests.empty());ch.BuyGemItem(1);assert(requests.size()==1 && requests.back().generation==9);
PortGayaForgetPlayer(1);sqlError=2006;assert(!PortGayaLoadItems(&ch));sqlError=0;
PortGayaChange(&ch,INT_MIN);assert(ch.balance==500);PortGayaChange(&ch,INT_MAX);assert(ch.balance==500);
PortGayaForgetPlayer(1);sqlGeneration=std::to_string(PortEconomy::RetiredGeneration);requests.clear();
assert(!PortGayaLoadItems(&ch));assert(!PortGayaLoadItems(&ch));
ch.BuyGemItem(1);ch.open=0;assert(!ch.OpenGemSlot());assert(!ch.RefreshGemALL(false));PortGayaChange(&ch,1);
assert(requests.empty() && ch.balance==500); // old local files cannot resurrect retired SQL catalogue
PortGayaForgetPlayer(1);
}
'''
with tempfile.TemporaryDirectory() as tmp:
src=Path(tmp)/'probe.cpp';exe=Path(tmp)/'probe';src.write_text(harness+body+main)
subprocess.run(['c++','-std=c++17','-fsanitize=undefined,address','-fno-sanitize-recover=all','-I'+str(ROOT),str(src),'-o',str(exe)],check=True)
subprocess.run([str(exe),str(Path(tmp)/'gem')],check=True)
if __name__=='__main__':unittest.main()
+23 -39
View File
@@ -50,7 +50,7 @@ class TestGold64System(unittest.TestCase):
self.assertTrue(re.search(r'void\s+SetGold\s*\(\s*int64_t\s+gold\s*\)\s*\{\s*m_points\.gold\s*=\s*gold;\s*\}', char_h))
self.assertTrue(re.search(r'bool\s+DropGold\s*\(\s*int64_t\s+gold\s*\);', char_h))
self.assertTrue(re.search(r'int64_t\s+GetAllowedGold\s*\(\)\s*const;', char_h))
self.assertTrue(re.search(r'void\s+GiveGold\s*\(\s*int64_t\s+iAmount\s*\);', char_h))
self.assertTrue(re.search(r'bool\s+GiveGold\s*\(\s*int64_t\s+iAmount\s*\);', char_h))
self.assertTrue(re.search(r'void\s+LoadSafebox\s*\(\s*int\s+iSize,\s*int64_t\s+dwGold,', char_h))
safebox_h = read_server_file("src/server/game/src/safebox.h")
@@ -87,29 +87,29 @@ class TestGold64System(unittest.TestCase):
def test_overflow_and_security_guards(self):
char_cpp = read_server_file("src/server/game/src/char.cpp")
self.assertIn("if (amount > 0 && GetGold() > GOLD_MAX_64 - amount)", char_cpp)
self.assertIn("else if (amount < 0 && -amount > GetGold())", char_cpp)
self.assertIn("if (GOLD_MAX_64 <= nTotalMoney)", char_cpp)
self.assertTrue("PortGoldCanChange(GetGold(),amount,GOLD_MAX_64)" in char_cpp)
self.assertNotIn("else if (amount < 0 && -amount > GetGold())", char_cpp)
self.assertIn("!PortGoldCanChange(nTotalMoney, price, GOLD_MAX_64)", char_cpp)
exchange_cpp = read_server_file("src/server/game/src/exchange.cpp")
self.assertIn("if (m_lGold > 0 && victim->GetGold() > GOLD_MAX_64 - m_lGold)", exchange_cpp)
self.assertIn("DWORD dwPacketGold = (m_lGold > 2000000000LL) ? 2000000000 : (DWORD)m_lGold;", exchange_cpp)
self.assertTrue("int64_t dwPacketGold = m_lGold;" in exchange_cpp)
shop_cpp = read_server_file("src/server/game/src/shop_manager.cpp")
self.assertIn("if (GOLD_MAX_64 <= nTotalMoney)", shop_cpp)
self.assertIn("!PortGoldCanChange(ch->GetGold(), dwPrice, GOLD_MAX_64)", shop_cpp)
offlineshop_cpp = read_server_file("src/server/game/src/offlineshop_manager.cpp")
self.assertIn("if (GOLD_MAX_64 <= nTotalMoney)", offlineshop_cpp)
input_main_cpp = read_server_file("src/server/game/src/input_main.cpp")
self.assertIn("if (ch->GetGold() >= GOLD_MAX_64)", input_main_cpp)
self.assertIn("if (GOLD_MAX_64 <= nTotalGold)", input_main_cpp)
self.assertTrue("pinfo->arg1 > GOLD_MAX_64-" in input_main_cpp)
guild_cpp = read_server_file("src/server/game/src/guild.cpp")
self.assertIn("if (m_data.gold > GOLD_MAX_64 - iGold)", guild_cpp)
self.assertIn("if (ch->GetGold() > GOLD_MAX_64 - iGold)", guild_cpp)
self.assertIn("pack_sub.gold\t= (m_data.gold > 2000000000LL) ? 2000000000 : (DWORD)m_data.gold;", guild_cpp)
self.assertIn("int packet_gold = (iGold > 2000000000LL) ? 2000000000 : (int)iGold;", guild_cpp)
self.assertTrue("pack_sub.gold\t= m_data.gold;" in guild_cpp)
self.assertTrue("int64_t packet_gold = iGold;" in guild_cpp)
def test_database_persistence_and_queries(self):
cmp_cpp = read_server_file("src/server/db/src/ClientManagerPlayer.cpp")
@@ -129,17 +129,15 @@ class TestGold64System(unittest.TestCase):
def test_sql_migration_and_rollback_scripts(self):
migrate_sql = read_server_file("tools/gold64/migrate_gold64.sql")
self.assertIn("ALTER TABLE `player` MODIFY COLUMN `gold` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0;", migrate_sql)
self.assertIn("ALTER TABLE `safebox` MODIFY COLUMN `gold` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0;", migrate_sql)
self.assertIn("ALTER TABLE `guild` MODIFY COLUMN `gold` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0;", migrate_sql)
self.assertIn("SIGNAL SQLSTATE", migrate_sql)
planner=read_server_file("tools/gold64/migrate_gold64.py")
self.assertIn("'player_deleted'", planner)
self.assertIn("'money_log'", planner)
self.assertNotIn("UPDATE `player` SET `gold`", planner)
rollback_sql = read_server_file("tools/gold64/rollback_gold64.sql")
self.assertIn("UPDATE `player` SET `gold` = 2000000000 WHERE `gold` > 2000000000;", rollback_sql)
self.assertIn("UPDATE `safebox` SET `gold` = 2000000000 WHERE `gold` > 2000000000;", rollback_sql)
self.assertIn("UPDATE `guild` SET `gold` = 2000000000 WHERE `gold` > 2000000000;", rollback_sql)
self.assertIn("ALTER TABLE `player` MODIFY COLUMN `gold` INT(11) NOT NULL DEFAULT 0;", rollback_sql)
self.assertIn("ALTER TABLE `safebox` MODIFY COLUMN `gold` INT(11) NOT NULL DEFAULT 0;", rollback_sql)
self.assertIn("ALTER TABLE `guild` MODIFY COLUMN `gold` INT(11) NOT NULL DEFAULT 0;", rollback_sql)
self.assertNotRegex(rollback_sql, r'(?im)^\s*(UPDATE|ALTER|DELETE|TRUNCATE)\b')
self.assertIn("compatible", rollback_sql)
def test_client_python_64bit_bridging(self):
if os.path.exists(CLIENT_ROOT):
@@ -172,26 +170,12 @@ class TestGold64System(unittest.TestCase):
static const int64_t GOLD_MAX_64 = 2000000000000000LL;
static const int64_t LEGACY_GOLD_MAX = 2000000000LL;
#include "src/server/common/gold_bounds.h"
struct MockCharacter {
int64_t gold;
MockCharacter(int64_t initial_gold = 0) : gold(initial_gold) {}
bool PointChange(int64_t amount) {
if (amount > 0 && gold > GOLD_MAX_64 - amount) {
gold = GOLD_MAX_64;
return false;
} else if (amount < 0 && -amount > gold) {
gold = 0;
return false;
}
gold += amount;
return true;
}
int32_t GetLegacyClampedGold() const {
return (gold > LEGACY_GOLD_MAX) ? (int32_t)LEGACY_GOLD_MAX : (int32_t)gold;
}
MockCharacter(int64_t value=0):gold(value){}
bool PointChange(int64_t delta){if(!PortGoldCanChange(gold,delta,GOLD_MAX_64))return false;gold+=delta;return true;}
int32_t GetLegacyClampedGold(){return gold>LEGACY_GOLD_MAX?LEGACY_GOLD_MAX:gold;}
};
int main() {
@@ -225,13 +209,13 @@ int main() {
MockCharacter richPlayer(GOLD_MAX_64 - 1000LL);
bool overflowBlocked = richPlayer.PointChange(2000LL);
assert(!overflowBlocked);
assert(richPlayer.gold == GOLD_MAX_64);
assert(richPlayer.gold == GOLD_MAX_64 - 1000LL);
// 4. Underflow protection
MockCharacter poorPlayer(500LL);
bool underflowBlocked = poorPlayer.PointChange(-1000LL);
assert(!underflowBlocked);
assert(poorPlayer.gold == 0);
assert(poorPlayer.gold == 500);
// 5. Cold restart persistence (100 billion gold)
int64_t originalGold = 100000000000LL; // 100B
@@ -264,7 +248,7 @@ int main() {
with open(src_file, "w") as f:
f.write(cxx_code)
compile_cmd = ["clang++", "-std=c++17", "-O2", src_file, "-o", bin_file]
compile_cmd = ["clang++", "-std=c++17", "-I"+SERVER_ROOT, "-O2", src_file, "-o", bin_file]
res = subprocess.run(compile_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
self.assertEqual(res.returncode, 0, f"Compilation failed: {res.stderr}")
+54 -220
View File
@@ -29,229 +29,63 @@ class ItemShopDurableTest(unittest.TestCase):
def test_game_durable_log_and_recovery(self):
harness = r'''
#include "src/server/common/ava2_itemshop.h"
#include <map>
#include <string>
#include <vector>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <sys/stat.h>
static std::string s_pointLogPath = "";
struct PendingPoints { Ava2ShopRequest request; unsigned handle; int attempts; time_t next; };
static std::map<std::string, PendingPoints> pendingPoints;
static std::vector<Ava2ShopRequest> dispatchedPackets;
void Ava2PointDropSetLogPath(const std::string& path) { s_pointLogPath = path; }
const std::string& Ava2PointDropGetLogPath() { return s_pointLogPath; }
size_t Ava2PointPendingCount() { return pendingPoints.size(); }
bool AppendDurableIntent(const Ava2ShopRequest& r) {
if (s_pointLogPath.empty()) return false;
size_t slash = s_pointLogPath.rfind('/');
if (slash != std::string::npos) {
std::string dir = s_pointLogPath.substr(0, slash);
mkdir(dir.c_str(), 0755);
}
FILE* fp = fopen(s_pointLogPath.c_str(), "a");
if (!fp) return false;
int res = fprintf(fp, "INTENT v1 %s %u %u %u %u %u %lld\n",
r.token, r.account, r.player, r.product, r.count, r.expectedVnum, (long long)time(0));
if (res < 0) { fclose(fp); return false; }
if (fflush(fp) != 0) { fclose(fp); return false; }
if (fsync(fileno(fp)) != 0) { fclose(fp); return false; }
fclose(fp);
return true;
}
bool AppendDurableDone(const char* token, uint8_t status, uint32_t granted, int64_t balance) {
if (s_pointLogPath.empty()) return false;
FILE* fp = fopen(s_pointLogPath.c_str(), "a");
if (!fp) return false;
int res = fprintf(fp, "DONE v1 %s %u %u %lld %lld\n",
token, (unsigned)status, (unsigned)granted, (long long)balance, (long long)time(0));
if (res < 0) { fclose(fp); return false; }
if (fflush(fp) != 0) { fclose(fp); return false; }
if (fsync(fileno(fp)) != 0) { fclose(fp); return false; }
fclose(fp);
return true;
}
void CompactDurableLog() {
if (s_pointLogPath.empty()) return;
FILE* fp = fopen(s_pointLogPath.c_str(), "r");
if (!fp) return;
std::map<std::string, Ava2ShopRequest> uncompleted;
char line[256];
while (fgets(line, sizeof(line), fp)) {
char op[16] = {}, ver[16] = {}, token[64] = {};
if (sscanf(line, "%15s %15s %63s", op, ver, token) >= 3) {
if (strcmp(op, "INTENT") == 0) {
Ava2ShopRequest r = {};
r.operation = 3;
unsigned long long t = 0;
if (sscanf(line, "%*s %*s %32s %u %u %u %u %u %llu",
r.token, &r.account, &r.player, &r.product, &r.count, &r.expectedVnum, &t) >= 6) {
uncompleted[token] = r;
}
} else if (strcmp(op, "DONE") == 0) {
uncompleted.erase(token);
}
}
}
fclose(fp);
std::string tmpPath = s_pointLogPath + ".tmp";
FILE* out = fopen(tmpPath.c_str(), "w");
if (!out) return;
for (const auto& kv : uncompleted) {
const auto& r = kv.second;
fprintf(out, "INTENT v1 %s %u %u %u %u %u 0\n",
r.token, r.account, r.player, r.product, r.count, r.expectedVnum);
}
fflush(out);
fsync(fileno(out));
fclose(out);
rename(tmpPath.c_str(), s_pointLogPath.c_str());
}
void Ava2PointDropInit() {
if (s_pointLogPath.empty()) return;
FILE* fp = fopen(s_pointLogPath.c_str(), "r");
if (!fp) return;
std::map<std::string, Ava2ShopRequest> uncompleted;
char line[256];
while (fgets(line, sizeof(line), fp)) {
char op[16] = {}, ver[16] = {}, token[64] = {};
if (sscanf(line, "%15s %15s %63s", op, ver, token) >= 3) {
if (strcmp(op, "INTENT") == 0) {
Ava2ShopRequest r = {};
r.operation = 3;
unsigned long long t = 0;
if (sscanf(line, "%*s %*s %32s %u %u %u %u %u %llu",
r.token, &r.account, &r.player, &r.product, &r.count, &r.expectedVnum, &t) >= 6) {
uncompleted[token] = r;
}
} else if (strcmp(op, "DONE") == 0) {
uncompleted.erase(token);
}
}
}
fclose(fp);
for (const auto& kv : uncompleted) {
const auto& r = kv.second;
if (pendingPoints.find(r.token) == pendingPoints.end()) {
PendingPoints pending = {r, 0, 1, time(0) + 2};
pendingPoints.emplace(r.token, pending);
dispatchedPackets.push_back(r);
}
}
}
bool HandlePointReply(const char* token, uint8_t status, uint32_t amount, int64_t balance) {
auto found = pendingPoints.find(token);
if (found == pendingPoints.end()) return false;
if (status == 6 || status == 8) return true; // Transient, retry
AppendDurableDone(token, status, amount, balance);
pendingPoints.erase(found);
return true;
}
void SimulateRetryTick(time_t now) {
for (auto it = pendingPoints.begin(); it != pendingPoints.end();) {
auto& p = it->second;
if (now < p.next) { ++it; continue; }
if (p.attempts >= 12) {
// Throttled retry: reschedule, NEVER erase
p.next = now + 60;
dispatchedPackets.push_back(p.request);
++p.attempts;
++it;
continue;
}
dispatchedPackets.push_back(p.request);
++p.attempts;
p.next = now + 10;
++it;
}
}
int main(int argc, char** argv) {
assert(argc > 1);
std::string logFile = argv[1];
Ava2PointDropSetLogPath(logFile);
// 1. Record two intents and ensure both sync to disk
Ava2ShopRequest r1 = {};
r1.operation = 3; r1.account = 100; r1.player = 1001; r1.product = 101; r1.count = 5; r1.expectedVnum = 120;
strcpy(r1.token, "11111111111111111111111111111111");
Ava2ShopRequest r2 = {};
r2.operation = 3; r2.account = 200; r2.player = 2001; r2.product = 8001; r2.count = 8; r2.expectedVnum = 120;
strcpy(r2.token, "22222222222222222222222222222222");
assert(AppendDurableIntent(r1));
assert(AppendDurableIntent(r2));
pendingPoints[r1.token] = {r1, 1, 1, 0};
pendingPoints[r2.token] = {r2, 2, 1, 0};
// 2. Complete r1 successfully
assert(HandlePointReply(r1.token, 0, 5, 50));
assert(pendingPoints.find(r1.token) == pendingPoints.end());
assert(pendingPoints.find(r2.token) != pendingPoints.end());
// 3. Transient error for r2 - should remain pending
assert(HandlePointReply(r2.token, 6, 0, 0));
assert(pendingPoints.find(r2.token) != pendingPoints.end());
// 4. Retry throttling after 12 attempts - never erase!
pendingPoints[r2.token].attempts = 12;
pendingPoints[r2.token].next = 0;
SimulateRetryTick(100);
assert(pendingPoints.find(r2.token) != pendingPoints.end());
assert(pendingPoints[r2.token].next == 160); // 60s throttle interval
// 5. Simulate cold reboot / crash recovery
pendingPoints.clear();
dispatchedPackets.clear();
assert(Ava2PointPendingCount() == 0);
Ava2PointDropInit();
// r1 was DONE, r2 was NOT DONE -> r2 must be recovered with exact token!
assert(Ava2PointPendingCount() == 1);
assert(pendingPoints.find(r2.token) != pendingPoints.end());
assert(pendingPoints[r2.token].request.account == 200);
assert(pendingPoints[r2.token].request.product == 8001);
assert(pendingPoints[r2.token].request.count == 8);
assert(dispatchedPackets.size() == 1);
assert(strcmp(dispatchedPackets[0].token, r2.token) == 0);
// 6. Compact durable log
CompactDurableLog();
FILE* fp = fopen(logFile.c_str(), "r");
assert(fp != NULL);
char buf[1024];
size_t lines = 0;
while (fgets(buf, sizeof(buf), fp)) lines++;
fclose(fp);
assert(lines == 1); // Only r2 uncompleted line remains in compacted log
puts("PASS: durable point queue, atomic disk commit, throttle retention, crash recovery, compaction");
return 0;
#include <cerrno>
static bool failWrite=false,failSync=false;
static ssize_t TestWrite(int fd,const void* data,size_t n){if(failWrite){errno=ENOSPC;return -1;}return ::write(fd,data,n);}
static int TestSync(int fd){if(failSync){errno=EIO;return -1;}return ::fsync(fd);}
#define write TestWrite
#define fsync TestSync
#include "src/server/common/point_journal.h"
#undef write
#undef fsync
#include <cassert>
#include <fstream>
#include <sys/wait.h>
int main(int argc,char** argv){
std::string path=argv[1];Ava2ShopRequest request={};request.operation=3;request.account=1;request.player=2;request.product=101;request.count=1;request.expectedVnum=10;strcpy(request.token,"0123456789abcdef0123456789abcdef");
{
PointJournal journal;std::map<std::string,Ava2ShopRequest> pending;assert(journal.Open(path,pending));assert(pending.empty());
auto invalid=request;invalid.count=0;assert(!journal.Intent(invalid) && journal.Ready());
invalid=request;memset(invalid.token,'z',32);assert(!journal.Intent(invalid) && journal.Ready());
assert(!journal.Done(request.token,0,1,-1) && journal.Ready());
assert(!journal.Done(request.token,255,0,100) && journal.Ready());
assert(!journal.Done(request.token,2,1,100) && journal.Ready());
assert(journal.Intent(request));
PointJournal competitor;assert(!competitor.Open(path,pending));
failWrite=true;assert(!journal.Done(request.token,0,1,10));assert(!journal.Ready());failWrite=false;
assert(!journal.Intent(request)); // I/O failure latches until repaired/reopened.
}
{
PointJournal journal;std::map<std::string,Ava2ShopRequest> pending;assert(journal.Open(path,pending));assert(pending.size()==1);assert(pending.begin()->second.count==1);
assert(journal.Done(request.token,0,1,10));
}
{
PointJournal journal;std::map<std::string,Ava2ShopRequest> pending;assert(journal.Open(path,pending));assert(pending.empty());
failSync=true;assert(!journal.Intent(request));failSync=false;assert(!journal.Ready());
}
{
PointJournal journal;std::map<std::string,Ava2ShopRequest> pending;assert(journal.Open(path,pending));assert(pending.size()==1); // same durable token, never reroll.
}
{std::ofstream out(path,std::ios::app);out<<"INTENT v2 broken tail";}
{
PointJournal journal;std::map<std::string,Ava2ShopRequest> pending;assert(!journal.Open(path,pending));assert(pending.size()==1);assert(!journal.Intent(request));
}
// A process death after fsync but before sending the request must be recoverable.
const std::string crash=path+".crash";pid_t child=fork();assert(child>=0);
if(child==0){PointJournal j;std::map<std::string,Ava2ShopRequest> p;assert(j.Open(crash,p));assert(j.Intent(request));_exit(0);}
int status=0;waitpid(child,&status,0);assert(WIFEXITED(status)&&WEXITSTATUS(status)==0);
{PointJournal j;std::map<std::string,Ava2ShopRequest> p;assert(j.Open(crash,p));assert(p.size()==1);assert(j.Done(request.token,0,1,10));}
// Checksums reject a syntactically valid but changed amount; original bytes remain on disk.
{std::fstream out(crash,std::ios::in|std::ios::out);out.seekp(10);out.put('f');}
{PointJournal j;std::map<std::string,Ava2ShopRequest> p;assert(!j.Open(crash,p));}
puts("PASS actual point journal: replay, exclusive recovery, ENOSPC/EIO, corrupt tail/checksum, abrupt exit");
}
'''
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / 'test_durable.cpp'
exe = Path(tmp) / 'test_durable'
log = Path(tmp) / 'pending.log'
src.write_text(harness)
subprocess.run(['c++', '-std=c++17', '-I' + str(ROOT), str(src), '-o', str(exe)], check=True)
res = subprocess.run([str(exe), str(log)], capture_output=True, text=True, check=True)
self.assertIn('PASS', res.stdout)
src=Path(tmp)/'journal.cpp';exe=Path(tmp)/'journal';src.write_text(harness)
subprocess.run(['c++','-std=c++17','-I'+str(ROOT),str(src),'-o',str(exe)],check=True)
subprocess.run([str(exe),str(Path(tmp)/'pending.log')],check=True)
if __name__ == '__main__':
unittest.main()
if __name__=='__main__':unittest.main()
+60
View File
@@ -0,0 +1,60 @@
"""Actual restart range allocation reserves unmigrated legacy escrow IDs."""
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
class LegacyIDs(unittest.TestCase):
def test_legacy_new_custody_errors_and_overflow(self):
text=(ROOT/'src/server/db/src/ItemIDRangeManager.cpp').read_text(encoding='latin1')
actual=text.split('bool CItemIDRangeManager::BuildRange',1)[1].split('void CItemIDRangeManager::UpdateRange',1)[0]
actual='bool CItemIDRangeManager::BuildRange'+actual
harness=r'''
#include "src/server/common/utils.h"
#include <cassert>
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>
using DWORD=uint32_t;
using MYSQL_ROW=char**;
struct MYSQL_RES {std::string value;char* fields[1];};
MYSQL_ROW mysql_fetch_row(MYSQL_RES* r){r->fields[0]=r->value.empty()?nullptr:r->value.data();return r->fields;}
struct SQLResult {unsigned uiNumRows=1;MYSQL_RES* pSQLResult=nullptr;};
struct SQLMsg {unsigned uiSQLErrno=0;SQLResult result;MYSQL_RES res;SQLMsg(){result.pSQLResult=&res;}SQLResult* Get(){return &result;}};
constexpr unsigned ER_NO_SUCH_TABLE=1146;
bool legacy=true,economy=true,failed=false;std::string maximum="900",count="0";
std::string maxQuery;
struct CDBManager {static CDBManager& instance(){static CDBManager m;return m;}
SQLMsg* DirectQuery(const char* q){auto* m=new SQLMsg;std::string sql=q;
if(failed){m->uiSQLErrno=2006;return m;}
if(sql.find("information_schema")!=std::string::npos)m->res.value=legacy?"1":"0";
else if(sql.find("SELECT version")!=std::string::npos){m->res.value="1";if(!economy)m->uiSQLErrno=ER_NO_SUCH_TABLE;}
else if(sql.find("SELECT MAX")!=std::string::npos){m->res.value=maximum;maxQuery=sql;}
else m->res.value=count;
return m;}};
const char* GetTablePostfix(){return "";}
#define sys_log(...) ((void)0)
struct TItemIDRangeTable {DWORD dwMin=0,dwMax=0,dwUsableItemIDMin=0;};
struct CItemIDRangeManager {static constexpr DWORD cs_dwMinimumRemainCount=10000;bool BuildRange(DWORD,DWORD,TItemIDRangeTable&);};
'''
main=r'''
int main(){CItemIDRangeManager manager;TItemIDRangeTable range;
assert(manager.BuildRange(1,100000,range)&&range.dwUsableItemIDMin==901);
assert(maxQuery.find("offline_shop_item")!=std::string::npos && maxQuery.find("port_economy_custody")!=std::string::npos && maxQuery.find("port_economy_item_reservations")!=std::string::npos);
economy=false;assert(manager.BuildRange(1,100000,range));assert(maxQuery.find("offline_shop_item")!=std::string::npos && maxQuery.find("port_economy_custody")==std::string::npos);
legacy=false;assert(manager.BuildRange(1,100000,range));assert(maxQuery.find("offline_shop_item")==std::string::npos);
maximum="";assert(manager.BuildRange(1,100000,range)&&range.dwUsableItemIDMin==1);
maximum="4294967295";assert(!manager.BuildRange(1,UINT32_MAX,range));
maximum="4294967296";assert(!manager.BuildRange(1,UINT32_MAX,range));
maximum="100";count="1";assert(!manager.BuildRange(1,100000,range));
count="bad";assert(!manager.BuildRange(1,100000,range));
failed=true;assert(!manager.BuildRange(1,100000,range));
}
'''
with tempfile.TemporaryDirectory() as tmp:
p=Path(tmp);(p/'probe.cpp').write_text(harness+actual+main)
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-I'+str(ROOT),str(p/'probe.cpp'),'-o',str(p/'probe')],check=True)
subprocess.run([str(p/'probe')],check=True)
+66
View File
@@ -0,0 +1,66 @@
"""Verify the disabled candidate formula and preserve default combat dispatch."""
from pathlib import Path
import re
import subprocess
import tempfile
import unittest
SRC=Path(__file__).resolve().parents[2]/'src/server/game/src'
class MagicReductionTests(unittest.TestCase):
def test_source_formula_boundaries_and_production_dispatch(self):
wrappers=[]
for filename,name in (('char_skill.cpp','skill'),('char_battle.cpp','magic_attack')):
text=(SRC/filename).read_bytes().decode('latin1')
branch=re.search(r'#ifdef ENABLE_MAGIC_REDUCTION_SYSTEM\s+(iDam = PortMagicDamageAfterResistance\(.*?\);)\s+#else\s+(iDam = iDam \* \(100 - .*?;)\s+#endif',text,re.S)
self.assertIsNotNone(branch, filename+' must preserve default resistance formula')
statement=branch.group(1)
wrappers.append('int '+name+'(int iDam, Actor* attacker, Actor* victim) {'
'Actor *m_pkChr=attacker,*m_me=attacker,*pkChrVictim=victim,*pkVictim=victim;'
+statement+' return iDam;}')
wrappers.append('int default_'+name+'(int iDam, Actor* pkChrVictim, Actor* pkVictim) {'
+branch.group(2)+' return iDam;}')
for path in (SRC.parent.parent/'common').glob('*.h'):
self.assertIsNone(re.search(rb'^\s*#\s*define\s+ENABLE_MAGIC_REDUCTION_SYSTEM\b',path.read_bytes(),re.M),str(path))
code=r'''
#include <cassert>
#include <climits>
#include <cstdint>
#include "port_magic_reduction.h"
enum{POINT_RESIST_MAGIC=77,POINT_RESIST_MAGIC_REDUCTION=144,JOB_SURA=2};
struct Actor {int job=0;int64_t resistance=0,reduction=0;
int GetJob(){return job;}int64_t GetPoint(int type){return type==POINT_RESIST_MAGIC?resistance:reduction;}};
'''+ '\n'.join(wrappers)+r'''
int main(){
struct Case {int damage;int64_t resist,reduction;bool sura;int expected;};
const Case cases[]={
{1000,80,30,false,500},{1000,80,30,true,350},
{1000,100,0,false,0},{1000,-1,0,false,1000},
{1000,200,200,false,500},{1000,80,-3,true,200},
{1000,80,1,true,200},{999,80,3,true,209},
{1000,10,50,false,1000},{0,80,30,false,0},
{INT_MAX,0,0,false,INT_MAX},{INT_MIN,0,0,false,INT_MIN},
{1000,INT64_MAX,INT64_MAX,true,500}
};
for(const auto& c:cases){
Actor attacker,victim;attacker.job=c.sura?JOB_SURA:0;
attacker.reduction=c.reduction;victim.resistance=c.resist;
assert(PortMagicDamageAfterResistance(c.damage,c.resist,c.reduction,c.sura)==c.expected);
assert(skill(c.damage,&attacker,&victim)==c.expected);
assert(magic_attack(c.damage,&attacker,&victim)==c.expected);
}
Actor victim;victim.resistance=80;
assert(default_skill(1000,&victim,&victim)==200);
assert(default_magic_attack(1000,&victim,&victim)==200);
}
'''
with tempfile.TemporaryDirectory(prefix='ch5-magic-') as folder:
root=Path(folder);(root/'probe.cpp').write_text(code)
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined',
'-fno-sanitize-recover=all','-I'+str(SRC),str(root/'probe.cpp'),
'-o',str(root/'probe')],check=True)
subprocess.run([str(root/'probe')],check=True)
if __name__=='__main__':unittest.main()
@@ -0,0 +1,48 @@
"""Run the production localized-proto search, without a language handshake stub."""
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[2]
class SearchNames(unittest.TestCase):
def test_localized_names_reload_and_bounded_strings(self):
text=(ROOT/'src/server/game/src/offlineshop_search_manager.cpp').read_text()
methods=text[text.index('bool COfflineShopManager::CheckItemNames'):text.index('void COfflineShopManager::SaveInMemory')]
code=r'''
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstring>
#include <map>
#include <string>
#include <vector>
#include <cstdint>
using BYTE=uint8_t;using DWORD=uint32_t;using LPCHARACTER=void*;
struct TItemTable {char szLocaleName[32];DWORD dwVnum;};
struct ITEM_MANAGER {std::vector<TItemTable> tables;static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;}const auto& GetTable(){return tables;}};
struct COfflineShopManager {
std::map<BYTE,std::vector<std::pair<std::string,DWORD>>> m_mapItemNames;
bool CheckItemNames(LPCHARACTER,const char*,std::vector<DWORD>&);
void LoadSearchLanguage();
};
'''+methods+r'''
int main(){
COfflineShopManager shop;auto& tables=ITEM_MANAGER::instance().tables;
tables={{{"Dragon Sword"},10},{{"Dragon Sword"},10},{{"龍牙"},20},{{""},30}};
TItemTable full={};memset(full.szLocaleName,'x',sizeof(full.szLocaleName));full.dwVnum=40;tables.push_back(full);
shop.LoadSearchLanguage();std::vector<DWORD> found;
assert(shop.CheckItemNames(&shop,"DRAGON",found) && found==std::vector<DWORD>{10});
found.clear();assert(shop.CheckItemNames(&shop,"龍",found) && found==std::vector<DWORD>{20});
found.clear();assert(shop.CheckItemNames(&shop,"xxxx",found) && found==std::vector<DWORD>{40});
assert(!shop.CheckItemNames(nullptr,"Dragon",found));assert(!shop.CheckItemNames(&shop,nullptr,found));assert(!shop.CheckItemNames(&shop,"",found));
tables={{{"Replacement"},50}};shop.LoadSearchLanguage();found.clear();
assert(!shop.CheckItemNames(&shop,"Dragon",found));assert(shop.CheckItemNames(&shop,"replace",found) && found==std::vector<DWORD>{50});
}
'''
with tempfile.TemporaryDirectory() as tmp:
src=Path(tmp)/'probe.cpp';exe=src.with_suffix('');src.write_text(code)
subprocess.run(['c++','-std=c++23','-fsanitize=address,undefined','-fno-sanitize-recover=all',str(src),'-o',str(exe)],check=True)
subprocess.run([str(exe)],check=True)
entry=(ROOT/'src/server/game/src/input_db.cpp').read_text(encoding='latin1')
self.assertEqual(entry.count('COfflineShopManager::instance().LoadSearchLanguage();'),2)
if __name__=='__main__':unittest.main()
+63
View File
@@ -0,0 +1,63 @@
"""Exercise actual OX status/quiz functions with timer/notice boundaries."""
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
def function(text, signature):
start = text.index(signature)
brace = text.index('{', start)
depth = 1
end = brace + 1
while depth:
depth += (text[end] == '{') - (text[end] == '}')
end += 1
return text[start:end]
class OXBounds(unittest.TestCase):
def test_equal_and_excess_level_and_untruncated_status(self):
source = (ROOT/'src/server/game/src/OXEvent.cpp').read_bytes().decode('latin1')
actual = '\n'.join(function(source, s) for s in
('OXEventStatus COXEventManager::GetStatus()',
'bool COXEventManager::Quiz('))
fixture = r'''
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <limits>
#include <vector>
enum OXEventStatus {OXEVENT_FINISH,OXEVENT_OPEN,OXEVENT_CLOSE,OXEVENT_QUIZ,OXEVENT_ERR};
int flag=0;
namespace quest {struct CQuestManager {static CQuestManager& instance(){static CQuestManager m;return m;}int GetEventFlag(const char*){return flag;}};}
struct OXEventInfoData {bool answer=false;};
struct Question {const char* Quiz="test";bool answer=true;};
struct COXEventManager {std::vector<std::vector<Question>> m_vec_quiz;void* m_timedEvent=nullptr;OXEventStatus status=OXEVENT_FINISH;
OXEventStatus GetStatus();bool Quiz(unsigned char,int);void SetStatus(OXEventStatus s){status=s;}};
int number(int lo,int hi){assert(lo==0 && hi>=0);return hi;}
void SendNoticeMap(const char*,int,bool){}
constexpr int OXEVENT_MAP_INDEX=113;
void event_cancel(void** p){*p=nullptr;}
template<class T>T* AllocEventInfo(){static T data;return &data;}
void* event_create(int,OXEventInfoData*,int){static int event;return &event;}
constexpr int oxevent_timer=1;
#define LC_TEXT(s) "notice"
#define PASSES_PER_SEC(t) (t)
'''
main = r'''
int main(){COXEventManager m;assert(!m.Quiz(0,30));
for(int value:{-1,4,256,257}){flag=value;assert(m.GetStatus()==OXEVENT_ERR);}
for(int value=0;value<4;++value){flag=value;assert(m.GetStatus()==static_cast<OXEventStatus>(value));}
m.m_vec_quiz={{{"first",true}}};assert(m.Quiz(1,30));assert(m.m_vec_quiz[0].empty());
m.m_vec_quiz={{{"first",true}},{{"last",false}}};assert(m.Quiz(255,-1));
assert(m.m_vec_quiz[0].size()==1 && m.m_vec_quiz[1].empty());assert(!m.Quiz(2,30));
assert(m.Quiz(0,30));assert(m.status==OXEVENT_QUIZ);
}
'''
with tempfile.TemporaryDirectory() as tmp:
path=Path(tmp);(path/'probe.cpp').write_text(fixture+actual+main)
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined',
'-fno-sanitize-recover=all',str(path/'probe.cpp'),'-o',str(path/'probe')],check=True)
subprocess.run([str(path/'probe')],check=True)
@@ -0,0 +1,88 @@
"""Exercise the actual dynamic packet builders and SQL catalogue numeric parser."""
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[2]
class Bounds(unittest.TestCase):
def native(self,code):
with tempfile.TemporaryDirectory() as tmp:
src=Path(tmp)/'probe.cpp';exe=src.with_suffix('');src.write_text(code)
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-Werror=implicit-int-conversion','-I'+str(ROOT),str(src),'-o',str(exe)],check=True)
subprocess.run([str(exe)],check=True)
def test_dynamic_package_lengths_and_repeated_serialization(self):
text=(ROOT/'src/server/game/src/packet.h').read_text()
bodies=text[text.index('typedef struct SPacketGCHybridCryptKeys'):text.index('#ifdef _IMPROVED_PACKET_ENCRYPTION_',text.index('typedef struct SPacketGCPackageSDB'))]
self.native(r'''
#include <cassert>
#include <cstring>
#include <cstdint>
#include <climits>
#include <vector>
using BYTE=uint8_t;using WORD=uint16_t;using DWORD=uint32_t;
'''+bodies+r'''
int main(){
TPacketGCHybridCryptKeys keys;TPacketGCPackageSDB sdb;
assert(keys.KeyStreamLen==0 && !keys.pDataKeyStream && sdb.iStreamLen==0 && !sdb.m_pDataSDBStream);
std::vector<BYTE> data(65528,0xa5);keys.bHeader=0x98;sdb.bHeader=0x99;
for(int count:{-1,INT_MIN,65529,65536,INT_MAX}){
keys.KeyStreamLen=count;keys.pDataKeyStream=data.data();sdb.iStreamLen=count;sdb.m_pDataSDBStream=data.data();
assert(!keys.GetStreamSize()&&!sdb.GetStreamSize());assert(!keys.GetStreamData()&&!sdb.GetStreamData());assert(!keys.uDynamicPacketSize&&!sdb.uDynamicPacketSize);
}
for(int count:{0,1,65528}){
keys.KeyStreamLen=count;keys.pDataKeyStream=data.data();sdb.iStreamLen=count;sdb.m_pDataSDBStream=data.data();
BYTE* a=keys.GetStreamData();BYTE* b=sdb.GetStreamData();assert(a&&b);
WORD size=0;memcpy(&size,a+1,2);assert(size==7+count && keys.GetStreamSize()==size);memcpy(&size,b+1,2);assert(size==7+count && sdb.GetStreamSize()==size);
assert(a[0]==0x98&&b[0]==0x99);if(count){assert(!memcmp(a+7,data.data(),count)&&!memcmp(b+7,data.data(),count));}
}
keys.pDataKeyStream=nullptr;sdb.m_pDataSDBStream=nullptr;assert(!keys.GetStreamData()&&!sdb.GetStreamData());
}
''')
def test_discount_and_product_fields_reject_before_narrowing(self):
text=(ROOT/'src/server/db/src/Ava2ItemShop.cpp').read_text();a=text.index('bool productNumber(');b=text.index('const char* fields=',a)
self.native(r'''
#include "src/server/common/ava2_itemshop.h"
#include <cassert>
#include <cerrno>
#include <cstdlib>
#include <string>
#include <vector>
using MYSQL_ROW=char**;
'''+text[a:b]+r'''
int main(){
std::vector<std::string> fields={"1","19","1000000000000","100","0","2147483647","9223372036854775807","2147483647","0","-1"};std::vector<char*> row;
auto parse=[&](){row.clear();for(auto& field:fields)row.push_back(&field[0]);return product(row.data());};
auto p=parse();assert(p.id==1&&p.vnum==19&&p.discount==100&&p.price==1000000000000LL&&p.sold==INT64_MAX&&p.stock==-1);
for(const char* discount:{"-1","101","256","356","512","junk","100junk","","999999999999999999999999"}){fields[3]=discount;assert(!parse().id);}fields[3]="3";
for(unsigned i=0;i<fields.size();++i){auto original=fields[i];fields[i]="not a number";assert(!parse().id);fields[i]=original;}
for(auto index:{0,1}){auto original=fields[index];fields[index]="4294967296";assert(!parse().id);fields[index]=original;}
fields[2]="1000000000001";assert(!parse().id);fields[2]="0";assert(parse().id&&parse().price==0);
row.clear();for(auto& field:fields)row.push_back(&field[0]);row[3]=nullptr;assert(!product(row.data()).id);assert(!product(nullptr).id);
int64_t number=123;assert(!productNumber("256",number,0,7)&&number==123);assert(productNumber("7",number,0,7)&&number==7);
}
''')
def test_item_admission_checks_destination_instead_of_old_cell(self):
text=(ROOT/'src/server/game/src/item.cpp').read_text(encoding='latin1')
a=text.index('bool CItem::AddToCharacter');b=text.index('\n\tif (ch->GetDesc())',a)
actual=text[a:b]+'\nreturn true;\n}\n'
self.native(r'''
#include <cassert>
#include <cstdint>
#include <initializer_list>
using BYTE=uint8_t;using WORD=uint16_t;using DWORD=uint32_t;
#include "src/server/common/length.h"
using LPCHARACTER=void*;
#define sys_err(...) ((void)0)
struct CItem { WORD m_wCell=0;void* m_pOwner=nullptr;void* GetSectree(){return nullptr;}bool AddToCharacter(LPCHARACTER,TItemPos);};
'''+actual+r'''
int main(){
CItem item;
for(WORD cell:{WORD(INVENTORY_MAX_NUM),WORD(BELT_INVENTORY_SLOT_START-1),WORD(BELT_INVENTORY_SLOT_END),WORD(UINT16_MAX)})assert(!item.AddToCharacter(nullptr,TItemPos(INVENTORY,cell)));
assert(!item.AddToCharacter(nullptr,TItemPos(DRAGON_SOUL_INVENTORY,DRAGON_SOUL_INVENTORY_MAX_NUM)));
item.m_wCell=UINT16_MAX;assert(item.AddToCharacter(nullptr,TItemPos(INVENTORY,0)));
assert(item.AddToCharacter(nullptr,TItemPos(INVENTORY,BELT_INVENTORY_SLOT_START)));
assert(item.AddToCharacter(nullptr,TItemPos(DRAGON_SOUL_INVENTORY,DRAGON_SOUL_INVENTORY_MAX_NUM-1)));
}
''')
if __name__=='__main__':unittest.main()
@@ -0,0 +1,99 @@
"""Execute real growing-pet commands with failing creation/placement/actor boundaries."""
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[2]
class PetCommands(unittest.TestCase):
def test_consumption_only_after_successful_hatch_or_unlock(self):
source=(ROOT/'src/server/game/src/cmd_general.cpp').read_text(encoding='latin1')
a=source.index('static bool PortPetCommandReady');b=source.index('\n#endif',a);body=source[a:b]
harness=r'''
#include "src/server/common/utils.h"
#include "src/server/common/port_item_extra.h"
#include <cassert>
#include <cstdint>
#include <ctime>
#include <map>
#include <sstream>
#include <string>
#include <vector>
bool questLoaded=true,questRunning=false;
namespace quest {struct PC{bool IsLoaded(){return questLoaded;}bool IsRunning(){return questRunning;}};struct CQuestManager{PC pc;static CQuestManager& instance(){static CQuestManager m;return m;}PC* GetPCForce(unsigned){return &pc;}};}
using BYTE=uint8_t;using WORD=uint16_t;using DWORD=uint32_t;
constexpr int INVENTORY_MAX_NUM=225,CHARACTER_NAME_MAX_LEN=24,ITEM_PET=28,PET_LEVELABLE=1,PET_EGG=0,POINT_GOLD=11,CHAT_TYPE_INFO=1,INVENTORY=1,WEAR_PET=30,POINT_PET_SKILL_INDEX_1=20;
#define _countof(a) (sizeof(a)/sizeof(a[0]))
struct CHARACTER;struct Item;using LPITEM=Item*;using LPCHARACTER=CHARACTER*;
struct TItemPos{int cell;TItemPos(int,int c):cell(c){}};
struct TItemTable{int bType=ITEM_PET,bSubType=PET_LEVELABLE,bSize=1;};
struct Item{CHARACTER* owner=nullptr;unsigned vnum=1,count=2;int type=ITEM_PET,sub=PET_EGG;bool locked=false,exchanged=false,equipped=false,skip=false;long sockets[3]={};BYTE attr[7]={};PortItemExtra extra={};
CHARACTER* GetOwner(){return owner;}unsigned GetCount(){return count;}unsigned GetVnum(){return vnum;}int GetType(){return type;}int GetSubType(){return sub;}
bool IsEquipped(){return equipped;}bool IsExchanging(){return exchanged;}bool isLocked(){return locked;}int GetValue(int){return 53000;}
void SetCount(unsigned n){count=n;}void SetSkipSave(bool b){skip=b;}void SetNewName(const char* s){strncpy(extra.name,s,sizeof(extra.name)-1);}
void SetSocket(unsigned i,long n){if(i<3)sockets[i]=n;else extra.sockets[i-3]=n;}long GetSocket(int i){return sockets[i];}
void SetForceAttribute(unsigned i,BYTE n,int){if(i<7)attr[i]=n;else extra.types[i-7]=n;}int GetAttributeType(int i){return i<7?attr[i]:extra.types[i-7];}
void Save(){}void UpdatePacket(){}bool AddToCharacter(CHARACTER*,TItemPos);
};
struct CPetActor{Item* summon=nullptr;bool accept=true;int changes=0,evolved=0;
Item* GetSummonItem(){return summon;}void IncreaseEvolve(){++evolved;}
bool PointChange(int point,int){if(!accept)return false;++changes;summon->SetForceAttribute(point-POINT_PET_SKILL_INDEX_1,0,0);return true;}
};using LPPET=CPetActor*;
struct CPetSystem{CPetActor actor;CPetActor* GetNewPet(){return &actor;}BYTE PetItemSocketMax(DWORD){return 14;}};
struct CHARACTER{int64_t gold=500000;bool itemLoaded=true,busy=false,full=false,failAdd=false;int material=1;std::map<int,Item*> items;Item* wear=nullptr;CPetSystem system;
unsigned GetPlayerID(){return 1;}bool IsItemLoaded(){return itemLoaded;}bool IsPC(){return true;}bool GetDesc(){return true;}bool CanHandleItem(){return !busy;}bool IsDead(){return false;}bool IsStun(){return false;}bool IsWarping(){return false;}
bool GetExchange(){return false;}bool GetMyShop(){return false;}bool GetShop(){return false;}bool IsOpenSafebox(){return false;}bool IsCubeOpen(){return false;}
int64_t GetGold(){return gold;}void PointChange(int,int64_t n){assert(gold+n>=0);gold+=n;}
Item* GetInventoryItem(int p){return items.count(p)?items[p]:nullptr;}int GetEmptyInventory(int){return full?-1:2;}
template<class...T>void ChatPacket(T...){}Item* GetWear(int){return wear;}CPetSystem* GetPetSystem(){return &system;}
int CountSpecifyItem(unsigned){return material;}void RemoveSpecifyItem(unsigned,unsigned n){assert(material>=int(n));material-=n;}
};
bool Item::AddToCharacter(CHARACTER* ch,TItemPos pos){if(ch->failAdd)return false;assert(skip && extra.name[0] && sockets[1]==1);for(int j=0;j<15;++j)assert(GetAttributeType(j)==99);owner=ch;ch->items[pos.cell]=this;return true;}
struct ITEM_MANAGER{bool fail=false,validProto=true;TItemTable table;std::vector<Item*> rewards;int flushed=0;
static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;}
TItemTable* GetTable(unsigned){return validProto?&table:nullptr;}
Item* CreateItem(unsigned vnum,unsigned count){if(fail)return nullptr;Item* i=new Item;i->vnum=vnum;i->count=count;i->sub=PET_LEVELABLE;rewards.push_back(i);return i;}
void Destroy(Item* i){assert(i->skip && !i->owner);for(auto& p:rewards)if(p==i){p=nullptr;break;}delete i;}
void FlushDelayedSave(Item* i){assert(!i->skip);++flushed;}
~ITEM_MANAGER(){for(auto* i:rewards)delete i;}
};
#define M2_DESTROY_ITEM(i) ITEM_MANAGER::instance().Destroy(i)
#define ACMD(name) void name(LPCHARACTER ch,const char* argument)
bool check_name(const char* name){return strchr(name,'!')==nullptr;}
'''
main=r'''
int main(){
CHARACTER ch;Item egg,scroll;egg.owner=&ch;scroll.owner=&ch;scroll.vnum=55008;ch.items[0]=&egg;ch.items[1]=&scroll;
auto unchanged=[&](){assert(ch.gold==500000 && egg.count==2 && ch.items.size()==2 && ITEM_MANAGER::instance().flushed==0);};
for(const char* arg:{"0","0 abc extra","-1 abc","225 abc","4294967296 abc","9223372036854775808 abc","0 !bad","0 aa","0 abcdefghijklmnopqrstuvwxyz"}){do_pet_egg(&ch,arg);unchanged();}
ch.itemLoaded=false;do_pet_egg(&ch,"0 abc");unchanged();ch.itemLoaded=true;questLoaded=false;do_pet_egg(&ch,"0 abc");unchanged();questLoaded=true;questRunning=true;do_pet_egg(&ch,"0 abc");unchanged();questRunning=false;
ch.busy=true;do_pet_egg(&ch,"0 abc");unchanged();ch.busy=false;
egg.exchanged=true;do_pet_egg(&ch,"0 abc");unchanged();egg.exchanged=false;
egg.locked=true;do_pet_egg(&ch,"0 abc");unchanged();egg.locked=false;
ch.full=true;do_pet_egg(&ch,"0 abc");unchanged();ch.full=false;
auto& manager=ITEM_MANAGER::instance();manager.validProto=false;do_pet_egg(&ch,"0 abc");unchanged();manager.validProto=true;
manager.table.bSubType=PET_EGG;do_pet_egg(&ch,"0 abc");unchanged();manager.table.bSubType=PET_LEVELABLE;
manager.fail=true;do_pet_egg(&ch,"0 abc");unchanged();manager.fail=false;
ch.failAdd=true;do_pet_egg(&ch,"0 abc");unchanged();ch.failAdd=false;
do_pet_egg(&ch,"0 abc");assert(ch.gold==400000 && egg.count==1 && ch.items.size()==3 && manager.flushed==1);
Item* pet=ch.items[2];assert(!strcmp(pet->extra.name,"abc") && pet->sockets[1]==1 && pet->sockets[0]>time(0));for(unsigned j=0;j<15;++j)assert(pet->GetAttributeType(j)==99);
pet->locked=true;do_change_name(&ch,"1 2 renamed");assert(ch.gold==400000 && scroll.count==2);pet->locked=false;
for(const char* arg:{"1 2 renamed extra","-1 2 renamed","1 4294967296 renamed"})do_change_name(&ch,arg);
assert(ch.gold==400000 && scroll.count==2 && !strcmp(pet->extra.name,"abc"));
do_change_name(&ch,"1 2 renamed");assert(ch.gold==300000 && scroll.count==1 && !strcmp(pet->extra.name,"renamed"));
ch.wear=pet;pet->equipped=true;pet->sockets[1]=115;ch.system.actor.summon=pet;
ch.system.actor.accept=false;do_pet_add_slot(&ch,"3");assert(ch.material==1 && ch.system.actor.changes==0);
ch.system.actor.accept=true;for(const char* arg:{"3 extra","-1","4294967299","15"})do_pet_add_slot(&ch,arg);
assert(ch.material==1 && ch.system.actor.changes==0);
pet->locked=true;do_pet_add_slot(&ch,"3");assert(ch.material==1);pet->locked=false;
do_pet_add_slot(&ch,"3");assert(ch.material==0 && ch.system.actor.changes==1 && pet->GetAttributeType(3)==0);
pet->sockets[1]=40;ch.busy=true;do_pet_evolve(&ch,"");assert(ch.system.actor.evolved==0);ch.busy=false;
do_pet_evolve(&ch,"");assert(ch.system.actor.evolved==1);
}
'''
with tempfile.TemporaryDirectory() as tmp:
src=Path(tmp)/'probe.cpp';exe=Path(tmp)/'probe';src.write_text(harness+body+main)
subprocess.run(['c++','-std=c++17','-fsanitize=undefined,address','-fno-sanitize-recover=all','-I'+str(ROOT),str(src),'-o',str(exe)],check=True)
subprocess.run([str(exe)],check=True)
if __name__=='__main__':unittest.main()
+4 -4
View File
@@ -104,17 +104,17 @@ class TestPetSystem(unittest.TestCase):
# do_change_name
self.assertIn('ACMD(do_change_name)', cg)
self.assertIn('vecArgs.size() < 4', cg) # Out-of-bounds guard
self.assertIn('vecArgs.size() != 4', cg) # Out-of-bounds guard
self.assertIn('ch->PointChange(POINT_GOLD, -100000);', cg)
self.assertIn('scroll->GetVnum() == 55008', cg)
self.assertIn('pet->SetNewName(vecArgs[3].c_str());', cg)
# do_pet_egg
self.assertIn('ACMD(do_pet_egg)', cg)
self.assertIn('vecArgs.size() < 3', cg) # Out-of-bounds guard
self.assertIn('vecArgs.size() != 3', cg) # Out-of-bounds guard
self.assertIn('ch->GetEmptyInventory(pPetTable->bSize)', cg) # Inventory space guard
self.assertIn('item->GetType() == ITEM_PET && item->GetSubType() == PET_EGG', cg)
self.assertIn('petItem->SetSocket(0, time(0) + 60 * 60 * 24 * 30);', cg) # 30 days
self.assertIn('petItem->SetSocket(0, static_cast<long>(expiresAt));', cg) # 30 days
self.assertIn('petItem->SetSocket(1, 1);', cg) # Level 1
self.assertIn('for (BYTE j = 0; j < 15; ++j)', cg)
self.assertIn('petItem->SetForceAttribute(j, 99, 0);', cg)
@@ -129,7 +129,7 @@ class TestPetSystem(unittest.TestCase):
self.assertIn('ACMD(do_pet_add_slot)', cg)
self.assertIn('item->GetSocket(1) < 115', cg) # 115 level requirement
self.assertIn('55036', cg) # item requirement
self.assertIn('petActor->PointChange(POINT_PET_SKILL_INDEX_1 + nextIndex, 0);', cg)
self.assertIn('if (!petActor->PointChange(POINT_PET_SKILL_INDEX_1 + nextIndex, 0)) return;', cg)
def test_legacy_pet_quest_lua_isolated(self):
ql_h = source('game/src/questlua.h')
+249
View File
@@ -0,0 +1,249 @@
"""Regression checks execute the helpers and loader used by production code."""
import hashlib
import importlib.util
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[2]
def module(name,file):
spec=importlib.util.spec_from_file_location(name,ROOT/file)
result=importlib.util.module_from_spec(spec);spec.loader.exec_module(result);return result
MIG=module('planb_migration','tools/ava2-itemshop/migrate_extended_items.py')
BUILD=module('planb_build','tools/ava2-itemshop/build_isolated.py')
class PlanBSafety(unittest.TestCase):
def native(self,source):
with tempfile.TemporaryDirectory() as tmp:
src=Path(tmp)/'probe.cpp';exe=Path(tmp)/'probe';src.write_text(source)
subprocess.run(['c++','-std=c++17','-fsanitize=undefined,address','-fno-sanitize-recover=all','-I'+str(ROOT),str(src),'-o',str(exe)],check=True)
subprocess.run([str(exe)],check=True)
def test_gold_extremes_reject_without_mutation(self):
self.native(r'''
#include "src/server/common/gold_bounds.h"
#include <cassert>
#include <climits>
int main(){
const int64_t limit=2000000000000000LL;
assert(!PortGoldCanChange(500,-1000,limit));
assert(!PortGoldCanChange(500,INT64_MIN,limit));
assert(!PortGoldCanChange(500,INT64_MAX,limit));
assert(PortGoldCanChange(500,-500,limit));
assert(PortGoldCanChange(limit-1,1,limit));
assert(!PortGoldCanChange(limit,1,limit));
int64_t total=123;assert(!PortGoldTotal(INT64_MAX,UINT32_MAX,limit,total));assert(total==123);
assert(PortGoldTotal(5000000000LL,20,limit,total));assert(total==100000000000LL);
}
''')
def test_shop_quote_and_settlement_preserve_64bit_values(self):
self.native(r'''
#include "src/server/common/shop_economy.h"
#include <cassert>
#include <climits>
int main(){
const int64_t cap=2000000000000000LL;
int64_t quote=123,tax=0,proceeds=0;
assert(PortShopQuote(100000000000LL,true,cap,quote));assert(quote==300000000000LL);
assert(PortShopSettlement(quote,3,cap,tax,proceeds));
assert(tax==9000000000LL && proceeds==291000000000LL && tax+proceeds==quote);
assert(PortGoldCanChange(cap-proceeds,proceeds,cap));assert(!PortGoldCanChange(cap-proceeds+1,proceeds,cap));
assert(PortShopQuote(0,true,cap,quote) && quote==0);
quote=123;assert(!PortShopQuote(INT64_MIN,true,cap,quote) && quote==123);
assert(!PortShopQuote(INT64_MAX,true,cap,quote) && quote==123);
assert(!PortShopQuote(cap/3+1,true,cap,quote) && quote==123);
assert(PortShopSettlement(INT64_MAX,100,INT64_MAX,tax,proceeds));assert(tax==INT64_MAX && proceeds==0);
assert(PortShopSettlement(101,3,cap,tax,proceeds));assert(tax==3 && proceeds==98);
assert(!PortShopSettlement(100,-1,cap,tax,proceeds));assert(!PortShopSettlement(100,101,cap,tax,proceeds));
}
''')
def test_actual_item_loader_rejects_corruption_atomically(self):
source=(ROOT/'src/server/db/src/ClientManagerPlayer.cpp').read_text(encoding='latin1')
start=source.index('bool CreateItemTableFromRes(');end=source.index('\nsize_t CreatePlayerSaveQuery',start)
actual=source[start:end]
self.native(r'''
#include "src/server/common/port_item_extra.h"
#include <vector>
#include <string>
#include <cassert>
#include <cstdlib>
using DWORD=uint32_t;
struct Attr{uint8_t bType;int16_t sValue;};
struct TPlayerItem{uint32_t id,window,pos,count,vnum;int32_t alSockets[3];Attr aAttr[7];PortItemExtra extra;uint32_t owner;};
constexpr int ITEM_ATTRIBUTE_MAX_NUM=7;
struct CClientManager{static CClientManager& instance(){static CClientManager c;return c;}bool ValidateLoadedExtra(const TPlayerItem&,const char*){return true;}};
struct MYSQL_RES{std::vector<std::vector<std::string>> rows;unsigned index=0;std::vector<char*> row;};
using MYSQL_ROW=char**;
int mysql_num_rows(MYSQL_RES* r){return r->rows.size();}
unsigned mysql_num_fields(MYSQL_RES* r){return r->rows[0].size();}
MYSQL_ROW mysql_fetch_row(MYSQL_RES* r){r->row.clear();for(auto& s:r->rows[r->index++])r->row.push_back(&s[0]);return r->row.data();}
template<class T>void str_to_number(T& v,const char* s){v=static_cast<T>(strtoll(s,nullptr,10));}
#define sys_err(...) ((void)0)
'''+actual+r'''
int main(){
MYSQL_RES res;res.rows.resize(2,std::vector<std::string>(23,"0"));
PortItemExtra extra={};strcpy(extra.name,"pet");
for(auto& row:res.rows)row[22]=PortItemExtraHex(extra);
res.rows[1][22]="00";
std::vector<TPlayerItem> output;assert(!CreateItemTableFromRes(&res,&output,7));assert(output.empty());
res.index=0;res.rows[1][22]=PortItemExtraHex(extra);assert(CreateItemTableFromRes(&res,&output,7));assert(output.size()==2);assert(!strcmp(output[1].extra.name,"pet"));
PortItemExtra before=extra;assert(!PortItemExtraRead("00",extra));assert(!memcmp(&extra,&before,sizeof(extra)));
}
''')
def test_actual_party_gold_distribution_is_all_or_nothing_at_cap(self):
source=(ROOT/'src/server/game/src/char_item.cpp').read_text(encoding='latin1')
start=source.index('\tstruct FCountNearMember')
method=source.index('bool CHARACTER::GiveGold(int64_t iAmount)')
end=source.index('\nbool CHARACTER::PickupItem',method)
helpers='namespace NPartyPickupDistribute {\n'+source[start:method]
self.native(r'''
#include "src/server/common/gold_bounds.h"
#include <vector>
#include <cassert>
#include <cstdlib>
constexpr int64_t GOLD_MAX_64=2000000000000000LL;
constexpr int POINT_GOLD=11,PARTY_DEFAULT_RANGE=5000;
struct Party;
struct CHARACTER{int64_t balance=0;Party* party=nullptr;int64_t GetGold(){return balance;}Party* GetParty(){return party;}int GetX(){return 0;}int GetY(){return 0;}const char* GetName(){return "test";}void PointChange(int,int64_t n,bool){assert(PortGoldCanChange(balance,n,GOLD_MAX_64));balance+=n;}bool GiveGold(int64_t);};
using LPCHARACTER=CHARACTER*;using LPPARTY=Party*;
struct Party{std::vector<LPCHARACTER> members;template<class F>void ForEachOnlineMember(F& f){for(auto* c:members)f(c);}};
inline int DISTANCE_APPROX(int x,int y){return abs(x)+abs(y);}
inline bool LC_IsBrazil(){return false;}
struct LogManager{static LogManager& instance(){static LogManager m;return m;}template<class... T>void CharLog(T...){};};
#define sys_log(...) ((void)0)
'''+helpers+source[method:end]+r'''
int main(){
CHARACTER a,b;Party p;p.members={&a,&b};a.party=&p;b.party=&p;
b.balance=GOLD_MAX_64;
assert(!a.GiveGold(100));assert(a.balance==0&&b.balance==GOLD_MAX_64);
b.balance=0;assert(a.GiveGold(10000000000LL));assert(a.balance==5000000000LL&&b.balance==5000000000LL);
a.party=nullptr;a.balance=GOLD_MAX_64;assert(!a.GiveGold(1));assert(a.balance==GOLD_MAX_64);
}
''')
def test_real_64bit_integer_parser(self):
self.native(r'''
#include "src/server/common/utils.h"
#include <cassert>
#include <climits>
int main(){long long v=7;unsigned long long u=7;
assert(str_to_number(v,"-9223372036854775808")&&v==LLONG_MIN);
assert(str_to_number(v,"5000000000")&&v==5000000000LL);
assert(!str_to_number(v,"9223372036854775808")&&v==5000000000LL);
assert(!str_to_number(v,"123oops"));
assert(!str_to_number(u,"-1")&&u==7);
assert(!str_to_number(u," -1")&&u==7);
assert(!str_to_number(u,"18446744073709551616")&&u==7);
}
''')
def test_migration_identity_checksum_and_column_definition(self):
identity=['player_sb','host','3306','1','uuid']
plan={'version':2,'target':identity,'items':[[1,'EQUIPMENT',32,40,123,10,1,'']],'quickslots':[],'item_state':{'1':'0'*64}}
plan['sha256']=MIG.plan_digest(plan);MIG.validate_plan(plan,identity)
with self.assertRaises(RuntimeError):MIG.validate_plan(plan,identity[:-1]+['different'])
plan['items'][0][6]=2
with self.assertRaises(RuntimeError):MIG.validate_plan(plan,identity)
good=[['port_extra','varbinary(69)','NO','','','']]
self.assertTrue(MIG.validate_extra_schema(good))
for name in ('blob','varchar(69)','varbinary(68)'):
with self.assertRaises(RuntimeError):MIG.validate_extra_schema([['port_extra',name,'NO','','','']])
with tempfile.TemporaryDirectory() as tmp:
path=Path(tmp)/'plan.json';MIG.atomic_json(path,plan)
self.assertEqual(json.loads(path.read_text()),plan)
self.assertEqual(path.stat().st_mode & 0o777,0o600)
def test_real_migration_control_flow_recovers_without_double_shift(self):
# This exercises main/SQL ordering, not MySQL's own transaction or DDL behavior.
from unittest.mock import patch
from types import SimpleNamespace
backend={'pos':32,'done':False,'crash':True,'updates':0,'owner':10}
def execute(command,**kwargs):
q=kwargs['input']
rows=[]
if q.startswith('SELECT DATABASE()'):rows=[['player_sb','host','3306','1','uuid']]
elif q.startswith('SHOW COLUMNS'):rows=[['port_extra','varbinary(69)','NO','','','']]
elif q.startswith('SELECT name FROM mt_migration'):
rows=[['ava2-shop-wear-40']] if backend['done'] else []
elif q.startswith('SELECT id,window,pos,vnum'):rows=[['1','EQUIPMENT',str(backend['pos']),'123',str(backend['owner']),'1','','0'*64]]
elif q.startswith('SELECT window,pos,vnum'):rows=[['EQUIPMENT',str(backend['pos']),'123',str(backend['owner']),'1','','0'*64]]
elif q.startswith('SELECT pos FROM item'):rows=[[str(backend['pos'])]]
elif q.startswith('UPDATE item SET'):
backend['updates']+=1;backend['pos']=40
if backend['crash']:
backend['crash']=False
raise subprocess.CalledProcessError(1,command)
elif q.startswith('INSERT IGNORE INTO mt_migration(name'):backend['done']=True
elif q.startswith(('CREATE TABLE','INSERT IGNORE INTO mt_migration_target','SELECT i.id','SELECT id FROM item WHERE','SELECT id,HEX(quickslot)')):pass
else:raise AssertionError('Unexpected SQL: '+q)
return SimpleNamespace(stdout=''.join('\t'.join(r)+'\n' for r in rows))
with tempfile.TemporaryDirectory() as tmp:
plan=Path(tmp)/'plan.json';args=['migrate','--player','player_sb','--plan',str(plan),'--apply','--offline','--backup-id','backup-1']
with patch.object(MIG.subprocess,'run',side_effect=execute),patch('sys.argv',args):
with self.assertRaises(subprocess.CalledProcessError):MIG.main()
self.assertTrue(plan.exists());self.assertFalse(backend['done']);self.assertEqual(backend['pos'],40)
MIG.main();self.assertTrue(backend['done']);self.assertEqual(backend['pos'],40)
backend['owner']=99;before=backend['updates']
with self.assertRaises(RuntimeError):MIG.main()
self.assertEqual(backend['updates'],before)
def test_fresh_build_binding_dependencies_and_warnings(self):
with tempfile.TemporaryDirectory() as tmp:
base=Path(tmp);source=base/'source';out=base/'output'
for part in ('game','db'):
d=source/'server'/part/'src';d.mkdir(parents=True);(d/'Makefile').write_text('CFLAGS = -w -m32\nDepend: .obj/a.o OBJDIR/b.o\n')
(source/'extern').mkdir();archive=source/'extern/libfixture.a';archive.write_bytes(b'fixture')
manifest={'source_sha256':BUILD.source_digest(source),'archives':{'extern/libfixture.a':BUILD.digest(archive)}}
run,snapshot,rev=BUILD.prepare(source,out,'game',manifest,True)
flags=(snapshot/'server/game/src/Makefile').read_text()
self.assertNotIn(' -w ',flags);self.assertIn('-Wformat=2',flags);self.assertIn('-Werror=shorten-64-to-32',flags);self.assertIn('$(OBJDIR)/a.o',flags)
with self.assertRaises(FileExistsError):BUILD.prepare(source,out,'game',manifest,True)
BUILD.prepare(source,out,'db',manifest)
system=base/'system.a';system.write_bytes(b'system archive')
manifest['system_archives']={str(system):BUILD.digest(system)}
BUILD.validate_dependencies(source,manifest,BUILD.source_digest(source))
system.write_bytes(b'foreign archive')
with self.assertRaises(ValueError):BUILD.validate_dependencies(source,manifest,BUILD.source_digest(source))
manifest.pop('system_archives')
archive.write_bytes(b'changed')
with self.assertRaises(ValueError):BUILD.prepare(source,base/'other','game',manifest)
def test_build_records_binary_after_make_moves_it_to_bin(self):
from unittest.mock import patch
with tempfile.TemporaryDirectory() as tmp:
base=Path(tmp);source=base/'source';out=base/'output'
for part in ('game','db'):
d=source/'server'/part/'src';d.mkdir(parents=True);(d/'Makefile').write_text('CFLAGS = -w -m32\n')
(source/'extern').mkdir();archive=source/'extern/libfixture.a';archive.write_bytes(b'fixture')
manifest=base/'dependencies.json'
manifest.write_text(json.dumps({'source_sha256':BUILD.source_digest(source),'archives':{'extern/libfixture.a':BUILD.digest(archive)}}))
for target in ('game','db'):
def make(cmd,**kwargs):
values=dict(arg.split('=',1) for arg in cmd if '=' in arg)
destination=Path(values['GAMEDIR' if target=='game' else 'DBDIR'])/target
self.assertEqual(destination.parent.parent,out.resolve()/(target+'-release'))
destination.write_bytes(b'candidate')
return subprocess.CompletedProcess(cmd,0)
argv=['build','--source',str(source),'--output',str(out),'--target',target,'--dependency-manifest',str(manifest)]
with patch('sys.argv',argv),patch.object(BUILD.platform,'system',return_value='FreeBSD'),patch.object(BUILD.subprocess,'run',side_effect=make),patch.object(BUILD.subprocess,'check_output',return_value='test compiler'):
BUILD.main()
result=json.loads((out/(target+'-release')/'result.json').read_text())
self.assertEqual(result['status'],'PASS')
self.assertEqual(Path(result['binary']),out.resolve()/(target+'-release')/'bin'/target)
def test_gold_migration_rejects_unexpected_column_kinds(self):
planner=module('gold_plan','tools/gold64/migrate_gold64.py')
for kind in ('int(11)','bigint(20) unsigned','bigint'):
planner.validate_column(kind)
for kind in ('varchar(32)','decimal(20,2)','int(11); DROP TABLE player','float'):
with self.assertRaises(ValueError):planner.validate_column(kind)
def test_offline_unverified_economy_cannot_be_enabled_by_runtime_flag(self):
self.native('#include "src/server/common/offline_shop_safety.h"\n#include <cassert>\nint main(){assert(!PortOfflineShopEconomyReady());}')
@@ -0,0 +1,93 @@
"""Execute production journal compaction, including fault and crash boundaries."""
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[2]
class PointJournalCompaction(unittest.TestCase):
def test_atomic_compaction_never_loses_unsettled_intents(self):
code=r'''
#include <unistd.h>
#include <fcntl.h>
#include <cerrno>
#include <cstdio>
static int syncCount=0,failSync=0,crash=0;static bool writeFailure=false,renameFailure=false,interruptOnce=false;static size_t allowance=0;
static ssize_t Write(int fd,const void* bytes,size_t count){
if(interruptOnce){interruptOnce=false;errno=EINTR;return -1;}
if(writeFailure){if(!allowance){errno=ENOSPC;return -1;}if(count>allowance)count=allowance;allowance-=count;}
return ::write(fd,bytes,count);
}
static int Sync(int fd){++syncCount;if(syncCount==failSync){errno=EIO;return -1;}int result=::fsync(fd);if(crash==1 && syncCount==1)_exit(0);return result;}
static int Rename(int a,const char* b,int c,const char* d){if(renameFailure){errno=EIO;return -1;}int result=::renameat(a,b,c,d);if(crash==2 && result==0)_exit(0);return result;}
#define write Write
#define fsync Sync
#define renameat Rename
#include "src/server/common/point_journal.h"
#undef write
#undef fsync
#undef renameat
#include <cassert>
#include <fstream>
#include <sys/wait.h>
std::string read(const std::string& path){std::ifstream in(path);return std::string((std::istreambuf_iterator<char>(in)),{});}
void write(const std::string& path,const std::string& text){std::ofstream out(path);out<<text;}
const std::string token="0123456789abcdef0123456789abcdef",other="1123456789abcdef0123456789abcdef";
std::string intent(const std::string& t){return "INTENT v1 "+t+" 1 2 3 8 10 123\n";}
std::string done(const std::string& t){return "DONE v1 "+t+" 0 8 100 124\n";}
int main(int argc,char** argv){
const std::string path=argv[1];const std::string history=intent(token)+done(token)+intent(other);
write(path,history);
{
PointJournal journal;std::map<std::string,Ava2ShopRequest> pending;assert(journal.Open(path,pending));assert(pending.size()==1 && !journal.NeedsCompaction());
auto invalid=pending.begin()->second;invalid.count=9;assert(!journal.Intent(invalid) && journal.Ready());assert(read(path)==history);
assert(!journal.Done(other.c_str(),0,9,100) && journal.Ready());assert(read(path)==history);
interruptOnce=true;assert(journal.Compact() && journal.Ready());
assert(read(path).find("INTENT v2 "+other+" 1 2 3 8 10 123 ")==0 && read(path).find("DONE")==std::string::npos);
PointJournal competitor;assert(!competitor.Open(path,pending));
int direct=open(path.c_str(),O_RDWR);assert(direct>=0 && flock(direct,LOCK_EX|LOCK_NB)!=0);close(direct);
assert(journal.Done(other.c_str(),0,8,100));assert(journal.Compact() && read(path).empty());
}
for(int fault=0;fault<5;++fault){
write(path,history);{PointJournal journal;std::map<std::string,Ava2ShopRequest> p;assert(journal.Open(path,p));
syncCount=0;failSync=fault==1?1:fault==3?2:0;writeFailure=fault==0;allowance=7;renameFailure=fault==2;
const std::string temporary=path+".compact."+std::to_string(getpid());
if(fault==4)write(temporary,"do not replace a pre-existing file");
assert(!journal.Compact() && !journal.Ready());
failSync=0;writeFailure=false;renameFailure=false;
if(fault!=3)assert(read(path)==history);else assert(read(path).find("DONE")==std::string::npos);
if(fault==4){assert(read(temporary)=="do not replace a pre-existing file");unlink(temporary.c_str());}
}
PointJournal recovery;std::map<std::string,Ava2ShopRequest> p;assert(recovery.Open(path,p));assert(p.size()==1 && p.begin()->first==other && p.begin()->second.count==8);
}
for(int boundary=1;boundary<=2;++boundary){
write(path,history);pid_t child=fork();assert(child>=0);
if(child==0){PointJournal journal;std::map<std::string,Ava2ShopRequest> p;assert(journal.Open(path,p));syncCount=0;crash=boundary;journal.Compact();_exit(9);}
int status=0;waitpid(child,&status,0);assert(WIFEXITED(status)&&WEXITSTATUS(status)==0);
PointJournal recovery;std::map<std::string,Ava2ShopRequest> p;assert(recovery.Open(path,p));assert(p.size()==1&&p.begin()->first==other);assert(recovery.Compact());
}
// A large active queue must not be truncated to 4096 during replacement.
{std::ofstream out(path);for(unsigned i=1;i<=5000;++i){char t[33];snprintf(t,sizeof(t),"%032x",i);out<<intent(t);}}
{PointJournal journal;std::map<std::string,Ava2ShopRequest> p;assert(journal.Open(path,p)&&p.size()==5000);assert(journal.Compact());}
{PointJournal journal;std::map<std::string,Ava2ShopRequest> p;assert(journal.Open(path,p)&&p.size()==5000);}
{std::ofstream out(path);for(unsigned i=0;i<12000;++i)out<<intent(token)<<done(token);out<<intent(other);}
{PointJournal journal;std::map<std::string,Ava2ShopRequest> p;assert(journal.Open(path,p)&&p.size()==1&&journal.NeedsCompaction());assert(journal.Compact()&&!journal.NeedsCompaction());}
// Reject invalid legacy numeric/status records too; compaction cannot sanitize corruption.
for(const auto& invalid:{"INTENT v1 "+token+" -1 2 3 8 10 123\n",intent(other)+"DONE v1 "+other+" 6 0 100 124\n",intent(other)+"DONE v1 "+other+" 0 9 100 124\n"}){
write(path,invalid);PointJournal journal;std::map<std::string,Ava2ShopRequest> p;assert(!journal.Open(path,p));assert(!journal.Compact() && read(path)==invalid);
}
unlink((path+".lock").c_str());symlink("/does/not/exist",(path+".lock").c_str());
{PointJournal journal;std::map<std::string,Ava2ShopRequest> p;assert(!journal.Open(path,p));}
}
'''
with tempfile.TemporaryDirectory() as tmp:
src=Path(tmp)/'probe.cpp';exe=src.with_suffix('');src.write_text(code)
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-Werror=implicit-int-conversion','-I'+str(ROOT),str(src),'-o',str(exe)],check=True)
subprocess.run([str(exe),str(Path(tmp)/'pending.log')],check=True)
def test_maintenance_is_wired_to_startup_and_retry(self):
text=(ROOT/'src/server/game/src/ava2_itemshop.cpp').read_text()
self.assertIn('pointJournal.NeedsCompaction()',text[text.index('EVENTFUNC(RetryPoints)'):text.index('bool PointReply(')])
self.assertIn('pointJournal.NeedsCompaction()',text[text.index('void Ava2PointDropInit()'):text.index('void Ava2PointDrop(CHARACTER*')])
if __name__=='__main__':unittest.main()
@@ -0,0 +1,53 @@
"""Run the game completion handler: malformed or unpersisted results stay pending."""
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[2]
class PointReply(unittest.TestCase):
def test_only_valid_durable_completion_removes_the_original_token(self):
source=(ROOT/'src/server/game/src/ava2_itemshop.cpp').read_text()
a=source.index('bool PointReply(');b=source.index('\n}\n}',a)+2;body=source[a:b]
harness=r'''
#include "src/server/common/ava2_itemshop.h"
#include <cassert>
#include <cstring>
#include <cstdlib>
#include <map>
#include <string>
using DWORD=uint32_t;
struct Pending{Ava2ShopRequest request;};std::map<std::string,Pending> pendingPoints;
bool allowDone=true;int done=0;
bool AppendDurableDone(const char*,uint8_t,uint32_t,int64_t){if(!allowDone)return false;++done;return true;}
struct Journal{std::string Error(){return "injected EIO";}}pointJournal;
#define sys_err(...) ((void)0)
struct Desc{struct Account{unsigned id=1;}account;Account GetAccountTable(){return account;}const char* GetClientVersion(){return "mt20261024";}};
struct Character{Desc desc;int notified=0;Desc* GetDesc(){return &desc;}template<class...T>void ChatPacket(T...){++notified;}}character;
struct CHARACTER_MANAGER{static CHARACTER_MANAGER& instance(){static CHARACTER_MANAGER m;return m;}Character* FindByPID(unsigned){return &character;}};
constexpr int CHAT_TYPE_COMMAND=1;
'''
main=r'''
int main(){
Ava2ShopReply reply={1,2,46};Ava2ShopRequest request={};request.account=1;request.player=2;request.count=8;
const std::string token="0123456789abcdef0123456789abcdef";char data[46]={};data[0]=9;memcpy(data+2,token.data(),32);
auto reset=[&](){pendingPoints.clear();pendingPoints[token]={request};};
auto response=[&](unsigned status,uint32_t amount,int64_t balance){data[1]=char(status);memcpy(data+34,&amount,4);memcpy(data+38,&balance,8);return PointReply(reply,data);};
for(unsigned status:{6u,8u,255u,3u}){reset();assert(response(status,0,100) && pendingPoints.size()==1 && !done);}
reset();assert(response(0,9,100) && pendingPoints.size()==1 && !done);
assert(response(0,1,-1) && pendingPoints.size()==1 && !done);
assert(response(2,1,100) && pendingPoints.size()==1 && !done);
allowDone=false;assert(response(0,8,100) && pendingPoints.size()==1 && !done);allowDone=true;
reply.account=99;assert(response(0,8,100) && pendingPoints.size()==1 && !done);reply.account=1;
assert(response(0,8,100) && pendingPoints.empty() && done==1 && character.notified==1);
assert(response(0,8,100) && done==1 && character.notified==1); // Duplicate completion is ignored.
reset();assert(response(2,0,100) && pendingPoints.empty() && done==2 && character.notified==1);
reset();reply.size=45;assert(!response(0,8,100) && pendingPoints.size()==1);reply.size=46;
}
'''
with tempfile.TemporaryDirectory() as tmp:
src=Path(tmp)/'probe.cpp';exe=Path(tmp)/'probe';src.write_text(harness+body+main)
subprocess.run(['c++','-std=c++17','-fsanitize=undefined,address','-fno-sanitize-recover=all','-I'+str(ROOT),str(src),'-o',str(exe)],check=True)
subprocess.run([str(exe)],check=True)
if __name__=='__main__':unittest.main()
@@ -0,0 +1,118 @@
"""Execute DB reward handler control flow with transactional SQL fault boundaries.
This is not a real MySQL or a full db-process crash acceptance test.
"""
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[2]
class PointSettlement(unittest.TestCase):
def test_commit_uncertainty_replay_and_configuration_changes(self):
source=(ROOT/'src/server/db/src/Ava2ItemShop.cpp').read_text()
body=source[source.index(' if(r.operation==3) {'):source.index(' auto login=GetLoginDataByAID')]
harness=r'''
#include "src/server/common/ava2_itemshop.h"
#include "src/server/common/point_drop.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <map>
#include <memory>
#include <string>
#include <vector>
using DWORD=uint32_t;
struct TMobTable{DWORD dwVnum;int bType,bLevel;};
struct CPeer{int GetChannel(){return 1;}};
struct Reward{unsigned account,player,vnum,requested,amount;};
struct State{int64_t coins=100;std::map<std::string,Reward> rewards;};
State durable,working;
Ava2ShopRequest current={};bool ownerPresent=true,walletPresent=true;unsigned ownerAccount=1;int ownershipQueries=0;bool active=false,commitLost=false,commitRefused=false,failInsert=false,engineOK=true;
std::string queryFailure;int writes=0,quotas=0;
struct Rows{std::vector<std::vector<std::string>> values;std::vector<char*> output;};
struct Result{unsigned uiNumRows=0;Rows rows;Rows* pSQLResult=&rows;};
struct SQL{unsigned uiSQLErrno=0;Result result;Result* Get(){return &result;}};
using Query=std::unique_ptr<SQL>;
Query result(std::vector<std::vector<std::string>> rows){Query q(new SQL);q->result.uiNumRows=rows.size();q->result.rows.values=std::move(rows);return q;}
char** mysql_fetch_row(Rows* rows){assert(!rows->values.empty());rows->output.clear();for(auto& v:rows->values[0])rows->output.push_back(v.data());return rows->output.data();}
bool ok(const Query& q){return q && !q->uiSQLErrno;}
std::string decimal(uint64_t v){return std::to_string(v);}std::string accountDB(){return "`account`";}
Query query(const std::string& sql){
if(!queryFailure.empty() && sql.find(queryFailure)!=std::string::npos){Query q(new SQL);q->uiSQLErrno=1;return q;}
if(sql.find("information_schema.tables")!=std::string::npos){assert(sql.find("ishop")==std::string::npos && sql.find("port_point_rewards")!=std::string::npos && sql.find("account")!=std::string::npos);return result({{engineOK?"2":"1"}});}
assert(active);
if(sql.find("SELECT account_id FROM player")==0){++ownershipQueries;return result(ownerPresent?std::vector<std::vector<std::string>>{{decimal(ownerAccount)}}:std::vector<std::vector<std::string>>{});}
if(sql.find("SELECT coins FROM")==0){assert(sql.find("FOR UPDATE")!=std::string::npos);return result(walletPresent?std::vector<std::vector<std::string>>{{std::to_string(working.coins)}}:std::vector<std::vector<std::string>>{});}
if(sql=="SELECT CURDATE()")return result({{"2026-10-20"}});
if(sql.find("SELECT account_id,vnum,requested,amount,player_id FROM port_point_rewards")==0){
auto it=working.rewards.find(current.token);if(it==working.rewards.end())return result({});const auto& r=it->second;
return result({{decimal(r.account),decimal(r.vnum),decimal(r.requested),decimal(r.amount),decimal(r.player)}});
}
if(sql.find("SELECT COALESCE(SUM(amount),0)")==0){++quotas;assert(sql.find("reward_day='2026-10-20'")!=std::string::npos);unsigned n=0;for(auto& row:working.rewards)if(row.second.account==current.account)n+=row.second.amount;return result({{decimal(n)}});}
assert(false);return {};
}
bool run(const std::string& sql){
assert(active);++writes;
if(sql.find("UPDATE `account`.account SET coins=coins+")==0){auto a=sql.find("coins+")+6;auto b=sql.find(" WHERE",a);working.coins+=std::stoll(sql.substr(a,b-a));return true;}
if(sql.find("INSERT INTO port_point_rewards")==0){
if(failInsert)return false;
auto before=durable.coins;unsigned amount=unsigned(working.coins-before);
assert(sql.find(","+decimal(current.count)+","+decimal(amount)+",'2026-10-20')")!=std::string::npos);
working.rewards[current.token]={current.account,current.player,current.product,current.count,amount};return true;
}
assert(false);return false;
}
struct Transaction{bool active=true;Transaction(){assert(!::active);::active=true;working=durable;}
bool commit(){if(commitRefused)return false;durable=working;if(commitLost)return false;active=false;return true;}
~Transaction(){::active=false;}
};
template<class T>void append(std::vector<char>& out,const T& v){auto p=reinterpret_cast<const char*>(&v);out.insert(out.end(),p,p+sizeof(v));}
std::vector<char> response;
void reply(CPeer*,DWORD,const Ava2ShopRequest&,const std::vector<char>& out){response=out;}
struct Handler{
std::vector<TMobTable> m_vec_mobTable={{8021,2,100}};
std::map<std::string,long> m_map_lEventFlag={{"points_stone_chance",10000},{"points_stone_min",3},{"points_stone_max",8},{"points_max_overlevel",15},{"points_daily_cap",500}};
void Handle(CPeer* peer,DWORD handle,const Ava2ShopRequest& r){ BODY }
};
uint8_t settle(Handler& handler,Ava2ShopRequest r){current=r;response.clear();CPeer peer;handler.Handle(&peer,0,r);assert(response.size()==46);return uint8_t(response[1]);}
unsigned granted(){unsigned n=0;memcpy(&n,response.data()+34,4);return n;}
'''.replace('BODY',body)
main=r'''
int main(){
Ava2ShopRequest r={};r.operation=3;r.account=1;r.player=2;r.product=8021;r.count=8;r.expectedVnum=110;strcpy(r.token,"0123456789abcdef0123456789abcdef");
Handler handler;durable.rewards["older"]={1,3,8021,498,498};
commitLost=true;assert(settle(handler,r)==8);assert(durable.coins==102 && durable.rewards[r.token].amount==2);int quotaCalls=quotas;
commitLost=false;ownerPresent=false;int ownershipBefore=ownershipQueries;handler.m_vec_mobTable.clear();handler.m_map_lEventFlag.clear();
assert(settle(handler,r)==0 && granted()==2 && durable.coins==102 && quotas==quotaCalls); // original committed result survives source changes.
assert(ownershipQueries==ownershipBefore);ownerPresent=true;
r.player=3;assert(settle(handler,r)==7 && durable.coins==102);r.player=2;
r.count=7;assert(settle(handler,r)==7 && durable.coins==102);r.count=8;
r.product=999;assert(settle(handler,r)==7 && durable.coins==102);r.product=8021;
// A new token with a removed mob is terminally refused, never dereferenced.
strcpy(r.token,"1123456789abcdef0123456789abcdef");assert(settle(handler,r)==1 && durable.coins==102);
handler=Handler();durable=State();failInsert=true;
assert(settle(handler,r)==6 && durable.coins==100 && durable.rewards.empty());failInsert=false;
assert(settle(handler,r)==0 && granted()==8 && durable.coins==108 && durable.rewards.size()==1);
assert(settle(handler,r)==0 && durable.coins==108);
strcpy(r.token,"2123456789abcdef0123456789abcdef");commitRefused=true;
assert(settle(handler,r)==8 && durable.coins==108 && durable.rewards.size()==1);commitRefused=false;
assert(settle(handler,r)==0 && durable.coins==116 && durable.rewards.size()==2);
strcpy(r.token,"3123456789abcdef0123456789abcdef");queryFailure="SELECT COALESCE";
assert(settle(handler,r)==6 && durable.coins==116);queryFailure.clear();
engineOK=false;assert(settle(handler,r)==6 && durable.coins==116);engineOK=true;
ownerPresent=false;assert(settle(handler,r)==2 && durable.coins==116);ownerPresent=true;
ownerAccount=99;assert(settle(handler,r)==2 && durable.coins==116);ownerAccount=1;
walletPresent=false;assert(settle(handler,r)==2 && durable.coins==116);walletPresent=true;
// Zero grants are durable results; later replay does not recalculate the cap.
handler.m_map_lEventFlag["points_daily_cap"]=16;assert(settle(handler,r)==0 && granted()==0 && durable.coins==116);
handler.m_map_lEventFlag["points_daily_cap"]=500;assert(settle(handler,r)==0 && granted()==0 && durable.coins==116);
}
'''
with tempfile.TemporaryDirectory() as tmp:
src=Path(tmp)/'probe.cpp';exe=Path(tmp)/'probe';src.write_text(harness+main)
subprocess.run(['c++','-std=c++17','-fsanitize=undefined,address','-fno-sanitize-recover=all','-I'+str(ROOT),str(src),'-o',str(exe)],check=True)
subprocess.run([str(exe)],check=True)
if __name__=='__main__':unittest.main()
@@ -0,0 +1,63 @@
"""Execute actual costume enchant/removal functions, including all AVA2 target masks."""
from pathlib import Path
import subprocess,tempfile,unittest
ROOT=Path(__file__).resolve().parents[2]
class CostumeProducts(unittest.TestCase):
def test_real_use_preserves_rare_state_and_consumes_only_after_success(self):
body=(ROOT/'src/server/game/src/port_costume_attr.cpp').read_text()
body='\n'.join(line for line in body.splitlines() if not line.startswith('#include'))
harness=r'''
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <array>
using BYTE=uint8_t;
enum {ITEM_USE=3,ITEM_COSTUME=28,ITEM_SHINING=35,USE_CHANGE_ATTRIBUTE=18,COSTUME_BODY=0,COSTUME_HAIR=1,COSTUME_WEAPON=5,COSTUME_MOUNT_SKIN=4,COSTUME_NEW_SASH=6,SHINING_WEAPON=0,SHINING_ARMOR=1,SHINING_SPECIAL=2,APPLY_NONE=0,MAX_APPLY_NUM=141,MAX_NORM_ATTR_NUM=5,CHAT_TYPE_COMMAND=1};
struct ITEM_MANAGER{enum {MAX_NORM_ATTR_NUM=5};};
struct CHARACTER;
struct CItem {int type=ITEM_USE,sub=USE_CHANGE_ATTRIBUTE;unsigned vnum=54001,count=2;int values[3]={23,10,2};CHARACTER* owner=nullptr;bool equipped=false,locked=false,exchanged=false;std::array<int,15> attrs{},amounts{};
int GetType(){return type;}int GetSubType(){return sub;}int GetValue(int i){return values[i];}unsigned GetVnum(){return vnum;}unsigned GetCount(){return count;}void SetCount(unsigned n){count=n;}unsigned GetID(){return 42;}
CHARACTER* GetOwner(){return owner;}bool IsEquipped(){return equipped;}bool isLocked(){return locked;}bool IsExchanging(){return exchanged;}
int GetAttributeType(int i){return attrs.at(i);}int GetAttributeCount(){int i=0;while(i<5&&attrs[i])++i;return i;}bool HasAttr(BYTE n){for(int i=0;i<5;++i)if(attrs[i]==n)return true;return false;}
void AddAttribute(BYTE n,short v){int i=GetAttributeCount();attrs.at(i)=n;amounts.at(i)=v;}void SetForceAttribute(int i,BYTE n,short v){attrs.at(i)=n;amounts.at(i)=v;}bool IsCostumeEnchant();
};using LPITEM=CItem*;
struct CHARACTER {char message[80]={};bool CostumeEnchantUse(LPITEM,LPITEM);void ChatPacket(int,const char* text){snprintf(message,sizeof(message),"%s",text);}};
struct LogManager{static LogManager& instance(){static LogManager m;return m;}template<class...T>void ItemLog(T...) {}};
'''
main=r'''
int main(){
CHARACTER ch,other;CItem scroll,target;scroll.owner=target.owner=&ch;target.type=ITEM_COSTUME;target.sub=COSTUME_BODY;
assert(!ch.CostumeEnchantUse(nullptr,&target));assert(!ch.CostumeEnchantUse(&scroll,nullptr));assert(!ch.CostumeEnchantUse(&scroll,&scroll));
for(int flag=1;flag<=6;++flag){
target.attrs.fill(0);target.amounts.fill(0);target.type=flag==6?ITEM_SHINING:ITEM_COSTUME;
const int subs[]={0,COSTUME_BODY,COSTUME_HAIR,COSTUME_WEAPON,COSTUME_MOUNT_SKIN,COSTUME_NEW_SASH,SHINING_SPECIAL};target.sub=subs[flag];
scroll.count=3;scroll.vnum=54001;scroll.values[2]=1<<flag;
assert(ch.CostumeEnchantUse(&scroll,&target));assert(scroll.count==2&&target.attrs[0]==23&&target.amounts[0]==10);
assert(!ch.CostumeEnchantUse(&scroll,&target)&&scroll.count==2); // duplicate
target.attrs[1]=24;target.attrs[2]=25;scroll.values[0]=26;
assert(!ch.CostumeEnchantUse(&scroll,&target)&&scroll.count==2); // full
target.attrs[5]=91;target.amounts[5]=555;target.attrs[6]=92;target.attrs[7]=93;target.attrs[14]=99;
scroll.vnum=53998;scroll.values[2]=0;assert(scroll.IsCostumeEnchant());
target.equipped=true;assert(!ch.CostumeEnchantUse(&scroll,&target));target.equipped=false;
target.locked=true;assert(!ch.CostumeEnchantUse(&scroll,&target));target.locked=false;
target.owner=&other;assert(!ch.CostumeEnchantUse(&scroll,&target));target.owner=&ch;
assert(ch.CostumeEnchantUse(&scroll,&target));assert(scroll.count==1&&target.attrs[0]==23&&target.attrs[1]==24&&target.attrs[2]==0);
scroll.vnum=53999;assert(ch.CostumeEnchantUse(&scroll,&target));assert(scroll.count==0&&target.attrs[0]==0&&target.attrs[1]==0);
assert(target.attrs[5]==91&&target.amounts[5]==555&&target.attrs[6]==92&&target.attrs[7]==93&&target.attrs[14]==99);
scroll.count=2;assert(ch.CostumeEnchantUse(&scroll,&target)&&scroll.count==2); // empty: no consumption
scroll.vnum=54001;scroll.values[0]=23;
}
target.type=ITEM_COSTUME;target.sub=COSTUME_BODY;scroll.values[2]=2;
for(int type:{-1,0,141,256,65559}){scroll.values[0]=type;assert(!ch.CostumeEnchantUse(&scroll,&target));assert(scroll.count==2&&target.attrs[0]==0);}
scroll.values[0]=23;for(int value:{-1,0,32768,65546}){scroll.values[1]=value;assert(!ch.CostumeEnchantUse(&scroll,&target)&&scroll.count==2);}
scroll.values[1]=10;scroll.values[2]=8;assert(!ch.CostumeEnchantUse(&scroll,&target));
scroll.values[2]=2;target.exchanged=true;assert(!ch.CostumeEnchantUse(&scroll,&target));target.exchanged=false;
scroll.locked=true;assert(!ch.CostumeEnchantUse(&scroll,&target));scroll.locked=false;
scroll.count=0;assert(!ch.CostumeEnchantUse(&scroll,&target));
}
'''
with tempfile.TemporaryDirectory() as d:
p=Path(d);(p/'probe.cpp').write_text(harness+body+main)
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all',str(p/'probe.cpp'),'-o',str(p/'probe')],check=True)
subprocess.run([str(p/'probe')],check=True)
@@ -0,0 +1,43 @@
"""Run the production proto reload encoder at WORD count boundaries."""
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[2]
class ProtoReloadBounds(unittest.TestCase):
def test_refuse_before_emitting_header_and_accept_empty_tables(self):
text=(ROOT/'src/server/db/src/ClientManager.cpp').read_text(encoding='latin1')
start=text.index('void CClientManager::QUERY_RELOAD_PROTO()')
end=text.index('// ADD_GUILD_PRIV_TIME',start)
actual=text[start:end]
harness=r'''
#include <cassert>
#include <cstdint>
#include <vector>
using WORD=uint16_t;
struct TSkillTable{char data[2];};struct TBanwordTable{char data[3];};struct TItemTable{char data[4];};struct TMobTable{char data[5];};
constexpr int HEADER_DG_RELOAD_PROTO=1;
#define sys_err(...) ((void)0)
struct CPeer {unsigned headers=0;size_t announced=0,bytes=0;std::vector<WORD> counts;
unsigned GetChannel(){return 1;}void EncodeHeader(int,int,size_t n){++headers;announced=n;}
void EncodeWORD(WORD n){counts.push_back(n);bytes+=sizeof(n);}void Encode(const void* ptr,size_t n){assert(!n||ptr);bytes+=n;}};
struct CClientManager {using TPeerList=std::vector<CPeer*>;TPeerList m_peerList;
std::vector<TSkillTable> m_vec_skillTable;std::vector<TBanwordTable> m_vec_banwordTable;
std::vector<TItemTable> m_vec_itemTable;std::vector<TMobTable> m_vec_mobTable;
bool InitializeTables(){return true;}void QUERY_RELOAD_PROTO();};
'''
main=r'''
int main(){CClientManager manager;CPeer peer;manager.m_peerList.push_back(&peer);
manager.QUERY_RELOAD_PROTO();assert(peer.headers==1 && peer.announced==8 && peer.bytes==8);
assert(peer.counts==std::vector<WORD>({0,0,0,0}));peer={};
manager.m_vec_skillTable.resize(UINT16_MAX);manager.QUERY_RELOAD_PROTO();assert(peer.headers==1 && peer.counts[0]==UINT16_MAX && peer.bytes==peer.announced);peer={};
manager.m_vec_skillTable.resize(UINT16_MAX+1u);manager.QUERY_RELOAD_PROTO();assert(peer.headers==0 && peer.bytes==0);
manager.m_vec_skillTable.clear();manager.m_vec_itemTable.resize(UINT16_MAX+1u);manager.QUERY_RELOAD_PROTO();assert(peer.headers==0 && peer.bytes==0);
}
'''
with tempfile.TemporaryDirectory() as tmp:
p=Path(tmp);(p/'probe.cpp').write_text(harness+actual+main)
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-Werror=implicit-int-conversion','-Werror=shorten-64-to-32',str(p/'probe.cpp'),'-o',str(p/'probe')],check=True)
subprocess.run([str(p/'probe')],check=True)
+5 -1
View File
@@ -74,6 +74,7 @@ static void PortCalendarQuery(LPCHARACTER,unsigned,unsigned){}
static bool PortDungeonQuery(LPCHARACTER,unsigned){return true;}
static unsigned travelBoss=0;static void PortTrackTravel(LPCHARACTER,unsigned,unsigned boss){travelBoss=boss;}
static unsigned bossQueries=0;void PortBossQuery(LPCHARACTER,unsigned request){bossQueries=request;}
static unsigned rankQuery=99;static void PortRankQuery(LPCHARACTER,unsigned,unsigned index){rankQuery=index;}
#include "port_features.h"
#include "port_dungeon_rules.h"
static void query(Character& ch,const char* text){clockms+=300;do_port_features(&ch,text);}
@@ -117,7 +118,10 @@ int main(){
assert(rewards[0].total==100 && rewards[0].rule==WIKI_SINGLE);
rewards=items.PortWikiChest(50012);assert(rewards[1].rule==WIKI_INDEPENDENT && rewards[1].weight==150 && rewards[1].total==100);
assert(items.PortWikiChest(50013).empty() && items.PortWikiChest(19).empty());
Character ch;query(ch,"1 99 travel 2493 0");assert(travelBoss==2493);query(ch,"1 1 cap");assert(ch.messages.back()=="MTF1 cap 1 1 959 1700000000");
Character ch;query(ch,"1 99 travel 2493 0");assert(travelBoss==2493);query(ch,"1 1 cap");assert(ch.messages.back()=="MTF1 cap 1 1 1983 1700000000");
query(ch,"1 90 rank 0 0");assert(rankQuery==0);
query(ch,"1 91 rank 10 0");assert(ch.messages.back()=="MTF1 error 91 invalid" && rankQuery==0);
query(ch,"1 92 rank 6 1");assert(ch.messages.back()=="MTF1 error 92 invalid" && rankQuery==0);
ch.messages.clear();query(ch,"1 2 mob 101 0");assert(ch.messages.size()==10 && ch.messages.back()=="MTF1 end 2 8");
query(ch,"1 3 mob 101 999");assert(ch.messages.back()=="MTF1 error 3 offset");
query(ch,"1 4 mob 9001 0");assert(ch.messages.back()=="MTF1 error 4 missing");
+116
View File
@@ -0,0 +1,116 @@
"""Execute the production async rank/cache/session handler with explicit SQL/peer substitutes."""
from pathlib import Path
import subprocess
import tempfile
import unittest
SRC = Path(__file__).resolve().parents[2] / 'src/server/game/src'
CODE = r'''
#include <cassert>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <functional>
#include <map>
#include <string>
#include <vector>
static unsigned tick=1000;
unsigned get_dword_time(){return tick;}
long long get_global_time(){return 1700000000;}
const char* get_table_postfix(){return "_sb";}
enum{CHAT_TYPE_COMMAND=5};
struct Character;
struct Desc{
unsigned handle=7,handshake=40;struct Account{unsigned id=3;} account;
Character* ch=nullptr;
unsigned GetHandle(){return handle;}unsigned GetHandshake(){return handshake;}
Account& GetAccountTable(){return account;}Character* GetCharacter(){return ch;}
};
struct Character{
unsigned pid=9;Desc* d;std::vector<std::string> lines;
Desc* GetDesc(){return d;}unsigned GetPlayerID(){return pid;}
void ChatPacket(int,const char* format,...){
char out[512];va_list args;va_start(args,format);vsnprintf(out,sizeof(out),format,args);va_end(args);
lines.emplace_back(out);
}
};
using LPCHARACTER=Character*;
struct DESC_MANAGER{
std::map<unsigned,Desc*> peers;
static DESC_MANAGER& instance(){static DESC_MANAGER m;return m;}
Desc* FindByHandle(unsigned h){auto i=peers.find(h);return i==peers.end()?nullptr:i->second;}
};
struct Result{
std::vector<std::vector<std::string>> rows;
size_t cursor=0;char* fields[3];
};
using MYSQL_ROW=char**;
MYSQL_ROW mysql_fetch_row(Result* r){
if(r->cursor>=r->rows.size())return nullptr;
auto& row=r->rows[r->cursor++];for(int i=0;i<3;++i)r->fields[i]=&row[i][0];return r->fields;
}
struct SQLMsg{
unsigned uiSQLErrno=0;
struct Data{Result* pSQLResult;unsigned uiNumRows;} data;
Data* Get(){return &data;}
};
struct DBManager{
std::vector<std::function<void(SQLMsg*)>> callbacks;std::vector<std::string> queries;
static DBManager& instance(){static DBManager m;return m;}
template<class F>void FuncQuery(F f,const char* format,...){
char out[4096];va_list args;va_start(args,format);vsnprintf(out,sizeof(out),format,args);va_end(args);
queries.emplace_back(out);callbacks.emplace_back(f);
}
void Complete(std::vector<std::vector<std::string>> rows,unsigned error=0){
Result r;r.rows=rows;SQLMsg msg;msg.uiSQLErrno=error;msg.data={&r,unsigned(rows.size())};
auto f=callbacks.front();callbacks.erase(callbacks.begin());f(&msg);
}
};
#include "port_rank_runtime.h"
int main(){
Desc d;Character c;c.d=&d;d.ch=&c;DESC_MANAGER::instance().peers[d.handle]=&d;
auto& db=DBManager::instance();
PortRankQuery(&c,1,0);PortRankQuery(&c,2,0);
assert(db.queries.size()==1 && c.lines.empty());
assert(db.queries[0].find("p.level")!=std::string::npos);
assert(db.queries[0].find("player_sb p JOIN player_index_sb")!=std::string::npos);
assert(db.queries[0].find("ORDER BY p.level DESC, p.id ASC LIMIT 10")!=std::string::npos);
db.Complete({{"hero","1","120"},{"second","2","119"}});
assert(c.lines.size()==8 && c.lines.front()=="MTF1 begin 1 rank 0 0 2 0 1700000000");
assert(c.lines[1]=="MTF1 rank 1 0 6865726f 1 120");
PortRankQuery(&c,3,0);assert(db.queries.size()==1 && c.lines.back()=="MTF1 end 3 2");
PortRankQuery(&c,4,1);assert(c.lines.back()=="MTF1 error 4 unsupported");
PortRankQuery(&c,5,10);assert(c.lines.back()=="MTF1 error 5 unsupported");
PortRankQuery(&c,6,6);db.Complete({{"rich","3","5000000000"}});
assert(c.lines[c.lines.size()-2]=="MTF1 rank 6 0 72696368 3 5000000000");
PortRankQuery(&c,7,5);db.Complete({});assert(c.lines.back()=="MTF1 end 7 0");
tick+=60001;PortRankQuery(&c,8,0);db.Complete({{"valid","1","5"},{"bad","9","1"}});
assert(c.lines.back()=="MTF1 error 8 storage");
PortRankQuery(&c,9,0);db.Complete({},1);assert(c.lines.back()=="MTF1 error 9 storage");
PortRankQuery(&c,10,0);size_t before=c.lines.size();d.handshake++;
db.Complete({{"hero","1","120"}});assert(c.lines.size()==before);
tick+=60001;PortRankQuery(&c,11,0);before=c.lines.size();c.pid++;
db.Complete({{"hero","1","120"}});assert(c.lines.size()==before);
tick+=60001;PortRankQuery(&c,12,0);before=c.lines.size();d.account.id++;
db.Complete({{"hero","1","120"}});assert(c.lines.size()==before);
uint64_t n;assert(!PortRank::Number("-1",10,n));assert(!PortRank::Number("11",10,n));
assert(PortRank::Number("18446744073709551615",UINT64_MAX,n));
assert(!PortRank::Number("18446744073709551616",UINT64_MAX,n));
puts("PASS: production rank query, async coalescing, persisted top10, 64bit, cache expiry, atomic failure, stale session/player/account");
}
'''
class RankRuntimeTests(unittest.TestCase):
def test_actual_rank_handler(self):
with tempfile.TemporaryDirectory(prefix='ch5-rank-') as folder:
root = Path(folder)
(root / 'probe.cpp').write_text(CODE)
subprocess.run(['c++', '-std=c++17', '-Wall', '-Wextra',
'-I' + str(SRC), str(root / 'probe.cpp'),
'-o', str(root / 'probe')], check=True)
subprocess.run([str(root / 'probe')], check=True)
if __name__ == '__main__':
unittest.main()
@@ -0,0 +1,36 @@
"""Compile common protocol headers without relying on a game-only include order."""
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[2]
class SharedWireHeaders(unittest.TestCase):
def test_game_and_db_include_order_share_enabled_fields(self):
body=r'''
#include <cstdint>
#include <cstring>
#include <iostream>
using BYTE=uint8_t;using WORD=uint16_t;using DWORD=uint32_t;using LONG=int32_t;using INT=int32_t;
SERVICE
#include "src/server/common/tables.h"
static_assert(OFFLINE_SHOP_HOST_ITEM_MAX_NUM==80);
static_assert(SHOP_SIGN_MAX_LEN==45);
static_assert(PET_LEVELABLE==0 && PET_FEEDSTUFF==14);
static_assert(APPLY_RESIST_HUMAN==99);
static_assert(sizeof(TShopItemTable)==17);
int main(){
TPlayerTable player={};player.shopFlag=1;player.inventory_unlock[0]=1;
TOfflineShop shop={};OFFLINE_SHOP_ITEM item={};
std::cout<<sizeof(player)<<' '<<sizeof(shop)<<' '<<sizeof(item)<<' '<<sizeof(TShopTable);
}
'''
with tempfile.TemporaryDirectory() as tmp:
outputs=[]
for index,include in enumerate(('', '#include "src/server/common/service.h"')):
src=Path(tmp)/('probe%d.cpp'%index);exe=src.with_suffix('');src.write_text(body.replace('SERVICE',include))
subprocess.run(['c++','-std=c++23','-I'+str(ROOT),str(src),'-o',str(exe)],check=True)
outputs.append(subprocess.check_output([str(exe)]))
self.assertEqual(outputs[0],outputs[1])
if __name__=='__main__':unittest.main()
+118
View File
@@ -0,0 +1,118 @@
"""Execute production CShop::Buy with deterministic inventory, wallet and log boundaries."""
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
class ShopEconomy(unittest.TestCase):
def test_actual_buy_checks_seller_before_charging_and_preserves_large_tax(self):
source = (ROOT/'src/server/game/src/shop.cpp').read_bytes().decode('latin1')
body = source[source.index('int CShop::Buy('):source.index('LPITEM CShop::GetGuestItem(')]
harness = r'''
#include "src/server/common/shop_economy.h"
#include <cassert>
#include <climits>
#include <cstdint>
#include <cstdio>
#include <map>
#include <vector>
#include <string>
using DWORD=uint32_t;using BYTE=uint8_t;
constexpr int64_t GOLD_MAX_64=2000000000000000LL;
enum {SHOP_SUBHEADER_GC_OK=4,SHOP_SUBHEADER_GC_INVALID_POS=8,SHOP_SUBHEADER_GC_END=1,SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY=5,SHOP_SUBHEADER_GC_SOLD_OUT=9,SHOP_SUBHEADER_GC_INVENTORY_FULL=7};
enum {POINT_GOLD,PORT_BP_NPC_SPEND,QUICKSLOT_TYPE_ITEM,DRAGON_SOUL_INVENTORY,INVENTORY,SHOP_BUY,SHOP_SELL,PERSONAL_SHOP_BUY,MONEY_LOG_SHOP,CHAT_TYPE_INFO};
#define sys_log(...) ((void)0)
#define LC_TEXT(x) (x)
bool LC_IsYMIR(){return false;}bool LC_IsKorea(){return false;}
struct Character;using LPCHARACTER=Character*;
struct TItemPos{TItemPos(int,int){}};
struct Item {DWORD vnum=19,id=1;BYTE count=1;Character* owner=nullptr;
DWORD GetVnum(){return vnum;}DWORD GetID(){return id;}BYTE GetCount(){return count;}
Character* GetOwner(){return owner;}int GetSize(){return 1;}bool IsDragonSoul(){return false;}
const char* GetName(){return "item";}int GetCell(){return 0;}
void RemoveFromCharacter(){owner=nullptr;}void AddToCharacter(Character* c,TItemPos){owner=c;}
};using LPITEM=Item*;
struct Character {int64_t gold=0;bool full=false;int writes=0,saves=0;
int64_t GetGold(){return gold;}const char* GetName(){return "test";}DWORD GetPlayerID(){return 1;}
int GetEmptyInventory(int){return full?-1:0;}int GetEmptyDragonSoulInventory(Item*){return full?-1:0;}
void PointChange(int,int64_t delta,bool){assert(PortGoldCanChange(gold,delta,GOLD_MAX_64));gold+=delta;++writes;}
void SyncQuickslot(int,int,int){}int GetEmpire(){return 1;}void Save(){++saves;}
template<class...T>void ChatPacket(T...){}
};
struct ITEM_MANAGER {std::map<int,Item*> items;int created=0,destroyed=0;
static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;}
Item* Find(int id){return items.count(id)?items[id]:nullptr;}
Item* CreateItem(DWORD vnum,BYTE count){auto* item=new Item;item->vnum=vnum;item->count=count;items[++created+10]=item;return item;}
void Destroy(Item* item){++destroyed;for(auto it=items.begin();it!=items.end();)if(it->second==item)it=items.erase(it);else ++it;delete item;}
void FlushDelayedSave(Item*){}
~ITEM_MANAGER(){for(auto& it:items)if(it.first!=1)delete it.second;}
};
#define M2_DESTROY_ITEM(i) ITEM_MANAGER::instance().Destroy(i)
struct LogManager {static LogManager& instance(){static LogManager m;return m;}template<class...T>void HackLog(T...){}template<class...T>void GoldBarLog(T...){}template<class...T>void ItemLog(T...){} };
namespace quest {struct CQuestManager {int tax=3;static CQuestManager& instance(){static CQuestManager q;return q;}int GetEventFlag(const char* key){return std::string(key)=="personal_shop"?tax:1;} };}
struct CMonarch {int64_t total=0;static CMonarch& instance(){static CMonarch m;return m;}void SendtoDBAddMoney(int64_t money,int,Character*){total+=money;} };
struct DBManager {int64_t logged=0;static DBManager& instance(){static DBManager m;return m;}void SendMoneyLog(int,DWORD,int64_t gold){logged+=gold;} };
void PortBpCount(Character*,int,int,int64_t){}void VCardUse(Character*,Character*,Item*){}
struct CShop {struct SHOP_ITEM{DWORD vnum=19;int64_t price=0;BYTE count=1;Item* pkItem=nullptr;int itemid=1;};
using GuestMapType=std::map<Character*,bool>;GuestMapType m_map_guest;std::vector<SHOP_ITEM> m_itemVector;
Character* m_pkPC=nullptr;bool IsPCShop(){return m_pkPC!=nullptr;}void BroadcastUpdateItem(BYTE){}int Buy(Character*,BYTE);
};
'''
extra_source=(ROOT/'src/server/game/src/shopEx.cpp').read_bytes().decode('latin1')
extra_body=extra_source[extra_source.index('int CShopEx::Buy('):]
harness=harness.replace('int64_t gold=0;', 'int secondary=100;int64_t gold=0;').replace('void SyncQuickslot(int,int,int){}', 'int CountSpecifyTypeItem(int){return secondary;}void RemoveSpecifyTypeItem(int,int n){assert(n>=0 && n<=secondary);secondary-=n;}void SaveReal(){Save();}void SyncQuickslot(int,int,int){}')
harness+=r'''
constexpr int SHOP_HOST_ITEM_MAX_NUM=40,SHOP_COIN_TYPE_GOLD=0,SHOP_COIN_TYPE_SECONDARY_COIN=1;
constexpr int ITEM_SECONDARY_COIN=1,SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY_EX=11,HEADER_GD_FLUSH_CACHE=0;
bool LC_IsBrazil(){return false;}
struct DbDesc{template<class...T>void DBPacketHeader(T...){}template<class...T>void Packet(T...){};} dbDesc;
auto* db_clientdesc=&dbDesc;
using TShopItemTable=CShop::SHOP_ITEM;
struct TShopTableEx{int coinType=SHOP_COIN_TYPE_GOLD;TShopItemTable items[SHOP_HOST_ITEM_MAX_NUM];};
struct CShopEx:CShop {std::vector<TShopTableEx> m_vec_shopTabs;int GetTabCount(){return m_vec_shopTabs.size();}int Buy(Character*,BYTE);};
'''
main = r'''
int main(){
Character buyer,seller;Item item;item.owner=&seller;ITEM_MANAGER::instance().items[1]=&item;
CShop shop;shop.m_pkPC=&seller;shop.m_itemVector.resize(1);auto& row=shop.m_itemVector[0];row.price=300000000000LL;row.pkItem=&item;
shop.m_map_guest[&buyer]=true; // PC shop never charges an empire multiplier.
buyer.gold=400000000000LL;seller.gold=GOLD_MAX_64-291000000000LL+1;
assert(shop.Buy(&buyer,0)==SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY);
assert(buyer.gold==400000000000LL && buyer.writes==0 && seller.writes==0 && item.owner==&seller && row.pkItem==&item);
--seller.gold;assert(shop.Buy(&buyer,0)==SHOP_SUBHEADER_GC_OK);
assert(buyer.gold==100000000000LL && seller.gold==GOLD_MAX_64 && item.owner==&buyer && !row.pkItem);
assert(CMonarch::instance().total==9000000000LL);
assert(shop.Buy(&buyer,0)==SHOP_SUBHEADER_GC_SOLD_OUT && buyer.gold==100000000000LL);
assert(shop.Buy(&buyer,255)==SHOP_SUBHEADER_GC_INVALID_POS);
CShop npc;npc.m_itemVector.resize(1);npc.m_itemVector[0].price=100000000000LL;npc.m_map_guest[&buyer]=true;
buyer.gold=400000000000LL;assert(npc.Buy(&buyer,0)==SHOP_SUBHEADER_GC_OK);
assert(buyer.gold==100000000000LL && DBManager::instance().logged==-300000000000LL);
npc.m_itemVector[0].price=INT64_MAX;int writes=buyer.writes;
assert(npc.Buy(&buyer,0)==SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY && buyer.writes==writes);
npc.m_itemVector[0].price=-1;assert(npc.Buy(&buyer,0)==SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY && buyer.writes==writes);
npc.m_itemVector[0].price=0;assert(npc.Buy(&buyer,0)==SHOP_SUBHEADER_GC_OK && buyer.gold==100000000000LL);
buyer.full=true;int created=ITEM_MANAGER::instance().created;
assert(npc.Buy(&buyer,0)==SHOP_SUBHEADER_GC_INVENTORY_FULL);
assert(ITEM_MANAGER::instance().created==created+1 && ITEM_MANAGER::instance().destroyed==1);
}
'''
exmain=r'''
CShopEx ex;ex.m_vec_shopTabs.resize(1);ex.m_map_guest[&buyer]=true;
auto& tab=ex.m_vec_shopTabs[0];tab.items[0].price=100000000000LL;
buyer.gold=400000000000LL;buyer.full=false;
assert(ex.Buy(&buyer,0)==SHOP_SUBHEADER_GC_OK && buyer.gold==100000000000LL);
tab.coinType=SHOP_COIN_TYPE_SECONDARY_COIN;tab.items[0].price=int64_t(INT_MAX)+1;
assert(ex.Buy(&buyer,0)==SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY_EX && buyer.secondary==100);
tab.items[0].price=20;int64_t logged=DBManager::instance().logged;
assert(ex.Buy(&buyer,0)==SHOP_SUBHEADER_GC_OK && buyer.secondary==80 && DBManager::instance().logged==logged);
tab.coinType=99;assert(ex.Buy(&buyer,0)==SHOP_SUBHEADER_GC_END && buyer.secondary==80);
'''
main=main[:main.rfind('}')]+exmain+'}\n'
with tempfile.TemporaryDirectory() as tmp:
src=Path(tmp)/'probe.cpp';exe=Path(tmp)/'probe'
src.write_text(harness+body+extra_body+main)
subprocess.run(['c++','-std=c++17','-fsanitize=undefined,address','-fno-sanitize-recover=all','-I'+str(ROOT),str(src),'-o',str(exe)],check=True)
subprocess.run([str(exe)],check=True)
if __name__=='__main__':unittest.main()
+153
View File
@@ -0,0 +1,153 @@
"""Run the production SQL metadata, mark index and boot encoder boundaries."""
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[2]
def function(text,signature):
start=text.index(signature);a=text.index('{',start);depth=1;b=a+1
while depth:
if text[b]=='{':depth+=1
elif text[b]=='}':depth-=1
b+=1
return text[start:b]+'\n'
class SQLMarkBounds(unittest.TestCase):
def native(self,code):
with tempfile.TemporaryDirectory() as tmp:
src=Path(tmp)/'probe.cpp';exe=src.with_suffix('');src.write_text(code)
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-Werror=implicit-int-conversion','-Werror=shorten-64-to-32','-I'+str(ROOT),str(src),'-o',str(exe)],check=True)
subprocess.run([str(exe)],cwd=tmp,check=True)
def test_sql_store_preserves_mysql_width_and_error_sentinel(self):
text=(ROOT/'src/server/libsql/AsyncSQL.h').read_text(encoding='latin1');a=text.index('typedef struct _SQLResult');b=text.index('class CAsyncSQL')
self.native(r'''
#include <cassert>
#include <cstdint>
#include <cstddef>
#include <string>
#include <vector>
using my_ulonglong=unsigned long long;
struct MYSQL_RES {my_ulonglong rows;};
struct Fake {MYSQL_RES* rows;my_ulonglong id,affected;};
struct MYSQL {std::vector<Fake> results;size_t index=0;};
unsigned frees=0;
MYSQL_RES* mysql_store_result(MYSQL* m){return m->results[m->index].rows;}
my_ulonglong mysql_insert_id(MYSQL* m){return m->results[m->index].id;}
my_ulonglong mysql_affected_rows(MYSQL* m){return m->results[m->index].affected;}
my_ulonglong mysql_num_rows(MYSQL_RES* r){return r->rows;}
int mysql_next_result(MYSQL* m){return ++m->index<m->results.size()?0:-1;}
void mysql_free_result(MYSQL_RES*){++frees;}
'''+text[a:b]+r'''
int main(){
static_assert(sizeof(SQLResult::uiNumRows)==8 && sizeof(SQLResult::uiAffectedRows)==8 && sizeof(SQLResult::uiInsertID)==8);
MYSQL_RES rows={uint64_t(UINT32_MAX)+17};MYSQL db={{{&rows,uint64_t(UINT32_MAX)+1,UINT64_MAX},{nullptr,UINT32_MAX,UINT32_MAX},{nullptr,0,0}}};
{
SQLMsg msg;msg.m_pkSQL=&db;msg.Store();assert(msg.vec_pkResult.size()==3);
SQLResult* result=msg.Get();assert(result->uiNumRows==uint64_t(UINT32_MAX)+17&&result->uiInsertID==uint64_t(UINT32_MAX)+1&&result->uiAffectedRows==UINT64_MAX&&!result->HasAffectedRows());
uint32_t id=123;assert(!result->GetInsertID32(id)&&id==123);
assert(msg.Next());result=msg.Get();assert(result->HasAffectedRows());assert(result->GetInsertID32(id)&&id==UINT32_MAX); // 2^32-1 is a valid count/ID, not the 64-bit error.
assert(msg.Next());assert(!msg.Get()->HasAffectedRows());id=7;assert(!msg.Get()->GetInsertID32(id)&&id==7);assert(!msg.Next());
}
assert(frees==1);
}
''')
def test_mark_index_validation_atomic_load_and_unaligned_output(self):
text=(ROOT/'src/server/game/src/MarkManager.cpp').read_text(encoding='latin1')
methods=''.join(function(text,s) for s in ['CGuildMarkManager::CGuildMarkManager()','bool CGuildMarkManager::LoadMarkIndex()','bool CGuildMarkManager::AddMarkIDByGuildID','DWORD CGuildMarkManager::GetMarkCount()','bool CGuildMarkManager::CopyMarkIdx','DWORD CGuildMarkManager::GetMarkID','DWORD CGuildMarkManager::__AllocMarkID','DWORD CGuildMarkManager::SaveMark'])
self.native(r'''
#include <cassert>
#include <cstdio>
#include <cstring>
#include <cstdint>
#include <map>
#include <set>
#include <string>
#include <sstream>
#include <fstream>
#include <array>
#include <sys/stat.h>
using BYTE=uint8_t;using WORD=uint16_t;using DWORD=uint32_t;
struct CGuildMarkImage {static constexpr unsigned MARK_TOTAL_COUNT=1280;void SaveMark(DWORD,BYTE*){}};
#define sys_log(...) ((void)0)
#define sys_err(...) ((void)0)
struct CGuildMarkManager {
static constexpr unsigned MAX_IMAGE_COUNT=5;static constexpr DWORD INVALID_MARK_ID=UINT32_MAX;CGuildMarkImage image;
std::map<DWORD,DWORD> m_mapGID_MarkID;std::set<DWORD> m_setFreeMarkID;std::string m_pathPrefix="probe";int imageLoads=0;
DWORD GetMarkID(DWORD);DWORD __AllocMarkID(DWORD);DWORD SaveMark(DWORD,BYTE*);CGuildMarkImage* __GetImage(DWORD){return &image;}void SaveMarkImage(DWORD){}bool SaveMarkIndex(){return true;}
CGuildMarkManager();bool LoadMarkIndex();bool AddMarkIDByGuildID(DWORD,DWORD);DWORD GetMarkCount()const;bool CopyMarkIdx(char*,size_t)const;void LoadMarkImages(){++imageLoads;}
};
'''+methods+r'''
void file(const std::string& text){std::ofstream out("mark/probe_index");out<<text;}
int main(){
mkdir("mark",0700);CGuildMarkManager marks;
assert(marks.SaveMark(65536,nullptr)==UINT32_MAX && !marks.GetMarkCount());assert(marks.SaveMark(1,nullptr)==0);
assert(marks.AddMarkIDByGuildID(1,0));assert(marks.AddMarkIDByGuildID(1,0));
assert(!marks.AddMarkIDByGuildID(1,1)&&!marks.AddMarkIDByGuildID(2,0));
assert(!marks.AddMarkIDByGuildID(65536,1)&&!marks.AddMarkIDByGuildID(0,1)&&!marks.AddMarkIDByGuildID(2,6400));
file("1 0\n65535 6399\n");assert(marks.LoadMarkIndex()&&marks.GetMarkCount()==2&&marks.imageLoads==1);
std::array<char,12> bytes;bytes.fill('Z');assert(!marks.CopyMarkIdx(bytes.data()+1,7));for(char c:bytes)assert(c=='Z');
assert(marks.CopyMarkIdx(bytes.data()+1,8));assert(bytes[0]=='Z'&&bytes[9]=='Z');WORD pair[4];memcpy(pair,bytes.data()+1,8);assert(pair[0]==1&&pair[1]==0&&pair[2]==65535&&pair[3]==6399);
for(const char* bad:{"1 0\n1 1\n","1 0\n2 0\n","65536 1\n","-1 1\n","1 6400\n","1 nope\n","1 2 junk\n"}){
file(bad);auto map=marks.m_mapGID_MarkID;auto free=marks.m_setFreeMarkID;assert(!marks.LoadMarkIndex());assert(marks.m_mapGID_MarkID==map&&marks.m_setFreeMarkID==free&&marks.imageLoads==1);
}
file(std::string("1 0\0junk\n",9));assert(!marks.LoadMarkIndex()&&marks.GetMarkCount()==2&&marks.imageLoads==1);
file("2 1\n");assert(marks.LoadMarkIndex()&&marks.GetMarkCount()==1&&!marks.m_mapGID_MarkID.count(1));
file("");assert(marks.LoadMarkIndex()&&marks.GetMarkCount()==0&&marks.m_setFreeMarkID.size()==6400&&marks.CopyMarkIdx(nullptr,0));
}
''')
def test_boot_table_counts_and_total_match_encoded_stream(self):
text=(ROOT/'src/server/db/src/ClientManager.cpp').read_text(encoding='latin1');actual=function(text,'void CClientManager::QUERY_BOOT')+function(text,'void CClientManager::ReloadAdmin(')
self.native(r'''
#include <cassert>
#include <cstdint>
#include <cstring>
#include <ctime>
#include <map>
#include <string>
#include <vector>
using BYTE=uint8_t;using WORD=uint16_t;using DWORD=uint32_t;using LONG=int32_t;using INT=int32_t;
#include "src/server/common/tables.h"
#include "src/server/common/building.h"
#include "src/server/common/wire_bounds.h"
#define sys_log(...) ((void)0)
#define sys_err(...) ((void)0)
#define itertype(v) decltype((v).begin())
bool g_test_server=false;
struct CPeer {
std::vector<char> bytes;DWORD announced=0;int headers=0;
void EncodeHeader(int,int,DWORD size){announced=size;++headers;}
void Encode(const void* p,size_t n){if(!n)return;assert(p);const char* b=static_cast<const char*>(p);bytes.insert(bytes.end(),b,b+n);}
void EncodeWORD(WORD value){Encode(&value,2);}int GetChannel(){return 1;}
void SetItemIDRange(TItemIDRangeTable){}void SetSpareItemIDRange(TItemIDRangeTable){}
};
struct CMonarch {
using VEC_MONARCHCANDIDACY=std::vector<MonarchCandidacy>;VEC_MONARCHCANDIDACY candidates;TMonarchInfo info={};
static CMonarch& instance(){static CMonarch m;return m;}size_t MonarchCandidacySize(){return candidates.size();}VEC_MONARCHCANDIDACY& GetVecMonarchCandidacy(){return candidates;}TMonarchInfo* GetMonarch(){return &info;}
};
struct CItemIDRangeManager {static CItemIDRangeManager& instance(){static CItemIDRangeManager m;return m;}TItemIDRangeTable GetRange(){return {};}};
struct CClientManager {
std::vector<TMobTable> m_vec_mobTable;std::vector<TItemTable> m_vec_itemTable;std::vector<TSkillTable> m_vec_skillTable;
int m_iShopTableSize=0,m_iRefineTableSize=0;TShopTable* m_pShopTable=nullptr;TRefineTable* m_pRefineTable=nullptr;
std::vector<TItemAttrTable> m_vec_itemAttrTable,m_vec_itemRareTable;std::vector<TBanwordTable> m_vec_banwordTable;
std::vector<building::TLand> m_vec_kLandTable;std::vector<building::TObjectProto> m_vec_kObjectProto;std::map<DWORD,building::TObject*> m_map_pkObjectTable;
std::vector<CPeer*> m_peerList;
std::map<DWORD,TOfflineShop*> m_Offlineshop;std::vector<std::string> hosts;std::vector<tAdminInfo> admins;bool queryOK=true;
bool __GetHostInfo(std::vector<std::string>& out){out=hosts;return queryOK;}bool __GetAdminInfo(const char*,std::vector<tAdminInfo>& out){out=admins;return queryOK;}
void QUERY_BOOT(CPeer*,TPacketGDBoot*);void ReloadAdmin(CPeer*,TPacketReloadAdmin*);
};
'''+actual+r'''
int main(){
PortBootSizer huge(0);assert(!huge.Add(UINT16_MAX,UINT16_MAX)&&!huge.Valid()&&!huge.Bytes());
PortBootSizer invalid(UINT64_MAX);assert(!invalid.Add(0,0)&&!invalid.Bytes());
CClientManager manager;TPacketGDBoot request={};CPeer peer;manager.QUERY_BOOT(&peer,&request);assert(peer.headers==1&&peer.announced==peer.bytes.size());
manager.hosts={"1.2.3.4"};manager.m_vec_banwordTable.resize(2);CPeer normal;manager.QUERY_BOOT(&normal,&request);assert(normal.headers==1&&normal.announced==normal.bytes.size());
DWORD declared=0;memcpy(&declared,normal.bytes.data(),4);assert(declared==normal.bytes.size()&&normal.bytes[4]==6);
manager.m_vec_banwordTable.resize(65536);CPeer overflow;manager.QUERY_BOOT(&overflow,&request);assert(!overflow.headers&&overflow.bytes.empty());manager.m_vec_banwordTable.clear();
manager.m_iShopTableSize=-1;manager.QUERY_BOOT(&overflow,&request);assert(!overflow.headers);manager.m_iShopTableSize=1;manager.QUERY_BOOT(&overflow,&request);assert(!overflow.headers);manager.m_iShopTableSize=0;
CPeer adminPeer;manager.m_peerList={&adminPeer};TPacketReloadAdmin adminRequest={};manager.ReloadAdmin(nullptr,&adminRequest);assert(adminPeer.headers==1&&adminPeer.announced==adminPeer.bytes.size());
adminPeer={};manager.admins.resize(65536);manager.ReloadAdmin(nullptr,&adminRequest);assert(!adminPeer.headers&&adminPeer.bytes.empty());manager.admins.clear();
manager.hosts={std::string(16,'x')};manager.QUERY_BOOT(&overflow,&request);assert(!overflow.headers);manager.hosts.clear();manager.queryOK=false;manager.QUERY_BOOT(&overflow,&request);assert(!overflow.headers);
}
''')
if __name__=='__main__':unittest.main()